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