xref: /freebsd/sys/netipsec/ipsec_output.c (revision dda5b39711dab90ae1c5624bdd6ff7453177df31)
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/if_var.h>
48 #include <net/pfil.h>
49 #include <net/route.h>
50 #include <net/vnet.h>
51 
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h>
54 #include <netinet/ip.h>
55 #include <netinet/ip_var.h>
56 #include <netinet/in_var.h>
57 #include <netinet/ip_ecn.h>
58 #ifdef INET6
59 #include <netinet6/ip6_ecn.h>
60 #endif
61 
62 #include <netinet/ip6.h>
63 #ifdef INET6
64 #include <netinet6/ip6_var.h>
65 #endif
66 #include <netinet/in_pcb.h>
67 #ifdef INET6
68 #include <netinet/icmp6.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 IPSEC_NAT_T
88 #include <netinet/udp.h>
89 #endif
90 
91 #ifdef DEV_ENC
92 #include <net/if_enc.h>
93 #endif
94 
95 
96 int
97 ipsec_process_done(struct mbuf *m, struct ipsecrequest *isr)
98 {
99 	struct tdb_ident *tdbi;
100 	struct m_tag *mtag;
101 	struct secasvar *sav;
102 	struct secasindex *saidx;
103 	int error;
104 
105 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
106 	IPSEC_ASSERT(isr != NULL, ("null ISR"));
107 	sav = isr->sav;
108 	IPSEC_ASSERT(sav != NULL, ("null SA"));
109 	IPSEC_ASSERT(sav->sah != NULL, ("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(("%s: unknown protocol family %u\n", __func__,
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(("%s: could not get packet tag\n", __func__));
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 		IPSECSTAT_INC(ips_out_bundlesa);
169 		/* XXX-BZ currently only support same AF bundles. */
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 	/*
195 	 * We're done with IPsec processing, transmit the packet using the
196 	 * appropriate network protocol (IP or IPv6). SPD lookup will be
197 	 * performed again there.
198 	 */
199 	switch (saidx->dst.sa.sa_family) {
200 #ifdef INET
201 	case AF_INET:
202 #ifdef IPSEC_NAT_T
203 		/*
204 		 * If NAT-T is enabled, now that all IPsec processing is done
205 		 * insert UDP encapsulation header after IP header.
206 		 */
207 		if (sav->natt_type) {
208 			struct ip *ip = mtod(m, struct ip *);
209 #ifdef _IP_VHL
210 			const int hlen = IP_VHL_HL(ip->ip_vhl);
211 #else
212 			const int hlen = (ip->ip_hl << 2);
213 #endif
214 			int size, off;
215 			struct mbuf *mi;
216 			struct udphdr *udp;
217 
218 			size = sizeof(struct udphdr);
219 			if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE) {
220 				/*
221 				 * draft-ietf-ipsec-nat-t-ike-0[01].txt and
222 				 * draft-ietf-ipsec-udp-encaps-(00/)01.txt,
223 				 * ignoring possible AH mode
224 				 * non-IKE marker + non-ESP marker
225 				 * from draft-ietf-ipsec-udp-encaps-00.txt.
226 				 */
227 				size += sizeof(u_int64_t);
228 			}
229 			mi = m_makespace(m, hlen, size, &off);
230 			if (mi == NULL) {
231 				DPRINTF(("%s: m_makespace for udphdr failed\n",
232 				    __func__));
233 				error = ENOBUFS;
234 				goto bad;
235 			}
236 
237 			udp = (struct udphdr *)(mtod(mi, caddr_t) + off);
238 			if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
239 				udp->uh_sport = htons(UDP_ENCAP_ESPINUDP_PORT);
240 			else
241 				udp->uh_sport =
242 					KEY_PORTFROMSADDR(&sav->sah->saidx.src);
243 			udp->uh_dport = KEY_PORTFROMSADDR(&sav->sah->saidx.dst);
244 			udp->uh_sum = 0;
245 			udp->uh_ulen = htons(m->m_pkthdr.len - hlen);
246 			ip->ip_len = htons(m->m_pkthdr.len);
247 			ip->ip_p = IPPROTO_UDP;
248 
249 			if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
250 				*(u_int64_t *)(udp + 1) = 0;
251 		}
252 #endif /* IPSEC_NAT_T */
253 
254 		return ip_output(m, NULL, NULL, IP_RAWOUTPUT, NULL, NULL);
255 #endif /* INET */
256 #ifdef INET6
257 	case AF_INET6:
258 		/*
259 		 * We don't need massage, IPv6 header fields are always in
260 		 * net endian.
261 		 */
262 		return ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
263 #endif /* INET6 */
264 	}
265 	panic("ipsec_process_done");
266 bad:
267 	m_freem(m);
268 	return (error);
269 }
270 
271 static struct ipsecrequest *
272 ipsec_nextisr(
273 	struct mbuf *m,
274 	struct ipsecrequest *isr,
275 	int af,
276 	struct secasindex *saidx,
277 	int *error
278 )
279 {
280 #define	IPSEC_OSTAT(name)	do {		\
281 	if (isr->saidx.proto == IPPROTO_ESP)	\
282 		ESPSTAT_INC(esps_##name);	\
283 	else if (isr->saidx.proto == IPPROTO_AH)\
284 		AHSTAT_INC(ahs_##name);		\
285 	else					\
286 		IPCOMPSTAT_INC(ipcomps_##name);	\
287 } while (0)
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 		IPSECSTAT_INC(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(pdrops);
396 		*error = EHOSTUNREACH;
397 		goto bad;
398 	}
399 
400 	/*
401 	 * Sanity check the SA contents for the caller
402 	 * before they invoke the xform output method.
403 	 */
404 	if (sav->tdb_xform == NULL) {
405 		DPRINTF(("%s: no transform for SA\n", __func__));
406 		IPSEC_OSTAT(noxform);
407 		*error = EHOSTUNREACH;
408 		goto bad;
409 	}
410 	return isr;
411 bad:
412 	IPSEC_ASSERT(*error != 0, ("error return w/ no error code"));
413 	IPSECREQUEST_UNLOCK(isr);
414 	return NULL;
415 #undef IPSEC_OSTAT
416 }
417 
418 #ifdef INET
419 /*
420  * IPsec output logic for IPv4.
421  */
422 int
423 ipsec4_process_packet(
424 	struct mbuf *m,
425 	struct ipsecrequest *isr,
426 	int flags,
427 	int tunalready)
428 {
429 	struct secasindex saidx;
430 	struct secasvar *sav;
431 	struct ip *ip;
432 	int error, i, off;
433 
434 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
435 	IPSEC_ASSERT(isr != NULL, ("null isr"));
436 
437 	IPSECREQUEST_LOCK(isr);		/* insure SA contents don't change */
438 
439 	isr = ipsec_nextisr(m, isr, AF_INET, &saidx, &error);
440 	if (isr == NULL) {
441 		if (error != 0)
442 			goto bad;
443 		return EJUSTRETURN;
444 	}
445 
446 	sav = isr->sav;
447 
448 #ifdef DEV_ENC
449 	encif->if_opackets++;
450 	encif->if_obytes += m->m_pkthdr.len;
451 
452 	/* pass the mbuf to enc0 for bpf processing */
453 	ipsec_bpf(m, sav, AF_INET, ENC_OUT|ENC_BEFORE);
454 	/* pass the mbuf to enc0 for packet filtering */
455 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_BEFORE)) != 0)
456 		goto bad;
457 #endif
458 
459 	if (!tunalready) {
460 		union sockaddr_union *dst = &sav->sah->saidx.dst;
461 		int setdf;
462 
463 		/*
464 		 * Collect IP_DF state from the outer header.
465 		 */
466 		if (dst->sa.sa_family == AF_INET) {
467 			if (m->m_len < sizeof (struct ip) &&
468 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
469 				error = ENOBUFS;
470 				goto bad;
471 			}
472 			ip = mtod(m, struct ip *);
473 			/* Honor system-wide control of how to handle IP_DF */
474 			switch (V_ip4_ipsec_dfbit) {
475 			case 0:			/* clear in outer header */
476 			case 1:			/* set in outer header */
477 				setdf = V_ip4_ipsec_dfbit;
478 				break;
479 			default:		/* propagate to outer header */
480 				setdf = ntohs(ip->ip_off & IP_DF);
481 				break;
482 			}
483 		} else {
484 			ip = NULL;		/* keep compiler happy */
485 			setdf = 0;
486 		}
487 		/* Do the appropriate encapsulation, if necessary */
488 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
489 		    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
490 #if 0
491 		    (sav->flags & SADB_X_SAFLAGS_TUNNEL) || /* Tunnel requ'd */
492 		    sav->tdb_xform->xf_type == XF_IP4 ||    /* ditto */
493 #endif
494 		    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
495 		     dst->sin.sin_addr.s_addr != INADDR_ANY &&
496 		     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
497 			struct mbuf *mp;
498 
499 			/* Fix IPv4 header checksum and length */
500 			if (m->m_len < sizeof (struct ip) &&
501 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
502 				error = ENOBUFS;
503 				goto bad;
504 			}
505 			ip = mtod(m, struct ip *);
506 			ip->ip_len = htons(m->m_pkthdr.len);
507 			ip->ip_sum = 0;
508 #ifdef _IP_VHL
509 			if (ip->ip_vhl == IP_VHL_BORING)
510 				ip->ip_sum = in_cksum_hdr(ip);
511 			else
512 				ip->ip_sum = in_cksum(m,
513 					_IP_VHL_HL(ip->ip_vhl) << 2);
514 #else
515 			ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
516 #endif
517 
518 			/* Encapsulate the packet */
519 			error = ipip_output(m, isr, &mp, 0, 0);
520 			if (mp == NULL && !error) {
521 				/* Should never happen. */
522 				DPRINTF(("%s: ipip_output returns no mbuf and "
523 					"no error!", __func__));
524 				error = EFAULT;
525 			}
526 			if (error) {
527 				if (mp) {
528 					/* XXX: Should never happen! */
529 					m_freem(mp);
530 				}
531 				m = NULL; /* ipip_output() already freed it */
532 				goto bad;
533 			}
534 			m = mp, mp = NULL;
535 			/*
536 			 * ipip_output clears IP_DF in the new header.  If
537 			 * we need to propagate IP_DF from the outer header,
538 			 * then we have to do it here.
539 			 *
540 			 * XXX shouldn't assume what ipip_output does.
541 			 */
542 			if (dst->sa.sa_family == AF_INET && setdf) {
543 				if (m->m_len < sizeof (struct ip) &&
544 				    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
545 					error = ENOBUFS;
546 					goto bad;
547 				}
548 				ip = mtod(m, struct ip *);
549 				ip->ip_off = ntohs(ip->ip_off);
550 				ip->ip_off |= IP_DF;
551 				ip->ip_off = htons(ip->ip_off);
552 			}
553 		}
554 	}
555 
556 #ifdef DEV_ENC
557 	/* pass the mbuf to enc0 for bpf processing */
558 	ipsec_bpf(m, sav, AF_INET, ENC_OUT|ENC_AFTER);
559 	/* pass the mbuf to enc0 for packet filtering */
560 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_AFTER)) != 0)
561 		goto bad;
562 #endif
563 
564 	/*
565 	 * Dispatch to the appropriate IPsec transform logic.  The
566 	 * packet will be returned for transmission after crypto
567 	 * processing, etc. are completed.  For encapsulation we
568 	 * bypass this call because of the explicit call done above
569 	 * (necessary to deal with IP_DF handling for IPv4).
570 	 *
571 	 * NB: m & sav are ``passed to caller'' who's reponsible for
572 	 *     for reclaiming their resources.
573 	 */
574 	if (sav->tdb_xform->xf_type != XF_IP4) {
575 		ip = mtod(m, struct ip *);
576 		i = ip->ip_hl << 2;
577 		off = offsetof(struct ip, ip_p);
578 		error = (*sav->tdb_xform->xf_output)(m, isr, NULL, i, off);
579 	} else {
580 		error = ipsec_process_done(m, isr);
581 	}
582 	IPSECREQUEST_UNLOCK(isr);
583 	return error;
584 bad:
585 	if (isr)
586 		IPSECREQUEST_UNLOCK(isr);
587 	if (m)
588 		m_freem(m);
589 	return error;
590 }
591 #endif
592 
593 #ifdef INET6
594 /*
595  * Chop IP6 header from the payload.
596  */
597 static struct mbuf *
598 ipsec6_splithdr(struct mbuf *m)
599 {
600 	struct mbuf *mh;
601 	struct ip6_hdr *ip6;
602 	int hlen;
603 
604 	IPSEC_ASSERT(m->m_len >= sizeof (struct ip6_hdr),
605 		("first mbuf too short, len %u", m->m_len));
606 	ip6 = mtod(m, struct ip6_hdr *);
607 	hlen = sizeof(struct ip6_hdr);
608 	if (m->m_len > hlen) {
609 		MGETHDR(mh, M_NOWAIT, MT_DATA);
610 		if (!mh) {
611 			m_freem(m);
612 			return NULL;
613 		}
614 		M_MOVE_PKTHDR(mh, m);
615 		MH_ALIGN(mh, hlen);
616 		m->m_len -= hlen;
617 		m->m_data += hlen;
618 		mh->m_next = m;
619 		m = mh;
620 		m->m_len = hlen;
621 		bcopy((caddr_t)ip6, mtod(m, caddr_t), hlen);
622 	} else if (m->m_len < hlen) {
623 		m = m_pullup(m, hlen);
624 		if (!m)
625 			return NULL;
626 	}
627 	return m;
628 }
629 
630 /*
631  * IPsec output logic for IPv6, transport mode.
632  */
633 int
634 ipsec6_output_trans(
635 	struct ipsec_output_state *state,
636 	u_char *nexthdrp,
637 	struct mbuf *mprev,
638 	struct secpolicy *sp,
639 	int flags,
640 	int *tun)
641 {
642 	struct ipsecrequest *isr;
643 	struct secasindex saidx;
644 	int error = 0;
645 	struct mbuf *m;
646 
647 	IPSEC_ASSERT(state != NULL, ("null state"));
648 	IPSEC_ASSERT(state->m != NULL, ("null m"));
649 	IPSEC_ASSERT(nexthdrp != NULL, ("null nexthdrp"));
650 	IPSEC_ASSERT(mprev != NULL, ("null mprev"));
651 	IPSEC_ASSERT(sp != NULL, ("null sp"));
652 	IPSEC_ASSERT(tun != NULL, ("null tun"));
653 
654 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
655 		printf("%s: applied SP\n", __func__);
656 		kdebug_secpolicy(sp));
657 
658 	isr = sp->req;
659 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
660 		/* the rest will be handled by ipsec6_output_tunnel() */
661 		*tun = 1;		/* need tunnel-mode processing */
662 		return 0;
663 	}
664 
665 	*tun = 0;
666 	m = state->m;
667 
668 	IPSECREQUEST_LOCK(isr);		/* insure SA contents don't change */
669 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
670 	if (isr == NULL) {
671 		if (error != 0) {
672 #ifdef notdef
673 			/* XXX should notification be done for all errors ? */
674 			/*
675 			 * Notify the fact that the packet is discarded
676 			 * to ourselves. I believe this is better than
677 			 * just silently discarding. (jinmei@kame.net)
678 			 * XXX: should we restrict the error to TCP packets?
679 			 * XXX: should we directly notify sockets via
680 			 *      pfctlinputs?
681 			 */
682 			icmp6_error(m, ICMP6_DST_UNREACH,
683 				    ICMP6_DST_UNREACH_ADMIN, 0);
684 			m = NULL;	/* NB: icmp6_error frees mbuf */
685 #endif
686 			goto bad;
687 		}
688 		return EJUSTRETURN;
689 	}
690 
691 	error = (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
692 						  sizeof (struct ip6_hdr),
693 						  offsetof(struct ip6_hdr,
694 							   ip6_nxt));
695 	IPSECREQUEST_UNLOCK(isr);
696 	return error;
697 bad:
698 	if (isr)
699 		IPSECREQUEST_UNLOCK(isr);
700 	if (m)
701 		m_freem(m);
702 	state->m = NULL;
703 	return error;
704 }
705 
706 static int
707 ipsec6_encapsulate(struct mbuf *m, struct secasvar *sav)
708 {
709 	struct ip6_hdr *oip6;
710 	struct ip6_hdr *ip6;
711 	size_t plen;
712 
713 	/* can't tunnel between different AFs */
714 	if (sav->sah->saidx.src.sa.sa_family != AF_INET6 ||
715 	    sav->sah->saidx.dst.sa.sa_family != AF_INET6) {
716 		m_freem(m);
717 		return EINVAL;
718 	}
719 	IPSEC_ASSERT(m->m_len == sizeof (struct ip6_hdr),
720 		("mbuf wrong size; len %u", m->m_len));
721 
722 
723 	/*
724 	 * grow the mbuf to accomodate the new IPv6 header.
725 	 */
726 	plen = m->m_pkthdr.len;
727 	if (M_LEADINGSPACE(m->m_next) < sizeof(struct ip6_hdr)) {
728 		struct mbuf *n;
729 		MGET(n, M_NOWAIT, MT_DATA);
730 		if (!n) {
731 			m_freem(m);
732 			return ENOBUFS;
733 		}
734 		n->m_len = sizeof(struct ip6_hdr);
735 		n->m_next = m->m_next;
736 		m->m_next = n;
737 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
738 		oip6 = mtod(n, struct ip6_hdr *);
739 	} else {
740 		m->m_next->m_len += sizeof(struct ip6_hdr);
741 		m->m_next->m_data -= sizeof(struct ip6_hdr);
742 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
743 		oip6 = mtod(m->m_next, struct ip6_hdr *);
744 	}
745 	ip6 = mtod(m, struct ip6_hdr *);
746 	bcopy((caddr_t)ip6, (caddr_t)oip6, sizeof(struct ip6_hdr));
747 
748 	/* Fake link-local scope-class addresses */
749 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_src))
750 		oip6->ip6_src.s6_addr16[1] = 0;
751 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_dst))
752 		oip6->ip6_dst.s6_addr16[1] = 0;
753 
754 	/* construct new IPv6 header. see RFC 2401 5.1.2.2 */
755 	/* ECN consideration. */
756 	ip6_ecn_ingress(V_ip6_ipsec_ecn, &ip6->ip6_flow, &oip6->ip6_flow);
757 	if (plen < IPV6_MAXPACKET - sizeof(struct ip6_hdr))
758 		ip6->ip6_plen = htons(plen);
759 	else {
760 		/* ip6->ip6_plen will be updated in ip6_output() */
761 	}
762 	ip6->ip6_nxt = IPPROTO_IPV6;
763 	ip6->ip6_src = sav->sah->saidx.src.sin6.sin6_addr;
764 	ip6->ip6_dst = sav->sah->saidx.dst.sin6.sin6_addr;
765 	ip6->ip6_hlim = IPV6_DEFHLIM;
766 
767 	/* XXX Should ip6_src be updated later ? */
768 
769 	return 0;
770 }
771 
772 /*
773  * IPsec output logic for IPv6, tunnel mode.
774  */
775 int
776 ipsec6_output_tunnel(struct ipsec_output_state *state, struct secpolicy *sp, int flags)
777 {
778 	struct ip6_hdr *ip6;
779 	struct ipsecrequest *isr;
780 	struct secasindex saidx;
781 	int error;
782 	struct sockaddr_in6 *dst6;
783 	struct mbuf *m;
784 
785 	IPSEC_ASSERT(state != NULL, ("null state"));
786 	IPSEC_ASSERT(state->m != NULL, ("null m"));
787 	IPSEC_ASSERT(sp != NULL, ("null sp"));
788 
789 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
790 		printf("%s: applied SP\n", __func__);
791 		kdebug_secpolicy(sp));
792 
793 	m = state->m;
794 	/*
795 	 * transport mode ipsec (before the 1st tunnel mode) is already
796 	 * processed by ipsec6_output_trans().
797 	 */
798 	for (isr = sp->req; isr; isr = isr->next) {
799 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
800 			break;
801 	}
802 
803 	IPSECREQUEST_LOCK(isr);		/* insure SA contents don't change */
804 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
805 	if (isr == NULL) {
806 		if (error != 0)
807 			goto bad;
808 		return EJUSTRETURN;
809 	}
810 
811 #ifdef DEV_ENC
812 	encif->if_opackets++;
813 	encif->if_obytes += m->m_pkthdr.len;
814 
815 	/* pass the mbuf to enc0 for bpf processing */
816 	ipsec_bpf(m, isr->sav, AF_INET6, ENC_OUT|ENC_BEFORE);
817 	/* pass the mbuf to enc0 for packet filtering */
818 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_BEFORE)) != 0)
819 		goto bad;
820 #endif
821 
822 	/*
823 	 * There may be the case that SA status will be changed when
824 	 * we are refering to one. So calling splsoftnet().
825 	 */
826 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
827 		/*
828 		 * build IPsec tunnel.
829 		 */
830 		/* XXX should be processed with other familiy */
831 		if (isr->sav->sah->saidx.src.sa.sa_family != AF_INET6) {
832 			ipseclog((LOG_ERR, "%s: family mismatched between "
833 			    "inner and outer, spi=%u\n", __func__,
834 			    ntohl(isr->sav->spi)));
835 			IPSEC6STAT_INC(ips_out_inval);
836 			error = EAFNOSUPPORT;
837 			goto bad;
838 		}
839 
840 		m = ipsec6_splithdr(m);
841 		if (!m) {
842 			IPSEC6STAT_INC(ips_out_nomem);
843 			error = ENOMEM;
844 			goto bad;
845 		}
846 		error = ipsec6_encapsulate(m, isr->sav);
847 		if (error) {
848 			m = NULL;
849 			goto bad;
850 		}
851 		ip6 = mtod(m, struct ip6_hdr *);
852 
853 		state->ro =
854 		    (struct route *)&isr->sav->sah->route_cache.sin6_route;
855 		state->dst = (struct sockaddr *)&state->ro->ro_dst;
856 		dst6 = (struct sockaddr_in6 *)state->dst;
857 		if (state->ro->ro_rt
858 		 && ((state->ro->ro_rt->rt_flags & RTF_UP) == 0
859 		  || !IN6_ARE_ADDR_EQUAL(&dst6->sin6_addr, &ip6->ip6_dst))) {
860 			RTFREE(state->ro->ro_rt);
861 			state->ro->ro_rt = NULL;
862 		}
863 		if (state->ro->ro_rt == NULL) {
864 			bzero(dst6, sizeof(*dst6));
865 			dst6->sin6_family = AF_INET6;
866 			dst6->sin6_len = sizeof(*dst6);
867 			dst6->sin6_addr = ip6->ip6_dst;
868 			rtalloc_ign_fib(state->ro, 0UL, M_GETFIB(m));
869 		}
870 		if (state->ro->ro_rt == NULL) {
871 			IP6STAT_INC(ip6s_noroute);
872 			IPSEC6STAT_INC(ips_out_noroute);
873 			error = EHOSTUNREACH;
874 			goto bad;
875 		}
876 
877 		/* adjust state->dst if tunnel endpoint is offlink */
878 		if (state->ro->ro_rt->rt_flags & RTF_GATEWAY)
879 			state->dst = (struct sockaddr *)state->ro->ro_rt->rt_gateway;
880 	}
881 
882 	m = ipsec6_splithdr(m);
883 	if (!m) {
884 		IPSEC6STAT_INC(ips_out_nomem);
885 		error = ENOMEM;
886 		goto bad;
887 	}
888 	ip6 = mtod(m, struct ip6_hdr *);
889 
890 #ifdef DEV_ENC
891 	/* pass the mbuf to enc0 for bpf processing */
892 	ipsec_bpf(m, isr->sav, AF_INET6, ENC_OUT|ENC_AFTER);
893 	/* pass the mbuf to enc0 for packet filtering */
894 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_AFTER)) != 0)
895 		goto bad;
896 #endif
897 
898 	error = (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
899 		sizeof (struct ip6_hdr),
900 		offsetof(struct ip6_hdr, ip6_nxt));
901 	IPSECREQUEST_UNLOCK(isr);
902 	return error;
903 bad:
904 	if (isr)
905 		IPSECREQUEST_UNLOCK(isr);
906 	if (m)
907 		m_freem(m);
908 	state->m = NULL;
909 	return error;
910 }
911 #endif /*INET6*/
912