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