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