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