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