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