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