xref: /freebsd/sys/netipsec/xform_esp.c (revision 240c614d48cb0484bfe7876decdf6bbdcc99ba73)
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
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
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
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
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
492 esp_input_cb(struct cryptop *crp)
493 {
494 	IPSEC_DEBUG_DECLARE(char buf[128]);
495 	struct rm_priotracker sahtree_tracker;
496 	uint8_t lastthree[3];
497 	const struct auth_hash *esph;
498 	struct mbuf *m;
499 	struct xform_data *xd;
500 	struct secasvar *sav;
501 	struct secasindex *saidx;
502 	crypto_session_t cryptoid;
503 	int hlen, skip, protoff, error, alen;
504 
505 	SECASVAR_RLOCK_TRACKER;
506 
507 	m = crp->crp_buf.cb_mbuf;
508 	xd = crp->crp_opaque;
509 	CURVNET_SET(xd->vnet);
510 	sav = xd->sav;
511 	ipsec_sahtree_rlock(&sahtree_tracker);
512 	if (sav->state >= SADB_SASTATE_DEAD) {
513 		/* saidx is freed */
514 		DPRINTF(("%s: dead SA %p spi %#x\n", __func__, sav, sav->spi));
515 		ESPSTAT_INC(esps_notdb);
516 		error = ESRCH;
517 		goto bad;
518 	}
519 	skip = xd->skip;
520 	protoff = xd->protoff;
521 	cryptoid = xd->cryptoid;
522 	saidx = &sav->sah->saidx;
523 	esph = sav->tdb_authalgxform;
524 
525 	/* Check for crypto errors */
526 	if (crp->crp_etype) {
527 		if (crp->crp_etype == EAGAIN) {
528 			/* Reset the session ID */
529 			if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
530 				crypto_freesession(cryptoid);
531 			xd->cryptoid = crp->crp_session;
532 			ipsec_sahtree_runlock(&sahtree_tracker);
533 			CURVNET_RESTORE();
534 			return (crypto_dispatch(crp));
535 		}
536 
537 		/* EBADMSG indicates authentication failure. */
538 		if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
539 			ESPSTAT_INC(esps_noxform);
540 			DPRINTF(("%s: crypto error %d\n", __func__,
541 				crp->crp_etype));
542 			error = crp->crp_etype;
543 			goto bad;
544 		}
545 	}
546 
547 	/* Shouldn't happen... */
548 	if (m == NULL) {
549 		ESPSTAT_INC(esps_crypto);
550 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
551 		error = EINVAL;
552 		goto bad;
553 	}
554 	ESPSTAT_INC2(esps_hist, sav->alg_enc);
555 
556 	/* If authentication was performed, check now. */
557 	if (esph != NULL) {
558 		alen = xform_ah_authsize(esph);
559 		AHSTAT_INC2(ahs_hist, sav->alg_auth);
560 		if (crp->crp_etype == EBADMSG) {
561 			DPRINTF(("%s: authentication hash mismatch for "
562 			    "packet in SA %s/%08lx\n", __func__,
563 			    ipsec_address(&saidx->dst, buf, sizeof(buf)),
564 			    (u_long) ntohl(sav->spi)));
565 			ESPSTAT_INC(esps_badauth);
566 			error = EACCES;
567 			goto bad;
568 		}
569 		m->m_flags |= M_AUTHIPDGM;
570 		/* Remove trailing authenticator */
571 		m_adj(m, -alen);
572 	}
573 
574 	/* Release the crypto descriptors */
575 	free(xd, M_ESP), xd = NULL;
576 	free(crp->crp_aad, M_ESP), crp->crp_aad = NULL;
577 	crypto_freereq(crp), crp = NULL;
578 
579 	/*
580 	 * Packet is now decrypted.
581 	 */
582 	m->m_flags |= M_DECRYPTED;
583 
584 	/*
585 	 * Update replay sequence number, if appropriate.
586 	 */
587 	if (sav->replay) {
588 		u_int32_t seq;
589 
590 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
591 			   sizeof (seq), (caddr_t) &seq);
592 		SECASVAR_RLOCK(sav);
593 		if (ipsec_updatereplay(ntohl(seq), sav)) {
594 			SECASVAR_RUNLOCK(sav);
595 			DPRINTF(("%s: packet replay check for %s\n", __func__,
596 			    ipsec_sa2str(sav, buf, sizeof(buf))));
597 			ESPSTAT_INC(esps_replay);
598 			error = EACCES;
599 			goto bad;
600 		}
601 		SECASVAR_RUNLOCK(sav);
602 	}
603 
604 	/* Determine the ESP header length */
605 	if (sav->flags & SADB_X_EXT_OLD)
606 		hlen = sizeof (struct esp) + sav->ivlen;
607 	else
608 		hlen = sizeof (struct newesp) + sav->ivlen;
609 
610 	/* Remove the ESP header and IV from the mbuf. */
611 	error = m_striphdr(m, skip, hlen);
612 	if (error) {
613 		ESPSTAT_INC(esps_hdrops);
614 		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
615 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
616 		    (u_long) ntohl(sav->spi)));
617 		goto bad;
618 	}
619 
620 	/* Save the last three bytes of decrypted data */
621 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
622 
623 	/* Verify pad length */
624 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
625 		ESPSTAT_INC(esps_badilen);
626 		DPRINTF(("%s: invalid padding length %d for %u byte packet "
627 		    "in SA %s/%08lx\n", __func__, lastthree[1],
628 		    m->m_pkthdr.len - skip,
629 		    ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
630 		    (u_long) ntohl(sav->spi)));
631 		error = EINVAL;
632 		goto bad;
633 	}
634 
635 	/* Verify correct decryption by checking the last padding bytes */
636 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
637 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
638 			ESPSTAT_INC(esps_badenc);
639 			DPRINTF(("%s: decryption failed for packet in "
640 			    "SA %s/%08lx\n", __func__, ipsec_address(
641 			    &sav->sah->saidx.dst, buf, sizeof(buf)),
642 			    (u_long) ntohl(sav->spi)));
643 			error = EINVAL;
644 			goto bad;
645 		}
646 	}
647 
648 	/*
649 	 * RFC4303 2.6:
650 	 * Silently drop packet if next header field is IPPROTO_NONE.
651 	 */
652 	if (lastthree[2] == IPPROTO_NONE)
653 		goto bad;
654 
655 	/* Trim the mbuf chain to remove trailing authenticator and padding */
656 	m_adj(m, -(lastthree[1] + 2));
657 
658 	/* Restore the Next Protocol field */
659 	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
660 
661 	switch (saidx->dst.sa.sa_family) {
662 #ifdef INET6
663 	case AF_INET6:
664 		error = ipsec6_common_input_cb(m, sav, skip, protoff,
665 		    &sahtree_tracker);
666 		break;
667 #endif
668 #ifdef INET
669 	case AF_INET:
670 		error = ipsec4_common_input_cb(m, sav, skip, protoff,
671 		    &sahtree_tracker);
672 		break;
673 #endif
674 	default:
675 		panic("%s: Unexpected address family: %d saidx=%p", __func__,
676 		    saidx->dst.sa.sa_family, saidx);
677 	}
678 	CURVNET_RESTORE();
679 	return error;
680 bad:
681 	ipsec_sahtree_runlock(&sahtree_tracker);
682 	if (sav != NULL)
683 		key_freesav(&sav);
684 	if (m != NULL)
685 		m_freem(m);
686 	if (xd != NULL)
687 		free(xd, M_ESP);
688 	if (crp != NULL) {
689 		free(crp->crp_aad, M_ESP);
690 		crypto_freereq(crp);
691 	}
692 	CURVNET_RESTORE();
693 	return error;
694 }
695 /*
696  * ESP output routine, called by ipsec[46]_perform_request().
697  */
698 static int
699 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
700     u_int idx, int skip, int protoff)
701 {
702 	IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
703 	struct cryptop *crp;
704 	const struct auth_hash *esph;
705 	const struct enc_xform *espx;
706 	struct mbuf *mo = NULL;
707 	struct xform_data *xd;
708 	struct secasindex *saidx;
709 	unsigned char *pad;
710 	uint8_t *ivp;
711 	uint64_t cntr;
712 	crypto_session_t cryptoid;
713 	int hlen, rlen, padding, blks, alen, i, roff;
714 	int error, maxpacketsize;
715 	uint8_t prot;
716 	uint32_t seqh;
717 	const struct crypto_session_params *csp;
718 
719 	SECASVAR_RLOCK_TRACKER;
720 
721 	IPSEC_ASSERT(sav != NULL, ("null SA"));
722 	esph = sav->tdb_authalgxform;
723 	espx = sav->tdb_encalgxform;
724 	IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
725 
726 	if (sav->flags & SADB_X_EXT_OLD)
727 		hlen = sizeof (struct esp) + sav->ivlen;
728 	else
729 		hlen = sizeof (struct newesp) + sav->ivlen;
730 
731 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
732 	/*
733 	 * RFC4303 2.4 Requires 4 byte alignment.
734 	 * Old versions of FreeBSD can't decrypt partial blocks encrypted
735 	 * with AES-CTR. Align payload to native_blocksize (16 bytes)
736 	 * in order to preserve compatibility.
737 	 */
738 	if (SAV_ISCTR(sav) && V_esp_ctr_compatibility)
739 		blks = MAX(4, espx->native_blocksize);	/* Cipher blocksize */
740 	else
741 		blks = MAX(4, espx->blocksize);
742 
743 	/* XXX clamp padding length a la KAME??? */
744 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
745 
746 	alen = xform_ah_authsize(esph);
747 
748 	ESPSTAT_INC(esps_output);
749 
750 	saidx = &sav->sah->saidx;
751 	/* Check for maximum packet size violations. */
752 	switch (saidx->dst.sa.sa_family) {
753 #ifdef INET
754 	case AF_INET:
755 		maxpacketsize = IP_MAXPACKET;
756 		break;
757 #endif /* INET */
758 #ifdef INET6
759 	case AF_INET6:
760 		maxpacketsize = IPV6_MAXPACKET;
761 		break;
762 #endif /* INET6 */
763 	default:
764 		DPRINTF(("%s: unknown/unsupported protocol "
765 		    "family %d, SA %s/%08lx\n", __func__,
766 		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
767 			buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
768 		ESPSTAT_INC(esps_nopf);
769 		error = EPFNOSUPPORT;
770 		goto bad;
771 	}
772 	/*
773 	DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
774 		__func__, skip, hlen, rlen, padding, alen, blks)); */
775 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
776 		DPRINTF(("%s: packet in SA %s/%08lx got too big "
777 		    "(len %u, max len %u)\n", __func__,
778 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
779 		    (u_long) ntohl(sav->spi),
780 		    skip + hlen + rlen + padding + alen, maxpacketsize));
781 		ESPSTAT_INC(esps_toobig);
782 		error = EMSGSIZE;
783 		goto bad;
784 	}
785 
786 	/* Update the counters. */
787 	ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
788 
789 	m = m_unshare(m, M_NOWAIT);
790 	if (m == NULL) {
791 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
792 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
793 		    (u_long) ntohl(sav->spi)));
794 		ESPSTAT_INC(esps_hdrops);
795 		error = ENOBUFS;
796 		goto bad;
797 	}
798 
799 	/* Inject ESP header. */
800 	mo = m_makespace(m, skip, hlen, &roff);
801 	if (mo == NULL) {
802 		DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
803 		    __func__, hlen, ipsec_address(&saidx->dst, buf,
804 		    sizeof(buf)), (u_long) ntohl(sav->spi)));
805 		ESPSTAT_INC(esps_hdrops);	/* XXX diffs from openbsd */
806 		error = ENOBUFS;
807 		goto bad;
808 	}
809 
810 	/* Initialize ESP header. */
811 	bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
812 	    sizeof(uint32_t));
813 	SECASVAR_RLOCK(sav);
814 	if (sav->replay) {
815 		uint32_t replay;
816 
817 		SECREPLAY_LOCK(sav->replay);
818 #ifdef REGRESSION
819 		/* Emulate replay attack when ipsec_replay is TRUE. */
820 		if (!V_ipsec_replay)
821 #endif
822 			sav->replay->count++;
823 		replay = htonl((uint32_t)sav->replay->count);
824 
825 		bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
826 		    sizeof(uint32_t), sizeof(uint32_t));
827 
828 		seqh = htonl((uint32_t)(sav->replay->count >> IPSEC_SEQH_SHIFT));
829 		SECREPLAY_UNLOCK(sav->replay);
830 	}
831 	cryptoid = sav->tdb_cryptoid;
832 	if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav))
833 		cntr = sav->cntr++;
834 	SECASVAR_RUNLOCK(sav);
835 
836 	/*
837 	 * Add padding -- better to do it ourselves than use the crypto engine,
838 	 * although if/when we support compression, we'd have to do that.
839 	 */
840 	pad = (u_char *) m_pad(m, padding + alen);
841 	if (pad == NULL) {
842 		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
843 		    ipsec_address(&saidx->dst, buf, sizeof(buf)),
844 		    (u_long) ntohl(sav->spi)));
845 		m = NULL;		/* NB: free'd by m_pad */
846 		error = ENOBUFS;
847 		goto bad;
848 	}
849 
850 	/*
851 	 * Add padding: random, zero, or self-describing.
852 	 * XXX catch unexpected setting
853 	 */
854 	switch (sav->flags & SADB_X_EXT_PMASK) {
855 	case SADB_X_EXT_PRAND:
856 		arc4random_buf(pad, padding - 2);
857 		break;
858 	case SADB_X_EXT_PZERO:
859 		bzero(pad, padding - 2);
860 		break;
861 	case SADB_X_EXT_PSEQ:
862 		for (i = 0; i < padding - 2; i++)
863 			pad[i] = i+1;
864 		break;
865 	}
866 
867 	/* Fix padding length and Next Protocol in padding itself. */
868 	pad[padding - 2] = padding - 2;
869 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
870 
871 	/* Fix Next Protocol in IPv4/IPv6 header. */
872 	prot = IPPROTO_ESP;
873 	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
874 
875 	/* Get crypto descriptor. */
876 	crp = crypto_getreq(cryptoid, M_NOWAIT);
877 	if (crp == NULL) {
878 		DPRINTF(("%s: failed to acquire crypto descriptor\n",
879 			__func__));
880 		ESPSTAT_INC(esps_crypto);
881 		error = ENOBUFS;
882 		goto bad;
883 	}
884 
885 	/* IPsec-specific opaque crypto info. */
886 	xd = malloc(sizeof(struct xform_data), M_ESP, M_NOWAIT | M_ZERO);
887 	if (xd == NULL) {
888 		DPRINTF(("%s: failed to allocate xform_data\n", __func__));
889 		goto xd_fail;
890 	}
891 
892 	/* Encryption descriptor. */
893 	crp->crp_payload_start = skip + hlen;
894 	crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
895 	crp->crp_op = CRYPTO_OP_ENCRYPT;
896 
897 	/* Generate cipher and ESP IVs. */
898 	ivp = &crp->crp_iv[0];
899 	if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav)) {
900 		/*
901 		 * See comment in esp_input() for details on the
902 		 * cipher IV.  A simple per-SA counter stored in
903 		 * 'cntr' is used as the explicit ESP IV.
904 		 */
905 		memcpy(ivp, sav->key_enc->key_data +
906 		    _KEYLEN(sav->key_enc) - 4, 4);
907 		be64enc(&ivp[4], cntr);
908 		if (SAV_ISCTR(sav)) {
909 			be32enc(&ivp[sav->ivlen + 4], 1);
910 		}
911 		m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
912 		crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
913 	} else if (sav->ivlen != 0) {
914 		arc4rand(ivp, sav->ivlen, 0);
915 		crp->crp_iv_start = skip + hlen - sav->ivlen;
916 		m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
917 	}
918 
919 	/* Callback parameters */
920 	xd->sp = sp;
921 	xd->sav = sav;
922 	xd->idx = idx;
923 	xd->cryptoid = cryptoid;
924 	xd->vnet = curvnet;
925 
926 	/* Crypto operation descriptor. */
927 	crp->crp_flags |= CRYPTO_F_CBIFSYNC;
928 	crypto_use_mbuf(crp, m);
929 	crp->crp_callback = esp_output_cb;
930 	crp->crp_opaque = xd;
931 
932 	if (esph) {
933 		/* Authentication descriptor. */
934 		crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
935 		if (SAV_ISGCM(sav) || SAV_ISCHACHA(sav))
936 			crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
937 		else
938 			crp->crp_aad_length = hlen;
939 
940 		csp = crypto_get_params(crp->crp_session);
941 		if (csp->csp_flags & CSP_F_SEPARATE_AAD &&
942 		    sav->replay != NULL) {
943 			int aad_skip;
944 
945 			crp->crp_aad_length += sizeof(seqh);
946 			crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
947 			if (crp->crp_aad == NULL) {
948 				DPRINTF(("%s: failed to allocate xform_data\n",
949 					 __func__));
950 				goto crp_aad_fail;
951 			}
952 
953 			/* SPI */
954 			m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
955 			aad_skip = SPI_SIZE;
956 
957 			/* ESN */
958 			bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
959 			aad_skip += sizeof(seqh);
960 
961 			/* Rest of aad */
962 			if (crp->crp_aad_length - aad_skip > 0)
963 				m_copydata(m, skip + SPI_SIZE,
964 					   crp->crp_aad_length - aad_skip,
965 					   (char *)crp->crp_aad + aad_skip);
966 		} else
967 			crp->crp_aad_start = skip;
968 
969 		if (csp->csp_flags & CSP_F_ESN && sav->replay != NULL)
970 			memcpy(crp->crp_esn, &seqh, sizeof(seqh));
971 
972 		crp->crp_digest_start = m->m_pkthdr.len - alen;
973 	}
974 
975 	if (V_async_crypto)
976 		return (crypto_dispatch_async(crp, CRYPTO_ASYNC_ORDERED));
977 	else
978 		return (crypto_dispatch(crp));
979 
980 crp_aad_fail:
981 	free(xd, M_ESP);
982 xd_fail:
983 	crypto_freereq(crp);
984 	ESPSTAT_INC(esps_crypto);
985 	error = ENOBUFS;
986 bad:
987 	if (m)
988 		m_freem(m);
989 	key_freesav(&sav);
990 	key_freesp(&sp);
991 	return (error);
992 }
993 /*
994  * ESP output callback from the crypto driver.
995  */
996 static int
997 esp_output_cb(struct cryptop *crp)
998 {
999 	struct xform_data *xd;
1000 	struct secpolicy *sp;
1001 	struct secasvar *sav;
1002 	struct mbuf *m;
1003 	crypto_session_t cryptoid;
1004 	u_int idx;
1005 	int error;
1006 
1007 	xd = (struct xform_data *) crp->crp_opaque;
1008 	CURVNET_SET(xd->vnet);
1009 	m = crp->crp_buf.cb_mbuf;
1010 	sp = xd->sp;
1011 	sav = xd->sav;
1012 	idx = xd->idx;
1013 	cryptoid = xd->cryptoid;
1014 
1015 	/* Check for crypto errors. */
1016 	if (crp->crp_etype) {
1017 		if (crp->crp_etype == EAGAIN) {
1018 			/* Reset the session ID */
1019 			if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
1020 				crypto_freesession(cryptoid);
1021 			xd->cryptoid = crp->crp_session;
1022 			CURVNET_RESTORE();
1023 			return (crypto_dispatch(crp));
1024 		}
1025 		ESPSTAT_INC(esps_noxform);
1026 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
1027 		error = crp->crp_etype;
1028 		m_freem(m);
1029 		goto bad;
1030 	}
1031 
1032 	/* Shouldn't happen... */
1033 	if (m == NULL) {
1034 		ESPSTAT_INC(esps_crypto);
1035 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
1036 		error = EINVAL;
1037 		goto bad;
1038 	}
1039 	free(xd, M_ESP);
1040 	free(crp->crp_aad, M_ESP);
1041 	crypto_freereq(crp);
1042 	ESPSTAT_INC2(esps_hist, sav->alg_enc);
1043 	if (sav->tdb_authalgxform != NULL)
1044 		AHSTAT_INC2(ahs_hist, sav->alg_auth);
1045 
1046 #ifdef REGRESSION
1047 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
1048 	if (V_ipsec_integrity) {
1049 		static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
1050 		const struct auth_hash *esph;
1051 
1052 		/*
1053 		 * Corrupt HMAC if we want to test integrity verification of
1054 		 * the other side.
1055 		 */
1056 		esph = sav->tdb_authalgxform;
1057 		if (esph !=  NULL) {
1058 			int alen;
1059 
1060 			alen = xform_ah_authsize(esph);
1061 			m_copyback(m, m->m_pkthdr.len - alen,
1062 			    alen, ipseczeroes);
1063 		}
1064 	}
1065 #endif
1066 
1067 	/* NB: m is reclaimed by ipsec_process_done. */
1068 	error = ipsec_process_done(m, sp, sav, idx);
1069 	CURVNET_RESTORE();
1070 	return (error);
1071 bad:
1072 	free(xd, M_ESP);
1073 	free(crp->crp_aad, M_ESP);
1074 	crypto_freereq(crp);
1075 	key_freesav(&sav);
1076 	key_freesp(&sp);
1077 	CURVNET_RESTORE();
1078 	return (error);
1079 }
1080 
1081 static struct xformsw esp_xformsw = {
1082 	.xf_type =	XF_ESP,
1083 	.xf_name =	"IPsec ESP",
1084 	.xf_init =	esp_init,
1085 	.xf_cleanup =	esp_cleanup,
1086 	.xf_input =	esp_input,
1087 	.xf_output =	esp_output,
1088 };
1089 
1090 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1091     xform_attach, &esp_xformsw);
1092 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1093     xform_detach, &esp_xformsw);
1094