mod.rs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. /// Functions for performing cryptographic operations on the main data structures.
  2. mod tpm;
  3. use super::*;
  4. use openssl::{
  5. error::ErrorStack,
  6. encrypt::{Encrypter as OsslEncrypter, Decrypter as OsslDecrypter},
  7. pkey::{PKey, Public as OsslPublic, Private as OsslPrivate, HasPublic, HasPrivate},
  8. symm::{Cipher, encrypt as openssl_encrypt, decrypt as openssl_decrypt},
  9. rand::rand_bytes,
  10. rsa::{Rsa, Padding as OpensslPadding},
  11. hash::{hash, MessageDigest},
  12. sign::{Signer as OsslSigner, Verifier as OsslVerifier}
  13. };
  14. use serde_block_tree::{self, to_vec, from_vec, write_to};
  15. use serde::{
  16. de::{self, DeserializeOwned, Deserializer, SeqAccess, Visitor},
  17. ser::{Serializer, SerializeStruct},
  18. };
  19. use std::{
  20. str::FromStr, num::TryFromIntError, marker::PhantomData,
  21. };
  22. use strum_macros::{EnumString, EnumDiscriminants, Display};
  23. use foreign_types::ForeignType;
  24. /// Data that may or may not be encrypted.
  25. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
  26. pub(crate) enum Cryptotext<T: Serialize> {
  27. /// The inner value of `T` is plaintext.
  28. Plain(T),
  29. /// The inner value is ciphertext.
  30. Cipher(Vec<u8>),
  31. }
  32. /// Errors that can occur during cryptographic operations.
  33. #[derive(Debug)]
  34. pub enum Error {
  35. NoReadCap,
  36. NoKeyAvailable,
  37. MissingPrivateKey,
  38. KeyVariantUnsupported,
  39. BlockNotEncrypted,
  40. InvalidHashFormat,
  41. Serde(serde_block_tree::Error),
  42. Io(std::io::Error),
  43. Custom(Box<dyn std::fmt::Debug>)
  44. }
  45. impl Error {
  46. fn custom<E: std::fmt::Debug + 'static>(err: E) -> Self {
  47. Error::Custom(Box::new(err))
  48. }
  49. }
  50. impl Display for Error {
  51. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  52. match self {
  53. Error::NoReadCap => write!(f, "no readcap"),
  54. Error::NoKeyAvailable => write!(f, "no key available"),
  55. Error::MissingPrivateKey => write!(f, "private key was missing"),
  56. Error::KeyVariantUnsupported => write!(f, "unsupported key variant"),
  57. Error::BlockNotEncrypted => write!(f, "block was not encrypted"),
  58. Error::InvalidHashFormat => write!(f, "invalid format"),
  59. Error::Serde(serde_err) => serde_err.fmt(f),
  60. Error::Io(io_err) => io_err.fmt(f),
  61. Error::Custom(cus) => cus.fmt(f),
  62. }
  63. }
  64. }
  65. impl From<ErrorStack> for Error {
  66. fn from(error: ErrorStack) -> Error {
  67. Error::custom(error)
  68. }
  69. }
  70. impl From<serde_block_tree::Error> for Error {
  71. fn from(error: serde_block_tree::Error) -> Error {
  72. Error::Serde(error)
  73. }
  74. }
  75. impl From<std::io::Error> for Error {
  76. fn from(error: std::io::Error) -> Error {
  77. Error::Io(error)
  78. }
  79. }
  80. impl From<TryFromIntError> for Error {
  81. fn from(err: TryFromIntError) -> Self {
  82. Error::custom(err)
  83. }
  84. }
  85. pub(crate) type Result<T> = std::result::Result<T, Error>;
  86. trait ConvErr<T> {
  87. fn conv_err(self) -> Result<T>;
  88. }
  89. impl<T, E: Into<Error>> ConvErr<T> for std::result::Result<T, E> {
  90. /// Converts the error value in self to a `crypto::Error`.
  91. fn conv_err(self) -> Result<T> {
  92. self.map_err(|e| e.into())
  93. }
  94. }
  95. /// A cryptographic hash.
  96. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable, Clone, EnumDiscriminants)]
  97. #[strum_discriminants(derive(EnumString, Display, Serialize, Deserialize))]
  98. #[strum_discriminants(name(HashKind))]
  99. pub(crate) enum Hash {
  100. Sha2_256([u8; 32]),
  101. #[serde(with = "BigArray")]
  102. Sha2_512([u8; 64]),
  103. }
  104. impl Default for HashKind {
  105. fn default() -> HashKind {
  106. HashKind::Sha2_256
  107. }
  108. }
  109. impl From<HashKind> for MessageDigest {
  110. fn from(kind: HashKind) -> Self {
  111. match kind {
  112. HashKind::Sha2_256 => MessageDigest::sha256(),
  113. HashKind::Sha2_512 => MessageDigest::sha512(),
  114. }
  115. }
  116. }
  117. impl Hash {
  118. /// The character that's used to separate a hash type from its value in its string
  119. /// representation.
  120. const HASH_SEP: char = ':';
  121. fn kind(&self) -> HashKind {
  122. HashKind::from(self)
  123. }
  124. }
  125. impl From<HashKind> for Hash {
  126. fn from(discriminant: HashKind) -> Hash {
  127. match discriminant {
  128. HashKind::Sha2_512 => Hash::Sha2_512([0u8; 64]),
  129. HashKind::Sha2_256 => Hash::Sha2_256([0u8; 32])
  130. }
  131. }
  132. }
  133. impl AsRef<[u8]> for Hash {
  134. fn as_ref(&self) -> &[u8] {
  135. match self {
  136. Hash::Sha2_256(arr) => arr,
  137. Hash::Sha2_512(arr) => arr
  138. }
  139. }
  140. }
  141. impl AsMut<[u8]> for Hash {
  142. fn as_mut(&mut self) -> &mut [u8] {
  143. match self {
  144. Hash::Sha2_256(arr) => arr,
  145. Hash::Sha2_512(arr) => arr
  146. }
  147. }
  148. }
  149. impl TryFrom<&str> for Hash {
  150. type Error = Error;
  151. fn try_from(string: &str) -> Result<Hash> {
  152. let mut split: Vec<&str> = string.split(Self::HASH_SEP).collect();
  153. if split.len() != 2 {
  154. return Err(Error::InvalidHashFormat)
  155. };
  156. let second = split.pop().ok_or(Error::InvalidHashFormat)?;
  157. let first = split.pop().ok_or(Error::InvalidHashFormat)?;
  158. let mut hash = Hash::from(HashKind::from_str(first)
  159. .map_err(|_| Error::InvalidHashFormat)?);
  160. base64_url::decode_to_slice(second, hash.as_mut())
  161. .map_err(|_| Error::InvalidHashFormat)?;
  162. Ok(hash)
  163. }
  164. }
  165. impl Display for Hash {
  166. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  167. let hash_type: HashKind = self.into();
  168. let hash_data = base64_url::encode(self.as_ref());
  169. write!(f, "{}{}{}", hash_type, Hash::HASH_SEP, hash_data)
  170. }
  171. }
  172. pub(crate) const RSA_KEY_BYTES: usize = 384;
  173. /// A cryptographic signature.
  174. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone, EnumDiscriminants)]
  175. #[strum_discriminants(name(SignatureKind))]
  176. pub(crate) enum Signature {
  177. #[serde(with = "BigArray")]
  178. Rsa([u8; RSA_KEY_BYTES]),
  179. }
  180. impl Signature {
  181. fn new(id: SignatureKind) -> Signature {
  182. match id {
  183. SignatureKind::Rsa => Signature::Rsa([0; RSA_KEY_BYTES])
  184. }
  185. }
  186. fn as_slice(&self) -> &[u8] {
  187. match self {
  188. Signature::Rsa(buf) => buf.as_slice()
  189. }
  190. }
  191. fn as_mut_slice(&mut self) -> &mut [u8] {
  192. match self {
  193. Signature::Rsa(buf) => buf.as_mut_slice()
  194. }
  195. }
  196. }
  197. impl AsRef<[u8]> for Signature {
  198. fn as_ref(&self) -> &[u8] {
  199. self.as_slice()
  200. }
  201. }
  202. impl AsMut<[u8]> for Signature {
  203. fn as_mut(&mut self) -> &mut [u8] {
  204. self.as_mut_slice()
  205. }
  206. }
  207. impl Default for Signature {
  208. fn default() -> Self {
  209. Signature::Rsa([0; RSA_KEY_BYTES])
  210. }
  211. }
  212. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone, EnumDiscriminants)]
  213. #[strum_discriminants(name(SymKeyKind))]
  214. pub(crate) enum SymKey {
  215. /// A key for the AES 256 cipher in Cipher Block Chaining mode. Note that this includes the
  216. /// initialization vector, so that a value of this variant contains all the information needed
  217. /// to fully initialize a cipher context.
  218. Aes256Cbc {
  219. key: [u8; 32],
  220. iv: [u8; 16],
  221. },
  222. /// A key for the AES 256 cipher in counter mode.
  223. Aes256Ctr {
  224. key: [u8; 32],
  225. iv: [u8; 16]
  226. },
  227. }
  228. struct SymParams<'a> {
  229. cipher: Cipher,
  230. key: &'a [u8],
  231. iv: Option<&'a [u8]>,
  232. }
  233. /// Returns an array of the given length filled with cryptographically random data.
  234. fn rand_array<const LEN: usize>() -> Result<[u8; LEN]> {
  235. let mut array = [0; LEN];
  236. rand_bytes(&mut array).conv_err()?;
  237. Ok(array)
  238. }
  239. impl SymKey {
  240. pub(crate) fn generate(kind: SymKeyKind) -> Result<SymKey> {
  241. match kind {
  242. SymKeyKind::Aes256Cbc => {
  243. Ok(SymKey::Aes256Cbc { key: rand_array()?, iv: rand_array()? })
  244. },
  245. SymKeyKind::Aes256Ctr => {
  246. Ok(SymKey::Aes256Ctr { key: rand_array()?, iv: rand_array()? })
  247. },
  248. }
  249. }
  250. fn params(&self) -> SymParams {
  251. let (cipher, key, iv) = match self {
  252. SymKey::Aes256Cbc { key, iv } => (Cipher::aes_256_cbc(), key, Some(iv.as_slice())),
  253. SymKey::Aes256Ctr { key, iv } => (Cipher::aes_256_ctr(), key, Some(iv.as_slice())),
  254. };
  255. SymParams { cipher, key, iv }
  256. }
  257. }
  258. impl Encrypter for SymKey {
  259. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  260. let SymParams { cipher, key, iv } = self.params();
  261. openssl_encrypt(cipher, key, iv, slice).conv_err()
  262. }
  263. }
  264. impl Decrypter for SymKey {
  265. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  266. let SymParams { cipher, key, iv } = self.params();
  267. openssl_decrypt(cipher, key, iv, slice).conv_err()
  268. }
  269. }
  270. pub trait Scheme: for<'de> Deserialize<'de> + Serialize + Copy + std::fmt::Debug + PartialEq {
  271. type Kind: Scheme;
  272. fn kind(self) -> Self::Kind;
  273. fn as_enum(self) -> SchemeKind;
  274. fn message_digest(&self) -> MessageDigest;
  275. fn padding(&self) -> Option<OpensslPadding>;
  276. fn public_from_der(self, der: &[u8]) -> Result<PKey<OsslPublic>>;
  277. fn private_from_der(self, der: &[u8]) -> Result<PKey<OsslPrivate>>;
  278. fn generate(self) -> Result<AsymKeyPair<Self::Kind>>;
  279. }
  280. pub enum SchemeKind {
  281. Sign(Sign),
  282. Encrypt(Encrypt),
  283. }
  284. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Copy)]
  285. pub enum Encrypt {
  286. RsaEsOaep(RsaEsOaep),
  287. }
  288. impl Scheme for Encrypt {
  289. type Kind = Encrypt;
  290. fn kind(self) -> Encrypt {
  291. self
  292. }
  293. fn as_enum(self) -> SchemeKind {
  294. SchemeKind::Encrypt(self.kind())
  295. }
  296. fn message_digest(&self) -> MessageDigest {
  297. match self {
  298. Encrypt::RsaEsOaep(inner) => inner.message_digest(),
  299. }
  300. }
  301. fn padding(&self) -> Option<OpensslPadding> {
  302. match self {
  303. Encrypt::RsaEsOaep(inner) => inner.padding(),
  304. }
  305. }
  306. fn public_from_der(self, der: &[u8]) -> Result<PKey<OsslPublic>> {
  307. match self {
  308. Encrypt::RsaEsOaep(inner) => inner.public_from_der(der),
  309. }
  310. }
  311. fn private_from_der(self, der: &[u8]) -> Result<PKey<OsslPrivate>> {
  312. match self {
  313. Encrypt::RsaEsOaep(inner) => inner.private_from_der(der),
  314. }
  315. }
  316. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  317. match self {
  318. Encrypt::RsaEsOaep(inner) => inner.generate(),
  319. }
  320. }
  321. }
  322. impl Encrypt {
  323. pub const RSA_OAEP_3072_SHA_256: Encrypt = Encrypt::RsaEsOaep(RsaEsOaep {
  324. key_bytes: 384,
  325. hash_kind: HashKind::Sha2_256,
  326. });
  327. }
  328. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Copy)]
  329. pub enum Sign {
  330. RsaSsaPss(RsaSsaPss),
  331. }
  332. impl Scheme for Sign {
  333. type Kind = Sign;
  334. fn kind(self) -> Sign {
  335. self
  336. }
  337. fn as_enum(self) -> SchemeKind {
  338. SchemeKind::Sign(self.kind())
  339. }
  340. fn message_digest(&self) -> MessageDigest {
  341. match self {
  342. Sign::RsaSsaPss(inner) => inner.message_digest(),
  343. }
  344. }
  345. fn padding(&self) -> Option<OpensslPadding> {
  346. match self {
  347. Sign::RsaSsaPss(inner) => inner.padding(),
  348. }
  349. }
  350. fn public_from_der(self, der: &[u8]) -> Result<PKey<OsslPublic>> {
  351. match self {
  352. Sign::RsaSsaPss(inner) => inner.public_from_der(der),
  353. }
  354. }
  355. fn private_from_der(self, der: &[u8]) -> Result<PKey<OsslPrivate>> {
  356. match self {
  357. Sign::RsaSsaPss(inner) => inner.private_from_der(der),
  358. }
  359. }
  360. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  361. match self {
  362. Sign::RsaSsaPss(inner) => inner.generate(),
  363. }
  364. }
  365. }
  366. impl Sign {
  367. pub const RSA_PSS_3072_SHA_256: Sign = Sign::RsaSsaPss(RsaSsaPss {
  368. key_bytes: 384,
  369. hash_kind: HashKind::Sha2_256,
  370. });
  371. fn sig_buf(&self) -> Signature {
  372. match self {
  373. Sign::RsaSsaPss(_) => Signature::Rsa([0u8; RSA_KEY_BYTES]),
  374. }
  375. }
  376. }
  377. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Copy)]
  378. pub struct RsaEsOaep {
  379. key_bytes: usize,
  380. hash_kind: HashKind,
  381. }
  382. fn generate_rsa<S: Scheme>(scheme: S) -> Result<AsymKeyPair<S>> {
  383. let key_bits = 8 * u32::try_from(RSA_KEY_BYTES).conv_err()?;
  384. let key = Rsa::generate(key_bits)?;
  385. // TODO: Separating the keys this way seems inefficient. Investigate alternatives.
  386. let public_der = key.public_key_to_der().conv_err()?;
  387. let private_der = key.private_key_to_der().conv_err()?;
  388. let public = AsymKey::<Public, S>::new(scheme, &public_der)?;
  389. let private = AsymKey::<Private, S>::new(scheme, &private_der)?;
  390. Ok(AsymKeyPair { public, private })
  391. }
  392. impl Scheme for RsaEsOaep {
  393. type Kind = Encrypt;
  394. fn kind(self) -> Encrypt {
  395. Encrypt::RsaEsOaep(self)
  396. }
  397. fn as_enum(self) -> SchemeKind {
  398. SchemeKind::Encrypt(self.kind())
  399. }
  400. fn message_digest(&self) -> MessageDigest {
  401. self.hash_kind.into()
  402. }
  403. fn padding(&self) -> Option<OpensslPadding> {
  404. Some(OpensslPadding::PKCS1_OAEP)
  405. }
  406. fn public_from_der(self, der: &[u8]) -> Result<PKey<OsslPublic>> {
  407. PKey::public_key_from_der(der).conv_err()
  408. }
  409. fn private_from_der(self, der: &[u8]) -> Result<PKey<OsslPrivate>> {
  410. PKey::private_key_from_der(der).conv_err()
  411. }
  412. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  413. generate_rsa(self.kind())
  414. }
  415. }
  416. impl From<RsaEsOaep> for Encrypt {
  417. fn from(scheme: RsaEsOaep) -> Self {
  418. scheme.kind()
  419. }
  420. }
  421. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Copy)]
  422. pub struct RsaSsaPss {
  423. key_bytes: usize,
  424. hash_kind: HashKind,
  425. }
  426. impl Scheme for RsaSsaPss {
  427. type Kind = Sign;
  428. fn kind(self) -> Sign {
  429. Sign::RsaSsaPss(self)
  430. }
  431. fn as_enum(self) -> SchemeKind {
  432. SchemeKind::Sign(self.kind())
  433. }
  434. fn message_digest(&self) -> MessageDigest {
  435. self.hash_kind.into()
  436. }
  437. fn padding(&self) -> Option<OpensslPadding> {
  438. Some(OpensslPadding::PKCS1_PSS)
  439. }
  440. fn public_from_der(self, der: &[u8]) -> Result<PKey<OsslPublic>> {
  441. PKey::public_key_from_der(der).conv_err()
  442. }
  443. fn private_from_der(self, der: &[u8]) -> Result<PKey<OsslPrivate>> {
  444. PKey::private_key_from_der(der).conv_err()
  445. }
  446. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  447. generate_rsa(self.kind())
  448. }
  449. }
  450. impl From<RsaSsaPss> for Sign {
  451. fn from(scheme: RsaSsaPss) -> Self {
  452. scheme.kind()
  453. }
  454. }
  455. pub trait KeyPrivacy {}
  456. #[derive(Clone, Debug)]
  457. pub enum Public {}
  458. impl KeyPrivacy for Public {}
  459. unsafe impl HasPublic for Public {}
  460. pub enum Private {}
  461. impl KeyPrivacy for Private {}
  462. unsafe impl HasPrivate for Private {}
  463. fn conv_pkey<T, Q>(pkey: PKey<T>) -> PKey<Q> {
  464. let ptr = pkey.as_ptr();
  465. let new_pkey = unsafe { PKey::from_ptr(ptr) };
  466. std::mem::forget(pkey);
  467. new_pkey
  468. }
  469. fn conv_pkey_pub(pkey: PKey<OsslPublic>) -> PKey<Public> {
  470. conv_pkey(pkey)
  471. }
  472. fn conv_pkey_priv(pkey: PKey<OsslPrivate>) -> PKey<Private> {
  473. conv_pkey(pkey)
  474. }
  475. #[derive(Debug, Clone)]
  476. pub struct AsymKey<P: KeyPrivacy, S: Scheme> {
  477. scheme: S,
  478. pkey: PKey<P>,
  479. }
  480. pub type AsymKeyPub<S> = AsymKey<Public, S>;
  481. impl<P: KeyPrivacy, S: Scheme> AsymKey<P, S> {
  482. fn digest(&self) -> MessageDigest {
  483. self.scheme.message_digest()
  484. }
  485. fn padding(&self) -> Option<OpensslPadding> {
  486. self.scheme.padding()
  487. }
  488. }
  489. impl<S: Scheme> AsymKey<Public, S> {
  490. pub(crate) fn new(scheme: S, der: &[u8]) -> Result<AsymKey<Public, S>> {
  491. let pkey = conv_pkey_pub(scheme.public_from_der(der)?);
  492. Ok(AsymKey { scheme, pkey })
  493. }
  494. fn to_der(&self) -> Result<Vec<u8>> {
  495. self.pkey.public_key_to_der().conv_err()
  496. }
  497. }
  498. impl<S: Scheme> AsymKey<Private, S> {
  499. pub(crate) fn new(scheme: S, der: &[u8]) -> Result<AsymKey<Private, S>> {
  500. let pkey = conv_pkey_priv(scheme.private_from_der(der)?);
  501. Ok(AsymKey { scheme, pkey })
  502. }
  503. }
  504. impl<P: KeyPrivacy> AsymKey<P, Sign> {
  505. fn signature_buf(&self) -> Signature {
  506. self.scheme.sig_buf()
  507. }
  508. }
  509. impl<'de, S: Scheme> Deserialize<'de> for AsymKey<Public, S> {
  510. fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
  511. const FIELDS: &[&str] = &["scheme", "pkey"];
  512. struct StructVisitor<S: Scheme>(PhantomData<S>);
  513. impl<'de, S: Scheme> Visitor<'de> for StructVisitor<S> {
  514. type Value = AsymKey<Public, S>;
  515. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  516. formatter.write_fmt(format_args!("struct {}", stringify!(AsymKey)))
  517. }
  518. fn visit_seq<V: SeqAccess<'de>>(
  519. self, mut seq: V
  520. ) -> std::result::Result<Self::Value, V::Error> {
  521. let scheme: S = seq.next_element()?
  522. .ok_or_else(|| de::Error::missing_field(FIELDS[0]))?;
  523. let der: Vec<u8> = seq.next_element()?
  524. .ok_or_else(|| de::Error::missing_field(FIELDS[1]))?;
  525. AsymKey::<Public, _>::new(scheme, der.as_slice())
  526. .map_err(de::Error::custom)
  527. }
  528. }
  529. d.deserialize_struct(
  530. stringify!(AsymKey), FIELDS, StructVisitor(PhantomData)
  531. )
  532. }
  533. }
  534. impl<S: Scheme> Serialize for AsymKey<Public, S> {
  535. fn serialize<T: Serializer>(&self, s: T) -> std::result::Result<T::Ok, T::Error> {
  536. let mut struct_s = s.serialize_struct(stringify!(AsymKey), 2)?;
  537. struct_s.serialize_field("scheme", &self.scheme)?;
  538. let der = self.pkey.public_key_to_der().unwrap();
  539. struct_s.serialize_field("pkey", der.as_slice())?;
  540. struct_s.end()
  541. }
  542. }
  543. impl<S: Scheme> PartialEq for AsymKey<Public, S> {
  544. fn eq(&self, other: &Self) -> bool {
  545. self.scheme == other.scheme && self.pkey.public_eq(&other.pkey)
  546. }
  547. }
  548. impl Owned for AsymKey<Public, Sign> {
  549. fn owner_of_kind(&self, kind: HashKind) -> Principal {
  550. match kind {
  551. HashKind::Sha2_256 => {
  552. let mut buf = [0; 32];
  553. let der = self.to_der().unwrap();
  554. let bytes = hash(MessageDigest::sha256(), der.as_slice()).unwrap();
  555. buf.copy_from_slice(&*bytes);
  556. Principal(Hash::Sha2_256(buf))
  557. },
  558. HashKind::Sha2_512 => {
  559. let mut buf = [0; 64];
  560. let der = self.to_der().unwrap();
  561. let bytes = hash(MessageDigest::sha512(), der.as_slice()).unwrap();
  562. buf.copy_from_slice(&*bytes);
  563. Principal(Hash::Sha2_512(buf))
  564. }
  565. }
  566. }
  567. }
  568. impl Encrypter for AsymKey<Public, Encrypt> {
  569. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  570. let mut encrypter = OsslEncrypter::new(&self.pkey)?;
  571. if let Some(padding) = self.padding() {
  572. encrypter.set_rsa_padding(padding)?;
  573. }
  574. {
  575. let Encrypt::RsaEsOaep(inner) = self.scheme;
  576. encrypter.set_rsa_oaep_md(inner.message_digest())?;
  577. }
  578. let buffer_len = encrypter.encrypt_len(slice)?;
  579. let mut ciphertext = vec![0; buffer_len];
  580. let ciphertext_len = encrypter.encrypt(slice, &mut ciphertext)?;
  581. ciphertext.truncate(ciphertext_len);
  582. Ok(ciphertext)
  583. }
  584. }
  585. impl Decrypter for AsymKey<Private, Encrypt> {
  586. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  587. let mut decrypter = OsslDecrypter::new(&self.pkey).conv_err()?;
  588. if let Some(padding) = self.padding() {
  589. decrypter.set_rsa_padding(padding).conv_err()?;
  590. }
  591. {
  592. let Encrypt::RsaEsOaep(inner) = self.scheme;
  593. decrypter.set_rsa_oaep_md(inner.message_digest())?;
  594. }
  595. let buffer_len = decrypter.decrypt_len(slice).conv_err()?;
  596. let mut plaintext = vec![0; buffer_len];
  597. let plaintext_len = decrypter.decrypt(slice, &mut plaintext).conv_err()?;
  598. plaintext.truncate(plaintext_len);
  599. Ok(plaintext)
  600. }
  601. }
  602. impl Signer for AsymKey<Private, Sign> {
  603. fn sign<'a, I: Iterator<Item=&'a [u8]>>(&self, parts: I) -> Result<Signature> {
  604. let mut signer = OsslSigner::new(self.scheme.message_digest(), &self.pkey)?;
  605. if let Some(padding) = self.scheme.padding() {
  606. signer.set_rsa_padding(padding)?;
  607. }
  608. for part in parts {
  609. signer.update(part)?;
  610. }
  611. let mut signature = self.scheme.sig_buf();
  612. signer.sign(signature.as_mut_slice())?;
  613. Ok(signature)
  614. }
  615. }
  616. impl Verifier for AsymKey<Public, Sign> {
  617. fn verify<'a, I: Iterator<Item=&'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<bool> {
  618. let mut verifier = OsslVerifier::new(self.digest(), &self.pkey)?;
  619. if let Some(padding) = self.scheme.padding() {
  620. verifier.set_rsa_padding(padding)?;
  621. }
  622. for part in parts {
  623. verifier.update(part)?;
  624. }
  625. Ok(verifier.verify(signature)?)
  626. }
  627. }
  628. pub struct AsymKeyPair<S: Scheme> {
  629. public: AsymKey<Public, S>,
  630. private: AsymKey<Private, S>,
  631. }
  632. impl<S: Scheme> AsymKeyPair<S> {
  633. pub fn new(scheme: S, public_der: &[u8], private_der: &[u8]) -> Result<AsymKeyPair<S>> {
  634. let public = AsymKey::<Public, _>::new(scheme, public_der)?;
  635. let private = AsymKey::<Private, _>::new(scheme, private_der)?;
  636. Ok(AsymKeyPair { public, private })
  637. }
  638. }
  639. impl Owned for AsymKeyPair<Sign> {
  640. fn owner_of_kind(&self, kind: HashKind) -> Principal {
  641. self.public.owner_of_kind(kind)
  642. }
  643. }
  644. impl Encrypter for AsymKeyPair<Encrypt> {
  645. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  646. self.public.encrypt(slice)
  647. }
  648. }
  649. impl Decrypter for AsymKeyPair<Encrypt> {
  650. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  651. self.private.decrypt(slice)
  652. }
  653. }
  654. impl Signer for AsymKeyPair<Sign> {
  655. fn sign<'a, I: Iterator<Item=&'a [u8]>>(&self, parts: I) -> Result<Signature> {
  656. self.private.sign(parts)
  657. }
  658. }
  659. impl Verifier for AsymKeyPair<Sign> {
  660. fn verify<'a, I: Iterator<Item=&'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<bool> {
  661. self.public.verify(parts, signature)
  662. }
  663. }
  664. pub struct ConcreteCreds {
  665. sign: AsymKeyPair<Sign>,
  666. encrypt: AsymKeyPair<Encrypt>,
  667. }
  668. impl ConcreteCreds {
  669. pub(crate) fn new(sign: AsymKeyPair<Sign>, encrypt: AsymKeyPair<Encrypt>) -> ConcreteCreds {
  670. ConcreteCreds { sign, encrypt }
  671. }
  672. pub(crate) fn generate() -> Result<ConcreteCreds> {
  673. let encrypt = Encrypt::RSA_OAEP_3072_SHA_256.generate()?;
  674. let sign = Sign::RSA_PSS_3072_SHA_256.generate()?;
  675. Ok(ConcreteCreds { sign, encrypt })
  676. }
  677. }
  678. impl Verifier for ConcreteCreds {
  679. fn verify<'a, I: Iterator<Item=&'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<bool> {
  680. self.sign.verify(parts, signature)
  681. }
  682. }
  683. impl Encrypter for ConcreteCreds {
  684. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  685. self.encrypt.encrypt(slice)
  686. }
  687. }
  688. impl Owned for ConcreteCreds {
  689. fn owner_of_kind(&self, kind: HashKind) -> Principal {
  690. self.sign.owner_of_kind(kind)
  691. }
  692. }
  693. impl CredsPub for ConcreteCreds {}
  694. impl Signer for ConcreteCreds {
  695. fn sign<'a, I: Iterator<Item=&'a [u8]>>(&self, parts: I) -> Result<Signature> {
  696. self.sign.sign(parts)
  697. }
  698. }
  699. impl Decrypter for ConcreteCreds {
  700. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  701. self.encrypt.decrypt(slice)
  702. }
  703. }
  704. impl CredsPriv for ConcreteCreds {}
  705. impl Creds for ConcreteCreds {
  706. fn public(&self) -> &AsymKey<Public, Sign> {
  707. &self.sign.public
  708. }
  709. }
  710. pub(crate) trait Encrypter {
  711. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>>;
  712. }
  713. pub(crate) trait Decrypter {
  714. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>>;
  715. }
  716. pub(crate) trait Signer {
  717. fn sign<'a, I: Iterator<Item=&'a [u8]>>(&self, parts: I) -> Result<Signature>;
  718. }
  719. pub(crate) trait Verifier {
  720. fn verify<'a, I: Iterator<Item=&'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<bool>;
  721. }
  722. /// Trait for types which can be used as public credentials.
  723. pub(crate) trait CredsPub: Verifier + Encrypter + Owned {}
  724. /// Trait for types which contain private credentials.
  725. pub(crate) trait CredsPriv: Decrypter + Signer {}
  726. /// Trait for types which contain both public and private credentials.
  727. pub(crate) trait Creds: CredsPriv + CredsPub {
  728. fn public(&self) -> &AsymKey<Public, Sign>;
  729. }
  730. /// A trait for types which store credentials.
  731. pub(crate) trait CredStore {
  732. type CredHandle: Creds;
  733. /// Returns the node credentials. If credentials haven't been generated, they are generated
  734. /// stored and returned.
  735. fn node_creds(&self) -> Result<Self::CredHandle>;
  736. /// Returns the root credentials. If no root credentials have been generated, or the provided
  737. /// password is incorrect, then an error is returned.
  738. fn root_creds(&self, password: &str) -> Result<Self::CredHandle>;
  739. /// Generates the root credentials and protects them using the given password. If the root
  740. /// credentials have already been generated then an error is returned.
  741. fn gen_root_creds(&self, password: &str) -> Result<Self::CredHandle>;
  742. }
  743. pub(crate) fn encrypt_block<C: Encrypter + Decrypter>(
  744. mut block: Block, principal: &Principal, creds: &C
  745. ) -> Result<Block> {
  746. let body = match block.body {
  747. Cryptotext::Cipher(_) => return Ok(block),
  748. Cryptotext::Plain(body) => body
  749. };
  750. let (principal_owned, read_cap) = block.readcaps.remove_entry(principal)
  751. .ok_or(Error::NoReadCap)?;
  752. let block_key = decrypt(read_cap, creds)?;
  753. let new_body = block_key.encrypt(&body)?;
  754. block.body = Cryptotext::Cipher(new_body);
  755. block.readcaps.insert(principal_owned, encrypt(&block_key, creds)?);
  756. Ok(block)
  757. }
  758. pub(crate) fn decrypt_block<C: Decrypter>(
  759. mut block: Block, principal: &Principal, creds: &C
  760. ) -> Result<Block> {
  761. let body = match block.body {
  762. Cryptotext::Plain(_) => return Ok(block),
  763. Cryptotext::Cipher(body) => body
  764. };
  765. let (principal_owned, read_cap) = block.readcaps.remove_entry(principal)
  766. .ok_or(Error::NoReadCap)?;
  767. let block_key = decrypt(read_cap, creds)?;
  768. let new_body = block_key.decrypt(&body)?;
  769. block.body = Cryptotext::Plain(new_body);
  770. block.readcaps.insert(principal_owned, Cryptotext::Plain(block_key));
  771. Ok(block)
  772. }
  773. fn encrypt<T: Serialize, K: Encrypter>(value: &T, key: &K) -> Result<Cryptotext<T>> {
  774. let data = to_vec(value).conv_err()?;
  775. let vec = key.encrypt(&data);
  776. Ok(Cryptotext::Cipher(vec?))
  777. }
  778. fn decrypt<T: Serialize + DeserializeOwned, K: Decrypter>(
  779. cryptotext: Cryptotext<T>, key: &K
  780. ) -> Result<T> {
  781. let data = match cryptotext {
  782. Cryptotext::Plain(value) => return Ok(value),
  783. Cryptotext::Cipher(data) => data
  784. };
  785. let vec = key.decrypt(&data);
  786. from_vec(&vec?).conv_err()
  787. }
  788. #[derive(Serialize)]
  789. struct HeaderSigInput<'a> {
  790. path: &'a Path,
  791. readcaps: &'a HashMap<Principal, Cryptotext<SymKey>>,
  792. writecap: &'a Writecap,
  793. }
  794. impl<'a> From<&'a Block> for HeaderSigInput<'a> {
  795. fn from(block: &'a Block) -> HeaderSigInput<'a> {
  796. HeaderSigInput {
  797. path: &block.path,
  798. readcaps: &block.readcaps,
  799. writecap: &block.writecap,
  800. }
  801. }
  802. }
  803. fn get_body(block: &Block) -> Result<&[u8]> {
  804. let body = match &block.body {
  805. Cryptotext::Cipher(body) => body,
  806. Cryptotext::Plain(_) => {
  807. return Err(Error::BlockNotEncrypted);
  808. }
  809. };
  810. Ok(body)
  811. }
  812. pub(crate) fn sign_block<K: Signer>(
  813. block: &mut Block, writecap: Writecap, priv_key: &K
  814. ) -> Result<()> {
  815. block.writecap = writecap;
  816. let body = get_body(block)?;
  817. let sig_input = HeaderSigInput::from(&*block);
  818. let header = to_vec(&sig_input)?;
  819. let signature = priv_key.sign([header.as_slice(), body].into_iter())?;
  820. block.signature = signature;
  821. Ok(())
  822. }
  823. pub(crate) fn verify_block(block: &Block) -> Result<bool> {
  824. let body = get_body(block)?;
  825. let sig_input = HeaderSigInput::from(&*block);
  826. let header = to_vec(&sig_input)?;
  827. let parts = [header.as_slice(), body].into_iter();
  828. block.writecap.signing_key.verify(parts, block.signature.as_slice())
  829. }
  830. #[derive(Serialize)]
  831. struct WritecapSigInput<'a> {
  832. issued_to: &'a Principal,
  833. path: &'a Path,
  834. expires: &'a Epoch,
  835. signing_key: &'a AsymKey<Public, Sign>,
  836. }
  837. impl<'a> From<&'a Writecap> for WritecapSigInput<'a> {
  838. fn from(writecap: &'a Writecap) -> WritecapSigInput<'a> {
  839. WritecapSigInput {
  840. issued_to: &writecap.issued_to,
  841. path: &writecap.path,
  842. expires: &writecap.expires,
  843. signing_key: &writecap.signing_key,
  844. }
  845. }
  846. }
  847. pub(crate) fn sign_writecap<K: Signer>(writecap: &mut Writecap, priv_key: &K) -> Result<()> {
  848. let sig_input = to_vec(&WritecapSigInput::from(&*writecap))?;
  849. writecap.signature = priv_key.sign([sig_input.as_slice()].into_iter())?;
  850. Ok(())
  851. }
  852. /// The types of errors which can occur when verifying a writecap chain is authorized to write to
  853. /// a given path.
  854. #[derive(Debug, PartialEq)]
  855. pub(crate) enum WritecapAuthzErr {
  856. /// The chain is not valid for use on the given path.
  857. UnauthorizedPath,
  858. /// At least one writecap in the chain is expired.
  859. Expired,
  860. /// The given writecaps do not actually form a chain.
  861. NotChained,
  862. /// There is an invalid signature in the chain.
  863. InvalidSignature,
  864. /// The principal the root writecap was issued to does not own the given path.
  865. RootDoesNotOwnPath,
  866. /// An error occurred while serializing a writecap.
  867. Serde(String),
  868. /// A cryptographic error occurred while attempting to verify a writecap.
  869. Crypto(String),
  870. }
  871. /// Verifies that the given `Writecap` actually grants permission to write to the given `Path`.
  872. pub(crate) fn verify_writecap(
  873. mut writecap: &Writecap, path: &Path
  874. ) -> std::result::Result<(), WritecapAuthzErr> {
  875. let mut prev: Option<&Writecap> = None;
  876. let mut sig_input = Vec::new();
  877. let now = Epoch::now();
  878. loop {
  879. if !writecap.path.contains(path) {
  880. return Err(WritecapAuthzErr::UnauthorizedPath);
  881. }
  882. if writecap.expires <= now {
  883. return Err(WritecapAuthzErr::Expired);
  884. }
  885. if let Some(prev) = &prev {
  886. if prev.signing_key.owner_of_kind(writecap.issued_to.kind()) != writecap.issued_to {
  887. return Err(WritecapAuthzErr::NotChained);
  888. }
  889. }
  890. let sig = WritecapSigInput::from(writecap);
  891. sig_input.clear();
  892. write_to(&sig, &mut sig_input).map_err(|e| WritecapAuthzErr::Serde(e.to_string()))?;
  893. let valid = writecap.signing_key
  894. .verify([sig_input.as_slice()].into_iter(), writecap.signature.as_slice())
  895. .map_err(|e| WritecapAuthzErr::Crypto(e.to_string()))?;
  896. if !valid {
  897. return Err(WritecapAuthzErr::InvalidSignature);
  898. }
  899. match &writecap.next {
  900. Some(next) => {
  901. prev = Some(writecap);
  902. writecap = next;
  903. },
  904. None => {
  905. // We're at the root key. As long as the signer of this writecap is the owner of
  906. // the path, then the writecap is valid.
  907. if writecap.signing_key.owner_of_kind(path.owner.kind()) == path.owner {
  908. return Ok(());
  909. }
  910. else {
  911. return Err(WritecapAuthzErr::RootDoesNotOwnPath)
  912. }
  913. }
  914. }
  915. }
  916. }
  917. #[cfg(test)]
  918. mod tests {
  919. use super::*;
  920. use test_helpers::*;
  921. fn encrypt_decrypt_block_test_case<C: Creds>(
  922. mut actual: Block, principal: &Principal, creds: &C
  923. ) -> Result<()> {
  924. let expected = actual.clone();
  925. actual = encrypt_block(actual, principal, creds)?;
  926. let encrypted = match &actual.body {
  927. Cryptotext::Cipher(_) => true,
  928. Cryptotext::Plain(_) => false
  929. };
  930. assert!(encrypted);
  931. actual = decrypt_block(actual, principal, creds)?;
  932. assert_eq!(expected, actual);
  933. Ok(())
  934. }
  935. #[test]
  936. fn encrypt_decrypt_block_aes256cbc() -> Result<()> {
  937. let readcap = make_readcap();
  938. let principal = readcap.issued_to.clone();
  939. let block = make_block_with(readcap)?;
  940. let key = make_key_pair();
  941. encrypt_decrypt_block_test_case(block, &principal, &key)
  942. }
  943. #[test]
  944. fn encrypt_decrypt_block_aes256ctr() -> Result<()> {
  945. let readcap = make_readcap();
  946. let principal = readcap.issued_to.clone();
  947. let block = make_block_with(readcap)?;
  948. let key = make_key_pair();
  949. encrypt_decrypt_block_test_case(block, &principal, &key)
  950. }
  951. #[test]
  952. fn rsa_sign_and_verify() -> Result<()> {
  953. let key = make_key_pair();
  954. let header = b"About: lyrics".as_slice();
  955. let message = b"Everything that feels so good is bad bad bad.".as_slice();
  956. let signature = key.sign([header, message].into_iter())?;
  957. let verified = key.verify([header, message].into_iter(), signature.as_slice())?;
  958. assert_eq!(true, verified);
  959. Ok(())
  960. }
  961. #[test]
  962. fn sign_verify_block_rsa() -> Result<()> {
  963. let readcap = make_readcap();
  964. let principal = readcap.issued_to.clone();
  965. let mut block = make_block_with(readcap)?;
  966. let key = make_key_pair();
  967. let writecap = Writecap {
  968. issued_to: Principal(Hash::Sha2_256(PRINCIPAL)),
  969. path: make_path(vec!["contacts", "emergency"]),
  970. expires: Epoch(1649904316),
  971. signing_key: key.public().clone(),
  972. signature: Signature::Rsa(SIGNATURE),
  973. next: None,
  974. };
  975. block = encrypt_block(block, &principal, &key)?;
  976. sign_block(&mut block, writecap, &key)?;
  977. assert_eq!(true, verify_block(&block)?);
  978. Ok(())
  979. }
  980. #[test]
  981. fn hash_to_string() {
  982. let hash = make_principal().0;
  983. let string = hash.to_string();
  984. assert_eq!("Sha2_256:dSip4J0kurN5VhVo_aTipM-ywOOWrqJuRRVQ7aa-bew", string)
  985. }
  986. #[test]
  987. fn hash_to_string_round_trip() -> Result<()> {
  988. let expected = make_principal().0;
  989. let string = expected.to_string();
  990. let actual = Hash::try_from(string.as_str())?;
  991. assert_eq!(expected, actual);
  992. Ok(())
  993. }
  994. #[test]
  995. fn verify_writecap_valid() -> Result<()> {
  996. let writecap = make_writecap()?;
  997. let result = verify_writecap(&writecap, &writecap.path);
  998. assert_eq!(Ok(()), result);
  999. Ok(())
  1000. }
  1001. #[test]
  1002. fn verify_writecap_invalid_signature() -> Result<()> {
  1003. let mut writecap = make_writecap()?;
  1004. writecap.signature = Signature::default();
  1005. let result = verify_writecap(&writecap, &writecap.path);
  1006. assert_eq!(Err(WritecapAuthzErr::InvalidSignature), result);
  1007. Ok(())
  1008. }
  1009. #[test]
  1010. fn verify_writecap_invalid_path_not_contained() -> Result<()> {
  1011. let writecap = make_writecap()?;
  1012. let mut path = writecap.path.clone();
  1013. path.components.pop();
  1014. // `path` is now a superpath of `writecap.path`, thus the writecap is not authorized to
  1015. // write to it.
  1016. let result = verify_writecap(&writecap, &path);
  1017. assert_eq!(Err(WritecapAuthzErr::UnauthorizedPath), result);
  1018. Ok(())
  1019. }
  1020. #[test]
  1021. fn verify_writecap_invalid_expired() -> Result<()> {
  1022. let mut writecap = make_writecap()?;
  1023. writecap.expires = Epoch::now() - Duration::from_secs(1);
  1024. let result = verify_writecap(&writecap, &writecap.path);
  1025. assert_eq!(Err(WritecapAuthzErr::Expired), result);
  1026. Ok(())
  1027. }
  1028. #[test]
  1029. fn verify_writecap_invalid_not_chained() -> Result<()> {
  1030. let (mut root_writecap, root_key) = make_self_signed_writecap()?;
  1031. root_writecap.issued_to = Principal(Hash::Sha2_256([0; 32]));
  1032. sign_writecap(&mut root_writecap, &root_key)?;
  1033. let node_key = AsymKeyPub::new(Sign::RSA_PSS_3072_SHA_256, NODE_PUBLIC_KEY.as_slice())?;
  1034. let node_principal = node_key.owner();
  1035. let writecap = make_writecap_trusted_by(
  1036. root_writecap, root_key, node_principal, vec!["apps", "contacts"])?;
  1037. let result = verify_writecap(&writecap, &writecap.path);
  1038. assert_eq!(Err(WritecapAuthzErr::NotChained), result);
  1039. Ok(())
  1040. }
  1041. #[test]
  1042. fn verify_writecap_invalid_root_doesnt_own_path() -> Result<()> {
  1043. let (mut root_writecap, root_key) = make_self_signed_writecap()?;
  1044. let owner = Principal(Hash::Sha2_256([0; 32]));
  1045. root_writecap.path = make_path_with_owner(owner, vec![]);
  1046. sign_writecap(&mut root_writecap, &root_key)?;
  1047. let node_key = AsymKeyPub::new(Sign::RSA_PSS_3072_SHA_256, NODE_PUBLIC_KEY.as_slice())?;
  1048. let node_owner = node_key.owner();
  1049. let writecap = make_writecap_trusted_by(
  1050. root_writecap, root_key, node_owner, vec!["apps", "contacts"])?;
  1051. let result = verify_writecap(&writecap, &writecap.path);
  1052. assert_eq!(Err(WritecapAuthzErr::RootDoesNotOwnPath), result);
  1053. Ok(())
  1054. }
  1055. /// Tests that validate the dependencies of this module.
  1056. mod dependency_tests {
  1057. use super::*;
  1058. use openssl::{
  1059. ec::{EcGroup, EcKey},
  1060. nid::Nid,
  1061. };
  1062. /// This test validates that data encrypted with AES 256 CBC can later be decrypted.
  1063. #[test]
  1064. fn aes_256_cbc_roundtrip() {
  1065. use super::*;
  1066. let expected = b"We attack at the crack of noon!";
  1067. let cipher = Cipher::aes_256_cbc();
  1068. let ciphertext = openssl_encrypt(cipher, &KEY, Some(&IV), expected).unwrap();
  1069. let actual = openssl_decrypt(cipher, &KEY, Some(&IV), ciphertext.as_slice()).unwrap();
  1070. assert_eq!(expected, actual.as_slice());
  1071. }
  1072. /// Tests that the keys for the SECP256K1 curve are the expected sizes.
  1073. #[test]
  1074. fn secp256k1_key_lengths() {
  1075. let group = EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
  1076. let key = EcKey::generate(&group).unwrap();
  1077. let public = key.public_key_to_der().unwrap();
  1078. let private = key.private_key_to_der().unwrap();
  1079. let public_len = public.len();
  1080. let private_len = private.len();
  1081. assert_eq!(88, public_len);
  1082. assert_eq!(118, private_len);
  1083. }
  1084. #[test]
  1085. fn ed25519_key_lengths() {
  1086. let key = PKey::generate_x25519().unwrap();
  1087. let public = key.public_key_to_der().unwrap();
  1088. let private = key.private_key_to_der().unwrap();
  1089. let public_len = public.len();
  1090. let private_len = private.len();
  1091. assert_eq!(44, public_len);
  1092. assert_eq!(48, private_len);
  1093. }
  1094. #[test]
  1095. fn rsa_signature_len() -> Result<()> {
  1096. let key = make_key_pair();
  1097. let signature = key.sign([NODE_PUBLIC_KEY.as_slice()].into_iter())?;
  1098. let length = match signature {
  1099. Signature::Rsa(data) => data.len(),
  1100. };
  1101. assert_eq!(RSA_KEY_BYTES, length);
  1102. Ok(())
  1103. }
  1104. }
  1105. }