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