xref: /netbsd-src/sys/netipsec/ipsec_output.c (revision fc4f42693f9b1c31f39f9cf50af1bf2010325808)
1 /*	$NetBSD: ipsec_output.c,v 1.71 2018/03/05 11:50:25 maxv 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: /repoman/r/ncvs/src/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.71 2018/03/05 11:50:25 maxv 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 	uint64_t * data = NULL;
155 	int hlen, roff;
156 
157 	IPSEC_SPLASSERT_SOFTNET("ipsec_process_done");
158 
159 	KASSERT(m != NULL);
160 	KASSERT(isr != NULL);
161 	KASSERT(sav != NULL);
162 
163 	saidx = &sav->sah->saidx;
164 
165 	if (sav->natt_type != 0) {
166 		ip = mtod(m, struct ip *);
167 
168 		hlen = sizeof(struct udphdr);
169 		if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
170 			hlen += sizeof(uint64_t);
171 
172 		mo = m_makespace(m, sizeof(struct ip), hlen, &roff);
173 		if (mo == NULL) {
174 			char buf[IPSEC_ADDRSTRLEN];
175 			IPSECLOG(LOG_DEBUG,
176 			    "failed to inject %u byte UDP for SA %s/%08lx\n",
177 			    hlen, ipsec_address(&saidx->dst, buf, sizeof(buf)),
178 			    (u_long) ntohl(sav->spi));
179 			error = ENOBUFS;
180 			goto bad;
181 		}
182 
183 		udp = (struct udphdr *)(mtod(mo, char *) + roff);
184 		data = (uint64_t *)(udp + 1);
185 
186 		if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
187 			*data = 0; /* NON-IKE Marker */
188 
189 		if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
190 			udp->uh_sport = htons(UDP_ENCAP_ESPINUDP_PORT);
191 		else
192 			udp->uh_sport = key_portfromsaddr(&saidx->src);
193 
194 		udp->uh_dport = key_portfromsaddr(&saidx->dst);
195 		udp->uh_sum = 0;
196 		udp->uh_ulen = htons(m->m_pkthdr.len - (ip->ip_hl << 2));
197 	}
198 
199 	switch (saidx->dst.sa.sa_family) {
200 #ifdef INET
201 	case AF_INET:
202 		/* Fix the header length, for AH processing. */
203 		ip = mtod(m, struct ip *);
204 		ip->ip_len = htons(m->m_pkthdr.len);
205 		if (sav->natt_type != 0)
206 			ip->ip_p = IPPROTO_UDP;
207 		break;
208 #endif
209 #ifdef INET6
210 	case AF_INET6:
211 		/* Fix the header length, for AH processing. */
212 		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
213 			error = ENXIO;
214 			goto bad;
215 		}
216 		if (m->m_pkthdr.len - sizeof(struct ip6_hdr) > IPV6_MAXPACKET) {
217 			/* No jumbogram support. */
218 			error = ENXIO;	/*?*/
219 			goto bad;
220 		}
221 		ip6 = mtod(m, struct ip6_hdr *);
222 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
223 		if (sav->natt_type != 0)
224 			ip6->ip6_nxt = IPPROTO_UDP;
225 		break;
226 #endif
227 	default:
228 		IPSECLOG(LOG_DEBUG, "unknown protocol family %u\n",
229 		    saidx->dst.sa.sa_family);
230 		error = ENXIO;
231 		goto bad;
232 	}
233 
234 	key_sa_recordxfer(sav, m);
235 
236 	/*
237 	 * If there's another (bundled) SA to apply, do so.
238 	 * Note that this puts a burden on the kernel stack size.
239 	 * If this is a problem we'll need to introduce a queue
240 	 * to set the packet on so we can unwind the stack before
241 	 * doing further processing.
242 	 */
243 	if (isr->next) {
244 		IPSEC_STATINC(IPSEC_STAT_OUT_BUNDLESA);
245 		switch (saidx->dst.sa.sa_family) {
246 #ifdef INET
247 		case AF_INET:
248 			return ipsec4_process_packet(m, isr->next, NULL);
249 #endif
250 #ifdef INET6
251 		case AF_INET6:
252 			return ipsec6_process_packet(m, isr->next);
253 #endif
254 		default:
255 			IPSECLOG(LOG_DEBUG, "unknown protocol family %u\n",
256 			    saidx->dst.sa.sa_family);
257 			error = ENXIO;
258 			goto bad;
259 		}
260 	}
261 
262 	/*
263 	 * We're done with IPsec processing,
264 	 * mark that we have already processed the packet
265 	 * transmit it packet using the appropriate network protocol (IP or IPv6).
266 	 */
267 
268 	if (ipsec_register_done(m, &error) < 0)
269 		goto bad;
270 
271 	return ipsec_reinject_ipstack(m, saidx->dst.sa.sa_family);
272 
273 bad:
274 	m_freem(m);
275 	return error;
276 }
277 
278 static void
279 ipsec_fill_saidx_bymbuf(struct secasindex *saidx, const struct mbuf *m,
280     const int af)
281 {
282 
283 	if (af == AF_INET) {
284 		struct sockaddr_in *sin;
285 		struct ip *ip = mtod(m, struct ip *);
286 
287 		if (saidx->src.sa.sa_len == 0) {
288 			sin = &saidx->src.sin;
289 			sin->sin_len = sizeof(*sin);
290 			sin->sin_family = AF_INET;
291 			sin->sin_port = IPSEC_PORT_ANY;
292 			sin->sin_addr = ip->ip_src;
293 		}
294 		if (saidx->dst.sa.sa_len == 0) {
295 			sin = &saidx->dst.sin;
296 			sin->sin_len = sizeof(*sin);
297 			sin->sin_family = AF_INET;
298 			sin->sin_port = IPSEC_PORT_ANY;
299 			sin->sin_addr = ip->ip_dst;
300 		}
301 	} else {
302 		struct sockaddr_in6 *sin6;
303 		struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
304 
305 		if (saidx->src.sin6.sin6_len == 0) {
306 			sin6 = (struct sockaddr_in6 *)&saidx->src;
307 			sin6->sin6_len = sizeof(*sin6);
308 			sin6->sin6_family = AF_INET6;
309 			sin6->sin6_port = IPSEC_PORT_ANY;
310 			sin6->sin6_addr = ip6->ip6_src;
311 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
312 				/* fix scope id for comparing SPD */
313 				sin6->sin6_addr.s6_addr16[1] = 0;
314 				sin6->sin6_scope_id =
315 				    ntohs(ip6->ip6_src.s6_addr16[1]);
316 			}
317 		}
318 		if (saidx->dst.sin6.sin6_len == 0) {
319 			sin6 = (struct sockaddr_in6 *)&saidx->dst;
320 			sin6->sin6_len = sizeof(*sin6);
321 			sin6->sin6_family = AF_INET6;
322 			sin6->sin6_port = IPSEC_PORT_ANY;
323 			sin6->sin6_addr = ip6->ip6_dst;
324 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
325 				/* fix scope id for comparing SPD */
326 				sin6->sin6_addr.s6_addr16[1] = 0;
327 				sin6->sin6_scope_id =
328 				    ntohs(ip6->ip6_dst.s6_addr16[1]);
329 			}
330 		}
331 	}
332 }
333 
334 struct secasvar *
335 ipsec_lookup_sa(const struct ipsecrequest *isr, const struct mbuf *m)
336 {
337 	struct secasindex saidx;
338 
339 	saidx = isr->saidx;
340 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
341 		/* Fillin unspecified SA peers only for transport mode */
342 		ipsec_fill_saidx_bymbuf(&saidx, m, isr->saidx.dst.sa.sa_family);
343 	}
344 
345 	return key_lookup_sa_bysaidx(&saidx);
346 }
347 
348 /*
349  * ipsec_nextisr can return :
350  * - isr == NULL and error != 0 => something is bad : the packet must be
351  *   discarded
352  * - isr == NULL and error == 0 => no more rules to apply, ipsec processing
353  *   is done, reinject it in ip stack
354  * - isr != NULL (error == 0) => we need to apply one rule to the packet
355  */
356 static const struct ipsecrequest *
357 ipsec_nextisr(struct mbuf *m, const struct ipsecrequest *isr, int af,
358     int *error, struct secasvar **ret)
359 {
360 #define	IPSEC_OSTAT(type)						\
361 do {									\
362 	switch (isr->saidx.proto) {					\
363 	case IPPROTO_ESP:						\
364 		ESP_STATINC(ESP_STAT_ ## type);				\
365 		break;							\
366 	case IPPROTO_AH:						\
367 		AH_STATINC(AH_STAT_ ## type);				\
368 		break;							\
369 	default:							\
370 		IPCOMP_STATINC(IPCOMP_STAT_ ## type);			\
371 		break;							\
372 	}								\
373 } while (/*CONSTCOND*/0)
374 
375 	struct secasvar *sav = NULL;
376 	struct secasindex saidx;
377 
378 	IPSEC_SPLASSERT_SOFTNET("ipsec_nextisr");
379 	KASSERTMSG(af == AF_INET || af == AF_INET6,
380 	    "invalid address family %u", af);
381 again:
382 	/*
383 	 * Craft SA index to search for proper SA.  Note that
384 	 * we only fillin unspecified SA peers for transport
385 	 * mode; for tunnel mode they must already be filled in.
386 	 */
387 	saidx = isr->saidx;
388 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
389 		/* Fillin unspecified SA peers only for transport mode */
390 		ipsec_fill_saidx_bymbuf(&saidx, m, af);
391 	}
392 
393 	/*
394 	 * Lookup SA and validate it.
395 	 */
396 	*error = key_checkrequest(isr, &saidx, &sav);
397 	if (*error != 0) {
398 		/*
399 		 * IPsec processing is required, but no SA found.
400 		 * I assume that key_acquire() had been called
401 		 * to get/establish the SA. Here I discard
402 		 * this packet because it is responsibility for
403 		 * upper layer to retransmit the packet.
404 		 */
405 		IPSEC_STATINC(IPSEC_STAT_OUT_NOSA);
406 		goto bad;
407 	}
408 	/* sav may be NULL here if we have an USE rule */
409 	if (sav == NULL) {
410 		KASSERTMSG(ipsec_get_reqlevel(isr) == IPSEC_LEVEL_USE,
411 		    "no SA found, but required; level %u",
412 		    ipsec_get_reqlevel(isr));
413 		isr = isr->next;
414 		/*
415 		 * No more rules to apply, return NULL isr and no error
416 		 * It can happen when the last rules are USE rules
417 		 */
418 		if (isr == NULL) {
419 			*ret = NULL;
420 			*error = 0;
421 			return isr;
422 		}
423 		goto again;
424 	}
425 
426 	/*
427 	 * Check system global policy controls.
428 	 */
429 	if ((isr->saidx.proto == IPPROTO_ESP && !esp_enable) ||
430 	    (isr->saidx.proto == IPPROTO_AH && !ah_enable) ||
431 	    (isr->saidx.proto == IPPROTO_IPCOMP && !ipcomp_enable)) {
432 		IPSECLOG(LOG_DEBUG, "IPsec outbound packet dropped due"
433 		    " to policy (check your sysctls)\n");
434 		IPSEC_OSTAT(PDROPS);
435 		*error = EHOSTUNREACH;
436 		KEY_SA_UNREF(&sav);
437 		goto bad;
438 	}
439 
440 	/*
441 	 * Sanity check the SA contents for the caller
442 	 * before they invoke the xform output method.
443 	 */
444 	KASSERT(sav->tdb_xform != NULL);
445 	*ret = sav;
446 	return isr;
447 
448 bad:
449 	KASSERTMSG(*error != 0, "error return w/ no error code");
450 	return NULL;
451 #undef IPSEC_OSTAT
452 }
453 
454 #ifdef INET
455 /*
456  * IPsec output logic for IPv4.
457  */
458 int
459 ipsec4_process_packet(struct mbuf *m, const struct ipsecrequest *isr,
460     u_long *mtu)
461 {
462 	struct secasvar *sav = NULL;
463 	struct ip *ip;
464 	int s, error, i, off;
465 	union sockaddr_union *dst;
466 	int setdf;
467 
468 	KASSERT(m != NULL);
469 	KASSERT(m->m_nextpkt == NULL);
470 	KASSERT(isr != NULL);
471 
472 	s = splsoftnet();	/* insure SA contents don't change */
473 
474 	isr = ipsec_nextisr(m, isr, AF_INET, &error, &sav);
475 	if (isr == NULL) {
476 		if (error != 0) {
477 			goto bad;
478 		} else {
479 			if (ipsec_register_done(m, &error) < 0)
480 				goto bad;
481 
482 			splx(s);
483 			return ipsec_reinject_ipstack(m, AF_INET);
484 		}
485 	}
486 	KASSERT(sav != NULL);
487 
488 	if (m->m_len < sizeof(struct ip) &&
489 	    (m = m_pullup(m, sizeof(struct ip))) == NULL) {
490 		error = ENOBUFS;
491 		goto unrefsav;
492 	}
493 
494 	/*
495 	 * Check if we need to handle NAT-T fragmentation.
496 	 */
497 	if (isr == isr->sp->req) { /* Check only if called from ipsec4_output */
498 		KASSERT(mtu != NULL);
499 		ip = mtod(m, struct ip *);
500 		if (!(sav->natt_type &
501 		    (UDP_ENCAP_ESPINUDP|UDP_ENCAP_ESPINUDP_NON_IKE))) {
502 			goto noneed;
503 		}
504 		if (ntohs(ip->ip_len) <= sav->esp_frag)
505 			goto noneed;
506 		*mtu = sav->esp_frag;
507 		KEY_SA_UNREF(&sav);
508 		splx(s);
509 		return 0;
510 	}
511 noneed:
512 	dst = &sav->sah->saidx.dst;
513 
514 	/*
515 	 * Collect IP_DF state from the outer header.
516 	 */
517 	if (dst->sa.sa_family == AF_INET) {
518 		ip = mtod(m, struct ip *);
519 		/* Honor system-wide control of how to handle IP_DF */
520 		switch (ip4_ipsec_dfbit) {
521 		case 0:			/* clear in outer header */
522 		case 1:			/* set in outer header */
523 			setdf = ip4_ipsec_dfbit;
524 			break;
525 		default:		/* propagate to outer header */
526 			setdf = ip->ip_off;
527 			setdf = ntohs(setdf);
528 			setdf = htons(setdf & IP_DF);
529 			break;
530 		}
531 	} else {
532 		ip = NULL;		/* keep compiler happy */
533 		setdf = 0;
534 	}
535 
536 	/* Do the appropriate encapsulation, if necessary */
537 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
538 	    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
539 #if 0
540 	    (sav->flags & SADB_X_SAFLAGS_TUNNEL) || /* Tunnel requ'd */
541 	    sav->tdb_xform->xf_type == XF_IP4 ||    /* ditto */
542 #endif
543 	    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
544 	     dst->sin.sin_addr.s_addr != INADDR_ANY &&
545 	     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
546 		struct mbuf *mp;
547 
548 		/* Fix IPv4 header checksum and length */
549 		ip = mtod(m, struct ip *);
550 		ip->ip_len = htons(m->m_pkthdr.len);
551 		ip->ip_sum = 0;
552 		ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
553 
554 		/* Encapsulate the packet */
555 		error = ipip_output(m, isr, sav, &mp, 0, 0);
556 		if (mp == NULL && !error) {
557 			/* Should never happen. */
558 			IPSECLOG(LOG_DEBUG,
559 			    "ipip_output returns no mbuf and no error!");
560 			error = EFAULT;
561 		}
562 		if (error) {
563 			if (mp) {
564 				/* XXX: Should never happen! */
565 				m_freem(mp);
566 			}
567 			m = NULL; /* ipip_output() already freed it */
568 			goto unrefsav;
569 		}
570 		m = mp, mp = NULL;
571 
572 		/*
573 		 * ipip_output clears IP_DF in the new header.  If
574 		 * we need to propagate IP_DF from the outer header,
575 		 * then we have to do it here.
576 		 *
577 		 * XXX shouldn't assume what ipip_output does.
578 		 */
579 		if (dst->sa.sa_family == AF_INET && setdf) {
580 			if (m->m_len < sizeof(struct ip) &&
581 			    (m = m_pullup(m, sizeof(struct ip))) == NULL) {
582 				error = ENOBUFS;
583 				goto unrefsav;
584 			}
585 			ip = mtod(m, struct ip *);
586 			ip->ip_off |= htons(IP_DF);
587 		}
588 	}
589 
590 	/*
591 	 * Dispatch to the appropriate IPsec transform logic.  The
592 	 * packet will be returned for transmission after crypto
593 	 * processing, etc. are completed.  For encapsulation we
594 	 * bypass this call because of the explicit call done above
595 	 * (necessary to deal with IP_DF handling for IPv4).
596 	 *
597 	 * NB: m & sav are ``passed to caller'' who's reponsible for
598 	 *     for reclaiming their resources.
599 	 */
600 	if (sav->tdb_xform->xf_type != XF_IP4) {
601 		if (dst->sa.sa_family == AF_INET) {
602 			ip = mtod(m, struct ip *);
603 			i = ip->ip_hl << 2;
604 			off = offsetof(struct ip, ip_p);
605 		} else {
606 			i = sizeof(struct ip6_hdr);
607 			off = offsetof(struct ip6_hdr, ip6_nxt);
608 		}
609 		error = (*sav->tdb_xform->xf_output)(m, isr, sav, NULL, i, off);
610 	} else {
611 		error = ipsec_process_done(m, isr, sav);
612 	}
613 	KEY_SA_UNREF(&sav);
614 	splx(s);
615 	return error;
616 
617 unrefsav:
618 	KEY_SA_UNREF(&sav);
619 bad:
620 	splx(s);
621 	if (m)
622 		m_freem(m);
623 	return error;
624 }
625 #endif
626 
627 #ifdef INET6
628 static void
629 compute_ipsec_pos(struct mbuf *m, int *i, int *off)
630 {
631 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
632 	struct ip6_ext ip6e;
633 	int dstopt = 0;
634 	int nxt;
635 
636 	*i = sizeof(struct ip6_hdr);
637 	*off = offsetof(struct ip6_hdr, ip6_nxt);
638 	nxt = ip6->ip6_nxt;
639 
640 	/*
641 	 * chase mbuf chain to find the appropriate place to
642 	 * put AH/ESP/IPcomp header.
643 	 *     IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
644 	 */
645 	do {
646 		switch (nxt) {
647 		case IPPROTO_AH:
648 		case IPPROTO_ESP:
649 		case IPPROTO_IPCOMP:
650 		/*
651 		 * we should not skip security header added
652 		 * beforehand.
653 		 */
654 			return;
655 
656 		case IPPROTO_HOPOPTS:
657 		case IPPROTO_DSTOPTS:
658 		case IPPROTO_ROUTING:
659 		/*
660 		 * if we see 2nd destination option header,
661 		 * we should stop there.
662 		 */
663 			if (nxt == IPPROTO_DSTOPTS && dstopt)
664 				return;
665 
666 			if (nxt == IPPROTO_DSTOPTS) {
667 				/*
668 				 * seen 1st or 2nd destination option.
669 				 * next time we see one, it must be 2nd.
670 				 */
671 				dstopt = 1;
672 			} else if (nxt == IPPROTO_ROUTING) {
673 				/*
674 				 * if we see destination option next
675 				 * time, it must be dest2.
676 				 */
677 				dstopt = 2;
678 			}
679 
680 			/* skip this header */
681 			m_copydata(m, *i, sizeof(ip6e), &ip6e);
682 			nxt = ip6e.ip6e_nxt;
683 			*off = *i + offsetof(struct ip6_ext, ip6e_nxt);
684 			/*
685 			 * we will never see nxt == IPPROTO_AH
686 			 * so it is safe to omit AH case.
687 			 */
688 			*i += (ip6e.ip6e_len + 1) << 3;
689 			break;
690 		default:
691 			return;
692 		}
693 	} while (*i + sizeof(ip6e) < m->m_pkthdr.len);
694 }
695 
696 static int
697 in6_sa_equal_addrwithscope(const struct sockaddr_in6 *sa,
698     const struct in6_addr *ia)
699 {
700 	struct in6_addr ia2;
701 
702 	memcpy(&ia2, &sa->sin6_addr, sizeof(ia2));
703 	if (IN6_IS_SCOPE_LINKLOCAL(&sa->sin6_addr))
704 		ia2.s6_addr16[1] = htons(sa->sin6_scope_id);
705 
706 	return IN6_ARE_ADDR_EQUAL(ia, &ia2);
707 }
708 
709 int
710 ipsec6_process_packet(struct mbuf *m, const struct ipsecrequest *isr)
711 {
712 	struct secasvar *sav = NULL;
713 	struct ip6_hdr *ip6;
714 	int s, error, i, off;
715 	union sockaddr_union *dst;
716 
717 	KASSERT(m != NULL);
718 	KASSERT(m->m_nextpkt == NULL);
719 	KASSERT(isr != NULL);
720 
721 	s = splsoftnet();   /* insure SA contents don't change */
722 
723 	isr = ipsec_nextisr(m, isr, AF_INET6, &error, &sav);
724 	if (isr == NULL) {
725 		if (error != 0) {
726 			/* XXX Should we send a notification ? */
727 			goto bad;
728 		} else {
729 			if (ipsec_register_done(m, &error) < 0)
730 				goto bad;
731 
732 			splx(s);
733 			return ipsec_reinject_ipstack(m, AF_INET6);
734 		}
735 	}
736 
737 	KASSERT(sav != NULL);
738 	dst = &sav->sah->saidx.dst;
739 
740 	if (m->m_len < sizeof(struct ip6_hdr)) {
741 		if ((m = m_pullup(m,sizeof(struct ip6_hdr))) == NULL) {
742 			error = ENOBUFS;
743 			goto unrefsav;
744 		}
745 	}
746 	ip6 = mtod(m, struct ip6_hdr *);
747 
748 	/* Do the appropriate encapsulation, if necessary */
749 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
750 	    dst->sa.sa_family != AF_INET6 ||        /* AF mismatch */
751 	    ((dst->sa.sa_family == AF_INET6) &&
752 	     (!IN6_IS_ADDR_UNSPECIFIED(&dst->sin6.sin6_addr)) &&
753 	     (!in6_sa_equal_addrwithscope(&dst->sin6, &ip6->ip6_dst)))) {
754 		struct mbuf *mp;
755 
756 		if (m->m_pkthdr.len - sizeof(*ip6) > IPV6_MAXPACKET) {
757 			/* No jumbogram support. */
758 			error = ENXIO;   /*XXX*/
759 			goto unrefsav;
760 		}
761 
762 		/* Fix IPv6 header payload length. */
763 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
764 
765 		/* Encapsulate the packet */
766 		error = ipip_output(m, isr, sav, &mp, 0, 0);
767 		if (mp == NULL && !error) {
768 			/* Should never happen. */
769 			IPSECLOG(LOG_DEBUG,
770 			    "ipip_output returns no mbuf and no error!");
771 			error = EFAULT;
772 		}
773 
774 		if (error) {
775 			if (mp) {
776 				/* XXX: Should never happen! */
777 				m_freem(mp);
778 			}
779 			m = NULL; /* ipip_output() already freed it */
780 			goto unrefsav;
781 		}
782 
783 		m = mp;
784 		mp = NULL;
785 	}
786 
787 	if (dst->sa.sa_family == AF_INET) {
788 		struct ip *ip;
789 		ip = mtod(m, struct ip *);
790 		i = ip->ip_hl << 2;
791 		off = offsetof(struct ip, ip_p);
792 	} else {
793 		compute_ipsec_pos(m, &i, &off);
794 	}
795 	error = (*sav->tdb_xform->xf_output)(m, isr, sav, NULL, i, off);
796 	KEY_SA_UNREF(&sav);
797 	splx(s);
798 	return error;
799 
800 unrefsav:
801 	KEY_SA_UNREF(&sav);
802 bad:
803 	splx(s);
804 	if (m)
805 		m_freem(m);
806 	return error;
807 }
808 #endif /* INET6 */
809 
810 void
811 ipsec_output_init(void)
812 {
813 
814 	ipsec_rtcache_percpu = percpu_alloc(sizeof(struct route));
815 }
816