Home | History | Annotate | Line # | Download | only in netipsec
xform_esp.c revision 1.48
      1 /*	$NetBSD: xform_esp.c,v 1.48 2017/04/10 14:19:22 christos 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.48 2017/04/10 14:19:22 christos 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, *cr;
    187 	int keylen;
    188 	int error;
    189 
    190 	txform = esp_algorithm_lookup(sav->alg_enc);
    191 	if (txform == NULL) {
    192 		DPRINTF(("%s: unsupported encryption algorithm %d\n", __func__,
    193 		    sav->alg_enc));
    194 		return EINVAL;
    195 	}
    196 	if (sav->key_enc == NULL) {
    197 		DPRINTF(("%s: no encoding key for %s algorithm\n", __func__,
    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(("%s: 4-byte IV not supported with protocol\n",
    203 		    __func__));
    204 		return EINVAL;
    205 	}
    206 	keylen = _KEYLEN(sav->key_enc);
    207 	if (txform->minkey > keylen || keylen > txform->maxkey) {
    208 		DPRINTF(("%s: invalid key length %u, must be in "
    209 		    "the range [%u..%u] for algorithm %s\n", __func__,
    210 		    keylen, txform->minkey, txform->maxkey, 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 	switch (sav->alg_enc) {
    230 	case SADB_X_EALG_AESGCM16:
    231 	case SADB_X_EALG_AESGMAC:
    232 		switch (keylen) {
    233 		case 20:
    234 			sav->alg_auth = SADB_X_AALG_AES128GMAC;
    235 			sav->tdb_authalgxform = &auth_hash_gmac_aes_128;
    236 			break;
    237 		case 28:
    238 			sav->alg_auth = SADB_X_AALG_AES192GMAC;
    239 			sav->tdb_authalgxform = &auth_hash_gmac_aes_192;
    240 			break;
    241 		case 36:
    242 			sav->alg_auth = SADB_X_AALG_AES256GMAC;
    243 			sav->tdb_authalgxform = &auth_hash_gmac_aes_256;
    244 			break;
    245 		default:
    246 			DPRINTF(("%s: invalid key length %u, must be either of "
    247 				"20, 28 or 36\n", __func__, keylen));
    248 			return EINVAL;
    249                 }
    250 
    251 		memset(&cria, 0, sizeof(cria));
    252 		cria.cri_alg = sav->tdb_authalgxform->type;
    253 		cria.cri_klen = _KEYBITS(sav->key_enc);
    254 		cria.cri_key = _KEYBUF(sav->key_enc);
    255 		break;
    256 	default:
    257 		break;
    258 	}
    259 
    260 	/* Initialize crypto session. */
    261 	memset(&crie, 0, sizeof (crie));
    262 	crie.cri_alg = sav->tdb_encalgxform->type;
    263 	crie.cri_klen = _KEYBITS(sav->key_enc);
    264 	crie.cri_key = _KEYBUF(sav->key_enc);
    265 	/* XXX Rounds ? */
    266 
    267 	if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
    268 		/* init both auth & enc */
    269 		crie.cri_next = &cria;
    270 		cr = &crie;
    271 	} else if (sav->tdb_encalgxform) {
    272 		cr = &crie;
    273 	} else if (sav->tdb_authalgxform) {
    274 		cr = &cria;
    275 	} else {
    276 		/* XXX cannot happen? */
    277 		DPRINTF(("%s: no encoding OR authentication xform!\n",
    278 		    __func__));
    279 		return EINVAL;
    280 	}
    281 
    282 	return crypto_newsession(&sav->tdb_cryptoid, cr, crypto_support);
    283 }
    284 
    285 /*
    286  * Paranoia.
    287  */
    288 static int
    289 esp_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 		memset(_KEYBUF(sav->key_enc), 0, _KEYLEN(sav->key_enc));
    296 	sav->tdb_encalgxform = NULL;
    297 	sav->tdb_xform = NULL;
    298 	return error;
    299 }
    300 
    301 /*
    302  * ESP input processing, called (eventually) through the protocol switch.
    303  */
    304 static int
    305 esp_input(struct mbuf *m, const struct secasvar *sav, int skip, int protoff)
    306 {
    307 	const struct auth_hash *esph;
    308 	const struct enc_xform *espx;
    309 	struct tdb_ident *tdbi;
    310 	struct tdb_crypto *tc;
    311 	int plen, alen, hlen, error;
    312 	struct m_tag *mtag;
    313 	struct newesp *esp;
    314 
    315 	struct cryptodesc *crde;
    316 	struct cryptop *crp;
    317 
    318 	IPSEC_SPLASSERT_SOFTNET("esp_input");
    319 
    320 	IPSEC_ASSERT(sav != NULL, ("esp_input: null SA"));
    321 	IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
    322 		("esp_input: null encoding xform"));
    323 	IPSEC_ASSERT((skip&3) == 0 && (m->m_pkthdr.len&3) == 0,
    324 		("esp_input: misaligned packet, skip %u pkt len %u",
    325 			skip, m->m_pkthdr.len));
    326 
    327 	/* XXX don't pullup, just copy header */
    328 	IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
    329 
    330 	esph = sav->tdb_authalgxform;
    331 	espx = sav->tdb_encalgxform;
    332 
    333 	/* Determine the ESP header length */
    334 	if (sav->flags & SADB_X_EXT_OLD)
    335 		hlen = sizeof (struct esp) + sav->ivlen;
    336 	else
    337 		hlen = sizeof (struct newesp) + sav->ivlen;
    338 	/* Authenticator hash size */
    339 	alen = esph ? esph->authsize : 0;
    340 
    341 	/*
    342 	 * Verify payload length is multiple of encryption algorithm
    343 	 * block size.
    344 	 *
    345 	 * NB: This works for the null algorithm because the blocksize
    346 	 *     is 4 and all packets must be 4-byte aligned regardless
    347 	 *     of the algorithm.
    348 	 */
    349 	plen = m->m_pkthdr.len - (skip + hlen + alen);
    350 	if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
    351 		DPRINTF(("esp_input: "
    352 		    "payload of %d octets not a multiple of %d octets,"
    353 		    "  SA %s/%08lx\n",
    354 		    plen, espx->blocksize,
    355 		    ipsec_address(&sav->sah->saidx.dst),
    356 		    (u_long) ntohl(sav->spi)));
    357 		ESP_STATINC(ESP_STAT_BADILEN);
    358 		m_freem(m);
    359 		return EINVAL;
    360 	}
    361 
    362 	/*
    363 	 * Check sequence number.
    364 	 */
    365 	if (esph && sav->replay && !ipsec_chkreplay(ntohl(esp->esp_seq), sav)) {
    366 		DPRINTF(("esp_input: packet replay check for %s\n",
    367 		    ipsec_logsastr(sav)));	/*XXX*/
    368 		ESP_STATINC(ESP_STAT_REPLAY);
    369 		m_freem(m);
    370 		return ENOBUFS;		/*XXX*/
    371 	}
    372 
    373 	/* Update the counters */
    374 	ESP_STATADD(ESP_STAT_IBYTES, m->m_pkthdr.len - skip - hlen - alen);
    375 
    376 	/* Find out if we've already done crypto */
    377 	for (mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, NULL);
    378 	     mtag != NULL;
    379 	     mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, mtag)) {
    380 		tdbi = (struct tdb_ident *) (mtag + 1);
    381 		if (tdbi->proto == sav->sah->saidx.proto &&
    382 		    tdbi->spi == sav->spi &&
    383 		    !memcmp(&tdbi->dst, &sav->sah->saidx.dst,
    384 			  sizeof(union sockaddr_union)))
    385 			break;
    386 	}
    387 
    388 	/* Get crypto descriptors */
    389 	crp = crypto_getreq(esph && espx ? 2 : 1);
    390 	if (crp == NULL) {
    391 		DPRINTF(("esp_input: failed to acquire crypto descriptors\n"));
    392 		ESP_STATINC(ESP_STAT_CRYPTO);
    393 		m_freem(m);
    394 		return ENOBUFS;
    395 	}
    396 
    397 	/* Get IPsec-specific opaque pointer */
    398 	if (esph == NULL || mtag != NULL)
    399 		tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
    400 		    M_XDATA, M_NOWAIT|M_ZERO);
    401 	else
    402 		tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto) + alen,
    403 		    M_XDATA, M_NOWAIT|M_ZERO);
    404 	if (tc == NULL) {
    405 		crypto_freereq(crp);
    406 		DPRINTF(("esp_input: failed to allocate tdb_crypto\n"));
    407 		ESP_STATINC(ESP_STAT_CRYPTO);
    408 		m_freem(m);
    409 		return ENOBUFS;
    410 	}
    411 
    412 	error = m_makewritable(&m, 0, m->m_pkthdr.len, M_NOWAIT);
    413 	if (error) {
    414 		m_freem(m);
    415 		free(tc, M_XDATA);
    416 		crypto_freereq(crp);
    417 		DPRINTF(("esp_input: m_makewritable failed\n"));
    418 		ESP_STATINC(ESP_STAT_CRYPTO);
    419 		return error;
    420 	}
    421 
    422 	tc->tc_ptr = mtag;
    423 
    424 	if (esph) {
    425 		struct cryptodesc *crda = crp->crp_desc;
    426 
    427 		IPSEC_ASSERT(crda != NULL, ("esp_input: null ah crypto descriptor"));
    428 
    429 		/* Authentication descriptor */
    430 		crda->crd_skip = skip;
    431 		if (espx && espx->type == CRYPTO_AES_GCM_16)
    432 			crda->crd_len = hlen - sav->ivlen;
    433 		else
    434 			crda->crd_len = m->m_pkthdr.len - (skip + alen);
    435 		crda->crd_inject = m->m_pkthdr.len - alen;
    436 
    437 		crda->crd_alg = esph->type;
    438 		if (espx && (espx->type == CRYPTO_AES_GCM_16 ||
    439 			     espx->type == CRYPTO_AES_GMAC)) {
    440 			crda->crd_key = _KEYBUF(sav->key_enc);
    441 			crda->crd_klen = _KEYBITS(sav->key_enc);
    442 		} else {
    443 			crda->crd_key = _KEYBUF(sav->key_auth);
    444 			crda->crd_klen = _KEYBITS(sav->key_auth);
    445 		}
    446 
    447 		/* Copy the authenticator */
    448 		if (mtag == NULL)
    449 			m_copydata(m, m->m_pkthdr.len - alen, alen,
    450 				      (tc + 1));
    451 
    452 		/* Chain authentication request */
    453 		crde = crda->crd_next;
    454 	} else {
    455 		crde = crp->crp_desc;
    456 	}
    457 
    458 	/* Crypto operation descriptor */
    459 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
    460 	crp->crp_flags = CRYPTO_F_IMBUF;
    461 	crp->crp_buf = m;
    462 	crp->crp_callback = esp_input_cb;
    463 	crp->crp_sid = sav->tdb_cryptoid;
    464 	crp->crp_opaque = tc;
    465 
    466 	/* These are passed as-is to the callback */
    467 	tc->tc_spi = sav->spi;
    468 	tc->tc_dst = sav->sah->saidx.dst;
    469 	tc->tc_proto = sav->sah->saidx.proto;
    470 	tc->tc_protoff = protoff;
    471 	tc->tc_skip = skip;
    472 
    473 	/* Decryption descriptor */
    474 	if (espx) {
    475 		IPSEC_ASSERT(crde != NULL, ("esp_input: null esp crypto descriptor"));
    476 		crde->crd_skip = skip + hlen;
    477 		if (espx->type == CRYPTO_AES_GMAC)
    478 			crde->crd_len = 0;
    479 		else
    480 			crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
    481 		crde->crd_inject = skip + hlen - sav->ivlen;
    482 
    483 		crde->crd_alg = espx->type;
    484 		crde->crd_key = _KEYBUF(sav->key_enc);
    485 		crde->crd_klen = _KEYBITS(sav->key_enc);
    486 		/* XXX Rounds ? */
    487 	}
    488 
    489 	if (mtag == NULL)
    490 		return crypto_dispatch(crp);
    491 	else
    492 		return esp_input_cb(crp);
    493 }
    494 
    495 #ifdef INET6
    496 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag) do {		     \
    497 	if (saidx->dst.sa.sa_family == AF_INET6) {			     \
    498 		error = ipsec6_common_input_cb(m, sav, skip, protoff, mtag); \
    499 	} else {							     \
    500 		error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag); \
    501 	}								     \
    502 } while (0)
    503 #else
    504 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag)		     \
    505 	(error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag))
    506 #endif
    507 
    508 /*
    509  * ESP input callback from the crypto driver.
    510  */
    511 static int
    512 esp_input_cb(struct cryptop *crp)
    513 {
    514 	u_int8_t lastthree[3], aalg[AH_ALEN_MAX];
    515 	int s, hlen, skip, protoff, error;
    516 	struct mbuf *m;
    517 	struct cryptodesc *crd __diagused;
    518 	const struct auth_hash *esph;
    519 	struct tdb_crypto *tc;
    520 	struct m_tag *mtag;
    521 	struct secasvar *sav;
    522 	struct secasindex *saidx;
    523 	void *ptr;
    524 	u_int16_t dport;
    525 	u_int16_t sport;
    526 
    527 	crd = crp->crp_desc;
    528 	IPSEC_ASSERT(crd != NULL, ("esp_input_cb: null crypto descriptor!"));
    529 
    530 	tc = (struct tdb_crypto *) crp->crp_opaque;
    531 	IPSEC_ASSERT(tc != NULL, ("esp_input_cb: null opaque crypto data area!"));
    532 	skip = tc->tc_skip;
    533 	protoff = tc->tc_protoff;
    534 	mtag = (struct m_tag *) tc->tc_ptr;
    535 	m = (struct mbuf *) crp->crp_buf;
    536 
    537 	/* find the source port for NAT-T */
    538 	nat_t_ports_get(m, &dport, &sport);
    539 
    540 	s = splsoftnet();
    541 	mutex_enter(softnet_lock);
    542 
    543 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi, sport, dport);
    544 	if (sav == NULL) {
    545 		ESP_STATINC(ESP_STAT_NOTDB);
    546 		DPRINTF(("esp_input_cb: SA expired while in crypto "
    547 		    "(SA %s/%08lx proto %u)\n", ipsec_address(&tc->tc_dst),
    548 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
    549 		error = ENOBUFS;		/*XXX*/
    550 		goto bad;
    551 	}
    552 
    553 	saidx = &sav->sah->saidx;
    554 	IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
    555 		saidx->dst.sa.sa_family == AF_INET6,
    556 		("esp_input_cb: unexpected protocol family %u",
    557 		 saidx->dst.sa.sa_family));
    558 
    559 	esph = sav->tdb_authalgxform;
    560 
    561 	/* Check for crypto errors */
    562 	if (crp->crp_etype) {
    563 		/* Reset the session ID */
    564 		if (sav->tdb_cryptoid != 0)
    565 			sav->tdb_cryptoid = crp->crp_sid;
    566 
    567 		if (crp->crp_etype == EAGAIN) {
    568 			KEY_FREESAV(&sav);
    569 			mutex_exit(softnet_lock);
    570 			splx(s);
    571 			return crypto_dispatch(crp);
    572 		}
    573 
    574 		ESP_STATINC(ESP_STAT_NOXFORM);
    575 		DPRINTF(("esp_input_cb: crypto error %d\n", crp->crp_etype));
    576 		error = crp->crp_etype;
    577 		goto bad;
    578 	}
    579 
    580 	/* Shouldn't happen... */
    581 	if (m == NULL) {
    582 		ESP_STATINC(ESP_STAT_CRYPTO);
    583 		DPRINTF(("esp_input_cb: bogus returned buffer from crypto\n"));
    584 		error = EINVAL;
    585 		goto bad;
    586 	}
    587 	ESP_STATINC(ESP_STAT_HIST + sav->alg_enc);
    588 
    589 	/* If authentication was performed, check now. */
    590 	if (esph != NULL) {
    591 		/*
    592 		 * If we have a tag, it means an IPsec-aware NIC did
    593 		 * the verification for us.  Otherwise we need to
    594 		 * check the authentication calculation.
    595 		 */
    596 		AH_STATINC(AH_STAT_HIST + sav->alg_auth);
    597 		if (mtag == NULL) {
    598 			/* Copy the authenticator from the packet */
    599 			m_copydata(m, m->m_pkthdr.len - esph->authsize,
    600 				esph->authsize, aalg);
    601 
    602 			ptr = (tc + 1);
    603 
    604 			/* Verify authenticator */
    605 			if (!consttime_memequal(ptr, aalg, esph->authsize)) {
    606 				DPRINTF(("esp_input_cb: "
    607 		    "authentication hash mismatch for packet in SA %s/%08lx\n",
    608 				    ipsec_address(&saidx->dst),
    609 				    (u_long) ntohl(sav->spi)));
    610 				ESP_STATINC(ESP_STAT_BADAUTH);
    611 				error = EACCES;
    612 				goto bad;
    613 			}
    614 		}
    615 
    616 		/* Remove trailing authenticator */
    617 		m_adj(m, -(esph->authsize));
    618 	}
    619 
    620 	/* Release the crypto descriptors */
    621 	free(tc, M_XDATA), tc = NULL;
    622 	crypto_freereq(crp), crp = NULL;
    623 
    624 	/*
    625 	 * Packet is now decrypted.
    626 	 */
    627 	m->m_flags |= M_DECRYPTED;
    628 
    629 	/*
    630 	 * Update replay sequence number, if appropriate.
    631 	 */
    632 	if (sav->replay) {
    633 		u_int32_t seq;
    634 
    635 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
    636 		    sizeof (seq), &seq);
    637 		if (ipsec_updatereplay(ntohl(seq), sav)) {
    638 			DPRINTF(("%s: packet replay check for %s\n", __func__,
    639 			    ipsec_logsastr(sav)));
    640 			ESP_STATINC(ESP_STAT_REPLAY);
    641 			error = ENOBUFS;
    642 			goto bad;
    643 		}
    644 	}
    645 
    646 	/* Determine the ESP header length */
    647 	if (sav->flags & SADB_X_EXT_OLD)
    648 		hlen = sizeof (struct esp) + sav->ivlen;
    649 	else
    650 		hlen = sizeof (struct newesp) + sav->ivlen;
    651 
    652 	/* Remove the ESP header and IV from the mbuf. */
    653 	error = m_striphdr(m, skip, hlen);
    654 	if (error) {
    655 		ESP_STATINC(ESP_STAT_HDROPS);
    656 		DPRINTF(("esp_input_cb: bad mbuf chain, SA %s/%08lx\n",
    657 		    ipsec_address(&sav->sah->saidx.dst),
    658 		    (u_long) ntohl(sav->spi)));
    659 		goto bad;
    660 	}
    661 
    662 	/* Save the last three bytes of decrypted data */
    663 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
    664 
    665 	/* Verify pad length */
    666 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
    667 		ESP_STATINC(ESP_STAT_BADILEN);
    668 		DPRINTF(("esp_input_cb: invalid padding length %d "
    669 			 "for %u byte packet in SA %s/%08lx\n",
    670 			 lastthree[1], m->m_pkthdr.len - skip,
    671 			 ipsec_address(&sav->sah->saidx.dst),
    672 			 (u_long) ntohl(sav->spi)));
    673 		error = EINVAL;
    674 		goto bad;
    675 	}
    676 
    677 	/* Verify correct decryption by checking the last padding bytes */
    678 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
    679 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
    680 			ESP_STATINC(ESP_STAT_BADENC);
    681 			DPRINTF(("esp_input_cb: decryption failed "
    682 				"for packet in SA %s/%08lx\n",
    683 				ipsec_address(&sav->sah->saidx.dst),
    684 				(u_long) ntohl(sav->spi)));
    685 DPRINTF(("esp_input_cb: %x %x\n", lastthree[0], lastthree[1]));
    686 			error = EINVAL;
    687 			goto bad;
    688 		}
    689 	}
    690 
    691 	/* Trim the mbuf chain to remove trailing authenticator and padding */
    692 	m_adj(m, -(lastthree[1] + 2));
    693 
    694 	/* Restore the Next Protocol field */
    695 	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
    696 
    697 	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag);
    698 
    699 	KEY_FREESAV(&sav);
    700 	mutex_exit(softnet_lock);
    701 	splx(s);
    702 	return error;
    703 bad:
    704 	if (sav)
    705 		KEY_FREESAV(&sav);
    706 	mutex_exit(softnet_lock);
    707 	splx(s);
    708 	if (m != NULL)
    709 		m_freem(m);
    710 	if (tc != NULL)
    711 		free(tc, M_XDATA);
    712 	if (crp != NULL)
    713 		crypto_freereq(crp);
    714 	return error;
    715 }
    716 
    717 /*
    718  * ESP output routine, called by ipsec[46]_process_packet().
    719  */
    720 static int
    721 esp_output(
    722     struct mbuf *m,
    723     struct ipsecrequest *isr,
    724     struct mbuf **mp,
    725     int skip,
    726     int protoff
    727 )
    728 {
    729 	const struct enc_xform *espx;
    730 	const struct auth_hash *esph;
    731 	int hlen, rlen, padding, blks, alen, i, roff;
    732 	struct mbuf *mo = NULL;
    733 	struct tdb_crypto *tc;
    734 	const struct secasvar *sav;
    735 	struct secasindex *saidx;
    736 	unsigned char *pad;
    737 	u_int8_t prot;
    738 	int error, maxpacketsize;
    739 
    740 	struct cryptodesc *crde = NULL, *crda = NULL;
    741 	struct cryptop *crp;
    742 
    743 	IPSEC_SPLASSERT_SOFTNET("esp_output");
    744 
    745 	sav = isr->sav;
    746 	IPSEC_ASSERT(sav != NULL, ("esp_output: null SA"));
    747 	esph = sav->tdb_authalgxform;
    748 	espx = sav->tdb_encalgxform;
    749 	IPSEC_ASSERT(espx != NULL, ("esp_output: null encoding xform"));
    750 
    751 	if (sav->flags & SADB_X_EXT_OLD)
    752 		hlen = sizeof (struct esp) + sav->ivlen;
    753 	else
    754 		hlen = sizeof (struct newesp) + sav->ivlen;
    755 
    756 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
    757 	/*
    758 	 * NB: The null encoding transform has a blocksize of 4
    759 	 *     so that headers are properly aligned.
    760 	 */
    761 	blks = espx->blocksize;		/* IV blocksize */
    762 
    763 	/* XXX clamp padding length a la KAME??? */
    764 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
    765 
    766 	if (esph)
    767 		alen = esph->authsize;
    768 	else
    769 		alen = 0;
    770 
    771 	ESP_STATINC(ESP_STAT_OUTPUT);
    772 
    773 	saidx = &sav->sah->saidx;
    774 	/* Check for maximum packet size violations. */
    775 	switch (saidx->dst.sa.sa_family) {
    776 #ifdef INET
    777 	case AF_INET:
    778 		maxpacketsize = IP_MAXPACKET;
    779 		break;
    780 #endif /* INET */
    781 #ifdef INET6
    782 	case AF_INET6:
    783 		maxpacketsize = IPV6_MAXPACKET;
    784 		break;
    785 #endif /* INET6 */
    786 	default:
    787 		DPRINTF(("esp_output: unknown/unsupported protocol "
    788 		    "family %d, SA %s/%08lx\n",
    789 		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst),
    790 		    (u_long) ntohl(sav->spi)));
    791 		ESP_STATINC(ESP_STAT_NOPF);
    792 		error = EPFNOSUPPORT;
    793 		goto bad;
    794 	}
    795 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
    796 		DPRINTF(("esp_output: packet in SA %s/%08lx got too big "
    797 		    "(len %u, max len %u)\n",
    798 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi),
    799 		    skip + hlen + rlen + padding + alen, maxpacketsize));
    800 		ESP_STATINC(ESP_STAT_TOOBIG);
    801 		error = EMSGSIZE;
    802 		goto bad;
    803 	}
    804 
    805 	/* Update the counters. */
    806 	ESP_STATADD(ESP_STAT_OBYTES, m->m_pkthdr.len - skip);
    807 
    808 	m = m_clone(m);
    809 	if (m == NULL) {
    810 		DPRINTF(("esp_output: cannot clone mbuf chain, SA %s/%08lx\n",
    811 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
    812 		ESP_STATINC(ESP_STAT_HDROPS);
    813 		error = ENOBUFS;
    814 		goto bad;
    815 	}
    816 
    817 	/* Inject ESP header. */
    818 	mo = m_makespace(m, skip, hlen, &roff);
    819 	if (mo == NULL) {
    820 		DPRINTF(("esp_output: failed to inject %u byte ESP hdr for SA "
    821 		    "%s/%08lx\n",
    822 		    hlen, ipsec_address(&saidx->dst),
    823 		    (u_long) ntohl(sav->spi)));
    824 		ESP_STATINC(ESP_STAT_HDROPS);	/* XXX diffs from openbsd */
    825 		error = ENOBUFS;
    826 		goto bad;
    827 	}
    828 
    829 	/* Initialize ESP header. */
    830 	memcpy(mtod(mo, char *) + roff, &sav->spi, sizeof(u_int32_t));
    831 	if (sav->replay) {
    832 		u_int32_t replay;
    833 
    834 #ifdef IPSEC_DEBUG
    835 		/* Emulate replay attack when ipsec_replay is TRUE. */
    836 		if (!ipsec_replay)
    837 #endif
    838 			sav->replay->count++;
    839 
    840 		replay = htonl(sav->replay->count);
    841 		bcopy(&replay,
    842 		    mtod(mo,char *) + roff + sizeof(u_int32_t),
    843 		    sizeof(u_int32_t));
    844 	}
    845 
    846 	/*
    847 	 * Add padding -- better to do it ourselves than use the crypto engine,
    848 	 * although if/when we support compression, we'd have to do that.
    849 	 */
    850 	pad = (u_char *) m_pad(m, padding + alen);
    851 	if (pad == NULL) {
    852 		DPRINTF(("esp_output: m_pad failed for SA %s/%08lx\n",
    853 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
    854 		m = NULL;		/* NB: free'd by m_pad */
    855 		error = ENOBUFS;
    856 		goto bad;
    857 	}
    858 
    859 	/*
    860 	 * Add padding: random, zero, or self-describing.
    861 	 * XXX catch unexpected setting
    862 	 */
    863 	switch (sav->flags & SADB_X_EXT_PMASK) {
    864 	case SADB_X_EXT_PRAND:
    865 		(void) read_random(pad, padding - 2);
    866 		break;
    867 	case SADB_X_EXT_PZERO:
    868 		memset(pad, 0, padding - 2);
    869 		break;
    870 	case SADB_X_EXT_PSEQ:
    871 		for (i = 0; i < padding - 2; i++)
    872 			pad[i] = i+1;
    873 		break;
    874 	}
    875 
    876 	/* Fix padding length and Next Protocol in padding itself. */
    877 	pad[padding - 2] = padding - 2;
    878 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
    879 
    880 	/* Fix Next Protocol in IPv4/IPv6 header. */
    881 	prot = IPPROTO_ESP;
    882 	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
    883 
    884 	/* Get crypto descriptors. */
    885 	crp = crypto_getreq(esph && espx ? 2 : 1);
    886 	if (crp == NULL) {
    887 		DPRINTF(("esp_output: failed to acquire crypto descriptors\n"));
    888 		ESP_STATINC(ESP_STAT_CRYPTO);
    889 		error = ENOBUFS;
    890 		goto bad;
    891 	}
    892 
    893 	if (espx) {
    894 		crde = crp->crp_desc;
    895 		crda = crde->crd_next;
    896 
    897 		/* Encryption descriptor. */
    898 		crde->crd_skip = skip + hlen;
    899 		if (espx->type == CRYPTO_AES_GMAC)
    900 			crde->crd_len = 0;
    901 		else
    902 			crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
    903 		crde->crd_flags = CRD_F_ENCRYPT;
    904 		crde->crd_inject = skip + hlen - sav->ivlen;
    905 
    906 		/* Encryption operation. */
    907 		crde->crd_alg = espx->type;
    908 		crde->crd_key = _KEYBUF(sav->key_enc);
    909 		crde->crd_klen = _KEYBITS(sav->key_enc);
    910 		/* XXX Rounds ? */
    911 	} else
    912 		crda = crp->crp_desc;
    913 
    914 	/* IPsec-specific opaque crypto info. */
    915 	tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
    916 		M_XDATA, M_NOWAIT|M_ZERO);
    917 	if (tc == NULL) {
    918 		crypto_freereq(crp);
    919 		DPRINTF(("esp_output: failed to allocate tdb_crypto\n"));
    920 		ESP_STATINC(ESP_STAT_CRYPTO);
    921 		error = ENOBUFS;
    922 		goto bad;
    923 	}
    924 
    925 	/* Callback parameters */
    926 	tc->tc_isr = isr;
    927 	tc->tc_spi = sav->spi;
    928 	tc->tc_dst = saidx->dst;
    929 	tc->tc_proto = saidx->proto;
    930 
    931 	/* Crypto operation descriptor. */
    932 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
    933 	crp->crp_flags = CRYPTO_F_IMBUF;
    934 	crp->crp_buf = m;
    935 	crp->crp_callback = esp_output_cb;
    936 	crp->crp_opaque = tc;
    937 	crp->crp_sid = sav->tdb_cryptoid;
    938 
    939 	if (esph) {
    940 		/* Authentication descriptor. */
    941 		crda->crd_skip = skip;
    942 		if (espx && espx->type == CRYPTO_AES_GCM_16)
    943 			crda->crd_len = hlen - sav->ivlen;
    944 		else
    945 			crda->crd_len = m->m_pkthdr.len - (skip + alen);
    946 		crda->crd_inject = m->m_pkthdr.len - alen;
    947 
    948 		/* Authentication operation. */
    949 		crda->crd_alg = esph->type;
    950 		if (espx && (espx->type == CRYPTO_AES_GCM_16 ||
    951 			     espx->type == CRYPTO_AES_GMAC)) {
    952 			crda->crd_key = _KEYBUF(sav->key_enc);
    953 			crda->crd_klen = _KEYBITS(sav->key_enc);
    954 		} else {
    955 			crda->crd_key = _KEYBUF(sav->key_auth);
    956 			crda->crd_klen = _KEYBITS(sav->key_auth);
    957 		}
    958 	}
    959 
    960 	return crypto_dispatch(crp);
    961 bad:
    962 	if (m)
    963 		m_freem(m);
    964 	return (error);
    965 }
    966 
    967 /*
    968  * ESP output callback from the crypto driver.
    969  */
    970 static int
    971 esp_output_cb(struct cryptop *crp)
    972 {
    973 	struct tdb_crypto *tc;
    974 	struct ipsecrequest *isr;
    975 	struct secasvar *sav;
    976 	struct mbuf *m;
    977 	int s, err, error;
    978 
    979 	tc = (struct tdb_crypto *) crp->crp_opaque;
    980 	IPSEC_ASSERT(tc != NULL, ("esp_output_cb: null opaque data area!"));
    981 	m = (struct mbuf *) crp->crp_buf;
    982 
    983 	s = splsoftnet();
    984 	mutex_enter(softnet_lock);
    985 
    986 	isr = tc->tc_isr;
    987 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi, 0, 0);
    988 	if (sav == NULL) {
    989 		ESP_STATINC(ESP_STAT_NOTDB);
    990 		DPRINTF(("esp_output_cb: SA expired while in crypto "
    991 		    "(SA %s/%08lx proto %u)\n", ipsec_address(&tc->tc_dst),
    992 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
    993 		error = ENOBUFS;		/*XXX*/
    994 		goto bad;
    995 	}
    996 	IPSEC_ASSERT(isr->sav == sav,
    997 		("esp_output_cb: SA changed was %p now %p\n", isr->sav, sav));
    998 
    999 	/* Check for crypto errors. */
   1000 	if (crp->crp_etype) {
   1001 		/* Reset session ID. */
   1002 		if (sav->tdb_cryptoid != 0)
   1003 			sav->tdb_cryptoid = crp->crp_sid;
   1004 
   1005 		if (crp->crp_etype == EAGAIN) {
   1006 			KEY_FREESAV(&sav);
   1007 			mutex_exit(softnet_lock);
   1008 			splx(s);
   1009 			return crypto_dispatch(crp);
   1010 		}
   1011 
   1012 		ESP_STATINC(ESP_STAT_NOXFORM);
   1013 		DPRINTF(("esp_output_cb: crypto error %d\n", crp->crp_etype));
   1014 		error = crp->crp_etype;
   1015 		goto bad;
   1016 	}
   1017 
   1018 	/* Shouldn't happen... */
   1019 	if (m == NULL) {
   1020 		ESP_STATINC(ESP_STAT_CRYPTO);
   1021 		DPRINTF(("esp_output_cb: bogus returned buffer from crypto\n"));
   1022 		error = EINVAL;
   1023 		goto bad;
   1024 	}
   1025 	ESP_STATINC(ESP_STAT_HIST + sav->alg_enc);
   1026 	if (sav->tdb_authalgxform != NULL)
   1027 		AH_STATINC(AH_STAT_HIST + sav->alg_auth);
   1028 
   1029 	/* Release crypto descriptors. */
   1030 	free(tc, M_XDATA);
   1031 	crypto_freereq(crp);
   1032 
   1033 #ifdef IPSEC_DEBUG
   1034 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
   1035 	if (ipsec_integrity) {
   1036 		static unsigned char ipseczeroes[AH_ALEN_MAX];
   1037 		const struct auth_hash *esph;
   1038 
   1039 		/*
   1040 		 * Corrupt HMAC if we want to test integrity verification of
   1041 		 * the other side.
   1042 		 */
   1043 		esph = sav->tdb_authalgxform;
   1044 		if (esph !=  NULL) {
   1045 			m_copyback(m, m->m_pkthdr.len - esph->authsize,
   1046 			    esph->authsize, ipseczeroes);
   1047 		}
   1048 	}
   1049 #endif
   1050 
   1051 	/* NB: m is reclaimed by ipsec_process_done. */
   1052 	err = ipsec_process_done(m, isr);
   1053 	KEY_FREESAV(&sav);
   1054 	mutex_exit(softnet_lock);
   1055 	splx(s);
   1056 	return err;
   1057 bad:
   1058 	if (sav)
   1059 		KEY_FREESAV(&sav);
   1060 	mutex_exit(softnet_lock);
   1061 	splx(s);
   1062 	if (m)
   1063 		m_freem(m);
   1064 	free(tc, M_XDATA);
   1065 	crypto_freereq(crp);
   1066 	return error;
   1067 }
   1068 
   1069 static struct xformsw esp_xformsw = {
   1070 	XF_ESP,		XFT_CONF|XFT_AUTH,	"IPsec ESP",
   1071 	esp_init,	esp_zeroize,		esp_input,
   1072 	esp_output,
   1073 	NULL,
   1074 };
   1075 
   1076 INITFN void
   1077 esp_attach(void)
   1078 {
   1079 
   1080 	espstat_percpu = percpu_alloc(sizeof(uint64_t) * ESP_NSTATS);
   1081 
   1082 #define	MAXIV(xform)					\
   1083 	if (xform.ivsize > esp_max_ivlen)		\
   1084 		esp_max_ivlen = xform.ivsize		\
   1085 
   1086 	esp_max_ivlen = 0;
   1087 	MAXIV(enc_xform_des);		/* SADB_EALG_DESCBC */
   1088 	MAXIV(enc_xform_3des);		/* SADB_EALG_3DESCBC */
   1089 	MAXIV(enc_xform_rijndael128);	/* SADB_X_EALG_AES */
   1090 	MAXIV(enc_xform_blf);		/* SADB_X_EALG_BLOWFISHCBC */
   1091 	MAXIV(enc_xform_cast5);		/* SADB_X_EALG_CAST128CBC */
   1092 	MAXIV(enc_xform_skipjack);	/* SADB_X_EALG_SKIPJACK */
   1093 	MAXIV(enc_xform_camellia);	/* SADB_X_EALG_CAMELLIACBC */
   1094 	MAXIV(enc_xform_aes_ctr);	/* SADB_X_EALG_AESCTR */
   1095 	MAXIV(enc_xform_null);		/* SADB_EALG_NULL */
   1096 
   1097 	xform_register(&esp_xformsw);
   1098 #undef MAXIV
   1099 }
   1100 #ifdef __FreeBSD__
   1101 SYSINIT(esp_xform_init, SI_SUB_DRIVERS, SI_ORDER_FIRST, esp_attach, NULL)
   1102 #else
   1103 #endif
   1104