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