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