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