Fixed leaks in PKCS #8 decoding
[gnutls.git] / lib / x509 / privkey_pkcs8.c
blob825ba8388f6f8f431ecc26de33c6bcc371300d47
1 /*
2 * Copyright (C) 2003-2012 Free Software Foundation, Inc.
4 * Author: Nikos Mavrogiannopoulos
6 * This file is part of GnuTLS.
8 * The GnuTLS is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public License
10 * as published by the Free Software Foundation; either version 3 of
11 * the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>
23 #include <gnutls_int.h>
25 #include <gnutls_datum.h>
26 #include <gnutls_global.h>
27 #include <gnutls_errors.h>
28 #include <gnutls_rsa_export.h>
29 #include <common.h>
30 #include <gnutls_x509.h>
31 #include <x509_b64.h>
32 #include "x509_int.h"
33 #include <algorithms.h>
34 #include <gnutls_num.h>
35 #include <random.h>
36 #include <pbkdf2-sha1.h>
38 static int _decode_pkcs8_ecc_key (ASN1_TYPE pkcs8_asn, gnutls_x509_privkey_t pkey);
40 #define PBES2_OID "1.2.840.113549.1.5.13"
41 #define PBKDF2_OID "1.2.840.113549.1.5.12"
42 #define DES_EDE3_CBC_OID "1.2.840.113549.3.7"
43 #define AES_128_CBC_OID "2.16.840.1.101.3.4.1.2"
44 #define AES_192_CBC_OID "2.16.840.1.101.3.4.1.22"
45 #define AES_256_CBC_OID "2.16.840.1.101.3.4.1.42"
46 #define DES_CBC_OID "1.3.14.3.2.7"
48 /* oid_pbeWithSHAAnd3_KeyTripleDES_CBC */
49 #define PKCS12_PBE_3DES_SHA1_OID "1.2.840.113549.1.12.1.3"
50 #define PKCS12_PBE_ARCFOUR_SHA1_OID "1.2.840.113549.1.12.1.1"
51 #define PKCS12_PBE_RC2_40_SHA1_OID "1.2.840.113549.1.12.1.6"
53 struct pbkdf2_params
55 uint8_t salt[32];
56 int salt_size;
57 unsigned int iter_count;
58 unsigned int key_size;
61 struct pbe_enc_params
63 gnutls_cipher_algorithm_t cipher;
64 uint8_t iv[MAX_CIPHER_BLOCK_SIZE];
65 int iv_size;
68 static int generate_key (schema_id schema, const char *password,
69 struct pbkdf2_params *kdf_params,
70 struct pbe_enc_params *enc_params,
71 gnutls_datum_t * key);
72 static int read_pbkdf2_params (ASN1_TYPE pbes2_asn,
73 const gnutls_datum_t * der,
74 struct pbkdf2_params *params);
75 static int read_pbe_enc_params (ASN1_TYPE pbes2_asn,
76 const gnutls_datum_t * der,
77 struct pbe_enc_params *params);
78 static int decrypt_data (schema_id, ASN1_TYPE pkcs8_asn, const char *root,
79 const char *password,
80 const struct pbkdf2_params *kdf_params,
81 const struct pbe_enc_params *enc_params,
82 gnutls_datum_t * decrypted_data);
83 static int decode_private_key_info (const gnutls_datum_t * der,
84 gnutls_x509_privkey_t pkey);
85 static int write_schema_params (schema_id schema, ASN1_TYPE pkcs8_asn,
86 const char *where,
87 const struct pbkdf2_params *kdf_params,
88 const struct pbe_enc_params *enc_params);
89 static int encrypt_data (const gnutls_datum_t * plain,
90 const struct pbe_enc_params *enc_params,
91 gnutls_datum_t * key, gnutls_datum_t * encrypted);
93 static int read_pkcs12_kdf_params (ASN1_TYPE pbes2_asn,
94 struct pbkdf2_params *params);
95 static int write_pkcs12_kdf_params (ASN1_TYPE pbes2_asn,
96 const struct pbkdf2_params *params);
98 #define PEM_PKCS8 "ENCRYPTED PRIVATE KEY"
99 #define PEM_UNENCRYPTED_PKCS8 "PRIVATE KEY"
101 /* Returns a negative error code if the encryption schema in
102 * the OID is not supported. The schema ID is returned.
104 static int
105 check_schema (const char *oid)
108 if (strcmp (oid, PBES2_OID) == 0)
109 return PBES2_GENERIC; /* ok */
111 if (strcmp (oid, PKCS12_PBE_3DES_SHA1_OID) == 0)
112 return PKCS12_3DES_SHA1;
114 if (strcmp (oid, PKCS12_PBE_ARCFOUR_SHA1_OID) == 0)
115 return PKCS12_ARCFOUR_SHA1;
117 if (strcmp (oid, PKCS12_PBE_RC2_40_SHA1_OID) == 0)
118 return PKCS12_RC2_40_SHA1;
120 _gnutls_debug_log ("PKCS encryption schema OID '%s' is unsupported.\n", oid);
122 return GNUTLS_E_UNKNOWN_CIPHER_TYPE;
125 /* Encodes a private key to the raw format PKCS #8 needs.
126 * For RSA it is a PKCS #1 DER private key and for DSA it is
127 * an ASN.1 INTEGER of the x value.
129 inline static int
130 _encode_privkey (gnutls_x509_privkey_t pkey, gnutls_datum_t * raw)
132 size_t size = 0;
133 uint8_t *data = NULL;
134 int ret;
135 ASN1_TYPE spk = ASN1_TYPE_EMPTY;
137 switch (pkey->pk_algorithm)
139 case GNUTLS_PK_RSA:
140 case GNUTLS_PK_EC:
141 ret =
142 gnutls_x509_privkey_export (pkey, GNUTLS_X509_FMT_DER, NULL, &size);
143 if (ret != GNUTLS_E_SHORT_MEMORY_BUFFER)
145 gnutls_assert ();
146 goto error;
149 data = gnutls_malloc (size);
150 if (data == NULL)
152 gnutls_assert ();
153 ret = GNUTLS_E_MEMORY_ERROR;
154 goto error;
158 ret =
159 gnutls_x509_privkey_export (pkey, GNUTLS_X509_FMT_DER, data, &size);
160 if (ret < 0)
162 gnutls_assert ();
163 goto error;
166 raw->data = data;
167 raw->size = size;
168 break;
169 case GNUTLS_PK_DSA:
170 /* DSAPublicKey == INTEGER */
171 if ((ret = asn1_create_element
172 (_gnutls_get_gnutls_asn (), "GNUTLS.DSAPublicKey", &spk))
173 != ASN1_SUCCESS)
175 gnutls_assert ();
176 return _gnutls_asn2err (ret);
179 ret = _gnutls_x509_write_int (spk, "", pkey->params.params[4], 1);
180 if (ret < 0)
182 gnutls_assert ();
183 goto error;
185 ret = _gnutls_x509_der_encode (spk, "", raw, 0);
186 if (ret < 0)
188 gnutls_assert ();
189 goto error;
192 asn1_delete_structure (&spk);
193 break;
195 default:
196 gnutls_assert ();
197 return GNUTLS_E_INVALID_REQUEST;
200 return 0;
202 error:
203 gnutls_free (data);
204 asn1_delete_structure (&spk);
205 return ret;
210 * Encodes a PKCS #1 private key to a PKCS #8 private key
211 * info. The output will be allocated and stored into der. Also
212 * the ASN1_TYPE of private key info will be returned.
214 static int
215 encode_to_private_key_info (gnutls_x509_privkey_t pkey,
216 gnutls_datum_t * der, ASN1_TYPE * pkey_info)
218 int result, len;
219 uint8_t null = 0;
220 const char *oid;
221 gnutls_datum_t algo_params = { NULL, 0 };
222 gnutls_datum_t algo_privkey = { NULL, 0 };
224 oid = _gnutls_x509_pk_to_oid(pkey->pk_algorithm);
225 if (oid == NULL)
227 gnutls_assert ();
228 return GNUTLS_E_UNIMPLEMENTED_FEATURE;
231 result =
232 _gnutls_x509_write_pubkey_params (pkey->pk_algorithm, &pkey->params, &algo_params);
233 if (result < 0)
235 gnutls_assert ();
236 return result;
239 if ((result =
240 asn1_create_element (_gnutls_get_pkix (),
241 "PKIX1.pkcs-8-PrivateKeyInfo",
242 pkey_info)) != ASN1_SUCCESS)
244 gnutls_assert ();
245 result = _gnutls_asn2err (result);
246 goto error;
249 /* Write the version.
251 result = asn1_write_value (*pkey_info, "version", &null, 1);
252 if (result != ASN1_SUCCESS)
254 gnutls_assert ();
255 result = _gnutls_asn2err (result);
256 goto error;
259 /* write the privateKeyAlgorithm
260 * fields. (OID+NULL data)
262 result =
263 asn1_write_value (*pkey_info, "privateKeyAlgorithm.algorithm", oid, 1);
264 if (result != ASN1_SUCCESS)
266 gnutls_assert ();
267 result = _gnutls_asn2err (result);
268 goto error;
271 result =
272 asn1_write_value (*pkey_info, "privateKeyAlgorithm.parameters",
273 algo_params.data, algo_params.size);
274 _gnutls_free_datum (&algo_params);
275 if (result != ASN1_SUCCESS)
277 gnutls_assert ();
278 result = _gnutls_asn2err (result);
279 goto error;
283 /* Write the raw private key
285 result = _encode_privkey (pkey, &algo_privkey);
286 if (result < 0)
288 gnutls_assert ();
289 goto error;
292 result =
293 asn1_write_value (*pkey_info, "privateKey", algo_privkey.data,
294 algo_privkey.size);
295 _gnutls_free_datum (&algo_privkey);
297 if (result != ASN1_SUCCESS)
299 gnutls_assert ();
300 result = _gnutls_asn2err (result);
301 goto error;
304 /* Append an empty Attributes field.
306 result = asn1_write_value (*pkey_info, "attributes", NULL, 0);
307 if (result != ASN1_SUCCESS)
309 gnutls_assert ();
310 result = _gnutls_asn2err (result);
311 goto error;
314 /* DER Encode the generated private key info.
316 len = 0;
317 result = asn1_der_coding (*pkey_info, "", NULL, &len, NULL);
318 if (result != ASN1_MEM_ERROR)
320 gnutls_assert ();
321 result = _gnutls_asn2err (result);
322 goto error;
325 /* allocate data for the der
327 der->size = len;
328 der->data = gnutls_malloc (len);
329 if (der->data == NULL)
331 gnutls_assert ();
332 return GNUTLS_E_MEMORY_ERROR;
335 result = asn1_der_coding (*pkey_info, "", der->data, &len, NULL);
336 if (result != ASN1_SUCCESS)
338 gnutls_assert ();
339 result = _gnutls_asn2err (result);
340 goto error;
343 return 0;
345 error:
346 asn1_delete_structure (pkey_info);
347 _gnutls_free_datum (&algo_params);
348 _gnutls_free_datum (&algo_privkey);
349 return result;
353 static const char *
354 cipher_to_pkcs_params (int cipher, const char **oid)
356 switch (cipher)
358 case GNUTLS_CIPHER_AES_128_CBC:
359 if (oid)
360 *oid = AES_128_CBC_OID;
361 return "PKIX1.pkcs-5-aes128-CBC-params";
362 break;
363 case GNUTLS_CIPHER_AES_192_CBC:
364 if (oid)
365 *oid = AES_192_CBC_OID;
366 return "PKIX1.pkcs-5-aes192-CBC-params";
367 break;
368 case GNUTLS_CIPHER_AES_256_CBC:
369 if (oid)
370 *oid = AES_256_CBC_OID;
371 return "PKIX1.pkcs-5-aes256-CBC-params";
372 break;
373 case GNUTLS_CIPHER_3DES_CBC:
374 if (oid)
375 *oid = DES_EDE3_CBC_OID;
376 return "PKIX1.pkcs-5-des-EDE3-CBC-params";
377 break;
378 default:
379 return NULL;
380 break;
384 static int
385 cipher_to_schema (int cipher)
387 switch (cipher)
389 case GNUTLS_CIPHER_AES_128_CBC:
390 return PBES2_AES_128;
391 break;
392 case GNUTLS_CIPHER_AES_192_CBC:
393 return PBES2_AES_192;
394 break;
395 case GNUTLS_CIPHER_AES_256_CBC:
396 return PBES2_AES_256;
397 break;
398 case GNUTLS_CIPHER_3DES_CBC:
399 return PBES2_3DES;
400 break;
401 default:
402 return GNUTLS_E_UNKNOWN_CIPHER_TYPE;
403 break;
409 _gnutls_pkcs_flags_to_schema (unsigned int flags)
411 int schema;
413 if (flags & GNUTLS_PKCS_USE_PKCS12_ARCFOUR)
414 schema = PKCS12_ARCFOUR_SHA1;
415 else if (flags & GNUTLS_PKCS_USE_PKCS12_RC2_40)
416 schema = PKCS12_RC2_40_SHA1;
417 else if (flags & GNUTLS_PKCS_USE_PBES2_3DES)
418 schema = PBES2_3DES;
419 else if (flags & GNUTLS_PKCS_USE_PBES2_AES_128)
420 schema = PBES2_AES_128;
421 else if (flags & GNUTLS_PKCS_USE_PBES2_AES_192)
422 schema = PBES2_AES_192;
423 else if (flags & GNUTLS_PKCS_USE_PBES2_AES_256)
424 schema = PBES2_AES_256;
425 else
427 gnutls_assert ();
428 _gnutls_debug_log
429 ("Selecting default encryption PKCS12_3DES_SHA1 (flags: %u).\n",
430 flags);
431 schema = PKCS12_3DES_SHA1;
434 return schema;
437 /* returns the OID corresponding to given schema
439 static int
440 schema_to_oid (schema_id schema, const char **str_oid)
442 int result = 0;
444 switch (schema)
446 case PBES2_3DES:
447 case PBES2_AES_128:
448 case PBES2_AES_192:
449 case PBES2_AES_256:
450 *str_oid = PBES2_OID;
451 break;
452 case PKCS12_3DES_SHA1:
453 *str_oid = PKCS12_PBE_3DES_SHA1_OID;
454 break;
455 case PKCS12_ARCFOUR_SHA1:
456 *str_oid = PKCS12_PBE_ARCFOUR_SHA1_OID;
457 break;
458 case PKCS12_RC2_40_SHA1:
459 *str_oid = PKCS12_PBE_RC2_40_SHA1_OID;
460 break;
461 default:
462 gnutls_assert ();
463 result = GNUTLS_E_INTERNAL_ERROR;
466 return result;
469 /* Converts a PKCS #8 private key info to
470 * a PKCS #8 EncryptedPrivateKeyInfo.
472 static int
473 encode_to_pkcs8_key (schema_id schema, const gnutls_datum_t * der_key,
474 const char *password, ASN1_TYPE * out)
476 int result;
477 gnutls_datum_t key = { NULL, 0 };
478 gnutls_datum_t tmp = { NULL, 0 };
479 ASN1_TYPE pkcs8_asn = ASN1_TYPE_EMPTY;
480 struct pbkdf2_params kdf_params;
481 struct pbe_enc_params enc_params;
482 const char *str_oid;
485 if ((result =
486 asn1_create_element (_gnutls_get_pkix (),
487 "PKIX1.pkcs-8-EncryptedPrivateKeyInfo",
488 &pkcs8_asn)) != ASN1_SUCCESS)
490 gnutls_assert ();
491 result = _gnutls_asn2err (result);
492 goto error;
495 /* Write the encryption schema OID
497 result = schema_to_oid (schema, &str_oid);
498 if (result < 0)
500 gnutls_assert ();
501 return result;
504 result =
505 asn1_write_value (pkcs8_asn, "encryptionAlgorithm.algorithm", str_oid, 1);
507 if (result != ASN1_SUCCESS)
509 gnutls_assert ();
510 result = _gnutls_asn2err (result);
511 goto error;
514 /* Generate a symmetric key.
517 result = generate_key (schema, password, &kdf_params, &enc_params, &key);
518 if (result < 0)
520 gnutls_assert ();
521 goto error;
524 result =
525 write_schema_params (schema, pkcs8_asn,
526 "encryptionAlgorithm.parameters", &kdf_params,
527 &enc_params);
528 if (result < 0)
530 gnutls_assert ();
531 goto error;
534 /* Parameters have been encoded. Now
535 * encrypt the Data.
537 result = encrypt_data (der_key, &enc_params, &key, &tmp);
538 if (result < 0)
540 gnutls_assert ();
541 goto error;
544 /* write the encrypted data.
546 result = asn1_write_value (pkcs8_asn, "encryptedData", tmp.data, tmp.size);
547 if (result != ASN1_SUCCESS)
549 gnutls_assert ();
550 result = _gnutls_asn2err (result);
551 goto error;
554 _gnutls_free_datum (&tmp);
555 _gnutls_free_datum (&key);
557 *out = pkcs8_asn;
559 return 0;
561 error:
562 _gnutls_free_datum (&key);
563 _gnutls_free_datum (&tmp);
564 asn1_delete_structure (&pkcs8_asn);
565 return result;
570 * gnutls_x509_privkey_export_pkcs8:
571 * @key: Holds the key
572 * @format: the format of output params. One of PEM or DER.
573 * @password: the password that will be used to encrypt the key.
574 * @flags: an ORed sequence of gnutls_pkcs_encrypt_flags_t
575 * @output_data: will contain a private key PEM or DER encoded
576 * @output_data_size: holds the size of output_data (and will be
577 * replaced by the actual size of parameters)
579 * This function will export the private key to a PKCS8 structure.
580 * Both RSA and DSA keys can be exported. For DSA keys we use
581 * PKCS #11 definitions. If the flags do not specify the encryption
582 * cipher, then the default 3DES (PBES2) will be used.
584 * The @password can be either ASCII or UTF-8 in the default PBES2
585 * encryption schemas, or ASCII for the PKCS12 schemas.
587 * If the buffer provided is not long enough to hold the output, then
588 * *output_data_size is updated and GNUTLS_E_SHORT_MEMORY_BUFFER will
589 * be returned.
591 * If the structure is PEM encoded, it will have a header
592 * of "BEGIN ENCRYPTED PRIVATE KEY" or "BEGIN PRIVATE KEY" if
593 * encryption is not used.
595 * Returns: In case of failure a negative error code will be
596 * returned, and 0 on success.
599 gnutls_x509_privkey_export_pkcs8 (gnutls_x509_privkey_t key,
600 gnutls_x509_crt_fmt_t format,
601 const char *password,
602 unsigned int flags,
603 void *output_data,
604 size_t * output_data_size)
606 ASN1_TYPE pkcs8_asn, pkey_info;
607 int ret;
608 gnutls_datum_t tmp;
609 schema_id schema;
611 if (key == NULL)
613 gnutls_assert ();
614 return GNUTLS_E_INVALID_REQUEST;
617 /* Get the private key info
618 * tmp holds the DER encoding.
620 ret = encode_to_private_key_info (key, &tmp, &pkey_info);
621 if (ret < 0)
623 gnutls_assert ();
624 return ret;
627 schema = _gnutls_pkcs_flags_to_schema (flags);
629 if ((flags & GNUTLS_PKCS_PLAIN) || password == NULL)
631 _gnutls_free_datum (&tmp);
633 ret =
634 _gnutls_x509_export_int (pkey_info, format,
635 PEM_UNENCRYPTED_PKCS8,
636 output_data, output_data_size);
638 asn1_delete_structure (&pkey_info);
640 else
642 asn1_delete_structure (&pkey_info); /* we don't need it */
644 ret = encode_to_pkcs8_key (schema, &tmp, password, &pkcs8_asn);
645 _gnutls_free_datum (&tmp);
647 if (ret < 0)
649 gnutls_assert ();
650 return ret;
653 ret =
654 _gnutls_x509_export_int (pkcs8_asn, format, PEM_PKCS8,
655 output_data, output_data_size);
657 asn1_delete_structure (&pkcs8_asn);
660 return ret;
664 /* Read the parameters cipher, IV, salt etc using the given
665 * schema ID.
667 static int
668 read_pkcs_schema_params (schema_id * schema, const char *password,
669 const uint8_t * data, int data_size,
670 struct pbkdf2_params *kdf_params,
671 struct pbe_enc_params *enc_params)
673 ASN1_TYPE pbes2_asn = ASN1_TYPE_EMPTY;
674 int result;
675 gnutls_datum_t tmp;
677 switch (*schema)
680 case PBES2_GENERIC:
682 /* Now check the key derivation and the encryption
683 * functions.
685 if ((result =
686 asn1_create_element (_gnutls_get_pkix (),
687 "PKIX1.pkcs-5-PBES2-params",
688 &pbes2_asn)) != ASN1_SUCCESS)
690 gnutls_assert ();
691 result = _gnutls_asn2err (result);
692 goto error;
695 /* Decode the parameters.
697 result = asn1_der_decoding (&pbes2_asn, data, data_size, NULL);
698 if (result != ASN1_SUCCESS)
700 gnutls_assert ();
701 result = _gnutls_asn2err (result);
702 goto error;
705 tmp.data = (uint8_t *) data;
706 tmp.size = data_size;
708 result = read_pbkdf2_params (pbes2_asn, &tmp, kdf_params);
709 if (result < 0)
711 gnutls_assert ();
712 result = _gnutls_asn2err (result);
713 goto error;
716 result = read_pbe_enc_params (pbes2_asn, &tmp, enc_params);
717 if (result < 0)
719 gnutls_assert ();
720 result = _gnutls_asn2err (result);
721 goto error;
724 asn1_delete_structure (&pbes2_asn);
726 result = cipher_to_schema (enc_params->cipher);
727 if (result < 0)
729 gnutls_assert ();
730 goto error;
733 *schema = result;
734 return 0;
736 case PKCS12_3DES_SHA1:
737 case PKCS12_ARCFOUR_SHA1:
738 case PKCS12_RC2_40_SHA1:
740 if ((*schema) == PKCS12_3DES_SHA1)
742 enc_params->cipher = GNUTLS_CIPHER_3DES_CBC;
743 enc_params->iv_size = 8;
745 else if ((*schema) == PKCS12_ARCFOUR_SHA1)
747 enc_params->cipher = GNUTLS_CIPHER_ARCFOUR_128;
748 enc_params->iv_size = 0;
750 else if ((*schema) == PKCS12_RC2_40_SHA1)
752 enc_params->cipher = GNUTLS_CIPHER_RC2_40_CBC;
753 enc_params->iv_size = 8;
756 if ((result =
757 asn1_create_element (_gnutls_get_pkix (),
758 "PKIX1.pkcs-12-PbeParams",
759 &pbes2_asn)) != ASN1_SUCCESS)
761 gnutls_assert ();
762 result = _gnutls_asn2err (result);
763 goto error;
766 /* Decode the parameters.
768 result = asn1_der_decoding (&pbes2_asn, data, data_size, NULL);
769 if (result != ASN1_SUCCESS)
771 gnutls_assert ();
772 result = _gnutls_asn2err (result);
773 goto error;
776 result = read_pkcs12_kdf_params (pbes2_asn, kdf_params);
777 if (result < 0)
779 gnutls_assert ();
780 goto error;
783 if (enc_params->iv_size)
785 result =
786 _gnutls_pkcs12_string_to_key (2 /*IV*/, kdf_params->salt,
787 kdf_params->salt_size,
788 kdf_params->iter_count, password,
789 enc_params->iv_size,
790 enc_params->iv);
791 if (result < 0)
793 gnutls_assert ();
794 goto error;
799 asn1_delete_structure (&pbes2_asn);
801 return 0;
803 default:
804 gnutls_assert ();
805 } /* switch */
807 return GNUTLS_E_UNKNOWN_CIPHER_TYPE;
809 error:
810 asn1_delete_structure (&pbes2_asn);
811 return result;
815 /* Converts a PKCS #8 key to
816 * an internal structure (gnutls_private_key)
817 * (normally a PKCS #1 encoded RSA key)
819 static int
820 decode_pkcs8_key (const gnutls_datum_t * raw_key,
821 const char *password, gnutls_x509_privkey_t pkey)
823 int result, len;
824 char enc_oid[64];
825 gnutls_datum_t tmp;
826 ASN1_TYPE pbes2_asn = ASN1_TYPE_EMPTY, pkcs8_asn = ASN1_TYPE_EMPTY;
827 int params_start, params_end, params_len;
828 struct pbkdf2_params kdf_params;
829 struct pbe_enc_params enc_params;
830 schema_id schema;
832 if ((result =
833 asn1_create_element (_gnutls_get_pkix (),
834 "PKIX1.pkcs-8-EncryptedPrivateKeyInfo",
835 &pkcs8_asn)) != ASN1_SUCCESS)
837 gnutls_assert ();
838 result = _gnutls_asn2err (result);
839 goto error;
842 result = asn1_der_decoding (&pkcs8_asn, raw_key->data, raw_key->size, NULL);
843 if (result != ASN1_SUCCESS)
845 gnutls_assert ();
846 result = _gnutls_asn2err (result);
847 goto error;
850 /* Check the encryption schema OID
852 len = sizeof (enc_oid);
853 result =
854 asn1_read_value (pkcs8_asn, "encryptionAlgorithm.algorithm",
855 enc_oid, &len);
856 if (result != ASN1_SUCCESS)
858 gnutls_assert ();
859 goto error;
862 if ((result = check_schema (enc_oid)) < 0)
864 gnutls_assert ();
865 goto error;
868 schema = result;
870 /* Get the DER encoding of the parameters.
872 result =
873 asn1_der_decoding_startEnd (pkcs8_asn, raw_key->data,
874 raw_key->size,
875 "encryptionAlgorithm.parameters",
876 &params_start, &params_end);
877 if (result != ASN1_SUCCESS)
879 gnutls_assert ();
880 result = _gnutls_asn2err (result);
881 goto error;
883 params_len = params_end - params_start + 1;
885 result =
886 read_pkcs_schema_params (&schema, password,
887 &raw_key->data[params_start],
888 params_len, &kdf_params, &enc_params);
890 if (result < 0)
892 gnutls_assert ();
893 goto error;
896 /* Parameters have been decoded. Now
897 * decrypt the EncryptedData.
899 result =
900 decrypt_data (schema, pkcs8_asn, "encryptedData", password,
901 &kdf_params, &enc_params, &tmp);
902 if (result < 0)
904 gnutls_assert ();
905 goto error;
908 asn1_delete_structure (&pkcs8_asn);
910 result = decode_private_key_info (&tmp, pkey);
911 _gnutls_free_datum (&tmp);
913 if (result < 0)
915 /* We've gotten this far. In the real world it's almost certain
916 * that we're dealing with a good file, but wrong password.
917 * Sadly like 90% of random data is somehow valid DER for the
918 * a first small number of bytes, so no easy way to guarantee. */
919 if (result == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND ||
920 result == GNUTLS_E_ASN1_IDENTIFIER_NOT_FOUND ||
921 result == GNUTLS_E_ASN1_DER_ERROR ||
922 result == GNUTLS_E_ASN1_VALUE_NOT_FOUND ||
923 result == GNUTLS_E_ASN1_GENERIC_ERROR ||
924 result == GNUTLS_E_ASN1_VALUE_NOT_VALID ||
925 result == GNUTLS_E_ASN1_TAG_ERROR ||
926 result == GNUTLS_E_ASN1_TAG_IMPLICIT ||
927 result == GNUTLS_E_ASN1_TYPE_ANY_ERROR ||
928 result == GNUTLS_E_ASN1_SYNTAX_ERROR ||
929 result == GNUTLS_E_ASN1_DER_OVERFLOW)
931 result = GNUTLS_E_DECRYPTION_FAILED;
934 gnutls_assert ();
935 goto error;
938 return 0;
940 error:
941 asn1_delete_structure (&pbes2_asn);
942 asn1_delete_structure (&pkcs8_asn);
943 return result;
946 /* Decodes an RSA privateKey from a PKCS8 structure.
948 static int
949 _decode_pkcs8_rsa_key (ASN1_TYPE pkcs8_asn, gnutls_x509_privkey_t pkey)
951 int ret;
952 gnutls_datum_t tmp;
954 ret = _gnutls_x509_read_value (pkcs8_asn, "privateKey", &tmp, 0);
955 if (ret < 0)
957 gnutls_assert ();
958 goto error;
961 pkey->key = _gnutls_privkey_decode_pkcs1_rsa_key (&tmp, pkey);
962 _gnutls_free_datum (&tmp);
963 if (pkey->key == NULL)
965 gnutls_assert ();
966 goto error;
969 ret = 0;
971 error:
972 return ret;
975 /* Decodes an ECC privateKey from a PKCS8 structure.
977 static int
978 _decode_pkcs8_ecc_key (ASN1_TYPE pkcs8_asn, gnutls_x509_privkey_t pkey)
980 int ret;
981 gnutls_datum_t tmp;
983 ret = _gnutls_x509_read_value (pkcs8_asn, "privateKey", &tmp, 0);
984 if (ret < 0)
986 gnutls_assert ();
987 goto error;
990 pkey->key = _gnutls_privkey_decode_ecc_key (&tmp, pkey);
991 _gnutls_free_datum (&tmp);
992 if (pkey->key == NULL)
994 ret = GNUTLS_E_PARSING_ERROR;
995 gnutls_assert ();
996 goto error;
999 ret = 0;
1001 error:
1002 return ret;
1005 /* Decodes an DSA privateKey and params from a PKCS8 structure.
1007 static int
1008 _decode_pkcs8_dsa_key (ASN1_TYPE pkcs8_asn, gnutls_x509_privkey_t pkey)
1010 int ret;
1011 gnutls_datum_t tmp;
1013 ret = _gnutls_x509_read_value (pkcs8_asn, "privateKey", &tmp, 0);
1014 if (ret < 0)
1016 gnutls_assert ();
1017 goto error;
1020 ret = _gnutls_x509_read_der_int (tmp.data, tmp.size, &pkey->params.params[4]);
1021 _gnutls_free_datum (&tmp);
1023 if (ret < 0)
1025 gnutls_assert ();
1026 goto error;
1029 ret =
1030 _gnutls_x509_read_value (pkcs8_asn, "privateKeyAlgorithm.parameters",
1031 &tmp, 0);
1032 if (ret < 0)
1034 gnutls_assert ();
1035 goto error;
1038 ret = _gnutls_x509_read_pubkey_params (GNUTLS_PK_DSA, tmp.data, tmp.size, &pkey->params);
1039 _gnutls_free_datum (&tmp);
1040 if (ret < 0)
1042 gnutls_assert ();
1043 goto error;
1046 /* the public key can be generated as g^x mod p */
1047 pkey->params.params[3] = _gnutls_mpi_alloc_like (pkey->params.params[0]);
1048 if (pkey->params.params[3] == NULL)
1050 gnutls_assert ();
1051 goto error;
1054 _gnutls_mpi_powm (pkey->params.params[3], pkey->params.params[2], pkey->params.params[4],
1055 pkey->params.params[0]);
1057 ret = _gnutls_asn1_encode_privkey (GNUTLS_PK_DSA, &pkey->key, &pkey->params);
1058 if (ret < 0)
1060 gnutls_assert ();
1061 goto error;
1064 pkey->params.params_nr = DSA_PRIVATE_PARAMS;
1066 ret = 0;
1068 error:
1069 return ret;
1073 static int
1074 decode_private_key_info (const gnutls_datum_t * der,
1075 gnutls_x509_privkey_t pkey)
1077 int result, len;
1078 char oid[64];
1079 ASN1_TYPE pkcs8_asn = ASN1_TYPE_EMPTY;
1082 if ((result =
1083 asn1_create_element (_gnutls_get_pkix (),
1084 "PKIX1.pkcs-8-PrivateKeyInfo",
1085 &pkcs8_asn)) != ASN1_SUCCESS)
1087 gnutls_assert ();
1088 result = _gnutls_asn2err (result);
1089 goto error;
1092 result = asn1_der_decoding (&pkcs8_asn, der->data, der->size, NULL);
1093 if (result != ASN1_SUCCESS)
1095 gnutls_assert ();
1096 result = _gnutls_asn2err (result);
1097 goto error;
1100 /* Check the private key algorithm OID
1102 len = sizeof (oid);
1103 result =
1104 asn1_read_value (pkcs8_asn, "privateKeyAlgorithm.algorithm", oid, &len);
1105 if (result != ASN1_SUCCESS)
1107 gnutls_assert ();
1108 result = _gnutls_asn2err (result);
1109 goto error;
1112 /* we only support RSA and DSA private keys.
1115 pkey->pk_algorithm = _gnutls_x509_oid2pk_algorithm(oid);
1116 if (pkey->pk_algorithm == GNUTLS_PK_UNKNOWN)
1118 gnutls_assert ();
1119 _gnutls_debug_log
1120 ("PKCS #8 private key OID '%s' is unsupported.\n", oid);
1121 result = GNUTLS_E_UNKNOWN_PK_ALGORITHM;
1122 goto error;
1125 /* Get the DER encoding of the actual private key.
1128 if (pkey->pk_algorithm == GNUTLS_PK_RSA)
1129 result = _decode_pkcs8_rsa_key (pkcs8_asn, pkey);
1130 else if (pkey->pk_algorithm == GNUTLS_PK_DSA)
1131 result = _decode_pkcs8_dsa_key (pkcs8_asn, pkey);
1132 else if (pkey->pk_algorithm == GNUTLS_PK_EC)
1133 result = _decode_pkcs8_ecc_key (pkcs8_asn, pkey);
1134 else return gnutls_assert_val(GNUTLS_E_UNIMPLEMENTED_FEATURE);
1136 if (result < 0)
1138 gnutls_assert ();
1139 return result;
1142 result = 0;
1144 error:
1145 asn1_delete_structure (&pkcs8_asn);
1147 return result;
1152 * gnutls_x509_privkey_import_pkcs8:
1153 * @key: The structure to store the parsed key
1154 * @data: The DER or PEM encoded key.
1155 * @format: One of DER or PEM
1156 * @password: the password to decrypt the key (if it is encrypted).
1157 * @flags: 0 if encrypted or GNUTLS_PKCS_PLAIN if not encrypted.
1159 * This function will convert the given DER or PEM encoded PKCS8 2.0
1160 * encrypted key to the native gnutls_x509_privkey_t format. The
1161 * output will be stored in @key. Both RSA and DSA keys can be
1162 * imported, and flags can only be used to indicate an unencrypted
1163 * key.
1165 * The @password can be either ASCII or UTF-8 in the default PBES2
1166 * encryption schemas, or ASCII for the PKCS12 schemas.
1168 * If the Certificate is PEM encoded it should have a header of
1169 * "ENCRYPTED PRIVATE KEY", or "PRIVATE KEY". You only need to
1170 * specify the flags if the key is DER encoded, since in that case
1171 * the encryption status cannot be auto-detected.
1173 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
1174 * negative error value.
1177 gnutls_x509_privkey_import_pkcs8 (gnutls_x509_privkey_t key,
1178 const gnutls_datum_t * data,
1179 gnutls_x509_crt_fmt_t format,
1180 const char *password, unsigned int flags)
1182 int result = 0, need_free = 0;
1183 gnutls_datum_t _data;
1185 if (key == NULL)
1187 gnutls_assert ();
1188 return GNUTLS_E_INVALID_REQUEST;
1191 _data.data = data->data;
1192 _data.size = data->size;
1194 key->pk_algorithm = GNUTLS_PK_UNKNOWN;
1196 /* If the Certificate is in PEM format then decode it
1198 if (format == GNUTLS_X509_FMT_PEM)
1200 uint8_t *out;
1202 /* Try the first header
1204 result =
1205 _gnutls_fbase64_decode (PEM_UNENCRYPTED_PKCS8,
1206 data->data, data->size, &out);
1208 if (result < 0)
1209 { /* Try the encrypted header
1211 result =
1212 _gnutls_fbase64_decode (PEM_PKCS8, data->data, data->size, &out);
1214 if (result <= 0)
1216 if (result == 0)
1217 result = GNUTLS_E_INTERNAL_ERROR;
1218 gnutls_assert ();
1219 return result;
1222 else if (flags == 0)
1223 flags |= GNUTLS_PKCS_PLAIN;
1225 _data.data = out;
1226 _data.size = result;
1228 need_free = 1;
1231 if (password == NULL || (flags & GNUTLS_PKCS_PLAIN))
1233 result = decode_private_key_info (&_data, key);
1235 else
1236 { /* encrypted. */
1237 result = decode_pkcs8_key (&_data, password, key);
1240 if (result < 0)
1242 gnutls_assert ();
1243 goto cleanup;
1246 if (need_free)
1247 _gnutls_free_datum (&_data);
1249 /* The key has now been decoded.
1252 return 0;
1254 cleanup:
1255 key->pk_algorithm = GNUTLS_PK_UNKNOWN;
1256 if (need_free)
1257 _gnutls_free_datum (&_data);
1258 return result;
1261 /* Reads the PBKDF2 parameters.
1263 static int
1264 read_pbkdf2_params (ASN1_TYPE pbes2_asn,
1265 const gnutls_datum_t * der, struct pbkdf2_params *params)
1267 int params_start, params_end;
1268 int params_len, len, result;
1269 ASN1_TYPE pbkdf2_asn = ASN1_TYPE_EMPTY;
1270 char oid[64];
1272 memset (params, 0, sizeof (*params));
1274 /* Check the key derivation algorithm
1276 len = sizeof (oid);
1277 result =
1278 asn1_read_value (pbes2_asn, "keyDerivationFunc.algorithm", oid, &len);
1279 if (result != ASN1_SUCCESS)
1281 gnutls_assert ();
1282 return _gnutls_asn2err (result);
1284 _gnutls_hard_log ("keyDerivationFunc.algorithm: %s\n", oid);
1286 if (strcmp (oid, PBKDF2_OID) != 0)
1288 gnutls_assert ();
1289 _gnutls_debug_log
1290 ("PKCS #8 key derivation OID '%s' is unsupported.\n", oid);
1291 return _gnutls_asn2err (result);
1294 result =
1295 asn1_der_decoding_startEnd (pbes2_asn, der->data, der->size,
1296 "keyDerivationFunc.parameters",
1297 &params_start, &params_end);
1298 if (result != ASN1_SUCCESS)
1300 gnutls_assert ();
1301 return _gnutls_asn2err (result);
1303 params_len = params_end - params_start + 1;
1305 /* Now check the key derivation and the encryption
1306 * functions.
1308 if ((result =
1309 asn1_create_element (_gnutls_get_pkix (),
1310 "PKIX1.pkcs-5-PBKDF2-params",
1311 &pbkdf2_asn)) != ASN1_SUCCESS)
1313 gnutls_assert ();
1314 return _gnutls_asn2err (result);
1317 result =
1318 asn1_der_decoding (&pbkdf2_asn, &der->data[params_start],
1319 params_len, NULL);
1320 if (result != ASN1_SUCCESS)
1322 gnutls_assert ();
1323 result = _gnutls_asn2err (result);
1324 goto error;
1327 /* read the salt */
1328 params->salt_size = sizeof (params->salt);
1329 result =
1330 asn1_read_value (pbkdf2_asn, "salt.specified", params->salt,
1331 &params->salt_size);
1332 if (result != ASN1_SUCCESS)
1334 gnutls_assert ();
1335 result = _gnutls_asn2err (result);
1336 goto error;
1338 _gnutls_hard_log ("salt.specified.size: %d\n", params->salt_size);
1340 /* read the iteration count
1342 result =
1343 _gnutls_x509_read_uint (pbkdf2_asn, "iterationCount",
1344 &params->iter_count);
1345 if (result != ASN1_SUCCESS)
1347 gnutls_assert ();
1348 goto error;
1350 _gnutls_hard_log ("iterationCount: %d\n", params->iter_count);
1352 /* read the keylength, if it is set.
1354 result =
1355 _gnutls_x509_read_uint (pbkdf2_asn, "keyLength", &params->key_size);
1356 if (result < 0)
1358 params->key_size = 0;
1360 _gnutls_hard_log ("keyLength: %d\n", params->key_size);
1362 /* We don't read the PRF. We only use the default.
1365 result = 0;
1367 error:
1368 asn1_delete_structure (&pbkdf2_asn);
1369 return result;
1373 /* Reads the PBE parameters from PKCS-12 schemas (*&#%*&#% RSA).
1375 static int
1376 read_pkcs12_kdf_params (ASN1_TYPE pbes2_asn, struct pbkdf2_params *params)
1378 int result;
1380 memset (params, 0, sizeof (*params));
1382 /* read the salt */
1383 params->salt_size = sizeof (params->salt);
1384 result =
1385 asn1_read_value (pbes2_asn, "salt", params->salt, &params->salt_size);
1386 if (result != ASN1_SUCCESS)
1388 gnutls_assert ();
1389 result = _gnutls_asn2err (result);
1390 goto error;
1392 _gnutls_hard_log ("salt.size: %d\n", params->salt_size);
1394 /* read the iteration count
1396 result =
1397 _gnutls_x509_read_uint (pbes2_asn, "iterations", &params->iter_count);
1398 if (result != ASN1_SUCCESS)
1400 gnutls_assert ();
1401 goto error;
1403 _gnutls_hard_log ("iterationCount: %d\n", params->iter_count);
1405 params->key_size = 0;
1407 return 0;
1409 error:
1410 return result;
1414 /* Writes the PBE parameters for PKCS-12 schemas.
1416 static int
1417 write_pkcs12_kdf_params (ASN1_TYPE pbes2_asn,
1418 const struct pbkdf2_params *kdf_params)
1420 int result;
1422 /* write the salt
1424 result =
1425 asn1_write_value (pbes2_asn, "salt",
1426 kdf_params->salt, kdf_params->salt_size);
1427 if (result != ASN1_SUCCESS)
1429 gnutls_assert ();
1430 result = _gnutls_asn2err (result);
1431 goto error;
1433 _gnutls_hard_log ("salt.size: %d\n", kdf_params->salt_size);
1435 /* write the iteration count
1437 result =
1438 _gnutls_x509_write_uint32 (pbes2_asn, "iterations",
1439 kdf_params->iter_count);
1440 if (result < 0)
1442 gnutls_assert ();
1443 goto error;
1445 _gnutls_hard_log ("iterationCount: %d\n", kdf_params->iter_count);
1447 return 0;
1449 error:
1450 return result;
1455 /* Converts an OID to a gnutls cipher type.
1457 inline static int
1458 oid2cipher (const char *oid, gnutls_cipher_algorithm_t * algo)
1461 *algo = 0;
1463 if (strcmp (oid, DES_EDE3_CBC_OID) == 0)
1465 *algo = GNUTLS_CIPHER_3DES_CBC;
1466 return 0;
1468 else if (strcmp (oid, DES_CBC_OID) == 0)
1470 *algo = GNUTLS_CIPHER_DES_CBC;
1471 return 0;
1473 else if (strcmp (oid, AES_128_CBC_OID) == 0)
1475 *algo = GNUTLS_CIPHER_AES_128_CBC;
1476 return 0;
1478 else if (strcmp (oid, AES_192_CBC_OID) == 0)
1480 *algo = GNUTLS_CIPHER_AES_192_CBC;
1481 return 0;
1483 else if (strcmp (oid, AES_256_CBC_OID) == 0)
1485 *algo = GNUTLS_CIPHER_AES_256_CBC;
1486 return 0;
1489 _gnutls_debug_log ("PKCS #8 encryption OID '%s' is unsupported.\n", oid);
1490 return GNUTLS_E_UNKNOWN_CIPHER_TYPE;
1495 static int
1496 read_pbe_enc_params (ASN1_TYPE pbes2_asn,
1497 const gnutls_datum_t * der,
1498 struct pbe_enc_params *params)
1500 int params_start, params_end;
1501 int params_len, len, result;
1502 ASN1_TYPE pbe_asn = ASN1_TYPE_EMPTY;
1503 char oid[64];
1504 const char *eparams;
1506 memset (params, 0, sizeof (*params));
1508 /* Check the encryption algorithm
1510 len = sizeof (oid);
1511 result =
1512 asn1_read_value (pbes2_asn, "encryptionScheme.algorithm", oid, &len);
1513 if (result != ASN1_SUCCESS)
1515 gnutls_assert ();
1516 goto error;
1518 _gnutls_hard_log ("encryptionScheme.algorithm: %s\n", oid);
1520 if ((result = oid2cipher (oid, &params->cipher)) < 0)
1522 gnutls_assert ();
1523 goto error;
1526 result =
1527 asn1_der_decoding_startEnd (pbes2_asn, der->data, der->size,
1528 "encryptionScheme.parameters",
1529 &params_start, &params_end);
1530 if (result != ASN1_SUCCESS)
1532 gnutls_assert ();
1533 return _gnutls_asn2err (result);
1535 params_len = params_end - params_start + 1;
1537 /* Now check the encryption parameters.
1539 eparams = cipher_to_pkcs_params (params->cipher, NULL);
1540 if (eparams == NULL)
1542 gnutls_assert ();
1543 return GNUTLS_E_INVALID_REQUEST;
1546 if ((result =
1547 asn1_create_element (_gnutls_get_pkix (),
1548 eparams, &pbe_asn)) != ASN1_SUCCESS)
1550 gnutls_assert ();
1551 return _gnutls_asn2err (result);
1554 result =
1555 asn1_der_decoding (&pbe_asn, &der->data[params_start], params_len, NULL);
1556 if (result != ASN1_SUCCESS)
1558 gnutls_assert ();
1559 result = _gnutls_asn2err (result);
1560 goto error;
1563 /* read the IV */
1564 params->iv_size = sizeof (params->iv);
1565 result = asn1_read_value (pbe_asn, "", params->iv, &params->iv_size);
1566 if (result != ASN1_SUCCESS)
1568 gnutls_assert ();
1569 result = _gnutls_asn2err (result);
1570 goto error;
1572 _gnutls_hard_log ("IV.size: %d\n", params->iv_size);
1574 result = 0;
1576 error:
1577 asn1_delete_structure (&pbe_asn);
1578 return result;
1582 static int
1583 decrypt_data (schema_id schema, ASN1_TYPE pkcs8_asn,
1584 const char *root, const char *password,
1585 const struct pbkdf2_params *kdf_params,
1586 const struct pbe_enc_params *enc_params,
1587 gnutls_datum_t * decrypted_data)
1589 int result;
1590 int data_size;
1591 uint8_t *data = NULL, *key = NULL;
1592 gnutls_datum_t dkey, d_iv;
1593 cipher_hd_st ch;
1594 int ch_init = 0;
1595 int key_size;
1597 data_size = 0;
1598 result = asn1_read_value (pkcs8_asn, root, NULL, &data_size);
1599 if (result != ASN1_MEM_ERROR)
1601 gnutls_assert ();
1602 return _gnutls_asn2err (result);
1605 data = gnutls_malloc (data_size);
1606 if (data == NULL)
1608 gnutls_assert ();
1609 return GNUTLS_E_MEMORY_ERROR;
1612 result = asn1_read_value (pkcs8_asn, root, data, &data_size);
1613 if (result != ASN1_SUCCESS)
1615 gnutls_assert ();
1616 result = _gnutls_asn2err (result);
1617 goto error;
1620 if (kdf_params->key_size == 0)
1622 key_size = gnutls_cipher_get_key_size (enc_params->cipher);
1624 else
1625 key_size = kdf_params->key_size;
1627 key = gnutls_malloc (key_size);
1628 if (key == NULL)
1630 gnutls_assert ();
1631 result = GNUTLS_E_MEMORY_ERROR;
1632 goto error;
1635 /* generate the key
1637 switch (schema)
1639 case PBES2_3DES:
1640 case PBES2_AES_128:
1641 case PBES2_AES_192:
1642 case PBES2_AES_256:
1644 result = _gnutls_pbkdf2_sha1 (password, strlen (password),
1645 kdf_params->salt, kdf_params->salt_size,
1646 kdf_params->iter_count, key, key_size);
1648 if (result < 0)
1650 gnutls_assert ();
1651 goto error;
1653 break;
1654 default:
1655 result =
1656 _gnutls_pkcs12_string_to_key (1 /*KEY*/, kdf_params->salt,
1657 kdf_params->salt_size,
1658 kdf_params->iter_count, password,
1659 key_size, key);
1661 if (result < 0)
1663 gnutls_assert ();
1664 goto error;
1668 /* do the decryption.
1670 dkey.data = key;
1671 dkey.size = key_size;
1673 d_iv.data = (uint8_t *) enc_params->iv;
1674 d_iv.size = enc_params->iv_size;
1675 result = _gnutls_cipher_init (&ch, enc_params->cipher, &dkey, &d_iv, 0);
1677 gnutls_free (key);
1678 key = NULL;
1680 if (result < 0)
1682 gnutls_assert ();
1683 goto error;
1686 ch_init = 1;
1688 result = _gnutls_cipher_decrypt (&ch, data, data_size);
1689 if (result < 0)
1691 gnutls_assert ();
1692 goto error;
1695 decrypted_data->data = data;
1697 if (gnutls_cipher_get_block_size (enc_params->cipher) != 1)
1698 decrypted_data->size = data_size - data[data_size - 1];
1699 else
1700 decrypted_data->size = data_size;
1702 _gnutls_cipher_deinit (&ch);
1704 return 0;
1706 error:
1707 gnutls_free (data);
1708 gnutls_free (key);
1709 if (ch_init != 0)
1710 _gnutls_cipher_deinit (&ch);
1711 return result;
1715 /* Writes the PBKDF2 parameters.
1717 static int
1718 write_pbkdf2_params (ASN1_TYPE pbes2_asn,
1719 const struct pbkdf2_params *kdf_params)
1721 int result;
1722 ASN1_TYPE pbkdf2_asn = ASN1_TYPE_EMPTY;
1723 uint8_t tmp[64];
1725 /* Write the key derivation algorithm
1727 result =
1728 asn1_write_value (pbes2_asn, "keyDerivationFunc.algorithm",
1729 PBKDF2_OID, 1);
1730 if (result != ASN1_SUCCESS)
1732 gnutls_assert ();
1733 return _gnutls_asn2err (result);
1736 /* Now write the key derivation and the encryption
1737 * functions.
1739 if ((result =
1740 asn1_create_element (_gnutls_get_pkix (),
1741 "PKIX1.pkcs-5-PBKDF2-params",
1742 &pbkdf2_asn)) != ASN1_SUCCESS)
1744 gnutls_assert ();
1745 return _gnutls_asn2err (result);
1748 result = asn1_write_value (pbkdf2_asn, "salt", "specified", 1);
1749 if (result != ASN1_SUCCESS)
1751 gnutls_assert ();
1752 result = _gnutls_asn2err (result);
1753 goto error;
1756 /* write the salt
1758 result =
1759 asn1_write_value (pbkdf2_asn, "salt.specified",
1760 kdf_params->salt, kdf_params->salt_size);
1761 if (result != ASN1_SUCCESS)
1763 gnutls_assert ();
1764 result = _gnutls_asn2err (result);
1765 goto error;
1767 _gnutls_hard_log ("salt.specified.size: %d\n", kdf_params->salt_size);
1769 /* write the iteration count
1771 _gnutls_write_uint32 (kdf_params->iter_count, tmp);
1773 result = asn1_write_value (pbkdf2_asn, "iterationCount", tmp, 4);
1774 if (result != ASN1_SUCCESS)
1776 gnutls_assert ();
1777 result = _gnutls_asn2err (result);
1778 goto error;
1780 _gnutls_hard_log ("iterationCount: %d\n", kdf_params->iter_count);
1782 /* write the keylength, if it is set.
1784 result = asn1_write_value (pbkdf2_asn, "keyLength", NULL, 0);
1785 if (result != ASN1_SUCCESS)
1787 gnutls_assert ();
1788 result = _gnutls_asn2err (result);
1789 goto error;
1792 /* We write an emptry prf.
1794 result = asn1_write_value (pbkdf2_asn, "prf", NULL, 0);
1795 if (result != ASN1_SUCCESS)
1797 gnutls_assert ();
1798 result = _gnutls_asn2err (result);
1799 goto error;
1802 /* now encode them an put the DER output
1803 * in the keyDerivationFunc.parameters
1805 result = _gnutls_x509_der_encode_and_copy (pbkdf2_asn, "",
1806 pbes2_asn,
1807 "keyDerivationFunc.parameters",
1809 if (result < 0)
1811 gnutls_assert ();
1812 goto error;
1815 return 0;
1817 error:
1818 asn1_delete_structure (&pbkdf2_asn);
1819 return result;
1824 static int
1825 write_pbe_enc_params (ASN1_TYPE pbes2_asn,
1826 const struct pbe_enc_params *params)
1828 int result;
1829 ASN1_TYPE pbe_asn = ASN1_TYPE_EMPTY;
1830 const char *oid, *eparams;
1832 /* Write the encryption algorithm
1834 eparams = cipher_to_pkcs_params (params->cipher, &oid);
1835 if (eparams == NULL)
1837 gnutls_assert ();
1838 return GNUTLS_E_INVALID_REQUEST;
1841 result = asn1_write_value (pbes2_asn, "encryptionScheme.algorithm", oid, 1);
1842 if (result != ASN1_SUCCESS)
1844 gnutls_assert ();
1845 goto error;
1847 _gnutls_hard_log ("encryptionScheme.algorithm: %s\n", oid);
1849 /* Now check the encryption parameters.
1851 if ((result =
1852 asn1_create_element (_gnutls_get_pkix (),
1853 eparams, &pbe_asn)) != ASN1_SUCCESS)
1855 gnutls_assert ();
1856 return _gnutls_asn2err (result);
1859 /* read the salt */
1860 result = asn1_write_value (pbe_asn, "", params->iv, params->iv_size);
1861 if (result != ASN1_SUCCESS)
1863 gnutls_assert ();
1864 result = _gnutls_asn2err (result);
1865 goto error;
1867 _gnutls_hard_log ("IV.size: %d\n", params->iv_size);
1869 /* now encode them an put the DER output
1870 * in the encryptionScheme.parameters
1872 result = _gnutls_x509_der_encode_and_copy (pbe_asn, "",
1873 pbes2_asn,
1874 "encryptionScheme.parameters",
1876 if (result < 0)
1878 gnutls_assert ();
1879 goto error;
1882 return 0;
1884 error:
1885 asn1_delete_structure (&pbe_asn);
1886 return result;
1890 /* Generates a key and also stores the key parameters.
1892 static int
1893 generate_key (schema_id schema,
1894 const char *password,
1895 struct pbkdf2_params *kdf_params,
1896 struct pbe_enc_params *enc_params, gnutls_datum_t * key)
1898 unsigned char rnd[2];
1899 int ret;
1901 ret = _gnutls_rnd (GNUTLS_RND_RANDOM, rnd, 2);
1902 if (ret < 0)
1904 gnutls_assert ();
1905 return ret;
1908 /* generate salt */
1909 kdf_params->salt_size =
1910 MIN (sizeof (kdf_params->salt), (unsigned) (10 + (rnd[1] % 10)));
1912 switch (schema)
1914 case PBES2_3DES:
1915 enc_params->cipher = GNUTLS_CIPHER_3DES_CBC;
1916 break;
1917 case PBES2_AES_128:
1918 enc_params->cipher = GNUTLS_CIPHER_AES_128_CBC;
1919 break;
1920 case PBES2_AES_192:
1921 enc_params->cipher = GNUTLS_CIPHER_AES_192_CBC;
1922 break;
1923 case PBES2_AES_256:
1924 enc_params->cipher = GNUTLS_CIPHER_AES_256_CBC;
1925 break;
1926 /* non PBES2 algorithms */
1927 case PKCS12_ARCFOUR_SHA1:
1928 enc_params->cipher = GNUTLS_CIPHER_ARCFOUR_128;
1929 kdf_params->salt_size = 8;
1930 break;
1931 case PKCS12_3DES_SHA1:
1932 enc_params->cipher = GNUTLS_CIPHER_3DES_CBC;
1933 kdf_params->salt_size = 8;
1934 break;
1935 case PKCS12_RC2_40_SHA1:
1936 enc_params->cipher = GNUTLS_CIPHER_RC2_40_CBC;
1937 kdf_params->salt_size = 8;
1938 break;
1939 default:
1940 gnutls_assert ();
1941 return GNUTLS_E_INVALID_REQUEST;
1944 ret = _gnutls_rnd (GNUTLS_RND_RANDOM, kdf_params->salt,
1945 kdf_params->salt_size);
1946 if (ret < 0)
1948 gnutls_assert ();
1949 return GNUTLS_E_RANDOM_FAILED;
1952 kdf_params->iter_count = 256 + rnd[0];
1953 key->size = kdf_params->key_size =
1954 gnutls_cipher_get_key_size (enc_params->cipher);
1956 enc_params->iv_size = _gnutls_cipher_get_iv_size (enc_params->cipher);
1957 key->data = gnutls_malloc (key->size);
1958 if (key->data == NULL)
1960 gnutls_assert ();
1961 return GNUTLS_E_MEMORY_ERROR;
1964 /* now generate the key.
1967 switch (schema)
1969 case PBES2_3DES:
1970 case PBES2_AES_128:
1971 case PBES2_AES_192:
1972 case PBES2_AES_256:
1974 ret = _gnutls_pbkdf2_sha1 (password, strlen (password),
1975 kdf_params->salt, kdf_params->salt_size,
1976 kdf_params->iter_count,
1977 key->data, kdf_params->key_size);
1978 if (ret < 0)
1980 gnutls_assert ();
1981 return ret;
1984 if (enc_params->iv_size)
1986 ret = _gnutls_rnd (GNUTLS_RND_NONCE,
1987 enc_params->iv, enc_params->iv_size);
1988 if (ret < 0)
1990 gnutls_assert ();
1991 return ret;
1994 break;
1996 default:
1997 ret =
1998 _gnutls_pkcs12_string_to_key (1 /*KEY*/, kdf_params->salt,
1999 kdf_params->salt_size,
2000 kdf_params->iter_count, password,
2001 kdf_params->key_size, key->data);
2002 if (ret < 0)
2004 gnutls_assert ();
2005 return ret;
2008 /* Now generate the IV
2010 if (enc_params->iv_size)
2012 ret =
2013 _gnutls_pkcs12_string_to_key (2 /*IV*/, kdf_params->salt,
2014 kdf_params->salt_size,
2015 kdf_params->iter_count, password,
2016 enc_params->iv_size,
2017 enc_params->iv);
2018 if (ret < 0)
2020 gnutls_assert ();
2021 return ret;
2027 return 0;
2031 /* Encodes the parameters to be written in the encryptionAlgorithm.parameters
2032 * part.
2034 static int
2035 write_schema_params (schema_id schema, ASN1_TYPE pkcs8_asn,
2036 const char *where,
2037 const struct pbkdf2_params *kdf_params,
2038 const struct pbe_enc_params *enc_params)
2040 int result;
2041 ASN1_TYPE pbes2_asn = ASN1_TYPE_EMPTY;
2043 switch (schema)
2045 case PBES2_3DES:
2046 case PBES2_AES_128:
2047 case PBES2_AES_192:
2048 case PBES2_AES_256:
2049 if ((result =
2050 asn1_create_element (_gnutls_get_pkix (),
2051 "PKIX1.pkcs-5-PBES2-params",
2052 &pbes2_asn)) != ASN1_SUCCESS)
2054 gnutls_assert ();
2055 return _gnutls_asn2err (result);
2058 result = write_pbkdf2_params (pbes2_asn, kdf_params);
2059 if (result < 0)
2061 gnutls_assert ();
2062 goto error;
2065 result = write_pbe_enc_params (pbes2_asn, enc_params);
2066 if (result < 0)
2068 gnutls_assert ();
2069 goto error;
2072 result = _gnutls_x509_der_encode_and_copy (pbes2_asn, "",
2073 pkcs8_asn, where, 0);
2074 if (result < 0)
2076 gnutls_assert ();
2077 goto error;
2080 asn1_delete_structure (&pbes2_asn);
2081 break;
2083 default:
2085 if ((result =
2086 asn1_create_element (_gnutls_get_pkix (),
2087 "PKIX1.pkcs-12-PbeParams",
2088 &pbes2_asn)) != ASN1_SUCCESS)
2090 gnutls_assert ();
2091 result = _gnutls_asn2err (result);
2092 goto error;
2095 result = write_pkcs12_kdf_params (pbes2_asn, kdf_params);
2096 if (result < 0)
2098 gnutls_assert ();
2099 goto error;
2102 result = _gnutls_x509_der_encode_and_copy (pbes2_asn, "",
2103 pkcs8_asn, where, 0);
2104 if (result < 0)
2106 gnutls_assert ();
2107 goto error;
2110 asn1_delete_structure (&pbes2_asn);
2114 return 0;
2116 error:
2117 asn1_delete_structure (&pbes2_asn);
2118 return result;
2122 static int
2123 encrypt_data (const gnutls_datum_t * plain,
2124 const struct pbe_enc_params *enc_params,
2125 gnutls_datum_t * key, gnutls_datum_t * encrypted)
2127 int result;
2128 int data_size;
2129 uint8_t *data = NULL;
2130 gnutls_datum_t d_iv;
2131 cipher_hd_st ch;
2132 int ch_init = 0;
2133 uint8_t pad, pad_size;
2135 pad_size = gnutls_cipher_get_block_size (enc_params->cipher);
2137 if (pad_size == 1) /* stream */
2138 pad_size = 0;
2140 data = gnutls_malloc (plain->size + pad_size);
2141 if (data == NULL)
2143 gnutls_assert ();
2144 return GNUTLS_E_MEMORY_ERROR;
2147 memcpy (data, plain->data, plain->size);
2149 if (pad_size > 0)
2151 pad = pad_size - (plain->size % pad_size);
2152 if (pad == 0)
2153 pad = pad_size;
2154 memset (&data[plain->size], pad, pad);
2156 else
2157 pad = 0;
2159 data_size = plain->size + pad;
2161 d_iv.data = (uint8_t *) enc_params->iv;
2162 d_iv.size = enc_params->iv_size;
2163 result = _gnutls_cipher_init (&ch, enc_params->cipher, key, &d_iv, 1);
2165 if (result < 0)
2167 gnutls_assert ();
2168 goto error;
2171 ch_init = 1;
2173 result = _gnutls_cipher_encrypt (&ch, data, data_size);
2174 if (result < 0)
2176 gnutls_assert ();
2177 goto error;
2180 encrypted->data = data;
2181 encrypted->size = data_size;
2183 _gnutls_cipher_deinit (&ch);
2185 return 0;
2187 error:
2188 gnutls_free (data);
2189 if (ch_init != 0)
2190 _gnutls_cipher_deinit (&ch);
2191 return result;
2194 /* Decrypts a PKCS #7 encryptedData. The output is allocated
2195 * and stored in dec.
2198 _gnutls_pkcs7_decrypt_data (const gnutls_datum_t * data,
2199 const char *password, gnutls_datum_t * dec)
2201 int result, len;
2202 char enc_oid[64];
2203 gnutls_datum_t tmp;
2204 ASN1_TYPE pbes2_asn = ASN1_TYPE_EMPTY, pkcs7_asn = ASN1_TYPE_EMPTY;
2205 int params_start, params_end, params_len;
2206 struct pbkdf2_params kdf_params;
2207 struct pbe_enc_params enc_params;
2208 schema_id schema;
2210 if ((result =
2211 asn1_create_element (_gnutls_get_pkix (),
2212 "PKIX1.pkcs-7-EncryptedData",
2213 &pkcs7_asn)) != ASN1_SUCCESS)
2215 gnutls_assert ();
2216 result = _gnutls_asn2err (result);
2217 goto error;
2220 result = asn1_der_decoding (&pkcs7_asn, data->data, data->size, NULL);
2221 if (result != ASN1_SUCCESS)
2223 gnutls_assert ();
2224 result = _gnutls_asn2err (result);
2225 goto error;
2228 /* Check the encryption schema OID
2230 len = sizeof (enc_oid);
2231 result =
2232 asn1_read_value (pkcs7_asn,
2233 "encryptedContentInfo.contentEncryptionAlgorithm.algorithm",
2234 enc_oid, &len);
2235 if (result != ASN1_SUCCESS)
2237 gnutls_assert ();
2238 result = _gnutls_asn2err (result);
2239 goto error;
2242 if ((result = check_schema (enc_oid)) < 0)
2244 gnutls_assert ();
2245 goto error;
2247 schema = result;
2249 /* Get the DER encoding of the parameters.
2251 result =
2252 asn1_der_decoding_startEnd (pkcs7_asn, data->data, data->size,
2253 "encryptedContentInfo.contentEncryptionAlgorithm.parameters",
2254 &params_start, &params_end);
2255 if (result != ASN1_SUCCESS)
2257 gnutls_assert ();
2258 result = _gnutls_asn2err (result);
2259 goto error;
2261 params_len = params_end - params_start + 1;
2263 result =
2264 read_pkcs_schema_params (&schema, password,
2265 &data->data[params_start],
2266 params_len, &kdf_params, &enc_params);
2267 if (result < ASN1_SUCCESS)
2269 gnutls_assert ();
2270 result = _gnutls_asn2err (result);
2271 goto error;
2274 /* Parameters have been decoded. Now
2275 * decrypt the EncryptedData.
2278 result =
2279 decrypt_data (schema, pkcs7_asn,
2280 "encryptedContentInfo.encryptedContent", password,
2281 &kdf_params, &enc_params, &tmp);
2282 if (result < 0)
2284 gnutls_assert ();
2285 goto error;
2288 asn1_delete_structure (&pkcs7_asn);
2290 *dec = tmp;
2292 return 0;
2294 error:
2295 asn1_delete_structure (&pbes2_asn);
2296 asn1_delete_structure (&pkcs7_asn);
2297 return result;
2300 /* Encrypts to a PKCS #7 encryptedData. The output is allocated
2301 * and stored in enc.
2304 _gnutls_pkcs7_encrypt_data (schema_id schema,
2305 const gnutls_datum_t * data,
2306 const char *password, gnutls_datum_t * enc)
2308 int result;
2309 gnutls_datum_t key = { NULL, 0 };
2310 gnutls_datum_t tmp = { NULL, 0 };
2311 ASN1_TYPE pkcs7_asn = ASN1_TYPE_EMPTY;
2312 struct pbkdf2_params kdf_params;
2313 struct pbe_enc_params enc_params;
2314 const char *str_oid;
2316 if ((result =
2317 asn1_create_element (_gnutls_get_pkix (),
2318 "PKIX1.pkcs-7-EncryptedData",
2319 &pkcs7_asn)) != ASN1_SUCCESS)
2321 gnutls_assert ();
2322 result = _gnutls_asn2err (result);
2323 goto error;
2326 /* Write the encryption schema OID
2328 result = schema_to_oid (schema, &str_oid);
2329 if (result < 0)
2331 gnutls_assert ();
2332 return result;
2335 result =
2336 asn1_write_value (pkcs7_asn,
2337 "encryptedContentInfo.contentEncryptionAlgorithm.algorithm",
2338 str_oid, 1);
2340 if (result != ASN1_SUCCESS)
2342 gnutls_assert ();
2343 result = _gnutls_asn2err (result);
2344 goto error;
2347 /* Generate a symmetric key.
2350 result = generate_key (schema, password, &kdf_params, &enc_params, &key);
2351 if (result < 0)
2353 gnutls_assert ();
2354 goto error;
2357 result = write_schema_params (schema, pkcs7_asn,
2358 "encryptedContentInfo.contentEncryptionAlgorithm.parameters",
2359 &kdf_params, &enc_params);
2360 if (result < 0)
2362 gnutls_assert ();
2363 goto error;
2366 /* Parameters have been encoded. Now
2367 * encrypt the Data.
2369 result = encrypt_data (data, &enc_params, &key, &tmp);
2370 if (result < 0)
2372 gnutls_assert ();
2373 goto error;
2376 /* write the encrypted data.
2378 result =
2379 asn1_write_value (pkcs7_asn,
2380 "encryptedContentInfo.encryptedContent", tmp.data,
2381 tmp.size);
2382 if (result != ASN1_SUCCESS)
2384 gnutls_assert ();
2385 result = _gnutls_asn2err (result);
2386 goto error;
2389 _gnutls_free_datum (&tmp);
2390 _gnutls_free_datum (&key);
2392 /* Now write the rest of the pkcs-7 stuff.
2395 result = _gnutls_x509_write_uint32 (pkcs7_asn, "version", 0);
2396 if (result < 0)
2398 gnutls_assert ();
2399 goto error;
2402 result =
2403 asn1_write_value (pkcs7_asn, "encryptedContentInfo.contentType",
2404 DATA_OID, 1);
2405 if (result != ASN1_SUCCESS)
2407 gnutls_assert ();
2408 result = _gnutls_asn2err (result);
2409 goto error;
2412 result = asn1_write_value (pkcs7_asn, "unprotectedAttrs", NULL, 0);
2413 if (result != ASN1_SUCCESS)
2415 gnutls_assert ();
2416 result = _gnutls_asn2err (result);
2417 goto error;
2420 /* Now encode and copy the DER stuff.
2422 result = _gnutls_x509_der_encode (pkcs7_asn, "", enc, 0);
2424 asn1_delete_structure (&pkcs7_asn);
2426 if (result < 0)
2428 gnutls_assert ();
2429 goto error;
2433 error:
2434 _gnutls_free_datum (&key);
2435 _gnutls_free_datum (&tmp);
2436 asn1_delete_structure (&pkcs7_asn);
2437 return result;