1 /* minip12.c - A minimal pkcs-12 implementation.
2 * Copyright (C) 2002, 2003, 2004, 2006, 2011 Free Software Foundation, Inc.
3 * Copyright (C) 2014 Werner Koch
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <https://www.gnu.org/licenses/>.
36 #include "../common/logging.h"
37 #include "../common/utf8conv.h"
41 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
63 TAG_OBJECT_DESCRIPTOR = 7,
67 TAG_EMBEDDED_PDV = 11,
69 TAG_REALTIVE_OID = 13,
72 TAG_NUMERIC_STRING = 18,
73 TAG_PRINTABLE_STRING = 19,
74 TAG_TELETEX_STRING = 20,
75 TAG_VIDEOTEX_STRING = 21,
78 TAG_GENERALIZED_TIME = 24,
79 TAG_GRAPHIC_STRING = 25,
80 TAG_VISIBLE_STRING = 26,
81 TAG_GENERAL_STRING = 27,
82 TAG_UNIVERSAL_STRING = 28,
83 TAG_CHARACTER_STRING = 29,
88 static unsigned char const oid_data[9] = {
89 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01 };
90 static unsigned char const oid_encryptedData[9] = {
91 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x06 };
92 static unsigned char const oid_pkcs_12_keyBag[11] = {
93 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x01 };
94 static unsigned char const oid_pkcs_12_pkcs_8ShroudedKeyBag[11] = {
95 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x02 };
96 static unsigned char const oid_pkcs_12_CertBag[11] = {
97 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x03 };
98 static unsigned char const oid_pkcs_12_CrlBag[11] = {
99 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x04 };
101 static unsigned char const oid_pbeWithSHAAnd3_KeyTripleDES_CBC[10] = {
102 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x03 };
103 static unsigned char const oid_pbeWithSHAAnd40BitRC2_CBC[10] = {
104 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x06 };
105 static unsigned char const oid_x509Certificate_for_pkcs_12[10] = {
106 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x16, 0x01 };
108 static unsigned char const oid_pkcs5PBKDF2[9] = {
109 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0C };
110 static unsigned char const oid_pkcs5PBES2[9] = {
111 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0D };
112 static unsigned char const oid_aes128_CBC[9] = {
113 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x02 };
115 static unsigned char const oid_rsaEncryption[9] = {
116 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 };
119 static unsigned char const data_3desiter2048[30] = {
120 0x30, 0x1C, 0x06, 0x0A, 0x2A, 0x86, 0x48, 0x86,
121 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x03, 0x30, 0x0E,
122 0x04, 0x08, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
123 0xFF, 0xFF, 0x02, 0x02, 0x08, 0x00 };
124 #define DATA_3DESITER2048_SALT_OFF 18
126 static unsigned char const data_rc2iter2048[30] = {
127 0x30, 0x1C, 0x06, 0x0A, 0x2A, 0x86, 0x48, 0x86,
128 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x06, 0x30, 0x0E,
129 0x04, 0x08, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
130 0xFF, 0xFF, 0x02, 0x02, 0x08, 0x00 };
131 #define DATA_RC2ITER2048_SALT_OFF 18
133 static unsigned char const data_mactemplate[51] = {
134 0x30, 0x31, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05,
135 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04,
136 0x14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
137 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
138 0xff, 0xff, 0xff, 0xff, 0xff, 0x04, 0x08, 0xff,
139 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02,
141 #define DATA_MACTEMPLATE_MAC_OFF 17
142 #define DATA_MACTEMPLATE_SALT_OFF 39
144 static unsigned char const data_attrtemplate[106] = {
145 0x31, 0x7c, 0x30, 0x55, 0x06, 0x09, 0x2a, 0x86,
146 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x14, 0x31,
147 0x48, 0x1e, 0x46, 0x00, 0x47, 0x00, 0x6e, 0x00,
148 0x75, 0x00, 0x50, 0x00, 0x47, 0x00, 0x20, 0x00,
149 0x65, 0x00, 0x78, 0x00, 0x70, 0x00, 0x6f, 0x00,
150 0x72, 0x00, 0x74, 0x00, 0x65, 0x00, 0x64, 0x00,
151 0x20, 0x00, 0x63, 0x00, 0x65, 0x00, 0x72, 0x00,
152 0x74, 0x00, 0x69, 0x00, 0x66, 0x00, 0x69, 0x00,
153 0x63, 0x00, 0x61, 0x00, 0x74, 0x00, 0x65, 0x00,
154 0x20, 0x00, 0x66, 0x00, 0x66, 0x00, 0x66, 0x00,
155 0x66, 0x00, 0x66, 0x00, 0x66, 0x00, 0x66, 0x00,
156 0x66, 0x30, 0x23, 0x06, 0x09, 0x2a, 0x86, 0x48,
157 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x15, 0x31, 0x16,
158 0x04, 0x14 }; /* Need to append SHA-1 digest. */
159 #define DATA_ATTRTEMPLATE_KEYID_OFF 73
163 unsigned char *buffer;
173 unsigned long length; /* length part of the TLV */
175 int ndef; /* It is an indefinite length */
179 /* Parse the buffer at the address BUFFER which is of SIZE and return
180 the tag and the length part from the TLV triplet. Update BUFFER
181 and SIZE on success. Checks that the encoded length does not
182 exhaust the length of the provided buffer. */
184 parse_tag (unsigned char const **buffer, size_t *size, struct tag_info *ti)
188 const unsigned char *buf = *buffer;
189 size_t length = *size;
197 return -1; /* premature eof */
198 c = *buf++; length--;
201 ti->class = (c & 0xc0) >> 6;
202 ti->is_constructed = !!(c & 0x20);
212 return -1; /* premature eof */
213 c = *buf++; length--;
223 return -1; /* prematureeof */
224 c = *buf++; length--;
232 return -1; /* forbidden length value */
235 unsigned long len = 0;
236 int count = c & 0x7f;
238 for (; count; count--)
242 return -1; /* premature_eof */
243 c = *buf++; length--;
250 if (ti->class == UNIVERSAL && !ti->tag)
253 if (ti->length > length)
254 return -1; /* data larger than buffer. */
262 /* Given an ASN.1 chunk of a structure like:
264 24 NDEF: OCTET STRING -- This is not passed to us
265 04 1: OCTET STRING -- INPUT point s to here
272 : } -- This denotes a Null tag and are the last
273 -- two bytes in INPUT.
275 Create a new buffer with the content of that octet string. INPUT
276 is the original buffer with a length as stored at LENGTH. Returns
277 NULL on error or a new malloced buffer with the length of this new
278 buffer stored at LENGTH and the number of bytes parsed from input
279 are added to the value stored at INPUT_CONSUMED. INPUT_CONSUMED is
280 allowed to be passed as NULL if the caller is not interested in
282 static unsigned char *
283 cram_octet_string (const unsigned char *input, size_t *length,
284 size_t *input_consumed)
286 const unsigned char *s = input;
288 unsigned char *output, *d;
291 /* Allocate output buf. We know that it won't be longer than the
293 d = output = gcry_malloc (n);
299 if (parse_tag (&s, &n, &ti))
301 if (ti.class == UNIVERSAL && ti.tag == TAG_OCTET_STRING
302 && !ti.ndef && !ti.is_constructed)
304 memcpy (d, s, ti.length);
309 else if (ti.class == UNIVERSAL && !ti.tag && !ti.is_constructed)
316 *length = d - output;
318 *input_consumed += s - input;
323 *input_consumed += s - input;
331 string_to_key (int id, char *salt, size_t saltlen, int iter, const char *pw,
332 int req_keylen, unsigned char *keybuf)
336 gcry_mpi_t num_b1 = NULL;
338 unsigned char hash[20], buf_b[64], buf_i[128], *p;
346 log_error ("password too long\n");
352 log_error ("salt too short\n");
356 /* Store salt and password in BUF_I */
358 for(i=0; i < 64; i++)
359 *p++ = salt [i%saltlen];
360 for(i=j=0; i < 64; i += 2)
364 if (++j > pwlen) /* Note, that we include the trailing zero */
370 rc = gcry_md_open (&md, GCRY_MD_SHA1, 0);
373 log_error ( "gcry_md_open failed: %s\n", gpg_strerror (rc));
376 for(i=0; i < 64; i++)
377 gcry_md_putc (md, id);
378 gcry_md_write (md, buf_i, 128);
379 memcpy (hash, gcry_md_read (md, 0), 20);
381 for (i=1; i < iter; i++)
382 gcry_md_hash_buffer (GCRY_MD_SHA1, hash, hash, 20);
384 for (i=0; i < 20 && cur_keylen < req_keylen; i++)
385 keybuf[cur_keylen++] = hash[i];
386 if (cur_keylen == req_keylen)
388 gcry_mpi_release (num_b1);
389 return 0; /* ready */
392 /* need more bytes. */
393 for(i=0; i < 64; i++)
394 buf_b[i] = hash[i % 20];
395 rc = gcry_mpi_scan (&num_b1, GCRYMPI_FMT_USG, buf_b, 64, &n);
398 log_error ( "gcry_mpi_scan failed: %s\n", gpg_strerror (rc));
401 gcry_mpi_add_ui (num_b1, num_b1, 1);
402 for (i=0; i < 128; i += 64)
406 rc = gcry_mpi_scan (&num_ij, GCRYMPI_FMT_USG, buf_i + i, 64, &n);
409 log_error ( "gcry_mpi_scan failed: %s\n",
413 gcry_mpi_add (num_ij, num_ij, num_b1);
414 gcry_mpi_clear_highbit (num_ij, 64*8);
415 rc = gcry_mpi_print (GCRYMPI_FMT_USG, buf_i + i, 64, &n, num_ij);
418 log_error ( "gcry_mpi_print failed: %s\n",
422 gcry_mpi_release (num_ij);
429 set_key_iv (gcry_cipher_hd_t chd, char *salt, size_t saltlen, int iter,
430 const char *pw, int keybytes)
432 unsigned char keybuf[24];
435 assert (keybytes == 5 || keybytes == 24);
436 if (string_to_key (1, salt, saltlen, iter, pw, keybytes, keybuf))
438 rc = gcry_cipher_setkey (chd, keybuf, keybytes);
441 log_error ( "gcry_cipher_setkey failed: %s\n", gpg_strerror (rc));
445 if (string_to_key (2, salt, saltlen, iter, pw, 8, keybuf))
447 rc = gcry_cipher_setiv (chd, keybuf, 8);
450 log_error ("gcry_cipher_setiv failed: %s\n", gpg_strerror (rc));
458 set_key_iv_pbes2 (gcry_cipher_hd_t chd, char *salt, size_t saltlen, int iter,
459 const void *iv, size_t ivlen, const char *pw, int algo)
461 unsigned char *keybuf;
465 keylen = gcry_cipher_get_algo_keylen (algo);
468 keybuf = gcry_malloc_secure (keylen);
472 rc = gcry_kdf_derive (pw, strlen (pw),
473 GCRY_KDF_PBKDF2, GCRY_MD_SHA1,
474 salt, saltlen, iter, keylen, keybuf);
477 log_error ("gcry_kdf_derive failed: %s\n", gpg_strerror (rc));
482 rc = gcry_cipher_setkey (chd, keybuf, keylen);
486 log_error ("gcry_cipher_setkey failed: %s\n", gpg_strerror (rc));
491 rc = gcry_cipher_setiv (chd, iv, ivlen);
494 log_error ("gcry_cipher_setiv failed: %s\n", gpg_strerror (rc));
502 crypt_block (unsigned char *buffer, size_t length, char *salt, size_t saltlen,
503 int iter, const void *iv, size_t ivlen,
504 const char *pw, int cipher_algo, int encrypt)
506 gcry_cipher_hd_t chd;
509 rc = gcry_cipher_open (&chd, cipher_algo, GCRY_CIPHER_MODE_CBC, 0);
512 log_error ( "gcry_cipher_open failed: %s\n", gpg_strerror(rc));
513 wipememory (buffer, length);
517 if (cipher_algo == GCRY_CIPHER_AES128
518 ? set_key_iv_pbes2 (chd, salt, saltlen, iter, iv, ivlen, pw, cipher_algo)
519 : set_key_iv (chd, salt, saltlen, iter, pw,
520 cipher_algo == GCRY_CIPHER_RFC2268_40? 5:24))
522 wipememory (buffer, length);
526 rc = encrypt? gcry_cipher_encrypt (chd, buffer, length, NULL, 0)
527 : gcry_cipher_decrypt (chd, buffer, length, NULL, 0);
531 wipememory (buffer, length);
532 log_error ( "en/de-crytion failed: %s\n", gpg_strerror (rc));
537 gcry_cipher_close (chd);
541 /* Decrypt a block of data and try several encodings of the key.
542 CIPHERTEXT is the encrypted data of size LENGTH bytes; PLAINTEXT is
543 a buffer of the same size to receive the decryption result. SALT,
544 SALTLEN, ITER and PW are the information required for decryption
545 and CIPHER_ALGO is the algorithm id to use. CHECK_FNC is a
546 function called with the plaintext and used to check whether the
547 decryption succeeded; i.e. that a correct passphrase has been
548 given. That function shall return true if the decryption has likely
551 decrypt_block (const void *ciphertext, unsigned char *plaintext, size_t length,
552 char *salt, size_t saltlen,
553 int iter, const void *iv, size_t ivlen,
554 const char *pw, int cipher_algo,
555 int (*check_fnc) (const void *, size_t))
557 static const char * const charsets[] = {
558 "", /* No conversion - use the UTF-8 passphrase direct. */
577 char *convertedpw = NULL; /* Malloced and converted password or NULL. */
578 size_t convertedpwsize = 0; /* Allocated length. */
580 for (charsetidx=0; charsets[charsetidx]; charsetidx++)
582 if (*charsets[charsetidx])
587 size_t inbytes, outbytes;
591 /* We assume one byte encodings. Thus we can allocate
592 the buffer of the same size as the original
593 passphrase; the result will actually be shorter
595 convertedpwsize = strlen (pw) + 1;
596 convertedpw = gcry_malloc_secure (convertedpwsize);
599 log_info ("out of secure memory while"
600 " converting passphrase\n");
601 break; /* Give up. */
605 cd = jnlib_iconv_open (charsets[charsetidx], "utf-8");
606 if (cd == (jnlib_iconv_t)(-1))
610 inbytes = strlen (pw);
611 outptr = convertedpw;
612 outbytes = convertedpwsize - 1;
613 if ( jnlib_iconv (cd, (const char **)&inptr, &inbytes,
614 &outptr, &outbytes) == (size_t)-1)
616 jnlib_iconv_close (cd);
620 jnlib_iconv_close (cd);
621 log_info ("decryption failed; trying charset '%s'\n",
622 charsets[charsetidx]);
624 memcpy (plaintext, ciphertext, length);
625 crypt_block (plaintext, length, salt, saltlen, iter, iv, ivlen,
626 convertedpw? convertedpw:pw, cipher_algo, 0);
627 if (check_fnc (plaintext, length))
628 break; /* Decryption succeeded. */
630 gcry_free (convertedpw);
634 /* Return true if the decryption of an bag_encrypted_data object has
637 bag_decrypted_data_p (const void *plaintext, size_t length)
640 const unsigned char *p = plaintext;
644 /* # warning debug code is enabled */
645 /* FILE *fp = fopen ("tmp-rc2-plain.der", "wb"); */
646 /* if (!fp || fwrite (p, n, 1, fp) != 1) */
651 if (parse_tag (&p, &n, &ti))
653 if (ti.class || ti.tag != TAG_SEQUENCE)
655 if (parse_tag (&p, &n, &ti))
661 /* Note: If R_RESULT is passed as NULL, a key object as already be
662 processed and thus we need to skip it here. */
664 parse_bag_encrypted_data (const unsigned char *buffer, size_t length,
665 int startoffset, size_t *r_consumed, const char *pw,
666 void (*certcb)(void*, const unsigned char*, size_t),
667 void *certcbarg, gcry_mpi_t **r_result,
671 const unsigned char *p = buffer;
672 const unsigned char *p_start = buffer;
679 unsigned char *plain = NULL;
681 unsigned char *cram_buffer = NULL;
682 size_t consumed = 0; /* Number of bytes consumed from the original buffer. */
685 gcry_mpi_t *result = NULL;
691 if (parse_tag (&p, &n, &ti))
693 if (ti.class != ASNCONTEXT || ti.tag)
695 if (parse_tag (&p, &n, &ti))
697 if (ti.tag != TAG_SEQUENCE)
700 where = "bag.encryptedData.version";
701 if (parse_tag (&p, &n, &ti))
703 if (ti.tag != TAG_INTEGER || ti.length != 1 || *p != 0)
706 if (parse_tag (&p, &n, &ti))
708 if (ti.tag != TAG_SEQUENCE)
711 where = "bag.encryptedData.data";
712 if (parse_tag (&p, &n, &ti))
714 if (ti.tag != TAG_OBJECT_ID || ti.length != DIM(oid_data)
715 || memcmp (p, oid_data, DIM(oid_data)))
720 where = "bag.encryptedData.keyinfo";
721 if (parse_tag (&p, &n, &ti))
723 if (ti.class || ti.tag != TAG_SEQUENCE)
725 if (parse_tag (&p, &n, &ti))
727 if (!ti.class && ti.tag == TAG_OBJECT_ID
728 && ti.length == DIM(oid_pbeWithSHAAnd40BitRC2_CBC)
729 && !memcmp (p, oid_pbeWithSHAAnd40BitRC2_CBC,
730 DIM(oid_pbeWithSHAAnd40BitRC2_CBC)))
732 p += DIM(oid_pbeWithSHAAnd40BitRC2_CBC);
733 n -= DIM(oid_pbeWithSHAAnd40BitRC2_CBC);
735 else if (!ti.class && ti.tag == TAG_OBJECT_ID
736 && ti.length == DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC)
737 && !memcmp (p, oid_pbeWithSHAAnd3_KeyTripleDES_CBC,
738 DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC)))
740 p += DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC);
741 n -= DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC);
744 else if (!ti.class && ti.tag == TAG_OBJECT_ID
745 && ti.length == DIM(oid_pkcs5PBES2)
746 && !memcmp (p, oid_pkcs5PBES2, ti.length))
757 where = "pkcs5PBES2-params";
758 if (parse_tag (&p, &n, &ti))
760 if (ti.class || ti.tag != TAG_SEQUENCE)
762 if (parse_tag (&p, &n, &ti))
764 if (ti.class || ti.tag != TAG_SEQUENCE)
766 if (parse_tag (&p, &n, &ti))
768 if (!(!ti.class && ti.tag == TAG_OBJECT_ID
769 && ti.length == DIM(oid_pkcs5PBKDF2)
770 && !memcmp (p, oid_pkcs5PBKDF2, ti.length)))
771 goto bailout; /* Not PBKDF2. */
774 if (parse_tag (&p, &n, &ti))
776 if (ti.class || ti.tag != TAG_SEQUENCE)
778 if (parse_tag (&p, &n, &ti))
780 if (!(!ti.class && ti.tag == TAG_OCTET_STRING
781 && ti.length >= 8 && ti.length < sizeof salt))
782 goto bailout; /* No salt or unsupported length. */
784 memcpy (salt, p, saltlen);
788 if (parse_tag (&p, &n, &ti))
790 if (!(!ti.class && ti.tag == TAG_INTEGER && ti.length))
791 goto bailout; /* No valid iteration count. */
792 for (iter=0; ti.length; ti.length--)
795 iter |= (*p++) & 0xff;
798 /* Note: We don't support the optional parameters but assume
799 that the algorithmIdentifier follows. */
800 if (parse_tag (&p, &n, &ti))
802 if (ti.class || ti.tag != TAG_SEQUENCE)
804 if (parse_tag (&p, &n, &ti))
806 if (!(!ti.class && ti.tag == TAG_OBJECT_ID
807 && ti.length == DIM(oid_aes128_CBC)
808 && !memcmp (p, oid_aes128_CBC, ti.length)))
809 goto bailout; /* Not AES-128. */
812 if (parse_tag (&p, &n, &ti))
814 if (!(!ti.class && ti.tag == TAG_OCTET_STRING && ti.length == sizeof iv))
815 goto bailout; /* Bad IV. */
816 memcpy (iv, p, sizeof iv);
822 where = "rc2or3des-params";
823 if (parse_tag (&p, &n, &ti))
825 if (ti.class || ti.tag != TAG_SEQUENCE)
827 if (parse_tag (&p, &n, &ti))
829 if (ti.class || ti.tag != TAG_OCTET_STRING
830 || ti.length < 8 || ti.length > 20 )
833 memcpy (salt, p, saltlen);
836 if (parse_tag (&p, &n, &ti))
838 if (ti.class || ti.tag != TAG_INTEGER || !ti.length )
840 for (iter=0; ti.length; ti.length--)
843 iter |= (*p++) & 0xff;
848 where = "rc2or3desoraes-ciphertext";
849 if (parse_tag (&p, &n, &ti))
852 consumed = p - p_start;
853 if (ti.class == ASNCONTEXT && ti.tag == 0 && ti.is_constructed && ti.ndef)
855 /* Mozilla exported certs now come with single byte chunks of
856 octect strings. (Mozilla Firefox 1.0.4). Arghh. */
857 where = "cram-rc2or3des-ciphertext";
858 cram_buffer = cram_octet_string ( p, &n, &consumed);
861 p = p_start = cram_buffer;
863 *r_consumed = consumed;
864 r_consumed = NULL; /* Ugly hack to not update that value any further. */
867 else if (ti.class == ASNCONTEXT && ti.tag == 0 && ti.length )
872 log_info ("%lu bytes of %s encrypted text\n",ti.length,
873 is_pbes2?"AES128":is_3des?"3DES":"RC2");
875 plain = gcry_malloc_secure (ti.length);
878 log_error ("error allocating decryption buffer\n");
881 decrypt_block (p, plain, ti.length, salt, saltlen, iter,
882 iv, is_pbes2?16:0, pw,
883 is_pbes2 ? GCRY_CIPHER_AES128 :
884 is_3des ? GCRY_CIPHER_3DES : GCRY_CIPHER_RFC2268_40,
885 bag_decrypted_data_p);
890 where = "outer.outer.seq";
891 if (parse_tag (&p, &n, &ti))
896 if (ti.class || ti.tag != TAG_SEQUENCE)
902 if (parse_tag (&p, &n, &ti))
908 /* Loop over all certificates inside the bag. */
914 where = "certbag.nextcert";
915 if (ti.class || ti.tag != TAG_SEQUENCE)
918 where = "certbag.objectidentifier";
919 if (parse_tag (&p, &n, &ti))
921 if (ti.class || ti.tag != TAG_OBJECT_ID)
923 if ( ti.length == DIM(oid_pkcs_12_CertBag)
924 && !memcmp (p, oid_pkcs_12_CertBag, DIM(oid_pkcs_12_CertBag)))
926 p += DIM(oid_pkcs_12_CertBag);
927 n -= DIM(oid_pkcs_12_CertBag);
929 else if ( ti.length == DIM(oid_pkcs_12_CrlBag)
930 && !memcmp (p, oid_pkcs_12_CrlBag, DIM(oid_pkcs_12_CrlBag)))
932 p += DIM(oid_pkcs_12_CrlBag);
933 n -= DIM(oid_pkcs_12_CrlBag);
936 else if ( ti.length == DIM(oid_pkcs_12_keyBag)
937 && !memcmp (p, oid_pkcs_12_keyBag, DIM(oid_pkcs_12_keyBag)))
939 /* The TrustedMIME plugin for MS Outlook started to create
940 files with just one outer 3DES encrypted container and
941 inside the certificates as well as the key. */
942 p += DIM(oid_pkcs_12_keyBag);
943 n -= DIM(oid_pkcs_12_keyBag);
949 where = "certbag.before.certheader";
950 if (parse_tag (&p, &n, &ti))
952 if (ti.class != ASNCONTEXT || ti.tag)
956 log_info ("skipping unsupported crlBag\n");
960 else if (iskeybag && (result || !r_result))
962 log_info ("one keyBag already processed; skipping this one\n");
970 log_info ("processing simple keyBag\n");
972 /* Fixme: This code is duplicated from parse_bag_data. */
973 if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
975 if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER
976 || ti.length != 1 || *p)
979 if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
982 if (parse_tag (&p, &n, &ti))
987 if (ti.class || ti.tag != TAG_OBJECT_ID
988 || ti.length != DIM(oid_rsaEncryption)
989 || memcmp (p, oid_rsaEncryption,
990 DIM(oid_rsaEncryption)))
992 p += DIM (oid_rsaEncryption);
993 n -= DIM (oid_rsaEncryption);
1001 if ( parse_tag (&p, &n, &ti)
1002 || ti.class || ti.tag != TAG_OCTET_STRING)
1004 if ( parse_tag (&p, &n, &ti)
1005 || ti.class || ti.tag != TAG_SEQUENCE)
1009 result = gcry_calloc (10, sizeof *result);
1012 log_error ( "error allocating result array\n");
1017 where = "reading.keybag.key-parameters";
1018 for (result_count = 0; len && result_count < 9;)
1020 if ( parse_tag (&p, &n, &ti)
1021 || ti.class || ti.tag != TAG_INTEGER)
1026 if (len < ti.length)
1029 if (!result_count && ti.length == 1 && !*p)
1030 ; /* ignore the very first one if it is a 0 */
1035 rc = gcry_mpi_scan (result+result_count, GCRYMPI_FMT_USG, p,
1039 log_error ("error parsing key parameter: %s\n",
1053 log_info ("processing certBag\n");
1054 if (parse_tag (&p, &n, &ti))
1056 if (ti.class || ti.tag != TAG_SEQUENCE)
1058 if (parse_tag (&p, &n, &ti))
1060 if (ti.class || ti.tag != TAG_OBJECT_ID
1061 || ti.length != DIM(oid_x509Certificate_for_pkcs_12)
1062 || memcmp (p, oid_x509Certificate_for_pkcs_12,
1063 DIM(oid_x509Certificate_for_pkcs_12)))
1065 p += DIM(oid_x509Certificate_for_pkcs_12);
1066 n -= DIM(oid_x509Certificate_for_pkcs_12);
1068 where = "certbag.before.octetstring";
1069 if (parse_tag (&p, &n, &ti))
1071 if (ti.class != ASNCONTEXT || ti.tag)
1073 if (parse_tag (&p, &n, &ti))
1075 if (ti.class || ti.tag != TAG_OCTET_STRING || ti.ndef)
1078 /* Return the certificate. */
1080 certcb (certcbarg, p, ti.length);
1086 /* Ugly hack to cope with the padding: Forget about the rest if
1087 that is less or equal to the cipher's block length. We can
1088 reasonable assume that all valid data will be longer than
1090 if (n <= (is_pbes2? 16:8))
1093 /* Skip the optional SET with the pkcs12 cert attributes. */
1096 where = "bag.attributes";
1097 if (parse_tag (&p, &n, &ti))
1099 if (!ti.class && ti.tag == TAG_SEQUENCE)
1100 ; /* No attributes. */
1101 else if (!ti.class && ti.tag == TAG_SET && !ti.ndef)
1102 { /* The optional SET. */
1105 if (n <= (is_pbes2?16:8))
1107 if (n && parse_tag (&p, &n, &ti))
1116 *r_consumed = consumed;
1118 gcry_free (cram_buffer);
1128 for (i=0; result[i]; i++)
1129 gcry_mpi_release (result[i]);
1133 *r_consumed = consumed;
1135 gcry_free (cram_buffer);
1136 log_error ("encryptedData error at \"%s\", offset %u\n",
1137 where, (unsigned int)((p - p_start)+startoffset));
1140 /* Note, that the following string might be used by other programs
1141 to check for a bad passphrase; it should therefore not be
1142 translated or changed. */
1143 log_error ("possibly bad passphrase given\n");
1150 /* Return true if the decryption of a bag_data object has likely
1153 bag_data_p (const void *plaintext, size_t length)
1156 const unsigned char *p = plaintext;
1160 /* # warning debug code is enabled */
1161 /* FILE *fp = fopen ("tmp-3des-plain-key.der", "wb"); */
1162 /* if (!fp || fwrite (p, n, 1, fp) != 1) */
1167 if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
1169 if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER
1170 || ti.length != 1 || *p)
1178 parse_bag_data (const unsigned char *buffer, size_t length, int startoffset,
1179 size_t *r_consumed, const char *pw)
1183 const unsigned char *p = buffer;
1184 const unsigned char *p_start = buffer;
1192 unsigned char *plain = NULL;
1193 gcry_mpi_t *result = NULL;
1194 int result_count, i;
1195 unsigned char *cram_buffer = NULL;
1196 size_t consumed = 0; /* Number of bytes consumed from the original buffer. */
1200 if (parse_tag (&p, &n, &ti))
1202 if (ti.class != ASNCONTEXT || ti.tag)
1204 if (parse_tag (&p, &n, &ti))
1206 if (ti.class || ti.tag != TAG_OCTET_STRING)
1209 consumed = p - p_start;
1210 if (ti.is_constructed && ti.ndef)
1212 /* Mozilla exported certs now come with single byte chunks of
1213 octect strings. (Mozilla Firefox 1.0.4). Arghh. */
1214 where = "cram-data.outersegs";
1215 cram_buffer = cram_octet_string ( p, &n, &consumed);
1218 p = p_start = cram_buffer;
1220 *r_consumed = consumed;
1221 r_consumed = NULL; /* Ugly hack to not update that value any further. */
1225 where = "data.outerseqs";
1226 if (parse_tag (&p, &n, &ti))
1228 if (ti.class || ti.tag != TAG_SEQUENCE)
1230 if (parse_tag (&p, &n, &ti))
1232 if (ti.class || ti.tag != TAG_SEQUENCE)
1235 where = "data.objectidentifier";
1236 if (parse_tag (&p, &n, &ti))
1238 if (ti.class || ti.tag != TAG_OBJECT_ID
1239 || ti.length != DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag)
1240 || memcmp (p, oid_pkcs_12_pkcs_8ShroudedKeyBag,
1241 DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag)))
1243 p += DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag);
1244 n -= DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag);
1246 where = "shrouded,outerseqs";
1247 if (parse_tag (&p, &n, &ti))
1249 if (ti.class != ASNCONTEXT || ti.tag)
1251 if (parse_tag (&p, &n, &ti))
1253 if (ti.class || ti.tag != TAG_SEQUENCE)
1255 if (parse_tag (&p, &n, &ti))
1257 if (ti.class || ti.tag != TAG_SEQUENCE)
1259 if (parse_tag (&p, &n, &ti))
1261 if (ti.class == 0 && ti.tag == TAG_OBJECT_ID
1262 && ti.length == DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC)
1263 && !memcmp (p, oid_pbeWithSHAAnd3_KeyTripleDES_CBC,
1264 DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC)))
1266 p += DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC);
1267 n -= DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC);
1269 else if (ti.class == 0 && ti.tag == TAG_OBJECT_ID
1270 && ti.length == DIM(oid_pkcs5PBES2)
1271 && !memcmp (p, oid_pkcs5PBES2, DIM(oid_pkcs5PBES2)))
1273 p += DIM(oid_pkcs5PBES2);
1274 n -= DIM(oid_pkcs5PBES2);
1282 where = "pkcs5PBES2-params";
1283 if (parse_tag (&p, &n, &ti))
1285 if (ti.class || ti.tag != TAG_SEQUENCE)
1287 if (parse_tag (&p, &n, &ti))
1289 if (ti.class || ti.tag != TAG_SEQUENCE)
1291 if (parse_tag (&p, &n, &ti))
1293 if (!(!ti.class && ti.tag == TAG_OBJECT_ID
1294 && ti.length == DIM(oid_pkcs5PBKDF2)
1295 && !memcmp (p, oid_pkcs5PBKDF2, ti.length)))
1296 goto bailout; /* Not PBKDF2. */
1299 if (parse_tag (&p, &n, &ti))
1301 if (ti.class || ti.tag != TAG_SEQUENCE)
1303 if (parse_tag (&p, &n, &ti))
1305 if (!(!ti.class && ti.tag == TAG_OCTET_STRING
1306 && ti.length >= 8 && ti.length < sizeof salt))
1307 goto bailout; /* No salt or unsupported length. */
1308 saltlen = ti.length;
1309 memcpy (salt, p, saltlen);
1313 if (parse_tag (&p, &n, &ti))
1315 if (!(!ti.class && ti.tag == TAG_INTEGER && ti.length))
1316 goto bailout; /* No valid iteration count. */
1317 for (iter=0; ti.length; ti.length--)
1320 iter |= (*p++) & 0xff;
1323 /* Note: We don't support the optional parameters but assume
1324 that the algorithmIdentifier follows. */
1325 if (parse_tag (&p, &n, &ti))
1327 if (ti.class || ti.tag != TAG_SEQUENCE)
1329 if (parse_tag (&p, &n, &ti))
1331 if (!(!ti.class && ti.tag == TAG_OBJECT_ID
1332 && ti.length == DIM(oid_aes128_CBC)
1333 && !memcmp (p, oid_aes128_CBC, ti.length)))
1334 goto bailout; /* Not AES-128. */
1337 if (parse_tag (&p, &n, &ti))
1339 if (!(!ti.class && ti.tag == TAG_OCTET_STRING && ti.length == sizeof iv))
1340 goto bailout; /* Bad IV. */
1341 memcpy (iv, p, sizeof iv);
1347 where = "3des-params";
1348 if (parse_tag (&p, &n, &ti))
1350 if (ti.class || ti.tag != TAG_SEQUENCE)
1352 if (parse_tag (&p, &n, &ti))
1354 if (ti.class || ti.tag != TAG_OCTET_STRING
1355 || ti.length < 8 || ti.length > 20)
1357 saltlen = ti.length;
1358 memcpy (salt, p, saltlen);
1361 if (parse_tag (&p, &n, &ti))
1363 if (ti.class || ti.tag != TAG_INTEGER || !ti.length )
1365 for (iter=0; ti.length; ti.length--)
1368 iter |= (*p++) & 0xff;
1373 where = "3desoraes-ciphertext";
1374 if (parse_tag (&p, &n, &ti))
1376 if (ti.class || ti.tag != TAG_OCTET_STRING || !ti.length )
1379 log_info ("%lu bytes of %s encrypted text\n",
1380 ti.length, is_pbes2? "AES128":"3DES");
1382 plain = gcry_malloc_secure (ti.length);
1385 log_error ("error allocating decryption buffer\n");
1388 consumed += p - p_start + ti.length;
1389 decrypt_block (p, plain, ti.length, salt, saltlen, iter,
1390 iv, is_pbes2? 16:0, pw,
1391 is_pbes2? GCRY_CIPHER_AES128 : GCRY_CIPHER_3DES,
1395 p_start = p = plain;
1397 where = "decrypted-text";
1398 if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
1400 if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER
1401 || ti.length != 1 || *p)
1404 if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
1407 if (parse_tag (&p, &n, &ti))
1412 if (ti.class || ti.tag != TAG_OBJECT_ID
1413 || ti.length != DIM(oid_rsaEncryption)
1414 || memcmp (p, oid_rsaEncryption,
1415 DIM(oid_rsaEncryption)))
1417 p += DIM (oid_rsaEncryption);
1418 n -= DIM (oid_rsaEncryption);
1419 if (len < ti.length)
1426 if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_OCTET_STRING)
1428 if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
1432 result = gcry_calloc (10, sizeof *result);
1435 log_error ( "error allocating result array\n");
1440 where = "reading.key-parameters";
1441 for (result_count=0; len && result_count < 9;)
1443 if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER)
1448 if (len < ti.length)
1451 if (!result_count && ti.length == 1 && !*p)
1452 ; /* ignore the very first one if it is a 0 */
1455 rc = gcry_mpi_scan (result+result_count, GCRYMPI_FMT_USG, p,
1459 log_error ("error parsing key parameter: %s\n",
1471 gcry_free (cram_buffer);
1473 *r_consumed = consumed;
1480 for (i=0; result[i]; i++)
1481 gcry_mpi_release (result[i]);
1484 gcry_free (cram_buffer);
1485 log_error ( "data error at \"%s\", offset %u\n",
1486 where, (unsigned int)((p - buffer) + startoffset));
1488 *r_consumed = consumed;
1493 /* Parse a PKCS12 object and return an array of MPI representing the
1494 secret key parameters. This is a very limited implementation in
1495 that it is only able to look for 3DES encoded encryptedData and
1496 tries to extract the first private key object it finds. In case of
1497 an error NULL is returned. CERTCB and CERRTCBARG are used to pass
1498 X.509 certificates back to the caller. */
1500 p12_parse (const unsigned char *buffer, size_t length, const char *pw,
1501 void (*certcb)(void*, const unsigned char*, size_t),
1502 void *certcbarg, int *r_badpass)
1505 const unsigned char *p = buffer;
1506 const unsigned char *p_start = buffer;
1509 int bagseqlength, len;
1510 int bagseqndef, lenndef;
1511 gcry_mpi_t *result = NULL;
1512 unsigned char *cram_buffer = NULL;
1516 if (parse_tag (&p, &n, &ti))
1518 if (ti.tag != TAG_SEQUENCE)
1521 where = "pfxVersion";
1522 if (parse_tag (&p, &n, &ti))
1524 if (ti.tag != TAG_INTEGER || ti.length != 1 || *p != 3)
1529 if (parse_tag (&p, &n, &ti))
1531 if (ti.tag != TAG_SEQUENCE)
1533 if (parse_tag (&p, &n, &ti))
1535 if (ti.tag != TAG_OBJECT_ID || ti.length != DIM(oid_data)
1536 || memcmp (p, oid_data, DIM(oid_data)))
1541 if (parse_tag (&p, &n, &ti))
1543 if (ti.class != ASNCONTEXT || ti.tag)
1545 if (parse_tag (&p, &n, &ti))
1547 if (ti.class != UNIVERSAL || ti.tag != TAG_OCTET_STRING)
1550 if (ti.is_constructed && ti.ndef)
1552 /* Mozilla exported certs now come with single byte chunks of
1553 octect strings. (Mozilla Firefox 1.0.4). Arghh. */
1554 where = "cram-bags";
1555 cram_buffer = cram_octet_string ( p, &n, NULL);
1558 p = p_start = cram_buffer;
1562 if (parse_tag (&p, &n, &ti))
1564 if (ti.class != UNIVERSAL || ti.tag != TAG_SEQUENCE)
1566 bagseqndef = ti.ndef;
1567 bagseqlength = ti.length;
1568 while (bagseqlength || bagseqndef)
1570 /* log_debug ( "at offset %u\n", (p - p_start)); */
1571 where = "bag-sequence";
1572 if (parse_tag (&p, &n, &ti))
1574 if (bagseqndef && ti.class == UNIVERSAL && !ti.tag && !ti.is_constructed)
1576 if (ti.class != UNIVERSAL || ti.tag != TAG_SEQUENCE)
1581 if (bagseqlength < ti.nhdr)
1583 bagseqlength -= ti.nhdr;
1584 if (bagseqlength < ti.length)
1586 bagseqlength -= ti.length;
1591 if (parse_tag (&p, &n, &ti))
1598 if (ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_encryptedData)
1599 && !memcmp (p, oid_encryptedData, DIM(oid_encryptedData)))
1601 size_t consumed = 0;
1603 p += DIM(oid_encryptedData);
1604 n -= DIM(oid_encryptedData);
1606 len -= DIM(oid_encryptedData);
1607 where = "bag.encryptedData";
1608 if (parse_bag_encrypted_data (p, n, (p - p_start), &consumed, pw,
1610 result? NULL : &result, r_badpass))
1615 else if (ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_data)
1616 && !memcmp (p, oid_data, DIM(oid_data)))
1620 log_info ("already got an key object, skipping this one\n");
1626 size_t consumed = 0;
1631 len -= DIM(oid_data);
1632 result = parse_bag_data (p, n, (p - p_start), &consumed, pw);
1641 log_info ("unknown bag type - skipped\n");
1646 if (len < 0 || len > n)
1652 /* Need to skip the Null Tag. */
1653 if (parse_tag (&p, &n, &ti))
1655 if (!(ti.class == UNIVERSAL && !ti.tag && !ti.is_constructed))
1660 gcry_free (cram_buffer);
1663 log_error ("error at \"%s\", offset %u\n",
1664 where, (unsigned int)(p - p_start));
1669 for (i=0; result[i]; i++)
1670 gcry_mpi_release (result[i]);
1673 gcry_free (cram_buffer);
1680 compute_tag_length (size_t n)
1685 needed += 2; /* tag and one length byte */
1687 needed += 3; /* tag, number of length bytes, 1 length byte */
1689 needed += 4; /* tag, number of length bytes, 2 length bytes */
1692 log_error ("object too larger to encode\n");
1698 static unsigned char *
1699 store_tag_length (unsigned char *p, int tag, size_t n)
1701 if (tag == TAG_SEQUENCE)
1702 tag |= 0x20; /* constructed */
1723 /* Create the final PKCS-12 object from the sequences contained in
1724 SEQLIST. PW is the password. That array is terminated with an NULL
1726 static unsigned char *
1727 create_final (struct buffer_s *sequences, const char *pw, size_t *r_length)
1732 unsigned char *macstart;
1734 unsigned char *result, *p;
1737 unsigned char keybuf[20];
1743 /* 9 steps to create the pkcs#12 Krampf. */
1746 /* We add this at step 0. */
1748 /* 7. All the buffers. */
1749 for (i=0; sequences[i].buffer; i++)
1750 needed += sequences[i].length;
1752 /* 6. This goes into a sequences. */
1754 n = compute_tag_length (needed);
1757 /* 5. Encapsulate all in an octet string. */
1759 n = compute_tag_length (needed);
1762 /* 4. And tag it with [0]. */
1764 n = compute_tag_length (needed);
1767 /* 3. Prepend an data OID. */
1768 needed += 2 + DIM (oid_data);
1770 /* 2. Put all into a sequences. */
1772 n = compute_tag_length (needed);
1775 /* 1. Prepend the version integer 3. */
1778 /* 0. And the final outer sequence. */
1780 needed += DIM (data_mactemplate);
1782 n = compute_tag_length (needed);
1785 /* Allocate a buffer. */
1786 result = gcry_malloc (needed);
1789 log_error ("error allocating buffer\n");
1794 /* 0. Store the very outer sequence. */
1795 p = store_tag_length (p, TAG_SEQUENCE, len[0]);
1797 /* 1. Store the version integer 3. */
1802 /* 2. Store another sequence. */
1803 p = store_tag_length (p, TAG_SEQUENCE, len[2]);
1805 /* 3. Store the data OID. */
1806 p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_data));
1807 memcpy (p, oid_data, DIM (oid_data));
1808 p += DIM (oid_data);
1810 /* 4. Next comes a context tag. */
1811 p = store_tag_length (p, 0xa0, len[4]);
1813 /* 5. And an octet string. */
1814 p = store_tag_length (p, TAG_OCTET_STRING, len[5]);
1816 /* 6. And the inner sequence. */
1818 p = store_tag_length (p, TAG_SEQUENCE, len[6]);
1820 /* 7. Append all the buffers. */
1821 for (i=0; sequences[i].buffer; i++)
1823 memcpy (p, sequences[i].buffer, sequences[i].length);
1824 p += sequences[i].length;
1829 /* Intermezzo to compute the MAC. */
1830 maclen = p - macstart;
1831 gcry_randomize (salt, 8, GCRY_STRONG_RANDOM);
1832 if (string_to_key (3, salt, 8, 2048, pw, 20, keybuf))
1837 rc = gcry_md_open (&md, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC);
1840 log_error ("gcry_md_open failed: %s\n", gpg_strerror (rc));
1844 rc = gcry_md_setkey (md, keybuf, 20);
1847 log_error ("gcry_md_setkey failed: %s\n", gpg_strerror (rc));
1852 gcry_md_write (md, macstart, maclen);
1854 /* 8. Append the MAC template and fix it up. */
1855 memcpy (p, data_mactemplate, DIM (data_mactemplate));
1856 memcpy (p + DATA_MACTEMPLATE_SALT_OFF, salt, 8);
1857 memcpy (p + DATA_MACTEMPLATE_MAC_OFF, gcry_md_read (md, 0), 20);
1858 p += DIM (data_mactemplate);
1863 resultlen = p - result;
1864 if (needed != resultlen)
1865 log_debug ("length mismatch: %lu, %lu\n",
1866 (unsigned long)needed, (unsigned long)resultlen);
1868 *r_length = resultlen;
1873 /* Build a DER encoded SEQUENCE with the key:
1878 OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1)
1881 OCTET STRING, encapsulates {
1896 MODE controls what is being generated:
1897 0 - As described above
1898 1 - Ditto but without the padding
1899 2 - Only the inner part (pkcs#1)
1902 static unsigned char *
1903 build_key_sequence (gcry_mpi_t *kparms, int mode, size_t *r_length)
1907 unsigned char *plain, *p;
1909 size_t outseqlen, oidseqlen, octstrlen, inseqlen;
1911 needed = 3; /* The version integer with value 0. */
1912 for (i=0; kparms[i]; i++)
1915 rc = gcry_mpi_print (GCRYMPI_FMT_STD, NULL, 0, &n, kparms[i]);
1918 log_error ("error formatting parameter: %s\n", gpg_strerror (rc));
1922 n = compute_tag_length (n);
1929 log_error ("invalid parameters for p12_build\n");
1932 /* Now this all goes into a sequence. */
1934 n = compute_tag_length (needed);
1941 /* Encapsulate all into an octet string. */
1943 n = compute_tag_length (needed);
1947 /* Prepend the object identifier sequence. */
1948 oidseqlen = 2 + DIM (oid_rsaEncryption) + 2;
1949 needed += 2 + oidseqlen;
1950 /* The version number. */
1952 /* And finally put the whole thing into a sequence. */
1954 n = compute_tag_length (needed);
1960 /* allocate 8 extra bytes for padding */
1961 plain = gcry_malloc_secure (needed+8);
1964 log_error ("error allocating encryption buffer\n");
1968 /* And now fill the plaintext buffer. */
1972 p = store_tag_length (p, TAG_SEQUENCE, outseqlen);
1973 /* Store version. */
1977 /* Store object identifier sequence. */
1978 p = store_tag_length (p, TAG_SEQUENCE, oidseqlen);
1979 p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_rsaEncryption));
1980 memcpy (p, oid_rsaEncryption, DIM (oid_rsaEncryption));
1981 p += DIM (oid_rsaEncryption);
1984 /* Start with the octet string. */
1985 p = store_tag_length (p, TAG_OCTET_STRING, octstrlen);
1988 p = store_tag_length (p, TAG_SEQUENCE, inseqlen);
1989 /* Store the key parameters. */
1993 for (i=0; kparms[i]; i++)
1996 rc = gcry_mpi_print (GCRYMPI_FMT_STD, NULL, 0, &n, kparms[i]);
1999 log_error ("oops: error formatting parameter: %s\n",
2004 p = store_tag_length (p, TAG_INTEGER, n);
2006 n = plain + needed - p;
2007 rc = gcry_mpi_print (GCRYMPI_FMT_STD, p, n, &n, kparms[i]);
2010 log_error ("oops: error storing parameter: %s\n",
2018 plainlen = p - plain;
2019 assert (needed == plainlen);
2023 /* Append some pad characters; we already allocated extra space. */
2024 n = 8 - plainlen % 8;
2025 for (i=0; i < n; i++, plainlen++)
2029 *r_length = plainlen;
2035 static unsigned char *
2036 build_key_bag (unsigned char *buffer, size_t buflen, char *salt,
2037 const unsigned char *sha1hash, const char *keyidstr,
2040 size_t len[11], needed;
2041 unsigned char *p, *keybag;
2044 /* Walk 11 steps down to collect the info: */
2046 /* 10. The data goes into an octet string. */
2047 needed = compute_tag_length (buflen);
2050 /* 9. Prepend the algorithm identifier. */
2051 needed += DIM (data_3desiter2048);
2053 /* 8. Put a sequence around. */
2055 needed += compute_tag_length (needed);
2057 /* 7. Prepend a [0] tag. */
2059 needed += compute_tag_length (needed);
2061 /* 6b. The attributes which are appended at the end. */
2063 needed += DIM (data_attrtemplate) + 20;
2065 /* 6. Prepend the shroudedKeyBag OID. */
2066 needed += 2 + DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag);
2068 /* 5+4. Put all into two sequences. */
2070 needed += compute_tag_length ( needed);
2072 needed += compute_tag_length (needed);
2074 /* 3. This all goes into an octet string. */
2076 needed += compute_tag_length (needed);
2078 /* 2. Prepend another [0] tag. */
2080 needed += compute_tag_length (needed);
2082 /* 1. Prepend the data OID. */
2083 needed += 2 + DIM (oid_data);
2085 /* 0. Prepend another sequence. */
2087 needed += compute_tag_length (needed);
2089 /* Now that we have all length information, allocate a buffer. */
2090 p = keybag = gcry_malloc (needed);
2093 log_error ("error allocating buffer\n");
2097 /* Walk 11 steps up to store the data. */
2099 /* 0. Store the first sequence. */
2100 p = store_tag_length (p, TAG_SEQUENCE, len[0]);
2102 /* 1. Store the data OID. */
2103 p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_data));
2104 memcpy (p, oid_data, DIM (oid_data));
2105 p += DIM (oid_data);
2107 /* 2. Store a [0] tag. */
2108 p = store_tag_length (p, 0xa0, len[2]);
2110 /* 3. And an octet string. */
2111 p = store_tag_length (p, TAG_OCTET_STRING, len[3]);
2113 /* 4+5. Two sequences. */
2114 p = store_tag_length (p, TAG_SEQUENCE, len[4]);
2115 p = store_tag_length (p, TAG_SEQUENCE, len[5]);
2117 /* 6. Store the shroudedKeyBag OID. */
2118 p = store_tag_length (p, TAG_OBJECT_ID,
2119 DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag));
2120 memcpy (p, oid_pkcs_12_pkcs_8ShroudedKeyBag,
2121 DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag));
2122 p += DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag);
2124 /* 7. Store a [0] tag. */
2125 p = store_tag_length (p, 0xa0, len[7]);
2127 /* 8. Store a sequence. */
2128 p = store_tag_length (p, TAG_SEQUENCE, len[8]);
2130 /* 9. Now for the pre-encoded algorithm identifier and the salt. */
2131 memcpy (p, data_3desiter2048, DIM (data_3desiter2048));
2132 memcpy (p + DATA_3DESITER2048_SALT_OFF, salt, 8);
2133 p += DIM (data_3desiter2048);
2135 /* 10. And the octet string with the encrypted data. */
2136 p = store_tag_length (p, TAG_OCTET_STRING, buflen);
2137 memcpy (p, buffer, buflen);
2140 /* Append the attributes whose length we calculated at step 2b. */
2145 memcpy (p, data_attrtemplate, DIM (data_attrtemplate));
2146 for (i=0; i < 8; i++)
2147 p[DATA_ATTRTEMPLATE_KEYID_OFF+2*i+1] = keyidstr[i];
2148 p += DIM (data_attrtemplate);
2149 memcpy (p, sha1hash, 20);
2154 keybaglen = p - keybag;
2155 if (needed != keybaglen)
2156 log_debug ("length mismatch: %lu, %lu\n",
2157 (unsigned long)needed, (unsigned long)keybaglen);
2159 *r_length = keybaglen;
2164 static unsigned char *
2165 build_cert_bag (unsigned char *buffer, size_t buflen, char *salt,
2168 size_t len[9], needed;
2169 unsigned char *p, *certbag;
2172 /* Walk 9 steps down to collect the info: */
2174 /* 8. The data goes into an octet string. */
2175 needed = compute_tag_length (buflen);
2178 /* 7. The algorithm identifier. */
2179 needed += DIM (data_rc2iter2048);
2181 /* 6. The data OID. */
2182 needed += 2 + DIM (oid_data);
2184 /* 5. A sequence. */
2186 needed += compute_tag_length ( needed);
2188 /* 4. An integer. */
2191 /* 3. A sequence. */
2193 needed += compute_tag_length (needed);
2197 needed += compute_tag_length (needed);
2199 /* 1. The encryptedData OID. */
2200 needed += 2 + DIM (oid_encryptedData);
2202 /* 0. The first sequence. */
2204 needed += compute_tag_length (needed);
2206 /* Now that we have all length information, allocate a buffer. */
2207 p = certbag = gcry_malloc (needed);
2210 log_error ("error allocating buffer\n");
2214 /* Walk 9 steps up to store the data. */
2216 /* 0. Store the first sequence. */
2217 p = store_tag_length (p, TAG_SEQUENCE, len[0]);
2219 /* 1. Store the encryptedData OID. */
2220 p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_encryptedData));
2221 memcpy (p, oid_encryptedData, DIM (oid_encryptedData));
2222 p += DIM (oid_encryptedData);
2224 /* 2. Store a [0] tag. */
2225 p = store_tag_length (p, 0xa0, len[2]);
2227 /* 3. Store a sequence. */
2228 p = store_tag_length (p, TAG_SEQUENCE, len[3]);
2230 /* 4. Store the integer 0. */
2235 /* 5. Store a sequence. */
2236 p = store_tag_length (p, TAG_SEQUENCE, len[5]);
2238 /* 6. Store the data OID. */
2239 p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_data));
2240 memcpy (p, oid_data, DIM (oid_data));
2241 p += DIM (oid_data);
2243 /* 7. Now for the pre-encoded algorithm identifier and the salt. */
2244 memcpy (p, data_rc2iter2048, DIM (data_rc2iter2048));
2245 memcpy (p + DATA_RC2ITER2048_SALT_OFF, salt, 8);
2246 p += DIM (data_rc2iter2048);
2248 /* 8. And finally the [0] tag with the encrypted data. */
2249 p = store_tag_length (p, 0x80, buflen);
2250 memcpy (p, buffer, buflen);
2252 certbaglen = p - certbag;
2254 if (needed != certbaglen)
2255 log_debug ("length mismatch: %lu, %lu\n",
2256 (unsigned long)needed, (unsigned long)certbaglen);
2258 *r_length = certbaglen;
2263 static unsigned char *
2264 build_cert_sequence (const unsigned char *buffer, size_t buflen,
2265 const unsigned char *sha1hash, const char *keyidstr,
2268 size_t len[8], needed, n;
2269 unsigned char *p, *certseq;
2273 assert (strlen (keyidstr) == 8);
2275 /* Walk 8 steps down to collect the info: */
2277 /* 7. The data goes into an octet string. */
2278 needed = compute_tag_length (buflen);
2283 needed += compute_tag_length (needed);
2286 needed += 2 + DIM (oid_x509Certificate_for_pkcs_12);
2288 /* 4. A sequence. */
2290 needed += compute_tag_length (needed);
2294 needed += compute_tag_length (needed);
2296 /* 2b. The attributes which are appended at the end. */
2298 needed += DIM (data_attrtemplate) + 20;
2301 needed += 2 + DIM (oid_pkcs_12_CertBag);
2303 /* 1. A sequence. */
2305 needed += compute_tag_length (needed);
2307 /* 0. The first sequence. */
2309 needed += compute_tag_length (needed);
2311 /* Now that we have all length information, allocate a buffer. */
2312 p = certseq = gcry_malloc (needed + 8 /*(for padding)*/);
2315 log_error ("error allocating buffer\n");
2319 /* Walk 8 steps up to store the data. */
2321 /* 0. Store the first sequence. */
2322 p = store_tag_length (p, TAG_SEQUENCE, len[0]);
2324 /* 1. Store the second sequence. */
2325 p = store_tag_length (p, TAG_SEQUENCE, len[1]);
2327 /* 2. Store the pkcs12-cert-bag OID. */
2328 p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_pkcs_12_CertBag));
2329 memcpy (p, oid_pkcs_12_CertBag, DIM (oid_pkcs_12_CertBag));
2330 p += DIM (oid_pkcs_12_CertBag);
2332 /* 3. Store a [0] tag. */
2333 p = store_tag_length (p, 0xa0, len[3]);
2335 /* 4. Store a sequence. */
2336 p = store_tag_length (p, TAG_SEQUENCE, len[4]);
2338 /* 5. Store the x509Certificate OID. */
2339 p = store_tag_length (p, TAG_OBJECT_ID,
2340 DIM (oid_x509Certificate_for_pkcs_12));
2341 memcpy (p, oid_x509Certificate_for_pkcs_12,
2342 DIM (oid_x509Certificate_for_pkcs_12));
2343 p += DIM (oid_x509Certificate_for_pkcs_12);
2345 /* 6. Store a [0] tag. */
2346 p = store_tag_length (p, 0xa0, len[6]);
2348 /* 7. And the octet string with the actual certificate. */
2349 p = store_tag_length (p, TAG_OCTET_STRING, buflen);
2350 memcpy (p, buffer, buflen);
2353 /* Append the attributes whose length we calculated at step 2b. */
2356 memcpy (p, data_attrtemplate, DIM (data_attrtemplate));
2357 for (i=0; i < 8; i++)
2358 p[DATA_ATTRTEMPLATE_KEYID_OFF+2*i+1] = keyidstr[i];
2359 p += DIM (data_attrtemplate);
2360 memcpy (p, sha1hash, 20);
2364 certseqlen = p - certseq;
2365 if (needed != certseqlen)
2366 log_debug ("length mismatch: %lu, %lu\n",
2367 (unsigned long)needed, (unsigned long)certseqlen);
2369 /* Append some pad characters; we already allocated extra space. */
2370 n = 8 - certseqlen % 8;
2371 for (i=0; i < n; i++, certseqlen++)
2374 *r_length = certseqlen;
2379 /* Expect the RSA key parameters in KPARMS and a password in PW.
2380 Create a PKCS structure from it and return it as well as the length
2381 in R_LENGTH; return NULL in case of an error. If CHARSET is not
2382 NULL, re-encode PW to that character set. */
2384 p12_build (gcry_mpi_t *kparms, const void *cert, size_t certlen,
2385 const char *pw, const char *charset, size_t *r_length)
2387 unsigned char *buffer = NULL;
2390 struct buffer_s seqlist[3];
2392 unsigned char sha1hash[20];
2395 size_t pwbufsize = 0;
2397 n = buflen = 0; /* (avoid compiler warning). */
2398 memset (sha1hash, 0, 20);
2401 if (charset && pw && *pw)
2406 size_t inbytes, outbytes;
2408 /* We assume that the converted passphrase is at max 2 times
2409 longer than its utf-8 encoding. */
2410 pwbufsize = strlen (pw)*2 + 1;
2411 pwbuf = gcry_malloc_secure (pwbufsize);
2414 log_error ("out of secure memory while converting passphrase\n");
2418 cd = jnlib_iconv_open (charset, "utf-8");
2419 if (cd == (jnlib_iconv_t)(-1))
2421 log_error ("can't convert passphrase to"
2422 " requested charset '%s': %s\n",
2423 charset, strerror (errno));
2428 inbytes = strlen (pw);
2430 outbytes = pwbufsize - 1;
2431 if ( jnlib_iconv (cd, (const char **)&inptr, &inbytes,
2432 &outptr, &outbytes) == (size_t)-1)
2434 log_error ("error converting passphrase to"
2435 " requested charset '%s': %s\n",
2436 charset, strerror (errno));
2437 jnlib_iconv_close (cd);
2441 jnlib_iconv_close (cd);
2446 if (cert && certlen)
2448 /* Calculate the hash value we need for the bag attributes. */
2449 gcry_md_hash_buffer (GCRY_MD_SHA1, sha1hash, cert, certlen);
2450 sprintf (keyidstr, "%02x%02x%02x%02x",
2451 sha1hash[16], sha1hash[17], sha1hash[18], sha1hash[19]);
2453 /* Encode the certificate. */
2454 buffer = build_cert_sequence (cert, certlen, sha1hash, keyidstr,
2460 gcry_randomize (salt, 8, GCRY_STRONG_RANDOM);
2461 crypt_block (buffer, buflen, salt, 8, 2048, NULL, 0, pw,
2462 GCRY_CIPHER_RFC2268_40, 1);
2464 /* Encode the encrypted stuff into a bag. */
2465 seqlist[seqlistidx].buffer = build_cert_bag (buffer, buflen, salt, &n);
2466 seqlist[seqlistidx].length = n;
2469 if (!seqlist[seqlistidx].buffer)
2477 /* Encode the key. */
2478 buffer = build_key_sequence (kparms, 0, &buflen);
2483 gcry_randomize (salt, 8, GCRY_STRONG_RANDOM);
2484 crypt_block (buffer, buflen, salt, 8, 2048, NULL, 0,
2485 pw, GCRY_CIPHER_3DES, 1);
2487 /* Encode the encrypted stuff into a bag. */
2488 if (cert && certlen)
2489 seqlist[seqlistidx].buffer = build_key_bag (buffer, buflen, salt,
2490 sha1hash, keyidstr, &n);
2492 seqlist[seqlistidx].buffer = build_key_bag (buffer, buflen, salt,
2494 seqlist[seqlistidx].length = n;
2497 if (!seqlist[seqlistidx].buffer)
2502 seqlist[seqlistidx].buffer = NULL;
2503 seqlist[seqlistidx].length = 0;
2505 buffer = create_final (seqlist, pw, &buflen);
2510 /* Note that wipememory is not really needed due to the use of
2511 gcry_malloc_secure. */
2512 wipememory (pwbuf, pwbufsize);
2515 for ( ; seqlistidx; seqlistidx--)
2516 gcry_free (seqlist[seqlistidx].buffer);
2518 *r_length = buffer? buflen : 0;
2523 /* This is actually not a pkcs#12 function but one which creates an
2524 unencrypted a pkcs#1 private key. */
2526 p12_raw_build (gcry_mpi_t *kparms, int rawmode, size_t *r_length)
2528 unsigned char *buffer;
2531 assert (rawmode == 1 || rawmode == 2);
2532 buffer = build_key_sequence (kparms, rawmode, &buflen);
2544 cert_cb (void *opaque, const unsigned char *cert, size_t certlen)
2546 printf ("got a certificate of %u bytes length\n", certlen);
2550 main (int argc, char **argv)
2561 fprintf (stderr, "usage: testp12 file passphrase\n");
2565 gcry_control (GCRYCTL_DISABLE_SECMEM, NULL);
2566 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, NULL);
2568 fp = fopen (argv[1], "rb");
2571 fprintf (stderr, "can't open '%s': %s\n", argv[1], strerror (errno));
2575 if (fstat (fileno(fp), &st))
2577 fprintf (stderr, "can't stat '%s': %s\n", argv[1], strerror (errno));
2581 buflen = st.st_size;
2582 buf = gcry_malloc (buflen+1);
2583 if (!buf || fread (buf, buflen, 1, fp) != 1)
2585 fprintf (stderr, "error reading '%s': %s\n", argv[1], strerror (errno));
2590 result = p12_parse (buf, buflen, argv[2], cert_cb, NULL, &badpass);
2594 unsigned char *tmpbuf;
2596 for (i=0; result[i]; i++)
2598 rc = gcry_mpi_aprint (GCRYMPI_FMT_HEX, &tmpbuf,
2601 printf ("%d: [error printing number: %s]\n",
2602 i, gpg_strerror (rc));
2605 printf ("%d: %s\n", i, tmpbuf);
2617 compile-command: "gcc -Wall -O0 -g -DTEST=1 -o minip12 minip12.c ../common/libcommon.a -L /usr/local/lib -lgcrypt -lgpg-error"