xref: /openbsd/sys/netinet/ip_esp.c (revision eebf22aa)
1 /*	$OpenBSD: ip_esp.c,v 1.185 2021/11/04 14:45:07 tobhe 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 
38 #include "pfsync.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/mbuf.h>
43 #include <sys/socket.h>
44 
45 #include <net/if.h>
46 #include <net/if_var.h>
47 #include <net/bpf.h>
48 
49 #include <netinet/in.h>
50 #include <netinet/ip.h>
51 #include <netinet/ip_var.h>
52 
53 #ifdef INET6
54 #include <netinet/ip6.h>
55 #endif /* INET6 */
56 
57 #include <netinet/ip_ipsp.h>
58 #include <netinet/ip_esp.h>
59 #include <net/pfkeyv2.h>
60 #include <net/if_enc.h>
61 
62 #if NPFSYNC > 0
63 #include <net/pfvar.h>
64 #include <net/if_pfsync.h>
65 #endif /* NPFSYNC > 0 */
66 
67 #include <crypto/cryptodev.h>
68 #include <crypto/xform.h>
69 
70 #include "bpfilter.h"
71 
72 #ifdef ENCDEBUG
73 #define DPRINTF(fmt, args...)						\
74 	do {								\
75 		if (encdebug)						\
76 			printf("%s: " fmt "\n", __func__, ## args);	\
77 	} while (0)
78 #else
79 #define DPRINTF(fmt, args...)						\
80 	do { } while (0)
81 #endif
82 
83 /*
84  * esp_attach() is called from the transformation initialization code.
85  */
86 int
87 esp_attach(void)
88 {
89 	return 0;
90 }
91 
92 /*
93  * esp_init() is called when an SPI is being set up.
94  */
95 int
96 esp_init(struct tdb *tdbp, const struct xformsw *xsp, struct ipsecinit *ii)
97 {
98 	const struct enc_xform *txform = NULL;
99 	const struct auth_hash *thash = NULL;
100 	struct cryptoini cria, crie, crin;
101 	int error;
102 
103 	if (!ii->ii_encalg && !ii->ii_authalg) {
104 		DPRINTF("neither authentication nor encryption algorithm "
105 		    "given");
106 		return EINVAL;
107 	}
108 
109 	if (ii->ii_encalg) {
110 		switch (ii->ii_encalg) {
111 		case SADB_EALG_NULL:
112 			txform = &enc_xform_null;
113 			break;
114 
115 		case SADB_EALG_3DESCBC:
116 			txform = &enc_xform_3des;
117 			break;
118 
119 		case SADB_X_EALG_AES:
120 			txform = &enc_xform_aes;
121 			break;
122 
123 		case SADB_X_EALG_AESCTR:
124 			txform = &enc_xform_aes_ctr;
125 			break;
126 
127 		case SADB_X_EALG_AESGCM16:
128 			txform = &enc_xform_aes_gcm;
129 			break;
130 
131 		case SADB_X_EALG_AESGMAC:
132 			txform = &enc_xform_aes_gmac;
133 			break;
134 
135 		case SADB_X_EALG_CHACHA20POLY1305:
136 			txform = &enc_xform_chacha20_poly1305;
137 			break;
138 
139 		case SADB_X_EALG_BLF:
140 			txform = &enc_xform_blf;
141 			break;
142 
143 		case SADB_X_EALG_CAST:
144 			txform = &enc_xform_cast5;
145 			break;
146 
147 		default:
148 			DPRINTF("unsupported encryption algorithm %d "
149 			    "specified",
150 			    ii->ii_encalg);
151 			return EINVAL;
152 		}
153 
154 		if (ii->ii_enckeylen < txform->minkey) {
155 			DPRINTF("keylength %d too small (min length is %d) "
156 			    "for algorithm %s",
157 			    ii->ii_enckeylen, txform->minkey, txform->name);
158 			return EINVAL;
159 		}
160 
161 		if (ii->ii_enckeylen > txform->maxkey) {
162 			DPRINTF("keylength %d too large (max length is %d) "
163 			    "for algorithm %s",
164 			    ii->ii_enckeylen, txform->maxkey, txform->name);
165 			return EINVAL;
166 		}
167 
168 		if (ii->ii_encalg == SADB_X_EALG_AESGCM16 ||
169 		    ii->ii_encalg == SADB_X_EALG_AESGMAC) {
170 			switch (ii->ii_enckeylen) {
171 			case 20:
172 				ii->ii_authalg = SADB_X_AALG_AES128GMAC;
173 				break;
174 			case 28:
175 				ii->ii_authalg = SADB_X_AALG_AES192GMAC;
176 				break;
177 			case 36:
178 				ii->ii_authalg = SADB_X_AALG_AES256GMAC;
179 				break;
180 			}
181 			ii->ii_authkeylen = ii->ii_enckeylen;
182 			ii->ii_authkey = ii->ii_enckey;
183 		} else if (ii->ii_encalg == SADB_X_EALG_CHACHA20POLY1305) {
184 			ii->ii_authalg = SADB_X_AALG_CHACHA20POLY1305;
185 			ii->ii_authkeylen = ii->ii_enckeylen;
186 			ii->ii_authkey = ii->ii_enckey;
187 		}
188 
189 		tdbp->tdb_encalgxform = txform;
190 
191 		DPRINTF("initialized TDB with enc algorithm %s", txform->name);
192 
193 		tdbp->tdb_ivlen = txform->ivsize;
194 	}
195 
196 	if (ii->ii_authalg) {
197 		switch (ii->ii_authalg) {
198 		case SADB_AALG_MD5HMAC:
199 			thash = &auth_hash_hmac_md5_96;
200 			break;
201 
202 		case SADB_AALG_SHA1HMAC:
203 			thash = &auth_hash_hmac_sha1_96;
204 			break;
205 
206 		case SADB_X_AALG_RIPEMD160HMAC:
207 			thash = &auth_hash_hmac_ripemd_160_96;
208 			break;
209 
210 		case SADB_X_AALG_SHA2_256:
211 			thash = &auth_hash_hmac_sha2_256_128;
212 			break;
213 
214 		case SADB_X_AALG_SHA2_384:
215 			thash = &auth_hash_hmac_sha2_384_192;
216 			break;
217 
218 		case SADB_X_AALG_SHA2_512:
219 			thash = &auth_hash_hmac_sha2_512_256;
220 			break;
221 
222 		case SADB_X_AALG_AES128GMAC:
223 			thash = &auth_hash_gmac_aes_128;
224 			break;
225 
226 		case SADB_X_AALG_AES192GMAC:
227 			thash = &auth_hash_gmac_aes_192;
228 			break;
229 
230 		case SADB_X_AALG_AES256GMAC:
231 			thash = &auth_hash_gmac_aes_256;
232 			break;
233 
234 		case SADB_X_AALG_CHACHA20POLY1305:
235 			thash = &auth_hash_chacha20_poly1305;
236 			break;
237 
238 		default:
239 			DPRINTF("unsupported authentication algorithm %d "
240 			    "specified",
241 			    ii->ii_authalg);
242 			return EINVAL;
243 		}
244 
245 		if (ii->ii_authkeylen != thash->keysize) {
246 			DPRINTF("keylength %d doesn't match algorithm %s "
247 			    "keysize (%d)",
248 			    ii->ii_authkeylen, thash->name, thash->keysize);
249 			return EINVAL;
250 		}
251 
252 		tdbp->tdb_authalgxform = thash;
253 
254 		DPRINTF("initialized TDB with hash algorithm %s", thash->name);
255 	}
256 
257 	tdbp->tdb_xform = xsp;
258 	tdbp->tdb_rpl = AH_HMAC_INITIAL_RPL;
259 
260 	/* Initialize crypto session */
261 	if (tdbp->tdb_encalgxform) {
262 		/* Save the raw keys */
263 		tdbp->tdb_emxkeylen = ii->ii_enckeylen;
264 		tdbp->tdb_emxkey = malloc(tdbp->tdb_emxkeylen, M_XDATA,
265 		    M_WAITOK);
266 		memcpy(tdbp->tdb_emxkey, ii->ii_enckey, tdbp->tdb_emxkeylen);
267 
268 		memset(&crie, 0, sizeof(crie));
269 
270 		crie.cri_alg = tdbp->tdb_encalgxform->type;
271 
272 		if (tdbp->tdb_authalgxform)
273 			crie.cri_next = &cria;
274 		else
275 			crie.cri_next = NULL;
276 
277 		crie.cri_klen = ii->ii_enckeylen * 8;
278 		crie.cri_key = ii->ii_enckey;
279 		/* XXX Rounds ? */
280 	}
281 
282 	if (tdbp->tdb_authalgxform) {
283 		/* Save the raw keys */
284 		tdbp->tdb_amxkeylen = ii->ii_authkeylen;
285 		tdbp->tdb_amxkey = malloc(tdbp->tdb_amxkeylen, M_XDATA,
286 		    M_WAITOK);
287 		memcpy(tdbp->tdb_amxkey, ii->ii_authkey, tdbp->tdb_amxkeylen);
288 
289 		memset(&cria, 0, sizeof(cria));
290 
291 		cria.cri_alg = tdbp->tdb_authalgxform->type;
292 
293 		if ((tdbp->tdb_wnd > 0) && (tdbp->tdb_flags & TDBF_ESN)) {
294 			memset(&crin, 0, sizeof(crin));
295 			crin.cri_alg = CRYPTO_ESN;
296 			cria.cri_next = &crin;
297 		}
298 
299 		cria.cri_klen = ii->ii_authkeylen * 8;
300 		cria.cri_key = ii->ii_authkey;
301 	}
302 
303 	KERNEL_LOCK();
304 	error = crypto_newsession(&tdbp->tdb_cryptoid,
305 	    (tdbp->tdb_encalgxform ? &crie : &cria), 0);
306 	KERNEL_UNLOCK();
307 	return error;
308 }
309 
310 /*
311  * Paranoia.
312  */
313 int
314 esp_zeroize(struct tdb *tdbp)
315 {
316 	int error;
317 
318 	if (tdbp->tdb_amxkey) {
319 		explicit_bzero(tdbp->tdb_amxkey, tdbp->tdb_amxkeylen);
320 		free(tdbp->tdb_amxkey, M_XDATA, tdbp->tdb_amxkeylen);
321 		tdbp->tdb_amxkey = NULL;
322 	}
323 
324 	if (tdbp->tdb_emxkey) {
325 		explicit_bzero(tdbp->tdb_emxkey, tdbp->tdb_emxkeylen);
326 		free(tdbp->tdb_emxkey, M_XDATA, tdbp->tdb_emxkeylen);
327 		tdbp->tdb_emxkey = NULL;
328 	}
329 
330 	KERNEL_LOCK();
331 	error = crypto_freesession(tdbp->tdb_cryptoid);
332 	KERNEL_UNLOCK();
333 	tdbp->tdb_cryptoid = 0;
334 	return error;
335 }
336 
337 #define MAXBUFSIZ (AH_ALEN_MAX > ESP_MAX_IVS ? AH_ALEN_MAX : ESP_MAX_IVS)
338 
339 /*
340  * ESP input processing, called (eventually) through the protocol switch.
341  */
342 int
343 esp_input(struct mbuf **mp, struct tdb *tdb, int skip, int protoff)
344 {
345 	const struct auth_hash *esph = tdb->tdb_authalgxform;
346 	const struct enc_xform *espx = tdb->tdb_encalgxform;
347 	struct mbuf *m = *mp, *m1, *mo;
348 	struct cryptodesc *crde = NULL, *crda = NULL;
349 	struct cryptop *crp = NULL;
350 	int plen, alen, hlen, error, clen, roff;
351 	uint32_t btsx, esn;
352 #ifdef ENCDEBUG
353 	char buf[INET6_ADDRSTRLEN];
354 #endif
355 	uint8_t abuf[AH_HMAC_MAX_HASHLEN];
356 	uint8_t lastthree[3], aalg[AH_HMAC_MAX_HASHLEN];
357 
358 	/* Determine the ESP header length */
359 	hlen = 2 * sizeof(u_int32_t) + tdb->tdb_ivlen; /* "new" ESP */
360 	alen = esph ? esph->authsize : 0;
361 	plen = m->m_pkthdr.len - (skip + hlen + alen);
362 	if (plen <= 0) {
363 		DPRINTF("invalid payload length");
364 		espstat_inc(esps_badilen);
365 		error = EINVAL;
366 		goto drop;
367 	}
368 
369 	if (espx) {
370 		/*
371 		 * Verify payload length is multiple of encryption algorithm
372 		 * block size.
373 		 */
374 		if (plen & (espx->blocksize - 1)) {
375 			DPRINTF("payload of %d octets not a multiple "
376 			    "of %d octets, SA %s/%08x",
377 			    plen, espx->blocksize,
378 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
379 			    ntohl(tdb->tdb_spi));
380 			espstat_inc(esps_badilen);
381 			error = EINVAL;
382 			goto drop;
383 		}
384 	}
385 
386 	/* Replay window checking, if appropriate -- no value commitment. */
387 	if (tdb->tdb_wnd > 0) {
388 		m_copydata(m, skip + sizeof(u_int32_t), sizeof(u_int32_t),
389 		    &btsx);
390 		btsx = ntohl(btsx);
391 
392 		switch (checkreplaywindow(tdb, tdb->tdb_rpl, btsx, &esn, 0)) {
393 		case 0: /* All's well */
394 			break;
395 		case 1:
396 			DPRINTF("replay counter wrapped for SA %s/%08x",
397 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
398 			    ntohl(tdb->tdb_spi));
399 			espstat_inc(esps_wrap);
400 			error = EACCES;
401 			goto drop;
402 		case 2:
403 			DPRINTF("old packet received in SA %s/%08x",
404 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
405 			    ntohl(tdb->tdb_spi));
406 			espstat_inc(esps_replay);
407 			error = EACCES;
408 			goto drop;
409 		case 3:
410 			DPRINTF("duplicate packet received in SA %s/%08x",
411 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
412 			    ntohl(tdb->tdb_spi));
413 			espstat_inc(esps_replay);
414 			error = EACCES;
415 			goto drop;
416 		default:
417 			DPRINTF("bogus value from checkreplaywindow() "
418 			    "in SA %s/%08x",
419 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
420 			    ntohl(tdb->tdb_spi));
421 			espstat_inc(esps_replay);
422 			error = EACCES;
423 			goto drop;
424 		}
425 	}
426 
427 	/* Update the counters */
428 	tdb->tdb_cur_bytes += plen;
429 	tdb->tdb_ibytes += plen;
430 	espstat_add(esps_ibytes, plen);
431 
432 	/* Hard expiration */
433 	if ((tdb->tdb_flags & TDBF_BYTES) &&
434 	    (tdb->tdb_cur_bytes >= tdb->tdb_exp_bytes))	{
435 		pfkeyv2_expire(tdb, SADB_EXT_LIFETIME_HARD);
436 		tdb_delete(tdb);
437 		error = ENXIO;
438 		goto drop;
439 	}
440 
441 	/* Notify on soft expiration */
442 	if ((tdb->tdb_flags & TDBF_SOFT_BYTES) &&
443 	    (tdb->tdb_cur_bytes >= tdb->tdb_soft_bytes)) {
444 		pfkeyv2_expire(tdb, SADB_EXT_LIFETIME_SOFT);
445 		tdb->tdb_flags &= ~TDBF_SOFT_BYTES;       /* Turn off checking */
446 	}
447 
448 	/* Get crypto descriptors */
449 	crp = crypto_getreq(esph && espx ? 2 : 1);
450 	if (crp == NULL) {
451 		DPRINTF("failed to acquire crypto descriptors");
452 		espstat_inc(esps_crypto);
453 		error = ENOBUFS;
454 		goto drop;
455 	}
456 
457 	if (esph) {
458 		crda = &crp->crp_desc[0];
459 		crde = &crp->crp_desc[1];
460 
461 		/* Authentication descriptor */
462 		crda->crd_skip = skip;
463 		crda->crd_inject = m->m_pkthdr.len - alen;
464 
465 		crda->crd_alg = esph->type;
466 		crda->crd_key = tdb->tdb_amxkey;
467 		crda->crd_klen = tdb->tdb_amxkeylen * 8;
468 
469 		if ((tdb->tdb_wnd > 0) && (tdb->tdb_flags & TDBF_ESN)) {
470 			esn = htonl(esn);
471 			memcpy(crda->crd_esn, &esn, 4);
472 			crda->crd_flags |= CRD_F_ESN;
473 		}
474 
475 		if (espx &&
476 		    (espx->type == CRYPTO_AES_GCM_16 ||
477 		     espx->type == CRYPTO_CHACHA20_POLY1305))
478 			crda->crd_len = hlen - tdb->tdb_ivlen;
479 		else
480 			crda->crd_len = m->m_pkthdr.len - (skip + alen);
481 
482 		/* Copy the authenticator */
483 		m_copydata(m, m->m_pkthdr.len - alen, alen, abuf);
484 	} else
485 		crde = &crp->crp_desc[0];
486 
487 	/* Crypto operation descriptor */
488 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
489 	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_MPSAFE;
490 	crp->crp_buf = (caddr_t)m;
491 	crp->crp_sid = tdb->tdb_cryptoid;
492 
493 	/* Decryption descriptor */
494 	if (espx) {
495 		crde->crd_skip = skip + hlen;
496 		crde->crd_inject = skip + hlen - tdb->tdb_ivlen;
497 		crde->crd_alg = espx->type;
498 		crde->crd_key = tdb->tdb_emxkey;
499 		crde->crd_klen = tdb->tdb_emxkeylen * 8;
500 		/* XXX Rounds ? */
501 
502 		if (crde->crd_alg == CRYPTO_AES_GMAC)
503 			crde->crd_len = 0;
504 		else
505 			crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
506 	}
507 
508 	KERNEL_LOCK();
509 	while ((error = crypto_invoke(crp)) == EAGAIN) {
510 		/* Reset the session ID */
511 		if (tdb->tdb_cryptoid != 0)
512 			tdb->tdb_cryptoid = crp->crp_sid;
513 	}
514 	KERNEL_UNLOCK();
515 	if (error) {
516 		DPRINTF("crypto error %d", error);
517 		ipsecstat_inc(ipsec_noxform);
518 		goto drop;
519 	}
520 
521 	clen = crp->crp_olen;
522 
523 	/* Release the crypto descriptors */
524 	crypto_freereq(crp);
525 	crp = NULL;
526 
527 	/* If authentication was performed, check now. */
528 	if (esph != NULL) {
529 		/* Copy the authenticator from the packet */
530 		m_copydata(m, m->m_pkthdr.len - esph->authsize,
531 		    esph->authsize, aalg);
532 
533 		/* Verify authenticator */
534 		if (timingsafe_bcmp(abuf, aalg, esph->authsize)) {
535 			DPRINTF("authentication failed for packet "
536 			    "in SA %s/%08x",
537 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
538 			    ntohl(tdb->tdb_spi));
539 			espstat_inc(esps_badauth);
540 			error = -1;
541 			goto drop;
542 		}
543 
544 		/* Remove trailing authenticator */
545 		m_adj(m, -(esph->authsize));
546 	}
547 
548 	/* Replay window checking, if appropriate */
549 	if (tdb->tdb_wnd > 0) {
550 		m_copydata(m, skip + sizeof(u_int32_t), sizeof(u_int32_t),
551 		    &btsx);
552 		btsx = ntohl(btsx);
553 
554 		switch (checkreplaywindow(tdb, tdb->tdb_rpl, btsx, &esn, 1)) {
555 		case 0: /* All's well */
556 #if NPFSYNC > 0
557 			pfsync_update_tdb(tdb,0);
558 #endif
559 			break;
560 
561 		case 1:
562 			DPRINTF("replay counter wrapped for SA %s/%08x",
563 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
564 			    ntohl(tdb->tdb_spi));
565 			espstat_inc(esps_wrap);
566 			error = -1;
567 			goto drop;
568 		case 2:
569 			DPRINTF("old packet received in SA %s/%08x",
570 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
571 			    ntohl(tdb->tdb_spi));
572 			espstat_inc(esps_replay);
573 			error = -1;
574 			goto drop;
575 		case 3:
576 			DPRINTF("duplicate packet received in SA %s/%08x",
577 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
578 			    ntohl(tdb->tdb_spi));
579 			espstat_inc(esps_replay);
580 			error = -1;
581 			goto drop;
582 		default:
583 			DPRINTF("bogus value from checkreplaywindow() "
584 			    "in SA %s/%08x",
585 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
586 			    ntohl(tdb->tdb_spi));
587 			espstat_inc(esps_replay);
588 			error = -1;
589 			goto drop;
590 		}
591 	}
592 
593 	/* Find beginning of ESP header */
594 	m1 = m_getptr(m, skip, &roff);
595 	if (m1 == NULL)	{
596 		DPRINTF("bad mbuf chain, SA %s/%08x",
597 		    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
598 		    ntohl(tdb->tdb_spi));
599 		espstat_inc(esps_hdrops);
600 		error = -1;
601 		goto drop;
602 	}
603 
604 	/* Remove the ESP header and IV from the mbuf. */
605 	if (roff == 0) {
606 		/* The ESP header was conveniently at the beginning of the mbuf */
607 		m_adj(m1, hlen);
608 		/*
609 		 * If m1 is the first mbuf, it has set M_PKTHDR and m_adj()
610 		 * has already adjusted the packet header length for us.
611 		 */
612 		if (m1 != m)
613 			m->m_pkthdr.len -= hlen;
614 	} else if (roff + hlen >= m1->m_len) {
615 		int adjlen;
616 
617 		/*
618 		 * Part or all of the ESP header is at the end of this mbuf, so
619 		 * first let's remove the remainder of the ESP header from the
620 		 * beginning of the remainder of the mbuf chain, if any.
621 		 */
622 		if (roff + hlen > m1->m_len) {
623 			adjlen = roff + hlen - m1->m_len;
624 
625 			/* Adjust the next mbuf by the remainder */
626 			m_adj(m1->m_next, adjlen);
627 
628 			/* The second mbuf is guaranteed not to have a pkthdr */
629 			m->m_pkthdr.len -= adjlen;
630 		}
631 
632 		/* Now, let's unlink the mbuf chain for a second...*/
633 		mo = m1->m_next;
634 		m1->m_next = NULL;
635 
636 		/* ...and trim the end of the first part of the chain...sick */
637 		adjlen = m1->m_len - roff;
638 		m_adj(m1, -adjlen);
639 		/*
640 		 * If m1 is the first mbuf, it has set M_PKTHDR and m_adj()
641 		 * has already adjusted the packet header length for us.
642 		 */
643 		if (m1 != m)
644 			m->m_pkthdr.len -= adjlen;
645 
646 		/* Finally, let's relink */
647 		m1->m_next = mo;
648 	} else {
649 		/*
650 		 * The ESP header lies in the "middle" of the mbuf...do an
651 		 * overlapping copy of the remainder of the mbuf over the ESP
652 		 * header.
653 		 */
654 		memmove(mtod(m1, u_char *) + roff,
655 		    mtod(m1, u_char *) + roff + hlen,
656 		    m1->m_len - (roff + hlen));
657 		m1->m_len -= hlen;
658 		m->m_pkthdr.len -= hlen;
659 	}
660 
661 	/* Save the last three bytes of decrypted data */
662 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
663 
664 	/* Verify pad length */
665 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
666 		DPRINTF("invalid padding length %d for packet in SA %s/%08x",
667 		    lastthree[1],
668 		    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
669 		    ntohl(tdb->tdb_spi));
670 		espstat_inc(esps_badilen);
671 		error = -1;
672 		goto drop;
673 	}
674 
675 	/* Verify correct decryption by checking the last padding bytes */
676 	if ((lastthree[1] != lastthree[0]) && (lastthree[1] != 0)) {
677 		DPRINTF("decryption failed for packet in SA %s/%08x",
678 		    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
679 		    ntohl(tdb->tdb_spi));
680 		espstat_inc(esps_badenc);
681 		error = -1;
682 		goto drop;
683 	}
684 
685 	/* Trim the mbuf chain to remove the padding */
686 	m_adj(m, -(lastthree[1] + 2));
687 
688 	/* Restore the Next Protocol field */
689 	m_copyback(m, protoff, sizeof(u_int8_t), lastthree + 2, M_NOWAIT);
690 
691 	/* Back to generic IPsec input processing */
692 	return ipsec_common_input_cb(mp, tdb, skip, protoff);
693 
694  drop:
695 	m_freemp(mp);
696 	crypto_freereq(crp);
697 	return error;
698 }
699 
700 /*
701  * ESP output routine, called by ipsp_process_packet().
702  */
703 int
704 esp_output(struct mbuf *m, struct tdb *tdb, int skip, int protoff)
705 {
706 	const struct enc_xform *espx = tdb->tdb_encalgxform;
707 	const struct auth_hash *esph = tdb->tdb_authalgxform;
708 	int ilen, olen, hlen, rlen, padding, blks, alen, roff, error;
709 	uint64_t replay64;
710 	uint32_t replay;
711 	struct mbuf *mi, *mo = (struct mbuf *) NULL;
712 	unsigned char *pad;
713 	uint8_t prot;
714 #ifdef ENCDEBUG
715 	char buf[INET6_ADDRSTRLEN];
716 #endif
717 	struct cryptodesc *crde = NULL, *crda = NULL;
718 	struct cryptop *crp = NULL;
719 #if NBPFILTER > 0
720 	struct ifnet *encif;
721 
722 	if ((encif = enc_getif(tdb->tdb_rdomain, tdb->tdb_tap)) != NULL) {
723 		encif->if_opackets++;
724 		encif->if_obytes += m->m_pkthdr.len;
725 
726 		if (encif->if_bpf) {
727 			struct enchdr hdr;
728 
729 			memset(&hdr, 0, sizeof(hdr));
730 
731 			hdr.af = tdb->tdb_dst.sa.sa_family;
732 			hdr.spi = tdb->tdb_spi;
733 			if (espx)
734 				hdr.flags |= M_CONF;
735 			if (esph)
736 				hdr.flags |= M_AUTH;
737 
738 			bpf_mtap_hdr(encif->if_bpf, (char *)&hdr,
739 			    ENC_HDRLEN, m, BPF_DIRECTION_OUT);
740 		}
741 	}
742 #endif
743 
744 	hlen = 2 * sizeof(u_int32_t) + tdb->tdb_ivlen;
745 
746 	rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
747 	if (espx)
748 		blks = MAX(espx->blocksize, 4);
749 	else
750 		blks = 4; /* If no encryption, we have to be 4-byte aligned. */
751 
752 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
753 
754 	alen = esph ? esph->authsize : 0;
755 	espstat_inc(esps_output);
756 
757 	switch (tdb->tdb_dst.sa.sa_family) {
758 	case AF_INET:
759 		/* Check for IP maximum packet size violations. */
760 		if (skip + hlen + rlen + padding + alen > IP_MAXPACKET)	{
761 			DPRINTF("packet in SA %s/%08x got too big",
762 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
763 			    ntohl(tdb->tdb_spi));
764 			espstat_inc(esps_toobig);
765 			error = EMSGSIZE;
766 			goto drop;
767 		}
768 		break;
769 
770 #ifdef INET6
771 	case AF_INET6:
772 		/* Check for IPv6 maximum packet size violations. */
773 		if (skip + hlen + rlen + padding + alen > IPV6_MAXPACKET) {
774 			DPRINTF("acket in SA %s/%08x got too big",
775 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
776 			    ntohl(tdb->tdb_spi));
777 			espstat_inc(esps_toobig);
778 			error = EMSGSIZE;
779 			goto drop;
780 		}
781 		break;
782 #endif /* INET6 */
783 
784 	default:
785 		DPRINTF("unknown/unsupported protocol family %d, SA %s/%08x",
786 		    tdb->tdb_dst.sa.sa_family,
787 		    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
788 		    ntohl(tdb->tdb_spi));
789 		espstat_inc(esps_nopf);
790 		error = EPFNOSUPPORT;
791 		goto drop;
792 	}
793 
794 	/* Update the counters. */
795 	tdb->tdb_cur_bytes += m->m_pkthdr.len - skip;
796 	espstat_add(esps_obytes, m->m_pkthdr.len - skip);
797 
798 	/* Hard byte expiration. */
799 	if (tdb->tdb_flags & TDBF_BYTES &&
800 	    tdb->tdb_cur_bytes >= tdb->tdb_exp_bytes) {
801 		pfkeyv2_expire(tdb, SADB_EXT_LIFETIME_HARD);
802 		tdb_delete(tdb);
803 		error = EINVAL;
804 		goto drop;
805 	}
806 
807 	/* Soft byte expiration. */
808 	if (tdb->tdb_flags & TDBF_SOFT_BYTES &&
809 	    tdb->tdb_cur_bytes >= tdb->tdb_soft_bytes) {
810 		pfkeyv2_expire(tdb, SADB_EXT_LIFETIME_SOFT);
811 		tdb->tdb_flags &= ~TDBF_SOFT_BYTES;    /* Turn off checking. */
812 	}
813 
814 	/*
815 	 * Loop through mbuf chain; if we find a readonly mbuf,
816 	 * copy the packet.
817 	 */
818 	mi = m;
819 	while (mi != NULL && !M_READONLY(mi))
820 		mi = mi->m_next;
821 
822 	if (mi != NULL)	{
823 		struct mbuf *n = m_dup_pkt(m, 0, M_DONTWAIT);
824 
825 		if (n == NULL) {
826 			DPRINTF("bad mbuf chain, SA %s/%08x",
827 			    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
828 			    ntohl(tdb->tdb_spi));
829 			espstat_inc(esps_hdrops);
830 			error = ENOBUFS;
831 			goto drop;
832 		}
833 
834 		m_freem(m);
835 		m = n;
836 	}
837 
838 	/* Inject ESP header. */
839 	mo = m_makespace(m, skip, hlen, &roff);
840 	if (mo == NULL) {
841 		DPRINTF("failed to inject ESP header for SA %s/%08x",
842 		    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
843 		    ntohl(tdb->tdb_spi));
844 		espstat_inc(esps_hdrops);
845 		error = ENOBUFS;
846 		goto drop;
847 	}
848 
849 	/* Initialize ESP header. */
850 	memcpy(mtod(mo, caddr_t) + roff, (caddr_t) &tdb->tdb_spi,
851 	    sizeof(u_int32_t));
852 	replay64 = tdb->tdb_rpl++;	/* used for both header and ESN */
853 	replay = htonl((u_int32_t)replay64);
854 	memcpy(mtod(mo, caddr_t) + roff + sizeof(u_int32_t), (caddr_t) &replay,
855 	    sizeof(u_int32_t));
856 
857 #if NPFSYNC > 0
858 	pfsync_update_tdb(tdb,1);
859 #endif
860 
861 	/*
862 	 * Add padding -- better to do it ourselves than use the crypto engine,
863 	 * although if/when we support compression, we'd have to do that.
864 	 */
865 	mo = m_makespace(m, m->m_pkthdr.len, padding + alen, &roff);
866 	if (mo == NULL) {
867 		DPRINTF("m_makespace() failed for SA %s/%08x",
868 		    ipsp_address(&tdb->tdb_dst, buf, sizeof(buf)),
869 		    ntohl(tdb->tdb_spi));
870 		espstat_inc(esps_hdrops);
871 		error = ENOBUFS;
872 		goto drop;
873 	}
874 	pad = mtod(mo, caddr_t) + roff;
875 
876 	/* Apply self-describing padding */
877 	for (ilen = 0; ilen < padding - 2; ilen++)
878 		pad[ilen] = ilen + 1;
879 
880 	/* Fix padding length and Next Protocol in padding itself. */
881 	pad[padding - 2] = padding - 2;
882 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
883 
884 	/* Fix Next Protocol in IPv4/IPv6 header. */
885 	prot = IPPROTO_ESP;
886 	m_copyback(m, protoff, sizeof(u_int8_t), &prot, M_NOWAIT);
887 
888 	/* Get crypto descriptors. */
889 	crp = crypto_getreq(esph && espx ? 2 : 1);
890 	if (crp == NULL) {
891 		DPRINTF("failed to acquire crypto descriptors");
892 		espstat_inc(esps_crypto);
893 		error = ENOBUFS;
894 		goto drop;
895 	}
896 
897 	if (espx) {
898 		crde = &crp->crp_desc[0];
899 		crda = &crp->crp_desc[1];
900 
901 		/* Encryption descriptor. */
902 		crde->crd_skip = skip + hlen;
903 		crde->crd_flags = CRD_F_ENCRYPT | CRD_F_IV_EXPLICIT;
904 		crde->crd_inject = skip + hlen - tdb->tdb_ivlen;
905 
906 		/* Encryption operation. */
907 		crde->crd_alg = espx->type;
908 		crde->crd_key = tdb->tdb_emxkey;
909 		crde->crd_klen = tdb->tdb_emxkeylen * 8;
910 		/* XXX Rounds ? */
911 
912 		if (crde->crd_alg == CRYPTO_AES_GMAC)
913 			crde->crd_len = 0;
914 		else
915 			crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
916 
917 		/* GCM & friends just require a NONCE (non-repeating!) */
918 		if (espx->type == CRYPTO_AES_CTR ||
919 		    espx->type == CRYPTO_AES_GCM_16 ||
920 		    espx->type == CRYPTO_CHACHA20_POLY1305)
921 			bcopy(&replay64, crde->crd_iv, sizeof(replay64));
922 		else
923 			arc4random_buf(crde->crd_iv, espx->ivsize);
924 	} else
925 		crda = &crp->crp_desc[0];
926 
927 	/* Crypto operation descriptor. */
928 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
929 	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_MPSAFE;
930 	crp->crp_buf = (caddr_t)m;
931 	crp->crp_sid = tdb->tdb_cryptoid;
932 
933 	if (esph) {
934 		/* Authentication descriptor. */
935 		crda->crd_skip = skip;
936 		crda->crd_inject = m->m_pkthdr.len - alen;
937 
938 		/* Authentication operation. */
939 		crda->crd_alg = esph->type;
940 		crda->crd_key = tdb->tdb_amxkey;
941 		crda->crd_klen = tdb->tdb_amxkeylen * 8;
942 
943 		if ((tdb->tdb_wnd > 0) && (tdb->tdb_flags & TDBF_ESN)) {
944 			u_int32_t esn;
945 
946 			esn = htonl((u_int32_t)(replay64 >> 32));
947 			memcpy(crda->crd_esn, &esn, 4);
948 			crda->crd_flags |= CRD_F_ESN;
949 		}
950 
951 		if (espx &&
952 		    (espx->type == CRYPTO_AES_GCM_16 ||
953 		     espx->type == CRYPTO_CHACHA20_POLY1305))
954 			crda->crd_len = hlen - tdb->tdb_ivlen;
955 		else
956 			crda->crd_len = m->m_pkthdr.len - (skip + alen);
957 	}
958 
959 	KERNEL_LOCK();
960 	while ((error = crypto_invoke(crp)) == EAGAIN) {
961 		/* Reset the session ID */
962 		if (tdb->tdb_cryptoid != 0)
963 			tdb->tdb_cryptoid = crp->crp_sid;
964 	}
965 	KERNEL_UNLOCK();
966 	if (error) {
967 		DPRINTF("crypto error %d", error);
968 		ipsecstat_inc(ipsec_noxform);
969 		goto drop;
970 	}
971 
972 	ilen = crp->crp_ilen;
973 	olen = crp->crp_olen;
974 
975 	/* Release the crypto descriptors */
976 	crypto_freereq(crp);
977 
978 	/* Call the IPsec input callback. */
979 	error = ipsp_process_done(m, tdb);
980 	if (error)
981 		espstat_inc(esps_outfail);
982 	return (error);
983 
984  drop:
985 	m_freem(m);
986 	crypto_freereq(crp);
987 	return error;
988 }
989 
990 #define SEEN_SIZE	howmany(TDB_REPLAYMAX, 32)
991 
992 /*
993  * return 0 on success
994  * return 1 for counter == 0
995  * return 2 for very old packet
996  * return 3 for packet within current window but already received
997  */
998 int
999 checkreplaywindow(struct tdb *tdb, u_int64_t t, u_int32_t seq, u_int32_t *seqh,
1000     int commit)
1001 {
1002 	u_int32_t	tl, th, wl;
1003 	u_int32_t	packet, window = TDB_REPLAYMAX - TDB_REPLAYWASTE;
1004 	int		idx, esn = tdb->tdb_flags & TDBF_ESN;
1005 
1006 	tl = (u_int32_t)t;
1007 	th = (u_int32_t)(t >> 32);
1008 
1009 	/* Zero SN is not allowed */
1010 	if ((esn && seq == 0 && tl <= AH_HMAC_INITIAL_RPL && th == 0) ||
1011 	    (!esn && seq == 0))
1012 		return (1);
1013 
1014 	if (th == 0 && tl < window)
1015 		window = tl;
1016 	/* Current replay window starts here */
1017 	wl = tl - window + 1;
1018 
1019 	idx = (seq % TDB_REPLAYMAX) / 32;
1020 	packet = 1 << (31 - (seq & 31));
1021 
1022 	/*
1023 	 * We keep the high part intact when:
1024 	 * 1) the SN is within [wl, 0xffffffff] and the whole window is
1025 	 *    within one subspace;
1026 	 * 2) the SN is within [0, wl) and window spans two subspaces.
1027 	 */
1028 	if ((tl >= window - 1 && seq >= wl) ||
1029 	    (tl <  window - 1 && seq <  wl)) {
1030 		*seqh = th;
1031 		if (seq > tl) {
1032 			if (commit) {
1033 				if (seq - tl > window)
1034 					memset(tdb->tdb_seen, 0,
1035 					    sizeof(tdb->tdb_seen));
1036 				else {
1037 					int i = (tl % TDB_REPLAYMAX) / 32;
1038 
1039 					while (i != idx) {
1040 						i = (i + 1) % SEEN_SIZE;
1041 						tdb->tdb_seen[i] = 0;
1042 					}
1043 				}
1044 				tdb->tdb_seen[idx] |= packet;
1045 				tdb->tdb_rpl = ((u_int64_t)*seqh << 32) | seq;
1046 			}
1047 		} else {
1048 			if (tl - seq >= window)
1049 				return (2);
1050 			if (tdb->tdb_seen[idx] & packet)
1051 				return (3);
1052 			if (commit)
1053 				tdb->tdb_seen[idx] |= packet;
1054 		}
1055 		return (0);
1056 	}
1057 
1058 	/* Can't wrap if not doing ESN */
1059 	if (!esn)
1060 		return (2);
1061 
1062 	/*
1063 	 * (3) SN is within [wl, 0xffffffff] and wl is within
1064 	 *     (0xffffffff-window+1, 0xffffffff].
1065 	 * This means we got a SN which is within our replay window,
1066 	 * but in the previous subspace.
1067 	 */
1068 	if (tl < window - 1 && seq >= wl) {
1069 		if (tdb->tdb_seen[idx] & packet)
1070 			return (3);
1071 		*seqh = th - 1;
1072 		if (commit)
1073 			tdb->tdb_seen[idx] |= packet;
1074 		return (0);
1075 	}
1076 
1077 	/*
1078 	 * (4) SN has wrapped and the last authenticated SN is in the old
1079 	 *     subspace.
1080 	 */
1081 	*seqh = th + 1;
1082 	if (*seqh == 0)		/* Don't let high bit to wrap */
1083 		return (1);
1084 	if (commit) {
1085 		if (seq - tl > window)
1086 			memset(tdb->tdb_seen, 0, sizeof(tdb->tdb_seen));
1087 		else {
1088 			int i = (tl % TDB_REPLAYMAX) / 32;
1089 
1090 			while (i != idx) {
1091 				i = (i + 1) % SEEN_SIZE;
1092 				tdb->tdb_seen[i] = 0;
1093 			}
1094 		}
1095 		tdb->tdb_seen[idx] |= packet;
1096 		tdb->tdb_rpl = ((u_int64_t)*seqh << 32) | seq;
1097 	}
1098 
1099 	return (0);
1100 }
1101