1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 /*
6  * RSA PKCS#1 v2.1 (RFC 3447) operations
7  */
8 
9 #ifdef FREEBL_NO_DEPEND
10 #include "stubs.h"
11 #endif
12 
13 #include "secerr.h"
14 
15 #include "blapi.h"
16 #include "secitem.h"
17 #include "blapii.h"
18 
19 #define RSA_BLOCK_MIN_PAD_LEN 8
20 #define RSA_BLOCK_FIRST_OCTET 0x00
21 #define RSA_BLOCK_PRIVATE_PAD_OCTET 0xff
22 #define RSA_BLOCK_AFTER_PAD_OCTET 0x00
23 
24 /*
25  * RSA block types
26  *
27  * The values of RSA_BlockPrivate and RSA_BlockPublic are fixed.
28  * The value of RSA_BlockRaw isn't fixed by definition, but we are keeping
29  * the value that NSS has been using in the past.
30  */
31 typedef enum {
32     RSA_BlockPrivate = 1, /* pad for a private-key operation */
33     RSA_BlockPublic = 2,  /* pad for a public-key operation */
34     RSA_BlockRaw = 4      /* simply justify the block appropriately */
35 } RSA_BlockType;
36 
37 /* Needed for RSA-PSS functions */
38 static const unsigned char eightZeros[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
39 
40 /* Constant time comparison of a single byte.
41  * Returns 1 iff a == b, otherwise returns 0.
42  * Note: For ranges of bytes, use constantTimeCompare.
43  */
44 static unsigned char
constantTimeEQ8(unsigned char a,unsigned char b)45 constantTimeEQ8(unsigned char a, unsigned char b)
46 {
47     unsigned char c = ~((a - b) | (b - a));
48     c >>= 7;
49     return c;
50 }
51 
52 /* Constant time comparison of a range of bytes.
53  * Returns 1 iff len bytes of a are identical to len bytes of b, otherwise
54  * returns 0.
55  */
56 static unsigned char
constantTimeCompare(const unsigned char * a,const unsigned char * b,unsigned int len)57 constantTimeCompare(const unsigned char *a,
58                     const unsigned char *b,
59                     unsigned int len)
60 {
61     unsigned char tmp = 0;
62     unsigned int i;
63     for (i = 0; i < len; ++i, ++a, ++b)
64         tmp |= *a ^ *b;
65     return constantTimeEQ8(0x00, tmp);
66 }
67 
68 /* Constant time conditional.
69  * Returns a if c is 1, or b if c is 0. The result is undefined if c is
70  * not 0 or 1.
71  */
72 static unsigned int
constantTimeCondition(unsigned int c,unsigned int a,unsigned int b)73 constantTimeCondition(unsigned int c,
74                       unsigned int a,
75                       unsigned int b)
76 {
77     return (~(c - 1) & a) | ((c - 1) & b);
78 }
79 
80 static unsigned int
rsa_modulusLen(SECItem * modulus)81 rsa_modulusLen(SECItem *modulus)
82 {
83     unsigned char byteZero = modulus->data[0];
84     unsigned int modLen = modulus->len - !byteZero;
85     return modLen;
86 }
87 
88 static unsigned int
rsa_modulusBits(SECItem * modulus)89 rsa_modulusBits(SECItem *modulus)
90 {
91     unsigned char byteZero = modulus->data[0];
92     unsigned int numBits = (modulus->len - 1) * 8;
93 
94     if (byteZero == 0) {
95         numBits -= 8;
96         byteZero = modulus->data[1];
97     }
98 
99     while (byteZero > 0) {
100         numBits++;
101         byteZero >>= 1;
102     }
103 
104     return numBits;
105 }
106 
107 /*
108  * Format one block of data for public/private key encryption using
109  * the rules defined in PKCS #1.
110  */
111 static unsigned char *
rsa_FormatOneBlock(unsigned modulusLen,RSA_BlockType blockType,SECItem * data)112 rsa_FormatOneBlock(unsigned modulusLen,
113                    RSA_BlockType blockType,
114                    SECItem *data)
115 {
116     unsigned char *block;
117     unsigned char *bp;
118     unsigned int padLen;
119     unsigned int i, j;
120     SECStatus rv;
121 
122     block = (unsigned char *)PORT_Alloc(modulusLen);
123     if (block == NULL)
124         return NULL;
125 
126     bp = block;
127 
128     /*
129      * All RSA blocks start with two octets:
130      *  0x00 || BlockType
131      */
132     *bp++ = RSA_BLOCK_FIRST_OCTET;
133     *bp++ = (unsigned char)blockType;
134 
135     switch (blockType) {
136 
137         /*
138          * Blocks intended for private-key operation.
139          */
140         case RSA_BlockPrivate: /* preferred method */
141             /*
142              * 0x00 || BT || Pad || 0x00 || ActualData
143              *   1      1   padLen    1      data->len
144              * padLen must be at least RSA_BLOCK_MIN_PAD_LEN (8) bytes.
145              * Pad is either all 0x00 or all 0xff bytes, depending on blockType.
146              */
147             padLen = modulusLen - data->len - 3;
148             PORT_Assert(padLen >= RSA_BLOCK_MIN_PAD_LEN);
149             if (padLen < RSA_BLOCK_MIN_PAD_LEN) {
150                 PORT_ZFree(block, modulusLen);
151                 return NULL;
152             }
153             PORT_Memset(bp, RSA_BLOCK_PRIVATE_PAD_OCTET, padLen);
154             bp += padLen;
155             *bp++ = RSA_BLOCK_AFTER_PAD_OCTET;
156             PORT_Memcpy(bp, data->data, data->len);
157             break;
158 
159         /*
160          * Blocks intended for public-key operation.
161          */
162         case RSA_BlockPublic:
163             /*
164              * 0x00 || BT || Pad || 0x00 || ActualData
165              *   1      1   padLen    1      data->len
166              * Pad is 8 or more non-zero random bytes.
167              *
168              * Build the block left to right.
169              * Fill the entire block from Pad to the end with random bytes.
170              * Use the bytes after Pad as a supply of extra random bytes from
171              * which to find replacements for the zero bytes in Pad.
172              * If we need more than that, refill the bytes after Pad with
173              * new random bytes as necessary.
174              */
175 
176             padLen = modulusLen - (data->len + 3);
177             PORT_Assert(padLen >= RSA_BLOCK_MIN_PAD_LEN);
178             if (padLen < RSA_BLOCK_MIN_PAD_LEN) {
179                 PORT_ZFree(block, modulusLen);
180                 return NULL;
181             }
182             j = modulusLen - 2;
183             rv = RNG_GenerateGlobalRandomBytes(bp, j);
184             if (rv == SECSuccess) {
185                 for (i = 0; i < padLen;) {
186                     unsigned char repl;
187                     /* Pad with non-zero random data. */
188                     if (bp[i] != RSA_BLOCK_AFTER_PAD_OCTET) {
189                         ++i;
190                         continue;
191                     }
192                     if (j <= padLen) {
193                         rv = RNG_GenerateGlobalRandomBytes(bp + padLen,
194                                                            modulusLen - (2 + padLen));
195                         if (rv != SECSuccess)
196                             break;
197                         j = modulusLen - 2;
198                     }
199                     do {
200                         repl = bp[--j];
201                     } while (repl == RSA_BLOCK_AFTER_PAD_OCTET && j > padLen);
202                     if (repl != RSA_BLOCK_AFTER_PAD_OCTET) {
203                         bp[i++] = repl;
204                     }
205                 }
206             }
207             if (rv != SECSuccess) {
208                 PORT_ZFree(block, modulusLen);
209                 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
210                 return NULL;
211             }
212             bp += padLen;
213             *bp++ = RSA_BLOCK_AFTER_PAD_OCTET;
214             PORT_Memcpy(bp, data->data, data->len);
215             break;
216 
217         default:
218             PORT_Assert(0);
219             PORT_ZFree(block, modulusLen);
220             return NULL;
221     }
222 
223     return block;
224 }
225 
226 static SECStatus
rsa_FormatBlock(SECItem * result,unsigned modulusLen,RSA_BlockType blockType,SECItem * data)227 rsa_FormatBlock(SECItem *result,
228                 unsigned modulusLen,
229                 RSA_BlockType blockType,
230                 SECItem *data)
231 {
232     switch (blockType) {
233         case RSA_BlockPrivate:
234         case RSA_BlockPublic:
235             /*
236              * 0x00 || BT || Pad || 0x00 || ActualData
237              *
238              * The "3" below is the first octet + the second octet + the 0x00
239              * octet that always comes just before the ActualData.
240              */
241             if (data->len > (modulusLen - (3 + RSA_BLOCK_MIN_PAD_LEN))) {
242                 return SECFailure;
243             }
244             result->data = rsa_FormatOneBlock(modulusLen, blockType, data);
245             if (result->data == NULL) {
246                 result->len = 0;
247                 return SECFailure;
248             }
249             result->len = modulusLen;
250 
251             break;
252 
253         case RSA_BlockRaw:
254             /*
255              * Pad || ActualData
256              * Pad is zeros. The application is responsible for recovering
257              * the actual data.
258              */
259             if (data->len > modulusLen) {
260                 return SECFailure;
261             }
262             result->data = (unsigned char *)PORT_ZAlloc(modulusLen);
263             result->len = modulusLen;
264             PORT_Memcpy(result->data + (modulusLen - data->len),
265                         data->data, data->len);
266             break;
267 
268         default:
269             PORT_Assert(0);
270             result->data = NULL;
271             result->len = 0;
272             return SECFailure;
273     }
274 
275     return SECSuccess;
276 }
277 
278 /*
279  * Mask generation function MGF1 as defined in PKCS #1 v2.1 / RFC 3447.
280  */
281 static SECStatus
MGF1(HASH_HashType hashAlg,unsigned char * mask,unsigned int maskLen,const unsigned char * mgfSeed,unsigned int mgfSeedLen)282 MGF1(HASH_HashType hashAlg,
283      unsigned char *mask,
284      unsigned int maskLen,
285      const unsigned char *mgfSeed,
286      unsigned int mgfSeedLen)
287 {
288     unsigned int digestLen;
289     PRUint32 counter;
290     PRUint32 rounds;
291     unsigned char *tempHash;
292     unsigned char *temp;
293     const SECHashObject *hash;
294     void *hashContext;
295     unsigned char C[4];
296     SECStatus rv = SECSuccess;
297 
298     hash = HASH_GetRawHashObject(hashAlg);
299     if (hash == NULL) {
300         return SECFailure;
301     }
302 
303     hashContext = (*hash->create)();
304     rounds = (maskLen + hash->length - 1) / hash->length;
305     for (counter = 0; counter < rounds; counter++) {
306         C[0] = (unsigned char)((counter >> 24) & 0xff);
307         C[1] = (unsigned char)((counter >> 16) & 0xff);
308         C[2] = (unsigned char)((counter >> 8) & 0xff);
309         C[3] = (unsigned char)(counter & 0xff);
310 
311         /* This could be optimized when the clone functions in
312          * rawhash.c are implemented. */
313         (*hash->begin)(hashContext);
314         (*hash->update)(hashContext, mgfSeed, mgfSeedLen);
315         (*hash->update)(hashContext, C, sizeof C);
316 
317         tempHash = mask + counter * hash->length;
318         if (counter != (rounds - 1)) {
319             (*hash->end)(hashContext, tempHash, &digestLen, hash->length);
320         } else { /* we're in the last round and need to cut the hash */
321             temp = (unsigned char *)PORT_Alloc(hash->length);
322             if (!temp) {
323                 rv = SECFailure;
324                 goto done;
325             }
326             (*hash->end)(hashContext, temp, &digestLen, hash->length);
327             PORT_Memcpy(tempHash, temp, maskLen - counter * hash->length);
328             PORT_Free(temp);
329         }
330     }
331 
332 done:
333     (*hash->destroy)(hashContext, PR_TRUE);
334     return rv;
335 }
336 
337 /* XXX Doesn't set error code */
338 SECStatus
RSA_SignRaw(RSAPrivateKey * key,unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * data,unsigned int dataLen)339 RSA_SignRaw(RSAPrivateKey *key,
340             unsigned char *output,
341             unsigned int *outputLen,
342             unsigned int maxOutputLen,
343             const unsigned char *data,
344             unsigned int dataLen)
345 {
346     SECStatus rv = SECSuccess;
347     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
348     SECItem formatted;
349     SECItem unformatted;
350 
351     if (maxOutputLen < modulusLen)
352         return SECFailure;
353 
354     unformatted.len = dataLen;
355     unformatted.data = (unsigned char *)data;
356     formatted.data = NULL;
357     rv = rsa_FormatBlock(&formatted, modulusLen, RSA_BlockRaw, &unformatted);
358     if (rv != SECSuccess)
359         goto done;
360 
361     rv = RSA_PrivateKeyOpDoubleChecked(key, output, formatted.data);
362     *outputLen = modulusLen;
363 
364 done:
365     if (formatted.data != NULL)
366         PORT_ZFree(formatted.data, modulusLen);
367     return rv;
368 }
369 
370 /* XXX Doesn't set error code */
371 SECStatus
RSA_CheckSignRaw(RSAPublicKey * key,const unsigned char * sig,unsigned int sigLen,const unsigned char * hash,unsigned int hashLen)372 RSA_CheckSignRaw(RSAPublicKey *key,
373                  const unsigned char *sig,
374                  unsigned int sigLen,
375                  const unsigned char *hash,
376                  unsigned int hashLen)
377 {
378     SECStatus rv;
379     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
380     unsigned char *buffer;
381 
382     if (sigLen != modulusLen)
383         goto failure;
384     if (hashLen > modulusLen)
385         goto failure;
386 
387     buffer = (unsigned char *)PORT_Alloc(modulusLen + 1);
388     if (!buffer)
389         goto failure;
390 
391     rv = RSA_PublicKeyOp(key, buffer, sig);
392     if (rv != SECSuccess)
393         goto loser;
394 
395     /*
396      * make sure we get the same results
397      */
398     /* XXX(rsleevi): Constant time */
399     /* NOTE: should we verify the leading zeros? */
400     if (PORT_Memcmp(buffer + (modulusLen - hashLen), hash, hashLen) != 0)
401         goto loser;
402 
403     PORT_Free(buffer);
404     return SECSuccess;
405 
406 loser:
407     PORT_Free(buffer);
408 failure:
409     return SECFailure;
410 }
411 
412 /* XXX Doesn't set error code */
413 SECStatus
RSA_CheckSignRecoverRaw(RSAPublicKey * key,unsigned char * data,unsigned int * dataLen,unsigned int maxDataLen,const unsigned char * sig,unsigned int sigLen)414 RSA_CheckSignRecoverRaw(RSAPublicKey *key,
415                         unsigned char *data,
416                         unsigned int *dataLen,
417                         unsigned int maxDataLen,
418                         const unsigned char *sig,
419                         unsigned int sigLen)
420 {
421     SECStatus rv;
422     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
423 
424     if (sigLen != modulusLen)
425         goto failure;
426     if (maxDataLen < modulusLen)
427         goto failure;
428 
429     rv = RSA_PublicKeyOp(key, data, sig);
430     if (rv != SECSuccess)
431         goto failure;
432 
433     *dataLen = modulusLen;
434     return SECSuccess;
435 
436 failure:
437     return SECFailure;
438 }
439 
440 /* XXX Doesn't set error code */
441 SECStatus
RSA_EncryptRaw(RSAPublicKey * key,unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * input,unsigned int inputLen)442 RSA_EncryptRaw(RSAPublicKey *key,
443                unsigned char *output,
444                unsigned int *outputLen,
445                unsigned int maxOutputLen,
446                const unsigned char *input,
447                unsigned int inputLen)
448 {
449     SECStatus rv;
450     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
451     SECItem formatted;
452     SECItem unformatted;
453 
454     formatted.data = NULL;
455     if (maxOutputLen < modulusLen)
456         goto failure;
457 
458     unformatted.len = inputLen;
459     unformatted.data = (unsigned char *)input;
460     formatted.data = NULL;
461     rv = rsa_FormatBlock(&formatted, modulusLen, RSA_BlockRaw, &unformatted);
462     if (rv != SECSuccess)
463         goto failure;
464 
465     rv = RSA_PublicKeyOp(key, output, formatted.data);
466     if (rv != SECSuccess)
467         goto failure;
468 
469     PORT_ZFree(formatted.data, modulusLen);
470     *outputLen = modulusLen;
471     return SECSuccess;
472 
473 failure:
474     if (formatted.data != NULL)
475         PORT_ZFree(formatted.data, modulusLen);
476     return SECFailure;
477 }
478 
479 /* XXX Doesn't set error code */
480 SECStatus
RSA_DecryptRaw(RSAPrivateKey * key,unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * input,unsigned int inputLen)481 RSA_DecryptRaw(RSAPrivateKey *key,
482                unsigned char *output,
483                unsigned int *outputLen,
484                unsigned int maxOutputLen,
485                const unsigned char *input,
486                unsigned int inputLen)
487 {
488     SECStatus rv;
489     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
490 
491     if (modulusLen > maxOutputLen)
492         goto failure;
493     if (inputLen != modulusLen)
494         goto failure;
495 
496     rv = RSA_PrivateKeyOp(key, output, input);
497     if (rv != SECSuccess)
498         goto failure;
499 
500     *outputLen = modulusLen;
501     return SECSuccess;
502 
503 failure:
504     return SECFailure;
505 }
506 
507 /*
508  * Decodes an EME-OAEP encoded block, validating the encoding in constant
509  * time.
510  * Described in RFC 3447, section 7.1.2.
511  * input contains the encoded block, after decryption.
512  * label is the optional value L that was associated with the message.
513  * On success, the original message and message length will be stored in
514  * output and outputLen.
515  */
516 static SECStatus
eme_oaep_decode(unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * input,unsigned int inputLen,HASH_HashType hashAlg,HASH_HashType maskHashAlg,const unsigned char * label,unsigned int labelLen)517 eme_oaep_decode(unsigned char *output,
518                 unsigned int *outputLen,
519                 unsigned int maxOutputLen,
520                 const unsigned char *input,
521                 unsigned int inputLen,
522                 HASH_HashType hashAlg,
523                 HASH_HashType maskHashAlg,
524                 const unsigned char *label,
525                 unsigned int labelLen)
526 {
527     const SECHashObject *hash;
528     void *hashContext;
529     SECStatus rv = SECFailure;
530     unsigned char labelHash[HASH_LENGTH_MAX];
531     unsigned int i;
532     unsigned int maskLen;
533     unsigned int paddingOffset;
534     unsigned char *mask = NULL;
535     unsigned char *tmpOutput = NULL;
536     unsigned char isGood;
537     unsigned char foundPaddingEnd;
538 
539     hash = HASH_GetRawHashObject(hashAlg);
540 
541     /* 1.c */
542     if (inputLen < (hash->length * 2) + 2) {
543         PORT_SetError(SEC_ERROR_INPUT_LEN);
544         return SECFailure;
545     }
546 
547     /* Step 3.a - Generate lHash */
548     hashContext = (*hash->create)();
549     if (hashContext == NULL) {
550         PORT_SetError(SEC_ERROR_NO_MEMORY);
551         return SECFailure;
552     }
553     (*hash->begin)(hashContext);
554     if (labelLen > 0)
555         (*hash->update)(hashContext, label, labelLen);
556     (*hash->end)(hashContext, labelHash, &i, sizeof(labelHash));
557     (*hash->destroy)(hashContext, PR_TRUE);
558 
559     tmpOutput = (unsigned char *)PORT_Alloc(inputLen);
560     if (tmpOutput == NULL) {
561         PORT_SetError(SEC_ERROR_NO_MEMORY);
562         goto done;
563     }
564 
565     maskLen = inputLen - hash->length - 1;
566     mask = (unsigned char *)PORT_Alloc(maskLen);
567     if (mask == NULL) {
568         PORT_SetError(SEC_ERROR_NO_MEMORY);
569         goto done;
570     }
571 
572     PORT_Memcpy(tmpOutput, input, inputLen);
573 
574     /* 3.c - Generate seedMask */
575     MGF1(maskHashAlg, mask, hash->length, &tmpOutput[1 + hash->length],
576          inputLen - hash->length - 1);
577     /* 3.d - Unmask seed */
578     for (i = 0; i < hash->length; ++i)
579         tmpOutput[1 + i] ^= mask[i];
580 
581     /* 3.e - Generate dbMask */
582     MGF1(maskHashAlg, mask, maskLen, &tmpOutput[1], hash->length);
583     /* 3.f - Unmask DB */
584     for (i = 0; i < maskLen; ++i)
585         tmpOutput[1 + hash->length + i] ^= mask[i];
586 
587     /* 3.g - Compare Y, lHash, and PS in constant time
588      * Warning: This code is timing dependent and must not disclose which of
589      * these were invalid.
590      */
591     paddingOffset = 0;
592     isGood = 1;
593     foundPaddingEnd = 0;
594 
595     /* Compare Y */
596     isGood &= constantTimeEQ8(0x00, tmpOutput[0]);
597 
598     /* Compare lHash and lHash' */
599     isGood &= constantTimeCompare(&labelHash[0],
600                                   &tmpOutput[1 + hash->length],
601                                   hash->length);
602 
603     /* Compare that the padding is zero or more zero octets, followed by a
604      * 0x01 octet */
605     for (i = 1 + (hash->length * 2); i < inputLen; ++i) {
606         unsigned char isZero = constantTimeEQ8(0x00, tmpOutput[i]);
607         unsigned char isOne = constantTimeEQ8(0x01, tmpOutput[i]);
608         /* non-constant time equivalent:
609          * if (tmpOutput[i] == 0x01 && !foundPaddingEnd)
610          *     paddingOffset = i;
611          */
612         paddingOffset = constantTimeCondition(isOne & ~foundPaddingEnd, i,
613                                               paddingOffset);
614         /* non-constant time equivalent:
615          * if (tmpOutput[i] == 0x01)
616          *    foundPaddingEnd = true;
617          *
618          * Note: This may yield false positives, as it will be set whenever
619          * a 0x01 byte is encountered. If there was bad padding (eg:
620          * 0x03 0x02 0x01), foundPaddingEnd will still be set to true, and
621          * paddingOffset will still be set to 2.
622          */
623         foundPaddingEnd = constantTimeCondition(isOne, 1, foundPaddingEnd);
624         /* non-constant time equivalent:
625          * if (tmpOutput[i] != 0x00 && tmpOutput[i] != 0x01 &&
626          *     !foundPaddingEnd) {
627          *    isGood = false;
628          * }
629          *
630          * Note: This may yield false positives, as a message (and padding)
631          * that is entirely zeros will result in isGood still being true. Thus
632          * it's necessary to check foundPaddingEnd is positive below.
633          */
634         isGood = constantTimeCondition(~foundPaddingEnd & ~isZero, 0, isGood);
635     }
636 
637     /* While both isGood and foundPaddingEnd may have false positives, they
638      * cannot BOTH have false positives. If both are not true, then an invalid
639      * message was received. Note, this comparison must still be done in constant
640      * time so as not to leak either condition.
641      */
642     if (!(isGood & foundPaddingEnd)) {
643         PORT_SetError(SEC_ERROR_BAD_DATA);
644         goto done;
645     }
646 
647     /* End timing dependent code */
648 
649     ++paddingOffset; /* Skip the 0x01 following the end of PS */
650 
651     *outputLen = inputLen - paddingOffset;
652     if (*outputLen > maxOutputLen) {
653         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
654         goto done;
655     }
656 
657     if (*outputLen)
658         PORT_Memcpy(output, &tmpOutput[paddingOffset], *outputLen);
659     rv = SECSuccess;
660 
661 done:
662     if (mask)
663         PORT_ZFree(mask, maskLen);
664     if (tmpOutput)
665         PORT_ZFree(tmpOutput, inputLen);
666     return rv;
667 }
668 
669 /*
670  * Generate an EME-OAEP encoded block for encryption
671  * Described in RFC 3447, section 7.1.1
672  * We use input instead of M for the message to be encrypted
673  * label is the optional value L to be associated with the message.
674  */
675 static SECStatus
eme_oaep_encode(unsigned char * em,unsigned int emLen,const unsigned char * input,unsigned int inputLen,HASH_HashType hashAlg,HASH_HashType maskHashAlg,const unsigned char * label,unsigned int labelLen,const unsigned char * seed,unsigned int seedLen)676 eme_oaep_encode(unsigned char *em,
677                 unsigned int emLen,
678                 const unsigned char *input,
679                 unsigned int inputLen,
680                 HASH_HashType hashAlg,
681                 HASH_HashType maskHashAlg,
682                 const unsigned char *label,
683                 unsigned int labelLen,
684                 const unsigned char *seed,
685                 unsigned int seedLen)
686 {
687     const SECHashObject *hash;
688     void *hashContext;
689     SECStatus rv;
690     unsigned char *mask;
691     unsigned int reservedLen;
692     unsigned int dbMaskLen;
693     unsigned int i;
694 
695     hash = HASH_GetRawHashObject(hashAlg);
696     PORT_Assert(seed == NULL || seedLen == hash->length);
697 
698     /* Step 1.b */
699     reservedLen = (2 * hash->length) + 2;
700     if (emLen < reservedLen || inputLen > (emLen - reservedLen)) {
701         PORT_SetError(SEC_ERROR_INPUT_LEN);
702         return SECFailure;
703     }
704 
705     /*
706      * From RFC 3447, Section 7.1
707      *                      +----------+---------+-------+
708      *                 DB = |  lHash   |    PS   |   M   |
709      *                      +----------+---------+-------+
710      *                                     |
711      *           +----------+              V
712      *           |   seed   |--> MGF ---> xor
713      *           +----------+              |
714      *                 |                   |
715      *        +--+     V                   |
716      *        |00|    xor <----- MGF <-----|
717      *        +--+     |                   |
718      *          |      |                   |
719      *          V      V                   V
720      *        +--+----------+----------------------------+
721      *  EM =  |00|maskedSeed|          maskedDB          |
722      *        +--+----------+----------------------------+
723      *
724      * We use mask to hold the result of the MGF functions, and all other
725      * values are generated in their final resting place.
726      */
727     *em = 0x00;
728 
729     /* Step 2.a - Generate lHash */
730     hashContext = (*hash->create)();
731     if (hashContext == NULL) {
732         PORT_SetError(SEC_ERROR_NO_MEMORY);
733         return SECFailure;
734     }
735     (*hash->begin)(hashContext);
736     if (labelLen > 0)
737         (*hash->update)(hashContext, label, labelLen);
738     (*hash->end)(hashContext, &em[1 + hash->length], &i, hash->length);
739     (*hash->destroy)(hashContext, PR_TRUE);
740 
741     /* Step 2.b - Generate PS */
742     if (emLen - reservedLen - inputLen > 0) {
743         PORT_Memset(em + 1 + (hash->length * 2), 0x00,
744                     emLen - reservedLen - inputLen);
745     }
746 
747     /* Step 2.c. - Generate DB
748      * DB = lHash || PS || 0x01 || M
749      * Note that PS and lHash have already been placed into em at their
750      * appropriate offsets. This just copies M into place
751      */
752     em[emLen - inputLen - 1] = 0x01;
753     if (inputLen)
754         PORT_Memcpy(em + emLen - inputLen, input, inputLen);
755 
756     if (seed == NULL) {
757         /* Step 2.d - Generate seed */
758         rv = RNG_GenerateGlobalRandomBytes(em + 1, hash->length);
759         if (rv != SECSuccess) {
760             return rv;
761         }
762     } else {
763         /* For Known Answer Tests, copy the supplied seed. */
764         PORT_Memcpy(em + 1, seed, seedLen);
765     }
766 
767     /* Step 2.e - Generate dbMask*/
768     dbMaskLen = emLen - hash->length - 1;
769     mask = (unsigned char *)PORT_Alloc(dbMaskLen);
770     if (mask == NULL) {
771         PORT_SetError(SEC_ERROR_NO_MEMORY);
772         return SECFailure;
773     }
774     MGF1(maskHashAlg, mask, dbMaskLen, em + 1, hash->length);
775     /* Step 2.f - Compute maskedDB*/
776     for (i = 0; i < dbMaskLen; ++i)
777         em[1 + hash->length + i] ^= mask[i];
778 
779     /* Step 2.g - Generate seedMask */
780     MGF1(maskHashAlg, mask, hash->length, &em[1 + hash->length], dbMaskLen);
781     /* Step 2.h - Compute maskedSeed */
782     for (i = 0; i < hash->length; ++i)
783         em[1 + i] ^= mask[i];
784 
785     PORT_ZFree(mask, dbMaskLen);
786     return SECSuccess;
787 }
788 
789 SECStatus
RSA_EncryptOAEP(RSAPublicKey * key,HASH_HashType hashAlg,HASH_HashType maskHashAlg,const unsigned char * label,unsigned int labelLen,const unsigned char * seed,unsigned int seedLen,unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * input,unsigned int inputLen)790 RSA_EncryptOAEP(RSAPublicKey *key,
791                 HASH_HashType hashAlg,
792                 HASH_HashType maskHashAlg,
793                 const unsigned char *label,
794                 unsigned int labelLen,
795                 const unsigned char *seed,
796                 unsigned int seedLen,
797                 unsigned char *output,
798                 unsigned int *outputLen,
799                 unsigned int maxOutputLen,
800                 const unsigned char *input,
801                 unsigned int inputLen)
802 {
803     SECStatus rv = SECFailure;
804     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
805     unsigned char *oaepEncoded = NULL;
806 
807     if (maxOutputLen < modulusLen) {
808         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
809         return SECFailure;
810     }
811 
812     if ((hashAlg == HASH_AlgNULL) || (maskHashAlg == HASH_AlgNULL)) {
813         PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
814         return SECFailure;
815     }
816 
817     if ((labelLen == 0 && label != NULL) ||
818         (labelLen > 0 && label == NULL)) {
819         PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
820         return SECFailure;
821     }
822 
823     oaepEncoded = (unsigned char *)PORT_Alloc(modulusLen);
824     if (oaepEncoded == NULL) {
825         PORT_SetError(SEC_ERROR_NO_MEMORY);
826         return SECFailure;
827     }
828     rv = eme_oaep_encode(oaepEncoded, modulusLen, input, inputLen,
829                          hashAlg, maskHashAlg, label, labelLen, seed, seedLen);
830     if (rv != SECSuccess)
831         goto done;
832 
833     rv = RSA_PublicKeyOp(key, output, oaepEncoded);
834     if (rv != SECSuccess)
835         goto done;
836     *outputLen = modulusLen;
837 
838 done:
839     PORT_Free(oaepEncoded);
840     return rv;
841 }
842 
843 SECStatus
RSA_DecryptOAEP(RSAPrivateKey * key,HASH_HashType hashAlg,HASH_HashType maskHashAlg,const unsigned char * label,unsigned int labelLen,unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * input,unsigned int inputLen)844 RSA_DecryptOAEP(RSAPrivateKey *key,
845                 HASH_HashType hashAlg,
846                 HASH_HashType maskHashAlg,
847                 const unsigned char *label,
848                 unsigned int labelLen,
849                 unsigned char *output,
850                 unsigned int *outputLen,
851                 unsigned int maxOutputLen,
852                 const unsigned char *input,
853                 unsigned int inputLen)
854 {
855     SECStatus rv = SECFailure;
856     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
857     unsigned char *oaepEncoded = NULL;
858 
859     if ((hashAlg == HASH_AlgNULL) || (maskHashAlg == HASH_AlgNULL)) {
860         PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
861         return SECFailure;
862     }
863 
864     if (inputLen != modulusLen) {
865         PORT_SetError(SEC_ERROR_INPUT_LEN);
866         return SECFailure;
867     }
868 
869     if ((labelLen == 0 && label != NULL) ||
870         (labelLen > 0 && label == NULL)) {
871         PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
872         return SECFailure;
873     }
874 
875     oaepEncoded = (unsigned char *)PORT_Alloc(modulusLen);
876     if (oaepEncoded == NULL) {
877         PORT_SetError(SEC_ERROR_NO_MEMORY);
878         return SECFailure;
879     }
880 
881     rv = RSA_PrivateKeyOpDoubleChecked(key, oaepEncoded, input);
882     if (rv != SECSuccess) {
883         goto done;
884     }
885     rv = eme_oaep_decode(output, outputLen, maxOutputLen, oaepEncoded,
886                          modulusLen, hashAlg, maskHashAlg, label,
887                          labelLen);
888 
889 done:
890     if (oaepEncoded)
891         PORT_ZFree(oaepEncoded, modulusLen);
892     return rv;
893 }
894 
895 /* XXX Doesn't set error code */
896 SECStatus
RSA_EncryptBlock(RSAPublicKey * key,unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * input,unsigned int inputLen)897 RSA_EncryptBlock(RSAPublicKey *key,
898                  unsigned char *output,
899                  unsigned int *outputLen,
900                  unsigned int maxOutputLen,
901                  const unsigned char *input,
902                  unsigned int inputLen)
903 {
904     SECStatus rv;
905     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
906     SECItem formatted;
907     SECItem unformatted;
908 
909     formatted.data = NULL;
910     if (maxOutputLen < modulusLen)
911         goto failure;
912 
913     unformatted.len = inputLen;
914     unformatted.data = (unsigned char *)input;
915     formatted.data = NULL;
916     rv = rsa_FormatBlock(&formatted, modulusLen, RSA_BlockPublic,
917                          &unformatted);
918     if (rv != SECSuccess)
919         goto failure;
920 
921     rv = RSA_PublicKeyOp(key, output, formatted.data);
922     if (rv != SECSuccess)
923         goto failure;
924 
925     PORT_ZFree(formatted.data, modulusLen);
926     *outputLen = modulusLen;
927     return SECSuccess;
928 
929 failure:
930     if (formatted.data != NULL)
931         PORT_ZFree(formatted.data, modulusLen);
932     return SECFailure;
933 }
934 
935 static HMACContext *
rsa_GetHMACContext(const SECHashObject * hash,RSAPrivateKey * key,const unsigned char * input,unsigned int inputLen)936 rsa_GetHMACContext(const SECHashObject *hash, RSAPrivateKey *key,
937                    const unsigned char *input, unsigned int inputLen)
938 {
939     unsigned char keyHash[HASH_LENGTH_MAX];
940     void *hashContext;
941     HMACContext *hmac = NULL;
942     unsigned int privKeyLen = key->privateExponent.len;
943     unsigned int keyLen;
944     SECStatus rv;
945 
946     /* first get the key hash (should store in the key structure) */
947     PORT_Memset(keyHash, 0, sizeof(keyHash));
948     hashContext = (*hash->create)();
949     if (hashContext == NULL) {
950         return NULL;
951     }
952     (*hash->begin)(hashContext);
953     if (privKeyLen < inputLen) {
954         int padLen = inputLen - privKeyLen;
955         while (padLen > sizeof(keyHash)) {
956             (*hash->update)(hashContext, keyHash, sizeof(keyHash));
957             padLen -= sizeof(keyHash);
958         }
959         (*hash->update)(hashContext, keyHash, padLen);
960     }
961     (*hash->update)(hashContext, key->privateExponent.data, privKeyLen);
962     (*hash->end)(hashContext, keyHash, &keyLen, sizeof(keyHash));
963     (*hash->destroy)(hashContext, PR_TRUE);
964 
965     /* now create the hmac key */
966     hmac = HMAC_Create(hash, keyHash, keyLen, PR_TRUE);
967     if (hmac == NULL) {
968         PORT_Memset(keyHash, 0, sizeof(keyHash));
969         return NULL;
970     }
971     HMAC_Begin(hmac);
972     HMAC_Update(hmac, input, inputLen);
973     rv = HMAC_Finish(hmac, keyHash, &keyLen, sizeof(keyHash));
974     if (rv != SECSuccess) {
975         PORT_Memset(keyHash, 0, sizeof(keyHash));
976         HMAC_Destroy(hmac, PR_TRUE);
977         return NULL;
978     }
979     /* Finally set the new key into the hash context. We
980      * reuse the original context allocated above so we don't
981      * need to allocate and free another one */
982     rv = HMAC_ReInit(hmac, hash, keyHash, keyLen, PR_TRUE);
983     PORT_Memset(keyHash, 0, sizeof(keyHash));
984     if (rv != SECSuccess) {
985         HMAC_Destroy(hmac, PR_TRUE);
986         return NULL;
987     }
988 
989     return hmac;
990 }
991 
992 static SECStatus
rsa_HMACPrf(HMACContext * hmac,const char * label,int labelLen,int hashLength,unsigned char * output,int length)993 rsa_HMACPrf(HMACContext *hmac, const char *label, int labelLen,
994             int hashLength, unsigned char *output, int length)
995 {
996     unsigned char iterator[2] = { 0, 0 };
997     unsigned char encodedLen[2] = { 0, 0 };
998     unsigned char hmacLast[HASH_LENGTH_MAX];
999     unsigned int left = length;
1000     unsigned int hashReturn;
1001     SECStatus rv = SECSuccess;
1002 
1003     /* encodedLen is in bits, length is in bytes, thus the shifts
1004      * do an implied multiply by 8 */
1005     encodedLen[0] = (length >> 5) & 0xff;
1006     encodedLen[1] = (length << 3) & 0xff;
1007 
1008     while (left > hashLength) {
1009         HMAC_Begin(hmac);
1010         HMAC_Update(hmac, iterator, 2);
1011         HMAC_Update(hmac, (const unsigned char *)label, labelLen);
1012         HMAC_Update(hmac, encodedLen, 2);
1013         rv = HMAC_Finish(hmac, output, &hashReturn, hashLength);
1014         if (rv != SECSuccess) {
1015             return rv;
1016         }
1017         iterator[1]++;
1018         if (iterator[1] == 0)
1019             iterator[0]++;
1020         left -= hashLength;
1021         output += hashLength;
1022     }
1023     if (left) {
1024         HMAC_Begin(hmac);
1025         HMAC_Update(hmac, iterator, 2);
1026         HMAC_Update(hmac, (const unsigned char *)label, labelLen);
1027         HMAC_Update(hmac, encodedLen, 2);
1028         rv = HMAC_Finish(hmac, hmacLast, &hashReturn, sizeof(hmacLast));
1029         if (rv != SECSuccess) {
1030             return rv;
1031         }
1032         PORT_Memcpy(output, hmacLast, left);
1033         PORT_Memset(hmacLast, 0, sizeof(hmacLast));
1034     }
1035     return rv;
1036 }
1037 
1038 /* This function takes a 16-bit input number and
1039  * creates the smallest mask which covers
1040  * the whole number. Examples:
1041  *     0x81 -> 0xff
1042  *     0x1af -> 0x1ff
1043  *     0x4d1 -> 0x7ff
1044  */
1045 static int
makeMask16(int len)1046 makeMask16(int len)
1047 {
1048     // or the high bit in each bit location
1049     len |= (len >> 1);
1050     len |= (len >> 2);
1051     len |= (len >> 4);
1052     len |= (len >> 8);
1053     return len;
1054 }
1055 
1056 #define STRING_AND_LENGTH(s) s, sizeof(s) - 1
1057 static int
rsa_GetErrorLength(HMACContext * hmac,int hashLen,int maxLegalLen)1058 rsa_GetErrorLength(HMACContext *hmac, int hashLen, int maxLegalLen)
1059 {
1060     unsigned char out[128 * 2];
1061     unsigned char *outp;
1062     int outLength = 0;
1063     int lengthMask;
1064     SECStatus rv;
1065 
1066     lengthMask = makeMask16(maxLegalLen);
1067     rv = rsa_HMACPrf(hmac, STRING_AND_LENGTH("length"), hashLen,
1068                      out, sizeof(out));
1069     if (rv != SECSuccess) {
1070         return -1;
1071     }
1072     for (outp = out; outp < out + sizeof(out); outp += 2) {
1073         int candidate = outp[0] << 8 | outp[1];
1074         candidate = candidate & lengthMask;
1075         outLength = PORT_CT_SEL(PORT_CT_LT(candidate, maxLegalLen),
1076                                 candidate, outLength);
1077     }
1078     PORT_Memset(out, 0, sizeof(out));
1079     return outLength;
1080 }
1081 
1082 /*
1083  * This function can only fail in environmental cases: Programming errors
1084  * and out of memory situations. It can't fail if the keys are valid and
1085  * the inputs are the proper size. If the actual RSA decryption fails, a
1086  * fake value and a fake length, both of which have already been generated
1087  * based on the key and input, are returned.
1088  * Applications are expected to detect decryption failures based on the fact
1089  * that the decrypted value (usually a key) doesn't validate. The prevents
1090  * Blecheinbaucher style attacks against the key. */
1091 SECStatus
RSA_DecryptBlock(RSAPrivateKey * key,unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * input,unsigned int inputLen)1092 RSA_DecryptBlock(RSAPrivateKey *key,
1093                  unsigned char *output,
1094                  unsigned int *outputLen,
1095                  unsigned int maxOutputLen,
1096                  const unsigned char *input,
1097                  unsigned int inputLen)
1098 {
1099     SECStatus rv;
1100     PRUint32 fail;
1101     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
1102     unsigned int i;
1103     unsigned char *buffer = NULL;
1104     unsigned char *errorBuffer = NULL;
1105     unsigned char *bp = NULL;
1106     unsigned char *ep = NULL;
1107     unsigned int outLen = modulusLen;
1108     unsigned int maxLegalLen = modulusLen - 10;
1109     unsigned int errorLength;
1110     const SECHashObject *hashObj;
1111     HMACContext *hmac = NULL;
1112 
1113     /* failures in the top section indicate failures in the environment
1114      * (memory) or the library. OK to return errors in these cases because
1115      * it doesn't provide any oracle information to attackers. */
1116     if (inputLen != modulusLen || modulusLen < 10) {
1117         PORT_SetError(SEC_ERROR_INVALID_ARGS);
1118         return SECFailure;
1119     }
1120 
1121     /* Allocate enough space to decrypt */
1122     buffer = PORT_ZAlloc(modulusLen);
1123     if (!buffer) {
1124         goto loser;
1125     }
1126     errorBuffer = PORT_ZAlloc(modulusLen);
1127     if (!errorBuffer) {
1128         goto loser;
1129     }
1130     hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
1131     if (hashObj == NULL) {
1132         goto loser;
1133     }
1134 
1135     /* calculate the values to return in the error case rather than
1136      * the actual returned values. This data is the same for the
1137      * same input and private key. */
1138     hmac = rsa_GetHMACContext(hashObj, key, input, inputLen);
1139     if (hmac == NULL) {
1140         goto loser;
1141     }
1142     errorLength = rsa_GetErrorLength(hmac, hashObj->length, maxLegalLen);
1143     if (((int)errorLength) < 0) {
1144         goto loser;
1145     }
1146     /* we always have to generate a full moduluslen error string. Otherwise
1147      * we create a timing dependency on errorLength, which could be used to
1148      * determine the difference between errorLength and outputLen and tell
1149      * us that there was a pkcs1 decryption failure */
1150     rv = rsa_HMACPrf(hmac, STRING_AND_LENGTH("message"),
1151                      hashObj->length, errorBuffer, modulusLen);
1152     if (rv != SECSuccess) {
1153         goto loser;
1154     }
1155 
1156     HMAC_Destroy(hmac, PR_TRUE);
1157     hmac = NULL;
1158 
1159     /* From here on out, we will always return success. If there is
1160      * an error, we will return deterministic output based on the key
1161      * and the input data. */
1162     rv = RSA_PrivateKeyOp(key, buffer, input);
1163 
1164     fail = PORT_CT_NE(rv, SECSuccess);
1165     fail |= PORT_CT_NE(buffer[0], RSA_BLOCK_FIRST_OCTET) | PORT_CT_NE(buffer[1], RSA_BlockPublic);
1166 
1167     /* There have to be at least 8 bytes of padding. */
1168     for (i = 2; i < 10; i++) {
1169         fail |= PORT_CT_EQ(buffer[i], RSA_BLOCK_AFTER_PAD_OCTET);
1170     }
1171 
1172     for (i = 10; i < modulusLen; i++) {
1173         unsigned int newLen = modulusLen - i - 1;
1174         PRUint32 condition = PORT_CT_EQ(buffer[i], RSA_BLOCK_AFTER_PAD_OCTET) & PORT_CT_EQ(outLen, modulusLen);
1175         outLen = PORT_CT_SEL(condition, newLen, outLen);
1176     }
1177     // this can only happen if a zero wasn't found above
1178     fail |= PORT_CT_GE(outLen, modulusLen);
1179 
1180     outLen = PORT_CT_SEL(fail, errorLength, outLen);
1181 
1182     /* index into the correct buffer. Do it before we truncate outLen if the
1183      * application was asking for less data than we can return */
1184     bp = buffer + modulusLen - outLen;
1185     ep = errorBuffer + modulusLen - outLen;
1186 
1187     /* at this point, outLen returns no information about decryption failures,
1188      * no need to hide its value. maxOutputLen is how much data the
1189      * application is expecting, which is also not sensitive. */
1190     if (outLen > maxOutputLen) {
1191         outLen = maxOutputLen;
1192     }
1193 
1194     /* we can't use PORT_Memcpy because caching could create a time dependency
1195      * on the status of fail. */
1196     for (i = 0; i < outLen; i++) {
1197         output[i] = PORT_CT_SEL(fail, ep[i], bp[i]);
1198     }
1199 
1200     *outputLen = outLen;
1201 
1202     PORT_Free(buffer);
1203     PORT_Free(errorBuffer);
1204 
1205     return SECSuccess;
1206 
1207 loser:
1208     if (hmac) {
1209         HMAC_Destroy(hmac, PR_TRUE);
1210     }
1211     PORT_Free(buffer);
1212     PORT_Free(errorBuffer);
1213 
1214     return SECFailure;
1215 }
1216 
1217 /*
1218  * Encode a RSA-PSS signature.
1219  * Described in RFC 3447, section 9.1.1.
1220  * We use mHash instead of M as input.
1221  * emBits from the RFC is just modBits - 1, see section 8.1.1.
1222  * We only support MGF1 as the MGF.
1223  */
1224 static SECStatus
emsa_pss_encode(unsigned char * em,unsigned int emLen,unsigned int emBits,const unsigned char * mHash,HASH_HashType hashAlg,HASH_HashType maskHashAlg,const unsigned char * salt,unsigned int saltLen)1225 emsa_pss_encode(unsigned char *em,
1226                 unsigned int emLen,
1227                 unsigned int emBits,
1228                 const unsigned char *mHash,
1229                 HASH_HashType hashAlg,
1230                 HASH_HashType maskHashAlg,
1231                 const unsigned char *salt,
1232                 unsigned int saltLen)
1233 {
1234     const SECHashObject *hash;
1235     void *hash_context;
1236     unsigned char *dbMask;
1237     unsigned int dbMaskLen;
1238     unsigned int i;
1239     SECStatus rv;
1240 
1241     hash = HASH_GetRawHashObject(hashAlg);
1242     dbMaskLen = emLen - hash->length - 1;
1243 
1244     /* Step 3 */
1245     if (emLen < hash->length + saltLen + 2) {
1246         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1247         return SECFailure;
1248     }
1249 
1250     /* Step 4 */
1251     if (salt == NULL) {
1252         rv = RNG_GenerateGlobalRandomBytes(&em[dbMaskLen - saltLen], saltLen);
1253         if (rv != SECSuccess) {
1254             return rv;
1255         }
1256     } else {
1257         PORT_Memcpy(&em[dbMaskLen - saltLen], salt, saltLen);
1258     }
1259 
1260     /* Step 5 + 6 */
1261     /* Compute H and store it at its final location &em[dbMaskLen]. */
1262     hash_context = (*hash->create)();
1263     if (hash_context == NULL) {
1264         PORT_SetError(SEC_ERROR_NO_MEMORY);
1265         return SECFailure;
1266     }
1267     (*hash->begin)(hash_context);
1268     (*hash->update)(hash_context, eightZeros, 8);
1269     (*hash->update)(hash_context, mHash, hash->length);
1270     (*hash->update)(hash_context, &em[dbMaskLen - saltLen], saltLen);
1271     (*hash->end)(hash_context, &em[dbMaskLen], &i, hash->length);
1272     (*hash->destroy)(hash_context, PR_TRUE);
1273 
1274     /* Step 7 + 8 */
1275     PORT_Memset(em, 0, dbMaskLen - saltLen - 1);
1276     em[dbMaskLen - saltLen - 1] = 0x01;
1277 
1278     /* Step 9 */
1279     dbMask = (unsigned char *)PORT_Alloc(dbMaskLen);
1280     if (dbMask == NULL) {
1281         PORT_SetError(SEC_ERROR_NO_MEMORY);
1282         return SECFailure;
1283     }
1284     MGF1(maskHashAlg, dbMask, dbMaskLen, &em[dbMaskLen], hash->length);
1285 
1286     /* Step 10 */
1287     for (i = 0; i < dbMaskLen; i++)
1288         em[i] ^= dbMask[i];
1289     PORT_Free(dbMask);
1290 
1291     /* Step 11 */
1292     em[0] &= 0xff >> (8 * emLen - emBits);
1293 
1294     /* Step 12 */
1295     em[emLen - 1] = 0xbc;
1296 
1297     return SECSuccess;
1298 }
1299 
1300 /*
1301  * Verify a RSA-PSS signature.
1302  * Described in RFC 3447, section 9.1.2.
1303  * We use mHash instead of M as input.
1304  * emBits from the RFC is just modBits - 1, see section 8.1.2.
1305  * We only support MGF1 as the MGF.
1306  */
1307 static SECStatus
emsa_pss_verify(const unsigned char * mHash,const unsigned char * em,unsigned int emLen,unsigned int emBits,HASH_HashType hashAlg,HASH_HashType maskHashAlg,unsigned int saltLen)1308 emsa_pss_verify(const unsigned char *mHash,
1309                 const unsigned char *em,
1310                 unsigned int emLen,
1311                 unsigned int emBits,
1312                 HASH_HashType hashAlg,
1313                 HASH_HashType maskHashAlg,
1314                 unsigned int saltLen)
1315 {
1316     const SECHashObject *hash;
1317     void *hash_context;
1318     unsigned char *db;
1319     unsigned char *H_; /* H' from the RFC */
1320     unsigned int i;
1321     unsigned int dbMaskLen;
1322     unsigned int zeroBits;
1323     SECStatus rv;
1324 
1325     hash = HASH_GetRawHashObject(hashAlg);
1326     dbMaskLen = emLen - hash->length - 1;
1327 
1328     /* Step 3 + 4 */
1329     if ((emLen < (hash->length + saltLen + 2)) ||
1330         (em[emLen - 1] != 0xbc)) {
1331         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1332         return SECFailure;
1333     }
1334 
1335     /* Step 6 */
1336     zeroBits = 8 * emLen - emBits;
1337     if (em[0] >> (8 - zeroBits)) {
1338         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1339         return SECFailure;
1340     }
1341 
1342     /* Step 7 */
1343     db = (unsigned char *)PORT_Alloc(dbMaskLen);
1344     if (db == NULL) {
1345         PORT_SetError(SEC_ERROR_NO_MEMORY);
1346         return SECFailure;
1347     }
1348     /* &em[dbMaskLen] points to H, used as mgfSeed */
1349     MGF1(maskHashAlg, db, dbMaskLen, &em[dbMaskLen], hash->length);
1350 
1351     /* Step 8 */
1352     for (i = 0; i < dbMaskLen; i++) {
1353         db[i] ^= em[i];
1354     }
1355 
1356     /* Step 9 */
1357     db[0] &= 0xff >> zeroBits;
1358 
1359     /* Step 10 */
1360     for (i = 0; i < (dbMaskLen - saltLen - 1); i++) {
1361         if (db[i] != 0) {
1362             PORT_Free(db);
1363             PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1364             return SECFailure;
1365         }
1366     }
1367     if (db[dbMaskLen - saltLen - 1] != 0x01) {
1368         PORT_Free(db);
1369         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1370         return SECFailure;
1371     }
1372 
1373     /* Step 12 + 13 */
1374     H_ = (unsigned char *)PORT_Alloc(hash->length);
1375     if (H_ == NULL) {
1376         PORT_Free(db);
1377         PORT_SetError(SEC_ERROR_NO_MEMORY);
1378         return SECFailure;
1379     }
1380     hash_context = (*hash->create)();
1381     if (hash_context == NULL) {
1382         PORT_Free(db);
1383         PORT_Free(H_);
1384         PORT_SetError(SEC_ERROR_NO_MEMORY);
1385         return SECFailure;
1386     }
1387     (*hash->begin)(hash_context);
1388     (*hash->update)(hash_context, eightZeros, 8);
1389     (*hash->update)(hash_context, mHash, hash->length);
1390     (*hash->update)(hash_context, &db[dbMaskLen - saltLen], saltLen);
1391     (*hash->end)(hash_context, H_, &i, hash->length);
1392     (*hash->destroy)(hash_context, PR_TRUE);
1393 
1394     PORT_Free(db);
1395 
1396     /* Step 14 */
1397     if (PORT_Memcmp(H_, &em[dbMaskLen], hash->length) != 0) {
1398         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1399         rv = SECFailure;
1400     } else {
1401         rv = SECSuccess;
1402     }
1403 
1404     PORT_Free(H_);
1405     return rv;
1406 }
1407 
1408 SECStatus
RSA_SignPSS(RSAPrivateKey * key,HASH_HashType hashAlg,HASH_HashType maskHashAlg,const unsigned char * salt,unsigned int saltLength,unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * input,unsigned int inputLen)1409 RSA_SignPSS(RSAPrivateKey *key,
1410             HASH_HashType hashAlg,
1411             HASH_HashType maskHashAlg,
1412             const unsigned char *salt,
1413             unsigned int saltLength,
1414             unsigned char *output,
1415             unsigned int *outputLen,
1416             unsigned int maxOutputLen,
1417             const unsigned char *input,
1418             unsigned int inputLen)
1419 {
1420     SECStatus rv = SECSuccess;
1421     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
1422     unsigned int modulusBits = rsa_modulusBits(&key->modulus);
1423     unsigned int emLen = modulusLen;
1424     unsigned char *pssEncoded, *em;
1425 
1426     if (maxOutputLen < modulusLen) {
1427         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1428         return SECFailure;
1429     }
1430 
1431     if ((hashAlg == HASH_AlgNULL) || (maskHashAlg == HASH_AlgNULL)) {
1432         PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1433         return SECFailure;
1434     }
1435 
1436     pssEncoded = em = (unsigned char *)PORT_Alloc(modulusLen);
1437     if (pssEncoded == NULL) {
1438         PORT_SetError(SEC_ERROR_NO_MEMORY);
1439         return SECFailure;
1440     }
1441 
1442     /* len(em) == ceil((modulusBits - 1) / 8). */
1443     if (modulusBits % 8 == 1) {
1444         em[0] = 0;
1445         emLen--;
1446         em++;
1447     }
1448     rv = emsa_pss_encode(em, emLen, modulusBits - 1, input, hashAlg,
1449                          maskHashAlg, salt, saltLength);
1450     if (rv != SECSuccess)
1451         goto done;
1452 
1453     // This sets error codes upon failure.
1454     rv = RSA_PrivateKeyOpDoubleChecked(key, output, pssEncoded);
1455     *outputLen = modulusLen;
1456 
1457 done:
1458     PORT_Free(pssEncoded);
1459     return rv;
1460 }
1461 
1462 SECStatus
RSA_CheckSignPSS(RSAPublicKey * key,HASH_HashType hashAlg,HASH_HashType maskHashAlg,unsigned int saltLength,const unsigned char * sig,unsigned int sigLen,const unsigned char * hash,unsigned int hashLen)1463 RSA_CheckSignPSS(RSAPublicKey *key,
1464                  HASH_HashType hashAlg,
1465                  HASH_HashType maskHashAlg,
1466                  unsigned int saltLength,
1467                  const unsigned char *sig,
1468                  unsigned int sigLen,
1469                  const unsigned char *hash,
1470                  unsigned int hashLen)
1471 {
1472     SECStatus rv;
1473     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
1474     unsigned int modulusBits = rsa_modulusBits(&key->modulus);
1475     unsigned int emLen = modulusLen;
1476     unsigned char *buffer, *em;
1477 
1478     if (sigLen != modulusLen) {
1479         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1480         return SECFailure;
1481     }
1482 
1483     if ((hashAlg == HASH_AlgNULL) || (maskHashAlg == HASH_AlgNULL)) {
1484         PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1485         return SECFailure;
1486     }
1487 
1488     buffer = em = (unsigned char *)PORT_Alloc(modulusLen);
1489     if (!buffer) {
1490         PORT_SetError(SEC_ERROR_NO_MEMORY);
1491         return SECFailure;
1492     }
1493 
1494     rv = RSA_PublicKeyOp(key, buffer, sig);
1495     if (rv != SECSuccess) {
1496         PORT_Free(buffer);
1497         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1498         return SECFailure;
1499     }
1500 
1501     /* len(em) == ceil((modulusBits - 1) / 8). */
1502     if (modulusBits % 8 == 1) {
1503         emLen--;
1504         em++;
1505     }
1506     rv = emsa_pss_verify(hash, em, emLen, modulusBits - 1, hashAlg,
1507                          maskHashAlg, saltLength);
1508 
1509     PORT_Free(buffer);
1510     return rv;
1511 }
1512 
1513 SECStatus
RSA_Sign(RSAPrivateKey * key,unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * input,unsigned int inputLen)1514 RSA_Sign(RSAPrivateKey *key,
1515          unsigned char *output,
1516          unsigned int *outputLen,
1517          unsigned int maxOutputLen,
1518          const unsigned char *input,
1519          unsigned int inputLen)
1520 {
1521     SECStatus rv = SECFailure;
1522     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
1523     SECItem formatted = { siBuffer, NULL, 0 };
1524     SECItem unformatted = { siBuffer, (unsigned char *)input, inputLen };
1525 
1526     if (maxOutputLen < modulusLen) {
1527         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1528         goto done;
1529     }
1530 
1531     rv = rsa_FormatBlock(&formatted, modulusLen, RSA_BlockPrivate,
1532                          &unformatted);
1533     if (rv != SECSuccess) {
1534         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1535         goto done;
1536     }
1537 
1538     // This sets error codes upon failure.
1539     rv = RSA_PrivateKeyOpDoubleChecked(key, output, formatted.data);
1540     *outputLen = modulusLen;
1541 
1542 done:
1543     if (formatted.data != NULL) {
1544         PORT_ZFree(formatted.data, modulusLen);
1545     }
1546     return rv;
1547 }
1548 
1549 SECStatus
RSA_CheckSign(RSAPublicKey * key,const unsigned char * sig,unsigned int sigLen,const unsigned char * data,unsigned int dataLen)1550 RSA_CheckSign(RSAPublicKey *key,
1551               const unsigned char *sig,
1552               unsigned int sigLen,
1553               const unsigned char *data,
1554               unsigned int dataLen)
1555 {
1556     SECStatus rv = SECFailure;
1557     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
1558     unsigned int i;
1559     unsigned char *buffer = NULL;
1560 
1561     if (sigLen != modulusLen) {
1562         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1563         goto done;
1564     }
1565 
1566     /*
1567      * 0x00 || BT || Pad || 0x00 || ActualData
1568      *
1569      * The "3" below is the first octet + the second octet + the 0x00
1570      * octet that always comes just before the ActualData.
1571      */
1572     if (dataLen > modulusLen - (3 + RSA_BLOCK_MIN_PAD_LEN)) {
1573         PORT_SetError(SEC_ERROR_BAD_DATA);
1574         goto done;
1575     }
1576 
1577     buffer = (unsigned char *)PORT_Alloc(modulusLen + 1);
1578     if (!buffer) {
1579         PORT_SetError(SEC_ERROR_NO_MEMORY);
1580         goto done;
1581     }
1582 
1583     if (RSA_PublicKeyOp(key, buffer, sig) != SECSuccess) {
1584         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1585         goto done;
1586     }
1587 
1588     /*
1589      * check the padding that was used
1590      */
1591     if (buffer[0] != RSA_BLOCK_FIRST_OCTET ||
1592         buffer[1] != (unsigned char)RSA_BlockPrivate) {
1593         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1594         goto done;
1595     }
1596     for (i = 2; i < modulusLen - dataLen - 1; i++) {
1597         if (buffer[i] != RSA_BLOCK_PRIVATE_PAD_OCTET) {
1598             PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1599             goto done;
1600         }
1601     }
1602     if (buffer[i] != RSA_BLOCK_AFTER_PAD_OCTET) {
1603         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1604         goto done;
1605     }
1606 
1607     /*
1608      * make sure we get the same results
1609      */
1610     if (PORT_Memcmp(buffer + modulusLen - dataLen, data, dataLen) == 0) {
1611         rv = SECSuccess;
1612     }
1613 
1614 done:
1615     if (buffer) {
1616         PORT_Free(buffer);
1617     }
1618     return rv;
1619 }
1620 
1621 SECStatus
RSA_CheckSignRecover(RSAPublicKey * key,unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * sig,unsigned int sigLen)1622 RSA_CheckSignRecover(RSAPublicKey *key,
1623                      unsigned char *output,
1624                      unsigned int *outputLen,
1625                      unsigned int maxOutputLen,
1626                      const unsigned char *sig,
1627                      unsigned int sigLen)
1628 {
1629     SECStatus rv = SECFailure;
1630     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
1631     unsigned int i;
1632     unsigned char *buffer = NULL;
1633     unsigned int padLen;
1634 
1635     if (sigLen != modulusLen) {
1636         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1637         goto done;
1638     }
1639 
1640     buffer = (unsigned char *)PORT_Alloc(modulusLen + 1);
1641     if (!buffer) {
1642         PORT_SetError(SEC_ERROR_NO_MEMORY);
1643         goto done;
1644     }
1645 
1646     if (RSA_PublicKeyOp(key, buffer, sig) != SECSuccess) {
1647         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1648         goto done;
1649     }
1650 
1651     *outputLen = 0;
1652 
1653     /*
1654      * check the padding that was used
1655      */
1656     if (buffer[0] != RSA_BLOCK_FIRST_OCTET ||
1657         buffer[1] != (unsigned char)RSA_BlockPrivate) {
1658         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1659         goto done;
1660     }
1661     for (i = 2; i < modulusLen; i++) {
1662         if (buffer[i] == RSA_BLOCK_AFTER_PAD_OCTET) {
1663             *outputLen = modulusLen - i - 1;
1664             break;
1665         }
1666         if (buffer[i] != RSA_BLOCK_PRIVATE_PAD_OCTET) {
1667             PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1668             goto done;
1669         }
1670     }
1671     padLen = i - 2;
1672     if (padLen < RSA_BLOCK_MIN_PAD_LEN) {
1673         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1674         goto done;
1675     }
1676     if (*outputLen == 0) {
1677         PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
1678         goto done;
1679     }
1680     if (*outputLen > maxOutputLen) {
1681         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1682         goto done;
1683     }
1684 
1685     PORT_Memcpy(output, buffer + modulusLen - *outputLen, *outputLen);
1686     rv = SECSuccess;
1687 
1688 done:
1689     if (buffer) {
1690         PORT_Free(buffer);
1691     }
1692     return rv;
1693 }
1694