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