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