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