xref: /freebsd/sys/netipsec/ipsec_input.c (revision e9e8876a4d6afc1ad5315faaa191b25121a813d7)
1 /*	$OpenBSD: ipsec_input.c,v 1.63 2003/02/20 18:35:43 deraadt 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  * Copyright (c) 2016 Andrey V. Elsukov <ae@FreeBSD.org>
22  *
23  * Permission to use, copy, and modify this software with or without fee
24  * is hereby granted, provided that this entire notice is included in
25  * all copies of any software which is or includes a copy or
26  * modification of this software.
27  * You may use this code under the GNU public license if you so wish. Please
28  * contribute changes back to the authors under this freer than GPL license
29  * so that we may further the use of strong encryption without limitations to
30  * all.
31  *
32  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
33  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
34  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
35  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
36  * PURPOSE.
37  */
38 
39 /*
40  * IPsec input processing.
41  */
42 
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 #include "opt_inet.h"
47 #include "opt_inet6.h"
48 #include "opt_ipsec.h"
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/malloc.h>
53 #include <sys/mbuf.h>
54 #include <sys/domain.h>
55 #include <sys/protosw.h>
56 #include <sys/socket.h>
57 #include <sys/errno.h>
58 #include <sys/hhook.h>
59 #include <sys/syslog.h>
60 
61 #include <net/if.h>
62 #include <net/if_var.h>
63 #include <net/if_enc.h>
64 #include <net/netisr.h>
65 #include <net/vnet.h>
66 
67 #include <netinet/in.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/ip_icmp.h>
72 #include <netinet/in_var.h>
73 #include <netinet/tcp_var.h>
74 
75 #include <netinet/ip6.h>
76 #ifdef INET6
77 #include <netinet6/ip6_var.h>
78 #endif
79 #include <netinet/in_pcb.h>
80 #ifdef INET6
81 #include <netinet/icmp6.h>
82 #endif
83 
84 #include <netipsec/ipsec.h>
85 #ifdef INET6
86 #include <netipsec/ipsec6.h>
87 #endif
88 #include <netipsec/ah_var.h>
89 #include <netipsec/esp.h>
90 #include <netipsec/esp_var.h>
91 #include <netipsec/ipcomp_var.h>
92 
93 #include <netipsec/key.h>
94 #include <netipsec/keydb.h>
95 #include <netipsec/key_debug.h>
96 
97 #include <netipsec/xform.h>
98 #include <netinet6/ip6protosw.h>
99 
100 #include <machine/in_cksum.h>
101 #include <machine/stdarg.h>
102 
103 #define	IPSEC_ISTAT(proto, name)	do {	\
104 	if ((proto) == IPPROTO_ESP)		\
105 		ESPSTAT_INC(esps_##name);	\
106 	else if ((proto) == IPPROTO_AH)		\
107 		AHSTAT_INC(ahs_##name);		\
108 	else					\
109 		IPCOMPSTAT_INC(ipcomps_##name);	\
110 } while (0)
111 
112 /*
113  * ipsec_common_input gets called when an IPsec-protected packet
114  * is received by IPv4 or IPv6.  Its job is to find the right SA
115  * and call the appropriate transform.  The transform callback
116  * takes care of further processing (like ingress filtering).
117  */
118 static int
119 ipsec_common_input(struct mbuf *m, int skip, int protoff, int af, int sproto)
120 {
121 	IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
122 	union sockaddr_union dst_address;
123 	struct secasvar *sav;
124 	uint32_t spi;
125 	int error;
126 
127 	IPSEC_ISTAT(sproto, input);
128 
129 	IPSEC_ASSERT(m != NULL, ("null packet"));
130 
131 	IPSEC_ASSERT(sproto == IPPROTO_ESP || sproto == IPPROTO_AH ||
132 		sproto == IPPROTO_IPCOMP,
133 		("unexpected security protocol %u", sproto));
134 
135 	if ((sproto == IPPROTO_ESP && !V_esp_enable) ||
136 	    (sproto == IPPROTO_AH && !V_ah_enable) ||
137 	    (sproto == IPPROTO_IPCOMP && !V_ipcomp_enable)) {
138 		m_freem(m);
139 		IPSEC_ISTAT(sproto, pdrops);
140 		return EOPNOTSUPP;
141 	}
142 
143 	if (m->m_pkthdr.len - skip < 2 * sizeof (u_int32_t)) {
144 		m_freem(m);
145 		IPSEC_ISTAT(sproto, hdrops);
146 		DPRINTF(("%s: packet too small\n", __func__));
147 		return EINVAL;
148 	}
149 
150 	/* Retrieve the SPI from the relevant IPsec header */
151 	if (sproto == IPPROTO_ESP)
152 		m_copydata(m, skip, sizeof(u_int32_t), (caddr_t) &spi);
153 	else if (sproto == IPPROTO_AH)
154 		m_copydata(m, skip + sizeof(u_int32_t), sizeof(u_int32_t),
155 		    (caddr_t) &spi);
156 	else if (sproto == IPPROTO_IPCOMP) {
157 		u_int16_t cpi;
158 		m_copydata(m, skip + sizeof(u_int16_t), sizeof(u_int16_t),
159 		    (caddr_t) &cpi);
160 		spi = ntohl(htons(cpi));
161 	}
162 
163 	/*
164 	 * Find the SA and (indirectly) call the appropriate
165 	 * kernel crypto routine. The resulting mbuf chain is a valid
166 	 * IP packet ready to go through input processing.
167 	 */
168 	bzero(&dst_address, sizeof (dst_address));
169 	dst_address.sa.sa_family = af;
170 	switch (af) {
171 #ifdef INET
172 	case AF_INET:
173 		dst_address.sin.sin_len = sizeof(struct sockaddr_in);
174 		m_copydata(m, offsetof(struct ip, ip_dst),
175 		    sizeof(struct in_addr),
176 		    (caddr_t) &dst_address.sin.sin_addr);
177 		break;
178 #endif /* INET */
179 #ifdef INET6
180 	case AF_INET6:
181 		dst_address.sin6.sin6_len = sizeof(struct sockaddr_in6);
182 		m_copydata(m, offsetof(struct ip6_hdr, ip6_dst),
183 		    sizeof(struct in6_addr),
184 		    (caddr_t) &dst_address.sin6.sin6_addr);
185 		/* We keep addresses in SADB without embedded scope id */
186 		if (IN6_IS_SCOPE_LINKLOCAL(&dst_address.sin6.sin6_addr)) {
187 			/* XXX: sa6_recoverscope() */
188 			dst_address.sin6.sin6_scope_id =
189 			    ntohs(dst_address.sin6.sin6_addr.s6_addr16[1]);
190 			dst_address.sin6.sin6_addr.s6_addr16[1] = 0;
191 		}
192 		break;
193 #endif /* INET6 */
194 	default:
195 		DPRINTF(("%s: unsupported protocol family %u\n", __func__, af));
196 		m_freem(m);
197 		IPSEC_ISTAT(sproto, nopf);
198 		return EPFNOSUPPORT;
199 	}
200 
201 	/* NB: only pass dst since key_allocsa follows RFC2401 */
202 	sav = key_allocsa(&dst_address, sproto, spi);
203 	if (sav == NULL) {
204 		DPRINTF(("%s: no key association found for SA %s/%08lx/%u\n",
205 		    __func__, ipsec_address(&dst_address, buf, sizeof(buf)),
206 		    (u_long) ntohl(spi), sproto));
207 		IPSEC_ISTAT(sproto, notdb);
208 		m_freem(m);
209 		return ENOENT;
210 	}
211 
212 	if (sav->tdb_xform == NULL) {
213 		DPRINTF(("%s: attempted to use uninitialized SA %s/%08lx/%u\n",
214 		    __func__, ipsec_address(&dst_address, buf, sizeof(buf)),
215 		    (u_long) ntohl(spi), sproto));
216 		IPSEC_ISTAT(sproto, noxform);
217 		key_freesav(&sav);
218 		m_freem(m);
219 		return ENXIO;
220 	}
221 
222 	/*
223 	 * Call appropriate transform and return -- callback takes care of
224 	 * everything else.
225 	 */
226 	error = (*sav->tdb_xform->xf_input)(m, sav, skip, protoff);
227 	return (error);
228 }
229 
230 #ifdef INET
231 extern struct protosw inetsw[];
232 
233 /*
234  * IPSEC_INPUT() method implementation for IPv4.
235  *  0 - Permitted by inbound security policy for further processing.
236  *  EACCES - Forbidden by inbound security policy.
237  *  EINPROGRESS - consumed by IPsec.
238  */
239 int
240 ipsec4_input(struct mbuf *m, int offset, int proto)
241 {
242 
243 	switch (proto) {
244 	case IPPROTO_AH:
245 	case IPPROTO_ESP:
246 	case IPPROTO_IPCOMP:
247 		/* Do inbound IPsec processing for AH/ESP/IPCOMP */
248 		ipsec_common_input(m, offset,
249 		    offsetof(struct ip, ip_p), AF_INET, proto);
250 		return (EINPROGRESS); /* mbuf consumed by IPsec */
251 	default:
252 		/*
253 		 * Protocols with further headers get their IPsec treatment
254 		 * within the protocol specific processing.
255 		 */
256 		if ((inetsw[ip_protox[proto]].pr_flags & PR_LASTHDR) == 0)
257 			return (0);
258 		/* FALLTHROUGH */
259 	};
260 	/*
261 	 * Enforce IPsec policy checking if we are seeing last header.
262 	 */
263 	if (ipsec4_in_reject(m, NULL) != 0) {
264 		/* Forbidden by inbound security policy */
265 		m_freem(m);
266 		return (EACCES);
267 	}
268 	return (0);
269 }
270 
271 int
272 ipsec4_ctlinput(int code, struct sockaddr *sa, void *v)
273 {
274 	struct in_conninfo inc;
275 	struct secasvar *sav;
276 	struct icmp *icp;
277 	struct ip *ip = v;
278 	uint32_t pmtu, spi;
279 	uint8_t proto;
280 
281 	if (code != PRC_MSGSIZE || ip == NULL)
282 		return (EINVAL);
283 	if (sa->sa_family != AF_INET ||
284 	    sa->sa_len != sizeof(struct sockaddr_in))
285 		return (EAFNOSUPPORT);
286 
287 	icp = __containerof(ip, struct icmp, icmp_ip);
288 	pmtu = ntohs(icp->icmp_nextmtu);
289 
290 	if (pmtu < V_ip4_ipsec_min_pmtu)
291 		return (EINVAL);
292 
293 	proto = ip->ip_p;
294 	if (proto != IPPROTO_ESP && proto != IPPROTO_AH &&
295 	    proto != IPPROTO_IPCOMP)
296 		return (EINVAL);
297 
298 	memcpy(&spi, (caddr_t)ip + (ip->ip_hl << 2), sizeof(spi));
299 	sav = key_allocsa((union sockaddr_union *)sa, proto, spi);
300 	if (sav == NULL)
301 		return (ENOENT);
302 
303 	key_freesav(&sav);
304 
305 	memset(&inc, 0, sizeof(inc));
306 	inc.inc_faddr = satosin(sa)->sin_addr;
307 	tcp_hc_updatemtu(&inc, pmtu);
308 	return (0);
309 }
310 
311 /*
312  * IPsec input callback for INET protocols.
313  * This routine is called as the transform callback.
314  * Takes care of filtering and other sanity checks on
315  * the processed packet.
316  */
317 int
318 ipsec4_common_input_cb(struct mbuf *m, struct secasvar *sav, int skip,
319     int protoff)
320 {
321 	IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
322 	struct epoch_tracker et;
323 	struct ipsec_ctx_data ctx;
324 	struct xform_history *xh;
325 	struct secasindex *saidx;
326 	struct m_tag *mtag;
327 	struct ip *ip;
328 	int error, prot, af, sproto, isr_prot;
329 
330 	IPSEC_ASSERT(sav != NULL, ("null SA"));
331 	IPSEC_ASSERT(sav->sah != NULL, ("null SAH"));
332 	saidx = &sav->sah->saidx;
333 	af = saidx->dst.sa.sa_family;
334 	IPSEC_ASSERT(af == AF_INET, ("unexpected af %u", af));
335 	sproto = saidx->proto;
336 	IPSEC_ASSERT(sproto == IPPROTO_ESP || sproto == IPPROTO_AH ||
337 		sproto == IPPROTO_IPCOMP,
338 		("unexpected security protocol %u", sproto));
339 
340 	if (skip != 0) {
341 		/*
342 		 * Fix IPv4 header
343 		 */
344 		if (m->m_len < skip && (m = m_pullup(m, skip)) == NULL) {
345 			DPRINTF(("%s: processing failed for SA %s/%08lx\n",
346 			    __func__, ipsec_address(&sav->sah->saidx.dst,
347 			    buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
348 			IPSEC_ISTAT(sproto, hdrops);
349 			error = ENOBUFS;
350 			goto bad_noepoch;
351 		}
352 
353 		ip = mtod(m, struct ip *);
354 		ip->ip_len = htons(m->m_pkthdr.len);
355 		ip->ip_sum = 0;
356 		ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
357 	} else {
358 		ip = mtod(m, struct ip *);
359 	}
360 	prot = ip->ip_p;
361 	/*
362 	 * Check that we have NAT-T enabled and apply transport mode
363 	 * decapsulation NAT procedure (RFC3948).
364 	 * Do this before invoking into the PFIL.
365 	 */
366 	if (sav->natt != NULL &&
367 	    (prot == IPPROTO_UDP || prot == IPPROTO_TCP))
368 		udp_ipsec_adjust_cksum(m, sav, prot, skip);
369 
370 	/*
371 	 * Needed for ipsec_run_hooks and netisr_queue_src
372 	 */
373 	NET_EPOCH_ENTER(et);
374 
375 	IPSEC_INIT_CTX(&ctx, &m, NULL, sav, AF_INET, IPSEC_ENC_BEFORE);
376 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_IN)) != 0)
377 		goto bad;
378 	ip = mtod(m, struct ip *);	/* update pointer */
379 
380 	/* IP-in-IP encapsulation */
381 	if (prot == IPPROTO_IPIP &&
382 	    saidx->mode != IPSEC_MODE_TRANSPORT) {
383 		if (m->m_pkthdr.len - skip < sizeof(struct ip)) {
384 			IPSEC_ISTAT(sproto, hdrops);
385 			error = EINVAL;
386 			goto bad;
387 		}
388 		/* enc0: strip outer IPv4 header */
389 		m_striphdr(m, 0, ip->ip_hl << 2);
390 	}
391 #ifdef INET6
392 	/* IPv6-in-IP encapsulation. */
393 	else if (prot == IPPROTO_IPV6 &&
394 	    saidx->mode != IPSEC_MODE_TRANSPORT) {
395 		if (m->m_pkthdr.len - skip < sizeof(struct ip6_hdr)) {
396 			IPSEC_ISTAT(sproto, hdrops);
397 			error = EINVAL;
398 			goto bad;
399 		}
400 		/* enc0: strip IPv4 header, keep IPv6 header only */
401 		m_striphdr(m, 0, ip->ip_hl << 2);
402 	}
403 #endif /* INET6 */
404 	else if (prot != IPPROTO_IPV6 && saidx->mode == IPSEC_MODE_ANY) {
405 		/*
406 		 * When mode is wildcard, inner protocol is IPv6 and
407 		 * we have no INET6 support - drop this packet a bit later.
408 		 * In other cases we assume transport mode. Set prot to
409 		 * correctly choose netisr.
410 		 */
411 		prot = IPPROTO_IPIP;
412 	}
413 
414 	/*
415 	 * Record what we've done to the packet (under what SA it was
416 	 * processed).
417 	 */
418 	if (sproto != IPPROTO_IPCOMP) {
419 		mtag = m_tag_get(PACKET_TAG_IPSEC_IN_DONE,
420 		    sizeof(struct xform_history), M_NOWAIT);
421 		if (mtag == NULL) {
422 			DPRINTF(("%s: failed to get tag\n", __func__));
423 			IPSEC_ISTAT(sproto, hdrops);
424 			error = ENOMEM;
425 			goto bad;
426 		}
427 
428 		xh = (struct xform_history *)(mtag + 1);
429 		bcopy(&saidx->dst, &xh->dst, saidx->dst.sa.sa_len);
430 		xh->spi = sav->spi;
431 		xh->proto = sproto;
432 		xh->mode = saidx->mode;
433 		m_tag_prepend(m, mtag);
434 	}
435 
436 	key_sa_recordxfer(sav, m);		/* record data transfer */
437 
438 	/*
439 	 * In transport mode requeue decrypted mbuf back to IPv4 protocol
440 	 * handler. This is necessary to correctly expose rcvif.
441 	 */
442 	if (saidx->mode == IPSEC_MODE_TRANSPORT)
443 		prot = IPPROTO_IPIP;
444 	/*
445 	 * Re-dispatch via software interrupt.
446 	 */
447 	switch (prot) {
448 	case IPPROTO_IPIP:
449 		isr_prot = NETISR_IP;
450 		af = AF_INET;
451 		break;
452 #ifdef INET6
453 	case IPPROTO_IPV6:
454 		isr_prot = NETISR_IPV6;
455 		af = AF_INET6;
456 		break;
457 #endif
458 	default:
459 		DPRINTF(("%s: cannot handle inner ip proto %d\n",
460 			    __func__, prot));
461 		IPSEC_ISTAT(sproto, nopf);
462 		error = EPFNOSUPPORT;
463 		goto bad;
464 	}
465 
466 	IPSEC_INIT_CTX(&ctx, &m, NULL, sav, af, IPSEC_ENC_AFTER);
467 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_IN)) != 0)
468 		goto bad;
469 
470 	/* Handle virtual tunneling interfaces */
471 	if (saidx->mode == IPSEC_MODE_TUNNEL)
472 		error = ipsec_if_input(m, sav, af);
473 	if (error == 0) {
474 		error = netisr_queue_src(isr_prot, (uintptr_t)sav->spi, m);
475 		if (error) {
476 			IPSEC_ISTAT(sproto, qfull);
477 			DPRINTF(("%s: queue full; proto %u packet dropped\n",
478 			    __func__, sproto));
479 		}
480 	}
481 	NET_EPOCH_EXIT(et);
482 	key_freesav(&sav);
483 	return (error);
484 bad:
485 	NET_EPOCH_EXIT(et);
486 bad_noepoch:
487 	key_freesav(&sav);
488 	if (m != NULL)
489 		m_freem(m);
490 	return (error);
491 }
492 #endif /* INET */
493 
494 #ifdef INET6
495 /*
496  * IPSEC_INPUT() method implementation for IPv6.
497  *  0 - Permitted by inbound security policy for further processing.
498  *  EACCES - Forbidden by inbound security policy.
499  *  EINPROGRESS - consumed by IPsec.
500  */
501 int
502 ipsec6_input(struct mbuf *m, int offset, int proto)
503 {
504 
505 	switch (proto) {
506 	case IPPROTO_AH:
507 	case IPPROTO_ESP:
508 	case IPPROTO_IPCOMP:
509 		/* Do inbound IPsec processing for AH/ESP/IPCOMP */
510 		ipsec_common_input(m, offset,
511 		    offsetof(struct ip6_hdr, ip6_nxt), AF_INET6, proto);
512 		return (EINPROGRESS); /* mbuf consumed by IPsec */
513 	default:
514 		/*
515 		 * Protocols with further headers get their IPsec treatment
516 		 * within the protocol specific processing.
517 		 */
518 		if ((inet6sw[ip6_protox[proto]].pr_flags & PR_LASTHDR) == 0)
519 			return (0);
520 		/* FALLTHROUGH */
521 	};
522 	/*
523 	 * Enforce IPsec policy checking if we are seeing last header.
524 	 */
525 	if (ipsec6_in_reject(m, NULL) != 0) {
526 		/* Forbidden by inbound security policy */
527 		m_freem(m);
528 		return (EACCES);
529 	}
530 	return (0);
531 }
532 
533 int
534 ipsec6_ctlinput(int code, struct sockaddr *sa, void *v)
535 {
536 	return (0);
537 }
538 
539 /*
540  * IPsec input callback, called by the transform callback. Takes care of
541  * filtering and other sanity checks on the processed packet.
542  */
543 int
544 ipsec6_common_input_cb(struct mbuf *m, struct secasvar *sav, int skip,
545     int protoff)
546 {
547 	IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
548 	struct epoch_tracker et;
549 	struct ipsec_ctx_data ctx;
550 	struct xform_history *xh;
551 	struct secasindex *saidx;
552 	struct ip6_hdr *ip6;
553 	struct m_tag *mtag;
554 	int prot, af, sproto;
555 	int nxt, isr_prot;
556 	int error, nest;
557 	uint8_t nxt8;
558 
559 	IPSEC_ASSERT(sav != NULL, ("null SA"));
560 	IPSEC_ASSERT(sav->sah != NULL, ("null SAH"));
561 	saidx = &sav->sah->saidx;
562 	af = saidx->dst.sa.sa_family;
563 	IPSEC_ASSERT(af == AF_INET6, ("unexpected af %u", af));
564 	sproto = saidx->proto;
565 	IPSEC_ASSERT(sproto == IPPROTO_ESP || sproto == IPPROTO_AH ||
566 		sproto == IPPROTO_IPCOMP,
567 		("unexpected security protocol %u", sproto));
568 
569 	NET_EPOCH_ENTER(et);
570 
571 	/* Fix IPv6 header */
572 	if (m->m_len < sizeof(struct ip6_hdr) &&
573 	    (m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
574 		DPRINTF(("%s: processing failed for SA %s/%08lx\n",
575 		    __func__, ipsec_address(&sav->sah->saidx.dst, buf,
576 		    sizeof(buf)), (u_long) ntohl(sav->spi)));
577 
578 		IPSEC_ISTAT(sproto, hdrops);
579 		error = EACCES;
580 		goto bad;
581 	}
582 
583 	IPSEC_INIT_CTX(&ctx, &m, NULL, sav, af, IPSEC_ENC_BEFORE);
584 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_IN)) != 0)
585 		goto bad;
586 
587 	ip6 = mtod(m, struct ip6_hdr *);
588 	ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
589 
590 	/* Save protocol */
591 	m_copydata(m, protoff, 1, &nxt8);
592 	prot = nxt8;
593 
594 	/* IPv6-in-IP encapsulation */
595 	if (prot == IPPROTO_IPV6 &&
596 	    saidx->mode != IPSEC_MODE_TRANSPORT) {
597 		if (m->m_pkthdr.len - skip < sizeof(struct ip6_hdr)) {
598 			IPSEC_ISTAT(sproto, hdrops);
599 			error = EINVAL;
600 			goto bad;
601 		}
602 		/* ip6n will now contain the inner IPv6 header. */
603 		m_striphdr(m, 0, skip);
604 		skip = 0;
605 	}
606 #ifdef INET
607 	/* IP-in-IP encapsulation */
608 	else if (prot == IPPROTO_IPIP &&
609 	    saidx->mode != IPSEC_MODE_TRANSPORT) {
610 		if (m->m_pkthdr.len - skip < sizeof(struct ip)) {
611 			IPSEC_ISTAT(sproto, hdrops);
612 			error = EINVAL;
613 			goto bad;
614 		}
615 		/* ipn will now contain the inner IPv4 header */
616 		m_striphdr(m, 0, skip);
617 		skip = 0;
618 	}
619 #endif /* INET */
620 	else {
621 		prot = IPPROTO_IPV6; /* for correct BPF processing */
622 	}
623 
624 	/*
625 	 * Record what we've done to the packet (under what SA it was
626 	 * processed).
627 	 */
628 	if (sproto != IPPROTO_IPCOMP) {
629 		mtag = m_tag_get(PACKET_TAG_IPSEC_IN_DONE,
630 		    sizeof(struct xform_history), M_NOWAIT);
631 		if (mtag == NULL) {
632 			DPRINTF(("%s: failed to get tag\n", __func__));
633 			IPSEC_ISTAT(sproto, hdrops);
634 			error = ENOMEM;
635 			goto bad;
636 		}
637 
638 		xh = (struct xform_history *)(mtag + 1);
639 		bcopy(&saidx->dst, &xh->dst, saidx->dst.sa.sa_len);
640 		xh->spi = sav->spi;
641 		xh->proto = sproto;
642 		xh->mode = saidx->mode;
643 		m_tag_prepend(m, mtag);
644 	}
645 
646 	key_sa_recordxfer(sav, m);
647 
648 #ifdef INET
649 	if (prot == IPPROTO_IPIP)
650 		af = AF_INET;
651 	else
652 #endif
653 		af = AF_INET6;
654 	IPSEC_INIT_CTX(&ctx, &m, NULL, sav, af, IPSEC_ENC_AFTER);
655 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_IN)) != 0)
656 		goto bad;
657 	if (skip == 0) {
658 		/*
659 		 * We stripped outer IPv6 header.
660 		 * Now we should requeue decrypted packet via netisr.
661 		 */
662 		switch (prot) {
663 #ifdef INET
664 		case IPPROTO_IPIP:
665 			isr_prot = NETISR_IP;
666 			break;
667 #endif
668 		case IPPROTO_IPV6:
669 			isr_prot = NETISR_IPV6;
670 			break;
671 		default:
672 			DPRINTF(("%s: cannot handle inner ip proto %d\n",
673 			    __func__, prot));
674 			IPSEC_ISTAT(sproto, nopf);
675 			error = EPFNOSUPPORT;
676 			goto bad;
677 		}
678 		/* Handle virtual tunneling interfaces */
679 		if (saidx->mode == IPSEC_MODE_TUNNEL)
680 			error = ipsec_if_input(m, sav, af);
681 		if (error == 0) {
682 			error = netisr_queue_src(isr_prot,
683 			    (uintptr_t)sav->spi, m);
684 			if (error) {
685 				IPSEC_ISTAT(sproto, qfull);
686 				DPRINTF(("%s: queue full; proto %u packet"
687 				    " dropped\n", __func__, sproto));
688 			}
689 		}
690 		NET_EPOCH_EXIT(et);
691 		key_freesav(&sav);
692 		return (error);
693 	}
694 	/*
695 	 * See the end of ip6_input for this logic.
696 	 * IPPROTO_IPV[46] case will be processed just like other ones
697 	 */
698 	nest = 0;
699 	nxt = nxt8;
700 	while (nxt != IPPROTO_DONE) {
701 		if (V_ip6_hdrnestlimit && (++nest > V_ip6_hdrnestlimit)) {
702 			IP6STAT_INC(ip6s_toomanyhdr);
703 			error = EINVAL;
704 			goto bad;
705 		}
706 
707 		/*
708 		 * Protection against faulty packet - there should be
709 		 * more sanity checks in header chain processing.
710 		 */
711 		if (m->m_pkthdr.len < skip) {
712 			IP6STAT_INC(ip6s_tooshort);
713 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_truncated);
714 			error = EINVAL;
715 			goto bad;
716 		}
717 		/*
718 		 * Enforce IPsec policy checking if we are seeing last header.
719 		 * note that we do not visit this with protocols with pcb layer
720 		 * code - like udp/tcp/raw ip.
721 		 */
722 		if ((inet6sw[ip6_protox[nxt]].pr_flags & PR_LASTHDR) != 0 &&
723 		    ipsec6_in_reject(m, NULL)) {
724 			error = EINVAL;
725 			goto bad;
726 		}
727 		nxt = (*inet6sw[ip6_protox[nxt]].pr_input)(&m, &skip, nxt);
728 	}
729 	NET_EPOCH_EXIT(et);
730 	key_freesav(&sav);
731 	return (0);
732 bad:
733 	NET_EPOCH_EXIT(et);
734 	key_freesav(&sav);
735 	if (m)
736 		m_freem(m);
737 	return (error);
738 }
739 #endif /* INET6 */
740