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
signature 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;...@@ -20,20 +20,20 @@ const Error = std.crypto.Error;
20// pseudorandom function. See Appendix B.1 for further discussion.)20// pseudorandom function. See Appendix B.1 for further discussion.)
21// PBKDF2 is recommended for new applications.21// PBKDF2 is recommended for new applications.
22//22//
23// PBKDF2 (P, S, c, dkLen)23// PBKDF2 (P, S, c, dk_len)
24//24//
25// Options: PRF underlying pseudorandom function (hLen25// Options: PRF underlying pseudorandom function (h_len
26// denotes the length in octets of the26// denotes the length in octets of the
27// pseudorandom function output)27// pseudorandom function output)
28//28//
29// Input: P password, an octet string29// Input: P password, an octet string
30// S salt, an octet string30// S salt, an octet string
31// c iteration count, a positive integer31// c iteration count, a positive integer
32// dkLen intended length in octets of the derived32// dk_len intended length in octets of the derived
33// key, a positive integer, at most33// key, a positive integer, at most
34// (2^32 - 1) * hLen34// (2^32 - 1) * h_len
35//35//
36// Output: DK derived key, a dkLen-octet string36// Output: DK derived key, a dk_len-octet string
3737
38// Based on Apple's CommonKeyDerivation, based originally on code by Damien Bergamini.38// Based on Apple's CommonKeyDerivation, based originally on code by Damien Bergamini.
3939
...@@ -41,7 +41,7 @@ const Error = std.crypto.Error;...@@ -41,7 +41,7 @@ const Error = std.crypto.Error;
41///41///
42/// PBKDF2 is defined in RFC 2898, and is a recommendation of NIST SP 800-132.42/// PBKDF2 is defined in RFC 2898, and is a recommendation of NIST SP 800-132.
43///43///
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.
45/// May be uninitialized. All bytes will be overwritten.45/// May be uninitialized. All bytes will be overwritten.
46/// Maximum size is `maxInt(u32) * Hash.digest_length`46/// Maximum size is `maxInt(u32) * Hash.digest_length`
47/// It is a programming error to pass buffer longer than the maximum size.47/// It is a programming error to pass buffer longer than the maximum size.
...@@ -52,43 +52,38 @@ const Error = std.crypto.Error;...@@ -52,43 +52,38 @@ const Error = std.crypto.Error;
52///52///
53/// rounds: Iteration count. Must be greater than 0. Common values range from 1,000 to 100,000.53/// rounds: Iteration count. Must be greater than 0. Common values range from 1,000 to 100,000.
54/// Larger iteration counts improve security by increasing the time required to compute54/// 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.
56///56///
57/// Prf: Pseudo-random function to use. A common choice is `std.crypto.auth.hmac.HmacSha256`.57/// 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 {
59 if (rounds < 1) return error.WeakParameters;59 if (rounds < 1) return error.WeakParameters;
6060
61 const dkLen = derivedKey.len;61 const dk_len = dk.len;
62 const hLen = Prf.mac_length;62 const h_len = Prf.mac_length;
63 comptime std.debug.assert(hLen >= 1);63 comptime std.debug.assert(h_len >= 1);
6464
65 // FromSpec:65 // FromSpec:
66 //66 //
67 // 1. If dkLen > maxInt(u32) * hLen, output "derived key too long" and67 // 1. If dk_len > maxInt(u32) * h_len, output "derived key too long" and
68 // stop.68 // stop.
69 //69 //
70 if (comptime (maxInt(usize) > maxInt(u32) * hLen) and (dkLen > @as(usize, maxInt(u32) * hLen))) {70 if (dk_len / h_len >= maxInt(u32)) {
71 // If maxInt(usize) is less than `maxInt(u32) * hLen` then dkLen is always inbounds71 // Counter starts at 1 and is 32 bit, so if we have to return more blocks, we would overflow
72 return error.OutputTooLong;72 return error.OutputTooLong;
73 }73 }
7474
75 // FromSpec:75 // FromSpec:
76 //76 //
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,
78 // rounding up, and let r be the number of bytes in the last78 // rounding up, and let r be the number of bytes in the last
79 // block79 // block
80 //80 //
8181
82 // l will not overflow, proof:82 const blocks_count = @intCast(u32, std.math.divCeil(usize, dk_len, h_len) catch unreachable);
83 // let `L(dkLen, hLen) = (dkLen + hLen - 1) / hLen`83 var r = dk_len % h_len;
84 // then `L^-1(l, hLen) = l*hLen - hLen + 1`84 if (r == 0) {
85 // 1) L^-1(maxInt(u32), hLen) <= maxInt(u32)*hLen85 r = h_len;
86 // 2) maxInt(u32)*hLen - hLen + 1 <= maxInt(u32)*hLen // subtract maxInt(u32)*hLen + 186 }
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_;
9287
93 // FromSpec:88 // FromSpec:
94 //89 //
...@@ -118,37 +113,38 @@ pub fn pbkdf2(derivedKey: []u8, password: []const u8, salt: []const u8, rounds:...@@ -118,37 +113,38 @@ pub fn pbkdf2(derivedKey: []u8, password: []const u8, salt: []const u8, rounds:
118 // Here, INT (i) is a four-octet encoding of the integer i, most113 // Here, INT (i) is a four-octet encoding of the integer i, most
119 // significant octet first.114 // significant octet first.
120 //115 //
121 // 4. Concatenate the blocks and extract the first dkLen octets to116 // 4. Concatenate the blocks and extract the first dk_len octets to
122 // produce a derived key DK:117 // produce a derived key DK:
123 //118 //
124 // DK = T_1 || T_2 || ... || T_l<0..r-1>119 // DK = T_1 || T_2 || ... || T_l<0..r-1>
125 var block: u32 = 0; // Spec limits to u32120
126 while (block < l) : (block += 1) {121 var block: u32 = 0;
127 var prevBlock: [hLen]u8 = undefined;122 while (block < blocks_count) : (block += 1) {
128 var newBlock: [hLen]u8 = undefined;123 var prev_block: [h_len]u8 = undefined;
124 var new_block: [h_len]u8 = undefined;
129125
130 // U_1 = PRF (P, S || INT (i))126 // U_1 = PRF (P, S || INT (i))
131 const blockIndex = mem.toBytes(mem.nativeToBig(u32, block + 1)); // Block index starts at 0001127 const block_index = mem.toBytes(mem.nativeToBig(u32, block + 1)); // Block index starts at 0001
132 var ctx = Prf.init(password);128 var ctx = Prf.init(password);
133 ctx.update(salt);129 ctx.update(salt);
134 ctx.update(blockIndex[0..]);130 ctx.update(block_index[0..]);
135 ctx.final(prevBlock[0..]);131 ctx.final(prev_block[0..]);
136132
137 // Choose portion of DK to write into (T_n) and initialize133 // Choose portion of DK to write into (T_n) and initialize
138 const offset = block * hLen;134 const offset = block * h_len;
139 const blockLen = if (block != l - 1) hLen else r;135 const block_len = if (block != blocks_count - 1) h_len else r;
140 const dkBlock: []u8 = derivedKey[offset..][0..blockLen];136 const dk_block: []u8 = dk[offset..][0..block_len];
141 mem.copy(u8, dkBlock, prevBlock[0..dkBlock.len]);137 mem.copy(u8, dk_block, prev_block[0..dk_block.len]);
142138
143 var i: u32 = 1;139 var i: u32 = 1;
144 while (i < rounds) : (i += 1) {140 while (i < rounds) : (i += 1) {
145 // U_c = PRF (P, U_{c-1})141 // U_c = PRF (P, U_{c-1})
146 Prf.create(&newBlock, prevBlock[0..], password);142 Prf.create(&new_block, prev_block[0..], password);
147 mem.copy(u8, prevBlock[0..], newBlock[0..]);143 mem.copy(u8, prev_block[0..], new_block[0..]);
148144
149 // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c145 // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
150 for (dkBlock) |_, j| {146 for (dk_block) |_, j| {
151 dkBlock[j] ^= newBlock[j];147 dk_block[j] ^= new_block[j];
152 }148 }
153 }149 }
154 }150 }
...@@ -158,49 +154,50 @@ const htest = @import("test.zig");...@@ -158,49 +154,50 @@ const htest = @import("test.zig");
158const HmacSha1 = std.crypto.auth.hmac.HmacSha1;154const HmacSha1 = std.crypto.auth.hmac.HmacSha1;
159155
160// RFC 6070 PBKDF2 HMAC-SHA1 Test Vectors156// RFC 6070 PBKDF2 HMAC-SHA1 Test Vectors
157
161test "RFC 6070 one iteration" {158test "RFC 6070 one iteration" {
162 const p = "password";159 const p = "password";
163 const s = "salt";160 const s = "salt";
164 const c = 1;161 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
171 const expected = "0c60c80f961f0e71f3a9b524af6012062fe037a6";168 const expected = "0c60c80f961f0e71f3a9b524af6012062fe037a6";
172169
173 htest.assertEqual(expected, derivedKey[0..]);170 htest.assertEqual(expected, dk[0..]);
174}171}
175172
176test "RFC 6070 two iterations" {173test "RFC 6070 two iterations" {
177 const p = "password";174 const p = "password";
178 const s = "salt";175 const s = "salt";
179 const c = 2;176 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
186 const expected = "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957";183 const expected = "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957";
187184
188 htest.assertEqual(expected, derivedKey[0..]);185 htest.assertEqual(expected, dk[0..]);
189}186}
190187
191test "RFC 6070 4096 iterations" {188test "RFC 6070 4096 iterations" {
192 const p = "password";189 const p = "password";
193 const s = "salt";190 const s = "salt";
194 const c = 4096;191 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
201 const expected = "4b007901b765489abead49d926f721d065a429c1";198 const expected = "4b007901b765489abead49d926f721d065a429c1";
202199
203 htest.assertEqual(expected, derivedKey[0..]);200 htest.assertEqual(expected, dk[0..]);
204}201}
205202
206test "RFC 6070 16,777,216 iterations" {203test "RFC 6070 16,777,216 iterations" {
...@@ -212,48 +209,48 @@ test "RFC 6070 16,777,216 iterations" {...@@ -212,48 +209,48 @@ test "RFC 6070 16,777,216 iterations" {
212 const p = "password";209 const p = "password";
213 const s = "salt";210 const s = "salt";
214 const c = 16777216;211 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
221 const expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984";218 const expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984";
222219
223 htest.assertEqual(expected, derivedKey[0..]);220 htest.assertEqual(expected, dk[0..]);
224}221}
225222
226test "RFC 6070 multi-block salt and password" {223test "RFC 6070 multi-block salt and password" {
227 const p = "passwordPASSWORDpassword";224 const p = "passwordPASSWORDpassword";
228 const s = "saltSALTsaltSALTsaltSALTsaltSALTsalt";225 const s = "saltSALTsaltSALTsaltSALTsaltSALTsalt";
229 const c = 4096;226 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
236 const expected = "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038";233 const expected = "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038";
237234
238 htest.assertEqual(expected, derivedKey[0..]);235 htest.assertEqual(expected, dk[0..]);
239}236}
240237
241test "RFC 6070 embedded NUL" {238test "RFC 6070 embedded NUL" {
242 const p = "pass\x00word";239 const p = "pass\x00word";
243 const s = "sa\x00lt";240 const s = "sa\x00lt";
244 const c = 4096;241 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
251 const expected = "56fa6aa75548099dcc37d7f03425e0c3";248 const expected = "56fa6aa75548099dcc37d7f03425e0c3";
252249
253 htest.assertEqual(expected, derivedKey[0..]);250 htest.assertEqual(expected, dk[0..]);
254}251}
255252
256test "Very large dkLen" {253test "Very large dk_len" {
257 // This test allocates 8GB of memory and is expected to take several hours to run.254 // This test allocates 8GB of memory and is expected to take several hours to run.
258 if (true) {255 if (true) {
259 return error.SkipZigTest;256 return error.SkipZigTest;
...@@ -261,13 +258,13 @@ test "Very large dkLen" {...@@ -261,13 +258,13 @@ test "Very large dkLen" {
261 const p = "password";258 const p = "password";
262 const s = "salt";259 const s = "salt";
263 const c = 1;260 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);
267 defer {264 defer {
268 std.testing.allocator.free(derivedKey);265 std.testing.allocator.free(dk);
269 }266 }
270267
271 try pbkdf2(derivedKey, p, s, c, HmacSha1);
272 // Just verify this doesn't crash with an overflow268 // Just verify this doesn't crash with an overflow
269 try pbkdf2(dk, p, s, c, HmacSha1);
273}270}