1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// LCOV_EXCL_LINE

//! Protected-access memory for cryptographic secrets.
//!
//! Provides a convenient way to allocate and access memory for
//! secret data. Data is protected from being read from and/or written
//! to outside of limited scopes, where it may be accessed through
//! pointer semantics or slice semantics.
//!
//! Memory allocations are protected by guard pages before after the
//! allocation, an underflow canary (to catch underflows before a
//! guard page), and are zeroed out when freed.
//!
//! # Core dumps
//!
//! This library explicitly disables core dumps in release builds that
//! target UNIX systems. This is done to avoid retrival of a secret
//! from it. You can still opt-in on allowing code dumps with
//! `allow-coredumps` feature flag.
//!
//! # Example: generating crytographic keys
//!
//! ```
//! use secrets::Secret;
//!
//! Secret::<[u8; 16]>::random(|s| {
//!     // use `s` as if it were a `&mut [u8; 16]`
//!     //
//!     // the memory is `mlock(2)`ed and will be zeroed when this closure
//!     // exits
//! });
//! ```
//!
//! # Example: load a master key from disk and generate subkeys from it
//!
//! ```
//! use std::fs::File;
//! use std::io::Read;
//!
//! use libsodium_sys as sodium;
//! use secrets::SecretBox;
//!
//! const KEY_LEN : usize = sodium::crypto_kdf_KEYBYTES     as _;
//! const CTX_LEN : usize = sodium::crypto_kdf_CONTEXTBYTES as _;
//!
//! const CONTEXT : &[u8; CTX_LEN] = b"example\0";
//!
//! fn derive_subkey(
//!     key:       &[u8; KEY_LEN],
//!     context:   &[u8; CTX_LEN],
//!     subkey_id: u64,
//!     subkey:    &mut [u8],
//! ) {
//!     unsafe {
//!         libsodium_sys::crypto_kdf_derive_from_key(
//!             subkey.as_mut_ptr(),
//!             subkey.len(),
//!             subkey_id,
//!             context.as_ptr() as *const i8,
//!             key.as_ptr()
//!         );
//!     }
//! }
//!
//! let master_key = SecretBox::<[u8; KEY_LEN]>::try_new(|mut s| {
//!     File::open("example/master_key/key")?.read_exact(s)
//! })?;
//!
//! let subkey_0 = SecretBox::<[u8; 16]>::new(|mut s| {
//!     derive_subkey(&master_key.borrow(), CONTEXT, 0, s);
//! });
//!
//! let subkey_1 = SecretBox::<[u8; 16]>::new(|mut s| {
//!     derive_subkey(&master_key.borrow(), CONTEXT, 1, s);
//! });
//!
//! assert_ne!(
//!     subkey_0.borrow(),
//!     subkey_1.borrow(),
//! );
//!
//! # Ok::<(), std::io::Error>(())
//! ```
//!
//! # Example: securely storing a decrypted ciphertext in memory
//!
//! ```
//! use std::fs::File;
//! use std::io::Read;
//!
//! use libsodium_sys as sodium;
//! use secrets::{SecretBox, SecretVec};
//!
//! const KEY_LEN   : usize = sodium::crypto_secretbox_KEYBYTES   as _;
//! const NONCE_LEN : usize = sodium::crypto_secretbox_NONCEBYTES as _;
//! const MAC_LEN   : usize = sodium::crypto_secretbox_MACBYTES   as _;
//!
//! let mut key        = SecretBox::<[u8; KEY_LEN]>::zero();
//! let mut nonce      = [0; NONCE_LEN];
//! let mut ciphertext = Vec::new();
//!
//! File::open("example/decrypted_ciphertext/key")?
//!     .read_exact(key.borrow_mut().as_mut())?;
//!
//! File::open("example/decrypted_ciphertext/nonce")?
//!     .read_exact(&mut nonce)?;
//!
//! File::open("example/decrypted_ciphertext/ciphertext")?
//!     .read_to_end(&mut ciphertext)?;
//!
//! let plaintext = SecretVec::<u8>::new(ciphertext.len() - MAC_LEN, |mut s| {
//!     if -1 == unsafe {
//!         sodium::crypto_secretbox_open_easy(
//!             s.as_mut_ptr(),
//!             ciphertext.as_ptr(),
//!             ciphertext.len() as _,
//!             nonce.as_ptr(),
//!             key.borrow().as_ptr(),
//!         )
//!     } {
//!         panic!("failed to authenticate ciphertext during decryption");
//!     }
//! });
//!
//! assert_eq!(
//!     *b"attack at dawn",
//!     *plaintext.borrow(),
//! );
//!
//! # Ok::<(), std::io::Error>(())
//! ```

// TODO: examples directory
// TODO: replace sodium::fail() with mocks for testing cleanliness

#![warn(future_incompatible)]
#![warn(nonstandard_style)]
#![warn(rust_2018_compatibility)]
#![warn(rust_2018_idioms)]
#![warn(rust_2021_compatibility)]
#![warn(unused)]

#![warn(bare_trait_objects)]
#![warn(dead_code)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(single_use_lifetimes)]
#![warn(trivial_casts)]
#![warn(trivial_numeric_casts)]
#![warn(unreachable_pub)]
#![warn(unstable_features)]
#![warn(unused_import_braces)]
#![warn(unused_lifetimes)]
#![warn(unused_qualifications)]
#![warn(unused_results)]
#![warn(unsafe_code)]
#![warn(variant_size_differences)]

