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