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