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