xref: /freebsd/sys/netipsec/xform_esp.c (revision 6f63e88c0166ed3e5f2805a9e667c7d24d304cf1)
1 /*	$FreeBSD$	*/
2 /*	$OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 angelos Exp $ */
3 /*-
4  * The authors of this code are John Ioannidis (ji@tla.org),
5  * Angelos D. Keromytis (kermit@csd.uch.gr) and
6  * Niels Provos (provos@physnet.uni-hamburg.de).
7  *
8  * The original version of this code was written by John Ioannidis
9  * for BSD/OS in Athens, Greece, in November 1995.
10  *
11  * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
12  * by Angelos D. Keromytis.
13  *
14  * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
15  * and Niels Provos.
16  *
17  * Additional features in 1999 by Angelos D. Keromytis.
18  *
19  * Copyright (C) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
20  * Angelos D. Keromytis and Niels Provos.
21  * Copyright (c) 2001 Angelos D. Keromytis.
22  *
23  * Permission to use, copy, and modify this software with or without fee
24  * is hereby granted, provided that this entire notice is included in
25  * all copies of any software which is or includes a copy or
26  * modification of this software.
27  * You may use this code under the GNU public license if you so wish. Please
28  * contribute changes back to the authors under this freer than GPL license
29  * so that we may further the use of strong encryption without limitations to
30  * all.
31  *
32  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
33  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
34  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
35  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
36  * PURPOSE.
37  */
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/mbuf.h>
44 #include <sys/socket.h>
45 #include <sys/syslog.h>
46 #include <sys/kernel.h>
47 #include <sys/lock.h>
48 #include <sys/random.h>
49 #include <sys/mutex.h>
50 #include <sys/sysctl.h>
51 #include <sys/mutex.h>
52 #include <machine/atomic.h>
53 
54 #include <net/if.h>
55 #include <net/vnet.h>
56 
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/ip.h>
60 #include <netinet/ip_ecn.h>
61 #include <netinet/ip6.h>
62 
63 #include <netipsec/ipsec.h>
64 #include <netipsec/ah.h>
65 #include <netipsec/ah_var.h>
66 #include <netipsec/esp.h>
67 #include <netipsec/esp_var.h>
68 #include <netipsec/xform.h>
69 
70 #ifdef INET6
71 #include <netinet6/ip6_var.h>
72 #include <netipsec/ipsec6.h>
73 #include <netinet6/ip6_ecn.h>
74 #endif
75 
76 #include <netipsec/key.h>
77 #include <netipsec/key_debug.h>
78 
79 #include <opencrypto/cryptodev.h>
80 #include <opencrypto/xform.h>
81 
82 VNET_DEFINE(int, esp_enable) = 1;
83 VNET_PCPUSTAT_DEFINE(struct espstat, espstat);
84 VNET_PCPUSTAT_SYSINIT(espstat);
85 
86 #ifdef VIMAGE
87 VNET_PCPUSTAT_SYSUNINIT(espstat);
88 #endif /* VIMAGE */
89 
90 SYSCTL_DECL(_net_inet_esp);
91 SYSCTL_INT(_net_inet_esp, OID_AUTO, esp_enable,
92 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_enable), 0, "");
93 SYSCTL_VNET_PCPUSTAT(_net_inet_esp, IPSECCTL_STATS, stats,
94     struct espstat, espstat,
95     "ESP statistics (struct espstat, netipsec/esp_var.h");
96 
97 static struct timeval deswarn, blfwarn, castwarn, camelliawarn, tdeswarn;
98 
99 static int esp_input_cb(struct cryptop *op);
100 static int esp_output_cb(struct cryptop *crp);
101 
102 size_t
103 esp_hdrsiz(struct secasvar *sav)
104 {
105 	size_t size;
106 
107 	if (sav != NULL) {
108 		/*XXX not right for null algorithm--does it matter??*/
109 		IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
110 			("SA with null xform"));
111 		if (sav->flags & SADB_X_EXT_OLD)
112 			size = sizeof (struct esp);
113 		else
114 			size = sizeof (struct newesp);
115 		size += sav->tdb_encalgxform->blocksize + 9;
116 		/*XXX need alg check???*/
117 		if (sav->tdb_authalgxform != NULL && sav->replay)
118 			size += ah_hdrsiz(sav);
119 	} else {
120 		/*
121 		 *   base header size
122 		 * + max iv length for CBC mode
123 		 * + max pad length
124 		 * + sizeof (pad length field)
125 		 * + sizeof (next header field)
126 		 * + max icv supported.
127 		 */
128 		size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
129 	}
130 	return size;
131 }
132 
133 /*
134  * esp_init() is called when an SPI is being set up.
135  */
136 static int
137 esp_init(struct secasvar *sav, struct xformsw *xsp)
138 {
139 	const struct enc_xform *txform;
140 	struct crypto_session_params csp;
141 	int keylen;
142 	int error;
143 
144 	txform = enc_algorithm_lookup(sav->alg_enc);
145 	if (txform == NULL) {
146 		DPRINTF(("%s: unsupported encryption algorithm %d\n",
147 			__func__, sav->alg_enc));
148 		return EINVAL;
149 	}
150 	if (sav->key_enc == NULL) {
151 		DPRINTF(("%s: no encoding key for %s algorithm\n",
152 			 __func__, txform->name));
153 		return EINVAL;
154 	}
155 	if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
156 	    SADB_X_EXT_IV4B) {
157 		DPRINTF(("%s: 4-byte IV not supported with protocol\n",
158 			__func__));
159 		return EINVAL;
160 	}
161 
162 	switch (sav->alg_enc) {
163 	case SADB_EALG_DESCBC:
164 		if (ratecheck(&deswarn, &ipsec_warn_interval))
165 			gone_in(13, "DES cipher for IPsec");
166 		break;
167 	case SADB_EALG_3DESCBC:
168 		if (ratecheck(&tdeswarn, &ipsec_warn_interval))
169 			gone_in(13, "3DES cipher for IPsec");
170 		break;
171 	case SADB_X_EALG_BLOWFISHCBC:
172 		if (ratecheck(&blfwarn, &ipsec_warn_interval))
173 			gone_in(13, "Blowfish cipher for IPsec");
174 		break;
175 	case SADB_X_EALG_CAST128CBC:
176 		if (ratecheck(&castwarn, &ipsec_warn_interval))
177 			gone_in(13, "CAST cipher for IPsec");
178 		break;
179 	case SADB_X_EALG_CAMELLIACBC:
180 		if (ratecheck(&camelliawarn, &ipsec_warn_interval))
181 			gone_in(13, "Camellia cipher for IPsec");
182 		break;
183 	}
184 
185 	/* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
186 	keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
187 	if (txform->minkey > keylen || keylen > txform->maxkey) {
188 		DPRINTF(("%s: invalid key length %u, must be in the range "
189 			"[%u..%u] for algorithm %s\n", __func__,
190 			keylen, txform->minkey, txform->maxkey,
191 			txform->name));
192 		return EINVAL;
193 	}
194 
195 	if (SAV_ISCTRORGCM(sav))
196 		sav->ivlen = 8;	/* RFC4106 3.1 and RFC3686 3.1 */
197 	else
198 		sav->ivlen = txform->ivsize;
199 
200 	memset(&csp, 0, sizeof(csp));
201 
202 	/*
203 	 * Setup AH-related state.
204 	 */
205 	if (sav->alg_auth != 0) {
206 		error = ah_init0(sav, xsp, &csp);
207 		if (error)
208 			return error;
209 	}
210 
211 	/* NB: override anything set in ah_init0 */
212 	sav->tdb_xform = xsp;
213 	sav->tdb_encalgxform = txform;
214 
215 	/*
216 	 * Whenever AES-GCM is used for encryption, one
217 	 * of the AES authentication algorithms is chosen
218 	 * as well, based on the key size.
219 	 */
220 	if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
221 		switch (keylen) {
222 		case AES_128_GMAC_KEY_LEN:
223 			sav->alg_auth = SADB_X_AALG_AES128GMAC;
224 			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
225 			break;
226 		case AES_192_GMAC_KEY_LEN:
227 			sav->alg_auth = SADB_X_AALG_AES192GMAC;
228 			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
229 			break;
230 		case AES_256_GMAC_KEY_LEN:
231 			sav->alg_auth = SADB_X_AALG_AES256GMAC;
232 			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
233 			break;
234 		default:
235 			DPRINTF(("%s: invalid key length %u"
236 				 "for algorithm %s\n", __func__,
237 				 keylen, txform->name));
238 			return EINVAL;
239 		}
240 		csp.csp_mode = CSP_MODE_AEAD;
241 	} else if (sav->alg_auth != 0)
242 		csp.csp_mode = CSP_MODE_ETA;
243 	else
244 		csp.csp_mode = CSP_MODE_CIPHER;
245 
246 	/* Initialize crypto session. */
247 	csp.csp_cipher_alg = sav->tdb_encalgxform->type;
248 	csp.csp_cipher_key = sav->key_enc->key_data;
249 	csp.csp_cipher_klen = _KEYBITS(sav->key_enc) / 8 -
250 	    SAV_ISCTRORGCM(sav) * 4;
251 	csp.csp_ivlen = txform->ivsize;
252 
253 	error = crypto_newsession(&sav->tdb_cryptoid, &csp, V_crypto_support);
254 	return error;
255 }
256 
257 /*
258  * Paranoia.
259  */
260 static int
261 esp_zeroize(struct secasvar *sav)
262 {
263 	/* NB: ah_zerorize free's the crypto session state */
264 	int error = ah_zeroize(sav);
265 
266 	if (sav->key_enc)
267 		bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
268 	sav->tdb_encalgxform = NULL;
269 	sav->tdb_xform = NULL;
270 	return error;
271 }
272 
273 /*
274  * ESP input processing, called (eventually) through the protocol switch.
275  */
276 static int
277 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
278 {
279 	IPSEC_DEBUG_DECLARE(char buf[128]);
280 	const struct auth_hash *esph;
281 	const struct enc_xform *espx;
282 	struct xform_data *xd;
283 	struct cryptop *crp;
284 	struct newesp *esp;
285 	uint8_t *ivp;
286 	crypto_session_t cryptoid;
287 	int alen, error, hlen, plen;
288 
289 	IPSEC_ASSERT(sav != NULL, ("null SA"));
290 	IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
291 
292 	error = EINVAL;
293 	/* Valid IP Packet length ? */
294 	if ( (skip&3) || (m->m_pkthdr.len&3) ){
295 		DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
296 				__func__, skip, m->m_pkthdr.len));
297 		ESPSTAT_INC(esps_badilen);
298 		goto bad;
299 	}
300 
301 	if (m->m_len < skip + sizeof(*esp)) {
302 		m = m_pullup(m, skip + sizeof(*esp));
303 		if (m == NULL) {
304 			DPRINTF(("%s: cannot pullup header\n", __func__));
305 			ESPSTAT_INC(esps_hdrops);	/*XXX*/
306 			error = ENOBUFS;
307 			goto bad;
308 		}
309 	}
310 	esp = (struct newesp *)(mtod(m, caddr_t) + skip);
311 
312 	esph = sav->tdb_authalgxform;
313 	espx = sav->tdb_encalgxform;
314 
315 	/* Determine the ESP header and auth length */
316 	if (sav->flags & SADB_X_EXT_OLD)
317 		hlen = sizeof (struct esp) + sav->ivlen;
318 	else
319 		hlen = sizeof (struct newesp) + sav->ivlen;
320 
321 	alen = xform_ah_authsize(esph);
322 
323 	/*
324 	 * Verify payload length is multiple of encryption algorithm
325 	 * block size.
326 	 *
327 	 * NB: This works for the null algorithm because the blocksize
328 	 *     is 4 and all packets must be 4-byte aligned regardless
329 	 *     of the algorithm.
330 	 */
331 	plen = m->m_pkthdr.len - (skip + hlen + alen);
332 	if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
333 		DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
334 		    "  SA %s/%08lx\n", __func__, plen, espx->blocksize,
335 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
336 		    (u_long)ntohl(sav->spi)));
337 		ESPSTAT_INC(esps_badilen);
338 		goto bad;
339 	}
340 
341 	/*
342 	 * Check sequence number.
343 	 */
344 	SECASVAR_LOCK(sav);
345 	if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
346 		if (ipsec_chkreplay(ntohl(esp->esp_seq), sav) == 0) {
347 			SECASVAR_UNLOCK(sav);
348 			DPRINTF(("%s: packet replay check for %s\n", __func__,
349 			    ipsec_sa2str(sav, buf, sizeof(buf))));
350 			ESPSTAT_INC(esps_replay);
351 			error = EACCES;
352 			goto bad;
353 		}
354 	}
355 	cryptoid = sav->tdb_cryptoid;
356 	SECASVAR_UNLOCK(sav);
357 
358 	/* Update the counters */
359 	ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
360 
361 	/* Get crypto descriptors */
362 	crp = crypto_getreq(cryptoid, M_NOWAIT);
363 	if (crp == NULL) {
364 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
365 			__func__));
366 		ESPSTAT_INC(esps_crypto);
367 		error = ENOBUFS;
368 		goto bad;
369 	}
370 
371 	/* Get IPsec-specific opaque pointer */
372 	xd = malloc(sizeof(*xd), M_XDATA, M_NOWAIT | M_ZERO);
373 	if (xd == NULL) {
374 		DPRINTF(("%s: failed to allocate xform_data\n", __func__));
375 		ESPSTAT_INC(esps_crypto);
376 		crypto_freereq(crp);
377 		error = ENOBUFS;
378 		goto bad;
379 	}
380 
381 	if (esph != NULL) {
382 		crp->crp_op = CRYPTO_OP_VERIFY_DIGEST;
383 		crp->crp_aad_start = skip;
384 		if (SAV_ISGCM(sav))
385 			crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
386 		else
387 			crp->crp_aad_length = hlen;
388 		crp->crp_digest_start = m->m_pkthdr.len - alen;
389 	}
390 
391 	/* Crypto operation descriptor */
392 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
393 	crp->crp_flags = CRYPTO_F_CBIFSYNC;
394 	if (V_async_crypto)
395 		crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
396 	crp->crp_mbuf = m;
397 	crp->crp_buf_type = CRYPTO_BUF_MBUF;
398 	crp->crp_callback = esp_input_cb;
399 	crp->crp_opaque = xd;
400 
401 	/* These are passed as-is to the callback */
402 	xd->sav = sav;
403 	xd->protoff = protoff;
404 	xd->skip = skip;
405 	xd->cryptoid = cryptoid;
406 	xd->vnet = curvnet;
407 
408 	/* Decryption descriptor */
409 	crp->crp_op |= CRYPTO_OP_DECRYPT;
410 	crp->crp_payload_start = skip + hlen;
411 	crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
412 
413 	/* Generate or read cipher IV. */
414 	if (SAV_ISCTRORGCM(sav)) {
415 		ivp = &crp->crp_iv[0];
416 
417 		/*
418 		 * AES-GCM and AES-CTR use similar cipher IV formats
419 		 * defined in RFC 4106 section 4 and RFC 3686 section
420 		 * 4, respectively.
421 		 *
422 		 * The first 4 bytes of the cipher IV contain an
423 		 * implicit salt, or nonce, obtained from the last 4
424 		 * bytes of the encryption key.  The next 8 bytes hold
425 		 * an explicit IV unique to each packet.  This
426 		 * explicit IV is used as the ESP IV for the packet.
427 		 * The last 4 bytes hold a big-endian block counter
428 		 * incremented for each block.  For AES-GCM, the block
429 		 * counter's initial value is defined as part of the
430 		 * algorithm.  For AES-CTR, the block counter's
431 		 * initial value for each packet is defined as 1 by
432 		 * RFC 3686.
433 		 *
434 		 * ------------------------------------------
435 		 * | Salt | Explicit ESP IV | Block Counter |
436 		 * ------------------------------------------
437 		 *  4 bytes     8 bytes          4 bytes
438 		 */
439 		memcpy(ivp, sav->key_enc->key_data +
440 		    _KEYLEN(sav->key_enc) - 4, 4);
441 		m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
442 		if (SAV_ISCTR(sav)) {
443 			be32enc(&ivp[sav->ivlen + 4], 1);
444 		}
445 		crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
446 	} else if (sav->ivlen != 0)
447 		crp->crp_iv_start = skip + hlen - sav->ivlen;
448 
449 	return (crypto_dispatch(crp));
450 bad:
451 	m_freem(m);
452 	key_freesav(&sav);
453 	return (error);
454 }
455 
456 /*
457  * ESP input callback from the crypto driver.
458  */
459 static int
460 esp_input_cb(struct cryptop *crp)
461 {
462 	IPSEC_DEBUG_DECLARE(char buf[128]);
463 	uint8_t lastthree[3];
464 	const struct auth_hash *esph;
465 	struct mbuf *m;
466 	struct xform_data *xd;
467 	struct secasvar *sav;
468 	struct secasindex *saidx;
469 	crypto_session_t cryptoid;
470 	int hlen, skip, protoff, error, alen;
471 
472 	m = crp->crp_mbuf;
473 	xd = crp->crp_opaque;
474 	CURVNET_SET(xd->vnet);
475 	sav = xd->sav;
476 	skip = xd->skip;
477 	protoff = xd->protoff;
478 	cryptoid = xd->cryptoid;
479 	saidx = &sav->sah->saidx;
480 	esph = sav->tdb_authalgxform;
481 
482 	/* Check for crypto errors */
483 	if (crp->crp_etype) {
484 		if (crp->crp_etype == EAGAIN) {
485 			/* Reset the session ID */
486 			if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
487 				crypto_freesession(cryptoid);
488 			xd->cryptoid = crp->crp_session;
489 			CURVNET_RESTORE();
490 			return (crypto_dispatch(crp));
491 		}
492 
493 		/* EBADMSG indicates authentication failure. */
494 		if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
495 			ESPSTAT_INC(esps_noxform);
496 			DPRINTF(("%s: crypto error %d\n", __func__,
497 				crp->crp_etype));
498 			error = crp->crp_etype;
499 			goto bad;
500 		}
501 	}
502 
503 	/* Shouldn't happen... */
504 	if (m == NULL) {
505 		ESPSTAT_INC(esps_crypto);
506 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
507 		error = EINVAL;
508 		goto bad;
509 	}
510 	ESPSTAT_INC(esps_hist[sav->alg_enc]);
511 
512 	/* If authentication was performed, check now. */
513 	if (esph != NULL) {
514 		alen = xform_ah_authsize(esph);
515 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
516 		if (crp->crp_etype == EBADMSG) {
517 			DPRINTF(("%s: authentication hash mismatch for "
518 			    "packet in SA %s/%08lx\n", __func__,
519 			    ipsec_address(&saidx->dst, buf, sizeof(buf)),
520 			    (u_long) ntohl(sav->spi)));
521 			ESPSTAT_INC(esps_badauth);
522 			error = EACCES;
523 			goto bad;
524 		}
525 		m->m_flags |= M_AUTHIPDGM;
526 		/* Remove trailing authenticator */
527 		m_adj(m, -alen);
528 	}
529 
530 	/* Release the crypto descriptors */
531 	free(xd, M_XDATA), xd = NULL;
532 	crypto_freereq(crp), crp = NULL;
533 
534 	/*
535 	 * Packet is now decrypted.
536 	 */
537 	m->m_flags |= M_DECRYPTED;
538 
539 	/*
540 	 * Update replay sequence number, if appropriate.
541 	 */
542 	if (sav->replay) {
543 		u_int32_t seq;
544 
545 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
546 			   sizeof (seq), (caddr_t) &seq);
547 		SECASVAR_LOCK(sav);
548 		if (ipsec_updatereplay(ntohl(seq), sav)) {
549 			SECASVAR_UNLOCK(sav);
550 			DPRINTF(("%s: packet replay check for %s\n", __func__,
551 			    ipsec_sa2str(sav, buf, sizeof(buf))));
552 			ESPSTAT_INC(esps_replay);
553 			error = EACCES;
554 			goto bad;
555 		}
556 		SECASVAR_UNLOCK(sav);
557 	}
558 
559 	/* Determine the ESP header length */
560 	if (sav->flags & SADB_X_EXT_OLD)
561 		hlen = sizeof (struct esp) + sav->ivlen;
562 	else
563 		hlen = sizeof (struct newesp) + sav->ivlen;
564 
565 	/* Remove the ESP header and IV from the mbuf. */
566 	error = m_striphdr(m, skip, hlen);
567 	if (error) {
568 		ESPSTAT_INC(esps_hdrops);
569 		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
570 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
571 		    (u_long) ntohl(sav->spi)));
572 		goto bad;
573 	}
574 
575 	/* Save the last three bytes of decrypted data */
576 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
577 
578 	/* Verify pad length */
579 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
580 		ESPSTAT_INC(esps_badilen);
581 		DPRINTF(("%s: invalid padding length %d for %u byte packet "
582 		    "in SA %s/%08lx\n", __func__, lastthree[1],
583 		    m->m_pkthdr.len - skip,
584 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
585 		    (u_long) ntohl(sav->spi)));
586 		error = EINVAL;
587 		goto bad;
588 	}
589 
590 	/* Verify correct decryption by checking the last padding bytes */
591 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
592 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
593 			ESPSTAT_INC(esps_badenc);
594 			DPRINTF(("%s: decryption failed for packet in "
595 			    "SA %s/%08lx\n", __func__, ipsec_address(
596 			    &sav->sah->saidx.dst, buf, sizeof(buf)),
597 			    (u_long) ntohl(sav->spi)));
598 			error = EINVAL;
599 			goto bad;
600 		}
601 	}
602 
603 	/*
604 	 * RFC4303 2.6:
605 	 * Silently drop packet if next header field is IPPROTO_NONE.
606 	 */
607 	if (lastthree[2] == IPPROTO_NONE)
608 		goto bad;
609 
610 	/* Trim the mbuf chain to remove trailing authenticator and padding */
611 	m_adj(m, -(lastthree[1] + 2));
612 
613 	/* Restore the Next Protocol field */
614 	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
615 
616 	switch (saidx->dst.sa.sa_family) {
617 #ifdef INET6
618 	case AF_INET6:
619 		error = ipsec6_common_input_cb(m, sav, skip, protoff);
620 		break;
621 #endif
622 #ifdef INET
623 	case AF_INET:
624 		error = ipsec4_common_input_cb(m, sav, skip, protoff);
625 		break;
626 #endif
627 	default:
628 		panic("%s: Unexpected address family: %d saidx=%p", __func__,
629 		    saidx->dst.sa.sa_family, saidx);
630 	}
631 	CURVNET_RESTORE();
632 	return error;
633 bad:
634 	CURVNET_RESTORE();
635 	if (sav != NULL)
636 		key_freesav(&sav);
637 	if (m != NULL)
638 		m_freem(m);
639 	if (xd != NULL)
640 		free(xd, M_XDATA);
641 	if (crp != NULL)
642 		crypto_freereq(crp);
643 	return error;
644 }
645 /*
646  * ESP output routine, called by ipsec[46]_perform_request().
647  */
648 static int
649 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
650     u_int idx, int skip, int protoff)
651 {
652 	IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
653 	struct cryptop *crp;
654 	const struct auth_hash *esph;
655 	const struct enc_xform *espx;
656 	struct mbuf *mo = NULL;
657 	struct xform_data *xd;
658 	struct secasindex *saidx;
659 	unsigned char *pad;
660 	uint8_t *ivp;
661 	uint64_t cntr;
662 	crypto_session_t cryptoid;
663 	int hlen, rlen, padding, blks, alen, i, roff;
664 	int error, maxpacketsize;
665 	uint8_t prot;
666 
667 	IPSEC_ASSERT(sav != NULL, ("null SA"));
668 	esph = sav->tdb_authalgxform;
669 	espx = sav->tdb_encalgxform;
670 	IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
671 
672 	if (sav->flags & SADB_X_EXT_OLD)
673 		hlen = sizeof (struct esp) + sav->ivlen;
674 	else
675 		hlen = sizeof (struct newesp) + sav->ivlen;
676 
677 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
678 	/*
679 	 * RFC4303 2.4 Requires 4 byte alignment.
680 	 */
681 	blks = MAX(4, espx->blocksize);		/* Cipher blocksize */
682 
683 	/* XXX clamp padding length a la KAME??? */
684 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
685 
686 	alen = xform_ah_authsize(esph);
687 
688 	ESPSTAT_INC(esps_output);
689 
690 	saidx = &sav->sah->saidx;
691 	/* Check for maximum packet size violations. */
692 	switch (saidx->dst.sa.sa_family) {
693 #ifdef INET
694 	case AF_INET:
695 		maxpacketsize = IP_MAXPACKET;
696 		break;
697 #endif /* INET */
698 #ifdef INET6
699 	case AF_INET6:
700 		maxpacketsize = IPV6_MAXPACKET;
701 		break;
702 #endif /* INET6 */
703 	default:
704 		DPRINTF(("%s: unknown/unsupported protocol "
705 		    "family %d, SA %s/%08lx\n", __func__,
706 		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
707 			buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
708 		ESPSTAT_INC(esps_nopf);
709 		error = EPFNOSUPPORT;
710 		goto bad;
711 	}
712 	/*
713 	DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
714 		__func__, skip, hlen, rlen, padding, alen, blks)); */
715 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
716 		DPRINTF(("%s: packet in SA %s/%08lx got too big "
717 		    "(len %u, max len %u)\n", __func__,
718 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
719 		    (u_long) ntohl(sav->spi),
720 		    skip + hlen + rlen + padding + alen, maxpacketsize));
721 		ESPSTAT_INC(esps_toobig);
722 		error = EMSGSIZE;
723 		goto bad;
724 	}
725 
726 	/* Update the counters. */
727 	ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
728 
729 	m = m_unshare(m, M_NOWAIT);
730 	if (m == NULL) {
731 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
732 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
733 		    (u_long) ntohl(sav->spi)));
734 		ESPSTAT_INC(esps_hdrops);
735 		error = ENOBUFS;
736 		goto bad;
737 	}
738 
739 	/* Inject ESP header. */
740 	mo = m_makespace(m, skip, hlen, &roff);
741 	if (mo == NULL) {
742 		DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
743 		    __func__, hlen, ipsec_address(&saidx->dst, buf,
744 		    sizeof(buf)), (u_long) ntohl(sav->spi)));
745 		ESPSTAT_INC(esps_hdrops);	/* XXX diffs from openbsd */
746 		error = ENOBUFS;
747 		goto bad;
748 	}
749 
750 	/* Initialize ESP header. */
751 	bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
752 	    sizeof(uint32_t));
753 	SECASVAR_LOCK(sav);
754 	if (sav->replay) {
755 		uint32_t replay;
756 
757 #ifdef REGRESSION
758 		/* Emulate replay attack when ipsec_replay is TRUE. */
759 		if (!V_ipsec_replay)
760 #endif
761 			sav->replay->count++;
762 		replay = htonl(sav->replay->count);
763 
764 		bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
765 		    sizeof(uint32_t), sizeof(uint32_t));
766 	}
767 	cryptoid = sav->tdb_cryptoid;
768 	if (SAV_ISCTRORGCM(sav))
769 		cntr = sav->cntr++;
770 	SECASVAR_UNLOCK(sav);
771 
772 	/*
773 	 * Add padding -- better to do it ourselves than use the crypto engine,
774 	 * although if/when we support compression, we'd have to do that.
775 	 */
776 	pad = (u_char *) m_pad(m, padding + alen);
777 	if (pad == NULL) {
778 		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
779 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
780 		    (u_long) ntohl(sav->spi)));
781 		m = NULL;		/* NB: free'd by m_pad */
782 		error = ENOBUFS;
783 		goto bad;
784 	}
785 
786 	/*
787 	 * Add padding: random, zero, or self-describing.
788 	 * XXX catch unexpected setting
789 	 */
790 	switch (sav->flags & SADB_X_EXT_PMASK) {
791 	case SADB_X_EXT_PRAND:
792 		arc4random_buf(pad, padding - 2);
793 		break;
794 	case SADB_X_EXT_PZERO:
795 		bzero(pad, padding - 2);
796 		break;
797 	case SADB_X_EXT_PSEQ:
798 		for (i = 0; i < padding - 2; i++)
799 			pad[i] = i+1;
800 		break;
801 	}
802 
803 	/* Fix padding length and Next Protocol in padding itself. */
804 	pad[padding - 2] = padding - 2;
805 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
806 
807 	/* Fix Next Protocol in IPv4/IPv6 header. */
808 	prot = IPPROTO_ESP;
809 	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
810 
811 	/* Get crypto descriptor. */
812 	crp = crypto_getreq(cryptoid, M_NOWAIT);
813 	if (crp == NULL) {
814 		DPRINTF(("%s: failed to acquire crypto descriptor\n",
815 			__func__));
816 		ESPSTAT_INC(esps_crypto);
817 		error = ENOBUFS;
818 		goto bad;
819 	}
820 
821 	/* IPsec-specific opaque crypto info. */
822 	xd =  malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
823 	if (xd == NULL) {
824 		crypto_freereq(crp);
825 		DPRINTF(("%s: failed to allocate xform_data\n", __func__));
826 		ESPSTAT_INC(esps_crypto);
827 		error = ENOBUFS;
828 		goto bad;
829 	}
830 
831 	/* Encryption descriptor. */
832 	crp->crp_payload_start = skip + hlen;
833 	crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
834 	crp->crp_op = CRYPTO_OP_ENCRYPT;
835 
836 	/* Generate cipher and ESP IVs. */
837 	ivp = &crp->crp_iv[0];
838 	if (SAV_ISCTRORGCM(sav)) {
839 		/*
840 		 * See comment in esp_input() for details on the
841 		 * cipher IV.  A simple per-SA counter stored in
842 		 * 'cntr' is used as the explicit ESP IV.
843 		 */
844 		memcpy(ivp, sav->key_enc->key_data +
845 		    _KEYLEN(sav->key_enc) - 4, 4);
846 		be64enc(&ivp[4], cntr);
847 		if (SAV_ISCTR(sav)) {
848 			be32enc(&ivp[sav->ivlen + 4], 1);
849 		}
850 		m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
851 		crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
852 	} else if (sav->ivlen != 0) {
853 		arc4rand(ivp, sav->ivlen, 0);
854 		crp->crp_iv_start = skip + hlen - sav->ivlen;
855 		m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
856 	}
857 
858 	/* Callback parameters */
859 	xd->sp = sp;
860 	xd->sav = sav;
861 	xd->idx = idx;
862 	xd->cryptoid = cryptoid;
863 	xd->vnet = curvnet;
864 
865 	/* Crypto operation descriptor. */
866 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
867 	crp->crp_flags |= CRYPTO_F_CBIFSYNC;
868 	if (V_async_crypto)
869 		crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
870 	crp->crp_mbuf = m;
871 	crp->crp_buf_type = CRYPTO_BUF_MBUF;
872 	crp->crp_callback = esp_output_cb;
873 	crp->crp_opaque = xd;
874 
875 	if (esph) {
876 		/* Authentication descriptor. */
877 		crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
878 		crp->crp_aad_start = skip;
879 		if (SAV_ISGCM(sav))
880 			crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
881 		else
882 			crp->crp_aad_length = hlen;
883 		crp->crp_digest_start = m->m_pkthdr.len - alen;
884 	}
885 
886 	return crypto_dispatch(crp);
887 bad:
888 	if (m)
889 		m_freem(m);
890 	key_freesav(&sav);
891 	key_freesp(&sp);
892 	return (error);
893 }
894 /*
895  * ESP output callback from the crypto driver.
896  */
897 static int
898 esp_output_cb(struct cryptop *crp)
899 {
900 	struct xform_data *xd;
901 	struct secpolicy *sp;
902 	struct secasvar *sav;
903 	struct mbuf *m;
904 	crypto_session_t cryptoid;
905 	u_int idx;
906 	int error;
907 
908 	xd = (struct xform_data *) crp->crp_opaque;
909 	CURVNET_SET(xd->vnet);
910 	m = (struct mbuf *) crp->crp_buf;
911 	sp = xd->sp;
912 	sav = xd->sav;
913 	idx = xd->idx;
914 	cryptoid = xd->cryptoid;
915 
916 	/* Check for crypto errors. */
917 	if (crp->crp_etype) {
918 		if (crp->crp_etype == EAGAIN) {
919 			/* Reset the session ID */
920 			if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
921 				crypto_freesession(cryptoid);
922 			xd->cryptoid = crp->crp_session;
923 			CURVNET_RESTORE();
924 			return (crypto_dispatch(crp));
925 		}
926 		ESPSTAT_INC(esps_noxform);
927 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
928 		error = crp->crp_etype;
929 		m_freem(m);
930 		goto bad;
931 	}
932 
933 	/* Shouldn't happen... */
934 	if (m == NULL) {
935 		ESPSTAT_INC(esps_crypto);
936 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
937 		error = EINVAL;
938 		goto bad;
939 	}
940 	free(xd, M_XDATA);
941 	crypto_freereq(crp);
942 	ESPSTAT_INC(esps_hist[sav->alg_enc]);
943 	if (sav->tdb_authalgxform != NULL)
944 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
945 
946 #ifdef REGRESSION
947 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
948 	if (V_ipsec_integrity) {
949 		static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
950 		const struct auth_hash *esph;
951 
952 		/*
953 		 * Corrupt HMAC if we want to test integrity verification of
954 		 * the other side.
955 		 */
956 		esph = sav->tdb_authalgxform;
957 		if (esph !=  NULL) {
958 			int alen;
959 
960 			alen = xform_ah_authsize(esph);
961 			m_copyback(m, m->m_pkthdr.len - alen,
962 			    alen, ipseczeroes);
963 		}
964 	}
965 #endif
966 
967 	/* NB: m is reclaimed by ipsec_process_done. */
968 	error = ipsec_process_done(m, sp, sav, idx);
969 	CURVNET_RESTORE();
970 	return (error);
971 bad:
972 	CURVNET_RESTORE();
973 	free(xd, M_XDATA);
974 	crypto_freereq(crp);
975 	key_freesav(&sav);
976 	key_freesp(&sp);
977 	return (error);
978 }
979 
980 static struct xformsw esp_xformsw = {
981 	.xf_type =	XF_ESP,
982 	.xf_name =	"IPsec ESP",
983 	.xf_init =	esp_init,
984 	.xf_zeroize =	esp_zeroize,
985 	.xf_input =	esp_input,
986 	.xf_output =	esp_output,
987 };
988 
989 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
990     xform_attach, &esp_xformsw);
991 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
992     xform_detach, &esp_xformsw);
993