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