Extract function to convert ASN.1 INTEGER object to u_int64_t
[strongswan.git] / src / libstrongswan / crypto / pkcs5.c
1 /*
2 * Copyright (C) 2012-2013 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 "pkcs5.h"
17
18 #include <utils/debug.h>
19 #include <asn1/oid.h>
20 #include <asn1/asn1.h>
21 #include <asn1/asn1_parser.h>
22
23 typedef struct private_pkcs5_t private_pkcs5_t;
24
25 /**
26 * Private data of a pkcs5_t object
27 */
28 struct private_pkcs5_t {
29
30 /**
31 * Implements pkcs5_t.
32 */
33 pkcs5_t public;
34
35 /**
36 * Salt used during encryption
37 */
38 chunk_t salt;
39
40 /**
41 * Iterations for key derivation
42 */
43 u_int64_t iterations;
44
45 /**
46 * Encryption algorithm
47 */
48 encryption_algorithm_t encr;
49
50 /**
51 * Encryption key length
52 */
53 size_t keylen;
54
55 /**
56 * Crypter
57 */
58 crypter_t *crypter;
59
60
61 /**
62 * The encryption scheme
63 */
64 enum {
65 PKCS5_SCHEME_PBES1,
66 PKCS5_SCHEME_PBES2,
67 } scheme;
68
69 /**
70 * Data used for individual schemes
71 */
72 union {
73 struct {
74 /**
75 * Hash algorithm
76 */
77 hash_algorithm_t hash;
78
79 /**
80 * Hasher
81 */
82 hasher_t *hasher;
83
84 } pbes1;
85 struct {
86 /**
87 * PRF algorithm
88 */
89 pseudo_random_function_t prf_alg;
90
91 /**
92 * PRF
93 */
94 prf_t * prf;
95
96 /**
97 * IV
98 */
99 chunk_t iv;
100
101 } pbes2;
102 } data;
103 };
104
105 /**
106 * Verify padding of decrypted blob.
107 * Length of blob is adjusted accordingly.
108 */
109 static bool verify_padding(chunk_t *blob)
110 {
111 u_int8_t padding, count;
112
113 padding = count = blob->ptr[blob->len - 1];
114
115 if (padding > 8)
116 {
117 return FALSE;
118 }
119 for (; blob->len && count; --blob->len, --count)
120 {
121 if (blob->ptr[blob->len - 1] != padding)
122 {
123 return FALSE;
124 }
125 }
126 return TRUE;
127 }
128
129 /**
130 * Prototype for key derivation functions.
131 */
132 typedef bool (*kdf_t)(private_pkcs5_t *this, chunk_t password, chunk_t key);
133
134 /**
135 * Try to decrypt the given data with the given password using the given
136 * key derivation function. keymat is where the kdf function writes the key
137 * to, key and iv point to the actual keys and initialization vectors resp.
138 */
139 static bool decrypt_generic(private_pkcs5_t *this, chunk_t password,
140 chunk_t data, chunk_t *decrypted, kdf_t kdf,
141 chunk_t keymat, chunk_t key, chunk_t iv)
142 {
143 if (!kdf(this, password, keymat))
144 {
145 return FALSE;
146 }
147 if (!this->crypter->set_key(this->crypter, key) ||
148 !this->crypter->decrypt(this->crypter, data, iv, decrypted))
149 {
150 memwipe(keymat.ptr, keymat.len);
151 return FALSE;
152 }
153 memwipe(keymat.ptr, keymat.len);
154 if (verify_padding(decrypted))
155 {
156 return TRUE;
157 }
158 chunk_free(decrypted);
159 return FALSE;
160 }
161
162 /**
163 * Function F of PBKDF2
164 */
165 static bool pbkdf2_f(chunk_t block, prf_t *prf, chunk_t seed,
166 u_int64_t iterations)
167 {
168 chunk_t u;
169 u_int64_t i;
170
171 u = chunk_alloca(prf->get_block_size(prf));
172 if (!prf->get_bytes(prf, seed, u.ptr))
173 {
174 return FALSE;
175 }
176 memcpy(block.ptr, u.ptr, block.len);
177
178 for (i = 1; i < iterations; i++)
179 {
180 if (!prf->get_bytes(prf, u, u.ptr))
181 {
182 return FALSE;
183 }
184 memxor(block.ptr, u.ptr, block.len);
185 }
186 return TRUE;
187 }
188
189 /**
190 * PBKDF2 key derivation function for PBES2, key must be allocated
191 */
192 static bool pbkdf2(private_pkcs5_t *this, chunk_t password, chunk_t key)
193 {
194 prf_t *prf;
195 chunk_t keymat, block, seed;
196 size_t blocks;
197 u_int32_t i = 0;
198
199 prf = this->data.pbes2.prf;
200
201 if (!prf->set_key(prf, password))
202 {
203 return FALSE;
204 }
205
206 block.len = prf->get_block_size(prf);
207 blocks = (key.len - 1) / block.len + 1;
208 keymat = chunk_alloca(blocks * block.len);
209
210 seed = chunk_cata("cc", this->salt, chunk_from_thing(i));
211
212 for (; i < blocks; i++)
213 {
214 htoun32(seed.ptr + this->salt.len, i + 1);
215 block.ptr = keymat.ptr + (i * block.len);
216 if (!pbkdf2_f(block, prf, seed, this->iterations))
217 {
218 return FALSE;
219 }
220 }
221 memcpy(key.ptr, keymat.ptr, key.len);
222 return TRUE;
223 }
224
225 /**
226 * PBKDF1 key derivation function for PBES1, key must be allocated
227 */
228 static bool pbkdf1(private_pkcs5_t *this, chunk_t password, chunk_t key)
229 {
230 hasher_t *hasher;
231 chunk_t hash;
232 u_int64_t i;
233
234 hasher = this->data.pbes1.hasher;
235
236 hash = chunk_alloca(hasher->get_hash_size(hasher));
237 if (!hasher->get_hash(hasher, password, NULL) ||
238 !hasher->get_hash(hasher, this->salt, hash.ptr))
239 {
240 return FALSE;
241 }
242
243 for (i = 1; i < this->iterations; i++)
244 {
245 if (!hasher->get_hash(hasher, hash, hash.ptr))
246 {
247 return FALSE;
248 }
249 }
250 memcpy(key.ptr, hash.ptr, key.len);
251 return TRUE;
252 }
253
254 static bool ensure_crypto_primitives(private_pkcs5_t *this, chunk_t data)
255 {
256 if (!this->crypter)
257 {
258 this->crypter = lib->crypto->create_crypter(lib->crypto, this->encr,
259 this->keylen);
260 if (!this->crypter)
261 {
262 DBG1(DBG_ASN, " %N encryption algorithm not available",
263 encryption_algorithm_names, this->encr);
264 return FALSE;
265 }
266 }
267 if (data.len % this->crypter->get_block_size(this->crypter))
268 {
269 DBG1(DBG_ASN, " data size is not a multiple of block size");
270 return FALSE;
271 }
272 switch (this->scheme)
273 {
274 case PKCS5_SCHEME_PBES1:
275 {
276 if (!this->data.pbes1.hasher)
277 {
278 hasher_t *hasher;
279
280 hasher = lib->crypto->create_hasher(lib->crypto,
281 this->data.pbes1.hash);
282 if (!hasher)
283 {
284 DBG1(DBG_ASN, " %N hash algorithm not available",
285 hash_algorithm_names, this->data.pbes1.hash);
286 return FALSE;
287 }
288 if (hasher->get_hash_size(hasher) < this->keylen)
289 {
290 hasher->destroy(hasher);
291 return FALSE;
292 }
293 this->data.pbes1.hasher = hasher;
294 }
295 }
296 case PKCS5_SCHEME_PBES2:
297 {
298 if (!this->data.pbes2.prf)
299 {
300 prf_t *prf;
301
302 prf = lib->crypto->create_prf(lib->crypto,
303 this->data.pbes2.prf_alg);
304 if (!prf)
305 {
306 DBG1(DBG_ASN, " %N prf algorithm not available",
307 pseudo_random_function_names,
308 this->data.pbes2.prf_alg);
309 return FALSE;
310 }
311 this->data.pbes2.prf = prf;
312 }
313 }
314 }
315 return TRUE;
316 }
317
318 METHOD(pkcs5_t, decrypt, bool,
319 private_pkcs5_t *this, chunk_t password, chunk_t data, chunk_t *decrypted)
320 {
321 chunk_t keymat, key, iv;
322 kdf_t kdf;
323
324 if (!ensure_crypto_primitives(this, data) || !decrypted)
325 {
326 return FALSE;
327 }
328 switch (this->scheme)
329 {
330 case PKCS5_SCHEME_PBES1:
331 kdf = pbkdf1;
332 keymat = chunk_alloca(this->keylen * 2);
333 key = chunk_create(keymat.ptr, this->keylen);
334 iv = chunk_create(keymat.ptr + this->keylen, this->keylen);
335 break;
336 case PKCS5_SCHEME_PBES2:
337 kdf = pbkdf2;
338 keymat = chunk_alloca(this->keylen);
339 key = keymat;
340 iv = this->data.pbes2.iv;
341 break;
342 default:
343 return FALSE;
344 }
345 return decrypt_generic(this, password, data, decrypted, kdf,
346 keymat, key, iv);
347 }
348
349 /**
350 * ASN.1 definition of a PBEParameter structure
351 */
352 static const asn1Object_t pbeParameterObjects[] = {
353 { 0, "PBEParameter", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
354 { 1, "salt", ASN1_OCTET_STRING, ASN1_BODY }, /* 1 */
355 { 1, "iterationCount", ASN1_INTEGER, ASN1_BODY }, /* 2 */
356 { 0, "exit", ASN1_EOC, ASN1_EXIT }
357 };
358 #define PBEPARAM_SALT 1
359 #define PBEPARAM_ITERATION_COUNT 2
360
361 /**
362 * Parse a PBEParameter structure
363 */
364 static bool parse_pbes1_params(private_pkcs5_t *this, chunk_t blob, int level0)
365 {
366 asn1_parser_t *parser;
367 chunk_t object;
368 int objectID;
369 bool success;
370
371 parser = asn1_parser_create(pbeParameterObjects, blob);
372 parser->set_top_level(parser, level0);
373
374 while (parser->iterate(parser, &objectID, &object))
375 {
376 switch (objectID)
377 {
378 case PBEPARAM_SALT:
379 {
380 this->salt = chunk_clone(object);
381 break;
382 }
383 case PBEPARAM_ITERATION_COUNT:
384 {
385 this->iterations = asn1_parse_integer_uint64(object);
386 break;
387 }
388 }
389 }
390 success = parser->success(parser);
391 parser->destroy(parser);
392 return success;
393 }
394
395 /**
396 * ASN.1 definition of a PBKDF2-params structure
397 * The salt is actually a CHOICE and could be an AlgorithmIdentifier from
398 * PBKDF2-SaltSources (but as per RFC 2898 that's for future versions).
399 */
400 static const asn1Object_t pbkdf2ParamsObjects[] = {
401 { 0, "PBKDF2-params", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
402 { 1, "salt", ASN1_OCTET_STRING, ASN1_BODY }, /* 1 */
403 { 1, "iterationCount",ASN1_INTEGER, ASN1_BODY }, /* 2 */
404 { 1, "keyLength", ASN1_INTEGER, ASN1_OPT|ASN1_BODY }, /* 3 */
405 { 1, "end opt", ASN1_EOC, ASN1_END }, /* 4 */
406 { 1, "prf", ASN1_EOC, ASN1_DEF|ASN1_RAW }, /* 5 */
407 { 0, "exit", ASN1_EOC, ASN1_EXIT }
408 };
409 #define PBKDF2_SALT 1
410 #define PBKDF2_ITERATION_COUNT 2
411 #define PBKDF2_KEYLENGTH 3
412 #define PBKDF2_PRF 5
413
414 /**
415 * Parse a PBKDF2-params structure
416 */
417 static bool parse_pbkdf2_params(private_pkcs5_t *this, chunk_t blob, int level0)
418 {
419 asn1_parser_t *parser;
420 chunk_t object;
421 int objectID;
422 bool success;
423
424 parser = asn1_parser_create(pbkdf2ParamsObjects, blob);
425 parser->set_top_level(parser, level0);
426
427 /* keylen is optional */
428 this->keylen = 0;
429
430 while (parser->iterate(parser, &objectID, &object))
431 {
432 switch (objectID)
433 {
434 case PBKDF2_SALT:
435 {
436 this->salt = chunk_clone(object);
437 break;
438 }
439 case PBKDF2_ITERATION_COUNT:
440 {
441 this->iterations = asn1_parse_integer_uint64(object);
442 break;
443 }
444 case PBKDF2_KEYLENGTH:
445 {
446 this->keylen = (size_t)asn1_parse_integer_uint64(object);
447 break;
448 }
449 case PBKDF2_PRF:
450 { /* defaults to id-hmacWithSHA1, no other is currently defined */
451 this->data.pbes2.prf_alg = PRF_HMAC_SHA1;
452 break;
453 }
454 }
455 }
456 success = parser->success(parser);
457 parser->destroy(parser);
458 return success;
459 }
460
461 /**
462 * ASN.1 definition of a PBES2-params structure
463 */
464 static const asn1Object_t pbes2ParamsObjects[] = {
465 { 0, "PBES2-params", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
466 { 1, "keyDerivationFunc", ASN1_EOC, ASN1_RAW }, /* 1 */
467 { 1, "encryptionScheme", ASN1_EOC, ASN1_RAW }, /* 2 */
468 { 0, "exit", ASN1_EOC, ASN1_EXIT }
469 };
470 #define PBES2PARAMS_KEY_DERIVATION_FUNC 1
471 #define PBES2PARAMS_ENCRYPTION_SCHEME 2
472
473 /**
474 * Parse a PBES2-params structure
475 */
476 static bool parse_pbes2_params(private_pkcs5_t *this, chunk_t blob, int level0)
477 {
478 asn1_parser_t *parser;
479 chunk_t object, params;
480 int objectID;
481 bool success = FALSE;
482
483 parser = asn1_parser_create(pbes2ParamsObjects, blob);
484 parser->set_top_level(parser, level0);
485
486 while (parser->iterate(parser, &objectID, &object))
487 {
488 switch (objectID)
489 {
490 case PBES2PARAMS_KEY_DERIVATION_FUNC:
491 {
492 int oid = asn1_parse_algorithmIdentifier(object,
493 parser->get_level(parser) + 1, &params);
494 if (oid != OID_PBKDF2)
495 { /* unsupported key derivation function */
496 goto end;
497 }
498 if (!parse_pbkdf2_params(this, params,
499 parser->get_level(parser) + 1))
500 {
501 goto end;
502 }
503 break;
504 }
505 case PBES2PARAMS_ENCRYPTION_SCHEME:
506 {
507 int oid = asn1_parse_algorithmIdentifier(object,
508 parser->get_level(parser) + 1, &params);
509 if (oid != OID_3DES_EDE_CBC)
510 { /* unsupported encryption scheme */
511 goto end;
512 }
513 if (this->keylen <= 0)
514 { /* default key length for DES-EDE3-CBC-Pad */
515 this->keylen = 24;
516 }
517 if (!asn1_parse_simple_object(&params, ASN1_OCTET_STRING,
518 parser->get_level(parser) + 1, "IV"))
519 {
520 goto end;
521 }
522 this->encr = ENCR_3DES;
523 this->data.pbes2.iv = chunk_clone(params);
524 break;
525 }
526 }
527 }
528 success = parser->success(parser);
529 end:
530 parser->destroy(parser);
531 return success;
532 }
533
534 METHOD(pkcs5_t, destroy, void,
535 private_pkcs5_t *this)
536 {
537 DESTROY_IF(this->crypter);
538 chunk_free(&this->salt);
539 switch (this->scheme)
540 {
541 case PKCS5_SCHEME_PBES1:
542 DESTROY_IF(this->data.pbes1.hasher);
543 break;
544 case PKCS5_SCHEME_PBES2:
545 DESTROY_IF(this->data.pbes2.prf);
546 chunk_free(&this->data.pbes2.iv);
547 break;
548 }
549 free(this);
550 }
551
552 /*
553 * Described in header
554 */
555 pkcs5_t *pkcs5_from_algorithmIdentifier(chunk_t blob, int level0)
556 {
557 private_pkcs5_t *this;
558 chunk_t params;
559 int oid;
560
561 INIT(this,
562 .public = {
563 .decrypt = _decrypt,
564 .destroy = _destroy,
565 },
566 .scheme = PKCS5_SCHEME_PBES1,
567 .keylen = 8,
568 );
569
570 oid = asn1_parse_algorithmIdentifier(blob, level0, &params);
571
572 switch (oid)
573 {
574 case OID_PBE_MD5_DES_CBC:
575 this->encr = ENCR_DES;
576 this->data.pbes1.hash = HASH_MD5;
577 break;
578 case OID_PBE_SHA1_DES_CBC:
579 this->encr = ENCR_DES;
580 this->data.pbes1.hash = HASH_SHA1;
581 break;
582 case OID_PBES2:
583 this->scheme = PKCS5_SCHEME_PBES2;
584 break;
585 default:
586 /* encryption scheme not supported */
587 goto failure;
588 }
589
590 switch (this->scheme)
591 {
592 case PKCS5_SCHEME_PBES1:
593 if (!parse_pbes1_params(this, params, level0))
594 {
595 goto failure;
596 }
597 break;
598 case PKCS5_SCHEME_PBES2:
599 if (!parse_pbes2_params(this, params, level0))
600 {
601 goto failure;
602 }
603 break;
604 }
605 return &this->public;
606
607 failure:
608 destroy(this);
609 return NULL;
610 }