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