xform_esp.c revision 286000
1/*	$FreeBSD: head/sys/netipsec/xform_esp.c 286000 2015-07-29 07:15:16Z jmg $	*/
2/*	$OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 angelos Exp $ */
3/*-
4 * The authors of this code are John Ioannidis (ji@tla.org),
5 * Angelos D. Keromytis (kermit@csd.uch.gr) and
6 * Niels Provos (provos@physnet.uni-hamburg.de).
7 *
8 * The original version of this code was written by John Ioannidis
9 * for BSD/OS in Athens, Greece, in November 1995.
10 *
11 * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
12 * by Angelos D. Keromytis.
13 *
14 * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
15 * and Niels Provos.
16 *
17 * Additional features in 1999 by Angelos D. Keromytis.
18 *
19 * Copyright (C) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
20 * Angelos D. Keromytis and Niels Provos.
21 * Copyright (c) 2001 Angelos D. Keromytis.
22 *
23 * Permission to use, copy, and modify this software with or without fee
24 * is hereby granted, provided that this entire notice is included in
25 * all copies of any software which is or includes a copy or
26 * modification of this software.
27 * You may use this code under the GNU public license if you so wish. Please
28 * contribute changes back to the authors under this freer than GPL license
29 * so that we may further the use of strong encryption without limitations to
30 * all.
31 *
32 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
33 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
34 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
35 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
36 * PURPOSE.
37 */
38#include "opt_inet.h"
39#include "opt_inet6.h"
40
41#include <sys/param.h>
42#include <sys/systm.h>
43#include <sys/mbuf.h>
44#include <sys/socket.h>
45#include <sys/syslog.h>
46#include <sys/kernel.h>
47#include <sys/lock.h>
48#include <sys/random.h>
49#include <sys/rwlock.h>
50#include <sys/sysctl.h>
51
52#include <net/if.h>
53#include <net/vnet.h>
54
55#include <netinet/in.h>
56#include <netinet/in_systm.h>
57#include <netinet/ip.h>
58#include <netinet/ip_ecn.h>
59#include <netinet/ip6.h>
60
61#include <netipsec/ipsec.h>
62#include <netipsec/ah.h>
63#include <netipsec/ah_var.h>
64#include <netipsec/esp.h>
65#include <netipsec/esp_var.h>
66#include <netipsec/xform.h>
67
68#ifdef INET6
69#include <netinet6/ip6_var.h>
70#include <netipsec/ipsec6.h>
71#include <netinet6/ip6_ecn.h>
72#endif
73
74#include <netipsec/key.h>
75#include <netipsec/key_debug.h>
76
77#include <opencrypto/cryptodev.h>
78#include <opencrypto/xform.h>
79
80VNET_DEFINE(int, esp_enable) = 1;
81VNET_PCPUSTAT_DEFINE(struct espstat, espstat);
82VNET_PCPUSTAT_SYSINIT(espstat);
83
84#ifdef VIMAGE
85VNET_PCPUSTAT_SYSUNINIT(espstat);
86#endif /* VIMAGE */
87
88SYSCTL_DECL(_net_inet_esp);
89SYSCTL_INT(_net_inet_esp, OID_AUTO, esp_enable,
90	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_enable), 0, "");
91SYSCTL_VNET_PCPUSTAT(_net_inet_esp, IPSECCTL_STATS, stats,
92    struct espstat, espstat,
93    "ESP statistics (struct espstat, netipsec/esp_var.h");
94
95static int esp_input_cb(struct cryptop *op);
96static int esp_output_cb(struct cryptop *crp);
97
98/*
99 * NB: this is public for use by the PF_KEY support.
100 * NB: if you add support here; be sure to add code to esp_attach below!
101 */
102struct enc_xform *
103esp_algorithm_lookup(int alg)
104{
105	if (alg >= ESP_ALG_MAX)
106		return NULL;
107	switch (alg) {
108	case SADB_EALG_DESCBC:
109		return &enc_xform_des;
110	case SADB_EALG_3DESCBC:
111		return &enc_xform_3des;
112	case SADB_X_EALG_AES:
113		return &enc_xform_rijndael128;
114	case SADB_X_EALG_BLOWFISHCBC:
115		return &enc_xform_blf;
116	case SADB_X_EALG_CAST128CBC:
117		return &enc_xform_cast5;
118	case SADB_X_EALG_SKIPJACK:
119		return &enc_xform_skipjack;
120	case SADB_EALG_NULL:
121		return &enc_xform_null;
122	case SADB_X_EALG_CAMELLIACBC:
123		return &enc_xform_camellia;
124	case SADB_X_EALG_AESCTR:
125		return &enc_xform_aes_icm;
126	case SADB_X_EALG_AESGCM16:
127		return &enc_xform_aes_nist_gcm;
128	case SADB_X_EALG_AESGMAC:
129		return &enc_xform_aes_nist_gmac;
130	}
131	return NULL;
132}
133
134size_t
135esp_hdrsiz(struct secasvar *sav)
136{
137	size_t size;
138
139	if (sav != NULL) {
140		/*XXX not right for null algorithm--does it matter??*/
141		IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
142			("SA with null xform"));
143		if (sav->flags & SADB_X_EXT_OLD)
144			size = sizeof (struct esp);
145		else
146			size = sizeof (struct newesp);
147		size += sav->tdb_encalgxform->blocksize + 9;
148		/*XXX need alg check???*/
149		if (sav->tdb_authalgxform != NULL && sav->replay)
150			size += ah_hdrsiz(sav);
151	} else {
152		/*
153		 *   base header size
154		 * + max iv length for CBC mode
155		 * + max pad length
156		 * + sizeof (pad length field)
157		 * + sizeof (next header field)
158		 * + max icv supported.
159		 */
160		size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
161	}
162	return size;
163}
164
165/*
166 * esp_init() is called when an SPI is being set up.
167 */
168static int
169esp_init(struct secasvar *sav, struct xformsw *xsp)
170{
171	struct enc_xform *txform;
172	struct cryptoini cria, crie;
173	int keylen;
174	int error;
175
176	txform = esp_algorithm_lookup(sav->alg_enc);
177	if (txform == NULL) {
178		DPRINTF(("%s: unsupported encryption algorithm %d\n",
179			__func__, sav->alg_enc));
180		return EINVAL;
181	}
182	if (sav->key_enc == NULL) {
183		DPRINTF(("%s: no encoding key for %s algorithm\n",
184			 __func__, txform->name));
185		return EINVAL;
186	}
187	if ((sav->flags&(SADB_X_EXT_OLD|SADB_X_EXT_IV4B)) == SADB_X_EXT_IV4B) {
188		DPRINTF(("%s: 4-byte IV not supported with protocol\n",
189			__func__));
190		return EINVAL;
191	}
192	keylen = _KEYLEN(sav->key_enc);
193	if (txform->minkey > keylen || keylen > txform->maxkey) {
194		DPRINTF(("%s: invalid key length %u, must be in the range "
195			"[%u..%u] for algorithm %s\n", __func__,
196			keylen, txform->minkey, txform->maxkey,
197			txform->name));
198		return EINVAL;
199	}
200
201	/*
202	 * NB: The null xform needs a non-zero blocksize to keep the
203	 *      crypto code happy but if we use it to set ivlen then
204	 *      the ESP header will be processed incorrectly.  The
205	 *      compromise is to force it to zero here.
206	 */
207	sav->ivlen = (txform == &enc_xform_null ? 0 : txform->ivsize);
208	sav->iv = (caddr_t) malloc(sav->ivlen, M_XDATA, M_WAITOK);
209	key_randomfill(sav->iv, sav->ivlen);	/*XXX*/
210
211	/*
212	 * Setup AH-related state.
213	 */
214	if (sav->alg_auth != 0) {
215		error = ah_init0(sav, xsp, &cria);
216		if (error)
217			return error;
218	}
219
220	/* NB: override anything set in ah_init0 */
221	sav->tdb_xform = xsp;
222	sav->tdb_encalgxform = txform;
223
224	/*
225	 * Whenever AES-GCM is used for encryption, one
226	 * of the AES authentication algorithms is chosen
227	 * as well, based on the key size.
228	 */
229	if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
230		switch (keylen) {
231		case AES_128_HMAC_KEY_LEN:
232			sav->alg_auth = SADB_X_AALG_AES128GMAC;
233			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
234			break;
235		case AES_192_HMAC_KEY_LEN:
236			sav->alg_auth = SADB_X_AALG_AES192GMAC;
237			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
238			break;
239		case AES_256_HMAC_KEY_LEN:
240			sav->alg_auth = SADB_X_AALG_AES256GMAC;
241			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
242			break;
243		default:
244			DPRINTF(("%s: invalid key length %u"
245				 "for algorithm %s\n", __func__,
246				 keylen, txform->name));
247			return EINVAL;
248		}
249		bzero(&cria, sizeof(cria));
250		cria.cri_alg = sav->tdb_authalgxform->type;
251		cria.cri_klen = _KEYBITS(sav->key_enc) + 4;
252		cria.cri_key = sav->key_enc->key_data;
253	}
254
255	/* Initialize crypto session. */
256	bzero(&crie, sizeof (crie));
257	crie.cri_alg = sav->tdb_encalgxform->type;
258	crie.cri_klen = _KEYBITS(sav->key_enc);
259	crie.cri_key = sav->key_enc->key_data;
260	if (sav->alg_enc == SADB_X_EALG_AESGCM16)
261		arc4rand(crie.cri_iv, sav->ivlen, 0);
262
263	/* XXX Rounds ? */
264
265	if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
266		/* init both auth & enc */
267		crie.cri_next = &cria;
268		error = crypto_newsession(&sav->tdb_cryptoid,
269					  &crie, V_crypto_support);
270	} else if (sav->tdb_encalgxform) {
271		error = crypto_newsession(&sav->tdb_cryptoid,
272					  &crie, V_crypto_support);
273	} else if (sav->tdb_authalgxform) {
274		error = crypto_newsession(&sav->tdb_cryptoid,
275					  &cria, V_crypto_support);
276	} else {
277		/* XXX cannot happen? */
278		DPRINTF(("%s: no encoding OR authentication xform!\n",
279			__func__));
280		error = EINVAL;
281	}
282	return error;
283}
284
285/*
286 * Paranoia.
287 */
288static int
289esp_zeroize(struct secasvar *sav)
290{
291	/* NB: ah_zerorize free's the crypto session state */
292	int error = ah_zeroize(sav);
293
294	if (sav->key_enc)
295		bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
296	if (sav->iv) {
297		free(sav->iv, M_XDATA);
298		sav->iv = NULL;
299	}
300	sav->tdb_encalgxform = NULL;
301	sav->tdb_xform = NULL;
302	return error;
303}
304
305/*
306 * ESP input processing, called (eventually) through the protocol switch.
307 */
308static int
309esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
310{
311	char buf[128];
312	struct auth_hash *esph;
313	struct enc_xform *espx;
314	struct tdb_crypto *tc;
315	int plen, alen, hlen;
316	struct newesp *esp;
317	struct cryptodesc *crde;
318	struct cryptop *crp;
319
320	IPSEC_ASSERT(sav != NULL, ("null SA"));
321	IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
322
323	/* Valid IP Packet length ? */
324	if ( (skip&3) || (m->m_pkthdr.len&3) ){
325		DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
326				__func__, skip, m->m_pkthdr.len));
327		ESPSTAT_INC(esps_badilen);
328		m_freem(m);
329		return EINVAL;
330	}
331	/* XXX don't pullup, just copy header */
332	IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
333
334	esph = sav->tdb_authalgxform;
335	espx = sav->tdb_encalgxform;
336
337	/* Determine the ESP header and auth length */
338	if (sav->flags & SADB_X_EXT_OLD)
339		hlen = sizeof (struct esp) + sav->ivlen;
340	else
341		hlen = sizeof (struct newesp) + sav->ivlen;
342
343	alen = xform_ah_authsize(esph);
344
345	/*
346	 * Verify payload length is multiple of encryption algorithm
347	 * block size.
348	 *
349	 * NB: This works for the null algorithm because the blocksize
350	 *     is 4 and all packets must be 4-byte aligned regardless
351	 *     of the algorithm.
352	 */
353	plen = m->m_pkthdr.len - (skip + hlen + alen);
354	if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
355		if (!espx || sav->alg_enc != SADB_X_EALG_AESGCM16) {
356			DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
357				"  SA %s/%08lx\n", __func__,
358				plen, espx->blocksize, ipsec_address(&sav->sah->saidx.dst,
359				buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
360			ESPSTAT_INC(esps_badilen);
361			m_freem(m);
362			return EINVAL;
363		}
364	}
365
366	/*
367	 * Check sequence number.
368	 */
369	if (esph != NULL && sav->replay != NULL &&
370	    !ipsec_chkreplay(ntohl(esp->esp_seq), sav)) {
371		DPRINTF(("%s: packet replay check for %s\n", __func__,
372		    ipsec_logsastr(sav, buf, sizeof(buf))));	/*XXX*/
373		ESPSTAT_INC(esps_replay);
374		m_freem(m);
375		return ENOBUFS;		/*XXX*/
376	}
377
378	/* Update the counters */
379	ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
380
381	/* Get crypto descriptors */
382	crp = crypto_getreq(esph && espx ? 2 : 1);
383	if (crp == NULL) {
384		DPRINTF(("%s: failed to acquire crypto descriptors\n",
385			__func__));
386		ESPSTAT_INC(esps_crypto);
387		m_freem(m);
388		return ENOBUFS;
389	}
390
391	/* Get IPsec-specific opaque pointer */
392	tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto) + alen,
393	    M_XDATA, M_NOWAIT | M_ZERO);
394	if (tc == NULL) {
395		crypto_freereq(crp);
396		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
397		ESPSTAT_INC(esps_crypto);
398		m_freem(m);
399		return ENOBUFS;
400	}
401
402	if (esph != NULL) {
403		struct cryptodesc *crda = crp->crp_desc;
404
405		IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
406
407		/* Authentication descriptor */
408		crda->crd_skip = skip;
409		if (espx && espx->type == CRYPTO_AES_NIST_GCM_16)
410			crda->crd_len = hlen - sav->ivlen;
411		else
412			crda->crd_len = m->m_pkthdr.len - (skip + alen);
413		crda->crd_inject = m->m_pkthdr.len - alen;
414
415		crda->crd_alg = esph->type;
416		if (espx && (espx->type == CRYPTO_AES_NIST_GCM_16)) {
417			crda->crd_key = sav->key_enc->key_data;
418			crda->crd_klen = _KEYBITS(sav->key_enc);
419		} else {
420			crda->crd_key = sav->key_auth->key_data;
421			crda->crd_klen = _KEYBITS(sav->key_auth);
422		}
423
424		/* Copy the authenticator */
425		m_copydata(m, m->m_pkthdr.len - alen, alen,
426		    (caddr_t) (tc + 1));
427
428		/* Chain authentication request */
429		crde = crda->crd_next;
430	} else {
431		crde = crp->crp_desc;
432	}
433
434	/* Crypto operation descriptor */
435	crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
436	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
437	crp->crp_buf = (caddr_t) m;
438	crp->crp_callback = esp_input_cb;
439	crp->crp_sid = sav->tdb_cryptoid;
440	crp->crp_opaque = (caddr_t) tc;
441
442	/* These are passed as-is to the callback */
443	tc->tc_spi = sav->spi;
444	tc->tc_dst = sav->sah->saidx.dst;
445	tc->tc_proto = sav->sah->saidx.proto;
446	tc->tc_protoff = protoff;
447	tc->tc_skip = skip;
448	KEY_ADDREFSA(sav);
449	tc->tc_sav = sav;
450
451	/* Decryption descriptor */
452	IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
453	crde->crd_skip = skip + hlen;
454	crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
455	crde->crd_inject = skip + hlen - sav->ivlen;
456
457	crde->crd_alg = espx->type;
458	crde->crd_key = sav->key_enc->key_data;
459	crde->crd_klen = _KEYBITS(sav->key_enc);
460	if (espx && (espx->type == CRYPTO_AES_NIST_GCM_16))
461		crde->crd_flags |= CRD_F_IV_EXPLICIT;
462
463	/* XXX Rounds ? */
464
465	return (crypto_dispatch(crp));
466}
467
468/*
469 * ESP input callback from the crypto driver.
470 */
471static int
472esp_input_cb(struct cryptop *crp)
473{
474	char buf[128];
475	u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
476	int hlen, skip, protoff, error, alen;
477	struct mbuf *m;
478	struct cryptodesc *crd;
479	struct auth_hash *esph;
480	struct enc_xform *espx;
481	struct tdb_crypto *tc;
482	struct secasvar *sav;
483	struct secasindex *saidx;
484	caddr_t ptr;
485
486	crd = crp->crp_desc;
487	IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
488
489	tc = (struct tdb_crypto *) crp->crp_opaque;
490	IPSEC_ASSERT(tc != NULL, ("null opaque crypto data area!"));
491	skip = tc->tc_skip;
492	protoff = tc->tc_protoff;
493	m = (struct mbuf *) crp->crp_buf;
494
495	sav = tc->tc_sav;
496	IPSEC_ASSERT(sav != NULL, ("null SA!"));
497
498	saidx = &sav->sah->saidx;
499	IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
500		saidx->dst.sa.sa_family == AF_INET6,
501		("unexpected protocol family %u", saidx->dst.sa.sa_family));
502
503	esph = sav->tdb_authalgxform;
504	espx = sav->tdb_encalgxform;
505
506	/* Check for crypto errors */
507	if (crp->crp_etype) {
508		/* Reset the session ID */
509		if (sav->tdb_cryptoid != 0)
510			sav->tdb_cryptoid = crp->crp_sid;
511
512		if (crp->crp_etype == EAGAIN)
513			return (crypto_dispatch(crp));
514
515		ESPSTAT_INC(esps_noxform);
516		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
517		error = crp->crp_etype;
518		goto bad;
519	}
520
521	/* Shouldn't happen... */
522	if (m == NULL) {
523		ESPSTAT_INC(esps_crypto);
524		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
525		error = EINVAL;
526		goto bad;
527	}
528	ESPSTAT_INC(esps_hist[sav->alg_enc]);
529
530	/* If authentication was performed, check now. */
531	if (esph != NULL) {
532		alen = xform_ah_authsize(esph);
533		AHSTAT_INC(ahs_hist[sav->alg_auth]);
534		/* Copy the authenticator from the packet */
535		m_copydata(m, m->m_pkthdr.len - alen, alen, aalg);
536		ptr = (caddr_t) (tc + 1);
537
538		/* Verify authenticator */
539		if (bcmp(ptr, aalg, alen) != 0) {
540			DPRINTF(("%s: authentication hash mismatch for "
541			    "packet in SA %s/%08lx\n", __func__,
542			    ipsec_address(&saidx->dst, buf, sizeof(buf)),
543			    (u_long) ntohl(sav->spi)));
544			ESPSTAT_INC(esps_badauth);
545			error = EACCES;
546			goto bad;
547		}
548
549		/* Remove trailing authenticator */
550		m_adj(m, -alen);
551	}
552
553	/* Release the crypto descriptors */
554	free(tc, M_XDATA), tc = NULL;
555	crypto_freereq(crp), crp = NULL;
556
557	/*
558	 * Packet is now decrypted.
559	 */
560	m->m_flags |= M_DECRYPTED;
561
562	/*
563	 * Update replay sequence number, if appropriate.
564	 */
565	if (sav->replay) {
566		u_int32_t seq;
567
568		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
569			   sizeof (seq), (caddr_t) &seq);
570		if (ipsec_updatereplay(ntohl(seq), sav)) {
571			DPRINTF(("%s: packet replay check for %s\n", __func__,
572			    ipsec_logsastr(sav, buf, sizeof(buf))));
573			ESPSTAT_INC(esps_replay);
574			error = ENOBUFS;
575			goto bad;
576		}
577	}
578
579	/* Determine the ESP header length */
580	if (sav->flags & SADB_X_EXT_OLD)
581		hlen = sizeof (struct esp) + sav->ivlen;
582	else
583		hlen = sizeof (struct newesp) + sav->ivlen;
584
585	/* Remove the ESP header and IV from the mbuf. */
586	error = m_striphdr(m, skip, hlen);
587	if (error) {
588		ESPSTAT_INC(esps_hdrops);
589		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
590		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
591		    (u_long) ntohl(sav->spi)));
592		goto bad;
593	}
594
595	/* Save the last three bytes of decrypted data */
596	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
597
598	/* Verify pad length */
599	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
600		ESPSTAT_INC(esps_badilen);
601		DPRINTF(("%s: invalid padding length %d for %u byte packet "
602		    "in SA %s/%08lx\n", __func__, lastthree[1],
603		    m->m_pkthdr.len - skip,
604		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
605		    (u_long) ntohl(sav->spi)));
606		error = EINVAL;
607		goto bad;
608	}
609
610	/* Verify correct decryption by checking the last padding bytes */
611	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
612		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
613			ESPSTAT_INC(esps_badenc);
614			DPRINTF(("%s: decryption failed for packet in "
615			    "SA %s/%08lx\n", __func__, ipsec_address(
616			    &sav->sah->saidx.dst, buf, sizeof(buf)),
617			    (u_long) ntohl(sav->spi)));
618			error = EINVAL;
619			goto bad;
620		}
621	}
622
623	/* Trim the mbuf chain to remove trailing authenticator and padding */
624	m_adj(m, -(lastthree[1] + 2));
625
626	/* Restore the Next Protocol field */
627	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
628
629	switch (saidx->dst.sa.sa_family) {
630#ifdef INET6
631	case AF_INET6:
632		error = ipsec6_common_input_cb(m, sav, skip, protoff);
633		break;
634#endif
635#ifdef INET
636	case AF_INET:
637		error = ipsec4_common_input_cb(m, sav, skip, protoff);
638		break;
639#endif
640	default:
641		panic("%s: Unexpected address family: %d saidx=%p", __func__,
642		    saidx->dst.sa.sa_family, saidx);
643	}
644
645	KEY_FREESAV(&sav);
646	return error;
647bad:
648	if (sav)
649		KEY_FREESAV(&sav);
650	if (m != NULL)
651		m_freem(m);
652	if (tc != NULL)
653		free(tc, M_XDATA);
654	if (crp != NULL)
655		crypto_freereq(crp);
656	return error;
657}
658
659/*
660 * ESP output routine, called by ipsec[46]_process_packet().
661 */
662static int
663esp_output(struct mbuf *m, struct ipsecrequest *isr, struct mbuf **mp,
664    int skip, int protoff)
665{
666	char buf[INET6_ADDRSTRLEN];
667	struct enc_xform *espx;
668	struct auth_hash *esph;
669	int hlen, rlen, padding, blks, alen, i, roff;
670	struct mbuf *mo = (struct mbuf *) NULL;
671	struct tdb_crypto *tc;
672	struct secasvar *sav;
673	struct secasindex *saidx;
674	unsigned char *pad;
675	u_int8_t prot;
676	int error, maxpacketsize;
677
678	struct cryptodesc *crde = NULL, *crda = NULL;
679	struct cryptop *crp;
680
681	sav = isr->sav;
682	IPSEC_ASSERT(sav != NULL, ("null SA"));
683	esph = sav->tdb_authalgxform;
684	espx = sav->tdb_encalgxform;
685	IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
686
687	if (sav->flags & SADB_X_EXT_OLD)
688		hlen = sizeof (struct esp) + sav->ivlen;
689	else
690		hlen = sizeof (struct newesp) + sav->ivlen;
691
692	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
693	/*
694	 * NB: The null encoding transform has a blocksize of 4
695	 *     so that headers are properly aligned.
696	 */
697	blks = espx->ivsize;		/* IV blocksize */
698
699	/* XXX clamp padding length a la KAME??? */
700	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
701
702	alen = xform_ah_authsize(esph);
703
704	ESPSTAT_INC(esps_output);
705
706	saidx = &sav->sah->saidx;
707	/* Check for maximum packet size violations. */
708	switch (saidx->dst.sa.sa_family) {
709#ifdef INET
710	case AF_INET:
711		maxpacketsize = IP_MAXPACKET;
712		break;
713#endif /* INET */
714#ifdef INET6
715	case AF_INET6:
716		maxpacketsize = IPV6_MAXPACKET;
717		break;
718#endif /* INET6 */
719	default:
720		DPRINTF(("%s: unknown/unsupported protocol "
721		    "family %d, SA %s/%08lx\n", __func__,
722		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
723			buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
724		ESPSTAT_INC(esps_nopf);
725		error = EPFNOSUPPORT;
726		goto bad;
727	}
728	DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
729		__func__, skip, hlen, rlen, padding, alen, blks));
730	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
731		DPRINTF(("%s: packet in SA %s/%08lx got too big "
732		    "(len %u, max len %u)\n", __func__,
733		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
734		    (u_long) ntohl(sav->spi),
735		    skip + hlen + rlen + padding + alen, maxpacketsize));
736		ESPSTAT_INC(esps_toobig);
737		error = EMSGSIZE;
738		goto bad;
739	}
740
741	/* Update the counters. */
742	ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
743
744	m = m_unshare(m, M_NOWAIT);
745	if (m == NULL) {
746		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
747		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
748		    (u_long) ntohl(sav->spi)));
749		ESPSTAT_INC(esps_hdrops);
750		error = ENOBUFS;
751		goto bad;
752	}
753
754	/* Inject ESP header. */
755	mo = m_makespace(m, skip, hlen, &roff);
756	if (mo == NULL) {
757		DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
758		    __func__, hlen, ipsec_address(&saidx->dst, buf,
759		    sizeof(buf)), (u_long) ntohl(sav->spi)));
760		ESPSTAT_INC(esps_hdrops);		/* XXX diffs from openbsd */
761		error = ENOBUFS;
762		goto bad;
763	}
764
765	/* Initialize ESP header. */
766	bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff, sizeof(u_int32_t));
767	if (sav->replay) {
768		u_int32_t replay;
769
770#ifdef REGRESSION
771		/* Emulate replay attack when ipsec_replay is TRUE. */
772		if (!V_ipsec_replay)
773#endif
774			sav->replay->count++;
775		replay = htonl(sav->replay->count);
776		bcopy((caddr_t) &replay,
777		    mtod(mo, caddr_t) + roff + sizeof(u_int32_t),
778		    sizeof(u_int32_t));
779	}
780
781	/*
782	 * Add padding -- better to do it ourselves than use the crypto engine,
783	 * although if/when we support compression, we'd have to do that.
784	 */
785	pad = (u_char *) m_pad(m, padding + alen);
786	if (pad == NULL) {
787		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
788		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
789		    (u_long) ntohl(sav->spi)));
790		m = NULL;		/* NB: free'd by m_pad */
791		error = ENOBUFS;
792		goto bad;
793	}
794
795	/*
796	 * Add padding: random, zero, or self-describing.
797	 * XXX catch unexpected setting
798	 */
799	switch (sav->flags & SADB_X_EXT_PMASK) {
800	case SADB_X_EXT_PRAND:
801		(void) read_random(pad, padding - 2);
802		break;
803	case SADB_X_EXT_PZERO:
804		bzero(pad, padding - 2);
805		break;
806	case SADB_X_EXT_PSEQ:
807		for (i = 0; i < padding - 2; i++)
808			pad[i] = i+1;
809		break;
810	}
811
812	/* Fix padding length and Next Protocol in padding itself. */
813	pad[padding - 2] = padding - 2;
814	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
815
816	/* Fix Next Protocol in IPv4/IPv6 header. */
817	prot = IPPROTO_ESP;
818	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
819
820	/* Get crypto descriptors. */
821	crp = crypto_getreq(esph && espx ? 2 : 1);
822	if (crp == NULL) {
823		DPRINTF(("%s: failed to acquire crypto descriptors\n",
824			__func__));
825		ESPSTAT_INC(esps_crypto);
826		error = ENOBUFS;
827		goto bad;
828	}
829
830	if (espx) {
831		crde = crp->crp_desc;
832		crda = crde->crd_next;
833
834		/* Encryption descriptor. */
835		crde->crd_skip = skip + hlen;
836		crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
837		crde->crd_flags = CRD_F_ENCRYPT;
838		crde->crd_inject = skip + hlen - sav->ivlen;
839
840		/* Encryption operation. */
841		crde->crd_alg = espx->type;
842		crde->crd_key = sav->key_enc->key_data;
843		crde->crd_klen = _KEYBITS(sav->key_enc);
844		if (espx->type == CRYPTO_AES_NIST_GCM_16)
845			crde->crd_flags |= CRD_F_IV_EXPLICIT;
846		/* XXX Rounds ? */
847	} else
848		crda = crp->crp_desc;
849
850	/* IPsec-specific opaque crypto info. */
851	tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
852		M_XDATA, M_NOWAIT|M_ZERO);
853	if (tc == NULL) {
854		crypto_freereq(crp);
855		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
856		ESPSTAT_INC(esps_crypto);
857		error = ENOBUFS;
858		goto bad;
859	}
860
861	/* Callback parameters */
862	tc->tc_isr = isr;
863	KEY_ADDREFSA(sav);
864	tc->tc_sav = sav;
865	tc->tc_spi = sav->spi;
866	tc->tc_dst = saidx->dst;
867	tc->tc_proto = saidx->proto;
868
869	/* Crypto operation descriptor. */
870	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
871	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
872	crp->crp_buf = (caddr_t) m;
873	crp->crp_callback = esp_output_cb;
874	crp->crp_opaque = (caddr_t) tc;
875	crp->crp_sid = sav->tdb_cryptoid;
876
877	if (esph) {
878		/* Authentication descriptor. */
879		crda->crd_skip = skip;
880		if (espx && espx->type == CRYPTO_AES_NIST_GCM_16)
881			crda->crd_len = hlen - sav->ivlen;
882		else
883			crda->crd_len = m->m_pkthdr.len - (skip + alen);
884		crda->crd_inject = m->m_pkthdr.len - alen;
885
886		/* Authentication operation. */
887		crda->crd_alg = esph->type;
888		if (espx && espx->type == CRYPTO_AES_NIST_GCM_16) {
889			crda->crd_key = sav->key_enc->key_data;
890			crda->crd_klen = _KEYBITS(sav->key_enc);
891		} else {
892			crda->crd_key = sav->key_auth->key_data;
893			crda->crd_klen = _KEYBITS(sav->key_auth);
894		}
895
896	}
897
898	return crypto_dispatch(crp);
899bad:
900	if (m)
901		m_freem(m);
902	return (error);
903}
904
905/*
906 * ESP output callback from the crypto driver.
907 */
908static int
909esp_output_cb(struct cryptop *crp)
910{
911	char buf[INET6_ADDRSTRLEN];
912	struct tdb_crypto *tc;
913	struct ipsecrequest *isr;
914	struct secasvar *sav;
915	struct mbuf *m;
916	int error;
917
918	tc = (struct tdb_crypto *) crp->crp_opaque;
919	IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
920	m = (struct mbuf *) crp->crp_buf;
921
922	isr = tc->tc_isr;
923	IPSEC_ASSERT(isr->sp != NULL, ("NULL isr->sp"));
924	IPSECREQUEST_LOCK(isr);
925	sav = tc->tc_sav;
926	/* With the isr lock released SA pointer can be updated. */
927	if (sav != isr->sav) {
928		ESPSTAT_INC(esps_notdb);
929		DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
930		    __func__, ipsec_address(&tc->tc_dst, buf, sizeof(buf)),
931		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
932		error = ENOBUFS;		/*XXX*/
933		goto bad;
934	}
935
936	/* Check for crypto errors. */
937	if (crp->crp_etype) {
938		/* Reset session ID. */
939		if (sav->tdb_cryptoid != 0)
940			sav->tdb_cryptoid = crp->crp_sid;
941
942		if (crp->crp_etype == EAGAIN) {
943			IPSECREQUEST_UNLOCK(isr);
944			return (crypto_dispatch(crp));
945		}
946
947		ESPSTAT_INC(esps_noxform);
948		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
949		error = crp->crp_etype;
950		goto bad;
951	}
952
953	/* Shouldn't happen... */
954	if (m == NULL) {
955		ESPSTAT_INC(esps_crypto);
956		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
957		error = EINVAL;
958		goto bad;
959	}
960	ESPSTAT_INC(esps_hist[sav->alg_enc]);
961	if (sav->tdb_authalgxform != NULL)
962		AHSTAT_INC(ahs_hist[sav->alg_auth]);
963
964	/* Release crypto descriptors. */
965	free(tc, M_XDATA);
966	crypto_freereq(crp);
967
968#ifdef REGRESSION
969	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
970	if (V_ipsec_integrity) {
971		static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
972		struct auth_hash *esph;
973
974		/*
975		 * Corrupt HMAC if we want to test integrity verification of
976		 * the other side.
977		 */
978		esph = sav->tdb_authalgxform;
979		if (esph !=  NULL) {
980			int alen;
981
982			alen = xform_ah_authsize(esph);
983			m_copyback(m, m->m_pkthdr.len - alen,
984			    alen, ipseczeroes);
985		}
986	}
987#endif
988
989	/* NB: m is reclaimed by ipsec_process_done. */
990	error = ipsec_process_done(m, isr);
991	KEY_FREESAV(&sav);
992	IPSECREQUEST_UNLOCK(isr);
993	KEY_FREESP(&isr->sp);
994	return (error);
995bad:
996	if (sav)
997		KEY_FREESAV(&sav);
998	IPSECREQUEST_UNLOCK(isr);
999	KEY_FREESP(&isr->sp);
1000	if (m)
1001		m_freem(m);
1002	free(tc, M_XDATA);
1003	crypto_freereq(crp);
1004	return (error);
1005}
1006
1007static struct xformsw esp_xformsw = {
1008	XF_ESP,		XFT_CONF|XFT_AUTH,	"IPsec ESP",
1009	esp_init,	esp_zeroize,		esp_input,
1010	esp_output
1011};
1012
1013static void
1014esp_attach(void)
1015{
1016
1017	xform_register(&esp_xformsw);
1018}
1019SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, esp_attach, NULL);
1020