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