1 /*
2  * Copyright (C) 2003-2016 Free Software Foundation, Inc.
3  * Copyright (C) 2014-2016 Red Hat
4  * Copyright (C) 2014-2016 Nikos Mavrogiannopoulos
5  *
6  * Author: Nikos Mavrogiannopoulos
7  *
8  * This file is part of GnuTLS.
9  *
10  * The GnuTLS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1 of
13  * the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program.  If not, see <https://www.gnu.org/licenses/>
22  *
23  */
24 
25 #include "gnutls_int.h"
26 
27 #include <datum.h>
28 #include <global.h>
29 #include "errors.h"
30 #include <common.h>
31 #include <x509.h>
32 #include <x509_b64.h>
33 #include "x509_int.h"
34 #include "pkcs7_int.h"
35 #include <algorithms.h>
36 #include <num.h>
37 #include <random.h>
38 #include <pk.h>
39 
40 #define PBES1_DES_MD5_OID "1.2.840.113549.1.5.3"
41 
42 #define PBES2_OID "1.2.840.113549.1.5.13"
43 #define PBKDF2_OID "1.2.840.113549.1.5.12"
44 #define DES_EDE3_CBC_OID "1.2.840.113549.3.7"
45 #define AES_128_CBC_OID "2.16.840.1.101.3.4.1.2"
46 #define AES_192_CBC_OID "2.16.840.1.101.3.4.1.22"
47 #define AES_256_CBC_OID "2.16.840.1.101.3.4.1.42"
48 #define DES_CBC_OID "1.3.14.3.2.7"
49 
50 /* oid_pbeWithSHAAnd3_KeyTripleDES_CBC */
51 #define PKCS12_PBE_3DES_SHA1_OID "1.2.840.113549.1.12.1.3"
52 #define PKCS12_PBE_ARCFOUR_SHA1_OID "1.2.840.113549.1.12.1.1"
53 #define PKCS12_PBE_RC2_40_SHA1_OID "1.2.840.113549.1.12.1.6"
54 
55 static const struct pkcs_cipher_schema_st avail_pkcs_cipher_schemas[] = {
56 	{
57 	 .schema = PBES1_DES_MD5,
58 	 .name = "PBES1-DES-CBC-MD5",
59 	 .flag = GNUTLS_PKCS_PBES1_DES_MD5,
60 	 .cipher = GNUTLS_CIPHER_DES_CBC,
61 	 .pbes2 = 0,
62 	 .cipher_oid = PBES1_DES_MD5_OID,
63 	 .write_oid = PBES1_DES_MD5_OID,
64 	 .desc = NULL,
65 	 .iv_name = NULL,
66 	 .decrypt_only = 1},
67 	{
68 	 .schema = PBES2_3DES,
69 	 .name = "PBES2-3DES-CBC",
70 	 .flag = GNUTLS_PKCS_PBES2_3DES,
71 	 .cipher = GNUTLS_CIPHER_3DES_CBC,
72 	 .pbes2 = 1,
73 	 .cipher_oid = DES_EDE3_CBC_OID,
74 	 .write_oid = PBES2_OID,
75 	 .desc = "PKIX1.pkcs-5-des-EDE3-CBC-params",
76 	 .iv_name = "",
77 	 .decrypt_only = 0},
78 	{
79 	 .schema = PBES2_DES,
80 	 .name = "PBES2-DES-CBC",
81 	 .flag = GNUTLS_PKCS_PBES2_DES,
82 	 .cipher = GNUTLS_CIPHER_DES_CBC,
83 	 .pbes2 = 1,
84 	 .cipher_oid = DES_CBC_OID,
85 	 .write_oid = PBES2_OID,
86 	 .desc = "PKIX1.pkcs-5-des-CBC-params",
87 	 .iv_name = "",
88 	 .decrypt_only = 0},
89 	{
90 	 .schema = PBES2_AES_128,
91 	 .name = "PBES2-AES128-CBC",
92 	 .flag = GNUTLS_PKCS_PBES2_AES_128,
93 	 .cipher = GNUTLS_CIPHER_AES_128_CBC,
94 	 .pbes2 = 1,
95 	 .cipher_oid = AES_128_CBC_OID,
96 	 .write_oid = PBES2_OID,
97 	 .desc = "PKIX1.pkcs-5-aes128-CBC-params",
98 	 .iv_name = "",
99 	 .decrypt_only = 0},
100 	{
101 	 .schema = PBES2_AES_192,
102 	 .name = "PBES2-AES192-CBC",
103 	 .flag = GNUTLS_PKCS_PBES2_AES_192,
104 	 .cipher = GNUTLS_CIPHER_AES_192_CBC,
105 	 .pbes2 = 1,
106 	 .cipher_oid = AES_192_CBC_OID,
107 	 .write_oid = PBES2_OID,
108 	 .desc = "PKIX1.pkcs-5-aes192-CBC-params",
109 	 .iv_name = "",
110 	 .decrypt_only = 0},
111 	{
112 	 .schema = PBES2_AES_256,
113 	 .name = "PBES2-AES256-CBC",
114 	 .flag = GNUTLS_PKCS_PBES2_AES_256,
115 	 .cipher = GNUTLS_CIPHER_AES_256_CBC,
116 	 .pbes2 = 1,
117 	 .cipher_oid = AES_256_CBC_OID,
118 	 .write_oid = PBES2_OID,
119 	 .desc = "PKIX1.pkcs-5-aes256-CBC-params",
120 	 .iv_name = "",
121 	 .decrypt_only = 0},
122 	{
123 	 .schema = PBES2_GOST28147_89_TC26Z,
124 	 .name = "PBES2-GOST28147-89-TC26Z",
125 	 .flag = GNUTLS_PKCS_PBES2_GOST_TC26Z,
126 	 .cipher = GNUTLS_CIPHER_GOST28147_TC26Z_CFB,
127 	 .pbes2 = 1,
128 	 .cipher_oid = GOST28147_89_TC26Z_OID,
129 	 .write_oid = PBES2_OID,
130 	 .desc = "PKIX1.Gost28147-89-Parameters",
131 	 .iv_name = "iv",
132 	 .decrypt_only = 0},
133 	{
134 	 .schema = PBES2_GOST28147_89_CPA,
135 	 .name = "PBES2-GOST28147-89-CPA",
136 	 .flag = GNUTLS_PKCS_PBES2_GOST_CPA,
137 	 .cipher = GNUTLS_CIPHER_GOST28147_CPA_CFB,
138 	 .pbes2 = 1,
139 	 .cipher_oid = GOST28147_89_CPA_OID,
140 	 .write_oid = PBES2_OID,
141 	 .desc = "PKIX1.Gost28147-89-Parameters",
142 	 .iv_name = "iv",
143 	 .decrypt_only = 0},
144 	{
145 	 .schema = PBES2_GOST28147_89_CPB,
146 	 .name = "PBES2-GOST28147-89-CPB",
147 	 .flag = GNUTLS_PKCS_PBES2_GOST_CPB,
148 	 .cipher = GNUTLS_CIPHER_GOST28147_CPB_CFB,
149 	 .pbes2 = 1,
150 	 .cipher_oid = GOST28147_89_CPB_OID,
151 	 .write_oid = PBES2_OID,
152 	 .desc = "PKIX1.Gost28147-89-Parameters",
153 	 .iv_name = "iv",
154 	 .decrypt_only = 0},
155 	{
156 	 .schema = PBES2_GOST28147_89_CPC,
157 	 .name = "PBES2-GOST28147-89-CPC",
158 	 .flag = GNUTLS_PKCS_PBES2_GOST_CPC,
159 	 .cipher = GNUTLS_CIPHER_GOST28147_CPC_CFB,
160 	 .pbes2 = 1,
161 	 .cipher_oid = GOST28147_89_CPC_OID,
162 	 .write_oid = PBES2_OID,
163 	 .desc = "PKIX1.Gost28147-89-Parameters",
164 	 .iv_name = "iv",
165 	 .decrypt_only = 0},
166 	{
167 	 .schema = PBES2_GOST28147_89_CPD,
168 	 .name = "PBES2-GOST28147-89-CPD",
169 	 .flag = GNUTLS_PKCS_PBES2_GOST_CPD,
170 	 .cipher = GNUTLS_CIPHER_GOST28147_CPD_CFB,
171 	 .pbes2 = 1,
172 	 .cipher_oid = GOST28147_89_CPD_OID,
173 	 .write_oid = PBES2_OID,
174 	 .desc = "PKIX1.Gost28147-89-Parameters",
175 	 .iv_name = "iv",
176 	 .decrypt_only = 0},
177 	{
178 	 .schema = PKCS12_ARCFOUR_SHA1,
179 	 .name = "PKCS12-ARCFOUR-SHA1",
180 	 .flag = GNUTLS_PKCS_PKCS12_ARCFOUR,
181 	 .cipher = GNUTLS_CIPHER_ARCFOUR,
182 	 .pbes2 = 0,
183 	 .cipher_oid = PKCS12_PBE_ARCFOUR_SHA1_OID,
184 	 .write_oid = PKCS12_PBE_ARCFOUR_SHA1_OID,
185 	 .desc = NULL,
186 	 .iv_name = NULL,
187 	 .decrypt_only = 0},
188 	{
189 	 .schema = PKCS12_RC2_40_SHA1,
190 	 .name = "PKCS12-RC2-40-SHA1",
191 	 .flag = GNUTLS_PKCS_PKCS12_RC2_40,
192 	 .cipher = GNUTLS_CIPHER_RC2_40_CBC,
193 	 .pbes2 = 0,
194 	 .cipher_oid = PKCS12_PBE_RC2_40_SHA1_OID,
195 	 .write_oid = PKCS12_PBE_RC2_40_SHA1_OID,
196 	 .desc = NULL,
197 	 .iv_name = NULL,
198 	 .decrypt_only = 0},
199 	{
200 	 .schema = PKCS12_3DES_SHA1,
201 	 .name = "PKCS12-3DES-SHA1",
202 	 .flag = GNUTLS_PKCS_PKCS12_3DES,
203 	 .cipher = GNUTLS_CIPHER_3DES_CBC,
204 	 .pbes2 = 0,
205 	 .cipher_oid = PKCS12_PBE_3DES_SHA1_OID,
206 	 .write_oid = PKCS12_PBE_3DES_SHA1_OID,
207 	 .desc = NULL,
208 	 .iv_name = NULL,
209 	 .decrypt_only = 0},
210 	{0, 0, 0, 0, 0}
211 };
212 
213 #define PBES2_SCHEMA_LOOP(b) { \
214 	const struct pkcs_cipher_schema_st * _p; \
215 		for (_p=avail_pkcs_cipher_schemas;_p->schema != 0;_p++) { b; } \
216 	}
217 
218 #define PBES2_SCHEMA_FIND_FROM_FLAGS(fl, what) \
219 	PBES2_SCHEMA_LOOP( if (_p->flag == GNUTLS_PKCS_CIPHER_MASK(fl)) { what; } )
220 
_gnutls_pkcs_flags_to_schema(unsigned int flags)221 int _gnutls_pkcs_flags_to_schema(unsigned int flags)
222 {
223 	PBES2_SCHEMA_FIND_FROM_FLAGS(flags, return _p->schema;
224 	    );
225 
226 	gnutls_assert();
227 	_gnutls_debug_log
228 	    ("Selecting default encryption PKCS12_3DES_SHA1 (flags: %u).\n",
229 	     flags);
230 	return PKCS12_3DES_SHA1;
231 }
232 
233 /**
234  * gnutls_pkcs_schema_get_name:
235  * @schema: Holds the PKCS #12 or PBES2 schema (%gnutls_pkcs_encrypt_flags_t)
236  *
237  * This function will return a human readable description of the
238  * PKCS12 or PBES2 schema.
239  *
240  * Returns: a constraint string or %NULL on error.
241  *
242  * Since: 3.4.0
243  */
gnutls_pkcs_schema_get_name(unsigned int schema)244 const char *gnutls_pkcs_schema_get_name(unsigned int schema)
245 {
246 	PBES2_SCHEMA_FIND_FROM_FLAGS(schema, return _p->name;
247 	    );
248 	return NULL;
249 }
250 
251 /**
252  * gnutls_pkcs_schema_get_oid:
253  * @schema: Holds the PKCS #12 or PBES2 schema (%gnutls_pkcs_encrypt_flags_t)
254  *
255  * This function will return the object identifier of the
256  * PKCS12 or PBES2 schema.
257  *
258  * Returns: a constraint string or %NULL on error.
259  *
260  * Since: 3.4.0
261  */
gnutls_pkcs_schema_get_oid(unsigned int schema)262 const char *gnutls_pkcs_schema_get_oid(unsigned int schema)
263 {
264 	PBES2_SCHEMA_FIND_FROM_FLAGS(schema, return _p->cipher_oid;
265 	    );
266 	return NULL;
267 }
268 
algo_to_pbes2_cipher_schema(unsigned cipher)269 static const struct pkcs_cipher_schema_st *algo_to_pbes2_cipher_schema(unsigned
270 								       cipher)
271 {
272 	PBES2_SCHEMA_LOOP(if (_p->cipher == cipher && _p->pbes2 != 0) {
273 			  return _p;}
274 	) ;
275 
276 	gnutls_assert();
277 	return NULL;
278 }
279 
280 /* Converts a PKCS#7 encryption schema OID to an internal
281  * schema_id or returns a negative value */
_gnutls_check_pkcs_cipher_schema(const char * oid)282 int _gnutls_check_pkcs_cipher_schema(const char *oid)
283 {
284 	if (strcmp(oid, PBES2_OID) == 0)
285 		return PBES2_GENERIC;	/* PBES2 ciphers are under an umbrella OID */
286 
287 	PBES2_SCHEMA_LOOP(if (_p->pbes2 == 0 && strcmp(oid, _p->write_oid) == 0) {
288 			  return _p->schema;}
289 	) ;
290 	_gnutls_debug_log
291 	    ("PKCS #12 encryption schema OID '%s' is unsupported.\n", oid);
292 
293 	return GNUTLS_E_UNKNOWN_CIPHER_TYPE;
294 }
295 
_gnutls_pkcs_schema_get(schema_id schema)296 const struct pkcs_cipher_schema_st *_gnutls_pkcs_schema_get(schema_id schema)
297 {
298 	PBES2_SCHEMA_LOOP(if (schema == _p->schema) return _p;) ;
299 
300 	gnutls_assert();
301 	return NULL;
302 }
303 
304 /* Converts an OID to a gnutls cipher type.
305  */
306 static int
pbes2_cipher_oid_to_algo(const char * oid,gnutls_cipher_algorithm_t * algo)307 pbes2_cipher_oid_to_algo(const char *oid, gnutls_cipher_algorithm_t * algo)
308 {
309 
310 	*algo = 0;
311 	PBES2_SCHEMA_LOOP(if
312 			  (_p->pbes2 != 0 && strcmp(_p->cipher_oid, oid) == 0) {
313 			  *algo = _p->cipher; return 0;}
314 	) ;
315 
316 	_gnutls_debug_log("PKCS #8 encryption OID '%s' is unsupported.\n", oid);
317 	return GNUTLS_E_UNKNOWN_CIPHER_TYPE;
318 }
319 
320 /* Decrypts a PKCS #7 encryptedData. The output is allocated
321  * and stored in dec.
322  */
323 int
_gnutls_pkcs7_decrypt_data(const gnutls_datum_t * data,const char * password,gnutls_datum_t * dec)324 _gnutls_pkcs7_decrypt_data(const gnutls_datum_t * data,
325 			   const char *password, gnutls_datum_t * dec)
326 {
327 	int result, len;
328 	char enc_oid[MAX_OID_SIZE];
329 	gnutls_datum_t tmp;
330 	ASN1_TYPE pasn = ASN1_TYPE_EMPTY, pkcs7_asn = ASN1_TYPE_EMPTY;
331 	int params_start, params_end, params_len;
332 	struct pbkdf2_params kdf_params;
333 	struct pbe_enc_params enc_params;
334 	schema_id schema;
335 
336 	if ((result =
337 	     asn1_create_element(_gnutls_get_pkix(),
338 				 "PKIX1.pkcs-7-EncryptedData",
339 				 &pkcs7_asn)) != ASN1_SUCCESS) {
340 		gnutls_assert();
341 		result = _gnutls_asn2err(result);
342 		goto error;
343 	}
344 
345 	result = asn1_der_decoding(&pkcs7_asn, data->data, data->size, NULL);
346 	if (result != ASN1_SUCCESS) {
347 		gnutls_assert();
348 		result = _gnutls_asn2err(result);
349 		goto error;
350 	}
351 
352 	/* Check the encryption schema OID
353 	 */
354 	len = sizeof(enc_oid);
355 	result =
356 	    asn1_read_value(pkcs7_asn,
357 			    "encryptedContentInfo.contentEncryptionAlgorithm.algorithm",
358 			    enc_oid, &len);
359 	if (result != ASN1_SUCCESS) {
360 		gnutls_assert();
361 		result = _gnutls_asn2err(result);
362 		goto error;
363 	}
364 
365 	if ((result = _gnutls_check_pkcs_cipher_schema(enc_oid)) < 0) {
366 		gnutls_assert();
367 		goto error;
368 	}
369 	schema = result;
370 
371 	/* Get the DER encoding of the parameters.
372 	 */
373 	result =
374 	    asn1_der_decoding_startEnd(pkcs7_asn, data->data, data->size,
375 				       "encryptedContentInfo.contentEncryptionAlgorithm.parameters",
376 				       &params_start, &params_end);
377 	if (result != ASN1_SUCCESS) {
378 		gnutls_assert();
379 		result = _gnutls_asn2err(result);
380 		goto error;
381 	}
382 	params_len = params_end - params_start + 1;
383 
384 	result =
385 	    _gnutls_read_pkcs_schema_params(&schema, password,
386 					    &data->data[params_start],
387 					    params_len, &kdf_params,
388 					    &enc_params);
389 	if (result < 0) {
390 		gnutls_assert();
391 		goto error;
392 	}
393 
394 	/* Parameters have been decoded. Now
395 	 * decrypt the EncryptedData.
396 	 */
397 
398 	result =
399 	    _gnutls_pkcs_raw_decrypt_data(schema, pkcs7_asn,
400 					  "encryptedContentInfo.encryptedContent",
401 					  password, &kdf_params, &enc_params,
402 					  &tmp);
403 	if (result < 0) {
404 		gnutls_assert();
405 		goto error;
406 	}
407 
408 	asn1_delete_structure2(&pkcs7_asn, ASN1_DELETE_FLAG_ZEROIZE);
409 
410 	*dec = tmp;
411 
412 	return 0;
413 
414  error:
415 	asn1_delete_structure(&pasn);
416 	asn1_delete_structure2(&pkcs7_asn, ASN1_DELETE_FLAG_ZEROIZE);
417 	return result;
418 }
419 
420 int
_gnutls_pkcs7_data_enc_info(const gnutls_datum_t * data,const struct pkcs_cipher_schema_st ** p,struct pbkdf2_params * kdf_params,char ** oid)421 _gnutls_pkcs7_data_enc_info(const gnutls_datum_t * data,
422 			    const struct pkcs_cipher_schema_st **p,
423 			    struct pbkdf2_params *kdf_params, char **oid)
424 {
425 	int result, len;
426 	char enc_oid[MAX_OID_SIZE];
427 	ASN1_TYPE pasn = ASN1_TYPE_EMPTY, pkcs7_asn = ASN1_TYPE_EMPTY;
428 	int params_start, params_end, params_len;
429 	struct pbe_enc_params enc_params;
430 	schema_id schema;
431 
432 	if ((result =
433 	     asn1_create_element(_gnutls_get_pkix(),
434 				 "PKIX1.pkcs-7-EncryptedData",
435 				 &pkcs7_asn)) != ASN1_SUCCESS) {
436 		gnutls_assert();
437 		result = _gnutls_asn2err(result);
438 		goto error;
439 	}
440 
441 	result = asn1_der_decoding(&pkcs7_asn, data->data, data->size, NULL);
442 	if (result != ASN1_SUCCESS) {
443 		gnutls_assert();
444 		result = _gnutls_asn2err(result);
445 		goto error;
446 	}
447 
448 	/* Check the encryption schema OID
449 	 */
450 	len = sizeof(enc_oid);
451 	result =
452 	    asn1_read_value(pkcs7_asn,
453 			    "encryptedContentInfo.contentEncryptionAlgorithm.algorithm",
454 			    enc_oid, &len);
455 	if (result != ASN1_SUCCESS) {
456 		gnutls_assert();
457 		result = _gnutls_asn2err(result);
458 		goto error;
459 	}
460 
461 	if (oid) {
462 		*oid = gnutls_strdup(enc_oid);
463 	}
464 
465 	if ((result = _gnutls_check_pkcs_cipher_schema(enc_oid)) < 0) {
466 		gnutls_assert();
467 		goto error;
468 	}
469 	schema = result;
470 
471 	/* Get the DER encoding of the parameters.
472 	 */
473 	result =
474 	    asn1_der_decoding_startEnd(pkcs7_asn, data->data, data->size,
475 				       "encryptedContentInfo.contentEncryptionAlgorithm.parameters",
476 				       &params_start, &params_end);
477 	if (result != ASN1_SUCCESS) {
478 		gnutls_assert();
479 		result = _gnutls_asn2err(result);
480 		goto error;
481 	}
482 	params_len = params_end - params_start + 1;
483 
484 	result =
485 	    _gnutls_read_pkcs_schema_params(&schema, NULL,
486 					    &data->data[params_start],
487 					    params_len, kdf_params,
488 					    &enc_params);
489 	if (result < 0) {
490 		gnutls_assert();
491 		goto error;
492 	}
493 
494 	*p = _gnutls_pkcs_schema_get(schema);
495 	if (*p == NULL) {
496 		gnutls_assert();
497 		result = GNUTLS_E_UNKNOWN_CIPHER_TYPE;
498 		goto error;
499 	}
500 
501 	asn1_delete_structure2(&pkcs7_asn, ASN1_DELETE_FLAG_ZEROIZE);
502 
503 	return 0;
504 
505  error:
506 	asn1_delete_structure(&pasn);
507 	asn1_delete_structure2(&pkcs7_asn, ASN1_DELETE_FLAG_ZEROIZE);
508 	return result;
509 }
510 
511 /* Encrypts to a PKCS #7 encryptedData. The output is allocated
512  * and stored in enc.
513  */
514 int
_gnutls_pkcs7_encrypt_data(schema_id schema,const gnutls_datum_t * data,const char * password,gnutls_datum_t * enc)515 _gnutls_pkcs7_encrypt_data(schema_id schema,
516 			   const gnutls_datum_t * data,
517 			   const char *password, gnutls_datum_t * enc)
518 {
519 	int result;
520 	gnutls_datum_t key = { NULL, 0 };
521 	gnutls_datum_t tmp = { NULL, 0 };
522 	ASN1_TYPE pkcs7_asn = ASN1_TYPE_EMPTY;
523 	struct pbkdf2_params kdf_params;
524 	struct pbe_enc_params enc_params;
525 	const struct pkcs_cipher_schema_st *s;
526 
527 	s = _gnutls_pkcs_schema_get(schema);
528 	if (s == NULL || s->decrypt_only) {
529 		return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
530 	}
531 
532 	if ((result =
533 	     asn1_create_element(_gnutls_get_pkix(),
534 				 "PKIX1.pkcs-7-EncryptedData",
535 				 &pkcs7_asn)) != ASN1_SUCCESS) {
536 		gnutls_assert();
537 		result = _gnutls_asn2err(result);
538 		goto error;
539 	}
540 
541 	result =
542 	    asn1_write_value(pkcs7_asn,
543 			     "encryptedContentInfo.contentEncryptionAlgorithm.algorithm",
544 			     s->write_oid, 1);
545 
546 	if (result != ASN1_SUCCESS) {
547 		gnutls_assert();
548 		result = _gnutls_asn2err(result);
549 		goto error;
550 	}
551 
552 	/* Generate a symmetric key.
553 	 */
554 
555 	result =
556 	    _gnutls_pkcs_generate_key(schema, password, &kdf_params,
557 				      &enc_params, &key);
558 	if (result < 0) {
559 		gnutls_assert();
560 		goto error;
561 	}
562 
563 	result = _gnutls_pkcs_write_schema_params(schema, pkcs7_asn,
564 						  "encryptedContentInfo.contentEncryptionAlgorithm.parameters",
565 						  &kdf_params, &enc_params);
566 	if (result < 0) {
567 		gnutls_assert();
568 		goto error;
569 	}
570 
571 	/* Parameters have been encoded. Now
572 	 * encrypt the Data.
573 	 */
574 	result = _gnutls_pkcs_raw_encrypt_data(data, &enc_params, &key, &tmp);
575 	if (result < 0) {
576 		gnutls_assert();
577 		goto error;
578 	}
579 
580 	/* write the encrypted data.
581 	 */
582 	result =
583 	    asn1_write_value(pkcs7_asn,
584 			     "encryptedContentInfo.encryptedContent",
585 			     tmp.data, tmp.size);
586 	if (result != ASN1_SUCCESS) {
587 		gnutls_assert();
588 		result = _gnutls_asn2err(result);
589 		goto error;
590 	}
591 
592 	_gnutls_free_datum(&tmp);
593 	_gnutls_free_key_datum(&key);
594 
595 	/* Now write the rest of the pkcs-7 stuff.
596 	 */
597 
598 	result = _gnutls_x509_write_uint32(pkcs7_asn, "version", 0);
599 	if (result < 0) {
600 		gnutls_assert();
601 		goto error;
602 	}
603 
604 	result =
605 	    asn1_write_value(pkcs7_asn, "encryptedContentInfo.contentType",
606 			     DATA_OID, 1);
607 	if (result != ASN1_SUCCESS) {
608 		gnutls_assert();
609 		result = _gnutls_asn2err(result);
610 		goto error;
611 	}
612 
613 	result = asn1_write_value(pkcs7_asn, "unprotectedAttrs", NULL, 0);
614 	if (result != ASN1_SUCCESS) {
615 		gnutls_assert();
616 		result = _gnutls_asn2err(result);
617 		goto error;
618 	}
619 
620 	/* Now encode and copy the DER stuff.
621 	 */
622 	result = _gnutls_x509_der_encode(pkcs7_asn, "", enc, 0);
623 
624 	asn1_delete_structure2(&pkcs7_asn, ASN1_DELETE_FLAG_ZEROIZE);
625 
626 	if (result < 0) {
627 		gnutls_assert();
628 		goto error;
629 	}
630 
631  error:
632 	_gnutls_free_key_datum(&key);
633 	_gnutls_free_datum(&tmp);
634 	asn1_delete_structure2(&pkcs7_asn, ASN1_DELETE_FLAG_ZEROIZE);
635 	return result;
636 }
637 
638 /* Reads the PBKDF2 parameters.
639  */
640 static int
read_pbkdf2_params(ASN1_TYPE pasn,const gnutls_datum_t * der,struct pbkdf2_params * params)641 read_pbkdf2_params(ASN1_TYPE pasn,
642 		   const gnutls_datum_t * der, struct pbkdf2_params *params)
643 {
644 	int params_start, params_end;
645 	int params_len, len, result;
646 	ASN1_TYPE pbkdf2_asn = ASN1_TYPE_EMPTY;
647 	char oid[MAX_OID_SIZE];
648 
649 	memset(params, 0, sizeof(*params));
650 
651 	params->mac = GNUTLS_MAC_SHA1;
652 
653 	/* Check the key derivation algorithm
654 	 */
655 	len = sizeof(oid);
656 	result =
657 	    asn1_read_value(pasn, "keyDerivationFunc.algorithm", oid, &len);
658 	if (result != ASN1_SUCCESS) {
659 		gnutls_assert();
660 		return _gnutls_asn2err(result);
661 	}
662 	_gnutls_hard_log("keyDerivationFunc.algorithm: %s\n", oid);
663 
664 	if (strcmp(oid, PBKDF2_OID) != 0) {
665 		gnutls_assert();
666 		_gnutls_debug_log
667 		    ("PKCS #8 key derivation OID '%s' is unsupported.\n", oid);
668 		return _gnutls_asn2err(result);
669 	}
670 
671 	result =
672 	    asn1_der_decoding_startEnd(pasn, der->data, der->size,
673 				       "keyDerivationFunc.parameters",
674 				       &params_start, &params_end);
675 	if (result != ASN1_SUCCESS) {
676 		gnutls_assert();
677 		return _gnutls_asn2err(result);
678 	}
679 	params_len = params_end - params_start + 1;
680 
681 	/* Now check the key derivation and the encryption
682 	 * functions.
683 	 */
684 	if ((result =
685 	     asn1_create_element(_gnutls_get_pkix(),
686 				 "PKIX1.pkcs-5-PBKDF2-params",
687 				 &pbkdf2_asn)) != ASN1_SUCCESS) {
688 		gnutls_assert();
689 		return _gnutls_asn2err(result);
690 	}
691 
692 	result =
693 	    _asn1_strict_der_decode(&pbkdf2_asn, &der->data[params_start],
694 				    params_len, NULL);
695 	if (result != ASN1_SUCCESS) {
696 		gnutls_assert();
697 		result = _gnutls_asn2err(result);
698 		goto error;
699 	}
700 
701 	/* read the salt */
702 	params->salt_size = sizeof(params->salt);
703 	result =
704 	    asn1_read_value(pbkdf2_asn, "salt.specified", params->salt,
705 			    &params->salt_size);
706 	if (result != ASN1_SUCCESS) {
707 		gnutls_assert();
708 		result = _gnutls_asn2err(result);
709 		goto error;
710 	}
711 	_gnutls_hard_log("salt.specified.size: %d\n", params->salt_size);
712 
713 	if (params->salt_size < 0) {
714 		result = gnutls_assert_val(GNUTLS_E_ILLEGAL_PARAMETER);
715 		goto error;
716 	}
717 
718 	/* read the iteration count
719 	 */
720 	result =
721 	    _gnutls_x509_read_uint(pbkdf2_asn, "iterationCount",
722 				   &params->iter_count);
723 	if (result < 0) {
724 		gnutls_assert();
725 		goto error;
726 	}
727 
728 	if (params->iter_count >= MAX_ITER_COUNT || params->iter_count == 0) {
729 		result = gnutls_assert_val(GNUTLS_E_ILLEGAL_PARAMETER);
730 		goto error;
731 	}
732 
733 	_gnutls_hard_log("iterationCount: %d\n", params->iter_count);
734 
735 	/* read the keylength, if it is set.
736 	 */
737 	result =
738 	    _gnutls_x509_read_uint(pbkdf2_asn, "keyLength", &params->key_size);
739 	if (result < 0) {
740 		params->key_size = 0;
741 	}
742 
743 	if (params->key_size > MAX_CIPHER_KEY_SIZE) {
744 		result = gnutls_assert_val(GNUTLS_E_ILLEGAL_PARAMETER);
745 		goto error;
746 	}
747 
748 	_gnutls_hard_log("keyLength: %d\n", params->key_size);
749 
750 	len = sizeof(oid);
751 	result = asn1_read_value(pbkdf2_asn, "prf.algorithm", oid, &len);
752 	if (result != ASN1_SUCCESS) {
753 		/* use the default MAC */
754 		result = 0;
755 		goto error;
756 	}
757 
758 	params->mac = gnutls_oid_to_mac(oid);
759 	if (params->mac == GNUTLS_MAC_UNKNOWN) {
760 		gnutls_assert();
761 		_gnutls_debug_log("Unsupported hash algorithm: %s\n", oid);
762 		result = GNUTLS_E_UNKNOWN_HASH_ALGORITHM;
763 		goto error;
764 	}
765 
766 	result = 0;
767 
768  error:
769 	asn1_delete_structure(&pbkdf2_asn);
770 	return result;
771 
772 }
773 
774 /* Reads the PBE parameters from PKCS-12 schemas (*&#%*&#% RSA).
775  */
read_pkcs12_kdf_params(ASN1_TYPE pasn,struct pbkdf2_params * params)776 static int read_pkcs12_kdf_params(ASN1_TYPE pasn, struct pbkdf2_params *params)
777 {
778 	int result;
779 
780 	memset(params, 0, sizeof(*params));
781 
782 	/* read the salt */
783 	params->salt_size = sizeof(params->salt);
784 	result =
785 	    asn1_read_value(pasn, "salt", params->salt, &params->salt_size);
786 	if (result != ASN1_SUCCESS) {
787 		gnutls_assert();
788 		return _gnutls_asn2err(result);
789 	}
790 
791 	if (params->salt_size < 0)
792 		return gnutls_assert_val(GNUTLS_E_ILLEGAL_PARAMETER);
793 
794 	_gnutls_hard_log("salt.size: %d\n", params->salt_size);
795 
796 	/* read the iteration count
797 	 */
798 	result =
799 	    _gnutls_x509_read_uint(pasn, "iterations", &params->iter_count);
800 	if (result < 0)
801 		return gnutls_assert_val(result);
802 
803 	if (params->iter_count >= MAX_ITER_COUNT || params->iter_count == 0)
804 		return gnutls_assert_val(GNUTLS_E_ILLEGAL_PARAMETER);
805 
806 	_gnutls_hard_log("iterationCount: %d\n", params->iter_count);
807 
808 	params->key_size = 0;
809 
810 	return 0;
811 }
812 
813 /* Writes the PBE parameters for PKCS-12 schemas.
814  */
815 static int
write_pkcs12_kdf_params(ASN1_TYPE pasn,const struct pbkdf2_params * kdf_params)816 write_pkcs12_kdf_params(ASN1_TYPE pasn, const struct pbkdf2_params *kdf_params)
817 {
818 	int result;
819 
820 	/* write the salt
821 	 */
822 	result =
823 	    asn1_write_value(pasn, "salt",
824 			     kdf_params->salt, kdf_params->salt_size);
825 	if (result != ASN1_SUCCESS) {
826 		gnutls_assert();
827 		result = _gnutls_asn2err(result);
828 		goto error;
829 	}
830 	_gnutls_hard_log("salt.size: %d\n", kdf_params->salt_size);
831 
832 	/* write the iteration count
833 	 */
834 	result =
835 	    _gnutls_x509_write_uint32(pasn, "iterations",
836 				      kdf_params->iter_count);
837 	if (result < 0) {
838 		gnutls_assert();
839 		goto error;
840 	}
841 	_gnutls_hard_log("iterationCount: %d\n", kdf_params->iter_count);
842 
843 	return 0;
844 
845  error:
846 	return result;
847 
848 }
849 
850 static int
read_pbes2_gost_oid(uint8_t * der,size_t len,char * oid,int oid_size)851 read_pbes2_gost_oid(uint8_t *der, size_t len, char *oid, int oid_size)
852 {
853 	int result;
854 	ASN1_TYPE pbe_asn = ASN1_TYPE_EMPTY;
855 
856 	if ((result =
857 	     asn1_create_element(_gnutls_get_pkix(),
858 				 "PKIX1.Gost28147-89-Parameters", &pbe_asn)) != ASN1_SUCCESS) {
859 		gnutls_assert();
860 		return _gnutls_asn2err(result);
861 	}
862 
863 	result =
864 	    _asn1_strict_der_decode(&pbe_asn, der, len, NULL);
865 	if (result != ASN1_SUCCESS) {
866 		gnutls_assert();
867 		result = _gnutls_asn2err(result);
868 		goto error;
869 	}
870 
871 	result = asn1_read_value(pbe_asn, "encryptionParamSet",
872 				 oid, &oid_size);
873 	if (result != ASN1_SUCCESS) {
874 		gnutls_assert();
875 		result = _gnutls_asn2err(result);
876 		goto error;
877 	}
878 
879 	result = 0;
880 
881  error:
882 	asn1_delete_structure(&pbe_asn);
883 	return result;
884 }
885 
886 static int
read_pbes2_enc_params(ASN1_TYPE pasn,const gnutls_datum_t * der,struct pbe_enc_params * params)887 read_pbes2_enc_params(ASN1_TYPE pasn,
888 		      const gnutls_datum_t * der, struct pbe_enc_params *params)
889 {
890 	int params_start, params_end;
891 	int params_len, len, result;
892 	ASN1_TYPE pbe_asn = ASN1_TYPE_EMPTY;
893 	const struct pkcs_cipher_schema_st *p;
894 
895 	memset(params, 0, sizeof(*params));
896 
897 	/* Check the encryption algorithm
898 	 */
899 	len = sizeof(params->pbes2_oid);
900 	result = asn1_read_value(pasn, "encryptionScheme.algorithm", params->pbes2_oid, &len);
901 	if (result != ASN1_SUCCESS) {
902 		gnutls_assert();
903 		return _gnutls_asn2err(result);
904 	}
905 	_gnutls_hard_log("encryptionScheme.algorithm: %s\n", params->pbes2_oid);
906 
907 	result =
908 	    asn1_der_decoding_startEnd(pasn, der->data, der->size,
909 				       "encryptionScheme.parameters",
910 				       &params_start, &params_end);
911 	if (result != ASN1_SUCCESS) {
912 		gnutls_assert();
913 		return _gnutls_asn2err(result);
914 	}
915 	params_len = params_end - params_start + 1;
916 
917 	/* For GOST we have to read params to determine actual cipher */
918 	if (!strcmp(params->pbes2_oid, GOST28147_89_OID)) {
919 		len = sizeof(params->pbes2_oid);
920 		result = read_pbes2_gost_oid(&der->data[params_start],
921 					     params_len, params->pbes2_oid, len);
922 		if (result < 0) {
923 			gnutls_assert();
924 			return result;
925 		}
926 	}
927 
928 	if ((result = pbes2_cipher_oid_to_algo(params->pbes2_oid, &params->cipher)) < 0) {
929 		gnutls_assert();
930 		return result;
931 	}
932 
933 	/* Now check the encryption parameters.
934 	 */
935 	p = algo_to_pbes2_cipher_schema(params->cipher);
936 	if (p == NULL) {
937 		gnutls_assert();
938 		return GNUTLS_E_INVALID_REQUEST;
939 	}
940 
941 	if ((result =
942 	     asn1_create_element(_gnutls_get_pkix(),
943 				 p->desc, &pbe_asn)) != ASN1_SUCCESS) {
944 		gnutls_assert();
945 		return _gnutls_asn2err(result);
946 	}
947 
948 	result =
949 	    _asn1_strict_der_decode(&pbe_asn, &der->data[params_start],
950 				    params_len, NULL);
951 	if (result != ASN1_SUCCESS) {
952 		gnutls_assert();
953 		result = _gnutls_asn2err(result);
954 		goto error;
955 	}
956 
957 	/* read the IV */
958 	params->iv_size = sizeof(params->iv);
959 	result = asn1_read_value(pbe_asn,
960 			p->iv_name,
961 			params->iv, &params->iv_size);
962 	if (result != ASN1_SUCCESS) {
963 		gnutls_assert();
964 		result = _gnutls_asn2err(result);
965 		goto error;
966 	}
967 	_gnutls_hard_log("IV.size: %d\n", params->iv_size);
968 
969 	result = 0;
970 
971  error:
972 	asn1_delete_structure(&pbe_asn);
973 	return result;
974 }
975 
976 /* Read the parameters cipher, IV, salt etc using the given
977  * schema ID. Initially the schema ID should have PBES2_GENERIC, for
978  * PBES2 schemas, and will be updated by this function for details.
979  */
980 int
_gnutls_read_pkcs_schema_params(schema_id * schema,const char * password,const uint8_t * data,int data_size,struct pbkdf2_params * kdf_params,struct pbe_enc_params * enc_params)981 _gnutls_read_pkcs_schema_params(schema_id * schema, const char *password,
982 				const uint8_t * data, int data_size,
983 				struct pbkdf2_params *kdf_params,
984 				struct pbe_enc_params *enc_params)
985 {
986 	ASN1_TYPE pasn = ASN1_TYPE_EMPTY;
987 	int result;
988 	gnutls_datum_t tmp;
989 	const struct pkcs_cipher_schema_st *p;
990 
991 	if (*schema == PBES2_GENERIC) {
992 		/* Now check the key derivation and the encryption
993 		 * functions.
994 		 */
995 		if ((result =
996 		     asn1_create_element(_gnutls_get_pkix(),
997 					 "PKIX1.pkcs-5-PBES2-params",
998 					 &pasn)) != ASN1_SUCCESS) {
999 			gnutls_assert();
1000 			result = _gnutls_asn2err(result);
1001 			goto error;
1002 		}
1003 
1004 		/* Decode the parameters.
1005 		 */
1006 		result = _asn1_strict_der_decode(&pasn, data, data_size, NULL);
1007 		if (result != ASN1_SUCCESS) {
1008 			gnutls_assert();
1009 			result = _gnutls_asn2err(result);
1010 			goto error;
1011 		}
1012 
1013 		tmp.data = (uint8_t *) data;
1014 		tmp.size = data_size;
1015 
1016 		result = read_pbkdf2_params(pasn, &tmp, kdf_params);
1017 		if (result < 0) {
1018 			gnutls_assert();
1019 			goto error;
1020 		}
1021 
1022 		result = read_pbes2_enc_params(pasn, &tmp, enc_params);
1023 		if (result < 0) {
1024 			gnutls_assert();
1025 			goto error;
1026 		}
1027 
1028 		asn1_delete_structure2(&pasn, ASN1_DELETE_FLAG_ZEROIZE);
1029 
1030 		p = algo_to_pbes2_cipher_schema(enc_params->cipher);
1031 		if (p == NULL) {
1032 			result = GNUTLS_E_INVALID_REQUEST;
1033 			gnutls_assert();
1034 			goto error;
1035 		}
1036 
1037 		*schema = p->schema;
1038 		return 0;
1039 	} else if (*schema == PBES1_DES_MD5) {
1040 		return _gnutls_read_pbkdf1_params(data, data_size, kdf_params,
1041 						  enc_params);
1042 	} else {		/* PKCS #12 schema */
1043 		memset(enc_params, 0, sizeof(*enc_params));
1044 
1045 		p = _gnutls_pkcs_schema_get(*schema);
1046 		if (p == NULL) {
1047 			gnutls_assert();
1048 			result = GNUTLS_E_UNKNOWN_CIPHER_TYPE;
1049 			goto error;
1050 		}
1051 		enc_params->cipher = p->cipher;
1052 		enc_params->iv_size = gnutls_cipher_get_iv_size(p->cipher);
1053 
1054 		if ((result =
1055 		     asn1_create_element(_gnutls_get_pkix(),
1056 					 "PKIX1.pkcs-12-PbeParams",
1057 					 &pasn)) != ASN1_SUCCESS) {
1058 			gnutls_assert();
1059 			result = _gnutls_asn2err(result);
1060 			goto error;
1061 		}
1062 
1063 		/* Decode the parameters.
1064 		 */
1065 		result = _asn1_strict_der_decode(&pasn, data, data_size, NULL);
1066 		if (result != ASN1_SUCCESS) {
1067 			gnutls_assert();
1068 			result = _gnutls_asn2err(result);
1069 			goto error;
1070 		}
1071 
1072 		result = read_pkcs12_kdf_params(pasn, kdf_params);
1073 		if (result < 0) {
1074 			gnutls_assert();
1075 			goto error;
1076 		}
1077 
1078 		if (enc_params->iv_size) {
1079 			result =
1080 			    _gnutls_pkcs12_string_to_key(mac_to_entry
1081 							 (GNUTLS_MAC_SHA1),
1082 							 2 /*IV*/,
1083 							 kdf_params->salt,
1084 							 kdf_params->salt_size,
1085 							 kdf_params->iter_count,
1086 							 password,
1087 							 enc_params->iv_size,
1088 							 enc_params->iv);
1089 			if (result < 0) {
1090 				gnutls_assert();
1091 				goto error;
1092 			}
1093 
1094 		}
1095 
1096 		asn1_delete_structure(&pasn);
1097 
1098 		return 0;
1099 	}			/* switch */
1100 
1101  error:
1102 	asn1_delete_structure(&pasn);
1103 	return result;
1104 }
1105 
1106 static int
_gnutls_pbes2_string_to_key(unsigned int pass_len,const char * password,const struct pbkdf2_params * kdf_params,int key_size,uint8_t * key)1107 _gnutls_pbes2_string_to_key(unsigned int pass_len, const char *password,
1108 			    const struct pbkdf2_params *kdf_params,
1109 			    int key_size, uint8_t *key)
1110 {
1111 	gnutls_datum_t _key;
1112 	gnutls_datum_t salt;
1113 
1114 	_key.data = (void *)password;
1115 	_key.size = pass_len;
1116 	salt.data = (void *)kdf_params->salt;
1117 	salt.size = kdf_params->salt_size;
1118 
1119 	return gnutls_pbkdf2(kdf_params->mac, &_key, &salt,
1120 			     kdf_params->iter_count, key, key_size);
1121 }
1122 
1123 int
_gnutls_pkcs_raw_decrypt_data(schema_id schema,ASN1_TYPE pkcs8_asn,const char * root,const char * _password,const struct pbkdf2_params * kdf_params,const struct pbe_enc_params * enc_params,gnutls_datum_t * decrypted_data)1124 _gnutls_pkcs_raw_decrypt_data(schema_id schema, ASN1_TYPE pkcs8_asn,
1125 			      const char *root, const char *_password,
1126 			      const struct pbkdf2_params *kdf_params,
1127 			      const struct pbe_enc_params *enc_params,
1128 			      gnutls_datum_t * decrypted_data)
1129 {
1130 	gnutls_datum_t enc = { NULL, 0 };
1131 	uint8_t *key = NULL;
1132 	gnutls_datum_t dkey, d_iv;
1133 	cipher_hd_st ch;
1134 	int ch_init = 0;
1135 	int key_size, ret;
1136 	unsigned int pass_len = 0;
1137 	const struct pkcs_cipher_schema_st *p;
1138 	unsigned block_size;
1139 	const cipher_entry_st *ce;
1140 	char *password;
1141 
1142 	if (_password) {
1143 		gnutls_datum_t pout;
1144 		ret = _gnutls_utf8_password_normalize(_password, strlen(_password), &pout, 1);
1145 		if (ret < 0)
1146 			return gnutls_assert_val(ret);
1147 
1148 		password = (char*)pout.data;
1149 		pass_len = pout.size;
1150 	} else {
1151 		password = NULL;
1152 		pass_len = 0;
1153 	}
1154 
1155 	ret = _gnutls_x509_read_value(pkcs8_asn, root, &enc);
1156 	if (ret < 0) {
1157 		gnutls_assert();
1158 		enc.data = NULL;
1159 		goto cleanup;
1160 	}
1161 
1162 	if (schema == PBES1_DES_MD5) {
1163 		ret = _gnutls_decrypt_pbes1_des_md5_data(password, pass_len,
1164 							  kdf_params,
1165 							  enc_params, &enc,
1166 							  decrypted_data);
1167 		if (ret < 0)
1168 			goto error;
1169 		goto cleanup;
1170 	}
1171 
1172 	if (kdf_params->key_size == 0) {
1173 		key_size = gnutls_cipher_get_key_size(enc_params->cipher);
1174 	} else
1175 		key_size = kdf_params->key_size;
1176 
1177 	key = gnutls_malloc(key_size);
1178 	if (key == NULL) {
1179 		gnutls_assert();
1180 		ret = GNUTLS_E_MEMORY_ERROR;
1181 		goto error;
1182 	}
1183 
1184 	/* generate the key
1185 	 */
1186 	p = _gnutls_pkcs_schema_get(schema);
1187 	if (p != NULL && p->pbes2 != 0) {	/* PBES2 */
1188 		ret = _gnutls_pbes2_string_to_key(pass_len, password,
1189 						     kdf_params,
1190 						     key_size, key);
1191 		if (ret < 0) {
1192 			gnutls_assert();
1193 			goto error;
1194 		}
1195 	} else if (p != NULL) {	/* PKCS 12 schema */
1196 		ret =
1197 		    _gnutls_pkcs12_string_to_key(mac_to_entry(GNUTLS_MAC_SHA1),
1198 						 1 /*KEY*/,
1199 						 kdf_params->salt,
1200 						 kdf_params->salt_size,
1201 						 kdf_params->iter_count,
1202 						 password, key_size, key);
1203 
1204 		if (ret < 0) {
1205 			gnutls_assert();
1206 			goto error;
1207 		}
1208 	} else {
1209 		gnutls_assert();
1210 		ret = GNUTLS_E_UNKNOWN_CIPHER_TYPE;
1211 		goto error;
1212 	}
1213 
1214 	ce = cipher_to_entry(enc_params->cipher);
1215 	block_size = _gnutls_cipher_get_block_size(ce);
1216 
1217 	if (ce->type == CIPHER_BLOCK) {
1218 		if (enc.size % block_size != 0 || (unsigned)enc_params->iv_size != block_size) {
1219 			gnutls_assert();
1220 			ret = GNUTLS_E_DECRYPTION_FAILED;
1221 			goto error;
1222 		}
1223 	} else {
1224 		unsigned iv_size = _gnutls_cipher_get_iv_size(ce);
1225 		if (iv_size > (unsigned)enc_params->iv_size) {
1226 			gnutls_assert();
1227 			ret = GNUTLS_E_DECRYPTION_FAILED;
1228 			goto error;
1229 		}
1230 	}
1231 
1232 	/* do the decryption.
1233 	 */
1234 	dkey.data = key;
1235 	dkey.size = key_size;
1236 
1237 	d_iv.data = (uint8_t *) enc_params->iv;
1238 	d_iv.size = enc_params->iv_size;
1239 
1240 	ret =
1241 	    _gnutls_cipher_init(&ch, ce, &dkey, &d_iv, 0);
1242 
1243 	gnutls_free(key);
1244 
1245 	if (ret < 0) {
1246 		gnutls_assert();
1247 		goto error;
1248 	}
1249 
1250 	ch_init = 1;
1251 
1252 	ret = _gnutls_cipher_decrypt(&ch, enc.data, enc.size);
1253 	if (ret < 0) {
1254 		gnutls_assert();
1255 		ret = GNUTLS_E_DECRYPTION_FAILED;
1256 		goto error;
1257 	}
1258 
1259 	decrypted_data->data = enc.data;
1260 
1261 	if (ce->type == CIPHER_BLOCK && block_size != 1) {
1262 		unsigned pslen = (uint8_t)enc.data[enc.size - 1];
1263 		unsigned i;
1264 
1265 		if (pslen > block_size || pslen >= enc.size  || pslen == 0) {
1266 			gnutls_assert();
1267 			ret = GNUTLS_E_DECRYPTION_FAILED;
1268 			goto error;
1269 		}
1270 
1271 		/* verify padding according to rfc2898 */
1272 		decrypted_data->size = enc.size - pslen;
1273 		for (i=0;i<pslen;i++) {
1274 			if (enc.data[enc.size-1-i] != pslen) {
1275 				gnutls_assert();
1276 				ret = GNUTLS_E_DECRYPTION_FAILED;
1277 				goto error;
1278 			}
1279 		}
1280 	} else {
1281 		decrypted_data->size = enc.size;
1282 	}
1283 
1284 	_gnutls_cipher_deinit(&ch);
1285 
1286 	ret = 0;
1287 
1288  cleanup:
1289 	gnutls_free(password);
1290 
1291 	return ret;
1292 
1293  error:
1294 	gnutls_free(password);
1295 	gnutls_free(enc.data);
1296 	gnutls_free(key);
1297 	if (ch_init != 0)
1298 		_gnutls_cipher_deinit(&ch);
1299 	return ret;
1300 }
1301 
1302 /* Writes the PBKDF2 parameters.
1303  */
1304 static int
write_pbkdf2_params(ASN1_TYPE pasn,const struct pbkdf2_params * kdf_params)1305 write_pbkdf2_params(ASN1_TYPE pasn, const struct pbkdf2_params *kdf_params)
1306 {
1307 	int result;
1308 	ASN1_TYPE pbkdf2_asn = ASN1_TYPE_EMPTY;
1309 	uint8_t tmp[MAX_OID_SIZE];
1310 	const mac_entry_st *me;
1311 
1312 	/* Write the key derivation algorithm
1313 	 */
1314 	result =
1315 	    asn1_write_value(pasn, "keyDerivationFunc.algorithm",
1316 			     PBKDF2_OID, 1);
1317 	if (result != ASN1_SUCCESS) {
1318 		gnutls_assert();
1319 		return _gnutls_asn2err(result);
1320 	}
1321 
1322 	/* Now write the key derivation and the encryption
1323 	 * functions.
1324 	 */
1325 	if ((result =
1326 	     asn1_create_element(_gnutls_get_pkix(),
1327 				 "PKIX1.pkcs-5-PBKDF2-params",
1328 				 &pbkdf2_asn)) != ASN1_SUCCESS) {
1329 		gnutls_assert();
1330 		return _gnutls_asn2err(result);
1331 	}
1332 
1333 	result = asn1_write_value(pbkdf2_asn, "salt", "specified", 1);
1334 	if (result != ASN1_SUCCESS) {
1335 		gnutls_assert();
1336 		result = _gnutls_asn2err(result);
1337 		goto error;
1338 	}
1339 
1340 	/* write the salt
1341 	 */
1342 	result =
1343 	    asn1_write_value(pbkdf2_asn, "salt.specified",
1344 			     kdf_params->salt, kdf_params->salt_size);
1345 	if (result != ASN1_SUCCESS) {
1346 		gnutls_assert();
1347 		result = _gnutls_asn2err(result);
1348 		goto error;
1349 	}
1350 	_gnutls_hard_log("salt.specified.size: %d\n", kdf_params->salt_size);
1351 
1352 	/* write the iteration count
1353 	 */
1354 	_gnutls_write_uint32(kdf_params->iter_count, tmp);
1355 
1356 	result = asn1_write_value(pbkdf2_asn, "iterationCount", tmp, 4);
1357 	if (result != ASN1_SUCCESS) {
1358 		gnutls_assert();
1359 		result = _gnutls_asn2err(result);
1360 		goto error;
1361 	}
1362 	_gnutls_hard_log("iterationCount: %d\n", kdf_params->iter_count);
1363 
1364 	/* write the keylength, if it is set.
1365 	 */
1366 	result = asn1_write_value(pbkdf2_asn, "keyLength", NULL, 0);
1367 	if (result != ASN1_SUCCESS) {
1368 		gnutls_assert();
1369 		result = _gnutls_asn2err(result);
1370 		goto error;
1371 	}
1372 
1373 	me = _gnutls_mac_to_entry(kdf_params->mac);
1374 	if (!me || !me->mac_oid) {
1375 		gnutls_assert();
1376 		result = GNUTLS_E_INTERNAL_ERROR;
1377 		goto error;
1378 	}
1379 
1380 	result = asn1_write_value(pbkdf2_asn, "prf.algorithm",
1381 				  me->mac_oid, strlen(me->mac_oid));
1382 	if (result != ASN1_SUCCESS) {
1383 		gnutls_assert();
1384 		result = _gnutls_asn2err(result);
1385 		goto error;
1386 	}
1387 
1388 	result = asn1_write_value(pbkdf2_asn, "prf.parameters", NULL, 0);
1389 	if (result != ASN1_SUCCESS) {
1390 		gnutls_assert();
1391 		result = _gnutls_asn2err(result);
1392 		goto error;
1393 	}
1394 
1395 	/* now encode them an put the DER output
1396 	 * in the keyDerivationFunc.parameters
1397 	 */
1398 	result = _gnutls_x509_der_encode_and_copy(pbkdf2_asn, "",
1399 						  pasn,
1400 						  "keyDerivationFunc.parameters",
1401 						  0);
1402 	if (result < 0) {
1403 		gnutls_assert();
1404 		goto error;
1405 	}
1406 
1407 	result = 0;
1408 
1409  error:
1410 	asn1_delete_structure(&pbkdf2_asn);
1411 	return result;
1412 
1413 }
1414 
1415 static int
write_pbes2_enc_params(ASN1_TYPE pasn,const struct pbe_enc_params * params)1416 write_pbes2_enc_params(ASN1_TYPE pasn, const struct pbe_enc_params *params)
1417 {
1418 	int result;
1419 	ASN1_TYPE pbe_asn = ASN1_TYPE_EMPTY;
1420 	const struct pkcs_cipher_schema_st *p;
1421 	const char *cipher_oid;
1422 
1423 	/* Write the encryption algorithm
1424 	 */
1425 	p = algo_to_pbes2_cipher_schema(params->cipher);
1426 	if (p == NULL || p->pbes2 == 0) {
1427 		gnutls_assert();
1428 		return GNUTLS_E_INVALID_REQUEST;
1429 	}
1430 
1431 	/* Now check the encryption parameters.
1432 	 */
1433 	if ((result =
1434 	     asn1_create_element(_gnutls_get_pkix(),
1435 				 p->desc, &pbe_asn)) != ASN1_SUCCESS) {
1436 		gnutls_assert();
1437 		return _gnutls_asn2err(result);
1438 	}
1439 
1440 	if (p->schema == PBES2_GOST28147_89_TC26Z ||
1441 	    p->schema == PBES2_GOST28147_89_CPA ||
1442 	    p->schema == PBES2_GOST28147_89_CPB ||
1443 	    p->schema == PBES2_GOST28147_89_CPC ||
1444 	    p->schema == PBES2_GOST28147_89_CPD) {
1445 		cipher_oid = GOST28147_89_OID;
1446 		result = asn1_write_value(pbe_asn, "encryptionParamSet",
1447 					  p->cipher_oid, 1);
1448 		if (result != ASN1_SUCCESS) {
1449 			gnutls_assert();
1450 			result = _gnutls_asn2err(result);
1451 			goto error;
1452 		}
1453 	} else {
1454 		cipher_oid = p->cipher_oid;
1455 	}
1456 
1457 	result =
1458 	    asn1_write_value(pasn, "encryptionScheme.algorithm",
1459 			     cipher_oid,
1460 			     1);
1461 	if (result != ASN1_SUCCESS) {
1462 		gnutls_assert();
1463 		goto error;
1464 	}
1465 	_gnutls_hard_log("encryptionScheme.algorithm: %s\n", cipher_oid);
1466 
1467 	/* read the salt */
1468 	result = asn1_write_value(pbe_asn, p->iv_name,
1469 				  params->iv, params->iv_size);
1470 	if (result != ASN1_SUCCESS) {
1471 		gnutls_assert();
1472 		result = _gnutls_asn2err(result);
1473 		goto error;
1474 	}
1475 	_gnutls_hard_log("IV.size: %d\n", params->iv_size);
1476 
1477 	/* now encode them an put the DER output
1478 	 * in the encryptionScheme.parameters
1479 	 */
1480 	result = _gnutls_x509_der_encode_and_copy(pbe_asn, "",
1481 						  pasn,
1482 						  "encryptionScheme.parameters",
1483 						  0);
1484 	if (result < 0) {
1485 		gnutls_assert();
1486 		goto error;
1487 	}
1488 
1489 	result = 0;
1490 
1491  error:
1492 	asn1_delete_structure(&pbe_asn);
1493 	return result;
1494 
1495 }
1496 
1497 /* Generates a key and also stores the key parameters.
1498  */
1499 int
_gnutls_pkcs_generate_key(schema_id schema,const char * _password,struct pbkdf2_params * kdf_params,struct pbe_enc_params * enc_params,gnutls_datum_t * key)1500 _gnutls_pkcs_generate_key(schema_id schema,
1501 			  const char *_password,
1502 			  struct pbkdf2_params *kdf_params,
1503 			  struct pbe_enc_params *enc_params,
1504 			  gnutls_datum_t * key)
1505 {
1506 	unsigned char rnd[2];
1507 	unsigned int pass_len = 0;
1508 	int ret;
1509 	const struct pkcs_cipher_schema_st *p;
1510 	char *password = NULL;
1511 
1512 	if (_password) {
1513 		gnutls_datum_t pout;
1514 		ret = _gnutls_utf8_password_normalize(_password, strlen(_password), &pout, 0);
1515 		if (ret < 0)
1516 			return gnutls_assert_val(ret);
1517 
1518 		password = (char*)pout.data;
1519 		pass_len = pout.size;
1520 	} else {
1521 		password = NULL;
1522 		pass_len = 0;
1523 	}
1524 
1525 	ret = gnutls_rnd(GNUTLS_RND_RANDOM, rnd, 2);
1526 	if (ret < 0) {
1527 		gnutls_assert();
1528 		goto cleanup;
1529 	}
1530 
1531 	/* generate salt */
1532 	kdf_params->salt_size =
1533 	    MIN(sizeof(kdf_params->salt), (unsigned)(12 + (rnd[1] % 10)));
1534 
1535 	p = _gnutls_pkcs_schema_get(schema);
1536 	if (p != NULL && p->pbes2 != 0) {	/* PBES2 */
1537 		enc_params->cipher = p->cipher;
1538 	} else if (p != NULL) {
1539 		/* non PBES2 algorithms */
1540 		enc_params->cipher = p->cipher;
1541 		kdf_params->salt_size = 8;
1542 	} else {
1543 		gnutls_assert();
1544 		ret = GNUTLS_E_INVALID_REQUEST;
1545 		goto cleanup;
1546 	}
1547 
1548 	ret = gnutls_rnd(GNUTLS_RND_RANDOM, kdf_params->salt,
1549 			  kdf_params->salt_size);
1550 	if (ret < 0) {
1551 		gnutls_assert();
1552 		goto cleanup;
1553 	}
1554 
1555 	kdf_params->iter_count = 5 * 1024 + rnd[0];
1556 	key->size = kdf_params->key_size =
1557 	    gnutls_cipher_get_key_size(enc_params->cipher);
1558 
1559 	enc_params->iv_size = gnutls_cipher_get_iv_size(enc_params->cipher);
1560 	key->data = gnutls_malloc(key->size);
1561 	if (key->data == NULL) {
1562 		gnutls_assert();
1563 		ret = GNUTLS_E_MEMORY_ERROR;
1564 		goto cleanup;
1565 	}
1566 
1567 	/* now generate the key.
1568 	 */
1569 
1570 	if (p->pbes2 != 0) {
1571 		if (p->schema == PBES2_GOST28147_89_TC26Z)
1572 			kdf_params->mac = GNUTLS_MAC_STREEBOG_256;
1573 		else if (p->schema == PBES2_GOST28147_89_CPA ||
1574 			 p->schema == PBES2_GOST28147_89_CPB ||
1575 			 p->schema == PBES2_GOST28147_89_CPC ||
1576 			 p->schema == PBES2_GOST28147_89_CPD)
1577 			kdf_params->mac = GNUTLS_MAC_GOSTR_94;
1578 		else
1579 			kdf_params->mac = GNUTLS_MAC_SHA1;
1580 		ret = _gnutls_pbes2_string_to_key(pass_len, password,
1581 						  kdf_params,
1582 						  kdf_params->key_size,
1583 						  key->data);
1584 		if (ret < 0) {
1585 			gnutls_assert();
1586 			return ret;
1587 		}
1588 
1589 		if (enc_params->iv_size) {
1590 			ret = gnutls_rnd(GNUTLS_RND_NONCE,
1591 					  enc_params->iv, enc_params->iv_size);
1592 			if (ret < 0) {
1593 				gnutls_assert();
1594 				goto cleanup;
1595 			}
1596 		}
1597 	} else {		/* PKCS 12 schema */
1598 		ret =
1599 		    _gnutls_pkcs12_string_to_key(mac_to_entry(GNUTLS_MAC_SHA1),
1600 						 1 /*KEY*/,
1601 						 kdf_params->salt,
1602 						 kdf_params->salt_size,
1603 						 kdf_params->iter_count,
1604 						 password,
1605 						 kdf_params->key_size,
1606 						 key->data);
1607 		if (ret < 0) {
1608 			gnutls_assert();
1609 			goto cleanup;
1610 		}
1611 
1612 		/* Now generate the IV
1613 		 */
1614 		if (enc_params->iv_size) {
1615 			ret =
1616 			    _gnutls_pkcs12_string_to_key(mac_to_entry
1617 							 (GNUTLS_MAC_SHA1),
1618 							 2 /*IV*/,
1619 							 kdf_params->salt,
1620 							 kdf_params->salt_size,
1621 							 kdf_params->iter_count,
1622 							 password,
1623 							 enc_params->iv_size,
1624 							 enc_params->iv);
1625 			if (ret < 0) {
1626 				gnutls_assert();
1627 				goto cleanup;
1628 			}
1629 		}
1630 	}
1631 
1632 	ret = 0;
1633 
1634  cleanup:
1635 	gnutls_free(password);
1636 	return ret;
1637 }
1638 
1639 /* Encodes the parameters to be written in the encryptionAlgorithm.parameters
1640  * part.
1641  */
1642 int
_gnutls_pkcs_write_schema_params(schema_id schema,ASN1_TYPE pkcs8_asn,const char * where,const struct pbkdf2_params * kdf_params,const struct pbe_enc_params * enc_params)1643 _gnutls_pkcs_write_schema_params(schema_id schema, ASN1_TYPE pkcs8_asn,
1644 				 const char *where,
1645 				 const struct pbkdf2_params *kdf_params,
1646 				 const struct pbe_enc_params *enc_params)
1647 {
1648 	int result;
1649 	ASN1_TYPE pasn = ASN1_TYPE_EMPTY;
1650 	const struct pkcs_cipher_schema_st *p;
1651 
1652 	p = _gnutls_pkcs_schema_get(schema);
1653 
1654 	if (p != NULL && p->pbes2 != 0) {	/* PBES2 */
1655 		if ((result =
1656 		     asn1_create_element(_gnutls_get_pkix(),
1657 					 "PKIX1.pkcs-5-PBES2-params",
1658 					 &pasn)) != ASN1_SUCCESS) {
1659 			gnutls_assert();
1660 			return _gnutls_asn2err(result);
1661 		}
1662 
1663 		result = write_pbkdf2_params(pasn, kdf_params);
1664 		if (result < 0) {
1665 			gnutls_assert();
1666 			goto error;
1667 		}
1668 
1669 		result = write_pbes2_enc_params(pasn, enc_params);
1670 		if (result < 0) {
1671 			gnutls_assert();
1672 			goto error;
1673 		}
1674 
1675 		result = _gnutls_x509_der_encode_and_copy(pasn, "",
1676 							  pkcs8_asn, where, 0);
1677 		if (result < 0) {
1678 			gnutls_assert();
1679 			goto error;
1680 		}
1681 
1682 		asn1_delete_structure(&pasn);
1683 
1684 	} else if (p != NULL) {	/* PKCS #12 */
1685 
1686 		if ((result =
1687 		     asn1_create_element(_gnutls_get_pkix(),
1688 					 "PKIX1.pkcs-12-PbeParams",
1689 					 &pasn)) != ASN1_SUCCESS) {
1690 			gnutls_assert();
1691 			result = _gnutls_asn2err(result);
1692 			goto error;
1693 		}
1694 
1695 		result = write_pkcs12_kdf_params(pasn, kdf_params);
1696 		if (result < 0) {
1697 			gnutls_assert();
1698 			goto error;
1699 		}
1700 
1701 		result = _gnutls_x509_der_encode_and_copy(pasn, "",
1702 							  pkcs8_asn, where, 0);
1703 		if (result < 0) {
1704 			gnutls_assert();
1705 			goto error;
1706 		}
1707 
1708 		asn1_delete_structure(&pasn);
1709 	}
1710 
1711 	return 0;
1712 
1713  error:
1714 	asn1_delete_structure(&pasn);
1715 	return result;
1716 
1717 }
1718 
1719 int
_gnutls_pkcs_raw_encrypt_data(const gnutls_datum_t * plain,const struct pbe_enc_params * enc_params,const gnutls_datum_t * key,gnutls_datum_t * encrypted)1720 _gnutls_pkcs_raw_encrypt_data(const gnutls_datum_t * plain,
1721 			      const struct pbe_enc_params *enc_params,
1722 			      const gnutls_datum_t * key, gnutls_datum_t * encrypted)
1723 {
1724 	int result;
1725 	int data_size;
1726 	uint8_t *data = NULL;
1727 	gnutls_datum_t d_iv;
1728 	cipher_hd_st ch;
1729 	int ch_init = 0;
1730 	uint8_t pad, pad_size;
1731 	const cipher_entry_st *ce;
1732 
1733 	ce = cipher_to_entry(enc_params->cipher);
1734 	pad_size = _gnutls_cipher_get_block_size(ce);
1735 
1736 	if (pad_size == 1 || ce->type == CIPHER_STREAM)	/* stream */
1737 		pad_size = 0;
1738 
1739 	data = gnutls_malloc(plain->size + pad_size);
1740 	if (data == NULL) {
1741 		gnutls_assert();
1742 		return GNUTLS_E_MEMORY_ERROR;
1743 	}
1744 
1745 	memcpy(data, plain->data, plain->size);
1746 
1747 	if (pad_size > 0) {
1748 		pad = pad_size - (plain->size % pad_size);
1749 		if (pad == 0)
1750 			pad = pad_size;
1751 		memset(&data[plain->size], pad, pad);
1752 	} else
1753 		pad = 0;
1754 
1755 	data_size = plain->size + pad;
1756 
1757 	d_iv.data = (uint8_t *) enc_params->iv;
1758 	d_iv.size = enc_params->iv_size;
1759 	result =
1760 	    _gnutls_cipher_init(&ch, cipher_to_entry(enc_params->cipher),
1761 				key, &d_iv, 1);
1762 
1763 	if (result < 0) {
1764 		gnutls_assert();
1765 		goto error;
1766 	}
1767 
1768 	ch_init = 1;
1769 
1770 	result = _gnutls_cipher_encrypt(&ch, data, data_size);
1771 	if (result < 0) {
1772 		gnutls_assert();
1773 		goto error;
1774 	}
1775 
1776 	encrypted->data = data;
1777 	encrypted->size = data_size;
1778 
1779 	_gnutls_cipher_deinit(&ch);
1780 
1781 	return 0;
1782 
1783  error:
1784 	gnutls_free(data);
1785 	if (ch_init != 0)
1786 		_gnutls_cipher_deinit(&ch);
1787 	return result;
1788 }
1789