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