crypto_digest.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. // Copyright (c) 2018-2019, The Tor Project, Inc.
  2. // Copyright (c) 2018, isis agora lovecruft
  3. // See LICENSE for licensing information
  4. //! Bindings to external digest and XOF functions which live within
  5. //! src/common/crypto_digest.[ch].
  6. //!
  7. //! We wrap our C implementations in src/common/crypto_digest.[ch] with more
  8. //! Rusty types and interfaces in src/rust/crypto/digest/.
  9. use std::process::abort;
  10. use libc::c_char;
  11. use libc::c_int;
  12. use libc::size_t;
  13. use libc::uint8_t;
  14. use smartlist::Stringlist;
  15. /// Length of the output of our message digest.
  16. pub const DIGEST_LEN: usize = 20;
  17. /// Length of the output of our second (improved) message digests. (For now
  18. /// this is just sha256, but it could be any other 256-bit digest.)
  19. pub const DIGEST256_LEN: usize = 32;
  20. /// Length of the output of our 64-bit optimized message digests (SHA512).
  21. pub const DIGEST512_LEN: usize = 64;
  22. /// Length of a sha1 message digest when encoded in base32 with trailing = signs
  23. /// removed.
  24. pub const BASE32_DIGEST_LEN: usize = 32;
  25. /// Length of a sha1 message digest when encoded in base64 with trailing = signs
  26. /// removed.
  27. pub const BASE64_DIGEST_LEN: usize = 27;
  28. /// Length of a sha256 message digest when encoded in base64 with trailing =
  29. /// signs removed.
  30. pub const BASE64_DIGEST256_LEN: usize = 43;
  31. /// Length of a sha512 message digest when encoded in base64 with trailing =
  32. /// signs removed.
  33. pub const BASE64_DIGEST512_LEN: usize = 86;
  34. /// Length of hex encoding of SHA1 digest, not including final NUL.
  35. pub const HEX_DIGEST_LEN: usize = 40;
  36. /// Length of hex encoding of SHA256 digest, not including final NUL.
  37. pub const HEX_DIGEST256_LEN: usize = 64;
  38. /// Length of hex encoding of SHA512 digest, not including final NUL.
  39. pub const HEX_DIGEST512_LEN: usize = 128;
  40. /// Our C code uses an enum to declare the digest algorithm types which we know
  41. /// about. However, because enums are implementation-defined in C, we can
  42. /// neither work with them directly nor translate them into Rust enums.
  43. /// Instead, we represent them as a u8 (under the assumption that we'll never
  44. /// support more than 256 hash functions).
  45. #[allow(non_camel_case_types)]
  46. type digest_algorithm_t = u8;
  47. const DIGEST_SHA1: digest_algorithm_t = 0;
  48. const DIGEST_SHA256: digest_algorithm_t = 1;
  49. const DIGEST_SHA512: digest_algorithm_t = 2;
  50. const DIGEST_SHA3_256: digest_algorithm_t = 3;
  51. const DIGEST_SHA3_512: digest_algorithm_t = 4;
  52. /// The number of hash digests we produce for a `common_digests_t`.
  53. ///
  54. /// We can't access these from Rust, because their definitions in C require
  55. /// introspecting the `digest_algorithm_t` typedef, which is an enum, so we have
  56. /// to redefine them here.
  57. const N_COMMON_DIGEST_ALGORITHMS: usize = DIGEST_SHA256 as usize + 1;
  58. /// A digest function.
  59. #[repr(C)]
  60. #[derive(Debug, Copy, Clone)]
  61. #[allow(non_camel_case_types)]
  62. struct crypto_digest_t {
  63. // This private, zero-length field forces the struct to be treated the same
  64. // as its opaque C couterpart.
  65. _unused: [u8; 0],
  66. }
  67. /// An eXtendible Output Function (XOF).
  68. #[repr(C)]
  69. #[derive(Debug, Copy, Clone)]
  70. #[allow(non_camel_case_types)]
  71. struct crypto_xof_t {
  72. // This private, zero-length field forces the struct to be treated the same
  73. // as its opaque C couterpart.
  74. _unused: [u8; 0],
  75. }
  76. /// A set of all the digests we commonly compute, taken on a single
  77. /// string. Any digests that are shorter than 512 bits are right-padded
  78. /// with 0 bits.
  79. ///
  80. /// Note that this representation wastes 44 bytes for the SHA1 case, so
  81. /// don't use it for anything where we need to allocate a whole bunch at
  82. /// once.
  83. #[repr(C)]
  84. #[derive(Debug, Copy, Clone)]
  85. #[allow(non_camel_case_types)]
  86. struct common_digests_t {
  87. pub d: [[c_char; N_COMMON_DIGEST_ALGORITHMS]; DIGEST256_LEN],
  88. }
  89. /// A `smartlist_t` is just an alias for the `#[repr(C)]` type `Stringlist`, to
  90. /// make it more clear that we're working with a smartlist which is owned by C.
  91. #[allow(non_camel_case_types)]
  92. // BINDGEN_GENERATED: This type isn't actually bindgen generated, but the code
  93. // below it which uses it is. As such, this comes up as "dead code" as well.
  94. #[allow(dead_code)]
  95. type smartlist_t = Stringlist;
  96. /// All of the external functions from `src/common/crypto_digest.h`.
  97. ///
  98. /// These are kept private because they should be wrapped with Rust to make their usage safer.
  99. //
  100. // BINDGEN_GENERATED: These definitions were generated with bindgen and cleaned
  101. // up manually. As such, there are more bindings than are likely necessary or
  102. // which are in use.
  103. #[allow(dead_code)]
  104. extern "C" {
  105. fn crypto_digest(digest: *mut c_char, m: *const c_char, len: size_t) -> c_int;
  106. fn crypto_digest256(
  107. digest: *mut c_char,
  108. m: *const c_char,
  109. len: size_t,
  110. algorithm: digest_algorithm_t,
  111. ) -> c_int;
  112. fn crypto_digest512(
  113. digest: *mut c_char,
  114. m: *const c_char,
  115. len: size_t,
  116. algorithm: digest_algorithm_t,
  117. ) -> c_int;
  118. fn crypto_common_digests(ds_out: *mut common_digests_t, m: *const c_char, len: size_t)
  119. -> c_int;
  120. fn crypto_digest_smartlist_prefix(
  121. digest_out: *mut c_char,
  122. len_out: size_t,
  123. prepend: *const c_char,
  124. lst: *const smartlist_t,
  125. append: *const c_char,
  126. alg: digest_algorithm_t,
  127. );
  128. fn crypto_digest_smartlist(
  129. digest_out: *mut c_char,
  130. len_out: size_t,
  131. lst: *const smartlist_t,
  132. append: *const c_char,
  133. alg: digest_algorithm_t,
  134. );
  135. fn crypto_digest_algorithm_get_name(alg: digest_algorithm_t) -> *const c_char;
  136. fn crypto_digest_algorithm_get_length(alg: digest_algorithm_t) -> size_t;
  137. fn crypto_digest_algorithm_parse_name(name: *const c_char) -> c_int;
  138. fn crypto_digest_new() -> *mut crypto_digest_t;
  139. fn crypto_digest256_new(algorithm: digest_algorithm_t) -> *mut crypto_digest_t;
  140. fn crypto_digest512_new(algorithm: digest_algorithm_t) -> *mut crypto_digest_t;
  141. fn crypto_digest_free_(digest: *mut crypto_digest_t);
  142. fn crypto_digest_add_bytes(digest: *mut crypto_digest_t, data: *const c_char, len: size_t);
  143. fn crypto_digest_get_digest(digest: *mut crypto_digest_t, out: *mut c_char, out_len: size_t);
  144. fn crypto_digest_dup(digest: *const crypto_digest_t) -> *mut crypto_digest_t;
  145. fn crypto_digest_assign(into: *mut crypto_digest_t, from: *const crypto_digest_t);
  146. fn crypto_hmac_sha256(
  147. hmac_out: *mut c_char,
  148. key: *const c_char,
  149. key_len: size_t,
  150. msg: *const c_char,
  151. msg_len: size_t,
  152. );
  153. fn crypto_mac_sha3_256(
  154. mac_out: *mut uint8_t,
  155. len_out: size_t,
  156. key: *const uint8_t,
  157. key_len: size_t,
  158. msg: *const uint8_t,
  159. msg_len: size_t,
  160. );
  161. fn crypto_xof_new() -> *mut crypto_xof_t;
  162. fn crypto_xof_add_bytes(xof: *mut crypto_xof_t, data: *const uint8_t, len: size_t);
  163. fn crypto_xof_squeeze_bytes(xof: *mut crypto_xof_t, out: *mut uint8_t, len: size_t);
  164. fn crypto_xof_free(xof: *mut crypto_xof_t);
  165. }
  166. /// A wrapper around a `digest_algorithm_t`.
  167. pub enum DigestAlgorithm {
  168. SHA2_256,
  169. SHA2_512,
  170. SHA3_256,
  171. SHA3_512,
  172. }
  173. impl From<DigestAlgorithm> for digest_algorithm_t {
  174. fn from(digest: DigestAlgorithm) -> digest_algorithm_t {
  175. match digest {
  176. DigestAlgorithm::SHA2_256 => DIGEST_SHA256,
  177. DigestAlgorithm::SHA2_512 => DIGEST_SHA512,
  178. DigestAlgorithm::SHA3_256 => DIGEST_SHA3_256,
  179. DigestAlgorithm::SHA3_512 => DIGEST_SHA3_512,
  180. }
  181. }
  182. }
  183. /// A wrapper around a mutable pointer to a `crypto_digest_t`.
  184. pub struct CryptoDigest(*mut crypto_digest_t);
  185. /// Explicitly copy the state of a `CryptoDigest` hash digest context.
  186. ///
  187. /// # C_RUST_COUPLED
  188. ///
  189. /// * `crypto_digest_dup`
  190. impl Clone for CryptoDigest {
  191. fn clone(&self) -> CryptoDigest {
  192. let digest: *mut crypto_digest_t;
  193. unsafe {
  194. digest = crypto_digest_dup(self.0 as *const crypto_digest_t);
  195. }
  196. // See the note in the implementation of CryptoDigest for the
  197. // reasoning for `abort()` here.
  198. if digest.is_null() {
  199. abort();
  200. }
  201. CryptoDigest(digest)
  202. }
  203. }
  204. impl CryptoDigest {
  205. /// A wrapper to call one of the C functions `crypto_digest_new`,
  206. /// `crypto_digest256_new`, or `crypto_digest512_new`.
  207. ///
  208. /// # Warnings
  209. ///
  210. /// This function will `abort()` the entire process in an "abnormal" fashion,
  211. /// i.e. not unwinding this or any other thread's stack, running any
  212. /// destructors, or calling any panic/exit hooks) if `tor_malloc()` (called in
  213. /// `crypto_digest256_new()`) is unable to allocate memory.
  214. ///
  215. /// # Returns
  216. ///
  217. /// A new `CryptoDigest`, which is a wrapper around a opaque representation
  218. /// of a `crypto_digest_t`. The underlying `crypto_digest_t` _MUST_ only
  219. /// ever be handled via a raw pointer, and never introspected.
  220. ///
  221. /// # C_RUST_COUPLED
  222. ///
  223. /// * `crypto_digest_new`
  224. /// * `crypto_digest256_new`
  225. /// * `crypto_digest512_new`
  226. /// * `tor_malloc` (called by `crypto_digest256_new`, but we make
  227. /// assumptions about its behvaiour and return values here)
  228. pub fn new(algorithm: Option<DigestAlgorithm>) -> CryptoDigest {
  229. let digest: *mut crypto_digest_t;
  230. if algorithm.is_none() {
  231. unsafe {
  232. digest = crypto_digest_new();
  233. }
  234. } else {
  235. let algo: digest_algorithm_t = algorithm.unwrap().into(); // can't fail because it's Some
  236. unsafe {
  237. // XXX This is a pretty awkward API to use from Rust...
  238. digest = match algo {
  239. DIGEST_SHA1 => crypto_digest_new(),
  240. DIGEST_SHA256 => crypto_digest256_new(DIGEST_SHA256),
  241. DIGEST_SHA3_256 => crypto_digest256_new(DIGEST_SHA3_256),
  242. DIGEST_SHA512 => crypto_digest512_new(DIGEST_SHA512),
  243. DIGEST_SHA3_512 => crypto_digest512_new(DIGEST_SHA3_512),
  244. _ => abort(),
  245. }
  246. }
  247. }
  248. // In our C code, `crypto_digest*_new()` allocates memory with
  249. // `tor_malloc()`. In `tor_malloc()`, if the underlying malloc
  250. // implementation fails to allocate the requested memory and returns a
  251. // NULL pointer, we call `exit(1)`. In the case that this `exit(1)` is
  252. // called within a worker, be that a process or a thread, the inline
  253. // comments within `tor_malloc()` mention "that's ok, since the parent
  254. // will run out of memory soon anyway". However, if it takes long
  255. // enough for the worker to die, and it manages to return a NULL pointer
  256. // to our Rust code, our Rust is now in an irreparably broken state and
  257. // may exhibit undefined behaviour. An even worse scenario, if/when we
  258. // have parent/child processes/threads controlled by Rust, would be that
  259. // the UB contagion in Rust manages to spread to other children before
  260. // the entire process (hopefully terminates).
  261. //
  262. // However, following the assumptions made in `tor_malloc()` that
  263. // calling `exit(1)` in a child is okay because the parent will
  264. // eventually run into the same errors, and also to stymie any UB
  265. // contagion in the meantime, we call abort!() here to terminate the
  266. // entire program immediately.
  267. if digest.is_null() {
  268. abort();
  269. }
  270. CryptoDigest(digest)
  271. }
  272. /// A wrapper to call the C function `crypto_digest_add_bytes`.
  273. ///
  274. /// # Inputs
  275. ///
  276. /// * `bytes`: a byte slice of bytes to be added into this digest.
  277. ///
  278. /// # C_RUST_COUPLED
  279. ///
  280. /// * `crypto_digest_add_bytes`
  281. pub fn add_bytes(&self, bytes: &[u8]) {
  282. unsafe {
  283. crypto_digest_add_bytes(
  284. self.0 as *mut crypto_digest_t,
  285. bytes.as_ptr() as *const c_char,
  286. bytes.len() as size_t,
  287. )
  288. }
  289. }
  290. }
  291. impl Drop for CryptoDigest {
  292. fn drop(&mut self) {
  293. unsafe {
  294. crypto_digest_free_(self.0 as *mut crypto_digest_t);
  295. }
  296. }
  297. }
  298. /// Get the 256-bit digest output of a `crypto_digest_t`.
  299. ///
  300. /// # Inputs
  301. ///
  302. /// * `digest`: A `CryptoDigest` which wraps either a `DIGEST_SHA256` or a
  303. /// `DIGEST_SHA3_256`.
  304. ///
  305. /// # Warning
  306. ///
  307. /// Calling this function with a `CryptoDigest` which is neither SHA2-256 or
  308. /// SHA3-256 is a programming error. Since we cannot introspect the opaque
  309. /// struct from Rust, however, there is no way for us to check that the correct
  310. /// one is being passed in. That is up to you, dear programmer. If you mess
  311. /// up, you will get a incorrectly-sized hash digest in return, and it will be
  312. /// your fault. Don't do that.
  313. ///
  314. /// # Returns
  315. ///
  316. /// A 256-bit hash digest, as a `[u8; 32]`.
  317. ///
  318. /// # C_RUST_COUPLED
  319. ///
  320. /// * `crypto_digest_get_digest`
  321. /// * `DIGEST256_LEN`
  322. //
  323. // FIXME: Once const generics land in Rust, we should genericise calling
  324. // crypto_digest_get_digest w.r.t. output array size.
  325. pub fn get_256_bit_digest(digest: CryptoDigest) -> [u8; DIGEST256_LEN] {
  326. let mut buffer: [u8; DIGEST256_LEN] = [0u8; DIGEST256_LEN];
  327. unsafe {
  328. crypto_digest_get_digest(
  329. digest.0,
  330. buffer.as_mut_ptr() as *mut c_char,
  331. DIGEST256_LEN as size_t,
  332. );
  333. if buffer.as_ptr().is_null() {
  334. abort();
  335. }
  336. }
  337. buffer
  338. }
  339. /// Get the 512-bit digest output of a `crypto_digest_t`.
  340. ///
  341. /// # Inputs
  342. ///
  343. /// * `digest`: A `CryptoDigest` which wraps either a `DIGEST_SHA512` or a
  344. /// `DIGEST_SHA3_512`.
  345. ///
  346. /// # Warning
  347. ///
  348. /// Calling this function with a `CryptoDigest` which is neither SHA2-512 or
  349. /// SHA3-512 is a programming error. Since we cannot introspect the opaque
  350. /// struct from Rust, however, there is no way for us to check that the correct
  351. /// one is being passed in. That is up to you, dear programmer. If you mess
  352. /// up, you will get a incorrectly-sized hash digest in return, and it will be
  353. /// your fault. Don't do that.
  354. ///
  355. /// # Returns
  356. ///
  357. /// A 512-bit hash digest, as a `[u8; 64]`.
  358. ///
  359. /// # C_RUST_COUPLED
  360. ///
  361. /// * `crypto_digest_get_digest`
  362. /// * `DIGEST512_LEN`
  363. //
  364. // FIXME: Once const generics land in Rust, we should genericise calling
  365. // crypto_digest_get_digest w.r.t. output array size.
  366. pub fn get_512_bit_digest(digest: CryptoDigest) -> [u8; DIGEST512_LEN] {
  367. let mut buffer: [u8; DIGEST512_LEN] = [0u8; DIGEST512_LEN];
  368. unsafe {
  369. crypto_digest_get_digest(
  370. digest.0,
  371. buffer.as_mut_ptr() as *mut c_char,
  372. DIGEST512_LEN as size_t,
  373. );
  374. if buffer.as_ptr().is_null() {
  375. abort();
  376. }
  377. }
  378. buffer
  379. }
  380. #[cfg(test)]
  381. mod test {
  382. use super::*;
  383. #[test]
  384. fn test_layout_common_digests_t() {
  385. assert_eq!(
  386. ::std::mem::size_of::<common_digests_t>(),
  387. 64usize,
  388. concat!("Size of: ", stringify!(common_digests_t))
  389. );
  390. assert_eq!(
  391. ::std::mem::align_of::<common_digests_t>(),
  392. 1usize,
  393. concat!("Alignment of ", stringify!(common_digests_t))
  394. );
  395. }
  396. #[test]
  397. fn test_layout_crypto_digest_t() {
  398. assert_eq!(
  399. ::std::mem::size_of::<crypto_digest_t>(),
  400. 0usize,
  401. concat!("Size of: ", stringify!(crypto_digest_t))
  402. );
  403. assert_eq!(
  404. ::std::mem::align_of::<crypto_digest_t>(),
  405. 1usize,
  406. concat!("Alignment of ", stringify!(crypto_digest_t))
  407. );
  408. }
  409. }