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