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