crypto.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. /// Functions for performing cryptographic operations on the main data structures.
  2. use super::*;
  3. use openssl::{
  4. error::ErrorStack,
  5. encrypt::{Encrypter, Decrypter},
  6. pkey::{PKey, Public as OsslPublic, Private as OsslPrivate},
  7. symm::{Cipher, encrypt as openssl_encrypt, decrypt as openssl_decrypt},
  8. rand::rand_bytes,
  9. rsa::{Rsa, Padding as OpensslPadding},
  10. hash::{hash, MessageDigest},
  11. sign::{Signer, Verifier}
  12. };
  13. use serde_block_tree::{self, to_vec, from_vec, write_to};
  14. use serde::de::{DeserializeOwned};
  15. use std::str::FromStr;
  16. use strum_macros::{EnumString, EnumDiscriminants, Display};
  17. /// Data that may or may not be encrypted.
  18. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
  19. pub(crate) enum Cryptotext<T: Serialize> {
  20. /// The inner value of `T` is plaintext.
  21. Plain(T),
  22. /// The inner value is ciphertext.
  23. Cipher(Vec<u8>),
  24. }
  25. /// Errors that can occur during cryptographic operations.
  26. #[derive(Debug)]
  27. pub(crate) enum Error {
  28. NoReadCap,
  29. NoKeyAvailable,
  30. MissingPrivateKey,
  31. KeyVariantUnsupported,
  32. BlockNotEncrypted,
  33. InvalidHashFormat,
  34. Message(String),
  35. Serde(serde_block_tree::Error),
  36. }
  37. impl Display for Error {
  38. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  39. match self {
  40. Error::NoReadCap => write!(f, "no readcap"),
  41. Error::NoKeyAvailable => write!(f, "no key available"),
  42. Error::MissingPrivateKey => write!(f, "private key was missing"),
  43. Error::KeyVariantUnsupported => write!(f, "unsupported key variant"),
  44. Error::BlockNotEncrypted => write!(f, "block was not encrypted"),
  45. Error::InvalidHashFormat => write!(f, "invalid format"),
  46. Error::Message(message) => f.write_str(message.as_str()),
  47. Error::Serde(serde_err) => serde_err.fmt(f),
  48. }
  49. }
  50. }
  51. impl From<ErrorStack> for Error {
  52. fn from(error: ErrorStack) -> Error {
  53. Error::Message(error.to_string())
  54. }
  55. }
  56. impl From<serde_block_tree::Error> for Error {
  57. fn from(error: serde_block_tree::Error) -> Error {
  58. Error::Serde(error)
  59. }
  60. }
  61. pub(crate) type Result<T> = std::result::Result<T, Error>;
  62. /// A cryptographic hash.
  63. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable, Clone, EnumDiscriminants)]
  64. #[strum_discriminants(derive(EnumString, Display))]
  65. #[strum_discriminants(name(HashKind))]
  66. pub(crate) enum Hash {
  67. Sha2_256([u8; 32]),
  68. #[serde(with = "BigArray")]
  69. Sha2_512([u8; 64]),
  70. }
  71. impl Default for HashKind {
  72. fn default() -> HashKind {
  73. HashKind::Sha2_256
  74. }
  75. }
  76. impl Hash {
  77. /// The character that's used to separate a hash type from its value in its string
  78. /// representation.
  79. const HASH_SEP: char = ':';
  80. fn kind(&self) -> HashKind {
  81. HashKind::from(self)
  82. }
  83. }
  84. impl From<HashKind> for Hash {
  85. fn from(discriminant: HashKind) -> Hash {
  86. match discriminant {
  87. HashKind::Sha2_512 => Hash::Sha2_512([0u8; 64]),
  88. HashKind::Sha2_256 => Hash::Sha2_256([0u8; 32])
  89. }
  90. }
  91. }
  92. impl AsRef<[u8]> for Hash {
  93. fn as_ref(&self) -> &[u8] {
  94. match self {
  95. Hash::Sha2_256(arr) => arr,
  96. Hash::Sha2_512(arr) => arr
  97. }
  98. }
  99. }
  100. impl AsMut<[u8]> for Hash {
  101. fn as_mut(&mut self) -> &mut [u8] {
  102. match self {
  103. Hash::Sha2_256(arr) => arr,
  104. Hash::Sha2_512(arr) => arr
  105. }
  106. }
  107. }
  108. impl TryFrom<&str> for Hash {
  109. type Error = Error;
  110. fn try_from(string: &str) -> Result<Hash> {
  111. let mut split: Vec<&str> = string.split(Self::HASH_SEP).collect();
  112. if split.len() != 2 {
  113. return Err(Error::InvalidHashFormat)
  114. };
  115. let second = split.pop().ok_or(Error::InvalidHashFormat)?;
  116. let first = split.pop().ok_or(Error::InvalidHashFormat)?;
  117. let mut hash = Hash::from(HashKind::from_str(first)
  118. .map_err(|_| Error::InvalidHashFormat)?);
  119. base64_url::decode_to_slice(second, hash.as_mut())
  120. .map_err(|_| Error::InvalidHashFormat)?;
  121. Ok(hash)
  122. }
  123. }
  124. impl Display for Hash {
  125. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  126. let hash_type: HashKind = self.into();
  127. let hash_data = base64_url::encode(self.as_ref());
  128. write!(f, "{}{}{}", hash_type, Hash::HASH_SEP, hash_data)
  129. }
  130. }
  131. const RSA_SIG_LEN: usize = 512;
  132. /// A cryptographic signature.
  133. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone, EnumDiscriminants)]
  134. #[strum_discriminants(name(SignatureKind))]
  135. pub(crate) enum Signature {
  136. #[serde(with = "BigArray")]
  137. Rsa([u8; RSA_SIG_LEN]),
  138. }
  139. impl Signature {
  140. fn new(id: SignatureKind) -> Signature {
  141. match id {
  142. SignatureKind::Rsa => Signature::Rsa([0; RSA_SIG_LEN])
  143. }
  144. }
  145. fn as_slice(&self) -> &[u8] {
  146. match self {
  147. Signature::Rsa(buf) => buf.as_slice()
  148. }
  149. }
  150. fn as_mut_slice(&mut self) -> &mut [u8] {
  151. match self {
  152. Signature::Rsa(buf) => buf.as_mut_slice()
  153. }
  154. }
  155. }
  156. impl AsRef<[u8]> for Signature {
  157. fn as_ref(&self) -> &[u8] {
  158. self.as_slice()
  159. }
  160. }
  161. impl AsMut<[u8]> for Signature {
  162. fn as_mut(&mut self) -> &mut [u8] {
  163. self.as_mut_slice()
  164. }
  165. }
  166. impl Default for Signature {
  167. fn default() -> Self {
  168. Signature::Rsa([0; RSA_SIG_LEN])
  169. }
  170. }
  171. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
  172. pub(crate) enum RsaPadding {
  173. None,
  174. Pkcs1,
  175. Pkcs1Oaep,
  176. Pkcs1Pss,
  177. }
  178. impl Default for RsaPadding {
  179. fn default() -> Self {
  180. RsaPadding::Pkcs1
  181. }
  182. }
  183. impl Copy for RsaPadding {}
  184. impl From<RsaPadding> for OpensslPadding {
  185. fn from(padding: RsaPadding) -> OpensslPadding {
  186. match padding {
  187. RsaPadding::None => OpensslPadding::NONE,
  188. RsaPadding::Pkcs1 => OpensslPadding::PKCS1,
  189. RsaPadding::Pkcs1Oaep => OpensslPadding::PKCS1_OAEP,
  190. RsaPadding::Pkcs1Pss => OpensslPadding::PKCS1_PSS,
  191. }
  192. }
  193. }
  194. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone, EnumDiscriminants)]
  195. #[strum_discriminants(name(SymKeyKind))]
  196. pub(crate) enum SymKey {
  197. /// A key for the AES 256 cipher in Cipher Block Chaining mode. Note that this includes the
  198. /// initialization vector, so that a value of this variant contains all the information needed
  199. /// to fully initialize a cipher context.
  200. Aes256Cbc {
  201. key: [u8; 32],
  202. iv: [u8; 16],
  203. },
  204. /// A key for the AES 256 cipher in counter mode.
  205. Aes256Ctr {
  206. key: [u8; 32],
  207. iv: [u8; 16]
  208. },
  209. }
  210. /// Returns an array of the given length filled with cryptographically random data.
  211. fn rand_array<const LEN: usize>() -> Result<[u8; LEN]> {
  212. let mut array = [0; LEN];
  213. rand_bytes(&mut array).map_err(Error::from)?;
  214. Ok(array)
  215. }
  216. impl SymKey {
  217. pub(crate) fn generate(kind: SymKeyKind) -> Result<SymKey> {
  218. match kind {
  219. SymKeyKind::Aes256Cbc => {
  220. Ok(SymKey::Aes256Cbc { key: rand_array()?, iv: rand_array()? })
  221. },
  222. SymKeyKind::Aes256Ctr => {
  223. Ok(SymKey::Aes256Ctr { key: rand_array()?, iv: rand_array()? })
  224. },
  225. }
  226. }
  227. }
  228. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
  229. pub(crate) struct Public;
  230. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
  231. pub(crate) struct Private;
  232. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone, EnumDiscriminants)]
  233. #[strum_discriminants(name(AsymKeyKind))]
  234. pub(crate) enum AsymKey<T> {
  235. Rsa {
  236. der: Vec<u8>,
  237. padding: RsaPadding,
  238. kind: T,
  239. }
  240. }
  241. impl<T> AsymKey<T> {
  242. pub(crate) fn as_slice(&self) -> &[u8] {
  243. match self {
  244. AsymKey::Rsa { der, .. } => der.as_slice()
  245. }
  246. }
  247. }
  248. impl<T> Owned for AsymKey<T> {
  249. fn owner_of_kind(&self, kind: HashKind) -> Principal {
  250. match kind {
  251. HashKind::Sha2_256 => {
  252. let mut buf = [0; 32];
  253. let bytes = hash(MessageDigest::sha256(), self.as_slice()).unwrap();
  254. buf.copy_from_slice(&*bytes);
  255. Principal(Hash::Sha2_256(buf))
  256. },
  257. HashKind::Sha2_512 => {
  258. let mut buf = [0; 64];
  259. let bytes = hash(MessageDigest::sha512(), self.as_slice()).unwrap();
  260. buf.copy_from_slice(&*bytes);
  261. Principal(Hash::Sha2_512(buf))
  262. }
  263. }
  264. }
  265. }
  266. pub(crate) struct KeyPair {
  267. pub(crate) public: AsymKey<Public>,
  268. pub(crate) private: AsymKey<Private>,
  269. }
  270. impl KeyPair {
  271. pub(crate) fn generate(kind: AsymKeyKind) -> Result<KeyPair> {
  272. match kind {
  273. AsymKeyKind::Rsa => {
  274. let key = PKey::from_rsa(Rsa::generate(4096)?)?;
  275. let public = key.public_key_to_der().map_err(Error::from)?;
  276. let private = key.private_key_to_der().map_err(Error::from)?;
  277. Ok(KeyPair {
  278. public: AsymKey::Rsa {
  279. der: public,
  280. padding: RsaPadding::default(),
  281. kind: Public,
  282. },
  283. private: AsymKey::Rsa {
  284. der: private,
  285. padding: RsaPadding::default(),
  286. kind: Private,
  287. },
  288. })
  289. },
  290. }
  291. }
  292. }
  293. impl Owned for KeyPair {
  294. fn owner_of_kind(&self, kind: HashKind) -> Principal {
  295. self.public.owner_of_kind(kind)
  296. }
  297. }
  298. enum EncryptionAlgo<'a> {
  299. Symmetric {
  300. cipher: Cipher,
  301. key: &'a [u8],
  302. iv: Option<&'a [u8]>
  303. },
  304. Asymmetric {
  305. key: PKey<OsslPublic>,
  306. rsa_padding: Option<OpensslPadding>,
  307. }
  308. }
  309. impl<'a> EncryptionAlgo<'a> {
  310. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  311. match self {
  312. EncryptionAlgo::Symmetric { cipher, key, iv } => {
  313. openssl_encrypt(*cipher, key, *iv, slice).map_err(Error::from)
  314. },
  315. EncryptionAlgo::Asymmetric { key, rsa_padding } => {
  316. let mut encrypter = Encrypter::new(key).map_err(Error::from)?;
  317. if let Some(padding) = rsa_padding {
  318. encrypter.set_rsa_padding(*padding).map_err(Error::from)?;
  319. }
  320. let buffer_len = encrypter.encrypt_len(slice).map_err(Error::from)?;
  321. let mut ciphertext = vec![0; buffer_len];
  322. let ciphertext_len = encrypter.encrypt(slice, &mut ciphertext)
  323. .map_err(Error::from)?;
  324. ciphertext.truncate(ciphertext_len);
  325. Ok(ciphertext)
  326. }
  327. }
  328. }
  329. }
  330. impl<'a> TryFrom<&'a SymKey> for EncryptionAlgo<'a> {
  331. type Error = Error;
  332. fn try_from(key: &'a SymKey) -> Result<EncryptionAlgo<'a>> {
  333. match key {
  334. SymKey::Aes256Cbc { key: key_slice, iv } => Ok(EncryptionAlgo::Symmetric {
  335. cipher: Cipher::aes_256_cbc(),
  336. key: key_slice,
  337. iv: Some(iv),
  338. }),
  339. SymKey::Aes256Ctr { key: key_slice, iv } => Ok(EncryptionAlgo::Symmetric {
  340. cipher: Cipher::aes_256_ctr(),
  341. key: key_slice,
  342. iv: Some(iv),
  343. }),
  344. }
  345. }
  346. }
  347. impl<'a> TryFrom<&'a AsymKey<Public>> for EncryptionAlgo<'a> {
  348. type Error = Error;
  349. fn try_from(key: &'a AsymKey<Public>) -> Result<EncryptionAlgo<'a>> {
  350. match key {
  351. AsymKey::Rsa { der, padding, .. } => {
  352. let key = PKey::public_key_from_der(der.as_slice()).map_err(Error::from)?;
  353. Ok(EncryptionAlgo::Asymmetric { key, rsa_padding: Some((*padding).into()) })
  354. },
  355. }
  356. }
  357. }
  358. enum DecryptionAlgo<'a> {
  359. Symmetric {
  360. cipher: Cipher,
  361. key: &'a [u8],
  362. iv: Option<&'a [u8]>
  363. },
  364. Asymmetric(PKey<OsslPrivate>),
  365. }
  366. impl<'a> DecryptionAlgo<'a> {
  367. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  368. match self {
  369. DecryptionAlgo::Symmetric { cipher, key, iv } => {
  370. openssl_decrypt(*cipher, key, *iv, slice).map_err(Error::from)
  371. },
  372. DecryptionAlgo::Asymmetric(pkey) => {
  373. let decrypter = Decrypter::new(pkey).map_err(Error::from)?;
  374. let buffer_len = decrypter.decrypt_len(slice).map_err(Error::from)?;
  375. let mut plaintext = vec![0; buffer_len];
  376. let plaintext_len = decrypter.decrypt(slice, &mut plaintext)
  377. .map_err(Error::from)?;
  378. plaintext.truncate(plaintext_len);
  379. Ok(plaintext)
  380. },
  381. }
  382. }
  383. }
  384. impl<'a> TryFrom<&'a SymKey> for DecryptionAlgo<'a> {
  385. type Error = Error;
  386. fn try_from(key: &'a SymKey) -> Result<DecryptionAlgo<'a>> {
  387. match key {
  388. SymKey::Aes256Cbc { key: key_slice, iv } => Ok(DecryptionAlgo::Symmetric {
  389. cipher: Cipher::aes_256_cbc(),
  390. key: key_slice,
  391. iv: Some(iv),
  392. }),
  393. SymKey::Aes256Ctr { key: key_slice, iv } => Ok(DecryptionAlgo::Symmetric {
  394. cipher: Cipher::aes_256_ctr(),
  395. key: key_slice,
  396. iv: Some(iv),
  397. }),
  398. }
  399. }
  400. }
  401. impl<'a> TryFrom<&'a AsymKey<Private>> for DecryptionAlgo<'a> {
  402. type Error = Error;
  403. fn try_from(key: &'a AsymKey<Private>) -> Result<DecryptionAlgo<'a>> {
  404. match key {
  405. AsymKey::Rsa { der, .. } => {
  406. let pkey = PKey::private_key_from_der(der.as_slice()).map_err(Error::from);
  407. Ok(DecryptionAlgo::Asymmetric(pkey?))
  408. }
  409. }
  410. }
  411. }
  412. struct SignAlgo {
  413. key: PKey<OsslPrivate>,
  414. digest: MessageDigest,
  415. signature: Signature
  416. }
  417. impl SignAlgo {
  418. fn sign<'a, I: Iterator<Item = &'a [u8]>>(&mut self, parts: I) -> Result<()> {
  419. let mut signer = Signer::new(self.digest, &self.key).map_err(Error::from)?;
  420. for part in parts {
  421. signer.update(part).map_err(Error::from)?;
  422. }
  423. let buf = self.signature.as_mut_slice();
  424. signer.sign(buf).map_err(Error::from)?;
  425. Ok(())
  426. }
  427. }
  428. impl TryFrom<&AsymKey<Private>> for SignAlgo {
  429. type Error = Error;
  430. fn try_from(key: &AsymKey<Private>) -> Result<SignAlgo> {
  431. match key {
  432. AsymKey::Rsa { der, .. } => {
  433. let rsa = Rsa::private_key_from_der(der.as_slice()).map_err(Error::from)?;
  434. Ok(SignAlgo {
  435. key: PKey::from_rsa(rsa).map_err(Error::from)?,
  436. digest: MessageDigest::sha256(),
  437. signature: Signature::new(SignatureKind::Rsa)
  438. })
  439. },
  440. }
  441. }
  442. }
  443. struct VerifyAlgo {
  444. key: PKey<OsslPublic>,
  445. digest: MessageDigest,
  446. }
  447. impl VerifyAlgo {
  448. fn verify<'a, I: Iterator<Item = &'a [u8]>>(
  449. &'a self, parts: I, signature: &[u8]
  450. ) -> Result<bool> {
  451. let mut verifier = Verifier::new(self.digest, &self.key).map_err(Error::from)?;
  452. for part in parts {
  453. verifier.update(part).map_err(Error::from)?;
  454. }
  455. verifier.verify(signature).map_err(Error::from)
  456. }
  457. }
  458. impl TryFrom<&AsymKey<Public>> for VerifyAlgo {
  459. type Error = Error;
  460. fn try_from(key: &AsymKey<Public>) -> Result<VerifyAlgo> {
  461. match key {
  462. AsymKey::Rsa { der, .. } => {
  463. let rsa = Rsa::public_key_from_der(der.as_slice()).map_err(Error::from)?;
  464. Ok(VerifyAlgo {
  465. key: PKey::from_rsa(rsa).map_err(Error::from)?,
  466. digest: MessageDigest::sha256()
  467. })
  468. },
  469. }
  470. }
  471. }
  472. pub(crate) fn encrypt_block(
  473. mut block: Block, principal: &Principal, key: &KeyPair
  474. ) -> Result<Block> {
  475. let body = match block.body {
  476. Cryptotext::Cipher(_) => return Ok(block),
  477. Cryptotext::Plain(body) => body
  478. };
  479. let (principal_owned, read_cap) = block.readcaps.remove_entry(principal)
  480. .ok_or(Error::NoReadCap)?;
  481. let block_key = decrypt(read_cap, &key.private)?;
  482. let new_body = encrypt_slice(&body, &block_key)?;
  483. block.body = Cryptotext::Cipher(new_body);
  484. block.readcaps.insert(principal_owned, encrypt(&block_key, &key.public)?);
  485. Ok(block)
  486. }
  487. pub(crate) fn decrypt_block(
  488. mut block: Block, principal: &Principal, key: &AsymKey<Private>
  489. ) -> Result<Block> {
  490. let body = match block.body {
  491. Cryptotext::Plain(_) => return Ok(block),
  492. Cryptotext::Cipher(body) => body
  493. };
  494. let (principal_owned, read_cap) = block.readcaps.remove_entry(principal)
  495. .ok_or(Error::NoReadCap)?;
  496. let block_key = decrypt(read_cap, key)?;
  497. let new_body = decrypt_slice(&body, &block_key)?;
  498. block.body = Cryptotext::Plain(new_body);
  499. block.readcaps.insert(principal_owned, Cryptotext::Plain(block_key));
  500. Ok(block)
  501. }
  502. fn encrypt<'a, T: Serialize, K: TryInto<EncryptionAlgo<'a>, Error = Error>>(
  503. value: &T, key: K
  504. ) -> Result<Cryptotext<T>> {
  505. let data = to_vec(value).map_err(Error::from)?;
  506. let vec = encrypt_slice(&data, key);
  507. Ok(Cryptotext::Cipher(vec?))
  508. }
  509. fn decrypt<'a, T: Serialize + DeserializeOwned, K: TryInto<DecryptionAlgo<'a>, Error = Error>>(
  510. cryptotext: Cryptotext<T>, key: K
  511. ) -> Result<T> {
  512. let data = match cryptotext {
  513. Cryptotext::Plain(value) => return Ok(value),
  514. Cryptotext::Cipher(data) => data
  515. };
  516. let vec = decrypt_slice(&data, key);
  517. from_vec(&vec?).map_err(Error::from)
  518. }
  519. fn encrypt_slice<'a, K: TryInto<EncryptionAlgo<'a>, Error = Error>>(
  520. plaintext: &[u8], key: K
  521. ) -> Result<Vec<u8>> {
  522. let algo: EncryptionAlgo<'a> = key.try_into()?;
  523. algo.encrypt(plaintext)
  524. }
  525. fn decrypt_slice<'a, K: TryInto<DecryptionAlgo<'a>, Error = Error>>(
  526. ciphertext: &[u8], key: K
  527. ) -> Result<Vec<u8>> {
  528. let algo: DecryptionAlgo<'a> = key.try_into()?;
  529. algo.decrypt(ciphertext)
  530. }
  531. #[derive(Serialize)]
  532. struct SigHeader<'a> {
  533. path: &'a Path,
  534. readcaps: &'a HashMap<Principal, Cryptotext<SymKey>>,
  535. writecap: &'a Writecap,
  536. }
  537. impl<'a> From<&'a Block> for SigHeader<'a> {
  538. fn from(block: &'a Block) -> SigHeader<'a> {
  539. SigHeader {
  540. path: &block.path,
  541. readcaps: &block.readcaps,
  542. writecap: &block.writecap,
  543. }
  544. }
  545. }
  546. fn get_body(block: &Block) -> Result<&[u8]> {
  547. let body = match &block.body {
  548. Cryptotext::Cipher(body) => body,
  549. Cryptotext::Plain(_) => {
  550. return Err(Error::BlockNotEncrypted);
  551. }
  552. };
  553. Ok(body)
  554. }
  555. pub(crate) fn sign_block(
  556. block: &mut Block, writecap: Writecap, priv_key: AsymKey<Private>
  557. ) -> Result<()> {
  558. block.writecap = writecap;
  559. let body = get_body(block)?;
  560. let sig_header = SigHeader::from(&*block);
  561. let header = to_vec(&sig_header)?;
  562. let mut sign_algo = SignAlgo::try_from(&priv_key)?;
  563. sign_algo.sign([header.as_slice(), body].into_iter())?;
  564. block.signature = sign_algo.signature;
  565. Ok(())
  566. }
  567. pub(crate) fn verify_block(block: &Block) -> Result<bool> {
  568. let body = get_body(block)?;
  569. let sig_header = SigHeader::from(&*block);
  570. let header = to_vec(&sig_header)?;
  571. let verify_algo = VerifyAlgo::try_from(&block.writecap.signing_key)?;
  572. let parts = [header.as_slice(), body].into_iter();
  573. Ok(verify_algo.verify(parts, block.signature.as_slice())?)
  574. }
  575. #[derive(Serialize)]
  576. struct WritecapSig<'a> {
  577. issued_to: &'a Principal,
  578. path: &'a Path,
  579. expires: &'a Epoch,
  580. signing_key: &'a AsymKey<Public>,
  581. }
  582. impl<'a> From<&'a Writecap> for WritecapSig<'a> {
  583. fn from(writecap: &'a Writecap) -> WritecapSig<'a> {
  584. WritecapSig {
  585. issued_to: &writecap.issued_to,
  586. path: &writecap.path,
  587. expires: &writecap.expires,
  588. signing_key: &writecap.signing_key,
  589. }
  590. }
  591. }
  592. pub(crate) fn sign_writecap(writecap: &mut Writecap, priv_key: &AsymKey<Private>) -> Result<()> {
  593. let mut sign_algo = SignAlgo::try_from(priv_key)?;
  594. let sig_input = to_vec(&WritecapSig::from(&*writecap))?;
  595. sign_algo.sign([sig_input.as_slice()].into_iter())?;
  596. writecap.signature = sign_algo.signature;
  597. Ok(())
  598. }
  599. /// The types of errors which can occur when verifying a writecap chain is authorized to write to
  600. /// a given path.
  601. #[derive(Debug, PartialEq)]
  602. pub(crate) enum WritecapAuthzErr {
  603. /// The chain is not valid for use on the given path.
  604. UnauthorizedPath,
  605. /// At least one writecap in the chain is expired.
  606. Expired,
  607. /// The given writecaps do not actually form a chain.
  608. NotChained,
  609. /// There is an invalid signature in the chain.
  610. InvalidSignature,
  611. /// The principal the root writecap was issued to does not own the given path.
  612. RootDoesNotOwnPath,
  613. /// An error occured while serializing a writecap.
  614. Serde(String),
  615. /// A cryptographic error occurred while attempting to verify a writecap.
  616. Crypto(String),
  617. }
  618. /// Verifies that the given `Writecap` actually grants permission to write to the given `Path`.
  619. pub(crate) fn verify_writecap(
  620. mut writecap: &Writecap, path: &Path
  621. ) -> std::result::Result<(), WritecapAuthzErr> {
  622. let mut prev: Option<&Writecap> = None;
  623. let mut sig_input = Vec::new();
  624. let now = Epoch::now();
  625. loop {
  626. if !writecap.path.contains(path) {
  627. return Err(WritecapAuthzErr::UnauthorizedPath);
  628. }
  629. if writecap.expires <= now {
  630. return Err(WritecapAuthzErr::Expired);
  631. }
  632. if let Some(prev) = &prev {
  633. if prev.signing_key.owner_of_kind(writecap.issued_to.kind()) != writecap.issued_to {
  634. return Err(WritecapAuthzErr::NotChained);
  635. }
  636. }
  637. let sig = WritecapSig::from(writecap);
  638. sig_input.clear();
  639. write_to(&sig, &mut sig_input).map_err(|e| WritecapAuthzErr::Serde(e.to_string()))?;
  640. let verify_algo = VerifyAlgo::try_from(&writecap.signing_key)
  641. .map_err(|e| WritecapAuthzErr::Crypto(e.to_string()))?;
  642. let valid = verify_algo
  643. .verify([sig_input.as_slice()].into_iter(), writecap.signature.as_slice())
  644. .map_err(|e| WritecapAuthzErr::Crypto(e.to_string()))?;
  645. if !valid {
  646. return Err(WritecapAuthzErr::InvalidSignature);
  647. }
  648. match &writecap.next {
  649. Some(next) => {
  650. prev = Some(writecap);
  651. writecap = next;
  652. },
  653. None => {
  654. // We're at the root key. As long as the signer of this writecap is the owner of
  655. // the path, then the writecap is valid.
  656. if writecap.signing_key.owner_of_kind(path.owner.kind()) == path.owner {
  657. return Ok(());
  658. }
  659. else {
  660. return Err(WritecapAuthzErr::RootDoesNotOwnPath)
  661. }
  662. }
  663. }
  664. }
  665. }
  666. #[cfg(test)]
  667. mod tests {
  668. use super::*;
  669. use test_helpers::*;
  670. fn encrypt_decrypt_block_test_case(
  671. mut actual: Block, principal: &Principal, key: &KeyPair
  672. ) -> Result<()> {
  673. let expected = actual.clone();
  674. actual = encrypt_block(actual, principal, key)?;
  675. let encrypted = match &actual.body {
  676. Cryptotext::Cipher(_) => true,
  677. Cryptotext::Plain(_) => false
  678. };
  679. assert!(encrypted);
  680. actual = decrypt_block(actual, principal, &key.private)?;
  681. assert_eq!(expected, actual);
  682. Ok(())
  683. }
  684. #[test]
  685. fn encrypt_decrypt_block_aes256cbc() -> Result<()> {
  686. let readcap = make_readcap();
  687. let principal = readcap.issued_to.clone();
  688. let block = make_block_with(readcap)?;
  689. let key = make_key_pair();
  690. encrypt_decrypt_block_test_case(block, &principal, &key)
  691. }
  692. #[test]
  693. fn encrypt_decrypt_block_aes256ctr() -> Result<()> {
  694. let readcap = make_readcap();
  695. let principal = readcap.issued_to.clone();
  696. let block = make_block_with(readcap)?;
  697. let key = make_key_pair();
  698. encrypt_decrypt_block_test_case(block, &principal, &key)
  699. }
  700. #[test]
  701. fn rsa_sign_and_verify() -> Result<()> {
  702. let key = make_key_pair();
  703. let header = b"About: lyrics".as_slice();
  704. let message = b"Everything that feels so good is bad bad bad.".as_slice();
  705. let mut signer = SignAlgo::try_from(&key.private)?;
  706. signer.sign([header, message].into_iter())?;
  707. let verifier = VerifyAlgo::try_from(&key.public)?;
  708. let verified = verifier.verify([header, message].into_iter(), signer.signature.as_slice())?;
  709. assert_eq!(true, verified);
  710. Ok(())
  711. }
  712. #[test]
  713. fn sign_verify_block_rsa() -> Result<()> {
  714. let readcap = make_readcap();
  715. let principal = readcap.issued_to.clone();
  716. let mut block = make_block_with(readcap)?;
  717. let key = make_key_pair();
  718. let writecap = Writecap {
  719. issued_to: Principal(Hash::Sha2_256(PRINCIPAL)),
  720. path: make_path(vec!["contacts", "emergency"]),
  721. expires: Epoch(1649904316),
  722. signing_key: key.public.clone(),
  723. signature: Signature::Rsa(SIGNATURE),
  724. next: None,
  725. };
  726. block = encrypt_block(block, &principal, &key)?;
  727. sign_block(&mut block, writecap, key.private)?;
  728. assert_eq!(true, verify_block(&block)?);
  729. Ok(())
  730. }
  731. #[test]
  732. fn hash_to_string() {
  733. let hash = make_principal().0;
  734. let string = hash.to_string();
  735. assert_eq!("Sha2_256:dSip4J0kurN5VhVo_aTipM-ywOOWrqJuRRVQ7aa-bew", string)
  736. }
  737. #[test]
  738. fn hash_to_string_round_trip() -> Result<()> {
  739. let expected = make_principal().0;
  740. let string = expected.to_string();
  741. let actual = Hash::try_from(string.as_str())?;
  742. assert_eq!(expected, actual);
  743. Ok(())
  744. }
  745. #[test]
  746. fn verify_writecap_valid() -> Result<()> {
  747. let writecap = make_writecap()?;
  748. let result = verify_writecap(&writecap, &writecap.path);
  749. assert_eq!(Ok(()), result);
  750. Ok(())
  751. }
  752. #[test]
  753. fn verify_writecap_invalid_signature() -> Result<()> {
  754. let mut writecap = make_writecap()?;
  755. writecap.signature = Signature::default();
  756. let result = verify_writecap(&writecap, &writecap.path);
  757. assert_eq!(Err(WritecapAuthzErr::InvalidSignature), result);
  758. Ok(())
  759. }
  760. #[test]
  761. fn verify_writecap_invalid_path_not_contained() -> Result<()> {
  762. let writecap = make_writecap()?;
  763. let mut path = writecap.path.clone();
  764. path.components.pop();
  765. // `path` is now a superpath of `writecap.path`, thus the writecap is not authorized to
  766. // write to it.
  767. let result = verify_writecap(&writecap, &path);
  768. assert_eq!(Err(WritecapAuthzErr::UnauthorizedPath), result);
  769. Ok(())
  770. }
  771. #[test]
  772. fn verify_writecap_invalid_expired() -> Result<()> {
  773. let mut writecap = make_writecap()?;
  774. writecap.expires = Epoch::now() - Duration::from_secs(1);
  775. let result = verify_writecap(&writecap, &writecap.path);
  776. assert_eq!(Err(WritecapAuthzErr::Expired), result);
  777. Ok(())
  778. }
  779. #[test]
  780. fn verify_writecap_invalid_not_chained() -> Result<()> {
  781. let (mut root_writecap, root_key) = make_self_signed_writecap()?;
  782. root_writecap.issued_to = Principal(Hash::Sha2_256([0; 32]));
  783. sign_writecap(&mut root_writecap, &root_key.private)?;
  784. let node_key = AsymKey::Rsa {
  785. der: Vec::from(NODE_PUBLIC_KEY),
  786. padding: RsaPadding::Pkcs1,
  787. kind: Public {},
  788. };
  789. let node_principal = node_key.owner();
  790. let writecap = make_writecap_trusted_by(
  791. root_writecap, root_key, node_principal, vec!["apps", "contacts"])?;
  792. let result = verify_writecap(&writecap, &writecap.path);
  793. assert_eq!(Err(WritecapAuthzErr::NotChained), result);
  794. Ok(())
  795. }
  796. #[test]
  797. fn verify_writecap_invalid_root_doesnt_own_path() -> Result<()> {
  798. let (mut root_writecap, root_key) = make_self_signed_writecap()?;
  799. let owner = Principal(Hash::Sha2_256([0; 32]));
  800. root_writecap.path = make_path_with_owner(owner, vec![]);
  801. sign_writecap(&mut root_writecap, &root_key.private)?;
  802. let node_key = AsymKey::Rsa {
  803. der: Vec::from(NODE_PUBLIC_KEY),
  804. padding: RsaPadding::Pkcs1,
  805. kind: Public {}
  806. };
  807. let node_owner = node_key.owner();
  808. let writecap = make_writecap_trusted_by(
  809. root_writecap, root_key, node_owner, vec!["apps", "contacts"])?;
  810. let result = verify_writecap(&writecap, &writecap.path);
  811. assert_eq!(Err(WritecapAuthzErr::RootDoesNotOwnPath), result);
  812. Ok(())
  813. }
  814. /// Tests that validate the dependencies of this module.
  815. mod dependency_tests {
  816. use super::*;
  817. use openssl::{
  818. ec::{EcGroup, EcKey},
  819. nid::Nid,
  820. };
  821. /// This test validates that data encrypted with AES 256 CBC can later be decrypted.
  822. #[test]
  823. fn aes_256_cbc_roundtrip() {
  824. use super::*;
  825. let expected = b"We attack at the crack of noon!";
  826. let cipher = Cipher::aes_256_cbc();
  827. let ciphertext = openssl_encrypt(cipher, &KEY, Some(&IV), expected).unwrap();
  828. let actual = openssl_decrypt(cipher, &KEY, Some(&IV), ciphertext.as_slice()).unwrap();
  829. assert_eq!(expected, actual.as_slice());
  830. }
  831. /// Tests that the keys for the SECP256K1 curve are the expected sizes.
  832. #[test]
  833. fn secp256k1_key_lengths() {
  834. let group = EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
  835. let key = EcKey::generate(&group).unwrap();
  836. let public = key.public_key_to_der().unwrap();
  837. let private = key.private_key_to_der().unwrap();
  838. let public_len = public.len();
  839. let private_len = private.len();
  840. assert_eq!(88, public_len);
  841. assert_eq!(118, private_len);
  842. }
  843. #[test]
  844. fn ed25519_key_lengths() {
  845. let key = PKey::generate_x25519().unwrap();
  846. let public = key.public_key_to_der().unwrap();
  847. let private = key.private_key_to_der().unwrap();
  848. let public_len = public.len();
  849. let private_len = private.len();
  850. assert_eq!(44, public_len);
  851. assert_eq!(48, private_len);
  852. }
  853. #[test]
  854. fn rsa_signature_len() -> Result<()> {
  855. use openssl::rsa::Rsa;
  856. let key = make_key_pair();
  857. let sign_algo = SignAlgo::try_from(&key.private)?;
  858. let der = match &key.private {
  859. AsymKey::Rsa { der, .. } => der,
  860. };
  861. let rsa = Rsa::private_key_from_der(der)?;
  862. let pkey = PKey::from_rsa(rsa)?;
  863. let signer = Signer::new(sign_algo.digest, &pkey)?;
  864. assert_eq!(RSA_SIG_LEN, signer.len()?);
  865. Ok(())
  866. }
  867. }
  868. }