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