Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(536)

Side by Side Diff: net/third_party/nss/patches/cbc.patch

Issue 12193010: net: implement CBC processing in constant-time in libssl. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: g try Created 7 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 diff --git a/mozilla/security/nss/lib/ssl/ssl3con.c b/mozilla/security/nss/lib/s sl/ssl3con.c
2 index c3706fe..d4be47a 100644
3 --- a/mozilla/security/nss/lib/ssl/ssl3con.c
4 +++ b/mozilla/security/nss/lib/ssl/ssl3con.c
5 @@ -1844,7 +1844,6 @@ static const unsigned char mac_pad_2 [60] = {
6 };
7
8 /* Called from: ssl3_SendRecord()
9 -** ssl3_HandleRecord()
10 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
11 */
12 static SECStatus
13 @@ -2026,6 +2025,128 @@ ssl3_ComputeRecordMAC(
14 return rv;
15 }
16
17 +/* This is a bodge to allow this code to be compiled against older NSS headers
18 + * that don't contains the CBC constant-time changes. */
19 +#ifndef CKM_NSS_HMAC_CONSTANT_TIME
20 +#define CKM_NSS_HMAC_CONSTANT_TIME (CKM_NSS + 19)
21 +#define CKM_NSS_SSLV3_MAC_CONSTANT_TIME (CKM_NSS + 20)
22 +
23 +typedef struct CK_NSS_MACConstantTimeParams {
24 + CK_MECHANISM_TYPE hashAlg; /* in */
25 + CK_ULONG ulBodyTotalLength; /* in */
26 + CK_BYTE * pHeader; /* in */
27 + CK_ULONG ulHeaderLength; /* in */
28 +} CK_NSS_MACConstantTimeParams;
29 +#endif
30 +
31 +/* Called from: ssl3_HandleRecord()
32 + * Caller must already hold the SpecReadLock. (wish we could assert that!)
33 + *
34 + * On entry:
35 + * originalLen >= inputLen >= MAC size
36 +*/
37 +static SECStatus
38 +ssl3_ComputeRecordMACConstantTime(
39 + ssl3CipherSpec * spec,
40 + PRBool useServerMacKey,
41 + PRBool isDTLS,
42 + SSL3ContentType type,
43 + SSL3ProtocolVersion version,
44 + SSL3SequenceNumber seq_num,
45 + const SSL3Opaque * input,
46 + int inputLen,
47 + int originalLen,
48 + unsigned char * outbuf,
49 + unsigned int * outLen)
50 +{
51 + CK_MECHANISM_TYPE macType;
52 + CK_NSS_MACConstantTimeParams params;
53 + PK11Context * mac_context;
54 + SECItem param;
55 + SECStatus rv;
56 + unsigned char header[13];
57 + PK11SymKey * key;
58 + int recordLength;
59 +
60 + PORT_Assert(inputLen >= spec->mac_size);
61 + PORT_Assert(originalLen >= inputLen);
62 +
63 + if (spec->bypassCiphers) {
64 + /* This function doesn't support PKCS#11 bypass. We fallback on the
65 + * non-constant time version. */
66 + goto fallback;
67 + }
68 +
69 + if (spec->mac_def->mac == mac_null) {
70 + *outLen = 0;
71 + return SECSuccess;
72 + }
73 +
74 + header[0] = (unsigned char)(seq_num.high >> 24);
75 + header[1] = (unsigned char)(seq_num.high >> 16);
76 + header[2] = (unsigned char)(seq_num.high >> 8);
77 + header[3] = (unsigned char)(seq_num.high >> 0);
78 + header[4] = (unsigned char)(seq_num.low >> 24);
79 + header[5] = (unsigned char)(seq_num.low >> 16);
80 + header[6] = (unsigned char)(seq_num.low >> 8);
81 + header[7] = (unsigned char)(seq_num.low >> 0);
82 + header[8] = type;
83 +
84 + macType = CKM_NSS_HMAC_CONSTANT_TIME;
85 + recordLength = inputLen - spec->mac_size;
86 + if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
87 + macType = CKM_NSS_SSLV3_MAC_CONSTANT_TIME;
88 + header[9] = recordLength >> 8;
89 + header[10] = recordLength;
90 + params.ulHeaderLength = 11;
91 + } else {
92 + header[9] = version >> 8;
93 + header[10] = version;
94 + header[11] = recordLength >> 8;
95 + header[12] = recordLength;
96 + params.ulHeaderLength = 13;
97 + }
98 +
99 + params.hashAlg = spec->mac_def->mmech;
100 + params.ulBodyTotalLength = originalLen;
101 + params.pHeader = header;
102 +
103 + param.data = (unsigned char*) &params;
104 + param.len = sizeof(params);
105 + param.type = 0;
106 +
107 + key = spec->server.write_mac_key;
108 + if (!useServerMacKey) {
109 + key = spec->client.write_mac_key;
110 + }
111 + mac_context = PK11_CreateContextBySymKey(macType, CKA_SIGN, key, &param);
112 + if (mac_context == NULL) {
113 + /* Older versions of NSS may not support constant-time MAC. */
114 + goto fallback;
115 + }
116 +
117 + rv = PK11_DigestBegin(mac_context);
118 + rv |= PK11_DigestOp(mac_context, input, inputLen);
119 + rv |= PK11_DigestFinal(mac_context, outbuf, outLen, spec->mac_size);
120 + PK11_DestroyContext(mac_context, PR_TRUE);
121 +
122 + PORT_Assert(rv != SECSuccess || *outLen == (unsigned)spec->mac_size);
123 +
124 + if (rv != SECSuccess) {
125 + rv = SECFailure;
126 + ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
127 + }
128 + return rv;
129 +
130 +fallback:
131 + /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the
132 + * length already. */
133 + inputLen -= spec->mac_size;
134 + return ssl3_ComputeRecordMAC(spec, useServerMacKey, isDTLS, type,
135 + version, seq_num, input, inputLen,
136 + outbuf, outLen);
137 +}
138 +
139 static PRBool
140 ssl3_ClientAuthTokenPresent(sslSessionID *sid) {
141 PK11SlotInfo *slot = NULL;
142 @@ -9530,6 +9651,174 @@ ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
143 return SECSuccess;
144 }
145
146 +/* These macros return the given value with the MSB copied to all the other
147 + * bits. They use the fact that arithmetic shift shifts-in the sign bit.
148 + * However, this is not ensured by the C standard so you may need to replace
149 + * them with something else on odd CPUs. */
150 +#define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) )
151 +#define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x)))
152 +
153 +/* SECStatusToMask returns, in constant time, a mask value of all ones if rv ==
154 + * SECSuccess. Otherwise it returns zero. */
155 +static unsigned SECStatusToMask(SECStatus rv) {
156 + unsigned int good;
157 + /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results in
158 + * the MSB being set to one iff it was zero before. */
159 + good = rv ^ SECSuccess;
160 + good--;
161 + return DUPLICATE_MSB_TO_ALL(good);
162 +}
163 +
164 +/* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */
165 +static unsigned char ssl_ConstantTimeGE(unsigned a, unsigned b) {
166 + a -= b;
167 + return DUPLICATE_MSB_TO_ALL(~a);
168 +}
169 +
170 +/* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */
171 +static unsigned char ssl_ConstantTimeEQ8(unsigned char a, unsigned char b) {
172 + unsigned c = a ^ b;
173 + c--;
174 + return DUPLICATE_MSB_TO_ALL_8(c);
175 +}
176 +
177 +static SECStatus ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
178 + unsigned blockSize,
179 + unsigned macSize) {
180 + unsigned int paddingLength, good, t;
181 + const unsigned int overhead = 1 /* padding length byte */ + macSize;
182 +
183 + /* These lengths are all public so we can test them in non-constant
184 + * time. */
185 + if (overhead > plaintext->len) {
186 + return SECFailure;
187 + }
188 +
189 + paddingLength = plaintext->buf[plaintext->len-1];
190 + /* SSLv3 padding bytes are random and cannot be checked. */
191 + t = plaintext->len;
192 + t -= paddingLength+overhead;
193 + /* If len >= padding_length+overhead then the MSB of t is zero. */
194 + good = DUPLICATE_MSB_TO_ALL(~t);
195 + /* SSLv3 requires that the padding is minimal. */
196 + t = blockSize - (paddingLength+1);
197 + good &= DUPLICATE_MSB_TO_ALL(~t);
198 + plaintext->len -= good & (paddingLength+1);
199 + return (good & SECSuccess) | (~good & SECFailure);
200 +}
201 +
202 +
203 +static SECStatus ssl_RemoveTLSCBCPadding(sslBuffer *plaintext,
204 + unsigned macSize) {
205 + unsigned int paddingLength, good, t, toCheck, i;
206 + const unsigned int overhead = 1 /* padding length byte */ + macSize;
207 +
208 + /* These lengths are all public so we can test them in non-constant
209 + * time. */
210 + if (overhead > plaintext->len) {
211 + return SECFailure;
212 + }
213 +
214 + paddingLength = plaintext->buf[plaintext->len-1];
215 + t = plaintext->len;
216 + t -= paddingLength+overhead;
217 + /* If len >= paddingLength+overhead then the MSB of t is zero. */
218 + good = DUPLICATE_MSB_TO_ALL(~t);
219 +
220 + /* The padding consists of a length byte at the end of the record and then
221 + * that many bytes of padding, all with the same value as the length byte.
222 + * Thus, with the length byte included, there are paddingLength+1 bytes of
223 + * padding.
224 + *
225 + * We can't check just |paddingLength+1| bytes because that leaks
226 + * decrypted information. Therefore we always have to check the maximum
227 + * amount of padding possible. (Again, the length of the record is
228 + * public information so we can use it.) */
229 + toCheck = 255; /* maximum amount of padding. */
230 + if (toCheck > plaintext->len-1) {
231 + toCheck = plaintext->len-1;
232 + }
233 +
234 + for (i = 0; i < toCheck; i++) {
235 + unsigned int t = paddingLength - i;
236 + /* If i <= paddingLength then the MSB of t is zero and mask is
237 + * 0xff. Otherwise, mask is 0. */
238 + unsigned char mask = DUPLICATE_MSB_TO_ALL(~t);
239 + unsigned char b = plaintext->buf[plaintext->len-1-i];
240 + /* The final |paddingLength+1| bytes should all have the value
241 + * |paddingLength|. Therefore the XOR should be zero. */
242 + good &= ~(mask&(paddingLength ^ b));
243 + }
244 +
245 + /* If any of the final |paddingLength+1| bytes had the wrong value,
246 + * one or more of the lower eight bits of |good| will be cleared. We
247 + * AND the bottom 8 bits together and duplicate the result to all the
248 + * bits. */
249 + good &= good >> 4;
250 + good &= good >> 2;
251 + good &= good >> 1;
252 + good <<= sizeof(good)*8-1;
253 + good = DUPLICATE_MSB_TO_ALL(good);
254 +
255 + plaintext->len -= good & (paddingLength+1);
256 + return (good & SECSuccess) | (~good & SECFailure);
257 +}
258 +
259 +/* On entry:
260 + * originalLength >= macSize
261 + * macSize <= MAX_MAC_LENGTH
262 + * plaintext->len >= macSize
263 + */
264 +static void ssl_CBCExtractMAC(sslBuffer *plaintext,
265 + unsigned int originalLength,
266 + SSL3Opaque* out,
267 + unsigned int macSize) {
268 + unsigned char rotatedMac[MAX_MAC_LENGTH];
269 + /* macEnd is the index of |plaintext->buf| just after the end of the MAC. * /
270 + unsigned macEnd = plaintext->len;
271 + unsigned macStart = macEnd - macSize;
272 + /* scanStart contains the number of bytes that we can ignore because
273 + * the MAC's position can only vary by 255 bytes. */
274 + unsigned scanStart = 0;
275 + unsigned i, j, divSpoiler;
276 + unsigned char rotateOffset;
277 +
278 + if (originalLength > macSize + 255 + 1)
279 + scanStart = originalLength - (macSize + 255 + 1);
280 +
281 + /* divSpoiler contains a multiple of macSize that is used to cause the
282 + * modulo operation to be constant time. Without this, the time varies
283 + * based on the amount of padding when running on Intel chips at least.
284 + *
285 + * The aim of right-shifting macSize is so that the compiler doesn't
286 + * figure out that it can remove divSpoiler as that would require it
287 + * to prove that macSize is always even, which I hope is beyond it. */
288 + divSpoiler = macSize >> 1;
289 + divSpoiler <<= (sizeof(divSpoiler)-1)*8;
290 + rotateOffset = (divSpoiler + macStart - scanStart) % macSize;
291 +
292 + memset(rotatedMac, 0, macSize);
293 + for (i = scanStart; i < originalLength;) {
294 + for (j = 0; j < macSize && i < originalLength; i++, j++) {
295 + unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
296 + unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
297 + unsigned char b = 0;
298 + b = plaintext->buf[i];
299 + rotatedMac[j] |= b & macStarted & ~macEnded;
300 + }
301 + }
302 +
303 + /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line we
304 + * could line-align |rotatedMac| and rotate in place. */
305 + memset(out, 0, macSize);
306 + for (i = 0; i < macSize; i++) {
307 + unsigned char offset = (divSpoiler + macSize - rotateOffset + i) % macSi ze;
308 + for (j = 0; j < macSize; j++) {
309 + out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset);
310 + }
311 + }
312 +}
313 +
314 /* if cText is non-null, then decipher, check MAC, and decompress the
315 * SSL record from cText->buf (typically gs->inbuf)
316 * into databuf (typically gs->buf), and any previous contents of databuf
317 @@ -9559,15 +9848,18 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
318 ssl3CipherSpec * crSpec;
319 SECStatus rv;
320 unsigned int hashBytes = MAX_MAC_LENGTH + 1;
321 - unsigned int padding_length;
322 PRBool isTLS;
323 - PRBool padIsBad = PR_FALSE;
324 SSL3ContentType rType;
325 SSL3Opaque hash[MAX_MAC_LENGTH];
326 + SSL3Opaque givenHashBuf[MAX_MAC_LENGTH];
327 + SSL3Opaque *givenHash;
328 sslBuffer *plaintext;
329 sslBuffer temp_buf;
330 PRUint64 dtls_seq_num;
331 unsigned int ivLen = 0;
332 + unsigned int originalLen = 0;
333 + unsigned int good;
334 + unsigned int minLength;
335
336 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
337
338 @@ -9635,6 +9927,30 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, s slBuffer *databuf)
339 }
340 }
341
342 + good = (unsigned)-1;
343 + minLength = crSpec->mac_size;
344 + if (cipher_def->type == type_block) {
345 + /* CBC records have a padding length byte at the end. */
346 + minLength++;
347 + if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
348 + /* With >= TLS 1.1, CBC records have an explicit IV. */
349 + minLength += cipher_def->iv_size;
350 + }
351 + }
352 +
353 + /* We can perform this test in variable time because the record's total
354 + * length and the ciphersuite are both public knowledge. */
355 + if (cText->buf->len < minLength) {
356 + SSL_DBG(("%d: SSL3[%d]: HandleRecord, record too small.",
357 + SSL_GETPID(), ss->fd));
358 + /* must not hold spec lock when calling SSL3_SendAlert. */
359 + ssl_ReleaseSpecReadLock(ss);
360 + SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
361 + /* always log mac error, in case attacker can read server logs. */
362 + PORT_SetError(SSL_ERROR_BAD_MAC_READ);
363 + return SECFailure;
364 + }
365 +
366 if (cipher_def->type == type_block &&
367 crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
368 /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
369 @@ -9652,16 +9968,6 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, s slBuffer *databuf)
370 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
371 return SECFailure;
372 }
373 - if (ivLen > cText->buf->len) {
374 - SSL_DBG(("%d: SSL3[%d]: HandleRecord, IV length check failed",
375 - SSL_GETPID(), ss->fd));
376 - /* must not hold spec lock when calling SSL3_SendAlert. */
377 - ssl_ReleaseSpecReadLock(ss);
378 - SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
379 - /* always log mac error, in case attacker can read server logs. */
380 - PORT_SetError(SSL_ERROR_BAD_MAC_READ);
381 - return SECFailure;
382 - }
383
384 PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
385
386 @@ -9672,12 +9978,7 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, s slBuffer *databuf)
387 rv = crSpec->decode(crSpec->decodeContext, iv, &decoded,
388 sizeof(iv), cText->buf->buf, ivLen);
389
390 - if (rv != SECSuccess) {
391 - /* All decryption failures must be treated like a bad record
392 - * MAC; see RFC 5246 (TLS 1.2).
393 - */
394 - padIsBad = PR_TRUE;
395 - }
396 + good &= SECStatusToMask(rv);
397 }
398
399 /* If we will be decompressing the buffer we need to decrypt somewhere
400 @@ -9719,54 +10020,70 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
401 rv = crSpec->decode(
402 crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len,
403 plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
404 + good &= SECStatusToMask(rv);
405
406 PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
407 - if (rv != SECSuccess) {
408 - /* All decryption failures must be treated like a bad record
409 - * MAC; see RFC 5246 (TLS 1.2).
410 - */
411 - padIsBad = PR_TRUE;
412 - }
413 +
414 + originalLen = plaintext->len;
415
416 /* If it's a block cipher, check and strip the padding. */
417 - if (cipher_def->type == type_block && !padIsBad) {
418 - PRUint8 * pPaddingLen = plaintext->buf + plaintext->len - 1;
419 - padding_length = *pPaddingLen;
420 - /* TLS permits padding to exceed the block size, up to 255 bytes. */
421 - if (padding_length + 1 + crSpec->mac_size > plaintext->len)
422 - padIsBad = PR_TRUE;
423 - else {
424 - plaintext->len -= padding_length + 1;
425 - /* In TLS all padding bytes must be equal to the padding length. */
426 - if (isTLS) {
427 - PRUint8 *p;
428 - for (p = pPaddingLen - padding_length; p < pPaddingLen; ++p) {
429 - padIsBad |= *p ^ padding_length;
430 - }
431 - }
432 - }
433 - }
434 + if (cipher_def->type == type_block) {
435 + const unsigned int blockSize = cipher_def->iv_size;
436 + const unsigned int macSize = crSpec->mac_size;
437
438 - /* Remove the MAC. */
439 - if (plaintext->len >= crSpec->mac_size)
440 - plaintext->len -= crSpec->mac_size;
441 - else
442 - padIsBad = PR_TRUE; /* really macIsBad */
443 + if (crSpec->version <= SSL_LIBRARY_VERSION_3_0) {
444 + good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
445 + plaintext, blockSize, macSize));
446 + } else {
447 + good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
448 + plaintext, macSize));
449 + }
450 + }
451
452 /* compute the MAC */
453 rType = cText->type;
454 - rv = ssl3_ComputeRecordMAC( crSpec, (PRBool)(!ss->sec.isServer),
455 - IS_DTLS(ss), rType, cText->version,
456 - IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
457 - plaintext->buf, plaintext->len, hash, &hashBytes);
458 - if (rv != SECSuccess) {
459 - padIsBad = PR_TRUE; /* really macIsBad */
460 + if (cipher_def->type == type_block) {
461 + rv = ssl3_ComputeRecordMACConstantTime(
462 + crSpec, (PRBool)(!ss->sec.isServer),
463 + IS_DTLS(ss), rType, cText->version,
464 + IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
465 + plaintext->buf, plaintext->len, originalLen,
466 + hash, &hashBytes);
467 +
468 + ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
469 + crSpec->mac_size);
470 + givenHash = givenHashBuf;
471 +
472 + /* plaintext->len will always have enough space to remove the MAC
473 + * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
474 + * plaintext->len if the result has enough space for the MAC and we
475 + * tested the unadjusted size against minLength, above. */
476 + plaintext->len -= crSpec->mac_size;
477 + } else {
478 + /* This is safe because we checked the minLength above. */
479 + plaintext->len -= crSpec->mac_size;
480 +
481 + rv = ssl3_ComputeRecordMAC(
482 + crSpec, (PRBool)(!ss->sec.isServer),
483 + IS_DTLS(ss), rType, cText->version,
484 + IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
485 + plaintext->buf, plaintext->len,
486 + hash, &hashBytes);
487 +
488 + /* We can read the MAC directly from the record because its location is
489 + * public when a stream cipher is used. */
490 + givenHash = plaintext->buf + plaintext->len;
491 + }
492 +
493 + good &= SECStatusToMask(rv);
494 +
495 + if (hashBytes != (unsigned)crSpec->mac_size ||
496 + NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) {
497 + /* We're allowed to leak whether or not the MAC check was correct */
498 + good = 0;
499 }
500
501 - /* Check the MAC */
502 - if (hashBytes != (unsigned)crSpec->mac_size || padIsBad ||
503 - NSS_SecureMemcmp(plaintext->buf + plaintext->len, hash,
504 - crSpec->mac_size) != 0) {
505 + if (good == 0) {
506 /* must not hold spec lock when calling SSL3_SendAlert. */
507 ssl_ReleaseSpecReadLock(ss);
508
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698