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