mod.rs 31 KB

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