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