Home | History | Annotate | Line # | Download | only in netipsec
key.c revision 1.193
      1 /*	$NetBSD: key.c,v 1.193 2017/07/26 03:59:59 ozaki-r Exp $	*/
      2 /*	$FreeBSD: src/sys/netipsec/key.c,v 1.3.2.3 2004/02/14 22:23:23 bms Exp $	*/
      3 /*	$KAME: key.c,v 1.191 2001/06/27 10:46:49 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: key.c,v 1.193 2017/07/26 03:59:59 ozaki-r Exp $");
     36 
     37 /*
     38  * This code is referd to RFC 2367
     39  */
     40 
     41 #if defined(_KERNEL_OPT)
     42 #include "opt_inet.h"
     43 #include "opt_ipsec.h"
     44 #include "opt_gateway.h"
     45 #endif
     46 
     47 #include <sys/types.h>
     48 #include <sys/param.h>
     49 #include <sys/systm.h>
     50 #include <sys/callout.h>
     51 #include <sys/kernel.h>
     52 #include <sys/mbuf.h>
     53 #include <sys/domain.h>
     54 #include <sys/socket.h>
     55 #include <sys/socketvar.h>
     56 #include <sys/sysctl.h>
     57 #include <sys/errno.h>
     58 #include <sys/proc.h>
     59 #include <sys/queue.h>
     60 #include <sys/syslog.h>
     61 #include <sys/once.h>
     62 #include <sys/cprng.h>
     63 #include <sys/psref.h>
     64 #include <sys/lwp.h>
     65 #include <sys/workqueue.h>
     66 #include <sys/kmem.h>
     67 #include <sys/cpu.h>
     68 #include <sys/atomic.h>
     69 
     70 #include <net/if.h>
     71 #include <net/route.h>
     72 
     73 #include <netinet/in.h>
     74 #include <netinet/in_systm.h>
     75 #include <netinet/ip.h>
     76 #include <netinet/in_var.h>
     77 #ifdef INET
     78 #include <netinet/ip_var.h>
     79 #endif
     80 
     81 #ifdef INET6
     82 #include <netinet/ip6.h>
     83 #include <netinet6/in6_var.h>
     84 #include <netinet6/ip6_var.h>
     85 #endif /* INET6 */
     86 
     87 #ifdef INET
     88 #include <netinet/in_pcb.h>
     89 #endif
     90 #ifdef INET6
     91 #include <netinet6/in6_pcb.h>
     92 #endif /* INET6 */
     93 
     94 #include <net/pfkeyv2.h>
     95 #include <netipsec/keydb.h>
     96 #include <netipsec/key.h>
     97 #include <netipsec/keysock.h>
     98 #include <netipsec/key_debug.h>
     99 
    100 #include <netipsec/ipsec.h>
    101 #ifdef INET6
    102 #include <netipsec/ipsec6.h>
    103 #endif
    104 #include <netipsec/ipsec_private.h>
    105 
    106 #include <netipsec/xform.h>
    107 #include <netipsec/ipcomp.h>
    108 
    109 
    110 #include <net/net_osdep.h>
    111 
    112 #define FULLMASK	0xff
    113 #define	_BITS(bytes)	((bytes) << 3)
    114 
    115 #define PORT_NONE	0
    116 #define PORT_LOOSE	1
    117 #define PORT_STRICT	2
    118 
    119 percpu_t *pfkeystat_percpu;
    120 
    121 /*
    122  * Note on SA reference counting:
    123  * - SAs that are not in DEAD state will have (total external reference + 1)
    124  *   following value in reference count field.  they cannot be freed and are
    125  *   referenced from SA header.
    126  * - SAs that are in DEAD state will have (total external reference)
    127  *   in reference count field.  they are ready to be freed.  reference from
    128  *   SA header will be removed in key_delsav(), when the reference count
    129  *   field hits 0 (= no external reference other than from SA header.
    130  */
    131 
    132 u_int32_t key_debug_level = 0;
    133 static u_int key_spi_trycnt = 1000;
    134 static u_int32_t key_spi_minval = 0x100;
    135 static u_int32_t key_spi_maxval = 0x0fffffff;	/* XXX */
    136 static u_int32_t policy_id = 0;
    137 static u_int key_int_random = 60;	/*interval to initialize randseed,1(m)*/
    138 static u_int key_larval_lifetime = 30;	/* interval to expire acquiring, 30(s)*/
    139 static int key_blockacq_count = 10;	/* counter for blocking SADB_ACQUIRE.*/
    140 static int key_blockacq_lifetime = 20;	/* lifetime for blocking SADB_ACQUIRE.*/
    141 static int key_prefered_oldsa = 0;	/* prefered old sa rather than new sa.*/
    142 
    143 static u_int32_t acq_seq = 0;
    144 
    145 static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];	/* SPD */
    146 static LIST_HEAD(_sahtree, secashead) sahtree;			/* SAD */
    147 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
    148 							/* registed list */
    149 #ifndef IPSEC_NONBLOCK_ACQUIRE
    150 static LIST_HEAD(_acqtree, secacq) acqtree;		/* acquiring list */
    151 #endif
    152 #ifdef notyet
    153 static LIST_HEAD(_spacqtree, secspacq) spacqtree;	/* SP acquiring list */
    154 #endif
    155 
    156 /*
    157  * Protect regtree, acqtree and items stored in the lists.
    158  */
    159 static kmutex_t key_mtx __cacheline_aligned;
    160 
    161 /* search order for SAs */
    162 	/*
    163 	 * This order is important because we must select the oldest SA
    164 	 * for outbound processing.  For inbound, This is not important.
    165 	 */
    166 static const u_int saorder_state_valid_prefer_old[] = {
    167 	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
    168 };
    169 static const u_int saorder_state_valid_prefer_new[] = {
    170 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
    171 };
    172 
    173 static const u_int saorder_state_alive[] = {
    174 	/* except DEAD */
    175 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
    176 };
    177 static const u_int saorder_state_any[] = {
    178 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
    179 	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
    180 };
    181 
    182 #define SASTATE_ALIVE_FOREACH(s)				\
    183 	for (int _i = 0;					\
    184 	    _i < __arraycount(saorder_state_alive) ?		\
    185 	    (s) = saorder_state_alive[_i], true : false;	\
    186 	    _i++)
    187 #define SASTATE_ANY_FOREACH(s)					\
    188 	for (int _i = 0;					\
    189 	    _i < __arraycount(saorder_state_any) ?		\
    190 	    (s) = saorder_state_any[_i], true : false;		\
    191 	    _i++)
    192 
    193 static const int minsize[] = {
    194 	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
    195 	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
    196 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
    197 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
    198 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
    199 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
    200 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
    201 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
    202 	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
    203 	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
    204 	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
    205 	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
    206 	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
    207 	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
    208 	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
    209 	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
    210 	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
    211 	0,				/* SADB_X_EXT_KMPRIVATE */
    212 	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
    213 	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
    214 	sizeof(struct sadb_x_nat_t_type),	/* SADB_X_EXT_NAT_T_TYPE */
    215 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_SPORT */
    216 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_DPORT */
    217 	sizeof(struct sadb_address),		/* SADB_X_EXT_NAT_T_OAI */
    218 	sizeof(struct sadb_address),		/* SADB_X_EXT_NAT_T_OAR */
    219 	sizeof(struct sadb_x_nat_t_frag),	/* SADB_X_EXT_NAT_T_FRAG */
    220 };
    221 static const int maxsize[] = {
    222 	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
    223 	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
    224 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
    225 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
    226 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
    227 	0,				/* SADB_EXT_ADDRESS_SRC */
    228 	0,				/* SADB_EXT_ADDRESS_DST */
    229 	0,				/* SADB_EXT_ADDRESS_PROXY */
    230 	0,				/* SADB_EXT_KEY_AUTH */
    231 	0,				/* SADB_EXT_KEY_ENCRYPT */
    232 	0,				/* SADB_EXT_IDENTITY_SRC */
    233 	0,				/* SADB_EXT_IDENTITY_DST */
    234 	0,				/* SADB_EXT_SENSITIVITY */
    235 	0,				/* SADB_EXT_PROPOSAL */
    236 	0,				/* SADB_EXT_SUPPORTED_AUTH */
    237 	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
    238 	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
    239 	0,				/* SADB_X_EXT_KMPRIVATE */
    240 	0,				/* SADB_X_EXT_POLICY */
    241 	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
    242 	sizeof(struct sadb_x_nat_t_type),	/* SADB_X_EXT_NAT_T_TYPE */
    243 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_SPORT */
    244 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_DPORT */
    245 	0,					/* SADB_X_EXT_NAT_T_OAI */
    246 	0,					/* SADB_X_EXT_NAT_T_OAR */
    247 	sizeof(struct sadb_x_nat_t_frag),	/* SADB_X_EXT_NAT_T_FRAG */
    248 };
    249 
    250 static int ipsec_esp_keymin = 256;
    251 static int ipsec_esp_auth = 0;
    252 static int ipsec_ah_keymin = 128;
    253 
    254 #ifdef SYSCTL_DECL
    255 SYSCTL_DECL(_net_key);
    256 #endif
    257 
    258 #ifdef SYSCTL_INT
    259 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,	CTLFLAG_RW, \
    260 	&key_debug_level,	0,	"");
    261 
    262 /* max count of trial for the decision of spi value */
    263 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY,		spi_trycnt,	CTLFLAG_RW, \
    264 	&key_spi_trycnt,	0,	"");
    265 
    266 /* minimum spi value to allocate automatically. */
    267 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,	spi_minval,	CTLFLAG_RW, \
    268 	&key_spi_minval,	0,	"");
    269 
    270 /* maximun spi value to allocate automatically. */
    271 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,	spi_maxval,	CTLFLAG_RW, \
    272 	&key_spi_maxval,	0,	"");
    273 
    274 /* interval to initialize randseed */
    275 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT,	int_random,	CTLFLAG_RW, \
    276 	&key_int_random,	0,	"");
    277 
    278 /* lifetime for larval SA */
    279 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,	larval_lifetime, CTLFLAG_RW, \
    280 	&key_larval_lifetime,	0,	"");
    281 
    282 /* counter for blocking to send SADB_ACQUIRE to IKEd */
    283 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,	blockacq_count,	CTLFLAG_RW, \
    284 	&key_blockacq_count,	0,	"");
    285 
    286 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
    287 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,	blockacq_lifetime, CTLFLAG_RW, \
    288 	&key_blockacq_lifetime,	0,	"");
    289 
    290 /* ESP auth */
    291 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth, CTLFLAG_RW, \
    292 	&ipsec_esp_auth,	0,	"");
    293 
    294 /* minimum ESP key length */
    295 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN,	esp_keymin, CTLFLAG_RW, \
    296 	&ipsec_esp_keymin,	0,	"");
    297 
    298 /* minimum AH key length */
    299 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin, CTLFLAG_RW, \
    300 	&ipsec_ah_keymin,	0,	"");
    301 
    302 /* perfered old SA rather than new SA */
    303 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,	prefered_oldsa, CTLFLAG_RW,\
    304 	&key_prefered_oldsa,	0,	"");
    305 #endif /* SYSCTL_INT */
    306 
    307 #define __LIST_CHAINED(elm) \
    308 	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
    309 #define LIST_INSERT_TAIL(head, elm, type, field) \
    310 do {\
    311 	struct type *curelm = LIST_FIRST(head); \
    312 	if (curelm == NULL) {\
    313 		LIST_INSERT_HEAD(head, elm, field); \
    314 	} else { \
    315 		while (LIST_NEXT(curelm, field)) \
    316 			curelm = LIST_NEXT(curelm, field);\
    317 		LIST_INSERT_AFTER(curelm, elm, field);\
    318 	}\
    319 } while (0)
    320 
    321 #define KEY_CHKSASTATE(head, sav) \
    322 /* do */ { \
    323 	if ((head) != (sav)) {						\
    324 		IPSECLOG(LOG_DEBUG,					\
    325 		    "state mismatched (TREE=%d SA=%d)\n",		\
    326 		    (head), (sav));					\
    327 		continue;						\
    328 	}								\
    329 } /* while (0) */
    330 
    331 #define KEY_CHKSPDIR(head, sp) \
    332 do { \
    333 	if ((head) != (sp)) {						\
    334 		IPSECLOG(LOG_DEBUG,					\
    335 		    "direction mismatched (TREE=%d SP=%d), anyway continue.\n",\
    336 		    (head), (sp));					\
    337 	}								\
    338 } while (0)
    339 
    340 /*
    341  * set parameters into secasindex buffer.
    342  * Must allocate secasindex buffer before calling this function.
    343  */
    344 static int
    345 key_setsecasidx(int, int, int, const struct sockaddr *,
    346     const struct sockaddr *, struct secasindex *);
    347 
    348 /* key statistics */
    349 struct _keystat {
    350 	u_long getspi_count; /* the avarage of count to try to get new SPI */
    351 } keystat;
    352 
    353 struct sadb_msghdr {
    354 	struct sadb_msg *msg;
    355 	struct sadb_ext *ext[SADB_EXT_MAX + 1];
    356 	int extoff[SADB_EXT_MAX + 1];
    357 	int extlen[SADB_EXT_MAX + 1];
    358 };
    359 
    360 static void
    361 key_init_spidx_bymsghdr(struct secpolicyindex *, const struct sadb_msghdr *);
    362 
    363 static const struct sockaddr *
    364 key_msghdr_get_sockaddr(const struct sadb_msghdr *mhp, int idx)
    365 {
    366 
    367 	return PFKEY_ADDR_SADDR((struct sadb_address *)mhp->ext[idx]);
    368 }
    369 
    370 static struct mbuf *
    371 key_fill_replymsg(struct mbuf *m, int seq)
    372 {
    373 	struct sadb_msg *msg;
    374 
    375 	if (m->m_len < sizeof(*msg)) {
    376 		m = m_pullup(m, sizeof(*msg));
    377 		if (m == NULL)
    378 			return NULL;
    379 	}
    380 	msg = mtod(m, struct sadb_msg *);
    381 	msg->sadb_msg_errno = 0;
    382 	msg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
    383 	if (seq != 0)
    384 		msg->sadb_msg_seq = seq;
    385 
    386 	return m;
    387 }
    388 
    389 static struct secasvar *key_lookup_sa_bysaidx(const struct secasindex *);
    390 #if 0
    391 static void key_freeso(struct socket *);
    392 static void key_freesp_so(struct secpolicy **);
    393 #endif
    394 static void key_delsp (struct secpolicy *);
    395 static struct secpolicy *key_getsp (const struct secpolicyindex *);
    396 static struct secpolicy *key_getspbyid (u_int32_t);
    397 static u_int16_t key_newreqid (void);
    398 static struct mbuf *key_gather_mbuf (struct mbuf *,
    399 	const struct sadb_msghdr *, int, int, ...);
    400 static int key_api_spdadd(struct socket *, struct mbuf *,
    401 	const struct sadb_msghdr *);
    402 static u_int32_t key_getnewspid (void);
    403 static int key_api_spddelete(struct socket *, struct mbuf *,
    404 	const struct sadb_msghdr *);
    405 static int key_api_spddelete2(struct socket *, struct mbuf *,
    406 	const struct sadb_msghdr *);
    407 static int key_api_spdget(struct socket *, struct mbuf *,
    408 	const struct sadb_msghdr *);
    409 static int key_api_spdflush(struct socket *, struct mbuf *,
    410 	const struct sadb_msghdr *);
    411 static int key_api_spddump(struct socket *, struct mbuf *,
    412 	const struct sadb_msghdr *);
    413 static struct mbuf * key_setspddump (int *errorp, pid_t);
    414 static struct mbuf * key_setspddump_chain (int *errorp, int *lenp, pid_t pid);
    415 static int key_api_nat_map(struct socket *, struct mbuf *,
    416 	const struct sadb_msghdr *);
    417 static struct mbuf *key_setdumpsp (struct secpolicy *,
    418 	u_int8_t, u_int32_t, pid_t);
    419 static u_int key_getspreqmsglen (const struct secpolicy *);
    420 static int key_spdexpire (struct secpolicy *);
    421 static struct secashead *key_newsah (const struct secasindex *);
    422 static void key_delsah (struct secashead *);
    423 static struct secasvar *key_newsav(struct mbuf *,
    424 	const struct sadb_msghdr *, int *, const char*, int);
    425 #define	KEY_NEWSAV(m, sadb, e)				\
    426 	key_newsav(m, sadb, e, __func__, __LINE__)
    427 static void key_delsav (struct secasvar *);
    428 static struct secashead *key_getsah(const struct secasindex *, int);
    429 static bool key_checkspidup(const struct secasindex *, u_int32_t);
    430 static struct secasvar *key_getsavbyspi (struct secashead *, u_int32_t);
    431 static int key_setsaval (struct secasvar *, struct mbuf *,
    432 	const struct sadb_msghdr *);
    433 static void key_freesaval(struct secasvar *);
    434 static int key_init_xform(struct secasvar *);
    435 static void key_clear_xform(struct secasvar *);
    436 static struct mbuf *key_setdumpsa (struct secasvar *, u_int8_t,
    437 	u_int8_t, u_int32_t, u_int32_t);
    438 static struct mbuf *key_setsadbxport (u_int16_t, u_int16_t);
    439 static struct mbuf *key_setsadbxtype (u_int16_t);
    440 static struct mbuf *key_setsadbxfrag (u_int16_t);
    441 static void key_porttosaddr (union sockaddr_union *, u_int16_t);
    442 static int key_checksalen (const union sockaddr_union *);
    443 static struct mbuf *key_setsadbmsg (u_int8_t, u_int16_t, u_int8_t,
    444 	u_int32_t, pid_t, u_int16_t);
    445 static struct mbuf *key_setsadbsa (struct secasvar *);
    446 static struct mbuf *key_setsadbaddr (u_int16_t,
    447 	const struct sockaddr *, u_int8_t, u_int16_t);
    448 #if 0
    449 static struct mbuf *key_setsadbident (u_int16_t, u_int16_t, void *,
    450 	int, u_int64_t);
    451 #endif
    452 static struct mbuf *key_setsadbxsa2 (u_int8_t, u_int32_t, u_int16_t);
    453 static struct mbuf *key_setsadbxpolicy (u_int16_t, u_int8_t,
    454 	u_int32_t);
    455 static void *key_newbuf (const void *, u_int);
    456 #ifdef INET6
    457 static int key_ismyaddr6 (const struct sockaddr_in6 *);
    458 #endif
    459 
    460 static void sysctl_net_keyv2_setup(struct sysctllog **);
    461 static void sysctl_net_key_compat_setup(struct sysctllog **);
    462 
    463 /* flags for key_saidx_match() */
    464 #define CMP_HEAD	1	/* protocol, addresses. */
    465 #define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
    466 #define CMP_REQID	3	/* additionally HEAD, reaid. */
    467 #define CMP_EXACTLY	4	/* all elements. */
    468 static int key_saidx_match(const struct secasindex *,
    469     const struct secasindex *, int);
    470 
    471 static int key_sockaddr_match(const struct sockaddr *,
    472     const struct sockaddr *, int);
    473 static int key_bb_match_withmask(const void *, const void *, u_int);
    474 static u_int16_t key_satype2proto (u_int8_t);
    475 static u_int8_t key_proto2satype (u_int16_t);
    476 
    477 static int key_spidx_match_exactly(const struct secpolicyindex *,
    478     const struct secpolicyindex *);
    479 static int key_spidx_match_withmask(const struct secpolicyindex *,
    480     const struct secpolicyindex *);
    481 
    482 static int key_api_getspi(struct socket *, struct mbuf *,
    483 	const struct sadb_msghdr *);
    484 static u_int32_t key_do_getnewspi (const struct sadb_spirange *,
    485 					const struct secasindex *);
    486 static int key_handle_natt_info (struct secasvar *,
    487 				     const struct sadb_msghdr *);
    488 static int key_set_natt_ports (union sockaddr_union *,
    489 			 	union sockaddr_union *,
    490 				const struct sadb_msghdr *);
    491 static int key_api_update(struct socket *, struct mbuf *,
    492 	const struct sadb_msghdr *);
    493 #ifdef IPSEC_DOSEQCHECK
    494 static struct secasvar *key_getsavbyseq (struct secashead *, u_int32_t);
    495 #endif
    496 static int key_api_add(struct socket *, struct mbuf *,
    497 	const struct sadb_msghdr *);
    498 static int key_setident (struct secashead *, struct mbuf *,
    499 	const struct sadb_msghdr *);
    500 static struct mbuf *key_getmsgbuf_x1 (struct mbuf *,
    501 	const struct sadb_msghdr *);
    502 static int key_api_delete(struct socket *, struct mbuf *,
    503 	const struct sadb_msghdr *);
    504 static int key_api_get(struct socket *, struct mbuf *,
    505 	const struct sadb_msghdr *);
    506 
    507 static void key_getcomb_setlifetime (struct sadb_comb *);
    508 static struct mbuf *key_getcomb_esp (void);
    509 static struct mbuf *key_getcomb_ah (void);
    510 static struct mbuf *key_getcomb_ipcomp (void);
    511 static struct mbuf *key_getprop (const struct secasindex *);
    512 
    513 static int key_acquire (const struct secasindex *, struct secpolicy *);
    514 #ifndef IPSEC_NONBLOCK_ACQUIRE
    515 static struct secacq *key_newacq (const struct secasindex *);
    516 static struct secacq *key_getacq (const struct secasindex *);
    517 static struct secacq *key_getacqbyseq (u_int32_t);
    518 #endif
    519 #ifdef notyet
    520 static struct secspacq *key_newspacq (const struct secpolicyindex *);
    521 static struct secspacq *key_getspacq (const struct secpolicyindex *);
    522 #endif
    523 static int key_api_acquire(struct socket *, struct mbuf *,
    524 	const struct sadb_msghdr *);
    525 static int key_api_register(struct socket *, struct mbuf *,
    526 	const struct sadb_msghdr *);
    527 static int key_expire (struct secasvar *);
    528 static int key_api_flush(struct socket *, struct mbuf *,
    529 	const struct sadb_msghdr *);
    530 static struct mbuf *key_setdump_chain (u_int8_t req_satype, int *errorp,
    531 	int *lenp, pid_t pid);
    532 static int key_api_dump(struct socket *, struct mbuf *,
    533 	const struct sadb_msghdr *);
    534 static int key_api_promisc(struct socket *, struct mbuf *,
    535 	const struct sadb_msghdr *);
    536 static int key_senderror (struct socket *, struct mbuf *, int);
    537 static int key_validate_ext (const struct sadb_ext *, int);
    538 static int key_align (struct mbuf *, struct sadb_msghdr *);
    539 #if 0
    540 static const char *key_getfqdn (void);
    541 static const char *key_getuserfqdn (void);
    542 #endif
    543 static void key_sa_chgstate (struct secasvar *, u_int8_t);
    544 static inline void key_sp_dead (struct secpolicy *);
    545 static void key_sp_unlink (struct secpolicy *sp);
    546 
    547 static struct mbuf *key_alloc_mbuf (int);
    548 
    549 static void key_timehandler(void *);
    550 static void key_timehandler_work(struct work *, void *);
    551 static struct callout	key_timehandler_ch;
    552 static struct workqueue	*key_timehandler_wq;
    553 static struct work	key_timehandler_wk;
    554 
    555 #ifdef IPSEC_REF_DEBUG
    556 #define REFLOG(label, p, where, tag)					\
    557 	log(LOG_DEBUG, "%s:%d: " label " : refcnt=%d (%p)\n.",		\
    558 	    (where), (tag), (p)->refcnt, (p))
    559 #else
    560 #define REFLOG(label, p, where, tag)	do {} while (0)
    561 #endif
    562 
    563 #define	SA_ADDREF(p) do {						\
    564 	atomic_inc_uint(&(p)->refcnt);					\
    565 	REFLOG("SA_ADDREF", (p), __func__, __LINE__);			\
    566 	KASSERTMSG((p)->refcnt != 0, "SA refcnt overflow");		\
    567 } while (0)
    568 #define	SA_ADDREF2(p, where, tag) do {					\
    569 	atomic_inc_uint(&(p)->refcnt);					\
    570 	REFLOG("SA_ADDREF", (p), (where), (tag));			\
    571 	KASSERTMSG((p)->refcnt != 0, "SA refcnt overflow");		\
    572 } while (0)
    573 #define	SA_DELREF(p) do {						\
    574 	KASSERTMSG((p)->refcnt > 0, "SA refcnt underflow");		\
    575 	atomic_dec_uint(&(p)->refcnt);					\
    576 	REFLOG("SA_DELREF", (p), __func__, __LINE__);			\
    577 } while (0)
    578 #define	SA_DELREF2(p, nv, where, tag) do {				\
    579 	KASSERTMSG((p)->refcnt > 0, "SA refcnt underflow");		\
    580 	nv = atomic_dec_uint_nv(&(p)->refcnt);				\
    581 	REFLOG("SA_DELREF", (p), (where), (tag));			\
    582 } while (0)
    583 
    584 #define	SP_ADDREF(p) do {						\
    585 	atomic_inc_uint(&(p)->refcnt);					\
    586 	REFLOG("SP_ADDREF", (p), __func__, __LINE__);			\
    587 	KASSERTMSG((p)->refcnt != 0, "SP refcnt overflow");		\
    588 } while (0)
    589 #define	SP_ADDREF2(p, where, tag) do {					\
    590 	atomic_inc_uint(&(p)->refcnt);					\
    591 	REFLOG("SP_ADDREF", (p), (where), (tag));			\
    592 	KASSERTMSG((p)->refcnt != 0, "SP refcnt overflow");		\
    593 } while (0)
    594 #define	SP_DELREF(p) do {						\
    595 	KASSERTMSG((p)->refcnt > 0, "SP refcnt underflow");		\
    596 	atomic_dec_uint(&(p)->refcnt);					\
    597 	REFLOG("SP_DELREF", (p), __func__, __LINE__);			\
    598 } while (0)
    599 #define	SP_DELREF2(p, nv, where, tag) do {				\
    600 	KASSERTMSG((p)->refcnt > 0, "SP refcnt underflow");		\
    601 	nv = atomic_dec_uint_nv(&(p)->refcnt);				\
    602 	REFLOG("SP_DELREF", (p), (where), (tag));			\
    603 } while (0)
    604 
    605 u_int
    606 key_sp_refcnt(const struct secpolicy *sp)
    607 {
    608 
    609 	if (sp == NULL)
    610 		return 0;
    611 
    612 	return sp->refcnt;
    613 }
    614 
    615 static inline void
    616 key_sp_dead(struct secpolicy *sp)
    617 {
    618 
    619 	/* mark the SP dead */
    620 	sp->state = IPSEC_SPSTATE_DEAD;
    621 }
    622 
    623 static void
    624 key_sp_unlink(struct secpolicy *sp)
    625 {
    626 
    627 	/* remove from SP index */
    628 	KASSERT(__LIST_CHAINED(sp));
    629 	LIST_REMOVE(sp, chain);
    630 	/* Release refcount held just for being on chain */
    631 	KEY_FREESP(&sp);
    632 }
    633 
    634 
    635 /*
    636  * Return 0 when there are known to be no SP's for the specified
    637  * direction.  Otherwise return 1.  This is used by IPsec code
    638  * to optimize performance.
    639  */
    640 int
    641 key_havesp(u_int dir)
    642 {
    643 	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
    644 		!LIST_EMPTY(&sptree[dir]) : 1);
    645 }
    646 
    647 /* %%% IPsec policy management */
    648 /*
    649  * allocating a SP for OUTBOUND or INBOUND packet.
    650  * Must call key_freesp() later.
    651  * OUT:	NULL:	not found
    652  *	others:	found and return the pointer.
    653  */
    654 struct secpolicy *
    655 key_lookup_sp_byspidx(const struct secpolicyindex *spidx,
    656     u_int dir, const char* where, int tag)
    657 {
    658 	struct secpolicy *sp;
    659 	int s;
    660 
    661 	KASSERT(spidx != NULL);
    662 	KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
    663 
    664 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
    665 
    666 	/* get a SP entry */
    667 	s = splsoftnet();	/*called from softclock()*/
    668 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
    669 		printf("*** objects\n");
    670 		kdebug_secpolicyindex(spidx);
    671 	}
    672 
    673 	LIST_FOREACH(sp, &sptree[dir], chain) {
    674 		if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
    675 			printf("*** in SPD\n");
    676 			kdebug_secpolicyindex(&sp->spidx);
    677 		}
    678 
    679 		if (sp->state == IPSEC_SPSTATE_DEAD)
    680 			continue;
    681 		if (key_spidx_match_withmask(&sp->spidx, spidx))
    682 			goto found;
    683 	}
    684 	sp = NULL;
    685 found:
    686 	if (sp) {
    687 		/* sanity check */
    688 		KEY_CHKSPDIR(sp->spidx.dir, dir);
    689 
    690 		/* found a SPD entry */
    691 		sp->lastused = time_uptime;
    692 		SP_ADDREF2(sp, where, tag);
    693 	}
    694 	splx(s);
    695 
    696 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    697 	    "DP return SP:%p (ID=%u) refcnt %u\n",
    698 	    sp, sp ? sp->id : 0, key_sp_refcnt(sp));
    699 	return sp;
    700 }
    701 
    702 /*
    703  * return a policy that matches this particular inbound packet.
    704  * XXX slow
    705  */
    706 struct secpolicy *
    707 key_gettunnel(const struct sockaddr *osrc,
    708 	      const struct sockaddr *odst,
    709 	      const struct sockaddr *isrc,
    710 	      const struct sockaddr *idst,
    711 	      const char* where, int tag)
    712 {
    713 	struct secpolicy *sp;
    714 	const int dir = IPSEC_DIR_INBOUND;
    715 	int s;
    716 	struct ipsecrequest *r1, *r2, *p;
    717 	struct secpolicyindex spidx;
    718 
    719 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
    720 
    721 	if (isrc->sa_family != idst->sa_family) {
    722 		IPSECLOG(LOG_ERR, "protocol family mismatched %d != %d\n.",
    723 		    isrc->sa_family, idst->sa_family);
    724 		sp = NULL;
    725 		goto done;
    726 	}
    727 
    728 	s = splsoftnet();	/*called from softclock()*/
    729 	LIST_FOREACH(sp, &sptree[dir], chain) {
    730 		if (sp->state == IPSEC_SPSTATE_DEAD)
    731 			continue;
    732 
    733 		r1 = r2 = NULL;
    734 		for (p = sp->req; p; p = p->next) {
    735 			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
    736 				continue;
    737 
    738 			r1 = r2;
    739 			r2 = p;
    740 
    741 			if (!r1) {
    742 				/* here we look at address matches only */
    743 				spidx = sp->spidx;
    744 				if (isrc->sa_len > sizeof(spidx.src) ||
    745 				    idst->sa_len > sizeof(spidx.dst))
    746 					continue;
    747 				memcpy(&spidx.src, isrc, isrc->sa_len);
    748 				memcpy(&spidx.dst, idst, idst->sa_len);
    749 				if (!key_spidx_match_withmask(&sp->spidx, &spidx))
    750 					continue;
    751 			} else {
    752 				if (!key_sockaddr_match(&r1->saidx.src.sa, isrc, PORT_NONE) ||
    753 				    !key_sockaddr_match(&r1->saidx.dst.sa, idst, PORT_NONE))
    754 					continue;
    755 			}
    756 
    757 			if (!key_sockaddr_match(&r2->saidx.src.sa, osrc, PORT_NONE) ||
    758 			    !key_sockaddr_match(&r2->saidx.dst.sa, odst, PORT_NONE))
    759 				continue;
    760 
    761 			goto found;
    762 		}
    763 	}
    764 	sp = NULL;
    765 found:
    766 	if (sp) {
    767 		sp->lastused = time_uptime;
    768 		SP_ADDREF2(sp, where, tag);
    769 	}
    770 	splx(s);
    771 done:
    772 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    773 	    "DP return SP:%p (ID=%u) refcnt %u\n",
    774 	    sp, sp ? sp->id : 0, key_sp_refcnt(sp));
    775 	return sp;
    776 }
    777 
    778 /*
    779  * allocating an SA entry for an *OUTBOUND* packet.
    780  * checking each request entries in SP, and acquire an SA if need.
    781  * OUT:	0: there are valid requests.
    782  *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
    783  */
    784 int
    785 key_checkrequest(struct ipsecrequest *isr, struct secasvar **ret)
    786 {
    787 	u_int level;
    788 	int error;
    789 	const struct secasindex *saidx = &isr->saidx;
    790 	struct secasvar *sav;
    791 
    792 	KASSERT(isr != NULL);
    793 	KASSERTMSG(saidx->mode == IPSEC_MODE_TRANSPORT ||
    794 	    saidx->mode == IPSEC_MODE_TUNNEL,
    795 	    "unexpected policy %u", saidx->mode);
    796 
    797 	/* get current level */
    798 	level = ipsec_get_reqlevel(isr);
    799 
    800 	/*
    801 	 * XXX guard against protocol callbacks from the crypto
    802 	 * thread as they reference ipsecrequest.sav which we
    803 	 * temporarily null out below.  Need to rethink how we
    804 	 * handle bundled SA's in the callback thread.
    805 	 */
    806 	IPSEC_SPLASSERT_SOFTNET("key_checkrequest");
    807 
    808 	sav = key_lookup_sa_bysaidx(saidx);
    809 	if (sav != NULL) {
    810 		*ret = sav;
    811 		return 0;
    812 	}
    813 
    814 	/* there is no SA */
    815 	error = key_acquire(saidx, isr->sp);
    816 	if (error != 0) {
    817 		/* XXX What should I do ? */
    818 		IPSECLOG(LOG_DEBUG, "error %d returned from key_acquire.\n",
    819 		    error);
    820 		return error;
    821 	}
    822 
    823 	if (level != IPSEC_LEVEL_REQUIRE) {
    824 		/* XXX sigh, the interface to this routine is botched */
    825 		*ret = NULL;
    826 		return 0;
    827 	} else {
    828 		return ENOENT;
    829 	}
    830 }
    831 
    832 /*
    833  * looking up a SA for policy entry from SAD.
    834  * NOTE: searching SAD of aliving state.
    835  * OUT:	NULL:	not found.
    836  *	others:	found and return the pointer.
    837  */
    838 static struct secasvar *
    839 key_lookup_sa_bysaidx(const struct secasindex *saidx)
    840 {
    841 	struct secashead *sah;
    842 	struct secasvar *sav;
    843 	u_int stateidx, state;
    844 	const u_int *saorder_state_valid;
    845 	int arraysize;
    846 
    847 	sah = key_getsah(saidx, CMP_MODE_REQID);
    848 	if (sah == NULL)
    849 		return NULL;
    850 
    851 	/*
    852 	 * search a valid state list for outbound packet.
    853 	 * This search order is important.
    854 	 */
    855 	if (key_prefered_oldsa) {
    856 		saorder_state_valid = saorder_state_valid_prefer_old;
    857 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
    858 	} else {
    859 		saorder_state_valid = saorder_state_valid_prefer_new;
    860 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
    861 	}
    862 
    863 	/* search valid state */
    864 	for (stateidx = 0;
    865 	     stateidx < arraysize;
    866 	     stateidx++) {
    867 
    868 		state = saorder_state_valid[stateidx];
    869 
    870 		if (key_prefered_oldsa)
    871 			sav = LIST_FIRST(&sah->savtree[state]);
    872 		else {
    873 			/* XXX need O(1) lookup */
    874 			struct secasvar *last = NULL;
    875 
    876 			LIST_FOREACH(sav, &sah->savtree[state], chain)
    877 				last = sav;
    878 			sav = last;
    879 		}
    880 		if (sav != NULL) {
    881 			SA_ADDREF(sav);
    882 			KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    883 			    "DP cause refcnt++:%d SA:%p\n",
    884 			    sav->refcnt, sav);
    885 			return sav;
    886 		}
    887 	}
    888 
    889 	return NULL;
    890 }
    891 
    892 #if 0
    893 static void
    894 key_sendup_message_delete(struct secasvar *sav)
    895 {
    896 	struct mbuf *m, *result = 0;
    897 	uint8_t satype;
    898 
    899 	satype = key_proto2satype(sav->sah->saidx.proto);
    900 	if (satype == 0)
    901 		goto msgfail;
    902 
    903 	m = key_setsadbmsg(SADB_DELETE, 0, satype, 0, 0, sav->refcnt - 1);
    904 	if (m == NULL)
    905 		goto msgfail;
    906 	result = m;
    907 
    908 	/* set sadb_address for saidx's. */
    909 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &sav->sah->saidx.src.sa,
    910 	    sav->sah->saidx.src.sa.sa_len << 3, IPSEC_ULPROTO_ANY);
    911 	if (m == NULL)
    912 		goto msgfail;
    913 	m_cat(result, m);
    914 
    915 	/* set sadb_address for saidx's. */
    916 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &sav->sah->saidx.src.sa,
    917 	    sav->sah->saidx.src.sa.sa_len << 3, IPSEC_ULPROTO_ANY);
    918 	if (m == NULL)
    919 		goto msgfail;
    920 	m_cat(result, m);
    921 
    922 	/* create SA extension */
    923 	m = key_setsadbsa(sav);
    924 	if (m == NULL)
    925 		goto msgfail;
    926 	m_cat(result, m);
    927 
    928 	if (result->m_len < sizeof(struct sadb_msg)) {
    929 		result = m_pullup(result, sizeof(struct sadb_msg));
    930 		if (result == NULL)
    931 			goto msgfail;
    932 	}
    933 
    934 	result->m_pkthdr.len = 0;
    935 	for (m = result; m; m = m->m_next)
    936 		result->m_pkthdr.len += m->m_len;
    937 	mtod(result, struct sadb_msg *)->sadb_msg_len =
    938 	    PFKEY_UNIT64(result->m_pkthdr.len);
    939 
    940 	key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
    941 	result = NULL;
    942 msgfail:
    943 	if (result)
    944 		m_freem(result);
    945 }
    946 #endif
    947 
    948 /*
    949  * allocating a usable SA entry for a *INBOUND* packet.
    950  * Must call key_freesav() later.
    951  * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
    952  *	NULL:		not found, or error occurred.
    953  *
    954  * In the comparison, no source address is used--for RFC2401 conformance.
    955  * To quote, from section 4.1:
    956  *	A security association is uniquely identified by a triple consisting
    957  *	of a Security Parameter Index (SPI), an IP Destination Address, and a
    958  *	security protocol (AH or ESP) identifier.
    959  * Note that, however, we do need to keep source address in IPsec SA.
    960  * IKE specification and PF_KEY specification do assume that we
    961  * keep source address in IPsec SA.  We see a tricky situation here.
    962  *
    963  * sport and dport are used for NAT-T. network order is always used.
    964  */
    965 struct secasvar *
    966 key_lookup_sa(
    967 	const union sockaddr_union *dst,
    968 	u_int proto,
    969 	u_int32_t spi,
    970 	u_int16_t sport,
    971 	u_int16_t dport,
    972 	const char* where, int tag)
    973 {
    974 	struct secashead *sah;
    975 	struct secasvar *sav;
    976 	u_int stateidx, state;
    977 	const u_int *saorder_state_valid;
    978 	int arraysize, chkport;
    979 	int s;
    980 
    981 	int must_check_spi = 1;
    982 	int must_check_alg = 0;
    983 	u_int16_t cpi = 0;
    984 	u_int8_t algo = 0;
    985 
    986 	if ((sport != 0) && (dport != 0))
    987 		chkport = PORT_STRICT;
    988 	else
    989 		chkport = PORT_NONE;
    990 
    991 	KASSERT(dst != NULL);
    992 
    993 	/*
    994 	 * XXX IPCOMP case
    995 	 * We use cpi to define spi here. In the case where cpi <=
    996 	 * IPCOMP_CPI_NEGOTIATE_MIN, cpi just define the algorithm used, not
    997 	 * the real spi. In this case, don't check the spi but check the
    998 	 * algorithm
    999 	 */
   1000 
   1001 	if (proto == IPPROTO_IPCOMP) {
   1002 		u_int32_t tmp;
   1003 		tmp = ntohl(spi);
   1004 		cpi = (u_int16_t) tmp;
   1005 		if (cpi < IPCOMP_CPI_NEGOTIATE_MIN) {
   1006 			algo = (u_int8_t) cpi;
   1007 			must_check_spi = 0;
   1008 			must_check_alg = 1;
   1009 		}
   1010 	}
   1011 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1012 	    "DP from %s:%u check_spi=%d, check_alg=%d\n",
   1013 	    where, tag, must_check_spi, must_check_alg);
   1014 
   1015 
   1016 	/*
   1017 	 * searching SAD.
   1018 	 * XXX: to be checked internal IP header somewhere.  Also when
   1019 	 * IPsec tunnel packet is received.  But ESP tunnel mode is
   1020 	 * encrypted so we can't check internal IP header.
   1021 	 */
   1022 	s = splsoftnet();	/*called from softclock()*/
   1023 	if (key_prefered_oldsa) {
   1024 		saorder_state_valid = saorder_state_valid_prefer_old;
   1025 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
   1026 	} else {
   1027 		saorder_state_valid = saorder_state_valid_prefer_new;
   1028 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
   1029 	}
   1030 	LIST_FOREACH(sah, &sahtree, chain) {
   1031 		/* search valid state */
   1032 		for (stateidx = 0; stateidx < arraysize; stateidx++) {
   1033 			state = saorder_state_valid[stateidx];
   1034 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   1035 				KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   1036 				    "try match spi %#x, %#x\n",
   1037 				    ntohl(spi), ntohl(sav->spi));
   1038 				/* sanity check */
   1039 				KEY_CHKSASTATE(sav->state, state);
   1040 				/* do not return entries w/ unusable state */
   1041 				if (!SADB_SASTATE_USABLE_P(sav)) {
   1042 					KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   1043 					    "bad state %d\n", sav->state);
   1044 					continue;
   1045 				}
   1046 				if (proto != sav->sah->saidx.proto) {
   1047 					KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   1048 					    "proto fail %d != %d\n",
   1049 					    proto, sav->sah->saidx.proto);
   1050 					continue;
   1051 				}
   1052 				if (must_check_spi && spi != sav->spi) {
   1053 					KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   1054 					    "spi fail %#x != %#x\n",
   1055 					    ntohl(spi), ntohl(sav->spi));
   1056 					continue;
   1057 				}
   1058 				/* XXX only on the ipcomp case */
   1059 				if (must_check_alg && algo != sav->alg_comp) {
   1060 					KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   1061 					    "algo fail %d != %d\n",
   1062 					    algo, sav->alg_comp);
   1063 					continue;
   1064 				}
   1065 
   1066 #if 0	/* don't check src */
   1067 	/* Fix port in src->sa */
   1068 
   1069 				/* check src address */
   1070 				if (!key_sockaddr_match(&src->sa, &sav->sah->saidx.src.sa, PORT_NONE))
   1071 					continue;
   1072 #endif
   1073 				/* fix port of dst address XXX*/
   1074 				key_porttosaddr(__UNCONST(dst), dport);
   1075 				/* check dst address */
   1076 				if (!key_sockaddr_match(&dst->sa, &sav->sah->saidx.dst.sa, chkport))
   1077 					continue;
   1078 				SA_ADDREF2(sav, where, tag);
   1079 				goto done;
   1080 			}
   1081 		}
   1082 	}
   1083 	sav = NULL;
   1084 done:
   1085 	splx(s);
   1086 
   1087 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1088 	    "DP return SA:%p; refcnt %u\n", sav, sav ? sav->refcnt : 0);
   1089 	return sav;
   1090 }
   1091 
   1092 static void
   1093 key_validate_savlist(const struct secashead *sah, const u_int state)
   1094 {
   1095 #ifdef DEBUG
   1096 	struct secasvar *sav, *next;
   1097 
   1098 	/*
   1099 	 * The list should be sorted by lft_c->sadb_lifetime_addtime
   1100 	 * in ascending order.
   1101 	 */
   1102 	LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, next) {
   1103 		if (next != NULL &&
   1104 		    sav->lft_c != NULL && next->lft_c != NULL) {
   1105 			KDASSERTMSG(sav->lft_c->sadb_lifetime_addtime <=
   1106 			    next->lft_c->sadb_lifetime_addtime,
   1107 			    "savlist is not sorted: sah=%p, state=%d, "
   1108 			    "sav=%" PRIu64 ", next=%" PRIu64, sah, state,
   1109 			    sav->lft_c->sadb_lifetime_addtime,
   1110 			    next->lft_c->sadb_lifetime_addtime);
   1111 		}
   1112 	}
   1113 #endif
   1114 }
   1115 
   1116 void
   1117 key_sp_ref(struct secpolicy *sp, const char* where, int tag)
   1118 {
   1119 
   1120 	SP_ADDREF2(sp, where, tag);
   1121 
   1122 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1123 	    "DP SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
   1124 	    sp, sp->id, where, tag, key_sp_refcnt(sp));
   1125 }
   1126 
   1127 void
   1128 key_sa_ref(struct secasvar *sav, const char* where, int tag)
   1129 {
   1130 
   1131 	SA_ADDREF2(sav, where, tag);
   1132 
   1133 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1134 	    "DP cause refcnt++:%d SA:%p from %s:%u\n",
   1135 	    sav->refcnt, sav, where, tag);
   1136 }
   1137 
   1138 /*
   1139  * Must be called after calling key_lookup_sp*().
   1140  * For both the packet without socket and key_freeso().
   1141  */
   1142 void
   1143 _key_freesp(struct secpolicy **spp, const char* where, int tag)
   1144 {
   1145 	struct secpolicy *sp = *spp;
   1146 	unsigned int nv;
   1147 
   1148 	KASSERT(sp != NULL);
   1149 
   1150 	SP_DELREF2(sp, nv, where, tag);
   1151 
   1152 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1153 	    "DP SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
   1154 	    sp, sp->id, where, tag, nv);
   1155 
   1156 	if (nv == 0) {
   1157 		*spp = NULL;
   1158 		key_delsp(sp);
   1159 	}
   1160 }
   1161 
   1162 #if 0
   1163 /*
   1164  * Must be called after calling key_lookup_sp*().
   1165  * For the packet with socket.
   1166  */
   1167 static void
   1168 key_freeso(struct socket *so)
   1169 {
   1170 	/* sanity check */
   1171 	KASSERT(so != NULL);
   1172 
   1173 	switch (so->so_proto->pr_domain->dom_family) {
   1174 #ifdef INET
   1175 	case PF_INET:
   1176 	    {
   1177 		struct inpcb *pcb = sotoinpcb(so);
   1178 
   1179 		/* Does it have a PCB ? */
   1180 		if (pcb == NULL)
   1181 			return;
   1182 
   1183 		struct inpcbpolicy *sp = pcb->inp_sp;
   1184 		key_freesp_so(&sp->sp_in);
   1185 		key_freesp_so(&sp->sp_out);
   1186 	    }
   1187 		break;
   1188 #endif
   1189 #ifdef INET6
   1190 	case PF_INET6:
   1191 	    {
   1192 #ifdef HAVE_NRL_INPCB
   1193 		struct inpcb *pcb  = sotoinpcb(so);
   1194 		struct inpcbpolicy *sp = pcb->inp_sp;
   1195 
   1196 		/* Does it have a PCB ? */
   1197 		if (pcb == NULL)
   1198 			return;
   1199 		key_freesp_so(&sp->sp_in);
   1200 		key_freesp_so(&sp->sp_out);
   1201 #else
   1202 		struct in6pcb *pcb  = sotoin6pcb(so);
   1203 
   1204 		/* Does it have a PCB ? */
   1205 		if (pcb == NULL)
   1206 			return;
   1207 		key_freesp_so(&pcb->in6p_sp->sp_in);
   1208 		key_freesp_so(&pcb->in6p_sp->sp_out);
   1209 #endif
   1210 	    }
   1211 		break;
   1212 #endif /* INET6 */
   1213 	default:
   1214 		IPSECLOG(LOG_DEBUG, "unknown address family=%d.\n",
   1215 		    so->so_proto->pr_domain->dom_family);
   1216 		return;
   1217 	}
   1218 }
   1219 
   1220 static void
   1221 key_freesp_so(struct secpolicy **sp)
   1222 {
   1223 
   1224 	KASSERT(sp != NULL);
   1225 	KASSERT(*sp != NULL);
   1226 
   1227 	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
   1228 	    (*sp)->policy == IPSEC_POLICY_BYPASS)
   1229 		return;
   1230 
   1231 	KASSERTMSG((*sp)->policy == IPSEC_POLICY_IPSEC,
   1232 	    "invalid policy %u", (*sp)->policy);
   1233 	KEY_FREESP(sp);
   1234 }
   1235 #endif
   1236 
   1237 /*
   1238  * Must be called after calling key_lookup_sa().
   1239  * This function is called by key_freesp() to free some SA allocated
   1240  * for a policy.
   1241  */
   1242 void
   1243 key_freesav(struct secasvar **psav, const char* where, int tag)
   1244 {
   1245 	struct secasvar *sav = *psav;
   1246 	unsigned int nv;
   1247 
   1248 	KASSERT(sav != NULL);
   1249 
   1250 	SA_DELREF2(sav, nv, where, tag);
   1251 
   1252 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1253 	    "DP SA:%p (SPI %lu) from %s:%u; refcnt now %u\n",
   1254 	    sav, (u_long)ntohl(sav->spi), where, tag, nv);
   1255 
   1256 	if (nv == 0) {
   1257 		*psav = NULL;
   1258 
   1259 		/* remove from SA header */
   1260 		KASSERT(__LIST_CHAINED(sav));
   1261 		LIST_REMOVE(sav, chain);
   1262 
   1263 		key_delsav(sav);
   1264 	}
   1265 }
   1266 
   1267 /* %%% SPD management */
   1268 /*
   1269  * free security policy entry.
   1270  */
   1271 static void
   1272 key_delsp(struct secpolicy *sp)
   1273 {
   1274 	int s;
   1275 
   1276 	KASSERT(sp != NULL);
   1277 
   1278 	key_sp_dead(sp);
   1279 
   1280 	KASSERTMSG(sp->refcnt == 0,
   1281 	    "SP with references deleted (refcnt %u)", sp->refcnt);
   1282 
   1283 	s = splsoftnet();	/*called from softclock()*/
   1284 
   1285     {
   1286 	struct ipsecrequest *isr = sp->req, *nextisr;
   1287 
   1288 	while (isr != NULL) {
   1289 		nextisr = isr->next;
   1290 		kmem_intr_free(isr, sizeof(*isr));
   1291 		isr = nextisr;
   1292 	}
   1293     }
   1294 
   1295 	kmem_intr_free(sp, sizeof(*sp));
   1296 
   1297 	splx(s);
   1298 }
   1299 
   1300 /*
   1301  * search SPD
   1302  * OUT:	NULL	: not found
   1303  *	others	: found, pointer to a SP.
   1304  */
   1305 static struct secpolicy *
   1306 key_getsp(const struct secpolicyindex *spidx)
   1307 {
   1308 	struct secpolicy *sp;
   1309 
   1310 	KASSERT(spidx != NULL);
   1311 
   1312 	LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
   1313 		if (sp->state == IPSEC_SPSTATE_DEAD)
   1314 			continue;
   1315 		if (key_spidx_match_exactly(spidx, &sp->spidx)) {
   1316 			SP_ADDREF(sp);
   1317 			return sp;
   1318 		}
   1319 	}
   1320 
   1321 	return NULL;
   1322 }
   1323 
   1324 /*
   1325  * get SP by index.
   1326  * OUT:	NULL	: not found
   1327  *	others	: found, pointer to a SP.
   1328  */
   1329 static struct secpolicy *
   1330 key_getspbyid(u_int32_t id)
   1331 {
   1332 	struct secpolicy *sp;
   1333 
   1334 	LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
   1335 		if (sp->state == IPSEC_SPSTATE_DEAD)
   1336 			continue;
   1337 		if (sp->id == id) {
   1338 			SP_ADDREF(sp);
   1339 			return sp;
   1340 		}
   1341 	}
   1342 
   1343 	LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
   1344 		if (sp->state == IPSEC_SPSTATE_DEAD)
   1345 			continue;
   1346 		if (sp->id == id) {
   1347 			SP_ADDREF(sp);
   1348 			return sp;
   1349 		}
   1350 	}
   1351 
   1352 	return NULL;
   1353 }
   1354 
   1355 struct secpolicy *
   1356 key_newsp(const char* where, int tag)
   1357 {
   1358 	struct secpolicy *newsp = NULL;
   1359 
   1360 	newsp = kmem_intr_zalloc(sizeof(struct secpolicy), KM_NOSLEEP);
   1361 	if (newsp != NULL)
   1362 		newsp->refcnt = 1;
   1363 
   1364 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   1365 	    "DP from %s:%u return SP:%p\n", where, tag, newsp);
   1366 	return newsp;
   1367 }
   1368 
   1369 /*
   1370  * create secpolicy structure from sadb_x_policy structure.
   1371  * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
   1372  * so must be set properly later.
   1373  */
   1374 struct secpolicy *
   1375 key_msg2sp(const struct sadb_x_policy *xpl0, size_t len, int *error)
   1376 {
   1377 	struct secpolicy *newsp;
   1378 
   1379 	KASSERT(!cpu_softintr_p());
   1380 	KASSERT(xpl0 != NULL);
   1381 	KASSERT(len >= sizeof(*xpl0));
   1382 
   1383 	if (len != PFKEY_EXTLEN(xpl0)) {
   1384 		IPSECLOG(LOG_DEBUG, "Invalid msg length.\n");
   1385 		*error = EINVAL;
   1386 		return NULL;
   1387 	}
   1388 
   1389 	newsp = KEY_NEWSP();
   1390 	if (newsp == NULL) {
   1391 		*error = ENOBUFS;
   1392 		return NULL;
   1393 	}
   1394 
   1395 	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
   1396 	newsp->policy = xpl0->sadb_x_policy_type;
   1397 
   1398 	/* check policy */
   1399 	switch (xpl0->sadb_x_policy_type) {
   1400 	case IPSEC_POLICY_DISCARD:
   1401 	case IPSEC_POLICY_NONE:
   1402 	case IPSEC_POLICY_ENTRUST:
   1403 	case IPSEC_POLICY_BYPASS:
   1404 		newsp->req = NULL;
   1405 		*error = 0;
   1406 		return newsp;
   1407 
   1408 	case IPSEC_POLICY_IPSEC:
   1409 		/* Continued */
   1410 		break;
   1411 	default:
   1412 		IPSECLOG(LOG_DEBUG, "invalid policy type.\n");
   1413 		KEY_FREESP(&newsp);
   1414 		*error = EINVAL;
   1415 		return NULL;
   1416 	}
   1417 
   1418 	/* IPSEC_POLICY_IPSEC */
   1419     {
   1420 	int tlen;
   1421 	const struct sadb_x_ipsecrequest *xisr;
   1422 	uint16_t xisr_reqid;
   1423 	struct ipsecrequest **p_isr = &newsp->req;
   1424 
   1425 	/* validity check */
   1426 	if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
   1427 		IPSECLOG(LOG_DEBUG, "Invalid msg length.\n");
   1428 		*error = EINVAL;
   1429 		goto free_exit;
   1430 	}
   1431 
   1432 	tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
   1433 	xisr = (const struct sadb_x_ipsecrequest *)(xpl0 + 1);
   1434 
   1435 	while (tlen > 0) {
   1436 		/* length check */
   1437 		if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
   1438 			IPSECLOG(LOG_DEBUG, "invalid ipsecrequest length.\n");
   1439 			*error = EINVAL;
   1440 			goto free_exit;
   1441 		}
   1442 
   1443 		/* allocate request buffer */
   1444 		*p_isr = kmem_zalloc(sizeof(**p_isr), KM_SLEEP);
   1445 
   1446 		/* set values */
   1447 		(*p_isr)->next = NULL;
   1448 
   1449 		switch (xisr->sadb_x_ipsecrequest_proto) {
   1450 		case IPPROTO_ESP:
   1451 		case IPPROTO_AH:
   1452 		case IPPROTO_IPCOMP:
   1453 			break;
   1454 		default:
   1455 			IPSECLOG(LOG_DEBUG, "invalid proto type=%u\n",
   1456 			    xisr->sadb_x_ipsecrequest_proto);
   1457 			*error = EPROTONOSUPPORT;
   1458 			goto free_exit;
   1459 		}
   1460 		(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
   1461 
   1462 		switch (xisr->sadb_x_ipsecrequest_mode) {
   1463 		case IPSEC_MODE_TRANSPORT:
   1464 		case IPSEC_MODE_TUNNEL:
   1465 			break;
   1466 		case IPSEC_MODE_ANY:
   1467 		default:
   1468 			IPSECLOG(LOG_DEBUG, "invalid mode=%u\n",
   1469 			    xisr->sadb_x_ipsecrequest_mode);
   1470 			*error = EINVAL;
   1471 			goto free_exit;
   1472 		}
   1473 		(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
   1474 
   1475 		switch (xisr->sadb_x_ipsecrequest_level) {
   1476 		case IPSEC_LEVEL_DEFAULT:
   1477 		case IPSEC_LEVEL_USE:
   1478 		case IPSEC_LEVEL_REQUIRE:
   1479 			break;
   1480 		case IPSEC_LEVEL_UNIQUE:
   1481 			xisr_reqid = xisr->sadb_x_ipsecrequest_reqid;
   1482 			/* validity check */
   1483 			/*
   1484 			 * If range violation of reqid, kernel will
   1485 			 * update it, don't refuse it.
   1486 			 */
   1487 			if (xisr_reqid > IPSEC_MANUAL_REQID_MAX) {
   1488 				IPSECLOG(LOG_DEBUG,
   1489 				    "reqid=%d range "
   1490 				    "violation, updated by kernel.\n",
   1491 				    xisr_reqid);
   1492 				xisr_reqid = 0;
   1493 			}
   1494 
   1495 			/* allocate new reqid id if reqid is zero. */
   1496 			if (xisr_reqid == 0) {
   1497 				u_int16_t reqid = key_newreqid();
   1498 				if (reqid == 0) {
   1499 					*error = ENOBUFS;
   1500 					goto free_exit;
   1501 				}
   1502 				(*p_isr)->saidx.reqid = reqid;
   1503 			} else {
   1504 			/* set it for manual keying. */
   1505 				(*p_isr)->saidx.reqid = xisr_reqid;
   1506 			}
   1507 			break;
   1508 
   1509 		default:
   1510 			IPSECLOG(LOG_DEBUG, "invalid level=%u\n",
   1511 			    xisr->sadb_x_ipsecrequest_level);
   1512 			*error = EINVAL;
   1513 			goto free_exit;
   1514 		}
   1515 		(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
   1516 
   1517 		/* set IP addresses if there */
   1518 		if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
   1519 			const struct sockaddr *paddr;
   1520 
   1521 			paddr = (const struct sockaddr *)(xisr + 1);
   1522 
   1523 			/* validity check */
   1524 			if (paddr->sa_len > sizeof((*p_isr)->saidx.src)) {
   1525 				IPSECLOG(LOG_DEBUG, "invalid request "
   1526 				    "address length.\n");
   1527 				*error = EINVAL;
   1528 				goto free_exit;
   1529 			}
   1530 			memcpy(&(*p_isr)->saidx.src, paddr, paddr->sa_len);
   1531 
   1532 			paddr = (const struct sockaddr *)((const char *)paddr
   1533 			    + paddr->sa_len);
   1534 
   1535 			/* validity check */
   1536 			if (paddr->sa_len > sizeof((*p_isr)->saidx.dst)) {
   1537 				IPSECLOG(LOG_DEBUG, "invalid request "
   1538 				    "address length.\n");
   1539 				*error = EINVAL;
   1540 				goto free_exit;
   1541 			}
   1542 			memcpy(&(*p_isr)->saidx.dst, paddr, paddr->sa_len);
   1543 		}
   1544 
   1545 		(*p_isr)->sp = newsp;
   1546 
   1547 		/* initialization for the next. */
   1548 		p_isr = &(*p_isr)->next;
   1549 		tlen -= xisr->sadb_x_ipsecrequest_len;
   1550 
   1551 		/* validity check */
   1552 		if (tlen < 0) {
   1553 			IPSECLOG(LOG_DEBUG, "becoming tlen < 0.\n");
   1554 			*error = EINVAL;
   1555 			goto free_exit;
   1556 		}
   1557 
   1558 		xisr = (const struct sadb_x_ipsecrequest *)((const char *)xisr +
   1559 		    xisr->sadb_x_ipsecrequest_len);
   1560 	}
   1561     }
   1562 
   1563 	*error = 0;
   1564 	return newsp;
   1565 
   1566 free_exit:
   1567 	KEY_FREESP(&newsp);
   1568 	return NULL;
   1569 }
   1570 
   1571 static u_int16_t
   1572 key_newreqid(void)
   1573 {
   1574 	static u_int16_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
   1575 
   1576 	auto_reqid = (auto_reqid == 0xffff ?
   1577 	    IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
   1578 
   1579 	/* XXX should be unique check */
   1580 
   1581 	return auto_reqid;
   1582 }
   1583 
   1584 /*
   1585  * copy secpolicy struct to sadb_x_policy structure indicated.
   1586  */
   1587 struct mbuf *
   1588 key_sp2msg(const struct secpolicy *sp)
   1589 {
   1590 	struct sadb_x_policy *xpl;
   1591 	int tlen;
   1592 	char *p;
   1593 	struct mbuf *m;
   1594 
   1595 	KASSERT(sp != NULL);
   1596 
   1597 	tlen = key_getspreqmsglen(sp);
   1598 
   1599 	m = key_alloc_mbuf(tlen);
   1600 	if (!m || m->m_next) {	/*XXX*/
   1601 		if (m)
   1602 			m_freem(m);
   1603 		return NULL;
   1604 	}
   1605 
   1606 	m->m_len = tlen;
   1607 	m->m_next = NULL;
   1608 	xpl = mtod(m, struct sadb_x_policy *);
   1609 	memset(xpl, 0, tlen);
   1610 
   1611 	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
   1612 	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
   1613 	xpl->sadb_x_policy_type = sp->policy;
   1614 	xpl->sadb_x_policy_dir = sp->spidx.dir;
   1615 	xpl->sadb_x_policy_id = sp->id;
   1616 	p = (char *)xpl + sizeof(*xpl);
   1617 
   1618 	/* if is the policy for ipsec ? */
   1619 	if (sp->policy == IPSEC_POLICY_IPSEC) {
   1620 		struct sadb_x_ipsecrequest *xisr;
   1621 		struct ipsecrequest *isr;
   1622 
   1623 		for (isr = sp->req; isr != NULL; isr = isr->next) {
   1624 
   1625 			xisr = (struct sadb_x_ipsecrequest *)p;
   1626 
   1627 			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
   1628 			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
   1629 			xisr->sadb_x_ipsecrequest_level = isr->level;
   1630 			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
   1631 
   1632 			p += sizeof(*xisr);
   1633 			memcpy(p, &isr->saidx.src, isr->saidx.src.sa.sa_len);
   1634 			p += isr->saidx.src.sa.sa_len;
   1635 			memcpy(p, &isr->saidx.dst, isr->saidx.dst.sa.sa_len);
   1636 			p += isr->saidx.src.sa.sa_len;
   1637 
   1638 			xisr->sadb_x_ipsecrequest_len =
   1639 			    PFKEY_ALIGN8(sizeof(*xisr)
   1640 			    + isr->saidx.src.sa.sa_len
   1641 			    + isr->saidx.dst.sa.sa_len);
   1642 		}
   1643 	}
   1644 
   1645 	return m;
   1646 }
   1647 
   1648 /* m will not be freed nor modified */
   1649 static struct mbuf *
   1650 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
   1651 		int ndeep, int nitem, ...)
   1652 {
   1653 	va_list ap;
   1654 	int idx;
   1655 	int i;
   1656 	struct mbuf *result = NULL, *n;
   1657 	int len;
   1658 
   1659 	KASSERT(m != NULL);
   1660 	KASSERT(mhp != NULL);
   1661 
   1662 	va_start(ap, nitem);
   1663 	for (i = 0; i < nitem; i++) {
   1664 		idx = va_arg(ap, int);
   1665 		if (idx < 0 || idx > SADB_EXT_MAX)
   1666 			goto fail;
   1667 		/* don't attempt to pull empty extension */
   1668 		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
   1669 			continue;
   1670 		if (idx != SADB_EXT_RESERVED &&
   1671 		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
   1672 			continue;
   1673 
   1674 		if (idx == SADB_EXT_RESERVED) {
   1675 			CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) <= MHLEN);
   1676 			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   1677 			MGETHDR(n, M_DONTWAIT, MT_DATA);
   1678 			if (!n)
   1679 				goto fail;
   1680 			n->m_len = len;
   1681 			n->m_next = NULL;
   1682 			m_copydata(m, 0, sizeof(struct sadb_msg),
   1683 			    mtod(n, void *));
   1684 		} else if (i < ndeep) {
   1685 			len = mhp->extlen[idx];
   1686 			n = key_alloc_mbuf(len);
   1687 			if (!n || n->m_next) {	/*XXX*/
   1688 				if (n)
   1689 					m_freem(n);
   1690 				goto fail;
   1691 			}
   1692 			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
   1693 			    mtod(n, void *));
   1694 		} else {
   1695 			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
   1696 			    M_DONTWAIT);
   1697 		}
   1698 		if (n == NULL)
   1699 			goto fail;
   1700 
   1701 		if (result)
   1702 			m_cat(result, n);
   1703 		else
   1704 			result = n;
   1705 	}
   1706 	va_end(ap);
   1707 
   1708 	if (result && (result->m_flags & M_PKTHDR) != 0) {
   1709 		result->m_pkthdr.len = 0;
   1710 		for (n = result; n; n = n->m_next)
   1711 			result->m_pkthdr.len += n->m_len;
   1712 	}
   1713 
   1714 	return result;
   1715 
   1716 fail:
   1717 	va_end(ap);
   1718 	m_freem(result);
   1719 	return NULL;
   1720 }
   1721 
   1722 /*
   1723  * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
   1724  * add an entry to SP database, when received
   1725  *   <base, address(SD), (lifetime(H),) policy>
   1726  * from the user(?).
   1727  * Adding to SP database,
   1728  * and send
   1729  *   <base, address(SD), (lifetime(H),) policy>
   1730  * to the socket which was send.
   1731  *
   1732  * SPDADD set a unique policy entry.
   1733  * SPDSETIDX like SPDADD without a part of policy requests.
   1734  * SPDUPDATE replace a unique policy entry.
   1735  *
   1736  * m will always be freed.
   1737  */
   1738 static int
   1739 key_api_spdadd(struct socket *so, struct mbuf *m,
   1740 	   const struct sadb_msghdr *mhp)
   1741 {
   1742 	const struct sockaddr *src, *dst;
   1743 	const struct sadb_x_policy *xpl0;
   1744 	struct sadb_x_policy *xpl;
   1745 	const struct sadb_lifetime *lft = NULL;
   1746 	struct secpolicyindex spidx;
   1747 	struct secpolicy *newsp;
   1748 	int error;
   1749 
   1750 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   1751 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   1752 	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
   1753 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   1754 		return key_senderror(so, m, EINVAL);
   1755 	}
   1756 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   1757 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   1758 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   1759 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   1760 		return key_senderror(so, m, EINVAL);
   1761 	}
   1762 	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
   1763 		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] <
   1764 		    sizeof(struct sadb_lifetime)) {
   1765 			IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   1766 			return key_senderror(so, m, EINVAL);
   1767 		}
   1768 		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
   1769 	}
   1770 
   1771 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
   1772 
   1773 	/* checking the direciton. */
   1774 	switch (xpl0->sadb_x_policy_dir) {
   1775 	case IPSEC_DIR_INBOUND:
   1776 	case IPSEC_DIR_OUTBOUND:
   1777 		break;
   1778 	default:
   1779 		IPSECLOG(LOG_DEBUG, "Invalid SP direction.\n");
   1780 		return key_senderror(so, m, EINVAL);
   1781 	}
   1782 
   1783 	/* check policy */
   1784 	/* key_api_spdadd() accepts DISCARD, NONE and IPSEC. */
   1785 	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST ||
   1786 	    xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
   1787 		IPSECLOG(LOG_DEBUG, "Invalid policy type.\n");
   1788 		return key_senderror(so, m, EINVAL);
   1789 	}
   1790 
   1791 	/* policy requests are mandatory when action is ipsec. */
   1792 	if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX &&
   1793 	    xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
   1794 	    mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
   1795 		IPSECLOG(LOG_DEBUG, "some policy requests part required.\n");
   1796 		return key_senderror(so, m, EINVAL);
   1797 	}
   1798 
   1799 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   1800 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   1801 
   1802 	/* sanity check on addr pair */
   1803 	if (src->sa_family != dst->sa_family)
   1804 		return key_senderror(so, m, EINVAL);
   1805 	if (src->sa_len != dst->sa_len)
   1806 		return key_senderror(so, m, EINVAL);
   1807 
   1808 	key_init_spidx_bymsghdr(&spidx, mhp);
   1809 
   1810 	/*
   1811 	 * checking there is SP already or not.
   1812 	 * SPDUPDATE doesn't depend on whether there is a SP or not.
   1813 	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
   1814 	 * then error.
   1815 	 */
   1816     {
   1817 	struct secpolicy *sp;
   1818 
   1819 	sp = key_getsp(&spidx);
   1820 	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
   1821 		if (sp) {
   1822 			key_sp_dead(sp);
   1823 			key_sp_unlink(sp);	/* XXX jrs ordering */
   1824 			KEY_FREESP(&sp);
   1825 		}
   1826 	} else {
   1827 		if (sp != NULL) {
   1828 			KEY_FREESP(&sp);
   1829 			IPSECLOG(LOG_DEBUG, "a SP entry exists already.\n");
   1830 			return key_senderror(so, m, EEXIST);
   1831 		}
   1832 	}
   1833     }
   1834 
   1835 	/* allocation new SP entry */
   1836 	newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error);
   1837 	if (newsp == NULL) {
   1838 		return key_senderror(so, m, error);
   1839 	}
   1840 
   1841 	newsp->id = key_getnewspid();
   1842 	if (newsp->id == 0) {
   1843 		kmem_free(newsp, sizeof(*newsp));
   1844 		return key_senderror(so, m, ENOBUFS);
   1845 	}
   1846 
   1847 	newsp->spidx = spidx;
   1848 	newsp->created = time_uptime;
   1849 	newsp->lastused = newsp->created;
   1850 	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
   1851 	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
   1852 
   1853 	newsp->refcnt = 1;	/* do not reclaim until I say I do */
   1854 	newsp->state = IPSEC_SPSTATE_ALIVE;
   1855 	if (newsp->policy == IPSEC_POLICY_IPSEC)
   1856 		KASSERT(newsp->req != NULL);
   1857 	LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
   1858 
   1859 #ifdef notyet
   1860 	/* delete the entry in spacqtree */
   1861 	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
   1862 		struct secspacq *spacq = key_getspacq(&spidx);
   1863 		if (spacq != NULL) {
   1864 			/* reset counter in order to deletion by timehandler. */
   1865 			spacq->created = time_uptime;
   1866 			spacq->count = 0;
   1867 		}
   1868     	}
   1869 #endif
   1870 
   1871 	/* Invalidate all cached SPD pointers in the PCBs. */
   1872 	ipsec_invalpcbcacheall();
   1873 
   1874 #if defined(GATEWAY)
   1875 	/* Invalidate the ipflow cache, as well. */
   1876 	ipflow_invalidate_all(0);
   1877 #ifdef INET6
   1878 	if (in6_present)
   1879 		ip6flow_invalidate_all(0);
   1880 #endif /* INET6 */
   1881 #endif /* GATEWAY */
   1882 
   1883     {
   1884 	struct mbuf *n, *mpolicy;
   1885 	int off;
   1886 
   1887 	/* create new sadb_msg to reply. */
   1888 	if (lft) {
   1889 		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
   1890 		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
   1891 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   1892 	} else {
   1893 		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
   1894 		    SADB_X_EXT_POLICY,
   1895 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   1896 	}
   1897 	if (!n)
   1898 		return key_senderror(so, m, ENOBUFS);
   1899 
   1900 	n = key_fill_replymsg(n, 0);
   1901 	if (n == NULL)
   1902 		return key_senderror(so, m, ENOBUFS);
   1903 
   1904 	off = 0;
   1905 	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
   1906 	    sizeof(*xpl), &off);
   1907 	if (mpolicy == NULL) {
   1908 		/* n is already freed */
   1909 		return key_senderror(so, m, ENOBUFS);
   1910 	}
   1911 	xpl = (struct sadb_x_policy *)(mtod(mpolicy, char *) + off);
   1912 	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
   1913 		m_freem(n);
   1914 		return key_senderror(so, m, EINVAL);
   1915 	}
   1916 	xpl->sadb_x_policy_id = newsp->id;
   1917 
   1918 	m_freem(m);
   1919 	key_update_used();
   1920 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   1921     }
   1922 }
   1923 
   1924 /*
   1925  * get new policy id.
   1926  * OUT:
   1927  *	0:	failure.
   1928  *	others: success.
   1929  */
   1930 static u_int32_t
   1931 key_getnewspid(void)
   1932 {
   1933 	u_int32_t newid = 0;
   1934 	int count = key_spi_trycnt;	/* XXX */
   1935 	struct secpolicy *sp;
   1936 
   1937 	/* when requesting to allocate spi ranged */
   1938 	while (count--) {
   1939 		newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
   1940 
   1941 		sp = key_getspbyid(newid);
   1942 		if (sp == NULL)
   1943 			break;
   1944 
   1945 		KEY_FREESP(&sp);
   1946 	}
   1947 
   1948 	if (count == 0 || newid == 0) {
   1949 		IPSECLOG(LOG_DEBUG, "to allocate policy id is failed.\n");
   1950 		return 0;
   1951 	}
   1952 
   1953 	return newid;
   1954 }
   1955 
   1956 /*
   1957  * SADB_SPDDELETE processing
   1958  * receive
   1959  *   <base, address(SD), policy(*)>
   1960  * from the user(?), and set SADB_SASTATE_DEAD,
   1961  * and send,
   1962  *   <base, address(SD), policy(*)>
   1963  * to the ikmpd.
   1964  * policy(*) including direction of policy.
   1965  *
   1966  * m will always be freed.
   1967  */
   1968 static int
   1969 key_api_spddelete(struct socket *so, struct mbuf *m,
   1970               const struct sadb_msghdr *mhp)
   1971 {
   1972 	struct sadb_x_policy *xpl0;
   1973 	struct secpolicyindex spidx;
   1974 	struct secpolicy *sp;
   1975 
   1976 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   1977 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   1978 	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
   1979 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   1980 		return key_senderror(so, m, EINVAL);
   1981 	}
   1982 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   1983 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   1984 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   1985 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   1986 		return key_senderror(so, m, EINVAL);
   1987 	}
   1988 
   1989 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
   1990 
   1991 	/* checking the direciton. */
   1992 	switch (xpl0->sadb_x_policy_dir) {
   1993 	case IPSEC_DIR_INBOUND:
   1994 	case IPSEC_DIR_OUTBOUND:
   1995 		break;
   1996 	default:
   1997 		IPSECLOG(LOG_DEBUG, "Invalid SP direction.\n");
   1998 		return key_senderror(so, m, EINVAL);
   1999 	}
   2000 
   2001 	/* make secindex */
   2002 	key_init_spidx_bymsghdr(&spidx, mhp);
   2003 
   2004 	/* Is there SP in SPD ? */
   2005 	sp = key_getsp(&spidx);
   2006 	if (sp == NULL) {
   2007 		IPSECLOG(LOG_DEBUG, "no SP found.\n");
   2008 		return key_senderror(so, m, EINVAL);
   2009 	}
   2010 
   2011 	/* save policy id to buffer to be returned. */
   2012 	xpl0->sadb_x_policy_id = sp->id;
   2013 
   2014 	key_sp_dead(sp);
   2015 	key_sp_unlink(sp);	/* XXX jrs ordering */
   2016 	KEY_FREESP(&sp);	/* ref gained by key_getspbyid */
   2017 
   2018 	/* Invalidate all cached SPD pointers in the PCBs. */
   2019 	ipsec_invalpcbcacheall();
   2020 
   2021 	/* We're deleting policy; no need to invalidate the ipflow cache. */
   2022 
   2023     {
   2024 	struct mbuf *n;
   2025 
   2026 	/* create new sadb_msg to reply. */
   2027 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
   2028 	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   2029 	if (!n)
   2030 		return key_senderror(so, m, ENOBUFS);
   2031 
   2032 	n = key_fill_replymsg(n, 0);
   2033 	if (n == NULL)
   2034 		return key_senderror(so, m, ENOBUFS);
   2035 
   2036 	m_freem(m);
   2037 	key_update_used();
   2038 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   2039     }
   2040 }
   2041 
   2042 /*
   2043  * SADB_SPDDELETE2 processing
   2044  * receive
   2045  *   <base, policy(*)>
   2046  * from the user(?), and set SADB_SASTATE_DEAD,
   2047  * and send,
   2048  *   <base, policy(*)>
   2049  * to the ikmpd.
   2050  * policy(*) including direction of policy.
   2051  *
   2052  * m will always be freed.
   2053  */
   2054 static int
   2055 key_api_spddelete2(struct socket *so, struct mbuf *m,
   2056 	       const struct sadb_msghdr *mhp)
   2057 {
   2058 	u_int32_t id;
   2059 	struct secpolicy *sp;
   2060 
   2061 	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
   2062 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   2063 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   2064 		return key_senderror(so, m, EINVAL);
   2065 	}
   2066 
   2067 	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
   2068 
   2069 	/* Is there SP in SPD ? */
   2070 	sp = key_getspbyid(id);
   2071 	if (sp == NULL) {
   2072 		IPSECLOG(LOG_DEBUG, "no SP found id:%u.\n", id);
   2073 		return key_senderror(so, m, EINVAL);
   2074 	}
   2075 
   2076 	key_sp_dead(sp);
   2077 	key_sp_unlink(sp);	/* XXX jrs ordering */
   2078 	KEY_FREESP(&sp);	/* ref gained by key_getsp */
   2079 	sp = NULL;
   2080 
   2081 	/* Invalidate all cached SPD pointers in the PCBs. */
   2082 	ipsec_invalpcbcacheall();
   2083 
   2084 	/* We're deleting policy; no need to invalidate the ipflow cache. */
   2085 
   2086     {
   2087 	struct mbuf *n, *nn;
   2088 	int off, len;
   2089 
   2090 	CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) <= MCLBYTES);
   2091 
   2092 	/* create new sadb_msg to reply. */
   2093 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   2094 
   2095 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   2096 	if (n && len > MHLEN) {
   2097 		MCLGET(n, M_DONTWAIT);
   2098 		if ((n->m_flags & M_EXT) == 0) {
   2099 			m_freem(n);
   2100 			n = NULL;
   2101 		}
   2102 	}
   2103 	if (!n)
   2104 		return key_senderror(so, m, ENOBUFS);
   2105 
   2106 	n->m_len = len;
   2107 	n->m_next = NULL;
   2108 	off = 0;
   2109 
   2110 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   2111 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   2112 
   2113 	KASSERTMSG(off == len, "length inconsistency");
   2114 
   2115 	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
   2116 	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
   2117 	if (!n->m_next) {
   2118 		m_freem(n);
   2119 		return key_senderror(so, m, ENOBUFS);
   2120 	}
   2121 
   2122 	n->m_pkthdr.len = 0;
   2123 	for (nn = n; nn; nn = nn->m_next)
   2124 		n->m_pkthdr.len += nn->m_len;
   2125 
   2126 	n = key_fill_replymsg(n, 0);
   2127 	if (n == NULL)
   2128 		return key_senderror(so, m, ENOBUFS);
   2129 
   2130 	m_freem(m);
   2131 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   2132     }
   2133 }
   2134 
   2135 /*
   2136  * SADB_X_GET processing
   2137  * receive
   2138  *   <base, policy(*)>
   2139  * from the user(?),
   2140  * and send,
   2141  *   <base, address(SD), policy>
   2142  * to the ikmpd.
   2143  * policy(*) including direction of policy.
   2144  *
   2145  * m will always be freed.
   2146  */
   2147 static int
   2148 key_api_spdget(struct socket *so, struct mbuf *m,
   2149 	   const struct sadb_msghdr *mhp)
   2150 {
   2151 	u_int32_t id;
   2152 	struct secpolicy *sp;
   2153 	struct mbuf *n;
   2154 
   2155 	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
   2156 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   2157 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   2158 		return key_senderror(so, m, EINVAL);
   2159 	}
   2160 
   2161 	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
   2162 
   2163 	/* Is there SP in SPD ? */
   2164 	sp = key_getspbyid(id);
   2165 	if (sp == NULL) {
   2166 		IPSECLOG(LOG_DEBUG, "no SP found id:%u.\n", id);
   2167 		return key_senderror(so, m, ENOENT);
   2168 	}
   2169 
   2170 	n = key_setdumpsp(sp, SADB_X_SPDGET, mhp->msg->sadb_msg_seq,
   2171 	    mhp->msg->sadb_msg_pid);
   2172 	KEY_FREESP(&sp); /* ref gained by key_getspbyid */
   2173 	if (n != NULL) {
   2174 		m_freem(m);
   2175 		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   2176 	} else
   2177 		return key_senderror(so, m, ENOBUFS);
   2178 }
   2179 
   2180 #ifdef notyet
   2181 /*
   2182  * SADB_X_SPDACQUIRE processing.
   2183  * Acquire policy and SA(s) for a *OUTBOUND* packet.
   2184  * send
   2185  *   <base, policy(*)>
   2186  * to KMD, and expect to receive
   2187  *   <base> with SADB_X_SPDACQUIRE if error occurred,
   2188  * or
   2189  *   <base, policy>
   2190  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
   2191  * policy(*) is without policy requests.
   2192  *
   2193  *    0     : succeed
   2194  *    others: error number
   2195  */
   2196 int
   2197 key_spdacquire(const struct secpolicy *sp)
   2198 {
   2199 	struct mbuf *result = NULL, *m;
   2200 	struct secspacq *newspacq;
   2201 	int error;
   2202 
   2203 	KASSERT(sp != NULL);
   2204 	KASSERTMSG(sp->req == NULL, "called but there is request");
   2205 	KASSERTMSG(sp->policy == IPSEC_POLICY_IPSEC,
   2206 	    "policy mismathed. IPsec is expected");
   2207 
   2208 	/* Get an entry to check whether sent message or not. */
   2209 	newspacq = key_getspacq(&sp->spidx);
   2210 	if (newspacq != NULL) {
   2211 		if (key_blockacq_count < newspacq->count) {
   2212 			/* reset counter and do send message. */
   2213 			newspacq->count = 0;
   2214 		} else {
   2215 			/* increment counter and do nothing. */
   2216 			newspacq->count++;
   2217 			return 0;
   2218 		}
   2219 	} else {
   2220 		/* make new entry for blocking to send SADB_ACQUIRE. */
   2221 		newspacq = key_newspacq(&sp->spidx);
   2222 		if (newspacq == NULL)
   2223 			return ENOBUFS;
   2224 
   2225 		/* add to acqtree */
   2226 		LIST_INSERT_HEAD(&spacqtree, newspacq, chain);
   2227 	}
   2228 
   2229 	/* create new sadb_msg to reply. */
   2230 	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
   2231 	if (!m) {
   2232 		error = ENOBUFS;
   2233 		goto fail;
   2234 	}
   2235 	result = m;
   2236 
   2237 	result->m_pkthdr.len = 0;
   2238 	for (m = result; m; m = m->m_next)
   2239 		result->m_pkthdr.len += m->m_len;
   2240 
   2241 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   2242 	    PFKEY_UNIT64(result->m_pkthdr.len);
   2243 
   2244 	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
   2245 
   2246 fail:
   2247 	if (result)
   2248 		m_freem(result);
   2249 	return error;
   2250 }
   2251 #endif /* notyet */
   2252 
   2253 /*
   2254  * SADB_SPDFLUSH processing
   2255  * receive
   2256  *   <base>
   2257  * from the user, and free all entries in secpctree.
   2258  * and send,
   2259  *   <base>
   2260  * to the user.
   2261  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
   2262  *
   2263  * m will always be freed.
   2264  */
   2265 static int
   2266 key_api_spdflush(struct socket *so, struct mbuf *m,
   2267 	     const struct sadb_msghdr *mhp)
   2268 {
   2269 	struct sadb_msg *newmsg;
   2270 	struct secpolicy *sp;
   2271 	u_int dir;
   2272 
   2273 	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
   2274 		return key_senderror(so, m, EINVAL);
   2275 
   2276 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   2277 		struct secpolicy * nextsp;
   2278 		LIST_FOREACH_SAFE(sp, &sptree[dir], chain, nextsp) {
   2279 			if (sp->state == IPSEC_SPSTATE_DEAD)
   2280 				continue;
   2281 			key_sp_dead(sp);
   2282 			key_sp_unlink(sp);
   2283 			/* 'sp' dead; continue transfers to 'sp = nextsp' */
   2284 			continue;
   2285 		}
   2286 	}
   2287 
   2288 	/* Invalidate all cached SPD pointers in the PCBs. */
   2289 	ipsec_invalpcbcacheall();
   2290 
   2291 	/* We're deleting policy; no need to invalidate the ipflow cache. */
   2292 
   2293 	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
   2294 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   2295 		return key_senderror(so, m, ENOBUFS);
   2296 	}
   2297 
   2298 	if (m->m_next)
   2299 		m_freem(m->m_next);
   2300 	m->m_next = NULL;
   2301 	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   2302 	newmsg = mtod(m, struct sadb_msg *);
   2303 	newmsg->sadb_msg_errno = 0;
   2304 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
   2305 
   2306 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   2307 }
   2308 
   2309 static struct sockaddr key_src = {
   2310 	.sa_len = 2,
   2311 	.sa_family = PF_KEY,
   2312 };
   2313 
   2314 static struct mbuf *
   2315 key_setspddump_chain(int *errorp, int *lenp, pid_t pid)
   2316 {
   2317 	struct secpolicy *sp;
   2318 	int cnt;
   2319 	u_int dir;
   2320 	struct mbuf *m, *n, *prev;
   2321 	int totlen;
   2322 
   2323 	*lenp = 0;
   2324 
   2325 	/* search SPD entry and get buffer size. */
   2326 	cnt = 0;
   2327 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   2328 		LIST_FOREACH(sp, &sptree[dir], chain) {
   2329 			cnt++;
   2330 		}
   2331 	}
   2332 
   2333 	if (cnt == 0) {
   2334 		*errorp = ENOENT;
   2335 		return (NULL);
   2336 	}
   2337 
   2338 	m = NULL;
   2339 	prev = m;
   2340 	totlen = 0;
   2341 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   2342 		LIST_FOREACH(sp, &sptree[dir], chain) {
   2343 			--cnt;
   2344 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
   2345 
   2346 			if (!n) {
   2347 				*errorp = ENOBUFS;
   2348 				if (m)
   2349 					m_freem(m);
   2350 				return (NULL);
   2351 			}
   2352 
   2353 			totlen += n->m_pkthdr.len;
   2354 			if (!m) {
   2355 				m = n;
   2356 			} else {
   2357 				prev->m_nextpkt = n;
   2358 			}
   2359 			prev = n;
   2360 		}
   2361 	}
   2362 
   2363 	*lenp = totlen;
   2364 	*errorp = 0;
   2365 	return (m);
   2366 }
   2367 
   2368 /*
   2369  * SADB_SPDDUMP processing
   2370  * receive
   2371  *   <base>
   2372  * from the user, and dump all SP leaves
   2373  * and send,
   2374  *   <base> .....
   2375  * to the ikmpd.
   2376  *
   2377  * m will always be freed.
   2378  */
   2379 static int
   2380 key_api_spddump(struct socket *so, struct mbuf *m0,
   2381  	    const struct sadb_msghdr *mhp)
   2382 {
   2383 	struct mbuf *n;
   2384 	int error, len;
   2385 	int ok, s;
   2386 	pid_t pid;
   2387 
   2388 	pid = mhp->msg->sadb_msg_pid;
   2389 	/*
   2390 	 * If the requestor has insufficient socket-buffer space
   2391 	 * for the entire chain, nobody gets any response to the DUMP.
   2392 	 * XXX For now, only the requestor ever gets anything.
   2393 	 * Moreover, if the requestor has any space at all, they receive
   2394 	 * the entire chain, otherwise the request is refused with  ENOBUFS.
   2395 	 */
   2396 	if (sbspace(&so->so_rcv) <= 0) {
   2397 		return key_senderror(so, m0, ENOBUFS);
   2398 	}
   2399 
   2400 	s = splsoftnet();
   2401 	n = key_setspddump_chain(&error, &len, pid);
   2402 	splx(s);
   2403 
   2404 	if (n == NULL) {
   2405 		return key_senderror(so, m0, ENOENT);
   2406 	}
   2407 	{
   2408 		uint64_t *ps = PFKEY_STAT_GETREF();
   2409 		ps[PFKEY_STAT_IN_TOTAL]++;
   2410 		ps[PFKEY_STAT_IN_BYTES] += len;
   2411 		PFKEY_STAT_PUTREF();
   2412 	}
   2413 
   2414 	/*
   2415 	 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
   2416 	 * The requestor receives either the entire chain, or an
   2417 	 * error message with ENOBUFS.
   2418 	 */
   2419 
   2420 	/*
   2421 	 * sbappendchainwith record takes the chain of entries, one
   2422 	 * packet-record per SPD entry, prepends the key_src sockaddr
   2423 	 * to each packet-record, links the sockaddr mbufs into a new
   2424 	 * list of records, then   appends the entire resulting
   2425 	 * list to the requesting socket.
   2426 	 */
   2427 	ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src, n,
   2428 	    SB_PRIO_ONESHOT_OVERFLOW);
   2429 
   2430 	if (!ok) {
   2431 		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
   2432 		m_freem(n);
   2433 		return key_senderror(so, m0, ENOBUFS);
   2434 	}
   2435 
   2436 	m_freem(m0);
   2437 	return error;
   2438 }
   2439 
   2440 /*
   2441  * SADB_X_NAT_T_NEW_MAPPING. Unused by racoon as of 2005/04/23
   2442  */
   2443 static int
   2444 key_api_nat_map(struct socket *so, struct mbuf *m,
   2445 	    const struct sadb_msghdr *mhp)
   2446 {
   2447 	struct sadb_x_nat_t_type *type;
   2448 	struct sadb_x_nat_t_port *sport;
   2449 	struct sadb_x_nat_t_port *dport;
   2450 	struct sadb_address *iaddr, *raddr;
   2451 	struct sadb_x_nat_t_frag *frag;
   2452 
   2453 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] == NULL ||
   2454 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] == NULL ||
   2455 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] == NULL) {
   2456 		IPSECLOG(LOG_DEBUG, "invalid message.\n");
   2457 		return key_senderror(so, m, EINVAL);
   2458 	}
   2459 	if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
   2460 	    (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
   2461 	    (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
   2462 		IPSECLOG(LOG_DEBUG, "invalid message.\n");
   2463 		return key_senderror(so, m, EINVAL);
   2464 	}
   2465 
   2466 	if ((mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) &&
   2467 	    (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr))) {
   2468 		IPSECLOG(LOG_DEBUG, "invalid message\n");
   2469 		return key_senderror(so, m, EINVAL);
   2470 	}
   2471 
   2472 	if ((mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) &&
   2473 	    (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr))) {
   2474 		IPSECLOG(LOG_DEBUG, "invalid message\n");
   2475 		return key_senderror(so, m, EINVAL);
   2476 	}
   2477 
   2478 	if ((mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) &&
   2479 	    (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag))) {
   2480 		IPSECLOG(LOG_DEBUG, "invalid message\n");
   2481 		return key_senderror(so, m, EINVAL);
   2482 	}
   2483 
   2484 	type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   2485 	sport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   2486 	dport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   2487 	iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
   2488 	raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
   2489 	frag = (struct sadb_x_nat_t_frag *) mhp->ext[SADB_X_EXT_NAT_T_FRAG];
   2490 
   2491 	/*
   2492 	 * XXX handle that, it should also contain a SA, or anything
   2493 	 * that enable to update the SA information.
   2494 	 */
   2495 
   2496 	return 0;
   2497 }
   2498 
   2499 static struct mbuf *
   2500 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, pid_t pid)
   2501 {
   2502 	struct mbuf *result = NULL, *m;
   2503 
   2504 	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid,
   2505 	    key_sp_refcnt(sp));
   2506 	if (!m)
   2507 		goto fail;
   2508 	result = m;
   2509 
   2510 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   2511 	    &sp->spidx.src.sa, sp->spidx.prefs, sp->spidx.ul_proto);
   2512 	if (!m)
   2513 		goto fail;
   2514 	m_cat(result, m);
   2515 
   2516 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   2517 	    &sp->spidx.dst.sa, sp->spidx.prefd, sp->spidx.ul_proto);
   2518 	if (!m)
   2519 		goto fail;
   2520 	m_cat(result, m);
   2521 
   2522 	m = key_sp2msg(sp);
   2523 	if (!m)
   2524 		goto fail;
   2525 	m_cat(result, m);
   2526 
   2527 	if ((result->m_flags & M_PKTHDR) == 0)
   2528 		goto fail;
   2529 
   2530 	if (result->m_len < sizeof(struct sadb_msg)) {
   2531 		result = m_pullup(result, sizeof(struct sadb_msg));
   2532 		if (result == NULL)
   2533 			goto fail;
   2534 	}
   2535 
   2536 	result->m_pkthdr.len = 0;
   2537 	for (m = result; m; m = m->m_next)
   2538 		result->m_pkthdr.len += m->m_len;
   2539 
   2540 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   2541 	    PFKEY_UNIT64(result->m_pkthdr.len);
   2542 
   2543 	return result;
   2544 
   2545 fail:
   2546 	m_freem(result);
   2547 	return NULL;
   2548 }
   2549 
   2550 /*
   2551  * get PFKEY message length for security policy and request.
   2552  */
   2553 static u_int
   2554 key_getspreqmsglen(const struct secpolicy *sp)
   2555 {
   2556 	u_int tlen;
   2557 
   2558 	tlen = sizeof(struct sadb_x_policy);
   2559 
   2560 	/* if is the policy for ipsec ? */
   2561 	if (sp->policy != IPSEC_POLICY_IPSEC)
   2562 		return tlen;
   2563 
   2564 	/* get length of ipsec requests */
   2565     {
   2566 	const struct ipsecrequest *isr;
   2567 	int len;
   2568 
   2569 	for (isr = sp->req; isr != NULL; isr = isr->next) {
   2570 		len = sizeof(struct sadb_x_ipsecrequest)
   2571 		    + isr->saidx.src.sa.sa_len + isr->saidx.dst.sa.sa_len;
   2572 
   2573 		tlen += PFKEY_ALIGN8(len);
   2574 	}
   2575     }
   2576 
   2577 	return tlen;
   2578 }
   2579 
   2580 /*
   2581  * SADB_SPDEXPIRE processing
   2582  * send
   2583  *   <base, address(SD), lifetime(CH), policy>
   2584  * to KMD by PF_KEY.
   2585  *
   2586  * OUT:	0	: succeed
   2587  *	others	: error number
   2588  */
   2589 static int
   2590 key_spdexpire(struct secpolicy *sp)
   2591 {
   2592 	int s;
   2593 	struct mbuf *result = NULL, *m;
   2594 	int len;
   2595 	int error = -1;
   2596 	struct sadb_lifetime *lt;
   2597 
   2598 	/* XXX: Why do we lock ? */
   2599 	s = splsoftnet();	/*called from softclock()*/
   2600 
   2601 	KASSERT(sp != NULL);
   2602 
   2603 	/* set msg header */
   2604 	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
   2605 	if (!m) {
   2606 		error = ENOBUFS;
   2607 		goto fail;
   2608 	}
   2609 	result = m;
   2610 
   2611 	/* create lifetime extension (current and hard) */
   2612 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
   2613 	m = key_alloc_mbuf(len);
   2614 	if (!m || m->m_next) {	/*XXX*/
   2615 		if (m)
   2616 			m_freem(m);
   2617 		error = ENOBUFS;
   2618 		goto fail;
   2619 	}
   2620 	memset(mtod(m, void *), 0, len);
   2621 	lt = mtod(m, struct sadb_lifetime *);
   2622 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   2623 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   2624 	lt->sadb_lifetime_allocations = 0;
   2625 	lt->sadb_lifetime_bytes = 0;
   2626 	lt->sadb_lifetime_addtime = time_mono_to_wall(sp->created);
   2627 	lt->sadb_lifetime_usetime = time_mono_to_wall(sp->lastused);
   2628 	lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
   2629 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   2630 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
   2631 	lt->sadb_lifetime_allocations = 0;
   2632 	lt->sadb_lifetime_bytes = 0;
   2633 	lt->sadb_lifetime_addtime = sp->lifetime;
   2634 	lt->sadb_lifetime_usetime = sp->validtime;
   2635 	m_cat(result, m);
   2636 
   2637 	/* set sadb_address for source */
   2638 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &sp->spidx.src.sa,
   2639 	    sp->spidx.prefs, sp->spidx.ul_proto);
   2640 	if (!m) {
   2641 		error = ENOBUFS;
   2642 		goto fail;
   2643 	}
   2644 	m_cat(result, m);
   2645 
   2646 	/* set sadb_address for destination */
   2647 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &sp->spidx.dst.sa,
   2648 	    sp->spidx.prefd, sp->spidx.ul_proto);
   2649 	if (!m) {
   2650 		error = ENOBUFS;
   2651 		goto fail;
   2652 	}
   2653 	m_cat(result, m);
   2654 
   2655 	/* set secpolicy */
   2656 	m = key_sp2msg(sp);
   2657 	if (!m) {
   2658 		error = ENOBUFS;
   2659 		goto fail;
   2660 	}
   2661 	m_cat(result, m);
   2662 
   2663 	if ((result->m_flags & M_PKTHDR) == 0) {
   2664 		error = EINVAL;
   2665 		goto fail;
   2666 	}
   2667 
   2668 	if (result->m_len < sizeof(struct sadb_msg)) {
   2669 		result = m_pullup(result, sizeof(struct sadb_msg));
   2670 		if (result == NULL) {
   2671 			error = ENOBUFS;
   2672 			goto fail;
   2673 		}
   2674 	}
   2675 
   2676 	result->m_pkthdr.len = 0;
   2677 	for (m = result; m; m = m->m_next)
   2678 		result->m_pkthdr.len += m->m_len;
   2679 
   2680 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   2681 	    PFKEY_UNIT64(result->m_pkthdr.len);
   2682 
   2683 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   2684 
   2685  fail:
   2686 	if (result)
   2687 		m_freem(result);
   2688 	splx(s);
   2689 	return error;
   2690 }
   2691 
   2692 /* %%% SAD management */
   2693 /*
   2694  * allocating a memory for new SA head, and copy from the values of mhp.
   2695  * OUT:	NULL	: failure due to the lack of memory.
   2696  *	others	: pointer to new SA head.
   2697  */
   2698 static struct secashead *
   2699 key_newsah(const struct secasindex *saidx)
   2700 {
   2701 	struct secashead *newsah;
   2702 	int i;
   2703 
   2704 	KASSERT(saidx != NULL);
   2705 
   2706 	newsah = kmem_zalloc(sizeof(struct secashead), KM_SLEEP);
   2707 	for (i = 0; i < __arraycount(newsah->savtree); i++)
   2708 		LIST_INIT(&newsah->savtree[i]);
   2709 	newsah->saidx = *saidx;
   2710 
   2711 	/* add to saidxtree */
   2712 	newsah->state = SADB_SASTATE_MATURE;
   2713 	LIST_INSERT_HEAD(&sahtree, newsah, chain);
   2714 
   2715 	return newsah;
   2716 }
   2717 
   2718 /*
   2719  * delete SA index and all SA registerd.
   2720  */
   2721 static void
   2722 key_delsah(struct secashead *sah)
   2723 {
   2724 	struct secasvar *sav;
   2725 	u_int state;
   2726 	int s;
   2727 	int zombie = 0;
   2728 
   2729 	KASSERT(!cpu_softintr_p());
   2730 	KASSERT(sah != NULL);
   2731 
   2732 	s = splsoftnet();
   2733 
   2734 	/* searching all SA registerd in the secindex. */
   2735 	SASTATE_ANY_FOREACH(state) {
   2736 		LIST_FOREACH(sav, &sah->savtree[state], chain) {
   2737 			/* give up to delete this sa */
   2738 			zombie++;
   2739 		}
   2740 	}
   2741 
   2742 	/* don't delete sah only if there are savs. */
   2743 	if (zombie) {
   2744 		splx(s);
   2745 		return;
   2746 	}
   2747 
   2748 	rtcache_free(&sah->sa_route);
   2749 
   2750 	/* remove from tree of SA index */
   2751 	KASSERT(__LIST_CHAINED(sah));
   2752 	LIST_REMOVE(sah, chain);
   2753 
   2754 	if (sah->idents != NULL)
   2755 		kmem_free(sah->idents, sah->idents_len);
   2756 	if (sah->identd != NULL)
   2757 		kmem_free(sah->identd, sah->identd_len);
   2758 
   2759 	kmem_free(sah, sizeof(*sah));
   2760 
   2761 	splx(s);
   2762 	return;
   2763 }
   2764 
   2765 /*
   2766  * allocating a new SA with LARVAL state.
   2767  * key_api_add() and key_api_getspi() call,
   2768  * and copy the values of mhp into new buffer.
   2769  * When SAD message type is GETSPI:
   2770  *	to set sequence number from acq_seq++,
   2771  *	to set zero to SPI.
   2772  *	not to call key_setsava().
   2773  * OUT:	NULL	: fail
   2774  *	others	: pointer to new secasvar.
   2775  *
   2776  * does not modify mbuf.  does not free mbuf on error.
   2777  */
   2778 static struct secasvar *
   2779 key_newsav(struct mbuf *m, const struct sadb_msghdr *mhp,
   2780     int *errp, const char* where, int tag)
   2781 {
   2782 	struct secasvar *newsav;
   2783 	const struct sadb_sa *xsa;
   2784 
   2785 	KASSERT(!cpu_softintr_p());
   2786 	KASSERT(m != NULL);
   2787 	KASSERT(mhp != NULL);
   2788 	KASSERT(mhp->msg != NULL);
   2789 
   2790 	newsav = kmem_zalloc(sizeof(struct secasvar), KM_SLEEP);
   2791 
   2792 	switch (mhp->msg->sadb_msg_type) {
   2793 	case SADB_GETSPI:
   2794 		newsav->spi = 0;
   2795 
   2796 #ifdef IPSEC_DOSEQCHECK
   2797 		/* sync sequence number */
   2798 		if (mhp->msg->sadb_msg_seq == 0)
   2799 			newsav->seq =
   2800 			    (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
   2801 		else
   2802 #endif
   2803 			newsav->seq = mhp->msg->sadb_msg_seq;
   2804 		break;
   2805 
   2806 	case SADB_ADD:
   2807 		/* sanity check */
   2808 		if (mhp->ext[SADB_EXT_SA] == NULL) {
   2809 			IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   2810 			*errp = EINVAL;
   2811 			goto error;
   2812 		}
   2813 		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   2814 		newsav->spi = xsa->sadb_sa_spi;
   2815 		newsav->seq = mhp->msg->sadb_msg_seq;
   2816 		break;
   2817 	default:
   2818 		*errp = EINVAL;
   2819 		goto error;
   2820 	}
   2821 
   2822 	/* copy sav values */
   2823 	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
   2824 		*errp = key_setsaval(newsav, m, mhp);
   2825 		if (*errp)
   2826 			goto error;
   2827 	}
   2828 
   2829 	/* reset created */
   2830 	newsav->created = time_uptime;
   2831 	newsav->pid = mhp->msg->sadb_msg_pid;
   2832 
   2833 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   2834 	    "DP from %s:%u return SA:%p\n", where, tag, newsav);
   2835 	return newsav;
   2836 
   2837 error:
   2838 	KASSERT(*errp != 0);
   2839 	kmem_free(newsav, sizeof(*newsav));
   2840 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   2841 	    "DP from %s:%u return SA:NULL\n", where, tag);
   2842 	return NULL;
   2843 }
   2844 
   2845 
   2846 static void
   2847 key_clear_xform(struct secasvar *sav)
   2848 {
   2849 
   2850 	/*
   2851 	 * Cleanup xform state.  Note that zeroize'ing causes the
   2852 	 * keys to be cleared; otherwise we must do it ourself.
   2853 	 */
   2854 	if (sav->tdb_xform != NULL) {
   2855 		sav->tdb_xform->xf_zeroize(sav);
   2856 		sav->tdb_xform = NULL;
   2857 	} else {
   2858 		if (sav->key_auth != NULL)
   2859 			explicit_memset(_KEYBUF(sav->key_auth), 0,
   2860 			    _KEYLEN(sav->key_auth));
   2861 		if (sav->key_enc != NULL)
   2862 			explicit_memset(_KEYBUF(sav->key_enc), 0,
   2863 			    _KEYLEN(sav->key_enc));
   2864 	}
   2865 }
   2866 
   2867 /*
   2868  * free() SA variable entry.
   2869  */
   2870 static void
   2871 key_delsav(struct secasvar *sav)
   2872 {
   2873 
   2874 	KASSERT(sav != NULL);
   2875 	KASSERTMSG(sav->refcnt == 0, "reference count %u > 0", sav->refcnt);
   2876 
   2877 	key_clear_xform(sav);
   2878 	key_freesaval(sav);
   2879 	kmem_intr_free(sav, sizeof(*sav));
   2880 
   2881 	return;
   2882 }
   2883 
   2884 /*
   2885  * search SAD.
   2886  * OUT:
   2887  *	NULL	: not found
   2888  *	others	: found, pointer to a SA.
   2889  */
   2890 static struct secashead *
   2891 key_getsah(const struct secasindex *saidx, int flag)
   2892 {
   2893 	struct secashead *sah;
   2894 
   2895 	LIST_FOREACH(sah, &sahtree, chain) {
   2896 		if (sah->state == SADB_SASTATE_DEAD)
   2897 			continue;
   2898 		if (key_saidx_match(&sah->saidx, saidx, flag))
   2899 			return sah;
   2900 	}
   2901 
   2902 	return NULL;
   2903 }
   2904 
   2905 /*
   2906  * check not to be duplicated SPI.
   2907  * NOTE: this function is too slow due to searching all SAD.
   2908  * OUT:
   2909  *	NULL	: not found
   2910  *	others	: found, pointer to a SA.
   2911  */
   2912 static bool
   2913 key_checkspidup(const struct secasindex *saidx, u_int32_t spi)
   2914 {
   2915 	struct secashead *sah;
   2916 	struct secasvar *sav;
   2917 
   2918 	/* check address family */
   2919 	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
   2920 		IPSECLOG(LOG_DEBUG, "address family mismatched.\n");
   2921 		return false;
   2922 	}
   2923 
   2924 	/* check all SAD */
   2925 	LIST_FOREACH(sah, &sahtree, chain) {
   2926 		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
   2927 			continue;
   2928 		sav = key_getsavbyspi(sah, spi);
   2929 		if (sav != NULL) {
   2930 			KEY_FREESAV(&sav);
   2931 			return true;
   2932 		}
   2933 	}
   2934 
   2935 	return false;
   2936 }
   2937 
   2938 /*
   2939  * search SAD litmited alive SA, protocol, SPI.
   2940  * OUT:
   2941  *	NULL	: not found
   2942  *	others	: found, pointer to a SA.
   2943  */
   2944 static struct secasvar *
   2945 key_getsavbyspi(struct secashead *sah, u_int32_t spi)
   2946 {
   2947 	struct secasvar *sav;
   2948 	u_int state;
   2949 
   2950 	/* search all status */
   2951 	SASTATE_ALIVE_FOREACH(state) {
   2952 		LIST_FOREACH(sav, &sah->savtree[state], chain) {
   2953 
   2954 			/* sanity check */
   2955 			if (sav->state != state) {
   2956 				IPSECLOG(LOG_DEBUG,
   2957 				    "invalid sav->state (queue: %d SA: %d)\n",
   2958 				    state, sav->state);
   2959 				continue;
   2960 			}
   2961 
   2962 			if (sav->spi == spi) {
   2963 				SA_ADDREF(sav);
   2964 				return sav;
   2965 			}
   2966 		}
   2967 	}
   2968 
   2969 	return NULL;
   2970 }
   2971 
   2972 /*
   2973  * Free allocated data to member variables of sav:
   2974  * sav->replay, sav->key_* and sav->lft_*.
   2975  */
   2976 static void
   2977 key_freesaval(struct secasvar *sav)
   2978 {
   2979 
   2980 	KASSERT(sav->refcnt == 0);
   2981 
   2982 	if (sav->replay != NULL)
   2983 		kmem_intr_free(sav->replay, sav->replay_len);
   2984 	if (sav->key_auth != NULL)
   2985 		kmem_intr_free(sav->key_auth, sav->key_auth_len);
   2986 	if (sav->key_enc != NULL)
   2987 		kmem_intr_free(sav->key_enc, sav->key_enc_len);
   2988 	if (sav->lft_c != NULL)
   2989 		kmem_intr_free(sav->lft_c, sizeof(*(sav->lft_c)));
   2990 	if (sav->lft_h != NULL)
   2991 		kmem_intr_free(sav->lft_h, sizeof(*(sav->lft_h)));
   2992 	if (sav->lft_s != NULL)
   2993 		kmem_intr_free(sav->lft_s, sizeof(*(sav->lft_s)));
   2994 }
   2995 
   2996 /*
   2997  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
   2998  * You must update these if need.
   2999  * OUT:	0:	success.
   3000  *	!0:	failure.
   3001  *
   3002  * does not modify mbuf.  does not free mbuf on error.
   3003  */
   3004 static int
   3005 key_setsaval(struct secasvar *sav, struct mbuf *m,
   3006 	     const struct sadb_msghdr *mhp)
   3007 {
   3008 	int error = 0;
   3009 
   3010 	KASSERT(!cpu_softintr_p());
   3011 	KASSERT(m != NULL);
   3012 	KASSERT(mhp != NULL);
   3013 	KASSERT(mhp->msg != NULL);
   3014 
   3015 	/* We shouldn't initialize sav variables while someone uses it. */
   3016 	KASSERT(sav->refcnt == 0);
   3017 
   3018 	/* SA */
   3019 	if (mhp->ext[SADB_EXT_SA] != NULL) {
   3020 		const struct sadb_sa *sa0;
   3021 
   3022 		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   3023 		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
   3024 			error = EINVAL;
   3025 			goto fail;
   3026 		}
   3027 
   3028 		sav->alg_auth = sa0->sadb_sa_auth;
   3029 		sav->alg_enc = sa0->sadb_sa_encrypt;
   3030 		sav->flags = sa0->sadb_sa_flags;
   3031 
   3032 		/* replay window */
   3033 		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
   3034 			size_t len = sizeof(struct secreplay) +
   3035 			    sa0->sadb_sa_replay;
   3036 			sav->replay = kmem_zalloc(len, KM_SLEEP);
   3037 			sav->replay_len = len;
   3038 			if (sa0->sadb_sa_replay != 0)
   3039 				sav->replay->bitmap = (char*)(sav->replay+1);
   3040 			sav->replay->wsize = sa0->sadb_sa_replay;
   3041 		}
   3042 	}
   3043 
   3044 	/* Authentication keys */
   3045 	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
   3046 		const struct sadb_key *key0;
   3047 		int len;
   3048 
   3049 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
   3050 		len = mhp->extlen[SADB_EXT_KEY_AUTH];
   3051 
   3052 		error = 0;
   3053 		if (len < sizeof(*key0)) {
   3054 			error = EINVAL;
   3055 			goto fail;
   3056 		}
   3057 		switch (mhp->msg->sadb_msg_satype) {
   3058 		case SADB_SATYPE_AH:
   3059 		case SADB_SATYPE_ESP:
   3060 		case SADB_X_SATYPE_TCPSIGNATURE:
   3061 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
   3062 			    sav->alg_auth != SADB_X_AALG_NULL)
   3063 				error = EINVAL;
   3064 			break;
   3065 		case SADB_X_SATYPE_IPCOMP:
   3066 		default:
   3067 			error = EINVAL;
   3068 			break;
   3069 		}
   3070 		if (error) {
   3071 			IPSECLOG(LOG_DEBUG, "invalid key_auth values.\n");
   3072 			goto fail;
   3073 		}
   3074 
   3075 		sav->key_auth = key_newbuf(key0, len);
   3076 		sav->key_auth_len = len;
   3077 	}
   3078 
   3079 	/* Encryption key */
   3080 	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
   3081 		const struct sadb_key *key0;
   3082 		int len;
   3083 
   3084 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
   3085 		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
   3086 
   3087 		error = 0;
   3088 		if (len < sizeof(*key0)) {
   3089 			error = EINVAL;
   3090 			goto fail;
   3091 		}
   3092 		switch (mhp->msg->sadb_msg_satype) {
   3093 		case SADB_SATYPE_ESP:
   3094 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
   3095 			    sav->alg_enc != SADB_EALG_NULL) {
   3096 				error = EINVAL;
   3097 				break;
   3098 			}
   3099 			sav->key_enc = key_newbuf(key0, len);
   3100 			sav->key_enc_len = len;
   3101 			break;
   3102 		case SADB_X_SATYPE_IPCOMP:
   3103 			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
   3104 				error = EINVAL;
   3105 			sav->key_enc = NULL;	/*just in case*/
   3106 			break;
   3107 		case SADB_SATYPE_AH:
   3108 		case SADB_X_SATYPE_TCPSIGNATURE:
   3109 		default:
   3110 			error = EINVAL;
   3111 			break;
   3112 		}
   3113 		if (error) {
   3114 			IPSECLOG(LOG_DEBUG, "invalid key_enc value.\n");
   3115 			goto fail;
   3116 		}
   3117 	}
   3118 
   3119 	/* set iv */
   3120 	sav->ivlen = 0;
   3121 
   3122 	switch (mhp->msg->sadb_msg_satype) {
   3123 	case SADB_SATYPE_AH:
   3124 		error = xform_init(sav, XF_AH);
   3125 		break;
   3126 	case SADB_SATYPE_ESP:
   3127 		error = xform_init(sav, XF_ESP);
   3128 		break;
   3129 	case SADB_X_SATYPE_IPCOMP:
   3130 		error = xform_init(sav, XF_IPCOMP);
   3131 		break;
   3132 	case SADB_X_SATYPE_TCPSIGNATURE:
   3133 		error = xform_init(sav, XF_TCPSIGNATURE);
   3134 		break;
   3135 	}
   3136 	if (error) {
   3137 		IPSECLOG(LOG_DEBUG, "unable to initialize SA type %u.\n",
   3138 		    mhp->msg->sadb_msg_satype);
   3139 		goto fail;
   3140 	}
   3141 
   3142 	/* reset created */
   3143 	sav->created = time_uptime;
   3144 
   3145 	/* make lifetime for CURRENT */
   3146 	sav->lft_c = kmem_alloc(sizeof(struct sadb_lifetime), KM_SLEEP);
   3147 
   3148 	sav->lft_c->sadb_lifetime_len =
   3149 	    PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   3150 	sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   3151 	sav->lft_c->sadb_lifetime_allocations = 0;
   3152 	sav->lft_c->sadb_lifetime_bytes = 0;
   3153 	sav->lft_c->sadb_lifetime_addtime = time_uptime;
   3154 	sav->lft_c->sadb_lifetime_usetime = 0;
   3155 
   3156 	/* lifetimes for HARD and SOFT */
   3157     {
   3158 	const struct sadb_lifetime *lft0;
   3159 
   3160 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
   3161 	if (lft0 != NULL) {
   3162 		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
   3163 			error = EINVAL;
   3164 			goto fail;
   3165 		}
   3166 		sav->lft_h = key_newbuf(lft0, sizeof(*lft0));
   3167 	}
   3168 
   3169 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
   3170 	if (lft0 != NULL) {
   3171 		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
   3172 			error = EINVAL;
   3173 			goto fail;
   3174 		}
   3175 		sav->lft_s = key_newbuf(lft0, sizeof(*lft0));
   3176 		/* to be initialize ? */
   3177 	}
   3178     }
   3179 
   3180 	return 0;
   3181 
   3182  fail:
   3183 	key_clear_xform(sav);
   3184 	key_freesaval(sav);
   3185 
   3186 	return error;
   3187 }
   3188 
   3189 /*
   3190  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
   3191  * OUT:	0:	valid
   3192  *	other:	errno
   3193  */
   3194 static int
   3195 key_init_xform(struct secasvar *sav)
   3196 {
   3197 	int error;
   3198 
   3199 	/* We shouldn't initialize sav variables while someone uses it. */
   3200 	KASSERT(sav->refcnt == 0);
   3201 
   3202 	/* check SPI value */
   3203 	switch (sav->sah->saidx.proto) {
   3204 	case IPPROTO_ESP:
   3205 	case IPPROTO_AH:
   3206 		if (ntohl(sav->spi) <= 255) {
   3207 			IPSECLOG(LOG_DEBUG, "illegal range of SPI %u.\n",
   3208 			    (u_int32_t)ntohl(sav->spi));
   3209 			return EINVAL;
   3210 		}
   3211 		break;
   3212 	}
   3213 
   3214 	/* check satype */
   3215 	switch (sav->sah->saidx.proto) {
   3216 	case IPPROTO_ESP:
   3217 		/* check flags */
   3218 		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
   3219 		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
   3220 			IPSECLOG(LOG_DEBUG,
   3221 			    "invalid flag (derived) given to old-esp.\n");
   3222 			return EINVAL;
   3223 		}
   3224 		error = xform_init(sav, XF_ESP);
   3225 		break;
   3226 	case IPPROTO_AH:
   3227 		/* check flags */
   3228 		if (sav->flags & SADB_X_EXT_DERIV) {
   3229 			IPSECLOG(LOG_DEBUG,
   3230 			    "invalid flag (derived) given to AH SA.\n");
   3231 			return EINVAL;
   3232 		}
   3233 		if (sav->alg_enc != SADB_EALG_NONE) {
   3234 			IPSECLOG(LOG_DEBUG,
   3235 			    "protocol and algorithm mismated.\n");
   3236 			return(EINVAL);
   3237 		}
   3238 		error = xform_init(sav, XF_AH);
   3239 		break;
   3240 	case IPPROTO_IPCOMP:
   3241 		if (sav->alg_auth != SADB_AALG_NONE) {
   3242 			IPSECLOG(LOG_DEBUG,
   3243 			    "protocol and algorithm mismated.\n");
   3244 			return(EINVAL);
   3245 		}
   3246 		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
   3247 		 && ntohl(sav->spi) >= 0x10000) {
   3248 			IPSECLOG(LOG_DEBUG, "invalid cpi for IPComp.\n");
   3249 			return(EINVAL);
   3250 		}
   3251 		error = xform_init(sav, XF_IPCOMP);
   3252 		break;
   3253 	case IPPROTO_TCP:
   3254 		if (sav->alg_enc != SADB_EALG_NONE) {
   3255 			IPSECLOG(LOG_DEBUG,
   3256 			    "protocol and algorithm mismated.\n");
   3257 			return(EINVAL);
   3258 		}
   3259 		error = xform_init(sav, XF_TCPSIGNATURE);
   3260 		break;
   3261 	default:
   3262 		IPSECLOG(LOG_DEBUG, "Invalid satype.\n");
   3263 		error = EPROTONOSUPPORT;
   3264 		break;
   3265 	}
   3266 
   3267 	return error;
   3268 }
   3269 
   3270 /*
   3271  * subroutine for SADB_GET and SADB_DUMP.
   3272  */
   3273 static struct mbuf *
   3274 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
   3275 	      u_int32_t seq, u_int32_t pid)
   3276 {
   3277 	struct mbuf *result = NULL, *tres = NULL, *m;
   3278 	int l = 0;
   3279 	int i;
   3280 	void *p;
   3281 	struct sadb_lifetime lt;
   3282 	int dumporder[] = {
   3283 		SADB_EXT_SA, SADB_X_EXT_SA2,
   3284 		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
   3285 		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
   3286 		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
   3287 		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
   3288 		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
   3289 		SADB_X_EXT_NAT_T_TYPE,
   3290 		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
   3291 		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
   3292 		SADB_X_EXT_NAT_T_FRAG,
   3293 
   3294 	};
   3295 
   3296 	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
   3297 	if (m == NULL)
   3298 		goto fail;
   3299 	result = m;
   3300 
   3301 	for (i = __arraycount(dumporder) - 1; i >= 0; i--) {
   3302 		m = NULL;
   3303 		p = NULL;
   3304 		switch (dumporder[i]) {
   3305 		case SADB_EXT_SA:
   3306 			m = key_setsadbsa(sav);
   3307 			break;
   3308 
   3309 		case SADB_X_EXT_SA2:
   3310 			m = key_setsadbxsa2(sav->sah->saidx.mode,
   3311 			    sav->replay ? sav->replay->count : 0,
   3312 			    sav->sah->saidx.reqid);
   3313 			break;
   3314 
   3315 		case SADB_EXT_ADDRESS_SRC:
   3316 			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   3317 			    &sav->sah->saidx.src.sa,
   3318 			    FULLMASK, IPSEC_ULPROTO_ANY);
   3319 			break;
   3320 
   3321 		case SADB_EXT_ADDRESS_DST:
   3322 			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   3323 			    &sav->sah->saidx.dst.sa,
   3324 			    FULLMASK, IPSEC_ULPROTO_ANY);
   3325 			break;
   3326 
   3327 		case SADB_EXT_KEY_AUTH:
   3328 			if (!sav->key_auth)
   3329 				continue;
   3330 			l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
   3331 			p = sav->key_auth;
   3332 			break;
   3333 
   3334 		case SADB_EXT_KEY_ENCRYPT:
   3335 			if (!sav->key_enc)
   3336 				continue;
   3337 			l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
   3338 			p = sav->key_enc;
   3339 			break;
   3340 
   3341 		case SADB_EXT_LIFETIME_CURRENT:
   3342 			KASSERT(sav->lft_c != NULL);
   3343 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
   3344 			memcpy(&lt, sav->lft_c, sizeof(struct sadb_lifetime));
   3345 			lt.sadb_lifetime_addtime =
   3346 			    time_mono_to_wall(lt.sadb_lifetime_addtime);
   3347 			lt.sadb_lifetime_usetime =
   3348 			    time_mono_to_wall(lt.sadb_lifetime_usetime);
   3349 			p = &lt;
   3350 			break;
   3351 
   3352 		case SADB_EXT_LIFETIME_HARD:
   3353 			if (!sav->lft_h)
   3354 				continue;
   3355 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
   3356 			p = sav->lft_h;
   3357 			break;
   3358 
   3359 		case SADB_EXT_LIFETIME_SOFT:
   3360 			if (!sav->lft_s)
   3361 				continue;
   3362 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
   3363 			p = sav->lft_s;
   3364 			break;
   3365 
   3366 		case SADB_X_EXT_NAT_T_TYPE:
   3367 			m = key_setsadbxtype(sav->natt_type);
   3368 			break;
   3369 
   3370 		case SADB_X_EXT_NAT_T_DPORT:
   3371 			if (sav->natt_type == 0)
   3372 				continue;
   3373 			m = key_setsadbxport(
   3374 			    key_portfromsaddr(&sav->sah->saidx.dst),
   3375 			    SADB_X_EXT_NAT_T_DPORT);
   3376 			break;
   3377 
   3378 		case SADB_X_EXT_NAT_T_SPORT:
   3379 			if (sav->natt_type == 0)
   3380 				continue;
   3381 			m = key_setsadbxport(
   3382 			    key_portfromsaddr(&sav->sah->saidx.src),
   3383 			    SADB_X_EXT_NAT_T_SPORT);
   3384 			break;
   3385 
   3386 		case SADB_X_EXT_NAT_T_FRAG:
   3387 			/* don't send frag info if not set */
   3388 			if (sav->natt_type == 0 || sav->esp_frag == IP_MAXPACKET)
   3389 				continue;
   3390 			m = key_setsadbxfrag(sav->esp_frag);
   3391 			break;
   3392 
   3393 		case SADB_X_EXT_NAT_T_OAI:
   3394 		case SADB_X_EXT_NAT_T_OAR:
   3395 			continue;
   3396 
   3397 		case SADB_EXT_ADDRESS_PROXY:
   3398 		case SADB_EXT_IDENTITY_SRC:
   3399 		case SADB_EXT_IDENTITY_DST:
   3400 			/* XXX: should we brought from SPD ? */
   3401 		case SADB_EXT_SENSITIVITY:
   3402 		default:
   3403 			continue;
   3404 		}
   3405 
   3406 		KASSERT(!(m && p));
   3407 		if (!m && !p)
   3408 			goto fail;
   3409 		if (p && tres) {
   3410 			M_PREPEND(tres, l, M_DONTWAIT);
   3411 			if (!tres)
   3412 				goto fail;
   3413 			memcpy(mtod(tres, void *), p, l);
   3414 			continue;
   3415 		}
   3416 		if (p) {
   3417 			m = key_alloc_mbuf(l);
   3418 			if (!m)
   3419 				goto fail;
   3420 			m_copyback(m, 0, l, p);
   3421 		}
   3422 
   3423 		if (tres)
   3424 			m_cat(m, tres);
   3425 		tres = m;
   3426 	}
   3427 
   3428 	m_cat(result, tres);
   3429 	tres = NULL; /* avoid free on error below */
   3430 
   3431 	if (result->m_len < sizeof(struct sadb_msg)) {
   3432 		result = m_pullup(result, sizeof(struct sadb_msg));
   3433 		if (result == NULL)
   3434 			goto fail;
   3435 	}
   3436 
   3437 	result->m_pkthdr.len = 0;
   3438 	for (m = result; m; m = m->m_next)
   3439 		result->m_pkthdr.len += m->m_len;
   3440 
   3441 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   3442 	    PFKEY_UNIT64(result->m_pkthdr.len);
   3443 
   3444 	return result;
   3445 
   3446 fail:
   3447 	m_freem(result);
   3448 	m_freem(tres);
   3449 	return NULL;
   3450 }
   3451 
   3452 
   3453 /*
   3454  * set a type in sadb_x_nat_t_type
   3455  */
   3456 static struct mbuf *
   3457 key_setsadbxtype(u_int16_t type)
   3458 {
   3459 	struct mbuf *m;
   3460 	size_t len;
   3461 	struct sadb_x_nat_t_type *p;
   3462 
   3463 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
   3464 
   3465 	m = key_alloc_mbuf(len);
   3466 	if (!m || m->m_next) {	/*XXX*/
   3467 		if (m)
   3468 			m_freem(m);
   3469 		return NULL;
   3470 	}
   3471 
   3472 	p = mtod(m, struct sadb_x_nat_t_type *);
   3473 
   3474 	memset(p, 0, len);
   3475 	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
   3476 	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
   3477 	p->sadb_x_nat_t_type_type = type;
   3478 
   3479 	return m;
   3480 }
   3481 /*
   3482  * set a port in sadb_x_nat_t_port. port is in network order
   3483  */
   3484 static struct mbuf *
   3485 key_setsadbxport(u_int16_t port, u_int16_t type)
   3486 {
   3487 	struct mbuf *m;
   3488 	size_t len;
   3489 	struct sadb_x_nat_t_port *p;
   3490 
   3491 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
   3492 
   3493 	m = key_alloc_mbuf(len);
   3494 	if (!m || m->m_next) {	/*XXX*/
   3495 		if (m)
   3496 			m_freem(m);
   3497 		return NULL;
   3498 	}
   3499 
   3500 	p = mtod(m, struct sadb_x_nat_t_port *);
   3501 
   3502 	memset(p, 0, len);
   3503 	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
   3504 	p->sadb_x_nat_t_port_exttype = type;
   3505 	p->sadb_x_nat_t_port_port = port;
   3506 
   3507 	return m;
   3508 }
   3509 
   3510 /*
   3511  * set fragmentation info in sadb_x_nat_t_frag
   3512  */
   3513 static struct mbuf *
   3514 key_setsadbxfrag(u_int16_t flen)
   3515 {
   3516 	struct mbuf *m;
   3517 	size_t len;
   3518 	struct sadb_x_nat_t_frag *p;
   3519 
   3520 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_frag));
   3521 
   3522 	m = key_alloc_mbuf(len);
   3523 	if (!m || m->m_next) {  /*XXX*/
   3524 		if (m)
   3525 			m_freem(m);
   3526 		return NULL;
   3527 	}
   3528 
   3529 	p = mtod(m, struct sadb_x_nat_t_frag *);
   3530 
   3531 	memset(p, 0, len);
   3532 	p->sadb_x_nat_t_frag_len = PFKEY_UNIT64(len);
   3533 	p->sadb_x_nat_t_frag_exttype = SADB_X_EXT_NAT_T_FRAG;
   3534 	p->sadb_x_nat_t_frag_fraglen = flen;
   3535 
   3536 	return m;
   3537 }
   3538 
   3539 /*
   3540  * Get port from sockaddr, port is in network order
   3541  */
   3542 u_int16_t
   3543 key_portfromsaddr(const union sockaddr_union *saddr)
   3544 {
   3545 	u_int16_t port;
   3546 
   3547 	switch (saddr->sa.sa_family) {
   3548 	case AF_INET: {
   3549 		port = saddr->sin.sin_port;
   3550 		break;
   3551 	}
   3552 #ifdef INET6
   3553 	case AF_INET6: {
   3554 		port = saddr->sin6.sin6_port;
   3555 		break;
   3556 	}
   3557 #endif
   3558 	default:
   3559 		printf("%s: unexpected address family\n", __func__);
   3560 		port = 0;
   3561 		break;
   3562 	}
   3563 
   3564 	return port;
   3565 }
   3566 
   3567 
   3568 /*
   3569  * Set port is struct sockaddr. port is in network order
   3570  */
   3571 static void
   3572 key_porttosaddr(union sockaddr_union *saddr, u_int16_t port)
   3573 {
   3574 	switch (saddr->sa.sa_family) {
   3575 	case AF_INET: {
   3576 		saddr->sin.sin_port = port;
   3577 		break;
   3578 	}
   3579 #ifdef INET6
   3580 	case AF_INET6: {
   3581 		saddr->sin6.sin6_port = port;
   3582 		break;
   3583 	}
   3584 #endif
   3585 	default:
   3586 		printf("%s: unexpected address family %d\n", __func__,
   3587 		    saddr->sa.sa_family);
   3588 		break;
   3589 	}
   3590 
   3591 	return;
   3592 }
   3593 
   3594 /*
   3595  * Safety check sa_len
   3596  */
   3597 static int
   3598 key_checksalen(const union sockaddr_union *saddr)
   3599 {
   3600 	switch (saddr->sa.sa_family) {
   3601 	case AF_INET:
   3602 		if (saddr->sa.sa_len != sizeof(struct sockaddr_in))
   3603 			return -1;
   3604 		break;
   3605 #ifdef INET6
   3606 	case AF_INET6:
   3607 		if (saddr->sa.sa_len != sizeof(struct sockaddr_in6))
   3608 			return -1;
   3609 		break;
   3610 #endif
   3611 	default:
   3612 		printf("%s: unexpected sa_family %d\n", __func__,
   3613 		    saddr->sa.sa_family);
   3614 			return -1;
   3615 		break;
   3616 	}
   3617 	return 0;
   3618 }
   3619 
   3620 
   3621 /*
   3622  * set data into sadb_msg.
   3623  */
   3624 static struct mbuf *
   3625 key_setsadbmsg(u_int8_t type,  u_int16_t tlen, u_int8_t satype,
   3626 	       u_int32_t seq, pid_t pid, u_int16_t reserved)
   3627 {
   3628 	struct mbuf *m;
   3629 	struct sadb_msg *p;
   3630 	int len;
   3631 
   3632 	CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) <= MCLBYTES);
   3633 
   3634 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   3635 
   3636 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   3637 	if (m && len > MHLEN) {
   3638 		MCLGET(m, M_DONTWAIT);
   3639 		if ((m->m_flags & M_EXT) == 0) {
   3640 			m_freem(m);
   3641 			m = NULL;
   3642 		}
   3643 	}
   3644 	if (!m)
   3645 		return NULL;
   3646 	m->m_pkthdr.len = m->m_len = len;
   3647 	m->m_next = NULL;
   3648 
   3649 	p = mtod(m, struct sadb_msg *);
   3650 
   3651 	memset(p, 0, len);
   3652 	p->sadb_msg_version = PF_KEY_V2;
   3653 	p->sadb_msg_type = type;
   3654 	p->sadb_msg_errno = 0;
   3655 	p->sadb_msg_satype = satype;
   3656 	p->sadb_msg_len = PFKEY_UNIT64(tlen);
   3657 	p->sadb_msg_reserved = reserved;
   3658 	p->sadb_msg_seq = seq;
   3659 	p->sadb_msg_pid = (u_int32_t)pid;
   3660 
   3661 	return m;
   3662 }
   3663 
   3664 /*
   3665  * copy secasvar data into sadb_address.
   3666  */
   3667 static struct mbuf *
   3668 key_setsadbsa(struct secasvar *sav)
   3669 {
   3670 	struct mbuf *m;
   3671 	struct sadb_sa *p;
   3672 	int len;
   3673 
   3674 	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
   3675 	m = key_alloc_mbuf(len);
   3676 	if (!m || m->m_next) {	/*XXX*/
   3677 		if (m)
   3678 			m_freem(m);
   3679 		return NULL;
   3680 	}
   3681 
   3682 	p = mtod(m, struct sadb_sa *);
   3683 
   3684 	memset(p, 0, len);
   3685 	p->sadb_sa_len = PFKEY_UNIT64(len);
   3686 	p->sadb_sa_exttype = SADB_EXT_SA;
   3687 	p->sadb_sa_spi = sav->spi;
   3688 	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
   3689 	p->sadb_sa_state = sav->state;
   3690 	p->sadb_sa_auth = sav->alg_auth;
   3691 	p->sadb_sa_encrypt = sav->alg_enc;
   3692 	p->sadb_sa_flags = sav->flags;
   3693 
   3694 	return m;
   3695 }
   3696 
   3697 /*
   3698  * set data into sadb_address.
   3699  */
   3700 static struct mbuf *
   3701 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
   3702 		u_int8_t prefixlen, u_int16_t ul_proto)
   3703 {
   3704 	struct mbuf *m;
   3705 	struct sadb_address *p;
   3706 	size_t len;
   3707 
   3708 	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
   3709 	    PFKEY_ALIGN8(saddr->sa_len);
   3710 	m = key_alloc_mbuf(len);
   3711 	if (!m || m->m_next) {	/*XXX*/
   3712 		if (m)
   3713 			m_freem(m);
   3714 		return NULL;
   3715 	}
   3716 
   3717 	p = mtod(m, struct sadb_address *);
   3718 
   3719 	memset(p, 0, len);
   3720 	p->sadb_address_len = PFKEY_UNIT64(len);
   3721 	p->sadb_address_exttype = exttype;
   3722 	p->sadb_address_proto = ul_proto;
   3723 	if (prefixlen == FULLMASK) {
   3724 		switch (saddr->sa_family) {
   3725 		case AF_INET:
   3726 			prefixlen = sizeof(struct in_addr) << 3;
   3727 			break;
   3728 		case AF_INET6:
   3729 			prefixlen = sizeof(struct in6_addr) << 3;
   3730 			break;
   3731 		default:
   3732 			; /*XXX*/
   3733 		}
   3734 	}
   3735 	p->sadb_address_prefixlen = prefixlen;
   3736 	p->sadb_address_reserved = 0;
   3737 
   3738 	memcpy(mtod(m, char *) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
   3739 	    saddr, saddr->sa_len);
   3740 
   3741 	return m;
   3742 }
   3743 
   3744 #if 0
   3745 /*
   3746  * set data into sadb_ident.
   3747  */
   3748 static struct mbuf *
   3749 key_setsadbident(u_int16_t exttype, u_int16_t idtype,
   3750 		 void *string, int stringlen, u_int64_t id)
   3751 {
   3752 	struct mbuf *m;
   3753 	struct sadb_ident *p;
   3754 	size_t len;
   3755 
   3756 	len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
   3757 	m = key_alloc_mbuf(len);
   3758 	if (!m || m->m_next) {	/*XXX*/
   3759 		if (m)
   3760 			m_freem(m);
   3761 		return NULL;
   3762 	}
   3763 
   3764 	p = mtod(m, struct sadb_ident *);
   3765 
   3766 	memset(p, 0, len);
   3767 	p->sadb_ident_len = PFKEY_UNIT64(len);
   3768 	p->sadb_ident_exttype = exttype;
   3769 	p->sadb_ident_type = idtype;
   3770 	p->sadb_ident_reserved = 0;
   3771 	p->sadb_ident_id = id;
   3772 
   3773 	memcpy(mtod(m, void *) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
   3774 	   	   string, stringlen);
   3775 
   3776 	return m;
   3777 }
   3778 #endif
   3779 
   3780 /*
   3781  * set data into sadb_x_sa2.
   3782  */
   3783 static struct mbuf *
   3784 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int16_t reqid)
   3785 {
   3786 	struct mbuf *m;
   3787 	struct sadb_x_sa2 *p;
   3788 	size_t len;
   3789 
   3790 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
   3791 	m = key_alloc_mbuf(len);
   3792 	if (!m || m->m_next) {	/*XXX*/
   3793 		if (m)
   3794 			m_freem(m);
   3795 		return NULL;
   3796 	}
   3797 
   3798 	p = mtod(m, struct sadb_x_sa2 *);
   3799 
   3800 	memset(p, 0, len);
   3801 	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
   3802 	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
   3803 	p->sadb_x_sa2_mode = mode;
   3804 	p->sadb_x_sa2_reserved1 = 0;
   3805 	p->sadb_x_sa2_reserved2 = 0;
   3806 	p->sadb_x_sa2_sequence = seq;
   3807 	p->sadb_x_sa2_reqid = reqid;
   3808 
   3809 	return m;
   3810 }
   3811 
   3812 /*
   3813  * set data into sadb_x_policy
   3814  */
   3815 static struct mbuf *
   3816 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
   3817 {
   3818 	struct mbuf *m;
   3819 	struct sadb_x_policy *p;
   3820 	size_t len;
   3821 
   3822 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
   3823 	m = key_alloc_mbuf(len);
   3824 	if (!m || m->m_next) {	/*XXX*/
   3825 		if (m)
   3826 			m_freem(m);
   3827 		return NULL;
   3828 	}
   3829 
   3830 	p = mtod(m, struct sadb_x_policy *);
   3831 
   3832 	memset(p, 0, len);
   3833 	p->sadb_x_policy_len = PFKEY_UNIT64(len);
   3834 	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
   3835 	p->sadb_x_policy_type = type;
   3836 	p->sadb_x_policy_dir = dir;
   3837 	p->sadb_x_policy_id = id;
   3838 
   3839 	return m;
   3840 }
   3841 
   3842 /* %%% utilities */
   3843 /*
   3844  * copy a buffer into the new buffer allocated.
   3845  */
   3846 static void *
   3847 key_newbuf(const void *src, u_int len)
   3848 {
   3849 	void *new;
   3850 
   3851 	new = kmem_alloc(len, KM_SLEEP);
   3852 	memcpy(new, src, len);
   3853 
   3854 	return new;
   3855 }
   3856 
   3857 /* compare my own address
   3858  * OUT:	1: true, i.e. my address.
   3859  *	0: false
   3860  */
   3861 int
   3862 key_ismyaddr(const struct sockaddr *sa)
   3863 {
   3864 #ifdef INET
   3865 	const struct sockaddr_in *sin;
   3866 	const struct in_ifaddr *ia;
   3867 	int s;
   3868 #endif
   3869 
   3870 	KASSERT(sa != NULL);
   3871 
   3872 	switch (sa->sa_family) {
   3873 #ifdef INET
   3874 	case AF_INET:
   3875 		sin = (const struct sockaddr_in *)sa;
   3876 		s = pserialize_read_enter();
   3877 		IN_ADDRLIST_READER_FOREACH(ia) {
   3878 			if (sin->sin_family == ia->ia_addr.sin_family &&
   3879 			    sin->sin_len == ia->ia_addr.sin_len &&
   3880 			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
   3881 			{
   3882 				pserialize_read_exit(s);
   3883 				return 1;
   3884 			}
   3885 		}
   3886 		pserialize_read_exit(s);
   3887 		break;
   3888 #endif
   3889 #ifdef INET6
   3890 	case AF_INET6:
   3891 		return key_ismyaddr6((const struct sockaddr_in6 *)sa);
   3892 #endif
   3893 	}
   3894 
   3895 	return 0;
   3896 }
   3897 
   3898 #ifdef INET6
   3899 /*
   3900  * compare my own address for IPv6.
   3901  * 1: ours
   3902  * 0: other
   3903  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
   3904  */
   3905 #include <netinet6/in6_var.h>
   3906 
   3907 static int
   3908 key_ismyaddr6(const struct sockaddr_in6 *sin6)
   3909 {
   3910 	struct in6_ifaddr *ia;
   3911 	int s;
   3912 	struct psref psref;
   3913 	int bound;
   3914 	int ours = 1;
   3915 
   3916 	bound = curlwp_bind();
   3917 	s = pserialize_read_enter();
   3918 	IN6_ADDRLIST_READER_FOREACH(ia) {
   3919 		bool ingroup;
   3920 
   3921 		if (key_sockaddr_match((const struct sockaddr *)&sin6,
   3922 		    (const struct sockaddr *)&ia->ia_addr, 0)) {
   3923 			pserialize_read_exit(s);
   3924 			goto ours;
   3925 		}
   3926 		ia6_acquire(ia, &psref);
   3927 		pserialize_read_exit(s);
   3928 
   3929 		/*
   3930 		 * XXX Multicast
   3931 		 * XXX why do we care about multlicast here while we don't care
   3932 		 * about IPv4 multicast??
   3933 		 * XXX scope
   3934 		 */
   3935 		ingroup = in6_multi_group(&sin6->sin6_addr, ia->ia_ifp);
   3936 		if (ingroup) {
   3937 			ia6_release(ia, &psref);
   3938 			goto ours;
   3939 		}
   3940 
   3941 		s = pserialize_read_enter();
   3942 		ia6_release(ia, &psref);
   3943 	}
   3944 	pserialize_read_exit(s);
   3945 
   3946 	/* loopback, just for safety */
   3947 	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
   3948 		goto ours;
   3949 
   3950 	ours = 0;
   3951 ours:
   3952 	curlwp_bindx(bound);
   3953 
   3954 	return ours;
   3955 }
   3956 #endif /*INET6*/
   3957 
   3958 /*
   3959  * compare two secasindex structure.
   3960  * flag can specify to compare 2 saidxes.
   3961  * compare two secasindex structure without both mode and reqid.
   3962  * don't compare port.
   3963  * IN:
   3964  *      saidx0: source, it can be in SAD.
   3965  *      saidx1: object.
   3966  * OUT:
   3967  *      1 : equal
   3968  *      0 : not equal
   3969  */
   3970 static int
   3971 key_saidx_match(
   3972 	const struct secasindex *saidx0,
   3973 	const struct secasindex *saidx1,
   3974 	int flag)
   3975 {
   3976 	int chkport;
   3977 	const struct sockaddr *sa0src, *sa0dst, *sa1src, *sa1dst;
   3978 
   3979 	KASSERT(saidx0 != NULL);
   3980 	KASSERT(saidx1 != NULL);
   3981 
   3982 	/* sanity */
   3983 	if (saidx0->proto != saidx1->proto)
   3984 		return 0;
   3985 
   3986 	if (flag == CMP_EXACTLY) {
   3987 		if (saidx0->mode != saidx1->mode)
   3988 			return 0;
   3989 		if (saidx0->reqid != saidx1->reqid)
   3990 			return 0;
   3991 		if (memcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
   3992 		    memcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
   3993 			return 0;
   3994 	} else {
   3995 
   3996 		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
   3997 		if (flag == CMP_MODE_REQID ||flag == CMP_REQID) {
   3998 			/*
   3999 			 * If reqid of SPD is non-zero, unique SA is required.
   4000 			 * The result must be of same reqid in this case.
   4001 			 */
   4002 			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
   4003 				return 0;
   4004 		}
   4005 
   4006 		if (flag == CMP_MODE_REQID) {
   4007 			if (saidx0->mode != IPSEC_MODE_ANY &&
   4008 			    saidx0->mode != saidx1->mode)
   4009 				return 0;
   4010 		}
   4011 
   4012 
   4013 		sa0src = &saidx0->src.sa;
   4014 		sa0dst = &saidx0->dst.sa;
   4015 		sa1src = &saidx1->src.sa;
   4016 		sa1dst = &saidx1->dst.sa;
   4017 		/*
   4018 		 * If NAT-T is enabled, check ports for tunnel mode.
   4019 		 * Don't do it for transport mode, as there is no
   4020 		 * port information available in the SP.
   4021 		 * Also don't check ports if they are set to zero
   4022 		 * in the SPD: This means we have a non-generated
   4023 		 * SPD which can't know UDP ports.
   4024 		 */
   4025 		if (saidx1->mode == IPSEC_MODE_TUNNEL)
   4026 			chkport = PORT_LOOSE;
   4027 		else
   4028 			chkport = PORT_NONE;
   4029 
   4030 		if (!key_sockaddr_match(sa0src, sa1src, chkport)) {
   4031 			return 0;
   4032 		}
   4033 		if (!key_sockaddr_match(sa0dst, sa1dst, chkport)) {
   4034 			return 0;
   4035 		}
   4036 	}
   4037 
   4038 	return 1;
   4039 }
   4040 
   4041 /*
   4042  * compare two secindex structure exactly.
   4043  * IN:
   4044  *	spidx0: source, it is often in SPD.
   4045  *	spidx1: object, it is often from PFKEY message.
   4046  * OUT:
   4047  *	1 : equal
   4048  *	0 : not equal
   4049  */
   4050 static int
   4051 key_spidx_match_exactly(
   4052 	const struct secpolicyindex *spidx0,
   4053 	const struct secpolicyindex *spidx1)
   4054 {
   4055 
   4056 	KASSERT(spidx0 != NULL);
   4057 	KASSERT(spidx1 != NULL);
   4058 
   4059 	/* sanity */
   4060 	if (spidx0->prefs != spidx1->prefs ||
   4061 	    spidx0->prefd != spidx1->prefd ||
   4062 	    spidx0->ul_proto != spidx1->ul_proto)
   4063 		return 0;
   4064 
   4065 	return key_sockaddr_match(&spidx0->src.sa, &spidx1->src.sa, PORT_STRICT) &&
   4066 	       key_sockaddr_match(&spidx0->dst.sa, &spidx1->dst.sa, PORT_STRICT);
   4067 }
   4068 
   4069 /*
   4070  * compare two secindex structure with mask.
   4071  * IN:
   4072  *	spidx0: source, it is often in SPD.
   4073  *	spidx1: object, it is often from IP header.
   4074  * OUT:
   4075  *	1 : equal
   4076  *	0 : not equal
   4077  */
   4078 static int
   4079 key_spidx_match_withmask(
   4080 	const struct secpolicyindex *spidx0,
   4081 	const struct secpolicyindex *spidx1)
   4082 {
   4083 
   4084 	KASSERT(spidx0 != NULL);
   4085 	KASSERT(spidx1 != NULL);
   4086 
   4087 	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
   4088 	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
   4089 	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
   4090 	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
   4091 		return 0;
   4092 
   4093 	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
   4094 	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY &&
   4095 	    spidx0->ul_proto != spidx1->ul_proto)
   4096 		return 0;
   4097 
   4098 	switch (spidx0->src.sa.sa_family) {
   4099 	case AF_INET:
   4100 		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY &&
   4101 		    spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
   4102 			return 0;
   4103 		if (!key_bb_match_withmask(&spidx0->src.sin.sin_addr,
   4104 		    &spidx1->src.sin.sin_addr, spidx0->prefs))
   4105 			return 0;
   4106 		break;
   4107 	case AF_INET6:
   4108 		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY &&
   4109 		    spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
   4110 			return 0;
   4111 		/*
   4112 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4113 		 * as a wildcard scope, which matches any scope zone ID.
   4114 		 */
   4115 		if (spidx0->src.sin6.sin6_scope_id &&
   4116 		    spidx1->src.sin6.sin6_scope_id &&
   4117 		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
   4118 			return 0;
   4119 		if (!key_bb_match_withmask(&spidx0->src.sin6.sin6_addr,
   4120 		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
   4121 			return 0;
   4122 		break;
   4123 	default:
   4124 		/* XXX */
   4125 		if (memcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
   4126 			return 0;
   4127 		break;
   4128 	}
   4129 
   4130 	switch (spidx0->dst.sa.sa_family) {
   4131 	case AF_INET:
   4132 		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY &&
   4133 		    spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
   4134 			return 0;
   4135 		if (!key_bb_match_withmask(&spidx0->dst.sin.sin_addr,
   4136 		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
   4137 			return 0;
   4138 		break;
   4139 	case AF_INET6:
   4140 		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY &&
   4141 		    spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
   4142 			return 0;
   4143 		/*
   4144 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4145 		 * as a wildcard scope, which matches any scope zone ID.
   4146 		 */
   4147 		if (spidx0->src.sin6.sin6_scope_id &&
   4148 		    spidx1->src.sin6.sin6_scope_id &&
   4149 		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
   4150 			return 0;
   4151 		if (!key_bb_match_withmask(&spidx0->dst.sin6.sin6_addr,
   4152 		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
   4153 			return 0;
   4154 		break;
   4155 	default:
   4156 		/* XXX */
   4157 		if (memcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
   4158 			return 0;
   4159 		break;
   4160 	}
   4161 
   4162 	/* XXX Do we check other field ?  e.g. flowinfo */
   4163 
   4164 	return 1;
   4165 }
   4166 
   4167 /* returns 0 on match */
   4168 static int
   4169 key_portcomp(in_port_t port1, in_port_t port2, int howport)
   4170 {
   4171 	switch (howport) {
   4172 	case PORT_NONE:
   4173 		return 0;
   4174 	case PORT_LOOSE:
   4175 		if (port1 == 0 || port2 == 0)
   4176 			return 0;
   4177 		/*FALLTHROUGH*/
   4178 	case PORT_STRICT:
   4179 		if (port1 != port2) {
   4180 			KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4181 			    "port fail %d != %d\n", port1, port2);
   4182 			return 1;
   4183 		}
   4184 		return 0;
   4185 	default:
   4186 		KASSERT(0);
   4187 		return 1;
   4188 	}
   4189 }
   4190 
   4191 /* returns 1 on match */
   4192 static int
   4193 key_sockaddr_match(
   4194 	const struct sockaddr *sa1,
   4195 	const struct sockaddr *sa2,
   4196 	int howport)
   4197 {
   4198 	const struct sockaddr_in *sin1, *sin2;
   4199 	const struct sockaddr_in6 *sin61, *sin62;
   4200 
   4201 	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len) {
   4202 		KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4203 		    "fam/len fail %d != %d || %d != %d\n",
   4204 			sa1->sa_family, sa2->sa_family, sa1->sa_len,
   4205 			sa2->sa_len);
   4206 		return 0;
   4207 	}
   4208 
   4209 	switch (sa1->sa_family) {
   4210 	case AF_INET:
   4211 		if (sa1->sa_len != sizeof(struct sockaddr_in)) {
   4212 			KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4213 			    "len fail %d != %zu\n",
   4214 			    sa1->sa_len, sizeof(struct sockaddr_in));
   4215 			return 0;
   4216 		}
   4217 		sin1 = (const struct sockaddr_in *)sa1;
   4218 		sin2 = (const struct sockaddr_in *)sa2;
   4219 		if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr) {
   4220 			KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4221 			    "addr fail %#x != %#x\n",
   4222 			    sin1->sin_addr.s_addr, sin2->sin_addr.s_addr);
   4223 			return 0;
   4224 		}
   4225 		if (key_portcomp(sin1->sin_port, sin2->sin_port, howport)) {
   4226 			return 0;
   4227 		}
   4228 		KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4229 		    "addr success %#x[%d] == %#x[%d]\n",
   4230 		    sin1->sin_addr.s_addr, sin1->sin_port,
   4231 		    sin2->sin_addr.s_addr, sin2->sin_port);
   4232 		break;
   4233 	case AF_INET6:
   4234 		sin61 = (const struct sockaddr_in6 *)sa1;
   4235 		sin62 = (const struct sockaddr_in6 *)sa2;
   4236 		if (sa1->sa_len != sizeof(struct sockaddr_in6))
   4237 			return 0;	/*EINVAL*/
   4238 
   4239 		if (sin61->sin6_scope_id != sin62->sin6_scope_id) {
   4240 			return 0;
   4241 		}
   4242 		if (!IN6_ARE_ADDR_EQUAL(&sin61->sin6_addr, &sin62->sin6_addr)) {
   4243 			return 0;
   4244 		}
   4245 		if (key_portcomp(sin61->sin6_port, sin62->sin6_port, howport)) {
   4246 			return 0;
   4247 		}
   4248 		break;
   4249 	default:
   4250 		if (memcmp(sa1, sa2, sa1->sa_len) != 0)
   4251 			return 0;
   4252 		break;
   4253 	}
   4254 
   4255 	return 1;
   4256 }
   4257 
   4258 /*
   4259  * compare two buffers with mask.
   4260  * IN:
   4261  *	addr1: source
   4262  *	addr2: object
   4263  *	bits:  Number of bits to compare
   4264  * OUT:
   4265  *	1 : equal
   4266  *	0 : not equal
   4267  */
   4268 static int
   4269 key_bb_match_withmask(const void *a1, const void *a2, u_int bits)
   4270 {
   4271 	const unsigned char *p1 = a1;
   4272 	const unsigned char *p2 = a2;
   4273 
   4274 	/* XXX: This could be considerably faster if we compare a word
   4275 	 * at a time, but it is complicated on LSB Endian machines */
   4276 
   4277 	/* Handle null pointers */
   4278 	if (p1 == NULL || p2 == NULL)
   4279 		return (p1 == p2);
   4280 
   4281 	while (bits >= 8) {
   4282 		if (*p1++ != *p2++)
   4283 			return 0;
   4284 		bits -= 8;
   4285 	}
   4286 
   4287 	if (bits > 0) {
   4288 		u_int8_t mask = ~((1<<(8-bits))-1);
   4289 		if ((*p1 & mask) != (*p2 & mask))
   4290 			return 0;
   4291 	}
   4292 	return 1;	/* Match! */
   4293 }
   4294 
   4295 static void
   4296 key_timehandler_spd(time_t now)
   4297 {
   4298 	u_int dir;
   4299 	struct secpolicy *sp, *nextsp;
   4300 
   4301 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   4302 		LIST_FOREACH_SAFE(sp, &sptree[dir], chain, nextsp) {
   4303 			if (sp->state == IPSEC_SPSTATE_DEAD) {
   4304 				key_sp_unlink(sp);	/*XXX*/
   4305 
   4306 				/* 'sp' dead; continue transfers to
   4307 				 * 'sp = nextsp'
   4308 				 */
   4309 				continue;
   4310 			}
   4311 
   4312 			if (sp->lifetime == 0 && sp->validtime == 0)
   4313 				continue;
   4314 
   4315 			/* the deletion will occur next time */
   4316 			if ((sp->lifetime && now - sp->created > sp->lifetime) ||
   4317 			    (sp->validtime && now - sp->lastused > sp->validtime)) {
   4318 			  	key_sp_dead(sp);
   4319 				key_spdexpire(sp);
   4320 				continue;
   4321 			}
   4322 		}
   4323 	}
   4324 }
   4325 
   4326 static void
   4327 key_timehandler_sad(time_t now)
   4328 {
   4329 	struct secashead *sah, *nextsah;
   4330 	struct secasvar *sav, *nextsav;
   4331 
   4332 	LIST_FOREACH_SAFE(sah, &sahtree, chain, nextsah) {
   4333 		/* if sah has been dead, then delete it and process next sah. */
   4334 		if (sah->state == SADB_SASTATE_DEAD) {
   4335 			key_delsah(sah);
   4336 			continue;
   4337 		}
   4338 
   4339 		/* if LARVAL entry doesn't become MATURE, delete it. */
   4340 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL],
   4341 		    chain, nextsav) {
   4342 			if (now - sav->created > key_larval_lifetime) {
   4343 				KEY_FREESAV(&sav);
   4344 			}
   4345 		}
   4346 
   4347 		/*
   4348 		 * check MATURE entry to start to send expire message
   4349 		 * whether or not.
   4350 		 */
   4351 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE],
   4352 		    chain, nextsav) {
   4353 			/* we don't need to check. */
   4354 			if (sav->lft_s == NULL)
   4355 				continue;
   4356 
   4357 			/* sanity check */
   4358 			KASSERT(sav->lft_c != NULL);
   4359 
   4360 			/* check SOFT lifetime */
   4361 			if (sav->lft_s->sadb_lifetime_addtime != 0 &&
   4362 			    now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4363 				/*
   4364 				 * check SA to be used whether or not.
   4365 				 * when SA hasn't been used, delete it.
   4366 				 */
   4367 				if (sav->lft_c->sadb_lifetime_usetime == 0) {
   4368 					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4369 					KEY_FREESAV(&sav);
   4370 				} else {
   4371 					key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4372 					/*
   4373 					 * XXX If we keep to send expire
   4374 					 * message in the status of
   4375 					 * DYING. Do remove below code.
   4376 					 */
   4377 					key_expire(sav);
   4378 				}
   4379 			}
   4380 			/* check SOFT lifetime by bytes */
   4381 			/*
   4382 			 * XXX I don't know the way to delete this SA
   4383 			 * when new SA is installed.  Caution when it's
   4384 			 * installed too big lifetime by time.
   4385 			 */
   4386 			else if (sav->lft_s->sadb_lifetime_bytes != 0 &&
   4387 			         sav->lft_s->sadb_lifetime_bytes <
   4388 			         sav->lft_c->sadb_lifetime_bytes) {
   4389 
   4390 				key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4391 				/*
   4392 				 * XXX If we keep to send expire
   4393 				 * message in the status of
   4394 				 * DYING. Do remove below code.
   4395 				 */
   4396 				key_expire(sav);
   4397 			}
   4398 		}
   4399 
   4400 		/* check DYING entry to change status to DEAD. */
   4401 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING],
   4402 		    chain, nextsav) {
   4403 			/* we don't need to check. */
   4404 			if (sav->lft_h == NULL)
   4405 				continue;
   4406 
   4407 			/* sanity check */
   4408 			KASSERT(sav->lft_c != NULL);
   4409 
   4410 			if (sav->lft_h->sadb_lifetime_addtime != 0 &&
   4411 			    now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
   4412 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4413 				KEY_FREESAV(&sav);
   4414 			}
   4415 #if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
   4416 			else if (sav->lft_s != NULL
   4417 			      && sav->lft_s->sadb_lifetime_addtime != 0
   4418 			      && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4419 				/*
   4420 				 * XXX: should be checked to be
   4421 				 * installed the valid SA.
   4422 				 */
   4423 
   4424 				/*
   4425 				 * If there is no SA then sending
   4426 				 * expire message.
   4427 				 */
   4428 				key_expire(sav);
   4429 			}
   4430 #endif
   4431 			/* check HARD lifetime by bytes */
   4432 			else if (sav->lft_h->sadb_lifetime_bytes != 0 &&
   4433 			         sav->lft_h->sadb_lifetime_bytes <
   4434 			         sav->lft_c->sadb_lifetime_bytes) {
   4435 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4436 				KEY_FREESAV(&sav);
   4437 			}
   4438 		}
   4439 
   4440 		/* delete entry in DEAD */
   4441 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD],
   4442 		    chain, nextsav) {
   4443 			/* sanity check */
   4444 			if (sav->state != SADB_SASTATE_DEAD) {
   4445 				IPSECLOG(LOG_DEBUG,
   4446 				    "invalid sav->state (queue: %d SA: %d): "
   4447 				    "kill it anyway\n",
   4448 				    SADB_SASTATE_DEAD, sav->state);
   4449 			}
   4450 
   4451 			/*
   4452 			 * do not call key_freesav() here.
   4453 			 * sav should already be freed, and sav->refcnt
   4454 			 * shows other references to sav
   4455 			 * (such as from SPD).
   4456 			 */
   4457 		}
   4458 	}
   4459 }
   4460 
   4461 static void
   4462 key_timehandler_acq(time_t now)
   4463 {
   4464 #ifndef IPSEC_NONBLOCK_ACQUIRE
   4465 	struct secacq *acq, *nextacq;
   4466 
   4467     restart:
   4468 	mutex_enter(&key_mtx);
   4469 	LIST_FOREACH_SAFE(acq, &acqtree, chain, nextacq) {
   4470 		if (now - acq->created > key_blockacq_lifetime) {
   4471 			LIST_REMOVE(acq, chain);
   4472 			mutex_exit(&key_mtx);
   4473 			kmem_free(acq, sizeof(*acq));
   4474 			goto restart;
   4475 		}
   4476 	}
   4477 	mutex_exit(&key_mtx);
   4478 #endif
   4479 }
   4480 
   4481 static void
   4482 key_timehandler_spacq(time_t now)
   4483 {
   4484 #ifdef notyet
   4485 	struct secspacq *acq, *nextacq;
   4486 
   4487 	LIST_FOREACH_SAFE(acq, &spacqtree, chain, nextacq) {
   4488 		if (now - acq->created > key_blockacq_lifetime) {
   4489 			KASSERT(__LIST_CHAINED(acq));
   4490 			LIST_REMOVE(acq, chain);
   4491 			kmem_free(acq, sizeof(*acq));
   4492 		}
   4493 	}
   4494 #endif
   4495 }
   4496 
   4497 /*
   4498  * time handler.
   4499  * scanning SPD and SAD to check status for each entries,
   4500  * and do to remove or to expire.
   4501  */
   4502 static void
   4503 key_timehandler_work(struct work *wk, void *arg)
   4504 {
   4505 	int s;
   4506 	time_t now = time_uptime;
   4507 
   4508 	s = splsoftnet();
   4509 	mutex_enter(softnet_lock);
   4510 
   4511 	key_timehandler_spd(now);
   4512 	key_timehandler_sad(now);
   4513 	key_timehandler_acq(now);
   4514 	key_timehandler_spacq(now);
   4515 
   4516 	/* do exchange to tick time !! */
   4517 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   4518 
   4519 	mutex_exit(softnet_lock);
   4520 	splx(s);
   4521 	return;
   4522 }
   4523 
   4524 static void
   4525 key_timehandler(void *arg)
   4526 {
   4527 
   4528 	workqueue_enqueue(key_timehandler_wq, &key_timehandler_wk, NULL);
   4529 }
   4530 
   4531 u_long
   4532 key_random(void)
   4533 {
   4534 	u_long value;
   4535 
   4536 	key_randomfill(&value, sizeof(value));
   4537 	return value;
   4538 }
   4539 
   4540 void
   4541 key_randomfill(void *p, size_t l)
   4542 {
   4543 
   4544 	cprng_fast(p, l);
   4545 }
   4546 
   4547 /*
   4548  * map SADB_SATYPE_* to IPPROTO_*.
   4549  * if satype == SADB_SATYPE then satype is mapped to ~0.
   4550  * OUT:
   4551  *	0: invalid satype.
   4552  */
   4553 static u_int16_t
   4554 key_satype2proto(u_int8_t satype)
   4555 {
   4556 	switch (satype) {
   4557 	case SADB_SATYPE_UNSPEC:
   4558 		return IPSEC_PROTO_ANY;
   4559 	case SADB_SATYPE_AH:
   4560 		return IPPROTO_AH;
   4561 	case SADB_SATYPE_ESP:
   4562 		return IPPROTO_ESP;
   4563 	case SADB_X_SATYPE_IPCOMP:
   4564 		return IPPROTO_IPCOMP;
   4565 	case SADB_X_SATYPE_TCPSIGNATURE:
   4566 		return IPPROTO_TCP;
   4567 	default:
   4568 		return 0;
   4569 	}
   4570 	/* NOTREACHED */
   4571 }
   4572 
   4573 /*
   4574  * map IPPROTO_* to SADB_SATYPE_*
   4575  * OUT:
   4576  *	0: invalid protocol type.
   4577  */
   4578 static u_int8_t
   4579 key_proto2satype(u_int16_t proto)
   4580 {
   4581 	switch (proto) {
   4582 	case IPPROTO_AH:
   4583 		return SADB_SATYPE_AH;
   4584 	case IPPROTO_ESP:
   4585 		return SADB_SATYPE_ESP;
   4586 	case IPPROTO_IPCOMP:
   4587 		return SADB_X_SATYPE_IPCOMP;
   4588 	case IPPROTO_TCP:
   4589 		return SADB_X_SATYPE_TCPSIGNATURE;
   4590 	default:
   4591 		return 0;
   4592 	}
   4593 	/* NOTREACHED */
   4594 }
   4595 
   4596 static int
   4597 key_setsecasidx(int proto, int mode, int reqid,
   4598     const struct sockaddr *src, const struct sockaddr *dst,
   4599     struct secasindex * saidx)
   4600 {
   4601 	const union sockaddr_union *src_u = (const union sockaddr_union *)src;
   4602 	const union sockaddr_union *dst_u = (const union sockaddr_union *)dst;
   4603 
   4604 	/* sa len safety check */
   4605 	if (key_checksalen(src_u) != 0)
   4606 		return -1;
   4607 	if (key_checksalen(dst_u) != 0)
   4608 		return -1;
   4609 
   4610 	memset(saidx, 0, sizeof(*saidx));
   4611 	saidx->proto = proto;
   4612 	saidx->mode = mode;
   4613 	saidx->reqid = reqid;
   4614 	memcpy(&saidx->src, src_u, src_u->sa.sa_len);
   4615 	memcpy(&saidx->dst, dst_u, dst_u->sa.sa_len);
   4616 
   4617 	key_porttosaddr(&((saidx)->src), 0);
   4618 	key_porttosaddr(&((saidx)->dst), 0);
   4619 	return 0;
   4620 }
   4621 
   4622 static void
   4623 key_init_spidx_bymsghdr(struct secpolicyindex *spidx,
   4624     const struct sadb_msghdr *mhp)
   4625 {
   4626 	const struct sadb_address *src0, *dst0;
   4627 	const struct sockaddr *src, *dst;
   4628 	const struct sadb_x_policy *xpl0;
   4629 
   4630 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   4631 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   4632 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   4633 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   4634 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
   4635 
   4636 	memset(spidx, 0, sizeof(*spidx));
   4637 	spidx->dir = xpl0->sadb_x_policy_dir;
   4638 	spidx->prefs = src0->sadb_address_prefixlen;
   4639 	spidx->prefd = dst0->sadb_address_prefixlen;
   4640 	spidx->ul_proto = src0->sadb_address_proto;
   4641 	/* XXX boundary check against sa_len */
   4642 	memcpy(&spidx->src, src, src->sa_len);
   4643 	memcpy(&spidx->dst, dst, dst->sa_len);
   4644 }
   4645 
   4646 /* %%% PF_KEY */
   4647 /*
   4648  * SADB_GETSPI processing is to receive
   4649  *	<base, (SA2), src address, dst address, (SPI range)>
   4650  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
   4651  * tree with the status of LARVAL, and send
   4652  *	<base, SA(*), address(SD)>
   4653  * to the IKMPd.
   4654  *
   4655  * IN:	mhp: pointer to the pointer to each header.
   4656  * OUT:	NULL if fail.
   4657  *	other if success, return pointer to the message to send.
   4658  */
   4659 static int
   4660 key_api_getspi(struct socket *so, struct mbuf *m,
   4661 	   const struct sadb_msghdr *mhp)
   4662 {
   4663 	const struct sockaddr *src, *dst;
   4664 	struct secasindex saidx;
   4665 	struct secashead *newsah;
   4666 	struct secasvar *newsav;
   4667 	u_int8_t proto;
   4668 	u_int32_t spi;
   4669 	u_int8_t mode;
   4670 	u_int16_t reqid;
   4671 	int error;
   4672 
   4673 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   4674 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   4675 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   4676 		return key_senderror(so, m, EINVAL);
   4677 	}
   4678 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   4679 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   4680 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   4681 		return key_senderror(so, m, EINVAL);
   4682 	}
   4683 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   4684 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   4685 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   4686 	} else {
   4687 		mode = IPSEC_MODE_ANY;
   4688 		reqid = 0;
   4689 	}
   4690 
   4691 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   4692 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   4693 
   4694 	/* map satype to proto */
   4695 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   4696 	if (proto == 0) {
   4697 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   4698 		return key_senderror(so, m, EINVAL);
   4699 	}
   4700 
   4701 
   4702 	error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
   4703 	if (error != 0)
   4704 		return key_senderror(so, m, EINVAL);
   4705 
   4706 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   4707 	if (error != 0)
   4708 		return key_senderror(so, m, EINVAL);
   4709 
   4710 	/* SPI allocation */
   4711 	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
   4712 	    &saidx);
   4713 	if (spi == 0)
   4714 		return key_senderror(so, m, EINVAL);
   4715 
   4716 	/* get a SA index */
   4717 	newsah = key_getsah(&saidx, CMP_REQID);
   4718 	if (newsah == NULL) {
   4719 		/* create a new SA index */
   4720 		newsah = key_newsah(&saidx);
   4721 		if (newsah == NULL) {
   4722 			IPSECLOG(LOG_DEBUG, "No more memory.\n");
   4723 			return key_senderror(so, m, ENOBUFS);
   4724 		}
   4725 	}
   4726 
   4727 	/* get a new SA */
   4728 	/* XXX rewrite */
   4729 	newsav = KEY_NEWSAV(m, mhp, &error);
   4730 	if (newsav == NULL) {
   4731 		/* XXX don't free new SA index allocated in above. */
   4732 		return key_senderror(so, m, error);
   4733 	}
   4734 
   4735 	/* set spi */
   4736 	newsav->spi = htonl(spi);
   4737 
   4738 	/* add to satree */
   4739 	newsav->refcnt = 1;
   4740 	newsav->sah = newsah;
   4741 	newsav->state = SADB_SASTATE_LARVAL;
   4742 	LIST_INSERT_TAIL(&newsah->savtree[SADB_SASTATE_LARVAL], newsav,
   4743 	    secasvar, chain);
   4744 	key_validate_savlist(newsah, SADB_SASTATE_LARVAL);
   4745 
   4746 #ifndef IPSEC_NONBLOCK_ACQUIRE
   4747 	/* delete the entry in acqtree */
   4748 	if (mhp->msg->sadb_msg_seq != 0) {
   4749 		struct secacq *acq;
   4750 		mutex_enter(&key_mtx);
   4751 		acq = key_getacqbyseq(mhp->msg->sadb_msg_seq);
   4752 		if (acq != NULL) {
   4753 			/* reset counter in order to deletion by timehandler. */
   4754 			acq->created = time_uptime;
   4755 			acq->count = 0;
   4756 		}
   4757 		mutex_exit(&key_mtx);
   4758 	}
   4759 #endif
   4760 
   4761     {
   4762 	struct mbuf *n, *nn;
   4763 	struct sadb_sa *m_sa;
   4764 	int off, len;
   4765 
   4766 	CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
   4767 	    PFKEY_ALIGN8(sizeof(struct sadb_sa)) <= MCLBYTES);
   4768 
   4769 	/* create new sadb_msg to reply. */
   4770 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
   4771 	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
   4772 
   4773 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   4774 	if (len > MHLEN) {
   4775 		MCLGET(n, M_DONTWAIT);
   4776 		if ((n->m_flags & M_EXT) == 0) {
   4777 			m_freem(n);
   4778 			n = NULL;
   4779 		}
   4780 	}
   4781 	if (!n)
   4782 		return key_senderror(so, m, ENOBUFS);
   4783 
   4784 	n->m_len = len;
   4785 	n->m_next = NULL;
   4786 	off = 0;
   4787 
   4788 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   4789 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   4790 
   4791 	m_sa = (struct sadb_sa *)(mtod(n, char *) + off);
   4792 	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
   4793 	m_sa->sadb_sa_exttype = SADB_EXT_SA;
   4794 	m_sa->sadb_sa_spi = htonl(spi);
   4795 	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
   4796 
   4797 	KASSERTMSG(off == len, "length inconsistency");
   4798 
   4799 	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
   4800 	    SADB_EXT_ADDRESS_DST);
   4801 	if (!n->m_next) {
   4802 		m_freem(n);
   4803 		return key_senderror(so, m, ENOBUFS);
   4804 	}
   4805 
   4806 	if (n->m_len < sizeof(struct sadb_msg)) {
   4807 		n = m_pullup(n, sizeof(struct sadb_msg));
   4808 		if (n == NULL)
   4809 			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   4810 	}
   4811 
   4812 	n->m_pkthdr.len = 0;
   4813 	for (nn = n; nn; nn = nn->m_next)
   4814 		n->m_pkthdr.len += nn->m_len;
   4815 
   4816 	key_fill_replymsg(n, newsav->seq);
   4817 
   4818 	m_freem(m);
   4819 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   4820     }
   4821 }
   4822 
   4823 /*
   4824  * allocating new SPI
   4825  * called by key_api_getspi().
   4826  * OUT:
   4827  *	0:	failure.
   4828  *	others: success.
   4829  */
   4830 static u_int32_t
   4831 key_do_getnewspi(const struct sadb_spirange *spirange,
   4832 		 const struct secasindex *saidx)
   4833 {
   4834 	u_int32_t newspi;
   4835 	u_int32_t spmin, spmax;
   4836 	int count = key_spi_trycnt;
   4837 
   4838 	/* set spi range to allocate */
   4839 	if (spirange != NULL) {
   4840 		spmin = spirange->sadb_spirange_min;
   4841 		spmax = spirange->sadb_spirange_max;
   4842 	} else {
   4843 		spmin = key_spi_minval;
   4844 		spmax = key_spi_maxval;
   4845 	}
   4846 	/* IPCOMP needs 2-byte SPI */
   4847 	if (saidx->proto == IPPROTO_IPCOMP) {
   4848 		u_int32_t t;
   4849 		if (spmin >= 0x10000)
   4850 			spmin = 0xffff;
   4851 		if (spmax >= 0x10000)
   4852 			spmax = 0xffff;
   4853 		if (spmin > spmax) {
   4854 			t = spmin; spmin = spmax; spmax = t;
   4855 		}
   4856 	}
   4857 
   4858 	if (spmin == spmax) {
   4859 		if (key_checkspidup(saidx, htonl(spmin))) {
   4860 			IPSECLOG(LOG_DEBUG, "SPI %u exists already.\n", spmin);
   4861 			return 0;
   4862 		}
   4863 
   4864 		count--; /* taking one cost. */
   4865 		newspi = spmin;
   4866 
   4867 	} else {
   4868 
   4869 		/* init SPI */
   4870 		newspi = 0;
   4871 
   4872 		/* when requesting to allocate spi ranged */
   4873 		while (count--) {
   4874 			/* generate pseudo-random SPI value ranged. */
   4875 			newspi = spmin + (key_random() % (spmax - spmin + 1));
   4876 
   4877 			if (!key_checkspidup(saidx, htonl(newspi)))
   4878 				break;
   4879 		}
   4880 
   4881 		if (count == 0 || newspi == 0) {
   4882 			IPSECLOG(LOG_DEBUG, "to allocate spi is failed.\n");
   4883 			return 0;
   4884 		}
   4885 	}
   4886 
   4887 	/* statistics */
   4888 	keystat.getspi_count =
   4889 	    (keystat.getspi_count + key_spi_trycnt - count) / 2;
   4890 
   4891 	return newspi;
   4892 }
   4893 
   4894 static int
   4895 key_handle_natt_info(struct secasvar *sav,
   4896       		     const struct sadb_msghdr *mhp)
   4897 {
   4898 	const char *msg = "?" ;
   4899 	struct sadb_x_nat_t_type *type;
   4900 	struct sadb_x_nat_t_port *sport, *dport;
   4901 	struct sadb_address *iaddr, *raddr;
   4902 	struct sadb_x_nat_t_frag *frag;
   4903 
   4904 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] == NULL ||
   4905 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] == NULL ||
   4906 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] == NULL)
   4907 		return 0;
   4908 
   4909 	if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) {
   4910 		msg = "TYPE";
   4911 		goto bad;
   4912 	}
   4913 
   4914 	if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) {
   4915 		msg = "SPORT";
   4916 		goto bad;
   4917 	}
   4918 
   4919 	if (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
   4920 		msg = "DPORT";
   4921 		goto bad;
   4922 	}
   4923 
   4924 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) {
   4925 		IPSECLOG(LOG_DEBUG, "NAT-T OAi present\n");
   4926 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr)) {
   4927 			msg = "OAI";
   4928 			goto bad;
   4929 		}
   4930 	}
   4931 
   4932 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
   4933 		IPSECLOG(LOG_DEBUG, "NAT-T OAr present\n");
   4934 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
   4935 			msg = "OAR";
   4936 			goto bad;
   4937 		}
   4938 	}
   4939 
   4940 	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
   4941 	    if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
   4942 		    msg = "FRAG";
   4943 		    goto bad;
   4944 	    }
   4945 	}
   4946 
   4947 	type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   4948 	sport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   4949 	dport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   4950 	iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
   4951 	raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
   4952 	frag = (struct sadb_x_nat_t_frag *)mhp->ext[SADB_X_EXT_NAT_T_FRAG];
   4953 
   4954 	IPSECLOG(LOG_DEBUG, "type %d, sport = %d, dport = %d\n",
   4955 	    type->sadb_x_nat_t_type_type,
   4956 	    ntohs(sport->sadb_x_nat_t_port_port),
   4957 	    ntohs(dport->sadb_x_nat_t_port_port));
   4958 
   4959 	sav->natt_type = type->sadb_x_nat_t_type_type;
   4960 	key_porttosaddr(&sav->sah->saidx.src, sport->sadb_x_nat_t_port_port);
   4961 	key_porttosaddr(&sav->sah->saidx.dst, dport->sadb_x_nat_t_port_port);
   4962 	if (frag)
   4963 		sav->esp_frag = frag->sadb_x_nat_t_frag_fraglen;
   4964 	else
   4965 		sav->esp_frag = IP_MAXPACKET;
   4966 
   4967 	return 0;
   4968 bad:
   4969 	IPSECLOG(LOG_DEBUG, "invalid message %s\n", msg);
   4970 	__USE(msg);
   4971 	return -1;
   4972 }
   4973 
   4974 /* Just update the IPSEC_NAT_T ports if present */
   4975 static int
   4976 key_set_natt_ports(union sockaddr_union *src, union sockaddr_union *dst,
   4977       		     const struct sadb_msghdr *mhp)
   4978 {
   4979 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
   4980 		IPSECLOG(LOG_DEBUG, "NAT-T OAi present\n");
   4981 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
   4982 		IPSECLOG(LOG_DEBUG, "NAT-T OAr present\n");
   4983 
   4984 	if ((mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL) &&
   4985 	    (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL) &&
   4986 	    (mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL)) {
   4987 		struct sadb_x_nat_t_type *type;
   4988 		struct sadb_x_nat_t_port *sport;
   4989 		struct sadb_x_nat_t_port *dport;
   4990 
   4991 		if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
   4992 		    (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
   4993 		    (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
   4994 			IPSECLOG(LOG_DEBUG, "invalid message\n");
   4995 			return -1;
   4996 		}
   4997 
   4998 		type = (struct sadb_x_nat_t_type *)
   4999 		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   5000 		sport = (struct sadb_x_nat_t_port *)
   5001 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   5002 		dport = (struct sadb_x_nat_t_port *)
   5003 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   5004 
   5005 		key_porttosaddr(src, sport->sadb_x_nat_t_port_port);
   5006 		key_porttosaddr(dst, dport->sadb_x_nat_t_port_port);
   5007 
   5008 		IPSECLOG(LOG_DEBUG, "type %d, sport = %d, dport = %d\n",
   5009 		    type->sadb_x_nat_t_type_type,
   5010 		    ntohs(sport->sadb_x_nat_t_port_port),
   5011 		    ntohs(dport->sadb_x_nat_t_port_port));
   5012 	}
   5013 
   5014 	return 0;
   5015 }
   5016 
   5017 
   5018 /*
   5019  * SADB_UPDATE processing
   5020  * receive
   5021  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5022  *       key(AE), (identity(SD),) (sensitivity)>
   5023  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
   5024  * and send
   5025  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5026  *       (identity(SD),) (sensitivity)>
   5027  * to the ikmpd.
   5028  *
   5029  * m will always be freed.
   5030  */
   5031 static int
   5032 key_api_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
   5033 {
   5034 	struct sadb_sa *sa0;
   5035 	const struct sockaddr *src, *dst;
   5036 	struct secasindex saidx;
   5037 	struct secashead *sah;
   5038 	struct secasvar *sav, *newsav;
   5039 	u_int16_t proto;
   5040 	u_int8_t mode;
   5041 	u_int16_t reqid;
   5042 	int error;
   5043 
   5044 	/* map satype to proto */
   5045 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   5046 	if (proto == 0) {
   5047 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5048 		return key_senderror(so, m, EINVAL);
   5049 	}
   5050 
   5051 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5052 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5053 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5054 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5055 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5056 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5057 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5058 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5059 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5060 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5061 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5062 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5063 		return key_senderror(so, m, EINVAL);
   5064 	}
   5065 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5066 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5067 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5068 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5069 		return key_senderror(so, m, EINVAL);
   5070 	}
   5071 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5072 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5073 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5074 	} else {
   5075 		mode = IPSEC_MODE_ANY;
   5076 		reqid = 0;
   5077 	}
   5078 	/* XXX boundary checking for other extensions */
   5079 
   5080 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5081 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5082 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5083 
   5084 	error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
   5085 	if (error != 0)
   5086 		return key_senderror(so, m, EINVAL);
   5087 
   5088 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5089 	if (error != 0)
   5090 		return key_senderror(so, m, EINVAL);
   5091 
   5092 	/* get a SA header */
   5093 	sah = key_getsah(&saidx, CMP_REQID);
   5094 	if (sah == NULL) {
   5095 		IPSECLOG(LOG_DEBUG, "no SA index found.\n");
   5096 		return key_senderror(so, m, ENOENT);
   5097 	}
   5098 
   5099 	/* set spidx if there */
   5100 	/* XXX rewrite */
   5101 	error = key_setident(sah, m, mhp);
   5102 	if (error)
   5103 		return key_senderror(so, m, error);
   5104 
   5105 	/* find a SA with sequence number. */
   5106 #ifdef IPSEC_DOSEQCHECK
   5107 	if (mhp->msg->sadb_msg_seq != 0) {
   5108 		sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq);
   5109 		if (sav == NULL) {
   5110 			IPSECLOG(LOG_DEBUG,
   5111 			    "no larval SA with sequence %u exists.\n",
   5112 			    mhp->msg->sadb_msg_seq);
   5113 			return key_senderror(so, m, ENOENT);
   5114 		}
   5115 	}
   5116 #else
   5117 	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5118 	if (sav == NULL) {
   5119 		IPSECLOG(LOG_DEBUG, "no such a SA found (spi:%u)\n",
   5120 		    (u_int32_t)ntohl(sa0->sadb_sa_spi));
   5121 		return key_senderror(so, m, EINVAL);
   5122 	}
   5123 #endif
   5124 
   5125 	/* validity check */
   5126 	if (sav->sah->saidx.proto != proto) {
   5127 		IPSECLOG(LOG_DEBUG, "protocol mismatched (DB=%u param=%u)\n",
   5128 		    sav->sah->saidx.proto, proto);
   5129 		error = EINVAL;
   5130 		goto error;
   5131 	}
   5132 #ifdef IPSEC_DOSEQCHECK
   5133 	if (sav->spi != sa0->sadb_sa_spi) {
   5134 		IPSECLOG(LOG_DEBUG, "SPI mismatched (DB:%u param:%u)\n",
   5135 		    (u_int32_t)ntohl(sav->spi),
   5136 		    (u_int32_t)ntohl(sa0->sadb_sa_spi));
   5137 		error = EINVAL;
   5138 		goto error;
   5139 	}
   5140 #endif
   5141 	if (sav->pid != mhp->msg->sadb_msg_pid) {
   5142 		IPSECLOG(LOG_DEBUG, "pid mismatched (DB:%u param:%u)\n",
   5143 		    sav->pid, mhp->msg->sadb_msg_pid);
   5144 		error = EINVAL;
   5145 		goto error;
   5146 	}
   5147 
   5148 	/*
   5149 	 * Allocate a new SA instead of modifying the existing SA directly
   5150 	 * to avoid race conditions.
   5151 	 */
   5152 	newsav = kmem_zalloc(sizeof(struct secasvar), KM_SLEEP);
   5153 
   5154 	/* copy sav values */
   5155 	newsav->spi = sav->spi;
   5156 	newsav->seq = sav->seq;
   5157 	newsav->created = sav->created;
   5158 	newsav->pid = sav->pid;
   5159 	newsav->sah = sav->sah;
   5160 
   5161 	error = key_setsaval(newsav, m, mhp);
   5162 	if (error) {
   5163 		key_delsav(newsav);
   5164 		goto error;
   5165 	}
   5166 
   5167 	error = key_handle_natt_info(newsav, mhp);
   5168 	if (error != 0) {
   5169 		key_delsav(newsav);
   5170 		goto error;
   5171 	}
   5172 
   5173 	error = key_init_xform(newsav);
   5174 	if (error != 0) {
   5175 		key_delsav(newsav);
   5176 		goto error;
   5177 	}
   5178 
   5179 	/* add to satree */
   5180 	newsav->refcnt = 1;
   5181 	newsav->state = SADB_SASTATE_MATURE;
   5182 	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_MATURE], newsav,
   5183 	    secasvar, chain);
   5184 	key_validate_savlist(sah, SADB_SASTATE_MATURE);
   5185 
   5186 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5187 	KEY_FREESAV(&sav);
   5188 	KEY_FREESAV(&sav);
   5189 
   5190     {
   5191 	struct mbuf *n;
   5192 
   5193 	/* set msg buf from mhp */
   5194 	n = key_getmsgbuf_x1(m, mhp);
   5195 	if (n == NULL) {
   5196 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   5197 		return key_senderror(so, m, ENOBUFS);
   5198 	}
   5199 
   5200 	m_freem(m);
   5201 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5202     }
   5203 error:
   5204 	KEY_FREESAV(&sav);
   5205 	return key_senderror(so, m, error);
   5206 }
   5207 
   5208 /*
   5209  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
   5210  * only called by key_api_update().
   5211  * OUT:
   5212  *	NULL	: not found
   5213  *	others	: found, pointer to a SA.
   5214  */
   5215 #ifdef IPSEC_DOSEQCHECK
   5216 static struct secasvar *
   5217 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
   5218 {
   5219 	struct secasvar *sav;
   5220 	u_int state;
   5221 
   5222 	state = SADB_SASTATE_LARVAL;
   5223 
   5224 	/* search SAD with sequence number ? */
   5225 	LIST_FOREACH(sav, &sah->savtree[state], chain) {
   5226 
   5227 		KEY_CHKSASTATE(state, sav->state);
   5228 
   5229 		if (sav->seq == seq) {
   5230 			SA_ADDREF(sav);
   5231 			KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   5232 			    "DP cause refcnt++:%d SA:%p\n",
   5233 			    sav->refcnt, sav);
   5234 			return sav;
   5235 		}
   5236 	}
   5237 
   5238 	return NULL;
   5239 }
   5240 #endif
   5241 
   5242 /*
   5243  * SADB_ADD processing
   5244  * add an entry to SA database, when received
   5245  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5246  *       key(AE), (identity(SD),) (sensitivity)>
   5247  * from the ikmpd,
   5248  * and send
   5249  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5250  *       (identity(SD),) (sensitivity)>
   5251  * to the ikmpd.
   5252  *
   5253  * IGNORE identity and sensitivity messages.
   5254  *
   5255  * m will always be freed.
   5256  */
   5257 static int
   5258 key_api_add(struct socket *so, struct mbuf *m,
   5259 	const struct sadb_msghdr *mhp)
   5260 {
   5261 	struct sadb_sa *sa0;
   5262 	const struct sockaddr *src, *dst;
   5263 	struct secasindex saidx;
   5264 	struct secashead *newsah;
   5265 	struct secasvar *newsav;
   5266 	u_int16_t proto;
   5267 	u_int8_t mode;
   5268 	u_int16_t reqid;
   5269 	int error;
   5270 
   5271 	/* map satype to proto */
   5272 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   5273 	if (proto == 0) {
   5274 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5275 		return key_senderror(so, m, EINVAL);
   5276 	}
   5277 
   5278 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5279 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5280 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5281 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5282 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5283 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5284 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5285 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5286 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5287 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5288 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5289 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5290 		return key_senderror(so, m, EINVAL);
   5291 	}
   5292 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5293 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5294 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5295 		/* XXX need more */
   5296 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5297 		return key_senderror(so, m, EINVAL);
   5298 	}
   5299 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5300 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5301 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5302 	} else {
   5303 		mode = IPSEC_MODE_ANY;
   5304 		reqid = 0;
   5305 	}
   5306 
   5307 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5308 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5309 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5310 
   5311 	error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
   5312 	if (error != 0)
   5313 		return key_senderror(so, m, EINVAL);
   5314 
   5315 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5316 	if (error != 0)
   5317 		return key_senderror(so, m, EINVAL);
   5318 
   5319 	/* get a SA header */
   5320 	newsah = key_getsah(&saidx, CMP_REQID);
   5321 	if (newsah == NULL) {
   5322 		/* create a new SA header */
   5323 		newsah = key_newsah(&saidx);
   5324 		if (newsah == NULL) {
   5325 			IPSECLOG(LOG_DEBUG, "No more memory.\n");
   5326 			return key_senderror(so, m, ENOBUFS);
   5327 		}
   5328 	}
   5329 
   5330 	/* set spidx if there */
   5331 	/* XXX rewrite */
   5332 	error = key_setident(newsah, m, mhp);
   5333 	if (error) {
   5334 		return key_senderror(so, m, error);
   5335 	}
   5336 
   5337     {
   5338 	struct secasvar *sav;
   5339 
   5340 	/* We can create new SA only if SPI is differenct. */
   5341 	sav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
   5342 	if (sav != NULL) {
   5343 		KEY_FREESAV(&sav);
   5344 		IPSECLOG(LOG_DEBUG, "SA already exists.\n");
   5345 		return key_senderror(so, m, EEXIST);
   5346 	}
   5347     }
   5348 
   5349 	/* create new SA entry. */
   5350 	newsav = KEY_NEWSAV(m, mhp, &error);
   5351 	if (newsav == NULL) {
   5352 		return key_senderror(so, m, error);
   5353 	}
   5354 	newsav->sah = newsah;
   5355 
   5356 	error = key_handle_natt_info(newsav, mhp);
   5357 	if (error != 0) {
   5358 		key_delsav(newsav);
   5359 		return key_senderror(so, m, EINVAL);
   5360 	}
   5361 
   5362 	error = key_init_xform(newsav);
   5363 	if (error != 0) {
   5364 		key_delsav(newsav);
   5365 		return key_senderror(so, m, error);
   5366 	}
   5367 
   5368 	/* add to satree */
   5369 	newsav->refcnt = 1;
   5370 	newsav->state = SADB_SASTATE_MATURE;
   5371 	LIST_INSERT_TAIL(&newsah->savtree[SADB_SASTATE_MATURE], newsav,
   5372 	    secasvar, chain);
   5373 	key_validate_savlist(newsah, SADB_SASTATE_MATURE);
   5374 
   5375 	/*
   5376 	 * don't call key_freesav() here, as we would like to keep the SA
   5377 	 * in the database on success.
   5378 	 */
   5379 
   5380     {
   5381 	struct mbuf *n;
   5382 
   5383 	/* set msg buf from mhp */
   5384 	n = key_getmsgbuf_x1(m, mhp);
   5385 	if (n == NULL) {
   5386 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   5387 		return key_senderror(so, m, ENOBUFS);
   5388 	}
   5389 
   5390 	m_freem(m);
   5391 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5392     }
   5393 }
   5394 
   5395 /* m is retained */
   5396 static int
   5397 key_setident(struct secashead *sah, struct mbuf *m,
   5398 	     const struct sadb_msghdr *mhp)
   5399 {
   5400 	const struct sadb_ident *idsrc, *iddst;
   5401 	int idsrclen, iddstlen;
   5402 
   5403 	KASSERT(!cpu_softintr_p());
   5404 	KASSERT(sah != NULL);
   5405 	KASSERT(m != NULL);
   5406 	KASSERT(mhp != NULL);
   5407 	KASSERT(mhp->msg != NULL);
   5408 
   5409 	/*
   5410 	 * Can be called with an existing sah from key_api_update().
   5411 	 */
   5412 	if (sah->idents != NULL) {
   5413 		kmem_free(sah->idents, sah->idents_len);
   5414 		sah->idents = NULL;
   5415 		sah->idents_len = 0;
   5416 	}
   5417 	if (sah->identd != NULL) {
   5418 		kmem_free(sah->identd, sah->identd_len);
   5419 		sah->identd = NULL;
   5420 		sah->identd_len = 0;
   5421 	}
   5422 
   5423 	/* don't make buffer if not there */
   5424 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
   5425 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5426 		sah->idents = NULL;
   5427 		sah->identd = NULL;
   5428 		return 0;
   5429 	}
   5430 
   5431 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
   5432 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5433 		IPSECLOG(LOG_DEBUG, "invalid identity.\n");
   5434 		return EINVAL;
   5435 	}
   5436 
   5437 	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
   5438 	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
   5439 	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
   5440 	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
   5441 
   5442 	/* validity check */
   5443 	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
   5444 		IPSECLOG(LOG_DEBUG, "ident type mismatch.\n");
   5445 		return EINVAL;
   5446 	}
   5447 
   5448 	switch (idsrc->sadb_ident_type) {
   5449 	case SADB_IDENTTYPE_PREFIX:
   5450 	case SADB_IDENTTYPE_FQDN:
   5451 	case SADB_IDENTTYPE_USERFQDN:
   5452 	default:
   5453 		/* XXX do nothing */
   5454 		sah->idents = NULL;
   5455 		sah->identd = NULL;
   5456 	 	return 0;
   5457 	}
   5458 
   5459 	/* make structure */
   5460 	sah->idents = kmem_alloc(idsrclen, KM_SLEEP);
   5461 	sah->idents_len = idsrclen;
   5462 	sah->identd = kmem_alloc(iddstlen, KM_SLEEP);
   5463 	sah->identd_len = iddstlen;
   5464 	memcpy(sah->idents, idsrc, idsrclen);
   5465 	memcpy(sah->identd, iddst, iddstlen);
   5466 
   5467 	return 0;
   5468 }
   5469 
   5470 /*
   5471  * m will not be freed on return.
   5472  * it is caller's responsibility to free the result.
   5473  */
   5474 static struct mbuf *
   5475 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
   5476 {
   5477 	struct mbuf *n;
   5478 
   5479 	KASSERT(m != NULL);
   5480 	KASSERT(mhp != NULL);
   5481 	KASSERT(mhp->msg != NULL);
   5482 
   5483 	/* create new sadb_msg to reply. */
   5484 	n = key_gather_mbuf(m, mhp, 1, 15, SADB_EXT_RESERVED,
   5485 	    SADB_EXT_SA, SADB_X_EXT_SA2,
   5486 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
   5487 	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
   5488 	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
   5489 	    SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
   5490 	    SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
   5491 	    SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NAT_T_FRAG);
   5492 	if (!n)
   5493 		return NULL;
   5494 
   5495 	if (n->m_len < sizeof(struct sadb_msg)) {
   5496 		n = m_pullup(n, sizeof(struct sadb_msg));
   5497 		if (n == NULL)
   5498 			return NULL;
   5499 	}
   5500 	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
   5501 	mtod(n, struct sadb_msg *)->sadb_msg_len =
   5502 	    PFKEY_UNIT64(n->m_pkthdr.len);
   5503 
   5504 	return n;
   5505 }
   5506 
   5507 static int key_delete_all (struct socket *, struct mbuf *,
   5508 			   const struct sadb_msghdr *, u_int16_t);
   5509 
   5510 /*
   5511  * SADB_DELETE processing
   5512  * receive
   5513  *   <base, SA(*), address(SD)>
   5514  * from the ikmpd, and set SADB_SASTATE_DEAD,
   5515  * and send,
   5516  *   <base, SA(*), address(SD)>
   5517  * to the ikmpd.
   5518  *
   5519  * m will always be freed.
   5520  */
   5521 static int
   5522 key_api_delete(struct socket *so, struct mbuf *m,
   5523 	   const struct sadb_msghdr *mhp)
   5524 {
   5525 	struct sadb_sa *sa0;
   5526 	const struct sockaddr *src, *dst;
   5527 	struct secasindex saidx;
   5528 	struct secashead *sah;
   5529 	struct secasvar *sav = NULL;
   5530 	u_int16_t proto;
   5531 	int error;
   5532 
   5533 	/* map satype to proto */
   5534 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   5535 	if (proto == 0) {
   5536 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5537 		return key_senderror(so, m, EINVAL);
   5538 	}
   5539 
   5540 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5541 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5542 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5543 		return key_senderror(so, m, EINVAL);
   5544 	}
   5545 
   5546 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5547 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5548 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5549 		return key_senderror(so, m, EINVAL);
   5550 	}
   5551 
   5552 	if (mhp->ext[SADB_EXT_SA] == NULL) {
   5553 		/*
   5554 		 * Caller wants us to delete all non-LARVAL SAs
   5555 		 * that match the src/dst.  This is used during
   5556 		 * IKE INITIAL-CONTACT.
   5557 		 */
   5558 		IPSECLOG(LOG_DEBUG, "doing delete all.\n");
   5559 		return key_delete_all(so, m, mhp, proto);
   5560 	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
   5561 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5562 		return key_senderror(so, m, EINVAL);
   5563 	}
   5564 
   5565 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5566 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5567 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5568 
   5569 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   5570 	if (error != 0)
   5571 		return key_senderror(so, m, EINVAL);
   5572 
   5573 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5574 	if (error != 0)
   5575 		return key_senderror(so, m, EINVAL);
   5576 
   5577 	/* get a SA header */
   5578 	sah = key_getsah(&saidx, CMP_HEAD);
   5579 	if (sah != NULL) {
   5580 		/* get a SA with SPI. */
   5581 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5582 	}
   5583 
   5584 	if (sav == NULL) {
   5585 		IPSECLOG(LOG_DEBUG, "no SA found.\n");
   5586 		return key_senderror(so, m, ENOENT);
   5587 	}
   5588 
   5589 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5590 	KEY_FREESAV(&sav);
   5591 	KEY_FREESAV(&sav);
   5592 
   5593     {
   5594 	struct mbuf *n;
   5595 
   5596 	/* create new sadb_msg to reply. */
   5597 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
   5598 	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5599 	if (!n)
   5600 		return key_senderror(so, m, ENOBUFS);
   5601 
   5602 	n = key_fill_replymsg(n, 0);
   5603 	if (n == NULL)
   5604 		return key_senderror(so, m, ENOBUFS);
   5605 
   5606 	m_freem(m);
   5607 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5608     }
   5609 }
   5610 
   5611 /*
   5612  * delete all SAs for src/dst.  Called from key_api_delete().
   5613  */
   5614 static int
   5615 key_delete_all(struct socket *so, struct mbuf *m,
   5616 	       const struct sadb_msghdr *mhp, u_int16_t proto)
   5617 {
   5618 	const struct sockaddr *src, *dst;
   5619 	struct secasindex saidx;
   5620 	struct secashead *sah;
   5621 	struct secasvar *sav, *nextsav;
   5622 	u_int state;
   5623 	int error;
   5624 
   5625 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5626 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5627 
   5628 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   5629 	if (error != 0)
   5630 		return key_senderror(so, m, EINVAL);
   5631 
   5632 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5633 	if (error != 0)
   5634 		return key_senderror(so, m, EINVAL);
   5635 
   5636 	sah = key_getsah(&saidx, CMP_HEAD);
   5637 	if (sah != NULL) {
   5638 		/* Delete all non-LARVAL SAs. */
   5639 		SASTATE_ALIVE_FOREACH(state) {
   5640 			if (state == SADB_SASTATE_LARVAL)
   5641 				continue;
   5642 			LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain,
   5643 			    nextsav) {
   5644 				/* sanity check */
   5645 				if (sav->state != state) {
   5646 					IPSECLOG(LOG_DEBUG,
   5647 					    "invalid sav->state "
   5648 					    "(queue: %d SA: %d)\n",
   5649 					    state, sav->state);
   5650 					continue;
   5651 				}
   5652 
   5653 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5654 				KEY_FREESAV(&sav);
   5655 			}
   5656 		}
   5657 	}
   5658     {
   5659 	struct mbuf *n;
   5660 
   5661 	/* create new sadb_msg to reply. */
   5662 	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
   5663 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5664 	if (!n)
   5665 		return key_senderror(so, m, ENOBUFS);
   5666 
   5667 	n = key_fill_replymsg(n, 0);
   5668 	if (n == NULL)
   5669 		return key_senderror(so, m, ENOBUFS);
   5670 
   5671 	m_freem(m);
   5672 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5673     }
   5674 }
   5675 
   5676 /*
   5677  * SADB_GET processing
   5678  * receive
   5679  *   <base, SA(*), address(SD)>
   5680  * from the ikmpd, and get a SP and a SA to respond,
   5681  * and send,
   5682  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
   5683  *       (identity(SD),) (sensitivity)>
   5684  * to the ikmpd.
   5685  *
   5686  * m will always be freed.
   5687  */
   5688 static int
   5689 key_api_get(struct socket *so, struct mbuf *m,
   5690 	const struct sadb_msghdr *mhp)
   5691 {
   5692 	struct sadb_sa *sa0;
   5693 	const struct sockaddr *src, *dst;
   5694 	struct secasindex saidx;
   5695 	struct secashead *sah;
   5696 	struct secasvar *sav = NULL;
   5697 	u_int16_t proto;
   5698 	int error;
   5699 
   5700 	/* map satype to proto */
   5701 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5702 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5703 		return key_senderror(so, m, EINVAL);
   5704 	}
   5705 
   5706 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5707 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5708 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5709 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5710 		return key_senderror(so, m, EINVAL);
   5711 	}
   5712 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5713 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5714 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5715 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5716 		return key_senderror(so, m, EINVAL);
   5717 	}
   5718 
   5719 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5720 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5721 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5722 
   5723 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   5724 	if (error != 0)
   5725 		return key_senderror(so, m, EINVAL);
   5726 
   5727 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5728 	if (error != 0)
   5729 		return key_senderror(so, m, EINVAL);
   5730 
   5731 	/* get a SA header */
   5732 	sah = key_getsah(&saidx, CMP_HEAD);
   5733 	if (sah != NULL) {
   5734 		/* get a SA with SPI. */
   5735 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5736 	}
   5737 	if (sav == NULL) {
   5738 		IPSECLOG(LOG_DEBUG, "no SA found.\n");
   5739 		return key_senderror(so, m, ENOENT);
   5740 	}
   5741 
   5742     {
   5743 	struct mbuf *n;
   5744 	u_int8_t satype;
   5745 
   5746 	/* map proto to satype */
   5747 	satype = key_proto2satype(sah->saidx.proto);
   5748 	if (satype == 0) {
   5749 		KEY_FREESAV(&sav);
   5750 		IPSECLOG(LOG_DEBUG, "there was invalid proto in SAD.\n");
   5751 		return key_senderror(so, m, EINVAL);
   5752 	}
   5753 
   5754 	/* create new sadb_msg to reply. */
   5755 	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
   5756 	    mhp->msg->sadb_msg_pid);
   5757 	KEY_FREESAV(&sav);
   5758 	if (!n)
   5759 		return key_senderror(so, m, ENOBUFS);
   5760 
   5761 	m_freem(m);
   5762 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   5763     }
   5764 }
   5765 
   5766 /* XXX make it sysctl-configurable? */
   5767 static void
   5768 key_getcomb_setlifetime(struct sadb_comb *comb)
   5769 {
   5770 
   5771 	comb->sadb_comb_soft_allocations = 1;
   5772 	comb->sadb_comb_hard_allocations = 1;
   5773 	comb->sadb_comb_soft_bytes = 0;
   5774 	comb->sadb_comb_hard_bytes = 0;
   5775 	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
   5776 	comb->sadb_comb_soft_addtime = comb->sadb_comb_hard_addtime * 80 / 100;
   5777 	comb->sadb_comb_hard_usetime = 28800;	/* 8 hours */
   5778 	comb->sadb_comb_soft_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
   5779 }
   5780 
   5781 /*
   5782  * XXX reorder combinations by preference
   5783  * XXX no idea if the user wants ESP authentication or not
   5784  */
   5785 static struct mbuf *
   5786 key_getcomb_esp(void)
   5787 {
   5788 	struct sadb_comb *comb;
   5789 	const struct enc_xform *algo;
   5790 	struct mbuf *result = NULL, *m, *n;
   5791 	int encmin;
   5792 	int i, off, o;
   5793 	int totlen;
   5794 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   5795 
   5796 	m = NULL;
   5797 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   5798 		algo = esp_algorithm_lookup(i);
   5799 		if (algo == NULL)
   5800 			continue;
   5801 
   5802 		/* discard algorithms with key size smaller than system min */
   5803 		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
   5804 			continue;
   5805 		if (_BITS(algo->minkey) < ipsec_esp_keymin)
   5806 			encmin = ipsec_esp_keymin;
   5807 		else
   5808 			encmin = _BITS(algo->minkey);
   5809 
   5810 		if (ipsec_esp_auth)
   5811 			m = key_getcomb_ah();
   5812 		else {
   5813 			KASSERTMSG(l <= MLEN,
   5814 			    "l=%u > MLEN=%lu", l, (u_long) MLEN);
   5815 			MGET(m, M_DONTWAIT, MT_DATA);
   5816 			if (m) {
   5817 				M_ALIGN(m, l);
   5818 				m->m_len = l;
   5819 				m->m_next = NULL;
   5820 				memset(mtod(m, void *), 0, m->m_len);
   5821 			}
   5822 		}
   5823 		if (!m)
   5824 			goto fail;
   5825 
   5826 		totlen = 0;
   5827 		for (n = m; n; n = n->m_next)
   5828 			totlen += n->m_len;
   5829 		KASSERTMSG((totlen % l) == 0, "totlen=%u, l=%u", totlen, l);
   5830 
   5831 		for (off = 0; off < totlen; off += l) {
   5832 			n = m_pulldown(m, off, l, &o);
   5833 			if (!n) {
   5834 				/* m is already freed */
   5835 				goto fail;
   5836 			}
   5837 			comb = (struct sadb_comb *)(mtod(n, char *) + o);
   5838 			memset(comb, 0, sizeof(*comb));
   5839 			key_getcomb_setlifetime(comb);
   5840 			comb->sadb_comb_encrypt = i;
   5841 			comb->sadb_comb_encrypt_minbits = encmin;
   5842 			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
   5843 		}
   5844 
   5845 		if (!result)
   5846 			result = m;
   5847 		else
   5848 			m_cat(result, m);
   5849 	}
   5850 
   5851 	return result;
   5852 
   5853  fail:
   5854 	if (result)
   5855 		m_freem(result);
   5856 	return NULL;
   5857 }
   5858 
   5859 static void
   5860 key_getsizes_ah(const struct auth_hash *ah, int alg,
   5861 	        u_int16_t* ksmin, u_int16_t* ksmax)
   5862 {
   5863 	*ksmin = *ksmax = ah->keysize;
   5864 	if (ah->keysize == 0) {
   5865 		/*
   5866 		 * Transform takes arbitrary key size but algorithm
   5867 		 * key size is restricted.  Enforce this here.
   5868 		 */
   5869 		switch (alg) {
   5870 		case SADB_X_AALG_MD5:	*ksmin = *ksmax = 16; break;
   5871 		case SADB_X_AALG_SHA:	*ksmin = *ksmax = 20; break;
   5872 		case SADB_X_AALG_NULL:	*ksmin = 0; *ksmax = 256; break;
   5873 		default:
   5874 			IPSECLOG(LOG_DEBUG, "unknown AH algorithm %u\n", alg);
   5875 			break;
   5876 		}
   5877 	}
   5878 }
   5879 
   5880 /*
   5881  * XXX reorder combinations by preference
   5882  */
   5883 static struct mbuf *
   5884 key_getcomb_ah(void)
   5885 {
   5886 	struct sadb_comb *comb;
   5887 	const struct auth_hash *algo;
   5888 	struct mbuf *m;
   5889 	u_int16_t minkeysize, maxkeysize;
   5890 	int i;
   5891 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   5892 
   5893 	m = NULL;
   5894 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   5895 #if 1
   5896 		/* we prefer HMAC algorithms, not old algorithms */
   5897 		if (i != SADB_AALG_SHA1HMAC &&
   5898 		    i != SADB_AALG_MD5HMAC &&
   5899 		    i != SADB_X_AALG_SHA2_256 &&
   5900 		    i != SADB_X_AALG_SHA2_384 &&
   5901 		    i != SADB_X_AALG_SHA2_512)
   5902 			continue;
   5903 #endif
   5904 		algo = ah_algorithm_lookup(i);
   5905 		if (!algo)
   5906 			continue;
   5907 		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
   5908 		/* discard algorithms with key size smaller than system min */
   5909 		if (_BITS(minkeysize) < ipsec_ah_keymin)
   5910 			continue;
   5911 
   5912 		if (!m) {
   5913 			KASSERTMSG(l <= MLEN,
   5914 			    "l=%u > MLEN=%lu", l, (u_long) MLEN);
   5915 			MGET(m, M_DONTWAIT, MT_DATA);
   5916 			if (m) {
   5917 				M_ALIGN(m, l);
   5918 				m->m_len = l;
   5919 				m->m_next = NULL;
   5920 			}
   5921 		} else
   5922 			M_PREPEND(m, l, M_DONTWAIT);
   5923 		if (!m)
   5924 			return NULL;
   5925 
   5926 		if (m->m_len < sizeof(struct sadb_comb)) {
   5927 			m = m_pullup(m, sizeof(struct sadb_comb));
   5928 			if (m == NULL)
   5929 				return NULL;
   5930 		}
   5931 
   5932 		comb = mtod(m, struct sadb_comb *);
   5933 		memset(comb, 0, sizeof(*comb));
   5934 		key_getcomb_setlifetime(comb);
   5935 		comb->sadb_comb_auth = i;
   5936 		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
   5937 		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
   5938 	}
   5939 
   5940 	return m;
   5941 }
   5942 
   5943 /*
   5944  * not really an official behavior.  discussed in pf_key (at) inner.net in Sep2000.
   5945  * XXX reorder combinations by preference
   5946  */
   5947 static struct mbuf *
   5948 key_getcomb_ipcomp(void)
   5949 {
   5950 	struct sadb_comb *comb;
   5951 	const struct comp_algo *algo;
   5952 	struct mbuf *m;
   5953 	int i;
   5954 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   5955 
   5956 	m = NULL;
   5957 	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
   5958 		algo = ipcomp_algorithm_lookup(i);
   5959 		if (!algo)
   5960 			continue;
   5961 
   5962 		if (!m) {
   5963 			KASSERTMSG(l <= MLEN,
   5964 			    "l=%u > MLEN=%lu", l, (u_long) MLEN);
   5965 			MGET(m, M_DONTWAIT, MT_DATA);
   5966 			if (m) {
   5967 				M_ALIGN(m, l);
   5968 				m->m_len = l;
   5969 				m->m_next = NULL;
   5970 			}
   5971 		} else
   5972 			M_PREPEND(m, l, M_DONTWAIT);
   5973 		if (!m)
   5974 			return NULL;
   5975 
   5976 		if (m->m_len < sizeof(struct sadb_comb)) {
   5977 			m = m_pullup(m, sizeof(struct sadb_comb));
   5978 			if (m == NULL)
   5979 				return NULL;
   5980 		}
   5981 
   5982 		comb = mtod(m, struct sadb_comb *);
   5983 		memset(comb, 0, sizeof(*comb));
   5984 		key_getcomb_setlifetime(comb);
   5985 		comb->sadb_comb_encrypt = i;
   5986 		/* what should we set into sadb_comb_*_{min,max}bits? */
   5987 	}
   5988 
   5989 	return m;
   5990 }
   5991 
   5992 /*
   5993  * XXX no way to pass mode (transport/tunnel) to userland
   5994  * XXX replay checking?
   5995  * XXX sysctl interface to ipsec_{ah,esp}_keymin
   5996  */
   5997 static struct mbuf *
   5998 key_getprop(const struct secasindex *saidx)
   5999 {
   6000 	struct sadb_prop *prop;
   6001 	struct mbuf *m, *n;
   6002 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
   6003 	int totlen;
   6004 
   6005 	switch (saidx->proto)  {
   6006 	case IPPROTO_ESP:
   6007 		m = key_getcomb_esp();
   6008 		break;
   6009 	case IPPROTO_AH:
   6010 		m = key_getcomb_ah();
   6011 		break;
   6012 	case IPPROTO_IPCOMP:
   6013 		m = key_getcomb_ipcomp();
   6014 		break;
   6015 	default:
   6016 		return NULL;
   6017 	}
   6018 
   6019 	if (!m)
   6020 		return NULL;
   6021 	M_PREPEND(m, l, M_DONTWAIT);
   6022 	if (!m)
   6023 		return NULL;
   6024 
   6025 	totlen = 0;
   6026 	for (n = m; n; n = n->m_next)
   6027 		totlen += n->m_len;
   6028 
   6029 	prop = mtod(m, struct sadb_prop *);
   6030 	memset(prop, 0, sizeof(*prop));
   6031 	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
   6032 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
   6033 	prop->sadb_prop_replay = 32;	/* XXX */
   6034 
   6035 	return m;
   6036 }
   6037 
   6038 /*
   6039  * SADB_ACQUIRE processing called by key_checkrequest() and key_api_acquire().
   6040  * send
   6041  *   <base, SA, address(SD), (address(P)), x_policy,
   6042  *       (identity(SD),) (sensitivity,) proposal>
   6043  * to KMD, and expect to receive
   6044  *   <base> with SADB_ACQUIRE if error occurred,
   6045  * or
   6046  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
   6047  * from KMD by PF_KEY.
   6048  *
   6049  * XXX x_policy is outside of RFC2367 (KAME extension).
   6050  * XXX sensitivity is not supported.
   6051  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
   6052  * see comment for key_getcomb_ipcomp().
   6053  *
   6054  * OUT:
   6055  *    0     : succeed
   6056  *    others: error number
   6057  */
   6058 static int
   6059 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
   6060 {
   6061 	struct mbuf *result = NULL, *m;
   6062 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6063 	struct secacq *newacq;
   6064 #endif
   6065 	u_int8_t satype;
   6066 	int error = -1;
   6067 	u_int32_t seq;
   6068 
   6069 	/* sanity check */
   6070 	KASSERT(saidx != NULL);
   6071 	satype = key_proto2satype(saidx->proto);
   6072 	KASSERTMSG(satype != 0, "null satype, protocol %u", saidx->proto);
   6073 
   6074 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6075 	/*
   6076 	 * We never do anything about acquirng SA.  There is anather
   6077 	 * solution that kernel blocks to send SADB_ACQUIRE message until
   6078 	 * getting something message from IKEd.  In later case, to be
   6079 	 * managed with ACQUIRING list.
   6080 	 */
   6081 	/* Get an entry to check whether sending message or not. */
   6082 	mutex_enter(&key_mtx);
   6083 	newacq = key_getacq(saidx);
   6084 	if (newacq != NULL) {
   6085 		if (key_blockacq_count < newacq->count) {
   6086 			/* reset counter and do send message. */
   6087 			newacq->count = 0;
   6088 		} else {
   6089 			/* increment counter and do nothing. */
   6090 			newacq->count++;
   6091 			mutex_exit(&key_mtx);
   6092 			return 0;
   6093 		}
   6094 	} else {
   6095 		/* make new entry for blocking to send SADB_ACQUIRE. */
   6096 		newacq = key_newacq(saidx);
   6097 		if (newacq == NULL)
   6098 			return ENOBUFS;
   6099 
   6100 		/* add to acqtree */
   6101 		LIST_INSERT_HEAD(&acqtree, newacq, chain);
   6102 	}
   6103 
   6104 	seq = newacq->seq;
   6105 	mutex_exit(&key_mtx);
   6106 #else
   6107 	seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
   6108 #endif
   6109 	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
   6110 	if (!m) {
   6111 		error = ENOBUFS;
   6112 		goto fail;
   6113 	}
   6114 	result = m;
   6115 
   6116 	/* set sadb_address for saidx's. */
   6117 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &saidx->src.sa, FULLMASK,
   6118 	    IPSEC_ULPROTO_ANY);
   6119 	if (!m) {
   6120 		error = ENOBUFS;
   6121 		goto fail;
   6122 	}
   6123 	m_cat(result, m);
   6124 
   6125 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &saidx->dst.sa, FULLMASK,
   6126 	    IPSEC_ULPROTO_ANY);
   6127 	if (!m) {
   6128 		error = ENOBUFS;
   6129 		goto fail;
   6130 	}
   6131 	m_cat(result, m);
   6132 
   6133 	/* XXX proxy address (optional) */
   6134 
   6135 	/* set sadb_x_policy */
   6136 	if (sp) {
   6137 		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
   6138 		if (!m) {
   6139 			error = ENOBUFS;
   6140 			goto fail;
   6141 		}
   6142 		m_cat(result, m);
   6143 	}
   6144 
   6145 	/* XXX identity (optional) */
   6146 #if 0
   6147 	if (idexttype && fqdn) {
   6148 		/* create identity extension (FQDN) */
   6149 		struct sadb_ident *id;
   6150 		int fqdnlen;
   6151 
   6152 		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
   6153 		id = (struct sadb_ident *)p;
   6154 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6155 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6156 		id->sadb_ident_exttype = idexttype;
   6157 		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
   6158 		memcpy(id + 1, fqdn, fqdnlen);
   6159 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
   6160 	}
   6161 
   6162 	if (idexttype) {
   6163 		/* create identity extension (USERFQDN) */
   6164 		struct sadb_ident *id;
   6165 		int userfqdnlen;
   6166 
   6167 		if (userfqdn) {
   6168 			/* +1 for terminating-NUL */
   6169 			userfqdnlen = strlen(userfqdn) + 1;
   6170 		} else
   6171 			userfqdnlen = 0;
   6172 		id = (struct sadb_ident *)p;
   6173 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6174 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6175 		id->sadb_ident_exttype = idexttype;
   6176 		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
   6177 		/* XXX is it correct? */
   6178 		if (curlwp)
   6179 			id->sadb_ident_id = kauth_cred_getuid(curlwp->l_cred);
   6180 		if (userfqdn && userfqdnlen)
   6181 			memcpy(id + 1, userfqdn, userfqdnlen);
   6182 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
   6183 	}
   6184 #endif
   6185 
   6186 	/* XXX sensitivity (optional) */
   6187 
   6188 	/* create proposal/combination extension */
   6189 	m = key_getprop(saidx);
   6190 #if 0
   6191 	/*
   6192 	 * spec conformant: always attach proposal/combination extension,
   6193 	 * the problem is that we have no way to attach it for ipcomp,
   6194 	 * due to the way sadb_comb is declared in RFC2367.
   6195 	 */
   6196 	if (!m) {
   6197 		error = ENOBUFS;
   6198 		goto fail;
   6199 	}
   6200 	m_cat(result, m);
   6201 #else
   6202 	/*
   6203 	 * outside of spec; make proposal/combination extension optional.
   6204 	 */
   6205 	if (m)
   6206 		m_cat(result, m);
   6207 #endif
   6208 
   6209 	if ((result->m_flags & M_PKTHDR) == 0) {
   6210 		error = EINVAL;
   6211 		goto fail;
   6212 	}
   6213 
   6214 	if (result->m_len < sizeof(struct sadb_msg)) {
   6215 		result = m_pullup(result, sizeof(struct sadb_msg));
   6216 		if (result == NULL) {
   6217 			error = ENOBUFS;
   6218 			goto fail;
   6219 		}
   6220 	}
   6221 
   6222 	result->m_pkthdr.len = 0;
   6223 	for (m = result; m; m = m->m_next)
   6224 		result->m_pkthdr.len += m->m_len;
   6225 
   6226 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6227 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6228 
   6229 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   6230 
   6231  fail:
   6232 	if (result)
   6233 		m_freem(result);
   6234 	return error;
   6235 }
   6236 
   6237 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6238 static struct secacq *
   6239 key_newacq(const struct secasindex *saidx)
   6240 {
   6241 	struct secacq *newacq;
   6242 
   6243 	/* get new entry */
   6244 	newacq = kmem_intr_zalloc(sizeof(struct secacq), KM_NOSLEEP);
   6245 	if (newacq == NULL) {
   6246 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   6247 		return NULL;
   6248 	}
   6249 
   6250 	/* copy secindex */
   6251 	memcpy(&newacq->saidx, saidx, sizeof(newacq->saidx));
   6252 	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
   6253 	newacq->created = time_uptime;
   6254 	newacq->count = 0;
   6255 
   6256 	return newacq;
   6257 }
   6258 
   6259 static struct secacq *
   6260 key_getacq(const struct secasindex *saidx)
   6261 {
   6262 	struct secacq *acq;
   6263 
   6264 	KASSERT(mutex_owned(&key_mtx));
   6265 
   6266 	LIST_FOREACH(acq, &acqtree, chain) {
   6267 		if (key_saidx_match(saidx, &acq->saidx, CMP_EXACTLY))
   6268 			return acq;
   6269 	}
   6270 
   6271 	return NULL;
   6272 }
   6273 
   6274 static struct secacq *
   6275 key_getacqbyseq(u_int32_t seq)
   6276 {
   6277 	struct secacq *acq;
   6278 
   6279 	KASSERT(mutex_owned(&key_mtx));
   6280 
   6281 	LIST_FOREACH(acq, &acqtree, chain) {
   6282 		if (acq->seq == seq)
   6283 			return acq;
   6284 	}
   6285 
   6286 	return NULL;
   6287 }
   6288 #endif
   6289 
   6290 #ifdef notyet
   6291 static struct secspacq *
   6292 key_newspacq(const struct secpolicyindex *spidx)
   6293 {
   6294 	struct secspacq *acq;
   6295 
   6296 	/* get new entry */
   6297 	acq = kmem_intr_zalloc(sizeof(struct secspacq), KM_NOSLEEP);
   6298 	if (acq == NULL) {
   6299 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   6300 		return NULL;
   6301 	}
   6302 
   6303 	/* copy secindex */
   6304 	memcpy(&acq->spidx, spidx, sizeof(acq->spidx));
   6305 	acq->created = time_uptime;
   6306 	acq->count = 0;
   6307 
   6308 	return acq;
   6309 }
   6310 
   6311 static struct secspacq *
   6312 key_getspacq(const struct secpolicyindex *spidx)
   6313 {
   6314 	struct secspacq *acq;
   6315 
   6316 	LIST_FOREACH(acq, &spacqtree, chain) {
   6317 		if (key_spidx_match_exactly(spidx, &acq->spidx))
   6318 			return acq;
   6319 	}
   6320 
   6321 	return NULL;
   6322 }
   6323 #endif /* notyet */
   6324 
   6325 /*
   6326  * SADB_ACQUIRE processing,
   6327  * in first situation, is receiving
   6328  *   <base>
   6329  * from the ikmpd, and clear sequence of its secasvar entry.
   6330  *
   6331  * In second situation, is receiving
   6332  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6333  * from a user land process, and return
   6334  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6335  * to the socket.
   6336  *
   6337  * m will always be freed.
   6338  */
   6339 static int
   6340 key_api_acquire(struct socket *so, struct mbuf *m,
   6341       	     const struct sadb_msghdr *mhp)
   6342 {
   6343 	const struct sockaddr *src, *dst;
   6344 	struct secasindex saidx;
   6345 	struct secashead *sah;
   6346 	u_int16_t proto;
   6347 	int error;
   6348 
   6349 	/*
   6350 	 * Error message from KMd.
   6351 	 * We assume that if error was occurred in IKEd, the length of PFKEY
   6352 	 * message is equal to the size of sadb_msg structure.
   6353 	 * We do not raise error even if error occurred in this function.
   6354 	 */
   6355 	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
   6356 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6357 		struct secacq *acq;
   6358 
   6359 		/* check sequence number */
   6360 		if (mhp->msg->sadb_msg_seq == 0) {
   6361 			IPSECLOG(LOG_DEBUG, "must specify sequence number.\n");
   6362 			m_freem(m);
   6363 			return 0;
   6364 		}
   6365 
   6366 		mutex_enter(&key_mtx);
   6367 		acq = key_getacqbyseq(mhp->msg->sadb_msg_seq);
   6368 		if (acq == NULL) {
   6369 			mutex_exit(&key_mtx);
   6370 			/*
   6371 			 * the specified larval SA is already gone, or we got
   6372 			 * a bogus sequence number.  we can silently ignore it.
   6373 			 */
   6374 			m_freem(m);
   6375 			return 0;
   6376 		}
   6377 
   6378 		/* reset acq counter in order to deletion by timehander. */
   6379 		acq->created = time_uptime;
   6380 		acq->count = 0;
   6381 		mutex_exit(&key_mtx);
   6382 #endif
   6383 		m_freem(m);
   6384 		return 0;
   6385 	}
   6386 
   6387 	/*
   6388 	 * This message is from user land.
   6389 	 */
   6390 
   6391 	/* map satype to proto */
   6392 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   6393 	if (proto == 0) {
   6394 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   6395 		return key_senderror(so, m, EINVAL);
   6396 	}
   6397 
   6398 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   6399 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   6400 	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
   6401 		/* error */
   6402 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   6403 		return key_senderror(so, m, EINVAL);
   6404 	}
   6405 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   6406 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   6407 	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
   6408 		/* error */
   6409 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   6410 		return key_senderror(so, m, EINVAL);
   6411 	}
   6412 
   6413 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   6414 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   6415 
   6416 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   6417 	if (error != 0)
   6418 		return key_senderror(so, m, EINVAL);
   6419 
   6420 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   6421 	if (error != 0)
   6422 		return key_senderror(so, m, EINVAL);
   6423 
   6424 	/* get a SA index */
   6425 	sah = key_getsah(&saidx, CMP_MODE_REQID);
   6426 	if (sah != NULL) {
   6427 		IPSECLOG(LOG_DEBUG, "a SA exists already.\n");
   6428 		return key_senderror(so, m, EEXIST);
   6429 	}
   6430 
   6431 	error = key_acquire(&saidx, NULL);
   6432 	if (error != 0) {
   6433 		IPSECLOG(LOG_DEBUG, "error %d returned from key_acquire.\n",
   6434 		    error);
   6435 		return key_senderror(so, m, error);
   6436 	}
   6437 
   6438 	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
   6439 }
   6440 
   6441 /*
   6442  * SADB_REGISTER processing.
   6443  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
   6444  * receive
   6445  *   <base>
   6446  * from the ikmpd, and register a socket to send PF_KEY messages,
   6447  * and send
   6448  *   <base, supported>
   6449  * to KMD by PF_KEY.
   6450  * If socket is detached, must free from regnode.
   6451  *
   6452  * m will always be freed.
   6453  */
   6454 static int
   6455 key_api_register(struct socket *so, struct mbuf *m,
   6456 	     const struct sadb_msghdr *mhp)
   6457 {
   6458 	struct secreg *reg, *newreg = 0;
   6459 
   6460 	/* check for invalid register message */
   6461 	if (mhp->msg->sadb_msg_satype >= __arraycount(regtree))
   6462 		return key_senderror(so, m, EINVAL);
   6463 
   6464 	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
   6465 	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
   6466 		goto setmsg;
   6467 
   6468 	/* Allocate regnode in advance, out of mutex */
   6469 	newreg = kmem_zalloc(sizeof(*newreg), KM_SLEEP);
   6470 
   6471 	/* check whether existing or not */
   6472 	mutex_enter(&key_mtx);
   6473 	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
   6474 		if (reg->so == so) {
   6475 			IPSECLOG(LOG_DEBUG, "socket exists already.\n");
   6476 			mutex_exit(&key_mtx);
   6477 			kmem_free(newreg, sizeof(*newreg));
   6478 			return key_senderror(so, m, EEXIST);
   6479 		}
   6480 	}
   6481 
   6482 	newreg->so = so;
   6483 	((struct keycb *)sotorawcb(so))->kp_registered++;
   6484 
   6485 	/* add regnode to regtree. */
   6486 	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
   6487 	mutex_exit(&key_mtx);
   6488 
   6489   setmsg:
   6490     {
   6491 	struct mbuf *n;
   6492 	struct sadb_supported *sup;
   6493 	u_int len, alen, elen;
   6494 	int off;
   6495 	int i;
   6496 	struct sadb_alg *alg;
   6497 
   6498 	/* create new sadb_msg to reply. */
   6499 	alen = 0;
   6500 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   6501 		if (ah_algorithm_lookup(i))
   6502 			alen += sizeof(struct sadb_alg);
   6503 	}
   6504 	if (alen)
   6505 		alen += sizeof(struct sadb_supported);
   6506 	elen = 0;
   6507 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   6508 		if (esp_algorithm_lookup(i))
   6509 			elen += sizeof(struct sadb_alg);
   6510 	}
   6511 	if (elen)
   6512 		elen += sizeof(struct sadb_supported);
   6513 
   6514 	len = sizeof(struct sadb_msg) + alen + elen;
   6515 
   6516 	if (len > MCLBYTES)
   6517 		return key_senderror(so, m, ENOBUFS);
   6518 
   6519 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   6520 	if (len > MHLEN) {
   6521 		MCLGET(n, M_DONTWAIT);
   6522 		if ((n->m_flags & M_EXT) == 0) {
   6523 			m_freem(n);
   6524 			n = NULL;
   6525 		}
   6526 	}
   6527 	if (!n)
   6528 		return key_senderror(so, m, ENOBUFS);
   6529 
   6530 	n->m_pkthdr.len = n->m_len = len;
   6531 	n->m_next = NULL;
   6532 	off = 0;
   6533 
   6534 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   6535 	n = key_fill_replymsg(n, 0);
   6536 	if (n == NULL)
   6537 		return key_senderror(so, m, ENOBUFS);
   6538 
   6539 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   6540 
   6541 	/* for authentication algorithm */
   6542 	if (alen) {
   6543 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6544 		sup->sadb_supported_len = PFKEY_UNIT64(alen);
   6545 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
   6546 		off += PFKEY_ALIGN8(sizeof(*sup));
   6547 
   6548 		for (i = 1; i <= SADB_AALG_MAX; i++) {
   6549 			const struct auth_hash *aalgo;
   6550 			u_int16_t minkeysize, maxkeysize;
   6551 
   6552 			aalgo = ah_algorithm_lookup(i);
   6553 			if (!aalgo)
   6554 				continue;
   6555 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6556 			alg->sadb_alg_id = i;
   6557 			alg->sadb_alg_ivlen = 0;
   6558 			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
   6559 			alg->sadb_alg_minbits = _BITS(minkeysize);
   6560 			alg->sadb_alg_maxbits = _BITS(maxkeysize);
   6561 			off += PFKEY_ALIGN8(sizeof(*alg));
   6562 		}
   6563 	}
   6564 
   6565 	/* for encryption algorithm */
   6566 	if (elen) {
   6567 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6568 		sup->sadb_supported_len = PFKEY_UNIT64(elen);
   6569 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
   6570 		off += PFKEY_ALIGN8(sizeof(*sup));
   6571 
   6572 		for (i = 1; i <= SADB_EALG_MAX; i++) {
   6573 			const struct enc_xform *ealgo;
   6574 
   6575 			ealgo = esp_algorithm_lookup(i);
   6576 			if (!ealgo)
   6577 				continue;
   6578 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6579 			alg->sadb_alg_id = i;
   6580 			alg->sadb_alg_ivlen = ealgo->blocksize;
   6581 			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
   6582 			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
   6583 			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
   6584 		}
   6585 	}
   6586 
   6587 	KASSERTMSG(off == len, "length inconsistency");
   6588 
   6589 	m_freem(m);
   6590 	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
   6591     }
   6592 }
   6593 
   6594 /*
   6595  * free secreg entry registered.
   6596  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
   6597  */
   6598 void
   6599 key_freereg(struct socket *so)
   6600 {
   6601 	struct secreg *reg;
   6602 	int i;
   6603 
   6604 	KASSERT(!cpu_softintr_p());
   6605 	KASSERT(so != NULL);
   6606 
   6607 	/*
   6608 	 * check whether existing or not.
   6609 	 * check all type of SA, because there is a potential that
   6610 	 * one socket is registered to multiple type of SA.
   6611 	 */
   6612 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   6613 		mutex_enter(&key_mtx);
   6614 		LIST_FOREACH(reg, &regtree[i], chain) {
   6615 			if (reg->so == so) {
   6616 				LIST_REMOVE(reg, chain);
   6617 				break;
   6618 			}
   6619 		}
   6620 		mutex_exit(&key_mtx);
   6621 		if (reg != NULL)
   6622 			kmem_free(reg, sizeof(*reg));
   6623 	}
   6624 
   6625 	return;
   6626 }
   6627 
   6628 /*
   6629  * SADB_EXPIRE processing
   6630  * send
   6631  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
   6632  * to KMD by PF_KEY.
   6633  * NOTE: We send only soft lifetime extension.
   6634  *
   6635  * OUT:	0	: succeed
   6636  *	others	: error number
   6637  */
   6638 static int
   6639 key_expire(struct secasvar *sav)
   6640 {
   6641 	int s;
   6642 	int satype;
   6643 	struct mbuf *result = NULL, *m;
   6644 	int len;
   6645 	int error = -1;
   6646 	struct sadb_lifetime *lt;
   6647 
   6648 	/* XXX: Why do we lock ? */
   6649 	s = splsoftnet();	/*called from softclock()*/
   6650 
   6651 	KASSERT(sav != NULL);
   6652 
   6653 	satype = key_proto2satype(sav->sah->saidx.proto);
   6654 	KASSERTMSG(satype != 0, "invalid proto is passed");
   6655 
   6656 	/* set msg header */
   6657 	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
   6658 	if (!m) {
   6659 		error = ENOBUFS;
   6660 		goto fail;
   6661 	}
   6662 	result = m;
   6663 
   6664 	/* create SA extension */
   6665 	m = key_setsadbsa(sav);
   6666 	if (!m) {
   6667 		error = ENOBUFS;
   6668 		goto fail;
   6669 	}
   6670 	m_cat(result, m);
   6671 
   6672 	/* create SA extension */
   6673 	m = key_setsadbxsa2(sav->sah->saidx.mode,
   6674 	    sav->replay ? sav->replay->count : 0, sav->sah->saidx.reqid);
   6675 	if (!m) {
   6676 		error = ENOBUFS;
   6677 		goto fail;
   6678 	}
   6679 	m_cat(result, m);
   6680 
   6681 	/* create lifetime extension (current and soft) */
   6682 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
   6683 	m = key_alloc_mbuf(len);
   6684 	if (!m || m->m_next) {	/*XXX*/
   6685 		if (m)
   6686 			m_freem(m);
   6687 		error = ENOBUFS;
   6688 		goto fail;
   6689 	}
   6690 	memset(mtod(m, void *), 0, len);
   6691 	lt = mtod(m, struct sadb_lifetime *);
   6692 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   6693 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   6694 	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
   6695 	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
   6696 	lt->sadb_lifetime_addtime =
   6697 	    time_mono_to_wall(sav->lft_c->sadb_lifetime_addtime);
   6698 	lt->sadb_lifetime_usetime =
   6699 	    time_mono_to_wall(sav->lft_c->sadb_lifetime_usetime);
   6700 	lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
   6701 	memcpy(lt, sav->lft_s, sizeof(*lt));
   6702 	m_cat(result, m);
   6703 
   6704 	/* set sadb_address for source */
   6705 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &sav->sah->saidx.src.sa,
   6706 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6707 	if (!m) {
   6708 		error = ENOBUFS;
   6709 		goto fail;
   6710 	}
   6711 	m_cat(result, m);
   6712 
   6713 	/* set sadb_address for destination */
   6714 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &sav->sah->saidx.dst.sa,
   6715 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6716 	if (!m) {
   6717 		error = ENOBUFS;
   6718 		goto fail;
   6719 	}
   6720 	m_cat(result, m);
   6721 
   6722 	if ((result->m_flags & M_PKTHDR) == 0) {
   6723 		error = EINVAL;
   6724 		goto fail;
   6725 	}
   6726 
   6727 	if (result->m_len < sizeof(struct sadb_msg)) {
   6728 		result = m_pullup(result, sizeof(struct sadb_msg));
   6729 		if (result == NULL) {
   6730 			error = ENOBUFS;
   6731 			goto fail;
   6732 		}
   6733 	}
   6734 
   6735 	result->m_pkthdr.len = 0;
   6736 	for (m = result; m; m = m->m_next)
   6737 		result->m_pkthdr.len += m->m_len;
   6738 
   6739 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6740 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6741 
   6742 	splx(s);
   6743 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   6744 
   6745  fail:
   6746 	if (result)
   6747 		m_freem(result);
   6748 	splx(s);
   6749 	return error;
   6750 }
   6751 
   6752 /*
   6753  * SADB_FLUSH processing
   6754  * receive
   6755  *   <base>
   6756  * from the ikmpd, and free all entries in secastree.
   6757  * and send,
   6758  *   <base>
   6759  * to the ikmpd.
   6760  * NOTE: to do is only marking SADB_SASTATE_DEAD.
   6761  *
   6762  * m will always be freed.
   6763  */
   6764 static int
   6765 key_api_flush(struct socket *so, struct mbuf *m,
   6766           const struct sadb_msghdr *mhp)
   6767 {
   6768 	struct sadb_msg *newmsg;
   6769 	struct secashead *sah;
   6770 	struct secasvar *sav, *nextsav;
   6771 	u_int16_t proto;
   6772 	u_int8_t state;
   6773 
   6774 	/* map satype to proto */
   6775 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   6776 	if (proto == 0) {
   6777 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   6778 		return key_senderror(so, m, EINVAL);
   6779 	}
   6780 
   6781 	/* no SATYPE specified, i.e. flushing all SA. */
   6782 	LIST_FOREACH(sah, &sahtree, chain) {
   6783 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
   6784 		    proto != sah->saidx.proto)
   6785 			continue;
   6786 
   6787 		SASTATE_ALIVE_FOREACH(state) {
   6788 			LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain,
   6789 			    nextsav) {
   6790 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   6791 				KEY_FREESAV(&sav);
   6792 			}
   6793 		}
   6794 
   6795 		sah->state = SADB_SASTATE_DEAD;
   6796 	}
   6797 
   6798 	if (m->m_len < sizeof(struct sadb_msg) ||
   6799 	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
   6800 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   6801 		return key_senderror(so, m, ENOBUFS);
   6802 	}
   6803 
   6804 	if (m->m_next)
   6805 		m_freem(m->m_next);
   6806 	m->m_next = NULL;
   6807 	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
   6808 	newmsg = mtod(m, struct sadb_msg *);
   6809 	newmsg->sadb_msg_errno = 0;
   6810 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
   6811 
   6812 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   6813 }
   6814 
   6815 
   6816 static struct mbuf *
   6817 key_setdump_chain(u_int8_t req_satype, int *errorp, int *lenp, pid_t pid)
   6818 {
   6819 	struct secashead *sah;
   6820 	struct secasvar *sav;
   6821 	u_int16_t proto;
   6822 	u_int8_t satype;
   6823 	u_int8_t state;
   6824 	int cnt;
   6825 	struct mbuf *m, *n, *prev;
   6826 
   6827 	*lenp = 0;
   6828 
   6829 	/* map satype to proto */
   6830 	proto = key_satype2proto(req_satype);
   6831 	if (proto == 0) {
   6832 		*errorp = EINVAL;
   6833 		return (NULL);
   6834 	}
   6835 
   6836 	/* count sav entries to be sent to userland. */
   6837 	cnt = 0;
   6838 	LIST_FOREACH(sah, &sahtree, chain) {
   6839 		if (req_satype != SADB_SATYPE_UNSPEC &&
   6840 		    proto != sah->saidx.proto)
   6841 			continue;
   6842 
   6843 		SASTATE_ANY_FOREACH(state) {
   6844 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   6845 				cnt++;
   6846 			}
   6847 		}
   6848 	}
   6849 
   6850 	if (cnt == 0) {
   6851 		*errorp = ENOENT;
   6852 		return (NULL);
   6853 	}
   6854 
   6855 	/* send this to the userland, one at a time. */
   6856 	m = NULL;
   6857 	prev = m;
   6858 	LIST_FOREACH(sah, &sahtree, chain) {
   6859 		if (req_satype != SADB_SATYPE_UNSPEC &&
   6860 		    proto != sah->saidx.proto)
   6861 			continue;
   6862 
   6863 		/* map proto to satype */
   6864 		satype = key_proto2satype(sah->saidx.proto);
   6865 		if (satype == 0) {
   6866 			m_freem(m);
   6867 			*errorp = EINVAL;
   6868 			return (NULL);
   6869 		}
   6870 
   6871 		SASTATE_ANY_FOREACH(state) {
   6872 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   6873 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   6874 				    --cnt, pid);
   6875 				if (!n) {
   6876 					m_freem(m);
   6877 					*errorp = ENOBUFS;
   6878 					return (NULL);
   6879 				}
   6880 
   6881 				if (!m)
   6882 					m = n;
   6883 				else
   6884 					prev->m_nextpkt = n;
   6885 				prev = n;
   6886 			}
   6887 		}
   6888 	}
   6889 
   6890 	if (!m) {
   6891 		*errorp = EINVAL;
   6892 		return (NULL);
   6893 	}
   6894 
   6895 	if ((m->m_flags & M_PKTHDR) != 0) {
   6896 		m->m_pkthdr.len = 0;
   6897 		for (n = m; n; n = n->m_next)
   6898 			m->m_pkthdr.len += n->m_len;
   6899 	}
   6900 
   6901 	*errorp = 0;
   6902 	return (m);
   6903 }
   6904 
   6905 /*
   6906  * SADB_DUMP processing
   6907  * dump all entries including status of DEAD in SAD.
   6908  * receive
   6909  *   <base>
   6910  * from the ikmpd, and dump all secasvar leaves
   6911  * and send,
   6912  *   <base> .....
   6913  * to the ikmpd.
   6914  *
   6915  * m will always be freed.
   6916  */
   6917 static int
   6918 key_api_dump(struct socket *so, struct mbuf *m0,
   6919 	 const struct sadb_msghdr *mhp)
   6920 {
   6921 	u_int16_t proto;
   6922 	u_int8_t satype;
   6923 	struct mbuf *n;
   6924 	int s;
   6925 	int error, len, ok;
   6926 
   6927 	/* map satype to proto */
   6928 	satype = mhp->msg->sadb_msg_satype;
   6929 	proto = key_satype2proto(satype);
   6930 	if (proto == 0) {
   6931 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   6932 		return key_senderror(so, m0, EINVAL);
   6933 	}
   6934 
   6935 	/*
   6936 	 * If the requestor has insufficient socket-buffer space
   6937 	 * for the entire chain, nobody gets any response to the DUMP.
   6938 	 * XXX For now, only the requestor ever gets anything.
   6939 	 * Moreover, if the requestor has any space at all, they receive
   6940 	 * the entire chain, otherwise the request is refused with ENOBUFS.
   6941 	 */
   6942 	if (sbspace(&so->so_rcv) <= 0) {
   6943 		return key_senderror(so, m0, ENOBUFS);
   6944 	}
   6945 
   6946 	s = splsoftnet();
   6947 	n = key_setdump_chain(satype, &error, &len, mhp->msg->sadb_msg_pid);
   6948 	splx(s);
   6949 
   6950 	if (n == NULL) {
   6951 		return key_senderror(so, m0, ENOENT);
   6952 	}
   6953 	{
   6954 		uint64_t *ps = PFKEY_STAT_GETREF();
   6955 		ps[PFKEY_STAT_IN_TOTAL]++;
   6956 		ps[PFKEY_STAT_IN_BYTES] += len;
   6957 		PFKEY_STAT_PUTREF();
   6958 	}
   6959 
   6960 	/*
   6961 	 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
   6962 	 * The requestor receives either the entire chain, or an
   6963 	 * error message with ENOBUFS.
   6964 	 *
   6965 	 * sbappendaddrchain() takes the chain of entries, one
   6966 	 * packet-record per SPD entry, prepends the key_src sockaddr
   6967 	 * to each packet-record, links the sockaddr mbufs into a new
   6968 	 * list of records, then   appends the entire resulting
   6969 	 * list to the requesting socket.
   6970 	 */
   6971 	ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src, n,
   6972 	    SB_PRIO_ONESHOT_OVERFLOW);
   6973 
   6974 	if (!ok) {
   6975 		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
   6976 		m_freem(n);
   6977 		return key_senderror(so, m0, ENOBUFS);
   6978 	}
   6979 
   6980 	m_freem(m0);
   6981 	return 0;
   6982 }
   6983 
   6984 /*
   6985  * SADB_X_PROMISC processing
   6986  *
   6987  * m will always be freed.
   6988  */
   6989 static int
   6990 key_api_promisc(struct socket *so, struct mbuf *m,
   6991 	    const struct sadb_msghdr *mhp)
   6992 {
   6993 	int olen;
   6994 
   6995 	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   6996 
   6997 	if (olen < sizeof(struct sadb_msg)) {
   6998 #if 1
   6999 		return key_senderror(so, m, EINVAL);
   7000 #else
   7001 		m_freem(m);
   7002 		return 0;
   7003 #endif
   7004 	} else if (olen == sizeof(struct sadb_msg)) {
   7005 		/* enable/disable promisc mode */
   7006 		struct keycb *kp = (struct keycb *)sotorawcb(so);
   7007 		if (kp == NULL)
   7008 			return key_senderror(so, m, EINVAL);
   7009 		mhp->msg->sadb_msg_errno = 0;
   7010 		switch (mhp->msg->sadb_msg_satype) {
   7011 		case 0:
   7012 		case 1:
   7013 			kp->kp_promisc = mhp->msg->sadb_msg_satype;
   7014 			break;
   7015 		default:
   7016 			return key_senderror(so, m, EINVAL);
   7017 		}
   7018 
   7019 		/* send the original message back to everyone */
   7020 		mhp->msg->sadb_msg_errno = 0;
   7021 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7022 	} else {
   7023 		/* send packet as is */
   7024 
   7025 		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
   7026 
   7027 		/* TODO: if sadb_msg_seq is specified, send to specific pid */
   7028 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7029 	}
   7030 }
   7031 
   7032 static int (*key_api_typesw[]) (struct socket *, struct mbuf *,
   7033 		const struct sadb_msghdr *) = {
   7034 	NULL,			/* SADB_RESERVED */
   7035 	key_api_getspi,		/* SADB_GETSPI */
   7036 	key_api_update,		/* SADB_UPDATE */
   7037 	key_api_add,		/* SADB_ADD */
   7038 	key_api_delete,		/* SADB_DELETE */
   7039 	key_api_get,		/* SADB_GET */
   7040 	key_api_acquire,	/* SADB_ACQUIRE */
   7041 	key_api_register,	/* SADB_REGISTER */
   7042 	NULL,			/* SADB_EXPIRE */
   7043 	key_api_flush,		/* SADB_FLUSH */
   7044 	key_api_dump,		/* SADB_DUMP */
   7045 	key_api_promisc,	/* SADB_X_PROMISC */
   7046 	NULL,			/* SADB_X_PCHANGE */
   7047 	key_api_spdadd,		/* SADB_X_SPDUPDATE */
   7048 	key_api_spdadd,		/* SADB_X_SPDADD */
   7049 	key_api_spddelete,	/* SADB_X_SPDDELETE */
   7050 	key_api_spdget,		/* SADB_X_SPDGET */
   7051 	NULL,			/* SADB_X_SPDACQUIRE */
   7052 	key_api_spddump,	/* SADB_X_SPDDUMP */
   7053 	key_api_spdflush,	/* SADB_X_SPDFLUSH */
   7054 	key_api_spdadd,		/* SADB_X_SPDSETIDX */
   7055 	NULL,			/* SADB_X_SPDEXPIRE */
   7056 	key_api_spddelete2,	/* SADB_X_SPDDELETE2 */
   7057 	key_api_nat_map,	/* SADB_X_NAT_T_NEW_MAPPING */
   7058 };
   7059 
   7060 /*
   7061  * parse sadb_msg buffer to process PFKEYv2,
   7062  * and create a data to response if needed.
   7063  * I think to be dealed with mbuf directly.
   7064  * IN:
   7065  *     msgp  : pointer to pointer to a received buffer pulluped.
   7066  *             This is rewrited to response.
   7067  *     so    : pointer to socket.
   7068  * OUT:
   7069  *    length for buffer to send to user process.
   7070  */
   7071 int
   7072 key_parse(struct mbuf *m, struct socket *so)
   7073 {
   7074 	struct sadb_msg *msg;
   7075 	struct sadb_msghdr mh;
   7076 	u_int orglen;
   7077 	int error;
   7078 
   7079 	KASSERT(m != NULL);
   7080 	KASSERT(so != NULL);
   7081 
   7082 #if 0	/*kdebug_sadb assumes msg in linear buffer*/
   7083 	if (KEYDEBUG_ON(KEYDEBUG_KEY_DUMP)) {
   7084 		IPSECLOG(LOG_DEBUG, "passed sadb_msg\n");
   7085 		kdebug_sadb(msg);
   7086 	}
   7087 #endif
   7088 
   7089 	if (m->m_len < sizeof(struct sadb_msg)) {
   7090 		m = m_pullup(m, sizeof(struct sadb_msg));
   7091 		if (!m)
   7092 			return ENOBUFS;
   7093 	}
   7094 	msg = mtod(m, struct sadb_msg *);
   7095 	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
   7096 
   7097 	if ((m->m_flags & M_PKTHDR) == 0 ||
   7098 	    m->m_pkthdr.len != orglen) {
   7099 		IPSECLOG(LOG_DEBUG, "invalid message length.\n");
   7100 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7101 		error = EINVAL;
   7102 		goto senderror;
   7103 	}
   7104 
   7105 	if (msg->sadb_msg_version != PF_KEY_V2) {
   7106 		IPSECLOG(LOG_DEBUG, "PF_KEY version %u is mismatched.\n",
   7107 		    msg->sadb_msg_version);
   7108 		PFKEY_STATINC(PFKEY_STAT_OUT_INVVER);
   7109 		error = EINVAL;
   7110 		goto senderror;
   7111 	}
   7112 
   7113 	if (msg->sadb_msg_type > SADB_MAX) {
   7114 		IPSECLOG(LOG_DEBUG, "invalid type %u is passed.\n",
   7115 		    msg->sadb_msg_type);
   7116 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7117 		error = EINVAL;
   7118 		goto senderror;
   7119 	}
   7120 
   7121 	/* for old-fashioned code - should be nuked */
   7122 	if (m->m_pkthdr.len > MCLBYTES) {
   7123 		m_freem(m);
   7124 		return ENOBUFS;
   7125 	}
   7126 	if (m->m_next) {
   7127 		struct mbuf *n;
   7128 
   7129 		MGETHDR(n, M_DONTWAIT, MT_DATA);
   7130 		if (n && m->m_pkthdr.len > MHLEN) {
   7131 			MCLGET(n, M_DONTWAIT);
   7132 			if ((n->m_flags & M_EXT) == 0) {
   7133 				m_free(n);
   7134 				n = NULL;
   7135 			}
   7136 		}
   7137 		if (!n) {
   7138 			m_freem(m);
   7139 			return ENOBUFS;
   7140 		}
   7141 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, void *));
   7142 		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
   7143 		n->m_next = NULL;
   7144 		m_freem(m);
   7145 		m = n;
   7146 	}
   7147 
   7148 	/* align the mbuf chain so that extensions are in contiguous region. */
   7149 	error = key_align(m, &mh);
   7150 	if (error)
   7151 		return error;
   7152 
   7153 	if (m->m_next) {	/*XXX*/
   7154 		m_freem(m);
   7155 		return ENOBUFS;
   7156 	}
   7157 
   7158 	msg = mh.msg;
   7159 
   7160 	/* check SA type */
   7161 	switch (msg->sadb_msg_satype) {
   7162 	case SADB_SATYPE_UNSPEC:
   7163 		switch (msg->sadb_msg_type) {
   7164 		case SADB_GETSPI:
   7165 		case SADB_UPDATE:
   7166 		case SADB_ADD:
   7167 		case SADB_DELETE:
   7168 		case SADB_GET:
   7169 		case SADB_ACQUIRE:
   7170 		case SADB_EXPIRE:
   7171 			IPSECLOG(LOG_DEBUG,
   7172 			    "must specify satype when msg type=%u.\n",
   7173 			    msg->sadb_msg_type);
   7174 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7175 			error = EINVAL;
   7176 			goto senderror;
   7177 		}
   7178 		break;
   7179 	case SADB_SATYPE_AH:
   7180 	case SADB_SATYPE_ESP:
   7181 	case SADB_X_SATYPE_IPCOMP:
   7182 	case SADB_X_SATYPE_TCPSIGNATURE:
   7183 		switch (msg->sadb_msg_type) {
   7184 		case SADB_X_SPDADD:
   7185 		case SADB_X_SPDDELETE:
   7186 		case SADB_X_SPDGET:
   7187 		case SADB_X_SPDDUMP:
   7188 		case SADB_X_SPDFLUSH:
   7189 		case SADB_X_SPDSETIDX:
   7190 		case SADB_X_SPDUPDATE:
   7191 		case SADB_X_SPDDELETE2:
   7192 			IPSECLOG(LOG_DEBUG, "illegal satype=%u\n",
   7193 			    msg->sadb_msg_type);
   7194 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7195 			error = EINVAL;
   7196 			goto senderror;
   7197 		}
   7198 		break;
   7199 	case SADB_SATYPE_RSVP:
   7200 	case SADB_SATYPE_OSPFV2:
   7201 	case SADB_SATYPE_RIPV2:
   7202 	case SADB_SATYPE_MIP:
   7203 		IPSECLOG(LOG_DEBUG, "type %u isn't supported.\n",
   7204 		    msg->sadb_msg_satype);
   7205 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7206 		error = EOPNOTSUPP;
   7207 		goto senderror;
   7208 	case 1:	/* XXX: What does it do? */
   7209 		if (msg->sadb_msg_type == SADB_X_PROMISC)
   7210 			break;
   7211 		/*FALLTHROUGH*/
   7212 	default:
   7213 		IPSECLOG(LOG_DEBUG, "invalid type %u is passed.\n",
   7214 		    msg->sadb_msg_satype);
   7215 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7216 		error = EINVAL;
   7217 		goto senderror;
   7218 	}
   7219 
   7220 	/* check field of upper layer protocol and address family */
   7221 	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL &&
   7222 	    mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
   7223 		struct sadb_address *src0, *dst0;
   7224 		u_int plen;
   7225 
   7226 		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
   7227 		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
   7228 
   7229 		/* check upper layer protocol */
   7230 		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
   7231 			IPSECLOG(LOG_DEBUG, "upper layer protocol mismatched.\n");
   7232 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7233 			error = EINVAL;
   7234 			goto senderror;
   7235 		}
   7236 
   7237 		/* check family */
   7238 		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
   7239 		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
   7240 			IPSECLOG(LOG_DEBUG, "address family mismatched.\n");
   7241 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7242 			error = EINVAL;
   7243 			goto senderror;
   7244 		}
   7245 		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7246 		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
   7247 			IPSECLOG(LOG_DEBUG,
   7248 			    "address struct size mismatched.\n");
   7249 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7250 			error = EINVAL;
   7251 			goto senderror;
   7252 		}
   7253 
   7254 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7255 		case AF_INET:
   7256 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7257 			    sizeof(struct sockaddr_in)) {
   7258 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7259 				error = EINVAL;
   7260 				goto senderror;
   7261 			}
   7262 			break;
   7263 		case AF_INET6:
   7264 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7265 			    sizeof(struct sockaddr_in6)) {
   7266 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7267 				error = EINVAL;
   7268 				goto senderror;
   7269 			}
   7270 			break;
   7271 		default:
   7272 			IPSECLOG(LOG_DEBUG, "unsupported address family.\n");
   7273 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7274 			error = EAFNOSUPPORT;
   7275 			goto senderror;
   7276 		}
   7277 
   7278 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7279 		case AF_INET:
   7280 			plen = sizeof(struct in_addr) << 3;
   7281 			break;
   7282 		case AF_INET6:
   7283 			plen = sizeof(struct in6_addr) << 3;
   7284 			break;
   7285 		default:
   7286 			plen = 0;	/*fool gcc*/
   7287 			break;
   7288 		}
   7289 
   7290 		/* check max prefix length */
   7291 		if (src0->sadb_address_prefixlen > plen ||
   7292 		    dst0->sadb_address_prefixlen > plen) {
   7293 			IPSECLOG(LOG_DEBUG, "illegal prefixlen.\n");
   7294 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7295 			error = EINVAL;
   7296 			goto senderror;
   7297 		}
   7298 
   7299 		/*
   7300 		 * prefixlen == 0 is valid because there can be a case when
   7301 		 * all addresses are matched.
   7302 		 */
   7303 	}
   7304 
   7305 	if (msg->sadb_msg_type >= __arraycount(key_api_typesw) ||
   7306 	    key_api_typesw[msg->sadb_msg_type] == NULL) {
   7307 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7308 		error = EINVAL;
   7309 		goto senderror;
   7310 	}
   7311 
   7312 	return (*key_api_typesw[msg->sadb_msg_type])(so, m, &mh);
   7313 
   7314 senderror:
   7315 	return key_senderror(so, m, error);
   7316 }
   7317 
   7318 static int
   7319 key_senderror(struct socket *so, struct mbuf *m, int code)
   7320 {
   7321 	struct sadb_msg *msg;
   7322 
   7323 	KASSERT(m->m_len >= sizeof(struct sadb_msg));
   7324 
   7325 	msg = mtod(m, struct sadb_msg *);
   7326 	msg->sadb_msg_errno = code;
   7327 	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   7328 }
   7329 
   7330 /*
   7331  * set the pointer to each header into message buffer.
   7332  * m will be freed on error.
   7333  * XXX larger-than-MCLBYTES extension?
   7334  */
   7335 static int
   7336 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
   7337 {
   7338 	struct mbuf *n;
   7339 	struct sadb_ext *ext;
   7340 	size_t off, end;
   7341 	int extlen;
   7342 	int toff;
   7343 
   7344 	KASSERT(m != NULL);
   7345 	KASSERT(mhp != NULL);
   7346 	KASSERT(m->m_len >= sizeof(struct sadb_msg));
   7347 
   7348 	/* initialize */
   7349 	memset(mhp, 0, sizeof(*mhp));
   7350 
   7351 	mhp->msg = mtod(m, struct sadb_msg *);
   7352 	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
   7353 
   7354 	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   7355 	extlen = end;	/*just in case extlen is not updated*/
   7356 	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
   7357 		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
   7358 		if (!n) {
   7359 			/* m is already freed */
   7360 			return ENOBUFS;
   7361 		}
   7362 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7363 
   7364 		/* set pointer */
   7365 		switch (ext->sadb_ext_type) {
   7366 		case SADB_EXT_SA:
   7367 		case SADB_EXT_ADDRESS_SRC:
   7368 		case SADB_EXT_ADDRESS_DST:
   7369 		case SADB_EXT_ADDRESS_PROXY:
   7370 		case SADB_EXT_LIFETIME_CURRENT:
   7371 		case SADB_EXT_LIFETIME_HARD:
   7372 		case SADB_EXT_LIFETIME_SOFT:
   7373 		case SADB_EXT_KEY_AUTH:
   7374 		case SADB_EXT_KEY_ENCRYPT:
   7375 		case SADB_EXT_IDENTITY_SRC:
   7376 		case SADB_EXT_IDENTITY_DST:
   7377 		case SADB_EXT_SENSITIVITY:
   7378 		case SADB_EXT_PROPOSAL:
   7379 		case SADB_EXT_SUPPORTED_AUTH:
   7380 		case SADB_EXT_SUPPORTED_ENCRYPT:
   7381 		case SADB_EXT_SPIRANGE:
   7382 		case SADB_X_EXT_POLICY:
   7383 		case SADB_X_EXT_SA2:
   7384 		case SADB_X_EXT_NAT_T_TYPE:
   7385 		case SADB_X_EXT_NAT_T_SPORT:
   7386 		case SADB_X_EXT_NAT_T_DPORT:
   7387 		case SADB_X_EXT_NAT_T_OAI:
   7388 		case SADB_X_EXT_NAT_T_OAR:
   7389 		case SADB_X_EXT_NAT_T_FRAG:
   7390 			/* duplicate check */
   7391 			/*
   7392 			 * XXX Are there duplication payloads of either
   7393 			 * KEY_AUTH or KEY_ENCRYPT ?
   7394 			 */
   7395 			if (mhp->ext[ext->sadb_ext_type] != NULL) {
   7396 				IPSECLOG(LOG_DEBUG,
   7397 				    "duplicate ext_type %u is passed.\n",
   7398 				    ext->sadb_ext_type);
   7399 				m_freem(m);
   7400 				PFKEY_STATINC(PFKEY_STAT_OUT_DUPEXT);
   7401 				return EINVAL;
   7402 			}
   7403 			break;
   7404 		default:
   7405 			IPSECLOG(LOG_DEBUG, "invalid ext_type %u is passed.\n",
   7406 			    ext->sadb_ext_type);
   7407 			m_freem(m);
   7408 			PFKEY_STATINC(PFKEY_STAT_OUT_INVEXTTYPE);
   7409 			return EINVAL;
   7410 		}
   7411 
   7412 		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
   7413 
   7414 		if (key_validate_ext(ext, extlen)) {
   7415 			m_freem(m);
   7416 			PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7417 			return EINVAL;
   7418 		}
   7419 
   7420 		n = m_pulldown(m, off, extlen, &toff);
   7421 		if (!n) {
   7422 			/* m is already freed */
   7423 			return ENOBUFS;
   7424 		}
   7425 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7426 
   7427 		mhp->ext[ext->sadb_ext_type] = ext;
   7428 		mhp->extoff[ext->sadb_ext_type] = off;
   7429 		mhp->extlen[ext->sadb_ext_type] = extlen;
   7430 	}
   7431 
   7432 	if (off != end) {
   7433 		m_freem(m);
   7434 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7435 		return EINVAL;
   7436 	}
   7437 
   7438 	return 0;
   7439 }
   7440 
   7441 static int
   7442 key_validate_ext(const struct sadb_ext *ext, int len)
   7443 {
   7444 	const struct sockaddr *sa;
   7445 	enum { NONE, ADDR } checktype = NONE;
   7446 	int baselen = 0;
   7447 	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
   7448 
   7449 	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
   7450 		return EINVAL;
   7451 
   7452 	/* if it does not match minimum/maximum length, bail */
   7453 	if (ext->sadb_ext_type >= __arraycount(minsize) ||
   7454 	    ext->sadb_ext_type >= __arraycount(maxsize))
   7455 		return EINVAL;
   7456 	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
   7457 		return EINVAL;
   7458 	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
   7459 		return EINVAL;
   7460 
   7461 	/* more checks based on sadb_ext_type XXX need more */
   7462 	switch (ext->sadb_ext_type) {
   7463 	case SADB_EXT_ADDRESS_SRC:
   7464 	case SADB_EXT_ADDRESS_DST:
   7465 	case SADB_EXT_ADDRESS_PROXY:
   7466 		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
   7467 		checktype = ADDR;
   7468 		break;
   7469 	case SADB_EXT_IDENTITY_SRC:
   7470 	case SADB_EXT_IDENTITY_DST:
   7471 		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
   7472 		    SADB_X_IDENTTYPE_ADDR) {
   7473 			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
   7474 			checktype = ADDR;
   7475 		} else
   7476 			checktype = NONE;
   7477 		break;
   7478 	default:
   7479 		checktype = NONE;
   7480 		break;
   7481 	}
   7482 
   7483 	switch (checktype) {
   7484 	case NONE:
   7485 		break;
   7486 	case ADDR:
   7487 		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
   7488 		if (len < baselen + sal)
   7489 			return EINVAL;
   7490 		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
   7491 			return EINVAL;
   7492 		break;
   7493 	}
   7494 
   7495 	return 0;
   7496 }
   7497 
   7498 static int
   7499 key_do_init(void)
   7500 {
   7501 	int i, error;
   7502 
   7503 	mutex_init(&key_mtx, MUTEX_DEFAULT, IPL_NONE);
   7504 
   7505 	pfkeystat_percpu = percpu_alloc(sizeof(uint64_t) * PFKEY_NSTATS);
   7506 
   7507 	callout_init(&key_timehandler_ch, 0);
   7508 	error = workqueue_create(&key_timehandler_wq, "key_timehandler",
   7509 	    key_timehandler_work, NULL, PRI_SOFTNET, IPL_SOFTNET, WQ_MPSAFE);
   7510 	if (error != 0)
   7511 		panic("%s: workqueue_create failed (%d)\n", __func__, error);
   7512 
   7513 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
   7514 		LIST_INIT(&sptree[i]);
   7515 	}
   7516 
   7517 	LIST_INIT(&sahtree);
   7518 
   7519 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   7520 		LIST_INIT(&regtree[i]);
   7521 	}
   7522 
   7523 #ifndef IPSEC_NONBLOCK_ACQUIRE
   7524 	LIST_INIT(&acqtree);
   7525 #endif
   7526 #ifdef notyet
   7527 	LIST_INIT(&spacqtree);
   7528 #endif
   7529 
   7530 	/* system default */
   7531 	ip4_def_policy.policy = IPSEC_POLICY_NONE;
   7532 	ip4_def_policy.refcnt++;	/*never reclaim this*/
   7533 
   7534 #ifdef INET6
   7535 	ip6_def_policy.policy = IPSEC_POLICY_NONE;
   7536 	ip6_def_policy.refcnt++;	/*never reclaim this*/
   7537 #endif
   7538 
   7539 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   7540 
   7541 	/* initialize key statistics */
   7542 	keystat.getspi_count = 1;
   7543 
   7544 	aprint_verbose("IPsec: Initialized Security Association Processing.\n");
   7545 
   7546 	return (0);
   7547 }
   7548 
   7549 void
   7550 key_init(void)
   7551 {
   7552 	static ONCE_DECL(key_init_once);
   7553 
   7554 	sysctl_net_keyv2_setup(NULL);
   7555 	sysctl_net_key_compat_setup(NULL);
   7556 
   7557 	RUN_ONCE(&key_init_once, key_do_init);
   7558 }
   7559 
   7560 /*
   7561  * XXX: maybe This function is called after INBOUND IPsec processing.
   7562  *
   7563  * Special check for tunnel-mode packets.
   7564  * We must make some checks for consistency between inner and outer IP header.
   7565  *
   7566  * xxx more checks to be provided
   7567  */
   7568 int
   7569 key_checktunnelsanity(
   7570     struct secasvar *sav,
   7571     u_int family,
   7572     void *src,
   7573     void *dst
   7574 )
   7575 {
   7576 
   7577 	/* XXX: check inner IP header */
   7578 
   7579 	return 1;
   7580 }
   7581 
   7582 #if 0
   7583 #define hostnamelen	strlen(hostname)
   7584 
   7585 /*
   7586  * Get FQDN for the host.
   7587  * If the administrator configured hostname (by hostname(1)) without
   7588  * domain name, returns nothing.
   7589  */
   7590 static const char *
   7591 key_getfqdn(void)
   7592 {
   7593 	int i;
   7594 	int hasdot;
   7595 	static char fqdn[MAXHOSTNAMELEN + 1];
   7596 
   7597 	if (!hostnamelen)
   7598 		return NULL;
   7599 
   7600 	/* check if it comes with domain name. */
   7601 	hasdot = 0;
   7602 	for (i = 0; i < hostnamelen; i++) {
   7603 		if (hostname[i] == '.')
   7604 			hasdot++;
   7605 	}
   7606 	if (!hasdot)
   7607 		return NULL;
   7608 
   7609 	/* NOTE: hostname may not be NUL-terminated. */
   7610 	memset(fqdn, 0, sizeof(fqdn));
   7611 	memcpy(fqdn, hostname, hostnamelen);
   7612 	fqdn[hostnamelen] = '\0';
   7613 	return fqdn;
   7614 }
   7615 
   7616 /*
   7617  * get username@FQDN for the host/user.
   7618  */
   7619 static const char *
   7620 key_getuserfqdn(void)
   7621 {
   7622 	const char *host;
   7623 	static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
   7624 	struct proc *p = curproc;
   7625 	char *q;
   7626 
   7627 	if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
   7628 		return NULL;
   7629 	if (!(host = key_getfqdn()))
   7630 		return NULL;
   7631 
   7632 	/* NOTE: s_login may not be-NUL terminated. */
   7633 	memset(userfqdn, 0, sizeof(userfqdn));
   7634 	memcpy(userfqdn, Mp->p_pgrp->pg_session->s_login, AXLOGNAME);
   7635 	userfqdn[MAXLOGNAME] = '\0';	/* safeguard */
   7636 	q = userfqdn + strlen(userfqdn);
   7637 	*q++ = '@';
   7638 	memcpy(q, host, strlen(host));
   7639 	q += strlen(host);
   7640 	*q++ = '\0';
   7641 
   7642 	return userfqdn;
   7643 }
   7644 #endif
   7645 
   7646 /* record data transfer on SA, and update timestamps */
   7647 void
   7648 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
   7649 {
   7650 
   7651 	KASSERT(sav != NULL);
   7652 	KASSERT(sav->lft_c != NULL);
   7653 	KASSERT(m != NULL);
   7654 
   7655 	/*
   7656 	 * XXX Currently, there is a difference of bytes size
   7657 	 * between inbound and outbound processing.
   7658 	 */
   7659 	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
   7660 	/* to check bytes lifetime is done in key_timehandler(). */
   7661 
   7662 	/*
   7663 	 * We use the number of packets as the unit of
   7664 	 * sadb_lifetime_allocations.  We increment the variable
   7665 	 * whenever {esp,ah}_{in,out}put is called.
   7666 	 */
   7667 	sav->lft_c->sadb_lifetime_allocations++;
   7668 	/* XXX check for expires? */
   7669 
   7670 	/*
   7671 	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
   7672 	 * in seconds.  HARD and SOFT lifetime are measured by the time
   7673 	 * difference (again in seconds) from sadb_lifetime_usetime.
   7674 	 *
   7675 	 *	usetime
   7676 	 *	v     expire   expire
   7677 	 * -----+-----+--------+---> t
   7678 	 *	<--------------> HARD
   7679 	 *	<-----> SOFT
   7680 	 */
   7681 	sav->lft_c->sadb_lifetime_usetime = time_uptime;
   7682 	/* XXX check for expires? */
   7683 
   7684 	return;
   7685 }
   7686 
   7687 /* dumb version */
   7688 void
   7689 key_sa_routechange(struct sockaddr *dst)
   7690 {
   7691 	struct secashead *sah;
   7692 	struct route *ro;
   7693 	const struct sockaddr *sa;
   7694 
   7695 	LIST_FOREACH(sah, &sahtree, chain) {
   7696 		ro = &sah->sa_route;
   7697 		sa = rtcache_getdst(ro);
   7698 		if (sa != NULL && dst->sa_len == sa->sa_len &&
   7699 		    memcmp(dst, sa, dst->sa_len) == 0)
   7700 			rtcache_free(ro);
   7701 	}
   7702 
   7703 	return;
   7704 }
   7705 
   7706 static void
   7707 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
   7708 {
   7709 	struct secasvar *_sav;
   7710 
   7711 	KASSERT(sav != NULL);
   7712 
   7713 	if (sav->state == state)
   7714 		return;
   7715 
   7716 	KASSERT(__LIST_CHAINED(sav));
   7717 	LIST_REMOVE(sav, chain);
   7718 
   7719 	sav->state = state;
   7720 	if (!SADB_SASTATE_USABLE_P(sav)) {
   7721 		/* We don't need to care about the order */
   7722 		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
   7723 		return;
   7724 	}
   7725 	/*
   7726 	 * Sort the list by lft_c->sadb_lifetime_addtime
   7727 	 * in ascending order.
   7728 	 */
   7729 	LIST_FOREACH(_sav, &sav->sah->savtree[state], chain) {
   7730 		if (_sav->lft_c->sadb_lifetime_addtime >
   7731 		    sav->lft_c->sadb_lifetime_addtime) {
   7732 			LIST_INSERT_BEFORE(_sav, sav, chain);
   7733 			break;
   7734 		}
   7735 	}
   7736 	if (_sav == NULL) {
   7737 		LIST_INSERT_TAIL(&sav->sah->savtree[state], sav, secasvar,
   7738 		    chain);
   7739 	}
   7740 	key_validate_savlist(sav->sah, state);
   7741 }
   7742 
   7743 /* XXX too much? */
   7744 static struct mbuf *
   7745 key_alloc_mbuf(int l)
   7746 {
   7747 	struct mbuf *m = NULL, *n;
   7748 	int len, t;
   7749 
   7750 	len = l;
   7751 	while (len > 0) {
   7752 		MGET(n, M_DONTWAIT, MT_DATA);
   7753 		if (n && len > MLEN)
   7754 			MCLGET(n, M_DONTWAIT);
   7755 		if (!n) {
   7756 			m_freem(m);
   7757 			return NULL;
   7758 		}
   7759 
   7760 		n->m_next = NULL;
   7761 		n->m_len = 0;
   7762 		n->m_len = M_TRAILINGSPACE(n);
   7763 		/* use the bottom of mbuf, hoping we can prepend afterwards */
   7764 		if (n->m_len > len) {
   7765 			t = (n->m_len - len) & ~(sizeof(long) - 1);
   7766 			n->m_data += t;
   7767 			n->m_len = len;
   7768 		}
   7769 
   7770 		len -= n->m_len;
   7771 
   7772 		if (m)
   7773 			m_cat(m, n);
   7774 		else
   7775 			m = n;
   7776 	}
   7777 
   7778 	return m;
   7779 }
   7780 
   7781 static struct mbuf *
   7782 key_setdump(u_int8_t req_satype, int *errorp, uint32_t pid)
   7783 {
   7784 	struct secashead *sah;
   7785 	struct secasvar *sav;
   7786 	u_int16_t proto;
   7787 	u_int8_t satype;
   7788 	u_int8_t state;
   7789 	int cnt;
   7790 	struct mbuf *m, *n;
   7791 
   7792 	/* map satype to proto */
   7793 	proto = key_satype2proto(req_satype);
   7794 	if (proto == 0) {
   7795 		*errorp = EINVAL;
   7796 		return (NULL);
   7797 	}
   7798 
   7799 	/* count sav entries to be sent to the userland. */
   7800 	cnt = 0;
   7801 	LIST_FOREACH(sah, &sahtree, chain) {
   7802 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7803 		    proto != sah->saidx.proto)
   7804 			continue;
   7805 
   7806 		SASTATE_ANY_FOREACH(state) {
   7807 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   7808 				cnt++;
   7809 			}
   7810 		}
   7811 	}
   7812 
   7813 	if (cnt == 0) {
   7814 		*errorp = ENOENT;
   7815 		return (NULL);
   7816 	}
   7817 
   7818 	/* send this to the userland, one at a time. */
   7819 	m = NULL;
   7820 	LIST_FOREACH(sah, &sahtree, chain) {
   7821 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7822 		    proto != sah->saidx.proto)
   7823 			continue;
   7824 
   7825 		/* map proto to satype */
   7826 		satype = key_proto2satype(sah->saidx.proto);
   7827 		if (satype == 0) {
   7828 			m_freem(m);
   7829 			*errorp = EINVAL;
   7830 			return (NULL);
   7831 		}
   7832 
   7833 		SASTATE_ANY_FOREACH(state) {
   7834 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   7835 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   7836 				    --cnt, pid);
   7837 				if (!n) {
   7838 					m_freem(m);
   7839 					*errorp = ENOBUFS;
   7840 					return (NULL);
   7841 				}
   7842 
   7843 				if (!m)
   7844 					m = n;
   7845 				else
   7846 					m_cat(m, n);
   7847 			}
   7848 		}
   7849 	}
   7850 
   7851 	if (!m) {
   7852 		*errorp = EINVAL;
   7853 		return (NULL);
   7854 	}
   7855 
   7856 	if ((m->m_flags & M_PKTHDR) != 0) {
   7857 		m->m_pkthdr.len = 0;
   7858 		for (n = m; n; n = n->m_next)
   7859 			m->m_pkthdr.len += n->m_len;
   7860 	}
   7861 
   7862 	*errorp = 0;
   7863 	return (m);
   7864 }
   7865 
   7866 static struct mbuf *
   7867 key_setspddump(int *errorp, pid_t pid)
   7868 {
   7869 	struct secpolicy *sp;
   7870 	int cnt;
   7871 	u_int dir;
   7872 	struct mbuf *m, *n;
   7873 
   7874 	/* search SPD entry and get buffer size. */
   7875 	cnt = 0;
   7876 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   7877 		LIST_FOREACH(sp, &sptree[dir], chain) {
   7878 			cnt++;
   7879 		}
   7880 	}
   7881 
   7882 	if (cnt == 0) {
   7883 		*errorp = ENOENT;
   7884 		return (NULL);
   7885 	}
   7886 
   7887 	m = NULL;
   7888 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   7889 		LIST_FOREACH(sp, &sptree[dir], chain) {
   7890 			--cnt;
   7891 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
   7892 
   7893 			if (!n) {
   7894 				*errorp = ENOBUFS;
   7895 				m_freem(m);
   7896 				return (NULL);
   7897 			}
   7898 			if (!m)
   7899 				m = n;
   7900 			else {
   7901 				m->m_pkthdr.len += n->m_pkthdr.len;
   7902 				m_cat(m, n);
   7903 			}
   7904 		}
   7905 	}
   7906 
   7907 	*errorp = 0;
   7908 	return (m);
   7909 }
   7910 
   7911 int
   7912 key_get_used(void) {
   7913 	return !LIST_EMPTY(&sptree[IPSEC_DIR_INBOUND]) ||
   7914 	    !LIST_EMPTY(&sptree[IPSEC_DIR_OUTBOUND]);
   7915 }
   7916 
   7917 void
   7918 key_update_used(void)
   7919 {
   7920 	switch (ipsec_enabled) {
   7921 	default:
   7922 	case 0:
   7923 #ifdef notyet
   7924 		/* XXX: racy */
   7925 		ipsec_used = 0;
   7926 #endif
   7927 		break;
   7928 	case 1:
   7929 #ifndef notyet
   7930 		/* XXX: racy */
   7931 		if (!ipsec_used)
   7932 #endif
   7933 		ipsec_used = key_get_used();
   7934 		break;
   7935 	case 2:
   7936 		ipsec_used = 1;
   7937 		break;
   7938 	}
   7939 }
   7940 
   7941 static int
   7942 sysctl_net_key_dumpsa(SYSCTLFN_ARGS)
   7943 {
   7944 	struct mbuf *m, *n;
   7945 	int err2 = 0;
   7946 	char *p, *ep;
   7947 	size_t len;
   7948 	int s, error;
   7949 
   7950 	if (newp)
   7951 		return (EPERM);
   7952 	if (namelen != 1)
   7953 		return (EINVAL);
   7954 
   7955 	s = splsoftnet();
   7956 	m = key_setdump(name[0], &error, l->l_proc->p_pid);
   7957 	splx(s);
   7958 	if (!m)
   7959 		return (error);
   7960 	if (!oldp)
   7961 		*oldlenp = m->m_pkthdr.len;
   7962 	else {
   7963 		p = oldp;
   7964 		if (*oldlenp < m->m_pkthdr.len) {
   7965 			err2 = ENOMEM;
   7966 			ep = p + *oldlenp;
   7967 		} else {
   7968 			*oldlenp = m->m_pkthdr.len;
   7969 			ep = p + m->m_pkthdr.len;
   7970 		}
   7971 		for (n = m; n; n = n->m_next) {
   7972 			len =  (ep - p < n->m_len) ?
   7973 				ep - p : n->m_len;
   7974 			error = copyout(mtod(n, const void *), p, len);
   7975 			p += len;
   7976 			if (error)
   7977 				break;
   7978 		}
   7979 		if (error == 0)
   7980 			error = err2;
   7981 	}
   7982 	m_freem(m);
   7983 
   7984 	return (error);
   7985 }
   7986 
   7987 static int
   7988 sysctl_net_key_dumpsp(SYSCTLFN_ARGS)
   7989 {
   7990 	struct mbuf *m, *n;
   7991 	int err2 = 0;
   7992 	char *p, *ep;
   7993 	size_t len;
   7994 	int s, error;
   7995 
   7996 	if (newp)
   7997 		return (EPERM);
   7998 	if (namelen != 0)
   7999 		return (EINVAL);
   8000 
   8001 	s = splsoftnet();
   8002 	m = key_setspddump(&error, l->l_proc->p_pid);
   8003 	splx(s);
   8004 	if (!m)
   8005 		return (error);
   8006 	if (!oldp)
   8007 		*oldlenp = m->m_pkthdr.len;
   8008 	else {
   8009 		p = oldp;
   8010 		if (*oldlenp < m->m_pkthdr.len) {
   8011 			err2 = ENOMEM;
   8012 			ep = p + *oldlenp;
   8013 		} else {
   8014 			*oldlenp = m->m_pkthdr.len;
   8015 			ep = p + m->m_pkthdr.len;
   8016 		}
   8017 		for (n = m; n; n = n->m_next) {
   8018 			len = (ep - p < n->m_len) ? ep - p : n->m_len;
   8019 			error = copyout(mtod(n, const void *), p, len);
   8020 			p += len;
   8021 			if (error)
   8022 				break;
   8023 		}
   8024 		if (error == 0)
   8025 			error = err2;
   8026 	}
   8027 	m_freem(m);
   8028 
   8029 	return (error);
   8030 }
   8031 
   8032 /*
   8033  * Create sysctl tree for native IPSEC key knobs, originally
   8034  * under name "net.keyv2"  * with MIB number { CTL_NET, PF_KEY_V2. }.
   8035  * However, sysctl(8) never checked for nodes under { CTL_NET, PF_KEY_V2 };
   8036  * and in any case the part of our sysctl namespace used for dumping the
   8037  * SPD and SA database  *HAS* to be compatible with the KAME sysctl
   8038  * namespace, for API reasons.
   8039  *
   8040  * Pending a consensus on the right way  to fix this, add a level of
   8041  * indirection in how we number the `native' IPSEC key nodes;
   8042  * and (as requested by Andrew Brown)  move registration of the
   8043  * KAME-compatible names  to a separate function.
   8044  */
   8045 #if 0
   8046 #  define IPSEC_PFKEY PF_KEY_V2
   8047 # define IPSEC_PFKEY_NAME "keyv2"
   8048 #else
   8049 #  define IPSEC_PFKEY PF_KEY
   8050 # define IPSEC_PFKEY_NAME "key"
   8051 #endif
   8052 
   8053 static int
   8054 sysctl_net_key_stats(SYSCTLFN_ARGS)
   8055 {
   8056 
   8057 	return (NETSTAT_SYSCTL(pfkeystat_percpu, PFKEY_NSTATS));
   8058 }
   8059 
   8060 static void
   8061 sysctl_net_keyv2_setup(struct sysctllog **clog)
   8062 {
   8063 
   8064 	sysctl_createv(clog, 0, NULL, NULL,
   8065 		       CTLFLAG_PERMANENT,
   8066 		       CTLTYPE_NODE, IPSEC_PFKEY_NAME, NULL,
   8067 		       NULL, 0, NULL, 0,
   8068 		       CTL_NET, IPSEC_PFKEY, CTL_EOL);
   8069 
   8070 	sysctl_createv(clog, 0, NULL, NULL,
   8071 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8072 		       CTLTYPE_INT, "debug", NULL,
   8073 		       NULL, 0, &key_debug_level, 0,
   8074 		       CTL_NET, IPSEC_PFKEY, KEYCTL_DEBUG_LEVEL, CTL_EOL);
   8075 	sysctl_createv(clog, 0, NULL, NULL,
   8076 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8077 		       CTLTYPE_INT, "spi_try", NULL,
   8078 		       NULL, 0, &key_spi_trycnt, 0,
   8079 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_TRY, CTL_EOL);
   8080 	sysctl_createv(clog, 0, NULL, NULL,
   8081 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8082 		       CTLTYPE_INT, "spi_min_value", NULL,
   8083 		       NULL, 0, &key_spi_minval, 0,
   8084 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MIN_VALUE, CTL_EOL);
   8085 	sysctl_createv(clog, 0, NULL, NULL,
   8086 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8087 		       CTLTYPE_INT, "spi_max_value", NULL,
   8088 		       NULL, 0, &key_spi_maxval, 0,
   8089 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MAX_VALUE, CTL_EOL);
   8090 	sysctl_createv(clog, 0, NULL, NULL,
   8091 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8092 		       CTLTYPE_INT, "random_int", NULL,
   8093 		       NULL, 0, &key_int_random, 0,
   8094 		       CTL_NET, IPSEC_PFKEY, KEYCTL_RANDOM_INT, CTL_EOL);
   8095 	sysctl_createv(clog, 0, NULL, NULL,
   8096 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8097 		       CTLTYPE_INT, "larval_lifetime", NULL,
   8098 		       NULL, 0, &key_larval_lifetime, 0,
   8099 		       CTL_NET, IPSEC_PFKEY, KEYCTL_LARVAL_LIFETIME, CTL_EOL);
   8100 	sysctl_createv(clog, 0, NULL, NULL,
   8101 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8102 		       CTLTYPE_INT, "blockacq_count", NULL,
   8103 		       NULL, 0, &key_blockacq_count, 0,
   8104 		       CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_COUNT, CTL_EOL);
   8105 	sysctl_createv(clog, 0, NULL, NULL,
   8106 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8107 		       CTLTYPE_INT, "blockacq_lifetime", NULL,
   8108 		       NULL, 0, &key_blockacq_lifetime, 0,
   8109 		       CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_LIFETIME, CTL_EOL);
   8110 	sysctl_createv(clog, 0, NULL, NULL,
   8111 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8112 		       CTLTYPE_INT, "esp_keymin", NULL,
   8113 		       NULL, 0, &ipsec_esp_keymin, 0,
   8114 		       CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_KEYMIN, CTL_EOL);
   8115 	sysctl_createv(clog, 0, NULL, NULL,
   8116 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8117 		       CTLTYPE_INT, "prefered_oldsa", NULL,
   8118 		       NULL, 0, &key_prefered_oldsa, 0,
   8119 		       CTL_NET, PF_KEY, KEYCTL_PREFERED_OLDSA, CTL_EOL);
   8120 	sysctl_createv(clog, 0, NULL, NULL,
   8121 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8122 		       CTLTYPE_INT, "esp_auth", NULL,
   8123 		       NULL, 0, &ipsec_esp_auth, 0,
   8124 		       CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_AUTH, CTL_EOL);
   8125 	sysctl_createv(clog, 0, NULL, NULL,
   8126 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8127 		       CTLTYPE_INT, "ah_keymin", NULL,
   8128 		       NULL, 0, &ipsec_ah_keymin, 0,
   8129 		       CTL_NET, IPSEC_PFKEY, KEYCTL_AH_KEYMIN, CTL_EOL);
   8130 	sysctl_createv(clog, 0, NULL, NULL,
   8131 		       CTLFLAG_PERMANENT,
   8132 		       CTLTYPE_STRUCT, "stats",
   8133 		       SYSCTL_DESCR("PF_KEY statistics"),
   8134 		       sysctl_net_key_stats, 0, NULL, 0,
   8135 		       CTL_NET, IPSEC_PFKEY, CTL_CREATE, CTL_EOL);
   8136 }
   8137 
   8138 /*
   8139  * Register sysctl names used by setkey(8). For historical reasons,
   8140  * and to share a single API, these names appear under { CTL_NET, PF_KEY }
   8141  * for both IPSEC and KAME IPSEC.
   8142  */
   8143 static void
   8144 sysctl_net_key_compat_setup(struct sysctllog **clog)
   8145 {
   8146 
   8147 	sysctl_createv(clog, 0, NULL, NULL,
   8148 		       CTLFLAG_PERMANENT,
   8149 		       CTLTYPE_NODE, "key", NULL,
   8150 		       NULL, 0, NULL, 0,
   8151 		       CTL_NET, PF_KEY, CTL_EOL);
   8152 
   8153 	/* Register the net.key.dump{sa,sp} nodes used by setkey(8). */
   8154 	sysctl_createv(clog, 0, NULL, NULL,
   8155 		       CTLFLAG_PERMANENT,
   8156 		       CTLTYPE_STRUCT, "dumpsa", NULL,
   8157 		       sysctl_net_key_dumpsa, 0, NULL, 0,
   8158 		       CTL_NET, PF_KEY, KEYCTL_DUMPSA, CTL_EOL);
   8159 	sysctl_createv(clog, 0, NULL, NULL,
   8160 		       CTLFLAG_PERMANENT,
   8161 		       CTLTYPE_STRUCT, "dumpsp", NULL,
   8162 		       sysctl_net_key_dumpsp, 0, NULL, 0,
   8163 		       CTL_NET, PF_KEY, KEYCTL_DUMPSP, CTL_EOL);
   8164 }
   8165