pkcs8: Initialize salt and IV properly.
[strongswan.git] / src / libstrongswan / plugins / pkcs8 / pkcs8_builder.c
1 /*
2 * Copyright (C) 2012 Tobias Brunner
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include "pkcs8_builder.h"
17
18 #include <debug.h>
19 #include <asn1/oid.h>
20 #include <asn1/asn1.h>
21 #include <asn1/asn1_parser.h>
22 #include <credentials/keys/private_key.h>
23
24 /**
25 * ASN.1 definition of a privateKeyInfo structure
26 */
27 static const asn1Object_t pkinfoObjects[] = {
28 { 0, "privateKeyInfo", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
29 { 1, "version", ASN1_INTEGER, ASN1_BODY }, /* 1 */
30 { 1, "privateKeyAlgorithm", ASN1_EOC, ASN1_RAW }, /* 2 */
31 { 1, "privateKey", ASN1_OCTET_STRING, ASN1_BODY }, /* 3 */
32 { 1, "attributes", ASN1_CONTEXT_C_0, ASN1_OPT }, /* 4 */
33 { 1, "end opt", ASN1_EOC, ASN1_END }, /* 5 */
34 { 0, "exit", ASN1_EOC, ASN1_EXIT }
35 };
36 #define PKINFO_PRIVATE_KEY_ALGORITHM 2
37 #define PKINFO_PRIVATE_KEY 3
38
39 /**
40 * Load a generic private key from an ASN.1 encoded blob
41 */
42 static private_key_t *parse_private_key(chunk_t blob)
43 {
44 asn1_parser_t *parser;
45 chunk_t object, params = chunk_empty;
46 int objectID;
47 private_key_t *key = NULL;
48 key_type_t type = KEY_ANY;
49
50 parser = asn1_parser_create(pkinfoObjects, blob);
51 parser->set_flags(parser, FALSE, TRUE);
52
53 while (parser->iterate(parser, &objectID, &object))
54 {
55 switch (objectID)
56 {
57 case PKINFO_PRIVATE_KEY_ALGORITHM:
58 {
59 int oid = asn1_parse_algorithmIdentifier(object,
60 parser->get_level(parser) + 1, &params);
61
62 switch (oid)
63 {
64 case OID_RSA_ENCRYPTION:
65 type = KEY_RSA;
66 break;
67 case OID_EC_PUBLICKEY:
68 type = KEY_ECDSA;
69 break;
70 default:
71 /* key type not supported */
72 goto end;
73 }
74 break;
75 }
76 case PKINFO_PRIVATE_KEY:
77 {
78 DBG2(DBG_ASN, "-- > --");
79 if (params.ptr)
80 {
81 key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY,
82 type, BUILD_BLOB_ALGID_PARAMS,
83 params, BUILD_BLOB_ASN1_DER,
84 object, BUILD_END);
85 }
86 else
87 {
88 key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY,
89 type, BUILD_BLOB_ASN1_DER, object,
90 BUILD_END);
91 }
92 DBG2(DBG_ASN, "-- < --");
93 break;
94 }
95 }
96 }
97
98 end:
99 parser->destroy(parser);
100 return key;
101 }
102
103 /**
104 * Verify padding of decrypted blob.
105 * Length of blob is adjusted accordingly.
106 */
107 static bool verify_padding(chunk_t *blob)
108 {
109 u_int8_t padding, count;
110
111 padding = count = blob->ptr[blob->len - 1];
112 if (padding > 8)
113 {
114 return FALSE;
115 }
116 for (; blob->len && count; --blob->len, --count)
117 {
118 if (blob->ptr[blob->len - 1] != padding)
119 {
120 return FALSE;
121 }
122 }
123 return TRUE;
124 }
125
126 /**
127 * Prototype for key derivation functions.
128 */
129 typedef void (*kdf_t)(void *generator, chunk_t password, chunk_t salt,
130 u_int64_t iterations, chunk_t key);
131
132 /**
133 * Try to decrypt the given blob with multiple passwords using the given
134 * key derivation function. keymat is where the kdf function writes the key
135 * to, key and iv point to the actual keys and initialization vectors resp.
136 */
137 static private_key_t *decrypt_private_key(chunk_t blob,
138 encryption_algorithm_t encr, size_t key_len, kdf_t kdf,
139 void *generator, chunk_t salt, u_int64_t iterations,
140 chunk_t keymat, chunk_t key, chunk_t iv)
141 {
142 enumerator_t *enumerator;
143 shared_key_t *shared;
144 crypter_t *crypter;
145 private_key_t *private_key = NULL;
146
147 crypter = lib->crypto->create_crypter(lib->crypto, encr, key_len);
148 if (!crypter)
149 {
150 DBG1(DBG_ASN, " %N encryption algorithm not available",
151 encryption_algorithm_names, encr);
152 return NULL;
153 }
154 if (blob.len % crypter->get_block_size(crypter))
155 {
156 DBG1(DBG_ASN, " data size is not a multiple of block size");
157 crypter->destroy(crypter);
158 return NULL;
159 }
160
161 enumerator = lib->credmgr->create_shared_enumerator(lib->credmgr,
162 SHARED_PRIVATE_KEY_PASS, NULL, NULL);
163 while (enumerator->enumerate(enumerator, &shared, NULL, NULL))
164 {
165 chunk_t decrypted;
166
167 kdf(generator, shared->get_key(shared), salt, iterations, keymat);
168
169 crypter->set_key(crypter, key);
170 crypter->decrypt(crypter, blob, iv, &decrypted);
171 if (verify_padding(&decrypted))
172 {
173 private_key = parse_private_key(decrypted);
174 if (private_key)
175 {
176 chunk_clear(&decrypted);
177 break;
178 }
179 }
180 chunk_free(&decrypted);
181 }
182 enumerator->destroy(enumerator);
183 crypter->destroy(crypter);
184
185 return private_key;
186 }
187
188 /**
189 * Function F of PBKDF2
190 */
191 static void pbkdf2_f(chunk_t block, prf_t *prf, chunk_t seed,
192 u_int64_t iterations)
193 {
194 chunk_t u;
195 u_int64_t i;
196
197 u = chunk_alloca(prf->get_block_size(prf));
198 prf->get_bytes(prf, seed, u.ptr);
199 memcpy(block.ptr, u.ptr, block.len);
200
201 for (i = 1; i < iterations; i++)
202 {
203 prf->get_bytes(prf, u, u.ptr);
204 memxor(block.ptr, u.ptr, block.len);
205 }
206 }
207
208 /**
209 * PBKDF2 key derivation function
210 */
211 static void pbkdf2(prf_t *prf, chunk_t password, chunk_t salt,
212 u_int64_t iterations, chunk_t key)
213 {
214 chunk_t keymat, block, seed;
215 size_t blocks;
216 u_int32_t i = 0, *ni;
217
218 prf->set_key(prf, password);
219
220 block.len = prf->get_block_size(prf);
221 blocks = (key.len - 1) / block.len + 1;
222 keymat = chunk_alloca(blocks * block.len);
223
224 seed = chunk_cata("cc", salt, chunk_from_thing(i));
225 ni = (u_int32_t*)(seed.ptr + salt.len);
226
227 for (; i < blocks; i++)
228 {
229 *ni = htonl(i + 1);
230 block.ptr = keymat.ptr + (i * block.len);
231 pbkdf2_f(block, prf, seed, iterations);
232 }
233
234 memcpy(key.ptr, keymat.ptr, key.len);
235 }
236
237 /**
238 * Decrypt an encrypted PKCS#8 encoded private key according to PBES2
239 */
240 static private_key_t *decrypt_private_key_pbes2(chunk_t blob,
241 encryption_algorithm_t encr, size_t key_len,
242 chunk_t iv, pseudo_random_function_t prf_func,
243 chunk_t salt, u_int64_t iterations)
244 {
245 private_key_t *private_key;
246 prf_t *prf;
247 chunk_t key;
248
249 prf = lib->crypto->create_prf(lib->crypto, prf_func);
250 if (!prf)
251 {
252 DBG1(DBG_ASN, " %N prf algorithm not available",
253 pseudo_random_function_names, prf_func);
254 return NULL;
255 }
256
257 key = chunk_alloca(key_len);
258
259 private_key = decrypt_private_key(blob, encr, key_len, (kdf_t)pbkdf2, prf,
260 salt, iterations, key, key, iv);
261
262 prf->destroy(prf);
263 return private_key;
264 }
265
266 /**
267 * PBKDF1 key derivation function
268 */
269 static void pbkdf1(hasher_t *hasher, chunk_t password, chunk_t salt,
270 u_int64_t iterations, chunk_t key)
271 {
272 chunk_t hash;
273 u_int64_t i;
274
275 hash = chunk_alloca(hasher->get_hash_size(hasher));
276 hasher->get_hash(hasher, password, NULL);
277 hasher->get_hash(hasher, salt, hash.ptr);
278
279 for (i = 1; i < iterations; i++)
280 {
281 hasher->get_hash(hasher, hash, hash.ptr);
282 }
283
284 memcpy(key.ptr, hash.ptr, key.len);
285 }
286
287 /**
288 * Decrypt an encrypted PKCS#8 encoded private key according to PBES1
289 */
290 static private_key_t *decrypt_private_key_pbes1(chunk_t blob,
291 encryption_algorithm_t encr, size_t key_len,
292 hash_algorithm_t hash, chunk_t salt,
293 u_int64_t iterations)
294 {
295 private_key_t *private_key = NULL;
296 hasher_t *hasher = NULL;
297 chunk_t keymat, key, iv;
298
299 hasher = lib->crypto->create_hasher(lib->crypto, hash);
300 if (!hasher)
301 {
302 DBG1(DBG_ASN, " %N hash algorithm not available",
303 hash_algorithm_names, hash);
304 goto end;
305 }
306 if (hasher->get_hash_size(hasher) < key_len)
307 {
308 goto end;
309 }
310
311 keymat = chunk_alloca(key_len * 2);
312 key.len = key_len;
313 key.ptr = keymat.ptr;
314 iv.len = key_len;
315 iv.ptr = keymat.ptr + key_len;
316
317 private_key = decrypt_private_key(blob, encr, key_len, (kdf_t)pbkdf1,
318 hasher, salt, iterations, keymat,
319 key, iv);
320
321 end:
322 DESTROY_IF(hasher);
323 return private_key;
324 }
325
326 /**
327 * Parse an ASN1_INTEGER to a u_int64_t.
328 */
329 static u_int64_t parse_asn1_integer_uint64(chunk_t blob)
330 {
331 u_int64_t val = 0;
332 int i;
333
334 for (i = 0; i < blob.len; i++)
335 { /* if it is longer than 8 bytes, we just use the 8 LSBs */
336 val <<= 8;
337 val |= (u_int64_t)blob.ptr[i];
338 }
339 return val;
340 }
341
342 /**
343 * ASN.1 definition of a PBKDF2-params structure
344 * The salt is actually a CHOICE and could be an AlgorithmIdentifier from
345 * PBKDF2-SaltSources (but as per RFC 2898 that's for future versions).
346 */
347 static const asn1Object_t pbkdf2ParamsObjects[] = {
348 { 0, "PBKDF2-params", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
349 { 1, "salt", ASN1_OCTET_STRING, ASN1_BODY }, /* 1 */
350 { 1, "iterationCount",ASN1_INTEGER, ASN1_BODY }, /* 2 */
351 { 1, "keyLength", ASN1_INTEGER, ASN1_OPT|ASN1_BODY }, /* 3 */
352 { 1, "end opt", ASN1_EOC, ASN1_END }, /* 4 */
353 { 1, "prf", ASN1_EOC, ASN1_DEF|ASN1_RAW }, /* 5 */
354 { 0, "exit", ASN1_EOC, ASN1_EXIT }
355 };
356 #define PBKDF2_SALT 1
357 #define PBKDF2_ITERATION_COUNT 2
358 #define PBKDF2_KEY_LENGTH 3
359 #define PBKDF2_PRF 5
360
361 /**
362 * Parse a PBKDF2-params structure
363 */
364 static void parse_pbkdf2_params(chunk_t blob, chunk_t *salt,
365 u_int64_t *iterations, size_t *key_len,
366 pseudo_random_function_t *prf)
367 {
368 asn1_parser_t *parser;
369 chunk_t object;
370 int objectID;
371
372 parser = asn1_parser_create(pbkdf2ParamsObjects, blob);
373
374 *key_len = 0; /* key_len is optional */
375
376 while (parser->iterate(parser, &objectID, &object))
377 {
378 switch (objectID)
379 {
380 case PBKDF2_SALT:
381 {
382 *salt = object;
383 break;
384 }
385 case PBKDF2_ITERATION_COUNT:
386 {
387 *iterations = parse_asn1_integer_uint64(object);
388 break;
389 }
390 case PBKDF2_KEY_LENGTH:
391 {
392 *key_len = (size_t)parse_asn1_integer_uint64(object);
393 break;
394 }
395 case PBKDF2_PRF:
396 { /* defaults to id-hmacWithSHA1 */
397 *prf = PRF_HMAC_SHA1;
398 break;
399 }
400 }
401 }
402
403 parser->destroy(parser);
404 }
405
406 /**
407 * ASN.1 definition of a PBES2-params structure
408 */
409 static const asn1Object_t pbes2ParamsObjects[] = {
410 { 0, "PBES2-params", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
411 { 1, "keyDerivationFunc", ASN1_EOC, ASN1_RAW }, /* 1 */
412 { 1, "encryptionScheme", ASN1_EOC, ASN1_RAW }, /* 2 */
413 { 0, "exit", ASN1_EOC, ASN1_EXIT }
414 };
415 #define PBES2PARAMS_KEY_DERIVATION_FUNC 1
416 #define PBES2PARAMS_ENCRYPTION_SCHEME 2
417
418 /**
419 * Parse a PBES2-params structure
420 */
421 static void parse_pbes2_params(chunk_t blob, chunk_t *salt,
422 u_int64_t *iterations, size_t *key_len,
423 pseudo_random_function_t *prf,
424 encryption_algorithm_t *encr, chunk_t *iv)
425 {
426 asn1_parser_t *parser;
427 chunk_t object, params;
428 int objectID;
429
430 parser = asn1_parser_create(pbes2ParamsObjects, blob);
431
432 while (parser->iterate(parser, &objectID, &object))
433 {
434 switch (objectID)
435 {
436 case PBES2PARAMS_KEY_DERIVATION_FUNC:
437 {
438 int oid = asn1_parse_algorithmIdentifier(object,
439 parser->get_level(parser) + 1, &params);
440 if (oid != OID_PBKDF2)
441 { /* unsupported key derivation function */
442 goto end;
443 }
444 parse_pbkdf2_params(params, salt, iterations, key_len, prf);
445 break;
446 }
447 case PBES2PARAMS_ENCRYPTION_SCHEME:
448 {
449 int oid = asn1_parse_algorithmIdentifier(object,
450 parser->get_level(parser) + 1, &params);
451 if (oid != OID_3DES_EDE_CBC)
452 { /* unsupported encryption scheme */
453 goto end;
454 }
455 if (*key_len <= 0)
456 { /* default key len for DES-EDE3-CBC-Pad */
457 *key_len = 24;
458 }
459 if (!asn1_parse_simple_object(&params, ASN1_OCTET_STRING,
460 parser->get_level(parser) + 1, "IV"))
461 {
462 goto end;
463 }
464 *encr = ENCR_3DES;
465 *iv = params;
466 break;
467 }
468 }
469 }
470
471 end:
472 parser->destroy(parser);
473 }
474
475 /**
476 * ASN.1 definition of a PBEParameter structure
477 */
478 static const asn1Object_t pbeParameterObjects[] = {
479 { 0, "PBEParameter", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
480 { 1, "salt", ASN1_OCTET_STRING, ASN1_BODY }, /* 1 */
481 { 1, "iterationCount", ASN1_INTEGER, ASN1_BODY }, /* 2 */
482 { 0, "exit", ASN1_EOC, ASN1_EXIT }
483 };
484 #define PBEPARAM_SALT 1
485 #define PBEPARAM_ITERATION_COUNT 2
486
487 /**
488 * Parse a PBEParameter structure
489 */
490 static void parse_pbe_parameters(chunk_t blob, chunk_t *salt,
491 u_int64_t *iterations)
492 {
493 asn1_parser_t *parser;
494 chunk_t object;
495 int objectID;
496
497 parser = asn1_parser_create(pbeParameterObjects, blob);
498
499 while (parser->iterate(parser, &objectID, &object))
500 {
501 switch (objectID)
502 {
503 case PBEPARAM_SALT:
504 {
505 *salt = object;
506 break;
507 }
508 case PBEPARAM_ITERATION_COUNT:
509 {
510 *iterations = parse_asn1_integer_uint64(object);
511 break;
512 }
513 }
514 }
515
516 parser->destroy(parser);
517 }
518
519 /**
520 * ASN.1 definition of an encryptedPrivateKeyInfo structure
521 */
522 static const asn1Object_t encryptedPKIObjects[] = {
523 { 0, "encryptedPrivateKeyInfo", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
524 { 1, "encryptionAlgorithm", ASN1_EOC, ASN1_RAW }, /* 1 */
525 { 1, "encryptedData", ASN1_OCTET_STRING, ASN1_BODY }, /* 2 */
526 { 0, "exit", ASN1_EOC, ASN1_EXIT }
527 };
528 #define EPKINFO_ENCRYPTION_ALGORITHM 1
529 #define EPKINFO_ENCRYPTED_DATA 2
530
531 /**
532 * Load an encrypted private key from an ASN.1 encoded blob
533 * Schemes per PKCS#5 (RFC 2898)
534 */
535 static private_key_t *parse_encrypted_private_key(chunk_t blob)
536 {
537 asn1_parser_t *parser;
538 chunk_t object, params, salt = chunk_empty, iv = chunk_empty;
539 u_int64_t iterations = 0;
540 int objectID;
541 encryption_algorithm_t encr = ENCR_UNDEFINED;
542 hash_algorithm_t hash = HASH_UNKNOWN;
543 pseudo_random_function_t prf = PRF_UNDEFINED;
544 private_key_t *key = NULL;
545 size_t key_len = 8;
546
547 parser = asn1_parser_create(encryptedPKIObjects, blob);
548
549 while (parser->iterate(parser, &objectID, &object))
550 {
551 switch (objectID)
552 {
553 case EPKINFO_ENCRYPTION_ALGORITHM:
554 {
555 int oid = asn1_parse_algorithmIdentifier(object,
556 parser->get_level(parser) + 1, &params);
557
558 switch (oid)
559 {
560 case OID_PBE_MD5_DES_CBC:
561 encr = ENCR_DES;
562 hash = HASH_MD5;
563 parse_pbe_parameters(params, &salt, &iterations);
564 break;
565 case OID_PBE_SHA1_DES_CBC:
566 encr = ENCR_DES;
567 hash = HASH_SHA1;
568 parse_pbe_parameters(params, &salt, &iterations);
569 break;
570 case OID_PBES2:
571 parse_pbes2_params(params, &salt, &iterations,
572 &key_len, &prf, &encr, &iv);
573 break;
574 default:
575 /* encryption scheme not supported */
576 goto end;
577 }
578 break;
579 }
580 case EPKINFO_ENCRYPTED_DATA:
581 {
582 if (prf != PRF_UNDEFINED)
583 {
584 key = decrypt_private_key_pbes2(object, encr, key_len, iv,
585 prf, salt, iterations);
586 }
587 else
588 {
589 key = decrypt_private_key_pbes1(object, encr, key_len, hash,
590 salt, iterations);
591 }
592 break;
593 }
594 }
595 }
596
597 end:
598 parser->destroy(parser);
599 return key;
600 }
601
602 /**
603 * See header.
604 */
605 private_key_t *pkcs8_private_key_load(key_type_t type, va_list args)
606 {
607 chunk_t blob = chunk_empty;
608 private_key_t *key;
609
610 while (TRUE)
611 {
612 switch (va_arg(args, builder_part_t))
613 {
614 case BUILD_BLOB_ASN1_DER:
615 blob = va_arg(args, chunk_t);
616 continue;
617 case BUILD_END:
618 break;
619 default:
620 return NULL;
621 }
622 break;
623 }
624 /* we don't know whether it is encrypted or not, try both ways */
625 key = parse_encrypted_private_key(blob);
626 if (!key)
627 {
628 key = parse_private_key(blob);
629 }
630 return key;
631 }
632