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