• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
2  * project 1999.
3  */
4 /* ====================================================================
5  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. All advertising materials mentioning features or use of this
20  *    software must display the following acknowledgment:
21  *    "This product includes software developed by the OpenSSL Project
22  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
23  *
24  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
25  *    endorse or promote products derived from this software without
26  *    prior written permission. For written permission, please contact
27  *    licensing@OpenSSL.org.
28  *
29  * 5. Products derived from this software may not be called "OpenSSL"
30  *    nor may "OpenSSL" appear in their names without prior written
31  *    permission of the OpenSSL Project.
32  *
33  * 6. Redistributions of any form whatsoever must retain the following
34  *    acknowledgment:
35  *    "This product includes software developed by the OpenSSL Project
36  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
37  *
38  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
39  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
41  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
42  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
44  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
45  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
47  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
49  * OF THE POSSIBILITY OF SUCH DAMAGE.
50  * ====================================================================
51  *
52  * This product includes cryptographic software written by Eric Young
53  * (eay@cryptsoft.com).  This product includes software written by Tim
54  * Hudson (tjh@cryptsoft.com). */
55 
56 #include <openssl/pkcs8.h>
57 
58 #include <assert.h>
59 #include <limits.h>
60 #include <string.h>
61 
62 #include <openssl/bytestring.h>
63 #include <openssl/cipher.h>
64 #include <openssl/digest.h>
65 #include <openssl/err.h>
66 #include <openssl/mem.h>
67 #include <openssl/nid.h>
68 #include <openssl/rand.h>
69 
70 #include "internal.h"
71 #include "../internal.h"
72 
73 
ascii_to_ucs2(const char * ascii,size_t ascii_len,uint8_t ** out,size_t * out_len)74 static int ascii_to_ucs2(const char *ascii, size_t ascii_len,
75                          uint8_t **out, size_t *out_len) {
76   size_t ulen = ascii_len * 2 + 2;
77   if (ascii_len * 2 < ascii_len || ulen < ascii_len * 2) {
78     return 0;
79   }
80 
81   uint8_t *unitmp = OPENSSL_malloc(ulen);
82   if (unitmp == NULL) {
83     OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
84     return 0;
85   }
86   for (size_t i = 0; i < ulen - 2; i += 2) {
87     unitmp[i] = 0;
88     unitmp[i + 1] = ascii[i >> 1];
89   }
90 
91   /* Terminate the result with a UCS-2 NUL. */
92   unitmp[ulen - 2] = 0;
93   unitmp[ulen - 1] = 0;
94   *out_len = ulen;
95   *out = unitmp;
96   return 1;
97 }
98 
pkcs12_key_gen(const char * pass,size_t pass_len,const uint8_t * salt,size_t salt_len,uint8_t id,unsigned iterations,size_t out_len,uint8_t * out,const EVP_MD * md)99 int pkcs12_key_gen(const char *pass, size_t pass_len, const uint8_t *salt,
100                    size_t salt_len, uint8_t id, unsigned iterations,
101                    size_t out_len, uint8_t *out, const EVP_MD *md) {
102   /* See https://tools.ietf.org/html/rfc7292#appendix-B. Quoted parts of the
103    * specification have errata applied and other typos fixed. */
104 
105   if (iterations < 1) {
106     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_ITERATION_COUNT);
107     return 0;
108   }
109 
110   int ret = 0;
111   EVP_MD_CTX ctx;
112   EVP_MD_CTX_init(&ctx);
113   uint8_t *pass_raw = NULL, *I = NULL;
114   size_t pass_raw_len = 0, I_len = 0;
115   /* If |pass| is NULL, we use the empty string rather than {0, 0} as the raw
116    * password. */
117   if (pass != NULL &&
118       !ascii_to_ucs2(pass, pass_len, &pass_raw, &pass_raw_len)) {
119     goto err;
120   }
121 
122   /* In the spec, |block_size| is called "v", but measured in bits. */
123   size_t block_size = EVP_MD_block_size(md);
124 
125   /* 1. Construct a string, D (the "diversifier"), by concatenating v/8 copies
126    * of ID. */
127   uint8_t D[EVP_MAX_MD_BLOCK_SIZE];
128   OPENSSL_memset(D, id, block_size);
129 
130   /* 2. Concatenate copies of the salt together to create a string S of length
131    * v(ceiling(s/v)) bits (the final copy of the salt may be truncated to
132    * create S). Note that if the salt is the empty string, then so is S.
133    *
134    * 3. Concatenate copies of the password together to create a string P of
135    * length v(ceiling(p/v)) bits (the final copy of the password may be
136    * truncated to create P).  Note that if the password is the empty string,
137    * then so is P.
138    *
139    * 4. Set I=S||P to be the concatenation of S and P. */
140   if (salt_len + block_size - 1 < salt_len ||
141       pass_raw_len + block_size - 1 < pass_raw_len) {
142     OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
143     goto err;
144   }
145   size_t S_len = block_size * ((salt_len + block_size - 1) / block_size);
146   size_t P_len = block_size * ((pass_raw_len + block_size - 1) / block_size);
147   I_len = S_len + P_len;
148   if (I_len < S_len) {
149     OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
150     goto err;
151   }
152 
153   I = OPENSSL_malloc(I_len);
154   if (I_len != 0 && I == NULL) {
155     OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
156     goto err;
157   }
158 
159   for (size_t i = 0; i < S_len; i++) {
160     I[i] = salt[i % salt_len];
161   }
162   for (size_t i = 0; i < P_len; i++) {
163     I[i + S_len] = pass_raw[i % pass_raw_len];
164   }
165 
166   while (out_len != 0) {
167     /* A. Set A_i=H^r(D||I). (i.e., the r-th hash of D||I,
168      * H(H(H(... H(D||I)))) */
169     uint8_t A[EVP_MAX_MD_SIZE];
170     unsigned A_len;
171     if (!EVP_DigestInit_ex(&ctx, md, NULL) ||
172         !EVP_DigestUpdate(&ctx, D, block_size) ||
173         !EVP_DigestUpdate(&ctx, I, I_len) ||
174         !EVP_DigestFinal_ex(&ctx, A, &A_len)) {
175       goto err;
176     }
177     for (unsigned iter = 1; iter < iterations; iter++) {
178       if (!EVP_DigestInit_ex(&ctx, md, NULL) ||
179           !EVP_DigestUpdate(&ctx, A, A_len) ||
180           !EVP_DigestFinal_ex(&ctx, A, &A_len)) {
181         goto err;
182       }
183     }
184 
185     size_t todo = out_len < A_len ? out_len : A_len;
186     OPENSSL_memcpy(out, A, todo);
187     out += todo;
188     out_len -= todo;
189     if (out_len == 0) {
190       break;
191     }
192 
193     /* B. Concatenate copies of A_i to create a string B of length v bits (the
194      * final copy of A_i may be truncated to create B). */
195     uint8_t B[EVP_MAX_MD_BLOCK_SIZE];
196     for (size_t i = 0; i < block_size; i++) {
197       B[i] = A[i % A_len];
198     }
199 
200     /* C. Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit blocks,
201      * where k=ceiling(s/v)+ceiling(p/v), modify I by setting I_j=(I_j+B+1) mod
202      * 2^v for each j. */
203     assert(I_len % block_size == 0);
204     for (size_t i = 0; i < I_len; i += block_size) {
205       unsigned carry = 1;
206       for (size_t j = block_size - 1; j < block_size; j--) {
207         carry += I[i + j] + B[j];
208         I[i + j] = (uint8_t)carry;
209         carry >>= 8;
210       }
211     }
212   }
213 
214   ret = 1;
215 
216 err:
217   if (I != NULL) {
218     OPENSSL_cleanse(I, I_len);
219     OPENSSL_free(I);
220   }
221   if (pass_raw != NULL) {
222     OPENSSL_cleanse(pass_raw, pass_raw_len);
223     OPENSSL_free(pass_raw);
224   }
225   EVP_MD_CTX_cleanup(&ctx);
226   return ret;
227 }
228 
pkcs12_pbe_cipher_init(const struct pbe_suite * suite,EVP_CIPHER_CTX * ctx,unsigned iterations,const char * pass,size_t pass_len,const uint8_t * salt,size_t salt_len,int is_encrypt)229 static int pkcs12_pbe_cipher_init(const struct pbe_suite *suite,
230                                   EVP_CIPHER_CTX *ctx, unsigned iterations,
231                                   const char *pass, size_t pass_len,
232                                   const uint8_t *salt, size_t salt_len,
233                                   int is_encrypt) {
234   const EVP_CIPHER *cipher = suite->cipher_func();
235   const EVP_MD *md = suite->md_func();
236 
237   uint8_t key[EVP_MAX_KEY_LENGTH];
238   uint8_t iv[EVP_MAX_IV_LENGTH];
239   if (!pkcs12_key_gen(pass, pass_len, salt, salt_len, PKCS12_KEY_ID, iterations,
240                       EVP_CIPHER_key_length(cipher), key, md) ||
241       !pkcs12_key_gen(pass, pass_len, salt, salt_len, PKCS12_IV_ID, iterations,
242                       EVP_CIPHER_iv_length(cipher), iv, md)) {
243     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_KEY_GEN_ERROR);
244     return 0;
245   }
246 
247   int ret = EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, is_encrypt);
248   OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH);
249   OPENSSL_cleanse(iv, EVP_MAX_IV_LENGTH);
250   return ret;
251 }
252 
pkcs12_pbe_decrypt_init(const struct pbe_suite * suite,EVP_CIPHER_CTX * ctx,const char * pass,size_t pass_len,CBS * param)253 static int pkcs12_pbe_decrypt_init(const struct pbe_suite *suite,
254                                    EVP_CIPHER_CTX *ctx, const char *pass,
255                                    size_t pass_len, CBS *param) {
256   CBS pbe_param, salt;
257   uint64_t iterations;
258   if (!CBS_get_asn1(param, &pbe_param, CBS_ASN1_SEQUENCE) ||
259       !CBS_get_asn1(&pbe_param, &salt, CBS_ASN1_OCTETSTRING) ||
260       !CBS_get_asn1_uint64(&pbe_param, &iterations) ||
261       CBS_len(&pbe_param) != 0 ||
262       CBS_len(param) != 0) {
263     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
264     return 0;
265   }
266 
267   if (iterations == 0 || iterations > UINT_MAX) {
268     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_ITERATION_COUNT);
269     return 0;
270   }
271 
272   return pkcs12_pbe_cipher_init(suite, ctx, (unsigned)iterations, pass,
273                                 pass_len, CBS_data(&salt), CBS_len(&salt),
274                                 0 /* decrypt */);
275 }
276 
277 static const struct pbe_suite kBuiltinPBE[] = {
278     {
279         NID_pbe_WithSHA1And40BitRC2_CBC,
280         /* 1.2.840.113549.1.12.1.6 */
281         {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x06},
282         10,
283         EVP_rc2_40_cbc,
284         EVP_sha1,
285         pkcs12_pbe_decrypt_init,
286     },
287     {
288         NID_pbe_WithSHA1And128BitRC4,
289         /* 1.2.840.113549.1.12.1.1 */
290         {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x01},
291         10,
292         EVP_rc4,
293         EVP_sha1,
294         pkcs12_pbe_decrypt_init,
295     },
296     {
297         NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
298         /* 1.2.840.113549.1.12.1.3 */
299         {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x03},
300         10,
301         EVP_des_ede3_cbc,
302         EVP_sha1,
303         pkcs12_pbe_decrypt_init,
304     },
305     {
306         NID_pbes2,
307         /* 1.2.840.113549.1.5.13 */
308         {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0d},
309         9,
310         NULL,
311         NULL,
312         PKCS5_pbe2_decrypt_init,
313     },
314 };
315 
get_pbe_suite(int pbe_nid)316 static const struct pbe_suite *get_pbe_suite(int pbe_nid) {
317   for (unsigned i = 0; i < OPENSSL_ARRAY_SIZE(kBuiltinPBE); i++) {
318     if (kBuiltinPBE[i].pbe_nid == pbe_nid) {
319       return &kBuiltinPBE[i];
320     }
321   }
322 
323   return NULL;
324 }
325 
pkcs12_pbe_encrypt_init(CBB * out,EVP_CIPHER_CTX * ctx,int alg,unsigned iterations,const char * pass,size_t pass_len,const uint8_t * salt,size_t salt_len)326 static int pkcs12_pbe_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, int alg,
327                                    unsigned iterations, const char *pass,
328                                    size_t pass_len, const uint8_t *salt,
329                                    size_t salt_len) {
330   const struct pbe_suite *suite = get_pbe_suite(alg);
331   if (suite == NULL) {
332     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNKNOWN_ALGORITHM);
333     return 0;
334   }
335 
336   /* See RFC 2898, appendix A.3. */
337   CBB algorithm, oid, param, salt_cbb;
338   if (!CBB_add_asn1(out, &algorithm, CBS_ASN1_SEQUENCE) ||
339       !CBB_add_asn1(&algorithm, &oid, CBS_ASN1_OBJECT) ||
340       !CBB_add_bytes(&oid, suite->oid, suite->oid_len) ||
341       !CBB_add_asn1(&algorithm, &param, CBS_ASN1_SEQUENCE) ||
342       !CBB_add_asn1(&param, &salt_cbb, CBS_ASN1_OCTETSTRING) ||
343       !CBB_add_bytes(&salt_cbb, salt, salt_len) ||
344       !CBB_add_asn1_uint64(&param, iterations) ||
345       !CBB_flush(out)) {
346     return 0;
347   }
348 
349   return pkcs12_pbe_cipher_init(suite, ctx, iterations, pass, pass_len, salt,
350                                 salt_len, 1 /* encrypt */);
351 }
352 
pkcs8_pbe_decrypt(uint8_t ** out,size_t * out_len,CBS * algorithm,const char * pass,size_t pass_len,const uint8_t * in,size_t in_len)353 int pkcs8_pbe_decrypt(uint8_t **out, size_t *out_len, CBS *algorithm,
354                       const char *pass, size_t pass_len, const uint8_t *in,
355                       size_t in_len) {
356   int ret = 0;
357   uint8_t *buf = NULL;;
358   EVP_CIPHER_CTX ctx;
359   EVP_CIPHER_CTX_init(&ctx);
360 
361   CBS obj;
362   if (!CBS_get_asn1(algorithm, &obj, CBS_ASN1_OBJECT)) {
363     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
364     goto err;
365   }
366 
367   const struct pbe_suite *suite = NULL;
368   for (unsigned i = 0; i < OPENSSL_ARRAY_SIZE(kBuiltinPBE); i++) {
369     if (CBS_mem_equal(&obj, kBuiltinPBE[i].oid, kBuiltinPBE[i].oid_len)) {
370       suite = &kBuiltinPBE[i];
371       break;
372     }
373   }
374   if (suite == NULL) {
375     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNKNOWN_ALGORITHM);
376     goto err;
377   }
378 
379   if (!suite->decrypt_init(suite, &ctx, pass, pass_len, algorithm)) {
380     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_KEYGEN_FAILURE);
381     goto err;
382   }
383 
384   buf = OPENSSL_malloc(in_len);
385   if (buf == NULL) {
386     OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
387     goto err;
388   }
389 
390   if (in_len > INT_MAX) {
391     OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
392     goto err;
393   }
394 
395   int n1, n2;
396   if (!EVP_DecryptUpdate(&ctx, buf, &n1, in, (int)in_len) ||
397       !EVP_DecryptFinal_ex(&ctx, buf + n1, &n2)) {
398     goto err;
399   }
400 
401   *out = buf;
402   *out_len = n1 + n2;
403   ret = 1;
404   buf = NULL;
405 
406 err:
407   OPENSSL_free(buf);
408   EVP_CIPHER_CTX_cleanup(&ctx);
409   return ret;
410 }
411 
PKCS8_parse_encrypted_private_key(CBS * cbs,const char * pass,size_t pass_len)412 EVP_PKEY *PKCS8_parse_encrypted_private_key(CBS *cbs, const char *pass,
413                                             size_t pass_len) {
414   /* See RFC 5208, section 6. */
415   CBS epki, algorithm, ciphertext;
416   if (!CBS_get_asn1(cbs, &epki, CBS_ASN1_SEQUENCE) ||
417       !CBS_get_asn1(&epki, &algorithm, CBS_ASN1_SEQUENCE) ||
418       !CBS_get_asn1(&epki, &ciphertext, CBS_ASN1_OCTETSTRING) ||
419       CBS_len(&epki) != 0) {
420     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
421     return 0;
422   }
423 
424   uint8_t *out;
425   size_t out_len;
426   if (!pkcs8_pbe_decrypt(&out, &out_len, &algorithm, pass, pass_len,
427                          CBS_data(&ciphertext), CBS_len(&ciphertext))) {
428     return 0;
429   }
430 
431   CBS pki;
432   CBS_init(&pki, out, out_len);
433   EVP_PKEY *ret = EVP_parse_private_key(&pki);
434   OPENSSL_cleanse(out, out_len);
435   OPENSSL_free(out);
436   return ret;
437 }
438 
PKCS8_marshal_encrypted_private_key(CBB * out,int pbe_nid,const EVP_CIPHER * cipher,const char * pass,size_t pass_len,const uint8_t * salt,size_t salt_len,int iterations,const EVP_PKEY * pkey)439 int PKCS8_marshal_encrypted_private_key(CBB *out, int pbe_nid,
440                                         const EVP_CIPHER *cipher,
441                                         const char *pass, size_t pass_len,
442                                         const uint8_t *salt, size_t salt_len,
443                                         int iterations, const EVP_PKEY *pkey) {
444   int ret = 0;
445   uint8_t *plaintext = NULL, *salt_buf = NULL;
446   size_t plaintext_len = 0;
447   EVP_CIPHER_CTX ctx;
448   EVP_CIPHER_CTX_init(&ctx);
449 
450   /* Generate a random salt if necessary. */
451   if (salt == NULL) {
452     if (salt_len == 0) {
453       salt_len = PKCS5_SALT_LEN;
454     }
455 
456     salt_buf = OPENSSL_malloc(salt_len);
457     if (salt_buf == NULL ||
458         !RAND_bytes(salt_buf, salt_len)) {
459       goto err;
460     }
461 
462     salt = salt_buf;
463   }
464 
465   if (iterations <= 0) {
466     iterations = PKCS5_DEFAULT_ITERATIONS;
467   }
468 
469   /* Serialize the input key. */
470   CBB plaintext_cbb;
471   if (!CBB_init(&plaintext_cbb, 128) ||
472       !EVP_marshal_private_key(&plaintext_cbb, pkey) ||
473       !CBB_finish(&plaintext_cbb, &plaintext, &plaintext_len)) {
474     CBB_cleanup(&plaintext_cbb);
475     goto err;
476   }
477 
478   CBB epki;
479   if (!CBB_add_asn1(out, &epki, CBS_ASN1_SEQUENCE)) {
480     goto err;
481   }
482 
483   int alg_ok;
484   if (pbe_nid == -1) {
485     alg_ok = PKCS5_pbe2_encrypt_init(&epki, &ctx, cipher, (unsigned)iterations,
486                                      pass, pass_len, salt, salt_len);
487   } else {
488     alg_ok = pkcs12_pbe_encrypt_init(&epki, &ctx, pbe_nid, (unsigned)iterations,
489                                      pass, pass_len, salt, salt_len);
490   }
491   if (!alg_ok) {
492     goto err;
493   }
494 
495   size_t max_out = plaintext_len + EVP_CIPHER_CTX_block_size(&ctx);
496   if (max_out < plaintext_len) {
497     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_TOO_LONG);
498     goto err;
499   }
500 
501   CBB ciphertext;
502   uint8_t *ptr;
503   int n1, n2;
504   if (!CBB_add_asn1(&epki, &ciphertext, CBS_ASN1_OCTETSTRING) ||
505       !CBB_reserve(&ciphertext, &ptr, max_out) ||
506       !EVP_CipherUpdate(&ctx, ptr, &n1, plaintext, plaintext_len) ||
507       !EVP_CipherFinal_ex(&ctx, ptr + n1, &n2) ||
508       !CBB_did_write(&ciphertext, n1 + n2) ||
509       !CBB_flush(out)) {
510     goto err;
511   }
512 
513   ret = 1;
514 
515 err:
516   if (plaintext != NULL) {
517     OPENSSL_cleanse(plaintext, plaintext_len);
518     OPENSSL_free(plaintext);
519   }
520   OPENSSL_free(salt_buf);
521   EVP_CIPHER_CTX_cleanup(&ctx);
522   return ret;
523 }
524