1 /* Microsoft Reference Implementation for TPM 2.0
2  *
3  *  The copyright in this software is being made available under the BSD License,
4  *  included below. This software may be subject to other third party and
5  *  contributor rights, including patent rights, and no such rights are granted
6  *  under this license.
7  *
8  *  Copyright (c) Microsoft Corporation
9  *
10  *  All rights reserved.
11  *
12  *  BSD License
13  *
14  *  Redistribution and use in source and binary forms, with or without modification,
15  *  are permitted provided that the following conditions are met:
16  *
17  *  Redistributions of source code must retain the above copyright notice, this list
18  *  of conditions and the following disclaimer.
19  *
20  *  Redistributions in binary form must reproduce the above copyright notice, this
21  *  list of conditions and the following disclaimer in the documentation and/or
22  *  other materials provided with the distribution.
23  *
24  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS""
25  *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27  *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
28  *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29  *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30  *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
31  *  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 //** Introduction
36 //
37 // This file contains implementation of cryptographic primitives for RSA.
38 // Vendors may replace the implementation in this file with their own library
39 // functions.
40 
41 //**  Includes
42 // Need this define to get the 'private' defines for this function
43 #define CRYPT_RSA_C
44 #include "Tpm.h"
45 
46 #if ALG_RSA
47 
48 //**  Obligatory Initialization Functions
49 
50 //*** CryptRsaInit()
51 // Function called at _TPM_Init().
52 BOOL
CryptRsaInit(void)53 CryptRsaInit(
54     void
55     )
56 {
57     return TRUE;
58 }
59 
60 //*** CryptRsaStartup()
61 // Function called at TPM2_Startup()
62 BOOL
CryptRsaStartup(void)63 CryptRsaStartup(
64     void
65     )
66 {
67     return TRUE;
68 }
69 
70 //** Internal Functions
71 
72 //*** RsaInitializeExponent()
73 // This function initializes the bignum data structure that holds the private
74 // exponent. This function returns the pointer to the private exponent value so that
75 // it can be used in an initializer for a data declaration.
76 static privateExponent *
RsaInitializeExponent(privateExponent * Z)77 RsaInitializeExponent(
78     privateExponent       *Z
79     )
80 {
81     bigNum              *bn = (bigNum *)&Z->P;
82     int                  i;
83 //
84     for(i = 0; i < 5; i++)
85     {
86         bn[i] = (bigNum)&Z->entries[i];
87         BnInit(bn[i], BYTES_TO_CRYPT_WORDS(sizeof(Z->entries[0].d)));
88     }
89     return Z;
90 }
91 
92 //*** MakePgreaterThanQ()
93 // This function swaps the pointers for P and Q if Q happens to be larger than Q.
94 static void
MakePgreaterThanQ(privateExponent * Z)95 MakePgreaterThanQ(
96     privateExponent         *Z
97 )
98 {
99     if(BnUnsignedCmp(Z->P, Z->Q) < 0)
100     {
101         bigNum          bnT = Z->P;
102         Z->P = Z->Q;
103         Z->Q = bnT;
104     }
105 }
106 
107 //*** PackExponent()
108 // This function takes the bignum private exponent and converts it into TPM2B form.
109 // In this form, the size field contains the overall size of the packed data. The
110 // buffer contains 5, equal sized values in P, Q, dP, dQ, qInv order. For example, if
111 // a key has a 2Kb public key, then the packed private key will contain 5, 1Kb values.
112 // This form makes it relatively easy to load and save the values without changing
113 // the normal unmarshaling to do anything more than allow a larger TPM2B for the
114 // private key. Also, when exporting the value, all that is needed is to change the
115 // size field of the private key in order to save just the P value.
116 //  Return Type: BOOL
117 //      TRUE(1)     success
118 //      FALSE(0)    failure         // The data is too big to fit
119 static BOOL
PackExponent(TPM2B_PRIVATE_KEY_RSA * packed,privateExponent * Z)120 PackExponent(
121     TPM2B_PRIVATE_KEY_RSA       *packed,
122     privateExponent             *Z
123 )
124 {
125     int                         i;
126     UINT16                      primeSize = (UINT16)BITS_TO_BYTES(BnMsb(Z->P));
127     UINT16                      pS = primeSize;
128 //
129     pAssert((primeSize * 5) <= sizeof(packed->t.buffer));
130     packed->t.size = (primeSize * 5) + RSA_prime_flag;
131     for(i = 0; i < 5; i++)
132         if(!BnToBytes((bigNum)&Z->entries[i], &packed->t.buffer[primeSize * i], &pS))
133             return FALSE;
134     if(pS != primeSize)
135         return FALSE;
136     return TRUE;
137 }
138 
139 //*** UnpackExponent()
140 // This function unpacks the private exponent from its TPM2B form into its bignum
141 // form.
142 //  Return Type: BOOL
143 //      TRUE(1)         success
144 //      FALSE(0)        TPM2B is not the correct size
145 static BOOL
UnpackExponent(TPM2B_PRIVATE_KEY_RSA * b,privateExponent * Z)146 UnpackExponent(
147     TPM2B_PRIVATE_KEY_RSA       *b,
148     privateExponent             *Z
149 )
150 {
151         UINT16               primeSize = b->t.size & ~RSA_prime_flag;
152         int                  i;
153         bigNum              *bn = &Z->P;
154 //
155     VERIFY(b->t.size & RSA_prime_flag);
156     RsaInitializeExponent(Z);
157     VERIFY((primeSize % 5) == 0);
158     primeSize /= 5;
159     for(i = 0; i < 5; i++)
160         VERIFY(BnFromBytes(bn[i], &b->t.buffer[primeSize * i], primeSize)
161                 != NULL);
162     MakePgreaterThanQ(Z);
163     return TRUE;
164 Error:
165     return FALSE;
166  }
167 
168 //*** ComputePrivateExponent()
169 // This function computes the private exponent from the primes.
170 //  Return Type: BOOL
171 //      TRUE(1)         success
172 //      FALSE(0)        failure
173 static BOOL
ComputePrivateExponent(bigNum pubExp,privateExponent * Z)174 ComputePrivateExponent(
175     bigNum               pubExp,        // IN: the public exponent
176     privateExponent     *Z              // IN/OUT: on input, has primes P and Q. On
177                                         //         output, has P, Q, dP, dQ, and pInv
178     )
179 {
180     BOOL                pOK;
181     BOOL                qOK;
182     BN_PRIME(pT);
183 //
184     // make p the larger value so that m2 is always less than p
185     MakePgreaterThanQ(Z);
186 
187     //dP = (1/e) mod (p-1)
188     pOK = BnSubWord(pT, Z->P, 1);
189     pOK = pOK && BnModInverse(Z->dP, pubExp, pT);
190     //dQ = (1/e) mod (q-1)
191     qOK = BnSubWord(pT, Z->Q, 1);
192     qOK = qOK && BnModInverse(Z->dQ, pubExp, pT);
193     // qInv = (1/q) mod p
194     if(pOK && qOK)
195         pOK = qOK = BnModInverse(Z->qInv, Z->Q, Z->P);
196     if(!pOK)
197         BnSetWord(Z->P, 0);
198     if(!qOK)
199         BnSetWord(Z->Q, 0);
200     return pOK && qOK;
201 }
202 
203 //*** RsaPrivateKeyOp()
204 // This function is called to do the exponentiation with the private key. Compile
205 // options allow use of the simple (but slow) private exponent, or the more complex
206 // but faster CRT method.
207 //  Return Type: BOOL
208 //      TRUE(1)         success
209 //      FALSE(0)        failure
210 static BOOL
RsaPrivateKeyOp(bigNum inOut,privateExponent * Z)211 RsaPrivateKeyOp(
212     bigNum               inOut, // IN/OUT: number to be exponentiated
213     privateExponent     *Z
214     )
215 {
216     BN_RSA(M1);
217     BN_RSA(M2);
218     BN_RSA(M);
219     BN_RSA(H);
220 //
221     MakePgreaterThanQ(Z);
222     // m1 = cdP mod p
223     VERIFY(BnModExp(M1, inOut, Z->dP, Z->P));
224     // m2 = cdQ mod q
225     VERIFY(BnModExp(M2, inOut, Z->dQ, Z->Q));
226     // h = qInv * (m1 - m2) mod p = qInv * (m1 + P - m2) mod P because Q < P
227     // so m2 < P
228     VERIFY(BnSub(H, Z->P, M2));
229     VERIFY(BnAdd(H, H, M1));
230     VERIFY(BnModMult(H, H, Z->qInv, Z->P));
231     // m = m2 + h * q
232     VERIFY(BnMult(M, H, Z->Q));
233     VERIFY(BnAdd(inOut, M2, M));
234     return TRUE;
235 Error:
236     return FALSE;
237 }
238 
239 //*** RSAEP()
240 // This function performs the RSAEP operation defined in PKCS#1v2.1. It is
241 // an exponentiation of a value ('m') with the public exponent ('e'), modulo
242 // the public ('n').
243 //
244 //  Return Type: TPM_RC
245 //      TPM_RC_VALUE     number to exponentiate is larger than the modulus
246 //
247 static TPM_RC
RSAEP(TPM2B * dInOut,OBJECT * key)248 RSAEP(
249     TPM2B       *dInOut,        // IN: size of the encrypted block and the size of
250                                 //     the encrypted value. It must be the size of
251                                 //     the modulus.
252                                 // OUT: the encrypted data. Will receive the
253                                 //      decrypted value
254     OBJECT      *key            // IN: the key to use
255     )
256 {
257     TPM2B_TYPE(4BYTES, 4);
258     TPM2B_4BYTES        e2B;
259     UINT32              e = key->publicArea.parameters.rsaDetail.exponent;
260 //
261     if(e == 0)
262         e = RSA_DEFAULT_PUBLIC_EXPONENT;
263     UINT32_TO_BYTE_ARRAY(e, e2B.t.buffer);
264     e2B.t.size = 4;
265     return ModExpB(dInOut->size, dInOut->buffer, dInOut->size, dInOut->buffer,
266                    e2B.t.size, e2B.t.buffer, key->publicArea.unique.rsa.t.size,
267                    key->publicArea.unique.rsa.t.buffer);
268 }
269 
270 //*** RSADP()
271 // This function performs the RSADP operation defined in PKCS#1v2.1. It is
272 // an exponentiation of a value ('c') with the private exponent ('d'), modulo
273 // the public modulus ('n'). The decryption is in place.
274 //
275 // This function also checks the size of the private key. If the size indicates
276 // that only a prime value is present, the key is converted to being a private
277 // exponent.
278 //
279 //  Return Type: TPM_RC
280 //      TPM_RC_SIZE         the value to decrypt is larger than the modulus
281 //
282 static TPM_RC
RSADP(TPM2B * inOut,OBJECT * key)283 RSADP(
284     TPM2B           *inOut,        // IN/OUT: the value to encrypt
285     OBJECT          *key           // IN: the key
286     )
287 {
288     BN_RSA_INITIALIZED(bnM, inOut);
289     NEW_PRIVATE_EXPONENT(Z);
290     if(UnsignedCompareB(inOut->size, inOut->buffer,
291                      key->publicArea.unique.rsa.t.size,
292                      key->publicArea.unique.rsa.t.buffer) >= 0)
293         return TPM_RC_SIZE;
294     // private key operation requires that private exponent be loaded
295     // During self-test, this might not be the case so load it up if it hasn't
296     // already done
297     // been done
298     if((key->sensitive.sensitive.rsa.t.size & RSA_prime_flag) == 0)
299     {
300         if(CryptRsaLoadPrivateExponent(&key->publicArea, &key->sensitive)
301            != TPM_RC_SUCCESS)
302             return TPM_RC_BINDING;
303     }
304     VERIFY(UnpackExponent(&key->sensitive.sensitive.rsa, Z));
305     VERIFY(RsaPrivateKeyOp(bnM, Z));
306     VERIFY(BnTo2B(bnM, inOut, inOut->size));
307     return TPM_RC_SUCCESS;
308 Error:
309     return TPM_RC_FAILURE;
310 }
311 
312 //*** OaepEncode()
313 // This function performs OAEP padding. The size of the buffer to receive the
314 // OAEP padded data must equal the size of the modulus
315 //
316 //  Return Type: TPM_RC
317 //      TPM_RC_VALUE     'hashAlg' is not valid or message size is too large
318 //
319 static TPM_RC
OaepEncode(TPM2B * padded,TPM_ALG_ID hashAlg,const TPM2B * label,TPM2B * message,RAND_STATE * rand)320 OaepEncode(
321     TPM2B       *padded,        // OUT: the pad data
322     TPM_ALG_ID   hashAlg,       // IN: algorithm to use for padding
323     const TPM2B *label,         // IN: null-terminated string (may be NULL)
324     TPM2B       *message,       // IN: the message being padded
325     RAND_STATE  *rand           // IN: the random number generator to use
326     )
327 {
328     INT32        padLen;
329     INT32        dbSize;
330     INT32        i;
331     BYTE         mySeed[MAX_DIGEST_SIZE];
332     BYTE        *seed = mySeed;
333     UINT16       hLen = CryptHashGetDigestSize(hashAlg);
334     BYTE         mask[MAX_RSA_KEY_BYTES];
335     BYTE        *pp;
336     BYTE        *pm;
337     TPM_RC       retVal = TPM_RC_SUCCESS;
338 
339     pAssert(padded != NULL && message != NULL);
340 
341     // A value of zero is not allowed because the KDF can't produce a result
342     // if the digest size is zero.
343     if(hLen == 0)
344         return TPM_RC_VALUE;
345 
346     // Basic size checks
347     //  make sure digest isn't too big for key size
348     if(padded->size < (2 * hLen) + 2)
349         ERROR_RETURN(TPM_RC_HASH);
350 
351     // and that message will fit messageSize <= k - 2hLen - 2
352     if(message->size > (padded->size - (2 * hLen) - 2))
353         ERROR_RETURN(TPM_RC_VALUE);
354 
355     // Hash L even if it is null
356     // Offset into padded leaving room for masked seed and byte of zero
357     pp = &padded->buffer[hLen + 1];
358     if(CryptHashBlock(hashAlg, label->size, (BYTE *)label->buffer,
359                       hLen, pp) != hLen)
360         ERROR_RETURN(TPM_RC_FAILURE);
361 
362     // concatenate PS of k  mLen  2hLen  2
363     padLen = padded->size - message->size - (2 * hLen) - 2;
364     MemorySet(&pp[hLen], 0, padLen);
365     pp[hLen + padLen] = 0x01;
366     padLen += 1;
367     memcpy(&pp[hLen + padLen], message->buffer, message->size);
368 
369     // The total size of db = hLen + pad + mSize;
370     dbSize = hLen + padLen + message->size;
371 
372     // If testing, then use the provided seed. Otherwise, use values
373     // from the RNG
374     CryptRandomGenerate(hLen, mySeed);
375     DRBG_Generate(rand, mySeed, (UINT16)hLen);
376     if(g_inFailureMode)
377         ERROR_RETURN(TPM_RC_FAILURE);
378     // mask = MGF1 (seed, nSize  hLen  1)
379     CryptMGF_KDF(dbSize, mask, hashAlg, hLen, seed, 0);
380 
381     // Create the masked db
382     pm = mask;
383     for(i = dbSize; i > 0; i--)
384         *pp++ ^= *pm++;
385     pp = &padded->buffer[hLen + 1];
386 
387     // Run the masked data through MGF1
388     if(CryptMGF_KDF(hLen, &padded->buffer[1], hashAlg, dbSize, pp, 0) != (unsigned)hLen)
389         ERROR_RETURN(TPM_RC_VALUE);
390 // Now XOR the seed to create masked seed
391     pp = &padded->buffer[1];
392     pm = seed;
393     for(i = hLen; i > 0; i--)
394         *pp++ ^= *pm++;
395     // Set the first byte to zero
396     padded->buffer[0] = 0x00;
397 Exit:
398     return retVal;
399 }
400 
401 //*** OaepDecode()
402 // This function performs OAEP padding checking. The size of the buffer to receive
403 // the recovered data. If the padding is not valid, the 'dSize' size is set to zero
404 // and the function returns TPM_RC_VALUE.
405 //
406 // The 'dSize' parameter is used as an input to indicate the size available in the
407 // buffer.
408 
409 // If insufficient space is available, the size is not changed and the return code
410 // is TPM_RC_VALUE.
411 //
412 //  Return Type: TPM_RC
413 //      TPM_RC_VALUE        the value to decode was larger than the modulus, or
414 //                          the padding is wrong or the buffer to receive the
415 //                          results is too small
416 //
417 //
418 static TPM_RC
OaepDecode(TPM2B * dataOut,TPM_ALG_ID hashAlg,const TPM2B * label,TPM2B * padded)419 OaepDecode(
420     TPM2B           *dataOut,       // OUT: the recovered data
421     TPM_ALG_ID       hashAlg,       // IN: algorithm to use for padding
422     const TPM2B     *label,         // IN: null-terminated string (may be NULL)
423     TPM2B           *padded         // IN: the padded data
424     )
425 {
426     UINT32       i;
427     BYTE         seedMask[MAX_DIGEST_SIZE];
428     UINT32       hLen = CryptHashGetDigestSize(hashAlg);
429 
430     BYTE         mask[MAX_RSA_KEY_BYTES];
431     BYTE        *pp;
432     BYTE        *pm;
433     TPM_RC       retVal = TPM_RC_SUCCESS;
434 
435     // Strange size (anything smaller can't be an OAEP padded block)
436     // Also check for no leading 0
437     if((padded->size < (unsigned)((2 * hLen) + 2)) || (padded->buffer[0] != 0))
438         ERROR_RETURN(TPM_RC_VALUE);
439 // Use the hash size to determine what to put through MGF1 in order
440 // to recover the seedMask
441     CryptMGF_KDF(hLen, seedMask, hashAlg, padded->size - hLen - 1,
442               &padded->buffer[hLen + 1], 0);
443 
444     // Recover the seed into seedMask
445     pAssert(hLen <= sizeof(seedMask));
446     pp = &padded->buffer[1];
447     pm = seedMask;
448     for(i = hLen; i > 0; i--)
449         *pm++ ^= *pp++;
450 
451     // Use the seed to generate the data mask
452     CryptMGF_KDF(padded->size - hLen - 1, mask, hashAlg, hLen, seedMask, 0);
453 
454     // Use the mask generated from seed to recover the padded data
455     pp = &padded->buffer[hLen + 1];
456     pm = mask;
457     for(i = (padded->size - hLen - 1); i > 0; i--)
458         *pm++ ^= *pp++;
459 
460     // Make sure that the recovered data has the hash of the label
461     // Put trial value in the seed mask
462     if((CryptHashBlock(hashAlg, label->size, (BYTE *)label->buffer,
463                        hLen, seedMask)) != hLen)
464         FAIL(FATAL_ERROR_INTERNAL);
465     if(memcmp(seedMask, mask, hLen) != 0)
466         ERROR_RETURN(TPM_RC_VALUE);
467 
468     // find the start of the data
469     pm = &mask[hLen];
470     for(i = (UINT32)padded->size - (2 * hLen) - 1; i > 0; i--)
471     {
472         if(*pm++ != 0)
473             break;
474     }
475     // If we ran out of data or didn't end with 0x01, then return an error
476     if(i == 0 || pm[-1] != 0x01)
477         ERROR_RETURN(TPM_RC_VALUE);
478 
479     // pm should be pointing at the first part of the data
480     // and i is one greater than the number of bytes to move
481     i--;
482     if(i > dataOut->size)
483         // Special exit to preserve the size of the output buffer
484         return TPM_RC_VALUE;
485     memcpy(dataOut->buffer, pm, i);
486     dataOut->size = (UINT16)i;
487 Exit:
488     if(retVal != TPM_RC_SUCCESS)
489         dataOut->size = 0;
490     return retVal;
491 }
492 
493 //*** PKCS1v1_5Encode()
494 // This function performs the encoding for RSAES-PKCS1-V1_5-ENCRYPT as defined in
495 // PKCS#1V2.1
496 //  Return Type: TPM_RC
497 //      TPM_RC_VALUE     message size is too large
498 //
499 static TPM_RC
RSAES_PKCS1v1_5Encode(TPM2B * padded,TPM2B * message,RAND_STATE * rand)500 RSAES_PKCS1v1_5Encode(
501     TPM2B       *padded,        // OUT: the pad data
502     TPM2B       *message,       // IN: the message being padded
503     RAND_STATE  *rand
504     )
505 {
506     UINT32      ps = padded->size - message->size - 3;
507 //
508     if(message->size > padded->size - 11)
509         return TPM_RC_VALUE;
510     // move the message to the end of the buffer
511     memcpy(&padded->buffer[padded->size - message->size], message->buffer,
512            message->size);
513     // Set the first byte to 0x00 and the second to 0x02
514     padded->buffer[0] = 0;
515     padded->buffer[1] = 2;
516 
517     // Fill with random bytes
518     DRBG_Generate(rand, &padded->buffer[2], (UINT16)ps);
519     if(g_inFailureMode)
520         return TPM_RC_FAILURE;
521 
522     // Set the delimiter for the random field to 0
523     padded->buffer[2 + ps] = 0;
524 
525     // Now, the only messy part. Make sure that all the 'ps' bytes are non-zero
526     // In this implementation, use the value of the current index
527     for(ps++; ps > 1; ps--)
528     {
529         if(padded->buffer[ps] == 0)
530             padded->buffer[ps] = 0x55;  // In the < 0.5% of the cases that the
531                                         // random value is 0, just pick a value to
532                                         // put into the spot.
533     }
534     return TPM_RC_SUCCESS;
535 }
536 
537 //*** RSAES_Decode()
538 // This function performs the decoding for RSAES-PKCS1-V1_5-ENCRYPT as defined in
539 // PKCS#1V2.1
540 //
541 //  Return Type: TPM_RC
542 //      TPM_RC_FAIL      decoding error or results would no fit into provided buffer
543 //
544 static TPM_RC
RSAES_Decode(TPM2B * message,TPM2B * coded)545 RSAES_Decode(
546     TPM2B       *message,       // OUT: the recovered message
547     TPM2B       *coded          // IN: the encoded message
548     )
549 {
550     BOOL        fail = FALSE;
551     UINT16      pSize;
552 
553     fail = (coded->size < 11);
554     fail = (coded->buffer[0] != 0x00) | fail;
555     fail = (coded->buffer[1] != 0x02) | fail;
556     for(pSize = 2; pSize < coded->size; pSize++)
557     {
558         if(coded->buffer[pSize] == 0)
559             break;
560     }
561     pSize++;
562 
563     // Make sure that pSize has not gone over the end and that there are at least 8
564     // bytes of pad data.
565     fail = (pSize > coded->size) | fail;
566     fail = ((pSize - 2) <= 8) | fail;
567     if((message->size < (UINT16)(coded->size - pSize)) || fail)
568         return TPM_RC_VALUE;
569     message->size = coded->size - pSize;
570     memcpy(message->buffer, &coded->buffer[pSize], coded->size - pSize);
571     return TPM_RC_SUCCESS;
572 }
573 
574 //*** CryptRsaPssSaltSize()
575 // This function computes the salt size used in PSS. It is broken out so that
576 // the X509 code can get the same value that is used by the encoding function in this
577 // module.
578 INT16
CryptRsaPssSaltSize(INT16 hashSize,INT16 outSize)579 CryptRsaPssSaltSize(
580     INT16              hashSize,
581     INT16               outSize
582 )
583 {
584     INT16               saltSize;
585 //
586     // (Mask Length) = (outSize - hashSize - 1);
587     // Max saltSize is (Mask Length) - 1
588     saltSize = (outSize - hashSize - 1) - 1;
589     // Use the maximum salt size allowed by FIPS 186-4
590     if(saltSize > hashSize)
591         saltSize = hashSize;
592     else if(saltSize < 0)
593         saltSize = 0;
594     return saltSize;
595 }
596 
597 //*** PssEncode()
598 // This function creates an encoded block of data that is the size of modulus.
599 // The function uses the maximum salt size that will fit in the encoded block.
600 //
601 //  Returns TPM_RC_SUCCESS or goes into failure mode.
602 static TPM_RC
PssEncode(TPM2B * out,TPM_ALG_ID hashAlg,TPM2B * digest,RAND_STATE * rand)603 PssEncode(
604     TPM2B           *out,       // OUT: the encoded buffer
605     TPM_ALG_ID       hashAlg,   // IN: hash algorithm for the encoding
606     TPM2B           *digest,    // IN: the digest
607     RAND_STATE      *rand       // IN: random number source
608     )
609 {
610     UINT32               hLen = CryptHashGetDigestSize(hashAlg);
611     BYTE                 salt[MAX_RSA_KEY_BYTES - 1];
612     UINT16               saltSize;
613     BYTE                *ps = salt;
614     BYTE                *pOut;
615     UINT16               mLen;
616     HASH_STATE           hashState;
617 
618     // These are fatal errors indicating bad TPM firmware
619     pAssert(out != NULL && hLen > 0 && digest != NULL);
620 
621     // Get the size of the mask
622     mLen = (UINT16)(out->size - hLen - 1);
623 
624     // Set the salt size
625     saltSize = CryptRsaPssSaltSize((INT16)hLen, (INT16)out->size);
626 
627 //using eOut for scratch space
628     // Set the first 8 bytes to zero
629     pOut = out->buffer;
630     memset(pOut, 0, 8);
631 
632     // Get set the salt
633     DRBG_Generate(rand, salt, saltSize);
634     if(g_inFailureMode)
635         return TPM_RC_FAILURE;
636 
637     // Create the hash of the pad || input hash || salt
638     CryptHashStart(&hashState, hashAlg);
639     CryptDigestUpdate(&hashState, 8, pOut);
640     CryptDigestUpdate2B(&hashState, digest);
641     CryptDigestUpdate(&hashState, saltSize, salt);
642     CryptHashEnd(&hashState, hLen, &pOut[out->size - hLen - 1]);
643 
644     // Create a mask
645     if(CryptMGF_KDF(mLen, pOut, hashAlg, hLen, &pOut[mLen], 0) != mLen)
646         FAIL(FATAL_ERROR_INTERNAL);
647 
648     // Since this implementation uses key sizes that are all even multiples of
649     // 8, just need to make sure that the most significant bit is CLEAR
650     *pOut &= 0x7f;
651 
652     // Before we mess up the pOut value, set the last byte to 0xbc
653     pOut[out->size - 1] = 0xbc;
654 
655     // XOR a byte of 0x01 at the position just before where the salt will be XOR'ed
656     pOut = &pOut[mLen - saltSize - 1];
657     *pOut++ ^= 0x01;
658 
659     // XOR the salt data into the buffer
660     for(; saltSize > 0; saltSize--)
661         *pOut++ ^= *ps++;
662 
663     // and we are done
664     return TPM_RC_SUCCESS;
665 }
666 
667 //*** PssDecode()
668 // This function checks that the PSS encoded block was built from the
669 // provided digest. If the check is successful, TPM_RC_SUCCESS is returned.
670 // Any other value indicates an error.
671 //
672 // This implementation of PSS decoding is intended for the reference TPM
673 // implementation and is not at all generalized.  It is used to check
674 // signatures over hashes and assumptions are made about the sizes of values.
675 // Those assumptions are enforce by this implementation.
676 // This implementation does allow for a variable size salt value to have been
677 // used by the creator of the signature.
678 //
679 //  Return Type: TPM_RC
680 //      TPM_RC_SCHEME       'hashAlg' is not a supported hash algorithm
681 //      TPM_RC_VALUE         decode operation failed
682 //
683 static TPM_RC
PssDecode(TPM_ALG_ID hashAlg,TPM2B * dIn,TPM2B * eIn)684 PssDecode(
685     TPM_ALG_ID   hashAlg,        // IN: hash algorithm to use for the encoding
686     TPM2B       *dIn,            // In: the digest to compare
687     TPM2B       *eIn             // IN: the encoded data
688     )
689 {
690     UINT32           hLen = CryptHashGetDigestSize(hashAlg);
691     BYTE             mask[MAX_RSA_KEY_BYTES];
692     BYTE            *pm = mask;
693     BYTE            *pe;
694     BYTE             pad[8] = {0};
695     UINT32           i;
696     UINT32           mLen;
697     BYTE             fail;
698     TPM_RC           retVal = TPM_RC_SUCCESS;
699     HASH_STATE       hashState;
700 
701     // These errors are indicative of failures due to programmer error
702     pAssert(dIn != NULL && eIn != NULL);
703     pe = eIn->buffer;
704 
705     // check the hash scheme
706     if(hLen == 0)
707         ERROR_RETURN(TPM_RC_SCHEME);
708 
709     // most significant bit must be zero
710     fail = pe[0] & 0x80;
711 
712     // last byte must be 0xbc
713     fail |= pe[eIn->size - 1] ^ 0xbc;
714 
715     // Use the hLen bytes at the end of the buffer to generate a mask
716     // Doesn't start at the end which is a flag byte
717     mLen = eIn->size - hLen - 1;
718     CryptMGF_KDF(mLen, mask, hashAlg, hLen, &pe[mLen], 0);
719 
720     // Clear the MSO of the mask to make it consistent with the encoding.
721     mask[0] &= 0x7F;
722 
723     pAssert(mLen <= sizeof(mask));
724     // XOR the data into the mask to recover the salt. This sequence
725     // advances eIn so that it will end up pointing to the seed data
726     // which is the hash of the signature data
727     for(i = mLen; i > 0; i--)
728         *pm++ ^= *pe++;
729 
730     // Find the first byte of 0x01 after a string of all 0x00
731     for(pm = mask, i = mLen; i > 0; i--)
732     {
733         if(*pm == 0x01)
734             break;
735         else
736             fail |= *pm++;
737     }
738     // i should not be zero
739     fail |= (i == 0);
740 
741     // if we have failed, will continue using the entire mask as the salt value so
742     // that the timing attacks will not disclose anything (I don't think that this
743     // is a problem for TPM applications but, usually, we don't fail so this
744     // doesn't cost anything).
745     if(fail)
746     {
747         i = mLen;
748         pm = mask;
749     }
750     else
751     {
752         pm++;
753         i--;
754     }
755     // i contains the salt size and pm points to the salt. Going to use the input
756     // hash and the seed to recreate the hash in the lower portion of eIn.
757     CryptHashStart(&hashState, hashAlg);
758 
759     // add the pad of 8 zeros
760     CryptDigestUpdate(&hashState, 8, pad);
761 
762     // add the provided digest value
763     CryptDigestUpdate(&hashState, dIn->size, dIn->buffer);
764 
765     // and the salt
766     CryptDigestUpdate(&hashState, i, pm);
767 
768     // get the result
769     fail |= (CryptHashEnd(&hashState, hLen, mask) != hLen);
770 
771     // Compare all bytes
772     for(pm = mask; hLen > 0; hLen--)
773         // don't use fail = because that could skip the increment and compare
774         // operations after the first failure and that gives away timing
775         // information.
776         fail |= *pm++ ^ *pe++;
777 
778     retVal = (fail != 0) ? TPM_RC_VALUE : TPM_RC_SUCCESS;
779 Exit:
780         return retVal;
781 }
782 
783 //*** MakeDerTag()
784 // Construct the DER value that is used in RSASSA
785 //  Return Type: INT16
786 //   > 0        size of value
787 //   <= 0       no hash exists
788 INT16
MakeDerTag(TPM_ALG_ID hashAlg,INT16 sizeOfBuffer,BYTE * buffer)789 MakeDerTag(
790     TPM_ALG_ID   hashAlg,
791     INT16        sizeOfBuffer,
792     BYTE        *buffer
793 )
794 {
795 //    0x30, 0x31,       // SEQUENCE (2 elements) 1st
796 //        0x30, 0x0D,   // SEQUENCE (2 elements)
797 //            0x06, 0x09,   // HASH OID
798 //                0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
799 //             0x05, 0x00,  // NULL
800 //        0x04, 0x20  //  OCTET STRING
801     HASH_DEF   *info = CryptGetHashDef(hashAlg);
802     INT16       oidSize;
803     // If no OID, can't do encode
804     VERIFY(info != NULL);
805     oidSize = 2 + (info->OID)[1];
806     // make sure this fits in the buffer
807     VERIFY(sizeOfBuffer >= (oidSize + 8));
808     *buffer++ = 0x30;  // 1st SEQUENCE
809     // Size of the 1st SEQUENCE is 6 bytes + size of the hash OID + size of the
810     // digest size
811     *buffer++ = (BYTE)(6 + oidSize + info->digestSize);   //
812     *buffer++ = 0x30; // 2nd SEQUENCE
813     // size is 4 bytes of overhead plus the side of the OID
814     *buffer++ = (BYTE)(2 + oidSize);
815     MemoryCopy(buffer, info->OID, oidSize);
816     buffer += oidSize;
817     *buffer++ = 0x05;   // Add a NULL
818     *buffer++ = 0x00;
819 
820     *buffer++ = 0x04;
821     *buffer++ = (BYTE)(info->digestSize);
822     return oidSize + 8;
823 Error:
824     return 0;
825 
826 }
827 
828 //*** RSASSA_Encode()
829 // Encode a message using PKCS1v1.5 method.
830 //
831 //  Return Type: TPM_RC
832 //      TPM_RC_SCHEME       'hashAlg' is not a supported hash algorithm
833 //      TPM_RC_SIZE         'eOutSize' is not large enough
834 //      TPM_RC_VALUE        'hInSize' does not match the digest size of hashAlg
835 static TPM_RC
RSASSA_Encode(TPM2B * pOut,TPM_ALG_ID hashAlg,TPM2B * hIn)836 RSASSA_Encode(
837     TPM2B               *pOut,      // IN:OUT on in, the size of the public key
838                                     //        on out, the encoded area
839     TPM_ALG_ID           hashAlg,   // IN: hash algorithm for PKCS1v1_5
840     TPM2B               *hIn        // IN: digest value to encode
841     )
842 {
843     BYTE             DER[20];
844     BYTE            *der = DER;
845     INT32            derSize = MakeDerTag(hashAlg, sizeof(DER), DER);
846     BYTE            *eOut;
847     INT32            fillSize;
848     TPM_RC           retVal = TPM_RC_SUCCESS;
849 
850     // Can't use this scheme if the algorithm doesn't have a DER string defined.
851     if(derSize == 0)
852         ERROR_RETURN(TPM_RC_SCHEME);
853 
854     // If the digest size of 'hashAl' doesn't match the input digest size, then
855     // the DER will misidentify the digest so return an error
856     if(CryptHashGetDigestSize(hashAlg) != hIn->size)
857         ERROR_RETURN(TPM_RC_VALUE);
858     fillSize = pOut->size - derSize - hIn->size - 3;
859     eOut = pOut->buffer;
860 
861     // Make sure that this combination will fit in the provided space
862     if(fillSize < 8)
863         ERROR_RETURN(TPM_RC_SIZE);
864 
865     // Start filling
866     *eOut++ = 0; // initial byte of zero
867     *eOut++ = 1; // byte of 0x01
868     for(; fillSize > 0; fillSize--)
869         *eOut++ = 0xff; // bunch of 0xff
870     *eOut++ = 0; // another 0
871     for(; derSize > 0; derSize--)
872         *eOut++ = *der++;   // copy the DER
873     der = hIn->buffer;
874     for(fillSize = hIn->size; fillSize > 0; fillSize--)
875         *eOut++ = *der++;   // copy the hash
876 Exit:
877     return retVal;
878 }
879 
880 //*** RSASSA_Decode()
881 // This function performs the RSASSA decoding of a signature.
882 //
883 //  Return Type: TPM_RC
884 //      TPM_RC_VALUE          decode unsuccessful
885 //      TPM_RC_SCHEME        'haslAlg' is not supported
886 //
887 static TPM_RC
RSASSA_Decode(TPM_ALG_ID hashAlg,TPM2B * hIn,TPM2B * eIn)888 RSASSA_Decode(
889     TPM_ALG_ID       hashAlg,        // IN: hash algorithm to use for the encoding
890     TPM2B           *hIn,            // In: the digest to compare
891     TPM2B           *eIn             // IN: the encoded data
892     )
893 {
894     BYTE             fail;
895     BYTE             DER[20];
896     BYTE            *der = DER;
897     INT32            derSize = MakeDerTag(hashAlg, sizeof(DER), DER);
898     BYTE            *pe;
899     INT32            hashSize = CryptHashGetDigestSize(hashAlg);
900     INT32            fillSize;
901     TPM_RC           retVal;
902     BYTE            *digest;
903     UINT16           digestSize;
904 
905     pAssert(hIn != NULL && eIn != NULL);
906     pe = eIn->buffer;
907 
908     // Can't use this scheme if the algorithm doesn't have a DER string
909     // defined or if the provided hash isn't the right size
910     if(derSize == 0 || (unsigned)hashSize != hIn->size)
911         ERROR_RETURN(TPM_RC_SCHEME);
912 
913     // Make sure that this combination will fit in the provided space
914     // Since no data movement takes place, can just walk though this
915     // and accept nearly random values. This can only be called from
916     // CryptValidateSignature() so eInSize is known to be in range.
917     fillSize = eIn->size - derSize - hashSize - 3;
918 
919     // Start checking (fail will become non-zero if any of the bytes do not have
920     // the expected value.
921     fail = *pe++;                   // initial byte of zero
922     fail |= *pe++ ^ 1;              // byte of 0x01
923     for(; fillSize > 0; fillSize--)
924         fail |= *pe++ ^ 0xff;       // bunch of 0xff
925     fail |= *pe++;                  // another 0
926     for(; derSize > 0; derSize--)
927         fail |= *pe++ ^ *der++;    // match the DER
928     digestSize = hIn->size;
929     digest = hIn->buffer;
930     for(; digestSize > 0; digestSize--)
931         fail |= *pe++ ^ *digest++; // match the hash
932     retVal = (fail != 0) ? TPM_RC_VALUE : TPM_RC_SUCCESS;
933 Exit:
934     return retVal;
935 }
936 
937 //** Externally Accessible Functions
938 
939 //*** CryptRsaSelectScheme()
940 // This function is used by TPM2_RSA_Decrypt and TPM2_RSA_Encrypt.  It sets up
941 // the rules to select a scheme between input and object default.
942 // This function assume the RSA object is loaded.
943 // If a default scheme is defined in object, the default scheme should be chosen,
944 // otherwise, the input scheme should be chosen.
945 // In the case that both the object and 'scheme' are not TPM_ALG_NULL, then
946 // if the schemes are the same, the input scheme will be chosen.
947 // if the scheme are not compatible, a NULL pointer will be returned.
948 //
949 // The return pointer may point to a TPM_ALG_NULL scheme.
950 TPMT_RSA_DECRYPT*
CryptRsaSelectScheme(TPMI_DH_OBJECT rsaHandle,TPMT_RSA_DECRYPT * scheme)951 CryptRsaSelectScheme(
952     TPMI_DH_OBJECT       rsaHandle,     // IN: handle of an RSA key
953     TPMT_RSA_DECRYPT    *scheme         // IN: a sign or decrypt scheme
954     )
955 {
956     OBJECT              *rsaObject;
957     TPMT_ASYM_SCHEME    *keyScheme;
958     TPMT_RSA_DECRYPT    *retVal = NULL;
959 
960     // Get sign object pointer
961     rsaObject = HandleToObject(rsaHandle);
962     keyScheme = &rsaObject->publicArea.parameters.asymDetail.scheme;
963 
964     // if the default scheme of the object is TPM_ALG_NULL, then select the
965     // input scheme
966     if(keyScheme->scheme == TPM_ALG_NULL)
967     {
968         retVal = scheme;
969     }
970     // if the object scheme is not TPM_ALG_NULL and the input scheme is
971     // TPM_ALG_NULL, then select the default scheme of the object.
972     else if(scheme->scheme == TPM_ALG_NULL)
973     {
974         // if input scheme is NULL
975         retVal = (TPMT_RSA_DECRYPT *)keyScheme;
976     }
977     // get here if both the object scheme and the input scheme are
978     // not TPM_ALG_NULL. Need to insure that they are the same.
979     // IMPLEMENTATION NOTE: This could cause problems if future versions have
980     // schemes that have more values than just a hash algorithm. A new function
981     // (IsSchemeSame()) might be needed then.
982     else if(keyScheme->scheme == scheme->scheme
983             && keyScheme->details.anySig.hashAlg == scheme->details.anySig.hashAlg)
984     {
985         retVal = scheme;
986     }
987     // two different, incompatible schemes specified will return NULL
988     return retVal;
989 }
990 
991 //*** CryptRsaLoadPrivateExponent()
992 // This function is called to generate the private exponent of an RSA key.
993 //  Return Type: TPM_RC
994 //      TPM_RC_BINDING      public and private parts of 'rsaKey' are not matched
995 TPM_RC
CryptRsaLoadPrivateExponent(TPMT_PUBLIC * publicArea,TPMT_SENSITIVE * sensitive)996 CryptRsaLoadPrivateExponent(
997     TPMT_PUBLIC             *publicArea,
998     TPMT_SENSITIVE          *sensitive
999     )
1000 {
1001 //
1002     if((sensitive->sensitive.rsa.t.size & RSA_prime_flag) == 0)
1003     {
1004         if((sensitive->sensitive.rsa.t.size * 2) == publicArea->unique.rsa.t.size)
1005         {
1006             NEW_PRIVATE_EXPONENT(Z);
1007             BN_RSA_INITIALIZED(bnN, &publicArea->unique.rsa);
1008             BN_RSA(bnQr);
1009             BN_VAR(bnE, RADIX_BITS);
1010 
1011             TEST(TPM_ALG_NULL);
1012 
1013             VERIFY((sensitive->sensitive.rsa.t.size * 2)
1014                    == publicArea->unique.rsa.t.size);
1015             // Initialize the exponent
1016             BnSetWord(bnE, publicArea->parameters.rsaDetail.exponent);
1017             if(BnEqualZero(bnE))
1018                 BnSetWord(bnE, RSA_DEFAULT_PUBLIC_EXPONENT);
1019             // Convert first prime to 2B
1020             VERIFY(BnFrom2B(Z->P, &sensitive->sensitive.rsa.b) != NULL);
1021 
1022             // Find the second prime by division. This uses 'bQ' rather than Z->Q
1023             // because the division could make the quotient larger than a prime during
1024             // some intermediate step.
1025             VERIFY(BnDiv(Z->Q, bnQr, bnN, Z->P));
1026             VERIFY(BnEqualZero(bnQr));
1027             // Compute the private exponent and return it if found
1028             VERIFY(ComputePrivateExponent(bnE, Z));
1029             VERIFY(PackExponent(&sensitive->sensitive.rsa, Z));
1030         }
1031         else
1032             VERIFY(((sensitive->sensitive.rsa.t.size / 5) * 2)
1033                    == publicArea->unique.rsa.t.size);
1034         sensitive->sensitive.rsa.t.size |= RSA_prime_flag;
1035     }
1036     return TPM_RC_SUCCESS;
1037 Error:
1038     return TPM_RC_BINDING;
1039 }
1040 
1041 //*** CryptRsaEncrypt()
1042 // This is the entry point for encryption using RSA. Encryption is
1043 // use of the public exponent. The padding parameter determines what
1044 // padding will be used.
1045 //
1046 // The 'cOutSize' parameter must be at least as large as the size of the key.
1047 //
1048 // If the padding is RSA_PAD_NONE, 'dIn' is treated as a number. It must be
1049 // lower in value than the key modulus.
1050 // NOTE: If dIn has fewer bytes than cOut, then we don't add low-order zeros to
1051 //       dIn to make it the size of the RSA key for the call to RSAEP. This is
1052 //       because the high order bytes of dIn might have a numeric value that is
1053 //       greater than the value of the key modulus. If this had low-order zeros
1054 //       added, it would have a numeric value larger than the modulus even though
1055 //       it started out with a lower numeric value.
1056 //
1057 //  Return Type: TPM_RC
1058 //      TPM_RC_VALUE     'cOutSize' is too small (must be the size
1059 //                        of the modulus)
1060 //      TPM_RC_SCHEME    'padType' is not a supported scheme
1061 //
1062 LIB_EXPORT TPM_RC
CryptRsaEncrypt(TPM2B_PUBLIC_KEY_RSA * cOut,TPM2B * dIn,OBJECT * key,TPMT_RSA_DECRYPT * scheme,const TPM2B * label,RAND_STATE * rand)1063 CryptRsaEncrypt(
1064     TPM2B_PUBLIC_KEY_RSA        *cOut,          // OUT: the encrypted data
1065     TPM2B                       *dIn,           // IN: the data to encrypt
1066     OBJECT                      *key,           // IN: the key used for encryption
1067     TPMT_RSA_DECRYPT            *scheme,        // IN: the type of padding and hash
1068                                                 //     if needed
1069     const TPM2B                 *label,         // IN: in case it is needed
1070     RAND_STATE                  *rand           // IN: random number generator
1071                                                 //     state (mostly for testing)
1072     )
1073 {
1074     TPM_RC                       retVal = TPM_RC_SUCCESS;
1075     TPM2B_PUBLIC_KEY_RSA         dataIn;
1076 //
1077     // if the input and output buffers are the same, copy the input to a scratch
1078     // buffer so that things don't get messed up.
1079     if(dIn == &cOut->b)
1080     {
1081         MemoryCopy2B(&dataIn.b, dIn, sizeof(dataIn.t.buffer));
1082         dIn = &dataIn.b;
1083     }
1084     // All encryption schemes return the same size of data
1085     cOut->t.size = key->publicArea.unique.rsa.t.size;
1086     TEST(scheme->scheme);
1087 
1088     switch(scheme->scheme)
1089     {
1090         case TPM_ALG_NULL:  // 'raw' encryption
1091         {
1092             INT32            i;
1093             INT32            dSize = dIn->size;
1094             // dIn can have more bytes than cOut as long as the extra bytes
1095             // are zero. Note: the more significant bytes of a number in a byte
1096             // buffer are the bytes at the start of the array.
1097             for(i = 0; (i < dSize) && (dIn->buffer[i] == 0); i++);
1098             dSize -= i;
1099             if(dSize > cOut->t.size)
1100                 ERROR_RETURN(TPM_RC_VALUE);
1101             // Pad cOut with zeros if dIn is smaller
1102             memset(cOut->t.buffer, 0, cOut->t.size - dSize);
1103             // And copy the rest of the value
1104             memcpy(&cOut->t.buffer[cOut->t.size - dSize], &dIn->buffer[i], dSize);
1105 
1106             // If the size of dIn is the same as cOut dIn could be larger than
1107             // the modulus. If it is, then RSAEP() will catch it.
1108         }
1109         break;
1110         case TPM_ALG_RSAES:
1111             retVal = RSAES_PKCS1v1_5Encode(&cOut->b, dIn, rand);
1112             break;
1113         case TPM_ALG_OAEP:
1114             retVal = OaepEncode(&cOut->b, scheme->details.oaep.hashAlg, label, dIn,
1115                                 rand);
1116             break;
1117         default:
1118             ERROR_RETURN(TPM_RC_SCHEME);
1119             break;
1120     }
1121     // All the schemes that do padding will come here for the encryption step
1122     // Check that the Encoding worked
1123     if(retVal == TPM_RC_SUCCESS)
1124         // Padding OK so do the encryption
1125         retVal = RSAEP(&cOut->b, key);
1126 Exit:
1127     return retVal;
1128 }
1129 
1130 //*** CryptRsaDecrypt()
1131 // This is the entry point for decryption using RSA. Decryption is
1132 // use of the private exponent. The 'padType' parameter determines what
1133 // padding was used.
1134 //
1135 //  Return Type: TPM_RC
1136 //      TPM_RC_SIZE        'cInSize' is not the same as the size of the public
1137 //                          modulus of 'key'; or numeric value of the encrypted
1138 //                          data is greater than the modulus
1139 //      TPM_RC_VALUE       'dOutSize' is not large enough for the result
1140 //      TPM_RC_SCHEME      'padType' is not supported
1141 //
1142 LIB_EXPORT TPM_RC
CryptRsaDecrypt(TPM2B * dOut,TPM2B * cIn,OBJECT * key,TPMT_RSA_DECRYPT * scheme,const TPM2B * label)1143 CryptRsaDecrypt(
1144     TPM2B               *dOut,          // OUT: the decrypted data
1145     TPM2B               *cIn,           // IN: the data to decrypt
1146     OBJECT              *key,           // IN: the key to use for decryption
1147     TPMT_RSA_DECRYPT    *scheme,        // IN: the padding scheme
1148     const TPM2B         *label          // IN: in case it is needed for the scheme
1149     )
1150 {
1151     TPM_RC                 retVal;
1152 
1153     // Make sure that the necessary parameters are provided
1154     pAssert(cIn != NULL && dOut != NULL && key != NULL);
1155 
1156     // Size is checked to make sure that the encrypted value is the right size
1157     if(cIn->size != key->publicArea.unique.rsa.t.size)
1158         ERROR_RETURN(TPM_RC_SIZE);
1159 
1160     TEST(scheme->scheme);
1161 
1162     // For others that do padding, do the decryption in place and then
1163     // go handle the decoding.
1164     retVal = RSADP(cIn, key);
1165     if(retVal == TPM_RC_SUCCESS)
1166     {
1167         // Remove padding
1168         switch(scheme->scheme)
1169         {
1170             case TPM_ALG_NULL:
1171                 if(dOut->size < cIn->size)
1172                     return TPM_RC_VALUE;
1173                 MemoryCopy2B(dOut, cIn, dOut->size);
1174                 break;
1175             case TPM_ALG_RSAES:
1176                 retVal = RSAES_Decode(dOut, cIn);
1177                 break;
1178             case TPM_ALG_OAEP:
1179                 retVal = OaepDecode(dOut, scheme->details.oaep.hashAlg, label, cIn);
1180                 break;
1181             default:
1182                 retVal = TPM_RC_SCHEME;
1183                 break;
1184         }
1185     }
1186 Exit:
1187     return retVal;
1188 }
1189 
1190 //*** CryptRsaSign()
1191 // This function is used to generate an RSA signature of the type indicated in
1192 // 'scheme'.
1193 //
1194 //  Return Type: TPM_RC
1195 //      TPM_RC_SCHEME       'scheme' or 'hashAlg' are not supported
1196 //      TPM_RC_VALUE        'hInSize' does not match 'hashAlg' (for RSASSA)
1197 //
1198 LIB_EXPORT TPM_RC
CryptRsaSign(TPMT_SIGNATURE * sigOut,OBJECT * key,TPM2B_DIGEST * hIn,RAND_STATE * rand)1199 CryptRsaSign(
1200     TPMT_SIGNATURE      *sigOut,
1201     OBJECT              *key,           // IN: key to use
1202     TPM2B_DIGEST        *hIn,           // IN: the digest to sign
1203     RAND_STATE          *rand           // IN: the random number generator
1204                                         //      to use (mostly for testing)
1205     )
1206 {
1207     TPM_RC                retVal = TPM_RC_SUCCESS;
1208     UINT16                modSize;
1209 
1210     // parameter checks
1211     pAssert(sigOut != NULL && key != NULL && hIn != NULL);
1212 
1213     modSize = key->publicArea.unique.rsa.t.size;
1214 
1215     // for all non-null signatures, the size is the size of the key modulus
1216     sigOut->signature.rsapss.sig.t.size = modSize;
1217 
1218     TEST(sigOut->sigAlg);
1219 
1220     switch(sigOut->sigAlg)
1221     {
1222         case TPM_ALG_NULL:
1223             sigOut->signature.rsapss.sig.t.size = 0;
1224             return TPM_RC_SUCCESS;
1225         case TPM_ALG_RSAPSS:
1226             retVal = PssEncode(&sigOut->signature.rsapss.sig.b,
1227                                sigOut->signature.rsapss.hash, &hIn->b, rand);
1228             break;
1229         case TPM_ALG_RSASSA:
1230             retVal = RSASSA_Encode(&sigOut->signature.rsassa.sig.b,
1231                                    sigOut->signature.rsassa.hash, &hIn->b);
1232             break;
1233         default:
1234             retVal = TPM_RC_SCHEME;
1235     }
1236     if(retVal == TPM_RC_SUCCESS)
1237     {
1238         // Do the encryption using the private key
1239         retVal = RSADP(&sigOut->signature.rsapss.sig.b, key);
1240     }
1241     return retVal;
1242 }
1243 
1244 //*** CryptRsaValidateSignature()
1245 // This function is used to validate an RSA signature. If the signature is valid
1246 // TPM_RC_SUCCESS is returned. If the signature is not valid, TPM_RC_SIGNATURE is
1247 // returned. Other return codes indicate either parameter problems or fatal errors.
1248 //
1249 //  Return Type: TPM_RC
1250 //      TPM_RC_SIGNATURE    the signature does not check
1251 //      TPM_RC_SCHEME       unsupported scheme or hash algorithm
1252 //
1253 LIB_EXPORT TPM_RC
CryptRsaValidateSignature(TPMT_SIGNATURE * sig,OBJECT * key,TPM2B_DIGEST * digest)1254 CryptRsaValidateSignature(
1255     TPMT_SIGNATURE  *sig,           // IN: signature
1256     OBJECT          *key,           // IN: public modulus
1257     TPM2B_DIGEST    *digest         // IN: The digest being validated
1258     )
1259 {
1260     TPM_RC          retVal;
1261 //
1262     // Fatal programming errors
1263     pAssert(key != NULL && sig != NULL && digest != NULL);
1264     switch(sig->sigAlg)
1265     {
1266         case TPM_ALG_RSAPSS:
1267         case TPM_ALG_RSASSA:
1268             break;
1269         default:
1270             return TPM_RC_SCHEME;
1271     }
1272 
1273     // Errors that might be caused by calling parameters
1274     if(sig->signature.rsassa.sig.t.size != key->publicArea.unique.rsa.t.size)
1275         ERROR_RETURN(TPM_RC_SIGNATURE);
1276 
1277     TEST(sig->sigAlg);
1278 
1279     // Decrypt the block
1280     retVal = RSAEP(&sig->signature.rsassa.sig.b, key);
1281     if(retVal == TPM_RC_SUCCESS)
1282     {
1283         switch(sig->sigAlg)
1284         {
1285             case TPM_ALG_RSAPSS:
1286                 retVal = PssDecode(sig->signature.any.hashAlg, &digest->b,
1287                                    &sig->signature.rsassa.sig.b);
1288                 break;
1289             case TPM_ALG_RSASSA:
1290                 retVal = RSASSA_Decode(sig->signature.any.hashAlg, &digest->b,
1291                                        &sig->signature.rsassa.sig.b);
1292                 break;
1293             default:
1294                 return TPM_RC_SCHEME;
1295         }
1296     }
1297 Exit:
1298     return (retVal != TPM_RC_SUCCESS) ? TPM_RC_SIGNATURE : TPM_RC_SUCCESS;
1299 }
1300 
1301 #if SIMULATION && USE_RSA_KEY_CACHE
1302 extern int s_rsaKeyCacheEnabled;
1303 int GetCachedRsaKey(TPMT_PUBLIC *publicArea, TPMT_SENSITIVE *sensitive,
1304                     RAND_STATE *rand);
1305 #define GET_CACHED_KEY(publicArea, sensitive, rand)                       \
1306             (s_rsaKeyCacheEnabled && GetCachedRsaKey(publicArea, sensitive, rand))
1307 #else
1308 #define GET_CACHED_KEY(key, rand)
1309 #endif
1310 
1311 //*** CryptRsaGenerateKey()
1312 // Generate an RSA key from a provided seed
1313 /*(See part 1 specification)
1314 //  The formulation is:
1315 //      KDFa(hash, seed, label, Name, Counter, bits)
1316 //  Where:
1317 //      hash        the nameAlg from the public template
1318 //      seed        a seed (will be a primary seed for a primary key)
1319 //      label       a distinguishing label including vendor ID and
1320 //                  vendor-assigned part number for the TPM.
1321 //      Name        the nameAlg from the template and the hash of the template
1322 //                  using nameAlg.
1323 //      Counter     a 32-bit integer that is incremented each time the KDF is
1324 //                  called in order to produce a specific key. This value
1325 //                  can be a 32-bit integer in host format and does not need
1326 //                  to be put in canonical form.
1327 //      bits        the number of bits needed for the key.
1328 //  The following process is implemented to find a RSA key pair:
1329 //  1. pick a random number with enough bits from KDFa as a prime candidate
1330 //  2. set the first two significant bits and the least significant bit of the
1331 //     prime candidate
1332 //  3. check if the number is a prime. if not, pick another random number
1333 //  4. Make sure the difference between the two primes are more than 2^104.
1334 //     Otherwise, restart the process for the second prime
1335 //  5. If the counter has reached its maximum but we still can not find a valid
1336 //     RSA key pair, return an internal error. This is an artificial bound.
1337 //     Other implementation may choose a smaller number to indicate how many
1338 //     times they are willing to try.
1339 */
1340 //  Return Type: TPM_RC
1341 //      TPM_RC_CANCELED     operation was canceled
1342 //      TPM_RC_RANGE        public exponent is not supported
1343 //      TPM_RC_VALUE        could not find a prime using the provided parameters
1344 LIB_EXPORT TPM_RC
CryptRsaGenerateKey(TPMT_PUBLIC * publicArea,TPMT_SENSITIVE * sensitive,RAND_STATE * rand)1345 CryptRsaGenerateKey(
1346     TPMT_PUBLIC         *publicArea,
1347     TPMT_SENSITIVE      *sensitive,
1348     RAND_STATE          *rand               // IN: if not NULL, the deterministic
1349                                             //     RNG state
1350     )
1351 {
1352     UINT32               i;
1353     BN_RSA(bnD);
1354     BN_RSA(bnN);
1355     BN_WORD(bnPubExp);
1356     UINT32               e = publicArea->parameters.rsaDetail.exponent;
1357     int                  keySizeInBits;
1358     TPM_RC               retVal = TPM_RC_NO_RESULT;
1359     NEW_PRIVATE_EXPONENT(Z);
1360 //
1361 
1362 // Need to make sure that the caller did not specify an exponent that is
1363 // not supported
1364     e = publicArea->parameters.rsaDetail.exponent;
1365     if(e == 0)
1366         e = RSA_DEFAULT_PUBLIC_EXPONENT;
1367     else
1368     {
1369         if(e < 65537)
1370             ERROR_RETURN(TPM_RC_RANGE);
1371         // Check that e is prime
1372         if(!IsPrimeInt(e))
1373             ERROR_RETURN(TPM_RC_RANGE);
1374     }
1375     BnSetWord(bnPubExp, e);
1376 
1377     // check for supported key size.
1378     keySizeInBits = publicArea->parameters.rsaDetail.keyBits;
1379     if(((keySizeInBits % 1024) != 0)
1380        || (keySizeInBits > MAX_RSA_KEY_BITS)  // this might be redundant, but...
1381        || (keySizeInBits == 0))
1382         ERROR_RETURN(TPM_RC_VALUE);
1383 
1384     // Set the prime size for instrumentation purposes
1385     INSTRUMENT_SET(PrimeIndex, PRIME_INDEX(keySizeInBits / 2));
1386 
1387 #if SIMULATION && USE_RSA_KEY_CACHE
1388     if(GET_CACHED_KEY(publicArea, sensitive, rand))
1389         return TPM_RC_SUCCESS;
1390 #endif
1391 
1392     // Make sure that key generation has been tested
1393     TEST(TPM_ALG_NULL);
1394 
1395 
1396     // The prime is computed in P. When a new prime is found, Q is checked to
1397     // see if it is zero.  If so, P is copied to Q and a new P is found.
1398     // When both P and Q are non-zero, the modulus and
1399     // private exponent are computed and a trial encryption/decryption is
1400     // performed.  If the encrypt/decrypt fails, assume that at least one of the
1401     // primes is composite. Since we don't know which one, set Q to zero and start
1402     // over and find a new pair of primes.
1403 
1404     for(i = 1; (retVal == TPM_RC_NO_RESULT) && (i != 100); i++)
1405     {
1406         if(_plat__IsCanceled())
1407             ERROR_RETURN(TPM_RC_CANCELED);
1408 
1409         if(BnGeneratePrimeForRSA(Z->P, keySizeInBits / 2, e, rand) == TPM_RC_FAILURE)
1410         {
1411             retVal = TPM_RC_FAILURE;
1412             goto Exit;
1413         }
1414 
1415         INSTRUMENT_INC(PrimeCounts[PrimeIndex]);
1416 
1417         // If this is the second prime, make sure that it differs from the
1418         // first prime by at least 2^100
1419         if(BnEqualZero(Z->Q))
1420         {
1421             // copy p to q and compute another prime in p
1422             BnCopy(Z->Q, Z->P);
1423             continue;
1424         }
1425         // Make sure that the difference is at least 100 bits. Need to do it this
1426         // way because the big numbers are only positive values
1427         if(BnUnsignedCmp(Z->P, Z->Q) < 0)
1428             BnSub(bnD, Z->Q, Z->P);
1429         else
1430             BnSub(bnD, Z->P, Z->Q);
1431         if(BnMsb(bnD) < 100)
1432             continue;
1433 
1434         //Form the public modulus and set the unique value
1435         BnMult(bnN, Z->P, Z->Q);
1436         BnTo2B(bnN, &publicArea->unique.rsa.b,
1437                (NUMBYTES)BITS_TO_BYTES(keySizeInBits));
1438         // Make sure everything came out right. The MSb of the values must be one
1439         if(((publicArea->unique.rsa.t.buffer[0] & 0x80) == 0)
1440             || (publicArea->unique.rsa.t.size
1441                 != (NUMBYTES)BITS_TO_BYTES(keySizeInBits)))
1442             FAIL(FATAL_ERROR_INTERNAL);
1443 
1444 
1445         // Make sure that we can form the private exponent values
1446         if(ComputePrivateExponent(bnPubExp, Z) != TRUE)
1447         {
1448             // If ComputePrivateExponent could not find an inverse for
1449             // Q, then copy P and recompute P. This might
1450             // cause both to be recomputed if P is also zero
1451             if(BnEqualZero(Z->Q))
1452                 BnCopy(Z->Q, Z->P);
1453             continue;
1454         }
1455 
1456         // Pack the private exponent into the sensitive area
1457         PackExponent(&sensitive->sensitive.rsa, Z);
1458         // Make sure everything came out right. The MSb of the values must be one
1459         if(((publicArea->unique.rsa.t.buffer[0] & 0x80) == 0)
1460            || ((sensitive->sensitive.rsa.t.buffer[0] & 0x80) == 0))
1461             FAIL(FATAL_ERROR_INTERNAL);
1462 
1463         retVal = TPM_RC_SUCCESS;
1464         // Do a trial encryption decryption if this is a signing key
1465         if(IS_ATTRIBUTE(publicArea->objectAttributes, TPMA_OBJECT, sign))
1466         {
1467             BN_RSA(temp1);
1468             BN_RSA(temp2);
1469             BnGenerateRandomInRange(temp1, bnN, rand);
1470 
1471             // Encrypt with public exponent...
1472             BnModExp(temp2, temp1, bnPubExp, bnN);
1473             // ...  then decrypt with private exponent
1474             RsaPrivateKeyOp(temp2, Z);
1475 
1476             // If the starting and ending values are not the same,
1477             // start over )-;
1478             if(BnUnsignedCmp(temp2, temp1) != 0)
1479             {
1480                 BnSetWord(Z->Q, 0);
1481                 retVal = TPM_RC_NO_RESULT;
1482             }
1483         }
1484     }
1485 Exit:
1486     return retVal;
1487 }
1488 
1489 #endif // ALG_RSA