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