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