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