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