crypto_digest.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. // Copyright (c) 2018, 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 total number of digest algorithms we currently support.
  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_DIGEST_ALGORITHMS: usize = DIGEST_SHA3_512 as usize + 1;
  58. /// The number of hash digests we produce for a `common_digests_t`.
  59. ///
  60. /// We can't access these from Rust, because their definitions in C require
  61. /// introspecting the `digest_algorithm_t` typedef, which is an enum, so we have
  62. /// to redefine them here.
  63. const N_COMMON_DIGEST_ALGORITHMS: usize = DIGEST_SHA256 as usize + 1;
  64. /// A digest function.
  65. #[repr(C)]
  66. #[derive(Debug, Copy, Clone)]
  67. #[allow(non_camel_case_types)]
  68. struct crypto_digest_t {
  69. // This private, zero-length field forces the struct to be treated the same
  70. // as its opaque C couterpart.
  71. _unused: [u8; 0],
  72. }
  73. /// An eXtendible Output Function (XOF).
  74. #[repr(C)]
  75. #[derive(Debug, Copy, Clone)]
  76. #[allow(non_camel_case_types)]
  77. struct crypto_xof_t {
  78. // This private, zero-length field forces the struct to be treated the same
  79. // as its opaque C couterpart.
  80. _unused: [u8; 0],
  81. }
  82. /// A set of all the digests we commonly compute, taken on a single
  83. /// string. Any digests that are shorter than 512 bits are right-padded
  84. /// with 0 bits.
  85. ///
  86. /// Note that this representation wastes 44 bytes for the SHA1 case, so
  87. /// don't use it for anything where we need to allocate a whole bunch at
  88. /// once.
  89. #[repr(C)]
  90. #[derive(Debug, Copy, Clone)]
  91. #[allow(non_camel_case_types)]
  92. struct common_digests_t {
  93. pub d: [[c_char; N_COMMON_DIGEST_ALGORITHMS]; DIGEST256_LEN],
  94. }
  95. /// A `smartlist_t` is just an alias for the `#[repr(C)]` type `Stringlist`, to
  96. /// make it more clear that we're working with a smartlist which is owned by C.
  97. #[allow(non_camel_case_types)]
  98. type smartlist_t = Stringlist;
  99. /// All of the external functions from `src/common/crypto_digest.h`.
  100. ///
  101. /// These are kept private because they should be wrapped with Rust to make their usage safer.
  102. //
  103. // BINDGEN_GENERATED: These definitions were generated with bindgen and cleaned
  104. // up manually. As such, there are more bindings than are likely necessary or
  105. // which are in use.
  106. #[allow(dead_code)]
  107. extern "C" {
  108. fn crypto_digest(digest: *mut c_char, m: *const c_char, len: size_t) -> c_int;
  109. fn crypto_digest256(digest: *mut c_char, m: *const c_char, len: size_t,
  110. algorithm: digest_algorithm_t) -> c_int;
  111. fn crypto_digest512(digest: *mut c_char, m: *const c_char, len: size_t,
  112. algorithm: digest_algorithm_t) -> c_int;
  113. fn crypto_common_digests(ds_out: *mut common_digests_t, m: *const c_char, len: size_t) -> c_int;
  114. fn crypto_digest_smartlist_prefix(digest_out: *mut c_char, len_out: size_t, prepend: *const c_char,
  115. lst: *const smartlist_t, append: *const c_char, alg: digest_algorithm_t);
  116. fn crypto_digest_smartlist(digest_out: *mut c_char, len_out: size_t,
  117. lst: *const smartlist_t, append: *const c_char, alg: digest_algorithm_t);
  118. fn crypto_digest_algorithm_get_name(alg: digest_algorithm_t) -> *const c_char;
  119. fn crypto_digest_algorithm_get_length(alg: digest_algorithm_t) -> size_t;
  120. fn crypto_digest_algorithm_parse_name(name: *const c_char) -> c_int;
  121. fn crypto_digest_new() -> *mut crypto_digest_t;
  122. fn crypto_digest256_new(algorithm: digest_algorithm_t) -> *mut crypto_digest_t;
  123. fn crypto_digest512_new(algorithm: digest_algorithm_t) -> *mut crypto_digest_t;
  124. fn crypto_digest_free(digest: *mut crypto_digest_t);
  125. fn crypto_digest_add_bytes(digest: *mut crypto_digest_t, data: *const c_char, len: size_t);
  126. fn crypto_digest_get_digest(digest: *mut crypto_digest_t, out: *mut c_char, out_len: size_t);
  127. fn crypto_digest_dup(digest: *const crypto_digest_t) -> *mut crypto_digest_t;
  128. fn crypto_digest_assign(into: *mut crypto_digest_t, from: *const crypto_digest_t);
  129. fn crypto_hmac_sha256(hmac_out: *mut c_char, key: *const c_char, key_len: size_t,
  130. msg: *const c_char, msg_len: size_t);
  131. fn crypto_mac_sha3_256(mac_out: *mut uint8_t, len_out: size_t,
  132. key: *const uint8_t, key_len: size_t,
  133. msg: *const uint8_t, msg_len: size_t);
  134. fn crypto_xof_new() -> *mut crypto_xof_t;
  135. fn crypto_xof_add_bytes(xof: *mut crypto_xof_t, data: *const uint8_t, len: size_t);
  136. fn crypto_xof_squeeze_bytes(xof: *mut crypto_xof_t, out: *mut uint8_t, len: size_t);
  137. fn crypto_xof_free(xof: *mut crypto_xof_t);
  138. }
  139. /// A wrapper around a `digest_algorithm_t`.
  140. pub enum DigestAlgorithm {
  141. SHA2_256,
  142. SHA2_512,
  143. SHA3_256,
  144. SHA3_512,
  145. }
  146. impl From<DigestAlgorithm> for digest_algorithm_t {
  147. fn from(digest: DigestAlgorithm) -> digest_algorithm_t {
  148. match digest {
  149. DigestAlgorithm::SHA2_256 => DIGEST_SHA256,
  150. DigestAlgorithm::SHA2_512 => DIGEST_SHA512,
  151. DigestAlgorithm::SHA3_256 => DIGEST_SHA3_256,
  152. DigestAlgorithm::SHA3_512 => DIGEST_SHA3_512,
  153. }
  154. }
  155. }
  156. /// A wrapper around a mutable pointer to a `crypto_digest_t`.
  157. pub struct CryptoDigest(*mut crypto_digest_t);
  158. /// Explicitly copy the state of a `CryptoDigest` hash digest context.
  159. ///
  160. /// # C_RUST_COUPLED
  161. ///
  162. /// * `crypto_digest_dup`
  163. impl Clone for CryptoDigest {
  164. fn clone(&self) -> CryptoDigest {
  165. let digest: *mut crypto_digest_t;
  166. unsafe {
  167. digest = crypto_digest_dup(self.0 as *const crypto_digest_t);
  168. }
  169. // See the note in the implementation of CryptoDigest for the
  170. // reasoning for `abort()` here.
  171. if digest.is_null() {
  172. abort();
  173. }
  174. CryptoDigest(digest)
  175. }
  176. }
  177. impl CryptoDigest {
  178. /// A wrapper to call one of the C functions `crypto_digest_new`,
  179. /// `crypto_digest256_new`, or `crypto_digest512_new`.
  180. ///
  181. /// # Warnings
  182. ///
  183. /// This function will `abort()` the entire process in an "abnormal" fashion,
  184. /// i.e. not unwinding this or any other thread's stack, running any
  185. /// destructors, or calling any panic/exit hooks) if `tor_malloc()` (called in
  186. /// `crypto_digest256_new()`) is unable to allocate memory.
  187. ///
  188. /// # Returns
  189. ///
  190. /// A new `CryptoDigest`, which is a wrapper around a opaque representation
  191. /// of a `crypto_digest_t`. The underlying `crypto_digest_t` _MUST_ only
  192. /// ever be handled via a raw pointer, and never introspected.
  193. ///
  194. /// # C_RUST_COUPLED
  195. ///
  196. /// * `crypto_digest_new`
  197. /// * `crypto_digest256_new`
  198. /// * `crypto_digest512_new`
  199. /// * `tor_malloc` (called by `crypto_digest256_new`, but we make
  200. /// assumptions about its behvaiour and return values here)
  201. pub fn new(algorithm: Option<DigestAlgorithm>) -> CryptoDigest {
  202. let digest: *mut crypto_digest_t;
  203. if algorithm.is_none() {
  204. unsafe {
  205. digest = crypto_digest_new();
  206. }
  207. } else {
  208. let algo: digest_algorithm_t = algorithm.unwrap().into(); // can't fail because it's Some
  209. unsafe {
  210. // XXX This is a pretty awkward API to use from Rust...
  211. digest = match algo {
  212. DIGEST_SHA1 => crypto_digest_new(),
  213. DIGEST_SHA256 => crypto_digest256_new(DIGEST_SHA256),
  214. DIGEST_SHA3_256 => crypto_digest256_new(DIGEST_SHA3_256),
  215. DIGEST_SHA512 => crypto_digest512_new(DIGEST_SHA512),
  216. DIGEST_SHA3_512 => crypto_digest512_new(DIGEST_SHA3_512),
  217. _ => abort(),
  218. }
  219. }
  220. }
  221. // In our C code, `crypto_digest*_new()` allocates memory with
  222. // `tor_malloc()`. In `tor_malloc()`, if the underlying malloc
  223. // implementation fails to allocate the requested memory and returns a
  224. // NULL pointer, we call `exit(1)`. In the case that this `exit(1)` is
  225. // called within a worker, be that a process or a thread, the inline
  226. // comments within `tor_malloc()` mention "that's ok, since the parent
  227. // will run out of memory soon anyway". However, if it takes long
  228. // enough for the worker to die, and it manages to return a NULL pointer
  229. // to our Rust code, our Rust is now in an irreparably broken state and
  230. // may exhibit undefined behaviour. An even worse scenario, if/when we
  231. // have parent/child processes/threads controlled by Rust, would be that
  232. // the UB contagion in Rust manages to spread to other children before
  233. // the entire process (hopefully terminates).
  234. //
  235. // However, following the assumptions made in `tor_malloc()` that
  236. // calling `exit(1)` in a child is okay because the parent will
  237. // eventually run into the same errors, and also to stymie any UB
  238. // contagion in the meantime, we call abort!() here to terminate the
  239. // entire program immediately.
  240. if digest.is_null() {
  241. abort();
  242. }
  243. CryptoDigest(digest)
  244. }
  245. /// A wrapper to call the C function `crypto_digest_add_bytes`.
  246. ///
  247. /// # Inputs
  248. ///
  249. /// * `bytes`: a byte slice of bytes to be added into this digest.
  250. ///
  251. /// # C_RUST_COUPLED
  252. ///
  253. /// * `crypto_digest_add_bytes`
  254. pub fn add_bytes(&self, bytes: &[u8]) {
  255. unsafe {
  256. crypto_digest_add_bytes(self.0 as *mut crypto_digest_t,
  257. bytes.as_ptr() as *const c_char,
  258. bytes.len() as size_t)
  259. }
  260. }
  261. }
  262. /// Get the 256-bit digest output of a `crypto_digest_t`.
  263. ///
  264. /// # Inputs
  265. ///
  266. /// * `digest`: A `CryptoDigest` which wraps either a `DIGEST_SHA256` or a
  267. /// `DIGEST_SHA3_256`.
  268. ///
  269. /// # Warning
  270. ///
  271. /// Calling this function with a `CryptoDigest` which is neither SHA2-256 or
  272. /// SHA3-256 is a programming error. Since we cannot introspect the opaque
  273. /// struct from Rust, however, there is no way for us to check that the correct
  274. /// one is being passed in. That is up to you, dear programmer. If you mess
  275. /// up, you will get a incorrectly-sized hash digest in return, and it will be
  276. /// your fault. Don't do that.
  277. ///
  278. /// # Returns
  279. ///
  280. /// A 256-bit hash digest, as a `[u8; 32]`.
  281. ///
  282. /// # C_RUST_COUPLED
  283. ///
  284. /// * `crypto_digest_get_digest`
  285. /// * `DIGEST256_LEN`
  286. //
  287. // FIXME: Once const generics land in Rust, we should genericise calling
  288. // crypto_digest_get_digest w.r.t. output array size.
  289. pub fn get_256_bit_digest(digest: CryptoDigest) -> [u8; DIGEST256_LEN] {
  290. let mut buffer: [u8; DIGEST256_LEN] = [0u8; DIGEST256_LEN];
  291. unsafe {
  292. crypto_digest_get_digest(digest.0,
  293. buffer.as_mut_ptr() as *mut c_char,
  294. DIGEST256_LEN as size_t);
  295. if buffer.as_ptr().is_null() {
  296. abort();
  297. }
  298. }
  299. buffer
  300. }
  301. /// Get the 512-bit digest output of a `crypto_digest_t`.
  302. ///
  303. /// # Inputs
  304. ///
  305. /// * `digest`: A `CryptoDigest` which wraps either a `DIGEST_SHA512` or a
  306. /// `DIGEST_SHA3_512`.
  307. ///
  308. /// # Warning
  309. ///
  310. /// Calling this function with a `CryptoDigest` which is neither SHA2-512 or
  311. /// SHA3-512 is a programming error. Since we cannot introspect the opaque
  312. /// struct from Rust, however, there is no way for us to check that the correct
  313. /// one is being passed in. That is up to you, dear programmer. If you mess
  314. /// up, you will get a incorrectly-sized hash digest in return, and it will be
  315. /// your fault. Don't do that.
  316. ///
  317. /// # Returns
  318. ///
  319. /// A 512-bit hash digest, as a `[u8; 64]`.
  320. ///
  321. /// # C_RUST_COUPLED
  322. ///
  323. /// * `crypto_digest_get_digest`
  324. /// * `DIGEST512_LEN`
  325. //
  326. // FIXME: Once const generics land in Rust, we should genericise calling
  327. // crypto_digest_get_digest w.r.t. output array size.
  328. pub fn get_512_bit_digest(digest: CryptoDigest) -> [u8; DIGEST512_LEN] {
  329. let mut buffer: [u8; DIGEST512_LEN] = [0u8; DIGEST512_LEN];
  330. unsafe {
  331. crypto_digest_get_digest(digest.0,
  332. buffer.as_mut_ptr() as *mut c_char,
  333. DIGEST512_LEN as size_t);
  334. if buffer.as_ptr().is_null() {
  335. abort();
  336. }
  337. }
  338. buffer
  339. }
  340. #[cfg(test)]
  341. mod test {
  342. use super::*;
  343. #[test]
  344. fn test_layout_common_digests_t() {
  345. assert_eq!(::std::mem::size_of::<common_digests_t>(), 64usize,
  346. concat!("Size of: ", stringify!(common_digests_t)));
  347. assert_eq!(::std::mem::align_of::<common_digests_t>(), 1usize,
  348. concat!("Alignment of ", stringify!(common_digests_t)));
  349. }
  350. #[test]
  351. fn test_layout_crypto_digest_t() {
  352. assert_eq!(::std::mem::size_of::<crypto_digest_t>(), 0usize,
  353. concat!("Size of: ", stringify!(crypto_digest_t)));
  354. assert_eq!(::std::mem::align_of::<crypto_digest_t>(), 1usize,
  355. concat!("Alignment of ", stringify!(crypto_digest_t)));
  356. }
  357. }