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