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