Home | History | Annotate | Line # | Download | only in netipsec
ipsec_output.c revision 1.63
      1 /*	$NetBSD: ipsec_output.c,v 1.63 2017/10/03 08:34:28 ozaki-r 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.63 2017/10/03 08:34:28 ozaki-r Exp $");
     33 
     34 /*
     35  * IPsec output processing.
     36  */
     37 #if defined(_KERNEL_OPT)
     38 #include "opt_inet.h"
     39 #include "opt_net_mpsafe.h"
     40 #endif
     41 
     42 #include <sys/param.h>
     43 #include <sys/systm.h>
     44 #include <sys/mbuf.h>
     45 #include <sys/domain.h>
     46 #include <sys/protosw.h>
     47 #include <sys/socket.h>
     48 #include <sys/errno.h>
     49 #include <sys/syslog.h>
     50 
     51 #include <net/if.h>
     52 #include <net/route.h>
     53 
     54 #include <netinet/in.h>
     55 #include <netinet/in_systm.h>
     56 #include <netinet/ip.h>
     57 #include <netinet/ip_var.h>
     58 #include <netinet/in_var.h>
     59 #include <netinet/ip_ecn.h>
     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 #include <netinet/udp.h>
     70 
     71 #include <netipsec/ipsec.h>
     72 #include <netipsec/ipsec_var.h>
     73 #include <netipsec/ipsec_private.h>
     74 #ifdef INET6
     75 #include <netipsec/ipsec6.h>
     76 #endif
     77 #include <netipsec/ah_var.h>
     78 #include <netipsec/esp_var.h>
     79 #include <netipsec/ipcomp_var.h>
     80 
     81 #include <netipsec/xform.h>
     82 
     83 #include <netipsec/key.h>
     84 #include <netipsec/keydb.h>
     85 #include <netipsec/key_debug.h>
     86 
     87 #include <net/net_osdep.h>		/* ovbcopy() in ipsec6_encapsulate() */
     88 
     89 static percpu_t *ipsec_rtcache_percpu __cacheline_aligned;
     90 
     91 /*
     92  * Add a IPSEC_OUT_DONE tag to mark that we have finished the ipsec processing
     93  * It will be used by ip{,6}_output to check if we have already or not
     94  * processed this packet.
     95  */
     96 static int
     97 ipsec_register_done(struct mbuf *m, int * error)
     98 {
     99 	struct m_tag *mtag;
    100 
    101 	mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE, 0, M_NOWAIT);
    102 	if (mtag == NULL) {
    103 		IPSECLOG(LOG_DEBUG, "could not get packet tag\n");
    104 		*error = ENOMEM;
    105 		return -1;
    106 	}
    107 
    108 	m_tag_prepend(m, mtag);
    109 	return 0;
    110 }
    111 
    112 static int
    113 ipsec_reinject_ipstack(struct mbuf *m, int af)
    114 {
    115 	int rv = -1;
    116 	struct route *ro;
    117 
    118 	KASSERT(af == AF_INET || af == AF_INET6);
    119 
    120 #ifndef NET_MPSAFE
    121 	KERNEL_LOCK(1, NULL);
    122 #endif
    123 	ro = percpu_getref(ipsec_rtcache_percpu);
    124 	switch (af) {
    125 #ifdef INET
    126 	case AF_INET:
    127 		rv = ip_output(m, NULL, ro, IP_RAWOUTPUT|IP_NOIPNEWID,
    128 		    NULL, NULL);
    129 		break;
    130 #endif
    131 #ifdef INET6
    132 	case AF_INET6:
    133 		/*
    134 		 * We don't need massage, IPv6 header fields are always in
    135 		 * net endian.
    136 		 */
    137 		rv = ip6_output(m, NULL, ro, 0, NULL, NULL, NULL);
    138 		break;
    139 #endif
    140 	}
    141 	percpu_putref(ipsec_rtcache_percpu);
    142 #ifndef NET_MPSAFE
    143 	KERNEL_UNLOCK_ONE(NULL);
    144 #endif
    145 
    146 	return rv;
    147 }
    148 
    149 int
    150 ipsec_process_done(struct mbuf *m, struct ipsecrequest *isr,
    151     struct secasvar *sav)
    152 {
    153 	struct secasindex *saidx;
    154 	int error;
    155 #ifdef INET
    156 	struct ip * ip;
    157 #endif /* INET */
    158 #ifdef INET6
    159 	struct ip6_hdr * ip6;
    160 #endif /* INET6 */
    161 	struct mbuf * mo;
    162 	struct udphdr *udp = NULL;
    163 	uint64_t * data = NULL;
    164 	int hlen, roff;
    165 
    166 	IPSEC_SPLASSERT_SOFTNET("ipsec_process_done");
    167 
    168 	KASSERT(m != NULL);
    169 	KASSERT(isr != NULL);
    170 	KASSERT(sav != NULL);
    171 
    172 	saidx = &sav->sah->saidx;
    173 
    174 	if(sav->natt_type != 0) {
    175 		ip = mtod(m, struct ip *);
    176 
    177 		hlen = sizeof(struct udphdr);
    178 		if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
    179 			hlen += sizeof(uint64_t);
    180 
    181 		mo = m_makespace(m, sizeof(struct ip), hlen, &roff);
    182 		if (mo == NULL) {
    183 			char buf[IPSEC_ADDRSTRLEN];
    184 			IPSECLOG(LOG_DEBUG,
    185 			    "failed to inject %u byte UDP for SA %s/%08lx\n",
    186 			    hlen, ipsec_address(&saidx->dst, buf, sizeof(buf)),
    187 			    (u_long) ntohl(sav->spi));
    188 			error = ENOBUFS;
    189 			goto bad;
    190 		}
    191 
    192 		udp = (struct udphdr*) (mtod(mo, char*) + roff);
    193 		data = (uint64_t*) (udp + 1);
    194 
    195 		if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
    196 			*data = 0; /* NON-IKE Marker */
    197 
    198 		if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
    199 			udp->uh_sport = htons(UDP_ENCAP_ESPINUDP_PORT);
    200 		else
    201 			udp->uh_sport = key_portfromsaddr(&saidx->src);
    202 
    203 		udp->uh_dport = key_portfromsaddr(&saidx->dst);
    204 		udp->uh_sum = 0;
    205 		udp->uh_ulen = htons(m->m_pkthdr.len - (ip->ip_hl << 2));
    206 	}
    207 
    208 	switch (saidx->dst.sa.sa_family) {
    209 #ifdef INET
    210 	case AF_INET:
    211 		/* Fix the header length, for AH processing. */
    212 		ip = mtod(m, struct ip *);
    213 		ip->ip_len = htons(m->m_pkthdr.len);
    214 		if (sav->natt_type != 0)
    215 			ip->ip_p = IPPROTO_UDP;
    216 		break;
    217 #endif /* INET */
    218 #ifdef INET6
    219 	case AF_INET6:
    220 		/* Fix the header length, for AH processing. */
    221 		if (m->m_pkthdr.len < sizeof (struct ip6_hdr)) {
    222 			error = ENXIO;
    223 			goto bad;
    224 		}
    225 		if (m->m_pkthdr.len - sizeof (struct ip6_hdr) > IPV6_MAXPACKET) {
    226 			/* No jumbogram support. */
    227 			error = ENXIO;	/*?*/
    228 			goto bad;
    229 		}
    230 		ip6 = mtod(m, struct ip6_hdr *);
    231 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
    232 		if (sav->natt_type != 0)
    233 			ip6->ip6_nxt = IPPROTO_UDP;
    234 		break;
    235 #endif /* INET6 */
    236 	default:
    237 		IPSECLOG(LOG_DEBUG, "unknown protocol family %u\n",
    238 		    saidx->dst.sa.sa_family);
    239 		error = ENXIO;
    240 		goto bad;
    241 	}
    242 
    243 	key_sa_recordxfer(sav, m);
    244 
    245 	/*
    246 	 * If there's another (bundled) SA to apply, do so.
    247 	 * Note that this puts a burden on the kernel stack size.
    248 	 * If this is a problem we'll need to introduce a queue
    249 	 * to set the packet on so we can unwind the stack before
    250 	 * doing further processing.
    251 	 */
    252 	if (isr->next) {
    253 		IPSEC_STATINC(IPSEC_STAT_OUT_BUNDLESA);
    254 		switch ( saidx->dst.sa.sa_family ) {
    255 #ifdef INET
    256 		case AF_INET:
    257 			return ipsec4_process_packet(m, isr->next, NULL);
    258 #endif /* INET */
    259 #ifdef INET6
    260 		case AF_INET6:
    261 			return ipsec6_process_packet(m,isr->next);
    262 #endif /* INET6 */
    263 		default :
    264 			IPSECLOG(LOG_DEBUG, "unknown protocol family %u\n",
    265 			    saidx->dst.sa.sa_family);
    266 			error = ENXIO;
    267 			goto bad;
    268 		}
    269 	}
    270 
    271 	/*
    272 	 * We're done with IPsec processing,
    273 	 * mark that we have already processed the packet
    274 	 * transmit it packet using the appropriate network protocol (IP or IPv6).
    275 	 */
    276 
    277 	if (ipsec_register_done(m, &error) < 0)
    278 		goto bad;
    279 
    280 	return ipsec_reinject_ipstack(m, saidx->dst.sa.sa_family);
    281 bad:
    282 	m_freem(m);
    283 	return (error);
    284 }
    285 
    286 static void
    287 ipsec_fill_saidx_bymbuf(struct secasindex *saidx, const struct mbuf *m,
    288     const int af)
    289 {
    290 
    291 	if (af == AF_INET) {
    292 		struct sockaddr_in *sin;
    293 		struct ip *ip = mtod(m, struct ip *);
    294 
    295 		if (saidx->src.sa.sa_len == 0) {
    296 			sin = &saidx->src.sin;
    297 			sin->sin_len = sizeof(*sin);
    298 			sin->sin_family = AF_INET;
    299 			sin->sin_port = IPSEC_PORT_ANY;
    300 			sin->sin_addr = ip->ip_src;
    301 		}
    302 		if (saidx->dst.sa.sa_len == 0) {
    303 			sin = &saidx->dst.sin;
    304 			sin->sin_len = sizeof(*sin);
    305 			sin->sin_family = AF_INET;
    306 			sin->sin_port = IPSEC_PORT_ANY;
    307 			sin->sin_addr = ip->ip_dst;
    308 		}
    309 	} else {
    310 		struct sockaddr_in6 *sin6;
    311 		struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
    312 
    313 		if (saidx->src.sin6.sin6_len == 0) {
    314 			sin6 = (struct sockaddr_in6 *)&saidx->src;
    315 			sin6->sin6_len = sizeof(*sin6);
    316 			sin6->sin6_family = AF_INET6;
    317 			sin6->sin6_port = IPSEC_PORT_ANY;
    318 			sin6->sin6_addr = ip6->ip6_src;
    319 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
    320 				/* fix scope id for comparing SPD */
    321 				sin6->sin6_addr.s6_addr16[1] = 0;
    322 				sin6->sin6_scope_id =
    323 				    ntohs(ip6->ip6_src.s6_addr16[1]);
    324 			}
    325 		}
    326 		if (saidx->dst.sin6.sin6_len == 0) {
    327 			sin6 = (struct sockaddr_in6 *)&saidx->dst;
    328 			sin6->sin6_len = sizeof(*sin6);
    329 			sin6->sin6_family = AF_INET6;
    330 			sin6->sin6_port = IPSEC_PORT_ANY;
    331 			sin6->sin6_addr = ip6->ip6_dst;
    332 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
    333 				/* fix scope id for comparing SPD */
    334 				sin6->sin6_addr.s6_addr16[1] = 0;
    335 				sin6->sin6_scope_id =
    336 				    ntohs(ip6->ip6_dst.s6_addr16[1]);
    337 			}
    338 		}
    339 	}
    340 }
    341 
    342 struct secasvar *
    343 ipsec_lookup_sa(const struct ipsecrequest *isr, const struct mbuf *m)
    344 {
    345 	struct secasindex saidx;
    346 
    347 	saidx = isr->saidx;
    348 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
    349 		/* Fillin unspecified SA peers only for transport mode */
    350 		ipsec_fill_saidx_bymbuf(&saidx, m, isr->saidx.dst.sa.sa_family);
    351 	}
    352 
    353 	return key_lookup_sa_bysaidx(&saidx);
    354 }
    355 
    356 /*
    357  * ipsec_nextisr can return :
    358  * - isr == NULL and error != 0 => something is bad : the packet must be
    359  *   discarded
    360  * - isr == NULL and error == 0 => no more rules to apply, ipsec processing
    361  *   is done, reinject it in ip stack
    362  * - isr != NULL (error == 0) => we need to apply one rule to the packet
    363  */
    364 static struct ipsecrequest *
    365 ipsec_nextisr(
    366 	struct mbuf *m,
    367 	struct ipsecrequest *isr,
    368 	int af,
    369 	int *error,
    370 	struct secasvar **ret
    371 )
    372 {
    373 #define	IPSEC_OSTAT(type)						\
    374 do {									\
    375 	switch (isr->saidx.proto) {					\
    376 	case IPPROTO_ESP:						\
    377 		ESP_STATINC(ESP_STAT_ ## type);				\
    378 		break;							\
    379 	case IPPROTO_AH:						\
    380 		AH_STATINC(AH_STAT_ ## type);				\
    381 		break;							\
    382 	default:							\
    383 		IPCOMP_STATINC(IPCOMP_STAT_ ## type);			\
    384 		break;							\
    385 	}								\
    386 } while (/*CONSTCOND*/0)
    387 
    388 	struct secasvar *sav = NULL;
    389 	struct secasindex saidx;
    390 
    391 	IPSEC_SPLASSERT_SOFTNET("ipsec_nextisr");
    392 	KASSERTMSG(af == AF_INET || af == AF_INET6,
    393 	    "invalid address family %u", af);
    394 again:
    395 	/*
    396 	 * Craft SA index to search for proper SA.  Note that
    397 	 * we only fillin unspecified SA peers for transport
    398 	 * mode; for tunnel mode they must already be filled in.
    399 	 */
    400 	saidx = isr->saidx;
    401 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
    402 		/* Fillin unspecified SA peers only for transport mode */
    403 		ipsec_fill_saidx_bymbuf(&saidx, m, af);
    404 	}
    405 
    406 	/*
    407 	 * Lookup SA and validate it.
    408 	 */
    409 	*error = key_checkrequest(isr, &saidx, &sav);
    410 	if (*error != 0) {
    411 		/*
    412 		 * IPsec processing is required, but no SA found.
    413 		 * I assume that key_acquire() had been called
    414 		 * to get/establish the SA. Here I discard
    415 		 * this packet because it is responsibility for
    416 		 * upper layer to retransmit the packet.
    417 		 */
    418 		IPSEC_STATINC(IPSEC_STAT_OUT_NOSA);
    419 		goto bad;
    420 	}
    421 	/* sav may be NULL here if we have an USE rule */
    422 	if (sav == NULL) {
    423 		KASSERTMSG(ipsec_get_reqlevel(isr) == IPSEC_LEVEL_USE,
    424 		    "no SA found, but required; level %u",
    425 		    ipsec_get_reqlevel(isr));
    426 		isr = isr->next;
    427 		/*
    428 		 * No more rules to apply, return NULL isr and no error
    429 		 * It can happen when the last rules are USE rules
    430 		 * */
    431 		if (isr == NULL) {
    432 			*ret = NULL;
    433 			*error = 0;
    434 			return isr;
    435 		}
    436 		goto again;
    437 	}
    438 
    439 	/*
    440 	 * Check system global policy controls.
    441 	 */
    442 	if ((isr->saidx.proto == IPPROTO_ESP && !esp_enable) ||
    443 	    (isr->saidx.proto == IPPROTO_AH && !ah_enable) ||
    444 	    (isr->saidx.proto == IPPROTO_IPCOMP && !ipcomp_enable)) {
    445 		IPSECLOG(LOG_DEBUG, "IPsec outbound packet dropped due"
    446 		    " to policy (check your sysctls)\n");
    447 		IPSEC_OSTAT(PDROPS);
    448 		*error = EHOSTUNREACH;
    449 		KEY_SA_UNREF(&sav);
    450 		goto bad;
    451 	}
    452 
    453 	/*
    454 	 * Sanity check the SA contents for the caller
    455 	 * before they invoke the xform output method.
    456 	 */
    457 	KASSERT(sav->tdb_xform != NULL);
    458 	*ret = sav;
    459 	return isr;
    460 bad:
    461 	KASSERTMSG(*error != 0, "error return w/ no error code");
    462 	return NULL;
    463 #undef IPSEC_OSTAT
    464 }
    465 
    466 #ifdef INET
    467 /*
    468  * IPsec output logic for IPv4.
    469  */
    470 int
    471 ipsec4_process_packet(struct mbuf *m, struct ipsecrequest *isr,
    472     u_long *mtu)
    473 {
    474 	struct secasvar *sav = NULL;
    475 	struct ip *ip;
    476 	int s, error, i, off;
    477 	union sockaddr_union *dst;
    478 	int setdf;
    479 
    480 	KASSERT(m != NULL);
    481 	KASSERT(isr != NULL);
    482 
    483 	s = splsoftnet();			/* insure SA contents don't change */
    484 
    485 	isr = ipsec_nextisr(m, isr, AF_INET, &error, &sav);
    486 	if (isr == NULL) {
    487 		if (error != 0) {
    488 			goto bad;
    489 		} else {
    490 			if (ipsec_register_done(m, &error) < 0)
    491 				goto bad;
    492 
    493 			splx(s);
    494 			return ipsec_reinject_ipstack(m, AF_INET);
    495 		}
    496 	}
    497 
    498 	KASSERT(sav != NULL);
    499 	/*
    500 	 * Check if we need to handle NAT-T fragmentation.
    501 	 */
    502 	if (isr == isr->sp->req) { /* Check only if called from ipsec4_output */
    503 		KASSERT(mtu != NULL);
    504 		ip = mtod(m, struct ip *);
    505 		if (!(sav->natt_type &
    506 		    (UDP_ENCAP_ESPINUDP|UDP_ENCAP_ESPINUDP_NON_IKE))) {
    507 			goto noneed;
    508 		}
    509 		if (ntohs(ip->ip_len) <= sav->esp_frag)
    510 			goto noneed;
    511 		*mtu = sav->esp_frag;
    512 		KEY_SA_UNREF(&sav);
    513 		splx(s);
    514 		return 0;
    515 	}
    516 noneed:
    517 	dst = &sav->sah->saidx.dst;
    518 
    519 	/*
    520 	 * Collect IP_DF state from the outer header.
    521 	 */
    522 	if (dst->sa.sa_family == AF_INET) {
    523 		if (m->m_len < sizeof (struct ip) &&
    524 		    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
    525 			error = ENOBUFS;
    526 			goto unrefsav;
    527 		}
    528 		ip = mtod(m, struct ip *);
    529 		/* Honor system-wide control of how to handle IP_DF */
    530 		switch (ip4_ipsec_dfbit) {
    531 		case 0:			/* clear in outer header */
    532 		case 1:			/* set in outer header */
    533 			setdf = ip4_ipsec_dfbit;
    534 			break;
    535 		default:		/* propagate to outer header */
    536 			setdf = ip->ip_off;
    537 			setdf = ntohs(setdf);
    538 			setdf = htons(setdf & IP_DF);
    539 			break;
    540 		}
    541 	} else {
    542 		ip = NULL;		/* keep compiler happy */
    543 		setdf = 0;
    544 	}
    545 	/* Do the appropriate encapsulation, if necessary */
    546 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
    547 	    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
    548 #if 0
    549 	    (sav->flags & SADB_X_SAFLAGS_TUNNEL) || /* Tunnel requ'd */
    550 	    sav->tdb_xform->xf_type == XF_IP4 ||    /* ditto */
    551 #endif
    552 	    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
    553 	     dst->sin.sin_addr.s_addr != INADDR_ANY &&
    554 	     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
    555 		struct mbuf *mp;
    556 
    557 		/* Fix IPv4 header checksum and length */
    558 		if (m->m_len < sizeof (struct ip) &&
    559 		    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
    560 			error = ENOBUFS;
    561 			goto unrefsav;
    562 		}
    563 		ip = mtod(m, struct ip *);
    564 		ip->ip_len = htons(m->m_pkthdr.len);
    565 		ip->ip_sum = 0;
    566 		ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
    567 
    568 		/* Encapsulate the packet */
    569 		error = ipip_output(m, isr, sav, &mp, 0, 0);
    570 		if (mp == NULL && !error) {
    571 			/* Should never happen. */
    572 			IPSECLOG(LOG_DEBUG,
    573 			    "ipip_output returns no mbuf and no error!");
    574 			error = EFAULT;
    575 		}
    576 		if (error) {
    577 			if (mp) {
    578 				/* XXX: Should never happen! */
    579 				m_freem(mp);
    580 			}
    581 			m = NULL; /* ipip_output() already freed it */
    582 			goto unrefsav;
    583 		}
    584 		m = mp, mp = NULL;
    585 		/*
    586 		 * ipip_output clears IP_DF in the new header.  If
    587 		 * we need to propagate IP_DF from the outer header,
    588 		 * then we have to do it here.
    589 		 *
    590 		 * XXX shouldn't assume what ipip_output does.
    591 		 */
    592 		if (dst->sa.sa_family == AF_INET && setdf) {
    593 			if (m->m_len < sizeof (struct ip) &&
    594 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
    595 				error = ENOBUFS;
    596 				goto unrefsav;
    597 			}
    598 			ip = mtod(m, struct ip *);
    599 			ip->ip_off |= htons(IP_DF);
    600 		}
    601 	}
    602 
    603 	/*
    604 	 * Dispatch to the appropriate IPsec transform logic.  The
    605 	 * packet will be returned for transmission after crypto
    606 	 * processing, etc. are completed.  For encapsulation we
    607 	 * bypass this call because of the explicit call done above
    608 	 * (necessary to deal with IP_DF handling for IPv4).
    609 	 *
    610 	 * NB: m & sav are ``passed to caller'' who's reponsible for
    611 	 *     for reclaiming their resources.
    612 	 */
    613 	if (sav->tdb_xform->xf_type != XF_IP4) {
    614 		if (dst->sa.sa_family == AF_INET) {
    615 			ip = mtod(m, struct ip *);
    616 			i = ip->ip_hl << 2;
    617 			off = offsetof(struct ip, ip_p);
    618 		} else {
    619 			i = sizeof(struct ip6_hdr);
    620 			off = offsetof(struct ip6_hdr, ip6_nxt);
    621 		}
    622 		error = (*sav->tdb_xform->xf_output)(m, isr, sav, NULL, i, off);
    623 	} else {
    624 		error = ipsec_process_done(m, isr, sav);
    625 	}
    626 	KEY_SA_UNREF(&sav);
    627 	splx(s);
    628 	return error;
    629 unrefsav:
    630 	KEY_SA_UNREF(&sav);
    631 bad:
    632 	splx(s);
    633 	if (m)
    634 		m_freem(m);
    635 	return error;
    636 }
    637 #endif
    638 
    639 #ifdef INET6
    640 static void
    641 compute_ipsec_pos(struct mbuf *m, int *i, int *off)
    642 {
    643 	int nxt;
    644 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr*);
    645 	struct ip6_ext ip6e;
    646 	int dstopt = 0;
    647 
    648 	*i = sizeof(struct ip6_hdr);
    649 	*off = offsetof(struct ip6_hdr, ip6_nxt);
    650 	nxt = ip6->ip6_nxt;
    651 
    652 	/*
    653 	 * chase mbuf chain to find the appropriate place to
    654 	 * put AH/ESP/IPcomp header.
    655 	 *  IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
    656 	 */
    657 	do {
    658 		switch (nxt) {
    659 		case IPPROTO_AH:
    660 		case IPPROTO_ESP:
    661 		case IPPROTO_IPCOMP:
    662 		/*
    663 		 * we should not skip security header added
    664 		 * beforehand.
    665 		 */
    666 			return;
    667 
    668 		case IPPROTO_HOPOPTS:
    669 		case IPPROTO_DSTOPTS:
    670 		case IPPROTO_ROUTING:
    671 		/*
    672 		 * if we see 2nd destination option header,
    673 		 * we should stop there.
    674 		 */
    675 			if (nxt == IPPROTO_DSTOPTS && dstopt)
    676 				return;
    677 
    678 			if (nxt == IPPROTO_DSTOPTS) {
    679 				/*
    680 				 * seen 1st or 2nd destination option.
    681 				 * next time we see one, it must be 2nd.
    682 				 */
    683 				dstopt = 1;
    684 			} else if (nxt == IPPROTO_ROUTING) {
    685 				/*
    686 				 * if we see destionation option next
    687 				 * time, it must be dest2.
    688 				 */
    689 				dstopt = 2;
    690 			}
    691 
    692 			/* skip this header */
    693 			m_copydata(m, *i, sizeof(ip6e), &ip6e);
    694 			nxt = ip6e.ip6e_nxt;
    695 			*off = *i + offsetof(struct ip6_ext, ip6e_nxt);
    696 			/*
    697 			 * we will never see nxt == IPPROTO_AH
    698 			 * so it is safe to omit AH case.
    699 			 */
    700 			*i += (ip6e.ip6e_len + 1) << 3;
    701 			break;
    702 		default:
    703 			return;
    704 		}
    705 	} while (*i < m->m_pkthdr.len);
    706 }
    707 
    708 static int
    709 in6_sa_equal_addrwithscope(const struct sockaddr_in6 *sa, const struct in6_addr *ia)
    710 {
    711 	struct in6_addr ia2;
    712 
    713 	memcpy(&ia2, &sa->sin6_addr, sizeof(ia2));
    714 	if (IN6_IS_SCOPE_LINKLOCAL(&sa->sin6_addr))
    715 		ia2.s6_addr16[1] = htons(sa->sin6_scope_id);
    716 
    717 	return IN6_ARE_ADDR_EQUAL(ia, &ia2);
    718 }
    719 
    720 int
    721 ipsec6_process_packet(
    722 	struct mbuf *m,
    723  	struct ipsecrequest *isr
    724     )
    725 {
    726 	struct secasvar *sav = NULL;
    727 	struct ip6_hdr *ip6;
    728 	int s, error, i, off;
    729 	union sockaddr_union *dst;
    730 
    731 	KASSERT(m != NULL);
    732 	KASSERT(isr != NULL);
    733 
    734 	s = splsoftnet();   /* insure SA contents don't change */
    735 
    736 	isr = ipsec_nextisr(m, isr, AF_INET6, &error, &sav);
    737 	if (isr == NULL) {
    738 		if (error != 0) {
    739 			/* XXX Should we send a notification ? */
    740 			goto bad;
    741 		} else {
    742 			if (ipsec_register_done(m, &error) < 0)
    743 				goto bad;
    744 
    745 			splx(s);
    746 			return ipsec_reinject_ipstack(m, AF_INET6);
    747 		}
    748 	}
    749 
    750 	KASSERT(sav != NULL);
    751 	dst = &sav->sah->saidx.dst;
    752 
    753 	ip6 = mtod(m, struct ip6_hdr *); /* XXX */
    754 
    755 	/* Do the appropriate encapsulation, if necessary */
    756 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
    757 	    dst->sa.sa_family != AF_INET6 ||        /* PF mismatch */
    758 	    ((dst->sa.sa_family == AF_INET6) &&
    759 	     (!IN6_IS_ADDR_UNSPECIFIED(&dst->sin6.sin6_addr)) &&
    760 	     (!in6_sa_equal_addrwithscope(&dst->sin6,
    761 				  &ip6->ip6_dst)))) {
    762 		struct mbuf *mp;
    763 
    764 		/* Fix IPv6 header payload length. */
    765 		if (m->m_len < sizeof(struct ip6_hdr)) {
    766 			if ((m = m_pullup(m,sizeof(struct ip6_hdr))) == NULL) {
    767 				error = ENOBUFS;
    768 				goto unrefsav;
    769 			}
    770 		}
    771 
    772 		if (m->m_pkthdr.len - sizeof(*ip6) > IPV6_MAXPACKET) {
    773 			/* No jumbogram support. */
    774 			error = ENXIO;   /*XXX*/
    775 			goto unrefsav;
    776 		}
    777 
    778 		ip6 = mtod(m, struct ip6_hdr *);
    779 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
    780 
    781 		/* Encapsulate the packet */
    782 		error = ipip_output(m, isr, sav, &mp, 0, 0);
    783 		if (mp == NULL && !error) {
    784 			/* Should never happen. */
    785 			IPSECLOG(LOG_DEBUG,
    786 			    "ipip_output returns no mbuf and no error!");
    787 			error = EFAULT;
    788 		}
    789 
    790 		if (error) {
    791 			if (mp) {
    792 				/* XXX: Should never happen! */
    793 				m_freem(mp);
    794 			}
    795 			m = NULL; /* ipip_output() already freed it */
    796 			goto unrefsav;
    797 		}
    798 
    799 		m = mp;
    800 		mp = NULL;
    801 	}
    802 
    803 	if (dst->sa.sa_family == AF_INET) {
    804 		struct ip *ip;
    805 		ip = mtod(m, struct ip *);
    806 		i = ip->ip_hl << 2;
    807 		off = offsetof(struct ip, ip_p);
    808 	} else {
    809 		compute_ipsec_pos(m, &i, &off);
    810 	}
    811 	error = (*sav->tdb_xform->xf_output)(m, isr, sav, NULL, i, off);
    812 	KEY_SA_UNREF(&sav);
    813 	splx(s);
    814 	return error;
    815 unrefsav:
    816 	KEY_SA_UNREF(&sav);
    817 bad:
    818 	splx(s);
    819 	if (m)
    820 		m_freem(m);
    821 	return error;
    822 }
    823 #endif /*INET6*/
    824 
    825 void
    826 ipsec_output_init(void)
    827 {
    828 
    829 	ipsec_rtcache_percpu = percpu_alloc(sizeof(struct route));
    830 }
    831