1 /****************************************************************************
2 * *
3 * cryptlib Key Derivation Mechanism Routines *
4 * Copyright Peter Gutmann 1992-2009 *
5 * *
6 ****************************************************************************/
7
8 #ifdef INC_ALL
9 #include "crypt.h"
10 #include "asn1.h"
11 #include "mech_int.h"
12 #include "pgp.h"
13 #else
14 #include "crypt.h"
15 #include "enc_dec/asn1.h"
16 #include "mechs/mech_int.h"
17 #include "misc/pgp.h"
18 #endif /* Compiler-specific includes */
19
20 /****************************************************************************
21 * *
22 * PRF Building Blocks *
23 * *
24 ****************************************************************************/
25
26 /* HMAC-based PRF used for PKCS #5 v2 and TLS */
27
28 #define HMAC_DATASIZE 64
29
30 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3, 5, 7, 8 ) ) \
31 static int prfInit( IN const HASH_FUNCTION hashFunction,
32 IN const HASH_FUNCTION_ATOMIC hashFunctionAtomic,
33 OUT TYPECAST( HASHINFO ) void *hashState,
34 IN_LENGTH_HASH const int hashSize,
35 OUT_BUFFER( processedKeyMaxLength, *processedKeyLength ) \
36 void *processedKey,
37 IN_LENGTH_FIXED( HMAC_DATASIZE ) \
38 const int processedKeyMaxLength,
39 OUT_RANGE( 0, HMAC_DATASIZE ) int *processedKeyLength,
40 IN_BUFFER( keyLength ) const void *key,
41 IN_LENGTH_SHORT const int keyLength )
42 {
43 BYTE hashBuffer[ HMAC_DATASIZE + 8 ], *keyPtr = processedKey;
44 int i;
45
46 assert( isWritePtr( hashState, sizeof( HASHINFO ) ) );
47 assert( isWritePtr( processedKey, processedKeyMaxLength ) );
48 assert( isWritePtr( processedKeyLength, sizeof( int ) ) );
49 assert( isReadPtr( key, keyLength ) );
50
51 REQUIRES( hashFunction != NULL && hashFunctionAtomic != NULL );
52 REQUIRES( hashSize >= 16 && hashSize <= CRYPT_MAX_HASHSIZE );
53 REQUIRES( processedKeyMaxLength == HMAC_DATASIZE );
54 REQUIRES( keyLength > 0 && keyLength < MAX_INTLENGTH_SHORT );
55
56 /* Clear return values */
57 memset( processedKey, 0, min( 16, processedKeyMaxLength ) );
58 *processedKeyLength = 0;
59
60 /* If the key size is larger than the hash data size reduce it to the
61 hash size before processing it (yuck. You're required to do this
62 though) */
63 if( keyLength > HMAC_DATASIZE )
64 {
65 /* Hash the user key down to the hash size and use the hashed form of
66 the key */
67 hashFunctionAtomic( processedKey, processedKeyMaxLength, key,
68 keyLength );
69 *processedKeyLength = hashSize;
70 }
71 else
72 {
73 /* Copy the key to internal storage. Note that this has the
74 potential to leak a tiny amount of timing information about the
75 key length, but given the mass of operations that follow this is
76 unlikely to be significant */
77 memcpy( processedKey, key, keyLength );
78 *processedKeyLength = keyLength;
79 }
80
81 /* Perform the start of the inner hash using the zero-padded key XORed
82 with the ipad value. This could be done slightly more efficiently,
83 but the following sequence of operations minimises timing channels
84 leaking the key length */
85 memcpy( hashBuffer, keyPtr, *processedKeyLength );
86 if( *processedKeyLength < HMAC_DATASIZE )
87 {
88 memset( hashBuffer + *processedKeyLength, 0,
89 HMAC_DATASIZE - *processedKeyLength );
90 }
91 for( i = 0; i < HMAC_DATASIZE; i++ )
92 hashBuffer[ i ] ^= HMAC_IPAD;
93 hashFunction( hashState, NULL, 0, hashBuffer, HMAC_DATASIZE,
94 HASH_STATE_START );
95 zeroise( hashBuffer, HMAC_DATASIZE );
96
97 return( CRYPT_OK );
98 }
99
100 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 4, 6 ) ) \
101 static int prfEnd( IN const HASH_FUNCTION hashFunction,
102 INOUT TYPECAST( HASHINFO ) void *hashState,
103 IN_LENGTH_HASH const int hashSize,
104 OUT_BUFFER_FIXED( hashMaxSize ) void *hash,
105 IN_LENGTH_HASH const int hashMaxSize,
106 IN_BUFFER( processedKeyLength ) const void *processedKey,
107 IN_RANGE( 1, HMAC_DATASIZE ) const int processedKeyLength )
108 {
109 BYTE hashBuffer[ HMAC_DATASIZE + 8 ];
110 BYTE digestBuffer[ CRYPT_MAX_HASHSIZE + 8 ];
111 int i;
112
113 assert( isWritePtr( hashState, sizeof( HASHINFO ) ) );
114 assert( isWritePtr( hash, hashMaxSize ) );
115 assert( isReadPtr( processedKey, processedKeyLength ) );
116
117 REQUIRES( hashFunction != NULL );
118 REQUIRES( hashSize >= 16 && hashSize <= CRYPT_MAX_HASHSIZE );
119 REQUIRES( hashMaxSize >= 16 && hashMaxSize <= CRYPT_MAX_HASHSIZE );
120 REQUIRES( processedKeyLength >= 1 && \
121 processedKeyLength <= HMAC_DATASIZE );
122
123 /* Complete the inner hash and extract the digest */
124 hashFunction( hashState, digestBuffer, CRYPT_MAX_HASHSIZE, NULL, 0,
125 HASH_STATE_END );
126
127 /* Perform the outer hash using the zero-padded key XORed with the opad
128 value followed by the digest from the inner hash. As with the init
129 function this could be done slightly more efficiently, but the
130 following sequence of operations minimises timing channels leaking
131 the key length */
132 memcpy( hashBuffer, processedKey, processedKeyLength );
133 if( processedKeyLength < HMAC_DATASIZE )
134 {
135 memset( hashBuffer + processedKeyLength, 0,
136 HMAC_DATASIZE - processedKeyLength );
137 }
138 for( i = 0; i < HMAC_DATASIZE; i++ )
139 hashBuffer[ i ] ^= HMAC_OPAD;
140 hashFunction( hashState, NULL, 0, hashBuffer, HMAC_DATASIZE,
141 HASH_STATE_START );
142 zeroise( hashBuffer, HMAC_DATASIZE );
143 hashFunction( hashState, hash, hashMaxSize, digestBuffer, hashSize,
144 HASH_STATE_END );
145 zeroise( digestBuffer, CRYPT_MAX_HASHSIZE );
146
147 return( CRYPT_OK );
148 }
149
150 /****************************************************************************
151 * *
152 * PKCS #5v2 Key Derivation *
153 * *
154 ****************************************************************************/
155
156 /* Implement one round of the PKCS #5v2 PRF */
157
158 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 3, 4, 6, 8 ) ) \
OUT_BUFFER_FIXED(outLength)159 static int pbkdf2Hash( OUT_BUFFER_FIXED( outLength ) BYTE *out,
160 IN_RANGE( 1, CRYPT_MAX_HASHSIZE ) const int outLength,
161 IN const HASH_FUNCTION hashFunction,
162 INOUT TYPECAST( HASHINFO ) void *initialHashState,
163 IN_LENGTH_HASH const int hashSize,
164 IN_BUFFER( keyLength ) const void *key,
165 IN_RANGE( 1, HMAC_DATASIZE ) const int keyLength,
166 IN_BUFFER( saltLength ) const void *salt,
167 IN_RANGE( 4, 512 ) const int saltLength,
168 IN_INT const int iterations,
169 IN_RANGE( 1, 1000 ) const int blockCount )
170 {
171 HASHINFO hashInfo;
172 BYTE block[ CRYPT_MAX_HASHSIZE + 8 ], countBuffer[ 4 + 8 ];
173 int i, status;
174
175 assert( isWritePtr( out, outLength ) );
176 assert( isWritePtr( initialHashState, sizeof( HASHINFO ) ) );
177 assert( isReadPtr( key, keyLength ) );
178 assert( isReadPtr( salt, saltLength ) );
179
180 REQUIRES( hashFunction != NULL );
181 REQUIRES( outLength > 0 && outLength <= hashSize && \
182 outLength <= CRYPT_MAX_HASHSIZE );
183 REQUIRES( hashSize >= 16 && hashSize <= CRYPT_MAX_HASHSIZE );
184 REQUIRES( keyLength >= 1 && keyLength <= HMAC_DATASIZE );
185 REQUIRES( saltLength >= 4 && saltLength <= 512 );
186 REQUIRES( iterations > 0 && iterations < MAX_INTLENGTH );
187 REQUIRES( blockCount > 0 && blockCount <= 1000 );
188
189 /* Clear return value */
190 memset( out, 0, outLength );
191
192 /* Set up the block counter buffer. This will never have more than the
193 last few bits set (8 bits = 5100 bytes of key) so we only change the
194 last byte */
195 memset( countBuffer, 0, 4 );
196 countBuffer[ 3 ] = ( BYTE ) blockCount;
197
198 /* Calculate HMAC( salt || counter ) */
199 memcpy( hashInfo, initialHashState, sizeof( HASHINFO ) );
200 hashFunction( hashInfo, NULL, 0, salt, saltLength, HASH_STATE_CONTINUE );
201 hashFunction( hashInfo, NULL, 0, countBuffer, 4, HASH_STATE_CONTINUE );
202 status = prfEnd( hashFunction, hashInfo, hashSize, block,
203 CRYPT_MAX_HASHSIZE, key, keyLength );
204 if( cryptStatusError( status ) )
205 {
206 zeroise( hashInfo, sizeof( HASHINFO ) );
207 return( status );
208 }
209 memcpy( out, block, outLength );
210
211 /* Calculate HMAC( T1 ) ^ HMAC( T2 ) ^ ... HMAC( Tc ) */
212 for( i = 0; i < iterations - 1 && i < FAILSAFE_ITERATIONS_MAX; i++ )
213 {
214 int j;
215
216 /* Generate the PRF output for the current iteration */
217 memcpy( hashInfo, initialHashState, sizeof( HASHINFO ) );
218 hashFunction( hashInfo, NULL, 0, block, hashSize, HASH_STATE_CONTINUE );
219 status = prfEnd( hashFunction, hashInfo, hashSize, block,
220 CRYPT_MAX_HASHSIZE, key, keyLength );
221 if( cryptStatusError( status ) )
222 {
223 zeroise( hashInfo, sizeof( HASHINFO ) );
224 zeroise( block, CRYPT_MAX_HASHSIZE );
225 return( status );
226 }
227
228 /* XOR the new PRF output into the existing PRF output */
229 for( j = 0; j < outLength; j++ )
230 out[ j ] ^= block[ j ];
231 }
232 ENSURES( i < FAILSAFE_ITERATIONS_MAX );
233
234 zeroise( hashInfo, sizeof( HASHINFO ) );
235 zeroise( block, CRYPT_MAX_HASHSIZE );
236
237 return( CRYPT_OK );
238 }
239
240 /* Perform PKCS #5v2 derivation */
241
242 CHECK_RETVAL STDC_NONNULL_ARG( ( 2 ) ) \
derivePKCS5(STDC_UNUSED void * dummy,INOUT MECHANISM_DERIVE_INFO * mechanismInfo)243 int derivePKCS5( STDC_UNUSED void *dummy,
244 INOUT MECHANISM_DERIVE_INFO *mechanismInfo )
245 {
246 CRYPT_ALGO_TYPE hashAlgo;
247 HASH_FUNCTION_ATOMIC hashFunctionAtomic;
248 HASH_FUNCTION hashFunction;
249 HASHINFO initialHashInfo;
250 BYTE processedKey[ HMAC_DATASIZE + 8 ];
251 BYTE *dataOutPtr = mechanismInfo->dataOut;
252 static const MAP_TABLE mapTbl[] = {
253 { CRYPT_ALGO_HMAC_SHA1, CRYPT_ALGO_SHA1 },
254 { CRYPT_ALGO_HMAC_SHA2, CRYPT_ALGO_SHA2 },
255 { CRYPT_ALGO_HMAC_SHAng, CRYPT_ALGO_SHAng },
256 { CRYPT_ERROR, CRYPT_ERROR }, { CRYPT_ERROR, CRYPT_ERROR }
257 };
258 int hashSize, keyIndex, processedKeyLength, blockCount = 1;
259 int value, iterationCount, status;
260
261 UNUSED_ARG( dummy );
262 assert( isWritePtr( mechanismInfo, sizeof( MECHANISM_DERIVE_INFO ) ) );
263
264 /* Clear return value */
265 memset( mechanismInfo->dataOut, 0, mechanismInfo->dataOutLength );
266
267 /* Convert the HMAC algorithm into the equivalent hash algorithm for use
268 with the PRF */
269 status = mapValue( mechanismInfo->hashAlgo, &value, mapTbl,
270 FAILSAFE_ARRAYSIZE( mapTbl, MAP_TABLE ) );
271 if( cryptStatusError( status ) )
272 return( status );
273 hashAlgo = value;
274 if( !algoAvailable( hashAlgo ) )
275 return( CRYPT_ERROR_NOTAVAIL );
276
277 /* Initialise the HMAC information with the user key. Although the user
278 has specified the algorithm in terms of an HMAC we're synthesising it
279 from the underlying hash algorithm since this allows us to perform the
280 PRF setup once and reuse the initial value for any future hashing */
281 getHashAtomicParameters( hashAlgo, mechanismInfo->hashParam,
282 &hashFunctionAtomic, &hashSize );
283 getHashParameters( hashAlgo, mechanismInfo->hashParam, &hashFunction,
284 NULL );
285 status = prfInit( hashFunction, hashFunctionAtomic, initialHashInfo,
286 hashSize, processedKey, HMAC_DATASIZE,
287 &processedKeyLength, mechanismInfo->dataIn,
288 mechanismInfo->dataInLength );
289 if( cryptStatusError( status ) )
290 return( status );
291
292 /* Produce enough blocks of output to fill the key (nil sine magno
293 labore) */
294 for( keyIndex = 0, iterationCount = 0;
295 keyIndex < mechanismInfo->dataOutLength && \
296 iterationCount < FAILSAFE_ITERATIONS_MED;
297 keyIndex += hashSize, dataOutPtr += hashSize, iterationCount++ )
298 {
299 const int noKeyBytes = \
300 ( mechanismInfo->dataOutLength - keyIndex > hashSize ) ? \
301 hashSize : mechanismInfo->dataOutLength - keyIndex;
302
303 status = pbkdf2Hash( dataOutPtr, noKeyBytes,
304 hashFunction, initialHashInfo, hashSize,
305 processedKey, processedKeyLength,
306 mechanismInfo->salt, mechanismInfo->saltLength,
307 mechanismInfo->iterations, blockCount++ );
308 if( cryptStatusError( status ) )
309 break;
310 }
311 ENSURES( iterationCount < FAILSAFE_ITERATIONS_MED );
312 zeroise( initialHashInfo, sizeof( HASHINFO ) );
313 zeroise( processedKey, HMAC_DATASIZE );
314 if( cryptStatusError( status ) )
315 {
316 zeroise( mechanismInfo->dataOut, mechanismInfo->dataOutLength );
317 return( status );
318 }
319
320 return( CRYPT_OK );
321 }
322
323 /* Apply PKCS #5v2 as a pure (single-round) KDF */
324
325 CHECK_RETVAL STDC_NONNULL_ARG( ( 2 ) ) \
kdfPKCS5(STDC_UNUSED void * dummy,INOUT MECHANISM_KDF_INFO * mechanismInfo)326 int kdfPKCS5( STDC_UNUSED void *dummy,
327 INOUT MECHANISM_KDF_INFO *mechanismInfo )
328 {
329 MECHANISM_DERIVE_INFO mechanismDeriveInfo;
330 MESSAGE_DATA msgData;
331 BYTE masterSecretBuffer[ CRYPT_MAX_KEYSIZE + 8 ];
332 BYTE keyBuffer[ CRYPT_MAX_KEYSIZE + 8 ];
333 int masterSecretSize, keySize DUMMY_INIT, status;
334
335 UNUSED_ARG( dummy );
336 assert( isWritePtr( mechanismInfo, sizeof( MECHANISM_DERIVE_INFO ) ) );
337
338 /* Get the key payload details from the key contexts */
339 status = krnlSendMessage( mechanismInfo->masterKeyContext,
340 IMESSAGE_GETATTRIBUTE, &masterSecretSize,
341 CRYPT_CTXINFO_KEYSIZE );
342 if( cryptStatusOK( status ) )
343 {
344 status = krnlSendMessage( mechanismInfo->keyContext,
345 IMESSAGE_GETATTRIBUTE, &keySize,
346 CRYPT_CTXINFO_KEYSIZE );
347 }
348 if( cryptStatusError( status ) )
349 return( status );
350 ENSURES( masterSecretSize > 0 && \
351 masterSecretSize <= CRYPT_MAX_KEYSIZE );
352
353 /* Extract the master secret value from the generic-secret context and
354 derive the key from it using PBKDF2 as the KDF */
355 status = extractKeyData( mechanismInfo->masterKeyContext,
356 masterSecretBuffer, CRYPT_MAX_KEYSIZE,
357 "keydata", 7 );
358 if( cryptStatusError( status ) )
359 return( status );
360 setMechanismDeriveInfo( &mechanismDeriveInfo, keyBuffer, keySize,
361 masterSecretBuffer, masterSecretSize,
362 mechanismInfo->hashAlgo, mechanismInfo->salt,
363 mechanismInfo->saltLength, 1 );
364 mechanismDeriveInfo.hashParam = mechanismInfo->hashParam;
365 status = derivePKCS5( NULL, &mechanismDeriveInfo );
366 zeroise( masterSecretBuffer, CRYPT_MAX_KEYSIZE );
367 if( cryptStatusError( status ) )
368 {
369 zeroise( keyBuffer, CRYPT_MAX_KEYSIZE );
370 return( status );
371 }
372
373 /* Load the derived key into the context */
374 setMessageData( &msgData, keyBuffer, keySize );
375 status = krnlSendMessage( mechanismInfo->keyContext,
376 IMESSAGE_SETATTRIBUTE_S, &msgData,
377 CRYPT_CTXINFO_KEY );
378 zeroise( keyBuffer, CRYPT_MAX_KEYSIZE );
379
380 return( status );
381 }
382
383 /****************************************************************************
384 * *
385 * PKCS #12 Key Derivation *
386 * *
387 ****************************************************************************/
388
389 #ifdef USE_PKCS12
390
391 /* The nominal block size for PKCS #12 derivation, based on the MD5/SHA-1
392 input size of 512 bits */
393
394 #define P12_BLOCKSIZE 64
395
396 /* The maximum size of the expanded diversifier, salt, and password (DSP),
397 one block for the expanded diversifier, one block for the expanded salt,
398 and up to three blocks for the password converted to Unicode with a
399 terminating \x00 appended, which for a maximum password length of
400 CRYPT_MAX_TEXTSIZE can be ( 64 + 1 ) * 2, rounded up to a multiple of
401 P12_BLOCKSIZE */
402
403 #define P12_DSPSIZE ( P12_BLOCKSIZE + P12_BLOCKSIZE + \
404 ( P12_BLOCKSIZE * 3 ) )
405
406 /* Add two P12_BLOCKSIZE-byte blocks as 64-byte big-endian values:
407
408 dest = (dest + src + 1) mod 2^P12_BLOCKSIZE */
409
410 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 3 ) ) \
add64(INOUT_BUFFER_FIXED (destLen)BYTE * dest,IN_LENGTH_FIXED (P12_BLOCKSIZE)const int destLen,IN_BUFFER (srcLen)const BYTE * src,IN_LENGTH_FIXED (P12_BLOCKSIZE)const int srcLen)411 static int add64( INOUT_BUFFER_FIXED( destLen ) BYTE *dest,
412 IN_LENGTH_FIXED( P12_BLOCKSIZE ) const int destLen,
413 IN_BUFFER( srcLen ) const BYTE *src,
414 IN_LENGTH_FIXED( P12_BLOCKSIZE ) const int srcLen )
415 {
416 int destIndex, srcIndex, carry = 1;
417
418 assert( isWritePtr( dest, destLen ) );
419 assert( isReadPtr( src, srcLen ) );
420
421 REQUIRES( destLen == P12_BLOCKSIZE );
422 REQUIRES( srcLen == P12_BLOCKSIZE );
423
424 /* dest = (dest + src + 1) mod 2^P12_BLOCKSIZE */
425 for( destIndex = P12_BLOCKSIZE - 1, srcIndex = P12_BLOCKSIZE - 1;
426 destIndex >= 0; destIndex--, srcIndex-- )
427 {
428 const int value = dest[ destIndex ] + src[ srcIndex ] + carry;
429 dest[ destIndex ] = intToByte( value & 0xFF );
430 carry = value >> 8;
431 }
432
433 return( CRYPT_OK );
434 }
435
436 /* Concantenate enough copies of the input data together to fill an output
437 buffer */
438
439 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 3 ) ) \
expandData(OUT_BUFFER_FIXED (destLen)BYTE * dest,IN_LENGTH_SHORT const int destLen,IN_BUFFER (srcLen)const BYTE * src,IN_LENGTH_SHORT const int srcLen)440 static int expandData( OUT_BUFFER_FIXED( destLen ) BYTE *dest,
441 IN_LENGTH_SHORT const int destLen,
442 IN_BUFFER( srcLen ) const BYTE *src,
443 IN_LENGTH_SHORT const int srcLen )
444 {
445 int index, iterationCount;
446
447 assert( isWritePtr( dest, destLen ) );
448 assert( isReadPtr( src, srcLen ) );
449
450 REQUIRES( destLen > 0 && destLen < MAX_INTLENGTH_SHORT );
451 REQUIRES( srcLen > 0 && srcLen < MAX_INTLENGTH_SHORT );
452
453 /* Clear return value */
454 memset( dest, 0, min( 16, destLen ) );
455
456 for( index = 0, iterationCount = 0;
457 index < destLen && iterationCount < FAILSAFE_ITERATIONS_MED;
458 iterationCount++ )
459 {
460 const int bytesToCopy = min( srcLen, destLen - index );
461
462 memcpy( dest, src, bytesToCopy );
463 dest += bytesToCopy;
464 index += bytesToCopy;
465 }
466 ENSURES( iterationCount < FAILSAFE_ITERATIONS_MED );
467
468 return( CRYPT_OK );
469 }
470
471 /* Build the diversifier/salt/password (DSP) string to use as the initial
472 input to the hash function:
473
474 <---- 64 bytes ----><------- 64 bytes -------><-- Mult.64 bytes ->
475 [ ID | ID | ID ... ][ salt | salt | salt ... ][ pw | pw | pw ... ] */
476
477 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 3, 4, 6 ) ) \
478 static int initDSP( OUT_BUFFER( dspMaxLen, *dspLen ) BYTE *dsp,
479 IN_RANGE( P12_DSPSIZE, 512 ) const int dspMaxLen,
480 OUT_RANGE( 0, 512 ) int *dspLen,
481 IN_BUFFER( keyLength ) const BYTE *key,
482 IN_LENGTH_TEXT const int keyLength,
483 IN_BUFFER( saltLength ) const BYTE *salt,
484 IN_RANGE( 1, P12_BLOCKSIZE ) const int saltLength,
485 IN_RANGE( 1, 3 ) const int diversifier )
486 {
487 BYTE bmpString[ ( ( CRYPT_MAX_TEXTSIZE + 1 ) * 2 ) + 8 ];
488 BYTE *dspPtr = dsp;
489 int keyIndex, bmpIndex, i, status;
490
491 assert( isWritePtr( dsp, dspMaxLen ) );
492 assert( isWritePtr( dspLen, sizeof( int ) ) );
493 assert( isReadPtr( key, keyLength ) );
494 assert( isReadPtr( salt, saltLength ) );
495
496 REQUIRES( dspMaxLen >= P12_DSPSIZE && dspMaxLen <= 512 );
497 REQUIRES( diversifier >= 1 && diversifier <= 3 );
498 REQUIRES( saltLength >= 1 && saltLength <= P12_BLOCKSIZE );
499 REQUIRES( keyLength >= MIN_NAME_LENGTH && \
500 keyLength <= CRYPT_MAX_TEXTSIZE );
501
502 /* Clear return values */
503 memset( dsp, 0, min( 16, dspMaxLen ) );
504 *dspLen = 0;
505
506 /* Set up the diversifier in the first P12_BLOCKSIZE bytes */
507 for( i = 0; i < P12_BLOCKSIZE; i++ )
508 dsp[ i ] = intToByte( diversifier );
509 dspPtr += P12_BLOCKSIZE;
510
511 /* Set up the salt in the next P12_BLOCKSIZE bytes */
512 status = expandData( dspPtr, P12_BLOCKSIZE, salt, saltLength );
513 if( cryptStatusError( status ) )
514 return( status );
515 dspPtr += P12_BLOCKSIZE;
516
517 /* Convert the password to a null-terminated Unicode string, a Microsoft
518 bug that was made part of the standard */
519 for( keyIndex = 0, bmpIndex = 0;
520 keyIndex < keyLength && keyIndex < CRYPT_MAX_TEXTSIZE;
521 keyIndex++, bmpIndex += 2 )
522 {
523 bmpString[ bmpIndex ] = '\0';
524 bmpString[ bmpIndex + 1 ] = key[ keyIndex ];
525 }
526 ENSURES( keyIndex < CRYPT_MAX_TEXTSIZE );
527 bmpString[ bmpIndex++ ] = '\0';
528 bmpString[ bmpIndex++ ] = '\0';
529 ENSURES( dspMaxLen >= P12_BLOCKSIZE + P12_BLOCKSIZE + \
530 roundUp( bmpIndex, P12_BLOCKSIZE ) );
531
532 /* Set up the Unicode password string as the remaining bytes */
533 status = expandData( dspPtr, roundUp( bmpIndex, P12_BLOCKSIZE ),
534 bmpString, bmpIndex );
535 zeroise( bmpString, ( CRYPT_MAX_TEXTSIZE + 1 ) * 2 );
536 if( cryptStatusError( status ) )
537 {
538 zeroise( dsp, dspMaxLen );
539 return( status );
540 }
541 *dspLen = P12_BLOCKSIZE + P12_BLOCKSIZE + \
542 roundUp( bmpIndex, P12_BLOCKSIZE );
543
544 return( CRYPT_OK );
545 }
546
547 /* Perform PKCS #12 derivation */
548
549 CHECK_RETVAL STDC_NONNULL_ARG( ( 2 ) ) \
derivePKCS12(STDC_UNUSED void * dummy,INOUT MECHANISM_DERIVE_INFO * mechanismInfo)550 int derivePKCS12( STDC_UNUSED void *dummy,
551 INOUT MECHANISM_DERIVE_INFO *mechanismInfo )
552 {
553 HASH_FUNCTION_ATOMIC hashFunctionAtomic;
554 BYTE p12_DSP[ P12_DSPSIZE + 8 ];
555 BYTE p12_Ai[ CRYPT_MAX_HASHSIZE + 8 ], p12_B[ P12_BLOCKSIZE + 8 ];
556 BYTE *dataOutPtr = mechanismInfo->dataOut;
557 const BYTE *saltPtr = mechanismInfo->salt;
558 int dspLen, hashSize, keyIndex, i, iterationCount, status;
559
560 UNUSED_ARG( dummy );
561 assert( isWritePtr( mechanismInfo, sizeof( MECHANISM_DERIVE_INFO ) ) );
562
563 /* Clear return value */
564 memset( mechanismInfo->dataOut, 0, mechanismInfo->dataOutLength );
565
566 getHashAtomicParameters( mechanismInfo->hashAlgo, 0, &hashFunctionAtomic,
567 &hashSize );
568
569 /* Set up the diversifier/salt/password (DSP) string. The first byte of
570 the PKCS #12 salt acts as a diversifier so we separate this out from
571 the rest of the salt data */
572 status = initDSP( p12_DSP, P12_DSPSIZE, &dspLen, mechanismInfo->dataIn,
573 mechanismInfo->dataInLength, saltPtr + 1,
574 mechanismInfo->saltLength - 1, byteToInt( *saltPtr ) );
575 if( cryptStatusError( status ) )
576 return( status );
577
578 /* Produce enough blocks of output to fill the key */
579 for( keyIndex = 0, iterationCount = 0;
580 keyIndex < mechanismInfo->dataOutLength && \
581 iterationCount < FAILSAFE_ITERATIONS_MED;
582 keyIndex += hashSize, iterationCount++ )
583 {
584 const int noKeyBytes = \
585 ( mechanismInfo->dataOutLength - keyIndex > hashSize ) ? \
586 hashSize : mechanismInfo->dataOutLength - keyIndex;
587 int dspIndex;
588
589 /* Hash the keying material the required number of times to obtain the
590 output value */
591 hashFunctionAtomic( p12_Ai, CRYPT_MAX_HASHSIZE, p12_DSP, dspLen );
592 for( i = 1; i < mechanismInfo->iterations && \
593 i < FAILSAFE_ITERATIONS_MAX; i++ )
594 {
595 hashFunctionAtomic( p12_Ai, CRYPT_MAX_HASHSIZE,
596 p12_Ai, hashSize );
597 }
598 ENSURES( i < FAILSAFE_ITERATIONS_MAX );
599 memcpy( dataOutPtr + keyIndex, p12_Ai, noKeyBytes );
600
601 /* Update the input keying material for the next iteration by
602 adding the output value expanded to P12_BLOCKSIZE, to
603 P12_BLOCKSIZE-sized blocks of the salt/password portion of the
604 DSP string */
605 status = expandData( p12_B, P12_BLOCKSIZE, p12_Ai, hashSize );
606 if( cryptStatusError( status ) )
607 break;
608 for( dspIndex = P12_BLOCKSIZE; dspIndex < dspLen;
609 dspIndex += P12_BLOCKSIZE )
610 {
611 status = add64( p12_DSP + dspIndex, P12_BLOCKSIZE,
612 p12_B, P12_BLOCKSIZE );
613 if( cryptStatusError( status ) )
614 break;
615 }
616 }
617 ENSURES( iterationCount < FAILSAFE_ITERATIONS_MED );
618 zeroise( p12_DSP, P12_DSPSIZE );
619 zeroise( p12_Ai, CRYPT_MAX_HASHSIZE );
620 zeroise( p12_B, P12_BLOCKSIZE );
621 if( cryptStatusError( status ) )
622 {
623 zeroise( mechanismInfo->dataOut, mechanismInfo->dataOutLength );
624 return( status );
625 }
626
627 return( CRYPT_OK );
628 }
629 #endif /* USE_PKCS12 */
630
631 /****************************************************************************
632 * *
633 * SSL/TLS Key Derivation *
634 * *
635 ****************************************************************************/
636
637 #ifdef USE_SSL
638
639 /* Structure used to store TLS PRF state information */
640
641 typedef struct {
642 /* The hash functions and hash info */
643 HASH_FUNCTION_ATOMIC hashFunctionAtomic;
644 HASH_FUNCTION hashFunction;
645 int hashSize;
646
647 /* The initial hash state from prfInit() and the current hash state */
648 HASHINFO initialHashInfo, hashInfo;
649
650 /* The HMAC processed key and intermediate data value */
651 BUFFER( HMAC_DATASIZE, processedKeyLength ) \
652 BYTE processedKey[ HMAC_DATASIZE + 8 ];
653 BUFFER( HMAC_DATASIZE, hashSize ) \
654 BYTE hashA[ CRYPT_MAX_HASHSIZE + 8 ];
655 int processedKeyLength;
656 } TLS_PRF_INFO;
657
658 /* Perform SSL key derivation */
659
660 CHECK_RETVAL STDC_NONNULL_ARG( ( 2 ) ) \
deriveSSL(STDC_UNUSED void * dummy,INOUT MECHANISM_DERIVE_INFO * mechanismInfo)661 int deriveSSL( STDC_UNUSED void *dummy,
662 INOUT MECHANISM_DERIVE_INFO *mechanismInfo )
663 {
664 HASH_FUNCTION md5HashFunction, shaHashFunction;
665 HASHINFO hashInfo;
666 BYTE hash[ CRYPT_MAX_HASHSIZE + 8 ], counterData[ 16 + 8 ];
667 BYTE *dataOutPtr = mechanismInfo->dataOut;
668 int md5HashSize, shaHashSize, counter = 0, keyIndex, iterationCount;
669
670 UNUSED_ARG( dummy );
671 assert( isWritePtr( mechanismInfo, sizeof( MECHANISM_DERIVE_INFO ) ) );
672
673 /* Clear return value */
674 memset( mechanismInfo->dataOut, 0, mechanismInfo->dataOutLength );
675
676 getHashParameters( CRYPT_ALGO_MD5, 0, &md5HashFunction, &md5HashSize );
677 getHashParameters( CRYPT_ALGO_SHA1, 0, &shaHashFunction, &shaHashSize );
678
679 /* Produce enough blocks of output to fill the key */
680 for( keyIndex = 0, iterationCount = 0;
681 keyIndex < mechanismInfo->dataOutLength && \
682 iterationCount < FAILSAFE_ITERATIONS_MED;
683 keyIndex += md5HashSize, iterationCount++ )
684 {
685 const int noKeyBytes = \
686 ( mechanismInfo->dataOutLength - keyIndex > md5HashSize ) ? \
687 md5HashSize : mechanismInfo->dataOutLength - keyIndex;
688 int i;
689
690 /* Set up the counter data */
691 for( i = 0; i <= counter && i < 16; i++ )
692 counterData[ i ] = intToByte( 'A' + counter );
693 ENSURES( i < 16 );
694 counter++;
695
696 /* Calculate SHA1( 'A'/'BB'/'CCC'/... || keyData || salt ) */
697 shaHashFunction( hashInfo, NULL, 0, counterData, counter,
698 HASH_STATE_START );
699 shaHashFunction( hashInfo, NULL, 0, mechanismInfo->dataIn,
700 mechanismInfo->dataInLength, HASH_STATE_CONTINUE );
701 shaHashFunction( hashInfo, hash, CRYPT_MAX_HASHSIZE,
702 mechanismInfo->salt, mechanismInfo->saltLength,
703 HASH_STATE_END );
704
705 /* Calculate MD5( keyData || SHA1-hash ) */
706 md5HashFunction( hashInfo, NULL, 0, mechanismInfo->dataIn,
707 mechanismInfo->dataInLength, HASH_STATE_START );
708 md5HashFunction( hashInfo, hash, CRYPT_MAX_HASHSIZE,
709 hash, shaHashSize, HASH_STATE_END );
710
711 /* Copy the result to the output */
712 memcpy( dataOutPtr + keyIndex, hash, noKeyBytes );
713 }
714 ENSURES( iterationCount < FAILSAFE_ITERATIONS_MED );
715 zeroise( hashInfo, sizeof( HASHINFO ) );
716 zeroise( hash, CRYPT_MAX_HASHSIZE );
717
718 return( CRYPT_OK );
719 }
720
721 /* Initialise the TLS PRF */
722
723 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 4 ) ) \
tlsPrfInit(INOUT TLS_PRF_INFO * prfInfo,IN_BUFFER (keyLength)const void * key,IN_LENGTH_SHORT const int keyLength,IN_BUFFER (saltLength)const void * salt,IN_LENGTH_SHORT const int saltLength)724 static int tlsPrfInit( INOUT TLS_PRF_INFO *prfInfo,
725 IN_BUFFER( keyLength ) const void *key,
726 IN_LENGTH_SHORT const int keyLength,
727 IN_BUFFER( saltLength ) const void *salt,
728 IN_LENGTH_SHORT const int saltLength )
729 {
730 int status;
731
732 assert( isWritePtr( prfInfo, sizeof( TLS_PRF_INFO ) ) );
733 assert( isReadPtr( key, keyLength ) );
734 assert( isReadPtr( salt, saltLength ) );
735
736 REQUIRES( keyLength > 0 && keyLength < MAX_INTLENGTH_SHORT );
737 REQUIRES( saltLength > 0 && saltLength < MAX_INTLENGTH_SHORT );
738
739 /* Initialise the hash information with the keying info. This is
740 reused for any future hashing since it's constant */
741 status = prfInit( prfInfo->hashFunction, prfInfo->hashFunctionAtomic,
742 prfInfo->initialHashInfo, prfInfo->hashSize,
743 prfInfo->processedKey, HMAC_DATASIZE,
744 &prfInfo->processedKeyLength, key, keyLength );
745 if( cryptStatusError( status ) )
746 return( status );
747
748 /* Calculate A1 = HMAC( salt ) */
749 memcpy( prfInfo->hashInfo, prfInfo->initialHashInfo, sizeof( HASHINFO ) );
750 prfInfo->hashFunction( prfInfo->hashInfo, NULL, 0, salt, saltLength,
751 HASH_STATE_CONTINUE );
752 return( prfEnd( prfInfo->hashFunction, prfInfo->hashInfo,
753 prfInfo->hashSize, prfInfo->hashA,
754 CRYPT_MAX_HASHSIZE, prfInfo->processedKey,
755 prfInfo->processedKeyLength ) );
756 }
757
758 /* Implement one round of the TLS PRF */
759
760 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 3, 4 ) ) \
tlsPrfHash(INOUT_BUFFER_FIXED (outLength)BYTE * out,IN_LENGTH_SHORT const int outLength,INOUT TLS_PRF_INFO * prfInfo,IN_BUFFER (saltLength)const void * salt,IN_LENGTH_SHORT const int saltLength)761 static int tlsPrfHash( INOUT_BUFFER_FIXED( outLength ) BYTE *out,
762 IN_LENGTH_SHORT const int outLength,
763 INOUT TLS_PRF_INFO *prfInfo,
764 IN_BUFFER( saltLength ) const void *salt,
765 IN_LENGTH_SHORT const int saltLength )
766 {
767 HASHINFO hashInfo, AnHashInfo;
768 BYTE hash[ CRYPT_MAX_HASHSIZE + 8 ];
769 int i, status;
770
771 assert( isWritePtr( out, outLength ) );
772 assert( isWritePtr( prfInfo, sizeof( TLS_PRF_INFO ) ) );
773 assert( isReadPtr( salt, saltLength ) );
774
775 REQUIRES( outLength > 0 && outLength <= prfInfo->hashSize && \
776 outLength <= CRYPT_MAX_HASHSIZE );
777 REQUIRES( saltLength >= 13 && saltLength <= 512 );
778
779 /* The result of the hashing is XORd to the output so we don't clear the
780 return value like usual */
781
782 /* Calculate HMAC( An || salt ) */
783 memcpy( hashInfo, prfInfo->initialHashInfo, sizeof( HASHINFO ) );
784 prfInfo->hashFunction( hashInfo, NULL, 0, prfInfo->hashA,
785 prfInfo->hashSize, HASH_STATE_CONTINUE );
786 memcpy( AnHashInfo, hashInfo, sizeof( HASHINFO ) );
787 prfInfo->hashFunction( hashInfo, NULL, 0, salt, saltLength,
788 HASH_STATE_CONTINUE );
789 status = prfEnd( prfInfo->hashFunction, hashInfo, prfInfo->hashSize,
790 hash, CRYPT_MAX_HASHSIZE, prfInfo->processedKey,
791 prfInfo->processedKeyLength );
792 if( cryptStatusError( status ) )
793 {
794 zeroise( AnHashInfo, sizeof( HASHINFO ) );
795 zeroise( hashInfo, sizeof( HASHINFO ) );
796 zeroise( hash, CRYPT_MAX_HASHSIZE );
797 return( status );
798 }
799
800 /* Calculate An+1 = HMAC( An ) */
801 memcpy( hashInfo, AnHashInfo, sizeof( HASHINFO ) );
802 status = prfEnd( prfInfo->hashFunction, hashInfo, prfInfo->hashSize,
803 prfInfo->hashA, prfInfo->hashSize,
804 prfInfo->processedKey, prfInfo->processedKeyLength );
805 if( cryptStatusError( status ) )
806 {
807 zeroise( AnHashInfo, sizeof( HASHINFO ) );
808 zeroise( hashInfo, sizeof( HASHINFO ) );
809 zeroise( hash, CRYPT_MAX_HASHSIZE );
810 return( status );
811 }
812
813 /* Copy the result to the output */
814 for( i = 0; i < outLength; i++ )
815 out[ i ] ^= hash[ i ];
816
817 zeroise( AnHashInfo, sizeof( HASHINFO ) );
818 zeroise( hashInfo, sizeof( HASHINFO ) );
819 zeroise( hash, CRYPT_MAX_HASHSIZE );
820
821 return( CRYPT_OK );
822 }
823
824 /* Perform TLS key derivation. This implements the function described as
825 'PRF()' in the TLS spec */
826
827 CHECK_RETVAL STDC_NONNULL_ARG( ( 2 ) ) \
deriveTLS(STDC_UNUSED void * dummy,INOUT MECHANISM_DERIVE_INFO * mechanismInfo)828 int deriveTLS( STDC_UNUSED void *dummy,
829 INOUT MECHANISM_DERIVE_INFO *mechanismInfo )
830 {
831 TLS_PRF_INFO md5Info, shaInfo;
832 BYTE *dataOutPtr = mechanismInfo->dataOut;
833 const void *s1, *s2;
834 const int dataOutLength = mechanismInfo->dataOutLength;
835 const int sLen = ( mechanismInfo->dataInLength + 1 ) / 2;
836 int md5Index, shaIndex, iterationCount, status;
837
838 UNUSED_ARG( dummy );
839 assert( isWritePtr( mechanismInfo, sizeof( MECHANISM_DERIVE_INFO ) ) );
840
841 /* Clear return value */
842 memset( mechanismInfo->dataOut, 0, mechanismInfo->dataOutLength );
843
844 memset( &md5Info, 0, sizeof( TLS_PRF_INFO ) );
845 getHashAtomicParameters( CRYPT_ALGO_MD5, 0, &md5Info.hashFunctionAtomic,
846 &md5Info.hashSize );
847 getHashParameters( CRYPT_ALGO_MD5, 0, &md5Info.hashFunction, NULL );
848 memset( &shaInfo, 0, sizeof( TLS_PRF_INFO ) );
849 getHashAtomicParameters( CRYPT_ALGO_SHA1, 0, &shaInfo.hashFunctionAtomic,
850 &shaInfo.hashSize );
851 getHashParameters( CRYPT_ALGO_SHA1, 0, &shaInfo.hashFunction, NULL );
852
853 /* Find the start of the two halves of the keying info used for the
854 HMACing. The size of each half is given by ceil( dataInLength / 2 )
855 so there's a one-byte overlap if the input is an odd number of bytes
856 long */
857 s1 = mechanismInfo->dataIn;
858 s2 = ( BYTE * ) mechanismInfo->dataIn + \
859 ( mechanismInfo->dataInLength - sLen );
860
861 /* The two hash functions have different block sizes that would require
862 complex buffering to handle leftover bytes from SHA-1, a simpler
863 method is to zero the output data block and XOR in the values from
864 each hash mechanism using separate output location indices for MD5 and
865 SHA-1 */
866 memset( mechanismInfo->dataOut, 0, mechanismInfo->dataOutLength );
867
868 /* Initialise the TLS PRF and calculate A1 = HMAC( salt ) */
869 status = tlsPrfInit( &md5Info, s1, sLen, mechanismInfo->salt,
870 mechanismInfo->saltLength );
871 if( cryptStatusOK( status ) )
872 status = tlsPrfInit( &shaInfo, s2, sLen, mechanismInfo->salt,
873 mechanismInfo->saltLength );
874 if( cryptStatusError( status ) )
875 {
876 zeroise( &md5Info, sizeof( TLS_PRF_INFO ) );
877 zeroise( &shaInfo, sizeof( TLS_PRF_INFO ) );
878 return( status );
879 }
880
881 /* Produce enough blocks of output to fill the key. We use the MD5 hash
882 size as the loop increment since this produces the smaller output
883 block */
884 for( md5Index = shaIndex = 0, iterationCount = 0;
885 md5Index < dataOutLength && iterationCount < FAILSAFE_ITERATIONS_MED;
886 iterationCount++ )
887 {
888 const int md5NoKeyBytes = min( dataOutLength - md5Index, \
889 md5Info.hashSize );
890 const int shaNoKeyBytes = min( dataOutLength - shaIndex, \
891 shaInfo.hashSize );
892
893 status = tlsPrfHash( dataOutPtr + md5Index, md5NoKeyBytes,
894 &md5Info, mechanismInfo->salt,
895 mechanismInfo->saltLength );
896 if( cryptStatusError( status ) )
897 break;
898 if( shaNoKeyBytes > 0 )
899 {
900 /* Since the SHA-1 counter advances faster than the MD5 one we
901 can end up with zero bytes left to process for SHA-1 when MD5
902 is processing it's last block */
903 status = tlsPrfHash( dataOutPtr + shaIndex, shaNoKeyBytes,
904 &shaInfo, mechanismInfo->salt,
905 mechanismInfo->saltLength );
906 if( cryptStatusError( status ) )
907 break;
908 }
909
910 md5Index += md5NoKeyBytes;
911 shaIndex += shaNoKeyBytes;
912 }
913 ENSURES( iterationCount < FAILSAFE_ITERATIONS_MED );
914 zeroise( &md5Info, sizeof( TLS_PRF_INFO ) );
915 zeroise( &shaInfo, sizeof( TLS_PRF_INFO ) );
916 if( cryptStatusError( status ) )
917 {
918 zeroise( mechanismInfo->dataOut, mechanismInfo->dataOutLength );
919 return( status );
920 }
921
922 return( CRYPT_OK );
923 }
924
925 /* Perform TLS 1.2 key derivation using a gratuitously incompatible PRF
926 invented for TLS 1.2 */
927
928 CHECK_RETVAL STDC_NONNULL_ARG( ( 2 ) ) \
deriveTLS12(STDC_UNUSED void * dummy,INOUT MECHANISM_DERIVE_INFO * mechanismInfo)929 int deriveTLS12( STDC_UNUSED void *dummy,
930 INOUT MECHANISM_DERIVE_INFO *mechanismInfo )
931 {
932 TLS_PRF_INFO shaInfo;
933 BYTE *dataOutPtr = mechanismInfo->dataOut;
934 const int dataOutLength = mechanismInfo->dataOutLength;
935 int keyIndex, iterationCount, status;
936
937 UNUSED_ARG( dummy );
938 assert( isWritePtr( mechanismInfo, sizeof( MECHANISM_DERIVE_INFO ) ) );
939
940 /* Clear return value */
941 memset( mechanismInfo->dataOut, 0, mechanismInfo->dataOutLength );
942
943 memset( &shaInfo, 0, sizeof( TLS_PRF_INFO ) );
944 getHashAtomicParameters( mechanismInfo->hashAlgo,
945 mechanismInfo->hashParam,
946 &shaInfo.hashFunctionAtomic,
947 &shaInfo.hashSize );
948 getHashParameters( mechanismInfo->hashAlgo, mechanismInfo->hashParam,
949 &shaInfo.hashFunction, NULL );
950
951 /* Initialise the TLS PRF and calculate A1 = HMAC( salt ) */
952 status = tlsPrfInit( &shaInfo, mechanismInfo->dataIn,
953 mechanismInfo->dataInLength, mechanismInfo->salt,
954 mechanismInfo->saltLength );
955 if( cryptStatusError( status ) )
956 {
957 zeroise( &shaInfo, sizeof( TLS_PRF_INFO ) );
958 return( status );
959 }
960
961 /* Produce enough blocks of output to fill the key */
962 for( keyIndex = 0, iterationCount = 0;
963 keyIndex < dataOutLength && \
964 iterationCount < FAILSAFE_ITERATIONS_MED;
965 keyIndex += shaInfo.hashSize, iterationCount++ )
966 {
967 const int noKeyBytes = min( dataOutLength - keyIndex, \
968 shaInfo.hashSize );
969
970 status = tlsPrfHash( dataOutPtr + keyIndex, noKeyBytes, &shaInfo,
971 mechanismInfo->salt, mechanismInfo->saltLength );
972 if( cryptStatusError( status ) )
973 break;
974 }
975 ENSURES( iterationCount < FAILSAFE_ITERATIONS_MED );
976 zeroise( &shaInfo, sizeof( TLS_PRF_INFO ) );
977 if( cryptStatusError( status ) )
978 {
979 zeroise( mechanismInfo->dataOut, mechanismInfo->dataOutLength );
980 return( status );
981 }
982
983 return( CRYPT_OK );
984 }
985 #endif /* USE_SSL */
986
987 /****************************************************************************
988 * *
989 * PGP Key Derivation *
990 * *
991 ****************************************************************************/
992
993 #if defined( USE_PGP ) || defined( USE_PGPKEYS )
994
995 /* Implement one round of the OpenPGP PRF */
996
997 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 3, 4, 6, 8, 10 ) ) \
OUT_BUFFER_FIXED(outLength)998 static int pgpPrfHash( OUT_BUFFER_FIXED( outLength ) BYTE *out,
999 IN_LENGTH_HASH const int outLength,
1000 IN const HASH_FUNCTION hashFunction,
1001 INOUT TYPECAST( HASHINFO ) void *hashInfo,
1002 IN_LENGTH_HASH const int hashSize,
1003 IN_BUFFER( keyLength ) const void *key,
1004 IN_LENGTH_SHORT_MIN( 2 ) const int keyLength,
1005 IN_BUFFER( saltLength ) const void *salt,
1006 IN_LENGTH_FIXED( PGP_SALTSIZE ) const int saltLength,
1007 INOUT_LENGTH_Z long *byteCount,
1008 IN_RANGE( CRYPT_UNUSED, 1 ) const int preloadLength )
1009 {
1010 long count = *byteCount;
1011
1012 assert( isWritePtr( out, outLength ) );
1013 assert( isWritePtr( hashInfo, sizeof( HASHINFO ) ) );
1014 assert( isReadPtr( key, keyLength ) );
1015 assert( isReadPtr( salt, saltLength ) );
1016 assert( isWritePtr( byteCount, sizeof( int ) ) );
1017
1018 REQUIRES( hashFunction != NULL );
1019 REQUIRES( outLength == hashSize );
1020 REQUIRES( hashSize >= 16 && hashSize <= CRYPT_MAX_HASHSIZE );
1021 REQUIRES( keyLength >= 2 && keyLength <= MAX_INTLENGTH_SHORT );
1022 REQUIRES( saltLength == PGP_SALTSIZE );
1023 REQUIRES( preloadLength == CRYPT_UNUSED || \
1024 ( preloadLength >= 0 && preloadLength <= 1 ) );
1025 REQUIRES( count > 0 && count < MAX_INTLENGTH );
1026
1027 /* Clear return value */
1028 memset( out, 0, outLength );
1029
1030 /* If it's a subsequent round of hashing, preload the hash with zero
1031 bytes. If it's the first round (preloadLength == 0) it's handled
1032 specially below */
1033 if( preloadLength > 0 )
1034 {
1035 hashFunction( hashInfo, NULL, 0, ( const BYTE * ) "\x00\x00\x00\x00",
1036 preloadLength, HASH_STATE_START );
1037 }
1038
1039 /* Hash the next round of salt || password. Since we're being asked to
1040 stop once we've processed 'count' input bytes we implement an early-
1041 out mechanism that exits if the length of the item being hashed is
1042 sufficient to reach 'count' */
1043 if( count <= saltLength )
1044 {
1045 hashFunction( hashInfo, out, outLength, salt, count,
1046 HASH_STATE_END );
1047 *byteCount = 0;
1048
1049 return( CRYPT_OK );
1050 }
1051 hashFunction( hashInfo, NULL, 0, salt, saltLength,
1052 ( preloadLength == 0 ) ? HASH_STATE_START : \
1053 HASH_STATE_CONTINUE );
1054 count -= saltLength;
1055 if( count <= keyLength )
1056 {
1057 hashFunction( hashInfo, out, outLength, key, count, HASH_STATE_END );
1058 *byteCount = 0;
1059
1060 return( CRYPT_OK );
1061 }
1062 hashFunction( hashInfo, NULL, 0, key, keyLength, HASH_STATE_CONTINUE );
1063 count -= keyLength;
1064 ENSURES( count > 0 && count < MAX_INTLENGTH );
1065
1066 *byteCount = count;
1067 return( CRYPT_OK );
1068 }
1069
1070 /* Perform OpenPGP S2K key derivation */
1071
1072 CHECK_RETVAL STDC_NONNULL_ARG( ( 2 ) ) \
derivePGP(STDC_UNUSED void * dummy,INOUT MECHANISM_DERIVE_INFO * mechanismInfo)1073 int derivePGP( STDC_UNUSED void *dummy,
1074 INOUT MECHANISM_DERIVE_INFO *mechanismInfo )
1075 {
1076 HASH_FUNCTION hashFunction;
1077 HASHINFO hashInfo;
1078 long byteCount = ( long ) mechanismInfo->iterations << 6;
1079 long secondByteCount = 0;
1080 int hashSize, i, iterationCount, status = CRYPT_OK;
1081
1082 assert( isWritePtr( mechanismInfo, sizeof( MECHANISM_DERIVE_INFO ) ) );
1083
1084 REQUIRES( mechanismInfo->iterations >= 0 && \
1085 mechanismInfo->iterations <= MAX_KEYSETUP_HASHSPECIFIER );
1086 REQUIRES( byteCount >= 0 && byteCount < MAX_BUFFER_SIZE );
1087
1088 /* Clear return value */
1089 memset( mechanismInfo->dataOut, 0, mechanismInfo->dataOutLength );
1090
1091 /* Set up the hash parameters */
1092 getHashParameters( mechanismInfo->hashAlgo, 0, &hashFunction,
1093 &hashSize );
1094 memset( hashInfo, 0, sizeof( HASHINFO ) );
1095
1096 REQUIRES( mechanismInfo->dataOutLength < 2 * hashSize );
1097
1098 /* If it's a non-iterated hash or the count won't allow even a single
1099 pass over the 8-byte salt and password, adjust it to make sure that
1100 we run at least one full iteration */
1101 if( byteCount < PGP_SALTSIZE + mechanismInfo->dataInLength )
1102 byteCount = PGP_SALTSIZE + mechanismInfo->dataInLength;
1103
1104 /* If the hash output size is less than the required key size we run a
1105 second round of hashing after the first one to provide the total
1106 required amount of keying material */
1107 if( hashSize < mechanismInfo->dataOutLength )
1108 secondByteCount = byteCount;
1109
1110 /* Repeatedly hash the salt and password until we've met the byte count.
1111 In effect this hashes:
1112
1113 salt || password || salt || password || ...
1114
1115 until we've processed 'byteCount' bytes of data.
1116
1117 This processing is complicated by the ridiculous number of iterations
1118 of processing specified by some versions of GPG (see the long comment
1119 in misc/consts.h), so that we can no longer employ the standard
1120 FAILSAFE_ITERATIONS_MAX as a failsafe value but have to use a
1121 multiple of that. There's no clean way to do this, the following
1122 hardcodes an upper bound that'll have to be varied based on what
1123 MAX_KEYSETUP_HASHSPECIFIER is set to */
1124 #define GPG_FAILSAFE_ITERATIONS_MAX ( 3 * FAILSAFE_ITERATIONS_MAX )
1125 static_assert( MAX_KEYSETUP_HASHSPECIFIER < GPG_FAILSAFE_ITERATIONS_MAX,
1126 "Failsafe value for PGP hashing" );
1127 for( i = 0, iterationCount = 0;
1128 byteCount > 0 && cryptStatusOK( status ) && \
1129 iterationCount < GPG_FAILSAFE_ITERATIONS_MAX;
1130 i++, iterationCount++ )
1131 {
1132 status = pgpPrfHash( mechanismInfo->dataOut,
1133 hashSize, hashFunction, hashInfo, hashSize,
1134 mechanismInfo->dataIn,
1135 mechanismInfo->dataInLength,
1136 mechanismInfo->salt,
1137 mechanismInfo->saltLength, &byteCount,
1138 ( i <= 0 ) ? 0 : CRYPT_UNUSED );
1139 }
1140 ENSURES( iterationCount < GPG_FAILSAFE_ITERATIONS_MAX );
1141 if( cryptStatusOK( status ) && secondByteCount > 0 )
1142 {
1143 for( i = 0, iterationCount = 0;
1144 secondByteCount > 0 && cryptStatusOK( status ) && \
1145 iterationCount < GPG_FAILSAFE_ITERATIONS_MAX;
1146 i++, iterationCount++ )
1147 {
1148 status = pgpPrfHash( ( BYTE * ) mechanismInfo->dataOut + hashSize,
1149 hashSize, hashFunction, hashInfo, hashSize,
1150 mechanismInfo->dataIn,
1151 mechanismInfo->dataInLength,
1152 mechanismInfo->salt,
1153 mechanismInfo->saltLength, &secondByteCount,
1154 ( i <= 0 ) ? 1 : CRYPT_UNUSED );
1155 }
1156 ENSURES( iterationCount < GPG_FAILSAFE_ITERATIONS_MAX );
1157 }
1158 zeroise( hashInfo, sizeof( HASHINFO ) );
1159 if( cryptStatusError( status ) )
1160 {
1161 zeroise( mechanismInfo->dataOut, mechanismInfo->dataOutLength );
1162 return( status );
1163 }
1164
1165 return( CRYPT_OK );
1166 }
1167 #endif /* USE_PGP || USE_PGPKEYS */
1168
1169 /****************************************************************************
1170 * *
1171 * Misc Key Derivation *
1172 * *
1173 ****************************************************************************/
1174
1175 #ifdef USE_CMP
1176
1177 /* Perform CMP/Entrust key derivation */
1178
1179 CHECK_RETVAL STDC_NONNULL_ARG( ( 2 ) ) \
deriveCMP(STDC_UNUSED void * dummy,INOUT MECHANISM_DERIVE_INFO * mechanismInfo)1180 int deriveCMP( STDC_UNUSED void *dummy,
1181 INOUT MECHANISM_DERIVE_INFO *mechanismInfo )
1182 {
1183 HASH_FUNCTION_ATOMIC hashFunctionAtomic;
1184 HASH_FUNCTION hashFunction;
1185 HASHINFO hashInfo;
1186 int hashSize, iterations;
1187
1188 UNUSED_ARG( dummy );
1189 assert( isWritePtr( mechanismInfo, sizeof( MECHANISM_DERIVE_INFO ) ) );
1190
1191 /* Clear return value */
1192 memset( mechanismInfo->dataOut, 0, mechanismInfo->dataOutLength );
1193
1194 /* Calculate SHA1( password || salt ) */
1195 getHashAtomicParameters( mechanismInfo->hashAlgo, 0,
1196 &hashFunctionAtomic, &hashSize );
1197 getHashParameters( mechanismInfo->hashAlgo, 0, &hashFunction, NULL );
1198 hashFunction( hashInfo, NULL, 0, mechanismInfo->dataIn,
1199 mechanismInfo->dataInLength, HASH_STATE_START );
1200 hashFunction( hashInfo, mechanismInfo->dataOut,
1201 mechanismInfo->dataOutLength, mechanismInfo->salt,
1202 mechanismInfo->saltLength, HASH_STATE_END );
1203
1204 /* Iterate the hashing the remaining number of times. We start the
1205 count at one since the first iteration has already been performed */
1206 for( iterations = 1; iterations < mechanismInfo->iterations && \
1207 iterations < FAILSAFE_ITERATIONS_MAX; iterations++ )
1208 {
1209 hashFunctionAtomic( mechanismInfo->dataOut,
1210 mechanismInfo->dataOutLength,
1211 mechanismInfo->dataOut, hashSize );
1212 }
1213 ENSURES( iterations < FAILSAFE_ITERATIONS_MAX );
1214 zeroise( hashInfo, sizeof( HASHINFO ) );
1215
1216 return( CRYPT_OK );
1217 }
1218 #endif /* USE_CMP */
1219