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