xref: /openbsd/sys/netinet/ipsec_input.c (revision 3cab2bb3)
1 /*	$OpenBSD: ipsec_input.c,v 1.172 2020/08/01 23:41:55 gnezdo 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  * This code was written by John Ioannidis for BSD/OS in Athens, Greece,
8  * 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 "pf.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/protosw.h>
43 #include <sys/mbuf.h>
44 #include <sys/socket.h>
45 #include <sys/sysctl.h>
46 #include <sys/kernel.h>
47 #include <sys/timeout.h>
48 
49 #include <net/if.h>
50 #include <net/if_var.h>
51 #include <net/netisr.h>
52 #include <net/bpf.h>
53 #include <net/route.h>
54 
55 #include <netinet/in.h>
56 #include <netinet/ip.h>
57 #include <netinet/ip_var.h>
58 #include <netinet/ip_icmp.h>
59 #include <netinet/tcp.h>
60 #include <netinet/udp.h>
61 
62 #if NPF > 0
63 #include <net/pfvar.h>
64 #endif
65 
66 #ifdef INET6
67 #include <netinet6/in6_var.h>
68 #include <netinet/ip6.h>
69 #include <netinet6/ip6_var.h>
70 #include <netinet6/ip6protosw.h>
71 #endif /* INET6 */
72 
73 #include <netinet/ip_ipsp.h>
74 #include <netinet/ip_esp.h>
75 #include <netinet/ip_ah.h>
76 #include <netinet/ip_ipcomp.h>
77 
78 #include <net/if_enc.h>
79 
80 #include <crypto/cryptodev.h>
81 #include <crypto/xform.h>
82 
83 #include "bpfilter.h"
84 
85 void ipsec_common_ctlinput(u_int, int, struct sockaddr *, void *, int);
86 
87 #ifdef ENCDEBUG
88 #define DPRINTF(x)	if (encdebug) printf x
89 #else
90 #define DPRINTF(x)
91 #endif
92 
93 /* sysctl variables */
94 int encdebug = 0;
95 int ipsec_keep_invalid = IPSEC_DEFAULT_EMBRYONIC_SA_TIMEOUT;
96 int ipsec_require_pfs = IPSEC_DEFAULT_PFS;
97 int ipsec_soft_allocations = IPSEC_DEFAULT_SOFT_ALLOCATIONS;
98 int ipsec_exp_allocations = IPSEC_DEFAULT_EXP_ALLOCATIONS;
99 int ipsec_soft_bytes = IPSEC_DEFAULT_SOFT_BYTES;
100 int ipsec_exp_bytes = IPSEC_DEFAULT_EXP_BYTES;
101 int ipsec_soft_timeout = IPSEC_DEFAULT_SOFT_TIMEOUT;
102 int ipsec_exp_timeout = IPSEC_DEFAULT_EXP_TIMEOUT;
103 int ipsec_soft_first_use = IPSEC_DEFAULT_SOFT_FIRST_USE;
104 int ipsec_exp_first_use = IPSEC_DEFAULT_EXP_FIRST_USE;
105 int ipsec_expire_acquire = IPSEC_DEFAULT_EXPIRE_ACQUIRE;
106 
107 int esp_enable = 1;
108 int ah_enable = 1;
109 int ipcomp_enable = 0;
110 
111 int *espctl_vars[ESPCTL_MAXID] = ESPCTL_VARS;
112 int *ahctl_vars[AHCTL_MAXID] = AHCTL_VARS;
113 int *ipcompctl_vars[IPCOMPCTL_MAXID] = IPCOMPCTL_VARS;
114 
115 struct cpumem *espcounters;
116 struct cpumem *ahcounters;
117 struct cpumem *ipcompcounters;
118 struct cpumem *ipseccounters;
119 
120 char ipsec_def_enc[20];
121 char ipsec_def_auth[20];
122 char ipsec_def_comp[20];
123 
124 int *ipsecctl_vars[IPSEC_MAXID] = IPSECCTL_VARS;
125 
126 int esp_sysctl_espstat(void *, size_t *, void *);
127 int ah_sysctl_ahstat(void *, size_t *, void *);
128 int ipcomp_sysctl_ipcompstat(void *, size_t *, void *);
129 int ipsec_sysctl_ipsecstat(void *, size_t *, void *);
130 
131 void
132 ipsec_init(void)
133 {
134 	espcounters = counters_alloc(esps_ncounters);
135 	ahcounters = counters_alloc(ahs_ncounters);
136 	ipcompcounters = counters_alloc(ipcomps_ncounters);
137 	ipseccounters = counters_alloc(ipsec_ncounters);
138 
139 	strlcpy(ipsec_def_enc, IPSEC_DEFAULT_DEF_ENC, sizeof(ipsec_def_enc));
140 	strlcpy(ipsec_def_auth, IPSEC_DEFAULT_DEF_AUTH, sizeof(ipsec_def_auth));
141 	strlcpy(ipsec_def_comp, IPSEC_DEFAULT_DEF_COMP, sizeof(ipsec_def_comp));
142 
143 }
144 
145 /*
146  * ipsec_common_input() gets called when we receive an IPsec-protected packet
147  * in IPv4 or IPv6. All it does is find the right TDB and call the appropriate
148  * transform. The callback takes care of further processing (like ingress
149  * filtering).
150  */
151 int
152 ipsec_common_input(struct mbuf *m, int skip, int protoff, int af, int sproto,
153     int udpencap)
154 {
155 #define IPSEC_ISTAT(x,y,z) do {			\
156 	if (sproto == IPPROTO_ESP)		\
157 		espstat_inc(x);			\
158 	else if (sproto == IPPROTO_AH)		\
159 		ahstat_inc(y);			\
160 	else					\
161 		ipcompstat_inc(z);		\
162 } while (0)
163 
164 	union sockaddr_union dst_address;
165 	struct tdb *tdbp = NULL;
166 	struct ifnet *encif;
167 	u_int32_t spi;
168 	u_int16_t cpi;
169 	int error;
170 #ifdef ENCDEBUG
171 	char buf[INET6_ADDRSTRLEN];
172 #endif
173 
174 	NET_ASSERT_LOCKED();
175 
176 	ipsecstat_inc(ipsec_ipackets);
177 	ipsecstat_add(ipsec_ibytes, m->m_pkthdr.len);
178 	IPSEC_ISTAT(esps_input, ahs_input, ipcomps_input);
179 
180 	if (m == NULL) {
181 		DPRINTF(("%s: NULL packet received\n", __func__));
182 		IPSEC_ISTAT(esps_hdrops, ahs_hdrops, ipcomps_hdrops);
183 		return EINVAL;
184 	}
185 
186 	if ((sproto == IPPROTO_IPCOMP) && (m->m_flags & M_COMP)) {
187 		DPRINTF(("%s: repeated decompression\n", __func__));
188 		ipcompstat_inc(ipcomps_pdrops);
189 		error = EINVAL;
190 		goto drop;
191 	}
192 
193 	if (m->m_pkthdr.len - skip < 2 * sizeof(u_int32_t)) {
194 		DPRINTF(("%s: packet too small\n", __func__));
195 		IPSEC_ISTAT(esps_hdrops, ahs_hdrops, ipcomps_hdrops);
196 		error = EINVAL;
197 		goto drop;
198 	}
199 
200 	/* Retrieve the SPI from the relevant IPsec header */
201 	switch (sproto) {
202 	case IPPROTO_ESP:
203 		m_copydata(m, skip, sizeof(u_int32_t), (caddr_t) &spi);
204 		break;
205 	case IPPROTO_AH:
206 		m_copydata(m, skip + sizeof(u_int32_t), sizeof(u_int32_t),
207 		    (caddr_t) &spi);
208 		break;
209 	case IPPROTO_IPCOMP:
210 		m_copydata(m, skip + sizeof(u_int16_t), sizeof(u_int16_t),
211 		    (caddr_t) &cpi);
212 		spi = ntohl(htons(cpi));
213 		break;
214 	default:
215 		panic("%s: unknown/unsupported security protocol %d",
216 		    __func__, sproto);
217 	}
218 
219 	/*
220 	 * Find tunnel control block and (indirectly) call the appropriate
221 	 * kernel crypto routine. The resulting mbuf chain is a valid
222 	 * IP packet ready to go through input processing.
223 	 */
224 
225 	memset(&dst_address, 0, sizeof(dst_address));
226 	dst_address.sa.sa_family = af;
227 
228 	switch (af) {
229 	case AF_INET:
230 		dst_address.sin.sin_len = sizeof(struct sockaddr_in);
231 		m_copydata(m, offsetof(struct ip, ip_dst),
232 		    sizeof(struct in_addr),
233 		    (caddr_t) &(dst_address.sin.sin_addr));
234 		break;
235 
236 #ifdef INET6
237 	case AF_INET6:
238 		dst_address.sin6.sin6_len = sizeof(struct sockaddr_in6);
239 		m_copydata(m, offsetof(struct ip6_hdr, ip6_dst),
240 		    sizeof(struct in6_addr),
241 		    (caddr_t) &(dst_address.sin6.sin6_addr));
242 		in6_recoverscope(&dst_address.sin6,
243 		    &dst_address.sin6.sin6_addr);
244 		break;
245 #endif /* INET6 */
246 
247 	default:
248 		DPRINTF(("%s: unsupported protocol family %d\n", __func__, af));
249 		IPSEC_ISTAT(esps_nopf, ahs_nopf, ipcomps_nopf);
250 		error = EPFNOSUPPORT;
251 		goto drop;
252 	}
253 
254 	tdbp = gettdb(rtable_l2(m->m_pkthdr.ph_rtableid),
255 	    spi, &dst_address, sproto);
256 	if (tdbp == NULL) {
257 		DPRINTF(("%s: could not find SA for packet to %s, spi %08x\n",
258 		    __func__,
259 		    ipsp_address(&dst_address, buf, sizeof(buf)), ntohl(spi)));
260 		IPSEC_ISTAT(esps_notdb, ahs_notdb, ipcomps_notdb);
261 		error = ENOENT;
262 		goto drop;
263 	}
264 
265 	if (tdbp->tdb_flags & TDBF_INVALID) {
266 		DPRINTF(("%s: attempted to use invalid SA %s/%08x/%u\n",
267 		    __func__, ipsp_address(&dst_address, buf,
268 		    sizeof(buf)), ntohl(spi), tdbp->tdb_sproto));
269 		IPSEC_ISTAT(esps_invalid, ahs_invalid, ipcomps_invalid);
270 		error = EINVAL;
271 		goto drop;
272 	}
273 
274 	if (udpencap && !(tdbp->tdb_flags & TDBF_UDPENCAP)) {
275 		DPRINTF(("%s: attempted to use non-udpencap SA %s/%08x/%u\n",
276 		    __func__, ipsp_address(&dst_address, buf,
277 		    sizeof(buf)), ntohl(spi), tdbp->tdb_sproto));
278 		espstat_inc(esps_udpinval);
279 		error = EINVAL;
280 		goto drop;
281 	}
282 
283 	if (!udpencap && (tdbp->tdb_flags & TDBF_UDPENCAP)) {
284 		DPRINTF(("%s: attempted to use udpencap SA %s/%08x/%u\n",
285 		    __func__, ipsp_address(&dst_address, buf,
286 		    sizeof(buf)), ntohl(spi), tdbp->tdb_sproto));
287 		espstat_inc(esps_udpneeded);
288 		error = EINVAL;
289 		goto drop;
290 	}
291 
292 	if (tdbp->tdb_xform == NULL) {
293 		DPRINTF(("%s: attempted to use uninitialized SA %s/%08x/%u\n",
294 		    __func__, ipsp_address(&dst_address, buf,
295 		    sizeof(buf)), ntohl(spi), tdbp->tdb_sproto));
296 		IPSEC_ISTAT(esps_noxform, ahs_noxform, ipcomps_noxform);
297 		error = ENXIO;
298 		goto drop;
299 	}
300 
301 	if (sproto != IPPROTO_IPCOMP) {
302 		if ((encif = enc_getif(tdbp->tdb_rdomain_post,
303 		    tdbp->tdb_tap)) == NULL) {
304 			DPRINTF(("%s: no enc%u interface for SA %s/%08x/%u\n",
305 			    __func__,
306 			    tdbp->tdb_tap, ipsp_address(&dst_address, buf,
307 			    sizeof(buf)), ntohl(spi), tdbp->tdb_sproto));
308 			IPSEC_ISTAT(esps_pdrops, ahs_pdrops, ipcomps_pdrops);
309 			error = EACCES;
310 			goto drop;
311 		}
312 
313 		/* XXX This conflicts with the scoped nature of IPv6 */
314 		m->m_pkthdr.ph_ifidx = encif->if_index;
315 	}
316 
317 	/* Register first use, setup expiration timer. */
318 	if (tdbp->tdb_first_use == 0) {
319 		tdbp->tdb_first_use = gettime();
320 		if (tdbp->tdb_flags & TDBF_FIRSTUSE)
321 			timeout_add_sec(&tdbp->tdb_first_tmo,
322 			    tdbp->tdb_exp_first_use);
323 		if (tdbp->tdb_flags & TDBF_SOFT_FIRSTUSE)
324 			timeout_add_sec(&tdbp->tdb_sfirst_tmo,
325 			    tdbp->tdb_soft_first_use);
326 	}
327 
328 	tdbp->tdb_ipackets++;
329 	tdbp->tdb_ibytes += m->m_pkthdr.len;
330 
331 	/*
332 	 * Call appropriate transform and return -- callback takes care of
333 	 * everything else.
334 	 */
335 	error = (*(tdbp->tdb_xform->xf_input))(m, tdbp, skip, protoff);
336 	if (error) {
337 		ipsecstat_inc(ipsec_idrops);
338 		tdbp->tdb_idrops++;
339 	}
340 	return error;
341 
342  drop:
343 	ipsecstat_inc(ipsec_idrops);
344 	if (tdbp != NULL)
345 		tdbp->tdb_idrops++;
346 	m_freem(m);
347 	return error;
348 }
349 
350 void
351 ipsec_input_cb(struct cryptop *crp)
352 {
353 	struct tdb_crypto *tc = (struct tdb_crypto *) crp->crp_opaque;
354 	struct mbuf *m = (struct mbuf *) crp->crp_buf;
355 	struct tdb *tdb = NULL;
356 	int clen, error;
357 
358 	if (m == NULL) {
359 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
360 		ipsecstat_inc(ipsec_crypto);
361 		goto droponly;
362 	}
363 
364 
365 	NET_LOCK();
366 	tdb = gettdb(tc->tc_rdomain, tc->tc_spi, &tc->tc_dst, tc->tc_proto);
367 	if (tdb == NULL) {
368 		DPRINTF(("%s: TDB is expired while in crypto", __func__));
369 		ipsecstat_inc(ipsec_notdb);
370 		goto baddone;
371 	}
372 
373 	/* Check for crypto errors */
374 	if (crp->crp_etype) {
375 		if (crp->crp_etype == EAGAIN) {
376 			/* Reset the session ID */
377 			if (tdb->tdb_cryptoid != 0)
378 				tdb->tdb_cryptoid = crp->crp_sid;
379 			NET_UNLOCK();
380 			crypto_dispatch(crp);
381 			return;
382 		}
383 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
384 		ipsecstat_inc(ipsec_noxform);
385 		goto baddone;
386 	}
387 
388 	/* Length of data after processing */
389 	clen = crp->crp_olen;
390 
391 	/* Release the crypto descriptors */
392 	crypto_freereq(crp);
393 
394 	switch (tdb->tdb_sproto) {
395 	case IPPROTO_ESP:
396 		error = esp_input_cb(tdb, tc, m, clen);
397 		break;
398 	case IPPROTO_AH:
399 		error = ah_input_cb(tdb, tc, m, clen);
400 		break;
401 	case IPPROTO_IPCOMP:
402 		error = ipcomp_input_cb(tdb, tc, m, clen);
403 		break;
404 	default:
405 		panic("%s: unknown/unsupported security protocol %d",
406 		    __func__, tdb->tdb_sproto);
407 	}
408 
409 	NET_UNLOCK();
410 	if (error) {
411 		ipsecstat_inc(ipsec_idrops);
412 		tdb->tdb_idrops++;
413 	}
414 	return;
415 
416  baddone:
417 	NET_UNLOCK();
418  droponly:
419 	ipsecstat_inc(ipsec_idrops);
420 	if (tdb != NULL)
421 		tdb->tdb_idrops++;
422 	free(tc, M_XDATA, 0);
423 	m_freem(m);
424 	crypto_freereq(crp);
425 }
426 
427 /*
428  * IPsec input callback, called by the transform callback. Takes care of
429  * filtering and other sanity checks on the processed packet.
430  */
431 int
432 ipsec_common_input_cb(struct mbuf *m, struct tdb *tdbp, int skip, int protoff)
433 {
434 	int af, sproto;
435 	u_int8_t prot;
436 
437 #if NBPFILTER > 0
438 	struct ifnet *encif;
439 #endif
440 
441 	struct ip *ip, ipn;
442 
443 #ifdef INET6
444 	struct ip6_hdr *ip6, ip6n;
445 #endif /* INET6 */
446 	struct m_tag *mtag;
447 	struct tdb_ident *tdbi;
448 
449 #ifdef ENCDEBUG
450 	char buf[INET6_ADDRSTRLEN];
451 #endif
452 
453 	af = tdbp->tdb_dst.sa.sa_family;
454 	sproto = tdbp->tdb_sproto;
455 
456 	tdbp->tdb_last_used = gettime();
457 
458 	/* Sanity check */
459 	if (m == NULL) {
460 		/* The called routine will print a message if necessary */
461 		IPSEC_ISTAT(esps_badkcr, ahs_badkcr, ipcomps_badkcr);
462 		return -1;
463 	}
464 
465 	/* Fix IPv4 header */
466 	if (af == AF_INET) {
467 		if ((m->m_len < skip) && ((m = m_pullup(m, skip)) == NULL)) {
468 			DPRINTF(("%s: processing failed for SA %s/%08x\n",
469 			    __func__, ipsp_address(&tdbp->tdb_dst,
470 			    buf, sizeof(buf)), ntohl(tdbp->tdb_spi)));
471 			IPSEC_ISTAT(esps_hdrops, ahs_hdrops, ipcomps_hdrops);
472 			return -1;
473 		}
474 
475 		ip = mtod(m, struct ip *);
476 		ip->ip_len = htons(m->m_pkthdr.len);
477 		ip->ip_sum = 0;
478 		ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
479 		prot = ip->ip_p;
480 
481 		/* IP-in-IP encapsulation */
482 		if (prot == IPPROTO_IPIP) {
483 			if (m->m_pkthdr.len - skip < sizeof(struct ip)) {
484 				m_freem(m);
485 				IPSEC_ISTAT(esps_hdrops, ahs_hdrops,
486 				    ipcomps_hdrops);
487 				return -1;
488 			}
489 			/* ipn will now contain the inner IPv4 header */
490 			m_copydata(m, skip, sizeof(struct ip),
491 			    (caddr_t) &ipn);
492 		}
493 
494 #ifdef INET6
495 		/* IPv6-in-IP encapsulation. */
496 		if (prot == IPPROTO_IPV6) {
497 			if (m->m_pkthdr.len - skip < sizeof(struct ip6_hdr)) {
498 				m_freem(m);
499 				IPSEC_ISTAT(esps_hdrops, ahs_hdrops,
500 				    ipcomps_hdrops);
501 				return -1;
502 			}
503 			/* ip6n will now contain the inner IPv6 header. */
504 			m_copydata(m, skip, sizeof(struct ip6_hdr),
505 			    (caddr_t) &ip6n);
506 		}
507 #endif /* INET6 */
508 	}
509 
510 #ifdef INET6
511 	/* Fix IPv6 header */
512 	if (af == AF_INET6)
513 	{
514 		if (m->m_len < sizeof(struct ip6_hdr) &&
515 		    (m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
516 
517 			DPRINTF(("%s: processing failed for SA %s/%08x\n",
518 			    __func__, ipsp_address(&tdbp->tdb_dst,
519 			    buf, sizeof(buf)), ntohl(tdbp->tdb_spi)));
520 
521 			IPSEC_ISTAT(esps_hdrops, ahs_hdrops, ipcomps_hdrops);
522 			return -1;
523 		}
524 
525 		ip6 = mtod(m, struct ip6_hdr *);
526 		ip6->ip6_plen = htons(m->m_pkthdr.len - skip);
527 
528 		/* Save protocol */
529 		m_copydata(m, protoff, 1, (caddr_t) &prot);
530 
531 		/* IP-in-IP encapsulation */
532 		if (prot == IPPROTO_IPIP) {
533 			if (m->m_pkthdr.len - skip < sizeof(struct ip)) {
534 				m_freem(m);
535 				IPSEC_ISTAT(esps_hdrops, ahs_hdrops,
536 				    ipcomps_hdrops);
537 				return -1;
538 			}
539 			/* ipn will now contain the inner IPv4 header */
540 			m_copydata(m, skip, sizeof(struct ip), (caddr_t) &ipn);
541 		}
542 
543 		/* IPv6-in-IP encapsulation */
544 		if (prot == IPPROTO_IPV6) {
545 			if (m->m_pkthdr.len - skip < sizeof(struct ip6_hdr)) {
546 				m_freem(m);
547 				IPSEC_ISTAT(esps_hdrops, ahs_hdrops,
548 				    ipcomps_hdrops);
549 				return -1;
550 			}
551 			/* ip6n will now contain the inner IPv6 header. */
552 			m_copydata(m, skip, sizeof(struct ip6_hdr),
553 			    (caddr_t) &ip6n);
554 		}
555 	}
556 #endif /* INET6 */
557 
558 	/*
559 	 * Fix TCP/UDP checksum of UDP encapsulated transport mode ESP packet.
560 	 * (RFC3948 3.1.2)
561 	 */
562 	if ((af == AF_INET || af == AF_INET6) &&
563 	    (tdbp->tdb_flags & TDBF_UDPENCAP) &&
564 	    (tdbp->tdb_flags & TDBF_TUNNELING) == 0) {
565 		u_int16_t cksum;
566 
567 		switch (prot) {
568 		case IPPROTO_UDP:
569 			if (m->m_pkthdr.len < skip + sizeof(struct udphdr)) {
570 				m_freem(m);
571 				IPSEC_ISTAT(esps_hdrops, ahs_hdrops,
572 				    ipcomps_hdrops);
573 				return -1;
574 			}
575 			cksum = 0;
576 			m_copyback(m, skip + offsetof(struct udphdr, uh_sum),
577 			    sizeof(cksum), &cksum, M_NOWAIT);
578 #ifdef INET6
579 			if (af == AF_INET6) {
580 				cksum = in6_cksum(m, IPPROTO_UDP, skip,
581 				    m->m_pkthdr.len - skip);
582 				m_copyback(m, skip + offsetof(struct udphdr,
583 				    uh_sum), sizeof(cksum), &cksum, M_NOWAIT);
584 			}
585 #endif
586 			break;
587 		case IPPROTO_TCP:
588 			if (m->m_pkthdr.len < skip + sizeof(struct tcphdr)) {
589 				m_freem(m);
590 				IPSEC_ISTAT(esps_hdrops, ahs_hdrops,
591 				    ipcomps_hdrops);
592 				return -1;
593 			}
594 			cksum = 0;
595 			m_copyback(m, skip + offsetof(struct tcphdr, th_sum),
596 			    sizeof(cksum), &cksum, M_NOWAIT);
597 			if (af == AF_INET)
598 				cksum = in4_cksum(m, IPPROTO_TCP, skip,
599 				    m->m_pkthdr.len - skip);
600 #ifdef INET6
601 			else if (af == AF_INET6)
602 				cksum = in6_cksum(m, IPPROTO_TCP, skip,
603 				    m->m_pkthdr.len - skip);
604 #endif
605 			m_copyback(m, skip + offsetof(struct tcphdr, th_sum),
606 			    sizeof(cksum), &cksum, M_NOWAIT);
607 			break;
608 		}
609 	}
610 
611 	/*
612 	 * Record what we've done to the packet (under what SA it was
613 	 * processed).
614 	 */
615 	if (tdbp->tdb_sproto != IPPROTO_IPCOMP) {
616 		mtag = m_tag_get(PACKET_TAG_IPSEC_IN_DONE,
617 		    sizeof(struct tdb_ident), M_NOWAIT);
618 		if (mtag == NULL) {
619 			m_freem(m);
620 			DPRINTF(("%s: failed to get tag\n", __func__));
621 			IPSEC_ISTAT(esps_hdrops, ahs_hdrops, ipcomps_hdrops);
622 			return -1;
623 		}
624 
625 		tdbi = (struct tdb_ident *)(mtag + 1);
626 		tdbi->dst = tdbp->tdb_dst;
627 		tdbi->proto = tdbp->tdb_sproto;
628 		tdbi->spi = tdbp->tdb_spi;
629 		tdbi->rdomain = tdbp->tdb_rdomain;
630 
631 		m_tag_prepend(m, mtag);
632 	}
633 
634 	switch (sproto) {
635 	case IPPROTO_ESP:
636 		/* Packet is confidential ? */
637 		if (tdbp->tdb_encalgxform)
638 			m->m_flags |= M_CONF;
639 
640 		/* Check if we had authenticated ESP. */
641 		if (tdbp->tdb_authalgxform)
642 			m->m_flags |= M_AUTH;
643 		break;
644 	case IPPROTO_AH:
645 		m->m_flags |= M_AUTH;
646 		break;
647 	case IPPROTO_IPCOMP:
648 		m->m_flags |= M_COMP;
649 		break;
650 	default:
651 		panic("%s: unknown/unsupported security protocol %d",
652 		    __func__, sproto);
653 	}
654 
655 #if NPF > 0
656 	/* Add pf tag if requested. */
657 	pf_tag_packet(m, tdbp->tdb_tag, -1);
658 	pf_pkt_addr_changed(m);
659 #endif
660 	if (tdbp->tdb_rdomain != tdbp->tdb_rdomain_post)
661 		m->m_pkthdr.ph_rtableid = tdbp->tdb_rdomain_post;
662 
663 	if (tdbp->tdb_flags & TDBF_TUNNELING)
664 		m->m_flags |= M_TUNNEL;
665 
666 	ipsecstat_add(ipsec_idecompbytes, m->m_pkthdr.len);
667 	tdbp->tdb_idecompbytes += m->m_pkthdr.len;
668 
669 #if NBPFILTER > 0
670 	if ((encif = enc_getif(tdbp->tdb_rdomain_post, tdbp->tdb_tap)) != NULL) {
671 		encif->if_ipackets++;
672 		encif->if_ibytes += m->m_pkthdr.len;
673 
674 		if (encif->if_bpf) {
675 			struct enchdr hdr;
676 
677 			hdr.af = af;
678 			hdr.spi = tdbp->tdb_spi;
679 			hdr.flags = m->m_flags & (M_AUTH|M_CONF);
680 
681 			bpf_mtap_hdr(encif->if_bpf, (char *)&hdr,
682 			    ENC_HDRLEN, m, BPF_DIRECTION_IN);
683 		}
684 	}
685 #endif
686 
687 #if NPF > 0
688 	/*
689 	 * The ip_deliver() shortcut avoids running through ip_input() with the
690 	 * same IP header twice.  Packets in transport mode have to be be
691 	 * passed to pf explicitly.  In tunnel mode the inner IP header will
692 	 * run through ip_input() and pf anyway.
693 	 */
694 	if ((tdbp->tdb_flags & TDBF_TUNNELING) == 0) {
695 		struct ifnet *ifp;
696 
697 		/* This is the enc0 interface unless for ipcomp. */
698 		if ((ifp = if_get(m->m_pkthdr.ph_ifidx)) == NULL) {
699 			m_freem(m);
700 			return -1;
701 		}
702 		if (pf_test(af, PF_IN, ifp, &m) != PF_PASS) {
703 			if_put(ifp);
704 			m_freem(m);
705 			return -1;
706 		}
707 		if_put(ifp);
708 		if (m == NULL)
709 			return -1;
710 	}
711 #endif
712 	/* Call the appropriate IPsec transform callback. */
713 	ip_deliver(&m, &skip, prot, af);
714 	return 0;
715 #undef IPSEC_ISTAT
716 }
717 
718 int
719 ipsec_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
720     size_t newlen)
721 {
722 	int error;
723 
724 	switch (name[0]) {
725 	case IPCTL_IPSEC_ENC_ALGORITHM:
726 		NET_LOCK();
727 		error = sysctl_tstring(oldp, oldlenp, newp, newlen,
728 		    ipsec_def_enc, sizeof(ipsec_def_enc));
729 		NET_UNLOCK();
730 		return (error);
731 	case IPCTL_IPSEC_AUTH_ALGORITHM:
732 		NET_LOCK();
733 		error = sysctl_tstring(oldp, oldlenp, newp, newlen,
734 		    ipsec_def_auth, sizeof(ipsec_def_auth));
735 		NET_UNLOCK();
736 		return (error);
737 	case IPCTL_IPSEC_IPCOMP_ALGORITHM:
738 		NET_LOCK();
739 		error = sysctl_tstring(oldp, oldlenp, newp, newlen,
740 		    ipsec_def_comp, sizeof(ipsec_def_comp));
741 		NET_UNLOCK();
742 		return (error);
743 	case IPCTL_IPSEC_STATS:
744 		return (ipsec_sysctl_ipsecstat(oldp, oldlenp, newp));
745 	default:
746 		NET_LOCK();
747 		error = sysctl_int_arr(ipsecctl_vars, nitems(ipsecctl_vars),
748 		    name, namelen, oldp, oldlenp, newp, newlen);
749 		NET_UNLOCK();
750 		return (error);
751 	}
752 }
753 
754 int
755 esp_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
756     size_t newlen)
757 {
758 	int error;
759 
760 	/* All sysctl names at this level are terminal. */
761 	if (namelen != 1)
762 		return (ENOTDIR);
763 
764 	switch (name[0]) {
765 	case ESPCTL_STATS:
766 		return (esp_sysctl_espstat(oldp, oldlenp, newp));
767 	default:
768 		NET_LOCK();
769 		error = sysctl_int_arr(espctl_vars, nitems(espctl_vars), name,
770 		    namelen, oldp, oldlenp, newp, newlen);
771 		NET_UNLOCK();
772 		return (error);
773 	}
774 }
775 
776 int
777 esp_sysctl_espstat(void *oldp, size_t *oldlenp, void *newp)
778 {
779 	struct espstat espstat;
780 
781 	CTASSERT(sizeof(espstat) == (esps_ncounters * sizeof(uint64_t)));
782 	memset(&espstat, 0, sizeof espstat);
783 	counters_read(espcounters, (uint64_t *)&espstat, esps_ncounters);
784 	return (sysctl_rdstruct(oldp, oldlenp, newp, &espstat,
785 	    sizeof(espstat)));
786 }
787 
788 int
789 ah_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
790     size_t newlen)
791 {
792 	int error;
793 
794 	/* All sysctl names at this level are terminal. */
795 	if (namelen != 1)
796 		return (ENOTDIR);
797 
798 	switch (name[0]) {
799 	case AHCTL_STATS:
800 		return ah_sysctl_ahstat(oldp, oldlenp, newp);
801 	default:
802 		NET_LOCK();
803 		error = sysctl_int_arr(ahctl_vars, nitems(ahctl_vars), name,
804 		    namelen, oldp, oldlenp, newp, newlen);
805 		NET_UNLOCK();
806 		return (error);
807 	}
808 }
809 
810 int
811 ah_sysctl_ahstat(void *oldp, size_t *oldlenp, void *newp)
812 {
813 	struct ahstat ahstat;
814 
815 	CTASSERT(sizeof(ahstat) == (ahs_ncounters * sizeof(uint64_t)));
816 	memset(&ahstat, 0, sizeof ahstat);
817 	counters_read(ahcounters, (uint64_t *)&ahstat, ahs_ncounters);
818 	return (sysctl_rdstruct(oldp, oldlenp, newp, &ahstat, sizeof(ahstat)));
819 }
820 
821 int
822 ipcomp_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
823     size_t newlen)
824 {
825 	int error;
826 
827 	/* All sysctl names at this level are terminal. */
828 	if (namelen != 1)
829 		return (ENOTDIR);
830 
831 	switch (name[0]) {
832 	case IPCOMPCTL_STATS:
833 		return ipcomp_sysctl_ipcompstat(oldp, oldlenp, newp);
834 	default:
835 		NET_LOCK();
836 		error = sysctl_int_arr(ipcompctl_vars, nitems(ipcompctl_vars), name,
837 		    namelen, oldp, oldlenp, newp, newlen);
838 		NET_UNLOCK();
839 		return (error);
840 	}
841 }
842 
843 int
844 ipcomp_sysctl_ipcompstat(void *oldp, size_t *oldlenp, void *newp)
845 {
846 	struct ipcompstat ipcompstat;
847 
848 	CTASSERT(sizeof(ipcompstat) == (ipcomps_ncounters * sizeof(uint64_t)));
849 	memset(&ipcompstat, 0, sizeof ipcompstat);
850 	counters_read(ipcompcounters, (uint64_t *)&ipcompstat,
851 	    ipcomps_ncounters);
852 	return (sysctl_rdstruct(oldp, oldlenp, newp, &ipcompstat,
853 	    sizeof(ipcompstat)));
854 }
855 
856 int
857 ipsec_sysctl_ipsecstat(void *oldp, size_t *oldlenp, void *newp)
858 {
859 	struct ipsecstat ipsecstat;
860 
861 	CTASSERT(sizeof(ipsecstat) == (ipsec_ncounters * sizeof(uint64_t)));
862 	memset(&ipsecstat, 0, sizeof ipsecstat);
863 	counters_read(ipseccounters, (uint64_t *)&ipsecstat, ipsec_ncounters);
864 	return (sysctl_rdstruct(oldp, oldlenp, newp, &ipsecstat,
865 	    sizeof(ipsecstat)));
866 }
867 
868 /* IPv4 AH wrapper. */
869 int
870 ah4_input(struct mbuf **mp, int *offp, int proto, int af)
871 {
872 	if (
873 #if NPF > 0
874 	    ((*mp)->m_pkthdr.pf.flags & PF_TAG_DIVERTED) ||
875 #endif
876 	    !ah_enable)
877 		return rip_input(mp, offp, proto, af);
878 
879 	ipsec_common_input(*mp, *offp, offsetof(struct ip, ip_p), AF_INET,
880 	    proto, 0);
881 	return IPPROTO_DONE;
882 }
883 
884 void
885 ah4_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *v)
886 {
887 	if (sa->sa_family != AF_INET ||
888 	    sa->sa_len != sizeof(struct sockaddr_in))
889 		return;
890 
891 	ipsec_common_ctlinput(rdomain, cmd, sa, v, IPPROTO_AH);
892 }
893 
894 /* IPv4 ESP wrapper. */
895 int
896 esp4_input(struct mbuf **mp, int *offp, int proto, int af)
897 {
898 	if (
899 #if NPF > 0
900 	    ((*mp)->m_pkthdr.pf.flags & PF_TAG_DIVERTED) ||
901 #endif
902 	    !esp_enable)
903 		return rip_input(mp, offp, proto, af);
904 
905 	ipsec_common_input(*mp, *offp, offsetof(struct ip, ip_p), AF_INET,
906 	    proto, 0);
907 	return IPPROTO_DONE;
908 }
909 
910 /* IPv4 IPCOMP wrapper */
911 int
912 ipcomp4_input(struct mbuf **mp, int *offp, int proto, int af)
913 {
914 	if (
915 #if NPF > 0
916 	    ((*mp)->m_pkthdr.pf.flags & PF_TAG_DIVERTED) ||
917 #endif
918 	    !ipcomp_enable)
919 		return rip_input(mp, offp, proto, af);
920 
921 	ipsec_common_input(*mp, *offp, offsetof(struct ip, ip_p), AF_INET,
922 	    proto, 0);
923 	return IPPROTO_DONE;
924 }
925 
926 void
927 ipsec_common_ctlinput(u_int rdomain, int cmd, struct sockaddr *sa,
928     void *v, int proto)
929 {
930 	struct ip *ip = v;
931 
932 	if (cmd == PRC_MSGSIZE && ip && ip_mtudisc && ip->ip_v == 4) {
933 		struct tdb *tdbp;
934 		struct sockaddr_in dst;
935 		struct icmp *icp;
936 		int hlen = ip->ip_hl << 2;
937 		u_int32_t spi, mtu;
938 		ssize_t adjust;
939 
940 		/* Find the right MTU. */
941 		icp = (struct icmp *)((caddr_t) ip -
942 		    offsetof(struct icmp, icmp_ip));
943 		mtu = ntohs(icp->icmp_nextmtu);
944 
945 		/*
946 		 * Ignore the packet, if we do not receive a MTU
947 		 * or the MTU is too small to be acceptable.
948 		 */
949 		if (mtu < 296)
950 			return;
951 
952 		memset(&dst, 0, sizeof(struct sockaddr_in));
953 		dst.sin_family = AF_INET;
954 		dst.sin_len = sizeof(struct sockaddr_in);
955 		dst.sin_addr.s_addr = ip->ip_dst.s_addr;
956 
957 		memcpy(&spi, (caddr_t)ip + hlen, sizeof(u_int32_t));
958 
959 		tdbp = gettdb_rev(rdomain, spi, (union sockaddr_union *)&dst,
960 		    proto);
961 		if (tdbp == NULL || tdbp->tdb_flags & TDBF_INVALID)
962 			return;
963 
964 		/* Walk the chain backwards to the first tdb */
965 		NET_ASSERT_LOCKED();
966 		for (; tdbp; tdbp = tdbp->tdb_inext) {
967 			if (tdbp->tdb_flags & TDBF_INVALID ||
968 			    (adjust = ipsec_hdrsz(tdbp)) == -1)
969 				return;
970 
971 			mtu -= adjust;
972 
973 			/* Store adjusted MTU in tdb */
974 			tdbp->tdb_mtu = mtu;
975 			tdbp->tdb_mtutimeout = gettime() +
976 			    ip_mtudisc_timeout;
977 			DPRINTF(("%s: spi %08x mtu %d adjust %ld\n", __func__,
978 			    ntohl(tdbp->tdb_spi), tdbp->tdb_mtu,
979 			    adjust));
980 		}
981 	}
982 }
983 
984 void
985 udpencap_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *v)
986 {
987 	struct ip *ip = v;
988 	struct tdb *tdbp;
989 	struct icmp *icp;
990 	u_int32_t mtu;
991 	ssize_t adjust;
992 	struct sockaddr_in dst, src;
993 	union sockaddr_union *su_dst, *su_src;
994 
995 	NET_ASSERT_LOCKED();
996 
997 	icp = (struct icmp *)((caddr_t) ip - offsetof(struct icmp, icmp_ip));
998 	mtu = ntohs(icp->icmp_nextmtu);
999 
1000 	/*
1001 	 * Ignore the packet, if we do not receive a MTU
1002 	 * or the MTU is too small to be acceptable.
1003 	 */
1004 	if (mtu < 296)
1005 		return;
1006 
1007 	memset(&dst, 0, sizeof(dst));
1008 	dst.sin_family = AF_INET;
1009 	dst.sin_len = sizeof(struct sockaddr_in);
1010 	dst.sin_addr.s_addr = ip->ip_dst.s_addr;
1011 	su_dst = (union sockaddr_union *)&dst;
1012 	memset(&src, 0, sizeof(src));
1013 	src.sin_family = AF_INET;
1014 	src.sin_len = sizeof(struct sockaddr_in);
1015 	src.sin_addr.s_addr = ip->ip_src.s_addr;
1016 	su_src = (union sockaddr_union *)&src;
1017 
1018 	tdbp = gettdbbysrcdst_rev(rdomain, 0, su_src, su_dst,
1019 	    IPPROTO_ESP);
1020 
1021 	for (; tdbp != NULL; tdbp = tdbp->tdb_snext) {
1022 		if (tdbp->tdb_sproto == IPPROTO_ESP &&
1023 		    ((tdbp->tdb_flags & (TDBF_INVALID|TDBF_UDPENCAP)) ==
1024 		    TDBF_UDPENCAP) &&
1025 		    !memcmp(&tdbp->tdb_dst, &dst, su_dst->sa.sa_len) &&
1026 		    !memcmp(&tdbp->tdb_src, &src, su_src->sa.sa_len)) {
1027 			if ((adjust = ipsec_hdrsz(tdbp)) != -1) {
1028 				/* Store adjusted MTU in tdb */
1029 				tdbp->tdb_mtu = mtu - adjust;
1030 				tdbp->tdb_mtutimeout = gettime() +
1031 				    ip_mtudisc_timeout;
1032 				DPRINTF(("%s: spi %08x mtu %d adjust %ld\n",
1033 				    __func__,
1034 				    ntohl(tdbp->tdb_spi), tdbp->tdb_mtu,
1035 				    adjust));
1036 			}
1037 		}
1038 	}
1039 }
1040 
1041 void
1042 esp4_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *v)
1043 {
1044 	if (sa->sa_family != AF_INET ||
1045 	    sa->sa_len != sizeof(struct sockaddr_in))
1046 		return;
1047 
1048 	ipsec_common_ctlinput(rdomain, cmd, sa, v, IPPROTO_ESP);
1049 }
1050 
1051 #ifdef INET6
1052 /* IPv6 AH wrapper. */
1053 int
1054 ah6_input(struct mbuf **mp, int *offp, int proto, int af)
1055 {
1056 	int l = 0;
1057 	int protoff, nxt;
1058 	struct ip6_ext ip6e;
1059 
1060 	if (
1061 #if NPF > 0
1062 	    ((*mp)->m_pkthdr.pf.flags & PF_TAG_DIVERTED) ||
1063 #endif
1064 	    !ah_enable)
1065 		return rip6_input(mp, offp, proto, af);
1066 
1067 	if (*offp < sizeof(struct ip6_hdr)) {
1068 		DPRINTF(("%s: bad offset\n", __func__));
1069 		ahstat_inc(ahs_hdrops);
1070 		m_freemp(mp);
1071 		return IPPROTO_DONE;
1072 	} else if (*offp == sizeof(struct ip6_hdr)) {
1073 		protoff = offsetof(struct ip6_hdr, ip6_nxt);
1074 	} else {
1075 		/* Chase down the header chain... */
1076 		protoff = sizeof(struct ip6_hdr);
1077 		nxt = (mtod(*mp, struct ip6_hdr *))->ip6_nxt;
1078 
1079 		do {
1080 			protoff += l;
1081 			m_copydata(*mp, protoff, sizeof(ip6e),
1082 			    (caddr_t) &ip6e);
1083 
1084 			if (nxt == IPPROTO_AH)
1085 				l = (ip6e.ip6e_len + 2) << 2;
1086 			else
1087 				l = (ip6e.ip6e_len + 1) << 3;
1088 #ifdef DIAGNOSTIC
1089 			if (l <= 0)
1090 				panic("ah6_input: l went zero or negative");
1091 #endif
1092 
1093 			nxt = ip6e.ip6e_nxt;
1094 		} while (protoff + l < *offp);
1095 
1096 		/* Malformed packet check */
1097 		if (protoff + l != *offp) {
1098 			DPRINTF(("%s: bad packet header chain\n", __func__));
1099 			ahstat_inc(ahs_hdrops);
1100 			m_freemp(mp);
1101 			return IPPROTO_DONE;
1102 		}
1103 		protoff += offsetof(struct ip6_ext, ip6e_nxt);
1104 	}
1105 	ipsec_common_input(*mp, *offp, protoff, AF_INET6, proto, 0);
1106 	return IPPROTO_DONE;
1107 }
1108 
1109 /* IPv6 ESP wrapper. */
1110 int
1111 esp6_input(struct mbuf **mp, int *offp, int proto, int af)
1112 {
1113 	int l = 0;
1114 	int protoff, nxt;
1115 	struct ip6_ext ip6e;
1116 
1117 	if (
1118 #if NPF > 0
1119 	    ((*mp)->m_pkthdr.pf.flags & PF_TAG_DIVERTED) ||
1120 #endif
1121 	    !esp_enable)
1122 		return rip6_input(mp, offp, proto, af);
1123 
1124 	if (*offp < sizeof(struct ip6_hdr)) {
1125 		DPRINTF(("%s: bad offset\n", __func__));
1126 		espstat_inc(esps_hdrops);
1127 		m_freemp(mp);
1128 		return IPPROTO_DONE;
1129 	} else if (*offp == sizeof(struct ip6_hdr)) {
1130 		protoff = offsetof(struct ip6_hdr, ip6_nxt);
1131 	} else {
1132 		/* Chase down the header chain... */
1133 		protoff = sizeof(struct ip6_hdr);
1134 		nxt = (mtod(*mp, struct ip6_hdr *))->ip6_nxt;
1135 
1136 		do {
1137 			protoff += l;
1138 			m_copydata(*mp, protoff, sizeof(ip6e),
1139 			    (caddr_t) &ip6e);
1140 
1141 			if (nxt == IPPROTO_AH)
1142 				l = (ip6e.ip6e_len + 2) << 2;
1143 			else
1144 				l = (ip6e.ip6e_len + 1) << 3;
1145 #ifdef DIAGNOSTIC
1146 			if (l <= 0)
1147 				panic("esp6_input: l went zero or negative");
1148 #endif
1149 
1150 			nxt = ip6e.ip6e_nxt;
1151 		} while (protoff + l < *offp);
1152 
1153 		/* Malformed packet check */
1154 		if (protoff + l != *offp) {
1155 			DPRINTF(("%s: bad packet header chain\n", __func__));
1156 			espstat_inc(esps_hdrops);
1157 			m_freemp(mp);
1158 			return IPPROTO_DONE;
1159 		}
1160 		protoff += offsetof(struct ip6_ext, ip6e_nxt);
1161 	}
1162 	ipsec_common_input(*mp, *offp, protoff, AF_INET6, proto, 0);
1163 	return IPPROTO_DONE;
1164 
1165 }
1166 
1167 /* IPv6 IPcomp wrapper */
1168 int
1169 ipcomp6_input(struct mbuf **mp, int *offp, int proto, int af)
1170 {
1171 	int l = 0;
1172 	int protoff, nxt;
1173 	struct ip6_ext ip6e;
1174 
1175 	if (
1176 #if NPF > 0
1177 	    ((*mp)->m_pkthdr.pf.flags & PF_TAG_DIVERTED) ||
1178 #endif
1179 	    !ipcomp_enable)
1180 		return rip6_input(mp, offp, proto, af);
1181 
1182 	if (*offp < sizeof(struct ip6_hdr)) {
1183 		DPRINTF(("%s: bad offset\n", __func__));
1184 		ipcompstat_inc(ipcomps_hdrops);
1185 		m_freemp(mp);
1186 		return IPPROTO_DONE;
1187 	} else if (*offp == sizeof(struct ip6_hdr)) {
1188 		protoff = offsetof(struct ip6_hdr, ip6_nxt);
1189 	} else {
1190 		/* Chase down the header chain... */
1191 		protoff = sizeof(struct ip6_hdr);
1192 		nxt = (mtod(*mp, struct ip6_hdr *))->ip6_nxt;
1193 
1194 		do {
1195 			protoff += l;
1196 			m_copydata(*mp, protoff, sizeof(ip6e),
1197 			    (caddr_t) &ip6e);
1198 			if (nxt == IPPROTO_AH)
1199 				l = (ip6e.ip6e_len + 2) << 2;
1200 			else
1201 				l = (ip6e.ip6e_len + 1) << 3;
1202 #ifdef DIAGNOSTIC
1203 			if (l <= 0)
1204 				panic("l went zero or negative");
1205 #endif
1206 
1207 			nxt = ip6e.ip6e_nxt;
1208 		} while (protoff + l < *offp);
1209 
1210 		/* Malformed packet check */
1211 		if (protoff + l != *offp) {
1212 			DPRINTF(("%s: bad packet header chain\n", __func__));
1213 			ipcompstat_inc(ipcomps_hdrops);
1214 			m_freemp(mp);
1215 			return IPPROTO_DONE;
1216 		}
1217 
1218 		protoff += offsetof(struct ip6_ext, ip6e_nxt);
1219 	}
1220 	ipsec_common_input(*mp, *offp, protoff, AF_INET6, proto, 0);
1221 	return IPPROTO_DONE;
1222 }
1223 #endif /* INET6 */
1224 
1225 int
1226 ipsec_forward_check(struct mbuf *m, int hlen, int af)
1227 {
1228 	struct tdb *tdb;
1229 	struct tdb_ident *tdbi;
1230 	struct m_tag *mtag;
1231 	int error = 0;
1232 
1233 	/*
1234 	 * IPsec policy check for forwarded packets. Look at
1235 	 * inner-most IPsec SA used.
1236 	 */
1237 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
1238 	if (mtag != NULL) {
1239 		tdbi = (struct tdb_ident *)(mtag + 1);
1240 		tdb = gettdb(tdbi->rdomain, tdbi->spi, &tdbi->dst, tdbi->proto);
1241 	} else
1242 		tdb = NULL;
1243 	ipsp_spd_lookup(m, af, hlen, &error, IPSP_DIRECTION_IN, tdb, NULL, 0);
1244 
1245 	return error;
1246 }
1247 
1248 int
1249 ipsec_local_check(struct mbuf *m, int hlen, int proto, int af)
1250 {
1251 	struct tdb *tdb;
1252 	struct tdb_ident *tdbi;
1253 	struct m_tag *mtag;
1254 	int error = 0;
1255 
1256 	/*
1257 	 * If it's a protected packet for us, skip the policy check.
1258 	 * That's because we really only care about the properties of
1259 	 * the protected packet, and not the intermediate versions.
1260 	 * While this is not the most paranoid setting, it allows
1261 	 * some flexibility in handling nested tunnels (in setting up
1262 	 * the policies).
1263 	 */
1264 	if ((proto == IPPROTO_ESP) || (proto == IPPROTO_AH) ||
1265 	    (proto == IPPROTO_IPCOMP))
1266 		return 0;
1267 
1268 	/*
1269 	 * If the protected packet was tunneled, then we need to
1270 	 * verify the protected packet's information, not the
1271 	 * external headers. Thus, skip the policy lookup for the
1272 	 * external packet, and keep the IPsec information linked on
1273 	 * the packet header (the encapsulation routines know how
1274 	 * to deal with that).
1275 	 */
1276 	if ((proto == IPPROTO_IPV4) || (proto == IPPROTO_IPV6))
1277 		return 0;
1278 
1279 	/*
1280 	 * When processing IPv6 header chains, do not look at the
1281 	 * outer header.  The inner protocol is relevant and will
1282 	 * be checked by the local delivery loop later.
1283 	 */
1284 	if ((af == AF_INET6) && ((proto == IPPROTO_DSTOPTS) ||
1285 	    (proto == IPPROTO_ROUTING) || (proto == IPPROTO_FRAGMENT)))
1286 		return 0;
1287 
1288 	/*
1289 	 * If the protected packet is TCP or UDP, we'll do the
1290 	 * policy check in the respective input routine, so we can
1291 	 * check for bypass sockets.
1292 	 */
1293 	if ((proto == IPPROTO_TCP) || (proto == IPPROTO_UDP))
1294 		return 0;
1295 
1296 	/*
1297 	 * IPsec policy check for local-delivery packets. Look at the
1298 	 * inner-most SA that protected the packet. This is in fact
1299 	 * a bit too restrictive (it could end up causing packets to
1300 	 * be dropped that semantically follow the policy, e.g., in
1301 	 * certain SA-bundle configurations); but the alternative is
1302 	 * very complicated (and requires keeping track of what
1303 	 * kinds of tunneling headers have been seen in-between the
1304 	 * IPsec headers), and I don't think we lose much functionality
1305 	 * that's needed in the real world (who uses bundles anyway ?).
1306 	 */
1307 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
1308 	if (mtag) {
1309 		tdbi = (struct tdb_ident *)(mtag + 1);
1310 		tdb = gettdb(tdbi->rdomain, tdbi->spi, &tdbi->dst,
1311 		    tdbi->proto);
1312 	} else
1313 		tdb = NULL;
1314 	ipsp_spd_lookup(m, af, hlen, &error, IPSP_DIRECTION_IN,
1315 	    tdb, NULL, 0);
1316 
1317 	return error;
1318 }
1319