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