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