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