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