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