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