xref: /netbsd-src/crypto/external/bsd/heimdal/dist/lib/hx509/crypto.c (revision afab4e300d3a9fb07dd8c80daf53d0feb3345706)
1 /*	$NetBSD: crypto.c,v 1.4 2023/06/19 21:41:44 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2004 - 2016 Kungliga Tekniska Högskolan
5  * (Royal Institute of Technology, Stockholm, Sweden).
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * 3. Neither the name of the Institute nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include "hx_locl.h"
37 
38 /*-
39  * RFC5758 specifies no parameters for ecdsa-with-SHA<N> signatures
40  * RFC5754 specifies NULL parameters for sha<N>WithRSAEncryption signatures
41  *
42  * XXX: Make sure that the parameters are either NULL in both the tbs and the
43  * signature, or absent from both the tbs and the signature.
44  */
45 
46 static const heim_octet_string null_entry_oid = { 2, rk_UNCONST("\x05\x00") };
47 
48 static const unsigned sha512_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 3 };
49 const AlgorithmIdentifier _hx509_signature_sha512_data = {
50     { 9, rk_UNCONST(sha512_oid_tree) }, rk_UNCONST(&null_entry_oid)
51 };
52 
53 static const unsigned sha384_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 2 };
54 const AlgorithmIdentifier _hx509_signature_sha384_data = {
55     { 9, rk_UNCONST(sha384_oid_tree) }, rk_UNCONST(&null_entry_oid)
56 };
57 
58 static const unsigned sha256_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 1 };
59 const AlgorithmIdentifier _hx509_signature_sha256_data = {
60     { 9, rk_UNCONST(sha256_oid_tree) }, rk_UNCONST(&null_entry_oid)
61 };
62 
63 static const unsigned sha1_oid_tree[] = { 1, 3, 14, 3, 2, 26 };
64 const AlgorithmIdentifier _hx509_signature_sha1_data = {
65     { 6, rk_UNCONST(sha1_oid_tree) }, rk_UNCONST(&null_entry_oid)
66 };
67 
68 static const unsigned md5_oid_tree[] = { 1, 2, 840, 113549, 2, 5 };
69 const AlgorithmIdentifier _hx509_signature_md5_data = {
70     { 6, rk_UNCONST(md5_oid_tree) }, rk_UNCONST(&null_entry_oid)
71 };
72 
73 static const unsigned rsa_with_sha512_oid[] ={ 1, 2, 840, 113549, 1, 1, 13 };
74 const AlgorithmIdentifier _hx509_signature_rsa_with_sha512_data = {
75     { 7, rk_UNCONST(rsa_with_sha512_oid) }, rk_UNCONST(&null_entry_oid)
76 };
77 
78 static const unsigned rsa_with_sha384_oid[] ={ 1, 2, 840, 113549, 1, 1, 12 };
79 const AlgorithmIdentifier _hx509_signature_rsa_with_sha384_data = {
80     { 7, rk_UNCONST(rsa_with_sha384_oid) }, rk_UNCONST(&null_entry_oid)
81 };
82 
83 static const unsigned rsa_with_sha256_oid[] ={ 1, 2, 840, 113549, 1, 1, 11 };
84 const AlgorithmIdentifier _hx509_signature_rsa_with_sha256_data = {
85     { 7, rk_UNCONST(rsa_with_sha256_oid) }, rk_UNCONST(&null_entry_oid)
86 };
87 
88 static const unsigned rsa_with_sha1_oid[] ={ 1, 2, 840, 113549, 1, 1, 5 };
89 const AlgorithmIdentifier _hx509_signature_rsa_with_sha1_data = {
90     { 7, rk_UNCONST(rsa_with_sha1_oid) }, rk_UNCONST(&null_entry_oid)
91 };
92 
93 static const unsigned rsa_with_md5_oid[] ={ 1, 2, 840, 113549, 1, 1, 4 };
94 const AlgorithmIdentifier _hx509_signature_rsa_with_md5_data = {
95     { 7, rk_UNCONST(rsa_with_md5_oid) }, rk_UNCONST(&null_entry_oid)
96 };
97 
98 static const unsigned rsa_oid[] ={ 1, 2, 840, 113549, 1, 1, 1 };
99 const AlgorithmIdentifier _hx509_signature_rsa_data = {
100     { 7, rk_UNCONST(rsa_oid) }, NULL
101 };
102 
103 static const unsigned rsa_pkcs1_x509_oid[] ={ 1, 2, 752, 43, 16, 1 };
104 const AlgorithmIdentifier _hx509_signature_rsa_pkcs1_x509_data = {
105     { 6, rk_UNCONST(rsa_pkcs1_x509_oid) }, NULL
106 };
107 
108 static const unsigned des_rsdi_ede3_cbc_oid[] ={ 1, 2, 840, 113549, 3, 7 };
109 const AlgorithmIdentifier _hx509_des_rsdi_ede3_cbc_oid = {
110     { 6, rk_UNCONST(des_rsdi_ede3_cbc_oid) }, NULL
111 };
112 
113 static const unsigned aes128_cbc_oid[] ={ 2, 16, 840, 1, 101, 3, 4, 1, 2 };
114 const AlgorithmIdentifier _hx509_crypto_aes128_cbc_data = {
115     { 9, rk_UNCONST(aes128_cbc_oid) }, NULL
116 };
117 
118 static const unsigned aes256_cbc_oid[] ={ 2, 16, 840, 1, 101, 3, 4, 1, 42 };
119 const AlgorithmIdentifier _hx509_crypto_aes256_cbc_data = {
120     { 9, rk_UNCONST(aes256_cbc_oid) }, NULL
121 };
122 
123 /*
124  *
125  */
126 
127 static BIGNUM *
heim_int2BN(const heim_integer * i)128 heim_int2BN(const heim_integer *i)
129 {
130     BIGNUM *bn;
131 
132     bn = BN_bin2bn(i->data, i->length, NULL);
133     BN_set_negative(bn, i->negative);
134     return bn;
135 }
136 
137 /*
138  *
139  */
140 
141 int
_hx509_set_digest_alg(DigestAlgorithmIdentifier * id,const heim_oid * oid,const void * param,size_t length)142 _hx509_set_digest_alg(DigestAlgorithmIdentifier *id,
143                       const heim_oid *oid,
144                       const void *param, size_t length)
145 {
146     int ret;
147     if (param) {
148 	id->parameters = malloc(sizeof(*id->parameters));
149 	if (id->parameters == NULL)
150 	    return ENOMEM;
151 	id->parameters->data = malloc(length);
152 	if (id->parameters->data == NULL) {
153 	    free(id->parameters);
154 	    id->parameters = NULL;
155 	    return ENOMEM;
156 	}
157 	memcpy(id->parameters->data, param, length);
158 	id->parameters->length = length;
159     } else
160 	id->parameters = NULL;
161     ret = der_copy_oid(oid, &id->algorithm);
162     if (ret) {
163 	if (id->parameters) {
164 	    free(id->parameters->data);
165 	    free(id->parameters);
166 	    id->parameters = NULL;
167 	}
168 	return ret;
169     }
170     return 0;
171 }
172 
173 /*
174  *
175  */
176 
177 static int
rsa_verify_signature(hx509_context context,const struct signature_alg * sig_alg,const Certificate * signer,const AlgorithmIdentifier * alg,const heim_octet_string * data,const heim_octet_string * sig)178 rsa_verify_signature(hx509_context context,
179 		     const struct signature_alg *sig_alg,
180 		     const Certificate *signer,
181 		     const AlgorithmIdentifier *alg,
182 		     const heim_octet_string *data,
183 		     const heim_octet_string *sig)
184 {
185     const SubjectPublicKeyInfo *spi;
186     DigestInfo di;
187     unsigned char *to;
188     int tosize, retsize;
189     int ret;
190     RSA *rsa;
191     size_t size;
192     const unsigned char *p;
193 
194     memset(&di, 0, sizeof(di));
195 
196     spi = &signer->tbsCertificate.subjectPublicKeyInfo;
197 
198     p = spi->subjectPublicKey.data;
199     size = spi->subjectPublicKey.length / 8;
200 
201     rsa = d2i_RSAPublicKey(NULL, &p, size);
202     if (rsa == NULL) {
203 	ret = ENOMEM;
204 	hx509_set_error_string(context, 0, ret, "out of memory");
205 	goto out;
206     }
207 
208     tosize = RSA_size(rsa);
209     to = malloc(tosize);
210     if (to == NULL) {
211 	ret = ENOMEM;
212 	hx509_set_error_string(context, 0, ret, "out of memory");
213 	goto out;
214     }
215 
216     retsize = RSA_public_decrypt(sig->length, (unsigned char *)sig->data,
217 				 to, rsa, RSA_PKCS1_PADDING);
218     if (retsize <= 0) {
219 	ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
220 	hx509_set_error_string(context, 0, ret,
221 			       "RSA public decrypt failed: %d", retsize);
222 	free(to);
223 	goto out;
224     }
225     if (retsize > tosize)
226 	_hx509_abort("internal rsa decryption failure: ret > tosize");
227 
228     if (sig_alg->flags & RA_RSA_USES_DIGEST_INFO) {
229 
230 	ret = decode_DigestInfo(to, retsize, &di, &size);
231 	free(to);
232 	if (ret) {
233 	    goto out;
234 	}
235 
236 	/* Check for extra data inside the sigature */
237 	if (size != (size_t)retsize) {
238 	    ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
239 	    hx509_set_error_string(context, 0, ret, "size from decryption mismatch");
240 	    goto out;
241 	}
242 
243 	if (sig_alg->digest_alg &&
244 	    der_heim_oid_cmp(&di.digestAlgorithm.algorithm,
245 			     &sig_alg->digest_alg->algorithm) != 0)
246 	{
247 	    ret = HX509_CRYPTO_OID_MISMATCH;
248 	    hx509_set_error_string(context, 0, ret, "object identifier in RSA sig mismatch");
249 	    goto out;
250 	}
251 
252 	/* verify that the parameters are NULL or the NULL-type */
253 	if (di.digestAlgorithm.parameters != NULL &&
254 	    (di.digestAlgorithm.parameters->length != 2 ||
255 	     memcmp(di.digestAlgorithm.parameters->data, "\x05\x00", 2) != 0))
256 	{
257 	    ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
258 	    hx509_set_error_string(context, 0, ret, "Extra parameters inside RSA signature");
259 	    goto out;
260 	}
261 
262 	ret = _hx509_verify_signature(context,
263 				      NULL,
264 				      &di.digestAlgorithm,
265 				      data,
266 				      &di.digest);
267 	if (ret)
268 	    goto out;
269 
270     } else {
271 	if ((size_t)retsize != data->length ||
272 	    ct_memcmp(to, data->data, retsize) != 0)
273 	{
274 	    ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
275 	    hx509_set_error_string(context, 0, ret, "RSA Signature incorrect");
276 	    goto out;
277 	}
278 	free(to);
279 	ret = 0;
280     }
281 
282  out:
283     free_DigestInfo(&di);
284     if (rsa)
285 	RSA_free(rsa);
286     return ret;
287 }
288 
289 static int
rsa_create_signature(hx509_context context,const struct signature_alg * sig_alg,const hx509_private_key signer,const AlgorithmIdentifier * alg,const heim_octet_string * data,AlgorithmIdentifier * signatureAlgorithm,heim_octet_string * sig)290 rsa_create_signature(hx509_context context,
291 		     const struct signature_alg *sig_alg,
292 		     const hx509_private_key signer,
293 		     const AlgorithmIdentifier *alg,
294 		     const heim_octet_string *data,
295 		     AlgorithmIdentifier *signatureAlgorithm,
296 		     heim_octet_string *sig)
297 {
298     const AlgorithmIdentifier *digest_alg;
299     heim_octet_string indata;
300     const heim_oid *sig_oid;
301     size_t size;
302     int ret;
303 
304     if (signer->ops && der_heim_oid_cmp(signer->ops->key_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) != 0)
305 	return HX509_ALG_NOT_SUPP;
306 
307     if (alg)
308 	sig_oid = &alg->algorithm;
309     else
310 	sig_oid = signer->signature_alg;
311 
312     if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA512WITHRSAENCRYPTION) == 0) {
313 	digest_alg = hx509_signature_sha512();
314     } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA384WITHRSAENCRYPTION) == 0) {
315 	digest_alg = hx509_signature_sha384();
316     } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA256WITHRSAENCRYPTION) == 0) {
317 	digest_alg = hx509_signature_sha256();
318     } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION) == 0) {
319 	digest_alg = hx509_signature_sha1();
320     } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_MD5WITHRSAENCRYPTION) == 0) {
321 	digest_alg = hx509_signature_md5();
322     } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_MD5WITHRSAENCRYPTION) == 0) {
323 	digest_alg = hx509_signature_md5();
324     } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_DSA_WITH_SHA1) == 0) {
325 	digest_alg = hx509_signature_sha1();
326     } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) == 0) {
327 	digest_alg = hx509_signature_sha1();
328     } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_HEIM_RSA_PKCS1_X509) == 0) {
329 	digest_alg = NULL;
330     } else
331 	return HX509_ALG_NOT_SUPP;
332 
333     if (signatureAlgorithm) {
334         ret = _hx509_set_digest_alg(signatureAlgorithm, sig_oid,
335                                     "\x05\x00", 2);
336 	if (ret) {
337 	    hx509_clear_error_string(context);
338 	    return ret;
339 	}
340     }
341 
342     if (digest_alg) {
343 	DigestInfo di;
344 	memset(&di, 0, sizeof(di));
345 
346 	ret = _hx509_create_signature(context,
347 				      NULL,
348 				      digest_alg,
349 				      data,
350 				      &di.digestAlgorithm,
351 				      &di.digest);
352 	if (ret)
353 	    return ret;
354 	ASN1_MALLOC_ENCODE(DigestInfo,
355 			   indata.data,
356 			   indata.length,
357 			   &di,
358 			   &size,
359 			   ret);
360 	free_DigestInfo(&di);
361 	if (ret) {
362 	    hx509_set_error_string(context, 0, ret, "out of memory");
363 	    return ret;
364 	}
365 	if (indata.length != size)
366 	    _hx509_abort("internal ASN.1 encoder error");
367     } else {
368 	indata = *data;
369     }
370 
371     sig->length = RSA_size(signer->private_key.rsa);
372     sig->data = malloc(sig->length);
373     if (sig->data == NULL) {
374 	der_free_octet_string(&indata);
375 	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
376 	return ENOMEM;
377     }
378 
379     ret = RSA_private_encrypt(indata.length, indata.data,
380 			      sig->data,
381 			      signer->private_key.rsa,
382 			      RSA_PKCS1_PADDING);
383     if (indata.data != data->data)
384 	der_free_octet_string(&indata);
385     if (ret <= 0) {
386 	ret = HX509_CMS_FAILED_CREATE_SIGATURE;
387 	hx509_set_error_string(context, 0, ret,
388 			       "RSA private encrypt failed: %d", ret);
389 	return ret;
390     }
391     if (sig->length > (size_t)ret) {
392 	size = sig->length - ret;
393 	memmove((uint8_t *)sig->data + size, sig->data, ret);
394 	memset(sig->data, 0, size);
395     } else if (sig->length < (size_t)ret)
396 	_hx509_abort("RSA signature prelen longer the output len");
397 
398     return 0;
399 }
400 
401 static int
rsa_private_key_import(hx509_context context,const AlgorithmIdentifier * keyai,const void * data,size_t len,hx509_key_format_t format,hx509_private_key private_key)402 rsa_private_key_import(hx509_context context,
403 		       const AlgorithmIdentifier *keyai,
404 		       const void *data,
405 		       size_t len,
406 		       hx509_key_format_t format,
407 		       hx509_private_key private_key)
408 {
409     switch (format) {
410     case HX509_KEY_FORMAT_DER: {
411 	const unsigned char *p = data;
412 
413 	private_key->private_key.rsa =
414 	    d2i_RSAPrivateKey(NULL, &p, len);
415 	if (private_key->private_key.rsa == NULL) {
416 	    hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
417 				   "Failed to parse RSA key");
418 	    return HX509_PARSING_KEY_FAILED;
419 	}
420 	private_key->signature_alg = ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION;
421 	break;
422 
423     }
424     default:
425 	return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED;
426     }
427 
428     return 0;
429 }
430 
431 static int
rsa_private_key2SPKI(hx509_context context,hx509_private_key private_key,SubjectPublicKeyInfo * spki)432 rsa_private_key2SPKI(hx509_context context,
433 		     hx509_private_key private_key,
434 		     SubjectPublicKeyInfo *spki)
435 {
436     int len, ret;
437 
438     memset(spki, 0, sizeof(*spki));
439 
440     len = i2d_RSAPublicKey(private_key->private_key.rsa, NULL);
441 
442     spki->subjectPublicKey.data = malloc(len);
443     if (spki->subjectPublicKey.data == NULL) {
444 	hx509_set_error_string(context, 0, ENOMEM, "malloc - out of memory");
445 	return ENOMEM;
446     }
447     spki->subjectPublicKey.length = len * 8;
448 
449     ret = _hx509_set_digest_alg(&spki->algorithm,
450                                 ASN1_OID_ID_PKCS1_RSAENCRYPTION,
451                                 "\x05\x00", 2);
452     if (ret) {
453 	hx509_set_error_string(context, 0, ret, "malloc - out of memory");
454 	free(spki->subjectPublicKey.data);
455 	spki->subjectPublicKey.data = NULL;
456 	spki->subjectPublicKey.length = 0;
457 	return ret;
458     }
459 
460     {
461 	unsigned char *pp = spki->subjectPublicKey.data;
462 	i2d_RSAPublicKey(private_key->private_key.rsa, &pp);
463     }
464 
465     return 0;
466 }
467 
468 static int
rsa_generate_private_key(hx509_context context,struct hx509_generate_private_context * ctx,hx509_private_key private_key)469 rsa_generate_private_key(hx509_context context,
470 			 struct hx509_generate_private_context *ctx,
471 			 hx509_private_key private_key)
472 {
473     BIGNUM *e;
474     int ret;
475     unsigned long bits;
476 
477     static const int default_rsa_e = 65537;
478     static const int default_rsa_bits = 2048;
479 
480     private_key->private_key.rsa = RSA_new();
481     if (private_key->private_key.rsa == NULL) {
482 	hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
483 			       "Failed to generate RSA key");
484 	return HX509_PARSING_KEY_FAILED;
485     }
486 
487     e = BN_new();
488     BN_set_word(e, default_rsa_e);
489 
490     bits = default_rsa_bits;
491 
492     if (ctx->num_bits)
493 	bits = ctx->num_bits;
494 
495     ret = RSA_generate_key_ex(private_key->private_key.rsa, bits, e, NULL);
496     BN_free(e);
497     if (ret != 1) {
498 	hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
499 			       "Failed to generate RSA key");
500 	return HX509_PARSING_KEY_FAILED;
501     }
502     private_key->signature_alg = ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION;
503 
504     return 0;
505 }
506 
507 static int
rsa_private_key_export(hx509_context context,const hx509_private_key key,hx509_key_format_t format,heim_octet_string * data)508 rsa_private_key_export(hx509_context context,
509 		       const hx509_private_key key,
510 		       hx509_key_format_t format,
511 		       heim_octet_string *data)
512 {
513     int ret;
514 
515     data->data = NULL;
516     data->length = 0;
517 
518     switch (format) {
519     case HX509_KEY_FORMAT_DER:
520 
521 	ret = i2d_RSAPrivateKey(key->private_key.rsa, NULL);
522 	if (ret <= 0) {
523 	    ret = EINVAL;
524 	    hx509_set_error_string(context, 0, ret,
525 			       "Private key is not exportable");
526 	    return ret;
527 	}
528 
529 	data->data = malloc(ret);
530 	if (data->data == NULL) {
531 	    ret = ENOMEM;
532 	    hx509_set_error_string(context, 0, ret, "malloc out of memory");
533 	    return ret;
534 	}
535 	data->length = ret;
536 
537 	{
538 	    unsigned char *p = data->data;
539 	    i2d_RSAPrivateKey(key->private_key.rsa, &p);
540 	}
541 	break;
542     default:
543 	return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED;
544     }
545 
546     return 0;
547 }
548 
549 static BIGNUM *
rsa_get_internal(hx509_context context,hx509_private_key key,const char * type)550 rsa_get_internal(hx509_context context,
551 		 hx509_private_key key,
552 		 const char *type)
553 {
554     if (strcasecmp(type, "rsa-modulus") == 0) {
555 	const BIGNUM *n;
556 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
557 	n = key->private_key.rsa->n;
558 #else
559 	RSA_get0_key(key->private_key.rsa, &n, NULL, NULL);
560 #endif
561 	return BN_dup(n);
562     } else if (strcasecmp(type, "rsa-exponent") == 0) {
563 	const BIGNUM *e;
564 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
565 	e = key->private_key.rsa->e;
566 #else
567 	RSA_get0_key(key->private_key.rsa, NULL, &e, NULL);
568 #endif
569 	return BN_dup(e);
570     } else
571 	return NULL;
572 }
573 
574 
575 
576 static hx509_private_key_ops rsa_private_key_ops = {
577     "RSA PRIVATE KEY",
578     ASN1_OID_ID_PKCS1_RSAENCRYPTION,
579     NULL,
580     rsa_private_key2SPKI,
581     rsa_private_key_export,
582     rsa_private_key_import,
583     rsa_generate_private_key,
584     rsa_get_internal
585 };
586 
587 /*
588  *
589  */
590 
591 static int
dsa_verify_signature(hx509_context context,const struct signature_alg * sig_alg,const Certificate * signer,const AlgorithmIdentifier * alg,const heim_octet_string * data,const heim_octet_string * sig)592 dsa_verify_signature(hx509_context context,
593 		     const struct signature_alg *sig_alg,
594 		     const Certificate *signer,
595 		     const AlgorithmIdentifier *alg,
596 		     const heim_octet_string *data,
597 		     const heim_octet_string *sig)
598 {
599     const SubjectPublicKeyInfo *spi;
600     DSAPublicKey pk;
601     DSAParams param;
602     size_t size;
603     DSA *dsa;
604     int ret;
605 
606     spi = &signer->tbsCertificate.subjectPublicKeyInfo;
607 
608     dsa = DSA_new();
609     if (dsa == NULL) {
610 	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
611 	return ENOMEM;
612     }
613 
614     ret = decode_DSAPublicKey(spi->subjectPublicKey.data,
615 			      spi->subjectPublicKey.length / 8,
616 			      &pk, &size);
617     if (ret)
618 	goto out;
619 
620 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
621     dsa->pub_key = heim_int2BN(&pk);
622     ret = dsa->pub_key == NULL;
623 #else
624     ret = !DSA_set0_key(dsa, heim_int2BN(&pk), NULL);
625 #endif
626 
627     free_DSAPublicKey(&pk);
628 
629     if (ret) {
630 	ret = ENOMEM;
631 	hx509_set_error_string(context, 0, ret, "out of memory");
632 	goto out;
633     }
634 
635     if (spi->algorithm.parameters == NULL) {
636 	ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
637 	hx509_set_error_string(context, 0, ret, "DSA parameters missing");
638 	goto out;
639     }
640 
641     ret = decode_DSAParams(spi->algorithm.parameters->data,
642 			   spi->algorithm.parameters->length,
643 			   &param,
644 			   &size);
645     if (ret) {
646 	hx509_set_error_string(context, 0, ret, "DSA parameters failed to decode");
647 	goto out;
648     }
649 
650     BIGNUM *p = heim_int2BN(&param.p);
651     BIGNUM *q = heim_int2BN(&param.q);
652     BIGNUM *g = heim_int2BN(&param.g);
653 
654     free_DSAParams(&param);
655 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
656     dsa->p = p;
657     dsa->q = q;
658     dsa->g = g;
659 #else
660     ret = DSA_set0_pqg(dsa, p, q, g);
661 #endif
662     ret |= p == NULL || q == NULL || g == NULL;
663 
664     if (ret) {
665 	ret = ENOMEM;
666 	hx509_set_error_string(context, 0, ret, "out of memory");
667 	goto out;
668     }
669 
670     ret = DSA_verify(-1, data->data, data->length,
671 		     (unsigned char*)sig->data, sig->length,
672 		     dsa);
673     if (ret == 1)
674 	ret = 0;
675     else if (ret == 0 || ret == -1) {
676 	ret = HX509_CRYPTO_BAD_SIGNATURE;
677 	hx509_set_error_string(context, 0, ret, "BAD DSA sigature");
678     } else {
679 	ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
680 	hx509_set_error_string(context, 0, ret, "Invalid format of DSA sigature");
681     }
682 
683  out:
684     DSA_free(dsa);
685 
686     return ret;
687 }
688 
689 #if 0
690 static int
691 dsa_parse_private_key(hx509_context context,
692 		      const void *data,
693 		      size_t len,
694 		      hx509_private_key private_key)
695 {
696     const unsigned char *p = data;
697 
698     private_key->private_key.dsa =
699 	d2i_DSAPrivateKey(NULL, &p, len);
700     if (private_key->private_key.dsa == NULL)
701 	return EINVAL;
702     private_key->signature_alg = ASN1_OID_ID_DSA_WITH_SHA1;
703 
704     return 0;
705 /* else */
706     hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
707 			   "No support to parse DSA keys");
708     return HX509_PARSING_KEY_FAILED;
709 }
710 #endif
711 
712 static int
evp_md_create_signature(hx509_context context,const struct signature_alg * sig_alg,const hx509_private_key signer,const AlgorithmIdentifier * alg,const heim_octet_string * data,AlgorithmIdentifier * signatureAlgorithm,heim_octet_string * sig)713 evp_md_create_signature(hx509_context context,
714 			const struct signature_alg *sig_alg,
715 			const hx509_private_key signer,
716 			const AlgorithmIdentifier *alg,
717 			const heim_octet_string *data,
718 			AlgorithmIdentifier *signatureAlgorithm,
719 			heim_octet_string *sig)
720 {
721     size_t sigsize = EVP_MD_size(sig_alg->evp_md());
722     EVP_MD_CTX *ctx;
723 
724     memset(sig, 0, sizeof(*sig));
725 
726     if (signatureAlgorithm) {
727 	int ret;
728         ret = _hx509_set_digest_alg(signatureAlgorithm,
729                                     sig_alg->sig_oid, "\x05\x00", 2);
730 	if (ret)
731 	    return ret;
732     }
733 
734 
735     sig->data = malloc(sigsize);
736     if (sig->data == NULL) {
737 	sig->length = 0;
738 	return ENOMEM;
739     }
740     sig->length = sigsize;
741 
742     ctx = EVP_MD_CTX_create();
743     EVP_DigestInit_ex(ctx, sig_alg->evp_md(), NULL);
744     EVP_DigestUpdate(ctx, data->data, data->length);
745     EVP_DigestFinal_ex(ctx, sig->data, NULL);
746     EVP_MD_CTX_destroy(ctx);
747 
748 
749     return 0;
750 }
751 
752 static int
evp_md_verify_signature(hx509_context context,const struct signature_alg * sig_alg,const Certificate * signer,const AlgorithmIdentifier * alg,const heim_octet_string * data,const heim_octet_string * sig)753 evp_md_verify_signature(hx509_context context,
754 			const struct signature_alg *sig_alg,
755 			const Certificate *signer,
756 			const AlgorithmIdentifier *alg,
757 			const heim_octet_string *data,
758 			const heim_octet_string *sig)
759 {
760     unsigned char digest[EVP_MAX_MD_SIZE];
761     EVP_MD_CTX *ctx;
762     size_t sigsize = EVP_MD_size(sig_alg->evp_md());
763 
764     if (sig->length != sigsize || sigsize > sizeof(digest)) {
765 	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
766 			       "SHA256 sigature have wrong length");
767 	return HX509_CRYPTO_SIG_INVALID_FORMAT;
768     }
769 
770     ctx = EVP_MD_CTX_create();
771     EVP_DigestInit_ex(ctx, sig_alg->evp_md(), NULL);
772     EVP_DigestUpdate(ctx, data->data, data->length);
773     EVP_DigestFinal_ex(ctx, digest, NULL);
774     EVP_MD_CTX_destroy(ctx);
775 
776     if (ct_memcmp(digest, sig->data, sigsize) != 0) {
777 	hx509_set_error_string(context, 0, HX509_CRYPTO_BAD_SIGNATURE,
778 			       "Bad %s sigature", sig_alg->name);
779 	return HX509_CRYPTO_BAD_SIGNATURE;
780     }
781 
782     return 0;
783 }
784 
785 #ifdef HAVE_HCRYPTO_W_OPENSSL
786 extern const struct signature_alg ecdsa_with_sha512_alg;
787 extern const struct signature_alg ecdsa_with_sha384_alg;
788 extern const struct signature_alg ecdsa_with_sha256_alg;
789 extern const struct signature_alg ecdsa_with_sha1_alg;
790 #endif
791 
792 static const struct signature_alg heim_rsa_pkcs1_x509 = {
793     "rsa-pkcs1-x509",
794     ASN1_OID_ID_HEIM_RSA_PKCS1_X509,
795     &_hx509_signature_rsa_pkcs1_x509_data,
796     ASN1_OID_ID_PKCS1_RSAENCRYPTION,
797     NULL,
798     PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
799     0,
800     NULL,
801     rsa_verify_signature,
802     rsa_create_signature,
803     0
804 };
805 
806 static const struct signature_alg pkcs1_rsa_sha1_alg = {
807     "rsa",
808     ASN1_OID_ID_PKCS1_RSAENCRYPTION,
809     &_hx509_signature_rsa_with_sha1_data,
810     ASN1_OID_ID_PKCS1_RSAENCRYPTION,
811     NULL,
812     PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
813     0,
814     NULL,
815     rsa_verify_signature,
816     rsa_create_signature,
817     0
818 };
819 
820 static const struct signature_alg rsa_with_sha512_alg = {
821     "rsa-with-sha512",
822     ASN1_OID_ID_PKCS1_SHA512WITHRSAENCRYPTION,
823     &_hx509_signature_rsa_with_sha512_data,
824     ASN1_OID_ID_PKCS1_RSAENCRYPTION,
825     &_hx509_signature_sha512_data,
826     PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
827     0,
828     NULL,
829     rsa_verify_signature,
830     rsa_create_signature,
831     0
832 };
833 
834 static const struct signature_alg rsa_with_sha384_alg = {
835     "rsa-with-sha384",
836     ASN1_OID_ID_PKCS1_SHA384WITHRSAENCRYPTION,
837     &_hx509_signature_rsa_with_sha384_data,
838     ASN1_OID_ID_PKCS1_RSAENCRYPTION,
839     &_hx509_signature_sha384_data,
840     PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
841     0,
842     NULL,
843     rsa_verify_signature,
844     rsa_create_signature,
845     0
846 };
847 
848 static const struct signature_alg rsa_with_sha256_alg = {
849     "rsa-with-sha256",
850     ASN1_OID_ID_PKCS1_SHA256WITHRSAENCRYPTION,
851     &_hx509_signature_rsa_with_sha256_data,
852     ASN1_OID_ID_PKCS1_RSAENCRYPTION,
853     &_hx509_signature_sha256_data,
854     PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
855     0,
856     NULL,
857     rsa_verify_signature,
858     rsa_create_signature,
859     0
860 };
861 
862 static const struct signature_alg rsa_with_sha1_alg = {
863     "rsa-with-sha1",
864     ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION,
865     &_hx509_signature_rsa_with_sha1_data,
866     ASN1_OID_ID_PKCS1_RSAENCRYPTION,
867     &_hx509_signature_sha1_data,
868     PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
869     0,
870     NULL,
871     rsa_verify_signature,
872     rsa_create_signature,
873     0
874 };
875 
876 static const struct signature_alg rsa_with_sha1_alg_secsig = {
877     "rsa-with-sha1",
878     ASN1_OID_ID_SECSIG_SHA_1WITHRSAENCRYPTION,
879     &_hx509_signature_rsa_with_sha1_data,
880     ASN1_OID_ID_PKCS1_RSAENCRYPTION,
881     &_hx509_signature_sha1_data,
882     PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SELF_SIGNED_OK,
883     0,
884     NULL,
885     rsa_verify_signature,
886     rsa_create_signature,
887     0
888 };
889 
890 static const struct signature_alg rsa_with_md5_alg = {
891     "rsa-with-md5",
892     ASN1_OID_ID_PKCS1_MD5WITHRSAENCRYPTION,
893     &_hx509_signature_rsa_with_md5_data,
894     ASN1_OID_ID_PKCS1_RSAENCRYPTION,
895     &_hx509_signature_md5_data,
896     PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|WEAK_SIG_ALG,
897     1230739889,
898     NULL,
899     rsa_verify_signature,
900     rsa_create_signature,
901     0
902 };
903 
904 static const struct signature_alg dsa_sha1_alg = {
905     "dsa-with-sha1",
906     ASN1_OID_ID_DSA_WITH_SHA1,
907     NULL,
908     ASN1_OID_ID_DSA,
909     &_hx509_signature_sha1_data,
910     PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
911     0,
912     NULL,
913     dsa_verify_signature,
914     /* create_signature */ NULL,
915     0
916 };
917 
918 static const struct signature_alg sha512_alg = {
919     "sha-512",
920     ASN1_OID_ID_SHA512,
921     &_hx509_signature_sha512_data,
922     NULL,
923     NULL,
924     SIG_DIGEST,
925     0,
926     EVP_sha512,
927     evp_md_verify_signature,
928     evp_md_create_signature,
929     0
930 };
931 
932 static const struct signature_alg sha384_alg = {
933     "sha-384",
934     ASN1_OID_ID_SHA384,
935     &_hx509_signature_sha384_data,
936     NULL,
937     NULL,
938     SIG_DIGEST,
939     0,
940     EVP_sha384,
941     evp_md_verify_signature,
942     evp_md_create_signature,
943     0
944 };
945 
946 static const struct signature_alg sha256_alg = {
947     "sha-256",
948     ASN1_OID_ID_SHA256,
949     &_hx509_signature_sha256_data,
950     NULL,
951     NULL,
952     SIG_DIGEST,
953     0,
954     EVP_sha256,
955     evp_md_verify_signature,
956     evp_md_create_signature,
957     0
958 };
959 
960 static const struct signature_alg sha1_alg = {
961     "sha1",
962     ASN1_OID_ID_SECSIG_SHA_1,
963     &_hx509_signature_sha1_data,
964     NULL,
965     NULL,
966     SIG_DIGEST,
967     0,
968     EVP_sha1,
969     evp_md_verify_signature,
970     evp_md_create_signature,
971     0
972 };
973 
974 static const struct signature_alg md5_alg = {
975     "rsa-md5",
976     ASN1_OID_ID_RSA_DIGEST_MD5,
977     &_hx509_signature_md5_data,
978     NULL,
979     NULL,
980     SIG_DIGEST|WEAK_SIG_ALG,
981     0,
982     EVP_md5,
983     evp_md_verify_signature,
984     NULL,
985     0
986 };
987 
988 /*
989  * Order matter in this structure, "best" first for each "key
990  * compatible" type (type is ECDSA, RSA, DSA, none, etc)
991  */
992 
993 static const struct signature_alg *sig_algs[] = {
994 #ifdef HAVE_HCRYPTO_W_OPENSSL
995     &ecdsa_with_sha512_alg,
996     &ecdsa_with_sha384_alg,
997     &ecdsa_with_sha256_alg,
998     &ecdsa_with_sha1_alg,
999 #endif
1000     &rsa_with_sha512_alg,
1001     &rsa_with_sha384_alg,
1002     &rsa_with_sha256_alg,
1003     &rsa_with_sha1_alg,
1004     &rsa_with_sha1_alg_secsig,
1005     &pkcs1_rsa_sha1_alg,
1006     &rsa_with_md5_alg,
1007     &heim_rsa_pkcs1_x509,
1008     &dsa_sha1_alg,
1009     &sha512_alg,
1010     &sha384_alg,
1011     &sha256_alg,
1012     &sha1_alg,
1013     &md5_alg,
1014     NULL
1015 };
1016 
1017 const struct signature_alg *
_hx509_find_sig_alg(const heim_oid * oid)1018 _hx509_find_sig_alg(const heim_oid *oid)
1019 {
1020     unsigned int i;
1021     for (i = 0; sig_algs[i]; i++)
1022 	if (der_heim_oid_cmp(sig_algs[i]->sig_oid, oid) == 0)
1023 	    return sig_algs[i];
1024     return NULL;
1025 }
1026 
1027 static const AlgorithmIdentifier *
alg_for_privatekey(const hx509_private_key pk,int type)1028 alg_for_privatekey(const hx509_private_key pk, int type)
1029 {
1030     const heim_oid *keytype;
1031     unsigned int i;
1032 
1033     if (pk->ops == NULL)
1034 	return NULL;
1035 
1036     keytype = pk->ops->key_oid;
1037 
1038     for (i = 0; sig_algs[i]; i++) {
1039 	if (sig_algs[i]->key_oid == NULL)
1040 	    continue;
1041 	if (der_heim_oid_cmp(sig_algs[i]->key_oid, keytype) != 0)
1042 	    continue;
1043 	if (pk->ops->available &&
1044 	    pk->ops->available(pk, sig_algs[i]->sig_alg) == 0)
1045 	    continue;
1046 	if (type == HX509_SELECT_PUBLIC_SIG)
1047 	    return sig_algs[i]->sig_alg;
1048 	if (type == HX509_SELECT_DIGEST)
1049 	    return sig_algs[i]->digest_alg;
1050 
1051 	return NULL;
1052     }
1053     return NULL;
1054 }
1055 
1056 /*
1057  *
1058  */
1059 #ifdef HAVE_HCRYPTO_W_OPENSSL
1060 extern hx509_private_key_ops ecdsa_private_key_ops;
1061 #endif
1062 
1063 static struct hx509_private_key_ops *private_algs[] = {
1064     &rsa_private_key_ops,
1065 #ifdef HAVE_HCRYPTO_W_OPENSSL
1066     &ecdsa_private_key_ops,
1067 #endif
1068     NULL
1069 };
1070 
1071 hx509_private_key_ops *
hx509_find_private_alg(const heim_oid * oid)1072 hx509_find_private_alg(const heim_oid *oid)
1073 {
1074     int i;
1075     for (i = 0; private_algs[i]; i++) {
1076 	if (private_algs[i]->key_oid == NULL)
1077 	    continue;
1078 	if (der_heim_oid_cmp(private_algs[i]->key_oid, oid) == 0)
1079 	    return private_algs[i];
1080     }
1081     return NULL;
1082 }
1083 
1084 /*
1085  * Check if the algorithm `alg' have a best before date, and if it
1086  * des, make sure the its before the time `t'.
1087  */
1088 
1089 int
_hx509_signature_is_weak(hx509_context context,const AlgorithmIdentifier * alg)1090 _hx509_signature_is_weak(hx509_context context, const AlgorithmIdentifier *alg)
1091 {
1092     const struct signature_alg *md;
1093 
1094     md = _hx509_find_sig_alg(&alg->algorithm);
1095     if (md == NULL) {
1096 	hx509_clear_error_string(context);
1097 	return HX509_SIG_ALG_NO_SUPPORTED;
1098     }
1099     if (md->flags & WEAK_SIG_ALG) {
1100 	hx509_set_error_string(context, 0, HX509_CRYPTO_ALGORITHM_BEST_BEFORE,
1101 			       "Algorithm %s is weak", md->name);
1102 	return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
1103     }
1104     return 0;
1105 }
1106 
1107 int
_hx509_self_signed_valid(hx509_context context,const AlgorithmIdentifier * alg)1108 _hx509_self_signed_valid(hx509_context context,
1109 			 const AlgorithmIdentifier *alg)
1110 {
1111     const struct signature_alg *md;
1112 
1113     md = _hx509_find_sig_alg(&alg->algorithm);
1114     if (md == NULL) {
1115 	hx509_clear_error_string(context);
1116 	return HX509_SIG_ALG_NO_SUPPORTED;
1117     }
1118     if ((md->flags & SELF_SIGNED_OK) == 0) {
1119 	hx509_set_error_string(context, 0, HX509_CRYPTO_ALGORITHM_BEST_BEFORE,
1120 			       "Algorithm %s not trusted for self signatures",
1121 			       md->name);
1122 	return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
1123     }
1124     return 0;
1125 }
1126 
1127 
1128 int
_hx509_verify_signature(hx509_context context,const hx509_cert cert,const AlgorithmIdentifier * alg,const heim_octet_string * data,const heim_octet_string * sig)1129 _hx509_verify_signature(hx509_context context,
1130 			const hx509_cert cert,
1131 			const AlgorithmIdentifier *alg,
1132 			const heim_octet_string *data,
1133 			const heim_octet_string *sig)
1134 {
1135     const struct signature_alg *md;
1136     const Certificate *signer = NULL;
1137 
1138     if (cert)
1139 	signer = _hx509_get_cert(cert);
1140 
1141     md = _hx509_find_sig_alg(&alg->algorithm);
1142     if (md == NULL) {
1143 	hx509_clear_error_string(context);
1144 	return HX509_SIG_ALG_NO_SUPPORTED;
1145     }
1146     if (signer && (md->flags & PROVIDE_CONF) == 0) {
1147 	hx509_clear_error_string(context);
1148 	return HX509_CRYPTO_SIG_NO_CONF;
1149     }
1150     if (signer == NULL && (md->flags & REQUIRE_SIGNER)) {
1151 	    hx509_clear_error_string(context);
1152 	return HX509_CRYPTO_SIGNATURE_WITHOUT_SIGNER;
1153     }
1154     if (md->key_oid && signer) {
1155 	const SubjectPublicKeyInfo *spi;
1156 	spi = &signer->tbsCertificate.subjectPublicKeyInfo;
1157 
1158 	if (der_heim_oid_cmp(&spi->algorithm.algorithm, md->key_oid) != 0) {
1159 	    hx509_clear_error_string(context);
1160 	    return HX509_SIG_ALG_DONT_MATCH_KEY_ALG;
1161 	}
1162     }
1163     return (*md->verify_signature)(context, md, signer, alg, data, sig);
1164 }
1165 
1166 int
_hx509_create_signature(hx509_context context,const hx509_private_key signer,const AlgorithmIdentifier * alg,const heim_octet_string * data,AlgorithmIdentifier * signatureAlgorithm,heim_octet_string * sig)1167 _hx509_create_signature(hx509_context context,
1168 			const hx509_private_key signer,
1169 			const AlgorithmIdentifier *alg,
1170 			const heim_octet_string *data,
1171 			AlgorithmIdentifier *signatureAlgorithm,
1172 			heim_octet_string *sig)
1173 {
1174     const struct signature_alg *md;
1175 
1176     md = _hx509_find_sig_alg(&alg->algorithm);
1177     if (md == NULL) {
1178 	hx509_set_error_string(context, 0, HX509_SIG_ALG_NO_SUPPORTED,
1179 	    "algorithm no supported");
1180 	return HX509_SIG_ALG_NO_SUPPORTED;
1181     }
1182 
1183     if (signer && (md->flags & PROVIDE_CONF) == 0) {
1184 	hx509_set_error_string(context, 0, HX509_SIG_ALG_NO_SUPPORTED,
1185 	    "algorithm provides no conf");
1186 	return HX509_CRYPTO_SIG_NO_CONF;
1187     }
1188 
1189     return (*md->create_signature)(context, md, signer, alg, data,
1190 				   signatureAlgorithm, sig);
1191 }
1192 
1193 int
_hx509_create_signature_bitstring(hx509_context context,const hx509_private_key signer,const AlgorithmIdentifier * alg,const heim_octet_string * data,AlgorithmIdentifier * signatureAlgorithm,heim_bit_string * sig)1194 _hx509_create_signature_bitstring(hx509_context context,
1195 				  const hx509_private_key signer,
1196 				  const AlgorithmIdentifier *alg,
1197 				  const heim_octet_string *data,
1198 				  AlgorithmIdentifier *signatureAlgorithm,
1199 				  heim_bit_string *sig)
1200 {
1201     heim_octet_string os;
1202     int ret;
1203 
1204     ret = _hx509_create_signature(context, signer, alg,
1205 				  data, signatureAlgorithm, &os);
1206     if (ret)
1207 	return ret;
1208     sig->data = os.data;
1209     sig->length = os.length * 8;
1210     return 0;
1211 }
1212 
1213 int
_hx509_public_encrypt(hx509_context context,const heim_octet_string * cleartext,const Certificate * cert,heim_oid * encryption_oid,heim_octet_string * ciphertext)1214 _hx509_public_encrypt(hx509_context context,
1215 		      const heim_octet_string *cleartext,
1216 		      const Certificate *cert,
1217 		      heim_oid *encryption_oid,
1218 		      heim_octet_string *ciphertext)
1219 {
1220     const SubjectPublicKeyInfo *spi;
1221     unsigned char *to;
1222     int tosize;
1223     int ret;
1224     RSA *rsa;
1225     size_t size;
1226     const unsigned char *p;
1227 
1228     ciphertext->data = NULL;
1229     ciphertext->length = 0;
1230 
1231     spi = &cert->tbsCertificate.subjectPublicKeyInfo;
1232 
1233     p = spi->subjectPublicKey.data;
1234     size = spi->subjectPublicKey.length / 8;
1235 
1236     rsa = d2i_RSAPublicKey(NULL, &p, size);
1237     if (rsa == NULL) {
1238 	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
1239 	return ENOMEM;
1240     }
1241 
1242     tosize = RSA_size(rsa);
1243     to = malloc(tosize);
1244     if (to == NULL) {
1245 	RSA_free(rsa);
1246 	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
1247 	return ENOMEM;
1248     }
1249 
1250     ret = RSA_public_encrypt(cleartext->length,
1251 			     (unsigned char *)cleartext->data,
1252 			     to, rsa, RSA_PKCS1_PADDING);
1253     RSA_free(rsa);
1254     if (ret <= 0) {
1255 	free(to);
1256 	hx509_set_error_string(context, 0, HX509_CRYPTO_RSA_PUBLIC_ENCRYPT,
1257 			       "RSA public encrypt failed with %d", ret);
1258 	return HX509_CRYPTO_RSA_PUBLIC_ENCRYPT;
1259     }
1260     if (ret > tosize)
1261 	_hx509_abort("internal rsa decryption failure: ret > tosize");
1262 
1263     ciphertext->length = ret;
1264     ciphertext->data = to;
1265 
1266     ret = der_copy_oid(ASN1_OID_ID_PKCS1_RSAENCRYPTION, encryption_oid);
1267     if (ret) {
1268 	der_free_octet_string(ciphertext);
1269 	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
1270 	return ENOMEM;
1271     }
1272 
1273     return 0;
1274 }
1275 
1276 int
hx509_private_key_private_decrypt(hx509_context context,const heim_octet_string * ciphertext,const heim_oid * encryption_oid,hx509_private_key p,heim_octet_string * cleartext)1277 hx509_private_key_private_decrypt(hx509_context context,
1278 				   const heim_octet_string *ciphertext,
1279 				   const heim_oid *encryption_oid,
1280 				   hx509_private_key p,
1281 				   heim_octet_string *cleartext)
1282 {
1283     int ret;
1284 
1285     cleartext->data = NULL;
1286     cleartext->length = 0;
1287 
1288     if (p->private_key.rsa == NULL) {
1289 	hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
1290 			       "Private RSA key missing");
1291 	return HX509_PRIVATE_KEY_MISSING;
1292     }
1293 
1294     cleartext->length = RSA_size(p->private_key.rsa);
1295     cleartext->data = malloc(cleartext->length);
1296     if (cleartext->data == NULL) {
1297 	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
1298 	return ENOMEM;
1299     }
1300     ret = RSA_private_decrypt(ciphertext->length, ciphertext->data,
1301 			      cleartext->data,
1302 			      p->private_key.rsa,
1303 			      RSA_PKCS1_PADDING);
1304     if (ret <= 0) {
1305 	der_free_octet_string(cleartext);
1306 	hx509_set_error_string(context, 0, HX509_CRYPTO_RSA_PRIVATE_DECRYPT,
1307 			       "Failed to decrypt using private key: %d", ret);
1308 	return HX509_CRYPTO_RSA_PRIVATE_DECRYPT;
1309     }
1310     if (cleartext->length < (size_t)ret)
1311 	_hx509_abort("internal rsa decryption failure: ret > tosize");
1312 
1313     cleartext->length = ret;
1314 
1315     return 0;
1316 }
1317 
1318 
1319 int
hx509_parse_private_key(hx509_context context,const AlgorithmIdentifier * keyai,const void * data,size_t len,hx509_key_format_t format,hx509_private_key * private_key)1320 hx509_parse_private_key(hx509_context context,
1321 			 const AlgorithmIdentifier *keyai,
1322 			 const void *data,
1323 			 size_t len,
1324 			 hx509_key_format_t format,
1325 			 hx509_private_key *private_key)
1326 {
1327     struct hx509_private_key_ops *ops;
1328     int ret;
1329 
1330     *private_key = NULL;
1331 
1332     ops = hx509_find_private_alg(&keyai->algorithm);
1333     if (ops == NULL) {
1334 	hx509_clear_error_string(context);
1335 	return HX509_SIG_ALG_NO_SUPPORTED;
1336     }
1337 
1338     ret = hx509_private_key_init(private_key, ops, NULL);
1339     if (ret) {
1340 	hx509_set_error_string(context, 0, ret, "out of memory");
1341 	return ret;
1342     }
1343 
1344     ret = (*ops->import)(context, keyai, data, len, format, *private_key);
1345     if (ret)
1346 	hx509_private_key_free(private_key);
1347 
1348     return ret;
1349 }
1350 
1351 /*
1352  *
1353  */
1354 
1355 int
hx509_private_key2SPKI(hx509_context context,hx509_private_key private_key,SubjectPublicKeyInfo * spki)1356 hx509_private_key2SPKI(hx509_context context,
1357 			hx509_private_key private_key,
1358 			SubjectPublicKeyInfo *spki)
1359 {
1360     const struct hx509_private_key_ops *ops = private_key->ops;
1361     if (ops == NULL || ops->get_spki == NULL) {
1362 	hx509_set_error_string(context, 0, HX509_UNIMPLEMENTED_OPERATION,
1363 			       "Private key have no key2SPKI function");
1364 	return HX509_UNIMPLEMENTED_OPERATION;
1365     }
1366     return (*ops->get_spki)(context, private_key, spki);
1367 }
1368 
1369 int
_hx509_generate_private_key_init(hx509_context context,const heim_oid * oid,struct hx509_generate_private_context ** ctx)1370 _hx509_generate_private_key_init(hx509_context context,
1371 				 const heim_oid *oid,
1372 				 struct hx509_generate_private_context **ctx)
1373 {
1374     *ctx = NULL;
1375 
1376     if (der_heim_oid_cmp(oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) != 0) {
1377 	hx509_set_error_string(context, 0, EINVAL,
1378 			       "private key not an RSA key");
1379 	return EINVAL;
1380     }
1381 
1382     *ctx = calloc(1, sizeof(**ctx));
1383     if (*ctx == NULL) {
1384 	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
1385 	return ENOMEM;
1386     }
1387     (*ctx)->key_oid = oid;
1388 
1389     return 0;
1390 }
1391 
1392 int
_hx509_generate_private_key_is_ca(hx509_context context,struct hx509_generate_private_context * ctx)1393 _hx509_generate_private_key_is_ca(hx509_context context,
1394 				  struct hx509_generate_private_context *ctx)
1395 {
1396     ctx->isCA = 1;
1397     return 0;
1398 }
1399 
1400 int
_hx509_generate_private_key_bits(hx509_context context,struct hx509_generate_private_context * ctx,unsigned long bits)1401 _hx509_generate_private_key_bits(hx509_context context,
1402 				 struct hx509_generate_private_context *ctx,
1403 				 unsigned long bits)
1404 {
1405     ctx->num_bits = bits;
1406     return 0;
1407 }
1408 
1409 
1410 void
_hx509_generate_private_key_free(struct hx509_generate_private_context ** ctx)1411 _hx509_generate_private_key_free(struct hx509_generate_private_context **ctx)
1412 {
1413     free(*ctx);
1414     *ctx = NULL;
1415 }
1416 
1417 int
_hx509_generate_private_key(hx509_context context,struct hx509_generate_private_context * ctx,hx509_private_key * private_key)1418 _hx509_generate_private_key(hx509_context context,
1419 			    struct hx509_generate_private_context *ctx,
1420 			    hx509_private_key *private_key)
1421 {
1422     struct hx509_private_key_ops *ops;
1423     int ret;
1424 
1425     *private_key = NULL;
1426 
1427     ops = hx509_find_private_alg(ctx->key_oid);
1428     if (ops == NULL) {
1429 	hx509_clear_error_string(context);
1430 	return HX509_SIG_ALG_NO_SUPPORTED;
1431     }
1432 
1433     ret = hx509_private_key_init(private_key, ops, NULL);
1434     if (ret) {
1435 	hx509_set_error_string(context, 0, ret, "out of memory");
1436 	return ret;
1437     }
1438 
1439     ret = (*ops->generate_private_key)(context, ctx, *private_key);
1440     if (ret)
1441 	hx509_private_key_free(private_key);
1442 
1443     return ret;
1444 }
1445 
1446 /*
1447  *
1448  */
1449 
1450 const AlgorithmIdentifier *
hx509_signature_sha512(void)1451 hx509_signature_sha512(void)
1452 { return &_hx509_signature_sha512_data; }
1453 
1454 const AlgorithmIdentifier *
hx509_signature_sha384(void)1455 hx509_signature_sha384(void)
1456 { return &_hx509_signature_sha384_data; }
1457 
1458 const AlgorithmIdentifier *
hx509_signature_sha256(void)1459 hx509_signature_sha256(void)
1460 { return &_hx509_signature_sha256_data; }
1461 
1462 const AlgorithmIdentifier *
hx509_signature_sha1(void)1463 hx509_signature_sha1(void)
1464 { return &_hx509_signature_sha1_data; }
1465 
1466 const AlgorithmIdentifier *
hx509_signature_md5(void)1467 hx509_signature_md5(void)
1468 { return &_hx509_signature_md5_data; }
1469 
1470 const AlgorithmIdentifier *
hx509_signature_rsa_with_sha512(void)1471 hx509_signature_rsa_with_sha512(void)
1472 { return &_hx509_signature_rsa_with_sha512_data; }
1473 
1474 const AlgorithmIdentifier *
hx509_signature_rsa_with_sha384(void)1475 hx509_signature_rsa_with_sha384(void)
1476 { return &_hx509_signature_rsa_with_sha384_data; }
1477 
1478 const AlgorithmIdentifier *
hx509_signature_rsa_with_sha256(void)1479 hx509_signature_rsa_with_sha256(void)
1480 { return &_hx509_signature_rsa_with_sha256_data; }
1481 
1482 const AlgorithmIdentifier *
hx509_signature_rsa_with_sha1(void)1483 hx509_signature_rsa_with_sha1(void)
1484 { return &_hx509_signature_rsa_with_sha1_data; }
1485 
1486 const AlgorithmIdentifier *
hx509_signature_rsa_with_md5(void)1487 hx509_signature_rsa_with_md5(void)
1488 { return &_hx509_signature_rsa_with_md5_data; }
1489 
1490 const AlgorithmIdentifier *
hx509_signature_rsa(void)1491 hx509_signature_rsa(void)
1492 { return &_hx509_signature_rsa_data; }
1493 
1494 const AlgorithmIdentifier *
hx509_signature_rsa_pkcs1_x509(void)1495 hx509_signature_rsa_pkcs1_x509(void)
1496 { return &_hx509_signature_rsa_pkcs1_x509_data; }
1497 
1498 const AlgorithmIdentifier *
hx509_crypto_des_rsdi_ede3_cbc(void)1499 hx509_crypto_des_rsdi_ede3_cbc(void)
1500 { return &_hx509_des_rsdi_ede3_cbc_oid; }
1501 
1502 const AlgorithmIdentifier *
hx509_crypto_aes128_cbc(void)1503 hx509_crypto_aes128_cbc(void)
1504 { return &_hx509_crypto_aes128_cbc_data; }
1505 
1506 const AlgorithmIdentifier *
hx509_crypto_aes256_cbc(void)1507 hx509_crypto_aes256_cbc(void)
1508 { return &_hx509_crypto_aes256_cbc_data; }
1509 
1510 /*
1511  *
1512  */
1513 
1514 const AlgorithmIdentifier * _hx509_crypto_default_sig_alg =
1515     &_hx509_signature_rsa_with_sha256_data;
1516 const AlgorithmIdentifier * _hx509_crypto_default_digest_alg =
1517     &_hx509_signature_sha256_data;
1518 const AlgorithmIdentifier * _hx509_crypto_default_secret_alg =
1519     &_hx509_crypto_aes128_cbc_data;
1520 
1521 /*
1522  *
1523  */
1524 
1525 int
hx509_private_key_init(hx509_private_key * key,hx509_private_key_ops * ops,void * keydata)1526 hx509_private_key_init(hx509_private_key *key,
1527 			hx509_private_key_ops *ops,
1528 			void *keydata)
1529 {
1530     *key = calloc(1, sizeof(**key));
1531     if (*key == NULL)
1532 	return ENOMEM;
1533     (*key)->ref = 1;
1534     (*key)->ops = ops;
1535     (*key)->private_key.keydata = keydata;
1536     return 0;
1537 }
1538 
1539 hx509_private_key
_hx509_private_key_ref(hx509_private_key key)1540 _hx509_private_key_ref(hx509_private_key key)
1541 {
1542     if (key->ref == 0)
1543 	_hx509_abort("key refcount <= 0 on ref");
1544     key->ref++;
1545     if (key->ref == UINT_MAX)
1546 	_hx509_abort("key refcount == UINT_MAX on ref");
1547     return key;
1548 }
1549 
1550 const char *
_hx509_private_pem_name(hx509_private_key key)1551 _hx509_private_pem_name(hx509_private_key key)
1552 {
1553     return key->ops->pemtype;
1554 }
1555 
1556 int
hx509_private_key_free(hx509_private_key * key)1557 hx509_private_key_free(hx509_private_key *key)
1558 {
1559     if (key == NULL || *key == NULL)
1560 	return 0;
1561 
1562     if ((*key)->ref == 0)
1563 	_hx509_abort("key refcount == 0 on free");
1564     if (--(*key)->ref > 0)
1565 	return 0;
1566 
1567     if ((*key)->ops && der_heim_oid_cmp((*key)->ops->key_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) == 0) {
1568 	if ((*key)->private_key.rsa)
1569 	    RSA_free((*key)->private_key.rsa);
1570     } else if ((*key)->ops && der_heim_oid_cmp((*key)->ops->key_oid,
1571                                                ASN1_OID_ID_ECPUBLICKEY) == 0 &&
1572                (*key)->private_key.ecdsa != NULL) {
1573       _hx509_private_eckey_free((*key)->private_key.ecdsa);
1574     }
1575     (*key)->private_key.rsa = NULL;
1576     free(*key);
1577     *key = NULL;
1578     return 0;
1579 }
1580 
1581 void
hx509_private_key_assign_rsa(hx509_private_key key,void * ptr)1582 hx509_private_key_assign_rsa(hx509_private_key key, void *ptr)
1583 {
1584     if (key->private_key.rsa)
1585 	RSA_free(key->private_key.rsa);
1586     key->private_key.rsa = ptr;
1587     key->signature_alg = ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION;
1588     key->md = &pkcs1_rsa_sha1_alg;
1589 }
1590 
1591 int
_hx509_private_key_oid(hx509_context context,const hx509_private_key key,heim_oid * data)1592 _hx509_private_key_oid(hx509_context context,
1593 		       const hx509_private_key key,
1594 		       heim_oid *data)
1595 {
1596     int ret;
1597     ret = der_copy_oid(key->ops->key_oid, data);
1598     if (ret)
1599 	hx509_set_error_string(context, 0, ret, "malloc out of memory");
1600     return ret;
1601 }
1602 
1603 int
_hx509_private_key_exportable(hx509_private_key key)1604 _hx509_private_key_exportable(hx509_private_key key)
1605 {
1606     if (key->ops->export == NULL)
1607 	return 0;
1608     return 1;
1609 }
1610 
1611 BIGNUM *
_hx509_private_key_get_internal(hx509_context context,hx509_private_key key,const char * type)1612 _hx509_private_key_get_internal(hx509_context context,
1613 				hx509_private_key key,
1614 				const char *type)
1615 {
1616     if (key->ops->get_internal == NULL)
1617 	return NULL;
1618     return (*key->ops->get_internal)(context, key, type);
1619 }
1620 
1621 int
_hx509_private_key_export(hx509_context context,const hx509_private_key key,hx509_key_format_t format,heim_octet_string * data)1622 _hx509_private_key_export(hx509_context context,
1623 			  const hx509_private_key key,
1624 			  hx509_key_format_t format,
1625 			  heim_octet_string *data)
1626 {
1627     if (key->ops->export == NULL) {
1628 	hx509_clear_error_string(context);
1629 	return HX509_UNIMPLEMENTED_OPERATION;
1630     }
1631     return (*key->ops->export)(context, key, format, data);
1632 }
1633 
1634 /*
1635  *
1636  */
1637 
1638 struct hx509cipher {
1639     const char *name;
1640     int flags;
1641 #define CIPHER_WEAK 1
1642     const heim_oid *oid;
1643     const AlgorithmIdentifier *(*ai_func)(void);
1644     const EVP_CIPHER *(*evp_func)(void);
1645     int (*get_params)(hx509_context, const hx509_crypto,
1646 		      const heim_octet_string *, heim_octet_string *);
1647     int (*set_params)(hx509_context, const heim_octet_string *,
1648 		      hx509_crypto, heim_octet_string *);
1649 };
1650 
1651 struct hx509_crypto_data {
1652     char *name;
1653     int flags;
1654 #define ALLOW_WEAK 	1
1655 
1656 #define PADDING_NONE	2
1657 #define PADDING_PKCS7	4
1658 #define PADDING_FLAGS	(2|4)
1659     const struct hx509cipher *cipher;
1660     const EVP_CIPHER *c;
1661     heim_octet_string key;
1662     heim_oid oid;
1663     void *param;
1664 };
1665 
1666 /*
1667  *
1668  */
1669 
1670 static unsigned private_rc2_40_oid_data[] = { 127, 1 };
1671 
1672 static heim_oid asn1_oid_private_rc2_40 =
1673     { 2, private_rc2_40_oid_data };
1674 
1675 /*
1676  *
1677  */
1678 
1679 static int
CMSCBCParam_get(hx509_context context,const hx509_crypto crypto,const heim_octet_string * ivec,heim_octet_string * param)1680 CMSCBCParam_get(hx509_context context, const hx509_crypto crypto,
1681 		 const heim_octet_string *ivec, heim_octet_string *param)
1682 {
1683     size_t size;
1684     int ret;
1685 
1686     assert(crypto->param == NULL);
1687     if (ivec == NULL)
1688 	return 0;
1689 
1690     ASN1_MALLOC_ENCODE(CMSCBCParameter, param->data, param->length,
1691 		       ivec, &size, ret);
1692     if (ret == 0 && size != param->length)
1693 	_hx509_abort("Internal asn1 encoder failure");
1694     if (ret)
1695 	hx509_clear_error_string(context);
1696     return ret;
1697 }
1698 
1699 static int
CMSCBCParam_set(hx509_context context,const heim_octet_string * param,hx509_crypto crypto,heim_octet_string * ivec)1700 CMSCBCParam_set(hx509_context context, const heim_octet_string *param,
1701 		hx509_crypto crypto, heim_octet_string *ivec)
1702 {
1703     int ret;
1704     if (ivec == NULL)
1705 	return 0;
1706 
1707     ret = decode_CMSCBCParameter(param->data, param->length, ivec, NULL);
1708     if (ret)
1709 	hx509_clear_error_string(context);
1710 
1711     return ret;
1712 }
1713 
1714 struct _RC2_params {
1715     int maximum_effective_key;
1716 };
1717 
1718 static int
CMSRC2CBCParam_get(hx509_context context,const hx509_crypto crypto,const heim_octet_string * ivec,heim_octet_string * param)1719 CMSRC2CBCParam_get(hx509_context context, const hx509_crypto crypto,
1720 		   const heim_octet_string *ivec, heim_octet_string *param)
1721 {
1722     CMSRC2CBCParameter rc2params;
1723     const struct _RC2_params *p = crypto->param;
1724     int maximum_effective_key = 128;
1725     size_t size;
1726     int ret;
1727 
1728     memset(&rc2params, 0, sizeof(rc2params));
1729 
1730     if (p)
1731 	maximum_effective_key = p->maximum_effective_key;
1732 
1733     switch(maximum_effective_key) {
1734     case 40:
1735 	rc2params.rc2ParameterVersion = 160;
1736 	break;
1737     case 64:
1738 	rc2params.rc2ParameterVersion = 120;
1739 	break;
1740     case 128:
1741 	rc2params.rc2ParameterVersion = 58;
1742 	break;
1743     }
1744     rc2params.iv = *ivec;
1745 
1746     ASN1_MALLOC_ENCODE(CMSRC2CBCParameter, param->data, param->length,
1747 		       &rc2params, &size, ret);
1748     if (ret == 0 && size != param->length)
1749 	_hx509_abort("Internal asn1 encoder failure");
1750 
1751     return ret;
1752 }
1753 
1754 static int
CMSRC2CBCParam_set(hx509_context context,const heim_octet_string * param,hx509_crypto crypto,heim_octet_string * ivec)1755 CMSRC2CBCParam_set(hx509_context context, const heim_octet_string *param,
1756 		   hx509_crypto crypto, heim_octet_string *ivec)
1757 {
1758     CMSRC2CBCParameter rc2param;
1759     struct _RC2_params *p;
1760     size_t size;
1761     int ret;
1762 
1763     ret = decode_CMSRC2CBCParameter(param->data, param->length,
1764 				    &rc2param, &size);
1765     if (ret) {
1766 	hx509_clear_error_string(context);
1767 	return ret;
1768     }
1769 
1770     p = calloc(1, sizeof(*p));
1771     if (p == NULL) {
1772 	free_CMSRC2CBCParameter(&rc2param);
1773 	hx509_clear_error_string(context);
1774 	return ENOMEM;
1775     }
1776     switch(rc2param.rc2ParameterVersion) {
1777     case 160:
1778 	crypto->c = EVP_rc2_40_cbc();
1779 	p->maximum_effective_key = 40;
1780 	break;
1781     case 120:
1782 	crypto->c = EVP_rc2_64_cbc();
1783 	p->maximum_effective_key = 64;
1784 	break;
1785     case 58:
1786 	crypto->c = EVP_rc2_cbc();
1787 	p->maximum_effective_key = 128;
1788 	break;
1789     default:
1790 	free(p);
1791 	free_CMSRC2CBCParameter(&rc2param);
1792 	return HX509_CRYPTO_SIG_INVALID_FORMAT;
1793     }
1794     if (ivec)
1795 	ret = der_copy_octet_string(&rc2param.iv, ivec);
1796     free_CMSRC2CBCParameter(&rc2param);
1797     if (ret) {
1798 	free(p);
1799 	hx509_clear_error_string(context);
1800     } else
1801 	crypto->param = p;
1802 
1803     return ret;
1804 }
1805 
1806 /*
1807  *
1808  */
1809 
1810 static const struct hx509cipher ciphers[] = {
1811     {
1812 	"rc2-cbc",
1813 	CIPHER_WEAK,
1814 	ASN1_OID_ID_PKCS3_RC2_CBC,
1815 	NULL,
1816 	EVP_rc2_cbc,
1817 	CMSRC2CBCParam_get,
1818 	CMSRC2CBCParam_set
1819     },
1820     {
1821 	"rc2-cbc",
1822 	CIPHER_WEAK,
1823 	ASN1_OID_ID_RSADSI_RC2_CBC,
1824 	NULL,
1825 	EVP_rc2_cbc,
1826 	CMSRC2CBCParam_get,
1827 	CMSRC2CBCParam_set
1828     },
1829     {
1830 	"rc2-40-cbc",
1831 	CIPHER_WEAK,
1832 	&asn1_oid_private_rc2_40,
1833 	NULL,
1834 	EVP_rc2_40_cbc,
1835 	CMSRC2CBCParam_get,
1836 	CMSRC2CBCParam_set
1837     },
1838     {
1839 	"des-ede3-cbc",
1840 	0,
1841 	ASN1_OID_ID_PKCS3_DES_EDE3_CBC,
1842 	NULL,
1843 	EVP_des_ede3_cbc,
1844 	CMSCBCParam_get,
1845 	CMSCBCParam_set
1846     },
1847     {
1848 	"des-ede3-cbc",
1849 	0,
1850 	ASN1_OID_ID_RSADSI_DES_EDE3_CBC,
1851 	hx509_crypto_des_rsdi_ede3_cbc,
1852 	EVP_des_ede3_cbc,
1853 	CMSCBCParam_get,
1854 	CMSCBCParam_set
1855     },
1856     {
1857 	"aes-128-cbc",
1858 	0,
1859 	ASN1_OID_ID_AES_128_CBC,
1860 	hx509_crypto_aes128_cbc,
1861 	EVP_aes_128_cbc,
1862 	CMSCBCParam_get,
1863 	CMSCBCParam_set
1864     },
1865     {
1866 	"aes-192-cbc",
1867 	0,
1868 	ASN1_OID_ID_AES_192_CBC,
1869 	NULL,
1870 	EVP_aes_192_cbc,
1871 	CMSCBCParam_get,
1872 	CMSCBCParam_set
1873     },
1874     {
1875 	"aes-256-cbc",
1876 	0,
1877 	ASN1_OID_ID_AES_256_CBC,
1878 	hx509_crypto_aes256_cbc,
1879 	EVP_aes_256_cbc,
1880 	CMSCBCParam_get,
1881 	CMSCBCParam_set
1882     }
1883 };
1884 
1885 static const struct hx509cipher *
find_cipher_by_oid(const heim_oid * oid)1886 find_cipher_by_oid(const heim_oid *oid)
1887 {
1888     size_t i;
1889 
1890     for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++)
1891 	if (der_heim_oid_cmp(oid, ciphers[i].oid) == 0)
1892 	    return &ciphers[i];
1893 
1894     return NULL;
1895 }
1896 
1897 static const struct hx509cipher *
find_cipher_by_name(const char * name)1898 find_cipher_by_name(const char *name)
1899 {
1900     size_t i;
1901 
1902     for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++)
1903 	if (strcasecmp(name, ciphers[i].name) == 0)
1904 	    return &ciphers[i];
1905 
1906     return NULL;
1907 }
1908 
1909 
1910 const heim_oid *
hx509_crypto_enctype_by_name(const char * name)1911 hx509_crypto_enctype_by_name(const char *name)
1912 {
1913     const struct hx509cipher *cipher;
1914 
1915     cipher = find_cipher_by_name(name);
1916     if (cipher == NULL)
1917 	return NULL;
1918     return cipher->oid;
1919 }
1920 
1921 int
hx509_crypto_init(hx509_context context,const char * provider,const heim_oid * enctype,hx509_crypto * crypto)1922 hx509_crypto_init(hx509_context context,
1923 		  const char *provider,
1924 		  const heim_oid *enctype,
1925 		  hx509_crypto *crypto)
1926 {
1927     const struct hx509cipher *cipher;
1928 
1929     *crypto = NULL;
1930 
1931     cipher = find_cipher_by_oid(enctype);
1932     if (cipher == NULL) {
1933 	hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
1934 			       "Algorithm not supported");
1935 	return HX509_ALG_NOT_SUPP;
1936     }
1937 
1938     *crypto = calloc(1, sizeof(**crypto));
1939     if (*crypto == NULL) {
1940 	hx509_clear_error_string(context);
1941 	return ENOMEM;
1942     }
1943 
1944     (*crypto)->flags = PADDING_PKCS7;
1945     (*crypto)->cipher = cipher;
1946     (*crypto)->c = (*cipher->evp_func)();
1947 
1948     if (der_copy_oid(enctype, &(*crypto)->oid)) {
1949 	hx509_crypto_destroy(*crypto);
1950 	*crypto = NULL;
1951 	hx509_clear_error_string(context);
1952 	return ENOMEM;
1953     }
1954 
1955     return 0;
1956 }
1957 
1958 const char *
hx509_crypto_provider(hx509_crypto crypto)1959 hx509_crypto_provider(hx509_crypto crypto)
1960 {
1961     return "unknown";
1962 }
1963 
1964 void
hx509_crypto_destroy(hx509_crypto crypto)1965 hx509_crypto_destroy(hx509_crypto crypto)
1966 {
1967     if (crypto->name)
1968 	free(crypto->name);
1969     if (crypto->key.data)
1970 	free(crypto->key.data);
1971     if (crypto->param)
1972 	free(crypto->param);
1973     der_free_oid(&crypto->oid);
1974     memset(crypto, 0, sizeof(*crypto));
1975     free(crypto);
1976 }
1977 
1978 int
hx509_crypto_set_key_name(hx509_crypto crypto,const char * name)1979 hx509_crypto_set_key_name(hx509_crypto crypto, const char *name)
1980 {
1981     return 0;
1982 }
1983 
1984 void
hx509_crypto_allow_weak(hx509_crypto crypto)1985 hx509_crypto_allow_weak(hx509_crypto crypto)
1986 {
1987     crypto->flags |= ALLOW_WEAK;
1988 }
1989 
1990 void
hx509_crypto_set_padding(hx509_crypto crypto,int padding_type)1991 hx509_crypto_set_padding(hx509_crypto crypto, int padding_type)
1992 {
1993     switch (padding_type) {
1994     case HX509_CRYPTO_PADDING_PKCS7:
1995 	crypto->flags &= ~PADDING_FLAGS;
1996 	crypto->flags |= PADDING_PKCS7;
1997 	break;
1998     case HX509_CRYPTO_PADDING_NONE:
1999 	crypto->flags &= ~PADDING_FLAGS;
2000 	crypto->flags |= PADDING_NONE;
2001 	break;
2002     default:
2003 	_hx509_abort("Invalid padding");
2004     }
2005 }
2006 
2007 int
hx509_crypto_set_key_data(hx509_crypto crypto,const void * data,size_t length)2008 hx509_crypto_set_key_data(hx509_crypto crypto, const void *data, size_t length)
2009 {
2010     if (EVP_CIPHER_key_length(crypto->c) > (int)length)
2011 	return HX509_CRYPTO_INTERNAL_ERROR;
2012 
2013     if (crypto->key.data) {
2014 	free(crypto->key.data);
2015 	crypto->key.data = NULL;
2016 	crypto->key.length = 0;
2017     }
2018     crypto->key.data = malloc(length);
2019     if (crypto->key.data == NULL)
2020 	return ENOMEM;
2021     memcpy(crypto->key.data, data, length);
2022     crypto->key.length = length;
2023 
2024     return 0;
2025 }
2026 
2027 int
hx509_crypto_set_random_key(hx509_crypto crypto,heim_octet_string * key)2028 hx509_crypto_set_random_key(hx509_crypto crypto, heim_octet_string *key)
2029 {
2030     if (crypto->key.data) {
2031 	free(crypto->key.data);
2032 	crypto->key.length = 0;
2033     }
2034 
2035     crypto->key.length = EVP_CIPHER_key_length(crypto->c);
2036     crypto->key.data = malloc(crypto->key.length);
2037     if (crypto->key.data == NULL) {
2038 	crypto->key.length = 0;
2039 	return ENOMEM;
2040     }
2041     if (RAND_bytes(crypto->key.data, crypto->key.length) <= 0) {
2042 	free(crypto->key.data);
2043 	crypto->key.data = NULL;
2044 	crypto->key.length = 0;
2045 	return HX509_CRYPTO_INTERNAL_ERROR;
2046     }
2047     if (key)
2048 	return der_copy_octet_string(&crypto->key, key);
2049     else
2050 	return 0;
2051 }
2052 
2053 int
hx509_crypto_set_params(hx509_context context,hx509_crypto crypto,const heim_octet_string * param,heim_octet_string * ivec)2054 hx509_crypto_set_params(hx509_context context,
2055 			hx509_crypto crypto,
2056 			const heim_octet_string *param,
2057 			heim_octet_string *ivec)
2058 {
2059     return (*crypto->cipher->set_params)(context, param, crypto, ivec);
2060 }
2061 
2062 int
hx509_crypto_get_params(hx509_context context,hx509_crypto crypto,const heim_octet_string * ivec,heim_octet_string * param)2063 hx509_crypto_get_params(hx509_context context,
2064 			hx509_crypto crypto,
2065 			const heim_octet_string *ivec,
2066 			heim_octet_string *param)
2067 {
2068     return (*crypto->cipher->get_params)(context, crypto, ivec, param);
2069 }
2070 
2071 int
hx509_crypto_random_iv(hx509_crypto crypto,heim_octet_string * ivec)2072 hx509_crypto_random_iv(hx509_crypto crypto, heim_octet_string *ivec)
2073 {
2074     ivec->length = EVP_CIPHER_iv_length(crypto->c);
2075     ivec->data = malloc(ivec->length);
2076     if (ivec->data == NULL) {
2077 	ivec->length = 0;
2078 	return ENOMEM;
2079     }
2080 
2081     if (RAND_bytes(ivec->data, ivec->length) <= 0) {
2082 	free(ivec->data);
2083 	ivec->data = NULL;
2084 	ivec->length = 0;
2085 	return HX509_CRYPTO_INTERNAL_ERROR;
2086     }
2087     return 0;
2088 }
2089 
2090 int
hx509_crypto_encrypt(hx509_crypto crypto,const void * data,const size_t length,const heim_octet_string * ivec,heim_octet_string ** ciphertext)2091 hx509_crypto_encrypt(hx509_crypto crypto,
2092 		     const void *data,
2093 		     const size_t length,
2094 		     const heim_octet_string *ivec,
2095 		     heim_octet_string **ciphertext)
2096 {
2097     EVP_CIPHER_CTX *evp;
2098     size_t padsize, bsize;
2099     int ret;
2100 
2101 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
2102     EVP_CIPHER_CTX ectx;
2103     evp = &ectx;
2104     EVP_CIPHER_CTX_init(evp);
2105 #else
2106     evp = EVP_CIPHER_CTX_new();
2107 #endif
2108 
2109     *ciphertext = NULL;
2110 
2111     if ((crypto->cipher->flags & CIPHER_WEAK) &&
2112 	(crypto->flags & ALLOW_WEAK) == 0)
2113 	return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
2114 
2115     assert(EVP_CIPHER_iv_length(crypto->c) == (int)ivec->length);
2116 
2117 
2118     ret = EVP_CipherInit_ex(evp, crypto->c, NULL,
2119 			    crypto->key.data, ivec->data, 1);
2120     if (ret != 1) {
2121 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
2122 	EVP_CIPHER_CTX_cleanup(evp);
2123 #else
2124 	EVP_CIPHER_CTX_free(evp);
2125 #endif
2126 	ret = HX509_CRYPTO_INTERNAL_ERROR;
2127 	goto out;
2128     }
2129 
2130     *ciphertext = calloc(1, sizeof(**ciphertext));
2131     if (*ciphertext == NULL) {
2132 	ret = ENOMEM;
2133 	goto out;
2134     }
2135 
2136     assert(crypto->flags & PADDING_FLAGS);
2137 
2138     bsize = EVP_CIPHER_block_size(crypto->c);
2139     padsize = 0;
2140 
2141     if (crypto->flags & PADDING_NONE) {
2142 	if (bsize != 1 && (length % bsize) != 0)
2143 	    return HX509_CMS_PADDING_ERROR;
2144     } else if (crypto->flags & PADDING_PKCS7) {
2145 	if (bsize != 1)
2146 	    padsize = bsize - (length % bsize);
2147     }
2148 
2149     (*ciphertext)->length = length + padsize;
2150     (*ciphertext)->data = malloc(length + padsize);
2151     if ((*ciphertext)->data == NULL) {
2152 	ret = ENOMEM;
2153 	goto out;
2154     }
2155 
2156     memcpy((*ciphertext)->data, data, length);
2157     if (padsize) {
2158 	size_t i;
2159 	unsigned char *p = (*ciphertext)->data;
2160 	p += length;
2161 	for (i = 0; i < padsize; i++)
2162 	    *p++ = padsize;
2163     }
2164 
2165     ret = EVP_Cipher(evp, (*ciphertext)->data,
2166 		     (*ciphertext)->data,
2167 		     length + padsize);
2168     if (ret != 1) {
2169 	ret = HX509_CRYPTO_INTERNAL_ERROR;
2170 	goto out;
2171     }
2172     ret = 0;
2173 
2174  out:
2175     if (ret) {
2176 	if (*ciphertext) {
2177 	    if ((*ciphertext)->data) {
2178 		free((*ciphertext)->data);
2179 	    }
2180 	    free(*ciphertext);
2181 	    *ciphertext = NULL;
2182 	}
2183     }
2184 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
2185     EVP_CIPHER_CTX_cleanup(evp);
2186 #else
2187     EVP_CIPHER_CTX_free(evp);
2188 #endif
2189 
2190     return ret;
2191 }
2192 
2193 int
hx509_crypto_decrypt(hx509_crypto crypto,const void * data,const size_t length,heim_octet_string * ivec,heim_octet_string * clear)2194 hx509_crypto_decrypt(hx509_crypto crypto,
2195 		     const void *data,
2196 		     const size_t length,
2197 		     heim_octet_string *ivec,
2198 		     heim_octet_string *clear)
2199 {
2200     EVP_CIPHER_CTX *evp;
2201     void *idata = NULL;
2202     int ret;
2203 
2204     clear->data = NULL;
2205     clear->length = 0;
2206 
2207     if ((crypto->cipher->flags & CIPHER_WEAK) &&
2208 	(crypto->flags & ALLOW_WEAK) == 0)
2209 	return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
2210 
2211     if (ivec && EVP_CIPHER_iv_length(crypto->c) < (int)ivec->length)
2212 	return HX509_CRYPTO_INTERNAL_ERROR;
2213 
2214     if (crypto->key.data == NULL)
2215 	return HX509_CRYPTO_INTERNAL_ERROR;
2216 
2217     if (ivec)
2218 	idata = ivec->data;
2219 
2220 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
2221     EVP_CIPHER_CTX ectx;
2222     evp = &ectx;
2223     EVP_CIPHER_CTX_init(evp);
2224 #else
2225     evp = EVP_CIPHER_CTX_new();
2226 #endif
2227 
2228     ret = EVP_CipherInit_ex(evp, crypto->c, NULL,
2229 			    crypto->key.data, idata, 0);
2230     if (ret != 1) {
2231 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
2232 	EVP_CIPHER_CTX_cleanup(evp);
2233 #else
2234 	EVP_CIPHER_CTX_free(evp);
2235 #endif
2236 	return HX509_CRYPTO_INTERNAL_ERROR;
2237     }
2238 
2239     clear->length = length;
2240     clear->data = malloc(length);
2241     if (clear->data == NULL) {
2242 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
2243 	EVP_CIPHER_CTX_cleanup(evp);
2244 #else
2245 	EVP_CIPHER_CTX_free(evp);
2246 #endif
2247 	clear->length = 0;
2248 	return ENOMEM;
2249     }
2250 
2251     if (EVP_Cipher(evp, clear->data, data, length) != 1) {
2252 	return HX509_CRYPTO_INTERNAL_ERROR;
2253     }
2254 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
2255     EVP_CIPHER_CTX_cleanup(evp);
2256 #else
2257     EVP_CIPHER_CTX_free(evp);
2258 #endif
2259 
2260     if ((crypto->flags & PADDING_PKCS7) && EVP_CIPHER_block_size(crypto->c) > 1) {
2261 	int padsize;
2262 	unsigned char *p;
2263 	int j, bsize = EVP_CIPHER_block_size(crypto->c);
2264 
2265 	if ((int)clear->length < bsize) {
2266 	    ret = HX509_CMS_PADDING_ERROR;
2267 	    goto out;
2268 	}
2269 
2270 	p = clear->data;
2271 	p += clear->length - 1;
2272 	padsize = *p;
2273 	if (padsize > bsize) {
2274 	    ret = HX509_CMS_PADDING_ERROR;
2275 	    goto out;
2276 	}
2277 	clear->length -= padsize;
2278 	for (j = 0; j < padsize; j++) {
2279 	    if (*p-- != padsize) {
2280 		ret = HX509_CMS_PADDING_ERROR;
2281 		goto out;
2282 	    }
2283 	}
2284     }
2285 
2286     return 0;
2287 
2288  out:
2289     if (clear->data)
2290 	free(clear->data);
2291     clear->data = NULL;
2292     clear->length = 0;
2293     return ret;
2294 }
2295 
2296 typedef int (*PBE_string2key_func)(hx509_context,
2297 				   const char *,
2298 				   const heim_octet_string *,
2299 				   hx509_crypto *, heim_octet_string *,
2300 				   heim_octet_string *,
2301 				   const heim_oid *, const EVP_MD *);
2302 
2303 static int
PBE_string2key(hx509_context context,const char * password,const heim_octet_string * parameters,hx509_crypto * crypto,heim_octet_string * key,heim_octet_string * iv,const heim_oid * enc_oid,const EVP_MD * md)2304 PBE_string2key(hx509_context context,
2305 	       const char *password,
2306 	       const heim_octet_string *parameters,
2307 	       hx509_crypto *crypto,
2308 	       heim_octet_string *key, heim_octet_string *iv,
2309 	       const heim_oid *enc_oid,
2310 	       const EVP_MD *md)
2311 {
2312     PKCS12_PBEParams p12params;
2313     int passwordlen;
2314     hx509_crypto c;
2315     int iter, saltlen, ret;
2316     unsigned char *salt;
2317 
2318     passwordlen = password ? strlen(password) : 0;
2319 
2320     if (parameters == NULL)
2321  	return HX509_ALG_NOT_SUPP;
2322 
2323     ret = decode_PKCS12_PBEParams(parameters->data,
2324 				  parameters->length,
2325 				  &p12params, NULL);
2326     if (ret)
2327 	goto out;
2328 
2329     if (p12params.iterations)
2330 	iter = *p12params.iterations;
2331     else
2332 	iter = 1;
2333     salt = p12params.salt.data;
2334     saltlen = p12params.salt.length;
2335 
2336     if (!PKCS12_key_gen (password, passwordlen, salt, saltlen,
2337 			 PKCS12_KEY_ID, iter, key->length, key->data, md)) {
2338 	ret = HX509_CRYPTO_INTERNAL_ERROR;
2339 	goto out;
2340     }
2341 
2342     if (!PKCS12_key_gen (password, passwordlen, salt, saltlen,
2343 			 PKCS12_IV_ID, iter, iv->length, iv->data, md)) {
2344 	ret = HX509_CRYPTO_INTERNAL_ERROR;
2345 	goto out;
2346     }
2347 
2348     ret = hx509_crypto_init(context, NULL, enc_oid, &c);
2349     if (ret)
2350 	goto out;
2351 
2352     hx509_crypto_allow_weak(c);
2353 
2354     ret = hx509_crypto_set_key_data(c, key->data, key->length);
2355     if (ret) {
2356 	hx509_crypto_destroy(c);
2357 	goto out;
2358     }
2359 
2360     *crypto = c;
2361 out:
2362     free_PKCS12_PBEParams(&p12params);
2363     return ret;
2364 }
2365 
2366 static const heim_oid *
find_string2key(const heim_oid * oid,const EVP_CIPHER ** c,const EVP_MD ** md,PBE_string2key_func * s2k)2367 find_string2key(const heim_oid *oid,
2368 		const EVP_CIPHER **c,
2369 		const EVP_MD **md,
2370 		PBE_string2key_func *s2k)
2371 {
2372     if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND40BITRC2_CBC) == 0) {
2373 	*c = EVP_rc2_40_cbc();
2374         if (*c == NULL)
2375             return NULL;
2376 	*md = EVP_sha1();
2377         if (*md == NULL)
2378             return NULL;
2379 	*s2k = PBE_string2key;
2380 	return &asn1_oid_private_rc2_40;
2381     } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND128BITRC2_CBC) == 0) {
2382 	*c = EVP_rc2_cbc();
2383         if (*c == NULL)
2384             return NULL;
2385 	*md = EVP_sha1();
2386         if (*md == NULL)
2387             return NULL;
2388 	*s2k = PBE_string2key;
2389 	return ASN1_OID_ID_PKCS3_RC2_CBC;
2390 #if 0
2391     } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND40BITRC4) == 0) {
2392 	*c = EVP_rc4_40();
2393         if (*c == NULL)
2394             return NULL;
2395 	*md = EVP_sha1();
2396         if (*md == NULL)
2397             return NULL;
2398 	*s2k = PBE_string2key;
2399 	return NULL;
2400     } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND128BITRC4) == 0) {
2401 	*c = EVP_rc4();
2402         if (*c == NULL)
2403             return NULL;
2404 	*md = EVP_sha1();
2405         if (*md == NULL)
2406             return NULL;
2407 	*s2k = PBE_string2key;
2408 	return ASN1_OID_ID_PKCS3_RC4;
2409 #endif
2410     } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND3_KEYTRIPLEDES_CBC) == 0) {
2411 	*c = EVP_des_ede3_cbc();
2412         if (*c == NULL)
2413             return NULL;
2414 	*md = EVP_sha1();
2415         if (*md == NULL)
2416             return NULL;
2417 	*s2k = PBE_string2key;
2418 	return ASN1_OID_ID_PKCS3_DES_EDE3_CBC;
2419     }
2420 
2421     return NULL;
2422 }
2423 
2424 /*
2425  *
2426  */
2427 
2428 int
_hx509_pbe_encrypt(hx509_context context,hx509_lock lock,const AlgorithmIdentifier * ai,const heim_octet_string * content,heim_octet_string * econtent)2429 _hx509_pbe_encrypt(hx509_context context,
2430 		   hx509_lock lock,
2431 		   const AlgorithmIdentifier *ai,
2432 		   const heim_octet_string *content,
2433 		   heim_octet_string *econtent)
2434 {
2435     hx509_clear_error_string(context);
2436     return EINVAL;
2437 }
2438 
2439 /*
2440  *
2441  */
2442 
2443 int
_hx509_pbe_decrypt(hx509_context context,hx509_lock lock,const AlgorithmIdentifier * ai,const heim_octet_string * econtent,heim_octet_string * content)2444 _hx509_pbe_decrypt(hx509_context context,
2445 		   hx509_lock lock,
2446 		   const AlgorithmIdentifier *ai,
2447 		   const heim_octet_string *econtent,
2448 		   heim_octet_string *content)
2449 {
2450     const struct _hx509_password *pw;
2451     heim_octet_string key, iv;
2452     const heim_oid *enc_oid;
2453     const EVP_CIPHER *c;
2454     const EVP_MD *md;
2455     PBE_string2key_func s2k;
2456     int ret = 0;
2457     size_t i;
2458 
2459     memset(&key, 0, sizeof(key));
2460     memset(&iv, 0, sizeof(iv));
2461 
2462     memset(content, 0, sizeof(*content));
2463 
2464     enc_oid = find_string2key(&ai->algorithm, &c, &md, &s2k);
2465     if (enc_oid == NULL) {
2466 	hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
2467 			       "String to key algorithm not supported");
2468 	ret = HX509_ALG_NOT_SUPP;
2469 	goto out;
2470     }
2471 
2472     key.length = EVP_CIPHER_key_length(c);
2473     key.data = malloc(key.length);
2474     if (key.data == NULL) {
2475 	ret = ENOMEM;
2476 	hx509_clear_error_string(context);
2477 	goto out;
2478     }
2479 
2480     iv.length = EVP_CIPHER_iv_length(c);
2481     iv.data = malloc(iv.length);
2482     if (iv.data == NULL) {
2483 	ret = ENOMEM;
2484 	hx509_clear_error_string(context);
2485 	goto out;
2486     }
2487 
2488     pw = _hx509_lock_get_passwords(lock);
2489 
2490     ret = HX509_CRYPTO_INTERNAL_ERROR;
2491     for (i = 0; i < pw->len + 1; i++) {
2492 	hx509_crypto crypto;
2493 	const char *password;
2494 
2495 	if (i < pw->len)
2496 	    password = pw->val[i];
2497 	else if (i < pw->len + 1)
2498 	    password = "";
2499 	else
2500 	    password = NULL;
2501 
2502 	ret = (*s2k)(context, password, ai->parameters, &crypto,
2503 		     &key, &iv, enc_oid, md);
2504 	if (ret)
2505 	    goto out;
2506 
2507 	ret = hx509_crypto_decrypt(crypto,
2508 				   econtent->data,
2509 				   econtent->length,
2510 				   &iv,
2511 				   content);
2512 	hx509_crypto_destroy(crypto);
2513 	if (ret == 0)
2514 	    goto out;
2515 
2516     }
2517 out:
2518     if (key.data)
2519 	der_free_octet_string(&key);
2520     if (iv.data)
2521 	der_free_octet_string(&iv);
2522     return ret;
2523 }
2524 
2525 /*
2526  *
2527  */
2528 
2529 
2530 static int
match_keys_rsa(hx509_cert c,hx509_private_key private_key)2531 match_keys_rsa(hx509_cert c, hx509_private_key private_key)
2532 {
2533     const Certificate *cert;
2534     const SubjectPublicKeyInfo *spi;
2535     RSAPublicKey pk;
2536     RSA *rsa;
2537     BIGNUM *n, *e;
2538     const BIGNUM *d, *p, *q;
2539     const BIGNUM *dmp1, *dmq1, *iqmp;
2540     size_t size;
2541     int ret;
2542 
2543     if (private_key->private_key.rsa == NULL)
2544 	return 0;
2545 
2546     rsa = private_key->private_key.rsa;
2547 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
2548     d = rsa->d;
2549     p = rsa->p;
2550     q = rsa->q;
2551 #else
2552     RSA_get0_key(rsa, NULL, NULL, &d);
2553     RSA_get0_factors(rsa, &p, &q);
2554 #endif
2555 
2556     if (d == NULL || p == NULL || q == NULL)
2557 	return 0;
2558 
2559     cert = _hx509_get_cert(c);
2560     spi = &cert->tbsCertificate.subjectPublicKeyInfo;
2561 
2562     rsa = RSA_new();
2563     if (rsa == NULL)
2564 	return 0;
2565 
2566     ret = decode_RSAPublicKey(spi->subjectPublicKey.data,
2567 			      spi->subjectPublicKey.length / 8,
2568 			      &pk, &size);
2569     if (ret) {
2570 	RSA_free(rsa);
2571 	return 0;
2572     }
2573     n = heim_int2BN(&pk.modulus);
2574     e = heim_int2BN(&pk.publicExponent);
2575 
2576     free_RSAPublicKey(&pk);
2577 
2578 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
2579     d = private_key->private_key.rsa->d;
2580     p = private_key->private_key.rsa->p;
2581     q = private_key->private_key.rsa->q;
2582     dmp1 = private_key->private_key.rsa->dmp1;
2583     dmq1 = private_key->private_key.rsa->dmq1;
2584     iqmp = private_key->private_key.rsa->iqmp;
2585 #else
2586     RSA_get0_key(private_key->private_key.rsa, NULL, NULL, &d);
2587     RSA_get0_factors(private_key->private_key.rsa, &p, &q);
2588     RSA_get0_crt_params(private_key->private_key.rsa, &dmp1, &dmq1, &iqmp);
2589 #endif
2590 
2591     BIGNUM *c_n = n;
2592     BIGNUM *c_e = e;
2593     BIGNUM *c_d = BN_dup(d);
2594     BIGNUM *c_p = BN_dup(p);
2595     BIGNUM *c_q = BN_dup(q);
2596     BIGNUM *c_dmp1 = BN_dup(dmp1);
2597     BIGNUM *c_dmq1 = BN_dup(dmq1);
2598     BIGNUM *c_iqmp = BN_dup(iqmp);
2599 
2600     if (c_n == NULL || c_e == NULL || c_d == NULL || c_p == NULL ||
2601 	c_q == NULL || c_dmp1 == NULL || c_dmq1 == NULL) {
2602 	RSA_free(rsa);
2603 	return 0;
2604     }
2605 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
2606     rsa->n = n;
2607     rsa->e = e;
2608     rsa->d = c_d;
2609     rsa->p = c_p;
2610     rsa->q = c_q;
2611     rsa->dmp1 = c_dmp1;
2612     rsa->dmq1 = c_dmq1;
2613     rsa->iqmp = c_iqmp;
2614 #else
2615     RSA_set0_key(rsa, n, e, c_d);
2616     RSA_set0_factors(rsa, c_p, c_q);
2617     RSA_set0_crt_params(rsa, c_dmp1, c_dmq1, c_iqmp);
2618 #endif
2619 
2620     ret = RSA_check_key(rsa);
2621     RSA_free(rsa);
2622 
2623     return ret == 1;
2624 }
2625 
2626 static int
match_keys_ec(hx509_cert c,hx509_private_key private_key)2627 match_keys_ec(hx509_cert c, hx509_private_key private_key)
2628 {
2629     return 1; /* XXX use EC_KEY_check_key */
2630 }
2631 
2632 
2633 int
_hx509_match_keys(hx509_cert c,hx509_private_key key)2634 _hx509_match_keys(hx509_cert c, hx509_private_key key)
2635 {
2636     if (!key->ops)
2637 	return 0;
2638     if (der_heim_oid_cmp(key->ops->key_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) == 0)
2639 	return match_keys_rsa(c, key);
2640     if (der_heim_oid_cmp(key->ops->key_oid, ASN1_OID_ID_ECPUBLICKEY) == 0)
2641 	return match_keys_ec(c, key);
2642     return 0;
2643 
2644 }
2645 
2646 
2647 static const heim_oid *
find_keytype(const hx509_private_key key)2648 find_keytype(const hx509_private_key key)
2649 {
2650     const struct signature_alg *md;
2651 
2652     if (key == NULL)
2653 	return NULL;
2654 
2655     md = _hx509_find_sig_alg(key->signature_alg);
2656     if (md == NULL)
2657 	return NULL;
2658     return md->key_oid;
2659 }
2660 
2661 int
hx509_crypto_select(const hx509_context context,int type,const hx509_private_key source,hx509_peer_info peer,AlgorithmIdentifier * selected)2662 hx509_crypto_select(const hx509_context context,
2663 		    int type,
2664 		    const hx509_private_key source,
2665 		    hx509_peer_info peer,
2666 		    AlgorithmIdentifier *selected)
2667 {
2668     const AlgorithmIdentifier *def = NULL;
2669     size_t i, j;
2670     int ret, bits;
2671 
2672     memset(selected, 0, sizeof(*selected));
2673 
2674     if (type == HX509_SELECT_DIGEST) {
2675 	bits = SIG_DIGEST;
2676 	if (source)
2677 	    def = alg_for_privatekey(source, type);
2678 	if (def == NULL)
2679 	    def = _hx509_crypto_default_digest_alg;
2680     } else if (type == HX509_SELECT_PUBLIC_SIG) {
2681 	bits = SIG_PUBLIC_SIG;
2682 	/* XXX depend on `source´ and `peer´ */
2683 	if (source)
2684 	    def = alg_for_privatekey(source, type);
2685 	if (def == NULL)
2686 	    def = _hx509_crypto_default_sig_alg;
2687     } else if (type == HX509_SELECT_SECRET_ENC) {
2688 	bits = SIG_SECRET;
2689 	def = _hx509_crypto_default_secret_alg;
2690     } else {
2691 	hx509_set_error_string(context, 0, EINVAL,
2692 			       "Unknown type %d of selection", type);
2693 	return EINVAL;
2694     }
2695 
2696     if (peer) {
2697 	const heim_oid *keytype = NULL;
2698 
2699 	keytype = find_keytype(source);
2700 
2701 	for (i = 0; i < peer->len; i++) {
2702 	    for (j = 0; sig_algs[j]; j++) {
2703 		if ((sig_algs[j]->flags & bits) != bits)
2704 		    continue;
2705 		if (der_heim_oid_cmp(sig_algs[j]->sig_oid,
2706 				     &peer->val[i].algorithm) != 0)
2707 		    continue;
2708 		if (keytype && sig_algs[j]->key_oid &&
2709 		    der_heim_oid_cmp(keytype, sig_algs[j]->key_oid))
2710 		    continue;
2711 
2712 		/* found one, use that */
2713 		ret = copy_AlgorithmIdentifier(&peer->val[i], selected);
2714 		if (ret)
2715 		    hx509_clear_error_string(context);
2716 		return ret;
2717 	    }
2718 	    if (bits & SIG_SECRET) {
2719 		const struct hx509cipher *cipher;
2720 
2721 		cipher = find_cipher_by_oid(&peer->val[i].algorithm);
2722 		if (cipher == NULL)
2723 		    continue;
2724 		if (cipher->ai_func == NULL)
2725 		    continue;
2726 		ret = copy_AlgorithmIdentifier(cipher->ai_func(), selected);
2727 		if (ret)
2728 		    hx509_clear_error_string(context);
2729 		return ret;
2730 	    }
2731 	}
2732     }
2733 
2734     /* use default */
2735     ret = copy_AlgorithmIdentifier(def, selected);
2736     if (ret)
2737 	hx509_clear_error_string(context);
2738     return ret;
2739 }
2740 
2741 int
hx509_crypto_available(hx509_context context,int type,hx509_cert source,AlgorithmIdentifier ** val,unsigned int * plen)2742 hx509_crypto_available(hx509_context context,
2743 		       int type,
2744 		       hx509_cert source,
2745 		       AlgorithmIdentifier **val,
2746 		       unsigned int *plen)
2747 {
2748     const heim_oid *keytype = NULL;
2749     unsigned int len, i;
2750     void *ptr;
2751     int bits, ret;
2752 
2753     *val = NULL;
2754 
2755     if (type == HX509_SELECT_ALL) {
2756 	bits = SIG_DIGEST | SIG_PUBLIC_SIG | SIG_SECRET;
2757     } else if (type == HX509_SELECT_DIGEST) {
2758 	bits = SIG_DIGEST;
2759     } else if (type == HX509_SELECT_PUBLIC_SIG) {
2760 	bits = SIG_PUBLIC_SIG;
2761     } else {
2762 	hx509_set_error_string(context, 0, EINVAL,
2763 			       "Unknown type %d of available", type);
2764 	return EINVAL;
2765     }
2766 
2767     if (source)
2768 	keytype = find_keytype(_hx509_cert_private_key(source));
2769 
2770     len = 0;
2771     for (i = 0; sig_algs[i]; i++) {
2772 	if ((sig_algs[i]->flags & bits) == 0)
2773 	    continue;
2774 	if (sig_algs[i]->sig_alg == NULL)
2775 	    continue;
2776 	if (keytype && sig_algs[i]->key_oid &&
2777 	    der_heim_oid_cmp(sig_algs[i]->key_oid, keytype))
2778 	    continue;
2779 
2780 	/* found one, add that to the list */
2781 	ptr = realloc(*val, sizeof(**val) * (len + 1));
2782 	if (ptr == NULL)
2783 	    goto out;
2784 	*val = ptr;
2785 
2786 	ret = copy_AlgorithmIdentifier(sig_algs[i]->sig_alg, &(*val)[len]);
2787 	if (ret)
2788 	    goto out;
2789 	len++;
2790     }
2791 
2792     /* Add AES */
2793     if (bits & SIG_SECRET) {
2794 
2795 	for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++) {
2796 
2797 	    if (ciphers[i].flags & CIPHER_WEAK)
2798 		continue;
2799 	    if (ciphers[i].ai_func == NULL)
2800 		continue;
2801 
2802 	    ptr = realloc(*val, sizeof(**val) * (len + 1));
2803 	    if (ptr == NULL)
2804 		goto out;
2805 	    *val = ptr;
2806 
2807 	    ret = copy_AlgorithmIdentifier((ciphers[i].ai_func)(), &(*val)[len]);
2808 	    if (ret)
2809 		goto out;
2810 	    len++;
2811 	}
2812     }
2813 
2814     *plen = len;
2815     return 0;
2816 
2817 out:
2818     for (i = 0; i < len; i++)
2819 	free_AlgorithmIdentifier(&(*val)[i]);
2820     free(*val);
2821     *val = NULL;
2822     hx509_set_error_string(context, 0, ENOMEM, "out of memory");
2823     return ENOMEM;
2824 }
2825 
2826 void
hx509_crypto_free_algs(AlgorithmIdentifier * val,unsigned int len)2827 hx509_crypto_free_algs(AlgorithmIdentifier *val,
2828 		       unsigned int len)
2829 {
2830     unsigned int i;
2831     for (i = 0; i < len; i++)
2832 	free_AlgorithmIdentifier(&val[i]);
2833     free(val);
2834 }
2835