xref: /freebsd/sys/netipsec/ipsec_output.c (revision 89d18518)
1 /*-
2  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 /*
30  * IPsec output processing.
31  */
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_ipsec.h"
35 #include "opt_enc.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/mbuf.h>
40 #include <sys/domain.h>
41 #include <sys/protosw.h>
42 #include <sys/socket.h>
43 #include <sys/errno.h>
44 #include <sys/syslog.h>
45 #include <sys/vimage.h>
46 
47 #include <net/if.h>
48 #include <net/pfil.h>
49 #include <net/route.h>
50 
51 #include <netinet/in.h>
52 #include <netinet/in_systm.h>
53 #include <netinet/ip.h>
54 #include <netinet/ip_var.h>
55 #include <netinet/in_var.h>
56 #include <netinet/ip_ecn.h>
57 #ifdef INET6
58 #include <netinet6/ip6_ecn.h>
59 #endif
60 
61 #include <netinet/ip6.h>
62 #ifdef INET6
63 #include <netinet6/ip6_var.h>
64 #endif
65 #include <netinet/in_pcb.h>
66 #ifdef INET6
67 #include <netinet/icmp6.h>
68 #include <netinet6/vinet6.h>
69 #endif
70 
71 #include <netipsec/ipsec.h>
72 #ifdef INET6
73 #include <netipsec/ipsec6.h>
74 #endif
75 #include <netipsec/ah_var.h>
76 #include <netipsec/esp_var.h>
77 #include <netipsec/ipcomp_var.h>
78 
79 #include <netipsec/xform.h>
80 
81 #include <netipsec/key.h>
82 #include <netipsec/keydb.h>
83 #include <netipsec/key_debug.h>
84 
85 #include <machine/in_cksum.h>
86 
87 #ifdef DEV_ENC
88 #include <net/if_enc.h>
89 #endif
90 
91 
92 int
93 ipsec_process_done(struct mbuf *m, struct ipsecrequest *isr)
94 {
95 	INIT_VNET_IPSEC(curvnet);
96 	struct tdb_ident *tdbi;
97 	struct m_tag *mtag;
98 	struct secasvar *sav;
99 	struct secasindex *saidx;
100 	int error;
101 
102 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
103 	IPSEC_ASSERT(isr != NULL, ("null ISR"));
104 	sav = isr->sav;
105 	IPSEC_ASSERT(sav != NULL, ("null SA"));
106 	IPSEC_ASSERT(sav->sah != NULL, ("null SAH"));
107 
108 	saidx = &sav->sah->saidx;
109 	switch (saidx->dst.sa.sa_family) {
110 #ifdef INET
111 	case AF_INET:
112 		/* Fix the header length, for AH processing. */
113 		mtod(m, struct ip *)->ip_len = htons(m->m_pkthdr.len);
114 		break;
115 #endif /* INET */
116 #ifdef INET6
117 	case AF_INET6:
118 		/* Fix the header length, for AH processing. */
119 		if (m->m_pkthdr.len < sizeof (struct ip6_hdr)) {
120 			error = ENXIO;
121 			goto bad;
122 		}
123 		if (m->m_pkthdr.len - sizeof (struct ip6_hdr) > IPV6_MAXPACKET) {
124 			/* No jumbogram support. */
125 			error = ENXIO;	/*?*/
126 			goto bad;
127 		}
128 		mtod(m, struct ip6_hdr *)->ip6_plen =
129 			htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
130 		break;
131 #endif /* INET6 */
132 	default:
133 		DPRINTF(("%s: unknown protocol family %u\n", __func__,
134 		    saidx->dst.sa.sa_family));
135 		error = ENXIO;
136 		goto bad;
137 	}
138 
139 	/*
140 	 * Add a record of what we've done or what needs to be done to the
141 	 * packet.
142 	 */
143 	mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE,
144 			sizeof(struct tdb_ident), M_NOWAIT);
145 	if (mtag == NULL) {
146 		DPRINTF(("%s: could not get packet tag\n", __func__));
147 		error = ENOMEM;
148 		goto bad;
149 	}
150 
151 	tdbi = (struct tdb_ident *)(mtag + 1);
152 	tdbi->dst = saidx->dst;
153 	tdbi->proto = saidx->proto;
154 	tdbi->spi = sav->spi;
155 	m_tag_prepend(m, mtag);
156 
157 	/*
158 	 * If there's another (bundled) SA to apply, do so.
159 	 * Note that this puts a burden on the kernel stack size.
160 	 * If this is a problem we'll need to introduce a queue
161 	 * to set the packet on so we can unwind the stack before
162 	 * doing further processing.
163 	 */
164 	if (isr->next) {
165 		V_ipsec4stat.ips_out_bundlesa++;
166 		return ipsec4_process_packet(m, isr->next, 0, 0);
167 	}
168 	key_sa_recordxfer(sav, m);		/* record data transfer */
169 
170 	/*
171 	 * We're done with IPsec processing, transmit the packet using the
172 	 * appropriate network protocol (IP or IPv6). SPD lookup will be
173 	 * performed again there.
174 	 */
175 	switch (saidx->dst.sa.sa_family) {
176 #ifdef INET
177 	struct ip *ip;
178 	case AF_INET:
179 		ip = mtod(m, struct ip *);
180 		ip->ip_len = ntohs(ip->ip_len);
181 		ip->ip_off = ntohs(ip->ip_off);
182 
183 		return ip_output(m, NULL, NULL, IP_RAWOUTPUT, NULL, NULL);
184 #endif /* INET */
185 #ifdef INET6
186 	case AF_INET6:
187 		/*
188 		 * We don't need massage, IPv6 header fields are always in
189 		 * net endian.
190 		 */
191 		return ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
192 #endif /* INET6 */
193 	}
194 	panic("ipsec_process_done");
195 bad:
196 	m_freem(m);
197 	KEY_FREESAV(&sav);
198 	return (error);
199 }
200 
201 static struct ipsecrequest *
202 ipsec_nextisr(
203 	struct mbuf *m,
204 	struct ipsecrequest *isr,
205 	int af,
206 	struct secasindex *saidx,
207 	int *error
208 )
209 {
210 #define IPSEC_OSTAT(x,y,z) (isr->saidx.proto == IPPROTO_ESP ? (x)++ : \
211 			    isr->saidx.proto == IPPROTO_AH ? (y)++ : (z)++)
212 	INIT_VNET_IPSEC(curvnet);
213 	struct secasvar *sav;
214 
215 	IPSECREQUEST_LOCK_ASSERT(isr);
216 
217 	IPSEC_ASSERT(af == AF_INET || af == AF_INET6,
218 		("invalid address family %u", af));
219 again:
220 	/*
221 	 * Craft SA index to search for proper SA.  Note that
222 	 * we only fillin unspecified SA peers for transport
223 	 * mode; for tunnel mode they must already be filled in.
224 	 */
225 	*saidx = isr->saidx;
226 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
227 		/* Fillin unspecified SA peers only for transport mode */
228 		if (af == AF_INET) {
229 			struct sockaddr_in *sin;
230 			struct ip *ip = mtod(m, struct ip *);
231 
232 			if (saidx->src.sa.sa_len == 0) {
233 				sin = &saidx->src.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_src;
238 			}
239 			if (saidx->dst.sa.sa_len == 0) {
240 				sin = &saidx->dst.sin;
241 				sin->sin_len = sizeof(*sin);
242 				sin->sin_family = AF_INET;
243 				sin->sin_port = IPSEC_PORT_ANY;
244 				sin->sin_addr = ip->ip_dst;
245 			}
246 		} else {
247 			struct sockaddr_in6 *sin6;
248 			struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
249 
250 			if (saidx->src.sin6.sin6_len == 0) {
251 				sin6 = (struct sockaddr_in6 *)&saidx->src;
252 				sin6->sin6_len = sizeof(*sin6);
253 				sin6->sin6_family = AF_INET6;
254 				sin6->sin6_port = IPSEC_PORT_ANY;
255 				sin6->sin6_addr = ip6->ip6_src;
256 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
257 					/* fix scope id for comparing SPD */
258 					sin6->sin6_addr.s6_addr16[1] = 0;
259 					sin6->sin6_scope_id =
260 					    ntohs(ip6->ip6_src.s6_addr16[1]);
261 				}
262 			}
263 			if (saidx->dst.sin6.sin6_len == 0) {
264 				sin6 = (struct sockaddr_in6 *)&saidx->dst;
265 				sin6->sin6_len = sizeof(*sin6);
266 				sin6->sin6_family = AF_INET6;
267 				sin6->sin6_port = IPSEC_PORT_ANY;
268 				sin6->sin6_addr = ip6->ip6_dst;
269 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
270 					/* fix scope id for comparing SPD */
271 					sin6->sin6_addr.s6_addr16[1] = 0;
272 					sin6->sin6_scope_id =
273 					    ntohs(ip6->ip6_dst.s6_addr16[1]);
274 				}
275 			}
276 		}
277 	}
278 
279 	/*
280 	 * Lookup SA and validate it.
281 	 */
282 	*error = key_checkrequest(isr, saidx);
283 	if (*error != 0) {
284 		/*
285 		 * IPsec processing is required, but no SA found.
286 		 * I assume that key_acquire() had been called
287 		 * to get/establish the SA. Here I discard
288 		 * this packet because it is responsibility for
289 		 * upper layer to retransmit the packet.
290 		 */
291 		V_ipsec4stat.ips_out_nosa++;
292 		goto bad;
293 	}
294 	sav = isr->sav;
295 	if (sav == NULL) {
296 		IPSEC_ASSERT(ipsec_get_reqlevel(isr) == IPSEC_LEVEL_USE,
297 			("no SA found, but required; level %u",
298 			ipsec_get_reqlevel(isr)));
299 		IPSECREQUEST_UNLOCK(isr);
300 		isr = isr->next;
301 		/*
302 		 * If isr is NULL, we found a 'use' policy w/o SA.
303 		 * Return w/o error and w/o isr so we can drop out
304 		 * and continue w/o IPsec processing.
305 		 */
306 		if (isr == NULL)
307 			return isr;
308 		IPSECREQUEST_LOCK(isr);
309 		goto again;
310 	}
311 
312 	/*
313 	 * Check system global policy controls.
314 	 */
315 	if ((isr->saidx.proto == IPPROTO_ESP && !V_esp_enable) ||
316 	    (isr->saidx.proto == IPPROTO_AH && !V_ah_enable) ||
317 	    (isr->saidx.proto == IPPROTO_IPCOMP && !V_ipcomp_enable)) {
318 		DPRINTF(("%s: IPsec outbound packet dropped due"
319 			" to policy (check your sysctls)\n", __func__));
320 		IPSEC_OSTAT(V_espstat.esps_pdrops, V_ahstat.ahs_pdrops,
321 		    V_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(("%s: no transform for SA\n", __func__));
332 		IPSEC_OSTAT(V_espstat.esps_noxform, V_ahstat.ahs_noxform,
333 		    V_ipcompstat.ipcomps_noxform);
334 		*error = EHOSTUNREACH;
335 		goto bad;
336 	}
337 	return isr;
338 bad:
339 	IPSEC_ASSERT(*error != 0, ("error return w/ no error code"));
340 	IPSECREQUEST_UNLOCK(isr);
341 	return NULL;
342 #undef IPSEC_OSTAT
343 }
344 
345 #ifdef INET
346 /*
347  * IPsec output logic for IPv4.
348  */
349 int
350 ipsec4_process_packet(
351 	struct mbuf *m,
352 	struct ipsecrequest *isr,
353 	int flags,
354 	int tunalready)
355 {
356 	INIT_VNET_IPSEC(curvnet);
357 	struct secasindex saidx;
358 	struct secasvar *sav;
359 	struct ip *ip;
360 	int error, i, off;
361 
362 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
363 	IPSEC_ASSERT(isr != NULL, ("null isr"));
364 
365 	IPSECREQUEST_LOCK(isr);		/* insure SA contents don't change */
366 
367 	isr = ipsec_nextisr(m, isr, AF_INET, &saidx, &error);
368 	if (isr == NULL) {
369 		if (error != 0)
370 			goto bad;
371 		return EJUSTRETURN;
372 	}
373 
374 	sav = isr->sav;
375 
376 #ifdef DEV_ENC
377 	encif->if_opackets++;
378 	encif->if_obytes += m->m_pkthdr.len;
379 
380 	/* pass the mbuf to enc0 for bpf processing */
381 	ipsec_bpf(m, sav, AF_INET, ENC_OUT|ENC_BEFORE);
382 	/* pass the mbuf to enc0 for packet filtering */
383 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_BEFORE)) != 0)
384 		goto bad;
385 #endif
386 
387 	if (!tunalready) {
388 		union sockaddr_union *dst = &sav->sah->saidx.dst;
389 		int setdf;
390 
391 		/*
392 		 * Collect IP_DF state from the outer header.
393 		 */
394 		if (dst->sa.sa_family == AF_INET) {
395 			if (m->m_len < sizeof (struct ip) &&
396 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
397 				error = ENOBUFS;
398 				goto bad;
399 			}
400 			ip = mtod(m, struct ip *);
401 			/* Honor system-wide control of how to handle IP_DF */
402 			switch (V_ip4_ipsec_dfbit) {
403 			case 0:			/* clear in outer header */
404 			case 1:			/* set in outer header */
405 				setdf = V_ip4_ipsec_dfbit;
406 				break;
407 			default:		/* propagate to outer header */
408 				setdf = ntohs(ip->ip_off & IP_DF);
409 				break;
410 			}
411 		} else {
412 			ip = NULL;		/* keep compiler happy */
413 			setdf = 0;
414 		}
415 		/* Do the appropriate encapsulation, if necessary */
416 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
417 		    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
418 #if 0
419 		    (sav->flags & SADB_X_SAFLAGS_TUNNEL) || /* Tunnel requ'd */
420 		    sav->tdb_xform->xf_type == XF_IP4 ||    /* ditto */
421 #endif
422 		    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
423 		     dst->sin.sin_addr.s_addr != INADDR_ANY &&
424 		     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
425 			struct mbuf *mp;
426 
427 			/* Fix IPv4 header checksum and length */
428 			if (m->m_len < sizeof (struct ip) &&
429 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
430 				error = ENOBUFS;
431 				goto bad;
432 			}
433 			ip = mtod(m, struct ip *);
434 			ip->ip_len = htons(m->m_pkthdr.len);
435 			ip->ip_sum = 0;
436 #ifdef _IP_VHL
437 			if (ip->ip_vhl == IP_VHL_BORING)
438 				ip->ip_sum = in_cksum_hdr(ip);
439 			else
440 				ip->ip_sum = in_cksum(m,
441 					_IP_VHL_HL(ip->ip_vhl) << 2);
442 #else
443 			ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
444 #endif
445 
446 			/* Encapsulate the packet */
447 			error = ipip_output(m, isr, &mp, 0, 0);
448 			if (mp == NULL && !error) {
449 				/* Should never happen. */
450 				DPRINTF(("%s: ipip_output returns no mbuf and "
451 					"no error!", __func__));
452 				error = EFAULT;
453 			}
454 			if (error) {
455 				if (mp) {
456 					/* XXX: Should never happen! */
457 					m_freem(mp);
458 				}
459 				m = NULL; /* ipip_output() already freed it */
460 				goto bad;
461 			}
462 			m = mp, mp = NULL;
463 			/*
464 			 * ipip_output clears IP_DF in the new header.  If
465 			 * we need to propagate IP_DF from the outer header,
466 			 * then we have to do it here.
467 			 *
468 			 * XXX shouldn't assume what ipip_output does.
469 			 */
470 			if (dst->sa.sa_family == AF_INET && setdf) {
471 				if (m->m_len < sizeof (struct ip) &&
472 				    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
473 					error = ENOBUFS;
474 					goto bad;
475 				}
476 				ip = mtod(m, struct ip *);
477 				ip->ip_off = ntohs(ip->ip_off);
478 				ip->ip_off |= IP_DF;
479 				ip->ip_off = htons(ip->ip_off);
480 			}
481 		}
482 	}
483 
484 #ifdef DEV_ENC
485 	/* pass the mbuf to enc0 for bpf processing */
486 	ipsec_bpf(m, sav, AF_INET, ENC_OUT|ENC_AFTER);
487 	/* pass the mbuf to enc0 for packet filtering */
488 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_AFTER)) != 0)
489 		goto bad;
490 #endif
491 
492 	/*
493 	 * Dispatch to the appropriate IPsec transform logic.  The
494 	 * packet will be returned for transmission after crypto
495 	 * processing, etc. are completed.  For encapsulation we
496 	 * bypass this call because of the explicit call done above
497 	 * (necessary to deal with IP_DF handling for IPv4).
498 	 *
499 	 * NB: m & sav are ``passed to caller'' who's reponsible for
500 	 *     for reclaiming their resources.
501 	 */
502 	if (sav->tdb_xform->xf_type != XF_IP4) {
503 		ip = mtod(m, struct ip *);
504 		i = ip->ip_hl << 2;
505 		off = offsetof(struct ip, ip_p);
506 		error = (*sav->tdb_xform->xf_output)(m, isr, NULL, i, off);
507 	} else {
508 		error = ipsec_process_done(m, isr);
509 	}
510 	IPSECREQUEST_UNLOCK(isr);
511 	return error;
512 bad:
513 	if (isr)
514 		IPSECREQUEST_UNLOCK(isr);
515 	if (m)
516 		m_freem(m);
517 	return error;
518 }
519 #endif
520 
521 #ifdef INET6
522 /*
523  * Chop IP6 header from the payload.
524  */
525 static struct mbuf *
526 ipsec6_splithdr(struct mbuf *m)
527 {
528 	struct mbuf *mh;
529 	struct ip6_hdr *ip6;
530 	int hlen;
531 
532 	IPSEC_ASSERT(m->m_len >= sizeof (struct ip6_hdr),
533 		("first mbuf too short, len %u", m->m_len));
534 	ip6 = mtod(m, struct ip6_hdr *);
535 	hlen = sizeof(struct ip6_hdr);
536 	if (m->m_len > hlen) {
537 		MGETHDR(mh, M_DONTWAIT, MT_DATA);
538 		if (!mh) {
539 			m_freem(m);
540 			return NULL;
541 		}
542 		M_MOVE_PKTHDR(mh, m);
543 		MH_ALIGN(mh, hlen);
544 		m->m_len -= hlen;
545 		m->m_data += hlen;
546 		mh->m_next = m;
547 		m = mh;
548 		m->m_len = hlen;
549 		bcopy((caddr_t)ip6, mtod(m, caddr_t), hlen);
550 	} else if (m->m_len < hlen) {
551 		m = m_pullup(m, hlen);
552 		if (!m)
553 			return NULL;
554 	}
555 	return m;
556 }
557 
558 /*
559  * IPsec output logic for IPv6, transport mode.
560  */
561 int
562 ipsec6_output_trans(
563 	struct ipsec_output_state *state,
564 	u_char *nexthdrp,
565 	struct mbuf *mprev,
566 	struct secpolicy *sp,
567 	int flags,
568 	int *tun)
569 {
570 	INIT_VNET_IPSEC(curvnet);
571 	struct ipsecrequest *isr;
572 	struct secasindex saidx;
573 	int error = 0;
574 	struct mbuf *m;
575 
576 	IPSEC_ASSERT(state != NULL, ("null state"));
577 	IPSEC_ASSERT(state->m != NULL, ("null m"));
578 	IPSEC_ASSERT(nexthdrp != NULL, ("null nexthdrp"));
579 	IPSEC_ASSERT(mprev != NULL, ("null mprev"));
580 	IPSEC_ASSERT(sp != NULL, ("null sp"));
581 	IPSEC_ASSERT(tun != NULL, ("null tun"));
582 
583 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
584 		printf("%s: applied SP\n", __func__);
585 		kdebug_secpolicy(sp));
586 
587 	isr = sp->req;
588 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
589 		/* the rest will be handled by ipsec6_output_tunnel() */
590 		*tun = 1;		/* need tunnel-mode processing */
591 		return 0;
592 	}
593 
594 	*tun = 0;
595 	m = state->m;
596 
597 	IPSECREQUEST_LOCK(isr);		/* insure SA contents don't change */
598 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
599 	if (isr == NULL) {
600 		if (error != 0) {
601 #ifdef notdef
602 			/* XXX should notification be done for all errors ? */
603 			/*
604 			 * Notify the fact that the packet is discarded
605 			 * to ourselves. I believe this is better than
606 			 * just silently discarding. (jinmei@kame.net)
607 			 * XXX: should we restrict the error to TCP packets?
608 			 * XXX: should we directly notify sockets via
609 			 *      pfctlinputs?
610 			 */
611 			icmp6_error(m, ICMP6_DST_UNREACH,
612 				    ICMP6_DST_UNREACH_ADMIN, 0);
613 			m = NULL;	/* NB: icmp6_error frees mbuf */
614 #endif
615 			goto bad;
616 		}
617 		return EJUSTRETURN;
618 	}
619 
620 	error = (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
621 						  sizeof (struct ip6_hdr),
622 						  offsetof(struct ip6_hdr,
623 							   ip6_nxt));
624 	IPSECREQUEST_UNLOCK(isr);
625 	return error;
626 bad:
627 	if (isr)
628 		IPSECREQUEST_UNLOCK(isr);
629 	if (m)
630 		m_freem(m);
631 	state->m = NULL;
632 	return error;
633 }
634 
635 static int
636 ipsec6_encapsulate(struct mbuf *m, struct secasvar *sav)
637 {
638 	INIT_VNET_IPSEC(curvnet);
639 	struct ip6_hdr *oip6;
640 	struct ip6_hdr *ip6;
641 	size_t plen;
642 
643 	/* can't tunnel between different AFs */
644 	if (sav->sah->saidx.src.sa.sa_family != AF_INET6 ||
645 	    sav->sah->saidx.dst.sa.sa_family != AF_INET6) {
646 		m_freem(m);
647 		return EINVAL;
648 	}
649 	IPSEC_ASSERT(m->m_len == sizeof (struct ip6_hdr),
650 		("mbuf wrong size; len %u", m->m_len));
651 
652 
653 	/*
654 	 * grow the mbuf to accomodate the new IPv6 header.
655 	 */
656 	plen = m->m_pkthdr.len;
657 	if (M_LEADINGSPACE(m->m_next) < sizeof(struct ip6_hdr)) {
658 		struct mbuf *n;
659 		MGET(n, M_DONTWAIT, MT_DATA);
660 		if (!n) {
661 			m_freem(m);
662 			return ENOBUFS;
663 		}
664 		n->m_len = sizeof(struct ip6_hdr);
665 		n->m_next = m->m_next;
666 		m->m_next = n;
667 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
668 		oip6 = mtod(n, struct ip6_hdr *);
669 	} else {
670 		m->m_next->m_len += sizeof(struct ip6_hdr);
671 		m->m_next->m_data -= sizeof(struct ip6_hdr);
672 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
673 		oip6 = mtod(m->m_next, struct ip6_hdr *);
674 	}
675 	ip6 = mtod(m, struct ip6_hdr *);
676 	bcopy((caddr_t)ip6, (caddr_t)oip6, sizeof(struct ip6_hdr));
677 
678 	/* Fake link-local scope-class addresses */
679 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_src))
680 		oip6->ip6_src.s6_addr16[1] = 0;
681 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_dst))
682 		oip6->ip6_dst.s6_addr16[1] = 0;
683 
684 	/* construct new IPv6 header. see RFC 2401 5.1.2.2 */
685 	/* ECN consideration. */
686 	ip6_ecn_ingress(V_ip6_ipsec_ecn, &ip6->ip6_flow, &oip6->ip6_flow);
687 	if (plen < IPV6_MAXPACKET - sizeof(struct ip6_hdr))
688 		ip6->ip6_plen = htons(plen);
689 	else {
690 		/* ip6->ip6_plen will be updated in ip6_output() */
691 	}
692 	ip6->ip6_nxt = IPPROTO_IPV6;
693 	ip6->ip6_src = sav->sah->saidx.src.sin6.sin6_addr;
694 	ip6->ip6_dst = sav->sah->saidx.dst.sin6.sin6_addr;
695 	ip6->ip6_hlim = IPV6_DEFHLIM;
696 
697 	/* XXX Should ip6_src be updated later ? */
698 
699 	return 0;
700 }
701 
702 /*
703  * IPsec output logic for IPv6, tunnel mode.
704  */
705 int
706 ipsec6_output_tunnel(struct ipsec_output_state *state, struct secpolicy *sp, int flags)
707 {
708 	INIT_VNET_INET6(curvnet);
709 	INIT_VNET_IPSEC(curvnet);
710 	struct ip6_hdr *ip6;
711 	struct ipsecrequest *isr;
712 	struct secasindex saidx;
713 	int error;
714 	struct sockaddr_in6* dst6;
715 	struct mbuf *m;
716 
717 	IPSEC_ASSERT(state != NULL, ("null state"));
718 	IPSEC_ASSERT(state->m != NULL, ("null m"));
719 	IPSEC_ASSERT(sp != NULL, ("null sp"));
720 
721 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
722 		printf("%s: applied SP\n", __func__);
723 		kdebug_secpolicy(sp));
724 
725 	m = state->m;
726 	/*
727 	 * transport mode ipsec (before the 1st tunnel mode) is already
728 	 * processed by ipsec6_output_trans().
729 	 */
730 	for (isr = sp->req; isr; isr = isr->next) {
731 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
732 			break;
733 	}
734 
735 	IPSECREQUEST_LOCK(isr);		/* insure SA contents don't change */
736 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
737 	if (isr == NULL) {
738 		if (error != 0)
739 			goto bad;
740 		return EJUSTRETURN;
741 	}
742 
743 #ifdef DEV_ENC
744 	encif->if_opackets++;
745 	encif->if_obytes += m->m_pkthdr.len;
746 
747 	/* pass the mbuf to enc0 for bpf processing */
748 	ipsec_bpf(m, isr->sav, AF_INET6, ENC_OUT|ENC_BEFORE);
749 	/* pass the mbuf to enc0 for packet filtering */
750 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_BEFORE)) != 0)
751 		goto bad;
752 #endif
753 
754 	/*
755 	 * There may be the case that SA status will be changed when
756 	 * we are refering to one. So calling splsoftnet().
757 	 */
758 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
759 		/*
760 		 * build IPsec tunnel.
761 		 */
762 		/* XXX should be processed with other familiy */
763 		if (isr->sav->sah->saidx.src.sa.sa_family != AF_INET6) {
764 			ipseclog((LOG_ERR, "%s: family mismatched between "
765 			    "inner and outer, spi=%u\n", __func__,
766 			    ntohl(isr->sav->spi)));
767 			V_ipsec6stat.ips_out_inval++;
768 			error = EAFNOSUPPORT;
769 			goto bad;
770 		}
771 
772 		m = ipsec6_splithdr(m);
773 		if (!m) {
774 			V_ipsec6stat.ips_out_nomem++;
775 			error = ENOMEM;
776 			goto bad;
777 		}
778 		error = ipsec6_encapsulate(m, isr->sav);
779 		if (error) {
780 			m = NULL;
781 			goto bad;
782 		}
783 		ip6 = mtod(m, struct ip6_hdr *);
784 
785 		state->ro = &isr->sav->sah->sa_route;
786 		state->dst = (struct sockaddr *)&state->ro->ro_dst;
787 		dst6 = (struct sockaddr_in6 *)state->dst;
788 		if (state->ro->ro_rt
789 		 && ((state->ro->ro_rt->rt_flags & RTF_UP) == 0
790 		  || !IN6_ARE_ADDR_EQUAL(&dst6->sin6_addr, &ip6->ip6_dst))) {
791 			RTFREE(state->ro->ro_rt);
792 			state->ro->ro_rt = NULL;
793 		}
794 		if (state->ro->ro_rt == NULL) {
795 			bzero(dst6, sizeof(*dst6));
796 			dst6->sin6_family = AF_INET6;
797 			dst6->sin6_len = sizeof(*dst6);
798 			dst6->sin6_addr = ip6->ip6_dst;
799 			rtalloc(state->ro);
800 		}
801 		if (state->ro->ro_rt == NULL) {
802 			V_ip6stat.ip6s_noroute++;
803 			V_ipsec6stat.ips_out_noroute++;
804 			error = EHOSTUNREACH;
805 			goto bad;
806 		}
807 
808 		/* adjust state->dst if tunnel endpoint is offlink */
809 		if (state->ro->ro_rt->rt_flags & RTF_GATEWAY) {
810 			state->dst = (struct sockaddr *)state->ro->ro_rt->rt_gateway;
811 			dst6 = (struct sockaddr_in6 *)state->dst;
812 		}
813 	}
814 
815 	m = ipsec6_splithdr(m);
816 	if (!m) {
817 		V_ipsec6stat.ips_out_nomem++;
818 		error = ENOMEM;
819 		goto bad;
820 	}
821 	ip6 = mtod(m, struct ip6_hdr *);
822 
823 #ifdef DEV_ENC
824 	/* pass the mbuf to enc0 for bpf processing */
825 	ipsec_bpf(m, isr->sav, AF_INET6, ENC_OUT|ENC_AFTER);
826 	/* pass the mbuf to enc0 for packet filtering */
827 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_AFTER)) != 0)
828 		goto bad;
829 #endif
830 
831 	error = (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
832 		sizeof (struct ip6_hdr),
833 		offsetof(struct ip6_hdr, ip6_nxt));
834 	IPSECREQUEST_UNLOCK(isr);
835 	return error;
836 bad:
837 	if (isr)
838 		IPSECREQUEST_UNLOCK(isr);
839 	if (m)
840 		m_freem(m);
841 	state->m = NULL;
842 	return error;
843 }
844 #endif /*INET6*/
845