Skip to main content

utopia_auth/
scrypt.rs

1//! `scrypt()` of the PECL `scrypt` extension 2.0.1, which `Utopia\Auth\Hashes\Scrypt` and
2//! `ScryptModified` call: the scrypt KDF of RFC 7914 (Colin Percival's `crypto_scrypt`), with
3//! the extension's checks, in its order and with its messages.
4//!
5//! PHP allocates scrypt's working memory with the system allocator (`posix_memalign` and an
6//! anonymous `mmap`), outside `memory_limit`, and returns `false` when it cannot; so does
7//! [`scrypt`], whose buffers are reserved fallibly.
8
9use sha2::{Digest, Sha256};
10use zeroize::Zeroize;
11
12/// How `scrypt()` fails.
13#[derive(Debug, PartialEq, Eq)]
14pub enum Failure {
15    /// It throws an `Error` with this message.
16    Error(String),
17    /// It raises this `E_WARNING` and returns `false`.
18    Warning(&'static str),
19    /// It returns `false` without a warning: the memory could not be allocated.
20    False,
21}
22
23/// `$keyLength`'s upper bound, `(2^32 - 1) * 32`.
24const MAX_KEY_LENGTH: i64 = ((1 << 32) - 1) * 32;
25
26/// `scrypt($password, $salt, $N, $r, $p, $keyLength, true)`: the raw derived key (PHP's
27/// default output is its hex, `bin2hex()` of this).
28///
29/// # Errors
30///
31/// As PHP `scrypt()` fails: the `Error` its arguments raise (`$N` not a power of 2 greater
32/// than 1, `$r` or `$p` below 1 or above `2^32 - 1`, `$keyLength` below 16 or above
33/// `(2^32 - 1) * 32`), the warning and `false` of `crypto_scrypt`'s checks (`$r * $p` of
34/// `2^30` or more, or memory beyond the address space), and `false` when memory runs out.
35pub fn scrypt(password: &[u8], salt: &[u8], n: i64, r: i64, p: i64, key_length: i64) -> Result<Vec<u8>, Failure> {
36    let argument = |position: u32, name: &str, rule: &str| {
37        Failure::Error(format!("scrypt(): Argument #{position} (${name}) {rule}"))
38    };
39    // clampAndCast64(3, "N", N, 1), clampAndCast32(4, "r", r, 0), clampAndCast32(5, "p", p, 0).
40    if n <= 1 {
41        return Err(argument(3, "N", "must be greater than 1"));
42    }
43    let n = n.unsigned_abs();
44    let cast32 = |position: u32, name: &str, value: i64| -> Result<u32, Failure> {
45        if value <= 0 {
46            return Err(argument(position, name, "must be greater than 0"));
47        }
48        u32::try_from(value).map_err(|_| argument(position, name, "is too large"))
49    };
50    let r = cast32(4, "r", r)?;
51    let p = cast32(5, "p", p)?;
52    if n & (n - 1) != 0 {
53        return Err(argument(3, "N", "must be a power of 2"));
54    }
55    if key_length < 16 {
56        return Err(argument(6, "key_length", "must be greater than or equal to 16"));
57    }
58    if key_length > MAX_KEY_LENGTH {
59        return Err(argument(6, "key_length", "must be less than or equal to (2^32 - 1) * 32"));
60    }
61    let key_length = usize::try_from(key_length).map_err(|_| Failure::False)?;
62    let mut key = reserve::<u8>(key_length)?;
63    derive(password, salt, n, r, p, &mut key)?;
64    Ok(key)
65}
66
67/// `crypto_scrypt()` into `key`, after the extension's own checks.
68fn derive(password: &[u8], salt: &[u8], n: u64, r: u32, p: u32, key: &mut [u8]) -> Result<(), Failure> {
69    let (r, p) = (u64::from(r), u64::from(p));
70    if r * p >= 1 << 30 {
71        return Err(Failure::Warning("Invalid Parameters; $r * $p is >= 2^30"));
72    }
73    let max = usize::MAX as u64;
74    if r > max / 128 / p || n > max / 128 / r {
75        return Err(Failure::Warning("Invalid Parameters"));
76    }
77    // Within the address space now: the checks above bound every product below.
78    let (r, p, n) = (r as usize, p as usize, n as usize);
79    let block = 32 * r; // 128 * r bytes, in 32-bit words
80    let mut b = reserve::<u8>(128 * r * p)?;
81    let mut xy = reserve::<u32>(2 * block)?;
82    let mut v = reserve::<u32>(block * n)?;
83
84    // 1: (B_0 ... B_{p-1}) <-- PBKDF2(P, S, 1, p * 128 * r)
85    pbkdf2_sha256(password, salt, &mut b);
86    // 2: for i = 0 to p - 1, B_i <-- ROMix(B_i, N)
87    let mut x = vec![0u32; block];
88    for chunk in b.chunks_exact_mut(128 * r) {
89        for (word, bytes) in x.iter_mut().zip(chunk.as_chunks::<4>().0) {
90            *word = u32::from_le_bytes(*bytes);
91        }
92        romix(&mut x, &mut v, &mut xy, r, n);
93        for (word, bytes) in x.iter().zip(chunk.as_chunks_mut::<4>().0) {
94            *bytes = word.to_le_bytes();
95        }
96    }
97    // 3: DK <-- PBKDF2(P, B, 1, dkLen)
98    pbkdf2_sha256(password, &b, key);
99    x.zeroize();
100    b.zeroize();
101    xy.zeroize();
102    v.zeroize();
103    Ok(())
104}
105
106/// A zeroed buffer of `len` items, or [`Failure::False`] where the allocator refuses it, as
107/// `posix_memalign` or `mmap` fail in PHP.
108fn reserve<T: Clone + Default>(len: usize) -> Result<Vec<T>, Failure> {
109    let mut buffer = Vec::new();
110    buffer.try_reserve_exact(len).map_err(|_| Failure::False)?;
111    buffer.resize(len, T::default());
112    Ok(buffer)
113}
114
115/// scrypt's ROMix over one block `x` (`32 * r` words), with `v` (`N` blocks) and `xy`
116/// (two blocks) as working memory.
117fn romix(x: &mut [u32], v: &mut [u32], xy: &mut [u32], r: usize, n: usize) {
118    let block = 32 * r;
119    let (y, scratch) = xy.split_at_mut(block);
120    for i in 0..n {
121        v[i * block..(i + 1) * block].copy_from_slice(x);
122        blockmix_salsa8(x, y, scratch, r);
123    }
124    for _ in 0..n {
125        // Integerify: the first 64 bits of the last 64-byte block, little-endian.
126        let last = (2 * r - 1) * 16;
127        let j = ((u64::from(x[last + 1]) << 32 | u64::from(x[last])) & (n as u64 - 1)) as usize;
128        for (a, b) in x.iter_mut().zip(&v[j * block..(j + 1) * block]) {
129            *a ^= b;
130        }
131        blockmix_salsa8(x, y, scratch, r);
132    }
133}
134
135/// scrypt's BlockMix with Salsa20/8: `b` (`2r` 64-byte blocks) in place, `y` and the first
136/// 16 words of `scratch` as working memory.
137fn blockmix_salsa8(b: &mut [u32], y: &mut [u32], scratch: &mut [u32], r: usize) {
138    let x = &mut scratch[..16];
139    x.copy_from_slice(&b[(2 * r - 1) * 16..2 * r * 16]);
140    for i in 0..2 * r {
141        for (a, w) in x.iter_mut().zip(&b[i * 16..(i + 1) * 16]) {
142            *a ^= w;
143        }
144        salsa20_8(x);
145        // Even blocks to the first half, odd blocks to the second.
146        let to = (i / 2 + (i & 1) * r) * 16;
147        y[to..to + 16].copy_from_slice(x);
148    }
149    b.copy_from_slice(&y[..32 * r]);
150}
151
152/// The Salsa20/8 core, in place on 16 words.
153fn salsa20_8(b: &mut [u32]) {
154    let mut x: [u32; 16] = b.try_into().expect("a Salsa20 block is 16 words");
155    let quarter = |x: &mut [u32; 16], a: usize, b: usize, c: usize, d: usize| {
156        x[b] ^= x[a].wrapping_add(x[d]).rotate_left(7);
157        x[c] ^= x[b].wrapping_add(x[a]).rotate_left(9);
158        x[d] ^= x[c].wrapping_add(x[b]).rotate_left(13);
159        x[a] ^= x[d].wrapping_add(x[c]).rotate_left(18);
160    };
161    for _ in 0..4 {
162        // Columns, then rows.
163        quarter(&mut x, 0, 4, 8, 12);
164        quarter(&mut x, 5, 9, 13, 1);
165        quarter(&mut x, 10, 14, 2, 6);
166        quarter(&mut x, 15, 3, 7, 11);
167        quarter(&mut x, 0, 1, 2, 3);
168        quarter(&mut x, 5, 6, 7, 4);
169        quarter(&mut x, 10, 11, 8, 9);
170        quarter(&mut x, 15, 12, 13, 14);
171    }
172    for (out, mixed) in b.iter_mut().zip(x) {
173        *out = out.wrapping_add(mixed);
174    }
175}
176
177/// HMAC-SHA256 of `parts` (concatenated) under `key`.
178fn hmac_sha256(key: &[u8], parts: &[&[u8]]) -> [u8; 32] {
179    let mut block = [0u8; 64];
180    if key.len() > 64 {
181        block[..32].copy_from_slice(&Sha256::digest(key));
182    } else {
183        block[..key.len()].copy_from_slice(key);
184    }
185    let mut inner = Sha256::new();
186    inner.update(block.map(|b| b ^ 0x36));
187    for part in parts {
188        inner.update(part);
189    }
190    let mut outer = Sha256::new();
191    outer.update(block.map(|b| b ^ 0x5c));
192    outer.update(inner.finalize());
193    block.zeroize();
194    outer.finalize().into()
195}
196
197/// PBKDF2-HMAC-SHA256 with one iteration, filling `out`.
198fn pbkdf2_sha256(password: &[u8], salt: &[u8], out: &mut [u8]) {
199    for (i, chunk) in out.chunks_mut(32).enumerate() {
200        let index = u32::try_from(i + 1).expect("at most 2^32 - 1 blocks").to_be_bytes();
201        let mut u = hmac_sha256(password, &[salt, &index]);
202        chunk.copy_from_slice(&u[..chunk.len()]);
203        u.zeroize();
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::{Failure, scrypt};
210
211    fn hex(bytes: &[u8]) -> String {
212        bytes.iter().map(|b| format!("{b:02x}")).collect()
213    }
214
215    #[test]
216    fn rfc_7914_vectors() {
217        assert_eq!(
218            hex(&scrypt(b"", b"", 16, 1, 1, 64).unwrap()),
219            "77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906"
220        );
221        assert_eq!(
222            hex(&scrypt(b"password", b"NaCl", 1024, 8, 16, 64).unwrap()),
223            "fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640"
224        );
225    }
226
227    /// Password, salt, N, r, p, key length and PECL's hex output.
228    type Case = (&'static [u8], &'static [u8], i64, i64, i64, i64, &'static str);
229
230    /// What PECL scrypt 2.0.1 returns in the development image, `bin2hex()`ed.
231    #[test]
232    fn pecl_outputs() {
233        let cases: [Case; 4] = [
234            (
235                b"pw",
236                b"salt",
237                8,
238                14,
239                1,
240                64,
241                "95b38cb05a94c075852e73a18dcc67bf47bf43599196ba17ed71293fa872f6fea9cbf466d1b5745cb709785b554fe505530ddd90f340835a9723d5196a53cb01",
242            ),
243            (b"pw", b"", 16, 8, 1, 16, "d2edcaceddb98a212607650d7fb42a5d"),
244            (b"", b"salt", 16, 8, 1, 16, "bcda6cb6c38d6459c333688c498370f4"),
245            (b"p\0w", b"s\0alt", 16, 8, 1, 16, "58d5604cbe4c2055289421bbad920a06"),
246        ];
247        for (password, salt, n, r, p, length, expected) in cases {
248            assert_eq!(hex(&scrypt(password, salt, n, r, p, length).unwrap()), expected);
249        }
250    }
251
252    #[test]
253    fn pecl_failures() {
254        let error = |message: &str| Err(Failure::Error(format!("scrypt(): {message}")));
255        assert_eq!(scrypt(b"", b"", 1, 8, 1, 16), error("Argument #3 ($N) must be greater than 1"));
256        assert_eq!(scrypt(b"", b"", -16, 8, 1, 16), error("Argument #3 ($N) must be greater than 1"));
257        assert_eq!(scrypt(b"", b"", 3, 8, 1, 16), error("Argument #3 ($N) must be a power of 2"));
258        assert_eq!(scrypt(b"", b"", 16, 0, 1, 16), error("Argument #4 ($r) must be greater than 0"));
259        assert_eq!(scrypt(b"", b"", 16, 1 << 32, 1, 16), error("Argument #4 ($r) is too large"));
260        assert_eq!(scrypt(b"", b"", 16, 8, 0, 16), error("Argument #5 ($p) must be greater than 0"));
261        assert_eq!(
262            scrypt(b"", b"", 16, 8, 1, 15),
263            error("Argument #6 ($key_length) must be greater than or equal to 16")
264        );
265        assert_eq!(
266            scrypt(b"", b"", 16, 8, 1, ((1 << 32) - 1) * 32 + 1),
267            error("Argument #6 ($key_length) must be less than or equal to (2^32 - 1) * 32")
268        );
269        assert_eq!(
270            scrypt(b"", b"", 2, 1 << 30, 1, 16),
271            Err(Failure::Warning("Invalid Parameters; $r * $p is >= 2^30"))
272        );
273        assert_eq!(
274            scrypt(b"", b"", 2, 1 << 15, 1 << 15, 16),
275            Err(Failure::Warning("Invalid Parameters; $r * $p is >= 2^30"))
276        );
277        assert_eq!(scrypt(b"", b"", 1 << 62, 1, 1, 16), Err(Failure::Warning("Invalid Parameters")));
278    }
279}