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