authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-03-17 11:25:19-07:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2021-03-17 11:25:19-07:00
log587243c7a50b751846f0633d762f4153ef230ce6
tree0abbc64ece7bd7f6c2aa6ecf1aac91cb45891967
parentf76bd56588e556ea580c1faa63667cc9264cc218
parent6d9b3e7b19f268fe24e6f14d289fe147745c7a62
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #8273 from jedisct1/pbkdf2-check

crypto/pbkdf2: simplify the check for the max number of iterations

1 files changed, 67 insertions(+), 70 deletions(-)

lib/std/crypto/pbkdf2.zig+67-70
......@@ -20,20 +20,20 @@ const Error = std.crypto.Error;
2020// pseudorandom function. See Appendix B.1 for further discussion.)
2121// PBKDF2 is recommended for new applications.
2222//
23// PBKDF2 (P, S, c, dkLen)
23// PBKDF2 (P, S, c, dk_len)
2424//
25// Options: PRF underlying pseudorandom function (hLen
25// Options: PRF underlying pseudorandom function (h_len
2626// denotes the length in octets of the
2727// pseudorandom function output)
2828//
2929// Input: P password, an octet string
3030// S salt, an octet string
3131// c iteration count, a positive integer
32// dkLen intended length in octets of the derived
32// dk_len intended length in octets of the derived
3333// key, a positive integer, at most
34// (2^32 - 1) * hLen
34// (2^32 - 1) * h_len
3535//
36// Output: DK derived key, a dkLen-octet string
36// Output: DK derived key, a dk_len-octet string
3737
3838// Based on Apple's CommonKeyDerivation, based originally on code by Damien Bergamini.
3939
......@@ -41,7 +41,7 @@ const Error = std.crypto.Error;
4141///
4242/// PBKDF2 is defined in RFC 2898, and is a recommendation of NIST SP 800-132.
4343///
44/// derivedKey: Slice of appropriate size for generated key. Generally 16 or 32 bytes in length.
44/// dk: Slice of appropriate size for generated key. Generally 16 or 32 bytes in length.
4545/// May be uninitialized. All bytes will be overwritten.
4646/// Maximum size is `maxInt(u32) * Hash.digest_length`
4747/// It is a programming error to pass buffer longer than the maximum size.
......@@ -52,43 +52,38 @@ const Error = std.crypto.Error;
5252///
5353/// rounds: Iteration count. Must be greater than 0. Common values range from 1,000 to 100,000.
5454/// Larger iteration counts improve security by increasing the time required to compute
55/// the derivedKey. It is common to tune this parameter to achieve approximately 100ms.
55/// the dk. It is common to tune this parameter to achieve approximately 100ms.
5656///
5757/// Prf: Pseudo-random function to use. A common choice is `std.crypto.auth.hmac.HmacSha256`.
58pub fn pbkdf2(derivedKey: []u8, password: []const u8, salt: []const u8, rounds: u32, comptime Prf: type) Error!void {
58pub fn pbkdf2(dk: []u8, password: []const u8, salt: []const u8, rounds: u32, comptime Prf: type) Error!void {
5959 if (rounds < 1) return error.WeakParameters;
6060
61 const dkLen = derivedKey.len;
62 const hLen = Prf.mac_length;
63 comptime std.debug.assert(hLen >= 1);
61 const dk_len = dk.len;
62 const h_len = Prf.mac_length;
63 comptime std.debug.assert(h_len >= 1);
6464
6565 // FromSpec:
6666 //
67 // 1. If dkLen > maxInt(u32) * hLen, output "derived key too long" and
67 // 1. If dk_len > maxInt(u32) * h_len, output "derived key too long" and
6868 // stop.
6969 //
70 if (comptime (maxInt(usize) > maxInt(u32) * hLen) and (dkLen > @as(usize, maxInt(u32) * hLen))) {
71 // If maxInt(usize) is less than `maxInt(u32) * hLen` then dkLen is always inbounds
70 if (dk_len / h_len >= maxInt(u32)) {
71 // Counter starts at 1 and is 32 bit, so if we have to return more blocks, we would overflow
7272 return error.OutputTooLong;
7373 }
7474
7575 // FromSpec:
7676 //
77 // 2. Let l be the number of hLen-long blocks of bytes in the derived key,
77 // 2. Let l be the number of h_len-long blocks of bytes in the derived key,
7878 // rounding up, and let r be the number of bytes in the last
7979 // block
8080 //
8181
82 // l will not overflow, proof:
83 // let `L(dkLen, hLen) = (dkLen + hLen - 1) / hLen`
84 // then `L^-1(l, hLen) = l*hLen - hLen + 1`
85 // 1) L^-1(maxInt(u32), hLen) <= maxInt(u32)*hLen
86 // 2) maxInt(u32)*hLen - hLen + 1 <= maxInt(u32)*hLen // subtract maxInt(u32)*hLen + 1
87 // 3) -hLen <= -1 // multiply by -1
88 // 4) hLen >= 1
89 const r_ = dkLen % hLen;
90 const l = @intCast(u32, (dkLen / hLen) + @as(u1, if (r_ == 0) 0 else 1)); // original: (dkLen + hLen - 1) / hLen
91 const r = if (r_ == 0) hLen else r_;
82 const blocks_count = @intCast(u32, std.math.divCeil(usize, dk_len, h_len) catch unreachable);
83 var r = dk_len % h_len;
84 if (r == 0) {
85 r = h_len;
86 }
9287
9388 // FromSpec:
9489 //
......@@ -118,37 +113,38 @@ pub fn pbkdf2(derivedKey: []u8, password: []const u8, salt: []const u8, rounds:
118113 // Here, INT (i) is a four-octet encoding of the integer i, most
119114 // significant octet first.
120115 //
121 // 4. Concatenate the blocks and extract the first dkLen octets to
116 // 4. Concatenate the blocks and extract the first dk_len octets to
122117 // produce a derived key DK:
123118 //
124119 // DK = T_1 || T_2 || ... || T_l<0..r-1>
125 var block: u32 = 0; // Spec limits to u32
126 while (block < l) : (block += 1) {
127 var prevBlock: [hLen]u8 = undefined;
128 var newBlock: [hLen]u8 = undefined;
120
121 var block: u32 = 0;
122 while (block < blocks_count) : (block += 1) {
123 var prev_block: [h_len]u8 = undefined;
124 var new_block: [h_len]u8 = undefined;
129125
130126 // U_1 = PRF (P, S || INT (i))
131 const blockIndex = mem.toBytes(mem.nativeToBig(u32, block + 1)); // Block index starts at 0001
127 const block_index = mem.toBytes(mem.nativeToBig(u32, block + 1)); // Block index starts at 0001
132128 var ctx = Prf.init(password);
133129 ctx.update(salt);
134 ctx.update(blockIndex[0..]);
135 ctx.final(prevBlock[0..]);
130 ctx.update(block_index[0..]);
131 ctx.final(prev_block[0..]);
136132
137133 // Choose portion of DK to write into (T_n) and initialize
138 const offset = block * hLen;
139 const blockLen = if (block != l - 1) hLen else r;
140 const dkBlock: []u8 = derivedKey[offset..][0..blockLen];
141 mem.copy(u8, dkBlock, prevBlock[0..dkBlock.len]);
134 const offset = block * h_len;
135 const block_len = if (block != blocks_count - 1) h_len else r;
136 const dk_block: []u8 = dk[offset..][0..block_len];
137 mem.copy(u8, dk_block, prev_block[0..dk_block.len]);
142138
143139 var i: u32 = 1;
144140 while (i < rounds) : (i += 1) {
145141 // U_c = PRF (P, U_{c-1})
146 Prf.create(&newBlock, prevBlock[0..], password);
147 mem.copy(u8, prevBlock[0..], newBlock[0..]);
142 Prf.create(&new_block, prev_block[0..], password);
143 mem.copy(u8, prev_block[0..], new_block[0..]);
148144
149145 // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
150 for (dkBlock) |_, j| {
151 dkBlock[j] ^= newBlock[j];
146 for (dk_block) |_, j| {
147 dk_block[j] ^= new_block[j];
152148 }
153149 }
154150 }
......@@ -158,49 +154,50 @@ const htest = @import("test.zig");
158154const HmacSha1 = std.crypto.auth.hmac.HmacSha1;
159155
160156// RFC 6070 PBKDF2 HMAC-SHA1 Test Vectors
157
161158test "RFC 6070 one iteration" {
162159 const p = "password";
163160 const s = "salt";
164161 const c = 1;
165 const dkLen = 20;
162 const dk_len = 20;
166163
167 var derivedKey: [dkLen]u8 = undefined;
164 var dk: [dk_len]u8 = undefined;
168165
169 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
166 try pbkdf2(&dk, p, s, c, HmacSha1);
170167
171168 const expected = "0c60c80f961f0e71f3a9b524af6012062fe037a6";
172169
173 htest.assertEqual(expected, derivedKey[0..]);
170 htest.assertEqual(expected, dk[0..]);
174171}
175172
176173test "RFC 6070 two iterations" {
177174 const p = "password";
178175 const s = "salt";
179176 const c = 2;
180 const dkLen = 20;
177 const dk_len = 20;
181178
182 var derivedKey: [dkLen]u8 = undefined;
179 var dk: [dk_len]u8 = undefined;
183180
184 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
181 try pbkdf2(&dk, p, s, c, HmacSha1);
185182
186183 const expected = "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957";
187184
188 htest.assertEqual(expected, derivedKey[0..]);
185 htest.assertEqual(expected, dk[0..]);
189186}
190187
191188test "RFC 6070 4096 iterations" {
192189 const p = "password";
193190 const s = "salt";
194191 const c = 4096;
195 const dkLen = 20;
192 const dk_len = 20;
196193
197 var derivedKey: [dkLen]u8 = undefined;
194 var dk: [dk_len]u8 = undefined;
198195
199 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
196 try pbkdf2(&dk, p, s, c, HmacSha1);
200197
201198 const expected = "4b007901b765489abead49d926f721d065a429c1";
202199
203 htest.assertEqual(expected, derivedKey[0..]);
200 htest.assertEqual(expected, dk[0..]);
204201}
205202
206203test "RFC 6070 16,777,216 iterations" {
......@@ -212,48 +209,48 @@ test "RFC 6070 16,777,216 iterations" {
212209 const p = "password";
213210 const s = "salt";
214211 const c = 16777216;
215 const dkLen = 20;
212 const dk_len = 20;
216213
217 var derivedKey = [_]u8{0} ** dkLen;
214 var dk = [_]u8{0} ** dk_len;
218215
219 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
216 try pbkdf2(&dk, p, s, c, HmacSha1);
220217
221218 const expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984";
222219
223 htest.assertEqual(expected, derivedKey[0..]);
220 htest.assertEqual(expected, dk[0..]);
224221}
225222
226223test "RFC 6070 multi-block salt and password" {
227224 const p = "passwordPASSWORDpassword";
228225 const s = "saltSALTsaltSALTsaltSALTsaltSALTsalt";
229226 const c = 4096;
230 const dkLen = 25;
227 const dk_len = 25;
231228
232 var derivedKey: [dkLen]u8 = undefined;
229 var dk: [dk_len]u8 = undefined;
233230
234 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
231 try pbkdf2(&dk, p, s, c, HmacSha1);
235232
236233 const expected = "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038";
237234
238 htest.assertEqual(expected, derivedKey[0..]);
235 htest.assertEqual(expected, dk[0..]);
239236}
240237
241238test "RFC 6070 embedded NUL" {
242239 const p = "pass\x00word";
243240 const s = "sa\x00lt";
244241 const c = 4096;
245 const dkLen = 16;
242 const dk_len = 16;
246243
247 var derivedKey: [dkLen]u8 = undefined;
244 var dk: [dk_len]u8 = undefined;
248245
249 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
246 try pbkdf2(&dk, p, s, c, HmacSha1);
250247
251248 const expected = "56fa6aa75548099dcc37d7f03425e0c3";
252249
253 htest.assertEqual(expected, derivedKey[0..]);
250 htest.assertEqual(expected, dk[0..]);
254251}
255252
256test "Very large dkLen" {
253test "Very large dk_len" {
257254 // This test allocates 8GB of memory and is expected to take several hours to run.
258255 if (true) {
259256 return error.SkipZigTest;
......@@ -261,13 +258,13 @@ test "Very large dkLen" {
261258 const p = "password";
262259 const s = "salt";
263260 const c = 1;
264 const dkLen = 1 << 33;
261 const dk_len = 1 << 33;
265262
266 var derivedKey = try std.testing.allocator.alloc(u8, dkLen);
263 var dk = try std.testing.allocator.alloc(u8, dk_len);
267264 defer {
268 std.testing.allocator.free(derivedKey);
265 std.testing.allocator.free(dk);
269266 }
270267
271 try pbkdf2(derivedKey, p, s, c, HmacSha1);
272268 // Just verify this doesn't crash with an overflow
269 try pbkdf2(dk, p, s, c, HmacSha1);
273270}