xref: /freebsd/sys/netipsec/ipsec_output.c (revision 7e00348e7605b9906601438008341ffc37c00e2c)
1 /*-
2  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 /*
30  * IPsec output processing.
31  */
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_ipsec.h"
35 #include "opt_enc.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/mbuf.h>
40 #include <sys/domain.h>
41 #include <sys/protosw.h>
42 #include <sys/socket.h>
43 #include <sys/errno.h>
44 #include <sys/syslog.h>
45 
46 #include <net/if.h>
47 #include <net/if_var.h>
48 #include <net/pfil.h>
49 #include <net/route.h>
50 #include <net/vnet.h>
51 
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h>
54 #include <netinet/ip.h>
55 #include <netinet/ip_var.h>
56 #include <netinet/in_var.h>
57 #include <netinet/ip_ecn.h>
58 #ifdef INET6
59 #include <netinet6/ip6_ecn.h>
60 #endif
61 
62 #include <netinet/ip6.h>
63 #ifdef INET6
64 #include <netinet6/ip6_var.h>
65 #endif
66 #include <netinet/in_pcb.h>
67 #ifdef INET6
68 #include <netinet/icmp6.h>
69 #endif
70 
71 #include <netipsec/ipsec.h>
72 #ifdef INET6
73 #include <netipsec/ipsec6.h>
74 #endif
75 #include <netipsec/ah_var.h>
76 #include <netipsec/esp_var.h>
77 #include <netipsec/ipcomp_var.h>
78 
79 #include <netipsec/xform.h>
80 
81 #include <netipsec/key.h>
82 #include <netipsec/keydb.h>
83 #include <netipsec/key_debug.h>
84 
85 #include <machine/in_cksum.h>
86 
87 #ifdef IPSEC_NAT_T
88 #include <netinet/udp.h>
89 #endif
90 
91 #ifdef DEV_ENC
92 #include <net/if_enc.h>
93 #endif
94 
95 
96 int
97 ipsec_process_done(struct mbuf *m, struct ipsecrequest *isr)
98 {
99 	struct tdb_ident *tdbi;
100 	struct m_tag *mtag;
101 	struct secasvar *sav;
102 	struct secasindex *saidx;
103 	int error;
104 
105 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
106 	IPSEC_ASSERT(isr != NULL, ("null ISR"));
107 	sav = isr->sav;
108 	IPSEC_ASSERT(sav != NULL, ("null SA"));
109 	IPSEC_ASSERT(sav->sah != NULL, ("null SAH"));
110 
111 	saidx = &sav->sah->saidx;
112 	switch (saidx->dst.sa.sa_family) {
113 #ifdef INET
114 	case AF_INET:
115 		/* Fix the header length, for AH processing. */
116 		mtod(m, struct ip *)->ip_len = htons(m->m_pkthdr.len);
117 		break;
118 #endif /* INET */
119 #ifdef INET6
120 	case AF_INET6:
121 		/* Fix the header length, for AH processing. */
122 		if (m->m_pkthdr.len < sizeof (struct ip6_hdr)) {
123 			error = ENXIO;
124 			goto bad;
125 		}
126 		if (m->m_pkthdr.len - sizeof (struct ip6_hdr) > IPV6_MAXPACKET) {
127 			/* No jumbogram support. */
128 			error = ENXIO;	/*?*/
129 			goto bad;
130 		}
131 		mtod(m, struct ip6_hdr *)->ip6_plen =
132 			htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
133 		break;
134 #endif /* INET6 */
135 	default:
136 		DPRINTF(("%s: unknown protocol family %u\n", __func__,
137 		    saidx->dst.sa.sa_family));
138 		error = ENXIO;
139 		goto bad;
140 	}
141 
142 	/*
143 	 * Add a record of what we've done or what needs to be done to the
144 	 * packet.
145 	 */
146 	mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE,
147 			sizeof(struct tdb_ident), M_NOWAIT);
148 	if (mtag == NULL) {
149 		DPRINTF(("%s: could not get packet tag\n", __func__));
150 		error = ENOMEM;
151 		goto bad;
152 	}
153 
154 	tdbi = (struct tdb_ident *)(mtag + 1);
155 	tdbi->dst = saidx->dst;
156 	tdbi->proto = saidx->proto;
157 	tdbi->spi = sav->spi;
158 	m_tag_prepend(m, mtag);
159 
160 	/*
161 	 * If there's another (bundled) SA to apply, do so.
162 	 * Note that this puts a burden on the kernel stack size.
163 	 * If this is a problem we'll need to introduce a queue
164 	 * to set the packet on so we can unwind the stack before
165 	 * doing further processing.
166 	 */
167 	if (isr->next) {
168 		/* XXX-BZ currently only support same AF bundles. */
169 		switch (saidx->dst.sa.sa_family) {
170 #ifdef INET
171 		case AF_INET:
172 			IPSECSTAT_INC(ips_out_bundlesa);
173 			return ipsec4_process_packet(m, isr->next, 0, 0);
174 			/* NOTREACHED */
175 #endif
176 #ifdef notyet
177 #ifdef INET6
178 		case AF_INET6:
179 			/* XXX */
180 			IPSEC6STAT_INC(ips_out_bundlesa);
181 			return ipsec6_process_packet(m, isr->next);
182 			/* NOTREACHED */
183 #endif /* INET6 */
184 #endif
185 		default:
186 			DPRINTF(("%s: unknown protocol family %u\n", __func__,
187 			    saidx->dst.sa.sa_family));
188 			error = ENXIO;
189 			goto bad;
190 		}
191 	}
192 	key_sa_recordxfer(sav, m);		/* record data transfer */
193 
194 	/*
195 	 * We're done with IPsec processing, transmit the packet using the
196 	 * appropriate network protocol (IP or IPv6). SPD lookup will be
197 	 * performed again there.
198 	 */
199 	switch (saidx->dst.sa.sa_family) {
200 #ifdef INET
201 	case AF_INET:
202 #ifdef IPSEC_NAT_T
203 		/*
204 		 * If NAT-T is enabled, now that all IPsec processing is done
205 		 * insert UDP encapsulation header after IP header.
206 		 */
207 		if (sav->natt_type) {
208 			struct ip *ip = mtod(m, struct ip *);
209 			const int hlen = (ip->ip_hl << 2);
210 			int size, off;
211 			struct mbuf *mi;
212 			struct udphdr *udp;
213 
214 			size = sizeof(struct udphdr);
215 			if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE) {
216 				/*
217 				 * draft-ietf-ipsec-nat-t-ike-0[01].txt and
218 				 * draft-ietf-ipsec-udp-encaps-(00/)01.txt,
219 				 * ignoring possible AH mode
220 				 * non-IKE marker + non-ESP marker
221 				 * from draft-ietf-ipsec-udp-encaps-00.txt.
222 				 */
223 				size += sizeof(u_int64_t);
224 			}
225 			mi = m_makespace(m, hlen, size, &off);
226 			if (mi == NULL) {
227 				DPRINTF(("%s: m_makespace for udphdr failed\n",
228 				    __func__));
229 				error = ENOBUFS;
230 				goto bad;
231 			}
232 
233 			udp = (struct udphdr *)(mtod(mi, caddr_t) + off);
234 			if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
235 				udp->uh_sport = htons(UDP_ENCAP_ESPINUDP_PORT);
236 			else
237 				udp->uh_sport =
238 					KEY_PORTFROMSADDR(&sav->sah->saidx.src);
239 			udp->uh_dport = KEY_PORTFROMSADDR(&sav->sah->saidx.dst);
240 			udp->uh_sum = 0;
241 			udp->uh_ulen = htons(m->m_pkthdr.len - hlen);
242 			ip->ip_len = htons(m->m_pkthdr.len);
243 			ip->ip_p = IPPROTO_UDP;
244 
245 			if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
246 				*(u_int64_t *)(udp + 1) = 0;
247 		}
248 #endif /* IPSEC_NAT_T */
249 
250 		return ip_output(m, NULL, NULL, IP_RAWOUTPUT, NULL, NULL);
251 #endif /* INET */
252 #ifdef INET6
253 	case AF_INET6:
254 		/*
255 		 * We don't need massage, IPv6 header fields are always in
256 		 * net endian.
257 		 */
258 		return ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
259 #endif /* INET6 */
260 	}
261 	panic("ipsec_process_done");
262 bad:
263 	m_freem(m);
264 	return (error);
265 }
266 
267 static struct ipsecrequest *
268 ipsec_nextisr(
269 	struct mbuf *m,
270 	struct ipsecrequest *isr,
271 	int af,
272 	struct secasindex *saidx,
273 	int *error
274 )
275 {
276 #define	IPSEC_OSTAT(name)	do {		\
277 	if (isr->saidx.proto == IPPROTO_ESP)	\
278 		ESPSTAT_INC(esps_##name);	\
279 	else if (isr->saidx.proto == IPPROTO_AH)\
280 		AHSTAT_INC(ahs_##name);		\
281 	else					\
282 		IPCOMPSTAT_INC(ipcomps_##name);	\
283 } while (0)
284 	struct secasvar *sav;
285 
286 	IPSECREQUEST_LOCK_ASSERT(isr);
287 
288 	IPSEC_ASSERT(af == AF_INET || af == AF_INET6,
289 		("invalid address family %u", af));
290 again:
291 	/*
292 	 * Craft SA index to search for proper SA.  Note that
293 	 * we only fillin unspecified SA peers for transport
294 	 * mode; for tunnel mode they must already be filled in.
295 	 */
296 	*saidx = isr->saidx;
297 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
298 		/* Fillin unspecified SA peers only for transport mode */
299 		if (af == AF_INET) {
300 			struct sockaddr_in *sin;
301 			struct ip *ip = mtod(m, struct ip *);
302 
303 			if (saidx->src.sa.sa_len == 0) {
304 				sin = &saidx->src.sin;
305 				sin->sin_len = sizeof(*sin);
306 				sin->sin_family = AF_INET;
307 				sin->sin_port = IPSEC_PORT_ANY;
308 				sin->sin_addr = ip->ip_src;
309 			}
310 			if (saidx->dst.sa.sa_len == 0) {
311 				sin = &saidx->dst.sin;
312 				sin->sin_len = sizeof(*sin);
313 				sin->sin_family = AF_INET;
314 				sin->sin_port = IPSEC_PORT_ANY;
315 				sin->sin_addr = ip->ip_dst;
316 			}
317 		} else {
318 			struct sockaddr_in6 *sin6;
319 			struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
320 
321 			if (saidx->src.sin6.sin6_len == 0) {
322 				sin6 = (struct sockaddr_in6 *)&saidx->src;
323 				sin6->sin6_len = sizeof(*sin6);
324 				sin6->sin6_family = AF_INET6;
325 				sin6->sin6_port = IPSEC_PORT_ANY;
326 				sin6->sin6_addr = ip6->ip6_src;
327 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
328 					/* fix scope id for comparing SPD */
329 					sin6->sin6_addr.s6_addr16[1] = 0;
330 					sin6->sin6_scope_id =
331 					    ntohs(ip6->ip6_src.s6_addr16[1]);
332 				}
333 			}
334 			if (saidx->dst.sin6.sin6_len == 0) {
335 				sin6 = (struct sockaddr_in6 *)&saidx->dst;
336 				sin6->sin6_len = sizeof(*sin6);
337 				sin6->sin6_family = AF_INET6;
338 				sin6->sin6_port = IPSEC_PORT_ANY;
339 				sin6->sin6_addr = ip6->ip6_dst;
340 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
341 					/* fix scope id for comparing SPD */
342 					sin6->sin6_addr.s6_addr16[1] = 0;
343 					sin6->sin6_scope_id =
344 					    ntohs(ip6->ip6_dst.s6_addr16[1]);
345 				}
346 			}
347 		}
348 	}
349 
350 	/*
351 	 * Lookup SA and validate it.
352 	 */
353 	*error = key_checkrequest(isr, saidx);
354 	if (*error != 0) {
355 		/*
356 		 * IPsec processing is required, but no SA found.
357 		 * I assume that key_acquire() had been called
358 		 * to get/establish the SA. Here I discard
359 		 * this packet because it is responsibility for
360 		 * upper layer to retransmit the packet.
361 		 */
362 		switch(af) {
363 		case AF_INET:
364 			IPSECSTAT_INC(ips_out_nosa);
365 			break;
366 #ifdef INET6
367 		case AF_INET6:
368 			IPSEC6STAT_INC(ips_out_nosa);
369 			break;
370 #endif
371 		}
372 		goto bad;
373 	}
374 	sav = isr->sav;
375 	if (sav == NULL) {
376 		IPSEC_ASSERT(ipsec_get_reqlevel(isr) == IPSEC_LEVEL_USE,
377 			("no SA found, but required; level %u",
378 			ipsec_get_reqlevel(isr)));
379 		IPSECREQUEST_UNLOCK(isr);
380 		isr = isr->next;
381 		/*
382 		 * If isr is NULL, we found a 'use' policy w/o SA.
383 		 * Return w/o error and w/o isr so we can drop out
384 		 * and continue w/o IPsec processing.
385 		 */
386 		if (isr == NULL)
387 			return isr;
388 		IPSECREQUEST_LOCK(isr);
389 		goto again;
390 	}
391 
392 	/*
393 	 * Check system global policy controls.
394 	 */
395 	if ((isr->saidx.proto == IPPROTO_ESP && !V_esp_enable) ||
396 	    (isr->saidx.proto == IPPROTO_AH && !V_ah_enable) ||
397 	    (isr->saidx.proto == IPPROTO_IPCOMP && !V_ipcomp_enable)) {
398 		DPRINTF(("%s: IPsec outbound packet dropped due"
399 			" to policy (check your sysctls)\n", __func__));
400 		IPSEC_OSTAT(pdrops);
401 		*error = EHOSTUNREACH;
402 		goto bad;
403 	}
404 
405 	/*
406 	 * Sanity check the SA contents for the caller
407 	 * before they invoke the xform output method.
408 	 */
409 	if (sav->tdb_xform == NULL) {
410 		DPRINTF(("%s: no transform for SA\n", __func__));
411 		IPSEC_OSTAT(noxform);
412 		*error = EHOSTUNREACH;
413 		goto bad;
414 	}
415 	return isr;
416 bad:
417 	IPSEC_ASSERT(*error != 0, ("error return w/ no error code"));
418 	IPSECREQUEST_UNLOCK(isr);
419 	return NULL;
420 #undef IPSEC_OSTAT
421 }
422 
423 #ifdef INET
424 /*
425  * IPsec output logic for IPv4.
426  */
427 int
428 ipsec4_process_packet(
429 	struct mbuf *m,
430 	struct ipsecrequest *isr,
431 	int flags,
432 	int tunalready)
433 {
434 	struct secasindex saidx;
435 	struct secasvar *sav;
436 	struct ip *ip;
437 	int error, i, off;
438 
439 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
440 	IPSEC_ASSERT(isr != NULL, ("null isr"));
441 
442 	IPSECREQUEST_LOCK(isr);		/* insure SA contents don't change */
443 
444 	isr = ipsec_nextisr(m, isr, AF_INET, &saidx, &error);
445 	if (isr == NULL) {
446 		if (error != 0)
447 			goto bad;
448 		return EJUSTRETURN;
449 	}
450 
451 	sav = isr->sav;
452 
453 #ifdef DEV_ENC
454 	if_inc_counter(encif, IFCOUNTER_OPACKETS, 1);
455 	if_inc_counter(encif, IFCOUNTER_OBYTES, m->m_pkthdr.len);
456 
457 	/* pass the mbuf to enc0 for bpf processing */
458 	ipsec_bpf(m, sav, AF_INET, ENC_OUT|ENC_BEFORE);
459 	/* pass the mbuf to enc0 for packet filtering */
460 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_BEFORE)) != 0)
461 		goto bad;
462 #endif
463 
464 	if (!tunalready) {
465 		union sockaddr_union *dst = &sav->sah->saidx.dst;
466 		int setdf;
467 
468 		/*
469 		 * Collect IP_DF state from the outer header.
470 		 */
471 		if (dst->sa.sa_family == AF_INET) {
472 			if (m->m_len < sizeof (struct ip) &&
473 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
474 				error = ENOBUFS;
475 				goto bad;
476 			}
477 			ip = mtod(m, struct ip *);
478 			/* Honor system-wide control of how to handle IP_DF */
479 			switch (V_ip4_ipsec_dfbit) {
480 			case 0:			/* clear in outer header */
481 			case 1:			/* set in outer header */
482 				setdf = V_ip4_ipsec_dfbit;
483 				break;
484 			default:		/* propagate to outer header */
485 				setdf = ntohs(ip->ip_off & IP_DF);
486 				break;
487 			}
488 		} else {
489 			ip = NULL;		/* keep compiler happy */
490 			setdf = 0;
491 		}
492 		/* Do the appropriate encapsulation, if necessary */
493 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
494 		    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
495 #if 0
496 		    (sav->flags & SADB_X_SAFLAGS_TUNNEL) || /* Tunnel requ'd */
497 		    sav->tdb_xform->xf_type == XF_IP4 ||    /* ditto */
498 #endif
499 		    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
500 		     dst->sin.sin_addr.s_addr != INADDR_ANY &&
501 		     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
502 			struct mbuf *mp;
503 
504 			/* Fix IPv4 header checksum and length */
505 			if (m->m_len < sizeof (struct ip) &&
506 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
507 				error = ENOBUFS;
508 				goto bad;
509 			}
510 			ip = mtod(m, struct ip *);
511 			if (ip->ip_v == IPVERSION) {
512 				ip->ip_len = htons(m->m_pkthdr.len);
513 				ip->ip_sum = 0;
514 				ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
515 			}
516 
517 			/* Encapsulate the packet */
518 			error = ipip_output(m, isr, &mp, 0, 0);
519 			if (mp == NULL && !error) {
520 				/* Should never happen. */
521 				DPRINTF(("%s: ipip_output returns no mbuf and "
522 					"no error!", __func__));
523 				error = EFAULT;
524 			}
525 			if (error) {
526 				if (mp) {
527 					/* XXX: Should never happen! */
528 					m_freem(mp);
529 				}
530 				m = NULL; /* ipip_output() already freed it */
531 				goto bad;
532 			}
533 			m = mp, mp = NULL;
534 			/*
535 			 * ipip_output clears IP_DF in the new header.  If
536 			 * we need to propagate IP_DF from the outer header,
537 			 * then we have to do it here.
538 			 *
539 			 * XXX shouldn't assume what ipip_output does.
540 			 */
541 			if (dst->sa.sa_family == AF_INET && setdf) {
542 				if (m->m_len < sizeof (struct ip) &&
543 				    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
544 					error = ENOBUFS;
545 					goto bad;
546 				}
547 				ip = mtod(m, struct ip *);
548 				ip->ip_off = ntohs(ip->ip_off);
549 				ip->ip_off |= IP_DF;
550 				ip->ip_off = htons(ip->ip_off);
551 			}
552 		}
553 	}
554 
555 #ifdef DEV_ENC
556 	/* pass the mbuf to enc0 for bpf processing */
557 	ipsec_bpf(m, sav, sav->sah->saidx.dst.sa.sa_family, ENC_OUT|ENC_AFTER);
558 	/* pass the mbuf to enc0 for packet filtering */
559 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_AFTER)) != 0)
560 		goto bad;
561 #endif
562 
563 	/*
564 	 * Dispatch to the appropriate IPsec transform logic.  The
565 	 * packet will be returned for transmission after crypto
566 	 * processing, etc. are completed.  For encapsulation we
567 	 * bypass this call because of the explicit call done above
568 	 * (necessary to deal with IP_DF handling for IPv4).
569 	 *
570 	 * NB: m & sav are ``passed to caller'' who's reponsible for
571 	 *     for reclaiming their resources.
572 	 */
573 	if (sav->tdb_xform->xf_type != XF_IP4) {
574 		union sockaddr_union *dst = &sav->sah->saidx.dst;
575 		switch(dst->sa.sa_family) {
576 		case AF_INET:
577 			ip = mtod(m, struct ip *);
578 			i = ip->ip_hl << 2;
579 			off = offsetof(struct ip, ip_p);
580 			break;
581 #ifdef INET6
582 		case AF_INET6:
583 			i = sizeof(struct ip6_hdr);
584 			off = offsetof(struct ip6_hdr, ip6_nxt);
585 			break;
586 #endif /* INET6 */
587 		default:
588 		DPRINTF(("%s: unsupported protocol family %u\n",
589 				 __func__, dst->sa.sa_family));
590 			error = EPFNOSUPPORT;
591 			IPSECSTAT_INC(ips_out_inval);
592 			goto bad;
593 		}
594 		error = (*sav->tdb_xform->xf_output)(m, isr, NULL, i, off);
595 	} else {
596 		error = ipsec_process_done(m, isr);
597 	}
598 	IPSECREQUEST_UNLOCK(isr);
599 	return error;
600 bad:
601 	if (isr)
602 		IPSECREQUEST_UNLOCK(isr);
603 	if (m)
604 		m_freem(m);
605 	return error;
606 }
607 #endif
608 
609 
610 #ifdef INET6
611 static int
612 in6_sa_equal_addrwithscope(const struct sockaddr_in6 *sa, const struct in6_addr *ia)
613 {
614 	struct in6_addr ia2;
615 
616 	memcpy(&ia2, &sa->sin6_addr, sizeof(ia2));
617 	if (IN6_IS_SCOPE_LINKLOCAL(&sa->sin6_addr))
618 		ia2.s6_addr16[1] = htons(sa->sin6_scope_id);
619 
620 	return IN6_ARE_ADDR_EQUAL(ia, &ia2);
621 }
622 
623 /*
624  * IPsec output logic for IPv6.
625  */
626 int
627 ipsec6_process_packet(
628 	struct mbuf *m,
629  	struct ipsecrequest *isr
630     )
631 {
632 	struct secasindex saidx;
633 	struct secasvar *sav;
634 	struct ip6_hdr *ip6;
635 	int error, i, off;
636 	union sockaddr_union *dst;
637 
638 	IPSEC_ASSERT(m != NULL, ("ipsec6_process_packet: null mbuf"));
639 	IPSEC_ASSERT(isr != NULL, ("ipsec6_process_packet: null isr"));
640 
641 	IPSECREQUEST_LOCK(isr);		/* insure SA contents don't change */
642 
643 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
644 	if (isr == NULL) {
645 		if (error != 0)
646 			goto bad;
647 		return EJUSTRETURN;
648 	}
649 
650 	sav = isr->sav;
651 	dst = &sav->sah->saidx.dst;
652 
653 	ip6 = mtod(m, struct ip6_hdr *);
654 	ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
655 #ifdef DEV_ENC
656 	if_inc_counter(encif, IFCOUNTER_OPACKETS, 1);
657 	if_inc_counter(encif, IFCOUNTER_OBYTES, m->m_pkthdr.len);
658 
659 	/* pass the mbuf to enc0 for bpf processing */
660 	ipsec_bpf(m, isr->sav, AF_INET6, ENC_OUT|ENC_BEFORE);
661 	/* pass the mbuf to enc0 for packet filtering */
662 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_BEFORE)) != 0)
663 		goto bad;
664 #endif /* DEV_ENC */
665 
666 	/* Do the appropriate encapsulation, if necessary */
667 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
668 	    dst->sa.sa_family != AF_INET6 ||        /* PF mismatch */
669 	    ((dst->sa.sa_family == AF_INET6) &&
670 	     (!IN6_IS_ADDR_UNSPECIFIED(&dst->sin6.sin6_addr)) &&
671 	     (!in6_sa_equal_addrwithscope(&dst->sin6,
672 				  &ip6->ip6_dst)))) {
673 		struct mbuf *mp;
674 
675 		/* Fix IPv6 header payload length. */
676 		if (m->m_len < sizeof(struct ip6_hdr))
677 			if ((m = m_pullup(m,sizeof(struct ip6_hdr))) == NULL) {
678 				error = ENOBUFS;
679 				goto bad;
680 			}
681 
682 		if (m->m_pkthdr.len - sizeof(*ip6) > IPV6_MAXPACKET) {
683 			/* No jumbogram support. */
684 			error = ENXIO;   /*XXX*/
685 			goto bad;
686 		}
687 
688 		/* Encapsulate the packet */
689 		error = ipip_output(m, isr, &mp, 0, 0);
690 		if (mp == NULL && !error) {
691 			/* Should never happen. */
692 			DPRINTF(("ipsec6_process_packet: ipip_output "
693 				 "returns no mbuf and no error!"));
694 			error = EFAULT;
695 			goto bad;
696 		}
697 
698 		if (error) {
699 			if (mp) {
700 				/* XXX: Should never happen! */
701 				m_freem(mp);
702 			}
703 			m = NULL; /* ipip_output() already freed it */
704 			goto bad;
705 		}
706 
707 		m = mp;
708 		mp = NULL;
709 	}
710 
711 #ifdef DEV_ENC
712 	ipsec_bpf(m, isr->sav, dst->sa.sa_family, ENC_OUT|ENC_AFTER);
713 	/* pass the mbuf to enc0 for packet filtering */
714 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_AFTER)) != 0)
715 		goto bad;
716 #endif /* DEV_ENC */
717 
718 	switch(dst->sa.sa_family) {
719 #ifdef INET
720 	case AF_INET:
721 		{
722 		struct ip *ip;
723 		ip = mtod(m, struct ip *);
724 		i = ip->ip_hl << 2;
725 		off = offsetof(struct ip, ip_p);
726 		}
727 		break;
728 #endif /* AF_INET */
729 	case AF_INET6:
730 		i = sizeof(struct ip6_hdr);
731 		off = offsetof(struct ip6_hdr, ip6_nxt);
732 		break;
733 	default:
734 		DPRINTF(("%s: unsupported protocol family %u\n",
735 				 __func__, dst->sa.sa_family));
736 		error = EPFNOSUPPORT;
737 		IPSEC6STAT_INC(ips_out_inval);
738 		goto bad;
739 	}
740 	error = (*sav->tdb_xform->xf_output)(m, isr, NULL, i, off);
741 	IPSECREQUEST_UNLOCK(isr);
742 	return error;
743 bad:
744 
745 	if (isr)
746 		IPSECREQUEST_UNLOCK(isr);
747 	if (m)
748 		m_freem(m);
749 	return error;
750 }
751 #endif /*INET6*/
752