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