Home | History | Annotate | Line # | Download | only in netipsec
xform_esp.c revision 1.40.8.1
      1 /*	$NetBSD: xform_esp.c,v 1.40.8.1 2018/03/13 17:18:14 snj 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.40.8.1 2018/03/13 17:18:14 snj Exp $");
     43 
     44 #include "opt_inet.h"
     45 #ifdef __FreeBSD__
     46 #include "opt_inet6.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/random.h>*/
     56 #include <sys/sysctl.h>
     57 #include <sys/socketvar.h> /* for softnet_lock */
     58 
     59 #include <net/if.h>
     60 
     61 #include <netinet/in.h>
     62 #include <netinet/in_systm.h>
     63 #include <netinet/ip.h>
     64 #include <netinet/ip_ecn.h>
     65 #include <netinet/ip6.h>
     66 
     67 #include <net/route.h>
     68 #include <netipsec/ipsec.h>
     69 #include <netipsec/ipsec_private.h>
     70 #include <netipsec/ah.h>
     71 #include <netipsec/ah_var.h>
     72 #include <netipsec/esp.h>
     73 #include <netipsec/esp_var.h>
     74 #include <netipsec/xform.h>
     75 
     76 #ifdef INET6
     77 #include <netinet6/ip6_var.h>
     78 #include <netipsec/ipsec6.h>
     79 #  ifdef __FreeBSD__
     80 #  include <netinet6/ip6_ecn.h>
     81 #  endif
     82 #endif
     83 
     84 #include <netipsec/key.h>
     85 #include <netipsec/key_debug.h>
     86 
     87 #include <netipsec/ipsec_osdep.h>
     88 
     89 #include <opencrypto/cryptodev.h>
     90 #include <opencrypto/xform.h>
     91 
     92 percpu_t *espstat_percpu;
     93 
     94 int	esp_enable = 1;
     95 
     96 #ifdef __FreeBSD__
     97 SYSCTL_DECL(_net_inet_esp);
     98 SYSCTL_INT(_net_inet_esp, OID_AUTO,
     99 	esp_enable,	CTLFLAG_RW,	&esp_enable,	0, "");
    100 SYSCTL_STRUCT(_net_inet_esp, IPSECCTL_STATS,
    101 	stats,		CTLFLAG_RD,	&espstat,	espstat, "");
    102 #endif /* __FreeBSD__ */
    103 
    104 static	int esp_max_ivlen;		/* max iv length over all algorithms */
    105 
    106 static int esp_input_cb(struct cryptop *op);
    107 static int esp_output_cb(struct cryptop *crp);
    108 
    109 /*
    110  * NB: this is public for use by the PF_KEY support.
    111  * NB: if you add support here; be sure to add code to esp_attach below!
    112  */
    113 const struct enc_xform *
    114 esp_algorithm_lookup(int alg)
    115 {
    116 	if (alg >= ESP_ALG_MAX)
    117 		return NULL;
    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 		IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
    153 			("esp_hdrsiz: SA with null xform"));
    154 		if (sav->flags & SADB_X_EXT_OLD)
    155 			size = sizeof (struct esp);
    156 		else
    157 			size = sizeof (struct newesp);
    158 		size += sav->tdb_encalgxform->ivsize + 9;
    159 		/*XXX need alg check???*/
    160 		if (sav->tdb_authalgxform != NULL && sav->replay)
    161 			size += ah_hdrsiz(sav);
    162 	} else {
    163 		/*
    164 		 *   base header size
    165 		 * + max iv length for CBC mode
    166 		 * + max pad length
    167 		 * + sizeof (pad length field)
    168 		 * + sizeof (next header field)
    169 		 * + max icv supported.
    170 		 */
    171 		size = sizeof (struct newesp) + esp_max_ivlen + 9 + 16;
    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;
    184 	int keylen;
    185 	int error;
    186 
    187 	txform = esp_algorithm_lookup(sav->alg_enc);
    188 	if (txform == NULL) {
    189 		DPRINTF(("esp_init: unsupported encryption algorithm %d\n",
    190 			sav->alg_enc));
    191 		return EINVAL;
    192 	}
    193 	if (sav->key_enc == NULL) {
    194 		DPRINTF(("esp_init: no encoding key for %s algorithm\n",
    195 			 txform->name));
    196 		return EINVAL;
    197 	}
    198 	if ((sav->flags&(SADB_X_EXT_OLD|SADB_X_EXT_IV4B)) == SADB_X_EXT_IV4B) {
    199 		DPRINTF(("esp_init: 4-byte IV not supported with protocol\n"));
    200 		return EINVAL;
    201 	}
    202 	keylen = _KEYLEN(sav->key_enc);
    203 	if (txform->minkey > keylen || keylen > txform->maxkey) {
    204 		DPRINTF(("esp_init: invalid key length %u, must be in "
    205 			"the range [%u..%u] for algorithm %s\n",
    206 			keylen, txform->minkey, txform->maxkey,
    207 			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 	if (sav->alg_enc == SADB_X_EALG_AESGCM16 ||
    227 	    sav->alg_enc == SADB_X_EALG_AESGMAC) {
    228 		switch (keylen) {
    229 		case 20:
    230 			sav->alg_auth = SADB_X_AALG_AES128GMAC;
    231 			sav->tdb_authalgxform = &auth_hash_gmac_aes_128;
    232 			break;
    233 		case 28:
    234 			sav->alg_auth = SADB_X_AALG_AES192GMAC;
    235 			sav->tdb_authalgxform = &auth_hash_gmac_aes_192;
    236 			break;
    237 		case 36:
    238 			sav->alg_auth = SADB_X_AALG_AES256GMAC;
    239 			sav->tdb_authalgxform = &auth_hash_gmac_aes_256;
    240 			break;
    241 		}
    242 		memset(&cria, 0, sizeof(cria));
    243 		cria.cri_alg = sav->tdb_authalgxform->type;
    244 		cria.cri_klen = _KEYBITS(sav->key_enc);
    245 		cria.cri_key = _KEYBUF(sav->key_enc);
    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 		error = crypto_newsession(&sav->tdb_cryptoid,
    259 					  &crie, crypto_support);
    260 	} else if (sav->tdb_encalgxform) {
    261 		error = crypto_newsession(&sav->tdb_cryptoid,
    262 					  &crie, crypto_support);
    263 	} else if (sav->tdb_authalgxform) {
    264 		error = crypto_newsession(&sav->tdb_cryptoid,
    265 					  &cria, crypto_support);
    266 	} else {
    267 		/* XXX cannot happen? */
    268 		DPRINTF(("esp_init: no encoding OR authentication xform!\n"));
    269 		error = EINVAL;
    270 	}
    271 	return error;
    272 }
    273 
    274 /*
    275  * Paranoia.
    276  */
    277 static int
    278 esp_zeroize(struct secasvar *sav)
    279 {
    280 	/* NB: ah_zerorize free's the crypto session state */
    281 	int error = ah_zeroize(sav);
    282 
    283 	if (sav->key_enc)
    284 		memset(_KEYBUF(sav->key_enc), 0, _KEYLEN(sav->key_enc));
    285 	sav->tdb_encalgxform = NULL;
    286 	sav->tdb_xform = NULL;
    287 	return error;
    288 }
    289 
    290 /*
    291  * ESP input processing, called (eventually) through the protocol switch.
    292  */
    293 static int
    294 esp_input(struct mbuf *m, const struct secasvar *sav, int skip, int protoff)
    295 {
    296 	const struct auth_hash *esph;
    297 	const struct enc_xform *espx;
    298 	struct tdb_ident *tdbi;
    299 	struct tdb_crypto *tc;
    300 	int plen, alen, hlen, error;
    301 	struct m_tag *mtag;
    302 	struct newesp *esp;
    303 
    304 	struct cryptodesc *crde;
    305 	struct cryptop *crp;
    306 
    307 	IPSEC_SPLASSERT_SOFTNET("esp_input");
    308 
    309 	IPSEC_ASSERT(sav != NULL, ("esp_input: null SA"));
    310 	IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
    311 		("esp_input: null encoding xform"));
    312 	IPSEC_ASSERT((skip&3) == 0 && (m->m_pkthdr.len&3) == 0,
    313 		("esp_input: misaligned packet, skip %u pkt len %u",
    314 			skip, m->m_pkthdr.len));
    315 
    316 	/* XXX don't pullup, just copy header */
    317 	IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
    318 	if (esp == NULL) {
    319 		/* m already freed */
    320 		return EINVAL;
    321 	}
    322 
    323 	esph = sav->tdb_authalgxform;
    324 	espx = sav->tdb_encalgxform;
    325 
    326 	/* Determine the ESP header length */
    327 	if (sav->flags & SADB_X_EXT_OLD)
    328 		hlen = sizeof (struct esp) + sav->ivlen;
    329 	else
    330 		hlen = sizeof (struct newesp) + sav->ivlen;
    331 	/* Authenticator hash size */
    332 	alen = esph ? esph->authsize : 0;
    333 
    334 	/*
    335 	 * Verify payload length is multiple of encryption algorithm
    336 	 * block size.
    337 	 *
    338 	 * NB: This works for the null algorithm because the blocksize
    339 	 *     is 4 and all packets must be 4-byte aligned regardless
    340 	 *     of the algorithm.
    341 	 */
    342 	plen = m->m_pkthdr.len - (skip + hlen + alen);
    343 	if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
    344 		DPRINTF(("esp_input: "
    345 		    "payload of %d octets not a multiple of %d octets,"
    346 		    "  SA %s/%08lx\n",
    347 		    plen, espx->blocksize,
    348 		    ipsec_address(&sav->sah->saidx.dst),
    349 		    (u_long) ntohl(sav->spi)));
    350 		ESP_STATINC(ESP_STAT_BADILEN);
    351 		m_freem(m);
    352 		return EINVAL;
    353 	}
    354 
    355 	/*
    356 	 * Check sequence number.
    357 	 */
    358 	if (esph && sav->replay && !ipsec_chkreplay(ntohl(esp->esp_seq), sav)) {
    359 		DPRINTF(("esp_input: packet replay check for %s\n",
    360 		    ipsec_logsastr(sav)));	/*XXX*/
    361 		ESP_STATINC(ESP_STAT_REPLAY);
    362 		m_freem(m);
    363 		return ENOBUFS;		/*XXX*/
    364 	}
    365 
    366 	/* Update the counters */
    367 	ESP_STATADD(ESP_STAT_IBYTES, m->m_pkthdr.len - skip - hlen - alen);
    368 
    369 	/* Find out if we've already done crypto */
    370 	for (mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, NULL);
    371 	     mtag != NULL;
    372 	     mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, mtag)) {
    373 		tdbi = (struct tdb_ident *) (mtag + 1);
    374 		if (tdbi->proto == sav->sah->saidx.proto &&
    375 		    tdbi->spi == sav->spi &&
    376 		    !memcmp(&tdbi->dst, &sav->sah->saidx.dst,
    377 			  sizeof(union sockaddr_union)))
    378 			break;
    379 	}
    380 
    381 	/* Get crypto descriptors */
    382 	crp = crypto_getreq(esph && espx ? 2 : 1);
    383 	if (crp == NULL) {
    384 		DPRINTF(("esp_input: failed to acquire crypto descriptors\n"));
    385 		ESP_STATINC(ESP_STAT_CRYPTO);
    386 		m_freem(m);
    387 		return ENOBUFS;
    388 	}
    389 
    390 	/* Get IPsec-specific opaque pointer */
    391 	if (esph == NULL || mtag != NULL)
    392 		tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
    393 		    M_XDATA, M_NOWAIT|M_ZERO);
    394 	else
    395 		tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto) + alen,
    396 		    M_XDATA, M_NOWAIT|M_ZERO);
    397 	if (tc == NULL) {
    398 		crypto_freereq(crp);
    399 		DPRINTF(("esp_input: failed to allocate tdb_crypto\n"));
    400 		ESP_STATINC(ESP_STAT_CRYPTO);
    401 		m_freem(m);
    402 		return ENOBUFS;
    403 	}
    404 
    405 	error = m_makewritable(&m, 0, m->m_pkthdr.len, M_NOWAIT);
    406 	if (error) {
    407 		m_freem(m);
    408 		free(tc, M_XDATA);
    409 		crypto_freereq(crp);
    410 		DPRINTF(("esp_input: m_makewritable failed\n"));
    411 		ESP_STATINC(ESP_STAT_CRYPTO);
    412 		return error;
    413 	}
    414 
    415 	tc->tc_ptr = mtag;
    416 
    417 	if (esph) {
    418 		struct cryptodesc *crda = crp->crp_desc;
    419 
    420 		IPSEC_ASSERT(crda != NULL, ("esp_input: null ah crypto descriptor"));
    421 
    422 		/* Authentication descriptor */
    423 		crda->crd_skip = skip;
    424 		if (espx && espx->type == CRYPTO_AES_GCM_16)
    425 			crda->crd_len = hlen - sav->ivlen;
    426 		else
    427 			crda->crd_len = m->m_pkthdr.len - (skip + alen);
    428 		crda->crd_inject = m->m_pkthdr.len - alen;
    429 
    430 		crda->crd_alg = esph->type;
    431 		if (espx && (espx->type == CRYPTO_AES_GCM_16 ||
    432 			     espx->type == CRYPTO_AES_GMAC)) {
    433 			crda->crd_key = _KEYBUF(sav->key_enc);
    434 			crda->crd_klen = _KEYBITS(sav->key_enc);
    435 		} else {
    436 			crda->crd_key = _KEYBUF(sav->key_auth);
    437 			crda->crd_klen = _KEYBITS(sav->key_auth);
    438 		}
    439 
    440 		/* Copy the authenticator */
    441 		if (mtag == NULL)
    442 			m_copydata(m, m->m_pkthdr.len - alen, alen,
    443 				      (tc + 1));
    444 
    445 		/* Chain authentication request */
    446 		crde = crda->crd_next;
    447 	} else {
    448 		crde = crp->crp_desc;
    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 
    466 	/* Decryption descriptor */
    467 	if (espx) {
    468 		IPSEC_ASSERT(crde != NULL, ("esp_input: null esp crypto descriptor"));
    469 		crde->crd_skip = skip + hlen;
    470 		if (espx->type == CRYPTO_AES_GMAC)
    471 			crde->crd_len = 0;
    472 		else
    473 			crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
    474 		crde->crd_inject = skip + hlen - sav->ivlen;
    475 
    476 		crde->crd_alg = espx->type;
    477 		crde->crd_key = _KEYBUF(sav->key_enc);
    478 		crde->crd_klen = _KEYBITS(sav->key_enc);
    479 		/* XXX Rounds ? */
    480 	}
    481 
    482 	if (mtag == NULL)
    483 		return crypto_dispatch(crp);
    484 	else
    485 		return esp_input_cb(crp);
    486 }
    487 
    488 #ifdef INET6
    489 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag) do {		     \
    490 	if (saidx->dst.sa.sa_family == AF_INET6) {			     \
    491 		error = ipsec6_common_input_cb(m, sav, skip, protoff, mtag); \
    492 	} else {							     \
    493 		error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag); \
    494 	}								     \
    495 } while (0)
    496 #else
    497 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag)		     \
    498 	(error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag))
    499 #endif
    500 
    501 /*
    502  * ESP input callback from the crypto driver.
    503  */
    504 static int
    505 esp_input_cb(struct cryptop *crp)
    506 {
    507 	u_int8_t lastthree[3], aalg[AH_ALEN_MAX];
    508 	int s, hlen, skip, protoff, error;
    509 	struct mbuf *m;
    510 	struct cryptodesc *crd;
    511 	const struct auth_hash *esph;
    512 	const struct enc_xform *espx;
    513 	struct tdb_crypto *tc;
    514 	struct m_tag *mtag;
    515 	struct secasvar *sav;
    516 	struct secasindex *saidx;
    517 	void *ptr;
    518 	u_int16_t dport = 0;
    519 	u_int16_t sport = 0;
    520 #ifdef IPSEC_NAT_T
    521 	struct m_tag * tag = NULL;
    522 #endif
    523 
    524 	crd = crp->crp_desc;
    525 	IPSEC_ASSERT(crd != NULL, ("esp_input_cb: null crypto descriptor!"));
    526 
    527 	tc = (struct tdb_crypto *) crp->crp_opaque;
    528 	IPSEC_ASSERT(tc != NULL, ("esp_input_cb: null opaque crypto data area!"));
    529 	skip = tc->tc_skip;
    530 	protoff = tc->tc_protoff;
    531 	mtag = (struct m_tag *) tc->tc_ptr;
    532 	m = (struct mbuf *) crp->crp_buf;
    533 
    534 #ifdef IPSEC_NAT_T
    535 	/* find the source port for NAT-T */
    536 	if ((tag = m_tag_find(m, PACKET_TAG_IPSEC_NAT_T_PORTS, NULL))) {
    537 		sport = ((u_int16_t *)(tag + 1))[0];
    538 		dport = ((u_int16_t *)(tag + 1))[1];
    539 	}
    540 #endif
    541 
    542 	s = splsoftnet();
    543 	mutex_enter(softnet_lock);
    544 
    545 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi, sport, dport);
    546 	if (sav == NULL) {
    547 		ESP_STATINC(ESP_STAT_NOTDB);
    548 		DPRINTF(("esp_input_cb: SA expired while in crypto "
    549 		    "(SA %s/%08lx proto %u)\n", ipsec_address(&tc->tc_dst),
    550 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
    551 		error = ENOBUFS;		/*XXX*/
    552 		goto bad;
    553 	}
    554 
    555 	saidx = &sav->sah->saidx;
    556 	IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
    557 		saidx->dst.sa.sa_family == AF_INET6,
    558 		("esp_input_cb: unexpected protocol family %u",
    559 		 saidx->dst.sa.sa_family));
    560 
    561 	esph = sav->tdb_authalgxform;
    562 	espx = sav->tdb_encalgxform;
    563 
    564 	/* Check for crypto errors */
    565 	if (crp->crp_etype) {
    566 		/* Reset the session ID */
    567 		if (sav->tdb_cryptoid != 0)
    568 			sav->tdb_cryptoid = crp->crp_sid;
    569 
    570 		if (crp->crp_etype == EAGAIN) {
    571 			KEY_FREESAV(&sav);
    572 			mutex_exit(softnet_lock);
    573 			splx(s);
    574 			return crypto_dispatch(crp);
    575 		}
    576 
    577 		ESP_STATINC(ESP_STAT_NOXFORM);
    578 		DPRINTF(("esp_input_cb: crypto error %d\n", crp->crp_etype));
    579 		error = crp->crp_etype;
    580 		goto bad;
    581 	}
    582 
    583 	/* Shouldn't happen... */
    584 	if (m == NULL) {
    585 		ESP_STATINC(ESP_STAT_CRYPTO);
    586 		DPRINTF(("esp_input_cb: bogus returned buffer from crypto\n"));
    587 		error = EINVAL;
    588 		goto bad;
    589 	}
    590 	ESP_STATINC(ESP_STAT_HIST + sav->alg_enc);
    591 
    592 	/* If authentication was performed, check now. */
    593 	if (esph != NULL) {
    594 		/*
    595 		 * If we have a tag, it means an IPsec-aware NIC did
    596 		 * the verification for us.  Otherwise we need to
    597 		 * check the authentication calculation.
    598 		 */
    599 		AH_STATINC(AH_STAT_HIST + sav->alg_auth);
    600 		if (mtag == NULL) {
    601 			/* Copy the authenticator from the packet */
    602 			m_copydata(m, m->m_pkthdr.len - esph->authsize,
    603 				esph->authsize, aalg);
    604 
    605 			ptr = (tc + 1);
    606 
    607 			/* Verify authenticator */
    608 			if (memcmp(ptr, aalg, esph->authsize) != 0) {
    609 				DPRINTF(("esp_input_cb: "
    610 		    "authentication hash mismatch for packet in SA %s/%08lx\n",
    611 				    ipsec_address(&saidx->dst),
    612 				    (u_long) ntohl(sav->spi)));
    613 				ESP_STATINC(ESP_STAT_BADAUTH);
    614 				error = EACCES;
    615 				goto bad;
    616 			}
    617 		}
    618 
    619 		/* Remove trailing authenticator */
    620 		m_adj(m, -(esph->authsize));
    621 	}
    622 
    623 	/* Release the crypto descriptors */
    624 	free(tc, M_XDATA), tc = NULL;
    625 	crypto_freereq(crp), crp = NULL;
    626 
    627 	/*
    628 	 * Packet is now decrypted.
    629 	 */
    630 	m->m_flags |= M_DECRYPTED;
    631 
    632 	/*
    633 	 * Update replay sequence number, if appropriate.
    634 	 */
    635 	if (sav->replay) {
    636 		u_int32_t seq;
    637 
    638 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
    639 		    sizeof (seq), &seq);
    640 		if (ipsec_updatereplay(ntohl(seq), sav)) {
    641 			DPRINTF(("%s: packet replay check for %s\n", __func__,
    642 			    ipsec_logsastr(sav)));
    643 			ESP_STATINC(ESP_STAT_REPLAY);
    644 			error = ENOBUFS;
    645 			goto bad;
    646 		}
    647 	}
    648 
    649 	/* Determine the ESP header length */
    650 	if (sav->flags & SADB_X_EXT_OLD)
    651 		hlen = sizeof (struct esp) + sav->ivlen;
    652 	else
    653 		hlen = sizeof (struct newesp) + sav->ivlen;
    654 
    655 	/* Remove the ESP header and IV from the mbuf. */
    656 	error = m_striphdr(m, skip, hlen);
    657 	if (error) {
    658 		ESP_STATINC(ESP_STAT_HDROPS);
    659 		DPRINTF(("esp_input_cb: bad mbuf chain, SA %s/%08lx\n",
    660 		    ipsec_address(&sav->sah->saidx.dst),
    661 		    (u_long) ntohl(sav->spi)));
    662 		goto bad;
    663 	}
    664 
    665 	/* Save the last three bytes of decrypted data */
    666 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
    667 
    668 	/* Verify pad length */
    669 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
    670 		ESP_STATINC(ESP_STAT_BADILEN);
    671 		DPRINTF(("esp_input_cb: invalid padding length %d "
    672 			 "for %u byte packet in SA %s/%08lx\n",
    673 			 lastthree[1], m->m_pkthdr.len - skip,
    674 			 ipsec_address(&sav->sah->saidx.dst),
    675 			 (u_long) ntohl(sav->spi)));
    676 		error = EINVAL;
    677 		goto bad;
    678 	}
    679 
    680 	/* Verify correct decryption by checking the last padding bytes */
    681 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
    682 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
    683 			ESP_STATINC(ESP_STAT_BADENC);
    684 			DPRINTF(("esp_input_cb: decryption failed "
    685 				"for packet in SA %s/%08lx\n",
    686 				ipsec_address(&sav->sah->saidx.dst),
    687 				(u_long) ntohl(sav->spi)));
    688 DPRINTF(("esp_input_cb: %x %x\n", lastthree[0], lastthree[1]));
    689 			error = EINVAL;
    690 			goto bad;
    691 		}
    692 	}
    693 
    694 	/* Trim the mbuf chain to remove trailing authenticator and padding */
    695 	m_adj(m, -(lastthree[1] + 2));
    696 
    697 	/* Restore the Next Protocol field */
    698 	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
    699 
    700 	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag);
    701 
    702 	KEY_FREESAV(&sav);
    703 	mutex_exit(softnet_lock);
    704 	splx(s);
    705 	return error;
    706 bad:
    707 	if (sav)
    708 		KEY_FREESAV(&sav);
    709 	mutex_exit(softnet_lock);
    710 	splx(s);
    711 	if (m != NULL)
    712 		m_freem(m);
    713 	if (tc != NULL)
    714 		free(tc, M_XDATA);
    715 	if (crp != NULL)
    716 		crypto_freereq(crp);
    717 	return error;
    718 }
    719 
    720 /*
    721  * ESP output routine, called by ipsec[46]_process_packet().
    722  */
    723 static int
    724 esp_output(
    725     struct mbuf *m,
    726     struct ipsecrequest *isr,
    727     struct mbuf **mp,
    728     int skip,
    729     int protoff
    730 )
    731 {
    732 	const struct enc_xform *espx;
    733 	const struct auth_hash *esph;
    734 	int hlen, rlen, plen, padding, blks, alen, i, roff;
    735 	struct mbuf *mo = NULL;
    736 	struct tdb_crypto *tc;
    737 	const struct secasvar *sav;
    738 	struct secasindex *saidx;
    739 	unsigned char *pad;
    740 	u_int8_t prot;
    741 	int error, maxpacketsize;
    742 
    743 	struct cryptodesc *crde = NULL, *crda = NULL;
    744 	struct cryptop *crp;
    745 
    746 	IPSEC_SPLASSERT_SOFTNET("esp_output");
    747 
    748 	sav = isr->sav;
    749 	IPSEC_ASSERT(sav != NULL, ("esp_output: null SA"));
    750 	esph = sav->tdb_authalgxform;
    751 	espx = sav->tdb_encalgxform;
    752 	IPSEC_ASSERT(espx != NULL, ("esp_output: null encoding xform"));
    753 
    754 	if (sav->flags & SADB_X_EXT_OLD)
    755 		hlen = sizeof (struct esp) + sav->ivlen;
    756 	else
    757 		hlen = sizeof (struct newesp) + sav->ivlen;
    758 
    759 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
    760 	/*
    761 	 * NB: The null encoding transform has a blocksize of 4
    762 	 *     so that headers are properly aligned.
    763 	 */
    764 	blks = espx->blocksize;		/* IV blocksize */
    765 
    766 	/* XXX clamp padding length a la KAME??? */
    767 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
    768 	plen = rlen + padding;		/* Padded payload length. */
    769 
    770 	if (esph)
    771 		alen = esph->authsize;
    772 	else
    773 		alen = 0;
    774 
    775 	ESP_STATINC(ESP_STAT_OUTPUT);
    776 
    777 	saidx = &sav->sah->saidx;
    778 	/* Check for maximum packet size violations. */
    779 	switch (saidx->dst.sa.sa_family) {
    780 #ifdef INET
    781 	case AF_INET:
    782 		maxpacketsize = IP_MAXPACKET;
    783 		break;
    784 #endif /* INET */
    785 #ifdef INET6
    786 	case AF_INET6:
    787 		maxpacketsize = IPV6_MAXPACKET;
    788 		break;
    789 #endif /* INET6 */
    790 	default:
    791 		DPRINTF(("esp_output: unknown/unsupported protocol "
    792 		    "family %d, SA %s/%08lx\n",
    793 		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst),
    794 		    (u_long) ntohl(sav->spi)));
    795 		ESP_STATINC(ESP_STAT_NOPF);
    796 		error = EPFNOSUPPORT;
    797 		goto bad;
    798 	}
    799 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
    800 		DPRINTF(("esp_output: packet in SA %s/%08lx got too big "
    801 		    "(len %u, max len %u)\n",
    802 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi),
    803 		    skip + hlen + rlen + padding + alen, maxpacketsize));
    804 		ESP_STATINC(ESP_STAT_TOOBIG);
    805 		error = EMSGSIZE;
    806 		goto bad;
    807 	}
    808 
    809 	/* Update the counters. */
    810 	ESP_STATADD(ESP_STAT_OBYTES, m->m_pkthdr.len - skip);
    811 
    812 	m = m_clone(m);
    813 	if (m == NULL) {
    814 		DPRINTF(("esp_output: cannot clone mbuf chain, SA %s/%08lx\n",
    815 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
    816 		ESP_STATINC(ESP_STAT_HDROPS);
    817 		error = ENOBUFS;
    818 		goto bad;
    819 	}
    820 
    821 	/* Inject ESP header. */
    822 	mo = m_makespace(m, skip, hlen, &roff);
    823 	if (mo == NULL) {
    824 		DPRINTF(("esp_output: failed to inject %u byte ESP hdr for SA "
    825 		    "%s/%08lx\n",
    826 		    hlen, ipsec_address(&saidx->dst),
    827 		    (u_long) ntohl(sav->spi)));
    828 		ESP_STATINC(ESP_STAT_HDROPS);	/* XXX diffs from openbsd */
    829 		error = ENOBUFS;
    830 		goto bad;
    831 	}
    832 
    833 	/* Initialize ESP header. */
    834 	memcpy(mtod(mo, char *) + roff, &sav->spi, sizeof(u_int32_t));
    835 	if (sav->replay) {
    836 		u_int32_t replay;
    837 
    838 #ifdef IPSEC_DEBUG
    839 		/* Emulate replay attack when ipsec_replay is TRUE. */
    840 		if (!ipsec_replay)
    841 #endif
    842 			sav->replay->count++;
    843 
    844 		replay = htonl(sav->replay->count);
    845 		bcopy(&replay,
    846 		    mtod(mo,char *) + roff + sizeof(u_int32_t),
    847 		    sizeof(u_int32_t));
    848 	}
    849 
    850 	/*
    851 	 * Add padding -- better to do it ourselves than use the crypto engine,
    852 	 * although if/when we support compression, we'd have to do that.
    853 	 */
    854 	pad = (u_char *) m_pad(m, padding + alen);
    855 	if (pad == NULL) {
    856 		DPRINTF(("esp_output: m_pad failed for SA %s/%08lx\n",
    857 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
    858 		m = NULL;		/* NB: free'd by m_pad */
    859 		error = ENOBUFS;
    860 		goto bad;
    861 	}
    862 
    863 	/*
    864 	 * Add padding: random, zero, or self-describing.
    865 	 * XXX catch unexpected setting
    866 	 */
    867 	switch (sav->flags & SADB_X_EXT_PMASK) {
    868 	case SADB_X_EXT_PRAND:
    869 		(void) read_random(pad, padding - 2);
    870 		break;
    871 	case SADB_X_EXT_PZERO:
    872 		memset(pad, 0, padding - 2);
    873 		break;
    874 	case SADB_X_EXT_PSEQ:
    875 		for (i = 0; i < padding - 2; i++)
    876 			pad[i] = i+1;
    877 		break;
    878 	}
    879 
    880 	/* Fix padding length and Next Protocol in padding itself. */
    881 	pad[padding - 2] = padding - 2;
    882 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
    883 
    884 	/* Fix Next Protocol in IPv4/IPv6 header. */
    885 	prot = IPPROTO_ESP;
    886 	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
    887 
    888 	/* Get crypto descriptors. */
    889 	crp = crypto_getreq(esph && espx ? 2 : 1);
    890 	if (crp == NULL) {
    891 		DPRINTF(("esp_output: failed to acquire crypto descriptors\n"));
    892 		ESP_STATINC(ESP_STAT_CRYPTO);
    893 		error = ENOBUFS;
    894 		goto bad;
    895 	}
    896 
    897 	if (espx) {
    898 		crde = crp->crp_desc;
    899 		crda = crde->crd_next;
    900 
    901 		/* Encryption descriptor. */
    902 		crde->crd_skip = skip + hlen;
    903 		if (espx->type == CRYPTO_AES_GMAC)
    904 			crde->crd_len = 0;
    905 		else
    906 			crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
    907 		crde->crd_flags = CRD_F_ENCRYPT;
    908 		crde->crd_inject = skip + hlen - sav->ivlen;
    909 
    910 		/* Encryption operation. */
    911 		crde->crd_alg = espx->type;
    912 		crde->crd_key = _KEYBUF(sav->key_enc);
    913 		crde->crd_klen = _KEYBITS(sav->key_enc);
    914 		/* XXX Rounds ? */
    915 	} else
    916 		crda = crp->crp_desc;
    917 
    918 	/* IPsec-specific opaque crypto info. */
    919 	tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
    920 		M_XDATA, M_NOWAIT|M_ZERO);
    921 	if (tc == NULL) {
    922 		crypto_freereq(crp);
    923 		DPRINTF(("esp_output: failed to allocate tdb_crypto\n"));
    924 		ESP_STATINC(ESP_STAT_CRYPTO);
    925 		error = ENOBUFS;
    926 		goto bad;
    927 	}
    928 
    929 	/* Callback parameters */
    930 	tc->tc_isr = isr;
    931 	tc->tc_spi = sav->spi;
    932 	tc->tc_dst = saidx->dst;
    933 	tc->tc_proto = saidx->proto;
    934 
    935 	/* Crypto operation descriptor. */
    936 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
    937 	crp->crp_flags = CRYPTO_F_IMBUF;
    938 	crp->crp_buf = m;
    939 	crp->crp_callback = esp_output_cb;
    940 	crp->crp_opaque = tc;
    941 	crp->crp_sid = sav->tdb_cryptoid;
    942 
    943 	if (esph) {
    944 		/* Authentication descriptor. */
    945 		crda->crd_skip = skip;
    946 		if (espx && espx->type == CRYPTO_AES_GCM_16)
    947 			crda->crd_len = hlen - sav->ivlen;
    948 		else
    949 			crda->crd_len = m->m_pkthdr.len - (skip + alen);
    950 		crda->crd_inject = m->m_pkthdr.len - alen;
    951 
    952 		/* Authentication operation. */
    953 		crda->crd_alg = esph->type;
    954 		if (espx && (espx->type == CRYPTO_AES_GCM_16 ||
    955 			     espx->type == CRYPTO_AES_GMAC)) {
    956 			crda->crd_key = _KEYBUF(sav->key_enc);
    957 			crda->crd_klen = _KEYBITS(sav->key_enc);
    958 		} else {
    959 			crda->crd_key = _KEYBUF(sav->key_auth);
    960 			crda->crd_klen = _KEYBITS(sav->key_auth);
    961 		}
    962 	}
    963 
    964 	return crypto_dispatch(crp);
    965 bad:
    966 	if (m)
    967 		m_freem(m);
    968 	return (error);
    969 }
    970 
    971 /*
    972  * ESP output callback from the crypto driver.
    973  */
    974 static int
    975 esp_output_cb(struct cryptop *crp)
    976 {
    977 	struct tdb_crypto *tc;
    978 	struct ipsecrequest *isr;
    979 	struct secasvar *sav;
    980 	struct mbuf *m;
    981 	int s, err, error;
    982 
    983 	tc = (struct tdb_crypto *) crp->crp_opaque;
    984 	IPSEC_ASSERT(tc != NULL, ("esp_output_cb: null opaque data area!"));
    985 	m = (struct mbuf *) crp->crp_buf;
    986 
    987 	s = splsoftnet();
    988 	mutex_enter(softnet_lock);
    989 
    990 	isr = tc->tc_isr;
    991 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi, 0, 0);
    992 	if (sav == NULL) {
    993 		ESP_STATINC(ESP_STAT_NOTDB);
    994 		DPRINTF(("esp_output_cb: SA expired while in crypto "
    995 		    "(SA %s/%08lx proto %u)\n", ipsec_address(&tc->tc_dst),
    996 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
    997 		error = ENOBUFS;		/*XXX*/
    998 		goto bad;
    999 	}
   1000 	IPSEC_ASSERT(isr->sav == sav,
   1001 		("esp_output_cb: SA changed was %p now %p\n", isr->sav, sav));
   1002 
   1003 	/* Check for crypto errors. */
   1004 	if (crp->crp_etype) {
   1005 		/* Reset session ID. */
   1006 		if (sav->tdb_cryptoid != 0)
   1007 			sav->tdb_cryptoid = crp->crp_sid;
   1008 
   1009 		if (crp->crp_etype == EAGAIN) {
   1010 			KEY_FREESAV(&sav);
   1011 			mutex_exit(softnet_lock);
   1012 			splx(s);
   1013 			return crypto_dispatch(crp);
   1014 		}
   1015 
   1016 		ESP_STATINC(ESP_STAT_NOXFORM);
   1017 		DPRINTF(("esp_output_cb: crypto error %d\n", crp->crp_etype));
   1018 		error = crp->crp_etype;
   1019 		goto bad;
   1020 	}
   1021 
   1022 	/* Shouldn't happen... */
   1023 	if (m == NULL) {
   1024 		ESP_STATINC(ESP_STAT_CRYPTO);
   1025 		DPRINTF(("esp_output_cb: bogus returned buffer from crypto\n"));
   1026 		error = EINVAL;
   1027 		goto bad;
   1028 	}
   1029 	ESP_STATINC(ESP_STAT_HIST + sav->alg_enc);
   1030 	if (sav->tdb_authalgxform != NULL)
   1031 		AH_STATINC(AH_STAT_HIST + sav->alg_auth);
   1032 
   1033 	/* Release crypto descriptors. */
   1034 	free(tc, M_XDATA);
   1035 	crypto_freereq(crp);
   1036 
   1037 #ifdef IPSEC_DEBUG
   1038 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
   1039 	if (ipsec_integrity) {
   1040 		static unsigned char ipseczeroes[AH_ALEN_MAX];
   1041 		const struct auth_hash *esph;
   1042 
   1043 		/*
   1044 		 * Corrupt HMAC if we want to test integrity verification of
   1045 		 * the other side.
   1046 		 */
   1047 		esph = sav->tdb_authalgxform;
   1048 		if (esph !=  NULL) {
   1049 			m_copyback(m, m->m_pkthdr.len - esph->authsize,
   1050 			    esph->authsize, ipseczeroes);
   1051 		}
   1052 	}
   1053 #endif
   1054 
   1055 	/* NB: m is reclaimed by ipsec_process_done. */
   1056 	err = ipsec_process_done(m, isr);
   1057 	KEY_FREESAV(&sav);
   1058 	mutex_exit(softnet_lock);
   1059 	splx(s);
   1060 	return err;
   1061 bad:
   1062 	if (sav)
   1063 		KEY_FREESAV(&sav);
   1064 	mutex_exit(softnet_lock);
   1065 	splx(s);
   1066 	if (m)
   1067 		m_freem(m);
   1068 	free(tc, M_XDATA);
   1069 	crypto_freereq(crp);
   1070 	return error;
   1071 }
   1072 
   1073 static struct xformsw esp_xformsw = {
   1074 	XF_ESP,		XFT_CONF|XFT_AUTH,	"IPsec ESP",
   1075 	esp_init,	esp_zeroize,		esp_input,
   1076 	esp_output,
   1077 	NULL,
   1078 };
   1079 
   1080 INITFN void
   1081 esp_attach(void)
   1082 {
   1083 
   1084 	espstat_percpu = percpu_alloc(sizeof(uint64_t) * ESP_NSTATS);
   1085 
   1086 #define	MAXIV(xform)					\
   1087 	if (xform.ivsize > esp_max_ivlen)		\
   1088 		esp_max_ivlen = xform.ivsize		\
   1089 
   1090 	esp_max_ivlen = 0;
   1091 	MAXIV(enc_xform_des);		/* SADB_EALG_DESCBC */
   1092 	MAXIV(enc_xform_3des);		/* SADB_EALG_3DESCBC */
   1093 	MAXIV(enc_xform_rijndael128);	/* SADB_X_EALG_AES */
   1094 	MAXIV(enc_xform_blf);		/* SADB_X_EALG_BLOWFISHCBC */
   1095 	MAXIV(enc_xform_cast5);		/* SADB_X_EALG_CAST128CBC */
   1096 	MAXIV(enc_xform_skipjack);	/* SADB_X_EALG_SKIPJACK */
   1097 	MAXIV(enc_xform_camellia);	/* SADB_X_EALG_CAMELLIACBC */
   1098 	MAXIV(enc_xform_aes_ctr);	/* SADB_X_EALG_AESCTR */
   1099 	MAXIV(enc_xform_null);		/* SADB_EALG_NULL */
   1100 
   1101 	xform_register(&esp_xformsw);
   1102 #undef MAXIV
   1103 }
   1104 #ifdef __FreeBSD__
   1105 SYSINIT(esp_xform_init, SI_SUB_DRIVERS, SI_ORDER_FIRST, esp_attach, NULL)
   1106 #else
   1107 #endif
   1108