1 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
2  * project 1999-2004.
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 <assert.h>
57 #include <limits.h>
58 #include <string.h>
59 
60 #include <openssl/asn1t.h>
61 #include <openssl/cipher.h>
62 #include <openssl/err.h>
63 #include <openssl/mem.h>
64 #include <openssl/pkcs8.h>
65 #include <openssl/rand.h>
66 #include <openssl/x509.h>
67 
68 #include "internal.h"
69 
70 
71 /* PKCS#5 v2.0 password based encryption structures */
72 
73 ASN1_SEQUENCE(PBE2PARAM) = {
74 	ASN1_SIMPLE(PBE2PARAM, keyfunc, X509_ALGOR),
75 	ASN1_SIMPLE(PBE2PARAM, encryption, X509_ALGOR)
76 } ASN1_SEQUENCE_END(PBE2PARAM)
77 
78 IMPLEMENT_ASN1_FUNCTIONS(PBE2PARAM)
79 
80 ASN1_SEQUENCE(PBKDF2PARAM) = {
81 	ASN1_SIMPLE(PBKDF2PARAM, salt, ASN1_ANY),
82 	ASN1_SIMPLE(PBKDF2PARAM, iter, ASN1_INTEGER),
83 	ASN1_OPT(PBKDF2PARAM, keylength, ASN1_INTEGER),
84 	ASN1_OPT(PBKDF2PARAM, prf, X509_ALGOR)
85 } ASN1_SEQUENCE_END(PBKDF2PARAM)
86 
87 IMPLEMENT_ASN1_FUNCTIONS(PBKDF2PARAM);
88 
ASN1_TYPE_set_octetstring(ASN1_TYPE * a,unsigned char * data,int len)89 static int ASN1_TYPE_set_octetstring(ASN1_TYPE *a, unsigned char *data, int len)
90 	{
91 	ASN1_STRING *os;
92 
93 	if ((os=M_ASN1_OCTET_STRING_new()) == NULL) return(0);
94 	if (!M_ASN1_OCTET_STRING_set(os,data,len))
95 		{
96 		M_ASN1_OCTET_STRING_free(os);
97 		return 0;
98 		}
99 	ASN1_TYPE_set(a,V_ASN1_OCTET_STRING,os);
100 	return(1);
101 	}
102 
param_to_asn1(EVP_CIPHER_CTX * c,ASN1_TYPE * type)103 static int param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type)
104 	{
105 	unsigned iv_len;
106 
107 	iv_len = EVP_CIPHER_CTX_iv_length(c);
108 	return ASN1_TYPE_set_octetstring(type, c->oiv, iv_len);
109 	}
110 
111 /* Return an algorithm identifier for a PKCS#5 v2.0 PBE algorithm:
112  * yes I know this is horrible!
113  *
114  * Extended version to allow application supplied PRF NID and IV. */
115 
PKCS5_pbe2_set_iv(const EVP_CIPHER * cipher,int iter,unsigned char * salt,int saltlen,unsigned char * aiv,int prf_nid)116 X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter,
117 				 unsigned char *salt, int saltlen,
118 				 unsigned char *aiv, int prf_nid)
119 {
120 	X509_ALGOR *scheme = NULL, *kalg = NULL, *ret = NULL;
121 	int alg_nid, keylen;
122 	EVP_CIPHER_CTX ctx;
123 	unsigned char iv[EVP_MAX_IV_LENGTH];
124 	PBE2PARAM *pbe2 = NULL;
125 	const ASN1_OBJECT *obj;
126 
127 	alg_nid = EVP_CIPHER_nid(cipher);
128 	if(alg_nid == NID_undef) {
129 		OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER);
130 		goto err;
131 	}
132 	obj = OBJ_nid2obj(alg_nid);
133 
134 	if(!(pbe2 = PBE2PARAM_new())) goto merr;
135 
136 	/* Setup the AlgorithmIdentifier for the encryption scheme */
137 	scheme = pbe2->encryption;
138 
139 	scheme->algorithm = (ASN1_OBJECT*) obj;
140 	if(!(scheme->parameter = ASN1_TYPE_new())) goto merr;
141 
142 	/* Create random IV */
143 	if (EVP_CIPHER_iv_length(cipher))
144 		{
145 		if (aiv)
146 			memcpy(iv, aiv, EVP_CIPHER_iv_length(cipher));
147 		else if (!RAND_bytes(iv, EVP_CIPHER_iv_length(cipher)))
148   			goto err;
149 		}
150 
151 	EVP_CIPHER_CTX_init(&ctx);
152 
153 	/* Dummy cipherinit to just setup the IV, and PRF */
154 	if (!EVP_CipherInit_ex(&ctx, cipher, NULL, NULL, iv, 0))
155 		goto err;
156 	if(param_to_asn1(&ctx, scheme->parameter) < 0) {
157 		OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_ERROR_SETTING_CIPHER_PARAMS);
158 		EVP_CIPHER_CTX_cleanup(&ctx);
159 		goto err;
160 	}
161 	/* If prf NID unspecified see if cipher has a preference.
162 	 * An error is OK here: just means use default PRF.
163 	 */
164 	if ((prf_nid == -1) &&
165 	EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_PBE_PRF_NID, 0, &prf_nid) <= 0)
166 		{
167 		ERR_clear_error();
168 		prf_nid = NID_hmacWithSHA1;
169 		}
170 	EVP_CIPHER_CTX_cleanup(&ctx);
171 
172 	/* If its RC2 then we'd better setup the key length */
173 
174 	if(alg_nid == NID_rc2_cbc)
175 		keylen = EVP_CIPHER_key_length(cipher);
176 	else
177 		keylen = -1;
178 
179 	/* Setup keyfunc */
180 
181 	X509_ALGOR_free(pbe2->keyfunc);
182 
183 	pbe2->keyfunc = PKCS5_pbkdf2_set(iter, salt, saltlen, prf_nid, keylen);
184 
185 	if (!pbe2->keyfunc)
186 		goto merr;
187 
188 	/* Now set up top level AlgorithmIdentifier */
189 
190 	if(!(ret = X509_ALGOR_new())) goto merr;
191 	if(!(ret->parameter = ASN1_TYPE_new())) goto merr;
192 
193 	ret->algorithm = (ASN1_OBJECT*) OBJ_nid2obj(NID_pbes2);
194 
195 	/* Encode PBE2PARAM into parameter */
196 
197 	if(!ASN1_item_pack(pbe2, ASN1_ITEM_rptr(PBE2PARAM),
198 				 &ret->parameter->value.sequence)) goto merr;
199 	ret->parameter->type = V_ASN1_SEQUENCE;
200 
201 	PBE2PARAM_free(pbe2);
202 	pbe2 = NULL;
203 
204 	return ret;
205 
206 	merr:
207 	OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
208 
209 	err:
210 	PBE2PARAM_free(pbe2);
211 	/* Note 'scheme' is freed as part of pbe2 */
212 	X509_ALGOR_free(kalg);
213 	X509_ALGOR_free(ret);
214 
215 	return NULL;
216 
217 }
218 
PKCS5_pbe2_set(const EVP_CIPHER * cipher,int iter,unsigned char * salt,int saltlen)219 X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter,
220 				 unsigned char *salt, int saltlen)
221 	{
222 	return PKCS5_pbe2_set_iv(cipher, iter, salt, saltlen, NULL, -1);
223 	}
224 
PKCS5_pbkdf2_set(int iter,unsigned char * salt,int saltlen,int prf_nid,int keylen)225 X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen,
226 				int prf_nid, int keylen)
227 	{
228 	X509_ALGOR *keyfunc = NULL;
229 	PBKDF2PARAM *kdf = NULL;
230 	ASN1_OCTET_STRING *osalt = NULL;
231 
232 	if(!(kdf = PBKDF2PARAM_new()))
233 		goto merr;
234 	if(!(osalt = M_ASN1_OCTET_STRING_new()))
235 		goto merr;
236 
237 	kdf->salt->value.octet_string = osalt;
238 	kdf->salt->type = V_ASN1_OCTET_STRING;
239 
240 	if (!saltlen)
241 		saltlen = PKCS5_SALT_LEN;
242 	if (!(osalt->data = OPENSSL_malloc (saltlen)))
243 		goto merr;
244 
245 	osalt->length = saltlen;
246 
247 	if (salt)
248 		memcpy (osalt->data, salt, saltlen);
249 	else if (!RAND_bytes(osalt->data, saltlen))
250 		goto merr;
251 
252 	if(iter <= 0)
253 		iter = PKCS5_DEFAULT_ITERATIONS;
254 
255 	if(!ASN1_INTEGER_set(kdf->iter, iter))
256 		goto merr;
257 
258 	/* If have a key len set it up */
259 
260 	if(keylen > 0)
261 		{
262 		if(!(kdf->keylength = M_ASN1_INTEGER_new()))
263 			goto merr;
264 		if(!ASN1_INTEGER_set (kdf->keylength, keylen))
265 			goto merr;
266 		}
267 
268 	/* prf can stay NULL if we are using hmacWithSHA1 */
269 	if (prf_nid > 0 && prf_nid != NID_hmacWithSHA1)
270 		{
271 		kdf->prf = X509_ALGOR_new();
272 		if (!kdf->prf)
273 			goto merr;
274 		X509_ALGOR_set0(kdf->prf, OBJ_nid2obj(prf_nid),
275 					V_ASN1_NULL, NULL);
276 		}
277 
278 	/* Finally setup the keyfunc structure */
279 
280 	keyfunc = X509_ALGOR_new();
281 	if (!keyfunc)
282 		goto merr;
283 
284 	keyfunc->algorithm = (ASN1_OBJECT*) OBJ_nid2obj(NID_id_pbkdf2);
285 
286 	/* Encode PBKDF2PARAM into parameter of pbe2 */
287 
288 	if(!(keyfunc->parameter = ASN1_TYPE_new()))
289 		goto merr;
290 
291 	if(!ASN1_item_pack(kdf, ASN1_ITEM_rptr(PBKDF2PARAM),
292 			 &keyfunc->parameter->value.sequence))
293 		goto merr;
294 	keyfunc->parameter->type = V_ASN1_SEQUENCE;
295 
296 	PBKDF2PARAM_free(kdf);
297 	return keyfunc;
298 
299 	merr:
300 	OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
301 	PBKDF2PARAM_free(kdf);
302 	X509_ALGOR_free(keyfunc);
303 	return NULL;
304 	}
305 
PKCS5_v2_PBKDF2_keyivgen(EVP_CIPHER_CTX * ctx,const uint8_t * pass_raw,size_t pass_raw_len,const ASN1_TYPE * param,const ASN1_TYPE * iv,int enc)306 static int PKCS5_v2_PBKDF2_keyivgen(EVP_CIPHER_CTX *ctx,
307                                     const uint8_t *pass_raw,
308                                     size_t pass_raw_len, const ASN1_TYPE *param,
309                                     const ASN1_TYPE *iv, int enc) {
310   int rv = 0;
311   PBKDF2PARAM *pbkdf2param = NULL;
312 
313   if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
314     OPENSSL_PUT_ERROR(PKCS8, CIPHER_R_NO_CIPHER_SET);
315     goto err;
316   }
317 
318   /* Decode parameters. */
319   if (param == NULL || param->type != V_ASN1_SEQUENCE) {
320     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
321     goto err;
322   }
323 
324   const uint8_t *pbuf = param->value.sequence->data;
325   int plen = param->value.sequence->length;
326   pbkdf2param = d2i_PBKDF2PARAM(NULL, &pbuf, plen);
327   if (pbkdf2param == NULL || pbuf != param->value.sequence->data + plen) {
328     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
329     goto err;
330   }
331 
332   /* Now check the parameters. */
333   uint8_t key[EVP_MAX_KEY_LENGTH];
334   const size_t key_len = EVP_CIPHER_CTX_key_length(ctx);
335   assert(key_len <= sizeof(key));
336 
337   if (pbkdf2param->keylength != NULL &&
338       ASN1_INTEGER_get(pbkdf2param->keylength) != (int) key_len) {
339     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNSUPPORTED_KEYLENGTH);
340     goto err;
341   }
342 
343   if (pbkdf2param->prf != NULL &&
344       OBJ_obj2nid(pbkdf2param->prf->algorithm) != NID_hmacWithSHA1) {
345     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNSUPPORTED_PRF);
346     goto err;
347   }
348 
349   if (pbkdf2param->salt->type != V_ASN1_OCTET_STRING) {
350     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNSUPPORTED_SALT_TYPE);
351     goto err;
352   }
353 
354   if (pbkdf2param->iter->type != V_ASN1_INTEGER) {
355     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_ITERATION_COUNT);
356     goto err;
357   }
358   long iterations = ASN1_INTEGER_get(pbkdf2param->iter);
359   if (iterations <= 0 ||
360       (sizeof(long) > sizeof(unsigned) && iterations > (long)UINT_MAX)) {
361     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_ITERATION_COUNT);
362     goto err;
363   }
364 
365   if (iv->type != V_ASN1_OCTET_STRING || iv->value.octet_string == NULL) {
366     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_ERROR_SETTING_CIPHER_PARAMS);
367     goto err;
368   }
369 
370   const size_t iv_len = EVP_CIPHER_CTX_iv_length(ctx);
371   if ((size_t) iv->value.octet_string->length != iv_len) {
372     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_ERROR_SETTING_CIPHER_PARAMS);
373     goto err;
374   }
375 
376   if (!PKCS5_PBKDF2_HMAC_SHA1((const char *) pass_raw, pass_raw_len,
377                               pbkdf2param->salt->value.octet_string->data,
378                               pbkdf2param->salt->value.octet_string->length,
379                               iterations, key_len, key)) {
380     goto err;
381   }
382 
383   rv = EVP_CipherInit_ex(ctx, NULL /* cipher */, NULL /* engine */, key,
384                          iv->value.octet_string->data, enc);
385 
386  err:
387   PBKDF2PARAM_free(pbkdf2param);
388   return rv;
389 }
390 
PKCS5_v2_PBE_keyivgen(EVP_CIPHER_CTX * ctx,const uint8_t * pass_raw,size_t pass_raw_len,ASN1_TYPE * param,const EVP_CIPHER * unused,const EVP_MD * unused2,int enc)391 int PKCS5_v2_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const uint8_t *pass_raw,
392                           size_t pass_raw_len, ASN1_TYPE *param,
393                           const EVP_CIPHER *unused, const EVP_MD *unused2,
394                           int enc) {
395   PBE2PARAM *pbe2param = NULL;
396   int rv = 0;
397 
398   if (param == NULL ||
399       param->type != V_ASN1_SEQUENCE ||
400       param->value.sequence == NULL) {
401     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
402     goto err;
403   }
404 
405   const uint8_t *pbuf = param->value.sequence->data;
406   int plen = param->value.sequence->length;
407   pbe2param = d2i_PBE2PARAM(NULL, &pbuf, plen);
408   if (pbe2param == NULL || pbuf != param->value.sequence->data + plen) {
409     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
410     goto err;
411   }
412 
413   /* Check that the key derivation function is PBKDF2. */
414   if (OBJ_obj2nid(pbe2param->keyfunc->algorithm) != NID_id_pbkdf2) {
415     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION);
416     goto err;
417   }
418 
419   /* See if we recognise the encryption algorithm. */
420   const EVP_CIPHER *cipher =
421       EVP_get_cipherbynid(OBJ_obj2nid(pbe2param->encryption->algorithm));
422   if (cipher == NULL) {
423     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNSUPPORTED_CIPHER);
424     goto err;
425   }
426 
427   /* Fixup cipher based on AlgorithmIdentifier. */
428   if (!EVP_CipherInit_ex(ctx, cipher, NULL /* engine */, NULL /* key */,
429                          NULL /* iv */, enc)) {
430     goto err;
431   }
432 
433   rv = PKCS5_v2_PBKDF2_keyivgen(ctx, pass_raw, pass_raw_len,
434                                 pbe2param->keyfunc->parameter,
435                                 pbe2param->encryption->parameter, enc);
436 
437  err:
438   PBE2PARAM_free(pbe2param);
439   return rv;
440 }
441