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