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