]> git.saurik.com Git - apple/security.git/blob - libsecurity_apple_csp/lib/pkcs12Derive.cpp
Security-55471.14.tar.gz
[apple/security.git] / libsecurity_apple_csp / lib / pkcs12Derive.cpp
1 /*
2 * Copyright (c) 2003 Apple Computer, Inc. All Rights Reserved.
3 *
4 * The contents of this file constitute Original Code as defined in and are
5 * subject to the Apple Public Source License Version 1.2 (the 'License').
6 * You may not use this file except in compliance with the License. Please
7 * obtain a copy of the License at http://www.apple.com/publicsource and
8 * read it before using this file.
9 *
10 * This Original Code and all software distributed under the License are
11 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
12 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
13 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
14 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
15 * Please see the License for the specific language governing rights and
16 * limitations under the License.
17 */
18 /*
19 * pkcs12Derive.cpp - PKCS12 PBE routine
20 *
21 * Created 2/28/03 by Doug Mitchell.
22 */
23
24 #include <Security/cssmapple.h>
25 #include <openssl/bn.h>
26 #include <pbkdDigest.h>
27
28 #include "pkcs12Derive.h"
29 #include "AppleCSPUtils.h"
30 #include "AppleCSPContext.h"
31
32 #include <string.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <assert.h>
36 #include <security_asn1/SecNssCoder.h>
37
38 #include <CoreFoundation/CoreFoundation.h>
39
40 /* specify which flavor of bits to generate */
41 typedef enum {
42 PBE_ID_Key = 1,
43 PBE_ID_IV = 2,
44 PBE_ID_MAC = 3
45 } P12_PBE_ID;
46
47 /*
48 * Create a "string" (in the loose p12 notation) of specified length
49 * from the concatention of copies of the specified input string.
50 */
51 static unsigned char *p12StrCat(
52 const unsigned char *inStr,
53 unsigned inStrLen,
54 SecNssCoder &coder,
55 unsigned outLen,
56 unsigned char *outStr = NULL) // if not present, we malloc
57 {
58 if(outStr == NULL) {
59 outStr = (unsigned char *)coder.malloc(outLen);
60 }
61 unsigned toMove = outLen;
62 unsigned char *outp = outStr;
63 while(toMove) {
64 unsigned thisMove = inStrLen;
65 if(thisMove > toMove) {
66 thisMove = toMove;
67 }
68 memmove(outp, inStr, thisMove);
69 toMove -= thisMove;
70 outp += thisMove;
71 }
72 return outStr;
73 }
74
75 /*
76 * PBE generator per PKCS12 v.1 section B.2.
77 */
78 static CSSM_RETURN p12PbeGen(
79 const CSSM_DATA &pwd, // unicode, double null terminated
80 const uint8 *salt,
81 unsigned saltLen,
82 unsigned iterCount,
83 P12_PBE_ID pbeId,
84 CSSM_ALGORITHMS hashAlg, // MS5 or SHA1 only
85 SecNssCoder &coder, // for temp allocs
86 /* result goes here, mallocd by caller */
87 uint8 *outbuf,
88 unsigned outbufLen)
89 {
90 CSSM_RETURN ourRtn = CSSM_OK;
91 unsigned unipassLen = (unsigned)pwd.Length;
92 unsigned char *unipass = pwd.Data;
93 int irtn;
94
95 /*
96 * all variables of the form p12_<XXX> represent <XXX> from the
97 * PKCS12 spec. E.g., p12_u is u, the length of the digest output.
98 * Only difference here is: all of our sizes are in BYTES, not
99 * bits.
100 */
101 unsigned p12_r = iterCount;
102 unsigned p12_n = outbufLen;
103
104 unsigned p12_u; // hash output size
105 unsigned p12_v; // hash block size
106 unsigned char *p12_P = NULL; // catted passwords
107 unsigned char *p12_S = NULL; // catted salts
108
109 switch(hashAlg) {
110 case CSSM_ALGID_MD5:
111 p12_u = kMD5DigestSize;
112 p12_v = kMD5BlockSize;
113 break;
114 case CSSM_ALGID_SHA1:
115 p12_u = kSHA1DigestSize;
116 p12_v = kSHA1BlockSize;
117 break;
118 default:
119 return CSSMERR_CSP_INVALID_ALGORITHM;
120 }
121
122 /*
123 * 1. Construct a string, D (the diversifier), by
124 * concatenating v/8 copies of ID.
125 */
126 unsigned char *p12_D = NULL; // diversifier
127 p12_D = (unsigned char *)coder.malloc(p12_v);
128 for(unsigned dex=0; dex<p12_v; dex++) {
129 p12_D[dex] = (unsigned char)pbeId;
130 }
131
132 /*
133 * 2. Concatenate copies of the salt together to create
134 * a string S of length v * ceil(s/v) bits (the final copy
135 * of the salt may be truncated to create S). Note that if
136 * the salt is the empty string, then so is S.
137 */
138 unsigned p12_Slen = p12_v * ((saltLen + p12_v - 1) / p12_v);
139 if(p12_Slen) {
140 p12_S = p12StrCat(salt, saltLen, coder, p12_Slen);
141 }
142
143
144 /*
145 * 3. Concatenate copies of the password together to create
146 * a string P of length v * ceil(p/v) bits (the final copy of
147 * the password may be truncated to create P). Note that
148 * if the password is the empty string, then so is P.
149 */
150 unsigned p12_Plen = p12_v * ((unipassLen + p12_v - 1) / p12_v);
151 if(p12_Plen) {
152 p12_P = p12StrCat(unipass, unipassLen, coder, p12_Plen);
153 }
154
155 /*
156 * 4. Set I= S||P to be the concatenation of S and P.
157 */
158 unsigned char *p12_I =
159 (unsigned char *)coder.malloc(p12_Slen + p12_Plen);
160 memmove(p12_I, p12_S, p12_Slen);
161 if(p12_Plen) {
162 memmove(p12_I + p12_Slen, p12_P, p12_Plen);
163 }
164
165 /*
166 * 5. Set c = ceil(n/u).
167 */
168 unsigned p12_c = (p12_n + p12_u - 1) / p12_u;
169
170 /* allocate c hash-output-size bufs */
171 unsigned char *p12_A = (unsigned char *)coder.malloc(p12_c * p12_u);
172
173 /* one reusable hash object */
174 DigestCtx ourDigest;
175 DigestCtx *hashHand = &ourDigest;
176
177 /* reused inside the loop */
178 unsigned char *p12_B = (unsigned char *)coder.malloc(p12_v + 1);
179 BIGNUM *Ij = BN_new();
180 BIGNUM *Bpl1 = BN_new();
181
182 /*
183 * 6. For i=1, 2, ..., p12_c, do the following:
184 */
185 for(unsigned p12_i=0; p12_i<p12_c; p12_i++) {
186 unsigned char *p12_AsubI = p12_A + (p12_i * p12_u);
187
188 /*
189 * a) Set A[i] = H**r(D||I). (i.e. the rth hash of D||I,
190 * H(H(H(...H(D||I))))
191 */
192 irtn = DigestCtxInit(hashHand, hashAlg);
193 if(!irtn) {
194 ourRtn = CSSMERR_CSP_INTERNAL_ERROR;
195 break;
196 }
197 DigestCtxUpdate(hashHand, p12_D, p12_v);
198 DigestCtxUpdate(hashHand, p12_I, p12_Slen + p12_Plen);
199 DigestCtxFinal(hashHand, p12_AsubI);
200
201 for(unsigned iter=1; iter<p12_r; iter++) {
202 irtn = DigestCtxInit(hashHand, hashAlg);
203 if(!irtn) {
204 ourRtn = CSSMERR_CSP_INTERNAL_ERROR;
205 break;
206 }
207 DigestCtxUpdate(hashHand, p12_AsubI, p12_u);
208 DigestCtxFinal(hashHand, p12_AsubI);
209 }
210
211 /*
212 * b) Concatenate copies of A[i] to create a string B of
213 * length v bits (the final copy of A[i]i may be truncated
214 * to create B).
215 */
216 p12StrCat(p12_AsubI, p12_u, coder, p12_v, p12_B);
217
218 /*
219 * c) Treating I as a concatenation I[0], I[1], ...,
220 * I[k-1] of v-bit blocks, where k = ceil(s/v) + ceil(p/v),
221 * modify I by setting I[j]=(I[j]+B+1) mod (2 ** v)
222 * for each j.
223 *
224 * Copied from PKCS12_key_gen_uni() from openssl...
225 */
226 /* Work out B + 1 first then can use B as tmp space */
227 BN_bin2bn (p12_B, p12_v, Bpl1);
228 BN_add_word (Bpl1, 1);
229 unsigned Ilen = p12_Slen + p12_Plen;
230
231 for (unsigned j = 0; j < Ilen; j+=p12_v) {
232 BN_bin2bn (p12_I + j, p12_v, Ij);
233 BN_add (Ij, Ij, Bpl1);
234 BN_bn2bin (Ij, p12_B);
235 unsigned Ijlen = BN_num_bytes (Ij);
236 /* If more than 2^(v*8) - 1 cut off MSB */
237 if (Ijlen > p12_v) {
238 BN_bn2bin (Ij, p12_B);
239 memcpy (p12_I + j, p12_B + 1, p12_v);
240 /* If less than v bytes pad with zeroes */
241 } else if (Ijlen < p12_v) {
242 memset(p12_I + j, 0, p12_v - Ijlen);
243 BN_bn2bin(Ij, p12_I + j + p12_v - Ijlen);
244 } else BN_bn2bin (Ij, p12_I + j);
245 }
246 }
247
248 if(ourRtn == CSSM_OK) {
249 /*
250 * 7. Concatenate A[1], A[2], ..., A[c] together to form a
251 * pseudo-random bit string, A.
252 *
253 * 8. Use the first n bits of A as the output of this entire
254 * process.
255 */
256 memmove(outbuf, p12_A, outbufLen);
257 }
258
259 /* clear all these strings */
260 if(p12_D) {
261 memset(p12_D, 0, p12_v);
262 }
263 if(p12_S) {
264 memset(p12_S, 0, p12_Slen);
265 }
266 if(p12_P) {
267 memset(p12_P, 0, p12_Plen);
268 }
269 if(p12_I) {
270 memset(p12_I, 0, p12_Slen + p12_Plen);
271 }
272 if(p12_A) {
273 memset(p12_A, 0, p12_c * p12_u);
274 }
275 if(p12_B) {
276 memset(p12_B, 0, p12_v);
277 }
278 if(hashHand) {
279 DigestCtxFree(hashHand);
280 }
281 BN_free(Bpl1);
282 BN_free(Ij);
283 return ourRtn;
284 }
285
286 /*
287 * Public P12 derive key function, called out from
288 * AppleCSPSession::DeriveKey()
289 *
290 * On input:
291 * ---------
292 * Context parameters:
293 * Salt
294 * Iteration Count
295 * CSSM_CRYPTO_DATA.Param - Unicode passphrase, double-NULL terminated
296 * Algorithm - CSSM_ALGID_PKCS12_PBE_{ENCR,MAC}
297 * Passed explicitly from DeriveKey():
298 * CSSM_DATA Param - IN/OUT - optional IV - caller mallocs space to
299 * tell us to generate an IV. The param itself is not
300 * optional; the presence or absence of allocated data in it
301 * is our IV indicator (present/absent as well as size)
302 * KeyData - mallocd by caller, we fill in keyData->Length bytes
303 */
304 void DeriveKey_PKCS12 (
305 const Context &context,
306 AppleCSPSession &session,
307 const CssmData &Param, // other's public key
308 CSSM_DATA *keyData) // mallocd by caller
309 // we fill in keyData->Length bytes
310 {
311 SecNssCoder tmpCoder;
312
313 /*
314 * According to the spec, both passphrase and salt are optional.
315 * Get them from context if they're present. In practical terms
316 * the user really should supply a passphrase either in the
317 * seed attribute (as a Unicode passphrase) or as the BaseKey
318 * as a CSSM_ALGID_SECURE_PASSPHRASE key).
319 */
320 CSSM_DATA pwd = {0, NULL};
321 CSSM_DATA appPwd = {0, NULL};
322 CssmCryptoData *cryptData =
323 context.get<CssmCryptoData>(CSSM_ATTRIBUTE_SEED);
324 if((cryptData != NULL) && (cryptData->Param.Length != 0)) {
325 appPwd = cryptData->Param;
326 }
327 else {
328 /* Get pwd from base key */
329 CssmKey *passKey = context.get<CssmKey>(CSSM_ATTRIBUTE_KEY);
330 if (passKey != NULL) {
331 AppleCSPContext::symmetricKeyBits(context, session,
332 CSSM_ALGID_SECURE_PASSPHRASE, CSSM_KEYUSE_DERIVE,
333 appPwd.Data, appPwd.Length);
334 }
335 }
336 if(appPwd.Data) {
337 /*
338 * The incoming passphrase is a UTF8 encoded enternal representation
339 * of a CFString. Convert to CFString and obtain the unicode characters
340 * from the string.
341 */
342 CFDataRef cfData = CFDataCreate(NULL, appPwd.Data, appPwd.Length);
343 CFStringRef cfStr = CFStringCreateFromExternalRepresentation(NULL,
344 cfData, kCFStringEncodingUTF8);
345 if (cfData)
346 CFRelease(cfData);
347 if(cfStr == NULL) {
348 CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_SEED);
349 }
350
351 /* convert unicode to chars with an extra double-NULL */
352 CFIndex len = CFStringGetLength(cfStr);
353 tmpCoder.allocItem(pwd, sizeof(UniChar) * (len + 1));
354 unsigned char *cp = pwd.Data;
355 UniChar uc = 0;
356 for(CFIndex dex=0; dex<len; dex++) {
357 uc = CFStringGetCharacterAtIndex(cfStr, dex);
358 *cp++ = uc >> 8;
359 *cp++ = uc & 0xff;
360 }
361 /* CFString tends to include a NULL at the end; add it if it's not there */
362 if(uc == 0) {
363 if(pwd.Length < 2) {
364 CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_SEED);
365 }
366 pwd.Length -= 2;
367 }
368 else {
369 *cp++ = 0;
370 *cp++ = 0;
371 }
372 if (cfStr)
373 CFRelease(cfStr);
374 }
375
376 /* salt from context */
377 uint32 saltLen = 0;
378 uint8 *salt = NULL;
379 CssmData *csalt = context.get<CssmData>(CSSM_ATTRIBUTE_SALT);
380 if(csalt) {
381 salt = csalt->Data;
382 saltLen = (uint32)csalt->Length;
383 }
384
385 /*
386 * Iteration count, from context, required.
387 * The spec's ASN1 definition says this is optional with a default
388 * of one but that's a BER encode/decode issue. Here we require
389 * a nonzero value.
390 */
391 uint32 iterCount = context.getInt(CSSM_ATTRIBUTE_ITERATION_COUNT,
392 CSSMERR_CSP_MISSING_ATTR_ITERATION_COUNT);
393 if(iterCount == 0) {
394 CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_ITERATION_COUNT);
395 }
396
397 /*
398 * Algorithm determines which of {PBE_ID_Key,PBE_ID_MAC} we now
399 * generate. We'll also do an optional PBE_ID_IV later.
400 */
401 P12_PBE_ID pbeId = PBE_ID_Key;
402 switch(context.algorithm()) {
403 case CSSM_ALGID_PKCS12_PBE_ENCR:
404 pbeId = PBE_ID_Key;
405 break;
406 case CSSM_ALGID_PKCS12_PBE_MAC:
407 pbeId = PBE_ID_MAC;
408 break;
409 default:
410 /* really should not be here */
411 assert(0);
412 CssmError::throwMe(CSSMERR_CSP_INTERNAL_ERROR);
413 }
414
415 /* Go */
416 CSSM_RETURN crtn = p12PbeGen(pwd,
417 salt, saltLen,
418 iterCount,
419 pbeId,
420 CSSM_ALGID_SHA1, // all we support for now
421 tmpCoder,
422 keyData->Data,
423 (unsigned)keyData->Length);
424 if(crtn) {
425 CssmError::throwMe(crtn);
426 }
427
428 /*
429 * Optional IV - makes no sense if we just did PBE_ID_MAC, but why
430 * bother restricting?
431 */
432 if(Param.Data) {
433 crtn = p12PbeGen(pwd,
434 salt, saltLen,
435 iterCount,
436 PBE_ID_IV,
437 CSSM_ALGID_SHA1, // all we support for now
438 tmpCoder,
439 Param.Data,
440 (unsigned)Param.Length);
441 if(crtn) {
442 CssmError::throwMe(crtn);
443 }
444 }
445 }
446