#![cfg_attr(feature = "cargo-clippy", warn(clippy::all))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::pedantic))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::nursery))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::clone_on_ref_ptr))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::decimal_literal_representation))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::else_if_without_else))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::float_arithmetic))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::float_cmp_const))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::indexing_slicing))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::mem_forget))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::missing_docs_in_private_items))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::multiple_inherent_impl))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::multiple_inherent_impl))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::print_stdout))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::unwrap_used))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::shadow_reuse))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::shadow_same))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::unimplemented))]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::use_debug))]

#![cfg_attr(feature = "cargo-clippy", allow(clippy::module_name_repetitions))]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::must_use_candidate))]

// disabled due to https://github.com/rust-lang/rust-clippy/issues/5369
#![cfg_attr(feature = "cargo-clippy", allow(clippy::redundant_pub_crate))]

// disabled due to https://github.com/rust-lang/rust/issues/69952
#![cfg_attr(feature = "cargo-clippy", allow(clippy::wildcard_imports))]

/// Macros for ensuring code correctness inspired by [sqlite].
///
/// [sqlite]: https://www.sqlite.org/assert.html
#[cfg(profile = "debug")]
#[macro_use]
mod assert {
    #![allow(unused_macros)]

    /// Results in an `assert!` in debug builds but is a no-op in
    /// coverage and release builds, since we have extraordinarily high
    /// guarantees that it is impossible for this condition to happen in
    /// released code.
    macro_rules! proven {
        ($($arg:tt)*) => {
            assert!($($arg)*)
        };
    }

    /// This is intended to be used in a conditional expression, and
    /// must have the negative case handled in the event that we're wrong;
    /// in debug builds it performs an `assert!`, in coverage builds it
    /// expands to `true`, and in production builds it evaluates to the
    /// condition itself.
    macro_rules! always {
        ($cond:expr) => { {
            assert!($cond); true
        } };

        ($cond:expr, $($arg:tt)*) => {
            assert!($cond, $($arg)*)
        };
    }

    /// The logical opposite of `always`
    macro_rules! never {
        ($cond:expr) => { {
            assert!(!$cond); false
        } };

        ($cond:expr, $($arg:tt)*) => {
            assert!(!$cond, $($arg)*)
        };
    }

    /// Ensures, for code-coverage purposes, that we have tests for
    /// which the condition provided evaluates to `true`, this allows
    /// us to ensure at the source location itself that known edge cases
    /// are considered and tested; in debug and release builds it's a
    /// no-op, and in coverage builds it does some work that can't be
    /// optimized away, so the coverage tool can ensure that that work
    /// is performed at least once (and therefore the condition was
    /// tested).
    macro_rules! tested {
        ($cond:expr)  => ()
    }
}

/// See above.
#[cfg(profile = "coverage")]
#[macro_use]
mod assert {
    #![allow(unused_macros)]
    macro_rules! proven {
        ($($arg:tt)*) => ();
    }

    macro_rules! always {
        ($cond:expr) => {
            true
        };

        ($cond:expr, $($arg:tt)*) => {
            assert!($cond, $($arg)*)
        };
    }

    macro_rules! never {
        ($cond:expr) => {
            false
        };

        ($cond:expr, $($arg:tt)*) => {
            assert!(!$cond, $($arg)*)
        };
    }

    // Well, this sucks. The intent here is that code coverage tools
    // will be able to detect if this line isn't run due to the
    // condition never being satisfied. But right now, they aren't smart
    // enough to do it due to how coverage is tracked. Macros are
    // expanded, but their line hits aren't tracked separately. So just
    // evaluating the condition is enough for the whole thing to be
    // considered run.
    //
    // Still, we'll leave this in place with the hopes that some day it
    // will start working and we'll live in a happy world where we can
    // verify edge cases are tracked.
    macro_rules! tested {
        ($cond:expr) => {
            if $cond {
                // TODO: replace with [`test::black_box`] when stable
                let _ = crate::ffi::sodium::memcmp(&[], &[]);
            }
        };
    }
}

/// See above.
#[cfg(profile = "release")]
#[macro_use]
mod assert {
    #![allow(unused_macros)]
    macro_rules! proven {
        ($($arg:tt)*) => ();
    }

    macro_rules! always {
        ($cond:expr) => {
            $cond
        };

        ($cond:expr, $($arg:tt)*) => {
            assert!($cond, $($arg)*)
        };
    }

    macro_rules! never {
        ($cond:expr) => {
            $cond
        };

        ($cond:expr, $($arg:tt)*) => {
            assert!(!$cond, $($arg)*)
        };
    }

    macro_rules! tested {
        ($cond:expr) => ();
    }
}

/// Container for FFI-related code.
mod ffi {
    pub(crate) mod sodium;
}

/// Container for `Box`.
mod boxed;

/// Container for `Secret`.
mod secret;

/// Container for `SecretBox`.
mod secret_box;

/// Container for `SecretVec`.
mod secret_vec;

pub mod traits;

pub use secret::Secret;
pub use secret_box::SecretBox;
pub use secret_vec::SecretVec;