Home | History | Annotate | Line # | Download | only in netipsec
ipsec.c revision 1.146
      1 /* $NetBSD: ipsec.c,v 1.146 2018/02/27 15:01:30 maxv Exp $ */
      2 /* $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.146 2018/02/27 15:01:30 maxv Exp $");
     36 
     37 /*
     38  * IPsec controller part.
     39  */
     40 
     41 #if defined(_KERNEL_OPT)
     42 #include "opt_inet.h"
     43 #include "opt_ipsec.h"
     44 #endif
     45 
     46 #include <sys/param.h>
     47 #include <sys/systm.h>
     48 #include <sys/mbuf.h>
     49 #include <sys/domain.h>
     50 #include <sys/protosw.h>
     51 #include <sys/socket.h>
     52 #include <sys/socketvar.h>
     53 #include <sys/errno.h>
     54 #include <sys/time.h>
     55 #include <sys/kernel.h>
     56 #include <sys/syslog.h>
     57 #include <sys/sysctl.h>
     58 #include <sys/proc.h>
     59 #include <sys/kauth.h>
     60 #include <sys/cpu.h>
     61 #include <sys/kmem.h>
     62 #include <sys/pserialize.h>
     63 
     64 #include <net/if.h>
     65 #include <net/route.h>
     66 
     67 #include <netinet/in.h>
     68 #include <netinet/in_systm.h>
     69 #include <netinet/ip.h>
     70 #include <netinet/ip_var.h>
     71 #include <netinet/in_var.h>
     72 #include <netinet/udp.h>
     73 #include <netinet/udp_var.h>
     74 #include <netinet/tcp.h>
     75 #include <netinet/udp.h>
     76 #include <netinet/ip_icmp.h>
     77 #include <netinet/ip_private.h>
     78 
     79 #include <netinet/ip6.h>
     80 #ifdef INET6
     81 #include <netinet6/ip6_var.h>
     82 #endif
     83 #include <netinet/in_pcb.h>
     84 #ifdef INET6
     85 #include <netinet6/in6_pcb.h>
     86 #include <netinet/icmp6.h>
     87 #endif
     88 
     89 #include <netipsec/ipsec.h>
     90 #include <netipsec/ipsec_var.h>
     91 #include <netipsec/ipsec_private.h>
     92 #ifdef INET6
     93 #include <netipsec/ipsec6.h>
     94 #endif
     95 #include <netipsec/ah_var.h>
     96 #include <netipsec/esp_var.h>
     97 #include <netipsec/ipcomp.h>		/*XXX*/
     98 #include <netipsec/ipcomp_var.h>
     99 
    100 #include <netipsec/key.h>
    101 #include <netipsec/keydb.h>
    102 #include <netipsec/key_debug.h>
    103 
    104 #include <netipsec/xform.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 
    129 int ip4_ah_offsetmask = 0;	/* maybe IP_DF? */
    130 int ip4_ipsec_dfbit = 2;	/* DF bit on encap. 0: clear 1: set 2: copy */
    131 int ip4_esp_trans_deflev = IPSEC_LEVEL_USE;
    132 int ip4_esp_net_deflev = IPSEC_LEVEL_USE;
    133 int ip4_ah_trans_deflev = IPSEC_LEVEL_USE;
    134 int ip4_ah_net_deflev = IPSEC_LEVEL_USE;
    135 struct secpolicy ip4_def_policy;
    136 int ip4_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
    137 
    138 u_int ipsec_spdgen = 1;		/* SPD generation # */
    139 
    140 static struct secpolicy ipsec_dummy_sp __read_mostly = {
    141 	.state		= IPSEC_SPSTATE_ALIVE,
    142 	/* If ENTRUST, the dummy SP never be used. See ipsec_getpolicybysock. */
    143 	.policy		= IPSEC_POLICY_ENTRUST,
    144 };
    145 
    146 static struct secpolicy *ipsec_checkpcbcache(struct mbuf *,
    147     struct inpcbpolicy *, int);
    148 static int ipsec_fillpcbcache(struct inpcbpolicy *, struct mbuf *,
    149     struct secpolicy *, int);
    150 static int ipsec_invalpcbcache(struct inpcbpolicy *, int);
    151 
    152 /*
    153  * Crypto support requirements:
    154  *
    155  *  1	require hardware support
    156  * -1	require software support
    157  *  0	take anything
    158  */
    159 int crypto_support = 0;
    160 
    161 static struct secpolicy *ipsec_getpolicybysock(struct mbuf *, u_int,
    162     struct inpcb_hdr *, int *);
    163 
    164 #ifdef INET6
    165 int ip6_esp_trans_deflev = IPSEC_LEVEL_USE;
    166 int ip6_esp_net_deflev = IPSEC_LEVEL_USE;
    167 int ip6_ah_trans_deflev = IPSEC_LEVEL_USE;
    168 int ip6_ah_net_deflev = IPSEC_LEVEL_USE;
    169 struct secpolicy ip6_def_policy;
    170 int ip6_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
    171 #endif
    172 
    173 static int ipsec4_setspidx_inpcb(struct mbuf *, struct inpcb *);
    174 #ifdef INET6
    175 static int ipsec6_setspidx_in6pcb(struct mbuf *, struct in6pcb *);
    176 #endif
    177 static int ipsec_setspidx(struct mbuf *, struct secpolicyindex *, int);
    178 static void ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *, int);
    179 static int ipsec4_setspidx_ipaddr(struct mbuf *, struct secpolicyindex *);
    180 #ifdef INET6
    181 static void ipsec6_get_ulp(struct mbuf *m, struct secpolicyindex *, int);
    182 static int ipsec6_setspidx_ipaddr(struct mbuf *, struct secpolicyindex *);
    183 #endif
    184 static void ipsec_delpcbpolicy(struct inpcbpolicy *);
    185 #if 0 /* unused */
    186 static struct secpolicy *ipsec_deepcopy_policy(const struct secpolicy *);
    187 #endif
    188 static void ipsec_destroy_policy(struct secpolicy *);
    189 static int ipsec_sp_reject(const struct secpolicy *, const struct mbuf *);
    190 static void vshiftl(unsigned char *, int, int);
    191 static size_t ipsec_sp_hdrsiz(const struct secpolicy *, const struct mbuf *);
    192 
    193 /*
    194  * Try to validate and use cached policy on a PCB.
    195  */
    196 static struct secpolicy *
    197 ipsec_checkpcbcache(struct mbuf *m, struct inpcbpolicy *pcbsp, int dir)
    198 {
    199 	struct secpolicyindex spidx;
    200 	struct secpolicy *sp = NULL;
    201 	int s;
    202 
    203 	KASSERT(IPSEC_DIR_IS_VALID(dir));
    204 	KASSERT(pcbsp != NULL);
    205 	KASSERT(dir < __arraycount(pcbsp->sp_cache));
    206 	KASSERT(inph_locked(pcbsp->sp_inph));
    207 
    208 	/*
    209 	 * Checking the generation and sp->state and taking a reference to an SP
    210 	 * must be in a critical section of pserialize. See key_unlink_sp.
    211 	 */
    212 	s = pserialize_read_enter();
    213 	/* SPD table change invalidate all the caches. */
    214 	if (ipsec_spdgen != pcbsp->sp_cache[dir].cachegen) {
    215 		ipsec_invalpcbcache(pcbsp, dir);
    216 		goto out;
    217 	}
    218 	sp = pcbsp->sp_cache[dir].cachesp;
    219 	if (sp == NULL)
    220 		goto out;
    221 	if (sp->state != IPSEC_SPSTATE_ALIVE) {
    222 		sp = NULL;
    223 		ipsec_invalpcbcache(pcbsp, dir);
    224 		goto out;
    225 	}
    226 	if ((pcbsp->sp_cacheflags & IPSEC_PCBSP_CONNECTED) == 0) {
    227 		/* NB: assume ipsec_setspidx never sleep */
    228 		if (ipsec_setspidx(m, &spidx, 1) != 0) {
    229 			sp = NULL;
    230 			goto out;
    231 		}
    232 
    233 		/*
    234 		 * We have to make an exact match here since the cached rule
    235 		 * might have lower priority than a rule that would otherwise
    236 		 * have matched the packet.
    237 		 */
    238 		if (memcmp(&pcbsp->sp_cache[dir].cacheidx, &spidx,
    239 		    sizeof(spidx))) {
    240 			sp = NULL;
    241 			goto out;
    242 		}
    243 	} else {
    244 		/*
    245 		 * The pcb is connected, and the L4 code is sure that:
    246 		 * - outgoing side uses inp_[lf]addr
    247 		 * - incoming side looks up policy after inpcb lookup
    248 		 * and address pair is know to be stable.  We do not need
    249 		 * to generate spidx again, nor check the address match again.
    250 		 *
    251 		 * For IPv4/v6 SOCK_STREAM sockets, this assumptions holds
    252 		 * and there are calls to ipsec_pcbconn() from in_pcbconnect().
    253 		 */
    254 	}
    255 
    256 	sp->lastused = time_second;
    257 	KEY_SP_REF(sp);
    258 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    259 	    "DP cause refcnt++:%d SP:%p\n",
    260 	    key_sp_refcnt(sp), pcbsp->sp_cache[dir].cachesp);
    261 out:
    262 	pserialize_read_exit(s);
    263 	return sp;
    264 }
    265 
    266 static int
    267 ipsec_fillpcbcache(struct inpcbpolicy *pcbsp, struct mbuf *m,
    268     struct secpolicy *sp, int dir)
    269 {
    270 
    271 	KASSERT(IPSEC_DIR_IS_INOROUT(dir));
    272 	KASSERT(dir < __arraycount(pcbsp->sp_cache));
    273 	KASSERT(inph_locked(pcbsp->sp_inph));
    274 
    275 	pcbsp->sp_cache[dir].cachesp = NULL;
    276 	pcbsp->sp_cache[dir].cachehint = IPSEC_PCBHINT_UNKNOWN;
    277 	if (ipsec_setspidx(m, &pcbsp->sp_cache[dir].cacheidx, 1) != 0) {
    278 		return EINVAL;
    279 	}
    280 	pcbsp->sp_cache[dir].cachesp = sp;
    281 	if (pcbsp->sp_cache[dir].cachesp) {
    282 		/*
    283 		 * If the PCB is connected, we can remember a hint to
    284 		 * possibly short-circuit IPsec processing in other places.
    285 		 */
    286 		if (pcbsp->sp_cacheflags & IPSEC_PCBSP_CONNECTED) {
    287 			switch (pcbsp->sp_cache[dir].cachesp->policy) {
    288 			case IPSEC_POLICY_NONE:
    289 			case IPSEC_POLICY_BYPASS:
    290 				pcbsp->sp_cache[dir].cachehint =
    291 				    IPSEC_PCBHINT_NO;
    292 				break;
    293 			default:
    294 				pcbsp->sp_cache[dir].cachehint =
    295 				    IPSEC_PCBHINT_YES;
    296 			}
    297 		}
    298 	}
    299 	pcbsp->sp_cache[dir].cachegen = ipsec_spdgen;
    300 
    301 	return 0;
    302 }
    303 
    304 static int
    305 ipsec_invalpcbcache(struct inpcbpolicy *pcbsp, int dir)
    306 {
    307 	int i;
    308 
    309 	KASSERT(inph_locked(pcbsp->sp_inph));
    310 
    311 	for (i = IPSEC_DIR_INBOUND; i <= IPSEC_DIR_OUTBOUND; i++) {
    312 		if (dir != IPSEC_DIR_ANY && i != dir)
    313 			continue;
    314 		pcbsp->sp_cache[i].cachesp = NULL;
    315 		pcbsp->sp_cache[i].cachehint = IPSEC_PCBHINT_UNKNOWN;
    316 		pcbsp->sp_cache[i].cachegen = 0;
    317 		memset(&pcbsp->sp_cache[i].cacheidx, 0,
    318 		    sizeof(pcbsp->sp_cache[i].cacheidx));
    319 	}
    320 	return 0;
    321 }
    322 
    323 void
    324 ipsec_pcbconn(struct inpcbpolicy *pcbsp)
    325 {
    326 
    327 	KASSERT(inph_locked(pcbsp->sp_inph));
    328 
    329 	pcbsp->sp_cacheflags |= IPSEC_PCBSP_CONNECTED;
    330 	ipsec_invalpcbcache(pcbsp, IPSEC_DIR_ANY);
    331 }
    332 
    333 void
    334 ipsec_pcbdisconn(struct inpcbpolicy *pcbsp)
    335 {
    336 
    337 	KASSERT(inph_locked(pcbsp->sp_inph));
    338 
    339 	pcbsp->sp_cacheflags &= ~IPSEC_PCBSP_CONNECTED;
    340 	ipsec_invalpcbcache(pcbsp, IPSEC_DIR_ANY);
    341 }
    342 
    343 void
    344 ipsec_invalpcbcacheall(void)
    345 {
    346 
    347 	if (ipsec_spdgen == UINT_MAX)
    348 		ipsec_spdgen = 1;
    349 	else
    350 		ipsec_spdgen++;
    351 }
    352 
    353 /*
    354  * Return a held reference to the default SP.
    355  */
    356 static struct secpolicy *
    357 key_get_default_sp(int af, const char *where, int tag)
    358 {
    359 	struct secpolicy *sp;
    360 
    361 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
    362 
    363 	switch(af) {
    364 	case AF_INET:
    365 		sp = &ip4_def_policy;
    366 		break;
    367 #ifdef INET6
    368 	case AF_INET6:
    369 		sp = &ip6_def_policy;
    370 		break;
    371 #endif
    372 	default:
    373 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    374 		    "unexpected protocol family %u\n", af);
    375 		return NULL;
    376 	}
    377 
    378 	if (sp->policy != IPSEC_POLICY_DISCARD &&
    379 	    sp->policy != IPSEC_POLICY_NONE) {
    380 		IPSECLOG(LOG_INFO, "fixed system default policy: %d->%d\n",
    381 		    sp->policy, IPSEC_POLICY_NONE);
    382 		sp->policy = IPSEC_POLICY_NONE;
    383 	}
    384 	KEY_SP_REF(sp);
    385 
    386 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP returns SP:%p (%u)\n",
    387 	    sp, key_sp_refcnt(sp));
    388 	return sp;
    389 }
    390 
    391 #define	KEY_GET_DEFAULT_SP(af) \
    392 	key_get_default_sp((af), __func__, __LINE__)
    393 
    394 /*
    395  * For OUTBOUND packet having a socket. Searching SPD for packet,
    396  * and return a pointer to SP.
    397  * OUT:	NULL:	no apropreate SP found, the following value is set to error.
    398  *		0	: bypass
    399  *		EACCES	: discard packet.
    400  *		ENOENT	: ipsec_acquire() in progress, maybe.
    401  *		others	: error occurred.
    402  *	others:	a pointer to SP
    403  *
    404  * NOTE: IPv6 mapped address concern is implemented here.
    405  */
    406 static struct secpolicy *
    407 ipsec_getpolicybysock(struct mbuf *m, u_int dir, struct inpcb_hdr *inph,
    408     int *error)
    409 {
    410 	struct inpcbpolicy *pcbsp = NULL;
    411 	struct secpolicy *currsp = NULL;	/* policy on socket */
    412 	struct secpolicy *sp;
    413 	int af;
    414 
    415 	KASSERT(m != NULL);
    416 	KASSERT(inph != NULL);
    417 	KASSERT(error != NULL);
    418 	KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
    419 
    420 	KASSERT(inph->inph_socket != NULL);
    421 	KASSERT(inph_locked(inph));
    422 
    423 	/* XXX FIXME inpcb/in6pcb  vs socket*/
    424 	af = inph->inph_af;
    425 	KASSERTMSG(af == AF_INET || af == AF_INET6,
    426 	    "unexpected protocol family %u", af);
    427 
    428 	KASSERT(inph->inph_sp != NULL);
    429 	/* If we have a cached entry, and if it is still valid, use it. */
    430 	IPSEC_STATINC(IPSEC_STAT_SPDCACHELOOKUP);
    431 	currsp = ipsec_checkpcbcache(m, inph->inph_sp, dir);
    432 	if (currsp) {
    433 		*error = 0;
    434 		return currsp;
    435 	}
    436 	IPSEC_STATINC(IPSEC_STAT_SPDCACHEMISS);
    437 
    438 	switch (af) {
    439 	case AF_INET: {
    440 		struct inpcb *in4p = (struct inpcb *)inph;
    441 		/* set spidx in pcb */
    442 		*error = ipsec4_setspidx_inpcb(m, in4p);
    443 		pcbsp = in4p->inp_sp;
    444 		break;
    445 		}
    446 #if defined(INET6)
    447 	case AF_INET6: {
    448 		struct in6pcb *in6p = (struct in6pcb *)inph;
    449 		/* set spidx in pcb */
    450 		*error = ipsec6_setspidx_in6pcb(m, in6p);
    451 		pcbsp = in6p->in6p_sp;
    452 		break;
    453 		}
    454 #endif
    455 	default:
    456 		*error = EPFNOSUPPORT;
    457 		break;
    458 	}
    459 	if (*error)
    460 		return NULL;
    461 
    462 	KASSERT(pcbsp != NULL);
    463 	switch (dir) {
    464 	case IPSEC_DIR_INBOUND:
    465 		currsp = pcbsp->sp_in;
    466 		break;
    467 	case IPSEC_DIR_OUTBOUND:
    468 		currsp = pcbsp->sp_out;
    469 		break;
    470 	}
    471 	KASSERT(currsp != NULL);
    472 
    473 	if (pcbsp->priv) {			/* when privilieged socket */
    474 		switch (currsp->policy) {
    475 		case IPSEC_POLICY_BYPASS:
    476 		case IPSEC_POLICY_IPSEC:
    477 			KEY_SP_REF(currsp);
    478 			sp = currsp;
    479 			break;
    480 
    481 		case IPSEC_POLICY_ENTRUST:
    482 			/* look for a policy in SPD */
    483 			sp = KEY_LOOKUP_SP_BYSPIDX(&currsp->spidx, dir);
    484 			if (sp == NULL)		/* no SP found */
    485 				sp = KEY_GET_DEFAULT_SP(af);
    486 			break;
    487 
    488 		default:
    489 			IPSECLOG(LOG_ERR, "Invalid policy for PCB %d\n",
    490 			    currsp->policy);
    491 			*error = EINVAL;
    492 			return NULL;
    493 		}
    494 	} else {				/* unpriv, SPD has policy */
    495 		sp = KEY_LOOKUP_SP_BYSPIDX(&currsp->spidx, dir);
    496 		if (sp == NULL) {		/* no SP found */
    497 			switch (currsp->policy) {
    498 			case IPSEC_POLICY_BYPASS:
    499 				IPSECLOG(LOG_ERR, "Illegal policy for "
    500 				    "non-priviliged defined %d\n",
    501 				    currsp->policy);
    502 				*error = EINVAL;
    503 				return NULL;
    504 
    505 			case IPSEC_POLICY_ENTRUST:
    506 				sp = KEY_GET_DEFAULT_SP(af);
    507 				break;
    508 
    509 			case IPSEC_POLICY_IPSEC:
    510 				KEY_SP_REF(currsp);
    511 				sp = currsp;
    512 				break;
    513 
    514 			default:
    515 				IPSECLOG(LOG_ERR, "Invalid policy for "
    516 				    "PCB %d\n", currsp->policy);
    517 				*error = EINVAL;
    518 				return NULL;
    519 			}
    520 		}
    521 	}
    522 	KASSERTMSG(sp != NULL, "null SP (priv %u policy %u", pcbsp->priv,
    523 	    currsp->policy);
    524 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    525 	    "DP (priv %u policy %u) allocates SP:%p (refcnt %u)\n",
    526 	    pcbsp->priv, currsp->policy, sp, key_sp_refcnt(sp));
    527 	ipsec_fillpcbcache(pcbsp, m, sp, dir);
    528 	return sp;
    529 }
    530 
    531 /*
    532  * For FORWARDING packet or OUTBOUND without a socket. Searching SPD for packet,
    533  * and return a pointer to SP.
    534  * OUT:	positive: a pointer to the entry for security policy leaf matched.
    535  *	NULL:	no apropreate SP found, the following value is set to error.
    536  *		0	: bypass
    537  *		EACCES	: discard packet.
    538  *		ENOENT	: ipsec_acquire() in progress, maybe.
    539  *		others	: error occurred.
    540  */
    541 static struct secpolicy *
    542 ipsec_getpolicybyaddr(struct mbuf *m, u_int dir, int flag, int *error)
    543 {
    544 	struct secpolicyindex spidx;
    545 	struct secpolicy *sp;
    546 
    547 	KASSERT(m != NULL);
    548 	KASSERT(error != NULL);
    549 	KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
    550 
    551 	sp = NULL;
    552 
    553 	/* Make an index to look for a policy. */
    554 	*error = ipsec_setspidx(m, &spidx, (flag & IP_FORWARDING) ? 0 : 1);
    555 	if (*error != 0) {
    556 		IPSECLOG(LOG_DEBUG, "setpidx failed, dir %u flag %u\n", dir, flag);
    557 		memset(&spidx, 0, sizeof(spidx));
    558 		return NULL;
    559 	}
    560 
    561 	spidx.dir = dir;
    562 
    563 	if (key_havesp(dir)) {
    564 		sp = KEY_LOOKUP_SP_BYSPIDX(&spidx, dir);
    565 	}
    566 
    567 	if (sp == NULL)			/* no SP found, use system default */
    568 		sp = KEY_GET_DEFAULT_SP(spidx.dst.sa.sa_family);
    569 	KASSERT(sp != NULL);
    570 	return sp;
    571 }
    572 
    573 static struct secpolicy *
    574 ipsec_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
    575     void *inp)
    576 {
    577 	struct secpolicy *sp;
    578 
    579 	*error = 0;
    580 
    581 	if (inp == NULL) {
    582 		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
    583 	} else {
    584 		struct inpcb_hdr *inph = (struct inpcb_hdr *)inp;
    585 		KASSERT(inph->inph_socket != NULL);
    586 		sp = ipsec_getpolicybysock(m, dir, inph, error);
    587 	}
    588 	if (sp == NULL) {
    589 		KASSERTMSG(*error != 0, "getpolicy failed w/o error");
    590 		IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
    591 		return NULL;
    592 	}
    593 	KASSERTMSG(*error == 0, "sp w/ error set to %u", *error);
    594 
    595 	switch (sp->policy) {
    596 	case IPSEC_POLICY_ENTRUST:
    597 	default:
    598 		printf("%s: invalid policy %u\n", __func__, sp->policy);
    599 		/* fall thru... */
    600 	case IPSEC_POLICY_DISCARD:
    601 		IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
    602 		*error = -EINVAL;	/* packet is discarded by caller */
    603 		break;
    604 	case IPSEC_POLICY_BYPASS:
    605 	case IPSEC_POLICY_NONE:
    606 		KEY_SP_UNREF(&sp);
    607 		sp = NULL;		/* NB: force NULL result */
    608 		break;
    609 	case IPSEC_POLICY_IPSEC:
    610 		KASSERT(sp->req != NULL);
    611 		break;
    612 	}
    613 
    614 	if (*error != 0) {
    615 		KEY_SP_UNREF(&sp);
    616 		sp = NULL;
    617 		IPSECLOG(LOG_DEBUG, "done, error %d\n", *error);
    618 	}
    619 
    620 	return sp;
    621 }
    622 
    623 int
    624 ipsec4_output(struct mbuf *m, struct inpcb *inp, int flags,
    625     u_long *mtu, bool *natt_frag, bool *done)
    626 {
    627 	struct secpolicy *sp = NULL;
    628 	int error, s;
    629 
    630 	/*
    631 	 * Check the security policy (SP) for the packet and, if required,
    632 	 * do IPsec-related processing.  There are two cases here; the first
    633 	 * time a packet is sent through it will be untagged and handled by
    634 	 * ipsec_checkpolicy().  If the packet is resubmitted to ip_output
    635 	 * (e.g. after AH, ESP, etc. processing), there will be a tag to
    636 	 * bypass the lookup and related policy checking.
    637 	 */
    638 	if (ipsec_outdone(m)) {
    639 		return 0;
    640 	}
    641 	s = splsoftnet();
    642 	if (inp && ipsec_pcb_skip_ipsec(inp->inp_sp, IPSEC_DIR_OUTBOUND)) {
    643 		splx(s);
    644 		return 0;
    645 	}
    646 	sp = ipsec_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, inp);
    647 
    648 	/*
    649 	 * There are four return cases:
    650 	 *	sp != NULL			apply IPsec policy
    651 	 *	sp == NULL, error == 0		no IPsec handling needed
    652 	 *	sp == NULL, error == -EINVAL	discard packet w/o error
    653 	 *	sp == NULL, error != 0		discard packet, report error
    654 	 */
    655 	if (sp == NULL) {
    656 		splx(s);
    657 		if (error) {
    658 			/*
    659 			 * Hack: -EINVAL is used to signal that a packet
    660 			 * should be silently discarded.  This is typically
    661 			 * because we asked key management for an SA and
    662 			 * it was delayed (e.g. kicked up to IKE).
    663 			 */
    664 			if (error == -EINVAL)
    665 				error = 0;
    666 			m_freem(m);
    667 			*done = true;
    668 			return error;
    669 		}
    670 		/* No IPsec processing for this packet. */
    671 		return 0;
    672 	}
    673 
    674 	/*
    675 	 * Do delayed checksums now because we send before
    676 	 * this is done in the normal processing path.
    677 	 */
    678 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    679 		in_delayed_cksum(m);
    680 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    681 	}
    682 
    683     {
    684 	u_long _mtu = 0;
    685 
    686 	error = ipsec4_process_packet(m, sp->req, &_mtu);
    687 
    688 	if (error == 0 && _mtu != 0) {
    689 		/*
    690 		 * NAT-T ESP fragmentation: do not do IPSec processing
    691 		 * now, we will do it on each fragmented packet.
    692 		 */
    693 		*mtu = _mtu;
    694 		*natt_frag = true;
    695 		KEY_SP_UNREF(&sp);
    696 		splx(s);
    697 		return 0;
    698 	}
    699     }
    700 
    701 	/*
    702 	 * Preserve KAME behaviour: ENOENT can be returned
    703 	 * when an SA acquire is in progress.  Don't propagate
    704 	 * this to user-level; it confuses applications.
    705 	 *
    706 	 * XXX this will go away when the SADB is redone.
    707 	 */
    708 	if (error == ENOENT)
    709 		error = 0;
    710 	KEY_SP_UNREF(&sp);
    711 	splx(s);
    712 	*done = true;
    713 	return error;
    714 }
    715 
    716 int
    717 ipsec4_input(struct mbuf *m, int flags)
    718 {
    719 	struct secpolicy *sp;
    720 	int error, s;
    721 
    722 	s = splsoftnet();
    723 	error = ipsec_in_reject(m, NULL);
    724 	splx(s);
    725 	if (error) {
    726 		return EINVAL;
    727 	}
    728 
    729 	if (flags == 0) {
    730 		/* We are done. */
    731 		return 0;
    732 	}
    733 
    734 	/*
    735 	 * Peek at the outbound SP for this packet to determine if
    736 	 * it is a Fast Forward candidate.
    737 	 */
    738 	s = splsoftnet();
    739 	sp = ipsec_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, NULL);
    740 	if (sp != NULL) {
    741 		m->m_flags &= ~M_CANFASTFWD;
    742 		KEY_SP_UNREF(&sp);
    743 	}
    744 	splx(s);
    745 	return 0;
    746 }
    747 
    748 int
    749 ipsec4_forward(struct mbuf *m, int *destmtu)
    750 {
    751 	/*
    752 	 * If the packet is routed over IPsec tunnel, tell the
    753 	 * originator the tunnel MTU.
    754 	 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
    755 	 * XXX quickhack!!!
    756 	 */
    757 	struct secpolicy *sp;
    758 	size_t ipsechdr;
    759 	int error;
    760 
    761 	sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, IP_FORWARDING,
    762 	    &error);
    763 	if (sp == NULL) {
    764 		return EINVAL;
    765 	}
    766 
    767 	/* Count IPsec header size. */
    768 	ipsechdr = ipsec_sp_hdrsiz(sp, m);
    769 
    770 	/*
    771 	 * Find the correct route for outer IPv4 header, compute tunnel MTU.
    772 	 */
    773 	if (sp->req) {
    774 		struct secasvar *sav;
    775 
    776 		sav = ipsec_lookup_sa(sp->req, m);
    777 		if (sav != NULL) {
    778 			struct route *ro;
    779 			struct rtentry *rt;
    780 
    781 			ro = &sav->sah->sa_route;
    782 			rt = rtcache_validate(ro);
    783 			if (rt && rt->rt_ifp) {
    784 				*destmtu = rt->rt_rmx.rmx_mtu ?
    785 				    rt->rt_rmx.rmx_mtu : rt->rt_ifp->if_mtu;
    786 				*destmtu -= ipsechdr;
    787 			}
    788 			rtcache_unref(rt, ro);
    789 			KEY_SA_UNREF(&sav);
    790 		}
    791 	}
    792 	KEY_SP_UNREF(&sp);
    793 	return 0;
    794 }
    795 
    796 static int
    797 ipsec4_setspidx_inpcb(struct mbuf *m, struct inpcb *pcb)
    798 {
    799 	int error;
    800 
    801 	KASSERT(pcb != NULL);
    802 	KASSERT(pcb->inp_sp != NULL);
    803 	KASSERT(pcb->inp_sp->sp_out != NULL);
    804 	KASSERT(pcb->inp_sp->sp_in != NULL);
    805 
    806 	error = ipsec_setspidx(m, &pcb->inp_sp->sp_in->spidx, 1);
    807 	if (error == 0) {
    808 		pcb->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
    809 		pcb->inp_sp->sp_out->spidx = pcb->inp_sp->sp_in->spidx;
    810 		pcb->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
    811 	} else {
    812 		memset(&pcb->inp_sp->sp_in->spidx, 0,
    813 		    sizeof(pcb->inp_sp->sp_in->spidx));
    814 		memset(&pcb->inp_sp->sp_out->spidx, 0,
    815 		    sizeof(pcb->inp_sp->sp_in->spidx));
    816 	}
    817 	return error;
    818 }
    819 
    820 #ifdef INET6
    821 static int
    822 ipsec6_setspidx_in6pcb(struct mbuf *m, struct in6pcb *pcb)
    823 {
    824 	struct secpolicyindex *spidx;
    825 	int error;
    826 
    827 	KASSERT(pcb != NULL);
    828 	KASSERT(pcb->in6p_sp != NULL);
    829 	KASSERT(pcb->in6p_sp->sp_out != NULL);
    830 	KASSERT(pcb->in6p_sp->sp_in != NULL);
    831 
    832 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
    833 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
    834 
    835 	spidx = &pcb->in6p_sp->sp_in->spidx;
    836 	error = ipsec_setspidx(m, spidx, 1);
    837 	if (error)
    838 		goto bad;
    839 	spidx->dir = IPSEC_DIR_INBOUND;
    840 
    841 	spidx = &pcb->in6p_sp->sp_out->spidx;
    842 	error = ipsec_setspidx(m, spidx, 1);
    843 	if (error)
    844 		goto bad;
    845 	spidx->dir = IPSEC_DIR_OUTBOUND;
    846 
    847 	return 0;
    848 
    849 bad:
    850 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
    851 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
    852 	return error;
    853 }
    854 #endif
    855 
    856 /*
    857  * configure security policy index (src/dst/proto/sport/dport)
    858  * by looking at the content of mbuf.
    859  * the caller is responsible for error recovery (like clearing up spidx).
    860  */
    861 static int
    862 ipsec_setspidx(struct mbuf *m, struct secpolicyindex *spidx, int needport)
    863 {
    864 	struct ip *ip = NULL;
    865 	struct ip ipbuf;
    866 	u_int v;
    867 	struct mbuf *n;
    868 	int len;
    869 	int error;
    870 
    871 	KASSERT(m != NULL);
    872 
    873 	/*
    874 	 * validate m->m_pkthdr.len.  we see incorrect length if we
    875 	 * mistakenly call this function with inconsistent mbuf chain
    876 	 * (like 4.4BSD tcp/udp processing).  XXX should we panic here?
    877 	 */
    878 	len = 0;
    879 	for (n = m; n; n = n->m_next)
    880 		len += n->m_len;
    881 	if (m->m_pkthdr.len != len) {
    882 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
    883 		    "total of m_len(%d) != pkthdr.len(%d), ignored.\n",
    884 		    len, m->m_pkthdr.len);
    885 		KASSERTMSG(0, "impossible");
    886 		return EINVAL;
    887 	}
    888 
    889 	if (m->m_pkthdr.len < sizeof(struct ip)) {
    890 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
    891 		    "pkthdr.len(%d) < sizeof(struct ip), ignored.\n",
    892 		    m->m_pkthdr.len);
    893 		return EINVAL;
    894 	}
    895 
    896 	if (m->m_len >= sizeof(*ip)) {
    897 		ip = mtod(m, struct ip *);
    898 	} else {
    899 		m_copydata(m, 0, sizeof(ipbuf), &ipbuf);
    900 		ip = &ipbuf;
    901 	}
    902 	v = ip->ip_v;
    903 	switch (v) {
    904 	case 4:
    905 		error = ipsec4_setspidx_ipaddr(m, spidx);
    906 		if (error)
    907 			return error;
    908 		ipsec4_get_ulp(m, spidx, needport);
    909 		return 0;
    910 #ifdef INET6
    911 	case 6:
    912 		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
    913 			KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
    914 			    "pkthdr.len(%d) < sizeof(struct ip6_hdr), "
    915 			    "ignored.\n", m->m_pkthdr.len);
    916 			return EINVAL;
    917 		}
    918 		error = ipsec6_setspidx_ipaddr(m, spidx);
    919 		if (error)
    920 			return error;
    921 		ipsec6_get_ulp(m, spidx, needport);
    922 		return 0;
    923 #endif
    924 	default:
    925 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
    926 		    "unknown IP version %u, ignored.\n", v);
    927 		return EINVAL;
    928 	}
    929 }
    930 
    931 static void
    932 ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
    933 {
    934 	u_int8_t nxt;
    935 	int off;
    936 
    937 	KASSERT(m != NULL);
    938 	KASSERTMSG(m->m_pkthdr.len >= sizeof(struct ip), "packet too short");
    939 
    940 	/* NB: ip_input() flips it into host endian XXX need more checking */
    941 	if (m->m_len >= sizeof(struct ip)) {
    942 		struct ip *ip = mtod(m, struct ip *);
    943 		if (ip->ip_off & htons(IP_MF | IP_OFFMASK))
    944 			goto done;
    945 		off = ip->ip_hl << 2;
    946 		nxt = ip->ip_p;
    947 	} else {
    948 		struct ip ih;
    949 
    950 		m_copydata(m, 0, sizeof(struct ip), &ih);
    951 		if (ih.ip_off & htons(IP_MF | IP_OFFMASK))
    952 			goto done;
    953 		off = ih.ip_hl << 2;
    954 		nxt = ih.ip_p;
    955 	}
    956 
    957 	while (off < m->m_pkthdr.len) {
    958 		struct ip6_ext ip6e;
    959 		struct tcphdr th;
    960 		struct udphdr uh;
    961 		struct icmp icmph;
    962 
    963 		switch (nxt) {
    964 		case IPPROTO_TCP:
    965 			spidx->ul_proto = nxt;
    966 			if (!needport)
    967 				goto done_proto;
    968 			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
    969 				goto done;
    970 			m_copydata(m, off, sizeof(th), &th);
    971 			spidx->src.sin.sin_port = th.th_sport;
    972 			spidx->dst.sin.sin_port = th.th_dport;
    973 			return;
    974 		case IPPROTO_UDP:
    975 			spidx->ul_proto = nxt;
    976 			if (!needport)
    977 				goto done_proto;
    978 			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
    979 				goto done;
    980 			m_copydata(m, off, sizeof(uh), &uh);
    981 			spidx->src.sin.sin_port = uh.uh_sport;
    982 			spidx->dst.sin.sin_port = uh.uh_dport;
    983 			return;
    984 		case IPPROTO_AH:
    985 			if (off + sizeof(ip6e) > m->m_pkthdr.len)
    986 				goto done;
    987 			/* XXX sigh, this works but is totally bogus */
    988 			m_copydata(m, off, sizeof(ip6e), &ip6e);
    989 			off += (ip6e.ip6e_len + 2) << 2;
    990 			nxt = ip6e.ip6e_nxt;
    991 			break;
    992 		case IPPROTO_ICMP:
    993 			spidx->ul_proto = nxt;
    994 			if (off + sizeof(struct icmp) > m->m_pkthdr.len)
    995 				goto done;
    996 			m_copydata(m, off, sizeof(icmph), &icmph);
    997 			((struct sockaddr_in *)&spidx->src)->sin_port =
    998 			    htons((uint16_t)icmph.icmp_type);
    999 			((struct sockaddr_in *)&spidx->dst)->sin_port =
   1000 			    htons((uint16_t)icmph.icmp_code);
   1001 			return;
   1002 		default:
   1003 			/* XXX intermediate headers??? */
   1004 			spidx->ul_proto = nxt;
   1005 			goto done_proto;
   1006 		}
   1007 	}
   1008 done:
   1009 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
   1010 done_proto:
   1011 	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
   1012 	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
   1013 }
   1014 
   1015 static int
   1016 ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
   1017 {
   1018 	static const struct sockaddr_in template = {
   1019 		sizeof(struct sockaddr_in),
   1020 		AF_INET,
   1021 		0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
   1022 	};
   1023 
   1024 	spidx->src.sin = template;
   1025 	spidx->dst.sin = template;
   1026 
   1027 	if (m->m_len < sizeof(struct ip)) {
   1028 		m_copydata(m, offsetof(struct ip, ip_src),
   1029 		    sizeof(struct in_addr), &spidx->src.sin.sin_addr);
   1030 		m_copydata(m, offsetof(struct ip, ip_dst),
   1031 		    sizeof(struct in_addr), &spidx->dst.sin.sin_addr);
   1032 	} else {
   1033 		struct ip *ip = mtod(m, struct ip *);
   1034 		spidx->src.sin.sin_addr = ip->ip_src;
   1035 		spidx->dst.sin.sin_addr = ip->ip_dst;
   1036 	}
   1037 
   1038 	spidx->prefs = sizeof(struct in_addr) << 3;
   1039 	spidx->prefd = sizeof(struct in_addr) << 3;
   1040 
   1041 	return 0;
   1042 }
   1043 
   1044 #ifdef INET6
   1045 static void
   1046 ipsec6_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
   1047 {
   1048 	int off, nxt;
   1049 	struct tcphdr th;
   1050 	struct udphdr uh;
   1051 	struct icmp6_hdr icmph;
   1052 
   1053 	KASSERT(m != NULL);
   1054 
   1055 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1056 		kdebug_mbuf(__func__, m);
   1057 	}
   1058 
   1059 	/* set default */
   1060 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
   1061 	((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
   1062 	((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
   1063 
   1064 	nxt = -1;
   1065 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
   1066 	if (off < 0 || m->m_pkthdr.len < off)
   1067 		return;
   1068 
   1069 	switch (nxt) {
   1070 	case IPPROTO_TCP:
   1071 		spidx->ul_proto = nxt;
   1072 		if (!needport)
   1073 			break;
   1074 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
   1075 			break;
   1076 		m_copydata(m, off, sizeof(th), &th);
   1077 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
   1078 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
   1079 		break;
   1080 	case IPPROTO_UDP:
   1081 		spidx->ul_proto = nxt;
   1082 		if (!needport)
   1083 			break;
   1084 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
   1085 			break;
   1086 		m_copydata(m, off, sizeof(uh), &uh);
   1087 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
   1088 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
   1089 		break;
   1090 	case IPPROTO_ICMPV6:
   1091 		spidx->ul_proto = nxt;
   1092 		if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
   1093 			break;
   1094 		m_copydata(m, off, sizeof(icmph), &icmph);
   1095 		((struct sockaddr_in6 *)&spidx->src)->sin6_port =
   1096 		    htons((uint16_t)icmph.icmp6_type);
   1097 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port =
   1098 		    htons((uint16_t)icmph.icmp6_code);
   1099 		break;
   1100 	default:
   1101 		/* XXX intermediate headers??? */
   1102 		spidx->ul_proto = nxt;
   1103 		break;
   1104 	}
   1105 }
   1106 
   1107 static int
   1108 ipsec6_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
   1109 {
   1110 	struct ip6_hdr *ip6 = NULL;
   1111 	struct ip6_hdr ip6buf;
   1112 	struct sockaddr_in6 *sin6;
   1113 
   1114 	if (m->m_len >= sizeof(*ip6))
   1115 		ip6 = mtod(m, struct ip6_hdr *);
   1116 	else {
   1117 		m_copydata(m, 0, sizeof(ip6buf), &ip6buf);
   1118 		ip6 = &ip6buf;
   1119 	}
   1120 
   1121 	sin6 = (struct sockaddr_in6 *)&spidx->src;
   1122 	memset(sin6, 0, sizeof(*sin6));
   1123 	sin6->sin6_family = AF_INET6;
   1124 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   1125 	memcpy(&sin6->sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src));
   1126 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
   1127 		sin6->sin6_addr.s6_addr16[1] = 0;
   1128 		sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
   1129 	}
   1130 	spidx->prefs = sizeof(struct in6_addr) << 3;
   1131 
   1132 	sin6 = (struct sockaddr_in6 *)&spidx->dst;
   1133 	memset(sin6, 0, sizeof(*sin6));
   1134 	sin6->sin6_family = AF_INET6;
   1135 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   1136 	memcpy(&sin6->sin6_addr, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
   1137 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
   1138 		sin6->sin6_addr.s6_addr16[1] = 0;
   1139 		sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
   1140 	}
   1141 	spidx->prefd = sizeof(struct in6_addr) << 3;
   1142 
   1143 	return 0;
   1144 }
   1145 #endif
   1146 
   1147 static void
   1148 ipsec_delpcbpolicy(struct inpcbpolicy *p)
   1149 {
   1150 
   1151 	kmem_intr_free(p, sizeof(*p));
   1152 }
   1153 
   1154 /* initialize policy in PCB */
   1155 int
   1156 ipsec_init_policy(struct socket *so, struct inpcbpolicy **policy)
   1157 {
   1158 	struct inpcbpolicy *new;
   1159 
   1160 	KASSERT(so != NULL);
   1161 	KASSERT(policy != NULL);
   1162 
   1163 	new = kmem_intr_zalloc(sizeof(*new), KM_NOSLEEP);
   1164 	if (new == NULL) {
   1165 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   1166 		return ENOBUFS;
   1167 	}
   1168 
   1169 	if (IPSEC_PRIVILEGED_SO(so))
   1170 		new->priv = 1;
   1171 	else
   1172 		new->priv = 0;
   1173 
   1174 	/*
   1175 	 * Set dummy SPs. Actual SPs will be allocated later if needed.
   1176 	 */
   1177 	new->sp_in = &ipsec_dummy_sp;
   1178 	new->sp_out = &ipsec_dummy_sp;
   1179 
   1180 	*policy = new;
   1181 
   1182 	return 0;
   1183 }
   1184 
   1185 #if 0 /* unused */
   1186 /* copy old ipsec policy into new */
   1187 int
   1188 ipsec_copy_policy(const struct inpcbpolicy *old, struct inpcbpolicy *new)
   1189 {
   1190 	struct secpolicy *sp;
   1191 
   1192 	sp = ipsec_deepcopy_policy(old->sp_in);
   1193 	if (sp) {
   1194 		KEY_SP_UNREF(&new->sp_in);
   1195 		new->sp_in = sp;
   1196 	} else
   1197 		return ENOBUFS;
   1198 
   1199 	sp = ipsec_deepcopy_policy(old->sp_out);
   1200 	if (sp) {
   1201 		KEY_SP_UNREF(&new->sp_out);
   1202 		new->sp_out = sp;
   1203 	} else
   1204 		return ENOBUFS;
   1205 
   1206 	new->priv = old->priv;
   1207 
   1208 	return 0;
   1209 }
   1210 
   1211 /* deep-copy a policy in PCB */
   1212 static struct secpolicy *
   1213 ipsec_deepcopy_policy(const struct secpolicy *src)
   1214 {
   1215 	struct ipsecrequest *newchain = NULL;
   1216 	const struct ipsecrequest *p;
   1217 	struct ipsecrequest **q;
   1218 	struct secpolicy *dst;
   1219 
   1220 	if (src == NULL)
   1221 		return NULL;
   1222 	dst = KEY_NEWSP();
   1223 	if (dst == NULL)
   1224 		return NULL;
   1225 
   1226 	/*
   1227 	 * deep-copy IPsec request chain.  This is required since struct
   1228 	 * ipsecrequest is not reference counted.
   1229 	 */
   1230 	q = &newchain;
   1231 	for (p = src->req; p; p = p->next) {
   1232 		*q = kmem_zalloc(sizeof(**q), KM_SLEEP);
   1233 		(*q)->next = NULL;
   1234 
   1235 		(*q)->saidx.proto = p->saidx.proto;
   1236 		(*q)->saidx.mode = p->saidx.mode;
   1237 		(*q)->level = p->level;
   1238 		(*q)->saidx.reqid = p->saidx.reqid;
   1239 
   1240 		memcpy(&(*q)->saidx.src, &p->saidx.src, sizeof((*q)->saidx.src));
   1241 		memcpy(&(*q)->saidx.dst, &p->saidx.dst, sizeof((*q)->saidx.dst));
   1242 
   1243 		(*q)->sp = dst;
   1244 
   1245 		q = &((*q)->next);
   1246 	}
   1247 
   1248 	dst->req = newchain;
   1249 	dst->state = src->state;
   1250 	dst->policy = src->policy;
   1251 	/* do not touch the refcnt fields */
   1252 
   1253 	return dst;
   1254 }
   1255 #endif
   1256 
   1257 static void
   1258 ipsec_destroy_policy(struct secpolicy *sp)
   1259 {
   1260 
   1261 	if (sp == &ipsec_dummy_sp)
   1262 		; /* It's dummy. No need to free it. */
   1263 	else {
   1264 		/*
   1265 		 * We cannot destroy here because it can be called in
   1266 		 * softint. So mark the SP as DEAD and let the timer
   1267 		 * destroy it. See key_timehandler_spd.
   1268 		 */
   1269 		sp->state = IPSEC_SPSTATE_DEAD;
   1270 	}
   1271 }
   1272 
   1273 int
   1274 ipsec_set_policy(void *inp, int optname, const void *request, size_t len,
   1275     kauth_cred_t cred)
   1276 {
   1277 	struct inpcb_hdr *inph = (struct inpcb_hdr *)inp;
   1278 	const struct sadb_x_policy *xpl;
   1279 	struct secpolicy *newsp, *oldsp;
   1280 	struct secpolicy **policy;
   1281 	int error;
   1282 
   1283 	KASSERT(!cpu_softintr_p());
   1284 	KASSERT(inph != NULL);
   1285 	KASSERT(inph_locked(inph));
   1286 	KASSERT(request != NULL);
   1287 
   1288 	if (len < sizeof(*xpl))
   1289 		return EINVAL;
   1290 	xpl = (const struct sadb_x_policy *)request;
   1291 
   1292 	KASSERT(inph->inph_sp != NULL);
   1293 
   1294 	/* select direction */
   1295 	switch (xpl->sadb_x_policy_dir) {
   1296 	case IPSEC_DIR_INBOUND:
   1297 		policy = &inph->inph_sp->sp_in;
   1298 		break;
   1299 	case IPSEC_DIR_OUTBOUND:
   1300 		policy = &inph->inph_sp->sp_out;
   1301 		break;
   1302 	default:
   1303 		IPSECLOG(LOG_ERR, "invalid direction=%u\n",
   1304 		    xpl->sadb_x_policy_dir);
   1305 		return EINVAL;
   1306 	}
   1307 
   1308 	/* sanity check. */
   1309 	if (policy == NULL || *policy == NULL)
   1310 		return EINVAL;
   1311 
   1312 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1313 		kdebug_sadb_xpolicy("set passed policy", request);
   1314 	}
   1315 
   1316 	/* check policy type */
   1317 	/* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
   1318 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD ||
   1319 	    xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
   1320 		return EINVAL;
   1321 
   1322 	/* check privileged socket */
   1323 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
   1324 		error = kauth_authorize_network(cred, KAUTH_NETWORK_IPSEC,
   1325 		    KAUTH_REQ_NETWORK_IPSEC_BYPASS, NULL, NULL, NULL);
   1326 		if (error)
   1327 			return error;
   1328 	}
   1329 
   1330 	/* allocation new SP entry */
   1331 	if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
   1332 		return error;
   1333 
   1334 	key_init_sp(newsp);
   1335 	newsp->created = time_uptime;
   1336 	/* Insert the global list for SPs for sockets */
   1337 	key_socksplist_add(newsp);
   1338 
   1339 	/* clear old SP and set new SP */
   1340 	oldsp = *policy;
   1341 	*policy = newsp;
   1342 	ipsec_destroy_policy(oldsp);
   1343 
   1344 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1345 		printf("%s: new policy\n", __func__);
   1346 		kdebug_secpolicy(newsp);
   1347 	}
   1348 
   1349 	return 0;
   1350 }
   1351 
   1352 int
   1353 ipsec_get_policy(void *inp, const void *request, size_t len,
   1354     struct mbuf **mp)
   1355 {
   1356 	struct inpcb_hdr *inph = (struct inpcb_hdr *)inp;
   1357 	const struct sadb_x_policy *xpl;
   1358 	struct secpolicy *policy;
   1359 
   1360 	/* sanity check. */
   1361 	if (inph == NULL || request == NULL || mp == NULL)
   1362 		return EINVAL;
   1363 	KASSERT(inph->inph_sp != NULL);
   1364 	if (len < sizeof(*xpl))
   1365 		return EINVAL;
   1366 	xpl = (const struct sadb_x_policy *)request;
   1367 
   1368 	/* select direction */
   1369 	switch (xpl->sadb_x_policy_dir) {
   1370 	case IPSEC_DIR_INBOUND:
   1371 		policy = inph->inph_sp->sp_in;
   1372 		break;
   1373 	case IPSEC_DIR_OUTBOUND:
   1374 		policy = inph->inph_sp->sp_out;
   1375 		break;
   1376 	default:
   1377 		IPSECLOG(LOG_ERR, "invalid direction=%u\n",
   1378 		    xpl->sadb_x_policy_dir);
   1379 		return EINVAL;
   1380 	}
   1381 
   1382 	if (policy == NULL)
   1383 		return EINVAL;
   1384 
   1385 	*mp = key_sp2msg(policy, M_NOWAIT);
   1386 	if (!*mp) {
   1387 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   1388 		return ENOBUFS;
   1389 	}
   1390 
   1391 	(*mp)->m_type = MT_DATA;
   1392 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
   1393 		kdebug_mbuf(__func__, *mp);
   1394 	}
   1395 
   1396 	return 0;
   1397 }
   1398 
   1399 int
   1400 ipsec_delete_pcbpolicy(void *inp)
   1401 {
   1402 	struct inpcb_hdr *inph = (struct inpcb_hdr *)inp;
   1403 
   1404 	KASSERT(inph != NULL);
   1405 
   1406 	if (inph->inph_sp == NULL)
   1407 		return 0;
   1408 
   1409 	if (inph->inph_sp->sp_in != NULL)
   1410 		ipsec_destroy_policy(inph->inph_sp->sp_in);
   1411 
   1412 	if (inph->inph_sp->sp_out != NULL)
   1413 		ipsec_destroy_policy(inph->inph_sp->sp_out);
   1414 
   1415 	ipsec_invalpcbcache(inph->inph_sp, IPSEC_DIR_ANY);
   1416 
   1417 	ipsec_delpcbpolicy(inph->inph_sp);
   1418 	inph->inph_sp = NULL;
   1419 
   1420 	return 0;
   1421 }
   1422 
   1423 /*
   1424  * Return the current level (either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE).
   1425  */
   1426 u_int
   1427 ipsec_get_reqlevel(const struct ipsecrequest *isr)
   1428 {
   1429 	u_int level = 0;
   1430 	u_int esp_trans_deflev, esp_net_deflev;
   1431 	u_int ah_trans_deflev, ah_net_deflev;
   1432 
   1433 	KASSERT(isr != NULL);
   1434 	KASSERT(isr->sp != NULL);
   1435 	KASSERTMSG(
   1436 	    isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family,
   1437 	    "af family mismatch, src %u, dst %u",
   1438 	    isr->sp->spidx.src.sa.sa_family, isr->sp->spidx.dst.sa.sa_family);
   1439 
   1440 /* XXX note that we have ipseclog() expanded here - code sync issue */
   1441 #define IPSEC_CHECK_DEFAULT(lev)					\
   1442     (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE		\
   1443     && (lev) != IPSEC_LEVEL_UNIQUE) ?					\
   1444 	(ipsec_debug ? log(LOG_INFO, "fixed system default level " #lev \
   1445 	":%d->%d\n", (lev), IPSEC_LEVEL_REQUIRE) : (void)0),		\
   1446 	(lev) = IPSEC_LEVEL_REQUIRE, (lev)				\
   1447     : (lev))
   1448 
   1449 	/* set default level */
   1450 	switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
   1451 #ifdef INET
   1452 	case AF_INET:
   1453 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
   1454 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
   1455 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
   1456 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
   1457 		break;
   1458 #endif
   1459 #ifdef INET6
   1460 	case AF_INET6:
   1461 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
   1462 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
   1463 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
   1464 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
   1465 		break;
   1466 #endif /* INET6 */
   1467 	default:
   1468 		panic("%s: unknown af %u", __func__,
   1469 		    isr->sp->spidx.src.sa.sa_family);
   1470 	}
   1471 
   1472 #undef IPSEC_CHECK_DEFAULT
   1473 
   1474 	/* set level */
   1475 	switch (isr->level) {
   1476 	case IPSEC_LEVEL_DEFAULT:
   1477 		switch (isr->saidx.proto) {
   1478 		case IPPROTO_ESP:
   1479 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
   1480 				level = esp_net_deflev;
   1481 			else
   1482 				level = esp_trans_deflev;
   1483 			break;
   1484 		case IPPROTO_AH:
   1485 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
   1486 				level = ah_net_deflev;
   1487 			else
   1488 				level = ah_trans_deflev;
   1489 			break;
   1490 		case IPPROTO_IPCOMP:
   1491 			/*
   1492 			 * we don't really care, as IPcomp document says that
   1493 			 * we shouldn't compress small packets
   1494 			 */
   1495 			level = IPSEC_LEVEL_USE;
   1496 			break;
   1497 		default:
   1498 			panic("%s: Illegal protocol defined %u", __func__,
   1499 			    isr->saidx.proto);
   1500 		}
   1501 		break;
   1502 
   1503 	case IPSEC_LEVEL_USE:
   1504 	case IPSEC_LEVEL_REQUIRE:
   1505 		level = isr->level;
   1506 		break;
   1507 	case IPSEC_LEVEL_UNIQUE:
   1508 		level = IPSEC_LEVEL_REQUIRE;
   1509 		break;
   1510 
   1511 	default:
   1512 		panic("%s: Illegal IPsec level %u", __func__, isr->level);
   1513 	}
   1514 
   1515 	return level;
   1516 }
   1517 
   1518 /*
   1519  * Check security policy requirements against the actual packet contents.
   1520  *
   1521  * If the SP requires an IPsec packet, and the packet was neither AH nor ESP,
   1522  * then kick it.
   1523  */
   1524 int
   1525 ipsec_sp_reject(const struct secpolicy *sp, const struct mbuf *m)
   1526 {
   1527 	struct ipsecrequest *isr;
   1528 
   1529 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
   1530 		printf("%s: using SP\n", __func__);
   1531 		kdebug_secpolicy(sp);
   1532 	}
   1533 
   1534 	/* check policy */
   1535 	switch (sp->policy) {
   1536 	case IPSEC_POLICY_DISCARD:
   1537 		return 1;
   1538 	case IPSEC_POLICY_BYPASS:
   1539 	case IPSEC_POLICY_NONE:
   1540 		return 0;
   1541 	}
   1542 
   1543 	KASSERTMSG(sp->policy == IPSEC_POLICY_IPSEC,
   1544 	    "invalid policy %u", sp->policy);
   1545 
   1546 	/* XXX should compare policy against ipsec header history */
   1547 
   1548 	for (isr = sp->req; isr != NULL; isr = isr->next) {
   1549 		if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
   1550 			continue;
   1551 		switch (isr->saidx.proto) {
   1552 		case IPPROTO_ESP:
   1553 			if ((m->m_flags & M_DECRYPTED) == 0) {
   1554 				KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1555 				    "ESP m_flags:%x\n", m->m_flags);
   1556 				return 1;
   1557 			}
   1558 			break;
   1559 		case IPPROTO_AH:
   1560 			if ((m->m_flags & M_AUTHIPHDR) == 0) {
   1561 				KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
   1562 				    "AH m_flags:%x\n", m->m_flags);
   1563 				return 1;
   1564 			}
   1565 			break;
   1566 		case IPPROTO_IPCOMP:
   1567 			/*
   1568 			 * We don't really care, as IPcomp document
   1569 			 * says that we shouldn't compress small
   1570 			 * packets, IPComp policy should always be
   1571 			 * treated as being in "use" level.
   1572 			 */
   1573 			break;
   1574 		}
   1575 	}
   1576 
   1577 	return 0;
   1578 }
   1579 
   1580 /*
   1581  * Check security policy requirements.
   1582  */
   1583 int
   1584 ipsec_in_reject(struct mbuf *m, void *inp)
   1585 {
   1586 	struct inpcb_hdr *inph = (struct inpcb_hdr *)inp;
   1587 	struct secpolicy *sp;
   1588 	int error;
   1589 	int result;
   1590 
   1591 	KASSERT(m != NULL);
   1592 
   1593 	if (inph == NULL)
   1594 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
   1595 		    IP_FORWARDING, &error);
   1596 	else
   1597 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
   1598 		    inph, &error);
   1599 
   1600 	if (sp != NULL) {
   1601 		result = ipsec_sp_reject(sp, m);
   1602 		if (result)
   1603 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
   1604 		KEY_SP_UNREF(&sp);
   1605 	} else {
   1606 		result = 0;
   1607 	}
   1608 	return result;
   1609 }
   1610 
   1611 /*
   1612  * Compute the byte size to be occupied by the IPsec header. If it is
   1613  * tunneled, it includes the size of outer IP header.
   1614  */
   1615 static size_t
   1616 ipsec_sp_hdrsiz(const struct secpolicy *sp, const struct mbuf *m)
   1617 {
   1618 	struct ipsecrequest *isr;
   1619 	size_t siz;
   1620 
   1621 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
   1622 		printf("%s: using SP\n", __func__);
   1623 		kdebug_secpolicy(sp);
   1624 	}
   1625 
   1626 	switch (sp->policy) {
   1627 	case IPSEC_POLICY_DISCARD:
   1628 	case IPSEC_POLICY_BYPASS:
   1629 	case IPSEC_POLICY_NONE:
   1630 		return 0;
   1631 	}
   1632 
   1633 	KASSERTMSG(sp->policy == IPSEC_POLICY_IPSEC,
   1634 	    "invalid policy %u", sp->policy);
   1635 
   1636 	siz = 0;
   1637 	for (isr = sp->req; isr != NULL; isr = isr->next) {
   1638 		size_t clen = 0;
   1639 		struct secasvar *sav;
   1640 
   1641 		switch (isr->saidx.proto) {
   1642 		case IPPROTO_ESP:
   1643 			sav = ipsec_lookup_sa(isr, m);
   1644 			if (sav != NULL) {
   1645 				clen = esp_hdrsiz(sav);
   1646 				KEY_SA_UNREF(&sav);
   1647 			} else
   1648 				clen = esp_hdrsiz(NULL);
   1649 			break;
   1650 		case IPPROTO_AH:
   1651 			sav = ipsec_lookup_sa(isr, m);
   1652 			if (sav != NULL) {
   1653 				clen = ah_hdrsiz(sav);
   1654 				KEY_SA_UNREF(&sav);
   1655 			} else
   1656 				clen = ah_hdrsiz(NULL);
   1657 			break;
   1658 		case IPPROTO_IPCOMP:
   1659 			clen = sizeof(struct ipcomp);
   1660 			break;
   1661 		}
   1662 
   1663 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
   1664 			switch (isr->saidx.dst.sa.sa_family) {
   1665 			case AF_INET:
   1666 				clen += sizeof(struct ip);
   1667 				break;
   1668 #ifdef INET6
   1669 			case AF_INET6:
   1670 				clen += sizeof(struct ip6_hdr);
   1671 				break;
   1672 #endif
   1673 			default:
   1674 				IPSECLOG(LOG_ERR, "unknown AF %d in "
   1675 				    "IPsec tunnel SA\n",
   1676 				    ((const struct sockaddr *)&isr->saidx.dst)
   1677 				    ->sa_family);
   1678 				break;
   1679 			}
   1680 		}
   1681 		siz += clen;
   1682 	}
   1683 
   1684 	return siz;
   1685 }
   1686 
   1687 size_t
   1688 ipsec_hdrsiz(struct mbuf *m, u_int dir, void *inp)
   1689 {
   1690 	struct inpcb_hdr *inph = (struct inpcb_hdr *)inp;
   1691 	struct secpolicy *sp;
   1692 	int error;
   1693 	size_t size;
   1694 
   1695 	KASSERT(m != NULL);
   1696 	KASSERTMSG(inph == NULL || inph->inph_socket != NULL,
   1697 	    "socket w/o inpcb");
   1698 
   1699 	if (inph == NULL)
   1700 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
   1701 	else
   1702 		sp = ipsec_getpolicybysock(m, dir, inph, &error);
   1703 
   1704 	if (sp != NULL) {
   1705 		size = ipsec_sp_hdrsiz(sp, m);
   1706 		KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DATA, "size:%zu.\n", size);
   1707 		KEY_SP_UNREF(&sp);
   1708 	} else {
   1709 		size = 0;
   1710 	}
   1711 
   1712 	return size;
   1713 }
   1714 
   1715 /*
   1716  * Check the variable replay window.
   1717  * ipsec_chkreplay() performs replay check before ICV verification.
   1718  * ipsec_updatereplay() updates replay bitmap.  This must be called after
   1719  * ICV verification (it also performs replay check, which is usually done
   1720  * beforehand).
   1721  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
   1722  *
   1723  * based on RFC 2401.
   1724  */
   1725 int
   1726 ipsec_chkreplay(u_int32_t seq, const struct secasvar *sav)
   1727 {
   1728 	const struct secreplay *replay;
   1729 	u_int32_t diff;
   1730 	int fr;
   1731 	u_int32_t wsizeb;	/* constant: bits of window size */
   1732 	int frlast;		/* constant: last frame */
   1733 
   1734 	IPSEC_SPLASSERT_SOFTNET(__func__);
   1735 
   1736 	KASSERT(sav != NULL);
   1737 	KASSERT(sav->replay != NULL);
   1738 
   1739 	replay = sav->replay;
   1740 
   1741 	if (replay->wsize == 0)
   1742 		return 1;	/* no need to check replay. */
   1743 
   1744 	/* constant */
   1745 	frlast = replay->wsize - 1;
   1746 	wsizeb = replay->wsize << 3;
   1747 
   1748 	/* sequence number of 0 is invalid */
   1749 	if (seq == 0)
   1750 		return 0;
   1751 
   1752 	/* first time is always okay */
   1753 	if (replay->count == 0)
   1754 		return 1;
   1755 
   1756 	if (seq > replay->lastseq) {
   1757 		/* larger sequences are okay */
   1758 		return 1;
   1759 	} else {
   1760 		/* seq is equal or less than lastseq. */
   1761 		diff = replay->lastseq - seq;
   1762 
   1763 		/* over range to check, i.e. too old or wrapped */
   1764 		if (diff >= wsizeb)
   1765 			return 0;
   1766 
   1767 		fr = frlast - diff / 8;
   1768 
   1769 		/* this packet already seen ? */
   1770 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
   1771 			return 0;
   1772 
   1773 		/* out of order but good */
   1774 		return 1;
   1775 	}
   1776 }
   1777 
   1778 /*
   1779  * check replay counter whether to update or not.
   1780  * OUT:	0:	OK
   1781  *	1:	NG
   1782  */
   1783 int
   1784 ipsec_updatereplay(u_int32_t seq, const struct secasvar *sav)
   1785 {
   1786 	struct secreplay *replay;
   1787 	u_int32_t diff;
   1788 	int fr;
   1789 	u_int32_t wsizeb;	/* constant: bits of window size */
   1790 	int frlast;		/* constant: last frame */
   1791 
   1792 	IPSEC_SPLASSERT_SOFTNET(__func__);
   1793 
   1794 	KASSERT(sav != NULL);
   1795 	KASSERT(sav->replay != NULL);
   1796 
   1797 	replay = sav->replay;
   1798 
   1799 	if (replay->wsize == 0)
   1800 		goto ok;	/* no need to check replay. */
   1801 
   1802 	/* constant */
   1803 	frlast = replay->wsize - 1;
   1804 	wsizeb = replay->wsize << 3;
   1805 
   1806 	/* sequence number of 0 is invalid */
   1807 	if (seq == 0)
   1808 		return 1;
   1809 
   1810 	/* first time */
   1811 	if (replay->count == 0) {
   1812 		replay->lastseq = seq;
   1813 		memset(replay->bitmap, 0, replay->wsize);
   1814 		(replay->bitmap)[frlast] = 1;
   1815 		goto ok;
   1816 	}
   1817 
   1818 	if (seq > replay->lastseq) {
   1819 		/* seq is larger than lastseq. */
   1820 		diff = seq - replay->lastseq;
   1821 
   1822 		/* new larger sequence number */
   1823 		if (diff < wsizeb) {
   1824 			/* In window */
   1825 			/* set bit for this packet */
   1826 			vshiftl(replay->bitmap, diff, replay->wsize);
   1827 			(replay->bitmap)[frlast] |= 1;
   1828 		} else {
   1829 			/* this packet has a "way larger" */
   1830 			memset(replay->bitmap, 0, replay->wsize);
   1831 			(replay->bitmap)[frlast] = 1;
   1832 		}
   1833 		replay->lastseq = seq;
   1834 
   1835 		/* larger is good */
   1836 	} else {
   1837 		/* seq is equal or less than lastseq. */
   1838 		diff = replay->lastseq - seq;
   1839 
   1840 		/* over range to check, i.e. too old or wrapped */
   1841 		if (diff >= wsizeb)
   1842 			return 1;
   1843 
   1844 		fr = frlast - diff / 8;
   1845 
   1846 		/* this packet already seen ? */
   1847 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
   1848 			return 1;
   1849 
   1850 		/* mark as seen */
   1851 		(replay->bitmap)[fr] |= (1 << (diff % 8));
   1852 
   1853 		/* out of order but good */
   1854 	}
   1855 
   1856 ok:
   1857 	if (replay->count == ~0) {
   1858 		char buf[IPSEC_LOGSASTRLEN];
   1859 
   1860 		/* set overflow flag */
   1861 		replay->overflow++;
   1862 
   1863 		/* don't increment, no more packets accepted */
   1864 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
   1865 			return 1;
   1866 
   1867 		IPSECLOG(LOG_WARNING, "replay counter made %d cycle. %s\n",
   1868 		    replay->overflow, ipsec_logsastr(sav, buf, sizeof(buf)));
   1869 	}
   1870 
   1871 	replay->count++;
   1872 
   1873 	return 0;
   1874 }
   1875 
   1876 /*
   1877  * shift variable length buffer to left.
   1878  * IN:	bitmap: pointer to the buffer
   1879  *	nbit:	the number of to shift.
   1880  *	wsize:	buffer size (bytes).
   1881  */
   1882 static void
   1883 vshiftl(unsigned char *bitmap, int nbit, int wsize)
   1884 {
   1885 	int s, j, i;
   1886 	unsigned char over;
   1887 
   1888 	for (j = 0; j < nbit; j += 8) {
   1889 		s = (nbit - j < 8) ? (nbit - j): 8;
   1890 		bitmap[0] <<= s;
   1891 		for (i = 1; i < wsize; i++) {
   1892 			over = (bitmap[i] >> (8 - s));
   1893 			bitmap[i] <<= s;
   1894 			bitmap[i-1] |= over;
   1895 		}
   1896 	}
   1897 
   1898 	return;
   1899 }
   1900 
   1901 /* Return a printable string for the address. */
   1902 const char *
   1903 ipsec_address(const union sockaddr_union *sa, char *buf, size_t size)
   1904 {
   1905 	switch (sa->sa.sa_family) {
   1906 #if INET
   1907 	case AF_INET:
   1908 		in_print(buf, size, &sa->sin.sin_addr);
   1909 		return buf;
   1910 #endif
   1911 #if INET6
   1912 	case AF_INET6:
   1913 		in6_print(buf, size, &sa->sin6.sin6_addr);
   1914 		return buf;
   1915 #endif
   1916 	default:
   1917 		return "(unknown address family)";
   1918 	}
   1919 }
   1920 
   1921 const char *
   1922 ipsec_logsastr(const struct secasvar *sav, char *buf, size_t size)
   1923 {
   1924 	const struct secasindex *saidx = &sav->sah->saidx;
   1925 	char sbuf[IPSEC_ADDRSTRLEN], dbuf[IPSEC_ADDRSTRLEN];
   1926 
   1927 	KASSERTMSG(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
   1928 	    "af family mismatch, src %u, dst %u",
   1929 	    saidx->src.sa.sa_family, saidx->dst.sa.sa_family);
   1930 
   1931 	snprintf(buf, size, "SA(SPI=%u src=%s dst=%s)",
   1932 	    (u_int32_t)ntohl(sav->spi),
   1933 	    ipsec_address(&saidx->src, sbuf, sizeof(sbuf)),
   1934 	    ipsec_address(&saidx->dst, dbuf, sizeof(dbuf)));
   1935 
   1936 	return buf;
   1937 }
   1938 
   1939 void
   1940 ipsec_dumpmbuf(struct mbuf *m)
   1941 {
   1942 	int totlen;
   1943 	int i;
   1944 	u_char *p;
   1945 
   1946 	totlen = 0;
   1947 	printf("---\n");
   1948 	while (m) {
   1949 		p = mtod(m, u_char *);
   1950 		for (i = 0; i < m->m_len; i++) {
   1951 			printf("%02x ", p[i]);
   1952 			totlen++;
   1953 			if (totlen % 16 == 0)
   1954 				printf("\n");
   1955 		}
   1956 		m = m->m_next;
   1957 	}
   1958 	if (totlen % 16 != 0)
   1959 		printf("\n");
   1960 	printf("---\n");
   1961 }
   1962 
   1963 #ifdef INET6
   1964 struct secpolicy *
   1965 ipsec6_check_policy(struct mbuf *m, struct in6pcb *in6p, int flags,
   1966     int *needipsecp, int *errorp)
   1967 {
   1968 	struct secpolicy *sp = NULL;
   1969 	int s;
   1970 	int error = 0;
   1971 	int needipsec = 0;
   1972 
   1973 	if (!ipsec_outdone(m)) {
   1974 		s = splsoftnet();
   1975 		if (in6p != NULL &&
   1976 		    ipsec_pcb_skip_ipsec(in6p->in6p_sp, IPSEC_DIR_OUTBOUND)) {
   1977 			splx(s);
   1978 			goto skippolicycheck;
   1979 		}
   1980 		sp = ipsec_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error,
   1981 		    in6p);
   1982 
   1983 		/*
   1984 		 * There are four return cases:
   1985 		 *	sp != NULL			apply IPsec policy
   1986 		 *	sp == NULL, error == 0		no IPsec handling needed
   1987 		 *	sp == NULL, error == -EINVAL  discard packet w/o error
   1988 		 *	sp == NULL, error != 0		discard packet, report error
   1989 		 */
   1990 
   1991 		splx(s);
   1992 		if (sp == NULL) {
   1993 			/*
   1994 			 * Caller must check the error return to see if it needs to discard
   1995 			 * the packet.
   1996 			 */
   1997 			needipsec = 0;
   1998 		} else {
   1999 			needipsec = 1;
   2000 		}
   2001 	}
   2002 skippolicycheck:;
   2003 
   2004 	*errorp = error;
   2005 	*needipsecp = needipsec;
   2006 	return sp;
   2007 }
   2008 
   2009 int
   2010 ipsec6_input(struct mbuf *m)
   2011 {
   2012 	int s, error;
   2013 
   2014 	s = splsoftnet();
   2015 	error = ipsec_in_reject(m, NULL);
   2016 	splx(s);
   2017 	if (error) {
   2018 		return EINVAL;
   2019 	}
   2020 
   2021 	return 0;
   2022 }
   2023 #endif /* INET6 */
   2024 
   2025 /*
   2026  * -----------------------------------------------------------------------------
   2027  */
   2028 
   2029 /* XXX this stuff doesn't belong here... */
   2030 
   2031 static struct xformsw *xforms = NULL;
   2032 
   2033 /*
   2034  * Register a transform; typically at system startup.
   2035  */
   2036 void
   2037 xform_register(struct xformsw *xsp)
   2038 {
   2039 	xsp->xf_next = xforms;
   2040 	xforms = xsp;
   2041 }
   2042 
   2043 /*
   2044  * Initialize transform support in an sav.
   2045  */
   2046 int
   2047 xform_init(struct secasvar *sav, int xftype)
   2048 {
   2049 	struct xformsw *xsp;
   2050 
   2051 	if (sav->tdb_xform != NULL)	/* previously initialized */
   2052 		return 0;
   2053 	for (xsp = xforms; xsp; xsp = xsp->xf_next)
   2054 		if (xsp->xf_type == xftype)
   2055 			return (*xsp->xf_init)(sav, xsp);
   2056 
   2057 	IPSECLOG(LOG_DEBUG, "no match for xform type %d\n", xftype);
   2058 	return EINVAL;
   2059 }
   2060 
   2061 void
   2062 nat_t_ports_get(struct mbuf *m, u_int16_t *dport, u_int16_t *sport)
   2063 {
   2064 	struct m_tag *tag;
   2065 
   2066 	if ((tag = m_tag_find(m, PACKET_TAG_IPSEC_NAT_T_PORTS, NULL))) {
   2067 		*sport = ((u_int16_t *)(tag + 1))[0];
   2068 		*dport = ((u_int16_t *)(tag + 1))[1];
   2069 	} else
   2070 		*sport = *dport = 0;
   2071 }
   2072 
   2073 /*
   2074  * XXXJRT This should be done as a protosw init call.
   2075  */
   2076 void
   2077 ipsec_attach(void)
   2078 {
   2079 
   2080 	ipsec_output_init();
   2081 
   2082 	ipsecstat_percpu = percpu_alloc(sizeof(uint64_t) * IPSEC_NSTATS);
   2083 
   2084 	sysctl_net_inet_ipsec_setup(NULL);
   2085 #ifdef INET6
   2086 	sysctl_net_inet6_ipsec6_setup(NULL);
   2087 #endif
   2088 
   2089 	ah_attach();
   2090 	esp_attach();
   2091 	ipcomp_attach();
   2092 	ipe4_attach();
   2093 #ifdef TCP_SIGNATURE
   2094 	tcpsignature_attach();
   2095 #endif
   2096 }
   2097