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