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