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