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