crypto.rs 76 KB

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