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