xref: /netbsd-src/sys/netipsec/ipsec_output.c (revision deb6f0161a9109e7de9b519dc8dfb9478668dcdd)
1 /*	$NetBSD: ipsec_output.c,v 1.81 2018/11/22 04:48:34 knakahara Exp $	*/
2 
3 /*
4  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD: sys/netipsec/ipsec_output.c,v 1.3.2.2 2003/03/28 20:32:53 sam Exp $
29  */
30 
31 #include <sys/cdefs.h>
32 __KERNEL_RCSID(0, "$NetBSD: ipsec_output.c,v 1.81 2018/11/22 04:48:34 knakahara Exp $");
33 
34 #if defined(_KERNEL_OPT)
35 #include "opt_inet.h"
36 #include "opt_net_mpsafe.h"
37 #endif
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/mbuf.h>
42 #include <sys/domain.h>
43 #include <sys/protosw.h>
44 #include <sys/socket.h>
45 #include <sys/errno.h>
46 #include <sys/syslog.h>
47 
48 #include <net/if.h>
49 #include <net/route.h>
50 
51 #include <netinet/in.h>
52 #include <netinet/in_systm.h>
53 #include <netinet/ip.h>
54 #include <netinet/ip_var.h>
55 #include <netinet/in_var.h>
56 #include <netinet/ip_ecn.h>
57 
58 #include <netinet/ip6.h>
59 #ifdef INET6
60 #include <netinet6/ip6_var.h>
61 #endif
62 #include <netinet/in_pcb.h>
63 #ifdef INET6
64 #include <netinet/icmp6.h>
65 #endif
66 #include <netinet/udp.h>
67 
68 #include <netipsec/ipsec.h>
69 #include <netipsec/ipsec_var.h>
70 #include <netipsec/ipsec_private.h>
71 #ifdef INET6
72 #include <netipsec/ipsec6.h>
73 #endif
74 #include <netipsec/ah_var.h>
75 #include <netipsec/esp_var.h>
76 #include <netipsec/ipcomp_var.h>
77 
78 #include <netipsec/xform.h>
79 
80 #include <netipsec/key.h>
81 #include <netipsec/keydb.h>
82 #include <netipsec/key_debug.h>
83 
84 static percpu_t *ipsec_rtcache_percpu __cacheline_aligned;
85 
86 /*
87  * Add a IPSEC_OUT_DONE tag to mark that we have finished the ipsec processing
88  * It will be used by ip{,6}_output to check if we have already or not
89  * processed this packet.
90  */
91 static int
92 ipsec_register_done(struct mbuf *m, int *error)
93 {
94 	struct m_tag *mtag;
95 
96 	mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE, 0, M_NOWAIT);
97 	if (mtag == NULL) {
98 		IPSECLOG(LOG_DEBUG, "could not get packet tag\n");
99 		*error = ENOMEM;
100 		return -1;
101 	}
102 
103 	m_tag_prepend(m, mtag);
104 	return 0;
105 }
106 
107 static int
108 ipsec_reinject_ipstack(struct mbuf *m, int af)
109 {
110 	int rv = -1;
111 	struct route *ro;
112 
113 	KASSERT(af == AF_INET || af == AF_INET6);
114 
115 	KERNEL_LOCK_UNLESS_NET_MPSAFE();
116 	ro = percpu_getref(ipsec_rtcache_percpu);
117 	switch (af) {
118 #ifdef INET
119 	case AF_INET:
120 		rv = ip_output(m, NULL, ro, IP_RAWOUTPUT|IP_NOIPNEWID,
121 		    NULL, NULL);
122 		break;
123 #endif
124 #ifdef INET6
125 	case AF_INET6:
126 		/*
127 		 * We don't need massage, IPv6 header fields are always in
128 		 * net endian.
129 		 */
130 		rv = ip6_output(m, NULL, ro, 0, NULL, NULL, NULL);
131 		break;
132 #endif
133 	}
134 	percpu_putref(ipsec_rtcache_percpu);
135 	KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
136 
137 	return rv;
138 }
139 
140 int
141 ipsec_process_done(struct mbuf *m, const struct ipsecrequest *isr,
142     struct secasvar *sav)
143 {
144 	struct secasindex *saidx;
145 	int error;
146 #ifdef INET
147 	struct ip *ip;
148 #endif
149 #ifdef INET6
150 	struct ip6_hdr *ip6;
151 #endif
152 	struct mbuf *mo;
153 	struct udphdr *udp = NULL;
154 	int hlen, roff, iphlen;
155 
156 	KASSERT(m != NULL);
157 	KASSERT(isr != NULL);
158 	KASSERT(sav != NULL);
159 
160 	saidx = &sav->sah->saidx;
161 
162 	if (sav->natt_type != 0) {
163 		hlen = sizeof(struct udphdr);
164 
165 		switch (saidx->dst.sa.sa_family) {
166 #ifdef INET
167 		case AF_INET:
168 			ip = mtod(m, struct ip *);
169 			mo = m_makespace(m, sizeof(struct ip), hlen, &roff);
170 			iphlen = ip->ip_hl << 2;
171 			break;
172 #endif
173 #ifdef INET6
174 		case AF_INET6:
175 			ip6 = mtod(m, struct ip6_hdr *);
176 			mo = m_makespace(m, sizeof(struct ip6_hdr), hlen, &roff);
177 			iphlen = sizeof(*ip6);
178 			break;
179 #endif
180 		default:
181 			IPSECLOG(LOG_DEBUG, "unknown protocol family %u\n",
182 			    saidx->dst.sa.sa_family);
183 			error = ENXIO;
184 			goto bad;
185 		}
186 
187 		if (mo == NULL) {
188 			char buf[IPSEC_ADDRSTRLEN];
189 			IPSECLOG(LOG_DEBUG,
190 			    "failed to inject %u byte UDP for SA %s/%08lx\n",
191 			    hlen, ipsec_address(&saidx->dst, buf, sizeof(buf)),
192 			    (u_long)ntohl(sav->spi));
193 			error = ENOBUFS;
194 			goto bad;
195 		}
196 
197 		udp = (struct udphdr *)(mtod(mo, char *) + roff);
198 		udp->uh_sport = key_portfromsaddr(&saidx->src);
199 		udp->uh_dport = key_portfromsaddr(&saidx->dst);
200 		udp->uh_sum = 0;
201 		udp->uh_ulen = htons(m->m_pkthdr.len - iphlen);
202 	}
203 
204 	/*
205 	 * Fix the header length, for AH processing.
206 	 */
207 	switch (saidx->dst.sa.sa_family) {
208 #ifdef INET
209 	case AF_INET:
210 		ip = mtod(m, struct ip *);
211 		ip->ip_len = htons(m->m_pkthdr.len);
212 		/* IPv4 packet does not have to be set UDP checksum. */
213 		if (sav->natt_type != 0)
214 			ip->ip_p = IPPROTO_UDP;
215 		break;
216 #endif
217 #ifdef INET6
218 	case AF_INET6:
219 		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
220 			error = ENXIO;
221 			goto bad;
222 		}
223 		if (m->m_pkthdr.len - sizeof(struct ip6_hdr) > IPV6_MAXPACKET) {
224 			/* No jumbogram support. */
225 			error = ENXIO;	/*?*/
226 			goto bad;
227 		}
228 		ip6 = mtod(m, struct ip6_hdr *);
229 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
230 		/* IPv6 packet should be set UDP checksum. */
231 		if (sav->natt_type != 0) {
232 			ip6->ip6_nxt = IPPROTO_UDP;
233 			ipsec6_udp_cksum(m);
234 		}
235 		break;
236 #endif
237 	default:
238 		IPSECLOG(LOG_DEBUG, "unknown protocol family %u\n",
239 		    saidx->dst.sa.sa_family);
240 		error = ENXIO;
241 		goto bad;
242 	}
243 
244 	key_sa_recordxfer(sav, m);
245 
246 	/*
247 	 * If there's another (bundled) SA to apply, do so.
248 	 * Note that this puts a burden on the kernel stack size.
249 	 * If this is a problem we'll need to introduce a queue
250 	 * to set the packet on so we can unwind the stack before
251 	 * doing further processing.
252 	 */
253 	if (isr->next) {
254 		IPSEC_STATINC(IPSEC_STAT_OUT_BUNDLESA);
255 		switch (saidx->dst.sa.sa_family) {
256 #ifdef INET
257 		case AF_INET:
258 			return ipsec4_process_packet(m, isr->next, NULL);
259 #endif
260 #ifdef INET6
261 		case AF_INET6:
262 			return ipsec6_process_packet(m, isr->next);
263 #endif
264 		default:
265 			IPSECLOG(LOG_DEBUG, "unknown protocol family %u\n",
266 			    saidx->dst.sa.sa_family);
267 			error = ENXIO;
268 			goto bad;
269 		}
270 	}
271 
272 	/*
273 	 * We're done with IPsec processing, mark the packet as processed,
274 	 * and transmit it using the appropriate network protocol
275 	 * (IPv4/IPv6).
276 	 */
277 
278 	if (ipsec_register_done(m, &error) < 0)
279 		goto bad;
280 
281 	return ipsec_reinject_ipstack(m, saidx->dst.sa.sa_family);
282 
283 bad:
284 	m_freem(m);
285 	return error;
286 }
287 
288 static void
289 ipsec_fill_saidx_bymbuf(struct secasindex *saidx, const struct mbuf *m,
290     const int af)
291 {
292 
293 	if (af == AF_INET) {
294 		struct sockaddr_in *sin;
295 		struct ip *ip = mtod(m, struct ip *);
296 
297 		if (saidx->src.sa.sa_len == 0) {
298 			sin = &saidx->src.sin;
299 			sin->sin_len = sizeof(*sin);
300 			sin->sin_family = AF_INET;
301 			sin->sin_port = IPSEC_PORT_ANY;
302 			sin->sin_addr = ip->ip_src;
303 		}
304 		if (saidx->dst.sa.sa_len == 0) {
305 			sin = &saidx->dst.sin;
306 			sin->sin_len = sizeof(*sin);
307 			sin->sin_family = AF_INET;
308 			sin->sin_port = IPSEC_PORT_ANY;
309 			sin->sin_addr = ip->ip_dst;
310 		}
311 	} else {
312 		struct sockaddr_in6 *sin6;
313 		struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
314 
315 		if (saidx->src.sin6.sin6_len == 0) {
316 			sin6 = (struct sockaddr_in6 *)&saidx->src;
317 			sin6->sin6_len = sizeof(*sin6);
318 			sin6->sin6_family = AF_INET6;
319 			sin6->sin6_port = IPSEC_PORT_ANY;
320 			sin6->sin6_addr = ip6->ip6_src;
321 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
322 				/* fix scope id for comparing SPD */
323 				sin6->sin6_addr.s6_addr16[1] = 0;
324 				sin6->sin6_scope_id =
325 				    ntohs(ip6->ip6_src.s6_addr16[1]);
326 			}
327 		}
328 		if (saidx->dst.sin6.sin6_len == 0) {
329 			sin6 = (struct sockaddr_in6 *)&saidx->dst;
330 			sin6->sin6_len = sizeof(*sin6);
331 			sin6->sin6_family = AF_INET6;
332 			sin6->sin6_port = IPSEC_PORT_ANY;
333 			sin6->sin6_addr = ip6->ip6_dst;
334 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
335 				/* fix scope id for comparing SPD */
336 				sin6->sin6_addr.s6_addr16[1] = 0;
337 				sin6->sin6_scope_id =
338 				    ntohs(ip6->ip6_dst.s6_addr16[1]);
339 			}
340 		}
341 	}
342 }
343 
344 struct secasvar *
345 ipsec_lookup_sa(const struct ipsecrequest *isr, const struct mbuf *m)
346 {
347 	struct secasindex saidx;
348 
349 	saidx = isr->saidx;
350 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
351 		/* Fillin unspecified SA peers only for transport mode */
352 		ipsec_fill_saidx_bymbuf(&saidx, m, isr->saidx.dst.sa.sa_family);
353 	}
354 
355 	return key_lookup_sa_bysaidx(&saidx);
356 }
357 
358 /*
359  * ipsec_nextisr can return :
360  * - isr == NULL and error != 0 => something is bad : the packet must be
361  *   discarded
362  * - isr == NULL and error == 0 => no more rules to apply, ipsec processing
363  *   is done, reinject it in ip stack
364  * - isr != NULL (error == 0) => we need to apply one rule to the packet
365  */
366 static const struct ipsecrequest *
367 ipsec_nextisr(struct mbuf *m, const struct ipsecrequest *isr, int af,
368     int *error, struct secasvar **ret)
369 {
370 #define	IPSEC_OSTAT(type)						\
371 do {									\
372 	switch (isr->saidx.proto) {					\
373 	case IPPROTO_ESP:						\
374 		ESP_STATINC(ESP_STAT_ ## type);				\
375 		break;							\
376 	case IPPROTO_AH:						\
377 		AH_STATINC(AH_STAT_ ## type);				\
378 		break;							\
379 	default:							\
380 		IPCOMP_STATINC(IPCOMP_STAT_ ## type);			\
381 		break;							\
382 	}								\
383 } while (/*CONSTCOND*/0)
384 
385 	struct secasvar *sav = NULL;
386 	struct secasindex saidx;
387 
388 	KASSERTMSG(af == AF_INET || af == AF_INET6,
389 	    "invalid address family %u", af);
390 again:
391 	/*
392 	 * Craft SA index to search for proper SA.  Note that
393 	 * we only fillin unspecified SA peers for transport
394 	 * mode; for tunnel mode they must already be filled in.
395 	 */
396 	saidx = isr->saidx;
397 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
398 		/* Fillin unspecified SA peers only for transport mode */
399 		ipsec_fill_saidx_bymbuf(&saidx, m, af);
400 	}
401 
402 	/*
403 	 * Lookup SA and validate it.
404 	 */
405 	*error = key_checkrequest(isr, &saidx, &sav);
406 	if (*error != 0) {
407 		/*
408 		 * IPsec processing is required, but no SA found.
409 		 * I assume that key_acquire() had been called
410 		 * to get/establish the SA. Here I discard
411 		 * this packet because it is responsibility for
412 		 * upper layer to retransmit the packet.
413 		 */
414 		IPSEC_STATINC(IPSEC_STAT_OUT_NOSA);
415 		goto bad;
416 	}
417 	/* sav may be NULL here if we have an USE rule */
418 	if (sav == NULL) {
419 		KASSERTMSG(ipsec_get_reqlevel(isr) == IPSEC_LEVEL_USE,
420 		    "no SA found, but required; level %u",
421 		    ipsec_get_reqlevel(isr));
422 		isr = isr->next;
423 		/*
424 		 * No more rules to apply, return NULL isr and no error.
425 		 * It can happen when the last rules are USE rules.
426 		 */
427 		if (isr == NULL) {
428 			*ret = NULL;
429 			*error = 0;
430 			return isr;
431 		}
432 		goto again;
433 	}
434 
435 	/*
436 	 * Check system global policy controls.
437 	 */
438 	if ((isr->saidx.proto == IPPROTO_ESP && !esp_enable) ||
439 	    (isr->saidx.proto == IPPROTO_AH && !ah_enable) ||
440 	    (isr->saidx.proto == IPPROTO_IPCOMP && !ipcomp_enable)) {
441 		IPSECLOG(LOG_DEBUG, "IPsec outbound packet dropped due"
442 		    " to policy (check your sysctls)\n");
443 		IPSEC_OSTAT(PDROPS);
444 		*error = EHOSTUNREACH;
445 		KEY_SA_UNREF(&sav);
446 		goto bad;
447 	}
448 
449 	/*
450 	 * Sanity check the SA contents for the caller
451 	 * before they invoke the xform output method.
452 	 */
453 	KASSERT(sav->tdb_xform != NULL);
454 	*ret = sav;
455 	return isr;
456 
457 bad:
458 	KASSERTMSG(*error != 0, "error return w/ no error code");
459 	return NULL;
460 #undef IPSEC_OSTAT
461 }
462 
463 #ifdef INET
464 /*
465  * IPsec output logic for IPv4.
466  */
467 int
468 ipsec4_process_packet(struct mbuf *m, const struct ipsecrequest *isr,
469     u_long *mtu)
470 {
471 	struct secasvar *sav = NULL;
472 	struct ip *ip;
473 	int s, error, i, off;
474 	union sockaddr_union *dst;
475 	int setdf;
476 
477 	KASSERT(m != NULL);
478 	KASSERT(m->m_nextpkt == NULL);
479 	KASSERT(isr != NULL);
480 
481 	s = splsoftnet();	/* insure SA contents don't change */
482 
483 	isr = ipsec_nextisr(m, isr, AF_INET, &error, &sav);
484 	if (isr == NULL) {
485 		if (error != 0) {
486 			goto bad;
487 		} else {
488 			if (ipsec_register_done(m, &error) < 0)
489 				goto bad;
490 
491 			splx(s);
492 			return ipsec_reinject_ipstack(m, AF_INET);
493 		}
494 	}
495 	KASSERT(sav != NULL);
496 
497 	if (m->m_len < sizeof(struct ip) &&
498 	    (m = m_pullup(m, sizeof(struct ip))) == NULL) {
499 		error = ENOBUFS;
500 		goto unrefsav;
501 	}
502 
503 	/*
504 	 * Check if we need to handle NAT-T fragmentation.
505 	 */
506 	if (isr == isr->sp->req) { /* Check only if called from ipsec4_output */
507 		KASSERT(mtu != NULL);
508 		ip = mtod(m, struct ip *);
509 		if (!(sav->natt_type & UDP_ENCAP_ESPINUDP)) {
510 			goto noneed;
511 		}
512 		if (ntohs(ip->ip_len) <= sav->esp_frag)
513 			goto noneed;
514 		*mtu = sav->esp_frag;
515 		KEY_SA_UNREF(&sav);
516 		splx(s);
517 		return 0;
518 	}
519 noneed:
520 	dst = &sav->sah->saidx.dst;
521 
522 	/*
523 	 * Collect IP_DF state from the outer header.
524 	 */
525 	if (dst->sa.sa_family == AF_INET) {
526 		ip = mtod(m, struct ip *);
527 		/* Honor system-wide control of how to handle IP_DF */
528 		switch (ip4_ipsec_dfbit) {
529 		case 0:			/* clear in outer header */
530 		case 1:			/* set in outer header */
531 			setdf = ip4_ipsec_dfbit;
532 			break;
533 		default:		/* propagate to outer header */
534 			setdf = ip->ip_off;
535 			setdf = ntohs(setdf);
536 			setdf = htons(setdf & IP_DF);
537 			break;
538 		}
539 	} else {
540 		ip = NULL;		/* keep compiler happy */
541 		setdf = 0;
542 	}
543 
544 	/* Do the appropriate encapsulation, if necessary */
545 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
546 	    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
547 	    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
548 	     dst->sin.sin_addr.s_addr != INADDR_ANY &&
549 	     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
550 		struct mbuf *mp;
551 
552 		/* Fix IPv4 header checksum and length */
553 		ip = mtod(m, struct ip *);
554 		ip->ip_len = htons(m->m_pkthdr.len);
555 		ip->ip_sum = 0;
556 		ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
557 
558 		/* Encapsulate the packet */
559 		error = ipip_output(m, sav, &mp);
560 		if (mp == NULL && !error) {
561 			/* Should never happen. */
562 			IPSECLOG(LOG_DEBUG,
563 			    "ipip_output returns no mbuf and no error!");
564 			error = EFAULT;
565 		}
566 		if (error) {
567 			if (mp) {
568 				/* XXX: Should never happen! */
569 				m_freem(mp);
570 			}
571 			m = NULL; /* ipip_output() already freed it */
572 			goto unrefsav;
573 		}
574 		m = mp, mp = NULL;
575 
576 		/*
577 		 * ipip_output clears IP_DF in the new header.  If
578 		 * we need to propagate IP_DF from the outer header,
579 		 * then we have to do it here.
580 		 *
581 		 * XXX shouldn't assume what ipip_output does.
582 		 */
583 		if (dst->sa.sa_family == AF_INET && setdf) {
584 			if (m->m_len < sizeof(struct ip) &&
585 			    (m = m_pullup(m, sizeof(struct ip))) == NULL) {
586 				error = ENOBUFS;
587 				goto unrefsav;
588 			}
589 			ip = mtod(m, struct ip *);
590 			ip->ip_off |= htons(IP_DF);
591 		}
592 	}
593 
594 	/*
595 	 * Dispatch to the appropriate IPsec transform logic.  The
596 	 * packet will be returned for transmission after crypto
597 	 * processing, etc. are completed.  For encapsulation we
598 	 * bypass this call because of the explicit call done above
599 	 * (necessary to deal with IP_DF handling for IPv4).
600 	 *
601 	 * NB: m & sav are ``passed to caller'' who's reponsible for
602 	 *     for reclaiming their resources.
603 	 */
604 	if (sav->tdb_xform->xf_type != XF_IP4) {
605 		if (dst->sa.sa_family == AF_INET) {
606 			ip = mtod(m, struct ip *);
607 			i = ip->ip_hl << 2;
608 			off = offsetof(struct ip, ip_p);
609 		} else {
610 			i = sizeof(struct ip6_hdr);
611 			off = offsetof(struct ip6_hdr, ip6_nxt);
612 		}
613 		error = (*sav->tdb_xform->xf_output)(m, isr, sav, i, off);
614 	} else {
615 		error = ipsec_process_done(m, isr, sav);
616 	}
617 	KEY_SA_UNREF(&sav);
618 	splx(s);
619 	return error;
620 
621 unrefsav:
622 	KEY_SA_UNREF(&sav);
623 bad:
624 	splx(s);
625 	if (m)
626 		m_freem(m);
627 	return error;
628 }
629 #endif
630 
631 #ifdef INET6
632 static int
633 compute_ipsec_pos(struct mbuf *m, int *i, int *off)
634 {
635 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
636 	struct ip6_ext ip6e;
637 	int dstopt = 0;
638 	int nxt;
639 
640 	*i = sizeof(struct ip6_hdr);
641 	*off = offsetof(struct ip6_hdr, ip6_nxt);
642 	nxt = ip6->ip6_nxt;
643 
644 	/*
645 	 * chase mbuf chain to find the appropriate place to
646 	 * put AH/ESP/IPcomp header.
647 	 *     IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
648 	 */
649 	while (1) {
650 		switch (nxt) {
651 		case IPPROTO_AH:
652 		case IPPROTO_ESP:
653 		case IPPROTO_IPCOMP:
654 			/*
655 			 * We should not skip security header added
656 			 * beforehand.
657 			 */
658 			return 0;
659 
660 		case IPPROTO_HOPOPTS:
661 		case IPPROTO_DSTOPTS:
662 		case IPPROTO_ROUTING:
663 			if (*i + sizeof(ip6e) > m->m_pkthdr.len) {
664 				return EINVAL;
665 			}
666 
667 			/*
668 			 * If we see 2nd destination option header,
669 			 * we should stop there.
670 			 */
671 			if (nxt == IPPROTO_DSTOPTS && dstopt)
672 				return 0;
673 
674 			if (nxt == IPPROTO_DSTOPTS) {
675 				/*
676 				 * Seen 1st or 2nd destination option.
677 				 * next time we see one, it must be 2nd.
678 				 */
679 				dstopt = 1;
680 			} else if (nxt == IPPROTO_ROUTING) {
681 				/*
682 				 * If we see destination option next
683 				 * time, it must be dest2.
684 				 */
685 				dstopt = 2;
686 			}
687 
688 			/* skip this header */
689 			m_copydata(m, *i, sizeof(ip6e), &ip6e);
690 			nxt = ip6e.ip6e_nxt;
691 			*off = *i + offsetof(struct ip6_ext, ip6e_nxt);
692 			*i += (ip6e.ip6e_len + 1) << 3;
693 			if (*i > m->m_pkthdr.len) {
694 				return EINVAL;
695 			}
696 			break;
697 		default:
698 			return 0;
699 		}
700 	}
701 
702 	return 0;
703 }
704 
705 static int
706 in6_sa_equal_addrwithscope(const struct sockaddr_in6 *sa,
707     const struct in6_addr *ia)
708 {
709 	struct in6_addr ia2;
710 
711 	memcpy(&ia2, &sa->sin6_addr, sizeof(ia2));
712 	if (IN6_IS_SCOPE_LINKLOCAL(&sa->sin6_addr))
713 		ia2.s6_addr16[1] = htons(sa->sin6_scope_id);
714 
715 	return IN6_ARE_ADDR_EQUAL(ia, &ia2);
716 }
717 
718 int
719 ipsec6_process_packet(struct mbuf *m, const struct ipsecrequest *isr)
720 {
721 	struct secasvar *sav = NULL;
722 	struct ip6_hdr *ip6;
723 	int s, error, i, off;
724 	union sockaddr_union *dst;
725 
726 	KASSERT(m != NULL);
727 	KASSERT(m->m_nextpkt == NULL);
728 	KASSERT(isr != NULL);
729 
730 	s = splsoftnet();   /* insure SA contents don't change */
731 
732 	isr = ipsec_nextisr(m, isr, AF_INET6, &error, &sav);
733 	if (isr == NULL) {
734 		if (error != 0) {
735 			/* XXX Should we send a notification ? */
736 			goto bad;
737 		} else {
738 			if (ipsec_register_done(m, &error) < 0)
739 				goto bad;
740 
741 			splx(s);
742 			return ipsec_reinject_ipstack(m, AF_INET6);
743 		}
744 	}
745 
746 	KASSERT(sav != NULL);
747 	dst = &sav->sah->saidx.dst;
748 
749 	if (m->m_len < sizeof(struct ip6_hdr)) {
750 		if ((m = m_pullup(m,sizeof(struct ip6_hdr))) == NULL) {
751 			error = ENOBUFS;
752 			goto unrefsav;
753 		}
754 	}
755 	ip6 = mtod(m, struct ip6_hdr *);
756 
757 	/* Do the appropriate encapsulation, if necessary */
758 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
759 	    dst->sa.sa_family != AF_INET6 ||        /* AF mismatch */
760 	    ((dst->sa.sa_family == AF_INET6) &&
761 	     (!IN6_IS_ADDR_UNSPECIFIED(&dst->sin6.sin6_addr)) &&
762 	     (!in6_sa_equal_addrwithscope(&dst->sin6, &ip6->ip6_dst)))) {
763 		struct mbuf *mp;
764 
765 		if (m->m_pkthdr.len - sizeof(*ip6) > IPV6_MAXPACKET) {
766 			/* No jumbogram support. */
767 			error = ENXIO;   /*XXX*/
768 			goto unrefsav;
769 		}
770 
771 		/* Fix IPv6 header payload length. */
772 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
773 
774 		/* Encapsulate the packet */
775 		error = ipip_output(m, sav, &mp);
776 		if (mp == NULL && !error) {
777 			/* Should never happen. */
778 			IPSECLOG(LOG_DEBUG,
779 			    "ipip_output returns no mbuf and no error!");
780 			error = EFAULT;
781 		}
782 
783 		if (error) {
784 			if (mp) {
785 				/* XXX: Should never happen! */
786 				m_freem(mp);
787 			}
788 			m = NULL; /* ipip_output() already freed it */
789 			goto unrefsav;
790 		}
791 
792 		m = mp;
793 		mp = NULL;
794 	}
795 
796 	if (dst->sa.sa_family == AF_INET) {
797 		struct ip *ip;
798 		ip = mtod(m, struct ip *);
799 		i = ip->ip_hl << 2;
800 		off = offsetof(struct ip, ip_p);
801 	} else {
802 		error = compute_ipsec_pos(m, &i, &off);
803 		if (error)
804 			goto unrefsav;
805 	}
806 	error = (*sav->tdb_xform->xf_output)(m, isr, sav, i, off);
807 	KEY_SA_UNREF(&sav);
808 	splx(s);
809 	return error;
810 
811 unrefsav:
812 	KEY_SA_UNREF(&sav);
813 bad:
814 	splx(s);
815 	if (m)
816 		m_freem(m);
817 	return error;
818 }
819 #endif /* INET6 */
820 
821 void
822 ipsec_output_init(void)
823 {
824 
825 	ipsec_rtcache_percpu = percpu_alloc(sizeof(struct route));
826 }
827