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