crypto.rs 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986
  1. // SPDX-License-Identifier: AGPL-3.0-or-later
  2. pub mod tpm;
  3. pub mod merkle_stream;
  4. pub mod x509;
  5. pub use merkle_stream::MerkleStream;
  6. pub mod secret_stream;
  7. pub use secret_stream::SecretStream;
  8. mod envelope;
  9. pub mod file_cred_store;
  10. pub use envelope::Envelope;
  11. //mod sign_stream;
  12. //pub use sign_stream::SignStream;
  13. use crate::{
  14. btensure, bterr, fmt, io, BigArray, BlockError, BlockMeta, BlockPath, Deserialize, Epoch,
  15. Formatter, Hashable, Principal, Principaled, Result, Serialize, Writecap, WritecapBody,
  16. };
  17. use btserde::{self, from_vec, to_vec, write_to};
  18. use foreign_types::ForeignType;
  19. use log::error;
  20. use openssl::{
  21. encrypt::{Decrypter as OsslDecrypter, Encrypter as OsslEncrypter},
  22. error::ErrorStack,
  23. hash::{hash, DigestBytes, Hasher, MessageDigest},
  24. nid::Nid,
  25. pkcs5::pbkdf2_hmac,
  26. pkey::{HasPrivate, HasPublic, PKey, PKeyRef},
  27. rand::rand_bytes,
  28. rsa::{Padding as OpensslPadding, Rsa as OsslRsa},
  29. sign::{Signer as OsslSigner, Verifier as OsslVerifier},
  30. symm::{decrypt as openssl_decrypt, encrypt as openssl_encrypt, Cipher, Crypter, Mode},
  31. };
  32. use serde::{
  33. de::{self, DeserializeOwned, Deserializer, SeqAccess, Visitor},
  34. ser::{Error as SerError, SerializeStruct, Serializer},
  35. };
  36. use std::{
  37. cell::RefCell,
  38. fmt::Display,
  39. io::{Read, Write},
  40. marker::PhantomData,
  41. ops::{Deref, DerefMut},
  42. sync::Arc,
  43. };
  44. use strum_macros::{Display, EnumDiscriminants, FromRepr};
  45. use zeroize::{ZeroizeOnDrop, Zeroizing};
  46. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)]
  47. pub struct Ciphertext<T> {
  48. data: Vec<u8>,
  49. phantom: PhantomData<T>,
  50. }
  51. impl<T> Ciphertext<T> {
  52. pub fn new(data: Vec<u8>) -> Ciphertext<T> {
  53. Ciphertext {
  54. data,
  55. phantom: PhantomData,
  56. }
  57. }
  58. }
  59. pub struct Signed<T> {
  60. _data: Vec<u8>,
  61. sig: Signature,
  62. phantom: PhantomData<T>,
  63. }
  64. impl<T> Signed<T> {
  65. pub fn new(data: Vec<u8>, sig: Signature) -> Signed<T> {
  66. Signed {
  67. _data: data,
  68. sig,
  69. phantom: PhantomData,
  70. }
  71. }
  72. }
  73. /// Errors that can occur during cryptographic operations.
  74. #[derive(Debug)]
  75. pub enum Error {
  76. NoReadCap,
  77. NoKeyAvailable,
  78. MissingPrivateKey,
  79. KeyVariantUnsupported,
  80. BlockNotEncrypted,
  81. InvalidHashFormat,
  82. InvalidSignature,
  83. IncorrectSize {
  84. expected: usize,
  85. actual: usize,
  86. },
  87. TooSmall {
  88. required: usize,
  89. actual: usize,
  90. },
  91. IndexOutOfBounds {
  92. index: usize,
  93. limit: usize,
  94. },
  95. IndivisibleSize {
  96. divisor: usize,
  97. actual: usize,
  98. },
  99. InvalidOffset {
  100. actual: usize,
  101. limit: usize,
  102. },
  103. HashCmpFailure,
  104. RootHashNotVerified,
  105. SignatureMismatch(Box<SignatureMismatch>),
  106. /// This variant is used to convey errors that originated in an underlying library.
  107. Library(Box<dyn ::std::error::Error + Send + Sync + 'static>),
  108. /// Occurs when an attempt is made to finish an [Op] that is already finished.
  109. OpAlreadyFinished,
  110. /// Indicates that a writecap was not issued to a particular [Principal].
  111. NotIssuedTo,
  112. }
  113. impl Error {
  114. fn signature_mismatch(expected: Principal, actual: Principal) -> Error {
  115. Error::SignatureMismatch(Box::new(SignatureMismatch { expected, actual }))
  116. }
  117. fn library<E: std::error::Error + Send + Sync + 'static>(err: E) -> Error {
  118. Error::Library(Box::new(err))
  119. }
  120. }
  121. impl Display for Error {
  122. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  123. match self {
  124. Error::NoReadCap => write!(f, "no readcap"),
  125. Error::NoKeyAvailable => write!(f, "no key available"),
  126. Error::MissingPrivateKey => write!(f, "private key was missing"),
  127. Error::KeyVariantUnsupported => write!(f, "unsupported key variant"),
  128. Error::BlockNotEncrypted => write!(f, "block was not encrypted"),
  129. Error::InvalidHashFormat => write!(f, "invalid format"),
  130. Error::InvalidSignature => write!(f, "invalid signature"),
  131. Error::IncorrectSize { expected, actual } => {
  132. write!(f, "expected size {expected} but got {actual}")
  133. }
  134. Error::TooSmall { required, actual } => {
  135. write!(f, "expected at least {required} but got {actual}")
  136. }
  137. Error::IndexOutOfBounds { index, limit } => write!(
  138. f,
  139. "index {index} is out of bounds, it must be strictly less than {limit}",
  140. ),
  141. Error::IndivisibleSize { divisor, actual } => write!(
  142. f,
  143. "expected a size which is divisible by {divisor} but got {actual}",
  144. ),
  145. Error::InvalidOffset { actual, limit } => write!(
  146. f,
  147. "offset {actual} is out of bounds, it must be strictly less than {limit}",
  148. ),
  149. Error::HashCmpFailure => write!(f, "hash data are not equal"),
  150. Error::RootHashNotVerified => write!(f, "root hash is not verified"),
  151. Error::SignatureMismatch(mismatch) => {
  152. let actual = &mismatch.actual;
  153. let expected = &mismatch.expected;
  154. write!(
  155. f,
  156. "expected a signature from {expected} but found one from {actual}"
  157. )
  158. }
  159. Error::Library(err) => err.fmt(f),
  160. Error::OpAlreadyFinished => write!(f, "operation is already finished"),
  161. Error::NotIssuedTo => write!(f, "writecap was not issued to the given principal"),
  162. }
  163. }
  164. }
  165. impl std::error::Error for Error {}
  166. impl From<ErrorStack> for Error {
  167. fn from(error: ErrorStack) -> Error {
  168. Error::library(error)
  169. }
  170. }
  171. #[derive(Debug)]
  172. pub struct SignatureMismatch {
  173. pub actual: Principal,
  174. pub expected: Principal,
  175. }
  176. /// Returns an array of the given length filled with cryptographically strong random data.
  177. pub fn rand_array<const LEN: usize>() -> Result<[u8; LEN]> {
  178. let mut array = [0; LEN];
  179. rand_bytes(&mut array)?;
  180. Ok(array)
  181. }
  182. /// Returns a vector of the given length with with cryptographically strong random data.
  183. pub fn rand_vec(len: usize) -> Result<Vec<u8>> {
  184. let mut vec = vec![0; len];
  185. rand_bytes(&mut vec)?;
  186. Ok(vec)
  187. }
  188. /// An ongoing Init-Update-Finish operation.
  189. pub trait Op {
  190. /// Update this operation using the given data.
  191. fn update(&mut self, data: &[u8]) -> Result<()>;
  192. /// Finish this operation and write the result into the given buffer. If the given buffer is not
  193. /// large enough the implementation must return Error::IncorrectSize.
  194. fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize>;
  195. }
  196. impl<T: ?Sized + Op, P: DerefMut<Target = T>> Op for P {
  197. fn update(&mut self, data: &[u8]) -> Result<()> {
  198. self.deref_mut().update(data)
  199. }
  200. fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize> {
  201. self.deref_mut().finish_into(buf)
  202. }
  203. }
  204. /// An ongoing hash hash operation.
  205. pub trait HashOp: Op {
  206. /// The specific hash type which is returned by the finish method.
  207. type Hash: Hash;
  208. /// Returns the kind of hash this operation is computing.
  209. fn kind(&self) -> HashKind;
  210. /// Finish this operation and return a hash type containing the result.
  211. fn finish(&mut self) -> Result<Self::Hash>;
  212. }
  213. // A hash operation which uses OpenSSL.
  214. pub struct OsslHashOp<H> {
  215. hasher: Hasher,
  216. phantom: PhantomData<H>,
  217. kind: HashKind,
  218. }
  219. impl<H> OsslHashOp<H> {
  220. fn new(arg: HashKind) -> Result<Self> {
  221. let hasher = Hasher::new(arg.into())?;
  222. let phantom = PhantomData;
  223. Ok(OsslHashOp {
  224. hasher,
  225. phantom,
  226. kind: arg,
  227. })
  228. }
  229. }
  230. impl<H> Op for OsslHashOp<H> {
  231. fn update(&mut self, data: &[u8]) -> Result<()> {
  232. Ok(self.hasher.update(data)?)
  233. }
  234. fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize> {
  235. if buf.len() < self.kind.len() {
  236. return Err(bterr!(Error::IncorrectSize {
  237. expected: self.kind.len(),
  238. actual: buf.len(),
  239. }));
  240. }
  241. let digest = self.hasher.finish()?;
  242. let slice = digest.as_ref();
  243. buf.copy_from_slice(slice);
  244. Ok(slice.len())
  245. }
  246. }
  247. impl<H: Hash + From<DigestBytes>> HashOp for OsslHashOp<H> {
  248. type Hash = H;
  249. fn kind(&self) -> HashKind {
  250. self.kind
  251. }
  252. fn finish(&mut self) -> Result<Self::Hash> {
  253. let digest = self.hasher.finish()?;
  254. Ok(H::from(digest))
  255. }
  256. }
  257. /// A wrapper which updates a `HashOp` when data is read or written.
  258. pub struct HashStream<T, Op: HashOp> {
  259. inner: T,
  260. op: Op,
  261. update_failed: bool,
  262. }
  263. impl<T, Op: HashOp> HashStream<T, Op> {
  264. /// Create a new `HashWrap`.
  265. pub fn new(inner: T, op: Op) -> HashStream<T, Op> {
  266. HashStream {
  267. inner,
  268. op,
  269. update_failed: false,
  270. }
  271. }
  272. /// Finish this hash operation and write the result into the given buffer. The number of bytes
  273. /// written is returned.
  274. pub fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize> {
  275. if self.update_failed {
  276. return Err(bterr!(
  277. "HashStream::finish_into can't produce result due to HashOp update failure",
  278. ));
  279. }
  280. self.op.finish_into(buf)
  281. }
  282. /// Finish this hash operation and return the resulting hash.
  283. pub fn finish(&mut self) -> Result<Op::Hash> {
  284. if self.update_failed {
  285. return Err(bterr!(
  286. "HashStream::finish can't produce result due to HashOp update failure",
  287. ));
  288. }
  289. self.op.finish()
  290. }
  291. }
  292. impl<T: Read, Op: HashOp> Read for HashStream<T, Op> {
  293. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  294. if self.update_failed {
  295. return Err(bterr!(
  296. "HashStream::read can't continue due to previous HashOp update failure",
  297. )
  298. .into());
  299. }
  300. let read = self.inner.read(buf)?;
  301. if read > 0 {
  302. if let Err(err) = self.op.update(&buf[..read]) {
  303. self.update_failed = true;
  304. error!("HashWrap::read failed to update HashOp: {}", err);
  305. }
  306. }
  307. Ok(read)
  308. }
  309. }
  310. impl<T: Write, Op: HashOp> Write for HashStream<T, Op> {
  311. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  312. self.op.update(buf)?;
  313. self.inner.write(buf)
  314. }
  315. fn flush(&mut self) -> io::Result<()> {
  316. self.inner.flush()
  317. }
  318. }
  319. /// A cryptographic hash.
  320. pub trait Hash: AsRef<[u8]> + AsMut<[u8]> + Sized {
  321. /// The hash operation associated with this `Hash`.
  322. type Op: HashOp;
  323. /// The type of the argument required by `new`.
  324. type Arg;
  325. /// Returns a new `Hash` instance.
  326. fn new(arg: Self::Arg) -> Self;
  327. /// Returns the `HashKind` of self.
  328. fn kind(&self) -> HashKind;
  329. /// Starts a new hash operation.
  330. fn start_op(&self) -> Result<Self::Op>;
  331. }
  332. /// Trait for hash types which can be created with no arguments.
  333. pub trait DefaultHash: Hash {
  334. fn default() -> Self;
  335. }
  336. impl<A: Default, T: Hash<Arg = A>> DefaultHash for T {
  337. fn default() -> Self {
  338. Self::new(A::default())
  339. }
  340. }
  341. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hashable, Clone)]
  342. pub struct Sha2_256([u8; Self::LEN]);
  343. impl Sha2_256 {
  344. pub const KIND: HashKind = HashKind::Sha2_256;
  345. pub const LEN: usize = Self::KIND.len();
  346. }
  347. impl AsRef<[u8]> for Sha2_256 {
  348. fn as_ref(&self) -> &[u8] {
  349. self.0.as_slice()
  350. }
  351. }
  352. impl AsMut<[u8]> for Sha2_256 {
  353. fn as_mut(&mut self) -> &mut [u8] {
  354. self.0.as_mut_slice()
  355. }
  356. }
  357. impl From<DigestBytes> for Sha2_256 {
  358. fn from(value: DigestBytes) -> Self {
  359. let mut hash = Sha2_256::new(());
  360. // TODO: It would be great if there was a way to avoid this copy.
  361. hash.as_mut().copy_from_slice(value.as_ref());
  362. hash
  363. }
  364. }
  365. impl From<[u8; Self::LEN]> for Sha2_256 {
  366. fn from(value: [u8; Self::LEN]) -> Self {
  367. Sha2_256(value)
  368. }
  369. }
  370. impl From<Sha2_256> for [u8; Sha2_256::LEN] {
  371. fn from(value: Sha2_256) -> Self {
  372. value.0
  373. }
  374. }
  375. impl Hash for Sha2_256 {
  376. type Op = OsslHashOp<Sha2_256>;
  377. type Arg = ();
  378. fn new(_: Self::Arg) -> Self {
  379. Sha2_256([0u8; Self::KIND.len()])
  380. }
  381. fn kind(&self) -> HashKind {
  382. Self::KIND
  383. }
  384. fn start_op(&self) -> Result<Self::Op> {
  385. OsslHashOp::new(Self::KIND)
  386. }
  387. }
  388. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hashable, Clone)]
  389. pub struct Sha2_512(#[serde(with = "BigArray")] [u8; Self::LEN]);
  390. impl Sha2_512 {
  391. pub const KIND: HashKind = HashKind::Sha2_512;
  392. pub const LEN: usize = Self::KIND.len();
  393. }
  394. impl AsRef<[u8]> for Sha2_512 {
  395. fn as_ref(&self) -> &[u8] {
  396. self.0.as_slice()
  397. }
  398. }
  399. impl AsMut<[u8]> for Sha2_512 {
  400. fn as_mut(&mut self) -> &mut [u8] {
  401. self.0.as_mut_slice()
  402. }
  403. }
  404. impl From<DigestBytes> for Sha2_512 {
  405. fn from(value: DigestBytes) -> Self {
  406. let mut hash = Sha2_512::new(());
  407. hash.as_mut().copy_from_slice(value.as_ref());
  408. hash
  409. }
  410. }
  411. impl From<[u8; Self::LEN]> for Sha2_512 {
  412. fn from(value: [u8; Self::LEN]) -> Self {
  413. Self(value)
  414. }
  415. }
  416. impl From<Sha2_512> for [u8; Sha2_512::LEN] {
  417. fn from(value: Sha2_512) -> Self {
  418. value.0
  419. }
  420. }
  421. impl Hash for Sha2_512 {
  422. type Op = OsslHashOp<Sha2_512>;
  423. type Arg = ();
  424. fn new(_: Self::Arg) -> Self {
  425. Sha2_512([0u8; Self::LEN])
  426. }
  427. fn kind(&self) -> HashKind {
  428. Self::KIND
  429. }
  430. fn start_op(&self) -> Result<Self::Op> {
  431. OsslHashOp::new(Self::KIND)
  432. }
  433. }
  434. /// One of several concrete hash types.
  435. #[derive(
  436. Debug,
  437. PartialEq,
  438. Eq,
  439. Serialize,
  440. Deserialize,
  441. Hashable,
  442. Clone,
  443. EnumDiscriminants,
  444. PartialOrd,
  445. Ord,
  446. )]
  447. #[strum_discriminants(derive(FromRepr, Display, Serialize, Deserialize))]
  448. #[strum_discriminants(name(HashKind))]
  449. pub enum VarHash {
  450. Sha2_256(Sha2_256),
  451. Sha2_512(Sha2_512),
  452. }
  453. #[allow(clippy::derivable_impls)]
  454. impl Default for HashKind {
  455. fn default() -> HashKind {
  456. HashKind::Sha2_256
  457. }
  458. }
  459. impl Default for VarHash {
  460. fn default() -> Self {
  461. HashKind::default().into()
  462. }
  463. }
  464. impl HashKind {
  465. #[allow(clippy::len_without_is_empty)]
  466. pub const fn len(self) -> usize {
  467. match self {
  468. HashKind::Sha2_256 => 32,
  469. HashKind::Sha2_512 => 64,
  470. }
  471. }
  472. pub fn digest<'a, I: Iterator<Item = &'a [u8]>>(self, dest: &mut [u8], parts: I) -> Result<()> {
  473. btensure!(
  474. dest.len() >= self.len(),
  475. Error::TooSmall {
  476. required: self.len(),
  477. actual: dest.len(),
  478. }
  479. );
  480. let mut hasher = Hasher::new(self.into())?;
  481. for part in parts {
  482. hasher.update(part)?;
  483. }
  484. let hash = hasher.finish()?;
  485. dest[..self.len()].copy_from_slice(&hash);
  486. Ok(())
  487. }
  488. }
  489. /// An implementation of [std::hash::Hasher] which allows cryptographic hash algorithms to be used.
  490. pub struct BtHasher {
  491. hasher: RefCell<Hasher>,
  492. }
  493. impl BtHasher {
  494. pub fn new(kind: HashKind) -> Result<Self> {
  495. btensure!(
  496. kind.len() >= 8,
  497. bterr!("only digests which produce at least 8 bytes are supported")
  498. );
  499. let hasher = RefCell::new(Hasher::new(kind.into())?);
  500. Ok(Self { hasher })
  501. }
  502. }
  503. impl std::hash::Hasher for BtHasher {
  504. fn write(&mut self, bytes: &[u8]) {
  505. let hasher = self.hasher.get_mut();
  506. hasher.update(bytes).unwrap();
  507. }
  508. fn finish(&self) -> u64 {
  509. let mut hasher = self.hasher.borrow_mut();
  510. let hash = hasher.finish().unwrap();
  511. let mut buf = [0u8; 8];
  512. buf.copy_from_slice(&hash[..8]);
  513. u64::from_le_bytes(buf)
  514. }
  515. fn write_u8(&mut self, i: u8) {
  516. self.write(&[i])
  517. }
  518. fn write_u16(&mut self, i: u16) {
  519. self.write(&i.to_le_bytes())
  520. }
  521. fn write_u32(&mut self, i: u32) {
  522. self.write(&i.to_le_bytes())
  523. }
  524. fn write_u64(&mut self, i: u64) {
  525. self.write(&i.to_le_bytes())
  526. }
  527. fn write_u128(&mut self, i: u128) {
  528. self.write(&i.to_le_bytes())
  529. }
  530. fn write_usize(&mut self, i: usize) {
  531. self.write(&i.to_le_bytes())
  532. }
  533. fn write_i8(&mut self, i: i8) {
  534. self.write_u8(i as u8)
  535. }
  536. fn write_i16(&mut self, i: i16) {
  537. self.write_u16(i as u16)
  538. }
  539. fn write_i32(&mut self, i: i32) {
  540. self.write_u32(i as u32)
  541. }
  542. fn write_i64(&mut self, i: i64) {
  543. self.write_u64(i as u64)
  544. }
  545. fn write_i128(&mut self, i: i128) {
  546. self.write_u128(i as u128)
  547. }
  548. fn write_isize(&mut self, i: isize) {
  549. self.write_usize(i as usize)
  550. }
  551. }
  552. impl TryFrom<MessageDigest> for HashKind {
  553. type Error = crate::Error;
  554. fn try_from(value: MessageDigest) -> Result<Self> {
  555. let nid = value.type_();
  556. if Nid::SHA256 == nid {
  557. Ok(HashKind::Sha2_256)
  558. } else if Nid::SHA512 == nid {
  559. Ok(HashKind::Sha2_512)
  560. } else {
  561. Err(bterr!("Unsupported MessageDigest with NID: {:?}", nid))
  562. }
  563. }
  564. }
  565. impl From<HashKind> for MessageDigest {
  566. fn from(kind: HashKind) -> Self {
  567. match kind {
  568. HashKind::Sha2_256 => MessageDigest::sha256(),
  569. HashKind::Sha2_512 => MessageDigest::sha512(),
  570. }
  571. }
  572. }
  573. impl VarHash {
  574. /// The character that's used to separate a hash type from its value in its string
  575. /// representation.
  576. const HASH_SEP: char = '!';
  577. pub fn kind(&self) -> HashKind {
  578. self.into()
  579. }
  580. pub fn as_slice(&self) -> &[u8] {
  581. self.as_ref()
  582. }
  583. pub fn as_mut_slice(&mut self) -> &mut [u8] {
  584. self.as_mut()
  585. }
  586. }
  587. impl From<HashKind> for VarHash {
  588. fn from(kind: HashKind) -> VarHash {
  589. match kind {
  590. HashKind::Sha2_256 => VarHash::Sha2_256(Sha2_256::default()),
  591. HashKind::Sha2_512 => VarHash::Sha2_512(Sha2_512::default()),
  592. }
  593. }
  594. }
  595. impl AsRef<[u8]> for VarHash {
  596. fn as_ref(&self) -> &[u8] {
  597. match self {
  598. VarHash::Sha2_256(arr) => arr.as_ref(),
  599. VarHash::Sha2_512(arr) => arr.as_ref(),
  600. }
  601. }
  602. }
  603. impl AsMut<[u8]> for VarHash {
  604. fn as_mut(&mut self) -> &mut [u8] {
  605. match self {
  606. VarHash::Sha2_256(arr) => arr.as_mut(),
  607. VarHash::Sha2_512(arr) => arr.as_mut(),
  608. }
  609. }
  610. }
  611. impl TryFrom<MessageDigest> for VarHash {
  612. type Error = crate::Error;
  613. fn try_from(value: MessageDigest) -> Result<Self> {
  614. let kind: HashKind = value.try_into()?;
  615. Ok(kind.into())
  616. }
  617. }
  618. impl Hash for VarHash {
  619. type Op = VarHashOp;
  620. type Arg = HashKind;
  621. fn new(arg: Self::Arg) -> Self {
  622. arg.into()
  623. }
  624. fn kind(&self) -> HashKind {
  625. self.kind()
  626. }
  627. fn start_op(&self) -> Result<Self::Op> {
  628. VarHashOp::new(self.kind())
  629. }
  630. }
  631. impl TryFrom<&str> for VarHash {
  632. type Error = crate::Error;
  633. fn try_from(string: &str) -> Result<VarHash> {
  634. let mut split: Vec<&str> = string.split(Self::HASH_SEP).collect();
  635. if split.len() != 2 {
  636. return Err(bterr!(Error::InvalidHashFormat));
  637. };
  638. let second = split.pop().ok_or(Error::InvalidHashFormat)?;
  639. let first = split
  640. .pop()
  641. .ok_or(Error::InvalidHashFormat)?
  642. .parse::<usize>()
  643. .map_err(|_| Error::InvalidHashFormat)?;
  644. let mut hash = VarHash::from(HashKind::from_repr(first).ok_or(Error::InvalidHashFormat)?);
  645. base64_url::decode_to_slice(second, hash.as_mut()).map_err(|_| Error::InvalidHashFormat)?;
  646. Ok(hash)
  647. }
  648. }
  649. impl Display for VarHash {
  650. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  651. let hash_kind: HashKind = self.into();
  652. let hash_data = base64_url::encode(self.as_ref());
  653. write!(f, "{}{}{hash_data}", hash_kind as u32, VarHash::HASH_SEP)
  654. }
  655. }
  656. pub struct VarHashOp {
  657. kind: HashKind,
  658. hasher: Hasher,
  659. }
  660. impl VarHashOp {
  661. pub fn new(arg: HashKind) -> Result<Self> {
  662. let hasher = Hasher::new(arg.into())?;
  663. Ok(VarHashOp { kind: arg, hasher })
  664. }
  665. }
  666. impl Op for VarHashOp {
  667. fn update(&mut self, data: &[u8]) -> Result<()> {
  668. Ok(self.hasher.update(data)?)
  669. }
  670. fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize> {
  671. btensure!(
  672. buf.len() >= self.kind.len(),
  673. bterr!(Error::IncorrectSize {
  674. expected: self.kind.len(),
  675. actual: buf.len(),
  676. })
  677. );
  678. let digest = self.hasher.finish()?;
  679. let slice = digest.as_ref();
  680. buf.copy_from_slice(slice);
  681. Ok(slice.len())
  682. }
  683. }
  684. impl HashOp for VarHashOp {
  685. type Hash = VarHash;
  686. fn kind(&self) -> HashKind {
  687. self.kind
  688. }
  689. fn finish(&mut self) -> Result<Self::Hash> {
  690. let digest = self.hasher.finish()?;
  691. let mut hash: VarHash = self.kind.into();
  692. hash.as_mut().copy_from_slice(digest.as_ref());
  693. Ok(hash)
  694. }
  695. }
  696. /// A cryptographic signature.
  697. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, Default)]
  698. pub struct Signature {
  699. kind: Sign,
  700. data: Vec<u8>,
  701. }
  702. impl Signature {
  703. pub fn new(kind: Sign, data: Vec<u8>) -> Self {
  704. Self { kind, data }
  705. }
  706. pub fn empty(kind: Sign) -> Signature {
  707. let data = vec![0; kind.key_len() as usize];
  708. Signature { kind, data }
  709. }
  710. pub fn copy_from(kind: Sign, from: &[u8]) -> Signature {
  711. let mut data = vec![0; kind.key_len() as usize];
  712. data.as_mut_slice().copy_from_slice(from);
  713. Signature { kind, data }
  714. }
  715. pub fn as_slice(&self) -> &[u8] {
  716. self.data.as_slice()
  717. }
  718. pub fn as_mut_slice(&mut self) -> &mut [u8] {
  719. self.data.as_mut_slice()
  720. }
  721. pub fn scheme(&self) -> Sign {
  722. self.kind
  723. }
  724. pub fn take_data(self) -> Vec<u8> {
  725. self.data
  726. }
  727. }
  728. impl AsRef<[u8]> for Signature {
  729. fn as_ref(&self) -> &[u8] {
  730. self.as_slice()
  731. }
  732. }
  733. impl AsMut<[u8]> for Signature {
  734. fn as_mut(&mut self) -> &mut [u8] {
  735. self.as_mut_slice()
  736. }
  737. }
  738. #[derive(Serialize, Deserialize)]
  739. pub struct TaggedCiphertext<T, U> {
  740. aad: U,
  741. ciphertext: Ciphertext<T>,
  742. tag: Vec<u8>,
  743. }
  744. #[derive(EnumDiscriminants, ZeroizeOnDrop, Serialize, Deserialize, PartialEq, Eq)]
  745. #[strum_discriminants(name(AeadKeyKind))]
  746. #[strum_discriminants(derive(Serialize, Deserialize))]
  747. pub enum AeadKey {
  748. AesGcm256 {
  749. key: [u8; AeadKeyKind::AesGcm256.key_len()],
  750. iv: [u8; AeadKeyKind::AesGcm256.iv_len()],
  751. },
  752. }
  753. impl AeadKeyKind {
  754. const fn key_len(self) -> usize {
  755. match self {
  756. AeadKeyKind::AesGcm256 => 32,
  757. }
  758. }
  759. const fn iv_len(self) -> usize {
  760. match self {
  761. AeadKeyKind::AesGcm256 => 16,
  762. }
  763. }
  764. }
  765. #[derive(Serialize, Deserialize)]
  766. /// Parameters used to derive cryptographic keys from passwords.
  767. pub struct DerivationParams {
  768. iter: usize,
  769. hash: HashKind,
  770. kind: AeadKeyKind,
  771. salt: Vec<u8>,
  772. iv: Vec<u8>,
  773. }
  774. impl DerivationParams {
  775. const PBKDF2_ITER: usize = 1000000;
  776. const PBKDF2_HASH: HashKind = HashKind::Sha2_256;
  777. /// The [AeadKeyKind] of the key derived from this struct.
  778. pub const EXPORT_KEY_KIND: AeadKeyKind = AeadKeyKind::AesGcm256;
  779. /// Creates a new struct containing the default value of all parameters.
  780. pub fn new() -> Result<DerivationParams> {
  781. const_assert!(
  782. DerivationParams::PBKDF2_HASH.len() == DerivationParams::EXPORT_KEY_KIND.key_len()
  783. );
  784. Ok(DerivationParams {
  785. iter: Self::PBKDF2_ITER,
  786. hash: Self::PBKDF2_HASH,
  787. kind: Self::EXPORT_KEY_KIND,
  788. salt: rand_vec(Self::PBKDF2_HASH.len())?,
  789. iv: rand_vec(Self::EXPORT_KEY_KIND.iv_len())?,
  790. })
  791. }
  792. /// Returns an HMAC of the given password based on the parameters in this struct.
  793. pub fn hmac(&self, password: &str) -> Result<Zeroizing<[u8; Self::EXPORT_KEY_KIND.key_len()]>> {
  794. let mut key = Zeroizing::new([0u8; Self::EXPORT_KEY_KIND.key_len()]);
  795. pbkdf2_hmac(
  796. password.as_bytes(),
  797. self.salt.as_slice(),
  798. self.iter,
  799. self.hash.into(),
  800. key.as_mut_slice(),
  801. )?;
  802. Ok(key)
  803. }
  804. /// Derives an [AeadKey] from the given password using the parameters in this struct.
  805. fn derive_key(&self, password: &str) -> Result<AeadKey> {
  806. let key = self.hmac(password)?;
  807. AeadKey::copy_components(self.kind, key.as_slice(), &self.iv)
  808. }
  809. }
  810. fn array_from<const N: usize>(slice: &[u8]) -> Result<[u8; N]> {
  811. let slice_len = slice.len();
  812. btensure!(
  813. N == slice_len,
  814. Error::IncorrectSize {
  815. actual: slice_len,
  816. expected: N,
  817. }
  818. );
  819. let mut array = [0u8; N];
  820. array.copy_from_slice(slice);
  821. Ok(array)
  822. }
  823. impl AeadKey {
  824. pub fn new(kind: AeadKeyKind) -> Result<AeadKey> {
  825. match kind {
  826. AeadKeyKind::AesGcm256 => Ok(AeadKey::AesGcm256 {
  827. key: rand_array()?,
  828. iv: rand_array()?,
  829. }),
  830. }
  831. }
  832. fn copy_components(kind: AeadKeyKind, key_buf: &[u8], iv_buf: &[u8]) -> Result<AeadKey> {
  833. match kind {
  834. AeadKeyKind::AesGcm256 => Ok(AeadKey::AesGcm256 {
  835. key: array_from(key_buf)?,
  836. iv: array_from(iv_buf)?,
  837. }),
  838. }
  839. }
  840. fn encrypt<T: Serialize + DeserializeOwned, U: Serialize + DeserializeOwned>(
  841. &self,
  842. aad: U,
  843. plaintext: &T,
  844. ) -> Result<TaggedCiphertext<T, U>> {
  845. let (cipher, key, iv, mut tag) = match self {
  846. AeadKey::AesGcm256 { key, iv } => (
  847. Cipher::aes_256_gcm(),
  848. key.as_slice(),
  849. iv.as_slice(),
  850. vec![0u8; 16],
  851. ),
  852. };
  853. let aad_data = to_vec(&aad)?;
  854. let plaintext_buf = to_vec(&plaintext)?;
  855. let mut ciphertext = vec![0u8; plaintext_buf.len() + cipher.block_size()];
  856. let mut crypter = Crypter::new(cipher, Mode::Encrypt, key, Some(iv))?;
  857. crypter.aad_update(&aad_data)?;
  858. let mut count = crypter.update(&plaintext_buf, &mut ciphertext)?;
  859. count += crypter.finalize(&mut ciphertext[count..])?;
  860. ciphertext.truncate(count);
  861. crypter.get_tag(&mut tag)?;
  862. Ok(TaggedCiphertext {
  863. aad,
  864. ciphertext: Ciphertext::new(ciphertext),
  865. tag,
  866. })
  867. }
  868. fn decrypt<T: Serialize + DeserializeOwned, U: Serialize + DeserializeOwned>(
  869. &self,
  870. tagged: &TaggedCiphertext<T, U>,
  871. ) -> Result<T> {
  872. let ciphertext = &tagged.ciphertext.data;
  873. let (cipher, key, iv) = match self {
  874. AeadKey::AesGcm256 { key, iv } => {
  875. (Cipher::aes_256_gcm(), key.as_slice(), iv.as_slice())
  876. }
  877. };
  878. let mut plaintext = vec![0u8; ciphertext.len() + cipher.block_size()];
  879. let mut crypter = Crypter::new(cipher, Mode::Decrypt, key, Some(iv))?;
  880. crypter.set_tag(&tagged.tag)?;
  881. let aad_buf = to_vec(&tagged.aad)?;
  882. crypter.aad_update(&aad_buf)?;
  883. let mut count = crypter.update(ciphertext, &mut plaintext)?;
  884. count += crypter.finalize(&mut plaintext[count..])?;
  885. plaintext.truncate(count);
  886. Ok(from_vec(&plaintext)?)
  887. }
  888. }
  889. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, EnumDiscriminants, ZeroizeOnDrop)]
  890. #[strum_discriminants(name(SymKeyKind))]
  891. pub enum SymKey {
  892. /// A key for the AES 256 cipher in Cipher Block Chaining mode. Note that this includes the
  893. /// initialization vector, so that a value of this variant contains all the information needed
  894. /// to fully initialize a cipher context.
  895. Aes256Cbc { key: [u8; 32], iv: [u8; 16] },
  896. /// A key for the AES 256 cipher in counter mode.
  897. Aes256Ctr { key: [u8; 32], iv: [u8; 16] },
  898. }
  899. struct SymParams<'a> {
  900. cipher: Cipher,
  901. key: &'a [u8],
  902. iv: Option<&'a [u8]>,
  903. }
  904. impl SymKey {
  905. pub(crate) fn generate(kind: SymKeyKind) -> Result<SymKey> {
  906. match kind {
  907. SymKeyKind::Aes256Cbc => Ok(SymKey::Aes256Cbc {
  908. key: rand_array()?,
  909. iv: rand_array()?,
  910. }),
  911. SymKeyKind::Aes256Ctr => Ok(SymKey::Aes256Ctr {
  912. key: rand_array()?,
  913. iv: rand_array()?,
  914. }),
  915. }
  916. }
  917. fn params(&self) -> SymParams {
  918. let (cipher, key, iv) = match self {
  919. SymKey::Aes256Cbc { key, iv } => (Cipher::aes_256_cbc(), key, Some(iv.as_slice())),
  920. SymKey::Aes256Ctr { key, iv } => (Cipher::aes_256_ctr(), key, Some(iv.as_slice())),
  921. };
  922. SymParams { cipher, key, iv }
  923. }
  924. fn block_size(&self) -> usize {
  925. let SymParams { cipher, .. } = self.params();
  926. cipher.block_size()
  927. }
  928. // The number of bytes that the plaintext expands by when encrypted.
  929. fn expansion_sz(&self) -> usize {
  930. match self {
  931. SymKey::Aes256Cbc { .. } => 16,
  932. SymKey::Aes256Ctr { .. } => 0,
  933. }
  934. }
  935. pub fn key_slice(&self) -> &[u8] {
  936. let SymParams { key, .. } = self.params();
  937. key
  938. }
  939. pub fn iv_slice(&self) -> Option<&[u8]> {
  940. let SymParams { iv, .. } = self.params();
  941. iv
  942. }
  943. }
  944. impl Encrypter for SymKey {
  945. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  946. let SymParams { cipher, key, iv } = self.params();
  947. Ok(openssl_encrypt(cipher, key, iv, slice)?)
  948. }
  949. }
  950. impl Decrypter for SymKey {
  951. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  952. let SymParams { cipher, key, iv } = self.params();
  953. Ok(openssl_decrypt(cipher, key, iv, slice)?)
  954. }
  955. }
  956. #[allow(clippy::derivable_impls)]
  957. impl Default for SymKeyKind {
  958. fn default() -> Self {
  959. SymKeyKind::Aes256Ctr
  960. }
  961. }
  962. #[repr(u32)]
  963. #[derive(Debug, Display, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
  964. pub enum BitLen {
  965. Bits128 = 16,
  966. Bits256 = 32,
  967. Bits512 = 64,
  968. Bits2048 = 256,
  969. Bits3072 = 384,
  970. Bits4096 = 512,
  971. }
  972. impl BitLen {
  973. const fn bits(self) -> u32 {
  974. 8 * self as u32
  975. }
  976. fn try_from_u32(value: u32) -> Result<Self> {
  977. match value {
  978. 16 => Ok(Self::Bits128),
  979. 32 => Ok(Self::Bits256),
  980. 64 => Ok(Self::Bits512),
  981. 256 => Ok(Self::Bits2048),
  982. 384 => Ok(Self::Bits3072),
  983. 512 => Ok(Self::Bits4096),
  984. _ => Err(bterr!("invalid KeyLen value: {value}")),
  985. }
  986. }
  987. }
  988. impl TryFrom<u32> for BitLen {
  989. type Error = crate::Error;
  990. fn try_from(value: u32) -> std::result::Result<Self, Self::Error> {
  991. Self::try_from_u32(value)
  992. }
  993. }
  994. /// A Cryptographic Scheme. This is a common type for operations such as encrypting, decrypting,
  995. /// signing and verifying.
  996. pub trait Scheme:
  997. DeserializeOwned + Serialize + Copy + std::fmt::Debug + PartialEq + Into<Self::Kind>
  998. {
  999. type Kind: Scheme;
  1000. fn as_enum(self) -> SchemeKind;
  1001. fn hash_kind(&self) -> HashKind;
  1002. fn padding(&self) -> Option<OpensslPadding>;
  1003. fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>>;
  1004. fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>>;
  1005. fn generate(self) -> Result<AsymKeyPair<Self::Kind>>;
  1006. fn key_len(self) -> BitLen;
  1007. fn message_digest(&self) -> MessageDigest {
  1008. self.hash_kind().into()
  1009. }
  1010. }
  1011. pub enum SchemeKind {
  1012. Sign(Sign),
  1013. Encrypt(Encrypt),
  1014. }
  1015. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
  1016. pub enum Encrypt {
  1017. RsaEsOaep(RsaEsOaep),
  1018. }
  1019. impl Scheme for Encrypt {
  1020. type Kind = Encrypt;
  1021. fn as_enum(self) -> SchemeKind {
  1022. SchemeKind::Encrypt(self)
  1023. }
  1024. fn hash_kind(&self) -> HashKind {
  1025. match self {
  1026. Encrypt::RsaEsOaep(inner) => inner.hash_kind(),
  1027. }
  1028. }
  1029. fn padding(&self) -> Option<OpensslPadding> {
  1030. match self {
  1031. Encrypt::RsaEsOaep(inner) => inner.padding(),
  1032. }
  1033. }
  1034. fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
  1035. match self {
  1036. Encrypt::RsaEsOaep(inner) => inner.public_from_der(der),
  1037. }
  1038. }
  1039. fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
  1040. match self {
  1041. Encrypt::RsaEsOaep(inner) => inner.private_from_der(der),
  1042. }
  1043. }
  1044. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  1045. match self {
  1046. Encrypt::RsaEsOaep(inner) => inner.generate(),
  1047. }
  1048. }
  1049. fn key_len(self) -> BitLen {
  1050. match self {
  1051. Encrypt::RsaEsOaep(inner) => inner.key_len(),
  1052. }
  1053. }
  1054. }
  1055. impl Encrypt {
  1056. pub const RSA_OAEP_2048_SHA_256: Encrypt = Encrypt::RsaEsOaep(RsaEsOaep {
  1057. key_len: BitLen::Bits2048,
  1058. hash_kind: HashKind::Sha2_256,
  1059. });
  1060. pub const RSA_OAEP_3072_SHA_256: Encrypt = Encrypt::RsaEsOaep(RsaEsOaep {
  1061. key_len: BitLen::Bits3072,
  1062. hash_kind: HashKind::Sha2_256,
  1063. });
  1064. }
  1065. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
  1066. pub enum Sign {
  1067. RsaSsaPss(RsaSsaPss),
  1068. }
  1069. impl Default for Sign {
  1070. fn default() -> Self {
  1071. Self::RSA_PSS_2048_SHA_256
  1072. }
  1073. }
  1074. impl Scheme for Sign {
  1075. type Kind = Sign;
  1076. fn as_enum(self) -> SchemeKind {
  1077. SchemeKind::Sign(self)
  1078. }
  1079. fn hash_kind(&self) -> HashKind {
  1080. match self {
  1081. Sign::RsaSsaPss(inner) => inner.hash_kind(),
  1082. }
  1083. }
  1084. fn padding(&self) -> Option<OpensslPadding> {
  1085. match self {
  1086. Sign::RsaSsaPss(inner) => inner.padding(),
  1087. }
  1088. }
  1089. fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
  1090. match self {
  1091. Sign::RsaSsaPss(inner) => inner.public_from_der(der),
  1092. }
  1093. }
  1094. fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
  1095. match self {
  1096. Sign::RsaSsaPss(inner) => inner.private_from_der(der),
  1097. }
  1098. }
  1099. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  1100. match self {
  1101. Sign::RsaSsaPss(inner) => inner.generate(),
  1102. }
  1103. }
  1104. fn key_len(self) -> BitLen {
  1105. self.key_len_const()
  1106. }
  1107. }
  1108. impl Sign {
  1109. pub const RSA_PSS_2048_SHA_256: Sign = Sign::RsaSsaPss(RsaSsaPss {
  1110. key_bits: BitLen::Bits2048,
  1111. hash_kind: HashKind::Sha2_256,
  1112. });
  1113. pub const RSA_PSS_3072_SHA_256: Sign = Sign::RsaSsaPss(RsaSsaPss {
  1114. key_bits: BitLen::Bits3072,
  1115. hash_kind: HashKind::Sha2_256,
  1116. });
  1117. const fn key_len_const(self) -> BitLen {
  1118. match self {
  1119. Sign::RsaSsaPss(inner) => inner.key_bits,
  1120. }
  1121. }
  1122. }
  1123. enum Rsa {}
  1124. impl Rsa {
  1125. /// The default public exponent to use for generated RSA keys.
  1126. const EXP: u32 = 65537; // 2**16 + 1
  1127. fn generate<S: Scheme>(scheme: S) -> Result<AsymKeyPair<S>> {
  1128. let key = OsslRsa::generate(scheme.key_len().bits())?;
  1129. // TODO: Separating the keys this way seems inefficient. Investigate alternatives.
  1130. let public_der = key.public_key_to_der()?;
  1131. let private_der = key.private_key_to_der()?;
  1132. let public = AsymKey::<Public, S>::new(scheme, &public_der)?;
  1133. let private = AsymKey::<Private, S>::new(scheme, &private_der)?;
  1134. Ok(AsymKeyPair { public, private })
  1135. }
  1136. }
  1137. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
  1138. pub struct RsaEsOaep {
  1139. key_len: BitLen,
  1140. hash_kind: HashKind,
  1141. }
  1142. impl Scheme for RsaEsOaep {
  1143. type Kind = Encrypt;
  1144. fn as_enum(self) -> SchemeKind {
  1145. SchemeKind::Encrypt(self.into())
  1146. }
  1147. fn hash_kind(&self) -> HashKind {
  1148. self.hash_kind
  1149. }
  1150. fn padding(&self) -> Option<OpensslPadding> {
  1151. Some(OpensslPadding::PKCS1_OAEP)
  1152. }
  1153. fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
  1154. Ok(PKey::public_key_from_der(der)?.conv_pub())
  1155. }
  1156. fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
  1157. Ok(PKey::private_key_from_der(der)?.conv_priv())
  1158. }
  1159. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  1160. Rsa::generate(self.into())
  1161. }
  1162. fn key_len(self) -> BitLen {
  1163. self.key_len
  1164. }
  1165. }
  1166. impl From<RsaEsOaep> for Encrypt {
  1167. fn from(scheme: RsaEsOaep) -> Self {
  1168. Encrypt::RsaEsOaep(scheme)
  1169. }
  1170. }
  1171. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
  1172. pub struct RsaSsaPss {
  1173. key_bits: BitLen,
  1174. hash_kind: HashKind,
  1175. }
  1176. impl Scheme for RsaSsaPss {
  1177. type Kind = Sign;
  1178. fn as_enum(self) -> SchemeKind {
  1179. SchemeKind::Sign(self.into())
  1180. }
  1181. fn hash_kind(&self) -> HashKind {
  1182. self.hash_kind
  1183. }
  1184. fn padding(&self) -> Option<OpensslPadding> {
  1185. Some(OpensslPadding::PKCS1_PSS)
  1186. }
  1187. fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
  1188. Ok(PKey::public_key_from_der(der)?.conv_pub())
  1189. }
  1190. fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
  1191. Ok(PKey::private_key_from_der(der)?.conv_priv())
  1192. }
  1193. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  1194. Rsa::generate(self.into())
  1195. }
  1196. fn key_len(self) -> BitLen {
  1197. self.key_bits
  1198. }
  1199. }
  1200. impl From<RsaSsaPss> for Sign {
  1201. fn from(scheme: RsaSsaPss) -> Self {
  1202. Sign::RsaSsaPss(scheme)
  1203. }
  1204. }
  1205. /// Marker trait for the `Public` and `Private` key privacy types.
  1206. pub trait KeyPrivacy {}
  1207. /// Represents keys which can be shared freely.
  1208. #[derive(Clone, Debug)]
  1209. pub enum Public {}
  1210. impl KeyPrivacy for Public {}
  1211. unsafe impl HasPublic for Public {}
  1212. #[derive(Debug, Clone)]
  1213. /// Represents keys which must be kept confidential.
  1214. pub enum Private {}
  1215. impl KeyPrivacy for Private {}
  1216. unsafe impl HasPrivate for Private {}
  1217. trait PKeyExt<T> {
  1218. /// Converts a PKey<T> to a PKey<U>. This hack allows for converting between openssl's
  1219. /// Public and Private types and ours.
  1220. fn conv_pkey<U>(self) -> PKey<U>;
  1221. /// Convert from openssl's Public type to `crypto::Public`.
  1222. fn conv_pub(self) -> PKey<Public>;
  1223. /// Convert from openssl's Private type to `crypto::Private`.
  1224. fn conv_priv(self) -> PKey<Private>;
  1225. }
  1226. impl<T> PKeyExt<T> for PKey<T> {
  1227. fn conv_pkey<U>(self) -> PKey<U> {
  1228. let ptr = self.as_ptr();
  1229. let new_pkey = unsafe { PKey::from_ptr(ptr) };
  1230. std::mem::forget(self);
  1231. new_pkey
  1232. }
  1233. fn conv_pub(self) -> PKey<Public> {
  1234. self.conv_pkey()
  1235. }
  1236. fn conv_priv(self) -> PKey<Private> {
  1237. self.conv_pkey()
  1238. }
  1239. }
  1240. /// Represents any kind of asymmetric key.
  1241. #[derive(Debug, Clone)]
  1242. pub struct AsymKey<P, S> {
  1243. scheme: S,
  1244. pkey: PKey<P>,
  1245. }
  1246. impl<P, S: Copy> AsymKey<P, S> {
  1247. pub fn scheme(&self) -> S {
  1248. self.scheme
  1249. }
  1250. }
  1251. pub type AsymKeyPub<S> = AsymKey<Public, S>;
  1252. impl<S: Scheme> AsymKey<Public, S> {
  1253. pub(crate) fn new(scheme: S, der: &[u8]) -> Result<AsymKey<Public, S>> {
  1254. let pkey = scheme.public_from_der(der)?;
  1255. Ok(AsymKey { scheme, pkey })
  1256. }
  1257. }
  1258. impl<S: Scheme> AsymKey<Private, S> {
  1259. pub(crate) fn new(scheme: S, der: &[u8]) -> Result<AsymKey<Private, S>> {
  1260. let pkey = scheme.private_from_der(der)?;
  1261. Ok(AsymKey { scheme, pkey })
  1262. }
  1263. pub fn to_der(&self) -> Result<Vec<u8>> {
  1264. self.pkey.private_key_to_der().map_err(|err| err.into())
  1265. }
  1266. }
  1267. macro_rules! impl_asym_key_serialize {
  1268. ($privacy:ty, $ser_lambda:expr) => {
  1269. impl<S: Scheme> Serialize for AsymKey<$privacy, S> {
  1270. fn serialize<T: Serializer>(&self, s: T) -> std::result::Result<T::Ok, T::Error> {
  1271. let mut struct_s = s.serialize_struct(stringify!(AsymKey), 2)?;
  1272. struct_s.serialize_field("scheme", &self.scheme)?;
  1273. let der = $ser_lambda(&self.pkey).map_err(T::Error::custom)?;
  1274. struct_s.serialize_field("pkey", der.as_slice())?;
  1275. struct_s.end()
  1276. }
  1277. }
  1278. };
  1279. }
  1280. impl_asym_key_serialize!(Public, |pkey: &PKey<Public>| pkey.public_key_to_der());
  1281. impl_asym_key_serialize!(Private, |pkey: &PKey<Private>| pkey.private_key_to_der());
  1282. macro_rules! impl_asym_key_deserialize {
  1283. ($privacy:ty) => {
  1284. impl<'de, S: Scheme> Deserialize<'de> for AsymKey<$privacy, S> {
  1285. fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
  1286. const FIELDS: &[&str] = &["scheme", "pkey"];
  1287. struct StructVisitor<S: Scheme>(PhantomData<S>);
  1288. impl<'de, S: Scheme> Visitor<'de> for StructVisitor<S> {
  1289. type Value = AsymKey<$privacy, S>;
  1290. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  1291. formatter.write_fmt(format_args!("struct {}", stringify!(AsymKey)))
  1292. }
  1293. fn visit_seq<V: SeqAccess<'de>>(
  1294. self,
  1295. mut seq: V,
  1296. ) -> std::result::Result<Self::Value, V::Error> {
  1297. let scheme: S = seq
  1298. .next_element()?
  1299. .ok_or_else(|| de::Error::missing_field(FIELDS[0]))?;
  1300. let der: Vec<u8> = seq
  1301. .next_element()?
  1302. .ok_or_else(|| de::Error::missing_field(FIELDS[1]))?;
  1303. AsymKey::<$privacy, _>::new(scheme, der.as_slice())
  1304. .map_err(de::Error::custom)
  1305. }
  1306. }
  1307. d.deserialize_struct(stringify!(AsymKey), FIELDS, StructVisitor(PhantomData))
  1308. }
  1309. }
  1310. };
  1311. }
  1312. impl_asym_key_deserialize!(Public);
  1313. impl_asym_key_deserialize!(Private);
  1314. impl<S: Scheme> PartialEq for AsymKey<Public, S> {
  1315. fn eq(&self, other: &Self) -> bool {
  1316. self.scheme == other.scheme && self.pkey.public_eq(&other.pkey)
  1317. }
  1318. }
  1319. impl Principaled for AsymKey<Public, Sign> {
  1320. fn principal_of_kind(&self, kind: HashKind) -> Principal {
  1321. let der = self.pkey.public_key_to_der().unwrap();
  1322. let bytes = hash(kind.into(), der.as_slice()).unwrap();
  1323. let mut hash_buf = VarHash::from(kind);
  1324. hash_buf.as_mut().copy_from_slice(&bytes);
  1325. Principal(hash_buf)
  1326. }
  1327. }
  1328. impl Encrypter for AsymKey<Public, Encrypt> {
  1329. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1330. let mut encrypter = OsslEncrypter::new(&self.pkey)?;
  1331. if let Some(padding) = self.scheme.padding() {
  1332. encrypter.set_rsa_padding(padding)?;
  1333. }
  1334. {
  1335. let Encrypt::RsaEsOaep(inner) = self.scheme;
  1336. encrypter.set_rsa_oaep_md(inner.message_digest())?;
  1337. }
  1338. let buffer_len = encrypter.encrypt_len(slice)?;
  1339. let mut ciphertext = vec![0; buffer_len];
  1340. let ciphertext_len = encrypter.encrypt(slice, &mut ciphertext)?;
  1341. ciphertext.truncate(ciphertext_len);
  1342. Ok(ciphertext)
  1343. }
  1344. }
  1345. impl Decrypter for AsymKey<Private, Encrypt> {
  1346. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1347. let mut decrypter = OsslDecrypter::new(&self.pkey)?;
  1348. if let Some(padding) = self.scheme.padding() {
  1349. decrypter.set_rsa_padding(padding)?;
  1350. }
  1351. {
  1352. let Encrypt::RsaEsOaep(inner) = self.scheme;
  1353. decrypter.set_rsa_oaep_md(inner.message_digest())?;
  1354. }
  1355. let buffer_len = decrypter.decrypt_len(slice)?;
  1356. let mut plaintext = vec![0; buffer_len];
  1357. let plaintext_len = decrypter.decrypt(slice, &mut plaintext)?;
  1358. plaintext.truncate(plaintext_len);
  1359. Ok(plaintext)
  1360. }
  1361. }
  1362. impl Signer for AsymKey<Private, Sign> {
  1363. fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>> {
  1364. let op = OsslSignOp::new((self.scheme, self.pkey.as_ref()))?;
  1365. Ok(Box::new(op))
  1366. }
  1367. fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature> {
  1368. let mut signer = OsslSigner::new(self.scheme.message_digest(), &self.pkey)?;
  1369. if let Some(padding) = self.scheme.padding() {
  1370. signer.set_rsa_padding(padding)?;
  1371. }
  1372. for part in parts {
  1373. signer.update(part)?;
  1374. }
  1375. let mut signature = Signature::empty(self.scheme);
  1376. signer.sign(signature.as_mut_slice())?;
  1377. Ok(signature)
  1378. }
  1379. fn kind(&self) -> Sign {
  1380. self.scheme
  1381. }
  1382. }
  1383. impl Verifier for AsymKey<Public, Sign> {
  1384. fn init_verify(&self) -> Result<Box<dyn '_ + VerifyOp>> {
  1385. let op = OsslVerifyOp::init(self.scheme, self.pkey.as_ref())?;
  1386. Ok(Box::new(op))
  1387. }
  1388. fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
  1389. let mut verifier = OsslVerifier::new(self.scheme.message_digest(), &self.pkey)?;
  1390. if let Some(padding) = self.scheme.padding() {
  1391. verifier.set_rsa_padding(padding)?;
  1392. }
  1393. for part in parts {
  1394. verifier.update(part)?;
  1395. }
  1396. if verifier.verify(signature)? {
  1397. Ok(())
  1398. } else {
  1399. Err(bterr!(Error::InvalidSignature))
  1400. }
  1401. }
  1402. fn kind(&self) -> Sign {
  1403. self.scheme
  1404. }
  1405. }
  1406. #[derive(Clone, Serialize)]
  1407. pub struct AsymKeyPair<S: Scheme> {
  1408. public: AsymKey<Public, S>,
  1409. private: AsymKey<Private, S>,
  1410. }
  1411. impl<'de, S: Scheme> Deserialize<'de> for AsymKeyPair<S> {
  1412. fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
  1413. const FIELDS: &[&str] = &["public", "private"];
  1414. struct StructVisitor<S: Scheme>(PhantomData<S>);
  1415. impl<'de, S: Scheme> Visitor<'de> for StructVisitor<S> {
  1416. type Value = AsymKeyPair<S>;
  1417. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  1418. formatter.write_fmt(format_args!("struct {}", stringify!(AsymKeyPair)))
  1419. }
  1420. fn visit_seq<V: SeqAccess<'de>>(
  1421. self,
  1422. mut seq: V,
  1423. ) -> std::result::Result<Self::Value, V::Error> {
  1424. let public: AsymKey<Public, S> = seq
  1425. .next_element()?
  1426. .ok_or_else(|| de::Error::missing_field(FIELDS[0]))?;
  1427. let private: AsymKey<Private, S> = seq
  1428. .next_element()?
  1429. .ok_or_else(|| de::Error::missing_field(FIELDS[1]))?;
  1430. Ok(AsymKeyPair { public, private })
  1431. }
  1432. }
  1433. d.deserialize_struct(stringify!(AsymKey), FIELDS, StructVisitor(PhantomData))
  1434. }
  1435. }
  1436. impl<S: Scheme> AsymKeyPair<S> {
  1437. pub fn new(scheme: S, public_der: &[u8], private_der: &[u8]) -> Result<AsymKeyPair<S>> {
  1438. let public = AsymKey::<Public, _>::new(scheme, public_der)?;
  1439. let private = AsymKey::<Private, _>::new(scheme, private_der)?;
  1440. Ok(AsymKeyPair { public, private })
  1441. }
  1442. pub fn public(&self) -> &AsymKey<Public, S> {
  1443. &self.public
  1444. }
  1445. pub fn private(&self) -> &AsymKey<Private, S> {
  1446. &self.private
  1447. }
  1448. }
  1449. // Note that only signing keys are associated with a Principal.
  1450. impl Principaled for AsymKeyPair<Sign> {
  1451. fn principal_of_kind(&self, kind: HashKind) -> Principal {
  1452. self.public.principal_of_kind(kind)
  1453. }
  1454. }
  1455. impl Encrypter for AsymKeyPair<Encrypt> {
  1456. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1457. self.public.encrypt(slice)
  1458. }
  1459. }
  1460. impl Decrypter for AsymKeyPair<Encrypt> {
  1461. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1462. self.private.decrypt(slice)
  1463. }
  1464. }
  1465. impl Signer for AsymKeyPair<Sign> {
  1466. fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>> {
  1467. self.private.init_sign()
  1468. }
  1469. fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature> {
  1470. self.private.sign(parts)
  1471. }
  1472. fn kind(&self) -> Sign {
  1473. self.private.kind()
  1474. }
  1475. }
  1476. impl Verifier for AsymKeyPair<Sign> {
  1477. fn init_verify(&self) -> Result<Box<dyn '_ + VerifyOp>> {
  1478. self.public.init_verify()
  1479. }
  1480. fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
  1481. self.public.verify(parts, signature)
  1482. }
  1483. fn kind(&self) -> Sign {
  1484. self.public.kind()
  1485. }
  1486. }
  1487. #[derive(Debug, Clone, Serialize, Deserialize)]
  1488. pub struct ConcretePub {
  1489. pub sign: AsymKeyPub<Sign>,
  1490. pub enc: AsymKeyPub<Encrypt>,
  1491. }
  1492. impl Principaled for ConcretePub {
  1493. fn principal_of_kind(&self, kind: HashKind) -> Principal {
  1494. self.sign.principal_of_kind(kind)
  1495. }
  1496. }
  1497. impl Encrypter for ConcretePub {
  1498. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1499. self.enc.encrypt(slice)
  1500. }
  1501. }
  1502. impl Verifier for ConcretePub {
  1503. fn init_verify(&self) -> Result<Box<dyn '_ + VerifyOp>> {
  1504. self.sign.init_verify()
  1505. }
  1506. fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
  1507. self.sign.verify(parts, signature)
  1508. }
  1509. fn kind(&self) -> Sign {
  1510. self.sign.kind()
  1511. }
  1512. }
  1513. impl CredsPub for ConcretePub {
  1514. fn public_sign(&self) -> &AsymKey<Public, Sign> {
  1515. &self.sign
  1516. }
  1517. fn concrete_pub(&self) -> ConcretePub {
  1518. self.clone()
  1519. }
  1520. }
  1521. impl PartialEq for ConcretePub {
  1522. fn eq(&self, other: &Self) -> bool {
  1523. self.principal() == other.principal()
  1524. }
  1525. }
  1526. #[derive(Clone, Serialize, Deserialize)]
  1527. pub struct ConcreteCreds {
  1528. sign: AsymKeyPair<Sign>,
  1529. encrypt: AsymKeyPair<Encrypt>,
  1530. writecap: Option<Writecap>,
  1531. }
  1532. impl ConcreteCreds {
  1533. pub fn new(sign: AsymKeyPair<Sign>, encrypt: AsymKeyPair<Encrypt>) -> ConcreteCreds {
  1534. ConcreteCreds {
  1535. sign,
  1536. encrypt,
  1537. writecap: None,
  1538. }
  1539. }
  1540. pub fn generate() -> Result<ConcreteCreds> {
  1541. let encrypt = Encrypt::RSA_OAEP_3072_SHA_256.generate()?;
  1542. let sign = Sign::RSA_PSS_3072_SHA_256.generate()?;
  1543. Ok(ConcreteCreds {
  1544. sign,
  1545. encrypt,
  1546. writecap: None,
  1547. })
  1548. }
  1549. pub fn set_writecap(&mut self, writecap: Writecap) -> Result<()> {
  1550. writecap.assert_issued_to(&self.principal())?;
  1551. self.writecap = Some(writecap);
  1552. Ok(())
  1553. }
  1554. pub fn sign_pair(&self) -> &AsymKeyPair<Sign> {
  1555. &self.sign
  1556. }
  1557. pub fn encrypt_pair(&self) -> &AsymKeyPair<Encrypt> {
  1558. &self.encrypt
  1559. }
  1560. }
  1561. impl Verifier for ConcreteCreds {
  1562. fn init_verify(&self) -> Result<Box<dyn '_ + VerifyOp>> {
  1563. self.sign.init_verify()
  1564. }
  1565. fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
  1566. self.sign.verify(parts, signature)
  1567. }
  1568. fn kind(&self) -> Sign {
  1569. Verifier::kind(&self.sign)
  1570. }
  1571. }
  1572. impl Encrypter for ConcreteCreds {
  1573. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1574. self.encrypt.encrypt(slice)
  1575. }
  1576. }
  1577. impl Principaled for ConcreteCreds {
  1578. fn principal_of_kind(&self, kind: HashKind) -> Principal {
  1579. self.sign.principal_of_kind(kind)
  1580. }
  1581. }
  1582. impl CredsPub for ConcreteCreds {
  1583. fn public_sign(&self) -> &AsymKey<Public, Sign> {
  1584. &self.sign.public
  1585. }
  1586. fn concrete_pub(&self) -> ConcretePub {
  1587. ConcretePub {
  1588. sign: self.sign.public.clone(),
  1589. enc: self.encrypt.public.clone(),
  1590. }
  1591. }
  1592. }
  1593. impl Signer for ConcreteCreds {
  1594. fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>> {
  1595. self.sign.init_sign()
  1596. }
  1597. fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature> {
  1598. self.sign.sign(parts)
  1599. }
  1600. fn kind(&self) -> Sign {
  1601. Signer::kind(&self.sign)
  1602. }
  1603. }
  1604. impl Decrypter for ConcreteCreds {
  1605. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1606. self.encrypt.decrypt(slice)
  1607. }
  1608. }
  1609. impl CredsPriv for ConcreteCreds {
  1610. fn writecap(&self) -> Option<&Writecap> {
  1611. self.writecap.as_ref()
  1612. }
  1613. }
  1614. pub trait Encrypter {
  1615. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>>;
  1616. }
  1617. impl<T: ?Sized + Encrypter, P: Deref<Target = T>> Encrypter for P {
  1618. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1619. self.deref().encrypt(slice)
  1620. }
  1621. }
  1622. pub trait EncrypterExt: Encrypter {
  1623. /// Serializes the given value into a new vector, then encrypts it and returns the resulting
  1624. /// ciphertext.
  1625. fn ser_encrypt<T: Serialize>(&self, value: &T) -> Result<Ciphertext<T>> {
  1626. let data = to_vec(value)?;
  1627. let data = self.encrypt(&data)?;
  1628. Ok(Ciphertext::new(data))
  1629. }
  1630. }
  1631. impl<T: Encrypter + ?Sized> EncrypterExt for T {}
  1632. pub trait Decrypter {
  1633. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>>;
  1634. }
  1635. impl<T: ?Sized + Decrypter, P: Deref<Target = T>> Decrypter for P {
  1636. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1637. self.deref().decrypt(slice)
  1638. }
  1639. }
  1640. pub trait DecrypterExt: Decrypter {
  1641. fn ser_decrypt<T: DeserializeOwned>(&self, ct: &Ciphertext<T>) -> Result<T> {
  1642. let pt = self.decrypt(ct.data.as_slice())?;
  1643. Ok(from_vec(&pt)?)
  1644. }
  1645. }
  1646. impl<T: Decrypter + ?Sized> DecrypterExt for T {}
  1647. /// Represents an ongoing signing operation.
  1648. pub trait SignOp: Op {
  1649. /// Returns the signature scheme that this operation is using.
  1650. fn scheme(&self) -> Sign;
  1651. /// Finishes this signature operation and returns a new signature containing the result.
  1652. fn finish(&mut self) -> Result<Signature> {
  1653. let scheme = self.scheme();
  1654. let mut sig = Signature::empty(scheme);
  1655. self.finish_into(sig.as_mut())?;
  1656. Ok(sig)
  1657. }
  1658. }
  1659. impl<T: ?Sized + SignOp, P: DerefMut<Target = T>> SignOp for P {
  1660. fn scheme(&self) -> Sign {
  1661. self.deref().scheme()
  1662. }
  1663. }
  1664. pub struct OsslSignOp<'a> {
  1665. signer: OsslSigner<'a>,
  1666. scheme: Sign,
  1667. }
  1668. impl<'a> OsslSignOp<'a> {
  1669. pub fn new(arg: (Sign, &'a PKeyRef<Private>)) -> Result<Self> {
  1670. let scheme = arg.0;
  1671. let mut signer = OsslSigner::new(arg.0.message_digest(), arg.1)?;
  1672. if let Some(padding) = scheme.padding() {
  1673. signer.set_rsa_padding(padding)?;
  1674. }
  1675. Ok(OsslSignOp { signer, scheme })
  1676. }
  1677. }
  1678. impl<'a> Op for OsslSignOp<'a> {
  1679. fn update(&mut self, data: &[u8]) -> Result<()> {
  1680. Ok(self.signer.update(data)?)
  1681. }
  1682. fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize> {
  1683. Ok(self.signer.sign(buf)?)
  1684. }
  1685. }
  1686. impl<'a> SignOp for OsslSignOp<'a> {
  1687. fn scheme(&self) -> Sign {
  1688. self.scheme
  1689. }
  1690. }
  1691. /// A struct which computes a signature over data as it is written to it.
  1692. pub struct SignWrite<T, Op> {
  1693. inner: T,
  1694. op: Op,
  1695. }
  1696. impl<T, Op: SignOp> SignWrite<T, Op> {
  1697. pub fn new(inner: T, op: Op) -> Self {
  1698. SignWrite { inner, op }
  1699. }
  1700. pub fn finish_into(mut self, buf: &mut [u8]) -> Result<(usize, T)> {
  1701. Ok((self.op.finish_into(buf)?, self.inner))
  1702. }
  1703. pub fn finish(mut self) -> Result<(Signature, T)> {
  1704. Ok((self.op.finish()?, self.inner))
  1705. }
  1706. }
  1707. impl<T: Write, Op: SignOp> Write for SignWrite<T, Op> {
  1708. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  1709. self.op.update(buf)?;
  1710. self.inner.write(buf)
  1711. }
  1712. fn flush(&mut self) -> io::Result<()> {
  1713. self.inner.flush()
  1714. }
  1715. }
  1716. pub trait Signer {
  1717. /// Starts a new signing operation and returns the struct representing it.
  1718. fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>>;
  1719. /// Returns a signature over the given parts. It's critical that subsequent invocations
  1720. /// of this method on the same instance return a [Signature] with `data` fields of the same
  1721. /// length.
  1722. fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature>;
  1723. fn sign_writecap(&self, writecap: &mut Writecap) -> Result<()> {
  1724. let signed = self.ser_sign(&writecap.body)?;
  1725. writecap.signature = signed.sig;
  1726. Ok(())
  1727. }
  1728. fn kind(&self) -> Sign;
  1729. }
  1730. impl<T: ?Sized + Signer> Signer for &T {
  1731. fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>> {
  1732. (*self).init_sign()
  1733. }
  1734. fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature> {
  1735. (*self).sign(parts)
  1736. }
  1737. fn kind(&self) -> Sign {
  1738. (*self).kind()
  1739. }
  1740. }
  1741. impl<T: ?Sized + Signer> Signer for Arc<T> {
  1742. fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>> {
  1743. self.deref().init_sign()
  1744. }
  1745. fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature> {
  1746. self.deref().sign(parts)
  1747. }
  1748. fn kind(&self) -> Sign {
  1749. self.deref().kind()
  1750. }
  1751. }
  1752. pub trait SignerExt: Signer {
  1753. fn ser_sign<T: Serialize>(&self, value: &T) -> Result<Signed<T>> {
  1754. let data = to_vec(value)?;
  1755. let sig = self.sign(&mut std::iter::once(data.as_slice()))?;
  1756. Ok(Signed::new(data, sig))
  1757. }
  1758. fn ser_sign_into<T: Serialize>(&self, value: &T, buf: &mut Vec<u8>) -> Result<Signature> {
  1759. write_to(value, &mut *buf)?;
  1760. self.sign(&mut std::iter::once(buf.as_slice()))
  1761. }
  1762. }
  1763. impl<T: ?Sized + Signer> SignerExt for T {}
  1764. pub trait VerifyOp {
  1765. fn update(&mut self, data: &[u8]) -> Result<()>;
  1766. fn finish(&mut self, sig: &[u8]) -> Result<()>;
  1767. fn scheme(&self) -> Sign;
  1768. }
  1769. impl<T: ?Sized + VerifyOp, P: DerefMut<Target = T>> VerifyOp for P {
  1770. fn update(&mut self, data: &[u8]) -> Result<()> {
  1771. self.deref_mut().update(data)
  1772. }
  1773. fn finish(&mut self, sig: &[u8]) -> Result<()> {
  1774. self.deref_mut().finish(sig)
  1775. }
  1776. fn scheme(&self) -> Sign {
  1777. self.deref().scheme()
  1778. }
  1779. }
  1780. pub struct OsslVerifyOp<'a> {
  1781. verifier: OsslVerifier<'a>,
  1782. scheme: Sign,
  1783. }
  1784. impl<'a> OsslVerifyOp<'a> {
  1785. pub fn init(scheme: Sign, pkey: &'a PKeyRef<Public>) -> Result<Self> {
  1786. let mut verifier = OsslVerifier::new(scheme.message_digest(), pkey)?;
  1787. if let Some(padding) = scheme.padding() {
  1788. verifier.set_rsa_padding(padding)?;
  1789. }
  1790. Ok(OsslVerifyOp { verifier, scheme })
  1791. }
  1792. }
  1793. impl<'a> VerifyOp for OsslVerifyOp<'a> {
  1794. fn update(&mut self, data: &[u8]) -> Result<()> {
  1795. Ok(self.verifier.update(data)?)
  1796. }
  1797. fn finish(&mut self, sig: &[u8]) -> Result<()> {
  1798. match self.verifier.verify(sig) {
  1799. Ok(true) => Ok(()),
  1800. Ok(false) => Err(bterr!(Error::InvalidSignature)),
  1801. Err(err) => Err(err.into()),
  1802. }
  1803. }
  1804. fn scheme(&self) -> Sign {
  1805. self.scheme
  1806. }
  1807. }
  1808. pub struct VerifyRead<T, Op> {
  1809. inner: T,
  1810. op: Op,
  1811. update_failed: bool,
  1812. }
  1813. impl<T: Read, Op: VerifyOp> VerifyRead<T, Op> {
  1814. pub fn new(inner: T, op: Op) -> Self {
  1815. VerifyRead {
  1816. inner,
  1817. op,
  1818. update_failed: false,
  1819. }
  1820. }
  1821. pub fn finish(mut self, sig: &[u8]) -> std::result::Result<T, (T, crate::Error)> {
  1822. if self.update_failed {
  1823. return Err((
  1824. self.inner,
  1825. bterr!("VerifyRead::finish: update_failed was true"),
  1826. ));
  1827. }
  1828. match self.op.finish(sig) {
  1829. Ok(_) => Ok(self.inner),
  1830. Err(err) => Err((self.inner, err)),
  1831. }
  1832. }
  1833. }
  1834. impl<T: Read, Op: VerifyOp> Read for VerifyRead<T, Op> {
  1835. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  1836. if self.update_failed {
  1837. return Err(bterr!("VerifyRead::read update previously failed").into());
  1838. }
  1839. let read = self.inner.read(buf)?;
  1840. if read > 0 {
  1841. if let Err(err) = self.op.update(&buf[..read]) {
  1842. self.update_failed = true;
  1843. error!("VerifyRead::read failed to update VerifyOp: {err}");
  1844. }
  1845. }
  1846. Ok(read)
  1847. }
  1848. }
  1849. pub trait Verifier {
  1850. fn init_verify(&self) -> Result<Box<dyn '_ + VerifyOp>>;
  1851. fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()>;
  1852. fn kind(&self) -> Sign;
  1853. }
  1854. impl<V: ?Sized + Verifier> Verifier for &V {
  1855. fn init_verify<'a>(&'a self) -> Result<Box<dyn 'a + VerifyOp>> {
  1856. self.deref().init_verify()
  1857. }
  1858. fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
  1859. self.deref().verify(parts, signature)
  1860. }
  1861. fn kind(&self) -> Sign {
  1862. self.deref().kind()
  1863. }
  1864. }
  1865. impl<V: ?Sized + Verifier> Verifier for Arc<V> {
  1866. fn init_verify<'a>(&'a self) -> Result<Box<dyn 'a + VerifyOp>> {
  1867. self.deref().init_verify()
  1868. }
  1869. fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
  1870. self.deref().verify(parts, signature)
  1871. }
  1872. fn kind(&self) -> Sign {
  1873. self.deref().kind()
  1874. }
  1875. }
  1876. pub trait VerifierExt: Verifier {
  1877. fn ser_verify<T: Serialize>(&self, value: &T, signature: &[u8]) -> Result<()>;
  1878. }
  1879. impl<V: ?Sized + Verifier> VerifierExt for V {
  1880. fn ser_verify<T: Serialize>(&self, value: &T, signature: &[u8]) -> Result<()> {
  1881. let data = to_vec(value)?;
  1882. self.verify(&mut std::iter::once(data.as_slice()), signature)
  1883. }
  1884. }
  1885. /// Trait for types which can be used as public credentials.
  1886. pub trait CredsPub: Verifier + Encrypter + Principaled {
  1887. /// Returns a reference to the public signing key which can be used to verify signatures.
  1888. fn public_sign(&self) -> &AsymKey<Public, Sign>;
  1889. fn concrete_pub(&self) -> ConcretePub;
  1890. fn sign_kind(&self) -> Sign {
  1891. Verifier::kind(self)
  1892. }
  1893. }
  1894. impl<T: ?Sized + CredsPub> CredsPub for &T {
  1895. fn public_sign(&self) -> &AsymKey<Public, Sign> {
  1896. (*self).public_sign()
  1897. }
  1898. fn concrete_pub(&self) -> ConcretePub {
  1899. (*self).concrete_pub()
  1900. }
  1901. }
  1902. impl<T: ?Sized + CredsPub> CredsPub for Arc<T> {
  1903. fn public_sign(&self) -> &AsymKey<Public, Sign> {
  1904. self.deref().public_sign()
  1905. }
  1906. fn concrete_pub(&self) -> ConcretePub {
  1907. self.deref().concrete_pub()
  1908. }
  1909. }
  1910. /// Trait for types which contain private credentials.
  1911. pub trait CredsPriv: Decrypter + Signer {
  1912. /// Returns a reference to the writecap associated with these credentials, if one has been
  1913. /// issued.
  1914. fn writecap(&self) -> Option<&Writecap>;
  1915. fn sign_kind(&self) -> Sign {
  1916. Signer::kind(self)
  1917. }
  1918. /// Returns the path these credentials are authorized to bind to according,
  1919. /// as specified by their [Writecap]. If these creds haven't been issued a [Writecap], then
  1920. /// an `Err` variant containing [BlockError::MissingWritecap] is returned.
  1921. fn bind_path(&self) -> Result<BlockPath> {
  1922. Ok(self
  1923. .writecap()
  1924. .ok_or(BlockError::MissingWritecap)?
  1925. .bind_path())
  1926. }
  1927. }
  1928. impl<T: ?Sized + CredsPriv> CredsPriv for &T {
  1929. fn writecap(&self) -> Option<&Writecap> {
  1930. (*self).writecap()
  1931. }
  1932. }
  1933. impl<T: ?Sized + CredsPriv> CredsPriv for Arc<T> {
  1934. fn writecap(&self) -> Option<&Writecap> {
  1935. self.deref().writecap()
  1936. }
  1937. }
  1938. /// Trait for types which contain both public and private credentials.
  1939. pub trait Creds: CredsPriv + CredsPub + Send + Sync {
  1940. fn issue_writecap(
  1941. &self,
  1942. issued_to: Principal,
  1943. path_components: Vec<String>,
  1944. expires: Epoch,
  1945. ) -> Result<Writecap> {
  1946. // The root principal is given by the path in our writecap, or if we don't have a writecap,
  1947. // then we assume we are the root principal.
  1948. let root_principal = self
  1949. .writecap()
  1950. .map(|e| e.root_principal())
  1951. .unwrap_or_else(|| self.principal());
  1952. let path = BlockPath::new(root_principal, path_components);
  1953. let body = WritecapBody {
  1954. issued_to,
  1955. path,
  1956. expires,
  1957. signing_key: self.public_sign().to_owned(),
  1958. };
  1959. let signed = self.ser_sign(&body)?;
  1960. Ok(Writecap {
  1961. body,
  1962. signature: signed.sig,
  1963. next: self.writecap().map(|e| Box::new(e.to_owned())),
  1964. })
  1965. }
  1966. fn pub_sign_kind(&self) -> Sign {
  1967. CredsPub::sign_kind(self)
  1968. }
  1969. fn priv_sign_kind(&self) -> Sign {
  1970. CredsPriv::sign_kind(self)
  1971. }
  1972. }
  1973. impl<C: ?Sized + CredsPriv + CredsPub + Send + Sync> Creds for C {}
  1974. /// A trait for types which store credentials.
  1975. pub trait CredStore {
  1976. /// The type of the credential handle returned by this store.
  1977. type CredHandle: Creds;
  1978. /// The type of the exported credentials returned by this store.
  1979. type ExportedCreds: Serialize + DeserializeOwned;
  1980. /// Returns the node credentials. If credentials haven't been generated, they are generated
  1981. /// stored and returned.
  1982. fn node_creds(&self) -> Result<Self::CredHandle>;
  1983. /// Returns the root credentials. If no root credentials have been generated, or the provided
  1984. /// password is incorrect, then an error is returned.
  1985. fn root_creds(&self, password: &str) -> Result<Self::CredHandle>;
  1986. /// Generates the root credentials and protects them using the given password. If the root
  1987. /// credentials have already been generated then an error is returned.
  1988. fn gen_root_creds(&self, password: &str) -> Result<Self::CredHandle>;
  1989. /// Returns a public key which can be used to encrypt data intended only to be accessed by this
  1990. /// node. The returned key can be given as the `new_parent` parameter to the [export_root_creds]
  1991. /// method.
  1992. fn storage_key(&self) -> Result<AsymKeyPub<Encrypt>>;
  1993. /// Exports the root credentials. These can be serialized and persisted external to the
  1994. /// application and later loaded and deserialized and passed to the [import_root_creds] method.
  1995. /// The `password` argument must match the value provided when the [root_creds] method was
  1996. /// called. The `new_parent` argument is the public key of the node that is to import the root
  1997. /// key, which can be obtained using the [gen_root_creds] method on the importing node.
  1998. fn export_root_creds(
  1999. &self,
  2000. root_creds: &Self::CredHandle,
  2001. password: &str,
  2002. new_parent: &AsymKeyPub<Encrypt>,
  2003. ) -> Result<Self::ExportedCreds>;
  2004. /// Imports root credentials that were previously created with [export_root_creds]. The provided
  2005. /// password must match the value that given to that method.
  2006. fn import_root_creds(
  2007. &self,
  2008. password: &str,
  2009. exported: Self::ExportedCreds,
  2010. ) -> Result<Self::CredHandle>;
  2011. /// Assigns the given [Writecap] to the node credentials referred to by the given handle.
  2012. /// This method is responsible for committing the given [Writecap] to durable storage.
  2013. fn assign_node_writecap(&self, handle: &mut Self::CredHandle, writecap: Writecap)
  2014. -> Result<()>;
  2015. /// Assigns `writecap` to the root credentials referred to by `handle`. This method
  2016. /// is responsible for committing the given [Writecap] to durable storage.
  2017. fn assign_root_writecap(&self, handle: &mut Self::CredHandle, writecap: Writecap)
  2018. -> Result<()>;
  2019. /// Generates new root credentials protected by `password` and issues them a self-signed
  2020. /// [Writecap] which expires after `valid_for`. The newly generated root credentials are
  2021. /// returned.
  2022. fn provision_root(&self, password: &str, expires: Epoch) -> Result<Self::CredHandle> {
  2023. let mut root_creds = self.gen_root_creds(password)?;
  2024. let writecap = root_creds.issue_writecap(root_creds.principal(), vec![], expires)?;
  2025. self.assign_root_writecap(&mut root_creds, writecap)?;
  2026. Ok(root_creds)
  2027. }
  2028. /// Begin the provisioning process for a node by generating a new set of node credentials. The
  2029. /// [Principal] of the newly generated credentials is returned. This [Principal] may then be
  2030. /// transmitted to a root node which can use it to issue a [Writecap] to this node.
  2031. fn provision_node_start(&self) -> Result<Principal> {
  2032. let node_creds = self.node_creds()?;
  2033. Ok(node_creds.principal())
  2034. }
  2035. /// Assigns the given [Writecap] to the node credentials and commits it to durable storage.
  2036. /// A handle to the node credentials is returned.
  2037. fn provision_node_finish(&self, writecap: Writecap) -> Result<Self::CredHandle> {
  2038. let mut node_creds = self.node_creds()?;
  2039. self.assign_node_writecap(&mut node_creds, writecap)?;
  2040. Ok(node_creds)
  2041. }
  2042. }
  2043. impl<T: ?Sized + CredStore, P: Deref<Target = T>> CredStore for P {
  2044. type CredHandle = T::CredHandle;
  2045. type ExportedCreds = T::ExportedCreds;
  2046. fn node_creds(&self) -> Result<Self::CredHandle> {
  2047. self.deref().node_creds()
  2048. }
  2049. fn root_creds(&self, password: &str) -> Result<Self::CredHandle> {
  2050. self.deref().root_creds(password)
  2051. }
  2052. fn gen_root_creds(&self, password: &str) -> Result<Self::CredHandle> {
  2053. self.deref().gen_root_creds(password)
  2054. }
  2055. fn storage_key(&self) -> Result<AsymKeyPub<Encrypt>> {
  2056. self.deref().storage_key()
  2057. }
  2058. fn export_root_creds(
  2059. &self,
  2060. root_creds: &Self::CredHandle,
  2061. password: &str,
  2062. new_parent: &AsymKeyPub<Encrypt>,
  2063. ) -> Result<Self::ExportedCreds> {
  2064. self.deref()
  2065. .export_root_creds(root_creds, password, new_parent)
  2066. }
  2067. fn import_root_creds(
  2068. &self,
  2069. password: &str,
  2070. exported: Self::ExportedCreds,
  2071. ) -> Result<Self::CredHandle> {
  2072. self.deref().import_root_creds(password, exported)
  2073. }
  2074. fn assign_node_writecap(
  2075. &self,
  2076. handle: &mut Self::CredHandle,
  2077. writecap: Writecap,
  2078. ) -> Result<()> {
  2079. self.deref().assign_node_writecap(handle, writecap)
  2080. }
  2081. fn assign_root_writecap(
  2082. &self,
  2083. handle: &mut Self::CredHandle,
  2084. writecap: Writecap,
  2085. ) -> Result<()> {
  2086. self.deref().assign_root_writecap(handle, writecap)
  2087. }
  2088. }
  2089. impl BlockMeta {
  2090. /// Validates that this metadata struct contains a valid writecap, that this writecap is
  2091. /// permitted to write to the path of this block and that the signature in this metadata struct
  2092. /// is valid and matches the key the writecap was issued to.
  2093. pub fn assert_valid(&self, path: &BlockPath) -> Result<()> {
  2094. let body = &self.body;
  2095. let writecap = body
  2096. .writecap
  2097. .as_ref()
  2098. .ok_or(crate::BlockError::MissingWritecap)?;
  2099. writecap.assert_valid_for(path)?;
  2100. let signed_by = body.signing_key.principal();
  2101. if writecap.body.issued_to != signed_by {
  2102. return Err(bterr!(Error::signature_mismatch(
  2103. writecap.body.issued_to.clone(),
  2104. signed_by,
  2105. )));
  2106. }
  2107. body.signing_key.ser_verify(&body, self.sig.as_slice())
  2108. }
  2109. }
  2110. /// The types of errors which can occur when verifying a writecap chain is authorized to write to
  2111. /// a given path.
  2112. #[derive(Debug, PartialEq, Eq, Display)]
  2113. pub enum WritecapAuthzErr {
  2114. /// The chain is not valid for use on the given path.
  2115. UnauthorizedPath,
  2116. /// At least one writecap in the chain is expired.
  2117. Expired,
  2118. /// The given writecaps do not actually form a chain.
  2119. NotChained,
  2120. /// The principal the root writecap was issued to does not own the given path.
  2121. RootDoesNotOwnPath,
  2122. /// An error occurred while serializing a writecap.
  2123. Serde(String),
  2124. /// The write cap chain was too long to be validated. The value contained in this error is
  2125. /// the maximum allowed length.
  2126. ChainTooLong(usize),
  2127. }
  2128. impl Writecap {
  2129. /// Verifies that the given [Writecap] actually grants permission to write to the given
  2130. /// [BlockPath].
  2131. pub fn assert_valid_for(&self, path: &BlockPath) -> Result<()> {
  2132. let mut writecap = self;
  2133. const CHAIN_LEN_LIMIT: usize = 256;
  2134. let mut prev: Option<&Writecap> = None;
  2135. let mut sig_input_buf = Vec::new();
  2136. let now = Epoch::now();
  2137. for _ in 0..CHAIN_LEN_LIMIT {
  2138. if !writecap.body.path.contains(path) {
  2139. return Err(bterr!(WritecapAuthzErr::UnauthorizedPath));
  2140. }
  2141. if writecap.body.expires <= now {
  2142. return Err(bterr!(WritecapAuthzErr::Expired));
  2143. }
  2144. if let Some(prev) = &prev {
  2145. if prev
  2146. .body
  2147. .signing_key
  2148. .principal_of_kind(writecap.body.issued_to.kind())
  2149. != writecap.body.issued_to
  2150. {
  2151. return Err(bterr!(WritecapAuthzErr::NotChained));
  2152. }
  2153. }
  2154. sig_input_buf.clear();
  2155. write_to(&writecap.body, &mut sig_input_buf)
  2156. .map_err(|e| bterr!(WritecapAuthzErr::Serde(e.to_string())))?;
  2157. writecap.body.signing_key.verify(
  2158. &mut std::iter::once(sig_input_buf.as_slice()),
  2159. writecap.signature.as_slice(),
  2160. )?;
  2161. match &writecap.next {
  2162. Some(next) => {
  2163. prev = Some(writecap);
  2164. writecap = next;
  2165. }
  2166. None => {
  2167. // We're at the root key. As long as the signer of this writecap is the owner of
  2168. // the path, then the writecap is valid.
  2169. if writecap
  2170. .body
  2171. .signing_key
  2172. .principal_of_kind(path.root().kind())
  2173. == *path.root()
  2174. {
  2175. return Ok(());
  2176. } else {
  2177. return Err(bterr!(WritecapAuthzErr::RootDoesNotOwnPath));
  2178. }
  2179. }
  2180. }
  2181. }
  2182. Err(bterr!(WritecapAuthzErr::ChainTooLong(CHAIN_LEN_LIMIT)))
  2183. }
  2184. }
  2185. #[cfg(test)]
  2186. mod tests {
  2187. use std::{
  2188. io::{Seek, SeekFrom},
  2189. time::Duration,
  2190. };
  2191. use super::*;
  2192. use crate::{
  2193. crypto::secret_stream::SecretStream,
  2194. test_helpers::{self, *},
  2195. Sectored, TryCompose,
  2196. };
  2197. #[test]
  2198. fn encrypt_decrypt_block() {
  2199. const SECT_SZ: usize = 16;
  2200. const SECT_CT: usize = 8;
  2201. let mut block = make_block_with();
  2202. write_fill(&mut block, SECT_SZ, SECT_CT);
  2203. block.rewind().expect("rewind failed");
  2204. read_check(block, SECT_SZ, SECT_CT);
  2205. }
  2206. #[test]
  2207. fn rsa_sign_and_verify() -> Result<()> {
  2208. let key = make_key_pair();
  2209. let header = b"About: lyrics".as_slice();
  2210. let message = b"Everything that feels so good is bad bad bad.".as_slice();
  2211. let signature = key.sign(&mut [header, message].into_iter())?;
  2212. key.verify(&mut [header, message].into_iter(), signature.as_slice())
  2213. }
  2214. #[test]
  2215. fn hash_to_string() {
  2216. let hash = make_principal().0;
  2217. let string = hash.to_string();
  2218. assert_eq!("0!dSip4J0kurN5VhVo_aTipM-ywOOWrqJuRRVQ7aa-bew", string)
  2219. }
  2220. #[test]
  2221. fn hash_to_string_round_trip() -> Result<()> {
  2222. let expected = make_principal().0;
  2223. let string = expected.to_string();
  2224. let actual = VarHash::try_from(string.as_str())?;
  2225. assert_eq!(expected, actual);
  2226. Ok(())
  2227. }
  2228. #[test]
  2229. fn verify_writecap_valid() {
  2230. let writecap = make_writecap(vec!["apps", "verse"]);
  2231. writecap
  2232. .assert_valid_for(&writecap.body.path)
  2233. .expect("failed to verify writecap");
  2234. }
  2235. #[test]
  2236. fn verify_writecap_invalid_signature() -> Result<()> {
  2237. let mut writecap = make_writecap(vec!["apps", "verse"]);
  2238. writecap.signature = Signature::empty(Sign::RSA_PSS_3072_SHA_256);
  2239. let result = writecap.assert_valid_for(&writecap.body.path);
  2240. if let Err(ref err) = result {
  2241. if let Some(err) = err.downcast_ref::<Error>() {
  2242. if let Error::InvalidSignature = err {
  2243. return Ok(());
  2244. }
  2245. }
  2246. }
  2247. Err(bterr!("unexpected result {:?}", result))
  2248. }
  2249. fn assert_authz_err<T: std::fmt::Debug>(
  2250. expected: WritecapAuthzErr,
  2251. result: Result<T>,
  2252. ) -> Result<()> {
  2253. if let Some(err) = result.as_ref().err() {
  2254. if let Some(actual) = err.downcast_ref::<WritecapAuthzErr>() {
  2255. if *actual == expected {
  2256. return Ok(());
  2257. }
  2258. }
  2259. }
  2260. Err(bterr!("unexpected result: {:?}", result))
  2261. }
  2262. #[test]
  2263. fn verify_writecap_invalid_path_not_contained() -> Result<()> {
  2264. let writecap = make_writecap(vec!["apps", "verse"]);
  2265. let mut path = writecap.body.path.clone();
  2266. path.pop_component();
  2267. // `path` is now a superpath of `writecap.path`, thus the writecap is not authorized to
  2268. // write to it.
  2269. let result = writecap.assert_valid_for(&path);
  2270. assert_authz_err(WritecapAuthzErr::UnauthorizedPath, result)
  2271. }
  2272. #[test]
  2273. fn verify_writecap_invalid_expired() -> Result<()> {
  2274. let mut writecap = make_writecap(vec!["apps", "verse"]);
  2275. writecap.body.expires = Epoch::now() - Duration::from_secs(1);
  2276. let result = writecap.assert_valid_for(&writecap.body.path);
  2277. assert_authz_err(WritecapAuthzErr::Expired, result)
  2278. }
  2279. #[test]
  2280. fn verify_writecap_invalid_not_chained() -> Result<()> {
  2281. let (mut root_writecap, root_key) = make_self_signed_writecap();
  2282. root_writecap.body.issued_to = Principal(VarHash::from(HashKind::Sha2_256));
  2283. root_key.sign_writecap(&mut root_writecap)?;
  2284. let node_principal = NODE_CREDS.principal();
  2285. let writecap = make_writecap_trusted_by(
  2286. root_writecap,
  2287. &root_key,
  2288. node_principal,
  2289. vec!["apps", "contacts"],
  2290. );
  2291. let result = writecap.assert_valid_for(&writecap.body.path);
  2292. assert_authz_err(WritecapAuthzErr::NotChained, result)
  2293. }
  2294. #[test]
  2295. fn verify_writecap_invalid_root_doesnt_own_path() -> Result<()> {
  2296. let (mut root_writecap, root_key) = make_self_signed_writecap();
  2297. let owner = Principal(VarHash::from(HashKind::Sha2_256));
  2298. root_writecap.body.path = make_path_with_root(owner, vec![]);
  2299. root_key.sign_writecap(&mut root_writecap)?;
  2300. let node_principal = NODE_CREDS.principal();
  2301. let writecap = make_writecap_trusted_by(
  2302. root_writecap,
  2303. &root_key,
  2304. node_principal,
  2305. vec!["apps", "contacts"],
  2306. );
  2307. let result = writecap.assert_valid_for(&writecap.body.path);
  2308. assert_authz_err(WritecapAuthzErr::RootDoesNotOwnPath, result)
  2309. }
  2310. #[test]
  2311. fn aeadkey_encrypt_decrypt_aes256gcm() {
  2312. let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
  2313. let aad = [1u8; 16];
  2314. let expected = [2u8; 32];
  2315. let tagged = key.encrypt(aad, &expected).expect("encrypt failed");
  2316. let actual = key.decrypt(&tagged).expect("decrypt failed");
  2317. assert_eq!(expected, actual.as_slice());
  2318. }
  2319. #[test]
  2320. fn aeadkey_decrypt_fails_when_ct_modified() {
  2321. let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
  2322. let aad = [1u8; 16];
  2323. let expected = [2u8; 32];
  2324. let mut tagged = key.encrypt(aad, &expected).expect("encrypt failed");
  2325. tagged.ciphertext.data[0] = tagged.ciphertext.data[0].wrapping_add(1);
  2326. let result = key.decrypt(&tagged);
  2327. assert!(result.is_err())
  2328. }
  2329. #[test]
  2330. fn aeadkey_decrypt_fails_when_aad_modified() {
  2331. let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
  2332. let aad = [1u8; 16];
  2333. let expected = [2u8; 32];
  2334. let mut tagged = key.encrypt(aad, &expected).expect("encrypt failed");
  2335. tagged.aad[0] = tagged.aad[0].wrapping_add(1);
  2336. let result = key.decrypt(&tagged);
  2337. assert!(result.is_err())
  2338. }
  2339. #[test]
  2340. fn compose_merkle_and_secret_streams() {
  2341. use merkle_stream::tests::make_merkle_stream_filled_with_zeros;
  2342. const SECT_SZ: usize = 4096;
  2343. const SECT_CT: usize = 16;
  2344. let merkle = make_merkle_stream_filled_with_zeros(SECT_SZ, SECT_CT);
  2345. let key = SymKey::generate(SymKeyKind::Aes256Cbc).expect("key generation failed");
  2346. let mut secret = SecretStream::new(key)
  2347. .try_compose(merkle)
  2348. .expect("compose for secret failed");
  2349. let secret_sect_sz = secret.sector_sz();
  2350. write_fill(&mut secret, secret_sect_sz, SECT_CT);
  2351. secret.rewind().expect("rewind failed");
  2352. read_check(secret, secret_sect_sz, SECT_CT);
  2353. }
  2354. fn ossl_hash_op_same_as_digest_test_case<H: Hash + From<DigestBytes>>(kind: HashKind) {
  2355. let parts = (0u8..32).map(|k| vec![k; kind.len()]).collect::<Vec<_>>();
  2356. let expected = {
  2357. let mut expected = vec![0u8; kind.len()];
  2358. kind.digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
  2359. .unwrap();
  2360. expected
  2361. };
  2362. let mut op = OsslHashOp::<H>::new(kind).unwrap();
  2363. for part in parts.iter() {
  2364. op.update(part.as_slice()).unwrap();
  2365. }
  2366. let actual = op.finish().unwrap();
  2367. assert_eq!(expected.as_slice(), actual.as_ref());
  2368. }
  2369. /// Tests that the hash computed using an `OsslHashOp` is the same as the one returned by the
  2370. /// `HashKind::digest` method.
  2371. #[test]
  2372. fn ossl_hash_op_same_as_digest() {
  2373. ossl_hash_op_same_as_digest_test_case::<Sha2_256>(Sha2_256::KIND);
  2374. ossl_hash_op_same_as_digest_test_case::<Sha2_512>(Sha2_512::KIND);
  2375. }
  2376. /// Tests that a `HashWrap` instance calculates the same hash as a call to the `digest` method.
  2377. #[test]
  2378. fn hash_stream_agrees_with_digest_method() {
  2379. let cursor = BtCursor::new([0u8; 3 * 32]);
  2380. let parts = (1u8..4).map(|k| [k; Sha2_512::LEN]).collect::<Vec<_>>();
  2381. let expected = {
  2382. let mut expected = Sha2_512::default();
  2383. HashKind::Sha2_512
  2384. .digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
  2385. .unwrap();
  2386. expected
  2387. };
  2388. let op = OsslHashOp::<Sha2_512>::new(Sha2_512::KIND).unwrap();
  2389. let mut wrap = HashStream::new(cursor, op);
  2390. for part in parts.iter() {
  2391. wrap.write(part.as_slice()).unwrap();
  2392. }
  2393. let actual = wrap.finish().unwrap();
  2394. assert_eq!(expected, actual);
  2395. }
  2396. /// Tests that the `VarHash` computed by `VarHashOp` is the same as the one returned by the
  2397. /// `digest` method.
  2398. #[test]
  2399. fn var_hash_op_agress_with_digest_method() {
  2400. let parts = (32..64u8).map(|k| [k; Sha2_512::LEN]).collect::<Vec<_>>();
  2401. let expected = {
  2402. let mut expected = VarHash::from(HashKind::Sha2_512);
  2403. HashKind::Sha2_512
  2404. .digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
  2405. .unwrap();
  2406. expected
  2407. };
  2408. let mut op = VarHashOp::new(HashKind::Sha2_512).unwrap();
  2409. for part in parts.iter() {
  2410. op.update(part.as_slice()).unwrap();
  2411. }
  2412. let actual = op.finish().unwrap();
  2413. assert_eq!(expected, actual);
  2414. }
  2415. /// Tests that the signature produced by `OsslSignOp` can be verified.
  2416. #[test]
  2417. fn ossl_sign_op_sig_can_be_verified() {
  2418. let keys = &test_helpers::NODE_CREDS;
  2419. let part_values = (1..9u8).map(|k| [k; 32]).collect::<Vec<_>>();
  2420. let get_parts = || part_values.iter().map(|a| a.as_slice());
  2421. let mut sign_op = keys.init_sign().expect("init_sign failed");
  2422. for part in get_parts() {
  2423. sign_op.update(part).expect("update failed");
  2424. }
  2425. let sig = sign_op.finish().expect("finish failed");
  2426. keys.verify(&mut get_parts(), sig.as_ref())
  2427. .expect("verify failed");
  2428. }
  2429. /// Tests that the signature produced by a `SignWrite` can be verified.
  2430. #[test]
  2431. fn sign_write_sig_can_be_verified() {
  2432. use crate::Decompose;
  2433. const LEN: usize = 512;
  2434. let cursor = BtCursor::new([0u8; LEN]);
  2435. let keys = &test_helpers::NODE_CREDS;
  2436. let sign_op = keys.sign.private.init_sign().expect("init_sign failed");
  2437. let mut sign_write = SignWrite::new(cursor, sign_op);
  2438. for part in (1..9u8).map(|k| [k; LEN / 8]) {
  2439. sign_write.write(part.as_slice()).expect("write failed");
  2440. }
  2441. let (sig, cursor) = sign_write.finish().expect("finish failed");
  2442. let array = cursor.into_inner();
  2443. keys.verify(&mut std::iter::once(array.as_slice()), sig.as_ref())
  2444. .expect("verify failed");
  2445. }
  2446. /// Tests that data signed using a `SignWrite` can later be verified using a `VerifyRead`.
  2447. #[test]
  2448. fn sign_write_then_verify_read() {
  2449. const LEN: usize = 512;
  2450. let cursor = BtCursor::new([0u8; LEN]);
  2451. let keys = &test_helpers::NODE_CREDS;
  2452. let sign_op = keys.sign.private.init_sign().expect("init_sign failed");
  2453. let mut sign_write = SignWrite::new(cursor, sign_op);
  2454. for part in (1..9u8).map(|k| [k; LEN / 8]) {
  2455. sign_write.write(part.as_slice()).expect("write failed");
  2456. }
  2457. let (sig, mut cursor) = sign_write.finish().expect("finish failed");
  2458. cursor.seek(SeekFrom::Start(0)).expect("seek failed");
  2459. let verify_op = keys.sign.public.init_verify().expect("init_verify failed");
  2460. let mut verify_read = VerifyRead::new(cursor, verify_op);
  2461. let mut buf = Vec::with_capacity(LEN);
  2462. verify_read
  2463. .read_to_end(&mut buf)
  2464. .expect("read_to_end failed");
  2465. verify_read
  2466. .finish(sig.as_ref())
  2467. .expect("failed to verify signature");
  2468. }
  2469. /// Tests that validate the dependencies of this module.
  2470. mod dependency_tests {
  2471. use super::*;
  2472. use openssl::{
  2473. ec::{EcGroup, EcKey},
  2474. nid::Nid,
  2475. };
  2476. /// This test validates that data encrypted with AES 256 CBC can later be decrypted.
  2477. #[test]
  2478. fn aes_256_cbc_roundtrip() {
  2479. use super::*;
  2480. let expected = b"We attack at the crack of noon!";
  2481. let cipher = Cipher::aes_256_cbc();
  2482. let key = BLOCK_KEY.key_slice();
  2483. let iv = BLOCK_KEY.iv_slice();
  2484. let ciphertext = openssl_encrypt(cipher, key, iv, expected).unwrap();
  2485. let actual = openssl_decrypt(cipher, key, iv, ciphertext.as_slice()).unwrap();
  2486. assert_eq!(expected, actual.as_slice());
  2487. }
  2488. /// Tests that the keys for the SECP256K1 curve are the expected sizes.
  2489. #[test]
  2490. fn secp256k1_key_lengths() {
  2491. let group = EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
  2492. let key = EcKey::generate(&group).unwrap();
  2493. let public = key.public_key_to_der().unwrap();
  2494. let private = key.private_key_to_der().unwrap();
  2495. let public_len = public.len();
  2496. let private_len = private.len();
  2497. assert_eq!(88, public_len);
  2498. assert_eq!(118, private_len);
  2499. }
  2500. #[test]
  2501. fn ed25519_key_lengths() {
  2502. let key = PKey::generate_x25519().unwrap();
  2503. let public = key.public_key_to_der().unwrap();
  2504. let private = key.private_key_to_der().unwrap();
  2505. let public_len = public.len();
  2506. let private_len = private.len();
  2507. assert_eq!(44, public_len);
  2508. assert_eq!(48, private_len);
  2509. }
  2510. }
  2511. mod obj_safety {
  2512. use super::*;
  2513. #[test]
  2514. fn op_obj_safe() {
  2515. assert_obj_safe!(Op);
  2516. }
  2517. #[test]
  2518. fn sign_op_obj_safe() {
  2519. assert_obj_safe!(SignOp);
  2520. }
  2521. #[test]
  2522. fn verify_op_obj_safe() {
  2523. assert_obj_safe!(VerifyOp);
  2524. }
  2525. #[test]
  2526. fn encrypter_obj_safe() {
  2527. assert_obj_safe!(Encrypter);
  2528. }
  2529. #[test]
  2530. fn decrypter_obj_safe() {
  2531. assert_obj_safe!(Decrypter);
  2532. }
  2533. #[test]
  2534. fn verifier_obj_safe() {
  2535. assert_obj_safe!(Verifier);
  2536. }
  2537. #[test]
  2538. fn signer_obj_safe() {
  2539. assert_obj_safe!(Signer);
  2540. }
  2541. #[test]
  2542. fn creds_pub_obj_safe() {
  2543. assert_obj_safe!(CredsPub);
  2544. }
  2545. #[test]
  2546. fn creds_priv_obj_safe() {
  2547. assert_obj_safe!(CredsPriv);
  2548. }
  2549. #[test]
  2550. fn creds_obj_safe() {
  2551. assert_obj_safe!(Creds);
  2552. }
  2553. }
  2554. }