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