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