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