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