xref: /freebsd/sys/netipsec/xform_esp.c (revision 2f513db72b034fd5ef7f080b11be5c711c15186a)
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;
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 cryptoini cria, crie;
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_X_EALG_BLOWFISHCBC:
168 		if (ratecheck(&blfwarn, &ipsec_warn_interval))
169 			gone_in(13, "Blowfish cipher for IPsec");
170 		break;
171 	case SADB_X_EALG_CAST128CBC:
172 		if (ratecheck(&castwarn, &ipsec_warn_interval))
173 			gone_in(13, "CAST cipher for IPsec");
174 		break;
175 	case SADB_X_EALG_CAMELLIACBC:
176 		if (ratecheck(&camelliawarn, &ipsec_warn_interval))
177 			gone_in(13, "Camellia cipher for IPsec");
178 		break;
179 	}
180 
181 	/* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
182 	keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
183 	if (txform->minkey > keylen || keylen > txform->maxkey) {
184 		DPRINTF(("%s: invalid key length %u, must be in the range "
185 			"[%u..%u] for algorithm %s\n", __func__,
186 			keylen, txform->minkey, txform->maxkey,
187 			txform->name));
188 		return EINVAL;
189 	}
190 
191 	if (SAV_ISCTRORGCM(sav))
192 		sav->ivlen = 8;	/* RFC4106 3.1 and RFC3686 3.1 */
193 	else
194 		sav->ivlen = txform->ivsize;
195 
196 	/*
197 	 * Setup AH-related state.
198 	 */
199 	if (sav->alg_auth != 0) {
200 		error = ah_init0(sav, xsp, &cria);
201 		if (error)
202 			return error;
203 	}
204 
205 	/* NB: override anything set in ah_init0 */
206 	sav->tdb_xform = xsp;
207 	sav->tdb_encalgxform = txform;
208 
209 	/*
210 	 * Whenever AES-GCM is used for encryption, one
211 	 * of the AES authentication algorithms is chosen
212 	 * as well, based on the key size.
213 	 */
214 	if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
215 		switch (keylen) {
216 		case AES_128_GMAC_KEY_LEN:
217 			sav->alg_auth = SADB_X_AALG_AES128GMAC;
218 			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
219 			break;
220 		case AES_192_GMAC_KEY_LEN:
221 			sav->alg_auth = SADB_X_AALG_AES192GMAC;
222 			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
223 			break;
224 		case AES_256_GMAC_KEY_LEN:
225 			sav->alg_auth = SADB_X_AALG_AES256GMAC;
226 			sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
227 			break;
228 		default:
229 			DPRINTF(("%s: invalid key length %u"
230 				 "for algorithm %s\n", __func__,
231 				 keylen, txform->name));
232 			return EINVAL;
233 		}
234 		bzero(&cria, sizeof(cria));
235 		cria.cri_alg = sav->tdb_authalgxform->type;
236 		cria.cri_key = sav->key_enc->key_data;
237 		cria.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISGCM(sav) * 32;
238 	}
239 
240 	/* Initialize crypto session. */
241 	bzero(&crie, sizeof(crie));
242 	crie.cri_alg = sav->tdb_encalgxform->type;
243 	crie.cri_key = sav->key_enc->key_data;
244 	crie.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISCTRORGCM(sav) * 32;
245 
246 	if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
247 		/* init both auth & enc */
248 		crie.cri_next = &cria;
249 		error = crypto_newsession(&sav->tdb_cryptoid,
250 					  &crie, V_crypto_support);
251 	} else if (sav->tdb_encalgxform) {
252 		error = crypto_newsession(&sav->tdb_cryptoid,
253 					  &crie, V_crypto_support);
254 	} else if (sav->tdb_authalgxform) {
255 		error = crypto_newsession(&sav->tdb_cryptoid,
256 					  &cria, V_crypto_support);
257 	} else {
258 		/* XXX cannot happen? */
259 		DPRINTF(("%s: no encoding OR authentication xform!\n",
260 			__func__));
261 		error = EINVAL;
262 	}
263 	return error;
264 }
265 
266 /*
267  * Paranoia.
268  */
269 static int
270 esp_zeroize(struct secasvar *sav)
271 {
272 	/* NB: ah_zerorize free's the crypto session state */
273 	int error = ah_zeroize(sav);
274 
275 	if (sav->key_enc)
276 		bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
277 	sav->tdb_encalgxform = NULL;
278 	sav->tdb_xform = NULL;
279 	return error;
280 }
281 
282 /*
283  * ESP input processing, called (eventually) through the protocol switch.
284  */
285 static int
286 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
287 {
288 	IPSEC_DEBUG_DECLARE(char buf[128]);
289 	const struct auth_hash *esph;
290 	const struct enc_xform *espx;
291 	struct xform_data *xd;
292 	struct cryptodesc *crde;
293 	struct cryptop *crp;
294 	struct newesp *esp;
295 	uint8_t *ivp;
296 	crypto_session_t cryptoid;
297 	int alen, error, hlen, plen;
298 
299 	IPSEC_ASSERT(sav != NULL, ("null SA"));
300 	IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
301 
302 	error = EINVAL;
303 	/* Valid IP Packet length ? */
304 	if ( (skip&3) || (m->m_pkthdr.len&3) ){
305 		DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
306 				__func__, skip, m->m_pkthdr.len));
307 		ESPSTAT_INC(esps_badilen);
308 		goto bad;
309 	}
310 
311 	if (m->m_len < skip + sizeof(*esp)) {
312 		m = m_pullup(m, skip + sizeof(*esp));
313 		if (m == NULL) {
314 			DPRINTF(("%s: cannot pullup header\n", __func__));
315 			ESPSTAT_INC(esps_hdrops);	/*XXX*/
316 			error = ENOBUFS;
317 			goto bad;
318 		}
319 	}
320 	esp = (struct newesp *)(mtod(m, caddr_t) + skip);
321 
322 	esph = sav->tdb_authalgxform;
323 	espx = sav->tdb_encalgxform;
324 
325 	/* Determine the ESP header and auth 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 
331 	alen = xform_ah_authsize(esph);
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 		DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
344 		    "  SA %s/%08lx\n", __func__, plen, espx->blocksize,
345 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
346 		    (u_long)ntohl(sav->spi)));
347 		ESPSTAT_INC(esps_badilen);
348 		goto bad;
349 	}
350 
351 	/*
352 	 * Check sequence number.
353 	 */
354 	SECASVAR_LOCK(sav);
355 	if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
356 		if (ipsec_chkreplay(ntohl(esp->esp_seq), sav) == 0) {
357 			SECASVAR_UNLOCK(sav);
358 			DPRINTF(("%s: packet replay check for %s\n", __func__,
359 			    ipsec_sa2str(sav, buf, sizeof(buf))));
360 			ESPSTAT_INC(esps_replay);
361 			error = EACCES;
362 			goto bad;
363 		}
364 	}
365 	cryptoid = sav->tdb_cryptoid;
366 	SECASVAR_UNLOCK(sav);
367 
368 	/* Update the counters */
369 	ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
370 
371 	/* Get crypto descriptors */
372 	crp = crypto_getreq(esph && espx ? 2 : 1);
373 	if (crp == NULL) {
374 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
375 			__func__));
376 		ESPSTAT_INC(esps_crypto);
377 		error = ENOBUFS;
378 		goto bad;
379 	}
380 
381 	/* Get IPsec-specific opaque pointer */
382 	xd = malloc(sizeof(*xd) + alen, M_XDATA, M_NOWAIT | M_ZERO);
383 	if (xd == NULL) {
384 		DPRINTF(("%s: failed to allocate xform_data\n", __func__));
385 		ESPSTAT_INC(esps_crypto);
386 		crypto_freereq(crp);
387 		error = ENOBUFS;
388 		goto bad;
389 	}
390 
391 	if (esph != NULL) {
392 		struct cryptodesc *crda = crp->crp_desc;
393 
394 		IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
395 
396 		/* Authentication descriptor */
397 		crda->crd_skip = skip;
398 		if (SAV_ISGCM(sav))
399 			crda->crd_len = 8;	/* RFC4106 5, SPI + SN */
400 		else
401 			crda->crd_len = m->m_pkthdr.len - (skip + alen);
402 		crda->crd_inject = m->m_pkthdr.len - alen;
403 
404 		crda->crd_alg = esph->type;
405 
406 		/* Copy the authenticator */
407 		m_copydata(m, m->m_pkthdr.len - alen, alen,
408 		    (caddr_t) (xd + 1));
409 
410 		/* Chain authentication request */
411 		crde = crda->crd_next;
412 	} else {
413 		crde = crp->crp_desc;
414 	}
415 
416 	/* Crypto operation descriptor */
417 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
418 	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
419 	if (V_async_crypto)
420 		crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
421 	crp->crp_buf = (caddr_t) m;
422 	crp->crp_callback = esp_input_cb;
423 	crp->crp_session = cryptoid;
424 	crp->crp_opaque = (caddr_t) xd;
425 
426 	/* These are passed as-is to the callback */
427 	xd->sav = sav;
428 	xd->protoff = protoff;
429 	xd->skip = skip;
430 	xd->cryptoid = cryptoid;
431 	xd->vnet = curvnet;
432 
433 	/* Decryption descriptor */
434 	IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
435 	crde->crd_skip = skip + hlen;
436 	crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
437 	crde->crd_inject = skip + hlen - sav->ivlen;
438 
439 	if (SAV_ISCTRORGCM(sav)) {
440 		ivp = &crde->crd_iv[0];
441 
442 		/* GCM IV Format: RFC4106 4 */
443 		/* CTR IV Format: RFC3686 4 */
444 		/* Salt is last four bytes of key, RFC4106 8.1 */
445 		/* Nonce is last four bytes of key, RFC3686 5.1 */
446 		memcpy(ivp, sav->key_enc->key_data +
447 		    _KEYLEN(sav->key_enc) - 4, 4);
448 
449 		if (SAV_ISCTR(sav)) {
450 			/* Initial block counter is 1, RFC3686 4 */
451 			be32enc(&ivp[sav->ivlen + 4], 1);
452 		}
453 
454 		m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
455 		crde->crd_flags |= CRD_F_IV_EXPLICIT;
456 	}
457 
458 	crde->crd_alg = espx->type;
459 
460 	return (crypto_dispatch(crp));
461 bad:
462 	m_freem(m);
463 	key_freesav(&sav);
464 	return (error);
465 }
466 
467 /*
468  * ESP input callback from the crypto driver.
469  */
470 static int
471 esp_input_cb(struct cryptop *crp)
472 {
473 	IPSEC_DEBUG_DECLARE(char buf[128]);
474 	u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
475 	const struct auth_hash *esph;
476 	struct mbuf *m;
477 	struct cryptodesc *crd;
478 	struct xform_data *xd;
479 	struct secasvar *sav;
480 	struct secasindex *saidx;
481 	caddr_t ptr;
482 	crypto_session_t cryptoid;
483 	int hlen, skip, protoff, error, alen;
484 
485 	crd = crp->crp_desc;
486 	IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
487 
488 	m = (struct mbuf *) crp->crp_buf;
489 	xd = (struct xform_data *) crp->crp_opaque;
490 	CURVNET_SET(xd->vnet);
491 	sav = xd->sav;
492 	skip = xd->skip;
493 	protoff = xd->protoff;
494 	cryptoid = xd->cryptoid;
495 	saidx = &sav->sah->saidx;
496 	esph = sav->tdb_authalgxform;
497 
498 	/* Check for crypto errors */
499 	if (crp->crp_etype) {
500 		if (crp->crp_etype == EAGAIN) {
501 			/* Reset the session ID */
502 			if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
503 				crypto_freesession(cryptoid);
504 			xd->cryptoid = crp->crp_session;
505 			CURVNET_RESTORE();
506 			return (crypto_dispatch(crp));
507 		}
508 		ESPSTAT_INC(esps_noxform);
509 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
510 		error = crp->crp_etype;
511 		goto bad;
512 	}
513 
514 	/* Shouldn't happen... */
515 	if (m == NULL) {
516 		ESPSTAT_INC(esps_crypto);
517 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
518 		error = EINVAL;
519 		goto bad;
520 	}
521 	ESPSTAT_INC(esps_hist[sav->alg_enc]);
522 
523 	/* If authentication was performed, check now. */
524 	if (esph != NULL) {
525 		alen = xform_ah_authsize(esph);
526 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
527 		/* Copy the authenticator from the packet */
528 		m_copydata(m, m->m_pkthdr.len - alen, alen, aalg);
529 		ptr = (caddr_t) (xd + 1);
530 
531 		/* Verify authenticator */
532 		if (timingsafe_bcmp(ptr, aalg, alen) != 0) {
533 			DPRINTF(("%s: authentication hash mismatch for "
534 			    "packet in SA %s/%08lx\n", __func__,
535 			    ipsec_address(&saidx->dst, buf, sizeof(buf)),
536 			    (u_long) ntohl(sav->spi)));
537 			ESPSTAT_INC(esps_badauth);
538 			error = EACCES;
539 			goto bad;
540 		}
541 		m->m_flags |= M_AUTHIPDGM;
542 		/* Remove trailing authenticator */
543 		m_adj(m, -alen);
544 	}
545 
546 	/* Release the crypto descriptors */
547 	free(xd, M_XDATA), xd = NULL;
548 	crypto_freereq(crp), crp = NULL;
549 
550 	/*
551 	 * Packet is now decrypted.
552 	 */
553 	m->m_flags |= M_DECRYPTED;
554 
555 	/*
556 	 * Update replay sequence number, if appropriate.
557 	 */
558 	if (sav->replay) {
559 		u_int32_t seq;
560 
561 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
562 			   sizeof (seq), (caddr_t) &seq);
563 		SECASVAR_LOCK(sav);
564 		if (ipsec_updatereplay(ntohl(seq), sav)) {
565 			SECASVAR_UNLOCK(sav);
566 			DPRINTF(("%s: packet replay check for %s\n", __func__,
567 			    ipsec_sa2str(sav, buf, sizeof(buf))));
568 			ESPSTAT_INC(esps_replay);
569 			error = EACCES;
570 			goto bad;
571 		}
572 		SECASVAR_UNLOCK(sav);
573 	}
574 
575 	/* Determine the ESP header length */
576 	if (sav->flags & SADB_X_EXT_OLD)
577 		hlen = sizeof (struct esp) + sav->ivlen;
578 	else
579 		hlen = sizeof (struct newesp) + sav->ivlen;
580 
581 	/* Remove the ESP header and IV from the mbuf. */
582 	error = m_striphdr(m, skip, hlen);
583 	if (error) {
584 		ESPSTAT_INC(esps_hdrops);
585 		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
586 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
587 		    (u_long) ntohl(sav->spi)));
588 		goto bad;
589 	}
590 
591 	/* Save the last three bytes of decrypted data */
592 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
593 
594 	/* Verify pad length */
595 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
596 		ESPSTAT_INC(esps_badilen);
597 		DPRINTF(("%s: invalid padding length %d for %u byte packet "
598 		    "in SA %s/%08lx\n", __func__, lastthree[1],
599 		    m->m_pkthdr.len - skip,
600 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
601 		    (u_long) ntohl(sav->spi)));
602 		error = EINVAL;
603 		goto bad;
604 	}
605 
606 	/* Verify correct decryption by checking the last padding bytes */
607 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
608 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
609 			ESPSTAT_INC(esps_badenc);
610 			DPRINTF(("%s: decryption failed for packet in "
611 			    "SA %s/%08lx\n", __func__, ipsec_address(
612 			    &sav->sah->saidx.dst, buf, sizeof(buf)),
613 			    (u_long) ntohl(sav->spi)));
614 			error = EINVAL;
615 			goto bad;
616 		}
617 	}
618 
619 	/*
620 	 * RFC4303 2.6:
621 	 * Silently drop packet if next header field is IPPROTO_NONE.
622 	 */
623 	if (lastthree[2] == IPPROTO_NONE)
624 		goto bad;
625 
626 	/* Trim the mbuf chain to remove trailing authenticator and padding */
627 	m_adj(m, -(lastthree[1] + 2));
628 
629 	/* Restore the Next Protocol field */
630 	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
631 
632 	switch (saidx->dst.sa.sa_family) {
633 #ifdef INET6
634 	case AF_INET6:
635 		error = ipsec6_common_input_cb(m, sav, skip, protoff);
636 		break;
637 #endif
638 #ifdef INET
639 	case AF_INET:
640 		error = ipsec4_common_input_cb(m, sav, skip, protoff);
641 		break;
642 #endif
643 	default:
644 		panic("%s: Unexpected address family: %d saidx=%p", __func__,
645 		    saidx->dst.sa.sa_family, saidx);
646 	}
647 	CURVNET_RESTORE();
648 	return error;
649 bad:
650 	CURVNET_RESTORE();
651 	if (sav != NULL)
652 		key_freesav(&sav);
653 	if (m != NULL)
654 		m_freem(m);
655 	if (xd != NULL)
656 		free(xd, M_XDATA);
657 	if (crp != NULL)
658 		crypto_freereq(crp);
659 	return error;
660 }
661 /*
662  * ESP output routine, called by ipsec[46]_perform_request().
663  */
664 static int
665 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
666     u_int idx, int skip, int protoff)
667 {
668 	IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
669 	struct cryptodesc *crde = NULL, *crda = NULL;
670 	struct cryptop *crp;
671 	const struct auth_hash *esph;
672 	const struct enc_xform *espx;
673 	struct mbuf *mo = NULL;
674 	struct xform_data *xd;
675 	struct secasindex *saidx;
676 	unsigned char *pad;
677 	uint8_t *ivp;
678 	uint64_t cntr;
679 	crypto_session_t cryptoid;
680 	int hlen, rlen, padding, blks, alen, i, roff;
681 	int error, maxpacketsize;
682 	uint8_t prot;
683 
684 	IPSEC_ASSERT(sav != NULL, ("null SA"));
685 	esph = sav->tdb_authalgxform;
686 	espx = sav->tdb_encalgxform;
687 	IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
688 
689 	if (sav->flags & SADB_X_EXT_OLD)
690 		hlen = sizeof (struct esp) + sav->ivlen;
691 	else
692 		hlen = sizeof (struct newesp) + sav->ivlen;
693 
694 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
695 	/*
696 	 * RFC4303 2.4 Requires 4 byte alignment.
697 	 */
698 	blks = MAX(4, espx->blocksize);		/* Cipher blocksize */
699 
700 	/* XXX clamp padding length a la KAME??? */
701 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
702 
703 	alen = xform_ah_authsize(esph);
704 
705 	ESPSTAT_INC(esps_output);
706 
707 	saidx = &sav->sah->saidx;
708 	/* Check for maximum packet size violations. */
709 	switch (saidx->dst.sa.sa_family) {
710 #ifdef INET
711 	case AF_INET:
712 		maxpacketsize = IP_MAXPACKET;
713 		break;
714 #endif /* INET */
715 #ifdef INET6
716 	case AF_INET6:
717 		maxpacketsize = IPV6_MAXPACKET;
718 		break;
719 #endif /* INET6 */
720 	default:
721 		DPRINTF(("%s: unknown/unsupported protocol "
722 		    "family %d, SA %s/%08lx\n", __func__,
723 		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
724 			buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
725 		ESPSTAT_INC(esps_nopf);
726 		error = EPFNOSUPPORT;
727 		goto bad;
728 	}
729 	/*
730 	DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
731 		__func__, skip, hlen, rlen, padding, alen, blks)); */
732 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
733 		DPRINTF(("%s: packet in SA %s/%08lx got too big "
734 		    "(len %u, max len %u)\n", __func__,
735 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
736 		    (u_long) ntohl(sav->spi),
737 		    skip + hlen + rlen + padding + alen, maxpacketsize));
738 		ESPSTAT_INC(esps_toobig);
739 		error = EMSGSIZE;
740 		goto bad;
741 	}
742 
743 	/* Update the counters. */
744 	ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
745 
746 	m = m_unshare(m, M_NOWAIT);
747 	if (m == NULL) {
748 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
749 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
750 		    (u_long) ntohl(sav->spi)));
751 		ESPSTAT_INC(esps_hdrops);
752 		error = ENOBUFS;
753 		goto bad;
754 	}
755 
756 	/* Inject ESP header. */
757 	mo = m_makespace(m, skip, hlen, &roff);
758 	if (mo == NULL) {
759 		DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
760 		    __func__, hlen, ipsec_address(&saidx->dst, buf,
761 		    sizeof(buf)), (u_long) ntohl(sav->spi)));
762 		ESPSTAT_INC(esps_hdrops);	/* XXX diffs from openbsd */
763 		error = ENOBUFS;
764 		goto bad;
765 	}
766 
767 	/* Initialize ESP header. */
768 	bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
769 	    sizeof(uint32_t));
770 	SECASVAR_LOCK(sav);
771 	if (sav->replay) {
772 		uint32_t replay;
773 
774 #ifdef REGRESSION
775 		/* Emulate replay attack when ipsec_replay is TRUE. */
776 		if (!V_ipsec_replay)
777 #endif
778 			sav->replay->count++;
779 		replay = htonl(sav->replay->count);
780 
781 		bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
782 		    sizeof(uint32_t), sizeof(uint32_t));
783 	}
784 	cryptoid = sav->tdb_cryptoid;
785 	if (SAV_ISCTRORGCM(sav))
786 		cntr = sav->cntr++;
787 	SECASVAR_UNLOCK(sav);
788 
789 	/*
790 	 * Add padding -- better to do it ourselves than use the crypto engine,
791 	 * although if/when we support compression, we'd have to do that.
792 	 */
793 	pad = (u_char *) m_pad(m, padding + alen);
794 	if (pad == NULL) {
795 		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
796 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
797 		    (u_long) ntohl(sav->spi)));
798 		m = NULL;		/* NB: free'd by m_pad */
799 		error = ENOBUFS;
800 		goto bad;
801 	}
802 
803 	/*
804 	 * Add padding: random, zero, or self-describing.
805 	 * XXX catch unexpected setting
806 	 */
807 	switch (sav->flags & SADB_X_EXT_PMASK) {
808 	case SADB_X_EXT_PRAND:
809 		arc4random_buf(pad, padding - 2);
810 		break;
811 	case SADB_X_EXT_PZERO:
812 		bzero(pad, padding - 2);
813 		break;
814 	case SADB_X_EXT_PSEQ:
815 		for (i = 0; i < padding - 2; i++)
816 			pad[i] = i+1;
817 		break;
818 	}
819 
820 	/* Fix padding length and Next Protocol in padding itself. */
821 	pad[padding - 2] = padding - 2;
822 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
823 
824 	/* Fix Next Protocol in IPv4/IPv6 header. */
825 	prot = IPPROTO_ESP;
826 	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
827 
828 	/* Get crypto descriptors. */
829 	crp = crypto_getreq(esph != NULL ? 2 : 1);
830 	if (crp == NULL) {
831 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
832 			__func__));
833 		ESPSTAT_INC(esps_crypto);
834 		error = ENOBUFS;
835 		goto bad;
836 	}
837 
838 	/* IPsec-specific opaque crypto info. */
839 	xd =  malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
840 	if (xd == NULL) {
841 		crypto_freereq(crp);
842 		DPRINTF(("%s: failed to allocate xform_data\n", __func__));
843 		ESPSTAT_INC(esps_crypto);
844 		error = ENOBUFS;
845 		goto bad;
846 	}
847 
848 	crde = crp->crp_desc;
849 	crda = crde->crd_next;
850 
851 	/* Encryption descriptor. */
852 	crde->crd_skip = skip + hlen;
853 	crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
854 	crde->crd_flags = CRD_F_ENCRYPT;
855 	crde->crd_inject = skip + hlen - sav->ivlen;
856 
857 	/* Encryption operation. */
858 	crde->crd_alg = espx->type;
859 	if (SAV_ISCTRORGCM(sav)) {
860 		ivp = &crde->crd_iv[0];
861 
862 		/* GCM IV Format: RFC4106 4 */
863 		/* CTR IV Format: RFC3686 4 */
864 		/* Salt is last four bytes of key, RFC4106 8.1 */
865 		/* Nonce is last four bytes of key, RFC3686 5.1 */
866 		memcpy(ivp, sav->key_enc->key_data +
867 		    _KEYLEN(sav->key_enc) - 4, 4);
868 		be64enc(&ivp[4], cntr);
869 		if (SAV_ISCTR(sav)) {
870 			/* Initial block counter is 1, RFC3686 4 */
871 			/* XXXAE: should we use this only for first packet? */
872 			be32enc(&ivp[sav->ivlen + 4], 1);
873 		}
874 
875 		m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
876 		crde->crd_flags |= CRD_F_IV_EXPLICIT|CRD_F_IV_PRESENT;
877 	}
878 
879 	/* Callback parameters */
880 	xd->sp = sp;
881 	xd->sav = sav;
882 	xd->idx = idx;
883 	xd->cryptoid = cryptoid;
884 	xd->vnet = curvnet;
885 
886 	/* Crypto operation descriptor. */
887 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
888 	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
889 	if (V_async_crypto)
890 		crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
891 	crp->crp_buf = (caddr_t) m;
892 	crp->crp_callback = esp_output_cb;
893 	crp->crp_opaque = (caddr_t) xd;
894 	crp->crp_session = cryptoid;
895 
896 	if (esph) {
897 		/* Authentication descriptor. */
898 		crda->crd_alg = esph->type;
899 		crda->crd_skip = skip;
900 		if (SAV_ISGCM(sav))
901 			crda->crd_len = 8;	/* RFC4106 5, SPI + SN */
902 		else
903 			crda->crd_len = m->m_pkthdr.len - (skip + alen);
904 		crda->crd_inject = m->m_pkthdr.len - alen;
905 	}
906 
907 	return crypto_dispatch(crp);
908 bad:
909 	if (m)
910 		m_freem(m);
911 	key_freesav(&sav);
912 	key_freesp(&sp);
913 	return (error);
914 }
915 /*
916  * ESP output callback from the crypto driver.
917  */
918 static int
919 esp_output_cb(struct cryptop *crp)
920 {
921 	struct xform_data *xd;
922 	struct secpolicy *sp;
923 	struct secasvar *sav;
924 	struct mbuf *m;
925 	crypto_session_t cryptoid;
926 	u_int idx;
927 	int error;
928 
929 	xd = (struct xform_data *) crp->crp_opaque;
930 	CURVNET_SET(xd->vnet);
931 	m = (struct mbuf *) crp->crp_buf;
932 	sp = xd->sp;
933 	sav = xd->sav;
934 	idx = xd->idx;
935 	cryptoid = xd->cryptoid;
936 
937 	/* Check for crypto errors. */
938 	if (crp->crp_etype) {
939 		if (crp->crp_etype == EAGAIN) {
940 			/* Reset the session ID */
941 			if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
942 				crypto_freesession(cryptoid);
943 			xd->cryptoid = crp->crp_session;
944 			CURVNET_RESTORE();
945 			return (crypto_dispatch(crp));
946 		}
947 		ESPSTAT_INC(esps_noxform);
948 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
949 		error = crp->crp_etype;
950 		m_freem(m);
951 		goto bad;
952 	}
953 
954 	/* Shouldn't happen... */
955 	if (m == NULL) {
956 		ESPSTAT_INC(esps_crypto);
957 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
958 		error = EINVAL;
959 		goto bad;
960 	}
961 	free(xd, M_XDATA);
962 	crypto_freereq(crp);
963 	ESPSTAT_INC(esps_hist[sav->alg_enc]);
964 	if (sav->tdb_authalgxform != NULL)
965 		AHSTAT_INC(ahs_hist[sav->alg_auth]);
966 
967 #ifdef REGRESSION
968 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
969 	if (V_ipsec_integrity) {
970 		static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
971 		const struct auth_hash *esph;
972 
973 		/*
974 		 * Corrupt HMAC if we want to test integrity verification of
975 		 * the other side.
976 		 */
977 		esph = sav->tdb_authalgxform;
978 		if (esph !=  NULL) {
979 			int alen;
980 
981 			alen = xform_ah_authsize(esph);
982 			m_copyback(m, m->m_pkthdr.len - alen,
983 			    alen, ipseczeroes);
984 		}
985 	}
986 #endif
987 
988 	/* NB: m is reclaimed by ipsec_process_done. */
989 	error = ipsec_process_done(m, sp, sav, idx);
990 	CURVNET_RESTORE();
991 	return (error);
992 bad:
993 	CURVNET_RESTORE();
994 	free(xd, M_XDATA);
995 	crypto_freereq(crp);
996 	key_freesav(&sav);
997 	key_freesp(&sp);
998 	return (error);
999 }
1000 
1001 static struct xformsw esp_xformsw = {
1002 	.xf_type =	XF_ESP,
1003 	.xf_name =	"IPsec ESP",
1004 	.xf_init =	esp_init,
1005 	.xf_zeroize =	esp_zeroize,
1006 	.xf_input =	esp_input,
1007 	.xf_output =	esp_output,
1008 };
1009 
1010 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1011     xform_attach, &esp_xformsw);
1012 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1013     xform_detach, &esp_xformsw);
1014