Home | History | Annotate | Line # | Download | only in netipsec
ipsec_output.c revision 1.9
      1 /*	$NetBSD: ipsec_output.c,v 1.9 2004/03/01 23:30:01 thorpej Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  *
     28  * $FreeBSD: /repoman/r/ncvs/src/sys/netipsec/ipsec_output.c,v 1.3.2.2 2003/03/28 20:32:53 sam Exp $
     29  */
     30 
     31 #include <sys/cdefs.h>
     32 __KERNEL_RCSID(0, "$NetBSD: ipsec_output.c,v 1.9 2004/03/01 23:30:01 thorpej Exp $");
     33 
     34 /*
     35  * IPsec output processing.
     36  */
     37 #include "opt_inet.h"
     38 #ifdef __FreeBSD__
     39 #include "opt_inet6.h"
     40 #endif
     41 #include "opt_ipsec.h"
     42 
     43 #include <sys/param.h>
     44 #include <sys/systm.h>
     45 #include <sys/mbuf.h>
     46 #include <sys/domain.h>
     47 #include <sys/protosw.h>
     48 #include <sys/socket.h>
     49 #include <sys/errno.h>
     50 #include <sys/syslog.h>
     51 
     52 #include <net/if.h>
     53 #include <net/route.h>
     54 
     55 #include <netinet/in.h>
     56 #include <netinet/in_systm.h>
     57 #include <netinet/ip.h>
     58 #include <netinet/ip_var.h>
     59 #include <netinet/in_var.h>
     60 #include <netinet/ip_ecn.h>
     61 #ifdef INET6
     62 #include <netinet6/ip6_ecn.h>
     63 #endif
     64 
     65 #include <netinet/ip6.h>
     66 #ifdef INET6
     67 #include <netinet6/ip6_var.h>
     68 #endif
     69 #include <netinet/in_pcb.h>
     70 #ifdef INET6
     71 #include <netinet/icmp6.h>
     72 #endif
     73 
     74 #include <netipsec/ipsec.h>
     75 #ifdef INET6
     76 #include <netipsec/ipsec6.h>
     77 #endif
     78 #include <netipsec/ah_var.h>
     79 #include <netipsec/esp_var.h>
     80 #include <netipsec/ipcomp_var.h>
     81 
     82 #include <netipsec/xform.h>
     83 
     84 #include <netipsec/key.h>
     85 #include <netipsec/keydb.h>
     86 #include <netipsec/key_debug.h>
     87 #include <netipsec/ipsec_osdep.h>
     88 
     89 int
     90 ipsec_process_done(struct mbuf *m, struct ipsecrequest *isr)
     91 {
     92 	struct tdb_ident *tdbi;
     93 	struct m_tag *mtag;
     94 	struct secasvar *sav;
     95 	struct secasindex *saidx;
     96 	int error;
     97 
     98 	IPSEC_SPLASSERT_SOFTNET("ipsec_process_done");
     99 
    100 	IPSEC_ASSERT(m != NULL, ("ipsec_process_done: null mbuf"));
    101 	IPSEC_ASSERT(isr != NULL, ("ipsec_process_done: null ISR"));
    102 	sav = isr->sav;
    103 	IPSEC_ASSERT(sav != NULL, ("ipsec_process_done: null SA"));
    104 	IPSEC_ASSERT(sav->sah != NULL, ("ipsec_process_done: null SAH"));
    105 
    106 	saidx = &sav->sah->saidx;
    107 	switch (saidx->dst.sa.sa_family) {
    108 #ifdef INET
    109 	case AF_INET:
    110 		/* Fix the header length, for AH processing. */
    111 		mtod(m, struct ip *)->ip_len = htons(m->m_pkthdr.len);
    112 		break;
    113 #endif /* INET */
    114 #ifdef INET6
    115 	case AF_INET6:
    116 		/* Fix the header length, for AH processing. */
    117 		if (m->m_pkthdr.len < sizeof (struct ip6_hdr)) {
    118 			error = ENXIO;
    119 			goto bad;
    120 		}
    121 		if (m->m_pkthdr.len - sizeof (struct ip6_hdr) > IPV6_MAXPACKET) {
    122 			/* No jumbogram support. */
    123 			error = ENXIO;	/*?*/
    124 			goto bad;
    125 		}
    126 		mtod(m, struct ip6_hdr *)->ip6_plen =
    127 			htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
    128 		break;
    129 #endif /* INET6 */
    130 	default:
    131 		DPRINTF(("ipsec_process_done: unknown protocol family %u\n",
    132 		    saidx->dst.sa.sa_family));
    133 		error = ENXIO;
    134 		goto bad;
    135 	}
    136 
    137 	/*
    138 	 * Add a record of what we've done or what needs to be done to the
    139 	 * packet.
    140 	 */
    141 	mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE,
    142 			sizeof(struct tdb_ident), M_NOWAIT);
    143 	if (mtag == NULL) {
    144 		DPRINTF(("ipsec_process_done: could not get packet tag\n"));
    145 		error = ENOMEM;
    146 		goto bad;
    147 	}
    148 
    149 	tdbi = (struct tdb_ident *)(mtag + 1);
    150 	tdbi->dst = saidx->dst;
    151 	tdbi->proto = saidx->proto;
    152 	tdbi->spi = sav->spi;
    153 	m_tag_prepend(m, mtag);
    154 
    155 	/*
    156 	 * If there's another (bundled) SA to apply, do so.
    157 	 * Note that this puts a burden on the kernel stack size.
    158 	 * If this is a problem we'll need to introduce a queue
    159 	 * to set the packet on so we can unwind the stack before
    160 	 * doing further processing.
    161 	 */
    162 	if (isr->next) {
    163 		newipsecstat.ips_out_bundlesa++;
    164 		return ipsec4_process_packet(m, isr->next, 0, 0);
    165 	}
    166 
    167 	/*
    168 	 * We're done with IPsec processing, transmit the packet using the
    169 	 * appropriate network protocol (IP or IPv6). SPD lookup will be
    170 	 * performed again there.
    171 	 */
    172 	switch (saidx->dst.sa.sa_family) {
    173 #ifdef INET
    174 	struct ip *ip;
    175 	case AF_INET:
    176 		ip = mtod(m, struct ip *);
    177 #ifdef __FreeBSD__
    178 		/* FreeBSD ip_output() expects ip_len, ip_off in host endian */
    179 		ip->ip_len = ntohs(ip->ip_len);
    180 		ip->ip_off = ntohs(ip->ip_off);
    181 #endif /* __FreeBSD_ */
    182 		return ip_output(m, NULL, NULL, IP_RAWOUTPUT,
    183 		    (struct ip_moptions *)NULL, (struct socket *)NULL);
    184 
    185 #endif /* INET */
    186 #ifdef INET6
    187 	case AF_INET6:
    188 		/*
    189 		 * We don't need massage, IPv6 header fields are always in
    190 		 * net endian.
    191 		 */
    192 		return ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
    193 #endif /* INET6 */
    194 	}
    195 	panic("ipsec_process_done");
    196 bad:
    197 	m_freem(m);
    198 	KEY_FREESAV(&sav);
    199 	return (error);
    200 }
    201 
    202 static struct ipsecrequest *
    203 ipsec_nextisr(
    204 	struct mbuf *m,
    205 	struct ipsecrequest *isr,
    206 	int af,
    207 	struct secasindex *saidx,
    208 	int *error
    209 )
    210 {
    211 #define IPSEC_OSTAT(x,y,z) (isr->saidx.proto == IPPROTO_ESP ? (x)++ : \
    212 			    isr->saidx.proto == IPPROTO_AH ? (y)++ : (z)++)
    213 	struct secasvar *sav;
    214 
    215 	IPSEC_SPLASSERT_SOFTNET("ipsec_nextisr");
    216 	IPSEC_ASSERT(af == AF_INET || af == AF_INET6,
    217 		("ipsec_nextisr: invalid address family %u", af));
    218 again:
    219 	/*
    220 	 * Craft SA index to search for proper SA.  Note that
    221 	 * we only fillin unspecified SA peers for transport
    222 	 * mode; for tunnel mode they must already be filled in.
    223 	 */
    224 	*saidx = isr->saidx;
    225 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
    226 		/* Fillin unspecified SA peers only for transport mode */
    227 		if (af == AF_INET) {
    228 			struct sockaddr_in *sin;
    229 			struct ip *ip = mtod(m, struct ip *);
    230 
    231 			if (saidx->src.sa.sa_len == 0) {
    232 				sin = &saidx->src.sin;
    233 				sin->sin_len = sizeof(*sin);
    234 				sin->sin_family = AF_INET;
    235 				sin->sin_port = IPSEC_PORT_ANY;
    236 				sin->sin_addr = ip->ip_src;
    237 			}
    238 			if (saidx->dst.sa.sa_len == 0) {
    239 				sin = &saidx->dst.sin;
    240 				sin->sin_len = sizeof(*sin);
    241 				sin->sin_family = AF_INET;
    242 				sin->sin_port = IPSEC_PORT_ANY;
    243 				sin->sin_addr = ip->ip_dst;
    244 			}
    245 		} else {
    246 			struct sockaddr_in6 *sin6;
    247 			struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
    248 
    249 			if (saidx->src.sin6.sin6_len == 0) {
    250 				sin6 = (struct sockaddr_in6 *)&saidx->src;
    251 				sin6->sin6_len = sizeof(*sin6);
    252 				sin6->sin6_family = AF_INET6;
    253 				sin6->sin6_port = IPSEC_PORT_ANY;
    254 				sin6->sin6_addr = ip6->ip6_src;
    255 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
    256 					/* fix scope id for comparing SPD */
    257 					sin6->sin6_addr.s6_addr16[1] = 0;
    258 					sin6->sin6_scope_id =
    259 					    ntohs(ip6->ip6_src.s6_addr16[1]);
    260 				}
    261 			}
    262 			if (saidx->dst.sin6.sin6_len == 0) {
    263 				sin6 = (struct sockaddr_in6 *)&saidx->dst;
    264 				sin6->sin6_len = sizeof(*sin6);
    265 				sin6->sin6_family = AF_INET6;
    266 				sin6->sin6_port = IPSEC_PORT_ANY;
    267 				sin6->sin6_addr = ip6->ip6_dst;
    268 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
    269 					/* fix scope id for comparing SPD */
    270 					sin6->sin6_addr.s6_addr16[1] = 0;
    271 					sin6->sin6_scope_id =
    272 					    ntohs(ip6->ip6_dst.s6_addr16[1]);
    273 				}
    274 			}
    275 		}
    276 	}
    277 
    278 	/*
    279 	 * Lookup SA and validate it.
    280 	 */
    281 	*error = key_checkrequest(isr, saidx);
    282 	if (*error != 0) {
    283 		/*
    284 		 * IPsec processing is required, but no SA found.
    285 		 * I assume that key_acquire() had been called
    286 		 * to get/establish the SA. Here I discard
    287 		 * this packet because it is responsibility for
    288 		 * upper layer to retransmit the packet.
    289 		 */
    290 		newipsecstat.ips_out_nosa++;
    291 		goto bad;
    292 	}
    293 	sav = isr->sav;
    294 	if (sav == NULL) {		/* XXX valid return */
    295 		IPSEC_ASSERT(ipsec_get_reqlevel(isr) == IPSEC_LEVEL_USE,
    296 			("ipsec_nextisr: no SA found, but required; level %u",
    297 			ipsec_get_reqlevel(isr)));
    298 		isr = isr->next;
    299 		if (isr == NULL) {
    300 			/*XXXstatistic??*/
    301 			*error = EINVAL;		/*XXX*/
    302 			return isr;
    303 		}
    304 		goto again;
    305 	}
    306 
    307 	/*
    308 	 * Check system global policy controls.
    309 	 */
    310 	if ((isr->saidx.proto == IPPROTO_ESP && !esp_enable) ||
    311 	    (isr->saidx.proto == IPPROTO_AH && !ah_enable) ||
    312 	    (isr->saidx.proto == IPPROTO_IPCOMP && !ipcomp_enable)) {
    313 		DPRINTF(("ipsec_nextisr: IPsec outbound packet dropped due"
    314 			" to policy (check your sysctls)\n"));
    315 		IPSEC_OSTAT(espstat.esps_pdrops, ahstat.ahs_pdrops,
    316 		    ipcompstat.ipcomps_pdrops);
    317 		*error = EHOSTUNREACH;
    318 		goto bad;
    319 	}
    320 
    321 	/*
    322 	 * Sanity check the SA contents for the caller
    323 	 * before they invoke the xform output method.
    324 	 */
    325 	if (sav->tdb_xform == NULL) {
    326 		DPRINTF(("ipsec_nextisr: no transform for SA\n"));
    327 		IPSEC_OSTAT(espstat.esps_noxform, ahstat.ahs_noxform,
    328 		    ipcompstat.ipcomps_noxform);
    329 		*error = EHOSTUNREACH;
    330 		goto bad;
    331 	}
    332 	return isr;
    333 bad:
    334 	IPSEC_ASSERT(*error != 0, ("ipsec_nextisr: error return w/ no error code"));
    335 	return NULL;
    336 #undef IPSEC_OSTAT
    337 }
    338 
    339 #ifdef INET
    340 /*
    341  * IPsec output logic for IPv4.
    342  */
    343 int
    344 ipsec4_process_packet(
    345 	struct mbuf *m,
    346 	struct ipsecrequest *isr,
    347 	int flags,
    348 	int tunalready)
    349 {
    350 	struct secasindex saidx;
    351 	struct secasvar *sav;
    352 	struct ip *ip;
    353 	int s, error, i, off;
    354 
    355 	IPSEC_ASSERT(m != NULL, ("ipsec4_process_packet: null mbuf"));
    356 	IPSEC_ASSERT(isr != NULL, ("ipsec4_process_packet: null isr"));
    357 
    358 	s = splsoftnet();			/* insure SA contents don't change */
    359 
    360 	isr = ipsec_nextisr(m, isr, AF_INET, &saidx, &error);
    361 	if (isr == NULL)
    362 		goto bad;
    363 
    364 	sav = isr->sav;
    365 	if (!tunalready) {
    366 		union sockaddr_union *dst = &sav->sah->saidx.dst;
    367 		int setdf;
    368 
    369 		/*
    370 		 * Collect IP_DF state from the outer header.
    371 		 */
    372 		if (dst->sa.sa_family == AF_INET) {
    373 			if (m->m_len < sizeof (struct ip) &&
    374 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
    375 				error = ENOBUFS;
    376 				goto bad;
    377 			}
    378 			ip = mtod(m, struct ip *);
    379 			/* Honor system-wide control of how to handle IP_DF */
    380 			switch (ip4_ipsec_dfbit) {
    381 			case 0:			/* clear in outer header */
    382 			case 1:			/* set in outer header */
    383 				setdf = ip4_ipsec_dfbit;
    384 				break;
    385 			default:		/* propagate to outer header */
    386 				setdf = ip->ip_off;
    387 #ifndef __FreeBSD__
    388 		/* On FreeBSD, ip_off and ip_len assumed in host endian. */
    389 				setdf = ntohs(setdf);
    390 #endif
    391 				setdf = htons(setdf & IP_DF);
    392 				break;
    393 			}
    394 		} else {
    395 			ip = NULL;		/* keep compiler happy */
    396 			setdf = 0;
    397 		}
    398 		/* Do the appropriate encapsulation, if necessary */
    399 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
    400 		    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
    401 #if 0
    402 		    (sav->flags & SADB_X_SAFLAGS_TUNNEL) || /* Tunnel requ'd */
    403 		    sav->tdb_xform->xf_type == XF_IP4 ||    /* ditto */
    404 #endif
    405 		    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
    406 		     dst->sin.sin_addr.s_addr != INADDR_ANY &&
    407 		     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
    408 			struct mbuf *mp;
    409 
    410 			/* Fix IPv4 header checksum and length */
    411 			if (m->m_len < sizeof (struct ip) &&
    412 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
    413 				error = ENOBUFS;
    414 				goto bad;
    415 			}
    416 			ip = mtod(m, struct ip *);
    417 			ip->ip_len = htons(m->m_pkthdr.len);
    418 			ip->ip_sum = 0;
    419 #ifdef _IP_VHL
    420 			if (ip->ip_vhl == IP_VHL_BORING)
    421 				ip->ip_sum = in_cksum_hdr(ip);
    422 			else
    423 				ip->ip_sum = in_cksum(m,
    424 					_IP_VHL_HL(ip->ip_vhl) << 2);
    425 #else
    426 			ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
    427 #endif
    428 
    429 			/* Encapsulate the packet */
    430 			error = ipip_output(m, isr, &mp, 0, 0);
    431 			if (mp == NULL && !error) {
    432 				/* Should never happen. */
    433 				DPRINTF(("ipsec4_process_packet: ipip_output "
    434 					"returns no mbuf and no error!"));
    435 				error = EFAULT;
    436 			}
    437 			if (error) {
    438 				if (mp) {
    439 					/* XXX: Should never happen! */
    440 					m_freem(mp);
    441 				}
    442 				m = NULL; /* ipip_output() already freed it */
    443 				goto bad;
    444 			}
    445 			m = mp, mp = NULL;
    446 			/*
    447 			 * ipip_output clears IP_DF in the new header.  If
    448 			 * we need to propagate IP_DF from the outer header,
    449 			 * then we have to do it here.
    450 			 *
    451 			 * XXX shouldn't assume what ipip_output does.
    452 			 */
    453 			if (dst->sa.sa_family == AF_INET && setdf) {
    454 				if (m->m_len < sizeof (struct ip) &&
    455 				    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
    456 					error = ENOBUFS;
    457 					goto bad;
    458 				}
    459 				ip = mtod(m, struct ip *);
    460 				ip->ip_off = ntohs(ip->ip_off);
    461 				ip->ip_off |= IP_DF;
    462 				ip->ip_off = htons(ip->ip_off);
    463 			}
    464 		}
    465 	}
    466 
    467 	/*
    468 	 * Dispatch to the appropriate IPsec transform logic.  The
    469 	 * packet will be returned for transmission after crypto
    470 	 * processing, etc. are completed.  For encapsulation we
    471 	 * bypass this call because of the explicit call done above
    472 	 * (necessary to deal with IP_DF handling for IPv4).
    473 	 *
    474 	 * NB: m & sav are ``passed to caller'' who's reponsible for
    475 	 *     for reclaiming their resources.
    476 	 */
    477 	if (sav->tdb_xform->xf_type != XF_IP4) {
    478 		ip = mtod(m, struct ip *);
    479 		i = ip->ip_hl << 2;
    480 		off = offsetof(struct ip, ip_p);
    481 		error = (*sav->tdb_xform->xf_output)(m, isr, NULL, i, off);
    482 	} else {
    483 		error = ipsec_process_done(m, isr);
    484 	}
    485 	splx(s);
    486 	return error;
    487 bad:
    488 	splx(s);
    489 	if (m)
    490 		m_freem(m);
    491 	return error;
    492 }
    493 #endif
    494 
    495 #ifdef INET6
    496 /*
    497  * Chop IP6 header from the payload.
    498  */
    499 static struct mbuf *
    500 ipsec6_splithdr(struct mbuf *m)
    501 {
    502 	struct mbuf *mh;
    503 	struct ip6_hdr *ip6;
    504 	int hlen;
    505 
    506 	IPSEC_ASSERT(m->m_len >= sizeof (struct ip6_hdr),
    507 		("ipsec6_splithdr: first mbuf too short, len %u", m->m_len));
    508 	ip6 = mtod(m, struct ip6_hdr *);
    509 	hlen = sizeof(struct ip6_hdr);
    510 	if (m->m_len > hlen) {
    511 		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
    512 		if (!mh) {
    513 			m_freem(m);
    514 			return NULL;
    515 		}
    516 		M_MOVE_PKTHDR(mh, m);
    517 		MH_ALIGN(mh, hlen);
    518 		m->m_len -= hlen;
    519 		m->m_data += hlen;
    520 		mh->m_next = m;
    521 		m = mh;
    522 		m->m_len = hlen;
    523 		bcopy((caddr_t)ip6, mtod(m, caddr_t), hlen);
    524 	} else if (m->m_len < hlen) {
    525 		m = m_pullup(m, hlen);
    526 		if (!m)
    527 			return NULL;
    528 	}
    529 	return m;
    530 }
    531 
    532 /*
    533  * IPsec output logic for IPv6, transport mode.
    534  */
    535 int
    536 ipsec6_output_trans(
    537 	struct ipsec_output_state *state,
    538 	u_char *nexthdrp,
    539 	struct mbuf *mprev,
    540 	struct secpolicy *sp,
    541 	int flags,
    542 	int *tun)
    543 {
    544 	struct ipsecrequest *isr;
    545 	struct secasindex saidx;
    546 	int error = 0;
    547 	struct mbuf *m;
    548 
    549 	IPSEC_ASSERT(state != NULL, ("ipsec6_output: null state"));
    550 	IPSEC_ASSERT(state->m != NULL, ("ipsec6_output: null m"));
    551 	IPSEC_ASSERT(nexthdrp != NULL, ("ipsec6_output: null nexthdrp"));
    552 	IPSEC_ASSERT(mprev != NULL, ("ipsec6_output: null mprev"));
    553 	IPSEC_ASSERT(sp != NULL, ("ipsec6_output: null sp"));
    554 	IPSEC_ASSERT(tun != NULL, ("ipsec6_output: null tun"));
    555 
    556 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
    557 		printf("ipsec6_output_trans: applyed SP\n");
    558 		kdebug_secpolicy(sp));
    559 
    560 	isr = sp->req;
    561 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
    562 		/* the rest will be handled by ipsec6_output_tunnel() */
    563 		*tun = 1;		/* need tunnel-mode processing */
    564 		return 0;
    565 	}
    566 
    567 	*tun = 0;
    568 	m = state->m;
    569 
    570 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
    571 	if (isr == NULL) {
    572 #ifdef notdef
    573 		/* XXX should notification be done for all errors ? */
    574 		/*
    575 		 * Notify the fact that the packet is discarded
    576 		 * to ourselves. I believe this is better than
    577 		 * just silently discarding. (jinmei (at) kame.net)
    578 		 * XXX: should we restrict the error to TCP packets?
    579 		 * XXX: should we directly notify sockets via
    580 		 *      pfctlinputs?
    581 		 */
    582 		icmp6_error(m, ICMP6_DST_UNREACH,
    583 			    ICMP6_DST_UNREACH_ADMIN, 0);
    584 		m = NULL;	/* NB: icmp6_error frees mbuf */
    585 #endif
    586 		goto bad;
    587 	}
    588 
    589 	return (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
    590 		sizeof (struct ip6_hdr),
    591 		offsetof(struct ip6_hdr, ip6_nxt));
    592 bad:
    593 	if (m)
    594 		m_freem(m);
    595 	state->m = NULL;
    596 	return error;
    597 }
    598 
    599 static int
    600 ipsec6_encapsulate(struct mbuf *m, struct secasvar *sav)
    601 {
    602 	struct ip6_hdr *oip6;
    603 	struct ip6_hdr *ip6;
    604 	size_t plen;
    605 
    606 	/* can't tunnel between different AFs */
    607 	if (sav->sah->saidx.src.sa.sa_family != AF_INET6 ||
    608 	    sav->sah->saidx.dst.sa.sa_family != AF_INET6) {
    609 		m_freem(m);
    610 		return EINVAL;
    611 	}
    612 	IPSEC_ASSERT(m->m_len != sizeof (struct ip6_hdr),
    613 		("ipsec6_encapsulate: mbuf wrong size; len %u", m->m_len));
    614 
    615 
    616 	/*
    617 	 * grow the mbuf to accomodate the new IPv6 header.
    618 	 */
    619 	plen = m->m_pkthdr.len;
    620 	if (M_LEADINGSPACE(m->m_next) < sizeof(struct ip6_hdr)) {
    621 		struct mbuf *n;
    622 		MGET(n, M_DONTWAIT, MT_DATA);
    623 		if (!n) {
    624 			m_freem(m);
    625 			return ENOBUFS;
    626 		}
    627 		n->m_len = sizeof(struct ip6_hdr);
    628 		n->m_next = m->m_next;
    629 		m->m_next = n;
    630 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
    631 		oip6 = mtod(n, struct ip6_hdr *);
    632 	} else {
    633 		m->m_next->m_len += sizeof(struct ip6_hdr);
    634 		m->m_next->m_data -= sizeof(struct ip6_hdr);
    635 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
    636 		oip6 = mtod(m->m_next, struct ip6_hdr *);
    637 	}
    638 	ip6 = mtod(m, struct ip6_hdr *);
    639 	ovbcopy((caddr_t)ip6, (caddr_t)oip6, sizeof(struct ip6_hdr));
    640 
    641 	/* Fake link-local scope-class addresses */
    642 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_src))
    643 		oip6->ip6_src.s6_addr16[1] = 0;
    644 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_dst))
    645 		oip6->ip6_dst.s6_addr16[1] = 0;
    646 
    647 	/* construct new IPv6 header. see RFC 2401 5.1.2.2 */
    648 	/* ECN consideration. */
    649 	ip6_ecn_ingress(ip6_ipsec_ecn, &ip6->ip6_flow, &oip6->ip6_flow);
    650 	if (plen < IPV6_MAXPACKET - sizeof(struct ip6_hdr))
    651 		ip6->ip6_plen = htons(plen);
    652 	else {
    653 		/* ip6->ip6_plen will be updated in ip6_output() */
    654 	}
    655 	ip6->ip6_nxt = IPPROTO_IPV6;
    656 	sav->sah->saidx.src.sin6.sin6_addr = ip6->ip6_src;
    657 	sav->sah->saidx.dst.sin6.sin6_addr = ip6->ip6_dst;
    658 	ip6->ip6_hlim = IPV6_DEFHLIM;
    659 
    660 	/* XXX Should ip6_src be updated later ? */
    661 
    662 	return 0;
    663 }
    664 
    665 /*
    666  * IPsec output logic for IPv6, tunnel mode.
    667  */
    668 int
    669 ipsec6_output_tunnel(struct ipsec_output_state *state, struct secpolicy *sp, int flags)
    670 {
    671 	struct ip6_hdr *ip6;
    672 	struct ipsecrequest *isr;
    673 	struct secasindex saidx;
    674 	int error;
    675 	struct sockaddr_in6* dst6;
    676 	struct mbuf *m;
    677 
    678 	IPSEC_ASSERT(state != NULL, ("ipsec6_output: null state"));
    679 	IPSEC_ASSERT(state->m != NULL, ("ipsec6_output: null m"));
    680 	IPSEC_ASSERT(sp != NULL, ("ipsec6_output: null sp"));
    681 
    682 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
    683 		printf("ipsec6_output_tunnel: applyed SP\n");
    684 		kdebug_secpolicy(sp));
    685 
    686 	m = state->m;
    687 	/*
    688 	 * transport mode ipsec (before the 1st tunnel mode) is already
    689 	 * processed by ipsec6_output_trans().
    690 	 */
    691 	for (isr = sp->req; isr; isr = isr->next) {
    692 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
    693 			break;
    694 	}
    695 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
    696 	if (isr == NULL)
    697 		goto bad;
    698 
    699 	/*
    700 	 * There may be the case that SA status will be changed when
    701 	 * we are refering to one. So calling splsoftnet().
    702 	 */
    703 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
    704 		/*
    705 		 * build IPsec tunnel.
    706 		 */
    707 		/* XXX should be processed with other familiy */
    708 		if (isr->sav->sah->saidx.src.sa.sa_family != AF_INET6) {
    709 			ipseclog((LOG_ERR, "ipsec6_output_tunnel: "
    710 			    "family mismatched between inner and outer, spi=%lu\n",
    711 			    ntohl(isr->sav->spi)));
    712 			newipsecstat.ips_out_inval++;
    713 			error = EAFNOSUPPORT;
    714 			goto bad;
    715 		}
    716 
    717 		m = ipsec6_splithdr(m);
    718 		if (!m) {
    719 			newipsecstat.ips_out_nomem++;
    720 			error = ENOMEM;
    721 			goto bad;
    722 		}
    723 		error = ipsec6_encapsulate(m, isr->sav);
    724 		if (error) {
    725 			m = NULL;
    726 			goto bad;
    727 		}
    728 		ip6 = mtod(m, struct ip6_hdr *);
    729 
    730 		state->ro = &isr->sav->sah->sa_route;
    731 		state->dst = (struct sockaddr *)&state->ro->ro_dst;
    732 		dst6 = (struct sockaddr_in6 *)state->dst;
    733 		if (state->ro->ro_rt
    734 		 && ((state->ro->ro_rt->rt_flags & RTF_UP) == 0
    735 		  || !IN6_ARE_ADDR_EQUAL(&dst6->sin6_addr, &ip6->ip6_dst))) {
    736 			RTFREE(state->ro->ro_rt);
    737 			state->ro->ro_rt = NULL;
    738 		}
    739 		if (state->ro->ro_rt == 0) {
    740 			bzero(dst6, sizeof(*dst6));
    741 			dst6->sin6_family = AF_INET6;
    742 			dst6->sin6_len = sizeof(*dst6);
    743 			dst6->sin6_addr = ip6->ip6_dst;
    744 			rtalloc(state->ro);
    745 		}
    746 		if (state->ro->ro_rt == 0) {
    747 			ip6stat.ip6s_noroute++;
    748 			newipsecstat.ips_out_noroute++;
    749 			error = EHOSTUNREACH;
    750 			goto bad;
    751 		}
    752 
    753 		/* adjust state->dst if tunnel endpoint is offlink */
    754 		if (state->ro->ro_rt->rt_flags & RTF_GATEWAY) {
    755 			state->dst = (struct sockaddr *)state->ro->ro_rt->rt_gateway;
    756 			dst6 = (struct sockaddr_in6 *)state->dst;
    757 		}
    758 	}
    759 
    760 	m = ipsec6_splithdr(m);
    761 	if (!m) {
    762 		newipsecstat.ips_out_nomem++;
    763 		error = ENOMEM;
    764 		goto bad;
    765 	}
    766 	ip6 = mtod(m, struct ip6_hdr *);
    767 	return (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
    768 		sizeof (struct ip6_hdr),
    769 		offsetof(struct ip6_hdr, ip6_nxt));
    770 bad:
    771 	if (m)
    772 		m_freem(m);
    773 	state->m = NULL;
    774 	return error;
    775 }
    776 #endif /*INET6*/
    777