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 // This file contains the code for prime validation.
37 
38 #include "Tpm.h"
39 #include "CryptPrime_fp.h"
40 
41 //#define CPRI_PRIME
42 //#include "PrimeTable.h"
43 
44 #include "CryptPrimeSieve_fp.h"
45 
46 extern const uint32_t      s_LastPrimeInTable;
47 extern const uint32_t      s_PrimeTableSize;
48 extern const uint32_t      s_PrimesInTable;
49 extern const unsigned char s_PrimeTable[];
50 extern bigConst            s_CompositeOfSmallPrimes;
51 
52 //** Functions
53 
54 //*** Root2()
55 // This finds ceil(sqrt(n)) to use as a stopping point for searching the prime
56 // table.
57 static uint32_t
Root2(uint32_t n)58 Root2(
59     uint32_t             n
60     )
61 {
62     int32_t              last = (int32_t)(n >> 2);
63     int32_t              next = (int32_t)(n >> 1);
64     int32_t              diff;
65     int32_t              stop = 10;
66 //
67     // get a starting point
68     for(; next != 0; last >>= 1, next >>= 2);
69     last++;
70     do
71     {
72         next = (last + (n / last)) >> 1;
73         diff = next - last;
74         last = next;
75         if(stop-- == 0)
76             FAIL(FATAL_ERROR_INTERNAL);
77     } while(diff < -1 || diff > 1);
78     if((n / next) > (unsigned)next)
79         next++;
80     pAssert(next != 0);
81     pAssert(((n / next) <= (unsigned)next) && (n / (next + 1) < (unsigned)next));
82     return next;
83 }
84 
85 //*** IsPrimeInt()
86 // This will do a test of a word of up to 32-bits in size.
87 BOOL
IsPrimeInt(uint32_t n)88 IsPrimeInt(
89     uint32_t            n
90     )
91 {
92     uint32_t            i;
93     uint32_t            stop;
94     if(n < 3 || ((n & 1) == 0))
95         return (n == 2);
96     if(n <= s_LastPrimeInTable)
97     {
98         n >>= 1;
99         return ((s_PrimeTable[n >> 3] >> (n & 7)) & 1);
100     }
101     // Need to search
102     stop = Root2(n) >> 1;
103     // starting at 1 is equivalent to staring at  (1 << 1) + 1 = 3
104     for(i = 1; i < stop; i++)
105     {
106         if((s_PrimeTable[i >> 3] >> (i & 7)) & 1)
107             // see if this prime evenly divides the number
108             if((n % ((i << 1) + 1)) == 0)
109                 return FALSE;
110     }
111     return TRUE;
112 }
113 
114 //*** BnIsProbablyPrime()
115 // This function is used when the key sieve is not implemented. This function
116 // Will try to eliminate some of the obvious things before going on
117 // to perform MillerRabin as a final verification of primeness.
118 BOOL
BnIsProbablyPrime(bigNum prime,RAND_STATE * rand)119 BnIsProbablyPrime(
120     bigNum          prime,           // IN:
121     RAND_STATE      *rand            // IN: the random state just
122                                      //     in case Miller-Rabin is required
123     )
124 {
125 #if RADIX_BITS > 32
126     if(BnUnsignedCmpWord(prime, UINT32_MAX) <= 0)
127 #else
128     if(BnGetSize(prime) == 1)
129 #endif
130         return IsPrimeInt((uint32_t)prime->d[0]);
131 
132     if(BnIsEven(prime))
133         return FALSE;
134     if(BnUnsignedCmpWord(prime, s_LastPrimeInTable) <= 0)
135     {
136         crypt_uword_t       temp = prime->d[0] >> 1;
137         return ((s_PrimeTable[temp >> 3] >> (temp & 7)) & 1);
138     }
139     {
140         BN_VAR(n, LARGEST_NUMBER_BITS);
141         BnGcd(n, prime, s_CompositeOfSmallPrimes);
142         if(!BnEqualWord(n, 1))
143             return FALSE;
144     }
145     return MillerRabin(prime, rand);
146 }
147 
148 //*** MillerRabinRounds()
149 // Function returns the number of Miller-Rabin rounds necessary to give an
150 // error probability equal to the security strength of the prime. These values
151 // are from FIPS 186-3.
152 UINT32
MillerRabinRounds(UINT32 bits)153 MillerRabinRounds(
154     UINT32           bits           // IN: Number of bits in the RSA prime
155     )
156 {
157     if(bits < 511) return 8;    // don't really expect this
158     if(bits < 1536) return 5;   // for 512 and 1K primes
159     return 4;                   // for 3K public modulus and greater
160 }
161 
162 //*** MillerRabin()
163 // This function performs a Miller-Rabin test from FIPS 186-3. It does
164 // 'iterations' trials on the number. In all likelihood, if the number
165 // is not prime, the first test fails.
166 //  Return Type: BOOL
167 //      TRUE(1)         probably prime
168 //      FALSE(0)        composite
169 BOOL
MillerRabin(bigNum bnW,RAND_STATE * rand)170 MillerRabin(
171     bigNum           bnW,
172     RAND_STATE      *rand
173     )
174 {
175     BN_MAX(bnWm1);
176     BN_PRIME(bnM);
177     BN_PRIME(bnB);
178     BN_PRIME(bnZ);
179     BOOL             ret = FALSE;   // Assumed composite for easy exit
180     unsigned int     a;
181     unsigned int     j;
182     int              wLen;
183     int              i;
184     int              iterations = MillerRabinRounds(BnSizeInBits(bnW));
185 //
186    INSTRUMENT_INC(MillerRabinTrials[PrimeIndex]);
187 
188     pAssert(bnW->size > 1);
189     // Let a be the largest integer such that 2^a divides w1.
190     BnSubWord(bnWm1, bnW, 1);
191     pAssert(bnWm1->size != 0);
192 
193     // Since w is odd (w-1) is even so start at bit number 1 rather than 0
194     // Get the number of bits in bnWm1 so that it doesn't have to be recomputed
195     // on each iteration.
196     i = (int)(bnWm1->size * RADIX_BITS);
197   // Now find the largest power of 2 that divides w1
198     for(a = 1;
199     (a < (bnWm1->size * RADIX_BITS)) &&
200         (BnTestBit(bnWm1, a) == 0);
201         a++);
202  // 2. m = (w1) / 2^a
203         BnShiftRight(bnM, bnWm1, a);
204       // 3. wlen = len (w).
205     wLen = BnSizeInBits(bnW);
206   // 4. For i = 1 to iterations do
207     for(i = 0; i < iterations; i++)
208     {
209         // 4.1 Obtain a string b of wlen bits from an RBG.
210         // Ensure that 1 < b < w1.
211         // 4.2 If ((b <= 1) or (b >= w1)), then go to step 4.1.
212         while(BnGetRandomBits(bnB, wLen, rand) && ((BnUnsignedCmpWord(bnB, 1) <= 0)
213             || (BnUnsignedCmp(bnB, bnWm1) >= 0)));
214         if(g_inFailureMode)
215             return FALSE;
216 
217        // 4.3 z = b^m mod w.
218        // if ModExp fails, then say this is not
219        // prime and bail out.
220         BnModExp(bnZ, bnB, bnM, bnW);
221 
222         // 4.4 If ((z == 1) or (z = w == 1)), then go to step 4.7.
223         if((BnUnsignedCmpWord(bnZ, 1) == 0)
224            || (BnUnsignedCmp(bnZ, bnWm1) == 0))
225             goto step4point7;
226         // 4.5 For j = 1 to a  1 do.
227         for(j = 1; j < a; j++)
228         {
229           // 4.5.1 z = z^2 mod w.
230             BnModMult(bnZ, bnZ, bnZ, bnW);
231           // 4.5.2 If (z = w1), then go to step 4.7.
232             if(BnUnsignedCmp(bnZ, bnWm1) == 0)
233                 goto step4point7;
234           // 4.5.3 If (z = 1), then go to step 4.6.
235             if(BnEqualWord(bnZ, 1))
236                 goto step4point6;
237         }
238         // 4.6 Return COMPOSITE.
239 step4point6:
240         INSTRUMENT_INC(failedAtIteration[i]);
241         goto end;
242       // 4.7 Continue. Comment: Increment i for the do-loop in step 4.
243 step4point7:
244         continue;
245     }
246   // 5. Return PROBABLY PRIME
247     ret = TRUE;
248 end:
249     return ret;
250 }
251 
252 #if ALG_RSA
253 
254 //*** RsaCheckPrime()
255 // This will check to see if a number is prime and appropriate for an
256 // RSA prime.
257 //
258 // This has different functionality based on whether we are using key
259 // sieving or not. If not, the number checked to see if it is divisible by
260 // the public exponent, then the number is adjusted either up or down
261 // in order to make it a better candidate. It is then checked for being
262 // probably prime.
263 //
264 // If sieving is used, the number is used to root a sieving process.
265 //
266 TPM_RC
RsaCheckPrime(bigNum prime,UINT32 exponent,RAND_STATE * rand)267 RsaCheckPrime(
268     bigNum           prime,
269     UINT32           exponent,
270     RAND_STATE      *rand
271     )
272 {
273 #if !RSA_KEY_SIEVE
274     TPM_RC          retVal = TPM_RC_SUCCESS;
275     UINT32          modE = BnModWord(prime, exponent);
276 
277     NOT_REFERENCED(rand);
278 
279     if(modE == 0)
280         // evenly divisible so add two keeping the number odd
281         BnAddWord(prime, prime, 2);
282     // want 0 != (p - 1) mod e
283     // which is 1 != p mod e
284     else if(modE == 1)
285         // subtract 2 keeping number odd and insuring that
286         // 0 != (p - 1) mod e
287         BnSubWord(prime, prime, 2);
288 
289     if(BnIsProbablyPrime(prime, rand) == 0)
290         ERROR_RETURN(g_inFailureMode ? TPM_RC_FAILURE : TPM_RC_VALUE);
291 Exit:
292     return retVal;
293 #else
294     return PrimeSelectWithSieve(prime, exponent, rand);
295 #endif
296 }
297 
298 //*** RsaAdjustPrimeCandiate()
299 // For this math, we assume that the RSA numbers are fixed-point numbers with
300 // the decimal point to the "left" of the most significant bit. This approach helps
301 // make it clear what is happening with the MSb of the values.
302 // The two RSA primes have to be large enough so that their product will be a number
303 // with the necessary number of significant bits. For example, we want to be able
304 // to multiply two 1024-bit numbers to produce a number with 2028 significant bits. If
305 // we accept any 1024-bit prime that has its MSb set, then it is possible to produce a
306 // product that does not have the MSb SET. For example, if we use tiny keys of 16 bits
307 // and have two 8-bit 'primes' of 0x80, then the public key would be 0x4000 which is
308 // only 15-bits. So, what we need to do is made sure that each of the primes is large
309 // enough so that the product of the primes is twice as large as each prime. A little
310 // arithmetic will show that the only way to do this is to make sure that each of the
311 // primes is no less than root(2)/2. That's what this functions does.
312 // This function adjusts the candidate prime so that it is odd and >= root(2)/2.
313 // This allows the product of these two numbers to be .5, which, in fixed point
314 // notation means that the most significant bit is 1.
315 // For this routine, the root(2)/2 (0.7071067811865475) approximated with 0xB505
316 // which is, in fixed point, 0.7071075439453125 or an error of 0.000108%. Just setting
317 // the upper two bits would give a value > 0.75 which is an error of > 6%. Given the
318 // amount of time all the other computations take, reducing the error is not much of
319 // a cost, but it isn't totally required either.
320 //
321 // This function can be replaced with a function that just sets the two most
322 // significant bits of each prime candidate without introducing any computational
323 // issues.
324 //
325 LIB_EXPORT void
RsaAdjustPrimeCandidate(bigNum prime)326 RsaAdjustPrimeCandidate(
327     bigNum          prime
328     )
329 {
330     UINT32          msw;
331     UINT32          adjusted;
332 
333     // If the radix is 32, the compiler should turn this into a simple assignment
334     msw = prime->d[prime->size - 1] >> ((RADIX_BITS == 64) ? 32 : 0);
335     // Multiplying 0xff...f by 0x4AFB gives 0xff..f - 0xB5050...0
336     adjusted = (msw >> 16) * 0x4AFB;
337     adjusted += ((msw & 0xFFFF) * 0x4AFB) >> 16;
338     adjusted += 0xB5050000UL;
339 #if RADIX_BITS == 64
340     // Save the low-order 32 bits
341     prime->d[prime->size - 1] &= 0xFFFFFFFFUL;
342     // replace the upper 32-bits
343     prime->d[prime->size -1] |= ((crypt_uword_t)adjusted << 32);
344 #else
345     prime->d[prime->size - 1] = (crypt_uword_t)adjusted;
346 #endif
347     // make sure the number is odd
348     prime->d[0] |= 1;
349 }
350 
351 //***BnGeneratePrimeForRSA()
352 // Function to generate a prime of the desired size with the proper attributes
353 // for an RSA prime.
354 TPM_RC
BnGeneratePrimeForRSA(bigNum prime,UINT32 bits,UINT32 exponent,RAND_STATE * rand)355 BnGeneratePrimeForRSA(
356     bigNum          prime,          // IN/OUT: points to the BN that will get the
357                                     //  random value
358     UINT32          bits,           // IN: number of bits to get
359     UINT32          exponent,       // IN: the exponent
360     RAND_STATE      *rand           // IN: the random state
361     )
362 {
363     BOOL            found = FALSE;
364 //
365     // Make sure that the prime is large enough
366     pAssert(prime->allocated >= BITS_TO_CRYPT_WORDS(bits));
367     // Only try to handle specific sizes of keys in order to save overhead
368     pAssert((bits % 32) == 0);
369 
370     prime->size = BITS_TO_CRYPT_WORDS(bits);
371 
372     while(!found)
373     {
374 // The change below is to make sure that all keys that are generated from the same
375 // seed value will be the same regardless of the endianess or word size of the CPU.
376 //       DRBG_Generate(rand, (BYTE *)prime->d, (UINT16)BITS_TO_BYTES(bits));// old
377 //       if(g_inFailureMode)                                                // old
378        if(!BnGetRandomBits(prime, bits, rand))                              // new
379             return TPM_RC_FAILURE;
380         RsaAdjustPrimeCandidate(prime);
381         found = RsaCheckPrime(prime, exponent, rand) == TPM_RC_SUCCESS;
382     }
383     return TPM_RC_SUCCESS;
384 }
385 
386 #endif // ALG_RSA