crypto.rs 30 KB

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