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