xref: /freebsd/sys/netipsec/ipsec_output.c (revision 729362425c09cf6b362366aabc6fb547eee8035a)
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 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/mbuf.h>
39 #include <sys/domain.h>
40 #include <sys/protosw.h>
41 #include <sys/socket.h>
42 #include <sys/errno.h>
43 #include <sys/syslog.h>
44 
45 #include <net/if.h>
46 #include <net/route.h>
47 
48 #include <netinet/in.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/ip.h>
51 #include <netinet/ip_var.h>
52 #include <netinet/in_var.h>
53 #include <netinet/ip_ecn.h>
54 #ifdef INET6
55 #include <netinet6/ip6_ecn.h>
56 #endif
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 
67 #include <netipsec/ipsec.h>
68 #ifdef INET6
69 #include <netipsec/ipsec6.h>
70 #endif
71 #include <netipsec/ah_var.h>
72 #include <netipsec/esp_var.h>
73 #include <netipsec/ipcomp_var.h>
74 
75 #include <netipsec/xform.h>
76 
77 #include <netipsec/key.h>
78 #include <netipsec/keydb.h>
79 #include <netipsec/key_debug.h>
80 
81 #include <machine/in_cksum.h>
82 
83 int
84 ipsec_process_done(struct mbuf *m, struct ipsecrequest *isr)
85 {
86 	struct tdb_ident *tdbi;
87 	struct m_tag *mtag;
88 	struct secasvar *sav;
89 	struct secasindex *saidx;
90 	int error;
91 
92 #if 0
93 	SPLASSERT(net, "ipsec_process_done");
94 #endif
95 
96 	KASSERT(m != NULL, ("ipsec_process_done: null mbuf"));
97 	KASSERT(isr != NULL, ("ipsec_process_done: null ISR"));
98 	sav = isr->sav;
99 	KASSERT(sav != NULL, ("ipsec_process_done: null SA"));
100 	KASSERT(sav->sah != NULL, ("ipsec_process_done: null SAH"));
101 
102 	saidx = &sav->sah->saidx;
103 	switch (saidx->dst.sa.sa_family) {
104 #ifdef INET
105 	case AF_INET:
106 		/* Fix the header length, for AH processing. */
107 		mtod(m, struct ip *)->ip_len = htons(m->m_pkthdr.len);
108 		break;
109 #endif /* INET */
110 #ifdef INET6
111 	case AF_INET6:
112 		/* Fix the header length, for AH processing. */
113 		if (m->m_pkthdr.len < sizeof (struct ip6_hdr)) {
114 			error = ENXIO;
115 			goto bad;
116 		}
117 		if (m->m_pkthdr.len - sizeof (struct ip6_hdr) > IPV6_MAXPACKET) {
118 			/* No jumbogram support. */
119 			error = ENXIO;	/*?*/
120 			goto bad;
121 		}
122 		mtod(m, struct ip6_hdr *)->ip6_plen =
123 			htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
124 		break;
125 #endif /* INET6 */
126 	default:
127 		DPRINTF(("ipsec_process_done: unknown protocol family %u\n",
128 		    saidx->dst.sa.sa_family));
129 		error = ENXIO;
130 		goto bad;
131 	}
132 
133 	/*
134 	 * Add a record of what we've done or what needs to be done to the
135 	 * packet.
136 	 */
137 	mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE,
138 			sizeof(struct tdb_ident), M_NOWAIT);
139 	if (mtag == NULL) {
140 		DPRINTF(("ipsec_process_done: could not get packet tag\n"));
141 		error = ENOMEM;
142 		goto bad;
143 	}
144 
145 	tdbi = (struct tdb_ident *)(mtag + 1);
146 	tdbi->dst = saidx->dst;
147 	tdbi->proto = saidx->proto;
148 	tdbi->spi = sav->spi;
149 	m_tag_prepend(m, mtag);
150 
151 	/*
152 	 * If there's another (bundled) SA to apply, do so.
153 	 * Note that this puts a burden on the kernel stack size.
154 	 * If this is a problem we'll need to introduce a queue
155 	 * to set the packet on so we can unwind the stack before
156 	 * doing further processing.
157 	 */
158 	if (isr->next) {
159 		newipsecstat.ips_out_bundlesa++;
160 		return ipsec4_process_packet(m, isr->next, 0, 0);
161 	}
162 
163 	/*
164 	 * We're done with IPsec processing, transmit the packet using the
165 	 * appropriate network protocol (IP or IPv6). SPD lookup will be
166 	 * performed again there.
167 	 */
168 	switch (saidx->dst.sa.sa_family) {
169 #ifdef INET
170 	struct ip *ip;
171 	case AF_INET:
172 		ip = mtod(m, struct ip *);
173 		ip->ip_len = ntohs(ip->ip_len);
174 		ip->ip_off = ntohs(ip->ip_off);
175 
176 		return ip_output(m, NULL, NULL, IP_RAWOUTPUT, NULL, NULL);
177 #endif /* INET */
178 #ifdef INET6
179 	case AF_INET6:
180 		/*
181 		 * We don't need massage, IPv6 header fields are always in
182 		 * net endian.
183 		 */
184 		return ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
185 #endif /* INET6 */
186 	}
187 	panic("ipsec_process_done");
188 bad:
189 	m_freem(m);
190 	KEY_FREESAV(&sav);
191 	return (error);
192 }
193 
194 static struct ipsecrequest *
195 ipsec_nextisr(
196 	struct mbuf *m,
197 	struct ipsecrequest *isr,
198 	int af,
199 	struct secasindex *saidx,
200 	int *error
201 )
202 {
203 #define IPSEC_OSTAT(x,y,z) (isr->saidx.proto == IPPROTO_ESP ? (x)++ : \
204 			    isr->saidx.proto == IPPROTO_AH ? (y)++ : (z)++)
205 	struct secasvar *sav;
206 
207 #if 0
208 	SPLASSERT(net, "ipsec_nextisr");
209 #endif
210 	KASSERT(af == AF_INET || af == AF_INET6,
211 		("ipsec_nextisr: invalid address family %u", af));
212 again:
213 	/*
214 	 * Craft SA index to search for proper SA.  Note that
215 	 * we only fillin unspecified SA peers for transport
216 	 * mode; for tunnel mode they must already be filled in.
217 	 */
218 	*saidx = isr->saidx;
219 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
220 		/* Fillin unspecified SA peers only for transport mode */
221 		if (af == AF_INET) {
222 			struct sockaddr_in *sin;
223 			struct ip *ip = mtod(m, struct ip *);
224 
225 			if (saidx->src.sa.sa_len == 0) {
226 				sin = &saidx->src.sin;
227 				sin->sin_len = sizeof(*sin);
228 				sin->sin_family = AF_INET;
229 				sin->sin_port = IPSEC_PORT_ANY;
230 				sin->sin_addr = ip->ip_src;
231 			}
232 			if (saidx->dst.sa.sa_len == 0) {
233 				sin = &saidx->dst.sin;
234 				sin->sin_len = sizeof(*sin);
235 				sin->sin_family = AF_INET;
236 				sin->sin_port = IPSEC_PORT_ANY;
237 				sin->sin_addr = ip->ip_dst;
238 			}
239 		} else {
240 			struct sockaddr_in6 *sin6;
241 			struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
242 
243 			if (saidx->src.sin6.sin6_len == 0) {
244 				sin6 = (struct sockaddr_in6 *)&saidx->src;
245 				sin6->sin6_len = sizeof(*sin6);
246 				sin6->sin6_family = AF_INET6;
247 				sin6->sin6_port = IPSEC_PORT_ANY;
248 				sin6->sin6_addr = ip6->ip6_src;
249 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
250 					/* fix scope id for comparing SPD */
251 					sin6->sin6_addr.s6_addr16[1] = 0;
252 					sin6->sin6_scope_id =
253 					    ntohs(ip6->ip6_src.s6_addr16[1]);
254 				}
255 			}
256 			if (saidx->dst.sin6.sin6_len == 0) {
257 				sin6 = (struct sockaddr_in6 *)&saidx->dst;
258 				sin6->sin6_len = sizeof(*sin6);
259 				sin6->sin6_family = AF_INET6;
260 				sin6->sin6_port = IPSEC_PORT_ANY;
261 				sin6->sin6_addr = ip6->ip6_dst;
262 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
263 					/* fix scope id for comparing SPD */
264 					sin6->sin6_addr.s6_addr16[1] = 0;
265 					sin6->sin6_scope_id =
266 					    ntohs(ip6->ip6_dst.s6_addr16[1]);
267 				}
268 			}
269 		}
270 	}
271 
272 	/*
273 	 * Lookup SA and validate it.
274 	 */
275 	*error = key_checkrequest(isr, saidx);
276 	if (*error != 0) {
277 		/*
278 		 * IPsec processing is required, but no SA found.
279 		 * I assume that key_acquire() had been called
280 		 * to get/establish the SA. Here I discard
281 		 * this packet because it is responsibility for
282 		 * upper layer to retransmit the packet.
283 		 */
284 		newipsecstat.ips_out_nosa++;
285 		goto bad;
286 	}
287 	sav = isr->sav;
288 	if (sav == NULL) {		/* XXX valid return */
289 		KASSERT(ipsec_get_reqlevel(isr) == IPSEC_LEVEL_USE,
290 			("ipsec_nextisr: no SA found, but required; level %u",
291 			ipsec_get_reqlevel(isr)));
292 		isr = isr->next;
293 		if (isr == NULL) {
294 			/*XXXstatistic??*/
295 			*error = EINVAL;		/*XXX*/
296 			return isr;
297 		}
298 		goto again;
299 	}
300 
301 	/*
302 	 * Check system global policy controls.
303 	 */
304 	if ((isr->saidx.proto == IPPROTO_ESP && !esp_enable) ||
305 	    (isr->saidx.proto == IPPROTO_AH && !ah_enable) ||
306 	    (isr->saidx.proto == IPPROTO_IPCOMP && !ipcomp_enable)) {
307 		DPRINTF(("ipsec_nextisr: IPsec outbound packet dropped due"
308 			" to policy (check your sysctls)\n"));
309 		IPSEC_OSTAT(espstat.esps_pdrops, ahstat.ahs_pdrops,
310 		    ipcompstat.ipcomps_pdrops);
311 		*error = EHOSTUNREACH;
312 		goto bad;
313 	}
314 
315 	/*
316 	 * Sanity check the SA contents for the caller
317 	 * before they invoke the xform output method.
318 	 */
319 	if (sav->tdb_xform == NULL) {
320 		DPRINTF(("ipsec_nextisr: no transform for SA\n"));
321 		IPSEC_OSTAT(espstat.esps_noxform, ahstat.ahs_noxform,
322 		    ipcompstat.ipcomps_noxform);
323 		*error = EHOSTUNREACH;
324 		goto bad;
325 	}
326 	return isr;
327 bad:
328 	KASSERT(*error != 0, ("ipsec_nextisr: error return w/ no error code"));
329 	return NULL;
330 #undef IPSEC_OSTAT
331 }
332 
333 #ifdef INET
334 /*
335  * IPsec output logic for IPv4.
336  */
337 int
338 ipsec4_process_packet(
339 	struct mbuf *m,
340 	struct ipsecrequest *isr,
341 	int flags,
342 	int tunalready)
343 {
344 	struct secasindex saidx;
345 	struct secasvar *sav;
346 	struct ip *ip;
347 	int s, error, i, off;
348 
349 	KASSERT(m != NULL, ("ipsec4_process_packet: null mbuf"));
350 	KASSERT(isr != NULL, ("ipsec4_process_packet: null isr"));
351 
352 	s = splnet();			/* insure SA contents don't change */
353 
354 	isr = ipsec_nextisr(m, isr, AF_INET, &saidx, &error);
355 	if (isr == NULL)
356 		goto bad;
357 
358 	sav = isr->sav;
359 	if (!tunalready) {
360 		union sockaddr_union *dst = &sav->sah->saidx.dst;
361 		int setdf;
362 
363 		/*
364 		 * Collect IP_DF state from the outer header.
365 		 */
366 		if (dst->sa.sa_family == AF_INET) {
367 			if (m->m_len < sizeof (struct ip) &&
368 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
369 				error = ENOBUFS;
370 				goto bad;
371 			}
372 			ip = mtod(m, struct ip *);
373 			/* Honor system-wide control of how to handle IP_DF */
374 			switch (ip4_ipsec_dfbit) {
375 			case 0:			/* clear in outer header */
376 			case 1:			/* set in outer header */
377 				setdf = ip4_ipsec_dfbit;
378 				break;
379 			default:		/* propagate to outer header */
380 				setdf = ntohs(ip->ip_off & IP_DF);
381 				break;
382 			}
383 		} else {
384 			ip = NULL;		/* keep compiler happy */
385 			setdf = 0;
386 		}
387 		/* Do the appropriate encapsulation, if necessary */
388 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
389 		    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
390 #if 0
391 		    (sav->flags & SADB_X_SAFLAGS_TUNNEL) || /* Tunnel requ'd */
392 		    sav->tdb_xform->xf_type == XF_IP4 ||    /* ditto */
393 #endif
394 		    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
395 		     dst->sin.sin_addr.s_addr != INADDR_ANY &&
396 		     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
397 			struct mbuf *mp;
398 
399 			/* Fix IPv4 header checksum and length */
400 			if (m->m_len < sizeof (struct ip) &&
401 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
402 				error = ENOBUFS;
403 				goto bad;
404 			}
405 			ip = mtod(m, struct ip *);
406 			ip->ip_len = htons(m->m_pkthdr.len);
407 			ip->ip_sum = 0;
408 #ifdef _IP_VHL
409 			if (ip->ip_vhl == IP_VHL_BORING)
410 				ip->ip_sum = in_cksum_hdr(ip);
411 			else
412 				ip->ip_sum = in_cksum(m,
413 					_IP_VHL_HL(ip->ip_vhl) << 2);
414 #else
415 			ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
416 #endif
417 
418 			/* Encapsulate the packet */
419 			error = ipip_output(m, isr, &mp, 0, 0);
420 			if (mp == NULL && !error) {
421 				/* Should never happen. */
422 				DPRINTF(("ipsec4_process_packet: ipip_output "
423 					"returns no mbuf and no error!"));
424 				error = EFAULT;
425 			}
426 			if (error) {
427 				if (mp)
428 					m_freem(mp);
429 				goto bad;
430 			}
431 			m = mp, mp = NULL;
432 			/*
433 			 * ipip_output clears IP_DF in the new header.  If
434 			 * we need to propagate IP_DF from the outer header,
435 			 * then we have to do it here.
436 			 *
437 			 * XXX shouldn't assume what ipip_output does.
438 			 */
439 			if (dst->sa.sa_family == AF_INET && setdf) {
440 				if (m->m_len < sizeof (struct ip) &&
441 				    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
442 					error = ENOBUFS;
443 					goto bad;
444 				}
445 				ip = mtod(m, struct ip *);
446 				ip->ip_off = ntohs(ip->ip_off);
447 				ip->ip_off |= IP_DF;
448 				ip->ip_off = htons(ip->ip_off);
449 			}
450 		}
451 	}
452 
453 	/*
454 	 * Dispatch to the appropriate IPsec transform logic.  The
455 	 * packet will be returned for transmission after crypto
456 	 * processing, etc. are completed.  For encapsulation we
457 	 * bypass this call because of the explicit call done above
458 	 * (necessary to deal with IP_DF handling for IPv4).
459 	 *
460 	 * NB: m & sav are ``passed to caller'' who's reponsible for
461 	 *     for reclaiming their resources.
462 	 */
463 	if (sav->tdb_xform->xf_type != XF_IP4) {
464 		ip = mtod(m, struct ip *);
465 		i = ip->ip_hl << 2;
466 		off = offsetof(struct ip, ip_p);
467 		error = (*sav->tdb_xform->xf_output)(m, isr, NULL, i, off);
468 	} else {
469 		error = ipsec_process_done(m, isr);
470 	}
471 	splx(s);
472 	return error;
473 bad:
474 	splx(s);
475 	if (m)
476 		m_freem(m);
477 	return error;
478 }
479 #endif
480 
481 #ifdef INET6
482 /*
483  * Chop IP6 header from the payload.
484  */
485 static struct mbuf *
486 ipsec6_splithdr(struct mbuf *m)
487 {
488 	struct mbuf *mh;
489 	struct ip6_hdr *ip6;
490 	int hlen;
491 
492 	KASSERT(m->m_len >= sizeof (struct ip6_hdr),
493 		("ipsec6_splithdr: first mbuf too short, len %u", m->m_len));
494 	ip6 = mtod(m, struct ip6_hdr *);
495 	hlen = sizeof(struct ip6_hdr);
496 	if (m->m_len > hlen) {
497 		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
498 		if (!mh) {
499 			m_freem(m);
500 			return NULL;
501 		}
502 		M_MOVE_PKTHDR(mh, m);
503 		MH_ALIGN(mh, hlen);
504 		m->m_len -= hlen;
505 		m->m_data += hlen;
506 		mh->m_next = m;
507 		m = mh;
508 		m->m_len = hlen;
509 		bcopy((caddr_t)ip6, mtod(m, caddr_t), hlen);
510 	} else if (m->m_len < hlen) {
511 		m = m_pullup(m, hlen);
512 		if (!m)
513 			return NULL;
514 	}
515 	return m;
516 }
517 
518 /*
519  * IPsec output logic for IPv6, transport mode.
520  */
521 int
522 ipsec6_output_trans(
523 	struct ipsec_output_state *state,
524 	u_char *nexthdrp,
525 	struct mbuf *mprev,
526 	struct secpolicy *sp,
527 	int flags,
528 	int *tun)
529 {
530 	struct ipsecrequest *isr;
531 	struct secasindex saidx;
532 	int error = 0;
533 	struct mbuf *m;
534 
535 	KASSERT(state != NULL, ("ipsec6_output: null state"));
536 	KASSERT(state->m != NULL, ("ipsec6_output: null m"));
537 	KASSERT(nexthdrp != NULL, ("ipsec6_output: null nexthdrp"));
538 	KASSERT(mprev != NULL, ("ipsec6_output: null mprev"));
539 	KASSERT(sp != NULL, ("ipsec6_output: null sp"));
540 	KASSERT(tun != NULL, ("ipsec6_output: null tun"));
541 
542 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
543 		printf("ipsec6_output_trans: applyed SP\n");
544 		kdebug_secpolicy(sp));
545 
546 	isr = sp->req;
547 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
548 		/* the rest will be handled by ipsec6_output_tunnel() */
549 		*tun = 1;		/* need tunnel-mode processing */
550 		return 0;
551 	}
552 
553 	*tun = 0;
554 	m = state->m;
555 
556 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
557 	if (isr == NULL) {
558 #ifdef notdef
559 		/* XXX should notification be done for all errors ? */
560 		/*
561 		 * Notify the fact that the packet is discarded
562 		 * to ourselves. I believe this is better than
563 		 * just silently discarding. (jinmei@kame.net)
564 		 * XXX: should we restrict the error to TCP packets?
565 		 * XXX: should we directly notify sockets via
566 		 *      pfctlinputs?
567 		 */
568 		icmp6_error(m, ICMP6_DST_UNREACH,
569 			    ICMP6_DST_UNREACH_ADMIN, 0);
570 		m = NULL;	/* NB: icmp6_error frees mbuf */
571 #endif
572 		goto bad;
573 	}
574 
575 	return (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
576 		sizeof (struct ip6_hdr),
577 		offsetof(struct ip6_hdr, ip6_nxt));
578 bad:
579 	if (m)
580 		m_freem(m);
581 	state->m = NULL;
582 	return error;
583 }
584 
585 static int
586 ipsec6_encapsulate(struct mbuf *m, struct secasvar *sav)
587 {
588 	struct ip6_hdr *oip6;
589 	struct ip6_hdr *ip6;
590 	size_t plen;
591 
592 	/* can't tunnel between different AFs */
593 	if (sav->sah->saidx.src.sa.sa_family != AF_INET6 ||
594 	    sav->sah->saidx.dst.sa.sa_family != AF_INET6) {
595 		m_freem(m);
596 		return EINVAL;
597 	}
598 	KASSERT(m->m_len != sizeof (struct ip6_hdr),
599 		("ipsec6_encapsulate: mbuf wrong size; len %u", m->m_len));
600 
601 
602 	/*
603 	 * grow the mbuf to accomodate the new IPv6 header.
604 	 */
605 	plen = m->m_pkthdr.len;
606 	if (M_LEADINGSPACE(m->m_next) < sizeof(struct ip6_hdr)) {
607 		struct mbuf *n;
608 		MGET(n, M_DONTWAIT, MT_DATA);
609 		if (!n) {
610 			m_freem(m);
611 			return ENOBUFS;
612 		}
613 		n->m_len = sizeof(struct ip6_hdr);
614 		n->m_next = m->m_next;
615 		m->m_next = n;
616 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
617 		oip6 = mtod(n, struct ip6_hdr *);
618 	} else {
619 		m->m_next->m_len += sizeof(struct ip6_hdr);
620 		m->m_next->m_data -= sizeof(struct ip6_hdr);
621 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
622 		oip6 = mtod(m->m_next, struct ip6_hdr *);
623 	}
624 	ip6 = mtod(m, struct ip6_hdr *);
625 	ovbcopy((caddr_t)ip6, (caddr_t)oip6, sizeof(struct ip6_hdr));
626 
627 	/* Fake link-local scope-class addresses */
628 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_src))
629 		oip6->ip6_src.s6_addr16[1] = 0;
630 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_dst))
631 		oip6->ip6_dst.s6_addr16[1] = 0;
632 
633 	/* construct new IPv6 header. see RFC 2401 5.1.2.2 */
634 	/* ECN consideration. */
635 	ip6_ecn_ingress(ip6_ipsec_ecn, &ip6->ip6_flow, &oip6->ip6_flow);
636 	if (plen < IPV6_MAXPACKET - sizeof(struct ip6_hdr))
637 		ip6->ip6_plen = htons(plen);
638 	else {
639 		/* ip6->ip6_plen will be updated in ip6_output() */
640 	}
641 	ip6->ip6_nxt = IPPROTO_IPV6;
642 	sav->sah->saidx.src.sin6.sin6_addr = ip6->ip6_src;
643 	sav->sah->saidx.dst.sin6.sin6_addr = ip6->ip6_dst;
644 	ip6->ip6_hlim = IPV6_DEFHLIM;
645 
646 	/* XXX Should ip6_src be updated later ? */
647 
648 	return 0;
649 }
650 
651 /*
652  * IPsec output logic for IPv6, tunnel mode.
653  */
654 int
655 ipsec6_output_tunnel(struct ipsec_output_state *state, struct secpolicy *sp, int flags)
656 {
657 	struct ip6_hdr *ip6;
658 	struct ipsecrequest *isr;
659 	struct secasindex saidx;
660 	int error;
661 	struct sockaddr_in6* dst6;
662 	struct mbuf *m;
663 
664 	KASSERT(state != NULL, ("ipsec6_output: null state"));
665 	KASSERT(state->m != NULL, ("ipsec6_output: null m"));
666 	KASSERT(sp != NULL, ("ipsec6_output: null sp"));
667 
668 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
669 		printf("ipsec6_output_tunnel: applyed SP\n");
670 		kdebug_secpolicy(sp));
671 
672 	m = state->m;
673 	/*
674 	 * transport mode ipsec (before the 1st tunnel mode) is already
675 	 * processed by ipsec6_output_trans().
676 	 */
677 	for (isr = sp->req; isr; isr = isr->next) {
678 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
679 			break;
680 	}
681 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
682 	if (isr == NULL)
683 		goto bad;
684 
685 	/*
686 	 * There may be the case that SA status will be changed when
687 	 * we are refering to one. So calling splsoftnet().
688 	 */
689 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
690 		/*
691 		 * build IPsec tunnel.
692 		 */
693 		/* XXX should be processed with other familiy */
694 		if (isr->sav->sah->saidx.src.sa.sa_family != AF_INET6) {
695 			ipseclog((LOG_ERR, "ipsec6_output_tunnel: "
696 			    "family mismatched between inner and outer, spi=%u\n",
697 			    ntohl(isr->sav->spi)));
698 			newipsecstat.ips_out_inval++;
699 			error = EAFNOSUPPORT;
700 			goto bad;
701 		}
702 
703 		m = ipsec6_splithdr(m);
704 		if (!m) {
705 			newipsecstat.ips_out_nomem++;
706 			error = ENOMEM;
707 			goto bad;
708 		}
709 		error = ipsec6_encapsulate(m, isr->sav);
710 		if (error) {
711 			m = NULL;
712 			goto bad;
713 		}
714 		ip6 = mtod(m, struct ip6_hdr *);
715 
716 		state->ro = &isr->sav->sah->sa_route;
717 		state->dst = (struct sockaddr *)&state->ro->ro_dst;
718 		dst6 = (struct sockaddr_in6 *)state->dst;
719 		if (state->ro->ro_rt
720 		 && ((state->ro->ro_rt->rt_flags & RTF_UP) == 0
721 		  || !IN6_ARE_ADDR_EQUAL(&dst6->sin6_addr, &ip6->ip6_dst))) {
722 			RTFREE(state->ro->ro_rt);
723 			state->ro->ro_rt = NULL;
724 		}
725 		if (state->ro->ro_rt == 0) {
726 			bzero(dst6, sizeof(*dst6));
727 			dst6->sin6_family = AF_INET6;
728 			dst6->sin6_len = sizeof(*dst6);
729 			dst6->sin6_addr = ip6->ip6_dst;
730 			rtalloc(state->ro);
731 		}
732 		if (state->ro->ro_rt == 0) {
733 			ip6stat.ip6s_noroute++;
734 			newipsecstat.ips_out_noroute++;
735 			error = EHOSTUNREACH;
736 			goto bad;
737 		}
738 
739 		/* adjust state->dst if tunnel endpoint is offlink */
740 		if (state->ro->ro_rt->rt_flags & RTF_GATEWAY) {
741 			state->dst = (struct sockaddr *)state->ro->ro_rt->rt_gateway;
742 			dst6 = (struct sockaddr_in6 *)state->dst;
743 		}
744 	}
745 
746 	m = ipsec6_splithdr(m);
747 	if (!m) {
748 		newipsecstat.ips_out_nomem++;
749 		error = ENOMEM;
750 		goto bad;
751 	}
752 	ip6 = mtod(m, struct ip6_hdr *);
753 	return (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
754 		sizeof (struct ip6_hdr),
755 		offsetof(struct ip6_hdr, ip6_nxt));
756 bad:
757 	if (m)
758 		m_freem(m);
759 	state->m = NULL;
760 	return error;
761 }
762 #endif /*INET6*/
763