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