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