Home | History | Annotate | Line # | Download | only in netipsec
xform_esp.c revision 1.55
      1 /*	$NetBSD: xform_esp.c,v 1.55 2017/05/11 05:55:14 ryo 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.55 2017/05/11 05:55:14 ryo 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 		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 		ESP_STATINC(ESP_STAT_BADILEN);
    348 		m_freem(m);
    349 		return EINVAL;
    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))));	/*XXX*/
    359 		ESP_STATINC(ESP_STAT_REPLAY);
    360 		m_freem(m);
    361 		return ENOBUFS;		/*XXX*/
    362 	}
    363 
    364 	/* Update the counters */
    365 	ESP_STATADD(ESP_STAT_IBYTES, m->m_pkthdr.len - skip - hlen - alen);
    366 
    367 	/* Find out if we've already done crypto */
    368 	for (mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, NULL);
    369 	     mtag != NULL;
    370 	     mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, mtag)) {
    371 		tdbi = (struct tdb_ident *) (mtag + 1);
    372 		if (tdbi->proto == sav->sah->saidx.proto &&
    373 		    tdbi->spi == sav->spi &&
    374 		    !memcmp(&tdbi->dst, &sav->sah->saidx.dst,
    375 			  sizeof(union sockaddr_union)))
    376 			break;
    377 	}
    378 
    379 	/* Get crypto descriptors */
    380 	crp = crypto_getreq(esph && espx ? 2 : 1);
    381 	if (crp == NULL) {
    382 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
    383 		    __func__));
    384 		error = ENOBUFS;
    385 		goto out;
    386 	}
    387 
    388 	/* Get IPsec-specific opaque pointer */
    389 	size_t extra = esph == NULL || mtag != NULL ? 0 : alen;
    390 	tc = malloc(sizeof(*tc) + extra, M_XDATA, M_NOWAIT|M_ZERO);
    391 	if (tc == NULL) {
    392 		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
    393 		error = ENOBUFS;
    394 		goto out1;
    395 	}
    396 
    397 	error = m_makewritable(&m, 0, m->m_pkthdr.len, M_NOWAIT);
    398 	if (error) {
    399 		DPRINTF(("%s: m_makewritable failed\n", __func__));
    400 		goto out2;
    401 	}
    402 
    403 	tc->tc_ptr = mtag;
    404 
    405 	if (esph) {
    406 		struct cryptodesc *crda;
    407 
    408 		KASSERT(crp->crp_desc != NULL);
    409 		crda = crp->crp_desc;
    410 
    411 		/* Authentication descriptor */
    412 		crda->crd_skip = skip;
    413 		if (espx && espx->type == CRYPTO_AES_GCM_16)
    414 			crda->crd_len = hlen - sav->ivlen;
    415 		else
    416 			crda->crd_len = m->m_pkthdr.len - (skip + alen);
    417 		crda->crd_inject = m->m_pkthdr.len - alen;
    418 
    419 		crda->crd_alg = esph->type;
    420 		if (espx && (espx->type == CRYPTO_AES_GCM_16 ||
    421 			     espx->type == CRYPTO_AES_GMAC)) {
    422 			crda->crd_key = _KEYBUF(sav->key_enc);
    423 			crda->crd_klen = _KEYBITS(sav->key_enc);
    424 		} else {
    425 			crda->crd_key = _KEYBUF(sav->key_auth);
    426 			crda->crd_klen = _KEYBITS(sav->key_auth);
    427 		}
    428 
    429 		/* Copy the authenticator */
    430 		if (mtag == NULL)
    431 			m_copydata(m, m->m_pkthdr.len - alen, alen, (tc + 1));
    432 
    433 		/* Chain authentication request */
    434 		crde = crda->crd_next;
    435 	} else {
    436 		crde = crp->crp_desc;
    437 	}
    438 
    439 	/* Crypto operation descriptor */
    440 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
    441 	crp->crp_flags = CRYPTO_F_IMBUF;
    442 	crp->crp_buf = m;
    443 	crp->crp_callback = esp_input_cb;
    444 	crp->crp_sid = sav->tdb_cryptoid;
    445 	crp->crp_opaque = tc;
    446 
    447 	/* These are passed as-is to the callback */
    448 	tc->tc_spi = sav->spi;
    449 	tc->tc_dst = sav->sah->saidx.dst;
    450 	tc->tc_proto = sav->sah->saidx.proto;
    451 	tc->tc_protoff = protoff;
    452 	tc->tc_skip = skip;
    453 
    454 	/* Decryption descriptor */
    455 	if (espx) {
    456 		KASSERTMSG(crde != NULL, "null esp crypto descriptor");
    457 		crde->crd_skip = skip + hlen;
    458 		if (espx->type == CRYPTO_AES_GMAC)
    459 			crde->crd_len = 0;
    460 		else
    461 			crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
    462 		crde->crd_inject = skip + hlen - sav->ivlen;
    463 
    464 		crde->crd_alg = espx->type;
    465 		crde->crd_key = _KEYBUF(sav->key_enc);
    466 		crde->crd_klen = _KEYBITS(sav->key_enc);
    467 		/* XXX Rounds ? */
    468 	}
    469 
    470 	if (mtag == NULL)
    471 		return crypto_dispatch(crp);
    472 	else
    473 		return esp_input_cb(crp);
    474 
    475 out2:
    476 	free(tc, M_XDATA);
    477 out1:
    478 	crypto_freereq(crp);
    479 out:
    480 	ESP_STATINC(ESP_STAT_CRYPTO);
    481 	m_freem(m);
    482 	return error;
    483 }
    484 
    485 #ifdef INET6
    486 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag) do {		     \
    487 	if (saidx->dst.sa.sa_family == AF_INET6) {			     \
    488 		error = ipsec6_common_input_cb(m, sav, skip, protoff, mtag); \
    489 	} else {							     \
    490 		error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag); \
    491 	}								     \
    492 } while (0)
    493 #else
    494 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag)		     \
    495 	(error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag))
    496 #endif
    497 
    498 /*
    499  * ESP input callback from the crypto driver.
    500  */
    501 static int
    502 esp_input_cb(struct cryptop *crp)
    503 {
    504 	char buf[IPSEC_ADDRSTRLEN];
    505 	uint8_t lastthree[3], aalg[AH_ALEN_MAX];
    506 	int s, hlen, skip, protoff, error;
    507 	struct mbuf *m;
    508 	const struct auth_hash *esph;
    509 	struct tdb_crypto *tc;
    510 	struct m_tag *mtag;
    511 	struct secasvar *sav;
    512 	struct secasindex *saidx;
    513 	void *ptr;
    514 	uint16_t dport;
    515 	uint16_t sport;
    516 
    517 	KASSERT(crp->crp_desc != NULL);
    518 	KASSERT(crp->crp_opaque != NULL);
    519 
    520 	tc = crp->crp_opaque;
    521 	skip = tc->tc_skip;
    522 	protoff = tc->tc_protoff;
    523 	mtag = tc->tc_ptr;
    524 	m = crp->crp_buf;
    525 
    526 	/* find the source port for NAT-T */
    527 	nat_t_ports_get(m, &dport, &sport);
    528 
    529 	s = splsoftnet();
    530 	mutex_enter(softnet_lock);
    531 
    532 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi, sport, dport);
    533 	if (sav == NULL) {
    534 		ESP_STATINC(ESP_STAT_NOTDB);
    535 		DPRINTF(("%s: SA expired while in crypto "
    536 		    "(SA %s/%08lx proto %u)\n", __func__,
    537 		    ipsec_address(&tc->tc_dst, buf, sizeof(buf)),
    538 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
    539 		error = ENOBUFS;		/*XXX*/
    540 		goto bad;
    541 	}
    542 
    543 	saidx = &sav->sah->saidx;
    544 	KASSERTMSG(saidx->dst.sa.sa_family == AF_INET ||
    545 	    saidx->dst.sa.sa_family == AF_INET6,
    546 	    "unexpected protocol family %u", saidx->dst.sa.sa_family);
    547 
    548 	esph = sav->tdb_authalgxform;
    549 
    550 	/* Check for crypto errors */
    551 	if (crp->crp_etype) {
    552 		/* Reset the session ID */
    553 		if (sav->tdb_cryptoid != 0)
    554 			sav->tdb_cryptoid = crp->crp_sid;
    555 
    556 		if (crp->crp_etype == EAGAIN) {
    557 			KEY_FREESAV(&sav);
    558 			mutex_exit(softnet_lock);
    559 			splx(s);
    560 			return crypto_dispatch(crp);
    561 		}
    562 
    563 		ESP_STATINC(ESP_STAT_NOXFORM);
    564 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
    565 		error = crp->crp_etype;
    566 		goto bad;
    567 	}
    568 
    569 	/* Shouldn't happen... */
    570 	if (m == NULL) {
    571 		ESP_STATINC(ESP_STAT_CRYPTO);
    572 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
    573 		error = EINVAL;
    574 		goto bad;
    575 	}
    576 	ESP_STATINC(ESP_STAT_HIST + esp_stats[sav->alg_enc]);
    577 
    578 	/* If authentication was performed, check now. */
    579 	if (esph != NULL) {
    580 		/*
    581 		 * If we have a tag, it means an IPsec-aware NIC did
    582 		 * the verification for us.  Otherwise we need to
    583 		 * check the authentication calculation.
    584 		 */
    585 		AH_STATINC(AH_STAT_HIST + ah_stats[sav->alg_auth]);
    586 		if (mtag == NULL) {
    587 			/* Copy the authenticator from the packet */
    588 			m_copydata(m, m->m_pkthdr.len - esph->authsize,
    589 				esph->authsize, aalg);
    590 
    591 			ptr = (tc + 1);
    592 
    593 			/* Verify authenticator */
    594 			if (!consttime_memequal(ptr, aalg, esph->authsize)) {
    595 				DPRINTF(("%s: authentication hash mismatch "
    596 				    "for packet in SA %s/%08lx\n", __func__,
    597 				    ipsec_address(&saidx->dst, buf,
    598 				    sizeof(buf)), (u_long) ntohl(sav->spi)));
    599 				ESP_STATINC(ESP_STAT_BADAUTH);
    600 				error = EACCES;
    601 				goto bad;
    602 			}
    603 		}
    604 
    605 		/* Remove trailing authenticator */
    606 		m_adj(m, -(esph->authsize));
    607 	}
    608 
    609 	/* Release the crypto descriptors */
    610 	free(tc, M_XDATA), tc = NULL;
    611 	crypto_freereq(crp), crp = NULL;
    612 
    613 	/*
    614 	 * Packet is now decrypted.
    615 	 */
    616 	m->m_flags |= M_DECRYPTED;
    617 
    618 	/*
    619 	 * Update replay sequence number, if appropriate.
    620 	 */
    621 	if (sav->replay) {
    622 		uint32_t seq;
    623 
    624 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
    625 		    sizeof(seq), &seq);
    626 		if (ipsec_updatereplay(ntohl(seq), sav)) {
    627 			char logbuf[IPSEC_LOGSASTRLEN];
    628 			DPRINTF(("%s: packet replay check for %s\n", __func__,
    629 			    ipsec_logsastr(sav, logbuf, sizeof(logbuf))));
    630 			ESP_STATINC(ESP_STAT_REPLAY);
    631 			error = ENOBUFS;
    632 			goto bad;
    633 		}
    634 	}
    635 
    636 	/* Determine the ESP header length */
    637 	if (sav->flags & SADB_X_EXT_OLD)
    638 		hlen = sizeof(struct esp) + sav->ivlen;
    639 	else
    640 		hlen = sizeof(struct newesp) + sav->ivlen;
    641 
    642 	/* Remove the ESP header and IV from the mbuf. */
    643 	error = m_striphdr(m, skip, hlen);
    644 	if (error) {
    645 		ESP_STATINC(ESP_STAT_HDROPS);
    646 		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
    647 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
    648 		    (u_long) ntohl(sav->spi)));
    649 		goto bad;
    650 	}
    651 
    652 	/* Save the last three bytes of decrypted data */
    653 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
    654 
    655 	/* Verify pad length */
    656 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
    657 		ESP_STATINC(ESP_STAT_BADILEN);
    658 		DPRINTF(("%s: invalid padding length %d "
    659 		    "for %u byte packet in SA %s/%08lx\n", __func__,
    660 		    lastthree[1], m->m_pkthdr.len - skip,
    661 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
    662 		    (u_long) ntohl(sav->spi)));
    663 		error = EINVAL;
    664 		goto bad;
    665 	}
    666 
    667 	/* Verify correct decryption by checking the last padding bytes */
    668 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
    669 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
    670 			ESP_STATINC(ESP_STAT_BADENC);
    671 			DPRINTF(("%s: decryption failed for packet in SA "
    672 			    "%s/%08lx\n", __func__,
    673 			    ipsec_address(&sav->sah->saidx.dst, buf,
    674 			    sizeof(buf)), (u_long) ntohl(sav->spi)));
    675 			DPRINTF(("%s: %x %x\n", __func__, lastthree[0],
    676 			    lastthree[1]));
    677 			error = EINVAL;
    678 			goto bad;
    679 		}
    680 	}
    681 
    682 	/* Trim the mbuf chain to remove trailing authenticator and padding */
    683 	m_adj(m, -(lastthree[1] + 2));
    684 
    685 	/* Restore the Next Protocol field */
    686 	m_copyback(m, protoff, sizeof(uint8_t), lastthree + 2);
    687 
    688 	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag);
    689 
    690 	KEY_FREESAV(&sav);
    691 	mutex_exit(softnet_lock);
    692 	splx(s);
    693 	return error;
    694 bad:
    695 	if (sav)
    696 		KEY_FREESAV(&sav);
    697 	mutex_exit(softnet_lock);
    698 	splx(s);
    699 	if (m != NULL)
    700 		m_freem(m);
    701 	if (tc != NULL)
    702 		free(tc, M_XDATA);
    703 	if (crp != NULL)
    704 		crypto_freereq(crp);
    705 	return error;
    706 }
    707 
    708 /*
    709  * ESP output routine, called by ipsec[46]_process_packet().
    710  */
    711 static int
    712 esp_output(
    713     struct mbuf *m,
    714     struct ipsecrequest *isr,
    715     struct mbuf **mp,
    716     int skip,
    717     int protoff
    718 )
    719 {
    720 	char buf[IPSEC_ADDRSTRLEN];
    721 	const struct enc_xform *espx;
    722 	const struct auth_hash *esph;
    723 	int hlen, rlen, padding, blks, alen, i, roff;
    724 	struct mbuf *mo = NULL;
    725 	struct tdb_crypto *tc;
    726 	const struct secasvar *sav;
    727 	struct secasindex *saidx;
    728 	unsigned char *pad;
    729 	uint8_t prot;
    730 	int error, maxpacketsize;
    731 
    732 	struct cryptodesc *crde = NULL, *crda = NULL;
    733 	struct cryptop *crp;
    734 
    735 	IPSEC_SPLASSERT_SOFTNET(__func__);
    736 
    737 	KASSERT(isr->sav != NULL);
    738 	sav = isr->sav;
    739 	esph = sav->tdb_authalgxform;
    740 	KASSERT(sav->tdb_encalgxform != NULL);
    741 	espx = sav->tdb_encalgxform;
    742 
    743 	if (sav->flags & SADB_X_EXT_OLD)
    744 		hlen = sizeof(struct esp) + sav->ivlen;
    745 	else
    746 		hlen = sizeof(struct newesp) + sav->ivlen;
    747 
    748 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
    749 	/*
    750 	 * NB: The null encoding transform has a blocksize of 4
    751 	 *     so that headers are properly aligned.
    752 	 */
    753 	blks = espx->blocksize;		/* IV blocksize */
    754 
    755 	/* XXX clamp padding length a la KAME??? */
    756 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
    757 
    758 	if (esph)
    759 		alen = esph->authsize;
    760 	else
    761 		alen = 0;
    762 
    763 	ESP_STATINC(ESP_STAT_OUTPUT);
    764 
    765 	saidx = &sav->sah->saidx;
    766 	/* Check for maximum packet size violations. */
    767 	switch (saidx->dst.sa.sa_family) {
    768 #ifdef INET
    769 	case AF_INET:
    770 		maxpacketsize = IP_MAXPACKET;
    771 		break;
    772 #endif /* INET */
    773 #ifdef INET6
    774 	case AF_INET6:
    775 		maxpacketsize = IPV6_MAXPACKET;
    776 		break;
    777 #endif /* INET6 */
    778 	default:
    779 		DPRINTF(("%s: unknown/unsupported protocol family %d, "
    780 		    "SA %s/%08lx\n", __func__, saidx->dst.sa.sa_family,
    781 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
    782 		    (u_long)ntohl(sav->spi)));
    783 		ESP_STATINC(ESP_STAT_NOPF);
    784 		error = EPFNOSUPPORT;
    785 		goto bad;
    786 	}
    787 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
    788 		DPRINTF(("%s: packet in SA %s/%08lx got too big (len %u, "
    789 		    "max len %u)\n", __func__,
    790 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
    791 		    (u_long) ntohl(sav->spi),
    792 		    skip + hlen + rlen + padding + alen, maxpacketsize));
    793 		ESP_STATINC(ESP_STAT_TOOBIG);
    794 		error = EMSGSIZE;
    795 		goto bad;
    796 	}
    797 
    798 	/* Update the counters. */
    799 	ESP_STATADD(ESP_STAT_OBYTES, m->m_pkthdr.len - skip);
    800 
    801 	m = m_clone(m);
    802 	if (m == NULL) {
    803 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
    804 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
    805 		    (u_long) ntohl(sav->spi)));
    806 		ESP_STATINC(ESP_STAT_HDROPS);
    807 		error = ENOBUFS;
    808 		goto bad;
    809 	}
    810 
    811 	/* Inject ESP header. */
    812 	mo = m_makespace(m, skip, hlen, &roff);
    813 	if (mo == NULL) {
    814 		DPRINTF(("%s: failed to inject %u byte ESP hdr for SA "
    815 		    "%s/%08lx\n", __func__, hlen,
    816 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
    817 		    (u_long) ntohl(sav->spi)));
    818 		ESP_STATINC(ESP_STAT_HDROPS);	/* XXX diffs from openbsd */
    819 		error = ENOBUFS;
    820 		goto bad;
    821 	}
    822 
    823 	/* Initialize ESP header. */
    824 	memcpy(mtod(mo, char *) + roff, &sav->spi, sizeof(uint32_t));
    825 	if (sav->replay) {
    826 		uint32_t replay;
    827 
    828 #ifdef IPSEC_DEBUG
    829 		/* Emulate replay attack when ipsec_replay is TRUE. */
    830 		if (!ipsec_replay)
    831 #endif
    832 			sav->replay->count++;
    833 
    834 		replay = htonl(sav->replay->count);
    835 		memcpy(mtod(mo,char *) + roff + sizeof(uint32_t), &replay,
    836 		    sizeof(uint32_t));
    837 	}
    838 
    839 	/*
    840 	 * Add padding -- better to do it ourselves than use the crypto engine,
    841 	 * although if/when we support compression, we'd have to do that.
    842 	 */
    843 	pad = m_pad(m, padding + alen);
    844 	if (pad == NULL) {
    845 		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
    846 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
    847 		    (u_long) ntohl(sav->spi)));
    848 		m = NULL;		/* NB: free'd by m_pad */
    849 		error = ENOBUFS;
    850 		goto bad;
    851 	}
    852 
    853 	/*
    854 	 * Add padding: random, zero, or self-describing.
    855 	 * XXX catch unexpected setting
    856 	 */
    857 	switch (sav->flags & SADB_X_EXT_PMASK) {
    858 	case SADB_X_EXT_PRAND:
    859 		(void) cprng_fast(pad, padding - 2);
    860 		break;
    861 	case SADB_X_EXT_PZERO:
    862 		memset(pad, 0, padding - 2);
    863 		break;
    864 	case SADB_X_EXT_PSEQ:
    865 		for (i = 0; i < padding - 2; i++)
    866 			pad[i] = i+1;
    867 		break;
    868 	}
    869 
    870 	/* Fix padding length and Next Protocol in padding itself. */
    871 	pad[padding - 2] = padding - 2;
    872 	m_copydata(m, protoff, sizeof(uint8_t), pad + padding - 1);
    873 
    874 	/* Fix Next Protocol in IPv4/IPv6 header. */
    875 	prot = IPPROTO_ESP;
    876 	m_copyback(m, protoff, sizeof(uint8_t), &prot);
    877 
    878 	/* Get crypto descriptors. */
    879 	crp = crypto_getreq(esph && espx ? 2 : 1);
    880 	if (crp == NULL) {
    881 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
    882 		    __func__));
    883 		ESP_STATINC(ESP_STAT_CRYPTO);
    884 		error = ENOBUFS;
    885 		goto bad;
    886 	}
    887 
    888 	if (espx) {
    889 		crde = crp->crp_desc;
    890 		crda = crde->crd_next;
    891 
    892 		/* Encryption descriptor. */
    893 		crde->crd_skip = skip + hlen;
    894 		if (espx->type == CRYPTO_AES_GMAC)
    895 			crde->crd_len = 0;
    896 		else
    897 			crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
    898 		crde->crd_flags = CRD_F_ENCRYPT;
    899 		crde->crd_inject = skip + hlen - sav->ivlen;
    900 
    901 		/* Encryption operation. */
    902 		crde->crd_alg = espx->type;
    903 		crde->crd_key = _KEYBUF(sav->key_enc);
    904 		crde->crd_klen = _KEYBITS(sav->key_enc);
    905 		/* XXX Rounds ? */
    906 	} else
    907 		crda = crp->crp_desc;
    908 
    909 	/* IPsec-specific opaque crypto info. */
    910 	tc = malloc(sizeof(*tc), M_XDATA, M_NOWAIT|M_ZERO);
    911 	if (tc == NULL) {
    912 		crypto_freereq(crp);
    913 		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
    914 		ESP_STATINC(ESP_STAT_CRYPTO);
    915 		error = ENOBUFS;
    916 		goto bad;
    917 	}
    918 
    919 	/* Callback parameters */
    920 	tc->tc_isr = isr;
    921 	tc->tc_spi = sav->spi;
    922 	tc->tc_dst = saidx->dst;
    923 	tc->tc_proto = saidx->proto;
    924 
    925 	/* Crypto operation descriptor. */
    926 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
    927 	crp->crp_flags = CRYPTO_F_IMBUF;
    928 	crp->crp_buf = m;
    929 	crp->crp_callback = esp_output_cb;
    930 	crp->crp_opaque = tc;
    931 	crp->crp_sid = sav->tdb_cryptoid;
    932 
    933 	if (esph) {
    934 		/* Authentication descriptor. */
    935 		crda->crd_skip = skip;
    936 		if (espx && espx->type == CRYPTO_AES_GCM_16)
    937 			crda->crd_len = hlen - sav->ivlen;
    938 		else
    939 			crda->crd_len = m->m_pkthdr.len - (skip + alen);
    940 		crda->crd_inject = m->m_pkthdr.len - alen;
    941 
    942 		/* Authentication operation. */
    943 		crda->crd_alg = esph->type;
    944 		if (espx && (espx->type == CRYPTO_AES_GCM_16 ||
    945 			     espx->type == CRYPTO_AES_GMAC)) {
    946 			crda->crd_key = _KEYBUF(sav->key_enc);
    947 			crda->crd_klen = _KEYBITS(sav->key_enc);
    948 		} else {
    949 			crda->crd_key = _KEYBUF(sav->key_auth);
    950 			crda->crd_klen = _KEYBITS(sav->key_auth);
    951 		}
    952 	}
    953 
    954 	return crypto_dispatch(crp);
    955 bad:
    956 	if (m)
    957 		m_freem(m);
    958 	return (error);
    959 }
    960 
    961 /*
    962  * ESP output callback from the crypto driver.
    963  */
    964 static int
    965 esp_output_cb(struct cryptop *crp)
    966 {
    967 	struct tdb_crypto *tc;
    968 	struct ipsecrequest *isr;
    969 	struct secasvar *sav;
    970 	struct mbuf *m;
    971 	int s, err, error;
    972 
    973 	KASSERT(crp->crp_opaque != NULL);
    974 	tc = crp->crp_opaque;
    975 	m = crp->crp_buf;
    976 
    977 	s = splsoftnet();
    978 	mutex_enter(softnet_lock);
    979 
    980 	isr = tc->tc_isr;
    981 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi, 0, 0);
    982 	if (sav == NULL) {
    983 		char buf[IPSEC_ADDRSTRLEN];
    984 		ESP_STATINC(ESP_STAT_NOTDB);
    985 		DPRINTF(("%s: SA expired while in crypto (SA %s/%08lx "
    986 		    "proto %u)\n", __func__,
    987 		    ipsec_address(&tc->tc_dst, buf, sizeof(buf)),
    988 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
    989 		error = ENOBUFS;		/*XXX*/
    990 		goto bad;
    991 	}
    992 	KASSERTMSG(isr->sav == sav,
    993 	    "SA changed was %p now %p", isr->sav, sav);
    994 
    995 	/* Check for crypto errors. */
    996 	if (crp->crp_etype) {
    997 		/* Reset session ID. */
    998 		if (sav->tdb_cryptoid != 0)
    999 			sav->tdb_cryptoid = crp->crp_sid;
   1000 
   1001 		if (crp->crp_etype == EAGAIN) {
   1002 			KEY_FREESAV(&sav);
   1003 			mutex_exit(softnet_lock);
   1004 			splx(s);
   1005 			return crypto_dispatch(crp);
   1006 		}
   1007 
   1008 		ESP_STATINC(ESP_STAT_NOXFORM);
   1009 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
   1010 		error = crp->crp_etype;
   1011 		goto bad;
   1012 	}
   1013 
   1014 	/* Shouldn't happen... */
   1015 	if (m == NULL) {
   1016 		ESP_STATINC(ESP_STAT_CRYPTO);
   1017 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
   1018 		error = EINVAL;
   1019 		goto bad;
   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 	free(tc, M_XDATA);
   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);
   1049 	KEY_FREESAV(&sav);
   1050 	mutex_exit(softnet_lock);
   1051 	splx(s);
   1052 	return err;
   1053 bad:
   1054 	if (sav)
   1055 		KEY_FREESAV(&sav);
   1056 	mutex_exit(softnet_lock);
   1057 	splx(s);
   1058 	if (m)
   1059 		m_freem(m);
   1060 	free(tc, M_XDATA);
   1061 	crypto_freereq(crp);
   1062 	return error;
   1063 }
   1064 
   1065 static struct xformsw esp_xformsw = {
   1066 	XF_ESP,		XFT_CONF|XFT_AUTH,	"IPsec ESP",
   1067 	esp_init,	esp_zeroize,		esp_input,
   1068 	esp_output,
   1069 	NULL,
   1070 };
   1071 
   1072 void
   1073 esp_attach(void)
   1074 {
   1075 
   1076 	espstat_percpu = percpu_alloc(sizeof(uint64_t) * ESP_NSTATS);
   1077 
   1078 #define	MAXIV(xform)					\
   1079 	if (xform.ivsize > esp_max_ivlen)		\
   1080 		esp_max_ivlen = xform.ivsize		\
   1081 
   1082 	esp_max_ivlen = 0;
   1083 	MAXIV(enc_xform_des);		/* SADB_EALG_DESCBC */
   1084 	MAXIV(enc_xform_3des);		/* SADB_EALG_3DESCBC */
   1085 	MAXIV(enc_xform_rijndael128);	/* SADB_X_EALG_AES */
   1086 	MAXIV(enc_xform_blf);		/* SADB_X_EALG_BLOWFISHCBC */
   1087 	MAXIV(enc_xform_cast5);		/* SADB_X_EALG_CAST128CBC */
   1088 	MAXIV(enc_xform_skipjack);	/* SADB_X_EALG_SKIPJACK */
   1089 	MAXIV(enc_xform_camellia);	/* SADB_X_EALG_CAMELLIACBC */
   1090 	MAXIV(enc_xform_aes_ctr);	/* SADB_X_EALG_AESCTR */
   1091 	MAXIV(enc_xform_null);		/* SADB_EALG_NULL */
   1092 
   1093 	xform_register(&esp_xformsw);
   1094 #undef MAXIV
   1095 }
   1096