Home | History | Annotate | Line # | Download | only in netipsec
ipsec_output.c revision 1.13
      1 /*	$NetBSD: ipsec_output.c,v 1.13 2004/05/07 00:55:15 jonathan 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.13 2004/05/07 00:55:15 jonathan 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 #  ifdef __FreeBSD__
     63 #  include <netinet6/ip6_ecn.h>
     64 #  endif
     65 #endif
     66 
     67 #include <netinet/ip6.h>
     68 #ifdef INET6
     69 #include <netinet6/ip6_var.h>
     70 #endif
     71 #include <netinet/in_pcb.h>
     72 #ifdef INET6
     73 #include <netinet/icmp6.h>
     74 #endif
     75 
     76 #include <netipsec/ipsec.h>
     77 #include <netipsec/ipsec_var.h>
     78 #ifdef INET6
     79 #include <netipsec/ipsec6.h>
     80 #endif
     81 #include <netipsec/ah_var.h>
     82 #include <netipsec/esp_var.h>
     83 #include <netipsec/ipcomp_var.h>
     84 
     85 #include <netipsec/xform.h>
     86 
     87 #include <netipsec/key.h>
     88 #include <netipsec/keydb.h>
     89 #include <netipsec/key_debug.h>
     90 #include <netipsec/ipsec_osdep.h>
     91 
     92 #include <net/net_osdep.h>		/* ovbcopy() in ipsec6_encapsulate() */
     93 
     94 int
     95 ipsec_process_done(struct mbuf *m, struct ipsecrequest *isr)
     96 {
     97 	struct tdb_ident *tdbi;
     98 	struct m_tag *mtag;
     99 	struct secasvar *sav;
    100 	struct secasindex *saidx;
    101 	int error;
    102 
    103 	IPSEC_SPLASSERT_SOFTNET("ipsec_process_done");
    104 
    105 	IPSEC_ASSERT(m != NULL, ("ipsec_process_done: null mbuf"));
    106 	IPSEC_ASSERT(isr != NULL, ("ipsec_process_done: null ISR"));
    107 	sav = isr->sav;
    108 	IPSEC_ASSERT(sav != NULL, ("ipsec_process_done: null SA"));
    109 	IPSEC_ASSERT(sav->sah != NULL, ("ipsec_process_done: 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(("ipsec_process_done: unknown protocol family %u\n",
    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(("ipsec_process_done: could not get packet tag\n"));
    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 		newipsecstat.ips_out_bundlesa++;
    169 		return ipsec4_process_packet(m, isr->next, 0, 0);
    170 	}
    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 #ifdef __FreeBSD__
    183 		/* FreeBSD ip_output() expects ip_len, ip_off in host endian */
    184 		ip->ip_len = ntohs(ip->ip_len);
    185 		ip->ip_off = ntohs(ip->ip_off);
    186 #endif /* __FreeBSD_ */
    187 		return ip_output(m, NULL, NULL, IP_RAWOUTPUT,
    188 		    (struct ip_moptions *)NULL, (struct socket *)NULL);
    189 
    190 #endif /* INET */
    191 #ifdef INET6
    192 	case AF_INET6:
    193 		/*
    194 		 * We don't need massage, IPv6 header fields are always in
    195 		 * net endian.
    196 		 */
    197 		return ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
    198 #endif /* INET6 */
    199 	}
    200 	panic("ipsec_process_done");
    201 bad:
    202 	m_freem(m);
    203 	KEY_FREESAV(&sav);
    204 	return (error);
    205 }
    206 
    207 static struct ipsecrequest *
    208 ipsec_nextisr(
    209 	struct mbuf *m,
    210 	struct ipsecrequest *isr,
    211 	int af,
    212 	struct secasindex *saidx,
    213 	int *error
    214 )
    215 {
    216 #define IPSEC_OSTAT(x,y,z) (isr->saidx.proto == IPPROTO_ESP ? (x)++ : \
    217 			    isr->saidx.proto == IPPROTO_AH ? (y)++ : (z)++)
    218 	struct secasvar *sav;
    219 
    220 	IPSEC_SPLASSERT_SOFTNET("ipsec_nextisr");
    221 	IPSEC_ASSERT(af == AF_INET || af == AF_INET6,
    222 		("ipsec_nextisr: invalid address family %u", af));
    223 again:
    224 	/*
    225 	 * Craft SA index to search for proper SA.  Note that
    226 	 * we only fillin unspecified SA peers for transport
    227 	 * mode; for tunnel mode they must already be filled in.
    228 	 */
    229 	*saidx = isr->saidx;
    230 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
    231 		/* Fillin unspecified SA peers only for transport mode */
    232 		if (af == AF_INET) {
    233 			struct sockaddr_in *sin;
    234 			struct ip *ip = mtod(m, struct ip *);
    235 
    236 			if (saidx->src.sa.sa_len == 0) {
    237 				sin = &saidx->src.sin;
    238 				sin->sin_len = sizeof(*sin);
    239 				sin->sin_family = AF_INET;
    240 				sin->sin_port = IPSEC_PORT_ANY;
    241 				sin->sin_addr = ip->ip_src;
    242 			}
    243 			if (saidx->dst.sa.sa_len == 0) {
    244 				sin = &saidx->dst.sin;
    245 				sin->sin_len = sizeof(*sin);
    246 				sin->sin_family = AF_INET;
    247 				sin->sin_port = IPSEC_PORT_ANY;
    248 				sin->sin_addr = ip->ip_dst;
    249 			}
    250 		} else {
    251 			struct sockaddr_in6 *sin6;
    252 			struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
    253 
    254 			if (saidx->src.sin6.sin6_len == 0) {
    255 				sin6 = (struct sockaddr_in6 *)&saidx->src;
    256 				sin6->sin6_len = sizeof(*sin6);
    257 				sin6->sin6_family = AF_INET6;
    258 				sin6->sin6_port = IPSEC_PORT_ANY;
    259 				sin6->sin6_addr = ip6->ip6_src;
    260 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
    261 					/* fix scope id for comparing SPD */
    262 					sin6->sin6_addr.s6_addr16[1] = 0;
    263 					sin6->sin6_scope_id =
    264 					    ntohs(ip6->ip6_src.s6_addr16[1]);
    265 				}
    266 			}
    267 			if (saidx->dst.sin6.sin6_len == 0) {
    268 				sin6 = (struct sockaddr_in6 *)&saidx->dst;
    269 				sin6->sin6_len = sizeof(*sin6);
    270 				sin6->sin6_family = AF_INET6;
    271 				sin6->sin6_port = IPSEC_PORT_ANY;
    272 				sin6->sin6_addr = ip6->ip6_dst;
    273 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
    274 					/* fix scope id for comparing SPD */
    275 					sin6->sin6_addr.s6_addr16[1] = 0;
    276 					sin6->sin6_scope_id =
    277 					    ntohs(ip6->ip6_dst.s6_addr16[1]);
    278 				}
    279 			}
    280 		}
    281 	}
    282 
    283 	/*
    284 	 * Lookup SA and validate it.
    285 	 */
    286 	*error = key_checkrequest(isr, saidx);
    287 	if (*error != 0) {
    288 		/*
    289 		 * IPsec processing is required, but no SA found.
    290 		 * I assume that key_acquire() had been called
    291 		 * to get/establish the SA. Here I discard
    292 		 * this packet because it is responsibility for
    293 		 * upper layer to retransmit the packet.
    294 		 */
    295 		newipsecstat.ips_out_nosa++;
    296 		goto bad;
    297 	}
    298 	sav = isr->sav;
    299 	if (sav == NULL) {		/* XXX valid return */
    300 		IPSEC_ASSERT(ipsec_get_reqlevel(isr) == IPSEC_LEVEL_USE,
    301 			("ipsec_nextisr: no SA found, but required; level %u",
    302 			ipsec_get_reqlevel(isr)));
    303 		isr = isr->next;
    304 		if (isr == NULL) {
    305 			/*XXXstatistic??*/
    306 			*error = EINVAL;		/*XXX*/
    307 			return isr;
    308 		}
    309 		goto again;
    310 	}
    311 
    312 	/*
    313 	 * Check system global policy controls.
    314 	 */
    315 	if ((isr->saidx.proto == IPPROTO_ESP && !esp_enable) ||
    316 	    (isr->saidx.proto == IPPROTO_AH && !ah_enable) ||
    317 	    (isr->saidx.proto == IPPROTO_IPCOMP && !ipcomp_enable)) {
    318 		DPRINTF(("ipsec_nextisr: IPsec outbound packet dropped due"
    319 			" to policy (check your sysctls)\n"));
    320 		IPSEC_OSTAT(espstat.esps_pdrops, ahstat.ahs_pdrops,
    321 		    ipcompstat.ipcomps_pdrops);
    322 		*error = EHOSTUNREACH;
    323 		goto bad;
    324 	}
    325 
    326 	/*
    327 	 * Sanity check the SA contents for the caller
    328 	 * before they invoke the xform output method.
    329 	 */
    330 	if (sav->tdb_xform == NULL) {
    331 		DPRINTF(("ipsec_nextisr: no transform for SA\n"));
    332 		IPSEC_OSTAT(espstat.esps_noxform, ahstat.ahs_noxform,
    333 		    ipcompstat.ipcomps_noxform);
    334 		*error = EHOSTUNREACH;
    335 		goto bad;
    336 	}
    337 	return isr;
    338 bad:
    339 	IPSEC_ASSERT(*error != 0, ("ipsec_nextisr: error return w/ no error code"));
    340 	return NULL;
    341 #undef IPSEC_OSTAT
    342 }
    343 
    344 #ifdef INET
    345 /*
    346  * IPsec output logic for IPv4.
    347  */
    348 int
    349 ipsec4_process_packet(
    350 	struct mbuf *m,
    351 	struct ipsecrequest *isr,
    352 	int flags,
    353 	int tunalready)
    354 {
    355 	struct secasindex saidx;
    356 	struct secasvar *sav;
    357 	struct ip *ip;
    358 	int s, error, i, off;
    359 
    360 	IPSEC_ASSERT(m != NULL, ("ipsec4_process_packet: null mbuf"));
    361 	IPSEC_ASSERT(isr != NULL, ("ipsec4_process_packet: null isr"));
    362 
    363 	s = splsoftnet();			/* insure SA contents don't change */
    364 
    365 	isr = ipsec_nextisr(m, isr, AF_INET, &saidx, &error);
    366 	if (isr == NULL)
    367 		goto bad;
    368 
    369 	sav = isr->sav;
    370 	if (!tunalready) {
    371 		union sockaddr_union *dst = &sav->sah->saidx.dst;
    372 		int setdf;
    373 
    374 		/*
    375 		 * Collect IP_DF state from the outer header.
    376 		 */
    377 		if (dst->sa.sa_family == AF_INET) {
    378 			if (m->m_len < sizeof (struct ip) &&
    379 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
    380 				error = ENOBUFS;
    381 				goto bad;
    382 			}
    383 			ip = mtod(m, struct ip *);
    384 			/* Honor system-wide control of how to handle IP_DF */
    385 			switch (ip4_ipsec_dfbit) {
    386 			case 0:			/* clear in outer header */
    387 			case 1:			/* set in outer header */
    388 				setdf = ip4_ipsec_dfbit;
    389 				break;
    390 			default:		/* propagate to outer header */
    391 				setdf = ip->ip_off;
    392 #ifndef __FreeBSD__
    393 		/* On FreeBSD, ip_off and ip_len assumed in host endian. */
    394 				setdf = ntohs(setdf);
    395 #endif
    396 				setdf = htons(setdf & IP_DF);
    397 				break;
    398 			}
    399 		} else {
    400 			ip = NULL;		/* keep compiler happy */
    401 			setdf = 0;
    402 		}
    403 		/* Do the appropriate encapsulation, if necessary */
    404 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
    405 		    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
    406 #if 0
    407 		    (sav->flags & SADB_X_SAFLAGS_TUNNEL) || /* Tunnel requ'd */
    408 		    sav->tdb_xform->xf_type == XF_IP4 ||    /* ditto */
    409 #endif
    410 		    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
    411 		     dst->sin.sin_addr.s_addr != INADDR_ANY &&
    412 		     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
    413 			struct mbuf *mp;
    414 
    415 			/* Fix IPv4 header checksum and length */
    416 			if (m->m_len < sizeof (struct ip) &&
    417 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
    418 				error = ENOBUFS;
    419 				goto bad;
    420 			}
    421 			ip = mtod(m, struct ip *);
    422 			ip->ip_len = htons(m->m_pkthdr.len);
    423 			ip->ip_sum = 0;
    424 #ifdef _IP_VHL
    425 			if (ip->ip_vhl == IP_VHL_BORING)
    426 				ip->ip_sum = in_cksum_hdr(ip);
    427 			else
    428 				ip->ip_sum = in_cksum(m,
    429 					_IP_VHL_HL(ip->ip_vhl) << 2);
    430 #else
    431 			ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
    432 #endif
    433 
    434 			/* Encapsulate the packet */
    435 			error = ipip_output(m, isr, &mp, 0, 0);
    436 			if (mp == NULL && !error) {
    437 				/* Should never happen. */
    438 				DPRINTF(("ipsec4_process_packet: ipip_output "
    439 					"returns no mbuf and no error!"));
    440 				error = EFAULT;
    441 			}
    442 			if (error) {
    443 				if (mp) {
    444 					/* XXX: Should never happen! */
    445 					m_freem(mp);
    446 				}
    447 				m = NULL; /* ipip_output() already freed it */
    448 				goto bad;
    449 			}
    450 			m = mp, mp = NULL;
    451 			/*
    452 			 * ipip_output clears IP_DF in the new header.  If
    453 			 * we need to propagate IP_DF from the outer header,
    454 			 * then we have to do it here.
    455 			 *
    456 			 * XXX shouldn't assume what ipip_output does.
    457 			 */
    458 			if (dst->sa.sa_family == AF_INET && setdf) {
    459 				if (m->m_len < sizeof (struct ip) &&
    460 				    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
    461 					error = ENOBUFS;
    462 					goto bad;
    463 				}
    464 				ip = mtod(m, struct ip *);
    465 				ip->ip_off = ntohs(ip->ip_off);
    466 				ip->ip_off |= IP_DF;
    467 				ip->ip_off = htons(ip->ip_off);
    468 			}
    469 		}
    470 	}
    471 
    472 	/*
    473 	 * Dispatch to the appropriate IPsec transform logic.  The
    474 	 * packet will be returned for transmission after crypto
    475 	 * processing, etc. are completed.  For encapsulation we
    476 	 * bypass this call because of the explicit call done above
    477 	 * (necessary to deal with IP_DF handling for IPv4).
    478 	 *
    479 	 * NB: m & sav are ``passed to caller'' who's reponsible for
    480 	 *     for reclaiming their resources.
    481 	 */
    482 	if (sav->tdb_xform->xf_type != XF_IP4) {
    483 		ip = mtod(m, struct ip *);
    484 		i = ip->ip_hl << 2;
    485 		off = offsetof(struct ip, ip_p);
    486 		error = (*sav->tdb_xform->xf_output)(m, isr, NULL, i, off);
    487 	} else {
    488 		error = ipsec_process_done(m, isr);
    489 	}
    490 	splx(s);
    491 	return error;
    492 bad:
    493 	splx(s);
    494 	if (m)
    495 		m_freem(m);
    496 	return error;
    497 }
    498 #endif
    499 
    500 #ifdef INET6
    501 /*
    502  * Chop IP6 header from the payload.
    503  */
    504 static struct mbuf *
    505 ipsec6_splithdr(struct mbuf *m)
    506 {
    507 	struct mbuf *mh;
    508 	struct ip6_hdr *ip6;
    509 	int hlen;
    510 
    511 	IPSEC_ASSERT(m->m_len >= sizeof (struct ip6_hdr),
    512 		("ipsec6_splithdr: first mbuf too short, len %u", m->m_len));
    513 	ip6 = mtod(m, struct ip6_hdr *);
    514 	hlen = sizeof(struct ip6_hdr);
    515 	if (m->m_len > hlen) {
    516 		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
    517 		if (!mh) {
    518 			m_freem(m);
    519 			return NULL;
    520 		}
    521 		M_MOVE_PKTHDR(mh, m);
    522 		MH_ALIGN(mh, hlen);
    523 		m->m_len -= hlen;
    524 		m->m_data += hlen;
    525 		mh->m_next = m;
    526 		m = mh;
    527 		m->m_len = hlen;
    528 		bcopy((caddr_t)ip6, mtod(m, caddr_t), hlen);
    529 	} else if (m->m_len < hlen) {
    530 		m = m_pullup(m, hlen);
    531 		if (!m)
    532 			return NULL;
    533 	}
    534 	return m;
    535 }
    536 
    537 /*
    538  * IPsec output logic for IPv6, transport mode.
    539  */
    540 int
    541 ipsec6_output_trans(
    542 	struct ipsec_output_state *state,
    543 	u_char *nexthdrp,
    544 	struct mbuf *mprev,
    545 	struct secpolicy *sp,
    546 	int flags,
    547 	int *tun)
    548 {
    549 	struct ipsecrequest *isr;
    550 	struct secasindex saidx;
    551 	int error = 0;
    552 	struct mbuf *m;
    553 
    554 	IPSEC_ASSERT(state != NULL, ("ipsec6_output: null state"));
    555 	IPSEC_ASSERT(state->m != NULL, ("ipsec6_output: null m"));
    556 	IPSEC_ASSERT(nexthdrp != NULL, ("ipsec6_output: null nexthdrp"));
    557 	IPSEC_ASSERT(mprev != NULL, ("ipsec6_output: null mprev"));
    558 	IPSEC_ASSERT(sp != NULL, ("ipsec6_output: null sp"));
    559 	IPSEC_ASSERT(tun != NULL, ("ipsec6_output: null tun"));
    560 
    561 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
    562 		printf("ipsec6_output_trans: applyed SP\n");
    563 		kdebug_secpolicy(sp));
    564 
    565 	isr = sp->req;
    566 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
    567 		/* the rest will be handled by ipsec6_output_tunnel() */
    568 		*tun = 1;		/* need tunnel-mode processing */
    569 		return 0;
    570 	}
    571 
    572 	*tun = 0;
    573 	m = state->m;
    574 
    575 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
    576 	if (isr == NULL) {
    577 #ifdef notdef
    578 		/* XXX should notification be done for all errors ? */
    579 		/*
    580 		 * Notify the fact that the packet is discarded
    581 		 * to ourselves. I believe this is better than
    582 		 * just silently discarding. (jinmei (at) kame.net)
    583 		 * XXX: should we restrict the error to TCP packets?
    584 		 * XXX: should we directly notify sockets via
    585 		 *      pfctlinputs?
    586 		 */
    587 		icmp6_error(m, ICMP6_DST_UNREACH,
    588 			    ICMP6_DST_UNREACH_ADMIN, 0);
    589 		m = NULL;	/* NB: icmp6_error frees mbuf */
    590 #endif
    591 		goto bad;
    592 	}
    593 
    594 	return (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
    595 		sizeof (struct ip6_hdr),
    596 		offsetof(struct ip6_hdr, ip6_nxt));
    597 bad:
    598 	if (m)
    599 		m_freem(m);
    600 	state->m = NULL;
    601 	return error;
    602 }
    603 
    604 static int
    605 ipsec6_encapsulate(struct mbuf *m, struct secasvar *sav)
    606 {
    607 	struct ip6_hdr *oip6;
    608 	struct ip6_hdr *ip6;
    609 	size_t plen;
    610 
    611 	/* can't tunnel between different AFs */
    612 	if (sav->sah->saidx.src.sa.sa_family != AF_INET6 ||
    613 	    sav->sah->saidx.dst.sa.sa_family != AF_INET6) {
    614 		m_freem(m);
    615 		return EINVAL;
    616 	}
    617 	IPSEC_ASSERT(m->m_len != sizeof (struct ip6_hdr),
    618 		("ipsec6_encapsulate: mbuf wrong size; len %u", m->m_len));
    619 
    620 
    621 	/*
    622 	 * grow the mbuf to accomodate the new IPv6 header.
    623 	 */
    624 	plen = m->m_pkthdr.len;
    625 	if (M_LEADINGSPACE(m->m_next) < sizeof(struct ip6_hdr)) {
    626 		struct mbuf *n;
    627 		MGET(n, M_DONTWAIT, MT_DATA);
    628 		if (!n) {
    629 			m_freem(m);
    630 			return ENOBUFS;
    631 		}
    632 		n->m_len = sizeof(struct ip6_hdr);
    633 		n->m_next = m->m_next;
    634 		m->m_next = n;
    635 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
    636 		oip6 = mtod(n, struct ip6_hdr *);
    637 	} else {
    638 		m->m_next->m_len += sizeof(struct ip6_hdr);
    639 		m->m_next->m_data -= sizeof(struct ip6_hdr);
    640 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
    641 		oip6 = mtod(m->m_next, struct ip6_hdr *);
    642 	}
    643 	ip6 = mtod(m, struct ip6_hdr *);
    644 	ovbcopy((caddr_t)ip6, (caddr_t)oip6, sizeof(struct ip6_hdr));
    645 
    646 	/* Fake link-local scope-class addresses */
    647 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_src))
    648 		oip6->ip6_src.s6_addr16[1] = 0;
    649 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_dst))
    650 		oip6->ip6_dst.s6_addr16[1] = 0;
    651 
    652 	/* construct new IPv6 header. see RFC 2401 5.1.2.2 */
    653 	/* ECN consideration. */
    654 	ip6_ecn_ingress(ip6_ipsec_ecn, &ip6->ip6_flow, &oip6->ip6_flow);
    655 	if (plen < IPV6_MAXPACKET - sizeof(struct ip6_hdr))
    656 		ip6->ip6_plen = htons(plen);
    657 	else {
    658 		/* ip6->ip6_plen will be updated in ip6_output() */
    659 	}
    660 	ip6->ip6_nxt = IPPROTO_IPV6;
    661 	sav->sah->saidx.src.sin6.sin6_addr = ip6->ip6_src;
    662 	sav->sah->saidx.dst.sin6.sin6_addr = ip6->ip6_dst;
    663 	ip6->ip6_hlim = IPV6_DEFHLIM;
    664 
    665 	/* XXX Should ip6_src be updated later ? */
    666 
    667 	return 0;
    668 }
    669 
    670 /*
    671  * IPsec output logic for IPv6, tunnel mode.
    672  */
    673 int
    674 ipsec6_output_tunnel(struct ipsec_output_state *state, struct secpolicy *sp, int flags)
    675 {
    676 	struct ip6_hdr *ip6;
    677 	struct ipsecrequest *isr;
    678 	struct secasindex saidx;
    679 	int error;
    680 	struct sockaddr_in6* dst6;
    681 	struct mbuf *m;
    682 
    683 	IPSEC_ASSERT(state != NULL, ("ipsec6_output: null state"));
    684 	IPSEC_ASSERT(state->m != NULL, ("ipsec6_output: null m"));
    685 	IPSEC_ASSERT(sp != NULL, ("ipsec6_output: null sp"));
    686 
    687 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
    688 		printf("ipsec6_output_tunnel: applyed SP\n");
    689 		kdebug_secpolicy(sp));
    690 
    691 	m = state->m;
    692 	/*
    693 	 * transport mode ipsec (before the 1st tunnel mode) is already
    694 	 * processed by ipsec6_output_trans().
    695 	 */
    696 	for (isr = sp->req; isr; isr = isr->next) {
    697 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
    698 			break;
    699 	}
    700 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
    701 	if (isr == NULL)
    702 		goto bad;
    703 
    704 	/*
    705 	 * There may be the case that SA status will be changed when
    706 	 * we are refering to one. So calling splsoftnet().
    707 	 */
    708 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
    709 		/*
    710 		 * build IPsec tunnel.
    711 		 */
    712 		/* XXX should be processed with other familiy */
    713 		if (isr->sav->sah->saidx.src.sa.sa_family != AF_INET6) {
    714 			ipseclog((LOG_ERR, "ipsec6_output_tunnel: "
    715 			    "family mismatched between inner and outer, spi=%lu\n",
    716 			    (u_long)ntohl(isr->sav->spi)));
    717 			newipsecstat.ips_out_inval++;
    718 			error = EAFNOSUPPORT;
    719 			goto bad;
    720 		}
    721 
    722 		m = ipsec6_splithdr(m);
    723 		if (!m) {
    724 			newipsecstat.ips_out_nomem++;
    725 			error = ENOMEM;
    726 			goto bad;
    727 		}
    728 		error = ipsec6_encapsulate(m, isr->sav);
    729 		if (error) {
    730 			m = NULL;
    731 			goto bad;
    732 		}
    733 		ip6 = mtod(m, struct ip6_hdr *);
    734 
    735 		state->ro = &isr->sav->sah->sa_route;
    736 		state->dst = (struct sockaddr *)&state->ro->ro_dst;
    737 		dst6 = (struct sockaddr_in6 *)state->dst;
    738 		if (state->ro->ro_rt
    739 		 && ((state->ro->ro_rt->rt_flags & RTF_UP) == 0
    740 		  || !IN6_ARE_ADDR_EQUAL(&dst6->sin6_addr, &ip6->ip6_dst))) {
    741 			RTFREE(state->ro->ro_rt);
    742 			state->ro->ro_rt = NULL;
    743 		}
    744 		if (state->ro->ro_rt == 0) {
    745 			bzero(dst6, sizeof(*dst6));
    746 			dst6->sin6_family = AF_INET6;
    747 			dst6->sin6_len = sizeof(*dst6);
    748 			dst6->sin6_addr = ip6->ip6_dst;
    749 			rtalloc(state->ro);
    750 		}
    751 		if (state->ro->ro_rt == 0) {
    752 			ip6stat.ip6s_noroute++;
    753 			newipsecstat.ips_out_noroute++;
    754 			error = EHOSTUNREACH;
    755 			goto bad;
    756 		}
    757 
    758 		/* adjust state->dst if tunnel endpoint is offlink */
    759 		if (state->ro->ro_rt->rt_flags & RTF_GATEWAY) {
    760 			state->dst = (struct sockaddr *)state->ro->ro_rt->rt_gateway;
    761 			dst6 = (struct sockaddr_in6 *)state->dst;
    762 		}
    763 	}
    764 
    765 	m = ipsec6_splithdr(m);
    766 	if (!m) {
    767 		newipsecstat.ips_out_nomem++;
    768 		error = ENOMEM;
    769 		goto bad;
    770 	}
    771 	ip6 = mtod(m, struct ip6_hdr *);
    772 	return (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
    773 		sizeof (struct ip6_hdr),
    774 		offsetof(struct ip6_hdr, ip6_nxt));
    775 bad:
    776 	if (m)
    777 		m_freem(m);
    778 	state->m = NULL;
    779 	return error;
    780 }
    781 #endif /*INET6*/
    782