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