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