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