Home | History | Annotate | Line # | Download | only in netipsec
ipsec.c revision 1.60.2.2
      1 /*	$NetBSD: ipsec.c,v 1.60.2.2 2014/05/18 17:46:13 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.2 2014/05/18 17:46:13 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("%s: NULL pcbsp\n", __func__);
    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 %s cause refcnt++:%d SP:%p\n", __func__,
    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 %s cause refcnt++:%d SP:%p\n", __func__,
    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 %s from %s:%u\n", __func__, 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("%s: unexpected protocol family %u\n", __func__,
    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, printf("DP %s returns SP:%p (%u)\n",
    466 	    __func__, sp, sp->refcnt));
    467 	return sp;
    468 }
    469 #define	KEY_ALLOCSP_DEFAULT(af) \
    470 	key_allocsp_default((af),__FILE__, __LINE__)
    471 
    472 /*
    473  * For OUTBOUND packet having a socket. Searching SPD for packet,
    474  * and return a pointer to SP.
    475  * OUT:	NULL:	no apropreate SP found, the following value is set to error.
    476  *		0	: bypass
    477  *		EACCES	: discard packet.
    478  *		ENOENT	: ipsec_acquire() in progress, maybe.
    479  *		others	: error occurred.
    480  *	others:	a pointer to SP
    481  *
    482  * NOTE: IPv6 mapped address concern is implemented here.
    483  */
    484 struct secpolicy *
    485 ipsec_getpolicy(const struct tdb_ident *tdbi, u_int dir)
    486 {
    487 	struct secpolicy *sp;
    488 
    489 	IPSEC_ASSERT(tdbi != NULL, ("%s: null tdbi", __func__));
    490 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
    491 	    ("%s: invalid direction %u", __func__, dir));
    492 
    493 	sp = KEY_ALLOCSP2(tdbi->spi, &tdbi->dst, tdbi->proto, dir);
    494 	if (sp == NULL)			/*XXX????*/
    495 		sp = KEY_ALLOCSP_DEFAULT(tdbi->dst.sa.sa_family);
    496 	IPSEC_ASSERT(sp != NULL, ("%s: null SP", __func__));
    497 	return sp;
    498 }
    499 
    500 /*
    501  * For OUTBOUND packet having a socket. Searching SPD for packet,
    502  * and return a pointer to SP.
    503  * OUT:	NULL:	no apropreate SP found, the following value is set to error.
    504  *		0	: bypass
    505  *		EACCES	: discard packet.
    506  *		ENOENT	: ipsec_acquire() in progress, maybe.
    507  *		others	: error occurred.
    508  *	others:	a pointer to SP
    509  *
    510  * NOTE: IPv6 mapped address concern is implemented here.
    511  */
    512 static struct secpolicy *
    513 ipsec_getpolicybysock(struct mbuf *m, u_int dir, PCB_T *inp, int *error)
    514 {
    515 	struct inpcbpolicy *pcbsp = NULL;
    516 	struct secpolicy *currsp = NULL;	/* policy on socket */
    517 	struct secpolicy *sp;
    518 	int af;
    519 
    520 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
    521 	IPSEC_ASSERT(inp != NULL, ("%s: null inpcb", __func__));
    522 	IPSEC_ASSERT(error != NULL, ("%s: null error", __func__));
    523 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
    524 	    ("%s: invalid direction %u", __func__, dir));
    525 
    526 	IPSEC_ASSERT(PCB_SOCKET(inp) != NULL, ("%s: null socket", __func__));
    527 
    528 	/* XXX FIXME inpcb/in6pcb  vs socket*/
    529 	af = PCB_FAMILY(inp);
    530 	IPSEC_ASSERT(af == AF_INET || af == AF_INET6,
    531 	    ("%s: unexpected protocol family %u", __func__, 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, ("%s: null pcbsp", __func__));
    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, ("%s: null currsp", __func__));
    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, "%s: Invalid policy for PCB %d\n",
    598 			    __func__, 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, "%s: Illegal policy for "
    608 				    "non-priviliged defined %d\n", __func__,
    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, "%s: Invalid policy for "
    624 				    "PCB %d\n", __func__, currsp->policy));
    625 				*error = EINVAL;
    626 				return NULL;
    627 			}
    628 		}
    629 	}
    630 	IPSEC_ASSERT(sp != NULL,
    631 	    ("%s: null SP (priv %u policy %u", __func__, pcbsp->priv,
    632 	    currsp->policy));
    633 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    634 	    printf("DP %s (priv %u policy %u) allocates SP:%p (refcnt %u)\n",
    635 	    __func__, pcbsp->priv, currsp->policy, sp, sp->refcnt));
    636 #ifdef __NetBSD__
    637 	ipsec_fillpcbcache(pcbsp, m, sp, dir);
    638 #endif /* __NetBSD__ */
    639 	return sp;
    640 }
    641 
    642 /*
    643  * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
    644  * and return a pointer to SP.
    645  * OUT:	positive: a pointer to the entry for security policy leaf matched.
    646  *	NULL:	no apropreate SP found, the following value is set to error.
    647  *		0	: bypass
    648  *		EACCES	: discard packet.
    649  *		ENOENT	: ipsec_acquire() in progress, maybe.
    650  *		others	: error occurred.
    651  */
    652 struct secpolicy *
    653 ipsec_getpolicybyaddr(struct mbuf *m, u_int dir, int flag, int *error)
    654 {
    655 	struct secpolicyindex spidx;
    656 	struct secpolicy *sp;
    657 
    658 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
    659 	IPSEC_ASSERT(error != NULL, ("%s: null error", __func__));
    660 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
    661 	    ("%s: invalid direction %u", __func__, dir));
    662 
    663 	sp = NULL;
    664 
    665 	/* Make an index to look for a policy. */
    666 	*error = ipsec_setspidx(m, &spidx, (flag & IP_FORWARDING) ? 0 : 1);
    667 	if (*error != 0) {
    668 		DPRINTF(("%s: setpidx failed, dir %u flag %u\n", __func__,
    669 		    dir, flag));
    670 		memset(&spidx, 0, sizeof (spidx));
    671 		return NULL;
    672 	}
    673 
    674 	spidx.dir = dir;
    675 
    676 	if (key_havesp(dir)) {
    677 		sp = KEY_ALLOCSP(&spidx, dir);
    678 	}
    679 
    680 	if (sp == NULL)			/* no SP found, use system default */
    681 		sp = KEY_ALLOCSP_DEFAULT(spidx.dst.sa.sa_family);
    682 	IPSEC_ASSERT(sp != NULL, ("%s: null SP", __func__));
    683 	return sp;
    684 }
    685 
    686 struct secpolicy *
    687 ipsec4_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
    688 		   struct inpcb *inp)
    689 {
    690 	struct secpolicy *sp;
    691 
    692 	*error = 0;
    693 
    694 
    695 	/* XXX KAME IPv6 calls us with non-null inp but bogus inp_socket? */
    696 	if (inp == NULL || inp->inp_socket == NULL) {
    697 		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
    698 	} else
    699 		sp = ipsec_getpolicybysock(m, dir, IN4PCB_TO_PCB(inp), error);
    700 	if (sp == NULL) {
    701 		IPSEC_ASSERT(*error != 0,
    702 		    ("%s: getpolicy failed w/o error", __func__));
    703 		IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
    704 		return NULL;
    705 	}
    706 	IPSEC_ASSERT(*error == 0, ("%s: sp w/ error set to %u", __func__,
    707 	    *error));
    708 	switch (sp->policy) {
    709 	case IPSEC_POLICY_ENTRUST:
    710 	default:
    711 		printf("%s: invalid policy %u\n", __func__, sp->policy);
    712 		/* fall thru... */
    713 	case IPSEC_POLICY_DISCARD:
    714 		IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
    715 		*error = -EINVAL;	/* packet is discarded by caller */
    716 		break;
    717 	case IPSEC_POLICY_BYPASS:
    718 	case IPSEC_POLICY_NONE:
    719 		KEY_FREESP(&sp);
    720 		sp = NULL;		/* NB: force NULL result */
    721 		break;
    722 	case IPSEC_POLICY_IPSEC:
    723 		if (sp->req == NULL)	/* acquire an SA */
    724 			*error = key_spdacquire(sp);
    725 		break;
    726 	}
    727 	if (*error != 0) {
    728 		KEY_FREESP(&sp);
    729 		sp = NULL;
    730 		DPRINTF(("%s: done, error %d\n", __func__, *error));
    731 	}
    732 	return sp;
    733 }
    734 
    735 int
    736 ipsec4_output(struct mbuf *m, struct socket *so, int flags,
    737     struct secpolicy **sp_out, u_long *mtu, bool *natt_frag, bool *done)
    738 {
    739 	const struct ip *ip = mtod(m, const struct ip *);
    740 	struct secpolicy *sp = NULL;
    741 	struct inpcb *inp;
    742 	int error, s;
    743 
    744 	inp = (so && so->so_proto->pr_domain->dom_family == AF_INET) ?
    745 	    (struct inpcb *)so->so_pcb : NULL;
    746 
    747 	/*
    748 	 * Check the security policy (SP) for the packet and, if required,
    749 	 * do IPsec-related processing.  There are two cases here; the first
    750 	 * time a packet is sent through it will be untagged and handled by
    751 	 * ipsec4_checkpolicy().  If the packet is resubmitted to ip_output
    752 	 * (e.g. after AH, ESP, etc. processing), there will be a tag to
    753 	 * bypass the lookup and related policy checking.
    754 	 */
    755 	if (ipsec_outdone(m)) {
    756 		return 0;
    757 	}
    758 	s = splsoftnet();
    759 	if (inp && IPSEC_PCB_SKIP_IPSEC(inp->inp_sp, IPSEC_DIR_OUTBOUND)) {
    760 		splx(s);
    761 		return 0;
    762 	}
    763 	sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, inp);
    764 
    765 	/*
    766 	 * There are four return cases:
    767 	 *	sp != NULL			apply IPsec policy
    768 	 *	sp == NULL, error == 0		no IPsec handling needed
    769 	 *	sp == NULL, error == -EINVAL	discard packet w/o error
    770 	 *	sp == NULL, error != 0		discard packet, report error
    771 	 */
    772 	if (sp == NULL) {
    773 		splx(s);
    774 		if (error) {
    775 			/*
    776 			 * Hack: -EINVAL is used to signal that a packet
    777 			 * should be silently discarded.  This is typically
    778 			 * because we asked key management for an SA and
    779 			 * it was delayed (e.g. kicked up to IKE).
    780 			 */
    781 			if (error == -EINVAL)
    782 				error = 0;
    783 			m_freem(m);
    784 			*done = true;
    785 			return error;
    786 		}
    787 		/* No IPsec processing for this packet. */
    788 		return 0;
    789 	}
    790 	*sp_out = sp;
    791 
    792 	/*
    793 	 * NAT-T ESP fragmentation: do not do IPSec processing now,
    794 	 * we will do it on each fragmented packet.
    795 	 */
    796 	if (sp->req->sav && (sp->req->sav->natt_type &
    797 	    (UDP_ENCAP_ESPINUDP|UDP_ENCAP_ESPINUDP_NON_IKE))) {
    798 		if (ntohs(ip->ip_len) > sp->req->sav->esp_frag) {
    799 			*mtu = sp->req->sav->esp_frag;
    800 			*natt_frag = true;
    801 			splx(s);
    802 			return 0;
    803 		}
    804 	}
    805 
    806 	/*
    807 	 * Do delayed checksums now because we send before
    808 	 * this is done in the normal processing path.
    809 	 */
    810 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    811 		in_delayed_cksum(m);
    812 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    813 	}
    814 
    815 	/* Note: callee frees mbuf */
    816 	error = ipsec4_process_packet(m, sp->req, flags, 0);
    817 	/*
    818 	 * Preserve KAME behaviour: ENOENT can be returned
    819 	 * when an SA acquire is in progress.  Don't propagate
    820 	 * this to user-level; it confuses applications.
    821 	 *
    822 	 * XXX this will go away when the SADB is redone.
    823 	 */
    824 	if (error == ENOENT)
    825 		error = 0;
    826 	splx(s);
    827 	*done = true;
    828 	return error;
    829 }
    830 
    831 int
    832 ipsec4_input(struct mbuf *m, int flags)
    833 {
    834 	struct m_tag *mtag;
    835 	struct tdb_ident *tdbi;
    836 	struct secpolicy *sp;
    837 	int error, s;
    838 
    839 	/*
    840 	 * Check if the packet has already had IPsec processing done.
    841 	 * If so, then just pass it along.  This tag gets set during AH,
    842 	 * ESP, etc. input handling, before the packet is returned to
    843 	 * the IP input queue for delivery.
    844 	 */
    845 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
    846 	s = splsoftnet();
    847 	if (mtag != NULL) {
    848 		tdbi = (struct tdb_ident *)(mtag + 1);
    849 		sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
    850 	} else {
    851 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
    852 		    IP_FORWARDING, &error);
    853 	}
    854 	if (sp == NULL) {
    855 		splx(s);
    856 		return EINVAL;
    857 	}
    858 
    859 	/*
    860 	 * Check security policy against packet attributes.
    861 	 */
    862 	error = ipsec_in_reject(sp, m);
    863 	KEY_FREESP(&sp);
    864 	splx(s);
    865 	if (error) {
    866 		return error;
    867 	}
    868 
    869 	if (flags == 0) {
    870 		/* We are done. */
    871 		return 0;
    872 	}
    873 
    874 	/*
    875 	 * Peek at the outbound SP for this packet to determine if
    876 	 * it is a Fast Forward candidate.
    877 	 */
    878 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
    879 	if (mtag != NULL) {
    880 		m->m_flags &= ~M_CANFASTFWD;
    881 		return 0;
    882 	}
    883 
    884 	s = splsoftnet();
    885 	sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, NULL);
    886 	if (sp != NULL) {
    887 		m->m_flags &= ~M_CANFASTFWD;
    888 		KEY_FREESP(&sp);
    889 	}
    890 	splx(s);
    891 	return 0;
    892 }
    893 
    894 int
    895 ipsec4_forward(struct mbuf *m, int *destmtu)
    896 {
    897 	/*
    898 	 * If the packet is routed over IPsec tunnel, tell the
    899 	 * originator the tunnel MTU.
    900 	 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
    901 	 * XXX quickhack!!!
    902 	 */
    903 	struct secpolicy *sp;
    904 	size_t ipsechdr;
    905 	int error;
    906 
    907 	sp = ipsec4_getpolicybyaddr(m,
    908 	    IPSEC_DIR_OUTBOUND, IP_FORWARDING, &error);
    909 	if (sp == NULL) {
    910 		return EINVAL;
    911 	}
    912 
    913 	/* Count IPsec header size. */
    914 	ipsechdr = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, NULL);
    915 
    916 	/*
    917 	 * Find the correct route for outer IPv4 header, compute tunnel MTU.
    918 	 */
    919 	if (sp->req && sp->req->sav && sp->req->sav->sah) {
    920 		struct route *ro;
    921 		struct rtentry *rt;
    922 
    923 		ro = &sp->req->sav->sah->sa_route;
    924 		rt = rtcache_validate(ro);
    925 		if (rt && rt->rt_ifp) {
    926 			*destmtu = rt->rt_rmx.rmx_mtu ?
    927 			    rt->rt_rmx.rmx_mtu : rt->rt_ifp->if_mtu;
    928 			*destmtu -= ipsechdr;
    929 		}
    930 	}
    931 	KEY_FREESP(&sp);
    932 	return 0;
    933 }
    934 
    935 #ifdef INET6
    936 struct secpolicy *
    937 ipsec6_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
    938 	 	   struct in6pcb *in6p)
    939 {
    940 	struct secpolicy *sp;
    941 
    942 	*error = 0;
    943 
    944 
    945 	/* XXX KAME IPv6 calls us with non-null inp but bogus inp_socket? */
    946 	if (in6p == NULL || in6p->in6p_socket == NULL) {
    947 		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
    948 	} else
    949 		sp = ipsec_getpolicybysock(m, dir, IN6PCB_TO_PCB(in6p), error);
    950 	if (sp == NULL) {
    951 		IPSEC_ASSERT(*error != 0, ("%s: getpolicy failed w/o error",
    952 		    __func__));
    953 		IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
    954 		return NULL;
    955 	}
    956 	IPSEC_ASSERT(*error == 0, ("%s: sp w/ error set to %u", __func__,
    957 	    *error));
    958 	switch (sp->policy) {
    959 	case IPSEC_POLICY_ENTRUST:
    960 	default:
    961 		printf("%s: invalid policy %u\n", __func__, sp->policy);
    962 		/* fall thru... */
    963 	case IPSEC_POLICY_DISCARD:
    964 		IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
    965 		*error = -EINVAL;   /* packet is discarded by caller */
    966 		break;
    967 	case IPSEC_POLICY_BYPASS:
    968 	case IPSEC_POLICY_NONE:
    969 		KEY_FREESP(&sp);
    970 		sp = NULL;	  /* NB: force NULL result */
    971 		break;
    972 	case IPSEC_POLICY_IPSEC:
    973 		if (sp->req == NULL)	/* acquire an SA */
    974 			*error = key_spdacquire(sp);
    975 		break;
    976 	}
    977 	if (*error != 0) {
    978 		KEY_FREESP(&sp);
    979 		sp = NULL;
    980 		DPRINTF(("%s: done, error %d\n", __func__, *error));
    981 	}
    982 	return sp;
    983 }
    984 #endif /* INET6 */
    985 
    986 static int
    987 ipsec4_setspidx_inpcb(struct mbuf *m, struct inpcb *pcb)
    988 {
    989 	int error;
    990 
    991 	IPSEC_ASSERT(pcb != NULL, ("%s: null pcb", __func__));
    992 	IPSEC_ASSERT(pcb->inp_sp != NULL, ("%s: null inp_sp", __func__));
    993 	IPSEC_ASSERT(pcb->inp_sp->sp_out != NULL && pcb->inp_sp->sp_in != NULL,
    994 	    ("%s: null sp_in || sp_out", __func__));
    995 
    996 	error = ipsec_setspidx(m, &pcb->inp_sp->sp_in->spidx, 1);
    997 	if (error == 0) {
    998 		pcb->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
    999 		pcb->inp_sp->sp_out->spidx = pcb->inp_sp->sp_in->spidx;
   1000 		pcb->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
   1001 	} else {
   1002 		memset(&pcb->inp_sp->sp_in->spidx, 0,
   1003 			sizeof (pcb->inp_sp->sp_in->spidx));
   1004 		memset(&pcb->inp_sp->sp_out->spidx, 0,
   1005 			sizeof (pcb->inp_sp->sp_in->spidx));
   1006 	}
   1007 	return error;
   1008 }
   1009 
   1010 #ifdef INET6
   1011 static int
   1012 ipsec6_setspidx_in6pcb(struct mbuf *m, struct in6pcb *pcb)
   1013 {
   1014 	struct secpolicyindex *spidx;
   1015 	int error;
   1016 
   1017 	IPSEC_ASSERT(pcb != NULL, ("%s: null pcb", __func__));
   1018 	IPSEC_ASSERT(pcb->in6p_sp != NULL, ("%s: null inp_sp", __func__));
   1019 	IPSEC_ASSERT(pcb->in6p_sp->sp_out != NULL &&
   1020 	    pcb->in6p_sp->sp_in != NULL, ("%s: null sp_in || sp_out",
   1021 	    __func__));
   1022 
   1023 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
   1024 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
   1025 
   1026 	spidx = &pcb->in6p_sp->sp_in->spidx;
   1027 	error = ipsec_setspidx(m, spidx, 1);
   1028 	if (error)
   1029 		goto bad;
   1030 	spidx->dir = IPSEC_DIR_INBOUND;
   1031 
   1032 	spidx = &pcb->in6p_sp->sp_out->spidx;
   1033 	error = ipsec_setspidx(m, spidx, 1);
   1034 	if (error)
   1035 		goto bad;
   1036 	spidx->dir = IPSEC_DIR_OUTBOUND;
   1037 
   1038 	return 0;
   1039 
   1040 bad:
   1041 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
   1042 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
   1043 	return error;
   1044 }
   1045 #endif
   1046 
   1047 /*
   1048  * configure security policy index (src/dst/proto/sport/dport)
   1049  * by looking at the content of mbuf.
   1050  * the caller is responsible for error recovery (like clearing up spidx).
   1051  */
   1052 static int
   1053 ipsec_setspidx(struct mbuf *m, struct secpolicyindex *spidx, int needport)
   1054 {
   1055 	struct ip *ip = NULL;
   1056 	struct ip ipbuf;
   1057 	u_int v;
   1058 	struct mbuf *n;
   1059 	int len;
   1060 	int error;
   1061 
   1062 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
   1063 
   1064 	/*
   1065 	 * validate m->m_pkthdr.len.  we see incorrect length if we
   1066 	 * mistakenly call this function with inconsistent mbuf chain
   1067 	 * (like 4.4BSD tcp/udp processing).  XXX should we panic here?
   1068 	 */
   1069 	len = 0;
   1070 	for (n = m; n; n = n->m_next)
   1071 		len += n->m_len;
   1072 	if (m->m_pkthdr.len != len) {
   1073 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: total of m_len(%d) "
   1074 		    "!= pkthdr.len(%d), ignored.\n", __func__, len,
   1075 		    m->m_pkthdr.len));
   1076 		return EINVAL;
   1077 	}
   1078 
   1079 	if (m->m_pkthdr.len < sizeof(struct ip)) {
   1080 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: pkthdr.len(%d) < "
   1081 		    "sizeof(struct ip), ignored.\n", __func__,
   1082 		    m->m_pkthdr.len));
   1083 		return EINVAL;
   1084 	}
   1085 
   1086 	if (m->m_len >= sizeof(*ip))
   1087 		ip = mtod(m, struct ip *);
   1088 	else {
   1089 		m_copydata(m, 0, sizeof(ipbuf), &ipbuf);
   1090 		ip = &ipbuf;
   1091 	}
   1092 	v = ip->ip_v;
   1093 	switch (v) {
   1094 	case 4:
   1095 		error = ipsec4_setspidx_ipaddr(m, spidx);
   1096 		if (error)
   1097 			return error;
   1098 		ipsec4_get_ulp(m, spidx, needport);
   1099 		return 0;
   1100 #ifdef INET6
   1101 	case 6:
   1102 		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
   1103 			KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: "
   1104 			    "pkthdr.len(%d) < sizeof(struct ip6_hdr), "
   1105 			    "ignored.\n", __func__, m->m_pkthdr.len));
   1106 			return EINVAL;
   1107 		}
   1108 		error = ipsec6_setspidx_ipaddr(m, spidx);
   1109 		if (error)
   1110 			return error;
   1111 		ipsec6_get_ulp(m, spidx, needport);
   1112 		return 0;
   1113 #endif
   1114 	default:
   1115 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: unknown IP version "
   1116 		    "%u, ignored.\n", __func__, v));
   1117 		return EINVAL;
   1118 	}
   1119 }
   1120 
   1121 static void
   1122 ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
   1123 {
   1124 	u_int8_t nxt;
   1125 	int off;
   1126 
   1127 	/* sanity check */
   1128 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
   1129 	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),
   1130 	    ("%s: packet too short", __func__));
   1131 
   1132 	/* NB: ip_input() flips it into host endian XXX need more checking */
   1133 	if (m->m_len >= sizeof(struct ip)) {
   1134 		struct ip *ip = mtod(m, struct ip *);
   1135 		if (ip->ip_off & IP_OFF_CONVERT(IP_MF | IP_OFFMASK))
   1136 			goto done;
   1137 		off = ip->ip_hl << 2;
   1138 		nxt = ip->ip_p;
   1139 	} else {
   1140 		struct ip ih;
   1141 
   1142 		m_copydata(m, 0, sizeof (struct ip), &ih);
   1143 		if (ih.ip_off & IP_OFF_CONVERT(IP_MF | IP_OFFMASK))
   1144 			goto done;
   1145 		off = ih.ip_hl << 2;
   1146 		nxt = ih.ip_p;
   1147 	}
   1148 
   1149 	while (off < m->m_pkthdr.len) {
   1150 		struct ip6_ext ip6e;
   1151 		struct tcphdr th;
   1152 		struct udphdr uh;
   1153 		struct icmp icmph;
   1154 
   1155 		switch (nxt) {
   1156 		case IPPROTO_TCP:
   1157 			spidx->ul_proto = nxt;
   1158 			if (!needport)
   1159 				goto done_proto;
   1160 			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
   1161 				goto done;
   1162 			m_copydata(m, off, sizeof (th), &th);
   1163 			spidx->src.sin.sin_port = th.th_sport;
   1164 			spidx->dst.sin.sin_port = th.th_dport;
   1165 			return;
   1166 		case IPPROTO_UDP:
   1167 			spidx->ul_proto = nxt;
   1168 			if (!needport)
   1169 				goto done_proto;
   1170 			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
   1171 				goto done;
   1172 			m_copydata(m, off, sizeof (uh), &uh);
   1173 			spidx->src.sin.sin_port = uh.uh_sport;
   1174 			spidx->dst.sin.sin_port = uh.uh_dport;
   1175 			return;
   1176 		case IPPROTO_AH:
   1177 			if (m->m_pkthdr.len > off + sizeof(ip6e))
   1178 				goto done;
   1179 			/* XXX sigh, this works but is totally bogus */
   1180 			m_copydata(m, off, sizeof(ip6e), &ip6e);
   1181 			off += (ip6e.ip6e_len + 2) << 2;
   1182 			nxt = ip6e.ip6e_nxt;
   1183 			break;
   1184 		case IPPROTO_ICMP:
   1185 			spidx->ul_proto = nxt;
   1186 			if (off + sizeof(struct icmp) > m->m_pkthdr.len)
   1187 				return;
   1188 			m_copydata(m, off, sizeof(icmph), &icmph);
   1189 			((struct sockaddr_in *)&spidx->src)->sin_port =
   1190 			    htons((uint16_t)icmph.icmp_type);
   1191 			((struct sockaddr_in *)&spidx->dst)->sin_port =
   1192 			    htons((uint16_t)icmph.icmp_code);
   1193 			return;
   1194 		default:
   1195 			/* XXX intermediate headers??? */
   1196 			spidx->ul_proto = nxt;
   1197 			goto done_proto;
   1198 		}
   1199 	}
   1200 done:
   1201 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
   1202 done_proto:
   1203 	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
   1204 	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
   1205 }
   1206 
   1207 /* assumes that m is sane */
   1208 static int
   1209 ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
   1210 {
   1211 	static const struct sockaddr_in template = {
   1212 		sizeof (struct sockaddr_in),
   1213 		AF_INET,
   1214 		0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
   1215 	};
   1216 
   1217 	spidx->src.sin = template;
   1218 	spidx->dst.sin = template;
   1219 
   1220 	if (m->m_len < sizeof (struct ip)) {
   1221 		m_copydata(m, offsetof(struct ip, ip_src),
   1222 			   sizeof (struct  in_addr),
   1223 			   &spidx->src.sin.sin_addr);
   1224 		m_copydata(m, offsetof(struct ip, ip_dst),
   1225 			   sizeof (struct  in_addr),
   1226 			   &spidx->dst.sin.sin_addr);
   1227 	} else {
   1228 		struct ip *ip = mtod(m, struct ip *);
   1229 		spidx->src.sin.sin_addr = ip->ip_src;
   1230 		spidx->dst.sin.sin_addr = ip->ip_dst;
   1231 	}
   1232 
   1233 	spidx->prefs = sizeof(struct in_addr) << 3;
   1234 	spidx->prefd = sizeof(struct in_addr) << 3;
   1235 
   1236 	return 0;
   1237 }
   1238 
   1239 #ifdef INET6
   1240 static void
   1241 ipsec6_get_ulp(struct mbuf *m, struct secpolicyindex *spidx,
   1242 	       int needport)
   1243 {
   1244 	int off, nxt;
   1245 	struct tcphdr th;
   1246 	struct udphdr uh;
   1247 	struct icmp6_hdr icmph;
   1248 
   1249 	/* sanity check */
   1250 	if (m == NULL)
   1251 		panic("%s: NULL pointer was passed", __func__);
   1252 
   1253 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s:\n", __func__);
   1254 	    kdebug_mbuf(m));
   1255 
   1256 	/* set default */
   1257 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
   1258 	((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
   1259 	((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
   1260 
   1261 	nxt = -1;
   1262 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
   1263 	if (off < 0 || m->m_pkthdr.len < off)
   1264 		return;
   1265 
   1266 	switch (nxt) {
   1267 	case IPPROTO_TCP:
   1268 		spidx->ul_proto = nxt;
   1269 		if (!needport)
   1270 			break;
   1271 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
   1272 			break;
   1273 		m_copydata(m, off, sizeof(th), &th);
   1274 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
   1275 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
   1276 		break;
   1277 	case IPPROTO_UDP:
   1278 		spidx->ul_proto = nxt;
   1279 		if (!needport)
   1280 			break;
   1281 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
   1282 			break;
   1283 		m_copydata(m, off, sizeof(uh), &uh);
   1284 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
   1285 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
   1286 		break;
   1287 	case IPPROTO_ICMPV6:
   1288 		spidx->ul_proto = nxt;
   1289 		if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
   1290 			break;
   1291 		m_copydata(m, off, sizeof(icmph), &icmph);
   1292 		((struct sockaddr_in6 *)&spidx->src)->sin6_port =
   1293 		    htons((uint16_t)icmph.icmp6_type);
   1294 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port =
   1295 		    htons((uint16_t)icmph.icmp6_code);
   1296 		break;
   1297 	default:
   1298 		/* XXX intermediate headers??? */
   1299 		spidx->ul_proto = nxt;
   1300 		break;
   1301 	}
   1302 }
   1303 
   1304 /* assumes that m is sane */
   1305 static int
   1306 ipsec6_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
   1307 {
   1308 	struct ip6_hdr *ip6 = NULL;
   1309 	struct ip6_hdr ip6buf;
   1310 	struct sockaddr_in6 *sin6;
   1311 
   1312 	if (m->m_len >= sizeof(*ip6))
   1313 		ip6 = mtod(m, struct ip6_hdr *);
   1314 	else {
   1315 		m_copydata(m, 0, sizeof(ip6buf), &ip6buf);
   1316 		ip6 = &ip6buf;
   1317 	}
   1318 
   1319 	sin6 = (struct sockaddr_in6 *)&spidx->src;
   1320 	memset(sin6, 0, sizeof(*sin6));
   1321 	sin6->sin6_family = AF_INET6;
   1322 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   1323 	memcpy(&sin6->sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src));
   1324 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
   1325 		sin6->sin6_addr.s6_addr16[1] = 0;
   1326 		sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
   1327 	}
   1328 	spidx->prefs = sizeof(struct in6_addr) << 3;
   1329 
   1330 	sin6 = (struct sockaddr_in6 *)&spidx->dst;
   1331 	memset(sin6, 0, sizeof(*sin6));
   1332 	sin6->sin6_family = AF_INET6;
   1333 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   1334 	memcpy(&sin6->sin6_addr, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
   1335 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
   1336 		sin6->sin6_addr.s6_addr16[1] = 0;
   1337 		sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
   1338 	}
   1339 	spidx->prefd = sizeof(struct in6_addr) << 3;
   1340 
   1341 	return 0;
   1342 }
   1343 #endif
   1344 
   1345 static void
   1346 ipsec_delpcbpolicy(struct inpcbpolicy *p)
   1347 {
   1348 	free(p, M_SECA);
   1349 }
   1350 
   1351 /* initialize policy in PCB */
   1352 int
   1353 ipsec_init_policy(struct socket *so, struct inpcbpolicy **policy)
   1354 {
   1355 	struct inpcbpolicy *new;
   1356 
   1357 	/* sanity check. */
   1358 	if (so == NULL || policy == NULL)
   1359 		panic("%s: NULL pointer was passed", __func__);
   1360 
   1361 	new = malloc(sizeof(*new), M_SECA, M_NOWAIT|M_ZERO);
   1362 	if (new == NULL) {
   1363 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
   1364 		return ENOBUFS;
   1365 	}
   1366 
   1367 	if (IPSEC_PRIVILEGED_SO(so))
   1368 		new->priv = 1;
   1369 	else
   1370 		new->priv = 0;
   1371 
   1372 	if ((new->sp_in = KEY_NEWSP()) == NULL) {
   1373 		ipsec_delpcbpolicy(new);
   1374 		return ENOBUFS;
   1375 	}
   1376 	new->sp_in->state = IPSEC_SPSTATE_ALIVE;
   1377 	new->sp_in->policy = IPSEC_POLICY_ENTRUST;
   1378 
   1379 	if ((new->sp_out = KEY_NEWSP()) == NULL) {
   1380 		KEY_FREESP(&new->sp_in);
   1381 		ipsec_delpcbpolicy(new);
   1382 		return ENOBUFS;
   1383 	}
   1384 	new->sp_out->state = IPSEC_SPSTATE_ALIVE;
   1385 	new->sp_out->policy = IPSEC_POLICY_ENTRUST;
   1386 
   1387 	*policy = new;
   1388 
   1389 	return 0;
   1390 }
   1391 
   1392 /* copy old ipsec policy into new */
   1393 int
   1394 ipsec_copy_policy(const struct inpcbpolicy *old, struct inpcbpolicy *new)
   1395 {
   1396 	struct secpolicy *sp;
   1397 
   1398 	sp = ipsec_deepcopy_policy(old->sp_in);
   1399 	if (sp) {
   1400 		KEY_FREESP(&new->sp_in);
   1401 		new->sp_in = sp;
   1402 	} else
   1403 		return ENOBUFS;
   1404 
   1405 	sp = ipsec_deepcopy_policy(old->sp_out);
   1406 	if (sp) {
   1407 		KEY_FREESP(&new->sp_out);
   1408 		new->sp_out = sp;
   1409 	} else
   1410 		return ENOBUFS;
   1411 
   1412 	new->priv = old->priv;
   1413 
   1414 	return 0;
   1415 }
   1416 
   1417 /* deep-copy a policy in PCB */
   1418 static struct secpolicy *
   1419 ipsec_deepcopy_policy(const struct secpolicy *src)
   1420 {
   1421 	struct ipsecrequest *newchain = NULL;
   1422 	const struct ipsecrequest *p;
   1423 	struct ipsecrequest **q;
   1424 	struct ipsecrequest *r;
   1425 	struct secpolicy *dst;
   1426 
   1427 	if (src == NULL)
   1428 		return NULL;
   1429 	dst = KEY_NEWSP();
   1430 	if (dst == NULL)
   1431 		return NULL;
   1432 
   1433 	/*
   1434 	 * deep-copy IPsec request chain.  This is required since struct
   1435 	 * ipsecrequest is not reference counted.
   1436 	 */
   1437 	q = &newchain;
   1438 	for (p = src->req; p; p = p->next) {
   1439 		*q = malloc(sizeof(**q), M_SECA, M_NOWAIT|M_ZERO);
   1440 		if (*q == NULL)
   1441 			goto fail;
   1442 		(*q)->next = NULL;
   1443 
   1444 		(*q)->saidx.proto = p->saidx.proto;
   1445 		(*q)->saidx.mode = p->saidx.mode;
   1446 		(*q)->level = p->level;
   1447 		(*q)->saidx.reqid = p->saidx.reqid;
   1448 
   1449 		memcpy(&(*q)->saidx.src, &p->saidx.src, sizeof((*q)->saidx.src));
   1450 		memcpy(&(*q)->saidx.dst, &p->saidx.dst, sizeof((*q)->saidx.dst));
   1451 
   1452 		(*q)->sav = NULL;
   1453 		(*q)->sp = dst;
   1454 
   1455 		q = &((*q)->next);
   1456 	}
   1457 
   1458 	dst->req = newchain;
   1459 	dst->state = src->state;
   1460 	dst->policy = src->policy;
   1461 	/* do not touch the refcnt fields */
   1462 
   1463 	return dst;
   1464 
   1465 fail:
   1466 	for (q = &newchain; *q; q = &r) {
   1467 		r = (*q)->next;
   1468 		free(*q, M_SECA);
   1469 	}
   1470 	return NULL;
   1471 }
   1472 
   1473 /* set policy and ipsec request if present. */
   1474 static int
   1475 ipsec_set_policy(
   1476 	struct secpolicy **policy,
   1477 	int optname,
   1478 	const void *request,
   1479 	size_t len,
   1480 	kauth_cred_t cred
   1481 )
   1482 {
   1483 	const struct sadb_x_policy *xpl;
   1484 	struct secpolicy *newsp = NULL;
   1485 	int error;
   1486 
   1487 	/* sanity check. */
   1488 	if (policy == NULL || *policy == NULL || request == NULL)
   1489 		return EINVAL;
   1490 	if (len < sizeof(*xpl))
   1491 		return EINVAL;
   1492 	xpl = (const struct sadb_x_policy *)request;
   1493 
   1494 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: passed policy\n", __func__);
   1495 	    kdebug_sadb_x_policy((const struct sadb_ext *)xpl));
   1496 
   1497 	/* check policy type */
   1498 	/* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
   1499 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
   1500 	 || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
   1501 		return EINVAL;
   1502 
   1503 	/* check privileged socket */
   1504 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
   1505 		error = kauth_authorize_network(cred, KAUTH_NETWORK_IPSEC,
   1506 		    KAUTH_REQ_NETWORK_IPSEC_BYPASS, NULL, NULL, NULL);
   1507 		if (error)
   1508 			return (error);
   1509 	}
   1510 
   1511 	/* allocation new SP entry */
   1512 	if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
   1513 		return error;
   1514 
   1515 	newsp->state = IPSEC_SPSTATE_ALIVE;
   1516 
   1517 	/* clear old SP and set new SP */
   1518 	KEY_FREESP(policy);
   1519 	*policy = newsp;
   1520 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: new policy\n", __func__);
   1521 	    kdebug_secpolicy(newsp));
   1522 
   1523 	return 0;
   1524 }
   1525 
   1526 static int
   1527 ipsec_get_policy(struct secpolicy *policy, struct mbuf **mp)
   1528 {
   1529 
   1530 	/* sanity check. */
   1531 	if (policy == NULL || mp == NULL)
   1532 		return EINVAL;
   1533 
   1534 	*mp = key_sp2msg(policy);
   1535 	if (!*mp) {
   1536 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
   1537 		return ENOBUFS;
   1538 	}
   1539 
   1540 	(*mp)->m_type = MT_DATA;
   1541 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s:\n", __func__);
   1542 	    kdebug_mbuf(*mp));
   1543 
   1544 	return 0;
   1545 }
   1546 
   1547 int
   1548 ipsec4_set_policy(struct inpcb *inp, int optname, const void *request,
   1549 		  size_t len, kauth_cred_t cred)
   1550 {
   1551 	const struct sadb_x_policy *xpl;
   1552 	struct secpolicy **policy;
   1553 
   1554 	/* sanity check. */
   1555 	if (inp == NULL || request == NULL)
   1556 		return EINVAL;
   1557 	if (len < sizeof(*xpl))
   1558 		return EINVAL;
   1559 	xpl = (const struct sadb_x_policy *)request;
   1560 
   1561 	IPSEC_ASSERT(inp->inp_sp != NULL, ("%s: null inp->in_sp", __func__));
   1562 
   1563 	/* select direction */
   1564 	switch (xpl->sadb_x_policy_dir) {
   1565 	case IPSEC_DIR_INBOUND:
   1566 		policy = &inp->inp_sp->sp_in;
   1567 		break;
   1568 	case IPSEC_DIR_OUTBOUND:
   1569 		policy = &inp->inp_sp->sp_out;
   1570 		break;
   1571 	default:
   1572 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
   1573 		    xpl->sadb_x_policy_dir));
   1574 		return EINVAL;
   1575 	}
   1576 
   1577 	return ipsec_set_policy(policy, optname, request, len, cred);
   1578 }
   1579 
   1580 int
   1581 ipsec4_get_policy(struct inpcb *inp, const void *request, size_t len,
   1582 		  struct mbuf **mp)
   1583 {
   1584 	const struct sadb_x_policy *xpl;
   1585 	struct secpolicy *policy;
   1586 
   1587 	/* sanity check. */
   1588 	if (inp == NULL || request == NULL || mp == NULL)
   1589 		return EINVAL;
   1590 	IPSEC_ASSERT(inp->inp_sp != NULL, ("%s: null inp_sp", __func__));
   1591 	if (len < sizeof(*xpl))
   1592 		return EINVAL;
   1593 	xpl = (const struct sadb_x_policy *)request;
   1594 
   1595 	/* select direction */
   1596 	switch (xpl->sadb_x_policy_dir) {
   1597 	case IPSEC_DIR_INBOUND:
   1598 		policy = inp->inp_sp->sp_in;
   1599 		break;
   1600 	case IPSEC_DIR_OUTBOUND:
   1601 		policy = inp->inp_sp->sp_out;
   1602 		break;
   1603 	default:
   1604 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
   1605 		    xpl->sadb_x_policy_dir));
   1606 		return EINVAL;
   1607 	}
   1608 
   1609 	return ipsec_get_policy(policy, mp);
   1610 }
   1611 
   1612 /* delete policy in PCB */
   1613 int
   1614 ipsec4_delete_pcbpolicy(struct inpcb *inp)
   1615 {
   1616 	IPSEC_ASSERT(inp != NULL, ("%s: null inp", __func__));
   1617 
   1618 	if (inp->inp_sp == NULL)
   1619 		return 0;
   1620 
   1621 	if (inp->inp_sp->sp_in != NULL)
   1622 		KEY_FREESP(&inp->inp_sp->sp_in);
   1623 
   1624 	if (inp->inp_sp->sp_out != NULL)
   1625 		KEY_FREESP(&inp->inp_sp->sp_out);
   1626 
   1627 #ifdef __NetBSD__
   1628 	ipsec_invalpcbcache(inp->inp_sp, IPSEC_DIR_ANY);
   1629 #endif
   1630 
   1631 	ipsec_delpcbpolicy(inp->inp_sp);
   1632 	inp->inp_sp = NULL;
   1633 
   1634 	return 0;
   1635 }
   1636 
   1637 #ifdef INET6
   1638 int
   1639 ipsec6_set_policy(struct in6pcb *in6p, int optname, const void *request,
   1640 		  size_t len, kauth_cred_t cred)
   1641 {
   1642 	const struct sadb_x_policy *xpl;
   1643 	struct secpolicy **policy;
   1644 
   1645 	/* sanity check. */
   1646 	if (in6p == NULL || request == NULL)
   1647 		return EINVAL;
   1648 	if (len < sizeof(*xpl))
   1649 		return EINVAL;
   1650 	xpl = (const struct sadb_x_policy *)request;
   1651 
   1652 	/* select direction */
   1653 	switch (xpl->sadb_x_policy_dir) {
   1654 	case IPSEC_DIR_INBOUND:
   1655 		policy = &in6p->in6p_sp->sp_in;
   1656 		break;
   1657 	case IPSEC_DIR_OUTBOUND:
   1658 		policy = &in6p->in6p_sp->sp_out;
   1659 		break;
   1660 	default:
   1661 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
   1662 		    xpl->sadb_x_policy_dir));
   1663 		return EINVAL;
   1664 	}
   1665 
   1666 	return ipsec_set_policy(policy, optname, request, len, cred);
   1667 }
   1668 
   1669 int
   1670 ipsec6_get_policy(struct in6pcb *in6p, const void *request, size_t len,
   1671 		  struct mbuf **mp)
   1672 {
   1673 	const struct sadb_x_policy *xpl;
   1674 	struct secpolicy *policy;
   1675 
   1676 	/* sanity check. */
   1677 	if (in6p == NULL || request == NULL || mp == NULL)
   1678 		return EINVAL;
   1679 	IPSEC_ASSERT(in6p->in6p_sp != NULL, ("%s: null in6p_sp", __func__));
   1680 	if (len < sizeof(*xpl))
   1681 		return EINVAL;
   1682 	xpl = (const struct sadb_x_policy *)request;
   1683 
   1684 	/* select direction */
   1685 	switch (xpl->sadb_x_policy_dir) {
   1686 	case IPSEC_DIR_INBOUND:
   1687 		policy = in6p->in6p_sp->sp_in;
   1688 		break;
   1689 	case IPSEC_DIR_OUTBOUND:
   1690 		policy = in6p->in6p_sp->sp_out;
   1691 		break;
   1692 	default:
   1693 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
   1694 		    xpl->sadb_x_policy_dir));
   1695 		return EINVAL;
   1696 	}
   1697 
   1698 	return ipsec_get_policy(policy, mp);
   1699 }
   1700 
   1701 int
   1702 ipsec6_delete_pcbpolicy(struct in6pcb *in6p)
   1703 {
   1704 	IPSEC_ASSERT(in6p != NULL, ("%s: null in6p", __func__));
   1705 
   1706 	if (in6p->in6p_sp == NULL)
   1707 		return 0;
   1708 
   1709 	if (in6p->in6p_sp->sp_in != NULL)
   1710 		KEY_FREESP(&in6p->in6p_sp->sp_in);
   1711 
   1712 	if (in6p->in6p_sp->sp_out != NULL)
   1713 		KEY_FREESP(&in6p->in6p_sp->sp_out);
   1714 
   1715 #ifdef __NetBSD
   1716 	ipsec_invalpcbcache(in6p->in6p_sp, IPSEC_DIR_ANY);
   1717 #endif
   1718 
   1719 	ipsec_delpcbpolicy(in6p->in6p_sp);
   1720 	in6p->in6p_sp = NULL;
   1721 
   1722 	return 0;
   1723 }
   1724 #endif
   1725 
   1726 /*
   1727  * return current level.
   1728  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
   1729  */
   1730 u_int
   1731 ipsec_get_reqlevel(const struct ipsecrequest *isr)
   1732 {
   1733 	u_int level = 0;
   1734 	u_int esp_trans_deflev, esp_net_deflev;
   1735 	u_int ah_trans_deflev, ah_net_deflev;
   1736 
   1737 	IPSEC_ASSERT(isr != NULL && isr->sp != NULL, ("%s: null argument",
   1738 	    __func__));
   1739 	IPSEC_ASSERT(isr->sp->spidx.src.sa.sa_family ==
   1740 	    isr->sp->spidx.dst.sa.sa_family,
   1741 	    ("%s: af family mismatch, src %u, dst %u", __func__,
   1742 	    isr->sp->spidx.src.sa.sa_family, isr->sp->spidx.dst.sa.sa_family));
   1743 
   1744 /* XXX note that we have ipseclog() expanded here - code sync issue */
   1745 #define IPSEC_CHECK_DEFAULT(lev) 					\
   1746     (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE		\
   1747     && (lev) != IPSEC_LEVEL_UNIQUE) ?					\
   1748 	(ipsec_debug ? log(LOG_INFO, "fixed system default level " #lev \
   1749 	":%d->%d\n", (lev), IPSEC_LEVEL_REQUIRE) : 0),			\
   1750 	(lev) = IPSEC_LEVEL_REQUIRE, (lev)				\
   1751     : (lev))
   1752 
   1753 	/* set default level */
   1754 	switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
   1755 #ifdef INET
   1756 	case AF_INET:
   1757 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
   1758 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
   1759 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
   1760 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
   1761 		break;
   1762 #endif
   1763 #ifdef INET6
   1764 	case AF_INET6:
   1765 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
   1766 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
   1767 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
   1768 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
   1769 		break;
   1770 #endif /* INET6 */
   1771 	default:
   1772 		panic("%s: unknown af %u", __func__,
   1773 		    isr->sp->spidx.src.sa.sa_family);
   1774 	}
   1775 
   1776 #undef IPSEC_CHECK_DEFAULT
   1777 
   1778 	/* set level */
   1779 	switch (isr->level) {
   1780 	case IPSEC_LEVEL_DEFAULT:
   1781 		switch (isr->saidx.proto) {
   1782 		case IPPROTO_ESP:
   1783 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
   1784 				level = esp_net_deflev;
   1785 			else
   1786 				level = esp_trans_deflev;
   1787 			break;
   1788 		case IPPROTO_AH:
   1789 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
   1790 				level = ah_net_deflev;
   1791 			else
   1792 				level = ah_trans_deflev;
   1793 			break;
   1794 		case IPPROTO_IPCOMP:
   1795 			/*
   1796 			 * we don't really care, as IPcomp document says that
   1797 			 * we shouldn't compress small packets
   1798 			 */
   1799 			level = IPSEC_LEVEL_USE;
   1800 			break;
   1801 		default:
   1802 			panic("%s: Illegal protocol defined %u", __func__,
   1803 			    isr->saidx.proto);
   1804 		}
   1805 		break;
   1806 
   1807 	case IPSEC_LEVEL_USE:
   1808 	case IPSEC_LEVEL_REQUIRE:
   1809 		level = isr->level;
   1810 		break;
   1811 	case IPSEC_LEVEL_UNIQUE:
   1812 		level = IPSEC_LEVEL_REQUIRE;
   1813 		break;
   1814 
   1815 	default:
   1816 		panic("%s: Illegal IPsec level %u", __func__, isr->level);
   1817 	}
   1818 
   1819 	return level;
   1820 }
   1821 
   1822 /*
   1823  * Check security policy requirements against the actual
   1824  * packet contents.  Return one if the packet should be
   1825  * reject as "invalid"; otherwiser return zero to have the
   1826  * packet treated as "valid".
   1827  *
   1828  * OUT:
   1829  *	0: valid
   1830  *	1: invalid
   1831  */
   1832 int
   1833 ipsec_in_reject(const struct secpolicy *sp, const struct mbuf *m)
   1834 {
   1835 	struct ipsecrequest *isr;
   1836 	int need_auth;
   1837 
   1838 	KEYDEBUG(KEYDEBUG_IPSEC_DATA, printf("%s: using SP\n", __func__);
   1839 	    kdebug_secpolicy(sp));
   1840 
   1841 	/* check policy */
   1842 	switch (sp->policy) {
   1843 	case IPSEC_POLICY_DISCARD:
   1844 		return 1;
   1845 	case IPSEC_POLICY_BYPASS:
   1846 	case IPSEC_POLICY_NONE:
   1847 		return 0;
   1848 	}
   1849 
   1850 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
   1851 	    ("%s: invalid policy %u", __func__, sp->policy));
   1852 
   1853 	/* XXX should compare policy against ipsec header history */
   1854 
   1855 	need_auth = 0;
   1856 	for (isr = sp->req; isr != NULL; isr = isr->next) {
   1857 		if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
   1858 			continue;
   1859 		switch (isr->saidx.proto) {
   1860 		case IPPROTO_ESP:
   1861 			if ((m->m_flags & M_DECRYPTED) == 0) {
   1862 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
   1863 				    printf("%s: ESP m_flags:%x\n", __func__,
   1864 				    m->m_flags));
   1865 				return 1;
   1866 			}
   1867 
   1868 			if (!need_auth &&
   1869 				isr->sav != NULL &&
   1870 				isr->sav->tdb_authalgxform != NULL &&
   1871 				(m->m_flags & M_AUTHIPDGM) == 0) {
   1872 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
   1873 				    printf("%s: ESP/AH m_flags:%x\n", __func__,
   1874 				    m->m_flags));
   1875 				return 1;
   1876 			}
   1877 			break;
   1878 		case IPPROTO_AH:
   1879 			need_auth = 1;
   1880 			if ((m->m_flags & M_AUTHIPHDR) == 0) {
   1881 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
   1882 				    printf("%s: AH m_flags:%x\n", __func__,
   1883 				    m->m_flags));
   1884 				return 1;
   1885 			}
   1886 			break;
   1887 		case IPPROTO_IPCOMP:
   1888 			/*
   1889 			 * we don't really care, as IPcomp document
   1890 			 * says that we shouldn't compress small
   1891 			 * packets, IPComp policy should always be
   1892 			 * treated as being in "use" level.
   1893 			 */
   1894 			break;
   1895 		}
   1896 	}
   1897 	return 0;		/* valid */
   1898 }
   1899 
   1900 /*
   1901  * Check AH/ESP integrity.
   1902  * This function is called from tcp_input(), udp_input(),
   1903  * and {ah,esp}4_input for tunnel mode
   1904  */
   1905 int
   1906 ipsec4_in_reject(struct mbuf *m, struct inpcb *inp)
   1907 {
   1908 	struct secpolicy *sp;
   1909 	int error;
   1910 	int result;
   1911 
   1912 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
   1913 
   1914 	/* get SP for this packet.
   1915 	 * When we are called from ip_forward(), we call
   1916 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
   1917 	 */
   1918 	if (inp == NULL)
   1919 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
   1920 	else
   1921 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
   1922 					   IN4PCB_TO_PCB(inp), &error);
   1923 
   1924 	if (sp != NULL) {
   1925 		result = ipsec_in_reject(sp, m);
   1926 		if (result)
   1927 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
   1928 		KEY_FREESP(&sp);
   1929 	} else {
   1930 		result = 0;	/* XXX should be panic ?
   1931 				 * -> No, there may be error. */
   1932 	}
   1933 	return result;
   1934 }
   1935 
   1936 
   1937 #ifdef INET6
   1938 /*
   1939  * Check AH/ESP integrity.
   1940  * This function is called from tcp6_input(), udp6_input(),
   1941  * and {ah,esp}6_input for tunnel mode
   1942  */
   1943 int
   1944 ipsec6_in_reject(struct mbuf *m, struct in6pcb *in6p)
   1945 {
   1946 	struct secpolicy *sp = NULL;
   1947 	int error;
   1948 	int result;
   1949 
   1950 	/* sanity check */
   1951 	if (m == NULL)
   1952 		return 0;	/* XXX should be panic ? */
   1953 
   1954 	/* get SP for this packet.
   1955 	 * When we are called from ip_forward(), we call
   1956 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
   1957 	 */
   1958 	if (in6p == NULL)
   1959 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
   1960 	else
   1961 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
   1962 			IN6PCB_TO_PCB(in6p),
   1963 			&error);
   1964 
   1965 	if (sp != NULL) {
   1966 		result = ipsec_in_reject(sp, m);
   1967 		if (result)
   1968 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
   1969 		KEY_FREESP(&sp);
   1970 	} else {
   1971 		result = 0;
   1972 	}
   1973 	return result;
   1974 }
   1975 #endif
   1976 
   1977 /*
   1978  * compute the byte size to be occupied by IPsec header.
   1979  * in case it is tunneled, it includes the size of outer IP header.
   1980  * NOTE: SP passed is free in this function.
   1981  */
   1982 static size_t
   1983 ipsec_hdrsiz(const struct secpolicy *sp)
   1984 {
   1985 	const struct ipsecrequest *isr;
   1986 	size_t siz;
   1987 
   1988 	KEYDEBUG(KEYDEBUG_IPSEC_DATA, printf("%s: using SP\n", __func__);
   1989 	    kdebug_secpolicy(sp));
   1990 
   1991 	switch (sp->policy) {
   1992 	case IPSEC_POLICY_DISCARD:
   1993 	case IPSEC_POLICY_BYPASS:
   1994 	case IPSEC_POLICY_NONE:
   1995 		return 0;
   1996 	}
   1997 
   1998 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
   1999 	    ("%s: invalid policy %u", __func__, sp->policy));
   2000 
   2001 	siz = 0;
   2002 	for (isr = sp->req; isr != NULL; isr = isr->next) {
   2003 		size_t clen = 0;
   2004 
   2005 		switch (isr->saidx.proto) {
   2006 		case IPPROTO_ESP:
   2007 			clen = esp_hdrsiz(isr->sav);
   2008 			break;
   2009 		case IPPROTO_AH:
   2010 			clen = ah_hdrsiz(isr->sav);
   2011 			break;
   2012 		case IPPROTO_IPCOMP:
   2013 			clen = sizeof(struct ipcomp);
   2014 			break;
   2015 		}
   2016 
   2017 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
   2018 			switch (isr->saidx.dst.sa.sa_family) {
   2019 			case AF_INET:
   2020 				clen += sizeof(struct ip);
   2021 				break;
   2022 #ifdef INET6
   2023 			case AF_INET6:
   2024 				clen += sizeof(struct ip6_hdr);
   2025 				break;
   2026 #endif
   2027 			default:
   2028 				ipseclog((LOG_ERR, "%s: unknown AF %d in "
   2029 				    "IPsec tunnel SA\n", __func__,
   2030 				    ((const struct sockaddr *)&isr->saidx.dst)
   2031 				    ->sa_family));
   2032 				break;
   2033 			}
   2034 		}
   2035 		siz += clen;
   2036 	}
   2037 
   2038 	return siz;
   2039 }
   2040 
   2041 /* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
   2042 size_t
   2043 ipsec4_hdrsiz(struct mbuf *m, u_int dir, struct inpcb *inp)
   2044 {
   2045 	struct secpolicy *sp;
   2046 	int error;
   2047 	size_t size;
   2048 
   2049 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
   2050 	IPSEC_ASSERT(inp == NULL || inp->inp_socket != NULL,
   2051 	    ("%s: socket w/o inpcb", __func__));
   2052 
   2053 	/* get SP for this packet.
   2054 	 * When we are called from ip_forward(), we call
   2055 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
   2056 	 */
   2057 	if (inp == NULL)
   2058 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
   2059 	else
   2060 		sp = ipsec_getpolicybysock(m, dir,
   2061 					   IN4PCB_TO_PCB(inp), &error);
   2062 
   2063 	if (sp != NULL) {
   2064 		size = ipsec_hdrsiz(sp);
   2065 		KEYDEBUG(KEYDEBUG_IPSEC_DATA, printf("%s: size:%lu.\n",
   2066 		    __func__, (unsigned long)size));
   2067 
   2068 		KEY_FREESP(&sp);
   2069 	} else {
   2070 		size = 0;	/* XXX should be panic ? */
   2071 	}
   2072 	return size;
   2073 }
   2074 
   2075 #ifdef INET6
   2076 /* This function is called from ipsec6_hdrsize_tcp(),
   2077  * and maybe from ip6_forward.()
   2078  */
   2079 size_t
   2080 ipsec6_hdrsiz(struct mbuf *m, u_int dir, struct in6pcb *in6p)
   2081 {
   2082 	struct secpolicy *sp;
   2083 	int error;
   2084 	size_t size;
   2085 
   2086 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
   2087 	IPSEC_ASSERT(in6p == NULL || in6p->in6p_socket != NULL,
   2088 	    ("%s: socket w/o inpcb", __func__));
   2089 
   2090 	/* get SP for this packet */
   2091 	/* XXX Is it right to call with IP_FORWARDING. */
   2092 	if (in6p == NULL)
   2093 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
   2094 	else
   2095 		sp = ipsec_getpolicybysock(m, dir,
   2096 			IN6PCB_TO_PCB(in6p),
   2097 			&error);
   2098 
   2099 	if (sp == NULL)
   2100 		return 0;
   2101 	size = ipsec_hdrsiz(sp);
   2102 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
   2103 	    printf("%s: size:%zu.\n", __func__, size));
   2104 	KEY_FREESP(&sp);
   2105 
   2106 	return size;
   2107 }
   2108 #endif /*INET6*/
   2109 
   2110 /*
   2111  * Check the variable replay window.
   2112  * ipsec_chkreplay() performs replay check before ICV verification.
   2113  * ipsec_updatereplay() updates replay bitmap.  This must be called after
   2114  * ICV verification (it also performs replay check, which is usually done
   2115  * beforehand).
   2116  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
   2117  *
   2118  * based on RFC 2401.
   2119  */
   2120 int
   2121 ipsec_chkreplay(u_int32_t seq, const struct secasvar *sav)
   2122 {
   2123 	const struct secreplay *replay;
   2124 	u_int32_t diff;
   2125 	int fr;
   2126 	u_int32_t wsizeb;	/* constant: bits of window size */
   2127 	int frlast;		/* constant: last frame */
   2128 
   2129 	IPSEC_SPLASSERT_SOFTNET(__func__);
   2130 
   2131 	IPSEC_ASSERT(sav != NULL, ("%s: Null SA", __func__));
   2132 	IPSEC_ASSERT(sav->replay != NULL, ("%s: Null replay state", __func__));
   2133 
   2134 	replay = sav->replay;
   2135 
   2136 	if (replay->wsize == 0)
   2137 		return 1;	/* no need to check replay. */
   2138 
   2139 	/* constant */
   2140 	frlast = replay->wsize - 1;
   2141 	wsizeb = replay->wsize << 3;
   2142 
   2143 	/* sequence number of 0 is invalid */
   2144 	if (seq == 0)
   2145 		return 0;
   2146 
   2147 	/* first time is always okay */
   2148 	if (replay->count == 0)
   2149 		return 1;
   2150 
   2151 	if (seq > replay->lastseq) {
   2152 		/* larger sequences are okay */
   2153 		return 1;
   2154 	} else {
   2155 		/* seq is equal or less than lastseq. */
   2156 		diff = replay->lastseq - seq;
   2157 
   2158 		/* over range to check, i.e. too old or wrapped */
   2159 		if (diff >= wsizeb)
   2160 			return 0;
   2161 
   2162 		fr = frlast - diff / 8;
   2163 
   2164 		/* this packet already seen ? */
   2165 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
   2166 			return 0;
   2167 
   2168 		/* out of order but good */
   2169 		return 1;
   2170 	}
   2171 }
   2172 
   2173 /*
   2174  * check replay counter whether to update or not.
   2175  * OUT:	0:	OK
   2176  *	1:	NG
   2177  */
   2178 int
   2179 ipsec_updatereplay(u_int32_t seq, const struct secasvar *sav)
   2180 {
   2181 	struct secreplay *replay;
   2182 	u_int32_t diff;
   2183 	int fr;
   2184 	u_int32_t wsizeb;	/* constant: bits of window size */
   2185 	int frlast;		/* constant: last frame */
   2186 
   2187 	IPSEC_SPLASSERT_SOFTNET(__func__);
   2188 
   2189 	IPSEC_ASSERT(sav != NULL, ("%s: Null SA", __func__));
   2190 	IPSEC_ASSERT(sav->replay != NULL, ("%s: Null replay state", __func__));
   2191 
   2192 	replay = sav->replay;
   2193 
   2194 	if (replay->wsize == 0)
   2195 		goto ok;	/* no need to check replay. */
   2196 
   2197 	/* constant */
   2198 	frlast = replay->wsize - 1;
   2199 	wsizeb = replay->wsize << 3;
   2200 
   2201 	/* sequence number of 0 is invalid */
   2202 	if (seq == 0)
   2203 		return 1;
   2204 
   2205 	/* first time */
   2206 	if (replay->count == 0) {
   2207 		replay->lastseq = seq;
   2208 		memset(replay->bitmap, 0, replay->wsize);
   2209 		(replay->bitmap)[frlast] = 1;
   2210 		goto ok;
   2211 	}
   2212 
   2213 	if (seq > replay->lastseq) {
   2214 		/* seq is larger than lastseq. */
   2215 		diff = seq - replay->lastseq;
   2216 
   2217 		/* new larger sequence number */
   2218 		if (diff < wsizeb) {
   2219 			/* In window */
   2220 			/* set bit for this packet */
   2221 			vshiftl(replay->bitmap, diff, replay->wsize);
   2222 			(replay->bitmap)[frlast] |= 1;
   2223 		} else {
   2224 			/* this packet has a "way larger" */
   2225 			memset(replay->bitmap, 0, replay->wsize);
   2226 			(replay->bitmap)[frlast] = 1;
   2227 		}
   2228 		replay->lastseq = seq;
   2229 
   2230 		/* larger is good */
   2231 	} else {
   2232 		/* seq is equal or less than lastseq. */
   2233 		diff = replay->lastseq - seq;
   2234 
   2235 		/* over range to check, i.e. too old or wrapped */
   2236 		if (diff >= wsizeb)
   2237 			return 1;
   2238 
   2239 		fr = frlast - diff / 8;
   2240 
   2241 		/* this packet already seen ? */
   2242 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
   2243 			return 1;
   2244 
   2245 		/* mark as seen */
   2246 		(replay->bitmap)[fr] |= (1 << (diff % 8));
   2247 
   2248 		/* out of order but good */
   2249 	}
   2250 
   2251 ok:
   2252 	if (replay->count == ~0) {
   2253 
   2254 		/* set overflow flag */
   2255 		replay->overflow++;
   2256 
   2257 		/* don't increment, no more packets accepted */
   2258 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
   2259 			return 1;
   2260 
   2261 		ipseclog((LOG_WARNING, "replay counter made %d cycle. %s\n",
   2262 		    replay->overflow, ipsec_logsastr(sav)));
   2263 	}
   2264 
   2265 	replay->count++;
   2266 
   2267 	return 0;
   2268 }
   2269 
   2270 /*
   2271  * shift variable length bunffer to left.
   2272  * IN:	bitmap: pointer to the buffer
   2273  * 	nbit:	the number of to shift.
   2274  *	wsize:	buffer size (bytes).
   2275  */
   2276 static void
   2277 vshiftl(unsigned char *bitmap, int nbit, int wsize)
   2278 {
   2279 	int s, j, i;
   2280 	unsigned char over;
   2281 
   2282 	for (j = 0; j < nbit; j += 8) {
   2283 		s = (nbit - j < 8) ? (nbit - j): 8;
   2284 		bitmap[0] <<= s;
   2285 		for (i = 1; i < wsize; i++) {
   2286 			over = (bitmap[i] >> (8 - s));
   2287 			bitmap[i] <<= s;
   2288 			bitmap[i-1] |= over;
   2289 		}
   2290 	}
   2291 
   2292 	return;
   2293 }
   2294 
   2295 /* Return a printable string for the IPv4 address. */
   2296 static char *
   2297 inet_ntoa4(struct in_addr ina)
   2298 {
   2299 	static char buf[4][4 * sizeof "123" + 4];
   2300 	unsigned char *ucp = (unsigned char *) &ina;
   2301 	static int i = 3;
   2302 
   2303 	i = (i + 1) % 4;
   2304 	snprintf(buf[i], sizeof(buf[i]), "%d.%d.%d.%d",
   2305 		ucp[0] & 0xff, ucp[1] & 0xff, ucp[2] & 0xff, ucp[3] & 0xff);
   2306 	return (buf[i]);
   2307 }
   2308 
   2309 /* Return a printable string for the address. */
   2310 const char *
   2311 ipsec_address(const union sockaddr_union *sa)
   2312 {
   2313 	switch (sa->sa.sa_family) {
   2314 #if INET
   2315 	case AF_INET:
   2316 		return inet_ntoa4(sa->sin.sin_addr);
   2317 #endif /* INET */
   2318 
   2319 #if INET6
   2320 	case AF_INET6:
   2321 		return ip6_sprintf(&sa->sin6.sin6_addr);
   2322 #endif /* INET6 */
   2323 
   2324 	default:
   2325 		return "(unknown address family)";
   2326 	}
   2327 }
   2328 
   2329 const char *
   2330 ipsec_logsastr(const struct secasvar *sav)
   2331 {
   2332 	static char buf[256];
   2333 	char *p;
   2334 	const struct secasindex *saidx = &sav->sah->saidx;
   2335 
   2336 	IPSEC_ASSERT(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
   2337 	    ("%s: address family mismatch", __func__));
   2338 
   2339 	p = buf;
   2340 	snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
   2341 	while (p && *p)
   2342 		p++;
   2343 	/* NB: only use ipsec_address on one address at a time */
   2344 	snprintf(p, sizeof (buf) - (p - buf), "src=%s ",
   2345 		ipsec_address(&saidx->src));
   2346 	while (p && *p)
   2347 		p++;
   2348 	snprintf(p, sizeof (buf) - (p - buf), "dst=%s)",
   2349 		ipsec_address(&saidx->dst));
   2350 
   2351 	return buf;
   2352 }
   2353 
   2354 void
   2355 ipsec_dumpmbuf(struct mbuf *m)
   2356 {
   2357 	int totlen;
   2358 	int i;
   2359 	u_char *p;
   2360 
   2361 	totlen = 0;
   2362 	printf("---\n");
   2363 	while (m) {
   2364 		p = mtod(m, u_char *);
   2365 		for (i = 0; i < m->m_len; i++) {
   2366 			printf("%02x ", p[i]);
   2367 			totlen++;
   2368 			if (totlen % 16 == 0)
   2369 				printf("\n");
   2370 		}
   2371 		m = m->m_next;
   2372 	}
   2373 	if (totlen % 16 != 0)
   2374 		printf("\n");
   2375 	printf("---\n");
   2376 }
   2377 
   2378 #ifdef INET6
   2379 struct secpolicy *
   2380 ipsec6_check_policy(struct mbuf *m, const struct socket *so,
   2381 		    int flags, int *needipsecp, int *errorp)
   2382 {
   2383 	struct in6pcb *in6p = NULL;
   2384 	struct secpolicy *sp = NULL;
   2385 	int s;
   2386 	int error = 0;
   2387 	int needipsec = 0;
   2388 
   2389 	if (so != NULL && so->so_proto->pr_domain->dom_family == AF_INET6)
   2390 		in6p = sotoin6pcb(so);
   2391 
   2392 	if (!ipsec_outdone(m)) {
   2393 		s = splsoftnet();
   2394 		if (in6p != NULL &&
   2395 		    IPSEC_PCB_SKIP_IPSEC(in6p->in6p_sp, IPSEC_DIR_OUTBOUND)) {
   2396 			splx(s);
   2397 			goto skippolicycheck;
   2398 		}
   2399 		sp = ipsec6_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error,in6p);
   2400 
   2401 		/*
   2402 		 * There are four return cases:
   2403 		 *	sp != NULL			apply IPsec policy
   2404 		 *	sp == NULL, error == 0		no IPsec handling needed
   2405 		 *	sp == NULL, error == -EINVAL  discard packet w/o error
   2406 		 *	sp == NULL, error != 0		discard packet, report error
   2407 		 */
   2408 
   2409 		splx(s);
   2410 		if (sp == NULL) {
   2411 			/*
   2412 			 * Caller must check the error return to see if it needs to discard
   2413 			 * the packet.
   2414 			 */
   2415 			needipsec = 0;
   2416 		} else {
   2417 			needipsec = 1;
   2418 		}
   2419 	}
   2420 skippolicycheck:;
   2421 
   2422 	*errorp = error;
   2423 	*needipsecp = needipsec;
   2424 	return sp;
   2425 }
   2426 #endif
   2427 
   2428 
   2429 
   2430 /* XXX this stuff doesn't belong here... */
   2431 
   2432 static	struct xformsw *xforms = NULL;
   2433 
   2434 /*
   2435  * Register a transform; typically at system startup.
   2436  */
   2437 void
   2438 xform_register(struct xformsw *xsp)
   2439 {
   2440 	xsp->xf_next = xforms;
   2441 	xforms = xsp;
   2442 }
   2443 
   2444 /*
   2445  * Initialize transform support in an sav.
   2446  */
   2447 int
   2448 xform_init(struct secasvar *sav, int xftype)
   2449 {
   2450 	struct xformsw *xsp;
   2451 
   2452 	if (sav->tdb_xform != NULL)	/* previously initialized */
   2453 		return 0;
   2454 	for (xsp = xforms; xsp; xsp = xsp->xf_next)
   2455 		if (xsp->xf_type == xftype)
   2456 			return (*xsp->xf_init)(sav, xsp);
   2457 
   2458 	DPRINTF(("%s: no match for xform type %d\n", __func__, xftype));
   2459 	return EINVAL;
   2460 }
   2461 
   2462 void
   2463 nat_t_ports_get(struct mbuf *m, u_int16_t *dport, u_int16_t *sport) {
   2464 	struct m_tag *tag;
   2465 
   2466 	if ((tag = m_tag_find(m, PACKET_TAG_IPSEC_NAT_T_PORTS, NULL))) {
   2467 		*sport = ((u_int16_t *)(tag + 1))[0];
   2468 		*dport = ((u_int16_t *)(tag + 1))[1];
   2469 	} else
   2470 		*sport = *dport = 0;
   2471 }
   2472 
   2473 #ifdef __NetBSD__
   2474 /*
   2475  * XXXJRT This should be done as a protosw init call.
   2476  */
   2477 void
   2478 ipsec_attach(void)
   2479 {
   2480 
   2481 	ipsecstat_percpu = percpu_alloc(sizeof(uint64_t) * IPSEC_NSTATS);
   2482 
   2483 	ah_attach();
   2484 	esp_attach();
   2485 	ipcomp_attach();
   2486 	ipe4_attach();
   2487 #ifdef TCP_SIGNATURE
   2488 	tcpsignature_attach();
   2489 #endif
   2490 }
   2491 #endif	/* __NetBSD__ */
   2492