Home | History | Annotate | Line # | Download | only in netipsec
ipsec.c revision 1.103
      1 /*	$NetBSD: ipsec.c,v 1.103 2017/07/18 08:55: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.103 2017/07/18 08:55: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 	const struct ip *ip = mtod(m, const struct ip *);
    659 	struct secpolicy *sp = NULL;
    660 	int error, s;
    661 
    662 	/*
    663 	 * Check the security policy (SP) for the packet and, if required,
    664 	 * do IPsec-related processing.  There are two cases here; the first
    665 	 * time a packet is sent through it will be untagged and handled by
    666 	 * ipsec4_checkpolicy().  If the packet is resubmitted to ip_output
    667 	 * (e.g. after AH, ESP, etc. processing), there will be a tag to
    668 	 * bypass the lookup and related policy checking.
    669 	 */
    670 	if (ipsec_outdone(m)) {
    671 		return 0;
    672 	}
    673 	s = splsoftnet();
    674 	if (inp && ipsec_pcb_skip_ipsec(inp->inp_sp, IPSEC_DIR_OUTBOUND)) {
    675 		splx(s);
    676 		return 0;
    677 	}
    678 	sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, inp);
    679 
    680 	/*
    681 	 * There are four return cases:
    682 	 *	sp != NULL			apply IPsec policy
    683 	 *	sp == NULL, error == 0		no IPsec handling needed
    684 	 *	sp == NULL, error == -EINVAL	discard packet w/o error
    685 	 *	sp == NULL, error != 0		discard packet, report error
    686 	 */
    687 	if (sp == NULL) {
    688 		splx(s);
    689 		if (error) {
    690 			/*
    691 			 * Hack: -EINVAL is used to signal that a packet
    692 			 * should be silently discarded.  This is typically
    693 			 * because we asked key management for an SA and
    694 			 * it was delayed (e.g. kicked up to IKE).
    695 			 */
    696 			if (error == -EINVAL)
    697 				error = 0;
    698 			m_freem(m);
    699 			*done = true;
    700 			return error;
    701 		}
    702 		/* No IPsec processing for this packet. */
    703 		return 0;
    704 	}
    705 
    706 	/*
    707 	 * NAT-T ESP fragmentation: do not do IPSec processing now,
    708 	 * we will do it on each fragmented packet.
    709 	 */
    710 	if (sp->req->sav && (sp->req->sav->natt_type &
    711 	    (UDP_ENCAP_ESPINUDP|UDP_ENCAP_ESPINUDP_NON_IKE))) {
    712 		if (ntohs(ip->ip_len) > sp->req->sav->esp_frag) {
    713 			*mtu = sp->req->sav->esp_frag;
    714 			*natt_frag = true;
    715 			KEY_FREESP(&sp);
    716 			splx(s);
    717 			return 0;
    718 		}
    719 	}
    720 
    721 	/*
    722 	 * Do delayed checksums now because we send before
    723 	 * this is done in the normal processing path.
    724 	 */
    725 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    726 		in_delayed_cksum(m);
    727 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    728 	}
    729 
    730 	/* Note: callee frees mbuf */
    731 	error = ipsec4_process_packet(m, sp->req);
    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 	s = splsoftnet();
    791 	sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, NULL);
    792 	if (sp != NULL) {
    793 		m->m_flags &= ~M_CANFASTFWD;
    794 		KEY_FREESP(&sp);
    795 	}
    796 	splx(s);
    797 	return 0;
    798 }
    799 
    800 int
    801 ipsec4_forward(struct mbuf *m, int *destmtu)
    802 {
    803 	/*
    804 	 * If the packet is routed over IPsec tunnel, tell the
    805 	 * originator the tunnel MTU.
    806 	 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
    807 	 * XXX quickhack!!!
    808 	 */
    809 	struct secpolicy *sp;
    810 	size_t ipsechdr;
    811 	int error;
    812 
    813 	sp = ipsec4_getpolicybyaddr(m,
    814 	    IPSEC_DIR_OUTBOUND, IP_FORWARDING, &error);
    815 	if (sp == NULL) {
    816 		return EINVAL;
    817 	}
    818 
    819 	/* Count IPsec header size. */
    820 	ipsechdr = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, NULL);
    821 
    822 	/*
    823 	 * Find the correct route for outer IPv4 header, compute tunnel MTU.
    824 	 */
    825 	if (sp->req && sp->req->sav) {
    826 		struct route *ro;
    827 		struct rtentry *rt;
    828 
    829 		ro = &sp->req->sav->sah->sa_route;
    830 		rt = rtcache_validate(ro);
    831 		if (rt && rt->rt_ifp) {
    832 			*destmtu = rt->rt_rmx.rmx_mtu ?
    833 			    rt->rt_rmx.rmx_mtu : rt->rt_ifp->if_mtu;
    834 			*destmtu -= ipsechdr;
    835 		}
    836 		rtcache_unref(rt, ro);
    837 	}
    838 	KEY_FREESP(&sp);
    839 	return 0;
    840 }
    841 
    842 #ifdef INET6
    843 struct secpolicy *
    844 ipsec6_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
    845 	 	   struct in6pcb *in6p)
    846 {
    847 	struct secpolicy *sp;
    848 
    849 	*error = 0;
    850 
    851 	if (in6p == NULL) {
    852 		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
    853 	} else {
    854 		KASSERT(in6p->in6p_socket != NULL);
    855 		sp = ipsec_getpolicybysock(m, dir, (struct inpcb_hdr *)in6p, error);
    856 	}
    857 	if (sp == NULL) {
    858 		KASSERTMSG(*error != 0, "getpolicy failed w/o error");
    859 		IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
    860 		return NULL;
    861 	}
    862 	KASSERTMSG(*error == 0, "sp w/ error set to %u", *error);
    863 	switch (sp->policy) {
    864 	case IPSEC_POLICY_ENTRUST:
    865 	default:
    866 		printf("%s: invalid policy %u\n", __func__, sp->policy);
    867 		/* fall thru... */
    868 	case IPSEC_POLICY_DISCARD:
    869 		IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
    870 		*error = -EINVAL;   /* packet is discarded by caller */
    871 		break;
    872 	case IPSEC_POLICY_BYPASS:
    873 	case IPSEC_POLICY_NONE:
    874 		KEY_FREESP(&sp);
    875 		sp = NULL;	  /* NB: force NULL result */
    876 		break;
    877 	case IPSEC_POLICY_IPSEC:
    878 		KASSERT(sp->req != NULL);
    879 		break;
    880 	}
    881 	if (*error != 0) {
    882 		KEY_FREESP(&sp);
    883 		sp = NULL;
    884 		IPSECLOG(LOG_DEBUG, "done, error %d\n", *error);
    885 	}
    886 	return sp;
    887 }
    888 #endif /* INET6 */
    889 
    890 static int
    891 ipsec4_setspidx_inpcb(struct mbuf *m, struct inpcb *pcb)
    892 {
    893 	int error;
    894 
    895 	KASSERT(pcb != NULL);
    896 	KASSERT(pcb->inp_sp != NULL);
    897 	KASSERT(pcb->inp_sp->sp_out != NULL);
    898 	KASSERT(pcb->inp_sp->sp_in != NULL);
    899 
    900 	error = ipsec_setspidx(m, &pcb->inp_sp->sp_in->spidx, 1);
    901 	if (error == 0) {
    902 		pcb->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
    903 		pcb->inp_sp->sp_out->spidx = pcb->inp_sp->sp_in->spidx;
    904 		pcb->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
    905 	} else {
    906 		memset(&pcb->inp_sp->sp_in->spidx, 0,
    907 		    sizeof(pcb->inp_sp->sp_in->spidx));
    908 		memset(&pcb->inp_sp->sp_out->spidx, 0,
    909 		    sizeof(pcb->inp_sp->sp_in->spidx));
    910 	}
    911 	return error;
    912 }
    913 
    914 #ifdef INET6
    915 static int
    916 ipsec6_setspidx_in6pcb(struct mbuf *m, struct in6pcb *pcb)
    917 {
    918 	struct secpolicyindex *spidx;
    919 	int error;
    920 
    921 	KASSERT(pcb != NULL);
    922 	KASSERT(pcb->in6p_sp != NULL);
    923 	KASSERT(pcb->in6p_sp->sp_out != NULL);
    924 	KASSERT(pcb->in6p_sp->sp_in != NULL);
    925 
    926 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
    927 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
    928 
    929 	spidx = &pcb->in6p_sp->sp_in->spidx;
    930 	error = ipsec_setspidx(m, spidx, 1);
    931 	if (error)
    932 		goto bad;
    933 	spidx->dir = IPSEC_DIR_INBOUND;
    934 
    935 	spidx = &pcb->in6p_sp->sp_out->spidx;
    936 	error = ipsec_setspidx(m, spidx, 1);
    937 	if (error)
    938 		goto bad;
    939 	spidx->dir = IPSEC_DIR_OUTBOUND;
    940 
    941 	return 0;
    942 
    943 bad:
    944 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
    945 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
    946 	return error;
    947 }
    948 #endif
    949 
    950 /*
    951  * configure security policy index (src/dst/proto/sport/dport)
    952  * by looking at the content of mbuf.
    953  * the caller is responsible for error recovery (like clearing up spidx).
    954  */
    955 static int
    956 ipsec_setspidx(struct mbuf *m, struct secpolicyindex *spidx, int needport)
    957 {
    958 	struct ip *ip = NULL;
    959 	struct ip ipbuf;
    960 	u_int v;
    961 	struct mbuf *n;
    962 	int len;
    963 	int error;
    964 
    965 	KASSERT(m != NULL);
    966 
    967 	/*
    968 	 * validate m->m_pkthdr.len.  we see incorrect length if we
    969 	 * mistakenly call this function with inconsistent mbuf chain
    970 	 * (like 4.4BSD tcp/udp processing).  XXX should we panic here?
    971 	 */
    972 	len = 0;
    973 	for (n = m; n; n = n->m_next)
    974 		len += n->m_len;
    975 	if (m->m_pkthdr.len != len) {
    976 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
    977 		    "total of m_len(%d) != pkthdr.len(%d), ignored.\n",
    978 		    len, m->m_pkthdr.len);
    979 		return EINVAL;
    980 	}
    981 
    982 	if (m->m_pkthdr.len < sizeof(struct ip)) {
    983 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
    984 		    "pkthdr.len(%d) < sizeof(struct ip), ignored.\n",
    985 		    m->m_pkthdr.len);
    986 		return EINVAL;
    987 	}
    988 
    989 	if (m->m_len >= sizeof(*ip))
    990 		ip = mtod(m, struct ip *);
    991 	else {
    992 		m_copydata(m, 0, sizeof(ipbuf), &ipbuf);
    993 		ip = &ipbuf;
    994 	}
    995 	v = ip->ip_v;
    996 	switch (v) {
    997 	case 4:
    998 		error = ipsec4_setspidx_ipaddr(m, spidx);
    999 		if (error)
   1000 			return error;
   1001 		ipsec4_get_ulp(m, spidx, needport);
   1002 		return 0;
   1003 #ifdef INET6
   1004 	case 6:
   1005 		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
   1006 			KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1007 			    "pkthdr.len(%d) < sizeof(struct ip6_hdr), "
   1008 			    "ignored.\n", m->m_pkthdr.len);
   1009 			return EINVAL;
   1010 		}
   1011 		error = ipsec6_setspidx_ipaddr(m, spidx);
   1012 		if (error)
   1013 			return error;
   1014 		ipsec6_get_ulp(m, spidx, needport);
   1015 		return 0;
   1016 #endif
   1017 	default:
   1018 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1019 		    "unknown IP version %u, ignored.\n", v);
   1020 		return EINVAL;
   1021 	}
   1022 }
   1023 
   1024 static void
   1025 ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
   1026 {
   1027 	u_int8_t nxt;
   1028 	int off;
   1029 
   1030 	/* sanity check */
   1031 	KASSERT(m != NULL);
   1032 	KASSERTMSG(m->m_pkthdr.len >= sizeof(struct ip), "packet too short");
   1033 
   1034 	/* NB: ip_input() flips it into host endian XXX need more checking */
   1035 	if (m->m_len >= sizeof(struct ip)) {
   1036 		struct ip *ip = mtod(m, struct ip *);
   1037 		if (ip->ip_off & htons(IP_MF | IP_OFFMASK))
   1038 			goto done;
   1039 		off = ip->ip_hl << 2;
   1040 		nxt = ip->ip_p;
   1041 	} else {
   1042 		struct ip ih;
   1043 
   1044 		m_copydata(m, 0, sizeof (struct ip), &ih);
   1045 		if (ih.ip_off & htons(IP_MF | IP_OFFMASK))
   1046 			goto done;
   1047 		off = ih.ip_hl << 2;
   1048 		nxt = ih.ip_p;
   1049 	}
   1050 
   1051 	while (off < m->m_pkthdr.len) {
   1052 		struct ip6_ext ip6e;
   1053 		struct tcphdr th;
   1054 		struct udphdr uh;
   1055 		struct icmp icmph;
   1056 
   1057 		switch (nxt) {
   1058 		case IPPROTO_TCP:
   1059 			spidx->ul_proto = nxt;
   1060 			if (!needport)
   1061 				goto done_proto;
   1062 			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
   1063 				goto done;
   1064 			m_copydata(m, off, sizeof (th), &th);
   1065 			spidx->src.sin.sin_port = th.th_sport;
   1066 			spidx->dst.sin.sin_port = th.th_dport;
   1067 			return;
   1068 		case IPPROTO_UDP:
   1069 			spidx->ul_proto = nxt;
   1070 			if (!needport)
   1071 				goto done_proto;
   1072 			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
   1073 				goto done;
   1074 			m_copydata(m, off, sizeof (uh), &uh);
   1075 			spidx->src.sin.sin_port = uh.uh_sport;
   1076 			spidx->dst.sin.sin_port = uh.uh_dport;
   1077 			return;
   1078 		case IPPROTO_AH:
   1079 			if (m->m_pkthdr.len > off + sizeof(ip6e))
   1080 				goto done;
   1081 			/* XXX sigh, this works but is totally bogus */
   1082 			m_copydata(m, off, sizeof(ip6e), &ip6e);
   1083 			off += (ip6e.ip6e_len + 2) << 2;
   1084 			nxt = ip6e.ip6e_nxt;
   1085 			break;
   1086 		case IPPROTO_ICMP:
   1087 			spidx->ul_proto = nxt;
   1088 			if (off + sizeof(struct icmp) > m->m_pkthdr.len)
   1089 				return;
   1090 			m_copydata(m, off, sizeof(icmph), &icmph);
   1091 			((struct sockaddr_in *)&spidx->src)->sin_port =
   1092 			    htons((uint16_t)icmph.icmp_type);
   1093 			((struct sockaddr_in *)&spidx->dst)->sin_port =
   1094 			    htons((uint16_t)icmph.icmp_code);
   1095 			return;
   1096 		default:
   1097 			/* XXX intermediate headers??? */
   1098 			spidx->ul_proto = nxt;
   1099 			goto done_proto;
   1100 		}
   1101 	}
   1102 done:
   1103 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
   1104 done_proto:
   1105 	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
   1106 	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
   1107 }
   1108 
   1109 /* assumes that m is sane */
   1110 static int
   1111 ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
   1112 {
   1113 	static const struct sockaddr_in template = {
   1114 		sizeof (struct sockaddr_in),
   1115 		AF_INET,
   1116 		0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
   1117 	};
   1118 
   1119 	spidx->src.sin = template;
   1120 	spidx->dst.sin = template;
   1121 
   1122 	if (m->m_len < sizeof (struct ip)) {
   1123 		m_copydata(m, offsetof(struct ip, ip_src),
   1124 		    sizeof(struct in_addr), &spidx->src.sin.sin_addr);
   1125 		m_copydata(m, offsetof(struct ip, ip_dst),
   1126 		    sizeof(struct in_addr), &spidx->dst.sin.sin_addr);
   1127 	} else {
   1128 		struct ip *ip = mtod(m, struct ip *);
   1129 		spidx->src.sin.sin_addr = ip->ip_src;
   1130 		spidx->dst.sin.sin_addr = ip->ip_dst;
   1131 	}
   1132 
   1133 	spidx->prefs = sizeof(struct in_addr) << 3;
   1134 	spidx->prefd = sizeof(struct in_addr) << 3;
   1135 
   1136 	return 0;
   1137 }
   1138 
   1139 #ifdef INET6
   1140 static void
   1141 ipsec6_get_ulp(struct mbuf *m, struct secpolicyindex *spidx,
   1142 	       int needport)
   1143 {
   1144 	int off, nxt;
   1145 	struct tcphdr th;
   1146 	struct udphdr uh;
   1147 	struct icmp6_hdr icmph;
   1148 
   1149 	KASSERT(m != NULL);
   1150 
   1151 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1152 		printf("%s:\n", __func__);
   1153 		kdebug_mbuf(m);
   1154 	}
   1155 
   1156 	/* set default */
   1157 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
   1158 	((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
   1159 	((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
   1160 
   1161 	nxt = -1;
   1162 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
   1163 	if (off < 0 || m->m_pkthdr.len < off)
   1164 		return;
   1165 
   1166 	switch (nxt) {
   1167 	case IPPROTO_TCP:
   1168 		spidx->ul_proto = nxt;
   1169 		if (!needport)
   1170 			break;
   1171 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
   1172 			break;
   1173 		m_copydata(m, off, sizeof(th), &th);
   1174 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
   1175 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
   1176 		break;
   1177 	case IPPROTO_UDP:
   1178 		spidx->ul_proto = nxt;
   1179 		if (!needport)
   1180 			break;
   1181 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
   1182 			break;
   1183 		m_copydata(m, off, sizeof(uh), &uh);
   1184 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
   1185 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
   1186 		break;
   1187 	case IPPROTO_ICMPV6:
   1188 		spidx->ul_proto = nxt;
   1189 		if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
   1190 			break;
   1191 		m_copydata(m, off, sizeof(icmph), &icmph);
   1192 		((struct sockaddr_in6 *)&spidx->src)->sin6_port =
   1193 		    htons((uint16_t)icmph.icmp6_type);
   1194 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port =
   1195 		    htons((uint16_t)icmph.icmp6_code);
   1196 		break;
   1197 	default:
   1198 		/* XXX intermediate headers??? */
   1199 		spidx->ul_proto = nxt;
   1200 		break;
   1201 	}
   1202 }
   1203 
   1204 /* assumes that m is sane */
   1205 static int
   1206 ipsec6_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
   1207 {
   1208 	struct ip6_hdr *ip6 = NULL;
   1209 	struct ip6_hdr ip6buf;
   1210 	struct sockaddr_in6 *sin6;
   1211 
   1212 	if (m->m_len >= sizeof(*ip6))
   1213 		ip6 = mtod(m, struct ip6_hdr *);
   1214 	else {
   1215 		m_copydata(m, 0, sizeof(ip6buf), &ip6buf);
   1216 		ip6 = &ip6buf;
   1217 	}
   1218 
   1219 	sin6 = (struct sockaddr_in6 *)&spidx->src;
   1220 	memset(sin6, 0, sizeof(*sin6));
   1221 	sin6->sin6_family = AF_INET6;
   1222 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   1223 	memcpy(&sin6->sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src));
   1224 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
   1225 		sin6->sin6_addr.s6_addr16[1] = 0;
   1226 		sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
   1227 	}
   1228 	spidx->prefs = sizeof(struct in6_addr) << 3;
   1229 
   1230 	sin6 = (struct sockaddr_in6 *)&spidx->dst;
   1231 	memset(sin6, 0, sizeof(*sin6));
   1232 	sin6->sin6_family = AF_INET6;
   1233 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   1234 	memcpy(&sin6->sin6_addr, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
   1235 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
   1236 		sin6->sin6_addr.s6_addr16[1] = 0;
   1237 		sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
   1238 	}
   1239 	spidx->prefd = sizeof(struct in6_addr) << 3;
   1240 
   1241 	return 0;
   1242 }
   1243 #endif
   1244 
   1245 static void
   1246 ipsec_delpcbpolicy(struct inpcbpolicy *p)
   1247 {
   1248 
   1249 	kmem_intr_free(p, sizeof(*p));
   1250 }
   1251 
   1252 /* initialize policy in PCB */
   1253 int
   1254 ipsec_init_policy(struct socket *so, struct inpcbpolicy **policy)
   1255 {
   1256 	struct inpcbpolicy *new;
   1257 
   1258 	KASSERT(so != NULL);
   1259 	KASSERT(policy != NULL);
   1260 
   1261 	new = kmem_intr_zalloc(sizeof(*new), KM_NOSLEEP);
   1262 	if (new == NULL) {
   1263 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   1264 		return ENOBUFS;
   1265 	}
   1266 
   1267 	if (IPSEC_PRIVILEGED_SO(so))
   1268 		new->priv = 1;
   1269 	else
   1270 		new->priv = 0;
   1271 
   1272 	if ((new->sp_in = KEY_NEWSP()) == NULL) {
   1273 		ipsec_delpcbpolicy(new);
   1274 		return ENOBUFS;
   1275 	}
   1276 	new->sp_in->state = IPSEC_SPSTATE_ALIVE;
   1277 	new->sp_in->policy = IPSEC_POLICY_ENTRUST;
   1278 
   1279 	if ((new->sp_out = KEY_NEWSP()) == NULL) {
   1280 		KEY_FREESP(&new->sp_in);
   1281 		ipsec_delpcbpolicy(new);
   1282 		return ENOBUFS;
   1283 	}
   1284 	new->sp_out->state = IPSEC_SPSTATE_ALIVE;
   1285 	new->sp_out->policy = IPSEC_POLICY_ENTRUST;
   1286 
   1287 	*policy = new;
   1288 
   1289 	return 0;
   1290 }
   1291 
   1292 /* copy old ipsec policy into new */
   1293 int
   1294 ipsec_copy_policy(const struct inpcbpolicy *old, struct inpcbpolicy *new)
   1295 {
   1296 	struct secpolicy *sp;
   1297 
   1298 	sp = ipsec_deepcopy_policy(old->sp_in);
   1299 	if (sp) {
   1300 		KEY_FREESP(&new->sp_in);
   1301 		new->sp_in = sp;
   1302 	} else
   1303 		return ENOBUFS;
   1304 
   1305 	sp = ipsec_deepcopy_policy(old->sp_out);
   1306 	if (sp) {
   1307 		KEY_FREESP(&new->sp_out);
   1308 		new->sp_out = sp;
   1309 	} else
   1310 		return ENOBUFS;
   1311 
   1312 	new->priv = old->priv;
   1313 
   1314 	return 0;
   1315 }
   1316 
   1317 /* deep-copy a policy in PCB */
   1318 static struct secpolicy *
   1319 ipsec_deepcopy_policy(const struct secpolicy *src)
   1320 {
   1321 	struct ipsecrequest *newchain = NULL;
   1322 	const struct ipsecrequest *p;
   1323 	struct ipsecrequest **q;
   1324 	struct secpolicy *dst;
   1325 
   1326 	if (src == NULL)
   1327 		return NULL;
   1328 	dst = KEY_NEWSP();
   1329 	if (dst == NULL)
   1330 		return NULL;
   1331 
   1332 	/*
   1333 	 * deep-copy IPsec request chain.  This is required since struct
   1334 	 * ipsecrequest is not reference counted.
   1335 	 */
   1336 	q = &newchain;
   1337 	for (p = src->req; p; p = p->next) {
   1338 		*q = kmem_zalloc(sizeof(**q), KM_SLEEP);
   1339 		(*q)->next = NULL;
   1340 
   1341 		(*q)->saidx.proto = p->saidx.proto;
   1342 		(*q)->saidx.mode = p->saidx.mode;
   1343 		(*q)->level = p->level;
   1344 		(*q)->saidx.reqid = p->saidx.reqid;
   1345 
   1346 		memcpy(&(*q)->saidx.src, &p->saidx.src, sizeof((*q)->saidx.src));
   1347 		memcpy(&(*q)->saidx.dst, &p->saidx.dst, sizeof((*q)->saidx.dst));
   1348 
   1349 		(*q)->sav = NULL;
   1350 		(*q)->sp = dst;
   1351 
   1352 		q = &((*q)->next);
   1353 	}
   1354 
   1355 	dst->req = newchain;
   1356 	dst->state = src->state;
   1357 	dst->policy = src->policy;
   1358 	/* do not touch the refcnt fields */
   1359 
   1360 	return dst;
   1361 }
   1362 
   1363 /* set policy and ipsec request if present. */
   1364 static int
   1365 ipsec_set_policy(
   1366 	struct secpolicy **policy,
   1367 	int optname,
   1368 	const void *request,
   1369 	size_t len,
   1370 	kauth_cred_t cred
   1371 )
   1372 {
   1373 	const struct sadb_x_policy *xpl;
   1374 	struct secpolicy *newsp = NULL;
   1375 	int error;
   1376 
   1377 	KASSERT(!cpu_softintr_p());
   1378 
   1379 	/* sanity check. */
   1380 	if (policy == NULL || *policy == NULL || request == NULL)
   1381 		return EINVAL;
   1382 	if (len < sizeof(*xpl))
   1383 		return EINVAL;
   1384 	xpl = (const struct sadb_x_policy *)request;
   1385 
   1386 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1387 		printf("%s: passed policy\n", __func__);
   1388 		kdebug_sadb_x_policy((const struct sadb_ext *)xpl);
   1389 	}
   1390 
   1391 	/* check policy type */
   1392 	/* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
   1393 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
   1394 	 || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
   1395 		return EINVAL;
   1396 
   1397 	/* check privileged socket */
   1398 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
   1399 		error = kauth_authorize_network(cred, KAUTH_NETWORK_IPSEC,
   1400 		    KAUTH_REQ_NETWORK_IPSEC_BYPASS, NULL, NULL, NULL);
   1401 		if (error)
   1402 			return (error);
   1403 	}
   1404 
   1405 	/* allocation new SP entry */
   1406 	if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
   1407 		return error;
   1408 
   1409 	newsp->state = IPSEC_SPSTATE_ALIVE;
   1410 
   1411 	/* clear old SP and set new SP */
   1412 	KEY_FREESP(policy);
   1413 	*policy = newsp;
   1414 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1415 		printf("%s: new policy\n", __func__);
   1416 		kdebug_secpolicy(newsp);
   1417 	}
   1418 
   1419 	return 0;
   1420 }
   1421 
   1422 static int
   1423 ipsec_get_policy(struct secpolicy *policy, struct mbuf **mp)
   1424 {
   1425 
   1426 	/* sanity check. */
   1427 	if (policy == NULL || mp == NULL)
   1428 		return EINVAL;
   1429 
   1430 	*mp = key_sp2msg(policy);
   1431 	if (!*mp) {
   1432 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   1433 		return ENOBUFS;
   1434 	}
   1435 
   1436 	(*mp)->m_type = MT_DATA;
   1437 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1438 		printf("%s:\n", __func__);
   1439 		kdebug_mbuf(*mp);
   1440 	}
   1441 
   1442 	return 0;
   1443 }
   1444 
   1445 int
   1446 ipsec4_set_policy(struct inpcb *inp, int optname, const void *request,
   1447 		  size_t len, kauth_cred_t cred)
   1448 {
   1449 	const struct sadb_x_policy *xpl;
   1450 	struct secpolicy **policy;
   1451 
   1452 	KASSERT(!cpu_softintr_p());
   1453 
   1454 	/* sanity check. */
   1455 	if (inp == NULL || request == NULL)
   1456 		return EINVAL;
   1457 	if (len < sizeof(*xpl))
   1458 		return EINVAL;
   1459 	xpl = (const struct sadb_x_policy *)request;
   1460 
   1461 	KASSERT(inp->inp_sp != NULL);
   1462 
   1463 	/* select direction */
   1464 	switch (xpl->sadb_x_policy_dir) {
   1465 	case IPSEC_DIR_INBOUND:
   1466 		policy = &inp->inp_sp->sp_in;
   1467 		break;
   1468 	case IPSEC_DIR_OUTBOUND:
   1469 		policy = &inp->inp_sp->sp_out;
   1470 		break;
   1471 	default:
   1472 		IPSECLOG(LOG_ERR, "invalid direction=%u\n",
   1473 		    xpl->sadb_x_policy_dir);
   1474 		return EINVAL;
   1475 	}
   1476 
   1477 	return ipsec_set_policy(policy, optname, request, len, cred);
   1478 }
   1479 
   1480 int
   1481 ipsec4_get_policy(struct inpcb *inp, const void *request, size_t len,
   1482 		  struct mbuf **mp)
   1483 {
   1484 	const struct sadb_x_policy *xpl;
   1485 	struct secpolicy *policy;
   1486 
   1487 	/* sanity check. */
   1488 	if (inp == NULL || request == NULL || mp == NULL)
   1489 		return EINVAL;
   1490 	KASSERT(inp->inp_sp != NULL);
   1491 	if (len < sizeof(*xpl))
   1492 		return EINVAL;
   1493 	xpl = (const struct sadb_x_policy *)request;
   1494 
   1495 	/* select direction */
   1496 	switch (xpl->sadb_x_policy_dir) {
   1497 	case IPSEC_DIR_INBOUND:
   1498 		policy = inp->inp_sp->sp_in;
   1499 		break;
   1500 	case IPSEC_DIR_OUTBOUND:
   1501 		policy = inp->inp_sp->sp_out;
   1502 		break;
   1503 	default:
   1504 		IPSECLOG(LOG_ERR, "invalid direction=%u\n",
   1505 		    xpl->sadb_x_policy_dir);
   1506 		return EINVAL;
   1507 	}
   1508 
   1509 	return ipsec_get_policy(policy, mp);
   1510 }
   1511 
   1512 /* delete policy in PCB */
   1513 int
   1514 ipsec4_delete_pcbpolicy(struct inpcb *inp)
   1515 {
   1516 
   1517 	KASSERT(inp != NULL);
   1518 
   1519 	if (inp->inp_sp == NULL)
   1520 		return 0;
   1521 
   1522 	if (inp->inp_sp->sp_in != NULL)
   1523 		KEY_FREESP(&inp->inp_sp->sp_in);
   1524 
   1525 	if (inp->inp_sp->sp_out != NULL)
   1526 		KEY_FREESP(&inp->inp_sp->sp_out);
   1527 
   1528 	ipsec_invalpcbcache(inp->inp_sp, IPSEC_DIR_ANY);
   1529 
   1530 	ipsec_delpcbpolicy(inp->inp_sp);
   1531 	inp->inp_sp = NULL;
   1532 
   1533 	return 0;
   1534 }
   1535 
   1536 #ifdef INET6
   1537 int
   1538 ipsec6_set_policy(struct in6pcb *in6p, int optname, const void *request,
   1539 		  size_t len, kauth_cred_t cred)
   1540 {
   1541 	const struct sadb_x_policy *xpl;
   1542 	struct secpolicy **policy;
   1543 
   1544 	KASSERT(!cpu_softintr_p());
   1545 
   1546 	/* sanity check. */
   1547 	if (in6p == NULL || request == NULL)
   1548 		return EINVAL;
   1549 	if (len < sizeof(*xpl))
   1550 		return EINVAL;
   1551 	xpl = (const struct sadb_x_policy *)request;
   1552 
   1553 	/* select direction */
   1554 	switch (xpl->sadb_x_policy_dir) {
   1555 	case IPSEC_DIR_INBOUND:
   1556 		policy = &in6p->in6p_sp->sp_in;
   1557 		break;
   1558 	case IPSEC_DIR_OUTBOUND:
   1559 		policy = &in6p->in6p_sp->sp_out;
   1560 		break;
   1561 	default:
   1562 		IPSECLOG(LOG_ERR, "invalid direction=%u\n",
   1563 		    xpl->sadb_x_policy_dir);
   1564 		return EINVAL;
   1565 	}
   1566 
   1567 	return ipsec_set_policy(policy, optname, request, len, cred);
   1568 }
   1569 
   1570 int
   1571 ipsec6_get_policy(struct in6pcb *in6p, const void *request, size_t len,
   1572 		  struct mbuf **mp)
   1573 {
   1574 	const struct sadb_x_policy *xpl;
   1575 	struct secpolicy *policy;
   1576 
   1577 	/* sanity check. */
   1578 	if (in6p == NULL || request == NULL || mp == NULL)
   1579 		return EINVAL;
   1580 	KASSERT(in6p->in6p_sp != NULL);
   1581 	if (len < sizeof(*xpl))
   1582 		return EINVAL;
   1583 	xpl = (const struct sadb_x_policy *)request;
   1584 
   1585 	/* select direction */
   1586 	switch (xpl->sadb_x_policy_dir) {
   1587 	case IPSEC_DIR_INBOUND:
   1588 		policy = in6p->in6p_sp->sp_in;
   1589 		break;
   1590 	case IPSEC_DIR_OUTBOUND:
   1591 		policy = in6p->in6p_sp->sp_out;
   1592 		break;
   1593 	default:
   1594 		IPSECLOG(LOG_ERR, "invalid direction=%u\n",
   1595 		    xpl->sadb_x_policy_dir);
   1596 		return EINVAL;
   1597 	}
   1598 
   1599 	return ipsec_get_policy(policy, mp);
   1600 }
   1601 
   1602 int
   1603 ipsec6_delete_pcbpolicy(struct in6pcb *in6p)
   1604 {
   1605 
   1606 	KASSERT(in6p != NULL);
   1607 
   1608 	if (in6p->in6p_sp == NULL)
   1609 		return 0;
   1610 
   1611 	if (in6p->in6p_sp->sp_in != NULL)
   1612 		KEY_FREESP(&in6p->in6p_sp->sp_in);
   1613 
   1614 	if (in6p->in6p_sp->sp_out != NULL)
   1615 		KEY_FREESP(&in6p->in6p_sp->sp_out);
   1616 
   1617 	ipsec_invalpcbcache(in6p->in6p_sp, IPSEC_DIR_ANY);
   1618 
   1619 	ipsec_delpcbpolicy(in6p->in6p_sp);
   1620 	in6p->in6p_sp = NULL;
   1621 
   1622 	return 0;
   1623 }
   1624 #endif
   1625 
   1626 /*
   1627  * return current level.
   1628  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
   1629  */
   1630 u_int
   1631 ipsec_get_reqlevel(const struct ipsecrequest *isr)
   1632 {
   1633 	u_int level = 0;
   1634 	u_int esp_trans_deflev, esp_net_deflev;
   1635 	u_int ah_trans_deflev, ah_net_deflev;
   1636 
   1637 	KASSERT(isr != NULL);
   1638 	KASSERT(isr->sp != NULL);
   1639 	KASSERTMSG(
   1640 	    isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family,
   1641 	    "af family mismatch, src %u, dst %u",
   1642 	    isr->sp->spidx.src.sa.sa_family, isr->sp->spidx.dst.sa.sa_family);
   1643 
   1644 /* XXX note that we have ipseclog() expanded here - code sync issue */
   1645 #define IPSEC_CHECK_DEFAULT(lev) 					\
   1646     (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE		\
   1647     && (lev) != IPSEC_LEVEL_UNIQUE) ?					\
   1648 	(ipsec_debug ? log(LOG_INFO, "fixed system default level " #lev \
   1649 	":%d->%d\n", (lev), IPSEC_LEVEL_REQUIRE) : (void)0),		\
   1650 	(lev) = IPSEC_LEVEL_REQUIRE, (lev)				\
   1651     : (lev))
   1652 
   1653 	/* set default level */
   1654 	switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
   1655 #ifdef INET
   1656 	case AF_INET:
   1657 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
   1658 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
   1659 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
   1660 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
   1661 		break;
   1662 #endif
   1663 #ifdef INET6
   1664 	case AF_INET6:
   1665 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
   1666 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
   1667 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
   1668 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
   1669 		break;
   1670 #endif /* INET6 */
   1671 	default:
   1672 		panic("%s: unknown af %u", __func__,
   1673 		    isr->sp->spidx.src.sa.sa_family);
   1674 	}
   1675 
   1676 #undef IPSEC_CHECK_DEFAULT
   1677 
   1678 	/* set level */
   1679 	switch (isr->level) {
   1680 	case IPSEC_LEVEL_DEFAULT:
   1681 		switch (isr->saidx.proto) {
   1682 		case IPPROTO_ESP:
   1683 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
   1684 				level = esp_net_deflev;
   1685 			else
   1686 				level = esp_trans_deflev;
   1687 			break;
   1688 		case IPPROTO_AH:
   1689 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
   1690 				level = ah_net_deflev;
   1691 			else
   1692 				level = ah_trans_deflev;
   1693 			break;
   1694 		case IPPROTO_IPCOMP:
   1695 			/*
   1696 			 * we don't really care, as IPcomp document says that
   1697 			 * we shouldn't compress small packets
   1698 			 */
   1699 			level = IPSEC_LEVEL_USE;
   1700 			break;
   1701 		default:
   1702 			panic("%s: Illegal protocol defined %u", __func__,
   1703 			    isr->saidx.proto);
   1704 		}
   1705 		break;
   1706 
   1707 	case IPSEC_LEVEL_USE:
   1708 	case IPSEC_LEVEL_REQUIRE:
   1709 		level = isr->level;
   1710 		break;
   1711 	case IPSEC_LEVEL_UNIQUE:
   1712 		level = IPSEC_LEVEL_REQUIRE;
   1713 		break;
   1714 
   1715 	default:
   1716 		panic("%s: Illegal IPsec level %u", __func__, isr->level);
   1717 	}
   1718 
   1719 	return level;
   1720 }
   1721 
   1722 /*
   1723  * Check security policy requirements against the actual
   1724  * packet contents.  Return one if the packet should be
   1725  * reject as "invalid"; otherwiser return zero to have the
   1726  * packet treated as "valid".
   1727  *
   1728  * OUT:
   1729  *	0: valid
   1730  *	1: invalid
   1731  */
   1732 int
   1733 ipsec_in_reject(const struct secpolicy *sp, const struct mbuf *m)
   1734 {
   1735 	struct ipsecrequest *isr;
   1736 	int need_auth;
   1737 
   1738 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
   1739 		printf("%s: using SP\n", __func__);
   1740 		kdebug_secpolicy(sp);
   1741 	}
   1742 
   1743 	/* check policy */
   1744 	switch (sp->policy) {
   1745 	case IPSEC_POLICY_DISCARD:
   1746 		return 1;
   1747 	case IPSEC_POLICY_BYPASS:
   1748 	case IPSEC_POLICY_NONE:
   1749 		return 0;
   1750 	}
   1751 
   1752 	KASSERTMSG(sp->policy == IPSEC_POLICY_IPSEC,
   1753 	    "invalid policy %u", sp->policy);
   1754 
   1755 	/* XXX should compare policy against ipsec header history */
   1756 
   1757 	need_auth = 0;
   1758 	for (isr = sp->req; isr != NULL; isr = isr->next) {
   1759 		if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
   1760 			continue;
   1761 		switch (isr->saidx.proto) {
   1762 		case IPPROTO_ESP:
   1763 			if ((m->m_flags & M_DECRYPTED) == 0) {
   1764 				KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1765 				    "ESP m_flags:%x\n", m->m_flags);
   1766 				return 1;
   1767 			}
   1768 
   1769 			if (!need_auth &&
   1770 				isr->sav != NULL &&
   1771 				isr->sav->tdb_authalgxform != NULL &&
   1772 				(m->m_flags & M_AUTHIPDGM) == 0) {
   1773 				KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1774 				    "ESP/AH m_flags:%x\n", m->m_flags);
   1775 				return 1;
   1776 			}
   1777 			break;
   1778 		case IPPROTO_AH:
   1779 			need_auth = 1;
   1780 			if ((m->m_flags & M_AUTHIPHDR) == 0) {
   1781 				KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1782 				    "AH m_flags:%x\n", m->m_flags);
   1783 				return 1;
   1784 			}
   1785 			break;
   1786 		case IPPROTO_IPCOMP:
   1787 			/*
   1788 			 * we don't really care, as IPcomp document
   1789 			 * says that we shouldn't compress small
   1790 			 * packets, IPComp policy should always be
   1791 			 * treated as being in "use" level.
   1792 			 */
   1793 			break;
   1794 		}
   1795 	}
   1796 	return 0;		/* valid */
   1797 }
   1798 
   1799 /*
   1800  * Check AH/ESP integrity.
   1801  * This function is called from tcp_input(), udp_input(),
   1802  * and {ah,esp}4_input for tunnel mode
   1803  */
   1804 int
   1805 ipsec4_in_reject(struct mbuf *m, struct inpcb *inp)
   1806 {
   1807 	struct secpolicy *sp;
   1808 	int error;
   1809 	int result;
   1810 
   1811 	KASSERT(m != NULL);
   1812 
   1813 	/* get SP for this packet.
   1814 	 * When we are called from ip_forward(), we call
   1815 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
   1816 	 */
   1817 	if (inp == NULL)
   1818 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
   1819 	else
   1820 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
   1821 					   (struct inpcb_hdr *)inp, &error);
   1822 
   1823 	if (sp != NULL) {
   1824 		result = ipsec_in_reject(sp, m);
   1825 		if (result)
   1826 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
   1827 		KEY_FREESP(&sp);
   1828 	} else {
   1829 		result = 0;	/* XXX should be panic ?
   1830 				 * -> No, there may be error. */
   1831 	}
   1832 	return result;
   1833 }
   1834 
   1835 
   1836 #ifdef INET6
   1837 /*
   1838  * Check AH/ESP integrity.
   1839  * This function is called from tcp6_input(), udp6_input(),
   1840  * and {ah,esp}6_input for tunnel mode
   1841  */
   1842 int
   1843 ipsec6_in_reject(struct mbuf *m, struct in6pcb *in6p)
   1844 {
   1845 	struct secpolicy *sp = NULL;
   1846 	int error;
   1847 	int result;
   1848 
   1849 	KASSERT(m != NULL);
   1850 
   1851 	/* get SP for this packet.
   1852 	 * When we are called from ip_forward(), we call
   1853 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
   1854 	 */
   1855 	if (in6p == NULL)
   1856 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
   1857 	else
   1858 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
   1859 			(struct inpcb_hdr *)in6p,
   1860 			&error);
   1861 
   1862 	if (sp != NULL) {
   1863 		result = ipsec_in_reject(sp, m);
   1864 		if (result)
   1865 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
   1866 		KEY_FREESP(&sp);
   1867 	} else {
   1868 		result = 0;
   1869 	}
   1870 	return result;
   1871 }
   1872 #endif
   1873 
   1874 /*
   1875  * compute the byte size to be occupied by IPsec header.
   1876  * in case it is tunneled, it includes the size of outer IP header.
   1877  * NOTE: SP passed is free in this function.
   1878  */
   1879 static size_t
   1880 ipsec_hdrsiz(const struct secpolicy *sp)
   1881 {
   1882 	const struct ipsecrequest *isr;
   1883 	size_t siz;
   1884 
   1885 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
   1886 		printf("%s: using SP\n", __func__);
   1887 		kdebug_secpolicy(sp);
   1888 	}
   1889 
   1890 	switch (sp->policy) {
   1891 	case IPSEC_POLICY_DISCARD:
   1892 	case IPSEC_POLICY_BYPASS:
   1893 	case IPSEC_POLICY_NONE:
   1894 		return 0;
   1895 	}
   1896 
   1897 	KASSERTMSG(sp->policy == IPSEC_POLICY_IPSEC,
   1898 	    "invalid policy %u", sp->policy);
   1899 
   1900 	siz = 0;
   1901 	for (isr = sp->req; isr != NULL; isr = isr->next) {
   1902 		size_t clen = 0;
   1903 
   1904 		switch (isr->saidx.proto) {
   1905 		case IPPROTO_ESP:
   1906 			clen = esp_hdrsiz(isr->sav);
   1907 			break;
   1908 		case IPPROTO_AH:
   1909 			clen = ah_hdrsiz(isr->sav);
   1910 			break;
   1911 		case IPPROTO_IPCOMP:
   1912 			clen = sizeof(struct ipcomp);
   1913 			break;
   1914 		}
   1915 
   1916 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
   1917 			switch (isr->saidx.dst.sa.sa_family) {
   1918 			case AF_INET:
   1919 				clen += sizeof(struct ip);
   1920 				break;
   1921 #ifdef INET6
   1922 			case AF_INET6:
   1923 				clen += sizeof(struct ip6_hdr);
   1924 				break;
   1925 #endif
   1926 			default:
   1927 				IPSECLOG(LOG_ERR, "unknown AF %d in "
   1928 				    "IPsec tunnel SA\n",
   1929 				    ((const struct sockaddr *)&isr->saidx.dst)
   1930 				    ->sa_family);
   1931 				break;
   1932 			}
   1933 		}
   1934 		siz += clen;
   1935 	}
   1936 
   1937 	return siz;
   1938 }
   1939 
   1940 /* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
   1941 size_t
   1942 ipsec4_hdrsiz(struct mbuf *m, u_int dir, struct inpcb *inp)
   1943 {
   1944 	struct secpolicy *sp;
   1945 	int error;
   1946 	size_t size;
   1947 
   1948 	KASSERT(m != NULL);
   1949 	KASSERTMSG(inp == NULL || inp->inp_socket != NULL, "socket w/o inpcb");
   1950 
   1951 	/* get SP for this packet.
   1952 	 * When we are called from ip_forward(), we call
   1953 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
   1954 	 */
   1955 	if (inp == NULL)
   1956 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
   1957 	else
   1958 		sp = ipsec_getpolicybysock(m, dir,
   1959 					   (struct inpcb_hdr *)inp, &error);
   1960 
   1961 	if (sp != NULL) {
   1962 		size = ipsec_hdrsiz(sp);
   1963 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DATA, "size:%lu.\n",
   1964 		    (unsigned long)size);
   1965 
   1966 		KEY_FREESP(&sp);
   1967 	} else {
   1968 		size = 0;	/* XXX should be panic ? */
   1969 	}
   1970 	return size;
   1971 }
   1972 
   1973 #ifdef INET6
   1974 /* This function is called from ipsec6_hdrsize_tcp(),
   1975  * and maybe from ip6_forward.()
   1976  */
   1977 size_t
   1978 ipsec6_hdrsiz(struct mbuf *m, u_int dir, struct in6pcb *in6p)
   1979 {
   1980 	struct secpolicy *sp;
   1981 	int error;
   1982 	size_t size;
   1983 
   1984 	KASSERT(m != NULL);
   1985 	KASSERTMSG(in6p == NULL || in6p->in6p_socket != NULL,
   1986 	    "socket w/o inpcb");
   1987 
   1988 	/* get SP for this packet */
   1989 	/* XXX Is it right to call with IP_FORWARDING. */
   1990 	if (in6p == NULL)
   1991 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
   1992 	else
   1993 		sp = ipsec_getpolicybysock(m, dir,
   1994 			(struct inpcb_hdr *)in6p,
   1995 			&error);
   1996 
   1997 	if (sp == NULL)
   1998 		return 0;
   1999 	size = ipsec_hdrsiz(sp);
   2000 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DATA, "size:%zu.\n", size);
   2001 	KEY_FREESP(&sp);
   2002 
   2003 	return size;
   2004 }
   2005 #endif /*INET6*/
   2006 
   2007 /*
   2008  * Check the variable replay window.
   2009  * ipsec_chkreplay() performs replay check before ICV verification.
   2010  * ipsec_updatereplay() updates replay bitmap.  This must be called after
   2011  * ICV verification (it also performs replay check, which is usually done
   2012  * beforehand).
   2013  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
   2014  *
   2015  * based on RFC 2401.
   2016  */
   2017 int
   2018 ipsec_chkreplay(u_int32_t seq, const struct secasvar *sav)
   2019 {
   2020 	const struct secreplay *replay;
   2021 	u_int32_t diff;
   2022 	int fr;
   2023 	u_int32_t wsizeb;	/* constant: bits of window size */
   2024 	int frlast;		/* constant: last frame */
   2025 
   2026 	IPSEC_SPLASSERT_SOFTNET(__func__);
   2027 
   2028 	KASSERT(sav != NULL);
   2029 	KASSERT(sav->replay != NULL);
   2030 
   2031 	replay = sav->replay;
   2032 
   2033 	if (replay->wsize == 0)
   2034 		return 1;	/* no need to check replay. */
   2035 
   2036 	/* constant */
   2037 	frlast = replay->wsize - 1;
   2038 	wsizeb = replay->wsize << 3;
   2039 
   2040 	/* sequence number of 0 is invalid */
   2041 	if (seq == 0)
   2042 		return 0;
   2043 
   2044 	/* first time is always okay */
   2045 	if (replay->count == 0)
   2046 		return 1;
   2047 
   2048 	if (seq > replay->lastseq) {
   2049 		/* larger sequences are okay */
   2050 		return 1;
   2051 	} else {
   2052 		/* seq is equal or less than lastseq. */
   2053 		diff = replay->lastseq - seq;
   2054 
   2055 		/* over range to check, i.e. too old or wrapped */
   2056 		if (diff >= wsizeb)
   2057 			return 0;
   2058 
   2059 		fr = frlast - diff / 8;
   2060 
   2061 		/* this packet already seen ? */
   2062 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
   2063 			return 0;
   2064 
   2065 		/* out of order but good */
   2066 		return 1;
   2067 	}
   2068 }
   2069 
   2070 /*
   2071  * check replay counter whether to update or not.
   2072  * OUT:	0:	OK
   2073  *	1:	NG
   2074  */
   2075 int
   2076 ipsec_updatereplay(u_int32_t seq, const struct secasvar *sav)
   2077 {
   2078 	struct secreplay *replay;
   2079 	u_int32_t diff;
   2080 	int fr;
   2081 	u_int32_t wsizeb;	/* constant: bits of window size */
   2082 	int frlast;		/* constant: last frame */
   2083 	char buf[INET6_ADDRSTRLEN];
   2084 
   2085 	IPSEC_SPLASSERT_SOFTNET(__func__);
   2086 
   2087 	KASSERT(sav != NULL);
   2088 	KASSERT(sav->replay != NULL);
   2089 
   2090 	replay = sav->replay;
   2091 
   2092 	if (replay->wsize == 0)
   2093 		goto ok;	/* no need to check replay. */
   2094 
   2095 	/* constant */
   2096 	frlast = replay->wsize - 1;
   2097 	wsizeb = replay->wsize << 3;
   2098 
   2099 	/* sequence number of 0 is invalid */
   2100 	if (seq == 0)
   2101 		return 1;
   2102 
   2103 	/* first time */
   2104 	if (replay->count == 0) {
   2105 		replay->lastseq = seq;
   2106 		memset(replay->bitmap, 0, replay->wsize);
   2107 		(replay->bitmap)[frlast] = 1;
   2108 		goto ok;
   2109 	}
   2110 
   2111 	if (seq > replay->lastseq) {
   2112 		/* seq is larger than lastseq. */
   2113 		diff = seq - replay->lastseq;
   2114 
   2115 		/* new larger sequence number */
   2116 		if (diff < wsizeb) {
   2117 			/* In window */
   2118 			/* set bit for this packet */
   2119 			vshiftl(replay->bitmap, diff, replay->wsize);
   2120 			(replay->bitmap)[frlast] |= 1;
   2121 		} else {
   2122 			/* this packet has a "way larger" */
   2123 			memset(replay->bitmap, 0, replay->wsize);
   2124 			(replay->bitmap)[frlast] = 1;
   2125 		}
   2126 		replay->lastseq = seq;
   2127 
   2128 		/* larger is good */
   2129 	} else {
   2130 		/* seq is equal or less than lastseq. */
   2131 		diff = replay->lastseq - seq;
   2132 
   2133 		/* over range to check, i.e. too old or wrapped */
   2134 		if (diff >= wsizeb)
   2135 			return 1;
   2136 
   2137 		fr = frlast - diff / 8;
   2138 
   2139 		/* this packet already seen ? */
   2140 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
   2141 			return 1;
   2142 
   2143 		/* mark as seen */
   2144 		(replay->bitmap)[fr] |= (1 << (diff % 8));
   2145 
   2146 		/* out of order but good */
   2147 	}
   2148 
   2149 ok:
   2150 	if (replay->count == ~0) {
   2151 
   2152 		/* set overflow flag */
   2153 		replay->overflow++;
   2154 
   2155 		/* don't increment, no more packets accepted */
   2156 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
   2157 			return 1;
   2158 
   2159 		IPSECLOG(LOG_WARNING, "replay counter made %d cycle. %s\n",
   2160 		    replay->overflow, ipsec_logsastr(sav, buf, sizeof(buf)));
   2161 	}
   2162 
   2163 	replay->count++;
   2164 
   2165 	return 0;
   2166 }
   2167 
   2168 /*
   2169  * shift variable length bunffer to left.
   2170  * IN:	bitmap: pointer to the buffer
   2171  * 	nbit:	the number of to shift.
   2172  *	wsize:	buffer size (bytes).
   2173  */
   2174 static void
   2175 vshiftl(unsigned char *bitmap, int nbit, int wsize)
   2176 {
   2177 	int s, j, i;
   2178 	unsigned char over;
   2179 
   2180 	for (j = 0; j < nbit; j += 8) {
   2181 		s = (nbit - j < 8) ? (nbit - j): 8;
   2182 		bitmap[0] <<= s;
   2183 		for (i = 1; i < wsize; i++) {
   2184 			over = (bitmap[i] >> (8 - s));
   2185 			bitmap[i] <<= s;
   2186 			bitmap[i-1] |= over;
   2187 		}
   2188 	}
   2189 
   2190 	return;
   2191 }
   2192 
   2193 /* Return a printable string for the address. */
   2194 const char *
   2195 ipsec_address(const union sockaddr_union *sa, char *buf, size_t size)
   2196 {
   2197 	switch (sa->sa.sa_family) {
   2198 #if INET
   2199 	case AF_INET:
   2200 		in_print(buf, size, &sa->sin.sin_addr);
   2201 		return buf;
   2202 #endif /* INET */
   2203 
   2204 #if INET6
   2205 	case AF_INET6:
   2206 		in6_print(buf, size, &sa->sin6.sin6_addr);
   2207 		return buf;
   2208 #endif /* INET6 */
   2209 
   2210 	default:
   2211 		return "(unknown address family)";
   2212 	}
   2213 }
   2214 
   2215 const char *
   2216 ipsec_logsastr(const struct secasvar *sav, char *buf, size_t size)
   2217 {
   2218 	const struct secasindex *saidx = &sav->sah->saidx;
   2219 	char sbuf[IPSEC_ADDRSTRLEN], dbuf[IPSEC_ADDRSTRLEN];
   2220 
   2221 	KASSERTMSG(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
   2222 	    "af family mismatch, src %u, dst %u",
   2223 	    saidx->src.sa.sa_family, saidx->dst.sa.sa_family);
   2224 
   2225 	snprintf(buf, size, "SA(SPI=%u src=%s dst=%s)",
   2226 	    (u_int32_t)ntohl(sav->spi),
   2227 	    ipsec_address(&saidx->src, sbuf, sizeof(sbuf)),
   2228 	    ipsec_address(&saidx->dst, dbuf, sizeof(dbuf)));
   2229 
   2230 	return buf;
   2231 }
   2232 
   2233 void
   2234 ipsec_dumpmbuf(struct mbuf *m)
   2235 {
   2236 	int totlen;
   2237 	int i;
   2238 	u_char *p;
   2239 
   2240 	totlen = 0;
   2241 	printf("---\n");
   2242 	while (m) {
   2243 		p = mtod(m, u_char *);
   2244 		for (i = 0; i < m->m_len; i++) {
   2245 			printf("%02x ", p[i]);
   2246 			totlen++;
   2247 			if (totlen % 16 == 0)
   2248 				printf("\n");
   2249 		}
   2250 		m = m->m_next;
   2251 	}
   2252 	if (totlen % 16 != 0)
   2253 		printf("\n");
   2254 	printf("---\n");
   2255 }
   2256 
   2257 #ifdef INET6
   2258 struct secpolicy *
   2259 ipsec6_check_policy(struct mbuf *m, struct in6pcb *in6p,
   2260 		    int flags, int *needipsecp, int *errorp)
   2261 {
   2262 	struct secpolicy *sp = NULL;
   2263 	int s;
   2264 	int error = 0;
   2265 	int needipsec = 0;
   2266 
   2267 	if (!ipsec_outdone(m)) {
   2268 		s = splsoftnet();
   2269 		if (in6p != NULL &&
   2270 		    ipsec_pcb_skip_ipsec(in6p->in6p_sp, IPSEC_DIR_OUTBOUND)) {
   2271 			splx(s);
   2272 			goto skippolicycheck;
   2273 		}
   2274 		sp = ipsec6_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error,in6p);
   2275 
   2276 		/*
   2277 		 * There are four return cases:
   2278 		 *	sp != NULL			apply IPsec policy
   2279 		 *	sp == NULL, error == 0		no IPsec handling needed
   2280 		 *	sp == NULL, error == -EINVAL  discard packet w/o error
   2281 		 *	sp == NULL, error != 0		discard packet, report error
   2282 		 */
   2283 
   2284 		splx(s);
   2285 		if (sp == NULL) {
   2286 			/*
   2287 			 * Caller must check the error return to see if it needs to discard
   2288 			 * the packet.
   2289 			 */
   2290 			needipsec = 0;
   2291 		} else {
   2292 			needipsec = 1;
   2293 		}
   2294 	}
   2295 skippolicycheck:;
   2296 
   2297 	*errorp = error;
   2298 	*needipsecp = needipsec;
   2299 	return sp;
   2300 }
   2301 
   2302 int
   2303 ipsec6_input(struct mbuf *m)
   2304 {
   2305 	struct m_tag *mtag;
   2306 	struct tdb_ident *tdbi;
   2307 	struct secpolicy *sp;
   2308 	int s, error;
   2309 
   2310 	/*
   2311 	 * Check if the packet has already had IPsec
   2312 	 * processing done. If so, then just pass it
   2313 	 * along. This tag gets set during AH, ESP,
   2314 	 * etc. input handling, before the packet is
   2315 	 * returned to the ip input queue for delivery.
   2316 	 */
   2317 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE,
   2318 	    NULL);
   2319 	s = splsoftnet();
   2320 	if (mtag != NULL) {
   2321 		tdbi = (struct tdb_ident *)(mtag + 1);
   2322 		sp = ipsec_getpolicy(tdbi,
   2323 		    IPSEC_DIR_INBOUND);
   2324 	} else {
   2325 		sp = ipsec_getpolicybyaddr(m,
   2326 		    IPSEC_DIR_INBOUND, IP_FORWARDING,
   2327 		    &error);
   2328 	}
   2329 	if (sp != NULL) {
   2330 		/*
   2331 		 * Check security policy against packet
   2332 		 * attributes.
   2333 		 */
   2334 		error = ipsec_in_reject(sp, m);
   2335 		KEY_FREESP(&sp);
   2336 	} else {
   2337 		/* XXX error stat??? */
   2338 		error = EINVAL;
   2339 		IPSECLOG(LOG_DEBUG, "no SP, packet discarded\n");/*XXX*/
   2340 	}
   2341 	splx(s);
   2342 
   2343 	return error;
   2344 }
   2345 #endif /* INET6 */
   2346 
   2347 
   2348 
   2349 /* XXX this stuff doesn't belong here... */
   2350 
   2351 static	struct xformsw *xforms = NULL;
   2352 
   2353 /*
   2354  * Register a transform; typically at system startup.
   2355  */
   2356 void
   2357 xform_register(struct xformsw *xsp)
   2358 {
   2359 	xsp->xf_next = xforms;
   2360 	xforms = xsp;
   2361 }
   2362 
   2363 /*
   2364  * Initialize transform support in an sav.
   2365  */
   2366 int
   2367 xform_init(struct secasvar *sav, int xftype)
   2368 {
   2369 	struct xformsw *xsp;
   2370 
   2371 	if (sav->tdb_xform != NULL)	/* previously initialized */
   2372 		return 0;
   2373 	for (xsp = xforms; xsp; xsp = xsp->xf_next)
   2374 		if (xsp->xf_type == xftype)
   2375 			return (*xsp->xf_init)(sav, xsp);
   2376 
   2377 	IPSECLOG(LOG_DEBUG, "no match for xform type %d\n", xftype);
   2378 	return EINVAL;
   2379 }
   2380 
   2381 void
   2382 nat_t_ports_get(struct mbuf *m, u_int16_t *dport, u_int16_t *sport) {
   2383 	struct m_tag *tag;
   2384 
   2385 	if ((tag = m_tag_find(m, PACKET_TAG_IPSEC_NAT_T_PORTS, NULL))) {
   2386 		*sport = ((u_int16_t *)(tag + 1))[0];
   2387 		*dport = ((u_int16_t *)(tag + 1))[1];
   2388 	} else
   2389 		*sport = *dport = 0;
   2390 }
   2391 
   2392 /*
   2393  * XXXJRT This should be done as a protosw init call.
   2394  */
   2395 void
   2396 ipsec_attach(void)
   2397 {
   2398 
   2399 	ipsecstat_percpu = percpu_alloc(sizeof(uint64_t) * IPSEC_NSTATS);
   2400 
   2401 	sysctl_net_inet_ipsec_setup(NULL);
   2402 #ifdef INET6
   2403 	sysctl_net_inet6_ipsec6_setup(NULL);
   2404 #endif
   2405 
   2406 	ah_attach();
   2407 	esp_attach();
   2408 	ipcomp_attach();
   2409 	ipe4_attach();
   2410 #ifdef TCP_SIGNATURE
   2411 	tcpsignature_attach();
   2412 #endif
   2413 }
   2414