Home | History | Annotate | Line # | Download | only in netipsec
ipsec.c revision 1.84
      1 /*	$NetBSD: ipsec.c,v 1.84 2017/04/25 05:44:11 ozaki-r Exp $	*/
      2 /*	$FreeBSD: /usr/local/www/cvsroot/FreeBSD/src/sys/netipsec/ipsec.c,v 1.2.2.2 2003/07/01 01:38:13 sam Exp $	*/
      3 /*	$KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $	*/
      4 
      5 /*
      6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      7  * All rights reserved.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *	notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *	notice, this list of conditions and the following disclaimer in the
     16  *	documentation and/or other materials provided with the distribution.
     17  * 3. Neither the name of the project nor the names of its contributors
     18  *	may be used to endorse or promote products derived from this software
     19  *	without specific prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     31  * SUCH DAMAGE.
     32  */
     33 
     34 #include <sys/cdefs.h>
     35 __KERNEL_RCSID(0, "$NetBSD: ipsec.c,v 1.84 2017/04/25 05:44:11 ozaki-r Exp $");
     36 
     37 /*
     38  * IPsec controller part.
     39  */
     40 
     41 #if defined(_KERNEL_OPT)
     42 #include "opt_inet.h"
     43 #include "opt_ipsec.h"
     44 #endif
     45 
     46 #include <sys/param.h>
     47 #include <sys/systm.h>
     48 #include <sys/malloc.h>
     49 #include <sys/mbuf.h>
     50 #include <sys/domain.h>
     51 #include <sys/protosw.h>
     52 #include <sys/socket.h>
     53 #include <sys/socketvar.h>
     54 #include <sys/errno.h>
     55 #include <sys/time.h>
     56 #include <sys/kernel.h>
     57 #include <sys/syslog.h>
     58 #include <sys/sysctl.h>
     59 #include <sys/proc.h>
     60 #include <sys/kauth.h>
     61 
     62 #include <net/if.h>
     63 #include <net/route.h>
     64 
     65 #include <netinet/in.h>
     66 #include <netinet/in_systm.h>
     67 #include <netinet/ip.h>
     68 #include <netinet/ip_var.h>
     69 #include <netinet/in_var.h>
     70 #include <netinet/udp.h>
     71 #include <netinet/udp_var.h>
     72 #include <netinet/tcp.h>
     73 #include <netinet/udp.h>
     74 #include <netinet/ip_icmp.h>
     75 #include <netinet/ip_private.h>
     76 
     77 #include <netinet/ip6.h>
     78 #ifdef INET6
     79 #include <netinet6/ip6_var.h>
     80 #endif
     81 #include <netinet/in_pcb.h>
     82 #ifdef INET6
     83 #include <netinet6/in6_pcb.h>
     84 #include <netinet/icmp6.h>
     85 #endif
     86 
     87 #include <netipsec/ipsec.h>
     88 #include <netipsec/ipsec_var.h>
     89 #include <netipsec/ipsec_private.h>
     90 #ifdef INET6
     91 #include <netipsec/ipsec6.h>
     92 #endif
     93 #include <netipsec/ah_var.h>
     94 #include <netipsec/esp_var.h>
     95 #include <netipsec/ipcomp.h>		/*XXX*/
     96 #include <netipsec/ipcomp_var.h>
     97 
     98 #include <netipsec/key.h>
     99 #include <netipsec/keydb.h>
    100 #include <netipsec/key_debug.h>
    101 
    102 #include <netipsec/xform.h>
    103 
    104 #include <net/net_osdep.h>
    105 
    106 int ipsec_used = 0;
    107 int ipsec_enabled = 1;
    108 
    109 #ifdef IPSEC_DEBUG
    110 int ipsec_debug = 1;
    111 
    112 /*
    113  * When set to 1, IPsec will send packets with the same sequence number.
    114  * This allows to verify if the other side has proper replay attacks detection.
    115  */
    116 int ipsec_replay = 0;
    117 
    118 /*
    119  * When set 1, IPsec will send packets with corrupted HMAC.
    120  * This allows to verify if the other side properly detects modified packets.
    121  */
    122 int ipsec_integrity = 0;
    123 #else
    124 int ipsec_debug = 0;
    125 #endif
    126 
    127 percpu_t *ipsecstat_percpu;
    128 int ip4_ah_offsetmask = 0;	/* maybe IP_DF? */
    129 int ip4_ipsec_dfbit = 2;	/* DF bit on encap. 0: clear 1: set 2: copy */
    130 int ip4_esp_trans_deflev = IPSEC_LEVEL_USE;
    131 int ip4_esp_net_deflev = IPSEC_LEVEL_USE;
    132 int ip4_ah_trans_deflev = IPSEC_LEVEL_USE;
    133 int ip4_ah_net_deflev = IPSEC_LEVEL_USE;
    134 struct secpolicy ip4_def_policy;
    135 int ip4_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
    136 int ip4_esp_randpad = -1;
    137 
    138 u_int ipsec_spdgen = 1;		/* SPD generation # */
    139 
    140 static struct secpolicy *ipsec_checkpcbcache (struct mbuf *,
    141 	struct inpcbpolicy *, int);
    142 static int ipsec_fillpcbcache (struct inpcbpolicy *, struct mbuf *,
    143 	struct secpolicy *, int);
    144 static int ipsec_invalpcbcache (struct inpcbpolicy *, int);
    145 
    146 /*
    147  * Crypto support requirements:
    148  *
    149  *  1	require hardware support
    150  * -1	require software support
    151  *  0	take anything
    152  */
    153 int	crypto_support = 0;
    154 
    155 static struct secpolicy *ipsec_getpolicybysock(struct mbuf *, u_int,
    156     struct inpcb_hdr *, int *);
    157 
    158 #ifdef __FreeBSD__
    159 /* net.inet.ipsec */
    160 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ESP_RANDPAD,
    161 	esp_randpad, CTLFLAG_RW,	&ip4_esp_randpad,	0, "");
    162 SYSCTL_INT(_net_inet_ipsec, OID_AUTO,
    163 	crypto_support,	CTLFLAG_RW,	&crypto_support,0, "");
    164 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_replay, CTLFLAG_RW, &ipsec_replay, 0,
    165 	"Emulate replay attack");
    166 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_integrity, CTLFLAG_RW,
    167 	&ipsec_integrity, 0, "Emulate man-in-the-middle attack");
    168 #endif /* __FreeBSD__ */
    169 
    170 #ifdef INET6
    171 int ip6_esp_trans_deflev = IPSEC_LEVEL_USE;
    172 int ip6_esp_net_deflev = IPSEC_LEVEL_USE;
    173 int ip6_ah_trans_deflev = IPSEC_LEVEL_USE;
    174 int ip6_ah_net_deflev = IPSEC_LEVEL_USE;
    175 struct secpolicy ip6_def_policy;
    176 int ip6_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
    177 int ip6_esp_randpad = -1;
    178 
    179 
    180 #ifdef __FreeBSD__
    181 /* net.inet6.ipsec6 */
    182 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ESP_RANDPAD,
    183 	esp_randpad, CTLFLAG_RW,	&ip6_esp_randpad,	0, "");
    184 #endif /* __FreeBSD__ */
    185 #endif /* INET6 */
    186 
    187 static int ipsec4_setspidx_inpcb (struct mbuf *, struct inpcb *);
    188 #ifdef INET6
    189 static int ipsec6_setspidx_in6pcb (struct mbuf *, struct in6pcb *);
    190 #endif
    191 static int ipsec_setspidx (struct mbuf *, struct secpolicyindex *, int);
    192 static void ipsec4_get_ulp (struct mbuf *m, struct secpolicyindex *, int);
    193 static int ipsec4_setspidx_ipaddr (struct mbuf *, struct secpolicyindex *);
    194 #ifdef INET6
    195 static void ipsec6_get_ulp (struct mbuf *m, struct secpolicyindex *, int);
    196 static int ipsec6_setspidx_ipaddr (struct mbuf *, struct secpolicyindex *);
    197 #endif
    198 static void ipsec_delpcbpolicy (struct inpcbpolicy *);
    199 static struct secpolicy *ipsec_deepcopy_policy (const struct secpolicy *);
    200 static int ipsec_set_policy (struct secpolicy **, int, const void *, size_t,
    201     kauth_cred_t);
    202 static int ipsec_get_policy (struct secpolicy *, struct mbuf **);
    203 static void vshiftl (unsigned char *, int, int);
    204 static size_t ipsec_hdrsiz (const struct secpolicy *);
    205 
    206 /*
    207  * Try to validate and use cached policy on a PCB.
    208  */
    209 static struct secpolicy *
    210 ipsec_checkpcbcache(struct mbuf *m, struct inpcbpolicy *pcbsp, int dir)
    211 {
    212 	struct secpolicyindex spidx;
    213 
    214 	KASSERT(IPSEC_DIR_IS_VALID(dir));
    215 	KASSERT(pcbsp != NULL);
    216 	KASSERT(dir < sizeof(pcbsp->sp_cache)/sizeof(pcbsp->sp_cache[0]));
    217 	KASSERT(inph_locked(pcbsp->sp_inph));
    218 
    219 	/* SPD table change invalidate all the caches. */
    220 	if (ipsec_spdgen != pcbsp->sp_cache[dir].cachegen) {
    221 		ipsec_invalpcbcache(pcbsp, dir);
    222 		return NULL;
    223 	}
    224 	if (!pcbsp->sp_cache[dir].cachesp)
    225 		return NULL;
    226 	if (pcbsp->sp_cache[dir].cachesp->state != IPSEC_SPSTATE_ALIVE) {
    227 		ipsec_invalpcbcache(pcbsp, dir);
    228 		return NULL;
    229 	}
    230 	if ((pcbsp->sp_cacheflags & IPSEC_PCBSP_CONNECTED) == 0) {
    231 		if (!pcbsp->sp_cache[dir].cachesp)
    232 			return NULL;
    233 		if (ipsec_setspidx(m, &spidx, 1) != 0)
    234 			return NULL;
    235 
    236 		/*
    237 		 * We have to make an exact match here since the cached rule
    238 		 * might have lower priority than a rule that would otherwise
    239 		 * have matched the packet.
    240 		 */
    241 
    242 		if (memcmp(&pcbsp->sp_cache[dir].cacheidx, &spidx, sizeof(spidx)))
    243 			return NULL;
    244 
    245 	} else {
    246 		/*
    247 		 * The pcb is connected, and the L4 code is sure that:
    248 		 * - outgoing side uses inp_[lf]addr
    249 		 * - incoming side looks up policy after inpcb lookup
    250 		 * and address pair is know to be stable.  We do not need
    251 		 * to generate spidx again, nor check the address match again.
    252 		 *
    253 		 * For IPv4/v6 SOCK_STREAM sockets, this assumptions holds
    254 		 * and there are calls to ipsec_pcbconn() from in_pcbconnect().
    255 		 */
    256 	}
    257 
    258 	pcbsp->sp_cache[dir].cachesp->lastused = time_second;
    259 	pcbsp->sp_cache[dir].cachesp->refcnt++;
    260 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    261 	    "DP cause refcnt++:%d SP:%p\n",
    262 	    pcbsp->sp_cache[dir].cachesp->refcnt,
    263 	    pcbsp->sp_cache[dir].cachesp);
    264 	return pcbsp->sp_cache[dir].cachesp;
    265 }
    266 
    267 static int
    268 ipsec_fillpcbcache(struct inpcbpolicy *pcbsp, struct mbuf *m,
    269 	struct secpolicy *sp, int dir)
    270 {
    271 
    272 	KASSERT(IPSEC_DIR_IS_INOROUT(dir));
    273 	KASSERT(dir < sizeof(pcbsp->sp_cache)/sizeof(pcbsp->sp_cache[0]));
    274 	KASSERT(inph_locked(pcbsp->sp_inph));
    275 
    276 	if (pcbsp->sp_cache[dir].cachesp)
    277 		KEY_FREESP(&pcbsp->sp_cache[dir].cachesp);
    278 	pcbsp->sp_cache[dir].cachesp = NULL;
    279 	pcbsp->sp_cache[dir].cachehint = IPSEC_PCBHINT_MAYBE;
    280 	if (ipsec_setspidx(m, &pcbsp->sp_cache[dir].cacheidx, 1) != 0) {
    281 		return EINVAL;
    282 	}
    283 	pcbsp->sp_cache[dir].cachesp = sp;
    284 	if (pcbsp->sp_cache[dir].cachesp) {
    285 		pcbsp->sp_cache[dir].cachesp->refcnt++;
    286 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    287 		    "DP cause refcnt++:%d SP:%p\n",
    288 		    pcbsp->sp_cache[dir].cachesp->refcnt,
    289 		    pcbsp->sp_cache[dir].cachesp);
    290 
    291 		/*
    292 		 * If the PCB is connected, we can remember a hint to
    293 		 * possibly short-circuit IPsec processing in other places.
    294 		 */
    295 		if (pcbsp->sp_cacheflags & IPSEC_PCBSP_CONNECTED) {
    296 			switch (pcbsp->sp_cache[dir].cachesp->policy) {
    297 			case IPSEC_POLICY_NONE:
    298 			case IPSEC_POLICY_BYPASS:
    299 				pcbsp->sp_cache[dir].cachehint =
    300 					IPSEC_PCBHINT_NO;
    301 				break;
    302 			default:
    303 				pcbsp->sp_cache[dir].cachehint =
    304 					IPSEC_PCBHINT_YES;
    305 			}
    306 		}
    307 	}
    308 	pcbsp->sp_cache[dir].cachegen = ipsec_spdgen;
    309 
    310 	return 0;
    311 }
    312 
    313 static int
    314 ipsec_invalpcbcache(struct inpcbpolicy *pcbsp, int dir)
    315 {
    316 	int i;
    317 
    318 	KASSERT(inph_locked(pcbsp->sp_inph));
    319 
    320 	for (i = IPSEC_DIR_INBOUND; i <= IPSEC_DIR_OUTBOUND; i++) {
    321 		if (dir != IPSEC_DIR_ANY && i != dir)
    322 			continue;
    323 		if (pcbsp->sp_cache[i].cachesp)
    324 			KEY_FREESP(&pcbsp->sp_cache[i].cachesp);
    325 		pcbsp->sp_cache[i].cachesp = NULL;
    326 		pcbsp->sp_cache[i].cachehint = IPSEC_PCBHINT_MAYBE;
    327 		pcbsp->sp_cache[i].cachegen = 0;
    328 		memset(&pcbsp->sp_cache[i].cacheidx, 0,
    329 			  sizeof(pcbsp->sp_cache[i].cacheidx));
    330 	}
    331 	return 0;
    332 }
    333 
    334 void
    335 ipsec_pcbconn(struct inpcbpolicy *pcbsp)
    336 {
    337 
    338 	KASSERT(inph_locked(pcbsp->sp_inph));
    339 
    340 	pcbsp->sp_cacheflags |= IPSEC_PCBSP_CONNECTED;
    341 	ipsec_invalpcbcache(pcbsp, IPSEC_DIR_ANY);
    342 }
    343 
    344 void
    345 ipsec_pcbdisconn(struct inpcbpolicy *pcbsp)
    346 {
    347 
    348 	KASSERT(inph_locked(pcbsp->sp_inph));
    349 
    350 	pcbsp->sp_cacheflags &= ~IPSEC_PCBSP_CONNECTED;
    351 	ipsec_invalpcbcache(pcbsp, IPSEC_DIR_ANY);
    352 }
    353 
    354 void
    355 ipsec_invalpcbcacheall(void)
    356 {
    357 
    358 	if (ipsec_spdgen == UINT_MAX)
    359 		ipsec_spdgen = 1;
    360 	else
    361 		ipsec_spdgen++;
    362 }
    363 
    364 /*
    365  * Return a held reference to the default SP.
    366  */
    367 static struct secpolicy *
    368 key_allocsp_default(int af, const char *where, int tag)
    369 {
    370 	struct secpolicy *sp;
    371 
    372 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
    373 
    374 	switch(af) {
    375 	case AF_INET:
    376 		sp = &ip4_def_policy;
    377 		break;
    378 #ifdef INET6
    379 	case AF_INET6:
    380 		sp = &ip6_def_policy;
    381 		break;
    382 #endif
    383 	default:
    384 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    385 		    "unexpected protocol family %u\n", af);
    386 		return NULL;
    387 	}
    388 
    389 	if (sp->policy != IPSEC_POLICY_DISCARD &&
    390 		sp->policy != IPSEC_POLICY_NONE) {
    391 		ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n",
    392 		    sp->policy, IPSEC_POLICY_NONE));
    393 		sp->policy = IPSEC_POLICY_NONE;
    394 	}
    395 	sp->refcnt++;
    396 
    397 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP returns SP:%p (%u)\n",
    398 	    sp, sp->refcnt);
    399 	return sp;
    400 }
    401 #define	KEY_ALLOCSP_DEFAULT(af) \
    402 	key_allocsp_default((af),__FILE__, __LINE__)
    403 
    404 /*
    405  * For OUTBOUND packet having a socket. Searching SPD for packet,
    406  * and return a pointer to SP.
    407  * OUT:	NULL:	no apropreate SP found, the following value is set to error.
    408  *		0	: bypass
    409  *		EACCES	: discard packet.
    410  *		ENOENT	: ipsec_acquire() in progress, maybe.
    411  *		others	: error occurred.
    412  *	others:	a pointer to SP
    413  *
    414  * NOTE: IPv6 mapped address concern is implemented here.
    415  */
    416 struct secpolicy *
    417 ipsec_getpolicy(const struct tdb_ident *tdbi, u_int dir)
    418 {
    419 	struct secpolicy *sp;
    420 
    421 	KASSERT(tdbi != NULL);
    422 	KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
    423 
    424 	sp = KEY_ALLOCSP2(tdbi->spi, &tdbi->dst, tdbi->proto, dir);
    425 	if (sp == NULL)			/*XXX????*/
    426 		sp = KEY_ALLOCSP_DEFAULT(tdbi->dst.sa.sa_family);
    427 	KASSERT(sp != NULL);
    428 	return sp;
    429 }
    430 
    431 /*
    432  * For OUTBOUND packet having a socket. Searching SPD for packet,
    433  * and return a pointer to SP.
    434  * OUT:	NULL:	no apropreate SP found, the following value is set to error.
    435  *		0	: bypass
    436  *		EACCES	: discard packet.
    437  *		ENOENT	: ipsec_acquire() in progress, maybe.
    438  *		others	: error occurred.
    439  *	others:	a pointer to SP
    440  *
    441  * NOTE: IPv6 mapped address concern is implemented here.
    442  */
    443 static struct secpolicy *
    444 ipsec_getpolicybysock(struct mbuf *m, u_int dir, struct inpcb_hdr *inph,
    445     int *error)
    446 {
    447 	struct inpcbpolicy *pcbsp = NULL;
    448 	struct secpolicy *currsp = NULL;	/* policy on socket */
    449 	struct secpolicy *sp;
    450 	int af;
    451 
    452 	KASSERT(m != NULL);
    453 	KASSERT(inph != NULL);
    454 	KASSERT(error != NULL);
    455 	KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
    456 
    457 	KASSERT(inph->inph_socket != NULL);
    458 	KASSERT(inph_locked(inph));
    459 
    460 	/* XXX FIXME inpcb/in6pcb  vs socket*/
    461 	af = inph->inph_af;
    462 	KASSERTMSG(af == AF_INET || af == AF_INET6,
    463 	    "unexpected protocol family %u", af);
    464 
    465 	KASSERT(inph->inph_sp != NULL);
    466 	/* If we have a cached entry, and if it is still valid, use it. */
    467 	IPSEC_STATINC(IPSEC_STAT_SPDCACHELOOKUP);
    468 	currsp = ipsec_checkpcbcache(m, inph->inph_sp, dir);
    469 	if (currsp) {
    470 		*error = 0;
    471 		return currsp;
    472 	}
    473 	IPSEC_STATINC(IPSEC_STAT_SPDCACHEMISS);
    474 
    475 	switch (af) {
    476 	case AF_INET: {
    477 		struct inpcb *in4p = (struct inpcb *)inph;
    478 		/* set spidx in pcb */
    479 		*error = ipsec4_setspidx_inpcb(m, in4p);
    480 		pcbsp = in4p->inp_sp;
    481 		break;
    482 		}
    483 
    484 #if defined(INET6)
    485 	case AF_INET6: {
    486 		struct in6pcb *in6p = (struct in6pcb *)inph;
    487 		/* set spidx in pcb */
    488 		*error = ipsec6_setspidx_in6pcb(m, in6p);
    489 		pcbsp = in6p->in6p_sp;
    490 		break;
    491 		}
    492 #endif
    493 	default:
    494 		*error = EPFNOSUPPORT;
    495 		break;
    496 	}
    497 	if (*error)
    498 		return NULL;
    499 
    500 	KASSERT(pcbsp != NULL);
    501 	switch (dir) {
    502 	case IPSEC_DIR_INBOUND:
    503 		currsp = pcbsp->sp_in;
    504 		break;
    505 	case IPSEC_DIR_OUTBOUND:
    506 		currsp = pcbsp->sp_out;
    507 		break;
    508 	}
    509 	KASSERT(currsp != NULL);
    510 
    511 	if (pcbsp->priv) {			/* when privilieged socket */
    512 		switch (currsp->policy) {
    513 		case IPSEC_POLICY_BYPASS:
    514 		case IPSEC_POLICY_IPSEC:
    515 			currsp->refcnt++;
    516 			sp = currsp;
    517 			break;
    518 
    519 		case IPSEC_POLICY_ENTRUST:
    520 			/* look for a policy in SPD */
    521 			sp = KEY_ALLOCSP(&currsp->spidx, dir);
    522 			if (sp == NULL)		/* no SP found */
    523 				sp = KEY_ALLOCSP_DEFAULT(af);
    524 			break;
    525 
    526 		default:
    527 			ipseclog((LOG_ERR, "%s: Invalid policy for PCB %d\n",
    528 			    __func__, currsp->policy));
    529 			*error = EINVAL;
    530 			return NULL;
    531 		}
    532 	} else {				/* unpriv, SPD has policy */
    533 		sp = KEY_ALLOCSP(&currsp->spidx, dir);
    534 		if (sp == NULL) {		/* no SP found */
    535 			switch (currsp->policy) {
    536 			case IPSEC_POLICY_BYPASS:
    537 				ipseclog((LOG_ERR, "%s: Illegal policy for "
    538 				    "non-priviliged defined %d\n", __func__,
    539 				    currsp->policy));
    540 				*error = EINVAL;
    541 				return NULL;
    542 
    543 			case IPSEC_POLICY_ENTRUST:
    544 				sp = KEY_ALLOCSP_DEFAULT(af);
    545 				break;
    546 
    547 			case IPSEC_POLICY_IPSEC:
    548 				currsp->refcnt++;
    549 				sp = currsp;
    550 				break;
    551 
    552 			default:
    553 				ipseclog((LOG_ERR, "%s: Invalid policy for "
    554 				    "PCB %d\n", __func__, currsp->policy));
    555 				*error = EINVAL;
    556 				return NULL;
    557 			}
    558 		}
    559 	}
    560 	KASSERTMSG(sp != NULL, "null SP (priv %u policy %u", pcbsp->priv,
    561 	    currsp->policy);
    562 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    563 	    "DP (priv %u policy %u) allocates SP:%p (refcnt %u)\n",
    564 	    pcbsp->priv, currsp->policy, sp, sp->refcnt);
    565 	ipsec_fillpcbcache(pcbsp, m, sp, dir);
    566 	return sp;
    567 }
    568 
    569 /*
    570  * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
    571  * and return a pointer to SP.
    572  * OUT:	positive: a pointer to the entry for security policy leaf matched.
    573  *	NULL:	no apropreate SP found, the following value is set to error.
    574  *		0	: bypass
    575  *		EACCES	: discard packet.
    576  *		ENOENT	: ipsec_acquire() in progress, maybe.
    577  *		others	: error occurred.
    578  */
    579 struct secpolicy *
    580 ipsec_getpolicybyaddr(struct mbuf *m, u_int dir, int flag, int *error)
    581 {
    582 	struct secpolicyindex spidx;
    583 	struct secpolicy *sp;
    584 
    585 	KASSERT(m != NULL);
    586 	KASSERT(error != NULL);
    587 	KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
    588 
    589 	sp = NULL;
    590 
    591 	/* Make an index to look for a policy. */
    592 	*error = ipsec_setspidx(m, &spidx, (flag & IP_FORWARDING) ? 0 : 1);
    593 	if (*error != 0) {
    594 		DPRINTF(("%s: setpidx failed, dir %u flag %u\n", __func__,
    595 		    dir, flag));
    596 		memset(&spidx, 0, sizeof (spidx));
    597 		return NULL;
    598 	}
    599 
    600 	spidx.dir = dir;
    601 
    602 	if (key_havesp(dir)) {
    603 		sp = KEY_ALLOCSP(&spidx, dir);
    604 	}
    605 
    606 	if (sp == NULL)			/* no SP found, use system default */
    607 		sp = KEY_ALLOCSP_DEFAULT(spidx.dst.sa.sa_family);
    608 	KASSERT(sp != NULL);
    609 	return sp;
    610 }
    611 
    612 struct secpolicy *
    613 ipsec4_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
    614 		   struct inpcb *inp)
    615 {
    616 	struct secpolicy *sp;
    617 
    618 	*error = 0;
    619 
    620 	if (inp == NULL) {
    621 		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
    622 	} else {
    623 		KASSERT(inp->inp_socket != NULL);
    624 		sp = ipsec_getpolicybysock(m, dir, (struct inpcb_hdr *)inp, error);
    625 	}
    626 	if (sp == NULL) {
    627 		KASSERTMSG(*error != 0, "getpolicy failed w/o error");
    628 		IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
    629 		return NULL;
    630 	}
    631 	KASSERTMSG(*error == 0, "sp w/ error set to %u", *error);
    632 	switch (sp->policy) {
    633 	case IPSEC_POLICY_ENTRUST:
    634 	default:
    635 		printf("%s: invalid policy %u\n", __func__, sp->policy);
    636 		/* fall thru... */
    637 	case IPSEC_POLICY_DISCARD:
    638 		IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
    639 		*error = -EINVAL;	/* packet is discarded by caller */
    640 		break;
    641 	case IPSEC_POLICY_BYPASS:
    642 	case IPSEC_POLICY_NONE:
    643 		KEY_FREESP(&sp);
    644 		sp = NULL;		/* NB: force NULL result */
    645 		break;
    646 	case IPSEC_POLICY_IPSEC:
    647 		if (sp->req == NULL)	/* acquire an SA */
    648 			*error = key_spdacquire(sp);
    649 		break;
    650 	}
    651 	if (*error != 0) {
    652 		KEY_FREESP(&sp);
    653 		sp = NULL;
    654 		DPRINTF(("%s: done, error %d\n", __func__, *error));
    655 	}
    656 	return sp;
    657 }
    658 
    659 int
    660 ipsec4_output(struct mbuf *m, struct inpcb *inp, int flags,
    661     struct secpolicy **sp_out, u_long *mtu, bool *natt_frag, bool *done)
    662 {
    663 	const struct ip *ip = mtod(m, const struct ip *);
    664 	struct secpolicy *sp = NULL;
    665 	int error, s;
    666 
    667 	/*
    668 	 * Check the security policy (SP) for the packet and, if required,
    669 	 * do IPsec-related processing.  There are two cases here; the first
    670 	 * time a packet is sent through it will be untagged and handled by
    671 	 * ipsec4_checkpolicy().  If the packet is resubmitted to ip_output
    672 	 * (e.g. after AH, ESP, etc. processing), there will be a tag to
    673 	 * bypass the lookup and related policy checking.
    674 	 */
    675 	if (ipsec_outdone(m)) {
    676 		return 0;
    677 	}
    678 	s = splsoftnet();
    679 	if (inp && IPSEC_PCB_SKIP_IPSEC(inp->inp_sp, IPSEC_DIR_OUTBOUND)) {
    680 		splx(s);
    681 		return 0;
    682 	}
    683 	sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, inp);
    684 
    685 	/*
    686 	 * There are four return cases:
    687 	 *	sp != NULL			apply IPsec policy
    688 	 *	sp == NULL, error == 0		no IPsec handling needed
    689 	 *	sp == NULL, error == -EINVAL	discard packet w/o error
    690 	 *	sp == NULL, error != 0		discard packet, report error
    691 	 */
    692 	if (sp == NULL) {
    693 		splx(s);
    694 		if (error) {
    695 			/*
    696 			 * Hack: -EINVAL is used to signal that a packet
    697 			 * should be silently discarded.  This is typically
    698 			 * because we asked key management for an SA and
    699 			 * it was delayed (e.g. kicked up to IKE).
    700 			 */
    701 			if (error == -EINVAL)
    702 				error = 0;
    703 			m_freem(m);
    704 			*done = true;
    705 			return error;
    706 		}
    707 		/* No IPsec processing for this packet. */
    708 		return 0;
    709 	}
    710 	*sp_out = sp;
    711 
    712 	/*
    713 	 * NAT-T ESP fragmentation: do not do IPSec processing now,
    714 	 * we will do it on each fragmented packet.
    715 	 */
    716 	if (sp->req->sav && (sp->req->sav->natt_type &
    717 	    (UDP_ENCAP_ESPINUDP|UDP_ENCAP_ESPINUDP_NON_IKE))) {
    718 		if (ntohs(ip->ip_len) > sp->req->sav->esp_frag) {
    719 			*mtu = sp->req->sav->esp_frag;
    720 			*natt_frag = true;
    721 			splx(s);
    722 			return 0;
    723 		}
    724 	}
    725 
    726 	/*
    727 	 * Do delayed checksums now because we send before
    728 	 * this is done in the normal processing path.
    729 	 */
    730 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    731 		in_delayed_cksum(m);
    732 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    733 	}
    734 
    735 	/* Note: callee frees mbuf */
    736 	error = ipsec4_process_packet(m, sp->req, flags, 0);
    737 	/*
    738 	 * Preserve KAME behaviour: ENOENT can be returned
    739 	 * when an SA acquire is in progress.  Don't propagate
    740 	 * this to user-level; it confuses applications.
    741 	 *
    742 	 * XXX this will go away when the SADB is redone.
    743 	 */
    744 	if (error == ENOENT)
    745 		error = 0;
    746 	splx(s);
    747 	*done = true;
    748 	return error;
    749 }
    750 
    751 int
    752 ipsec4_input(struct mbuf *m, int flags)
    753 {
    754 	struct m_tag *mtag;
    755 	struct tdb_ident *tdbi;
    756 	struct secpolicy *sp;
    757 	int error, s;
    758 
    759 	/*
    760 	 * Check if the packet has already had IPsec processing done.
    761 	 * If so, then just pass it along.  This tag gets set during AH,
    762 	 * ESP, etc. input handling, before the packet is returned to
    763 	 * the IP input queue for delivery.
    764 	 */
    765 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
    766 	s = splsoftnet();
    767 	if (mtag != NULL) {
    768 		tdbi = (struct tdb_ident *)(mtag + 1);
    769 		sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
    770 	} else {
    771 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
    772 		    IP_FORWARDING, &error);
    773 	}
    774 	if (sp == NULL) {
    775 		splx(s);
    776 		return EINVAL;
    777 	}
    778 
    779 	/*
    780 	 * Check security policy against packet attributes.
    781 	 */
    782 	error = ipsec_in_reject(sp, m);
    783 	KEY_FREESP(&sp);
    784 	splx(s);
    785 	if (error) {
    786 		return error;
    787 	}
    788 
    789 	if (flags == 0) {
    790 		/* We are done. */
    791 		return 0;
    792 	}
    793 
    794 	/*
    795 	 * Peek at the outbound SP for this packet to determine if
    796 	 * it is a Fast Forward candidate.
    797 	 */
    798 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
    799 	if (mtag != NULL) {
    800 		m->m_flags &= ~M_CANFASTFWD;
    801 		return 0;
    802 	}
    803 
    804 	s = splsoftnet();
    805 	sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, NULL);
    806 	if (sp != NULL) {
    807 		m->m_flags &= ~M_CANFASTFWD;
    808 		KEY_FREESP(&sp);
    809 	}
    810 	splx(s);
    811 	return 0;
    812 }
    813 
    814 int
    815 ipsec4_forward(struct mbuf *m, int *destmtu)
    816 {
    817 	/*
    818 	 * If the packet is routed over IPsec tunnel, tell the
    819 	 * originator the tunnel MTU.
    820 	 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
    821 	 * XXX quickhack!!!
    822 	 */
    823 	struct secpolicy *sp;
    824 	size_t ipsechdr;
    825 	int error;
    826 
    827 	sp = ipsec4_getpolicybyaddr(m,
    828 	    IPSEC_DIR_OUTBOUND, IP_FORWARDING, &error);
    829 	if (sp == NULL) {
    830 		return EINVAL;
    831 	}
    832 
    833 	/* Count IPsec header size. */
    834 	ipsechdr = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, NULL);
    835 
    836 	/*
    837 	 * Find the correct route for outer IPv4 header, compute tunnel MTU.
    838 	 */
    839 	if (sp->req && sp->req->sav && sp->req->sav->sah) {
    840 		struct route *ro;
    841 		struct rtentry *rt;
    842 
    843 		ro = &sp->req->sav->sah->sa_route;
    844 		rt = rtcache_validate(ro);
    845 		if (rt && rt->rt_ifp) {
    846 			*destmtu = rt->rt_rmx.rmx_mtu ?
    847 			    rt->rt_rmx.rmx_mtu : rt->rt_ifp->if_mtu;
    848 			*destmtu -= ipsechdr;
    849 		}
    850 		rtcache_unref(rt, ro);
    851 	}
    852 	KEY_FREESP(&sp);
    853 	return 0;
    854 }
    855 
    856 #ifdef INET6
    857 struct secpolicy *
    858 ipsec6_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
    859 	 	   struct in6pcb *in6p)
    860 {
    861 	struct secpolicy *sp;
    862 
    863 	*error = 0;
    864 
    865 	if (in6p == NULL) {
    866 		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
    867 	} else {
    868 		KASSERT(in6p->in6p_socket != NULL);
    869 		sp = ipsec_getpolicybysock(m, dir, (struct inpcb_hdr *)in6p, error);
    870 	}
    871 	if (sp == NULL) {
    872 		KASSERTMSG(*error != 0, "getpolicy failed w/o error");
    873 		IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
    874 		return NULL;
    875 	}
    876 	KASSERTMSG(*error == 0, "sp w/ error set to %u", *error);
    877 	switch (sp->policy) {
    878 	case IPSEC_POLICY_ENTRUST:
    879 	default:
    880 		printf("%s: invalid policy %u\n", __func__, sp->policy);
    881 		/* fall thru... */
    882 	case IPSEC_POLICY_DISCARD:
    883 		IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
    884 		*error = -EINVAL;   /* packet is discarded by caller */
    885 		break;
    886 	case IPSEC_POLICY_BYPASS:
    887 	case IPSEC_POLICY_NONE:
    888 		KEY_FREESP(&sp);
    889 		sp = NULL;	  /* NB: force NULL result */
    890 		break;
    891 	case IPSEC_POLICY_IPSEC:
    892 		if (sp->req == NULL)	/* acquire an SA */
    893 			*error = key_spdacquire(sp);
    894 		break;
    895 	}
    896 	if (*error != 0) {
    897 		KEY_FREESP(&sp);
    898 		sp = NULL;
    899 		DPRINTF(("%s: done, error %d\n", __func__, *error));
    900 	}
    901 	return sp;
    902 }
    903 #endif /* INET6 */
    904 
    905 static int
    906 ipsec4_setspidx_inpcb(struct mbuf *m, struct inpcb *pcb)
    907 {
    908 	int error;
    909 
    910 	KASSERT(pcb != NULL);
    911 	KASSERT(pcb->inp_sp != NULL);
    912 	KASSERT(pcb->inp_sp->sp_out != NULL);
    913 	KASSERT(pcb->inp_sp->sp_in != NULL);
    914 
    915 	error = ipsec_setspidx(m, &pcb->inp_sp->sp_in->spidx, 1);
    916 	if (error == 0) {
    917 		pcb->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
    918 		pcb->inp_sp->sp_out->spidx = pcb->inp_sp->sp_in->spidx;
    919 		pcb->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
    920 	} else {
    921 		memset(&pcb->inp_sp->sp_in->spidx, 0,
    922 			sizeof (pcb->inp_sp->sp_in->spidx));
    923 		memset(&pcb->inp_sp->sp_out->spidx, 0,
    924 			sizeof (pcb->inp_sp->sp_in->spidx));
    925 	}
    926 	return error;
    927 }
    928 
    929 #ifdef INET6
    930 static int
    931 ipsec6_setspidx_in6pcb(struct mbuf *m, struct in6pcb *pcb)
    932 {
    933 	struct secpolicyindex *spidx;
    934 	int error;
    935 
    936 	KASSERT(pcb != NULL);
    937 	KASSERT(pcb->in6p_sp != NULL);
    938 	KASSERT(pcb->in6p_sp->sp_out != NULL);
    939 	KASSERT(pcb->in6p_sp->sp_in != NULL);
    940 
    941 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
    942 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
    943 
    944 	spidx = &pcb->in6p_sp->sp_in->spidx;
    945 	error = ipsec_setspidx(m, spidx, 1);
    946 	if (error)
    947 		goto bad;
    948 	spidx->dir = IPSEC_DIR_INBOUND;
    949 
    950 	spidx = &pcb->in6p_sp->sp_out->spidx;
    951 	error = ipsec_setspidx(m, spidx, 1);
    952 	if (error)
    953 		goto bad;
    954 	spidx->dir = IPSEC_DIR_OUTBOUND;
    955 
    956 	return 0;
    957 
    958 bad:
    959 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
    960 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
    961 	return error;
    962 }
    963 #endif
    964 
    965 /*
    966  * configure security policy index (src/dst/proto/sport/dport)
    967  * by looking at the content of mbuf.
    968  * the caller is responsible for error recovery (like clearing up spidx).
    969  */
    970 static int
    971 ipsec_setspidx(struct mbuf *m, struct secpolicyindex *spidx, int needport)
    972 {
    973 	struct ip *ip = NULL;
    974 	struct ip ipbuf;
    975 	u_int v;
    976 	struct mbuf *n;
    977 	int len;
    978 	int error;
    979 
    980 	KASSERT(m != NULL);
    981 
    982 	/*
    983 	 * validate m->m_pkthdr.len.  we see incorrect length if we
    984 	 * mistakenly call this function with inconsistent mbuf chain
    985 	 * (like 4.4BSD tcp/udp processing).  XXX should we panic here?
    986 	 */
    987 	len = 0;
    988 	for (n = m; n; n = n->m_next)
    989 		len += n->m_len;
    990 	if (m->m_pkthdr.len != len) {
    991 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
    992 		    "total of m_len(%d) != pkthdr.len(%d), ignored.\n",
    993 		    len, m->m_pkthdr.len);
    994 		return EINVAL;
    995 	}
    996 
    997 	if (m->m_pkthdr.len < sizeof(struct ip)) {
    998 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
    999 		    "pkthdr.len(%d) < sizeof(struct ip), ignored.\n",
   1000 		    m->m_pkthdr.len);
   1001 		return EINVAL;
   1002 	}
   1003 
   1004 	if (m->m_len >= sizeof(*ip))
   1005 		ip = mtod(m, struct ip *);
   1006 	else {
   1007 		m_copydata(m, 0, sizeof(ipbuf), &ipbuf);
   1008 		ip = &ipbuf;
   1009 	}
   1010 	v = ip->ip_v;
   1011 	switch (v) {
   1012 	case 4:
   1013 		error = ipsec4_setspidx_ipaddr(m, spidx);
   1014 		if (error)
   1015 			return error;
   1016 		ipsec4_get_ulp(m, spidx, needport);
   1017 		return 0;
   1018 #ifdef INET6
   1019 	case 6:
   1020 		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
   1021 			KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1022 			    "pkthdr.len(%d) < sizeof(struct ip6_hdr), "
   1023 			    "ignored.\n", m->m_pkthdr.len);
   1024 			return EINVAL;
   1025 		}
   1026 		error = ipsec6_setspidx_ipaddr(m, spidx);
   1027 		if (error)
   1028 			return error;
   1029 		ipsec6_get_ulp(m, spidx, needport);
   1030 		return 0;
   1031 #endif
   1032 	default:
   1033 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1034 		    "unknown IP version %u, ignored.\n", v);
   1035 		return EINVAL;
   1036 	}
   1037 }
   1038 
   1039 static void
   1040 ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
   1041 {
   1042 	u_int8_t nxt;
   1043 	int off;
   1044 
   1045 	/* sanity check */
   1046 	KASSERT(m != NULL);
   1047 	KASSERTMSG(m->m_pkthdr.len >= sizeof(struct ip), "packet too short");
   1048 
   1049 	/* NB: ip_input() flips it into host endian XXX need more checking */
   1050 	if (m->m_len >= sizeof(struct ip)) {
   1051 		struct ip *ip = mtod(m, struct ip *);
   1052 		if (ip->ip_off & htons(IP_MF | IP_OFFMASK))
   1053 			goto done;
   1054 		off = ip->ip_hl << 2;
   1055 		nxt = ip->ip_p;
   1056 	} else {
   1057 		struct ip ih;
   1058 
   1059 		m_copydata(m, 0, sizeof (struct ip), &ih);
   1060 		if (ih.ip_off & htons(IP_MF | IP_OFFMASK))
   1061 			goto done;
   1062 		off = ih.ip_hl << 2;
   1063 		nxt = ih.ip_p;
   1064 	}
   1065 
   1066 	while (off < m->m_pkthdr.len) {
   1067 		struct ip6_ext ip6e;
   1068 		struct tcphdr th;
   1069 		struct udphdr uh;
   1070 		struct icmp icmph;
   1071 
   1072 		switch (nxt) {
   1073 		case IPPROTO_TCP:
   1074 			spidx->ul_proto = nxt;
   1075 			if (!needport)
   1076 				goto done_proto;
   1077 			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
   1078 				goto done;
   1079 			m_copydata(m, off, sizeof (th), &th);
   1080 			spidx->src.sin.sin_port = th.th_sport;
   1081 			spidx->dst.sin.sin_port = th.th_dport;
   1082 			return;
   1083 		case IPPROTO_UDP:
   1084 			spidx->ul_proto = nxt;
   1085 			if (!needport)
   1086 				goto done_proto;
   1087 			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
   1088 				goto done;
   1089 			m_copydata(m, off, sizeof (uh), &uh);
   1090 			spidx->src.sin.sin_port = uh.uh_sport;
   1091 			spidx->dst.sin.sin_port = uh.uh_dport;
   1092 			return;
   1093 		case IPPROTO_AH:
   1094 			if (m->m_pkthdr.len > off + sizeof(ip6e))
   1095 				goto done;
   1096 			/* XXX sigh, this works but is totally bogus */
   1097 			m_copydata(m, off, sizeof(ip6e), &ip6e);
   1098 			off += (ip6e.ip6e_len + 2) << 2;
   1099 			nxt = ip6e.ip6e_nxt;
   1100 			break;
   1101 		case IPPROTO_ICMP:
   1102 			spidx->ul_proto = nxt;
   1103 			if (off + sizeof(struct icmp) > m->m_pkthdr.len)
   1104 				return;
   1105 			m_copydata(m, off, sizeof(icmph), &icmph);
   1106 			((struct sockaddr_in *)&spidx->src)->sin_port =
   1107 			    htons((uint16_t)icmph.icmp_type);
   1108 			((struct sockaddr_in *)&spidx->dst)->sin_port =
   1109 			    htons((uint16_t)icmph.icmp_code);
   1110 			return;
   1111 		default:
   1112 			/* XXX intermediate headers??? */
   1113 			spidx->ul_proto = nxt;
   1114 			goto done_proto;
   1115 		}
   1116 	}
   1117 done:
   1118 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
   1119 done_proto:
   1120 	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
   1121 	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
   1122 }
   1123 
   1124 /* assumes that m is sane */
   1125 static int
   1126 ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
   1127 {
   1128 	static const struct sockaddr_in template = {
   1129 		sizeof (struct sockaddr_in),
   1130 		AF_INET,
   1131 		0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
   1132 	};
   1133 
   1134 	spidx->src.sin = template;
   1135 	spidx->dst.sin = template;
   1136 
   1137 	if (m->m_len < sizeof (struct ip)) {
   1138 		m_copydata(m, offsetof(struct ip, ip_src),
   1139 			   sizeof (struct  in_addr),
   1140 			   &spidx->src.sin.sin_addr);
   1141 		m_copydata(m, offsetof(struct ip, ip_dst),
   1142 			   sizeof (struct  in_addr),
   1143 			   &spidx->dst.sin.sin_addr);
   1144 	} else {
   1145 		struct ip *ip = mtod(m, struct ip *);
   1146 		spidx->src.sin.sin_addr = ip->ip_src;
   1147 		spidx->dst.sin.sin_addr = ip->ip_dst;
   1148 	}
   1149 
   1150 	spidx->prefs = sizeof(struct in_addr) << 3;
   1151 	spidx->prefd = sizeof(struct in_addr) << 3;
   1152 
   1153 	return 0;
   1154 }
   1155 
   1156 #ifdef INET6
   1157 static void
   1158 ipsec6_get_ulp(struct mbuf *m, struct secpolicyindex *spidx,
   1159 	       int needport)
   1160 {
   1161 	int off, nxt;
   1162 	struct tcphdr th;
   1163 	struct udphdr uh;
   1164 	struct icmp6_hdr icmph;
   1165 
   1166 	KASSERT(m != NULL);
   1167 
   1168 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1169 		printf("%s:\n", __func__);
   1170 		kdebug_mbuf(m);
   1171 	}
   1172 
   1173 	/* set default */
   1174 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
   1175 	((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
   1176 	((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
   1177 
   1178 	nxt = -1;
   1179 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
   1180 	if (off < 0 || m->m_pkthdr.len < off)
   1181 		return;
   1182 
   1183 	switch (nxt) {
   1184 	case IPPROTO_TCP:
   1185 		spidx->ul_proto = nxt;
   1186 		if (!needport)
   1187 			break;
   1188 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
   1189 			break;
   1190 		m_copydata(m, off, sizeof(th), &th);
   1191 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
   1192 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
   1193 		break;
   1194 	case IPPROTO_UDP:
   1195 		spidx->ul_proto = nxt;
   1196 		if (!needport)
   1197 			break;
   1198 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
   1199 			break;
   1200 		m_copydata(m, off, sizeof(uh), &uh);
   1201 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
   1202 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
   1203 		break;
   1204 	case IPPROTO_ICMPV6:
   1205 		spidx->ul_proto = nxt;
   1206 		if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
   1207 			break;
   1208 		m_copydata(m, off, sizeof(icmph), &icmph);
   1209 		((struct sockaddr_in6 *)&spidx->src)->sin6_port =
   1210 		    htons((uint16_t)icmph.icmp6_type);
   1211 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port =
   1212 		    htons((uint16_t)icmph.icmp6_code);
   1213 		break;
   1214 	default:
   1215 		/* XXX intermediate headers??? */
   1216 		spidx->ul_proto = nxt;
   1217 		break;
   1218 	}
   1219 }
   1220 
   1221 /* assumes that m is sane */
   1222 static int
   1223 ipsec6_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
   1224 {
   1225 	struct ip6_hdr *ip6 = NULL;
   1226 	struct ip6_hdr ip6buf;
   1227 	struct sockaddr_in6 *sin6;
   1228 
   1229 	if (m->m_len >= sizeof(*ip6))
   1230 		ip6 = mtod(m, struct ip6_hdr *);
   1231 	else {
   1232 		m_copydata(m, 0, sizeof(ip6buf), &ip6buf);
   1233 		ip6 = &ip6buf;
   1234 	}
   1235 
   1236 	sin6 = (struct sockaddr_in6 *)&spidx->src;
   1237 	memset(sin6, 0, sizeof(*sin6));
   1238 	sin6->sin6_family = AF_INET6;
   1239 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   1240 	memcpy(&sin6->sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src));
   1241 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
   1242 		sin6->sin6_addr.s6_addr16[1] = 0;
   1243 		sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
   1244 	}
   1245 	spidx->prefs = sizeof(struct in6_addr) << 3;
   1246 
   1247 	sin6 = (struct sockaddr_in6 *)&spidx->dst;
   1248 	memset(sin6, 0, sizeof(*sin6));
   1249 	sin6->sin6_family = AF_INET6;
   1250 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   1251 	memcpy(&sin6->sin6_addr, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
   1252 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
   1253 		sin6->sin6_addr.s6_addr16[1] = 0;
   1254 		sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
   1255 	}
   1256 	spidx->prefd = sizeof(struct in6_addr) << 3;
   1257 
   1258 	return 0;
   1259 }
   1260 #endif
   1261 
   1262 static void
   1263 ipsec_delpcbpolicy(struct inpcbpolicy *p)
   1264 {
   1265 	free(p, M_SECA);
   1266 }
   1267 
   1268 /* initialize policy in PCB */
   1269 int
   1270 ipsec_init_policy(struct socket *so, struct inpcbpolicy **policy)
   1271 {
   1272 	struct inpcbpolicy *new;
   1273 
   1274 	KASSERT(so != NULL);
   1275 	KASSERT(policy != NULL);
   1276 
   1277 	new = malloc(sizeof(*new), M_SECA, M_NOWAIT|M_ZERO);
   1278 	if (new == NULL) {
   1279 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
   1280 		return ENOBUFS;
   1281 	}
   1282 
   1283 	if (IPSEC_PRIVILEGED_SO(so))
   1284 		new->priv = 1;
   1285 	else
   1286 		new->priv = 0;
   1287 
   1288 	if ((new->sp_in = KEY_NEWSP()) == NULL) {
   1289 		ipsec_delpcbpolicy(new);
   1290 		return ENOBUFS;
   1291 	}
   1292 	new->sp_in->state = IPSEC_SPSTATE_ALIVE;
   1293 	new->sp_in->policy = IPSEC_POLICY_ENTRUST;
   1294 
   1295 	if ((new->sp_out = KEY_NEWSP()) == NULL) {
   1296 		KEY_FREESP(&new->sp_in);
   1297 		ipsec_delpcbpolicy(new);
   1298 		return ENOBUFS;
   1299 	}
   1300 	new->sp_out->state = IPSEC_SPSTATE_ALIVE;
   1301 	new->sp_out->policy = IPSEC_POLICY_ENTRUST;
   1302 
   1303 	*policy = new;
   1304 
   1305 	return 0;
   1306 }
   1307 
   1308 /* copy old ipsec policy into new */
   1309 int
   1310 ipsec_copy_policy(const struct inpcbpolicy *old, struct inpcbpolicy *new)
   1311 {
   1312 	struct secpolicy *sp;
   1313 
   1314 	sp = ipsec_deepcopy_policy(old->sp_in);
   1315 	if (sp) {
   1316 		KEY_FREESP(&new->sp_in);
   1317 		new->sp_in = sp;
   1318 	} else
   1319 		return ENOBUFS;
   1320 
   1321 	sp = ipsec_deepcopy_policy(old->sp_out);
   1322 	if (sp) {
   1323 		KEY_FREESP(&new->sp_out);
   1324 		new->sp_out = sp;
   1325 	} else
   1326 		return ENOBUFS;
   1327 
   1328 	new->priv = old->priv;
   1329 
   1330 	return 0;
   1331 }
   1332 
   1333 /* deep-copy a policy in PCB */
   1334 static struct secpolicy *
   1335 ipsec_deepcopy_policy(const struct secpolicy *src)
   1336 {
   1337 	struct ipsecrequest *newchain = NULL;
   1338 	const struct ipsecrequest *p;
   1339 	struct ipsecrequest **q;
   1340 	struct ipsecrequest *r;
   1341 	struct secpolicy *dst;
   1342 
   1343 	if (src == NULL)
   1344 		return NULL;
   1345 	dst = KEY_NEWSP();
   1346 	if (dst == NULL)
   1347 		return NULL;
   1348 
   1349 	/*
   1350 	 * deep-copy IPsec request chain.  This is required since struct
   1351 	 * ipsecrequest is not reference counted.
   1352 	 */
   1353 	q = &newchain;
   1354 	for (p = src->req; p; p = p->next) {
   1355 		*q = malloc(sizeof(**q), M_SECA, M_NOWAIT|M_ZERO);
   1356 		if (*q == NULL)
   1357 			goto fail;
   1358 		(*q)->next = NULL;
   1359 
   1360 		(*q)->saidx.proto = p->saidx.proto;
   1361 		(*q)->saidx.mode = p->saidx.mode;
   1362 		(*q)->level = p->level;
   1363 		(*q)->saidx.reqid = p->saidx.reqid;
   1364 
   1365 		memcpy(&(*q)->saidx.src, &p->saidx.src, sizeof((*q)->saidx.src));
   1366 		memcpy(&(*q)->saidx.dst, &p->saidx.dst, sizeof((*q)->saidx.dst));
   1367 
   1368 		(*q)->sav = NULL;
   1369 		(*q)->sp = dst;
   1370 
   1371 		q = &((*q)->next);
   1372 	}
   1373 
   1374 	dst->req = newchain;
   1375 	dst->state = src->state;
   1376 	dst->policy = src->policy;
   1377 	/* do not touch the refcnt fields */
   1378 
   1379 	return dst;
   1380 
   1381 fail:
   1382 	for (q = &newchain; *q; q = &r) {
   1383 		r = (*q)->next;
   1384 		free(*q, M_SECA);
   1385 	}
   1386 	return NULL;
   1387 }
   1388 
   1389 /* set policy and ipsec request if present. */
   1390 static int
   1391 ipsec_set_policy(
   1392 	struct secpolicy **policy,
   1393 	int optname,
   1394 	const void *request,
   1395 	size_t len,
   1396 	kauth_cred_t cred
   1397 )
   1398 {
   1399 	const struct sadb_x_policy *xpl;
   1400 	struct secpolicy *newsp = NULL;
   1401 	int error;
   1402 
   1403 	/* sanity check. */
   1404 	if (policy == NULL || *policy == NULL || request == NULL)
   1405 		return EINVAL;
   1406 	if (len < sizeof(*xpl))
   1407 		return EINVAL;
   1408 	xpl = (const struct sadb_x_policy *)request;
   1409 
   1410 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1411 		printf("%s: passed policy\n", __func__);
   1412 		kdebug_sadb_x_policy((const struct sadb_ext *)xpl);
   1413 	}
   1414 
   1415 	/* check policy type */
   1416 	/* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
   1417 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
   1418 	 || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
   1419 		return EINVAL;
   1420 
   1421 	/* check privileged socket */
   1422 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
   1423 		error = kauth_authorize_network(cred, KAUTH_NETWORK_IPSEC,
   1424 		    KAUTH_REQ_NETWORK_IPSEC_BYPASS, NULL, NULL, NULL);
   1425 		if (error)
   1426 			return (error);
   1427 	}
   1428 
   1429 	/* allocation new SP entry */
   1430 	if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
   1431 		return error;
   1432 
   1433 	newsp->state = IPSEC_SPSTATE_ALIVE;
   1434 
   1435 	/* clear old SP and set new SP */
   1436 	KEY_FREESP(policy);
   1437 	*policy = newsp;
   1438 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1439 		printf("%s: new policy\n", __func__);
   1440 		kdebug_secpolicy(newsp);
   1441 	}
   1442 
   1443 	return 0;
   1444 }
   1445 
   1446 static int
   1447 ipsec_get_policy(struct secpolicy *policy, struct mbuf **mp)
   1448 {
   1449 
   1450 	/* sanity check. */
   1451 	if (policy == NULL || mp == NULL)
   1452 		return EINVAL;
   1453 
   1454 	*mp = key_sp2msg(policy);
   1455 	if (!*mp) {
   1456 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
   1457 		return ENOBUFS;
   1458 	}
   1459 
   1460 	(*mp)->m_type = MT_DATA;
   1461 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1462 		printf("%s:\n", __func__);
   1463 		kdebug_mbuf(*mp);
   1464 	}
   1465 
   1466 	return 0;
   1467 }
   1468 
   1469 int
   1470 ipsec4_set_policy(struct inpcb *inp, int optname, const void *request,
   1471 		  size_t len, kauth_cred_t cred)
   1472 {
   1473 	const struct sadb_x_policy *xpl;
   1474 	struct secpolicy **policy;
   1475 
   1476 	/* sanity check. */
   1477 	if (inp == NULL || request == NULL)
   1478 		return EINVAL;
   1479 	if (len < sizeof(*xpl))
   1480 		return EINVAL;
   1481 	xpl = (const struct sadb_x_policy *)request;
   1482 
   1483 	KASSERT(inp->inp_sp != NULL);
   1484 
   1485 	/* select direction */
   1486 	switch (xpl->sadb_x_policy_dir) {
   1487 	case IPSEC_DIR_INBOUND:
   1488 		policy = &inp->inp_sp->sp_in;
   1489 		break;
   1490 	case IPSEC_DIR_OUTBOUND:
   1491 		policy = &inp->inp_sp->sp_out;
   1492 		break;
   1493 	default:
   1494 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
   1495 		    xpl->sadb_x_policy_dir));
   1496 		return EINVAL;
   1497 	}
   1498 
   1499 	return ipsec_set_policy(policy, optname, request, len, cred);
   1500 }
   1501 
   1502 int
   1503 ipsec4_get_policy(struct inpcb *inp, const void *request, size_t len,
   1504 		  struct mbuf **mp)
   1505 {
   1506 	const struct sadb_x_policy *xpl;
   1507 	struct secpolicy *policy;
   1508 
   1509 	/* sanity check. */
   1510 	if (inp == NULL || request == NULL || mp == NULL)
   1511 		return EINVAL;
   1512 	KASSERT(inp->inp_sp != NULL);
   1513 	if (len < sizeof(*xpl))
   1514 		return EINVAL;
   1515 	xpl = (const struct sadb_x_policy *)request;
   1516 
   1517 	/* select direction */
   1518 	switch (xpl->sadb_x_policy_dir) {
   1519 	case IPSEC_DIR_INBOUND:
   1520 		policy = inp->inp_sp->sp_in;
   1521 		break;
   1522 	case IPSEC_DIR_OUTBOUND:
   1523 		policy = inp->inp_sp->sp_out;
   1524 		break;
   1525 	default:
   1526 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
   1527 		    xpl->sadb_x_policy_dir));
   1528 		return EINVAL;
   1529 	}
   1530 
   1531 	return ipsec_get_policy(policy, mp);
   1532 }
   1533 
   1534 /* delete policy in PCB */
   1535 int
   1536 ipsec4_delete_pcbpolicy(struct inpcb *inp)
   1537 {
   1538 
   1539 	KASSERT(inp != NULL);
   1540 
   1541 	if (inp->inp_sp == NULL)
   1542 		return 0;
   1543 
   1544 	if (inp->inp_sp->sp_in != NULL)
   1545 		KEY_FREESP(&inp->inp_sp->sp_in);
   1546 
   1547 	if (inp->inp_sp->sp_out != NULL)
   1548 		KEY_FREESP(&inp->inp_sp->sp_out);
   1549 
   1550 	ipsec_invalpcbcache(inp->inp_sp, IPSEC_DIR_ANY);
   1551 
   1552 	ipsec_delpcbpolicy(inp->inp_sp);
   1553 	inp->inp_sp = NULL;
   1554 
   1555 	return 0;
   1556 }
   1557 
   1558 #ifdef INET6
   1559 int
   1560 ipsec6_set_policy(struct in6pcb *in6p, int optname, const void *request,
   1561 		  size_t len, kauth_cred_t cred)
   1562 {
   1563 	const struct sadb_x_policy *xpl;
   1564 	struct secpolicy **policy;
   1565 
   1566 	/* sanity check. */
   1567 	if (in6p == NULL || request == NULL)
   1568 		return EINVAL;
   1569 	if (len < sizeof(*xpl))
   1570 		return EINVAL;
   1571 	xpl = (const struct sadb_x_policy *)request;
   1572 
   1573 	/* select direction */
   1574 	switch (xpl->sadb_x_policy_dir) {
   1575 	case IPSEC_DIR_INBOUND:
   1576 		policy = &in6p->in6p_sp->sp_in;
   1577 		break;
   1578 	case IPSEC_DIR_OUTBOUND:
   1579 		policy = &in6p->in6p_sp->sp_out;
   1580 		break;
   1581 	default:
   1582 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
   1583 		    xpl->sadb_x_policy_dir));
   1584 		return EINVAL;
   1585 	}
   1586 
   1587 	return ipsec_set_policy(policy, optname, request, len, cred);
   1588 }
   1589 
   1590 int
   1591 ipsec6_get_policy(struct in6pcb *in6p, const void *request, size_t len,
   1592 		  struct mbuf **mp)
   1593 {
   1594 	const struct sadb_x_policy *xpl;
   1595 	struct secpolicy *policy;
   1596 
   1597 	/* sanity check. */
   1598 	if (in6p == NULL || request == NULL || mp == NULL)
   1599 		return EINVAL;
   1600 	KASSERT(in6p->in6p_sp != NULL);
   1601 	if (len < sizeof(*xpl))
   1602 		return EINVAL;
   1603 	xpl = (const struct sadb_x_policy *)request;
   1604 
   1605 	/* select direction */
   1606 	switch (xpl->sadb_x_policy_dir) {
   1607 	case IPSEC_DIR_INBOUND:
   1608 		policy = in6p->in6p_sp->sp_in;
   1609 		break;
   1610 	case IPSEC_DIR_OUTBOUND:
   1611 		policy = in6p->in6p_sp->sp_out;
   1612 		break;
   1613 	default:
   1614 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
   1615 		    xpl->sadb_x_policy_dir));
   1616 		return EINVAL;
   1617 	}
   1618 
   1619 	return ipsec_get_policy(policy, mp);
   1620 }
   1621 
   1622 int
   1623 ipsec6_delete_pcbpolicy(struct in6pcb *in6p)
   1624 {
   1625 
   1626 	KASSERT(in6p != NULL);
   1627 
   1628 	if (in6p->in6p_sp == NULL)
   1629 		return 0;
   1630 
   1631 	if (in6p->in6p_sp->sp_in != NULL)
   1632 		KEY_FREESP(&in6p->in6p_sp->sp_in);
   1633 
   1634 	if (in6p->in6p_sp->sp_out != NULL)
   1635 		KEY_FREESP(&in6p->in6p_sp->sp_out);
   1636 
   1637 	ipsec_invalpcbcache(in6p->in6p_sp, IPSEC_DIR_ANY);
   1638 
   1639 	ipsec_delpcbpolicy(in6p->in6p_sp);
   1640 	in6p->in6p_sp = NULL;
   1641 
   1642 	return 0;
   1643 }
   1644 #endif
   1645 
   1646 /*
   1647  * return current level.
   1648  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
   1649  */
   1650 u_int
   1651 ipsec_get_reqlevel(const struct ipsecrequest *isr)
   1652 {
   1653 	u_int level = 0;
   1654 	u_int esp_trans_deflev, esp_net_deflev;
   1655 	u_int ah_trans_deflev, ah_net_deflev;
   1656 
   1657 	KASSERT(isr != NULL);
   1658 	KASSERT(isr->sp != NULL);
   1659 	KASSERTMSG(
   1660 	    isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family,
   1661 	    "af family mismatch, src %u, dst %u",
   1662 	    isr->sp->spidx.src.sa.sa_family, isr->sp->spidx.dst.sa.sa_family);
   1663 
   1664 /* XXX note that we have ipseclog() expanded here - code sync issue */
   1665 #define IPSEC_CHECK_DEFAULT(lev) 					\
   1666     (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE		\
   1667     && (lev) != IPSEC_LEVEL_UNIQUE) ?					\
   1668 	(ipsec_debug ? log(LOG_INFO, "fixed system default level " #lev \
   1669 	":%d->%d\n", (lev), IPSEC_LEVEL_REQUIRE) : (void)0),		\
   1670 	(lev) = IPSEC_LEVEL_REQUIRE, (lev)				\
   1671     : (lev))
   1672 
   1673 	/* set default level */
   1674 	switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
   1675 #ifdef INET
   1676 	case AF_INET:
   1677 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
   1678 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
   1679 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
   1680 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
   1681 		break;
   1682 #endif
   1683 #ifdef INET6
   1684 	case AF_INET6:
   1685 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
   1686 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
   1687 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
   1688 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
   1689 		break;
   1690 #endif /* INET6 */
   1691 	default:
   1692 		panic("%s: unknown af %u", __func__,
   1693 		    isr->sp->spidx.src.sa.sa_family);
   1694 	}
   1695 
   1696 #undef IPSEC_CHECK_DEFAULT
   1697 
   1698 	/* set level */
   1699 	switch (isr->level) {
   1700 	case IPSEC_LEVEL_DEFAULT:
   1701 		switch (isr->saidx.proto) {
   1702 		case IPPROTO_ESP:
   1703 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
   1704 				level = esp_net_deflev;
   1705 			else
   1706 				level = esp_trans_deflev;
   1707 			break;
   1708 		case IPPROTO_AH:
   1709 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
   1710 				level = ah_net_deflev;
   1711 			else
   1712 				level = ah_trans_deflev;
   1713 			break;
   1714 		case IPPROTO_IPCOMP:
   1715 			/*
   1716 			 * we don't really care, as IPcomp document says that
   1717 			 * we shouldn't compress small packets
   1718 			 */
   1719 			level = IPSEC_LEVEL_USE;
   1720 			break;
   1721 		default:
   1722 			panic("%s: Illegal protocol defined %u", __func__,
   1723 			    isr->saidx.proto);
   1724 		}
   1725 		break;
   1726 
   1727 	case IPSEC_LEVEL_USE:
   1728 	case IPSEC_LEVEL_REQUIRE:
   1729 		level = isr->level;
   1730 		break;
   1731 	case IPSEC_LEVEL_UNIQUE:
   1732 		level = IPSEC_LEVEL_REQUIRE;
   1733 		break;
   1734 
   1735 	default:
   1736 		panic("%s: Illegal IPsec level %u", __func__, isr->level);
   1737 	}
   1738 
   1739 	return level;
   1740 }
   1741 
   1742 /*
   1743  * Check security policy requirements against the actual
   1744  * packet contents.  Return one if the packet should be
   1745  * reject as "invalid"; otherwiser return zero to have the
   1746  * packet treated as "valid".
   1747  *
   1748  * OUT:
   1749  *	0: valid
   1750  *	1: invalid
   1751  */
   1752 int
   1753 ipsec_in_reject(const struct secpolicy *sp, const struct mbuf *m)
   1754 {
   1755 	struct ipsecrequest *isr;
   1756 	int need_auth;
   1757 
   1758 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
   1759 		printf("%s: using SP\n", __func__);
   1760 		kdebug_secpolicy(sp);
   1761 	}
   1762 
   1763 	/* check policy */
   1764 	switch (sp->policy) {
   1765 	case IPSEC_POLICY_DISCARD:
   1766 		return 1;
   1767 	case IPSEC_POLICY_BYPASS:
   1768 	case IPSEC_POLICY_NONE:
   1769 		return 0;
   1770 	}
   1771 
   1772 	KASSERTMSG(sp->policy == IPSEC_POLICY_IPSEC,
   1773 	    "invalid policy %u", sp->policy);
   1774 
   1775 	/* XXX should compare policy against ipsec header history */
   1776 
   1777 	need_auth = 0;
   1778 	for (isr = sp->req; isr != NULL; isr = isr->next) {
   1779 		if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
   1780 			continue;
   1781 		switch (isr->saidx.proto) {
   1782 		case IPPROTO_ESP:
   1783 			if ((m->m_flags & M_DECRYPTED) == 0) {
   1784 				KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1785 				    "ESP m_flags:%x\n", m->m_flags);
   1786 				return 1;
   1787 			}
   1788 
   1789 			if (!need_auth &&
   1790 				isr->sav != NULL &&
   1791 				isr->sav->tdb_authalgxform != NULL &&
   1792 				(m->m_flags & M_AUTHIPDGM) == 0) {
   1793 				KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1794 				    "ESP/AH m_flags:%x\n", m->m_flags);
   1795 				return 1;
   1796 			}
   1797 			break;
   1798 		case IPPROTO_AH:
   1799 			need_auth = 1;
   1800 			if ((m->m_flags & M_AUTHIPHDR) == 0) {
   1801 				KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1802 				    "AH m_flags:%x\n", m->m_flags);
   1803 				return 1;
   1804 			}
   1805 			break;
   1806 		case IPPROTO_IPCOMP:
   1807 			/*
   1808 			 * we don't really care, as IPcomp document
   1809 			 * says that we shouldn't compress small
   1810 			 * packets, IPComp policy should always be
   1811 			 * treated as being in "use" level.
   1812 			 */
   1813 			break;
   1814 		}
   1815 	}
   1816 	return 0;		/* valid */
   1817 }
   1818 
   1819 /*
   1820  * Check AH/ESP integrity.
   1821  * This function is called from tcp_input(), udp_input(),
   1822  * and {ah,esp}4_input for tunnel mode
   1823  */
   1824 int
   1825 ipsec4_in_reject(struct mbuf *m, struct inpcb *inp)
   1826 {
   1827 	struct secpolicy *sp;
   1828 	int error;
   1829 	int result;
   1830 
   1831 	KASSERT(m != NULL);
   1832 
   1833 	/* get SP for this packet.
   1834 	 * When we are called from ip_forward(), we call
   1835 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
   1836 	 */
   1837 	if (inp == NULL)
   1838 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
   1839 	else
   1840 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
   1841 					   (struct inpcb_hdr *)inp, &error);
   1842 
   1843 	if (sp != NULL) {
   1844 		result = ipsec_in_reject(sp, m);
   1845 		if (result)
   1846 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
   1847 		KEY_FREESP(&sp);
   1848 	} else {
   1849 		result = 0;	/* XXX should be panic ?
   1850 				 * -> No, there may be error. */
   1851 	}
   1852 	return result;
   1853 }
   1854 
   1855 
   1856 #ifdef INET6
   1857 /*
   1858  * Check AH/ESP integrity.
   1859  * This function is called from tcp6_input(), udp6_input(),
   1860  * and {ah,esp}6_input for tunnel mode
   1861  */
   1862 int
   1863 ipsec6_in_reject(struct mbuf *m, struct in6pcb *in6p)
   1864 {
   1865 	struct secpolicy *sp = NULL;
   1866 	int error;
   1867 	int result;
   1868 
   1869 	KASSERT(m != NULL);
   1870 
   1871 	/* get SP for this packet.
   1872 	 * When we are called from ip_forward(), we call
   1873 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
   1874 	 */
   1875 	if (in6p == NULL)
   1876 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
   1877 	else
   1878 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
   1879 			(struct inpcb_hdr *)in6p,
   1880 			&error);
   1881 
   1882 	if (sp != NULL) {
   1883 		result = ipsec_in_reject(sp, m);
   1884 		if (result)
   1885 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
   1886 		KEY_FREESP(&sp);
   1887 	} else {
   1888 		result = 0;
   1889 	}
   1890 	return result;
   1891 }
   1892 #endif
   1893 
   1894 /*
   1895  * compute the byte size to be occupied by IPsec header.
   1896  * in case it is tunneled, it includes the size of outer IP header.
   1897  * NOTE: SP passed is free in this function.
   1898  */
   1899 static size_t
   1900 ipsec_hdrsiz(const struct secpolicy *sp)
   1901 {
   1902 	const struct ipsecrequest *isr;
   1903 	size_t siz;
   1904 
   1905 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
   1906 		printf("%s: using SP\n", __func__);
   1907 		kdebug_secpolicy(sp);
   1908 	}
   1909 
   1910 	switch (sp->policy) {
   1911 	case IPSEC_POLICY_DISCARD:
   1912 	case IPSEC_POLICY_BYPASS:
   1913 	case IPSEC_POLICY_NONE:
   1914 		return 0;
   1915 	}
   1916 
   1917 	KASSERTMSG(sp->policy == IPSEC_POLICY_IPSEC,
   1918 	    "invalid policy %u", sp->policy);
   1919 
   1920 	siz = 0;
   1921 	for (isr = sp->req; isr != NULL; isr = isr->next) {
   1922 		size_t clen = 0;
   1923 
   1924 		switch (isr->saidx.proto) {
   1925 		case IPPROTO_ESP:
   1926 			clen = esp_hdrsiz(isr->sav);
   1927 			break;
   1928 		case IPPROTO_AH:
   1929 			clen = ah_hdrsiz(isr->sav);
   1930 			break;
   1931 		case IPPROTO_IPCOMP:
   1932 			clen = sizeof(struct ipcomp);
   1933 			break;
   1934 		}
   1935 
   1936 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
   1937 			switch (isr->saidx.dst.sa.sa_family) {
   1938 			case AF_INET:
   1939 				clen += sizeof(struct ip);
   1940 				break;
   1941 #ifdef INET6
   1942 			case AF_INET6:
   1943 				clen += sizeof(struct ip6_hdr);
   1944 				break;
   1945 #endif
   1946 			default:
   1947 				ipseclog((LOG_ERR, "%s: unknown AF %d in "
   1948 				    "IPsec tunnel SA\n", __func__,
   1949 				    ((const struct sockaddr *)&isr->saidx.dst)
   1950 				    ->sa_family));
   1951 				break;
   1952 			}
   1953 		}
   1954 		siz += clen;
   1955 	}
   1956 
   1957 	return siz;
   1958 }
   1959 
   1960 /* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
   1961 size_t
   1962 ipsec4_hdrsiz(struct mbuf *m, u_int dir, struct inpcb *inp)
   1963 {
   1964 	struct secpolicy *sp;
   1965 	int error;
   1966 	size_t size;
   1967 
   1968 	KASSERT(m != NULL);
   1969 	KASSERTMSG(inp == NULL || inp->inp_socket != NULL, "socket w/o inpcb");
   1970 
   1971 	/* get SP for this packet.
   1972 	 * When we are called from ip_forward(), we call
   1973 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
   1974 	 */
   1975 	if (inp == NULL)
   1976 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
   1977 	else
   1978 		sp = ipsec_getpolicybysock(m, dir,
   1979 					   (struct inpcb_hdr *)inp, &error);
   1980 
   1981 	if (sp != NULL) {
   1982 		size = ipsec_hdrsiz(sp);
   1983 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DATA, "size:%lu.\n",
   1984 		    (unsigned long)size);
   1985 
   1986 		KEY_FREESP(&sp);
   1987 	} else {
   1988 		size = 0;	/* XXX should be panic ? */
   1989 	}
   1990 	return size;
   1991 }
   1992 
   1993 #ifdef INET6
   1994 /* This function is called from ipsec6_hdrsize_tcp(),
   1995  * and maybe from ip6_forward.()
   1996  */
   1997 size_t
   1998 ipsec6_hdrsiz(struct mbuf *m, u_int dir, struct in6pcb *in6p)
   1999 {
   2000 	struct secpolicy *sp;
   2001 	int error;
   2002 	size_t size;
   2003 
   2004 	KASSERT(m != NULL);
   2005 	KASSERTMSG(in6p == NULL || in6p->in6p_socket != NULL,
   2006 	    "socket w/o inpcb");
   2007 
   2008 	/* get SP for this packet */
   2009 	/* XXX Is it right to call with IP_FORWARDING. */
   2010 	if (in6p == NULL)
   2011 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
   2012 	else
   2013 		sp = ipsec_getpolicybysock(m, dir,
   2014 			(struct inpcb_hdr *)in6p,
   2015 			&error);
   2016 
   2017 	if (sp == NULL)
   2018 		return 0;
   2019 	size = ipsec_hdrsiz(sp);
   2020 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DATA, "size:%zu.\n", size);
   2021 	KEY_FREESP(&sp);
   2022 
   2023 	return size;
   2024 }
   2025 #endif /*INET6*/
   2026 
   2027 /*
   2028  * Check the variable replay window.
   2029  * ipsec_chkreplay() performs replay check before ICV verification.
   2030  * ipsec_updatereplay() updates replay bitmap.  This must be called after
   2031  * ICV verification (it also performs replay check, which is usually done
   2032  * beforehand).
   2033  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
   2034  *
   2035  * based on RFC 2401.
   2036  */
   2037 int
   2038 ipsec_chkreplay(u_int32_t seq, const struct secasvar *sav)
   2039 {
   2040 	const struct secreplay *replay;
   2041 	u_int32_t diff;
   2042 	int fr;
   2043 	u_int32_t wsizeb;	/* constant: bits of window size */
   2044 	int frlast;		/* constant: last frame */
   2045 
   2046 	IPSEC_SPLASSERT_SOFTNET(__func__);
   2047 
   2048 	KASSERT(sav != NULL);
   2049 	KASSERT(sav->replay != NULL);
   2050 
   2051 	replay = sav->replay;
   2052 
   2053 	if (replay->wsize == 0)
   2054 		return 1;	/* no need to check replay. */
   2055 
   2056 	/* constant */
   2057 	frlast = replay->wsize - 1;
   2058 	wsizeb = replay->wsize << 3;
   2059 
   2060 	/* sequence number of 0 is invalid */
   2061 	if (seq == 0)
   2062 		return 0;
   2063 
   2064 	/* first time is always okay */
   2065 	if (replay->count == 0)
   2066 		return 1;
   2067 
   2068 	if (seq > replay->lastseq) {
   2069 		/* larger sequences are okay */
   2070 		return 1;
   2071 	} else {
   2072 		/* seq is equal or less than lastseq. */
   2073 		diff = replay->lastseq - seq;
   2074 
   2075 		/* over range to check, i.e. too old or wrapped */
   2076 		if (diff >= wsizeb)
   2077 			return 0;
   2078 
   2079 		fr = frlast - diff / 8;
   2080 
   2081 		/* this packet already seen ? */
   2082 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
   2083 			return 0;
   2084 
   2085 		/* out of order but good */
   2086 		return 1;
   2087 	}
   2088 }
   2089 
   2090 /*
   2091  * check replay counter whether to update or not.
   2092  * OUT:	0:	OK
   2093  *	1:	NG
   2094  */
   2095 int
   2096 ipsec_updatereplay(u_int32_t seq, const struct secasvar *sav)
   2097 {
   2098 	struct secreplay *replay;
   2099 	u_int32_t diff;
   2100 	int fr;
   2101 	u_int32_t wsizeb;	/* constant: bits of window size */
   2102 	int frlast;		/* constant: last frame */
   2103 
   2104 	IPSEC_SPLASSERT_SOFTNET(__func__);
   2105 
   2106 	KASSERT(sav != NULL);
   2107 	KASSERT(sav->replay != NULL);
   2108 
   2109 	replay = sav->replay;
   2110 
   2111 	if (replay->wsize == 0)
   2112 		goto ok;	/* no need to check replay. */
   2113 
   2114 	/* constant */
   2115 	frlast = replay->wsize - 1;
   2116 	wsizeb = replay->wsize << 3;
   2117 
   2118 	/* sequence number of 0 is invalid */
   2119 	if (seq == 0)
   2120 		return 1;
   2121 
   2122 	/* first time */
   2123 	if (replay->count == 0) {
   2124 		replay->lastseq = seq;
   2125 		memset(replay->bitmap, 0, replay->wsize);
   2126 		(replay->bitmap)[frlast] = 1;
   2127 		goto ok;
   2128 	}
   2129 
   2130 	if (seq > replay->lastseq) {
   2131 		/* seq is larger than lastseq. */
   2132 		diff = seq - replay->lastseq;
   2133 
   2134 		/* new larger sequence number */
   2135 		if (diff < wsizeb) {
   2136 			/* In window */
   2137 			/* set bit for this packet */
   2138 			vshiftl(replay->bitmap, diff, replay->wsize);
   2139 			(replay->bitmap)[frlast] |= 1;
   2140 		} else {
   2141 			/* this packet has a "way larger" */
   2142 			memset(replay->bitmap, 0, replay->wsize);
   2143 			(replay->bitmap)[frlast] = 1;
   2144 		}
   2145 		replay->lastseq = seq;
   2146 
   2147 		/* larger is good */
   2148 	} else {
   2149 		/* seq is equal or less than lastseq. */
   2150 		diff = replay->lastseq - seq;
   2151 
   2152 		/* over range to check, i.e. too old or wrapped */
   2153 		if (diff >= wsizeb)
   2154 			return 1;
   2155 
   2156 		fr = frlast - diff / 8;
   2157 
   2158 		/* this packet already seen ? */
   2159 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
   2160 			return 1;
   2161 
   2162 		/* mark as seen */
   2163 		(replay->bitmap)[fr] |= (1 << (diff % 8));
   2164 
   2165 		/* out of order but good */
   2166 	}
   2167 
   2168 ok:
   2169 	if (replay->count == ~0) {
   2170 
   2171 		/* set overflow flag */
   2172 		replay->overflow++;
   2173 
   2174 		/* don't increment, no more packets accepted */
   2175 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
   2176 			return 1;
   2177 
   2178 		ipseclog((LOG_WARNING, "replay counter made %d cycle. %s\n",
   2179 		    replay->overflow, ipsec_logsastr(sav)));
   2180 	}
   2181 
   2182 	replay->count++;
   2183 
   2184 	return 0;
   2185 }
   2186 
   2187 /*
   2188  * shift variable length bunffer to left.
   2189  * IN:	bitmap: pointer to the buffer
   2190  * 	nbit:	the number of to shift.
   2191  *	wsize:	buffer size (bytes).
   2192  */
   2193 static void
   2194 vshiftl(unsigned char *bitmap, int nbit, int wsize)
   2195 {
   2196 	int s, j, i;
   2197 	unsigned char over;
   2198 
   2199 	for (j = 0; j < nbit; j += 8) {
   2200 		s = (nbit - j < 8) ? (nbit - j): 8;
   2201 		bitmap[0] <<= s;
   2202 		for (i = 1; i < wsize; i++) {
   2203 			over = (bitmap[i] >> (8 - s));
   2204 			bitmap[i] <<= s;
   2205 			bitmap[i-1] |= over;
   2206 		}
   2207 	}
   2208 
   2209 	return;
   2210 }
   2211 
   2212 /* Return a printable string for the IPv4 address. */
   2213 static char *
   2214 inet_ntoa4(struct in_addr ina)
   2215 {
   2216 	static char buf[4][4 * sizeof "123" + 4];
   2217 	unsigned char *ucp = (unsigned char *) &ina;
   2218 	static int i = 3;
   2219 
   2220 	i = (i + 1) % 4;
   2221 	snprintf(buf[i], sizeof(buf[i]), "%d.%d.%d.%d",
   2222 		ucp[0] & 0xff, ucp[1] & 0xff, ucp[2] & 0xff, ucp[3] & 0xff);
   2223 	return (buf[i]);
   2224 }
   2225 
   2226 /* Return a printable string for the address. */
   2227 const char *
   2228 ipsec_address(const union sockaddr_union *sa)
   2229 {
   2230 #if INET6
   2231 	static char ip6buf[INET6_ADDRSTRLEN];	/* XXX: NOMPSAFE */
   2232 #endif
   2233 
   2234 	switch (sa->sa.sa_family) {
   2235 #if INET
   2236 	case AF_INET:
   2237 		return inet_ntoa4(sa->sin.sin_addr);
   2238 #endif /* INET */
   2239 
   2240 #if INET6
   2241 	case AF_INET6:
   2242 		return IN6_PRINT(ip6buf, &sa->sin6.sin6_addr);
   2243 #endif /* INET6 */
   2244 
   2245 	default:
   2246 		return "(unknown address family)";
   2247 	}
   2248 }
   2249 
   2250 const char *
   2251 ipsec_logsastr(const struct secasvar *sav)
   2252 {
   2253 	static char buf[256];
   2254 	char *p;
   2255 	const struct secasindex *saidx = &sav->sah->saidx;
   2256 
   2257 	KASSERTMSG(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
   2258 	    "af family mismatch, src %u, dst %u",
   2259 	    saidx->src.sa.sa_family, saidx->dst.sa.sa_family);
   2260 
   2261 	p = buf;
   2262 	snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
   2263 	while (p && *p)
   2264 		p++;
   2265 	/* NB: only use ipsec_address on one address at a time */
   2266 	snprintf(p, sizeof (buf) - (p - buf), "src=%s ",
   2267 		ipsec_address(&saidx->src));
   2268 	while (p && *p)
   2269 		p++;
   2270 	snprintf(p, sizeof (buf) - (p - buf), "dst=%s)",
   2271 		ipsec_address(&saidx->dst));
   2272 
   2273 	return buf;
   2274 }
   2275 
   2276 void
   2277 ipsec_dumpmbuf(struct mbuf *m)
   2278 {
   2279 	int totlen;
   2280 	int i;
   2281 	u_char *p;
   2282 
   2283 	totlen = 0;
   2284 	printf("---\n");
   2285 	while (m) {
   2286 		p = mtod(m, u_char *);
   2287 		for (i = 0; i < m->m_len; i++) {
   2288 			printf("%02x ", p[i]);
   2289 			totlen++;
   2290 			if (totlen % 16 == 0)
   2291 				printf("\n");
   2292 		}
   2293 		m = m->m_next;
   2294 	}
   2295 	if (totlen % 16 != 0)
   2296 		printf("\n");
   2297 	printf("---\n");
   2298 }
   2299 
   2300 #ifdef INET6
   2301 struct secpolicy *
   2302 ipsec6_check_policy(struct mbuf *m, struct in6pcb *in6p,
   2303 		    int flags, int *needipsecp, int *errorp)
   2304 {
   2305 	struct secpolicy *sp = NULL;
   2306 	int s;
   2307 	int error = 0;
   2308 	int needipsec = 0;
   2309 
   2310 	if (!ipsec_outdone(m)) {
   2311 		s = splsoftnet();
   2312 		if (in6p != NULL &&
   2313 		    IPSEC_PCB_SKIP_IPSEC(in6p->in6p_sp, IPSEC_DIR_OUTBOUND)) {
   2314 			splx(s);
   2315 			goto skippolicycheck;
   2316 		}
   2317 		sp = ipsec6_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error,in6p);
   2318 
   2319 		/*
   2320 		 * There are four return cases:
   2321 		 *	sp != NULL			apply IPsec policy
   2322 		 *	sp == NULL, error == 0		no IPsec handling needed
   2323 		 *	sp == NULL, error == -EINVAL  discard packet w/o error
   2324 		 *	sp == NULL, error != 0		discard packet, report error
   2325 		 */
   2326 
   2327 		splx(s);
   2328 		if (sp == NULL) {
   2329 			/*
   2330 			 * Caller must check the error return to see if it needs to discard
   2331 			 * the packet.
   2332 			 */
   2333 			needipsec = 0;
   2334 		} else {
   2335 			needipsec = 1;
   2336 		}
   2337 	}
   2338 skippolicycheck:;
   2339 
   2340 	*errorp = error;
   2341 	*needipsecp = needipsec;
   2342 	return sp;
   2343 }
   2344 
   2345 int
   2346 ipsec6_input(struct mbuf *m)
   2347 {
   2348 	struct m_tag *mtag;
   2349 	struct tdb_ident *tdbi;
   2350 	struct secpolicy *sp;
   2351 	int s, error;
   2352 
   2353 	/*
   2354 	 * Check if the packet has already had IPsec
   2355 	 * processing done. If so, then just pass it
   2356 	 * along. This tag gets set during AH, ESP,
   2357 	 * etc. input handling, before the packet is
   2358 	 * returned to the ip input queue for delivery.
   2359 	 */
   2360 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE,
   2361 	    NULL);
   2362 	s = splsoftnet();
   2363 	if (mtag != NULL) {
   2364 		tdbi = (struct tdb_ident *)(mtag + 1);
   2365 		sp = ipsec_getpolicy(tdbi,
   2366 		    IPSEC_DIR_INBOUND);
   2367 	} else {
   2368 		sp = ipsec_getpolicybyaddr(m,
   2369 		    IPSEC_DIR_INBOUND, IP_FORWARDING,
   2370 		    &error);
   2371 	}
   2372 	if (sp != NULL) {
   2373 		/*
   2374 		 * Check security policy against packet
   2375 		 * attributes.
   2376 		 */
   2377 		error = ipsec_in_reject(sp, m);
   2378 		KEY_FREESP(&sp);
   2379 	} else {
   2380 		/* XXX error stat??? */
   2381 		error = EINVAL;
   2382 		DPRINTF(("ip6_input: no SP, packet"
   2383 		    " discarded\n"));/*XXX*/
   2384 	}
   2385 	splx(s);
   2386 
   2387 	return error;
   2388 }
   2389 #endif /* INET6 */
   2390 
   2391 
   2392 
   2393 /* XXX this stuff doesn't belong here... */
   2394 
   2395 static	struct xformsw *xforms = NULL;
   2396 
   2397 /*
   2398  * Register a transform; typically at system startup.
   2399  */
   2400 void
   2401 xform_register(struct xformsw *xsp)
   2402 {
   2403 	xsp->xf_next = xforms;
   2404 	xforms = xsp;
   2405 }
   2406 
   2407 /*
   2408  * Initialize transform support in an sav.
   2409  */
   2410 int
   2411 xform_init(struct secasvar *sav, int xftype)
   2412 {
   2413 	struct xformsw *xsp;
   2414 
   2415 	if (sav->tdb_xform != NULL)	/* previously initialized */
   2416 		return 0;
   2417 	for (xsp = xforms; xsp; xsp = xsp->xf_next)
   2418 		if (xsp->xf_type == xftype)
   2419 			return (*xsp->xf_init)(sav, xsp);
   2420 
   2421 	DPRINTF(("%s: no match for xform type %d\n", __func__, xftype));
   2422 	return EINVAL;
   2423 }
   2424 
   2425 void
   2426 nat_t_ports_get(struct mbuf *m, u_int16_t *dport, u_int16_t *sport) {
   2427 	struct m_tag *tag;
   2428 
   2429 	if ((tag = m_tag_find(m, PACKET_TAG_IPSEC_NAT_T_PORTS, NULL))) {
   2430 		*sport = ((u_int16_t *)(tag + 1))[0];
   2431 		*dport = ((u_int16_t *)(tag + 1))[1];
   2432 	} else
   2433 		*sport = *dport = 0;
   2434 }
   2435 
   2436 /*
   2437  * XXXJRT This should be done as a protosw init call.
   2438  */
   2439 void
   2440 ipsec_attach(void)
   2441 {
   2442 
   2443 	ipsecstat_percpu = percpu_alloc(sizeof(uint64_t) * IPSEC_NSTATS);
   2444 
   2445 	sysctl_net_inet_ipsec_setup(NULL);
   2446 #ifdef INET6
   2447 	sysctl_net_inet6_ipsec6_setup(NULL);
   2448 #endif
   2449 
   2450 	ah_attach();
   2451 	esp_attach();
   2452 	ipcomp_attach();
   2453 	ipe4_attach();
   2454 #ifdef TCP_SIGNATURE
   2455 	tcpsignature_attach();
   2456 #endif
   2457 }
   2458