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