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