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