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