crypto.c revision 1.29
1/*	$OpenBSD: crypto.c,v 1.29 2020/11/26 22:24:06 tobhe Exp $	*/
2
3/*
4 * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19#include <sys/param.h>	/* roundup */
20#include <sys/queue.h>
21#include <sys/socket.h>
22#include <sys/uio.h>
23
24#include <stdio.h>
25#include <stdlib.h>
26#include <unistd.h>
27#include <string.h>
28#include <errno.h>
29#include <fcntl.h>
30#include <event.h>
31
32#include <openssl/hmac.h>
33#include <openssl/evp.h>
34#include <openssl/sha.h>
35#include <openssl/md5.h>
36#include <openssl/x509.h>
37#include <openssl/rsa.h>
38
39#include "iked.h"
40#include "ikev2.h"
41
42/* RFC 7427, A.1 RSA */
43static const uint8_t sha256WithRSA[] = {
44	0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
45	0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00
46};
47static const uint8_t sha384WithRSA[] = {
48	0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
49	0xf7, 0x0d, 0x01, 0x01, 0x0c, 0x05, 0x00
50};
51static const uint8_t sha512WithRSA[] = {
52	0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
53	0xf7, 0x0d, 0x01, 0x01, 0x0d, 0x05, 0x00
54};
55/* RFC 7427, A.3 ECDSA */
56static const uint8_t ecdsa_sha256[] = {
57	0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce,
58	0x3d, 0x04, 0x03, 0x02
59};
60static const uint8_t ecdsa_sha384[] = {
61	0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce,
62	0x3d, 0x04, 0x03, 0x03
63};
64static const uint8_t ecdsa_sha512[] = {
65	0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce,
66	0x3d, 0x04, 0x03, 0x04
67};
68
69static const struct {
70	int		 sc_keytype;
71	const EVP_MD	*(*sc_md)(void);
72	uint8_t		 sc_len;
73	const uint8_t	*sc_oid;
74} schemes[] = {
75	{ EVP_PKEY_RSA, EVP_sha256, sizeof(sha256WithRSA), sha256WithRSA },
76	{ EVP_PKEY_RSA, EVP_sha384, sizeof(sha384WithRSA), sha384WithRSA },
77	{ EVP_PKEY_RSA, EVP_sha512, sizeof(sha512WithRSA), sha512WithRSA },
78	{ EVP_PKEY_EC,  EVP_sha256, sizeof(ecdsa_sha256),  ecdsa_sha256 },
79	{ EVP_PKEY_EC,  EVP_sha384, sizeof(ecdsa_sha384),  ecdsa_sha384 },
80	{ EVP_PKEY_EC,  EVP_sha512, sizeof(ecdsa_sha512),  ecdsa_sha512 },
81};
82
83int	_dsa_verify_init(struct iked_dsa *, const uint8_t *, size_t);
84int	_dsa_verify_prepare(struct iked_dsa *, uint8_t **, size_t *,
85	    uint8_t **);
86int	_dsa_sign_encode(struct iked_dsa *, uint8_t *, size_t, size_t *);
87int	_dsa_sign_ecdsa(struct iked_dsa *, uint8_t *, size_t);
88
89struct iked_hash *
90hash_new(uint8_t type, uint16_t id)
91{
92	struct iked_hash	*hash;
93	const EVP_MD		*md = NULL;
94	HMAC_CTX		*ctx = NULL;
95	int			 length = 0, fixedkey = 0, trunc = 0, isaead = 0;
96
97	switch (type) {
98	case IKEV2_XFORMTYPE_PRF:
99		switch (id) {
100		case IKEV2_XFORMPRF_HMAC_MD5:
101			md = EVP_md5();
102			length = MD5_DIGEST_LENGTH;
103			break;
104		case IKEV2_XFORMPRF_HMAC_SHA1:
105			md = EVP_sha1();
106			length = SHA_DIGEST_LENGTH;
107			break;
108		case IKEV2_XFORMPRF_HMAC_SHA2_256:
109			md = EVP_sha256();
110			length = SHA256_DIGEST_LENGTH;
111			break;
112		case IKEV2_XFORMPRF_HMAC_SHA2_384:
113			md = EVP_sha384();
114			length = SHA384_DIGEST_LENGTH;
115			break;
116		case IKEV2_XFORMPRF_HMAC_SHA2_512:
117			md = EVP_sha512();
118			length = SHA512_DIGEST_LENGTH;
119			break;
120		case IKEV2_XFORMPRF_AES128_XCBC:
121			fixedkey = 128 / 8;
122			length = fixedkey;
123			/* FALLTHROUGH */
124		case IKEV2_XFORMPRF_HMAC_TIGER:
125		case IKEV2_XFORMPRF_AES128_CMAC:
126		default:
127			log_debug("%s: prf %s not supported", __func__,
128			    print_map(id, ikev2_xformprf_map));
129			break;
130		}
131		break;
132	case IKEV2_XFORMTYPE_INTEGR:
133		switch (id) {
134		case IKEV2_XFORMAUTH_HMAC_MD5_96:
135			md = EVP_md5();
136			length = MD5_DIGEST_LENGTH;
137			trunc = 12;
138			break;
139		case IKEV2_XFORMAUTH_HMAC_SHA1_96:
140			md = EVP_sha1();
141			length = SHA_DIGEST_LENGTH;
142			trunc = 12;
143			break;
144		case IKEV2_XFORMAUTH_HMAC_SHA2_256_128:
145			md = EVP_sha256();
146			length = SHA256_DIGEST_LENGTH;
147			trunc = 16;
148			break;
149		case IKEV2_XFORMAUTH_HMAC_SHA2_384_192:
150			md = EVP_sha384();
151			length = SHA384_DIGEST_LENGTH;
152			trunc = 24;
153			break;
154		case IKEV2_XFORMAUTH_HMAC_SHA2_512_256:
155			md = EVP_sha512();
156			length = SHA512_DIGEST_LENGTH;
157			trunc = 32;
158			break;
159		case IKEV2_XFORMAUTH_AES_GCM_12:
160			length = 12;
161			isaead = 1;
162			break;
163		case IKEV2_XFORMAUTH_AES_GCM_16:
164			length = 16;
165			isaead = 1;
166			break;
167		case IKEV2_XFORMAUTH_NONE:
168		case IKEV2_XFORMAUTH_DES_MAC:
169		case IKEV2_XFORMAUTH_KPDK_MD5:
170		case IKEV2_XFORMAUTH_AES_XCBC_96:
171		case IKEV2_XFORMAUTH_HMAC_MD5_128:
172		case IKEV2_XFORMAUTH_HMAC_SHA1_160:
173		case IKEV2_XFORMAUTH_AES_CMAC_96:
174		case IKEV2_XFORMAUTH_AES_128_GMAC:
175		case IKEV2_XFORMAUTH_AES_192_GMAC:
176		case IKEV2_XFORMAUTH_AES_256_GMAC:
177		default:
178			log_debug("%s: auth %s not supported", __func__,
179			    print_map(id, ikev2_xformauth_map));
180			break;
181		}
182		break;
183	default:
184		log_debug("%s: hash type %s not supported", __func__,
185		    print_map(id, ikev2_xformtype_map));
186		break;
187	}
188	if (!isaead && md == NULL)
189		return (NULL);
190
191	if ((hash = calloc(1, sizeof(*hash))) == NULL) {
192		log_debug("%s: alloc hash", __func__);
193		return (NULL);
194	}
195
196	hash->hash_type = type;
197	hash->hash_id = id;
198	hash->hash_priv = md;
199	hash->hash_ctx = NULL;
200	hash->hash_trunc = trunc;
201	hash->hash_length = length;
202	hash->hash_fixedkey = fixedkey;
203	hash->hash_isaead = isaead;
204
205	if (isaead)
206		return (hash);
207
208	if ((ctx = calloc(1, sizeof(*ctx))) == NULL) {
209		log_debug("%s: alloc hash ctx", __func__);
210		hash_free(hash);
211		return (NULL);
212	}
213
214	HMAC_CTX_init(ctx);
215	hash->hash_ctx = ctx;
216
217	return (hash);
218}
219
220struct ibuf *
221hash_setkey(struct iked_hash *hash, void *key, size_t keylen)
222{
223	ibuf_release(hash->hash_key);
224	if ((hash->hash_key = ibuf_new(key, keylen)) == NULL) {
225		log_debug("%s: alloc hash key", __func__);
226		return (NULL);
227	}
228	return (hash->hash_key);
229}
230
231void
232hash_free(struct iked_hash *hash)
233{
234	if (hash == NULL)
235		return;
236	if (hash->hash_ctx != NULL) {
237		HMAC_CTX_cleanup(hash->hash_ctx);
238		free(hash->hash_ctx);
239	}
240	ibuf_release(hash->hash_key);
241	free(hash);
242}
243
244void
245hash_init(struct iked_hash *hash)
246{
247	HMAC_Init_ex(hash->hash_ctx, hash->hash_key->buf,
248	    ibuf_length(hash->hash_key), hash->hash_priv, NULL);
249}
250
251void
252hash_update(struct iked_hash *hash, void *buf, size_t len)
253{
254	HMAC_Update(hash->hash_ctx, buf, len);
255}
256
257void
258hash_final(struct iked_hash *hash, void *buf, size_t *len)
259{
260	unsigned int	 length = 0;
261
262	HMAC_Final(hash->hash_ctx, buf, &length);
263	*len = (size_t)length;
264
265	/* Truncate the result if required by the alg */
266	if (hash->hash_trunc && *len > hash->hash_trunc)
267		*len = hash->hash_trunc;
268}
269
270size_t
271hash_length(struct iked_hash *hash)
272{
273	if (hash->hash_trunc)
274		return (hash->hash_trunc);
275	return (hash->hash_length);
276}
277
278size_t
279hash_keylength(struct iked_hash *hash)
280{
281	return (hash->hash_length);
282}
283
284struct iked_cipher *
285cipher_new(uint8_t type, uint16_t id, uint16_t id_length)
286{
287	struct iked_cipher	*encr;
288	const EVP_CIPHER	*cipher = NULL;
289	EVP_CIPHER_CTX		*ctx = NULL;
290	int			 length = 0, fixedkey = 0, ivlength = 0;
291	int			 saltlength = 0, authid = 0;
292
293	switch (type) {
294	case IKEV2_XFORMTYPE_ENCR:
295		switch (id) {
296		case IKEV2_XFORMENCR_3DES:
297			cipher = EVP_des_ede3_cbc();
298			length = EVP_CIPHER_block_size(cipher);
299			fixedkey = EVP_CIPHER_key_length(cipher);
300			ivlength = EVP_CIPHER_iv_length(cipher);
301			break;
302		case IKEV2_XFORMENCR_AES_CBC:
303			switch (id_length) {
304			case 128:
305				cipher = EVP_aes_128_cbc();
306				break;
307			case 192:
308				cipher = EVP_aes_192_cbc();
309				break;
310			case 256:
311				cipher = EVP_aes_256_cbc();
312				break;
313			default:
314				log_debug("%s: invalid key length %d"
315				    " for cipher %s", __func__, id_length,
316				    print_map(id, ikev2_xformencr_map));
317				break;
318			}
319			if (cipher == NULL)
320				break;
321			length = EVP_CIPHER_block_size(cipher);
322			ivlength = EVP_CIPHER_iv_length(cipher);
323			fixedkey = EVP_CIPHER_key_length(cipher);
324			break;
325		case IKEV2_XFORMENCR_AES_GCM_16:
326		case IKEV2_XFORMENCR_AES_GCM_12:
327			switch (id_length) {
328			case 128:
329				cipher = EVP_aes_128_gcm();
330				break;
331			case 256:
332				cipher = EVP_aes_256_gcm();
333				break;
334			default:
335				log_debug("%s: invalid key length %d"
336				    " for cipher %s", __func__, id_length,
337				    print_map(id, ikev2_xformencr_map));
338				break;
339			}
340			if (cipher == NULL)
341				break;
342			switch(id) {
343			case IKEV2_XFORMENCR_AES_GCM_16:
344				authid = IKEV2_XFORMAUTH_AES_GCM_16;
345				break;
346			case IKEV2_XFORMENCR_AES_GCM_12:
347				authid = IKEV2_XFORMAUTH_AES_GCM_12;
348				break;
349			}
350			length = EVP_CIPHER_block_size(cipher);
351			ivlength = 8;
352			saltlength = 4;
353			fixedkey = EVP_CIPHER_key_length(cipher) + saltlength;
354			break;
355		case IKEV2_XFORMENCR_DES_IV64:
356		case IKEV2_XFORMENCR_DES:
357		case IKEV2_XFORMENCR_RC5:
358		case IKEV2_XFORMENCR_IDEA:
359		case IKEV2_XFORMENCR_CAST:
360		case IKEV2_XFORMENCR_BLOWFISH:
361		case IKEV2_XFORMENCR_3IDEA:
362		case IKEV2_XFORMENCR_DES_IV32:
363		case IKEV2_XFORMENCR_NULL:
364		case IKEV2_XFORMENCR_AES_CTR:
365			/* FALLTHROUGH */
366		default:
367			log_debug("%s: cipher %s not supported", __func__,
368			    print_map(id, ikev2_xformencr_map));
369			cipher = NULL;
370			break;
371		}
372		break;
373	default:
374		log_debug("%s: cipher type %s not supported", __func__,
375		    print_map(id, ikev2_xformtype_map));
376		break;
377	}
378	if (cipher == NULL)
379		return (NULL);
380
381	if ((encr = calloc(1, sizeof(*encr))) == NULL) {
382		log_debug("%s: alloc cipher", __func__);
383		return (NULL);
384	}
385
386	encr->encr_id = id;
387	encr->encr_priv = cipher;
388	encr->encr_ctx = NULL;
389	encr->encr_length = length;
390	encr->encr_fixedkey = fixedkey;
391	encr->encr_ivlength = ivlength ? ivlength : length;
392	encr->encr_saltlength = saltlength;
393	encr->encr_authid = authid;
394
395	if ((ctx = calloc(1, sizeof(*ctx))) == NULL) {
396		log_debug("%s: alloc cipher ctx", __func__);
397		cipher_free(encr);
398		return (NULL);
399	}
400
401	EVP_CIPHER_CTX_init(ctx);
402	encr->encr_ctx = ctx;
403
404	return (encr);
405}
406
407struct ibuf *
408cipher_setkey(struct iked_cipher *encr, void *key, size_t keylen)
409{
410	ibuf_release(encr->encr_key);
411	if ((encr->encr_key = ibuf_new(key, keylen)) == NULL) {
412		log_debug("%s: alloc cipher key", __func__);
413		return (NULL);
414	}
415	return (encr->encr_key);
416}
417
418struct ibuf *
419cipher_setiv(struct iked_cipher *encr, void *iv, size_t len)
420{
421	ibuf_release(encr->encr_iv);
422	encr->encr_iv = NULL;
423	if (iv != NULL) {
424		if (len < encr->encr_ivlength) {
425			log_debug("%s: invalid IV length %zu", __func__, len);
426			return (NULL);
427		}
428		encr->encr_iv = ibuf_new(iv, encr->encr_ivlength);
429	} else {
430		switch (encr->encr_id) {
431		case IKEV2_XFORMENCR_AES_GCM_16:
432		case IKEV2_XFORMENCR_AES_GCM_12:
433			if (encr->encr_ivlength != sizeof(encr->encr_civ)) {
434				log_info("%s: ivlen does not match %zu != %zu",
435				    __func__, encr->encr_ivlength,
436				    sizeof(encr->encr_civ));
437				return (NULL);
438			}
439			encr->encr_iv = ibuf_new(&encr->encr_civ, sizeof(encr->encr_civ));
440			encr->encr_civ++;
441			break;
442		default:
443			/* Get new random IV */
444			encr->encr_iv = ibuf_random(encr->encr_ivlength);
445		}
446	}
447	if (encr->encr_iv == NULL) {
448		log_debug("%s: failed to set IV", __func__);
449		return (NULL);
450	}
451	return (encr->encr_iv);
452}
453
454int
455cipher_settag(struct iked_cipher *encr, uint8_t *data, size_t len)
456{
457	return (EVP_CIPHER_CTX_ctrl(encr->encr_ctx,
458	    EVP_CTRL_GCM_SET_TAG, len, data) != 1);
459}
460
461int
462cipher_gettag(struct iked_cipher *encr, uint8_t *data, size_t len)
463{
464	return (EVP_CIPHER_CTX_ctrl(encr->encr_ctx,
465	    EVP_CTRL_GCM_GET_TAG, len, data) != 1);
466}
467
468void
469cipher_free(struct iked_cipher *encr)
470{
471	if (encr == NULL)
472		return;
473	if (encr->encr_ctx != NULL) {
474		EVP_CIPHER_CTX_cleanup(encr->encr_ctx);
475		free(encr->encr_ctx);
476	}
477	ibuf_release(encr->encr_iv);
478	ibuf_release(encr->encr_key);
479	free(encr);
480}
481
482int
483cipher_init(struct iked_cipher *encr, int enc)
484{
485	struct ibuf	*nonce = NULL;
486	int		 ret = -1;
487
488	if (EVP_CipherInit_ex(encr->encr_ctx, encr->encr_priv, NULL,
489	    NULL, NULL, enc) != 1)
490		return (-1);
491	if (encr->encr_saltlength > 0) {
492		/* For AEADs the nonce is salt + IV  (see RFC5282) */
493		nonce = ibuf_new(ibuf_data(encr->encr_key) +
494		    ibuf_size(encr->encr_key) - encr->encr_saltlength,
495		    encr->encr_saltlength);
496		if (nonce == NULL)
497			return (-1);
498		if (ibuf_add(nonce, ibuf_data(encr->encr_iv) , ibuf_size(encr->encr_iv)) != 0)
499			goto done;
500		if (EVP_CipherInit_ex(encr->encr_ctx, NULL, NULL,
501		    ibuf_data(encr->encr_key), ibuf_data(nonce), enc) != 1)
502			goto done;
503	} else
504		if (EVP_CipherInit_ex(encr->encr_ctx, NULL, NULL,
505		    ibuf_data(encr->encr_key), ibuf_data(encr->encr_iv), enc) != 1)
506			return (-1);
507	EVP_CIPHER_CTX_set_padding(encr->encr_ctx, 0);
508	ret = 0;
509 done:
510	ibuf_free(nonce);
511	return (ret);
512}
513
514int
515cipher_init_encrypt(struct iked_cipher *encr)
516{
517	return (cipher_init(encr, 1));
518}
519
520int
521cipher_init_decrypt(struct iked_cipher *encr)
522{
523	return (cipher_init(encr, 0));
524}
525
526void
527cipher_aad(struct iked_cipher *encr, void *in, size_t inlen,
528    size_t *outlen)
529{
530	int	 olen = 0;
531
532	if (EVP_CipherUpdate(encr->encr_ctx, NULL, &olen, in, inlen) != 1) {
533		ca_sslerror(__func__);
534		*outlen = 0;
535		return;
536	}
537	*outlen = (size_t)olen;
538}
539
540int
541cipher_update(struct iked_cipher *encr, void *in, size_t inlen,
542    void *out, size_t *outlen)
543{
544	int	 olen;
545
546	olen = 0;
547	if (EVP_CipherUpdate(encr->encr_ctx, out, &olen, in, inlen) != 1) {
548		ca_sslerror(__func__);
549		*outlen = 0;
550		return (-1);
551	}
552	*outlen = (size_t)olen;
553	return (0);
554}
555
556int
557cipher_final(struct iked_cipher *encr)
558{
559	int	 olen;
560
561	/*
562	 * We always have EVP_CIPH_NO_PADDING set.  This means arg
563         * out is not used and olen should always be 0.
564         */
565	if (EVP_CipherFinal_ex(encr->encr_ctx, NULL, &olen) != 1) {
566		ca_sslerror(__func__);
567		return (-1);
568	}
569	return (0);
570}
571
572size_t
573cipher_length(struct iked_cipher *encr)
574{
575	return (encr->encr_length);
576}
577
578size_t
579cipher_keylength(struct iked_cipher *encr)
580{
581	if (encr->encr_fixedkey)
582		return (encr->encr_fixedkey);
583
584	/* Might return zero */
585	return (ibuf_length(encr->encr_key));
586}
587
588size_t
589cipher_ivlength(struct iked_cipher *encr)
590{
591	return (encr->encr_ivlength);
592}
593
594size_t
595cipher_outlength(struct iked_cipher *encr, size_t inlen)
596{
597	return (roundup(inlen, encr->encr_length));
598}
599
600struct iked_dsa *
601dsa_new(uint16_t id, struct iked_hash *prf, int sign)
602{
603	struct iked_dsa		*dsap = NULL, dsa;
604
605	bzero(&dsa, sizeof(dsa));
606
607	switch (id) {
608	case IKEV2_AUTH_SIG:
609		if (sign)
610			dsa.dsa_priv = EVP_sha256(); /* XXX should be passed */
611		else
612			dsa.dsa_priv = NULL; /* set later by dsa_init() */
613		break;
614	case IKEV2_AUTH_RSA_SIG:
615		/* RFC5996 says we SHOULD use SHA1 here */
616		dsa.dsa_priv = EVP_sha1();
617		break;
618	case IKEV2_AUTH_SHARED_KEY_MIC:
619		if (prf == NULL || prf->hash_priv == NULL)
620			fatalx("dsa_new: invalid PRF");
621		dsa.dsa_priv = prf->hash_priv;
622		dsa.dsa_hmac = 1;
623		break;
624	case IKEV2_AUTH_DSS_SIG:
625		dsa.dsa_priv = EVP_dss1();
626		break;
627	case IKEV2_AUTH_ECDSA_256:
628		dsa.dsa_priv = EVP_sha256();
629		break;
630	case IKEV2_AUTH_ECDSA_384:
631		dsa.dsa_priv = EVP_sha384();
632		break;
633	case IKEV2_AUTH_ECDSA_521:
634		dsa.dsa_priv = EVP_sha512();
635		break;
636	default:
637		log_debug("%s: auth method %s not supported", __func__,
638		    print_map(id, ikev2_auth_map));
639		break;
640	}
641
642	if ((dsap = calloc(1, sizeof(*dsap))) == NULL) {
643		log_debug("%s: alloc dsa ctx", __func__);
644
645		return (NULL);
646	}
647	memcpy(dsap, &dsa, sizeof(*dsap));
648
649	dsap->dsa_method = id;
650	dsap->dsa_sign = sign;
651
652	if (dsap->dsa_hmac) {
653		if ((dsap->dsa_ctx = calloc(1, sizeof(HMAC_CTX))) == NULL) {
654			log_debug("%s: alloc hash ctx", __func__);
655			dsa_free(dsap);
656			return (NULL);
657		}
658		HMAC_CTX_init((HMAC_CTX *)dsap->dsa_ctx);
659	} else {
660		if ((dsap->dsa_ctx = EVP_MD_CTX_create()) == NULL) {
661			log_debug("%s: alloc digest ctx", __func__);
662			dsa_free(dsap);
663			return (NULL);
664		}
665	}
666
667	return (dsap);
668}
669
670struct iked_dsa *
671dsa_sign_new(uint16_t id, struct iked_hash *prf)
672{
673	return (dsa_new(id, prf, 1));
674}
675
676struct iked_dsa *
677dsa_verify_new(uint16_t id, struct iked_hash *prf)
678{
679	return (dsa_new(id, prf, 0));
680}
681
682void
683dsa_free(struct iked_dsa *dsa)
684{
685	if (dsa == NULL)
686		return;
687	if (dsa->dsa_hmac) {
688		HMAC_CTX_cleanup((HMAC_CTX *)dsa->dsa_ctx);
689		free(dsa->dsa_ctx);
690	} else {
691		EVP_MD_CTX_destroy((EVP_MD_CTX *)dsa->dsa_ctx);
692		if (dsa->dsa_key)
693			EVP_PKEY_free(dsa->dsa_key);
694	}
695
696	ibuf_release(dsa->dsa_keydata);
697	free(dsa);
698}
699
700struct ibuf *
701dsa_setkey(struct iked_dsa *dsa, void *key, size_t keylen, uint8_t type)
702{
703	BIO		*rawcert = NULL;
704	X509		*cert = NULL;
705	RSA		*rsa = NULL;
706	EC_KEY		*ec = NULL;
707	EVP_PKEY	*pkey = NULL;
708
709	ibuf_release(dsa->dsa_keydata);
710	if ((dsa->dsa_keydata = ibuf_new(key, keylen)) == NULL) {
711		log_debug("%s: alloc signature key", __func__);
712		return (NULL);
713	}
714
715	if ((rawcert = BIO_new_mem_buf(key, keylen)) == NULL)
716		goto err;
717
718	switch (type) {
719	case IKEV2_CERT_X509_CERT:
720		if ((cert = d2i_X509_bio(rawcert, NULL)) == NULL)
721			goto sslerr;
722		if ((pkey = X509_get_pubkey(cert)) == NULL)
723			goto sslerr;
724		dsa->dsa_key = pkey;
725		break;
726	case IKEV2_CERT_RSA_KEY:
727		if (dsa->dsa_sign) {
728			if ((rsa = d2i_RSAPrivateKey_bio(rawcert,
729			    NULL)) == NULL)
730				goto sslerr;
731		} else {
732			if ((rsa = d2i_RSAPublicKey_bio(rawcert,
733			    NULL)) == NULL)
734				goto sslerr;
735		}
736
737		if ((pkey = EVP_PKEY_new()) == NULL)
738			goto sslerr;
739		if (!EVP_PKEY_set1_RSA(pkey, rsa))
740			goto sslerr;
741
742		RSA_free(rsa);		/* pkey now has the reference */
743		dsa->dsa_key = pkey;
744		break;
745	case IKEV2_CERT_ECDSA:
746		if (dsa->dsa_sign) {
747			if ((ec = d2i_ECPrivateKey_bio(rawcert, NULL)) == NULL)
748				goto sslerr;
749		} else {
750			if ((ec = d2i_EC_PUBKEY_bio(rawcert, NULL)) == NULL)
751				goto sslerr;
752		}
753
754		if ((pkey = EVP_PKEY_new()) == NULL)
755			goto sslerr;
756		if (!EVP_PKEY_set1_EC_KEY(pkey, ec))
757			goto sslerr;
758
759		EC_KEY_free(ec);	/* pkey now has the reference */
760		dsa->dsa_key = pkey;
761		break;
762	default:
763		if (dsa->dsa_hmac)
764			break;
765		log_debug("%s: unsupported key type", __func__);
766		goto err;
767	}
768
769	if (cert != NULL)
770		X509_free(cert);
771	BIO_free(rawcert);	/* temporary for parsing */
772
773	return (dsa->dsa_keydata);
774
775 sslerr:
776	ca_sslerror(__func__);
777 err:
778	log_debug("%s: error", __func__);
779
780	if (rsa != NULL)
781		RSA_free(rsa);
782	if (ec != NULL)
783		EC_KEY_free(ec);
784	if (pkey != NULL)
785		EVP_PKEY_free(pkey);
786	if (cert != NULL)
787		X509_free(cert);
788	if (rawcert != NULL)
789		BIO_free(rawcert);
790	ibuf_release(dsa->dsa_keydata);
791	dsa->dsa_keydata = NULL;
792	return (NULL);
793}
794
795int
796_dsa_verify_init(struct iked_dsa *dsa, const uint8_t *sig, size_t len)
797{
798	uint8_t			 oidlen;
799	size_t			 i;
800	int			 keytype;
801
802	if (dsa->dsa_priv != NULL)
803		return (0);
804	/*
805	 * For IKEV2_AUTH_SIG the oid of the authentication signature
806	 * is encoded in the first bytes of the auth message.
807	 */
808	if (dsa->dsa_method != IKEV2_AUTH_SIG)  {
809		log_debug("%s: dsa_priv not set for %s", __func__,
810		    print_map(dsa->dsa_method, ikev2_auth_map));
811		return (-1);
812	}
813	if (dsa->dsa_key == NULL) {
814		log_debug("%s: dsa_key not set for %s", __func__,
815		    print_map(dsa->dsa_method, ikev2_auth_map));
816		return (-1);
817	}
818	keytype = EVP_PKEY_type(((EVP_PKEY *)dsa->dsa_key)->type);
819	if (sig == NULL) {
820		log_debug("%s: signature missing", __func__);
821		return (-1);
822	}
823	if (len < sizeof(oidlen)) {
824		log_debug("%s: signature (%zu) too small for oid length",
825		    __func__, len);
826		return (-1);
827	}
828	memcpy(&oidlen, sig, sizeof(oidlen));
829	if (len < (size_t)oidlen + sizeof(oidlen)) {
830		log_debug("%s: signature (%zu) too small for oid (%u)",
831		    __func__, len, oidlen);
832		return (-1);
833	}
834	for (i = 0; i < nitems(schemes); i++) {
835		if (keytype == schemes[i].sc_keytype &&
836		    oidlen == schemes[i].sc_len &&
837		    memcmp(sig + 1, schemes[i].sc_oid,
838		    schemes[i].sc_len) == 0) {
839			dsa->dsa_priv = (*schemes[i].sc_md)();
840			log_debug("%s: signature scheme %zd selected",
841			    __func__, i);
842			return (0);
843		}
844	}
845	log_debug("%s: unsupported signature (%d)", __func__, oidlen);
846	return (-1);
847}
848
849int
850dsa_init(struct iked_dsa *dsa, const void *buf, size_t len)
851{
852	int	 ret;
853
854	if (dsa->dsa_hmac) {
855		if (!HMAC_Init_ex(dsa->dsa_ctx, ibuf_data(dsa->dsa_keydata),
856		    ibuf_length(dsa->dsa_keydata), dsa->dsa_priv, NULL))
857			return (-1);
858		return (0);
859	}
860
861	if (dsa->dsa_sign)
862		ret = EVP_DigestSignInit(dsa->dsa_ctx, NULL, dsa->dsa_priv,
863		    NULL, dsa->dsa_key);
864	else {
865		if ((ret = _dsa_verify_init(dsa, buf, len)) != 0)
866			return (ret);
867		ret = EVP_DigestVerifyInit(dsa->dsa_ctx, NULL, dsa->dsa_priv,
868		    NULL, dsa->dsa_key);
869	}
870
871	return (ret == 1 ? 0 : -1);
872}
873
874int
875dsa_update(struct iked_dsa *dsa, const void *buf, size_t len)
876{
877	int	ret;
878
879	if (dsa->dsa_hmac)
880		ret = HMAC_Update(dsa->dsa_ctx, buf, len);
881	else if (dsa->dsa_sign)
882		ret = EVP_DigestSignUpdate(dsa->dsa_ctx, buf, len);
883	else
884		ret = EVP_DigestVerifyUpdate(dsa->dsa_ctx, buf, len);
885
886	return (ret == 1 ? 0 : -1);
887}
888
889/* Prefix signature hash with encoded type */
890int
891_dsa_sign_encode(struct iked_dsa *dsa, uint8_t *ptr, size_t len, size_t *offp)
892{
893	int		 keytype;
894	size_t		 i, need;
895
896	if (offp)
897		*offp = 0;
898	if (dsa->dsa_method != IKEV2_AUTH_SIG)
899		return (0);
900	if (dsa->dsa_key == NULL)
901		return (-1);
902	keytype = EVP_PKEY_type(((EVP_PKEY *)dsa->dsa_key)->type);
903	for (i = 0; i < nitems(schemes); i++) {
904		/* XXX should avoid calling sc_md() each time... */
905		if (keytype == schemes[i].sc_keytype &&
906		    (dsa->dsa_priv == (*schemes[i].sc_md)()))
907			break;
908	}
909	if (i >= nitems(schemes))
910		return (-1);
911	log_debug("%s: signature scheme %zd selected", __func__, i);
912	need = sizeof(ptr[0]) + schemes[i].sc_len;
913	if (ptr) {
914		if (len < need)
915			return (-1);
916		ptr[0] = schemes[i].sc_len;
917		memcpy(ptr + sizeof(ptr[0]), schemes[i].sc_oid,
918		    schemes[i].sc_len);
919	}
920	if (offp)
921		*offp = need;
922	return (0);
923}
924
925/* Export size of encoded signature hash type */
926size_t
927dsa_prefix(struct iked_dsa *dsa)
928{
929	size_t		off = 0;
930
931	if (_dsa_sign_encode(dsa, NULL, 0, &off) < 0)
932		fatal("dsa_prefix: internal error");
933	return off;
934}
935
936size_t
937dsa_length(struct iked_dsa *dsa)
938{
939	if (dsa->dsa_hmac)
940		return (EVP_MD_size(dsa->dsa_priv));
941	switch (dsa->dsa_method) {
942	case IKEV2_AUTH_ECDSA_256:
943	case IKEV2_AUTH_ECDSA_384:
944	case IKEV2_AUTH_ECDSA_521:
945		/* size of concat(r|s) */
946		return (2 * ((EVP_PKEY_bits(dsa->dsa_key) + 7) / 8));
947	}
948	return (dsa_prefix(dsa) + EVP_PKEY_size(dsa->dsa_key));
949}
950
951int
952_dsa_sign_ecdsa(struct iked_dsa *dsa, uint8_t *ptr, size_t len)
953{
954	ECDSA_SIG	*obj = NULL;
955	uint8_t		*tmp = NULL;
956	const uint8_t	*p;
957	size_t		 tmplen;
958	int		 ret = -1;
959	int		 bnlen, off;
960
961	if (len % 2)
962		goto done;	/* must be even */
963	bnlen = len/2;
964	/*
965	 * (a) create DER signature into 'tmp' buffer
966	 * (b) convert buffer to ECDSA_SIG object
967	 * (c) concatenate the padded r|s BIGNUMS into 'ptr'
968	 */
969	if (EVP_DigestSignFinal(dsa->dsa_ctx, NULL, &tmplen) != 1)
970		goto done;
971	if ((tmp = calloc(1, tmplen)) == NULL)
972		goto done;
973	if (EVP_DigestSignFinal(dsa->dsa_ctx, tmp, &tmplen) != 1)
974		goto done;
975	p = tmp;
976	if (d2i_ECDSA_SIG(&obj, &p, tmplen) == NULL)
977		goto done;
978	if (BN_num_bytes(obj->r) > bnlen || BN_num_bytes(obj->s) > bnlen)
979		goto done;
980	memset(ptr, 0, len);
981	off = bnlen - BN_num_bytes(obj->r);
982	BN_bn2bin(obj->r, ptr + off);
983	off = 2 * bnlen - BN_num_bytes(obj->s);
984	BN_bn2bin(obj->s, ptr + off);
985	ret = 0;
986 done:
987	free(tmp);
988	if (obj)
989		ECDSA_SIG_free(obj);
990	return (ret);
991}
992
993ssize_t
994dsa_sign_final(struct iked_dsa *dsa, void *buf, size_t len)
995{
996	unsigned int	 hmaclen;
997	size_t		 off = 0;
998	uint8_t		*ptr = buf;
999
1000	if (len < dsa_length(dsa))
1001		return (-1);
1002
1003	if (dsa->dsa_hmac) {
1004		if (!HMAC_Final(dsa->dsa_ctx, buf, &hmaclen))
1005			return (-1);
1006		if (hmaclen > INT_MAX)
1007			return (-1);
1008		return (ssize_t)hmaclen;
1009	} else {
1010		switch (dsa->dsa_method) {
1011		case IKEV2_AUTH_ECDSA_256:
1012		case IKEV2_AUTH_ECDSA_384:
1013		case IKEV2_AUTH_ECDSA_521:
1014			if (_dsa_sign_ecdsa(dsa, buf, len) < 0)
1015				return (-1);
1016			return (len);
1017		default:
1018			if (_dsa_sign_encode(dsa, ptr, len, &off) < 0)
1019				return (-1);
1020			if (off > len)
1021				return (-1);
1022			len -= off;
1023			ptr += off;
1024			if (EVP_DigestSignFinal(dsa->dsa_ctx, ptr, &len) != 1)
1025				return (-1);
1026			return (len + off);
1027		}
1028	}
1029	return (-1);
1030}
1031
1032int
1033_dsa_verify_prepare(struct iked_dsa *dsa, uint8_t **sigp, size_t *lenp,
1034    uint8_t **freemep)
1035{
1036	ECDSA_SIG	*obj = NULL;
1037	uint8_t		*ptr = NULL;
1038	size_t		 bnlen, len, off;
1039	int		 ret = -1;
1040
1041	*freemep = NULL;	/* don't return garbage in case of an error */
1042
1043	switch (dsa->dsa_method) {
1044	case IKEV2_AUTH_SIG:
1045		/*
1046		 * The first byte of the signature encodes the OID
1047		 * prefix length which we need to skip.
1048		 */
1049		off = (*sigp)[0] + 1;
1050		*sigp = *sigp + off;
1051		*lenp = *lenp - off;
1052		*freemep = NULL;
1053		ret = 0;
1054		break;
1055	case IKEV2_AUTH_ECDSA_256:
1056	case IKEV2_AUTH_ECDSA_384:
1057	case IKEV2_AUTH_ECDSA_521:
1058		/*
1059		 * sigp points to concatenation r|s, while EVP_VerifyFinal()
1060		 * expects the signature as a DER-encoded blob (of the two
1061		 * values), so we need to convert the signature in a new
1062		 * buffer (we cannot override the given buffer) and the caller
1063		 * has to free this buffer ('freeme').
1064		 */
1065		if (*lenp < 64 || *lenp > 132 || *lenp % 2)
1066			goto done;
1067		bnlen = (*lenp)/2;
1068		/* sigp points to concatenation: r|s */
1069		if ((obj = ECDSA_SIG_new()) == NULL ||
1070		    BN_bin2bn(*sigp, bnlen, obj->r) == NULL ||
1071		    BN_bin2bn(*sigp+bnlen, bnlen, obj->s) == NULL ||
1072		    (len = i2d_ECDSA_SIG(obj, &ptr)) == 0)
1073			goto done;
1074		*lenp = len;
1075		*sigp = ptr;
1076		*freemep = ptr;
1077		ptr = NULL;
1078		ret = 0;
1079		break;
1080	default:
1081		return (0);
1082	}
1083 done:
1084	free(ptr);
1085	if (obj)
1086		ECDSA_SIG_free(obj);
1087	return (ret);
1088}
1089
1090ssize_t
1091dsa_verify_final(struct iked_dsa *dsa, void *buf, size_t len)
1092{
1093	uint8_t		 sig[EVP_MAX_MD_SIZE];
1094	uint8_t		*ptr = buf, *freeme = NULL;
1095	unsigned int	 siglen = sizeof(sig);
1096
1097	if (dsa->dsa_hmac) {
1098		if (!HMAC_Final(dsa->dsa_ctx, sig, &siglen))
1099			return (-1);
1100		if (siglen != len || memcmp(buf, sig, siglen) != 0)
1101			return (-1);
1102	} else {
1103		if (_dsa_verify_prepare(dsa, &ptr, &len, &freeme) < 0)
1104			return (-1);
1105		if (EVP_DigestVerifyFinal(dsa->dsa_ctx, ptr, len) != 1) {
1106			free(freeme);
1107			ca_sslerror(__func__);
1108			return (-1);
1109		}
1110		free(freeme);
1111	}
1112
1113	return (0);
1114}
1115