Add a return value to hasher_t.get_hash()
[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 bool (*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 if (!kdf(generator, shared->get_key(shared), salt, iterations, keymat))
168 {
169 continue;
170 }
171 if (!crypter->set_key(crypter, key) ||
172 !crypter->decrypt(crypter, blob, iv, &decrypted))
173 {
174 continue;
175 }
176 if (verify_padding(&decrypted))
177 {
178 private_key = parse_private_key(decrypted);
179 if (private_key)
180 {
181 chunk_clear(&decrypted);
182 break;
183 }
184 }
185 chunk_free(&decrypted);
186 }
187 enumerator->destroy(enumerator);
188 crypter->destroy(crypter);
189
190 return private_key;
191 }
192
193 /**
194 * Function F of PBKDF2
195 */
196 static bool pbkdf2_f(chunk_t block, prf_t *prf, chunk_t seed,
197 u_int64_t iterations)
198 {
199 chunk_t u;
200 u_int64_t i;
201
202 u = chunk_alloca(prf->get_block_size(prf));
203 if (!prf->get_bytes(prf, seed, u.ptr))
204 {
205 return FALSE;
206 }
207 memcpy(block.ptr, u.ptr, block.len);
208
209 for (i = 1; i < iterations; i++)
210 {
211 if (!prf->get_bytes(prf, u, u.ptr))
212 {
213 return FALSE;
214 }
215 memxor(block.ptr, u.ptr, block.len);
216 }
217 return TRUE;
218 }
219
220 /**
221 * PBKDF2 key derivation function
222 */
223 static bool pbkdf2(prf_t *prf, chunk_t password, chunk_t salt,
224 u_int64_t iterations, chunk_t key)
225 {
226 chunk_t keymat, block, seed;
227 size_t blocks;
228 u_int32_t i = 0, *ni;
229
230 if (!prf->set_key(prf, password))
231 {
232 return FALSE;
233 }
234
235 block.len = prf->get_block_size(prf);
236 blocks = (key.len - 1) / block.len + 1;
237 keymat = chunk_alloca(blocks * block.len);
238
239 seed = chunk_cata("cc", salt, chunk_from_thing(i));
240 ni = (u_int32_t*)(seed.ptr + salt.len);
241
242 for (; i < blocks; i++)
243 {
244 *ni = htonl(i + 1);
245 block.ptr = keymat.ptr + (i * block.len);
246 if (!pbkdf2_f(block, prf, seed, iterations))
247 {
248 return FALSE;
249 }
250 }
251
252 memcpy(key.ptr, keymat.ptr, key.len);
253
254 return TRUE;
255 }
256
257 /**
258 * Decrypt an encrypted PKCS#8 encoded private key according to PBES2
259 */
260 static private_key_t *decrypt_private_key_pbes2(chunk_t blob,
261 encryption_algorithm_t encr, size_t key_len,
262 chunk_t iv, pseudo_random_function_t prf_func,
263 chunk_t salt, u_int64_t iterations)
264 {
265 private_key_t *private_key;
266 prf_t *prf;
267 chunk_t key;
268
269 prf = lib->crypto->create_prf(lib->crypto, prf_func);
270 if (!prf)
271 {
272 DBG1(DBG_ASN, " %N prf algorithm not available",
273 pseudo_random_function_names, prf_func);
274 return NULL;
275 }
276
277 key = chunk_alloca(key_len);
278
279 private_key = decrypt_private_key(blob, encr, key_len, (kdf_t)pbkdf2, prf,
280 salt, iterations, key, key, iv);
281
282 prf->destroy(prf);
283 return private_key;
284 }
285
286 /**
287 * PBKDF1 key derivation function
288 */
289 static bool pbkdf1(hasher_t *hasher, chunk_t password, chunk_t salt,
290 u_int64_t iterations, chunk_t key)
291 {
292 chunk_t hash;
293 u_int64_t i;
294
295 hash = chunk_alloca(hasher->get_hash_size(hasher));
296 if (!hasher->get_hash(hasher, password, NULL) ||
297 !hasher->get_hash(hasher, salt, hash.ptr))
298 {
299 return FALSE;
300 }
301
302 for (i = 1; i < iterations; i++)
303 {
304 if (!hasher->get_hash(hasher, hash, hash.ptr))
305 {
306 return FALSE;
307 }
308 }
309
310 memcpy(key.ptr, hash.ptr, key.len);
311
312 return TRUE;
313 }
314
315 /**
316 * Decrypt an encrypted PKCS#8 encoded private key according to PBES1
317 */
318 static private_key_t *decrypt_private_key_pbes1(chunk_t blob,
319 encryption_algorithm_t encr, size_t key_len,
320 hash_algorithm_t hash, chunk_t salt,
321 u_int64_t iterations)
322 {
323 private_key_t *private_key = NULL;
324 hasher_t *hasher = NULL;
325 chunk_t keymat, key, iv;
326
327 hasher = lib->crypto->create_hasher(lib->crypto, hash);
328 if (!hasher)
329 {
330 DBG1(DBG_ASN, " %N hash algorithm not available",
331 hash_algorithm_names, hash);
332 goto end;
333 }
334 if (hasher->get_hash_size(hasher) < key_len)
335 {
336 goto end;
337 }
338
339 keymat = chunk_alloca(key_len * 2);
340 key.len = key_len;
341 key.ptr = keymat.ptr;
342 iv.len = key_len;
343 iv.ptr = keymat.ptr + key_len;
344
345 private_key = decrypt_private_key(blob, encr, key_len, (kdf_t)pbkdf1,
346 hasher, salt, iterations, keymat,
347 key, iv);
348
349 end:
350 DESTROY_IF(hasher);
351 return private_key;
352 }
353
354 /**
355 * Parse an ASN1_INTEGER to a u_int64_t.
356 */
357 static u_int64_t parse_asn1_integer_uint64(chunk_t blob)
358 {
359 u_int64_t val = 0;
360 int i;
361
362 for (i = 0; i < blob.len; i++)
363 { /* if it is longer than 8 bytes, we just use the 8 LSBs */
364 val <<= 8;
365 val |= (u_int64_t)blob.ptr[i];
366 }
367 return val;
368 }
369
370 /**
371 * ASN.1 definition of a PBKDF2-params structure
372 * The salt is actually a CHOICE and could be an AlgorithmIdentifier from
373 * PBKDF2-SaltSources (but as per RFC 2898 that's for future versions).
374 */
375 static const asn1Object_t pbkdf2ParamsObjects[] = {
376 { 0, "PBKDF2-params", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
377 { 1, "salt", ASN1_OCTET_STRING, ASN1_BODY }, /* 1 */
378 { 1, "iterationCount",ASN1_INTEGER, ASN1_BODY }, /* 2 */
379 { 1, "keyLength", ASN1_INTEGER, ASN1_OPT|ASN1_BODY }, /* 3 */
380 { 1, "end opt", ASN1_EOC, ASN1_END }, /* 4 */
381 { 1, "prf", ASN1_EOC, ASN1_DEF|ASN1_RAW }, /* 5 */
382 { 0, "exit", ASN1_EOC, ASN1_EXIT }
383 };
384 #define PBKDF2_SALT 1
385 #define PBKDF2_ITERATION_COUNT 2
386 #define PBKDF2_KEY_LENGTH 3
387 #define PBKDF2_PRF 5
388
389 /**
390 * Parse a PBKDF2-params structure
391 */
392 static void parse_pbkdf2_params(chunk_t blob, chunk_t *salt,
393 u_int64_t *iterations, size_t *key_len,
394 pseudo_random_function_t *prf)
395 {
396 asn1_parser_t *parser;
397 chunk_t object;
398 int objectID;
399
400 parser = asn1_parser_create(pbkdf2ParamsObjects, blob);
401
402 *key_len = 0; /* key_len is optional */
403
404 while (parser->iterate(parser, &objectID, &object))
405 {
406 switch (objectID)
407 {
408 case PBKDF2_SALT:
409 {
410 *salt = object;
411 break;
412 }
413 case PBKDF2_ITERATION_COUNT:
414 {
415 *iterations = parse_asn1_integer_uint64(object);
416 break;
417 }
418 case PBKDF2_KEY_LENGTH:
419 {
420 *key_len = (size_t)parse_asn1_integer_uint64(object);
421 break;
422 }
423 case PBKDF2_PRF:
424 { /* defaults to id-hmacWithSHA1 */
425 *prf = PRF_HMAC_SHA1;
426 break;
427 }
428 }
429 }
430
431 parser->destroy(parser);
432 }
433
434 /**
435 * ASN.1 definition of a PBES2-params structure
436 */
437 static const asn1Object_t pbes2ParamsObjects[] = {
438 { 0, "PBES2-params", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
439 { 1, "keyDerivationFunc", ASN1_EOC, ASN1_RAW }, /* 1 */
440 { 1, "encryptionScheme", ASN1_EOC, ASN1_RAW }, /* 2 */
441 { 0, "exit", ASN1_EOC, ASN1_EXIT }
442 };
443 #define PBES2PARAMS_KEY_DERIVATION_FUNC 1
444 #define PBES2PARAMS_ENCRYPTION_SCHEME 2
445
446 /**
447 * Parse a PBES2-params structure
448 */
449 static void parse_pbes2_params(chunk_t blob, chunk_t *salt,
450 u_int64_t *iterations, size_t *key_len,
451 pseudo_random_function_t *prf,
452 encryption_algorithm_t *encr, chunk_t *iv)
453 {
454 asn1_parser_t *parser;
455 chunk_t object, params;
456 int objectID;
457
458 parser = asn1_parser_create(pbes2ParamsObjects, blob);
459
460 while (parser->iterate(parser, &objectID, &object))
461 {
462 switch (objectID)
463 {
464 case PBES2PARAMS_KEY_DERIVATION_FUNC:
465 {
466 int oid = asn1_parse_algorithmIdentifier(object,
467 parser->get_level(parser) + 1, &params);
468 if (oid != OID_PBKDF2)
469 { /* unsupported key derivation function */
470 goto end;
471 }
472 parse_pbkdf2_params(params, salt, iterations, key_len, prf);
473 break;
474 }
475 case PBES2PARAMS_ENCRYPTION_SCHEME:
476 {
477 int oid = asn1_parse_algorithmIdentifier(object,
478 parser->get_level(parser) + 1, &params);
479 if (oid != OID_3DES_EDE_CBC)
480 { /* unsupported encryption scheme */
481 goto end;
482 }
483 if (*key_len <= 0)
484 { /* default key len for DES-EDE3-CBC-Pad */
485 *key_len = 24;
486 }
487 if (!asn1_parse_simple_object(&params, ASN1_OCTET_STRING,
488 parser->get_level(parser) + 1, "IV"))
489 {
490 goto end;
491 }
492 *encr = ENCR_3DES;
493 *iv = params;
494 break;
495 }
496 }
497 }
498
499 end:
500 parser->destroy(parser);
501 }
502
503 /**
504 * ASN.1 definition of a PBEParameter structure
505 */
506 static const asn1Object_t pbeParameterObjects[] = {
507 { 0, "PBEParameter", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
508 { 1, "salt", ASN1_OCTET_STRING, ASN1_BODY }, /* 1 */
509 { 1, "iterationCount", ASN1_INTEGER, ASN1_BODY }, /* 2 */
510 { 0, "exit", ASN1_EOC, ASN1_EXIT }
511 };
512 #define PBEPARAM_SALT 1
513 #define PBEPARAM_ITERATION_COUNT 2
514
515 /**
516 * Parse a PBEParameter structure
517 */
518 static void parse_pbe_parameters(chunk_t blob, chunk_t *salt,
519 u_int64_t *iterations)
520 {
521 asn1_parser_t *parser;
522 chunk_t object;
523 int objectID;
524
525 parser = asn1_parser_create(pbeParameterObjects, blob);
526
527 while (parser->iterate(parser, &objectID, &object))
528 {
529 switch (objectID)
530 {
531 case PBEPARAM_SALT:
532 {
533 *salt = object;
534 break;
535 }
536 case PBEPARAM_ITERATION_COUNT:
537 {
538 *iterations = parse_asn1_integer_uint64(object);
539 break;
540 }
541 }
542 }
543
544 parser->destroy(parser);
545 }
546
547 /**
548 * ASN.1 definition of an encryptedPrivateKeyInfo structure
549 */
550 static const asn1Object_t encryptedPKIObjects[] = {
551 { 0, "encryptedPrivateKeyInfo", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
552 { 1, "encryptionAlgorithm", ASN1_EOC, ASN1_RAW }, /* 1 */
553 { 1, "encryptedData", ASN1_OCTET_STRING, ASN1_BODY }, /* 2 */
554 { 0, "exit", ASN1_EOC, ASN1_EXIT }
555 };
556 #define EPKINFO_ENCRYPTION_ALGORITHM 1
557 #define EPKINFO_ENCRYPTED_DATA 2
558
559 /**
560 * Load an encrypted private key from an ASN.1 encoded blob
561 * Schemes per PKCS#5 (RFC 2898)
562 */
563 static private_key_t *parse_encrypted_private_key(chunk_t blob)
564 {
565 asn1_parser_t *parser;
566 chunk_t object, params, salt = chunk_empty, iv = chunk_empty;
567 u_int64_t iterations = 0;
568 int objectID;
569 encryption_algorithm_t encr = ENCR_UNDEFINED;
570 hash_algorithm_t hash = HASH_UNKNOWN;
571 pseudo_random_function_t prf = PRF_UNDEFINED;
572 private_key_t *key = NULL;
573 size_t key_len = 8;
574
575 parser = asn1_parser_create(encryptedPKIObjects, blob);
576
577 while (parser->iterate(parser, &objectID, &object))
578 {
579 switch (objectID)
580 {
581 case EPKINFO_ENCRYPTION_ALGORITHM:
582 {
583 int oid = asn1_parse_algorithmIdentifier(object,
584 parser->get_level(parser) + 1, &params);
585
586 switch (oid)
587 {
588 case OID_PBE_MD5_DES_CBC:
589 encr = ENCR_DES;
590 hash = HASH_MD5;
591 parse_pbe_parameters(params, &salt, &iterations);
592 break;
593 case OID_PBE_SHA1_DES_CBC:
594 encr = ENCR_DES;
595 hash = HASH_SHA1;
596 parse_pbe_parameters(params, &salt, &iterations);
597 break;
598 case OID_PBES2:
599 parse_pbes2_params(params, &salt, &iterations,
600 &key_len, &prf, &encr, &iv);
601 break;
602 default:
603 /* encryption scheme not supported */
604 goto end;
605 }
606 break;
607 }
608 case EPKINFO_ENCRYPTED_DATA:
609 {
610 if (prf != PRF_UNDEFINED)
611 {
612 key = decrypt_private_key_pbes2(object, encr, key_len, iv,
613 prf, salt, iterations);
614 }
615 else
616 {
617 key = decrypt_private_key_pbes1(object, encr, key_len, hash,
618 salt, iterations);
619 }
620 break;
621 }
622 }
623 }
624
625 end:
626 parser->destroy(parser);
627 return key;
628 }
629
630 /**
631 * See header.
632 */
633 private_key_t *pkcs8_private_key_load(key_type_t type, va_list args)
634 {
635 chunk_t blob = chunk_empty;
636 private_key_t *key;
637
638 while (TRUE)
639 {
640 switch (va_arg(args, builder_part_t))
641 {
642 case BUILD_BLOB_ASN1_DER:
643 blob = va_arg(args, chunk_t);
644 continue;
645 case BUILD_END:
646 break;
647 default:
648 return NULL;
649 }
650 break;
651 }
652 /* we don't know whether it is encrypted or not, try both ways */
653 key = parse_encrypted_private_key(blob);
654 if (!key)
655 {
656 key = parse_private_key(blob);
657 }
658 return key;
659 }
660