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