Home | History | Annotate | Line # | Download | only in netipsec
key.c revision 1.174
      1 /*	$NetBSD: key.c,v 1.174 2017/07/11 04:55:39 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.174 2017/07/11 04:55:39 ozaki-r Exp $");
     36 
     37 /*
     38  * This code is referd to RFC 2367
     39  */
     40 
     41 #if defined(_KERNEL_OPT)
     42 #include "opt_inet.h"
     43 #include "opt_ipsec.h"
     44 #include "opt_gateway.h"
     45 #endif
     46 
     47 #include <sys/types.h>
     48 #include <sys/param.h>
     49 #include <sys/systm.h>
     50 #include <sys/callout.h>
     51 #include <sys/kernel.h>
     52 #include <sys/mbuf.h>
     53 #include <sys/domain.h>
     54 #include <sys/socket.h>
     55 #include <sys/socketvar.h>
     56 #include <sys/sysctl.h>
     57 #include <sys/errno.h>
     58 #include <sys/proc.h>
     59 #include <sys/queue.h>
     60 #include <sys/syslog.h>
     61 #include <sys/once.h>
     62 #include <sys/cprng.h>
     63 #include <sys/psref.h>
     64 #include <sys/lwp.h>
     65 #include <sys/workqueue.h>
     66 #include <sys/kmem.h>
     67 #include <sys/cpu.h>
     68 #include <sys/atomic.h>
     69 
     70 #include <net/if.h>
     71 #include <net/route.h>
     72 
     73 #include <netinet/in.h>
     74 #include <netinet/in_systm.h>
     75 #include <netinet/ip.h>
     76 #include <netinet/in_var.h>
     77 #ifdef INET
     78 #include <netinet/ip_var.h>
     79 #endif
     80 
     81 #ifdef INET6
     82 #include <netinet/ip6.h>
     83 #include <netinet6/in6_var.h>
     84 #include <netinet6/ip6_var.h>
     85 #endif /* INET6 */
     86 
     87 #ifdef INET
     88 #include <netinet/in_pcb.h>
     89 #endif
     90 #ifdef INET6
     91 #include <netinet6/in6_pcb.h>
     92 #endif /* INET6 */
     93 
     94 #include <net/pfkeyv2.h>
     95 #include <netipsec/keydb.h>
     96 #include <netipsec/key.h>
     97 #include <netipsec/keysock.h>
     98 #include <netipsec/key_debug.h>
     99 
    100 #include <netipsec/ipsec.h>
    101 #ifdef INET6
    102 #include <netipsec/ipsec6.h>
    103 #endif
    104 #include <netipsec/ipsec_private.h>
    105 
    106 #include <netipsec/xform.h>
    107 #include <netipsec/ipcomp.h>
    108 
    109 
    110 #include <net/net_osdep.h>
    111 
    112 #define FULLMASK	0xff
    113 #define	_BITS(bytes)	((bytes) << 3)
    114 
    115 #define PORT_NONE	0
    116 #define PORT_LOOSE	1
    117 #define PORT_STRICT	2
    118 
    119 percpu_t *pfkeystat_percpu;
    120 
    121 /*
    122  * Note on SA reference counting:
    123  * - SAs that are not in DEAD state will have (total external reference + 1)
    124  *   following value in reference count field.  they cannot be freed and are
    125  *   referenced from SA header.
    126  * - SAs that are in DEAD state will have (total external reference)
    127  *   in reference count field.  they are ready to be freed.  reference from
    128  *   SA header will be removed in key_delsav(), when the reference count
    129  *   field hits 0 (= no external reference other than from SA header.
    130  */
    131 
    132 u_int32_t key_debug_level = 0;
    133 static u_int key_spi_trycnt = 1000;
    134 static u_int32_t key_spi_minval = 0x100;
    135 static u_int32_t key_spi_maxval = 0x0fffffff;	/* XXX */
    136 static u_int32_t policy_id = 0;
    137 static u_int key_int_random = 60;	/*interval to initialize randseed,1(m)*/
    138 static u_int key_larval_lifetime = 30;	/* interval to expire acquiring, 30(s)*/
    139 static int key_blockacq_count = 10;	/* counter for blocking SADB_ACQUIRE.*/
    140 static int key_blockacq_lifetime = 20;	/* lifetime for blocking SADB_ACQUIRE.*/
    141 static int key_prefered_oldsa = 0;	/* prefered old sa rather than new sa.*/
    142 
    143 static u_int32_t acq_seq = 0;
    144 
    145 static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];	/* SPD */
    146 static LIST_HEAD(_sahtree, secashead) sahtree;			/* SAD */
    147 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
    148 							/* registed list */
    149 #ifndef IPSEC_NONBLOCK_ACQUIRE
    150 static LIST_HEAD(_acqtree, secacq) acqtree;		/* acquiring list */
    151 #endif
    152 #ifdef notyet
    153 static LIST_HEAD(_spacqtree, secspacq) spacqtree;	/* SP acquiring list */
    154 #endif
    155 
    156 /*
    157  * Protect regtree, acqtree and items stored in the lists.
    158  */
    159 static kmutex_t key_mtx __cacheline_aligned;
    160 
    161 /* search order for SAs */
    162 	/*
    163 	 * This order is important because we must select the oldest SA
    164 	 * for outbound processing.  For inbound, This is not important.
    165 	 */
    166 static const u_int saorder_state_valid_prefer_old[] = {
    167 	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
    168 };
    169 static const u_int saorder_state_valid_prefer_new[] = {
    170 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
    171 };
    172 
    173 static const u_int saorder_state_alive[] = {
    174 	/* except DEAD */
    175 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
    176 };
    177 static const u_int saorder_state_any[] = {
    178 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
    179 	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
    180 };
    181 
    182 #define SASTATE_ALIVE_FOREACH(s)				\
    183 	for (int _i = 0;					\
    184 	    _i < __arraycount(saorder_state_alive) ?		\
    185 	    (s) = saorder_state_alive[_i], true : false;	\
    186 	    _i++)
    187 #define SASTATE_ANY_FOREACH(s)					\
    188 	for (int _i = 0;					\
    189 	    _i < __arraycount(saorder_state_any) ?		\
    190 	    (s) = saorder_state_any[_i], true : false;		\
    191 	    _i++)
    192 
    193 static const int minsize[] = {
    194 	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
    195 	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
    196 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
    197 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
    198 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
    199 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
    200 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
    201 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
    202 	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
    203 	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
    204 	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
    205 	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
    206 	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
    207 	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
    208 	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
    209 	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
    210 	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
    211 	0,				/* SADB_X_EXT_KMPRIVATE */
    212 	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
    213 	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
    214 	sizeof(struct sadb_x_nat_t_type),	/* SADB_X_EXT_NAT_T_TYPE */
    215 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_SPORT */
    216 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_DPORT */
    217 	sizeof(struct sadb_address),		/* SADB_X_EXT_NAT_T_OAI */
    218 	sizeof(struct sadb_address),		/* SADB_X_EXT_NAT_T_OAR */
    219 	sizeof(struct sadb_x_nat_t_frag),	/* SADB_X_EXT_NAT_T_FRAG */
    220 };
    221 static const int maxsize[] = {
    222 	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
    223 	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
    224 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
    225 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
    226 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
    227 	0,				/* SADB_EXT_ADDRESS_SRC */
    228 	0,				/* SADB_EXT_ADDRESS_DST */
    229 	0,				/* SADB_EXT_ADDRESS_PROXY */
    230 	0,				/* SADB_EXT_KEY_AUTH */
    231 	0,				/* SADB_EXT_KEY_ENCRYPT */
    232 	0,				/* SADB_EXT_IDENTITY_SRC */
    233 	0,				/* SADB_EXT_IDENTITY_DST */
    234 	0,				/* SADB_EXT_SENSITIVITY */
    235 	0,				/* SADB_EXT_PROPOSAL */
    236 	0,				/* SADB_EXT_SUPPORTED_AUTH */
    237 	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
    238 	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
    239 	0,				/* SADB_X_EXT_KMPRIVATE */
    240 	0,				/* SADB_X_EXT_POLICY */
    241 	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
    242 	sizeof(struct sadb_x_nat_t_type),	/* SADB_X_EXT_NAT_T_TYPE */
    243 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_SPORT */
    244 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_DPORT */
    245 	0,					/* SADB_X_EXT_NAT_T_OAI */
    246 	0,					/* SADB_X_EXT_NAT_T_OAR */
    247 	sizeof(struct sadb_x_nat_t_frag),	/* SADB_X_EXT_NAT_T_FRAG */
    248 };
    249 
    250 static int ipsec_esp_keymin = 256;
    251 static int ipsec_esp_auth = 0;
    252 static int ipsec_ah_keymin = 128;
    253 
    254 #ifdef SYSCTL_DECL
    255 SYSCTL_DECL(_net_key);
    256 #endif
    257 
    258 #ifdef SYSCTL_INT
    259 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,	CTLFLAG_RW, \
    260 	&key_debug_level,	0,	"");
    261 
    262 /* max count of trial for the decision of spi value */
    263 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY,		spi_trycnt,	CTLFLAG_RW, \
    264 	&key_spi_trycnt,	0,	"");
    265 
    266 /* minimum spi value to allocate automatically. */
    267 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,	spi_minval,	CTLFLAG_RW, \
    268 	&key_spi_minval,	0,	"");
    269 
    270 /* maximun spi value to allocate automatically. */
    271 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,	spi_maxval,	CTLFLAG_RW, \
    272 	&key_spi_maxval,	0,	"");
    273 
    274 /* interval to initialize randseed */
    275 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT,	int_random,	CTLFLAG_RW, \
    276 	&key_int_random,	0,	"");
    277 
    278 /* lifetime for larval SA */
    279 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,	larval_lifetime, CTLFLAG_RW, \
    280 	&key_larval_lifetime,	0,	"");
    281 
    282 /* counter for blocking to send SADB_ACQUIRE to IKEd */
    283 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,	blockacq_count,	CTLFLAG_RW, \
    284 	&key_blockacq_count,	0,	"");
    285 
    286 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
    287 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,	blockacq_lifetime, CTLFLAG_RW, \
    288 	&key_blockacq_lifetime,	0,	"");
    289 
    290 /* ESP auth */
    291 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth, CTLFLAG_RW, \
    292 	&ipsec_esp_auth,	0,	"");
    293 
    294 /* minimum ESP key length */
    295 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN,	esp_keymin, CTLFLAG_RW, \
    296 	&ipsec_esp_keymin,	0,	"");
    297 
    298 /* minimum AH key length */
    299 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin, CTLFLAG_RW, \
    300 	&ipsec_ah_keymin,	0,	"");
    301 
    302 /* perfered old SA rather than new SA */
    303 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,	prefered_oldsa, CTLFLAG_RW,\
    304 	&key_prefered_oldsa,	0,	"");
    305 #endif /* SYSCTL_INT */
    306 
    307 #define __LIST_CHAINED(elm) \
    308 	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
    309 #define LIST_INSERT_TAIL(head, elm, type, field) \
    310 do {\
    311 	struct type *curelm = LIST_FIRST(head); \
    312 	if (curelm == NULL) {\
    313 		LIST_INSERT_HEAD(head, elm, field); \
    314 	} else { \
    315 		while (LIST_NEXT(curelm, field)) \
    316 			curelm = LIST_NEXT(curelm, field);\
    317 		LIST_INSERT_AFTER(curelm, elm, field);\
    318 	}\
    319 } while (0)
    320 
    321 #define KEY_CHKSASTATE(head, sav) \
    322 /* do */ { \
    323 	if ((head) != (sav)) {						\
    324 		IPSECLOG(LOG_DEBUG,					\
    325 		    "state mismatched (TREE=%d SA=%d)\n",		\
    326 		    (head), (sav));					\
    327 		continue;						\
    328 	}								\
    329 } /* while (0) */
    330 
    331 #define KEY_CHKSPDIR(head, sp) \
    332 do { \
    333 	if ((head) != (sp)) {						\
    334 		IPSECLOG(LOG_DEBUG,					\
    335 		    "direction mismatched (TREE=%d SP=%d), anyway continue.\n",\
    336 		    (head), (sp));					\
    337 	}								\
    338 } while (0)
    339 
    340 /*
    341  * set parameters into secasindex buffer.
    342  * Must allocate secasindex buffer before calling this function.
    343  */
    344 static int
    345 key_setsecasidx(int, int, int, const struct sockaddr *,
    346     const struct sockaddr *, struct secasindex *);
    347 
    348 /* key statistics */
    349 struct _keystat {
    350 	u_long getspi_count; /* the avarage of count to try to get new SPI */
    351 } keystat;
    352 
    353 struct sadb_msghdr {
    354 	struct sadb_msg *msg;
    355 	struct sadb_ext *ext[SADB_EXT_MAX + 1];
    356 	int extoff[SADB_EXT_MAX + 1];
    357 	int extlen[SADB_EXT_MAX + 1];
    358 };
    359 
    360 static void
    361 key_init_spidx_bymsghdr(struct secpolicyindex *, const struct sadb_msghdr *);
    362 
    363 static const struct sockaddr *
    364 key_msghdr_get_sockaddr(const struct sadb_msghdr *mhp, int idx)
    365 {
    366 
    367 	return PFKEY_ADDR_SADDR((struct sadb_address *)mhp->ext[idx]);
    368 }
    369 
    370 static struct mbuf *
    371 key_fill_replymsg(struct mbuf *m, int seq)
    372 {
    373 	struct sadb_msg *msg;
    374 
    375 	if (m->m_len < sizeof(*msg)) {
    376 		m = m_pullup(m, sizeof(*msg));
    377 		if (m == NULL)
    378 			return NULL;
    379 	}
    380 	msg = mtod(m, struct sadb_msg *);
    381 	msg->sadb_msg_errno = 0;
    382 	msg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
    383 	if (seq != 0)
    384 		msg->sadb_msg_seq = seq;
    385 
    386 	return m;
    387 }
    388 
    389 static struct secasvar *key_allocsa_policy (const struct secasindex *);
    390 #if 0
    391 static void key_freeso(struct socket *);
    392 static void key_freesp_so(struct secpolicy **);
    393 #endif
    394 static struct secasvar *key_do_allocsa_policy (struct secashead *, u_int);
    395 static void key_delsp (struct secpolicy *);
    396 static struct secpolicy *key_getsp (const struct secpolicyindex *);
    397 static struct secpolicy *key_getspbyid (u_int32_t);
    398 static u_int16_t key_newreqid (void);
    399 static struct mbuf *key_gather_mbuf (struct mbuf *,
    400 	const struct sadb_msghdr *, int, int, ...);
    401 static int key_api_spdadd(struct socket *, struct mbuf *,
    402 	const struct sadb_msghdr *);
    403 static u_int32_t key_getnewspid (void);
    404 static int key_api_spddelete(struct socket *, struct mbuf *,
    405 	const struct sadb_msghdr *);
    406 static int key_api_spddelete2(struct socket *, struct mbuf *,
    407 	const struct sadb_msghdr *);
    408 static int key_api_spdget(struct socket *, struct mbuf *,
    409 	const struct sadb_msghdr *);
    410 static int key_api_spdflush(struct socket *, struct mbuf *,
    411 	const struct sadb_msghdr *);
    412 static int key_api_spddump(struct socket *, struct mbuf *,
    413 	const struct sadb_msghdr *);
    414 static struct mbuf * key_setspddump (int *errorp, pid_t);
    415 static struct mbuf * key_setspddump_chain (int *errorp, int *lenp, pid_t pid);
    416 static int key_api_nat_map(struct socket *, struct mbuf *,
    417 	const struct sadb_msghdr *);
    418 static struct mbuf *key_setdumpsp (struct secpolicy *,
    419 	u_int8_t, u_int32_t, pid_t);
    420 static u_int key_getspreqmsglen (const struct secpolicy *);
    421 static int key_spdexpire (struct secpolicy *);
    422 static struct secashead *key_newsah (const struct secasindex *);
    423 static void key_delsah (struct secashead *);
    424 static struct secasvar *key_newsav(struct mbuf *,
    425 	const struct sadb_msghdr *, int *, const char*, int);
    426 #define	KEY_NEWSAV(m, sadb, e)				\
    427 	key_newsav(m, sadb, e, __func__, __LINE__)
    428 static void key_delsav (struct secasvar *);
    429 static struct secashead *key_getsah(const struct secasindex *, int);
    430 static bool key_checkspidup(const struct secasindex *, u_int32_t);
    431 static struct secasvar *key_getsavbyspi (struct secashead *, u_int32_t);
    432 static int key_setsaval (struct secasvar *, struct mbuf *,
    433 	const struct sadb_msghdr *);
    434 static void key_freesaval(struct secasvar *);
    435 static int key_init_xform(struct secasvar *);
    436 static void key_clear_xform(struct secasvar *);
    437 static struct mbuf *key_setdumpsa (struct secasvar *, u_int8_t,
    438 	u_int8_t, u_int32_t, u_int32_t);
    439 static struct mbuf *key_setsadbxport (u_int16_t, u_int16_t);
    440 static struct mbuf *key_setsadbxtype (u_int16_t);
    441 static struct mbuf *key_setsadbxfrag (u_int16_t);
    442 static void key_porttosaddr (union sockaddr_union *, u_int16_t);
    443 static int key_checksalen (const union sockaddr_union *);
    444 static struct mbuf *key_setsadbmsg (u_int8_t, u_int16_t, u_int8_t,
    445 	u_int32_t, pid_t, u_int16_t);
    446 static struct mbuf *key_setsadbsa (struct secasvar *);
    447 static struct mbuf *key_setsadbaddr (u_int16_t,
    448 	const struct sockaddr *, u_int8_t, u_int16_t);
    449 #if 0
    450 static struct mbuf *key_setsadbident (u_int16_t, u_int16_t, void *,
    451 	int, u_int64_t);
    452 #endif
    453 static struct mbuf *key_setsadbxsa2 (u_int8_t, u_int32_t, u_int16_t);
    454 static struct mbuf *key_setsadbxpolicy (u_int16_t, u_int8_t,
    455 	u_int32_t);
    456 static void *key_newbuf (const void *, u_int);
    457 #ifdef INET6
    458 static int key_ismyaddr6 (const struct sockaddr_in6 *);
    459 #endif
    460 
    461 static void sysctl_net_keyv2_setup(struct sysctllog **);
    462 static void sysctl_net_key_compat_setup(struct sysctllog **);
    463 
    464 /* flags for key_saidx_match() */
    465 #define CMP_HEAD	1	/* protocol, addresses. */
    466 #define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
    467 #define CMP_REQID	3	/* additionally HEAD, reaid. */
    468 #define CMP_EXACTLY	4	/* all elements. */
    469 static int key_saidx_match(const struct secasindex *,
    470     const struct secasindex *, int);
    471 
    472 static int key_sockaddr_match(const struct sockaddr *,
    473     const struct sockaddr *, int);
    474 static int key_bb_match_withmask(const void *, const void *, u_int);
    475 static u_int16_t key_satype2proto (u_int8_t);
    476 static u_int8_t key_proto2satype (u_int16_t);
    477 
    478 static int key_spidx_match_exactly(const struct secpolicyindex *,
    479     const struct secpolicyindex *);
    480 static int key_spidx_match_withmask(const struct secpolicyindex *,
    481     const struct secpolicyindex *);
    482 
    483 static int key_api_getspi(struct socket *, struct mbuf *,
    484 	const struct sadb_msghdr *);
    485 static u_int32_t key_do_getnewspi (const struct sadb_spirange *,
    486 					const struct secasindex *);
    487 static int key_handle_natt_info (struct secasvar *,
    488 				     const struct sadb_msghdr *);
    489 static int key_set_natt_ports (union sockaddr_union *,
    490 			 	union sockaddr_union *,
    491 				const struct sadb_msghdr *);
    492 static int key_api_update(struct socket *, struct mbuf *,
    493 	const struct sadb_msghdr *);
    494 #ifdef IPSEC_DOSEQCHECK
    495 static struct secasvar *key_getsavbyseq (struct secashead *, u_int32_t);
    496 #endif
    497 static int key_api_add(struct socket *, struct mbuf *,
    498 	const struct sadb_msghdr *);
    499 static int key_setident (struct secashead *, struct mbuf *,
    500 	const struct sadb_msghdr *);
    501 static struct mbuf *key_getmsgbuf_x1 (struct mbuf *,
    502 	const struct sadb_msghdr *);
    503 static int key_api_delete(struct socket *, struct mbuf *,
    504 	const struct sadb_msghdr *);
    505 static int key_api_get(struct socket *, struct mbuf *,
    506 	const struct sadb_msghdr *);
    507 
    508 static void key_getcomb_setlifetime (struct sadb_comb *);
    509 static struct mbuf *key_getcomb_esp (void);
    510 static struct mbuf *key_getcomb_ah (void);
    511 static struct mbuf *key_getcomb_ipcomp (void);
    512 static struct mbuf *key_getprop (const struct secasindex *);
    513 
    514 static int key_acquire (const struct secasindex *, struct secpolicy *);
    515 #ifndef IPSEC_NONBLOCK_ACQUIRE
    516 static struct secacq *key_newacq (const struct secasindex *);
    517 static struct secacq *key_getacq (const struct secasindex *);
    518 static struct secacq *key_getacqbyseq (u_int32_t);
    519 #endif
    520 #ifdef notyet
    521 static struct secspacq *key_newspacq (const struct secpolicyindex *);
    522 static struct secspacq *key_getspacq (const struct secpolicyindex *);
    523 #endif
    524 static int key_api_acquire(struct socket *, struct mbuf *,
    525 	const struct sadb_msghdr *);
    526 static int key_api_register(struct socket *, struct mbuf *,
    527 	const struct sadb_msghdr *);
    528 static int key_expire (struct secasvar *);
    529 static int key_api_flush(struct socket *, struct mbuf *,
    530 	const struct sadb_msghdr *);
    531 static struct mbuf *key_setdump_chain (u_int8_t req_satype, int *errorp,
    532 	int *lenp, pid_t pid);
    533 static int key_api_dump(struct socket *, struct mbuf *,
    534 	const struct sadb_msghdr *);
    535 static int key_api_promisc(struct socket *, struct mbuf *,
    536 	const struct sadb_msghdr *);
    537 static int key_senderror (struct socket *, struct mbuf *, int);
    538 static int key_validate_ext (const struct sadb_ext *, int);
    539 static int key_align (struct mbuf *, struct sadb_msghdr *);
    540 #if 0
    541 static const char *key_getfqdn (void);
    542 static const char *key_getuserfqdn (void);
    543 #endif
    544 static void key_sa_chgstate (struct secasvar *, u_int8_t);
    545 static inline void key_sp_dead (struct secpolicy *);
    546 static void key_sp_unlink (struct secpolicy *sp);
    547 
    548 static struct mbuf *key_alloc_mbuf (int);
    549 
    550 static void key_timehandler(void *);
    551 static void key_timehandler_work(struct work *, void *);
    552 static struct callout	key_timehandler_ch;
    553 static struct workqueue	*key_timehandler_wq;
    554 static struct work	key_timehandler_wk;
    555 
    556 #ifdef IPSEC_REF_DEBUG
    557 #define REFLOG(label, p, where, tag)					\
    558 	log(LOG_DEBUG, "%s:%d: " label " : refcnt=%d (%p)\n.",		\
    559 	    (where), (tag), (p)->refcnt, (p))
    560 #else
    561 #define REFLOG(label, p, where, tag)	do {} while (0)
    562 #endif
    563 
    564 #define	SA_ADDREF(p) do {						\
    565 	atomic_inc_uint(&(p)->refcnt);					\
    566 	REFLOG("SA_ADDREF", (p), __func__, __LINE__);			\
    567 	KASSERTMSG((p)->refcnt != 0, "SA refcnt overflow");		\
    568 } while (0)
    569 #define	SA_ADDREF2(p, where, tag) do {					\
    570 	atomic_inc_uint(&(p)->refcnt);					\
    571 	REFLOG("SA_ADDREF", (p), (where), (tag));			\
    572 	KASSERTMSG((p)->refcnt != 0, "SA refcnt overflow");		\
    573 } while (0)
    574 #define	SA_DELREF(p) do {						\
    575 	KASSERTMSG((p)->refcnt > 0, "SA refcnt underflow");		\
    576 	atomic_dec_uint(&(p)->refcnt);					\
    577 	REFLOG("SA_DELREF", (p), __func__, __LINE__);			\
    578 } while (0)
    579 #define	SA_DELREF2(p, nv, where, tag) do {				\
    580 	KASSERTMSG((p)->refcnt > 0, "SA refcnt underflow");		\
    581 	nv = atomic_dec_uint_nv(&(p)->refcnt);				\
    582 	REFLOG("SA_DELREF", (p), (where), (tag));			\
    583 } while (0)
    584 
    585 #define	SP_ADDREF(p) do {						\
    586 	atomic_inc_uint(&(p)->refcnt);					\
    587 	REFLOG("SP_ADDREF", (p), __func__, __LINE__);			\
    588 	KASSERTMSG((p)->refcnt != 0, "SP refcnt overflow");		\
    589 } while (0)
    590 #define	SP_ADDREF2(p, where, tag) do {					\
    591 	atomic_inc_uint(&(p)->refcnt);					\
    592 	REFLOG("SP_ADDREF", (p), (where), (tag));			\
    593 	KASSERTMSG((p)->refcnt != 0, "SP refcnt overflow");		\
    594 } while (0)
    595 #define	SP_DELREF(p) do {						\
    596 	KASSERTMSG((p)->refcnt > 0, "SP refcnt underflow");		\
    597 	atomic_dec_uint(&(p)->refcnt);					\
    598 	REFLOG("SP_DELREF", (p), __func__, __LINE__);			\
    599 } while (0)
    600 #define	SP_DELREF2(p, nv, where, tag) do {				\
    601 	KASSERTMSG((p)->refcnt > 0, "SP refcnt underflow");		\
    602 	nv = atomic_dec_uint_nv(&(p)->refcnt);				\
    603 	REFLOG("SP_DELREF", (p), (where), (tag));			\
    604 } while (0)
    605 
    606 
    607 static inline void
    608 key_sp_dead(struct secpolicy *sp)
    609 {
    610 
    611 	/* mark the SP dead */
    612 	sp->state = IPSEC_SPSTATE_DEAD;
    613 }
    614 
    615 static void
    616 key_sp_unlink(struct secpolicy *sp)
    617 {
    618 
    619 	/* remove from SP index */
    620 	KASSERT(__LIST_CHAINED(sp));
    621 	LIST_REMOVE(sp, chain);
    622 	/* Release refcount held just for being on chain */
    623 	KEY_FREESP(&sp);
    624 }
    625 
    626 
    627 /*
    628  * Return 0 when there are known to be no SP's for the specified
    629  * direction.  Otherwise return 1.  This is used by IPsec code
    630  * to optimize performance.
    631  */
    632 int
    633 key_havesp(u_int dir)
    634 {
    635 	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
    636 		!LIST_EMPTY(&sptree[dir]) : 1);
    637 }
    638 
    639 /* %%% IPsec policy management */
    640 /*
    641  * allocating a SP for OUTBOUND or INBOUND packet.
    642  * Must call key_freesp() later.
    643  * OUT:	NULL:	not found
    644  *	others:	found and return the pointer.
    645  */
    646 struct secpolicy *
    647 key_lookup_sp_byspidx(const struct secpolicyindex *spidx,
    648     u_int dir, const char* where, int tag)
    649 {
    650 	struct secpolicy *sp;
    651 	int s;
    652 
    653 	KASSERT(spidx != NULL);
    654 	KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
    655 
    656 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
    657 
    658 	/* get a SP entry */
    659 	s = splsoftnet();	/*called from softclock()*/
    660 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
    661 		printf("*** objects\n");
    662 		kdebug_secpolicyindex(spidx);
    663 	}
    664 
    665 	LIST_FOREACH(sp, &sptree[dir], chain) {
    666 		if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
    667 			printf("*** in SPD\n");
    668 			kdebug_secpolicyindex(&sp->spidx);
    669 		}
    670 
    671 		if (sp->state == IPSEC_SPSTATE_DEAD)
    672 			continue;
    673 		if (key_spidx_match_withmask(&sp->spidx, spidx))
    674 			goto found;
    675 	}
    676 	sp = NULL;
    677 found:
    678 	if (sp) {
    679 		/* sanity check */
    680 		KEY_CHKSPDIR(sp->spidx.dir, dir);
    681 
    682 		/* found a SPD entry */
    683 		sp->lastused = time_uptime;
    684 		SP_ADDREF2(sp, where, tag);
    685 	}
    686 	splx(s);
    687 
    688 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    689 	    "DP return SP:%p (ID=%u) refcnt %u\n",
    690 	    sp, sp ? sp->id : 0, sp ? sp->refcnt : 0);
    691 	return sp;
    692 }
    693 
    694 /*
    695  * allocating a SP for OUTBOUND or INBOUND packet.
    696  * Must call key_freesp() later.
    697  * OUT:	NULL:	not found
    698  *	others:	found and return the pointer.
    699  */
    700 struct secpolicy *
    701 key_lookup_sp(u_int32_t spi,
    702 	     const union sockaddr_union *dst,
    703 	     u_int8_t proto,
    704 	     u_int dir,
    705 	     const char* where, int tag)
    706 {
    707 	struct secpolicy *sp;
    708 	int s;
    709 
    710 	KASSERT(dst != NULL);
    711 	KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
    712 
    713 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
    714 
    715 	/* get a SP entry */
    716 	s = splsoftnet();	/*called from softclock()*/
    717 	if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
    718 		printf("*** objects\n");
    719 		printf("spi %u proto %u dir %u\n", spi, proto, dir);
    720 		kdebug_sockaddr(&dst->sa);
    721 	}
    722 
    723 	LIST_FOREACH(sp, &sptree[dir], chain) {
    724 		if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
    725 			printf("*** in SPD\n");
    726 			kdebug_secpolicyindex(&sp->spidx);
    727 		}
    728 
    729 		if (sp->state == IPSEC_SPSTATE_DEAD)
    730 			continue;
    731 		/* compare simple values, then dst address */
    732 		if (sp->spidx.ul_proto != proto)
    733 			continue;
    734 		/* NB: spi's must exist and match */
    735 		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
    736 			continue;
    737 		if (key_sockaddr_match(&sp->spidx.dst.sa, &dst->sa, PORT_STRICT))
    738 			goto found;
    739 	}
    740 	sp = NULL;
    741 found:
    742 	if (sp) {
    743 		/* sanity check */
    744 		KEY_CHKSPDIR(sp->spidx.dir, dir);
    745 
    746 		/* found a SPD entry */
    747 		sp->lastused = time_uptime;
    748 		SP_ADDREF2(sp, where, tag);
    749 	}
    750 	splx(s);
    751 
    752 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    753 	    "DP return SP:%p (ID=%u) refcnt %u\n",
    754 	    sp, sp ? sp->id : 0, sp ? sp->refcnt : 0);
    755 	return sp;
    756 }
    757 
    758 /*
    759  * return a policy that matches this particular inbound packet.
    760  * XXX slow
    761  */
    762 struct secpolicy *
    763 key_gettunnel(const struct sockaddr *osrc,
    764 	      const struct sockaddr *odst,
    765 	      const struct sockaddr *isrc,
    766 	      const struct sockaddr *idst,
    767 	      const char* where, int tag)
    768 {
    769 	struct secpolicy *sp;
    770 	const int dir = IPSEC_DIR_INBOUND;
    771 	int s;
    772 	struct ipsecrequest *r1, *r2, *p;
    773 	struct secpolicyindex spidx;
    774 
    775 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
    776 
    777 	if (isrc->sa_family != idst->sa_family) {
    778 		IPSECLOG(LOG_ERR, "protocol family mismatched %d != %d\n.",
    779 		    isrc->sa_family, idst->sa_family);
    780 		sp = NULL;
    781 		goto done;
    782 	}
    783 
    784 	s = splsoftnet();	/*called from softclock()*/
    785 	LIST_FOREACH(sp, &sptree[dir], chain) {
    786 		if (sp->state == IPSEC_SPSTATE_DEAD)
    787 			continue;
    788 
    789 		r1 = r2 = NULL;
    790 		for (p = sp->req; p; p = p->next) {
    791 			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
    792 				continue;
    793 
    794 			r1 = r2;
    795 			r2 = p;
    796 
    797 			if (!r1) {
    798 				/* here we look at address matches only */
    799 				spidx = sp->spidx;
    800 				if (isrc->sa_len > sizeof(spidx.src) ||
    801 				    idst->sa_len > sizeof(spidx.dst))
    802 					continue;
    803 				memcpy(&spidx.src, isrc, isrc->sa_len);
    804 				memcpy(&spidx.dst, idst, idst->sa_len);
    805 				if (!key_spidx_match_withmask(&sp->spidx, &spidx))
    806 					continue;
    807 			} else {
    808 				if (!key_sockaddr_match(&r1->saidx.src.sa, isrc, PORT_NONE) ||
    809 				    !key_sockaddr_match(&r1->saidx.dst.sa, idst, PORT_NONE))
    810 					continue;
    811 			}
    812 
    813 			if (!key_sockaddr_match(&r2->saidx.src.sa, osrc, PORT_NONE) ||
    814 			    !key_sockaddr_match(&r2->saidx.dst.sa, odst, PORT_NONE))
    815 				continue;
    816 
    817 			goto found;
    818 		}
    819 	}
    820 	sp = NULL;
    821 found:
    822 	if (sp) {
    823 		sp->lastused = time_uptime;
    824 		SP_ADDREF2(sp, where, tag);
    825 	}
    826 	splx(s);
    827 done:
    828 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
    829 	    "DP return SP:%p (ID=%u) refcnt %u\n",
    830 	    sp, sp ? sp->id : 0, sp ? sp->refcnt : 0);
    831 	return sp;
    832 }
    833 
    834 /*
    835  * allocating an SA entry for an *OUTBOUND* packet.
    836  * checking each request entries in SP, and acquire an SA if need.
    837  * OUT:	0: there are valid requests.
    838  *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
    839  */
    840 int
    841 key_checkrequest(struct ipsecrequest *isr, 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;
   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(sav, &sah->savtree[state], chain) {
   2861 			/* give up to delete this sa */
   2862 			zombie++;
   2863 		}
   2864 	}
   2865 
   2866 	/* don't delete sah only if there are savs. */
   2867 	if (zombie) {
   2868 		splx(s);
   2869 		return;
   2870 	}
   2871 
   2872 	rtcache_free(&sah->sa_route);
   2873 
   2874 	/* remove from tree of SA index */
   2875 	KASSERT(__LIST_CHAINED(sah));
   2876 	LIST_REMOVE(sah, chain);
   2877 
   2878 	if (sah->idents != NULL)
   2879 		kmem_free(sah->idents, sah->idents_len);
   2880 	if (sah->identd != NULL)
   2881 		kmem_free(sah->identd, sah->identd_len);
   2882 
   2883 	kmem_free(sah, sizeof(*sah));
   2884 
   2885 	splx(s);
   2886 	return;
   2887 }
   2888 
   2889 /*
   2890  * allocating a new SA with LARVAL state.
   2891  * key_api_add() and key_api_getspi() call,
   2892  * and copy the values of mhp into new buffer.
   2893  * When SAD message type is GETSPI:
   2894  *	to set sequence number from acq_seq++,
   2895  *	to set zero to SPI.
   2896  *	not to call key_setsava().
   2897  * OUT:	NULL	: fail
   2898  *	others	: pointer to new secasvar.
   2899  *
   2900  * does not modify mbuf.  does not free mbuf on error.
   2901  */
   2902 static struct secasvar *
   2903 key_newsav(struct mbuf *m, const struct sadb_msghdr *mhp,
   2904     int *errp, const char* where, int tag)
   2905 {
   2906 	struct secasvar *newsav;
   2907 	const struct sadb_sa *xsa;
   2908 
   2909 	KASSERT(!cpu_softintr_p());
   2910 	KASSERT(m != NULL);
   2911 	KASSERT(mhp != NULL);
   2912 	KASSERT(mhp->msg != NULL);
   2913 
   2914 	newsav = kmem_zalloc(sizeof(struct secasvar), KM_SLEEP);
   2915 
   2916 	switch (mhp->msg->sadb_msg_type) {
   2917 	case SADB_GETSPI:
   2918 		newsav->spi = 0;
   2919 
   2920 #ifdef IPSEC_DOSEQCHECK
   2921 		/* sync sequence number */
   2922 		if (mhp->msg->sadb_msg_seq == 0)
   2923 			newsav->seq =
   2924 			    (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
   2925 		else
   2926 #endif
   2927 			newsav->seq = mhp->msg->sadb_msg_seq;
   2928 		break;
   2929 
   2930 	case SADB_ADD:
   2931 		/* sanity check */
   2932 		if (mhp->ext[SADB_EXT_SA] == NULL) {
   2933 			IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   2934 			*errp = EINVAL;
   2935 			goto error;
   2936 		}
   2937 		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   2938 		newsav->spi = xsa->sadb_sa_spi;
   2939 		newsav->seq = mhp->msg->sadb_msg_seq;
   2940 		break;
   2941 	default:
   2942 		*errp = EINVAL;
   2943 		goto error;
   2944 	}
   2945 
   2946 	/* copy sav values */
   2947 	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
   2948 		*errp = key_setsaval(newsav, m, mhp);
   2949 		if (*errp)
   2950 			goto error;
   2951 	}
   2952 
   2953 	/* reset created */
   2954 	newsav->created = time_uptime;
   2955 	newsav->pid = mhp->msg->sadb_msg_pid;
   2956 
   2957 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   2958 	    "DP from %s:%u return SA:%p\n", where, tag, newsav);
   2959 	return newsav;
   2960 
   2961 error:
   2962 	KASSERT(*errp != 0);
   2963 	kmem_free(newsav, sizeof(*newsav));
   2964 	KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   2965 	    "DP from %s:%u return SA:NULL\n", where, tag);
   2966 	return NULL;
   2967 }
   2968 
   2969 
   2970 static void
   2971 key_clear_xform(struct secasvar *sav)
   2972 {
   2973 
   2974 	/*
   2975 	 * Cleanup xform state.  Note that zeroize'ing causes the
   2976 	 * keys to be cleared; otherwise we must do it ourself.
   2977 	 */
   2978 	if (sav->tdb_xform != NULL) {
   2979 		sav->tdb_xform->xf_zeroize(sav);
   2980 		sav->tdb_xform = NULL;
   2981 	} else {
   2982 		if (sav->key_auth != NULL)
   2983 			explicit_memset(_KEYBUF(sav->key_auth), 0,
   2984 			    _KEYLEN(sav->key_auth));
   2985 		if (sav->key_enc != NULL)
   2986 			explicit_memset(_KEYBUF(sav->key_enc), 0,
   2987 			    _KEYLEN(sav->key_enc));
   2988 	}
   2989 }
   2990 
   2991 /*
   2992  * free() SA variable entry.
   2993  */
   2994 static void
   2995 key_delsav(struct secasvar *sav)
   2996 {
   2997 
   2998 	KASSERT(sav != NULL);
   2999 	KASSERTMSG(sav->refcnt == 0, "reference count %u > 0", sav->refcnt);
   3000 
   3001 	key_clear_xform(sav);
   3002 	key_freesaval(sav);
   3003 	kmem_intr_free(sav, sizeof(*sav));
   3004 
   3005 	return;
   3006 }
   3007 
   3008 /*
   3009  * search SAD.
   3010  * OUT:
   3011  *	NULL	: not found
   3012  *	others	: found, pointer to a SA.
   3013  */
   3014 static struct secashead *
   3015 key_getsah(const struct secasindex *saidx, int flag)
   3016 {
   3017 	struct secashead *sah;
   3018 
   3019 	LIST_FOREACH(sah, &sahtree, chain) {
   3020 		if (sah->state == SADB_SASTATE_DEAD)
   3021 			continue;
   3022 		if (key_saidx_match(&sah->saidx, saidx, flag))
   3023 			return sah;
   3024 	}
   3025 
   3026 	return NULL;
   3027 }
   3028 
   3029 /*
   3030  * check not to be duplicated SPI.
   3031  * NOTE: this function is too slow due to searching all SAD.
   3032  * OUT:
   3033  *	NULL	: not found
   3034  *	others	: found, pointer to a SA.
   3035  */
   3036 static bool
   3037 key_checkspidup(const struct secasindex *saidx, u_int32_t spi)
   3038 {
   3039 	struct secashead *sah;
   3040 	struct secasvar *sav;
   3041 
   3042 	/* check address family */
   3043 	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
   3044 		IPSECLOG(LOG_DEBUG, "address family mismatched.\n");
   3045 		return false;
   3046 	}
   3047 
   3048 	/* check all SAD */
   3049 	LIST_FOREACH(sah, &sahtree, chain) {
   3050 		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
   3051 			continue;
   3052 		sav = key_getsavbyspi(sah, spi);
   3053 		if (sav != NULL) {
   3054 			KEY_FREESAV(&sav);
   3055 			return true;
   3056 		}
   3057 	}
   3058 
   3059 	return false;
   3060 }
   3061 
   3062 /*
   3063  * search SAD litmited alive SA, protocol, SPI.
   3064  * OUT:
   3065  *	NULL	: not found
   3066  *	others	: found, pointer to a SA.
   3067  */
   3068 static struct secasvar *
   3069 key_getsavbyspi(struct secashead *sah, u_int32_t spi)
   3070 {
   3071 	struct secasvar *sav;
   3072 	u_int state;
   3073 
   3074 	/* search all status */
   3075 	SASTATE_ALIVE_FOREACH(state) {
   3076 		LIST_FOREACH(sav, &sah->savtree[state], chain) {
   3077 
   3078 			/* sanity check */
   3079 			if (sav->state != state) {
   3080 				IPSECLOG(LOG_DEBUG,
   3081 				    "invalid sav->state (queue: %d SA: %d)\n",
   3082 				    state, sav->state);
   3083 				continue;
   3084 			}
   3085 
   3086 			if (sav->spi == spi) {
   3087 				SA_ADDREF(sav);
   3088 				return sav;
   3089 			}
   3090 		}
   3091 	}
   3092 
   3093 	return NULL;
   3094 }
   3095 
   3096 /*
   3097  * Free allocated data to member variables of sav:
   3098  * sav->replay, sav->key_* and sav->lft_*.
   3099  */
   3100 static void
   3101 key_freesaval(struct secasvar *sav)
   3102 {
   3103 
   3104 	if (sav->replay != NULL) {
   3105 		kmem_intr_free(sav->replay, sav->replay_len);
   3106 		sav->replay = NULL;
   3107 		sav->replay_len = 0;
   3108 	}
   3109 	if (sav->key_auth != NULL) {
   3110 		kmem_intr_free(sav->key_auth, sav->key_auth_len);
   3111 		sav->key_auth = NULL;
   3112 		sav->key_auth_len = 0;
   3113 	}
   3114 	if (sav->key_enc != NULL) {
   3115 		kmem_intr_free(sav->key_enc, sav->key_enc_len);
   3116 		sav->key_enc = NULL;
   3117 		sav->key_enc_len = 0;
   3118 	}
   3119 	if (sav->lft_c != NULL) {
   3120 		kmem_intr_free(sav->lft_c, sizeof(*(sav->lft_c)));
   3121 		sav->lft_c = NULL;
   3122 	}
   3123 	if (sav->lft_h != NULL) {
   3124 		kmem_intr_free(sav->lft_h, sizeof(*(sav->lft_h)));
   3125 		sav->lft_h = NULL;
   3126 	}
   3127 	if (sav->lft_s != NULL) {
   3128 		kmem_intr_free(sav->lft_s, sizeof(*(sav->lft_s)));
   3129 		sav->lft_s = NULL;
   3130 	}
   3131 }
   3132 
   3133 /*
   3134  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
   3135  * You must update these if need.
   3136  * OUT:	0:	success.
   3137  *	!0:	failure.
   3138  *
   3139  * does not modify mbuf.  does not free mbuf on error.
   3140  */
   3141 static int
   3142 key_setsaval(struct secasvar *sav, struct mbuf *m,
   3143 	     const struct sadb_msghdr *mhp)
   3144 {
   3145 	int error = 0;
   3146 
   3147 	KASSERT(!cpu_softintr_p());
   3148 	KASSERT(m != NULL);
   3149 	KASSERT(mhp != NULL);
   3150 	KASSERT(mhp->msg != NULL);
   3151 
   3152 	/* We shouldn't initialize sav variables while someone uses it. */
   3153 	KASSERT(sav->refcnt == 0);
   3154 
   3155 	/* SA */
   3156 	if (mhp->ext[SADB_EXT_SA] != NULL) {
   3157 		const struct sadb_sa *sa0;
   3158 
   3159 		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   3160 		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
   3161 			error = EINVAL;
   3162 			goto fail;
   3163 		}
   3164 
   3165 		sav->alg_auth = sa0->sadb_sa_auth;
   3166 		sav->alg_enc = sa0->sadb_sa_encrypt;
   3167 		sav->flags = sa0->sadb_sa_flags;
   3168 
   3169 		/* replay window */
   3170 		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
   3171 			size_t len = sizeof(struct secreplay) +
   3172 			    sa0->sadb_sa_replay;
   3173 			sav->replay = kmem_zalloc(len, KM_SLEEP);
   3174 			sav->replay_len = len;
   3175 			if (sa0->sadb_sa_replay != 0)
   3176 				sav->replay->bitmap = (char*)(sav->replay+1);
   3177 			sav->replay->wsize = sa0->sadb_sa_replay;
   3178 		}
   3179 	}
   3180 
   3181 	/* Authentication keys */
   3182 	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
   3183 		const struct sadb_key *key0;
   3184 		int len;
   3185 
   3186 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
   3187 		len = mhp->extlen[SADB_EXT_KEY_AUTH];
   3188 
   3189 		error = 0;
   3190 		if (len < sizeof(*key0)) {
   3191 			error = EINVAL;
   3192 			goto fail;
   3193 		}
   3194 		switch (mhp->msg->sadb_msg_satype) {
   3195 		case SADB_SATYPE_AH:
   3196 		case SADB_SATYPE_ESP:
   3197 		case SADB_X_SATYPE_TCPSIGNATURE:
   3198 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
   3199 			    sav->alg_auth != SADB_X_AALG_NULL)
   3200 				error = EINVAL;
   3201 			break;
   3202 		case SADB_X_SATYPE_IPCOMP:
   3203 		default:
   3204 			error = EINVAL;
   3205 			break;
   3206 		}
   3207 		if (error) {
   3208 			IPSECLOG(LOG_DEBUG, "invalid key_auth values.\n");
   3209 			goto fail;
   3210 		}
   3211 
   3212 		sav->key_auth = key_newbuf(key0, len);
   3213 		sav->key_auth_len = len;
   3214 	}
   3215 
   3216 	/* Encryption key */
   3217 	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
   3218 		const struct sadb_key *key0;
   3219 		int len;
   3220 
   3221 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
   3222 		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
   3223 
   3224 		error = 0;
   3225 		if (len < sizeof(*key0)) {
   3226 			error = EINVAL;
   3227 			goto fail;
   3228 		}
   3229 		switch (mhp->msg->sadb_msg_satype) {
   3230 		case SADB_SATYPE_ESP:
   3231 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
   3232 			    sav->alg_enc != SADB_EALG_NULL) {
   3233 				error = EINVAL;
   3234 				break;
   3235 			}
   3236 			sav->key_enc = key_newbuf(key0, len);
   3237 			sav->key_enc_len = len;
   3238 			break;
   3239 		case SADB_X_SATYPE_IPCOMP:
   3240 			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
   3241 				error = EINVAL;
   3242 			sav->key_enc = NULL;	/*just in case*/
   3243 			break;
   3244 		case SADB_SATYPE_AH:
   3245 		case SADB_X_SATYPE_TCPSIGNATURE:
   3246 		default:
   3247 			error = EINVAL;
   3248 			break;
   3249 		}
   3250 		if (error) {
   3251 			IPSECLOG(LOG_DEBUG, "invalid key_enc value.\n");
   3252 			goto fail;
   3253 		}
   3254 	}
   3255 
   3256 	/* set iv */
   3257 	sav->ivlen = 0;
   3258 
   3259 	switch (mhp->msg->sadb_msg_satype) {
   3260 	case SADB_SATYPE_AH:
   3261 		error = xform_init(sav, XF_AH);
   3262 		break;
   3263 	case SADB_SATYPE_ESP:
   3264 		error = xform_init(sav, XF_ESP);
   3265 		break;
   3266 	case SADB_X_SATYPE_IPCOMP:
   3267 		error = xform_init(sav, XF_IPCOMP);
   3268 		break;
   3269 	case SADB_X_SATYPE_TCPSIGNATURE:
   3270 		error = xform_init(sav, XF_TCPSIGNATURE);
   3271 		break;
   3272 	}
   3273 	if (error) {
   3274 		IPSECLOG(LOG_DEBUG, "unable to initialize SA type %u.\n",
   3275 		    mhp->msg->sadb_msg_satype);
   3276 		goto fail;
   3277 	}
   3278 
   3279 	/* reset created */
   3280 	sav->created = time_uptime;
   3281 
   3282 	/* make lifetime for CURRENT */
   3283 	sav->lft_c = kmem_alloc(sizeof(struct sadb_lifetime), KM_SLEEP);
   3284 
   3285 	sav->lft_c->sadb_lifetime_len =
   3286 	    PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   3287 	sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   3288 	sav->lft_c->sadb_lifetime_allocations = 0;
   3289 	sav->lft_c->sadb_lifetime_bytes = 0;
   3290 	sav->lft_c->sadb_lifetime_addtime = time_uptime;
   3291 	sav->lft_c->sadb_lifetime_usetime = 0;
   3292 
   3293 	/* lifetimes for HARD and SOFT */
   3294     {
   3295 	const struct sadb_lifetime *lft0;
   3296 
   3297 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
   3298 	if (lft0 != NULL) {
   3299 		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
   3300 			error = EINVAL;
   3301 			goto fail;
   3302 		}
   3303 		sav->lft_h = key_newbuf(lft0, sizeof(*lft0));
   3304 	}
   3305 
   3306 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
   3307 	if (lft0 != NULL) {
   3308 		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
   3309 			error = EINVAL;
   3310 			goto fail;
   3311 		}
   3312 		sav->lft_s = key_newbuf(lft0, sizeof(*lft0));
   3313 		/* to be initialize ? */
   3314 	}
   3315     }
   3316 
   3317 	return 0;
   3318 
   3319  fail:
   3320 	key_clear_xform(sav);
   3321 	key_freesaval(sav);
   3322 
   3323 	return error;
   3324 }
   3325 
   3326 /*
   3327  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
   3328  * OUT:	0:	valid
   3329  *	other:	errno
   3330  */
   3331 static int
   3332 key_init_xform(struct secasvar *sav)
   3333 {
   3334 	int error;
   3335 
   3336 	/* We shouldn't initialize sav variables while someone uses it. */
   3337 	KASSERT(sav->refcnt == 0);
   3338 
   3339 	/* check SPI value */
   3340 	switch (sav->sah->saidx.proto) {
   3341 	case IPPROTO_ESP:
   3342 	case IPPROTO_AH:
   3343 		if (ntohl(sav->spi) <= 255) {
   3344 			IPSECLOG(LOG_DEBUG, "illegal range of SPI %u.\n",
   3345 			    (u_int32_t)ntohl(sav->spi));
   3346 			return EINVAL;
   3347 		}
   3348 		break;
   3349 	}
   3350 
   3351 	/* check satype */
   3352 	switch (sav->sah->saidx.proto) {
   3353 	case IPPROTO_ESP:
   3354 		/* check flags */
   3355 		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
   3356 		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
   3357 			IPSECLOG(LOG_DEBUG,
   3358 			    "invalid flag (derived) given to old-esp.\n");
   3359 			return EINVAL;
   3360 		}
   3361 		error = xform_init(sav, XF_ESP);
   3362 		break;
   3363 	case IPPROTO_AH:
   3364 		/* check flags */
   3365 		if (sav->flags & SADB_X_EXT_DERIV) {
   3366 			IPSECLOG(LOG_DEBUG,
   3367 			    "invalid flag (derived) given to AH SA.\n");
   3368 			return EINVAL;
   3369 		}
   3370 		if (sav->alg_enc != SADB_EALG_NONE) {
   3371 			IPSECLOG(LOG_DEBUG,
   3372 			    "protocol and algorithm mismated.\n");
   3373 			return(EINVAL);
   3374 		}
   3375 		error = xform_init(sav, XF_AH);
   3376 		break;
   3377 	case IPPROTO_IPCOMP:
   3378 		if (sav->alg_auth != SADB_AALG_NONE) {
   3379 			IPSECLOG(LOG_DEBUG,
   3380 			    "protocol and algorithm mismated.\n");
   3381 			return(EINVAL);
   3382 		}
   3383 		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
   3384 		 && ntohl(sav->spi) >= 0x10000) {
   3385 			IPSECLOG(LOG_DEBUG, "invalid cpi for IPComp.\n");
   3386 			return(EINVAL);
   3387 		}
   3388 		error = xform_init(sav, XF_IPCOMP);
   3389 		break;
   3390 	case IPPROTO_TCP:
   3391 		if (sav->alg_enc != SADB_EALG_NONE) {
   3392 			IPSECLOG(LOG_DEBUG,
   3393 			    "protocol and algorithm mismated.\n");
   3394 			return(EINVAL);
   3395 		}
   3396 		error = xform_init(sav, XF_TCPSIGNATURE);
   3397 		break;
   3398 	default:
   3399 		IPSECLOG(LOG_DEBUG, "Invalid satype.\n");
   3400 		error = EPROTONOSUPPORT;
   3401 		break;
   3402 	}
   3403 
   3404 	return error;
   3405 }
   3406 
   3407 /*
   3408  * subroutine for SADB_GET and SADB_DUMP.
   3409  */
   3410 static struct mbuf *
   3411 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
   3412 	      u_int32_t seq, u_int32_t pid)
   3413 {
   3414 	struct mbuf *result = NULL, *tres = NULL, *m;
   3415 	int l = 0;
   3416 	int i;
   3417 	void *p;
   3418 	struct sadb_lifetime lt;
   3419 	int dumporder[] = {
   3420 		SADB_EXT_SA, SADB_X_EXT_SA2,
   3421 		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
   3422 		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
   3423 		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
   3424 		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
   3425 		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
   3426 		SADB_X_EXT_NAT_T_TYPE,
   3427 		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
   3428 		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
   3429 		SADB_X_EXT_NAT_T_FRAG,
   3430 
   3431 	};
   3432 
   3433 	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
   3434 	if (m == NULL)
   3435 		goto fail;
   3436 	result = m;
   3437 
   3438 	for (i = __arraycount(dumporder) - 1; i >= 0; i--) {
   3439 		m = NULL;
   3440 		p = NULL;
   3441 		switch (dumporder[i]) {
   3442 		case SADB_EXT_SA:
   3443 			m = key_setsadbsa(sav);
   3444 			break;
   3445 
   3446 		case SADB_X_EXT_SA2:
   3447 			m = key_setsadbxsa2(sav->sah->saidx.mode,
   3448 			    sav->replay ? sav->replay->count : 0,
   3449 			    sav->sah->saidx.reqid);
   3450 			break;
   3451 
   3452 		case SADB_EXT_ADDRESS_SRC:
   3453 			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   3454 			    &sav->sah->saidx.src.sa,
   3455 			    FULLMASK, IPSEC_ULPROTO_ANY);
   3456 			break;
   3457 
   3458 		case SADB_EXT_ADDRESS_DST:
   3459 			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   3460 			    &sav->sah->saidx.dst.sa,
   3461 			    FULLMASK, IPSEC_ULPROTO_ANY);
   3462 			break;
   3463 
   3464 		case SADB_EXT_KEY_AUTH:
   3465 			if (!sav->key_auth)
   3466 				continue;
   3467 			l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
   3468 			p = sav->key_auth;
   3469 			break;
   3470 
   3471 		case SADB_EXT_KEY_ENCRYPT:
   3472 			if (!sav->key_enc)
   3473 				continue;
   3474 			l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
   3475 			p = sav->key_enc;
   3476 			break;
   3477 
   3478 		case SADB_EXT_LIFETIME_CURRENT:
   3479 			if (!sav->lft_c)
   3480 				continue;
   3481 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
   3482 			memcpy(&lt, sav->lft_c, sizeof(struct sadb_lifetime));
   3483 			lt.sadb_lifetime_addtime += time_second - time_uptime;
   3484 			lt.sadb_lifetime_usetime += time_second - time_uptime;
   3485 			p = &lt;
   3486 			break;
   3487 
   3488 		case SADB_EXT_LIFETIME_HARD:
   3489 			if (!sav->lft_h)
   3490 				continue;
   3491 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
   3492 			p = sav->lft_h;
   3493 			break;
   3494 
   3495 		case SADB_EXT_LIFETIME_SOFT:
   3496 			if (!sav->lft_s)
   3497 				continue;
   3498 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
   3499 			p = sav->lft_s;
   3500 			break;
   3501 
   3502 		case SADB_X_EXT_NAT_T_TYPE:
   3503 			m = key_setsadbxtype(sav->natt_type);
   3504 			break;
   3505 
   3506 		case SADB_X_EXT_NAT_T_DPORT:
   3507 			if (sav->natt_type == 0)
   3508 				continue;
   3509 			m = key_setsadbxport(
   3510 			    key_portfromsaddr(&sav->sah->saidx.dst),
   3511 			    SADB_X_EXT_NAT_T_DPORT);
   3512 			break;
   3513 
   3514 		case SADB_X_EXT_NAT_T_SPORT:
   3515 			if (sav->natt_type == 0)
   3516 				continue;
   3517 			m = key_setsadbxport(
   3518 			    key_portfromsaddr(&sav->sah->saidx.src),
   3519 			    SADB_X_EXT_NAT_T_SPORT);
   3520 			break;
   3521 
   3522 		case SADB_X_EXT_NAT_T_FRAG:
   3523 			/* don't send frag info if not set */
   3524 			if (sav->natt_type == 0 || sav->esp_frag == IP_MAXPACKET)
   3525 				continue;
   3526 			m = key_setsadbxfrag(sav->esp_frag);
   3527 			break;
   3528 
   3529 		case SADB_X_EXT_NAT_T_OAI:
   3530 		case SADB_X_EXT_NAT_T_OAR:
   3531 			continue;
   3532 
   3533 		case SADB_EXT_ADDRESS_PROXY:
   3534 		case SADB_EXT_IDENTITY_SRC:
   3535 		case SADB_EXT_IDENTITY_DST:
   3536 			/* XXX: should we brought from SPD ? */
   3537 		case SADB_EXT_SENSITIVITY:
   3538 		default:
   3539 			continue;
   3540 		}
   3541 
   3542 		KASSERT(!(m && p));
   3543 		if (!m && !p)
   3544 			goto fail;
   3545 		if (p && tres) {
   3546 			M_PREPEND(tres, l, M_DONTWAIT);
   3547 			if (!tres)
   3548 				goto fail;
   3549 			memcpy(mtod(tres, void *), p, l);
   3550 			continue;
   3551 		}
   3552 		if (p) {
   3553 			m = key_alloc_mbuf(l);
   3554 			if (!m)
   3555 				goto fail;
   3556 			m_copyback(m, 0, l, p);
   3557 		}
   3558 
   3559 		if (tres)
   3560 			m_cat(m, tres);
   3561 		tres = m;
   3562 	}
   3563 
   3564 	m_cat(result, tres);
   3565 	tres = NULL; /* avoid free on error below */
   3566 
   3567 	if (result->m_len < sizeof(struct sadb_msg)) {
   3568 		result = m_pullup(result, sizeof(struct sadb_msg));
   3569 		if (result == NULL)
   3570 			goto fail;
   3571 	}
   3572 
   3573 	result->m_pkthdr.len = 0;
   3574 	for (m = result; m; m = m->m_next)
   3575 		result->m_pkthdr.len += m->m_len;
   3576 
   3577 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   3578 	    PFKEY_UNIT64(result->m_pkthdr.len);
   3579 
   3580 	return result;
   3581 
   3582 fail:
   3583 	m_freem(result);
   3584 	m_freem(tres);
   3585 	return NULL;
   3586 }
   3587 
   3588 
   3589 /*
   3590  * set a type in sadb_x_nat_t_type
   3591  */
   3592 static struct mbuf *
   3593 key_setsadbxtype(u_int16_t type)
   3594 {
   3595 	struct mbuf *m;
   3596 	size_t len;
   3597 	struct sadb_x_nat_t_type *p;
   3598 
   3599 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
   3600 
   3601 	m = key_alloc_mbuf(len);
   3602 	if (!m || m->m_next) {	/*XXX*/
   3603 		if (m)
   3604 			m_freem(m);
   3605 		return NULL;
   3606 	}
   3607 
   3608 	p = mtod(m, struct sadb_x_nat_t_type *);
   3609 
   3610 	memset(p, 0, len);
   3611 	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
   3612 	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
   3613 	p->sadb_x_nat_t_type_type = type;
   3614 
   3615 	return m;
   3616 }
   3617 /*
   3618  * set a port in sadb_x_nat_t_port. port is in network order
   3619  */
   3620 static struct mbuf *
   3621 key_setsadbxport(u_int16_t port, u_int16_t type)
   3622 {
   3623 	struct mbuf *m;
   3624 	size_t len;
   3625 	struct sadb_x_nat_t_port *p;
   3626 
   3627 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
   3628 
   3629 	m = key_alloc_mbuf(len);
   3630 	if (!m || m->m_next) {	/*XXX*/
   3631 		if (m)
   3632 			m_freem(m);
   3633 		return NULL;
   3634 	}
   3635 
   3636 	p = mtod(m, struct sadb_x_nat_t_port *);
   3637 
   3638 	memset(p, 0, len);
   3639 	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
   3640 	p->sadb_x_nat_t_port_exttype = type;
   3641 	p->sadb_x_nat_t_port_port = port;
   3642 
   3643 	return m;
   3644 }
   3645 
   3646 /*
   3647  * set fragmentation info in sadb_x_nat_t_frag
   3648  */
   3649 static struct mbuf *
   3650 key_setsadbxfrag(u_int16_t flen)
   3651 {
   3652 	struct mbuf *m;
   3653 	size_t len;
   3654 	struct sadb_x_nat_t_frag *p;
   3655 
   3656 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_frag));
   3657 
   3658 	m = key_alloc_mbuf(len);
   3659 	if (!m || m->m_next) {  /*XXX*/
   3660 		if (m)
   3661 			m_freem(m);
   3662 		return NULL;
   3663 	}
   3664 
   3665 	p = mtod(m, struct sadb_x_nat_t_frag *);
   3666 
   3667 	memset(p, 0, len);
   3668 	p->sadb_x_nat_t_frag_len = PFKEY_UNIT64(len);
   3669 	p->sadb_x_nat_t_frag_exttype = SADB_X_EXT_NAT_T_FRAG;
   3670 	p->sadb_x_nat_t_frag_fraglen = flen;
   3671 
   3672 	return m;
   3673 }
   3674 
   3675 /*
   3676  * Get port from sockaddr, port is in network order
   3677  */
   3678 u_int16_t
   3679 key_portfromsaddr(const union sockaddr_union *saddr)
   3680 {
   3681 	u_int16_t port;
   3682 
   3683 	switch (saddr->sa.sa_family) {
   3684 	case AF_INET: {
   3685 		port = saddr->sin.sin_port;
   3686 		break;
   3687 	}
   3688 #ifdef INET6
   3689 	case AF_INET6: {
   3690 		port = saddr->sin6.sin6_port;
   3691 		break;
   3692 	}
   3693 #endif
   3694 	default:
   3695 		printf("%s: unexpected address family\n", __func__);
   3696 		port = 0;
   3697 		break;
   3698 	}
   3699 
   3700 	return port;
   3701 }
   3702 
   3703 
   3704 /*
   3705  * Set port is struct sockaddr. port is in network order
   3706  */
   3707 static void
   3708 key_porttosaddr(union sockaddr_union *saddr, u_int16_t port)
   3709 {
   3710 	switch (saddr->sa.sa_family) {
   3711 	case AF_INET: {
   3712 		saddr->sin.sin_port = port;
   3713 		break;
   3714 	}
   3715 #ifdef INET6
   3716 	case AF_INET6: {
   3717 		saddr->sin6.sin6_port = port;
   3718 		break;
   3719 	}
   3720 #endif
   3721 	default:
   3722 		printf("%s: unexpected address family %d\n", __func__,
   3723 		    saddr->sa.sa_family);
   3724 		break;
   3725 	}
   3726 
   3727 	return;
   3728 }
   3729 
   3730 /*
   3731  * Safety check sa_len
   3732  */
   3733 static int
   3734 key_checksalen(const union sockaddr_union *saddr)
   3735 {
   3736 	switch (saddr->sa.sa_family) {
   3737 	case AF_INET:
   3738 		if (saddr->sa.sa_len != sizeof(struct sockaddr_in))
   3739 			return -1;
   3740 		break;
   3741 #ifdef INET6
   3742 	case AF_INET6:
   3743 		if (saddr->sa.sa_len != sizeof(struct sockaddr_in6))
   3744 			return -1;
   3745 		break;
   3746 #endif
   3747 	default:
   3748 		printf("%s: unexpected sa_family %d\n", __func__,
   3749 		    saddr->sa.sa_family);
   3750 			return -1;
   3751 		break;
   3752 	}
   3753 	return 0;
   3754 }
   3755 
   3756 
   3757 /*
   3758  * set data into sadb_msg.
   3759  */
   3760 static struct mbuf *
   3761 key_setsadbmsg(u_int8_t type,  u_int16_t tlen, u_int8_t satype,
   3762 	       u_int32_t seq, pid_t pid, u_int16_t reserved)
   3763 {
   3764 	struct mbuf *m;
   3765 	struct sadb_msg *p;
   3766 	int len;
   3767 
   3768 	CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) <= MCLBYTES);
   3769 
   3770 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   3771 
   3772 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   3773 	if (m && len > MHLEN) {
   3774 		MCLGET(m, M_DONTWAIT);
   3775 		if ((m->m_flags & M_EXT) == 0) {
   3776 			m_freem(m);
   3777 			m = NULL;
   3778 		}
   3779 	}
   3780 	if (!m)
   3781 		return NULL;
   3782 	m->m_pkthdr.len = m->m_len = len;
   3783 	m->m_next = NULL;
   3784 
   3785 	p = mtod(m, struct sadb_msg *);
   3786 
   3787 	memset(p, 0, len);
   3788 	p->sadb_msg_version = PF_KEY_V2;
   3789 	p->sadb_msg_type = type;
   3790 	p->sadb_msg_errno = 0;
   3791 	p->sadb_msg_satype = satype;
   3792 	p->sadb_msg_len = PFKEY_UNIT64(tlen);
   3793 	p->sadb_msg_reserved = reserved;
   3794 	p->sadb_msg_seq = seq;
   3795 	p->sadb_msg_pid = (u_int32_t)pid;
   3796 
   3797 	return m;
   3798 }
   3799 
   3800 /*
   3801  * copy secasvar data into sadb_address.
   3802  */
   3803 static struct mbuf *
   3804 key_setsadbsa(struct secasvar *sav)
   3805 {
   3806 	struct mbuf *m;
   3807 	struct sadb_sa *p;
   3808 	int len;
   3809 
   3810 	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
   3811 	m = key_alloc_mbuf(len);
   3812 	if (!m || m->m_next) {	/*XXX*/
   3813 		if (m)
   3814 			m_freem(m);
   3815 		return NULL;
   3816 	}
   3817 
   3818 	p = mtod(m, struct sadb_sa *);
   3819 
   3820 	memset(p, 0, len);
   3821 	p->sadb_sa_len = PFKEY_UNIT64(len);
   3822 	p->sadb_sa_exttype = SADB_EXT_SA;
   3823 	p->sadb_sa_spi = sav->spi;
   3824 	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
   3825 	p->sadb_sa_state = sav->state;
   3826 	p->sadb_sa_auth = sav->alg_auth;
   3827 	p->sadb_sa_encrypt = sav->alg_enc;
   3828 	p->sadb_sa_flags = sav->flags;
   3829 
   3830 	return m;
   3831 }
   3832 
   3833 /*
   3834  * set data into sadb_address.
   3835  */
   3836 static struct mbuf *
   3837 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
   3838 		u_int8_t prefixlen, u_int16_t ul_proto)
   3839 {
   3840 	struct mbuf *m;
   3841 	struct sadb_address *p;
   3842 	size_t len;
   3843 
   3844 	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
   3845 	    PFKEY_ALIGN8(saddr->sa_len);
   3846 	m = key_alloc_mbuf(len);
   3847 	if (!m || m->m_next) {	/*XXX*/
   3848 		if (m)
   3849 			m_freem(m);
   3850 		return NULL;
   3851 	}
   3852 
   3853 	p = mtod(m, struct sadb_address *);
   3854 
   3855 	memset(p, 0, len);
   3856 	p->sadb_address_len = PFKEY_UNIT64(len);
   3857 	p->sadb_address_exttype = exttype;
   3858 	p->sadb_address_proto = ul_proto;
   3859 	if (prefixlen == FULLMASK) {
   3860 		switch (saddr->sa_family) {
   3861 		case AF_INET:
   3862 			prefixlen = sizeof(struct in_addr) << 3;
   3863 			break;
   3864 		case AF_INET6:
   3865 			prefixlen = sizeof(struct in6_addr) << 3;
   3866 			break;
   3867 		default:
   3868 			; /*XXX*/
   3869 		}
   3870 	}
   3871 	p->sadb_address_prefixlen = prefixlen;
   3872 	p->sadb_address_reserved = 0;
   3873 
   3874 	memcpy(mtod(m, char *) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
   3875 	    saddr, saddr->sa_len);
   3876 
   3877 	return m;
   3878 }
   3879 
   3880 #if 0
   3881 /*
   3882  * set data into sadb_ident.
   3883  */
   3884 static struct mbuf *
   3885 key_setsadbident(u_int16_t exttype, u_int16_t idtype,
   3886 		 void *string, int stringlen, u_int64_t id)
   3887 {
   3888 	struct mbuf *m;
   3889 	struct sadb_ident *p;
   3890 	size_t len;
   3891 
   3892 	len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
   3893 	m = key_alloc_mbuf(len);
   3894 	if (!m || m->m_next) {	/*XXX*/
   3895 		if (m)
   3896 			m_freem(m);
   3897 		return NULL;
   3898 	}
   3899 
   3900 	p = mtod(m, struct sadb_ident *);
   3901 
   3902 	memset(p, 0, len);
   3903 	p->sadb_ident_len = PFKEY_UNIT64(len);
   3904 	p->sadb_ident_exttype = exttype;
   3905 	p->sadb_ident_type = idtype;
   3906 	p->sadb_ident_reserved = 0;
   3907 	p->sadb_ident_id = id;
   3908 
   3909 	memcpy(mtod(m, void *) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
   3910 	   	   string, stringlen);
   3911 
   3912 	return m;
   3913 }
   3914 #endif
   3915 
   3916 /*
   3917  * set data into sadb_x_sa2.
   3918  */
   3919 static struct mbuf *
   3920 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int16_t reqid)
   3921 {
   3922 	struct mbuf *m;
   3923 	struct sadb_x_sa2 *p;
   3924 	size_t len;
   3925 
   3926 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
   3927 	m = key_alloc_mbuf(len);
   3928 	if (!m || m->m_next) {	/*XXX*/
   3929 		if (m)
   3930 			m_freem(m);
   3931 		return NULL;
   3932 	}
   3933 
   3934 	p = mtod(m, struct sadb_x_sa2 *);
   3935 
   3936 	memset(p, 0, len);
   3937 	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
   3938 	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
   3939 	p->sadb_x_sa2_mode = mode;
   3940 	p->sadb_x_sa2_reserved1 = 0;
   3941 	p->sadb_x_sa2_reserved2 = 0;
   3942 	p->sadb_x_sa2_sequence = seq;
   3943 	p->sadb_x_sa2_reqid = reqid;
   3944 
   3945 	return m;
   3946 }
   3947 
   3948 /*
   3949  * set data into sadb_x_policy
   3950  */
   3951 static struct mbuf *
   3952 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
   3953 {
   3954 	struct mbuf *m;
   3955 	struct sadb_x_policy *p;
   3956 	size_t len;
   3957 
   3958 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
   3959 	m = key_alloc_mbuf(len);
   3960 	if (!m || m->m_next) {	/*XXX*/
   3961 		if (m)
   3962 			m_freem(m);
   3963 		return NULL;
   3964 	}
   3965 
   3966 	p = mtod(m, struct sadb_x_policy *);
   3967 
   3968 	memset(p, 0, len);
   3969 	p->sadb_x_policy_len = PFKEY_UNIT64(len);
   3970 	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
   3971 	p->sadb_x_policy_type = type;
   3972 	p->sadb_x_policy_dir = dir;
   3973 	p->sadb_x_policy_id = id;
   3974 
   3975 	return m;
   3976 }
   3977 
   3978 /* %%% utilities */
   3979 /*
   3980  * copy a buffer into the new buffer allocated.
   3981  */
   3982 static void *
   3983 key_newbuf(const void *src, u_int len)
   3984 {
   3985 	void *new;
   3986 
   3987 	new = kmem_alloc(len, KM_SLEEP);
   3988 	memcpy(new, src, len);
   3989 
   3990 	return new;
   3991 }
   3992 
   3993 /* compare my own address
   3994  * OUT:	1: true, i.e. my address.
   3995  *	0: false
   3996  */
   3997 int
   3998 key_ismyaddr(const struct sockaddr *sa)
   3999 {
   4000 #ifdef INET
   4001 	const struct sockaddr_in *sin;
   4002 	const struct in_ifaddr *ia;
   4003 	int s;
   4004 #endif
   4005 
   4006 	KASSERT(sa != NULL);
   4007 
   4008 	switch (sa->sa_family) {
   4009 #ifdef INET
   4010 	case AF_INET:
   4011 		sin = (const struct sockaddr_in *)sa;
   4012 		s = pserialize_read_enter();
   4013 		IN_ADDRLIST_READER_FOREACH(ia) {
   4014 			if (sin->sin_family == ia->ia_addr.sin_family &&
   4015 			    sin->sin_len == ia->ia_addr.sin_len &&
   4016 			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
   4017 			{
   4018 				pserialize_read_exit(s);
   4019 				return 1;
   4020 			}
   4021 		}
   4022 		pserialize_read_exit(s);
   4023 		break;
   4024 #endif
   4025 #ifdef INET6
   4026 	case AF_INET6:
   4027 		return key_ismyaddr6((const struct sockaddr_in6 *)sa);
   4028 #endif
   4029 	}
   4030 
   4031 	return 0;
   4032 }
   4033 
   4034 #ifdef INET6
   4035 /*
   4036  * compare my own address for IPv6.
   4037  * 1: ours
   4038  * 0: other
   4039  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
   4040  */
   4041 #include <netinet6/in6_var.h>
   4042 
   4043 static int
   4044 key_ismyaddr6(const struct sockaddr_in6 *sin6)
   4045 {
   4046 	struct in6_ifaddr *ia;
   4047 	int s;
   4048 	struct psref psref;
   4049 	int bound;
   4050 	int ours = 1;
   4051 
   4052 	bound = curlwp_bind();
   4053 	s = pserialize_read_enter();
   4054 	IN6_ADDRLIST_READER_FOREACH(ia) {
   4055 		bool ingroup;
   4056 
   4057 		if (key_sockaddr_match((const struct sockaddr *)&sin6,
   4058 		    (const struct sockaddr *)&ia->ia_addr, 0)) {
   4059 			pserialize_read_exit(s);
   4060 			goto ours;
   4061 		}
   4062 		ia6_acquire(ia, &psref);
   4063 		pserialize_read_exit(s);
   4064 
   4065 		/*
   4066 		 * XXX Multicast
   4067 		 * XXX why do we care about multlicast here while we don't care
   4068 		 * about IPv4 multicast??
   4069 		 * XXX scope
   4070 		 */
   4071 		ingroup = in6_multi_group(&sin6->sin6_addr, ia->ia_ifp);
   4072 		if (ingroup) {
   4073 			ia6_release(ia, &psref);
   4074 			goto ours;
   4075 		}
   4076 
   4077 		s = pserialize_read_enter();
   4078 		ia6_release(ia, &psref);
   4079 	}
   4080 	pserialize_read_exit(s);
   4081 
   4082 	/* loopback, just for safety */
   4083 	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
   4084 		goto ours;
   4085 
   4086 	ours = 0;
   4087 ours:
   4088 	curlwp_bindx(bound);
   4089 
   4090 	return ours;
   4091 }
   4092 #endif /*INET6*/
   4093 
   4094 /*
   4095  * compare two secasindex structure.
   4096  * flag can specify to compare 2 saidxes.
   4097  * compare two secasindex structure without both mode and reqid.
   4098  * don't compare port.
   4099  * IN:
   4100  *      saidx0: source, it can be in SAD.
   4101  *      saidx1: object.
   4102  * OUT:
   4103  *      1 : equal
   4104  *      0 : not equal
   4105  */
   4106 static int
   4107 key_saidx_match(
   4108 	const struct secasindex *saidx0,
   4109 	const struct secasindex *saidx1,
   4110 	int flag)
   4111 {
   4112 	int chkport;
   4113 	const struct sockaddr *sa0src, *sa0dst, *sa1src, *sa1dst;
   4114 
   4115 	KASSERT(saidx0 != NULL);
   4116 	KASSERT(saidx1 != NULL);
   4117 
   4118 	/* sanity */
   4119 	if (saidx0->proto != saidx1->proto)
   4120 		return 0;
   4121 
   4122 	if (flag == CMP_EXACTLY) {
   4123 		if (saidx0->mode != saidx1->mode)
   4124 			return 0;
   4125 		if (saidx0->reqid != saidx1->reqid)
   4126 			return 0;
   4127 		if (memcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
   4128 		    memcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
   4129 			return 0;
   4130 	} else {
   4131 
   4132 		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
   4133 		if (flag == CMP_MODE_REQID ||flag == CMP_REQID) {
   4134 			/*
   4135 			 * If reqid of SPD is non-zero, unique SA is required.
   4136 			 * The result must be of same reqid in this case.
   4137 			 */
   4138 			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
   4139 				return 0;
   4140 		}
   4141 
   4142 		if (flag == CMP_MODE_REQID) {
   4143 			if (saidx0->mode != IPSEC_MODE_ANY &&
   4144 			    saidx0->mode != saidx1->mode)
   4145 				return 0;
   4146 		}
   4147 
   4148 
   4149 		sa0src = &saidx0->src.sa;
   4150 		sa0dst = &saidx0->dst.sa;
   4151 		sa1src = &saidx1->src.sa;
   4152 		sa1dst = &saidx1->dst.sa;
   4153 		/*
   4154 		 * If NAT-T is enabled, check ports for tunnel mode.
   4155 		 * Don't do it for transport mode, as there is no
   4156 		 * port information available in the SP.
   4157 		 * Also don't check ports if they are set to zero
   4158 		 * in the SPD: This means we have a non-generated
   4159 		 * SPD which can't know UDP ports.
   4160 		 */
   4161 		if (saidx1->mode == IPSEC_MODE_TUNNEL)
   4162 			chkport = PORT_LOOSE;
   4163 		else
   4164 			chkport = PORT_NONE;
   4165 
   4166 		if (!key_sockaddr_match(sa0src, sa1src, chkport)) {
   4167 			return 0;
   4168 		}
   4169 		if (!key_sockaddr_match(sa0dst, sa1dst, chkport)) {
   4170 			return 0;
   4171 		}
   4172 	}
   4173 
   4174 	return 1;
   4175 }
   4176 
   4177 /*
   4178  * compare two secindex structure exactly.
   4179  * IN:
   4180  *	spidx0: source, it is often in SPD.
   4181  *	spidx1: object, it is often from PFKEY message.
   4182  * OUT:
   4183  *	1 : equal
   4184  *	0 : not equal
   4185  */
   4186 static int
   4187 key_spidx_match_exactly(
   4188 	const struct secpolicyindex *spidx0,
   4189 	const struct secpolicyindex *spidx1)
   4190 {
   4191 
   4192 	KASSERT(spidx0 != NULL);
   4193 	KASSERT(spidx1 != NULL);
   4194 
   4195 	/* sanity */
   4196 	if (spidx0->prefs != spidx1->prefs ||
   4197 	    spidx0->prefd != spidx1->prefd ||
   4198 	    spidx0->ul_proto != spidx1->ul_proto)
   4199 		return 0;
   4200 
   4201 	return key_sockaddr_match(&spidx0->src.sa, &spidx1->src.sa, PORT_STRICT) &&
   4202 	       key_sockaddr_match(&spidx0->dst.sa, &spidx1->dst.sa, PORT_STRICT);
   4203 }
   4204 
   4205 /*
   4206  * compare two secindex structure with mask.
   4207  * IN:
   4208  *	spidx0: source, it is often in SPD.
   4209  *	spidx1: object, it is often from IP header.
   4210  * OUT:
   4211  *	1 : equal
   4212  *	0 : not equal
   4213  */
   4214 static int
   4215 key_spidx_match_withmask(
   4216 	const struct secpolicyindex *spidx0,
   4217 	const struct secpolicyindex *spidx1)
   4218 {
   4219 
   4220 	KASSERT(spidx0 != NULL);
   4221 	KASSERT(spidx1 != NULL);
   4222 
   4223 	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
   4224 	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
   4225 	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
   4226 	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
   4227 		return 0;
   4228 
   4229 	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
   4230 	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY &&
   4231 	    spidx0->ul_proto != spidx1->ul_proto)
   4232 		return 0;
   4233 
   4234 	switch (spidx0->src.sa.sa_family) {
   4235 	case AF_INET:
   4236 		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY &&
   4237 		    spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
   4238 			return 0;
   4239 		if (!key_bb_match_withmask(&spidx0->src.sin.sin_addr,
   4240 		    &spidx1->src.sin.sin_addr, spidx0->prefs))
   4241 			return 0;
   4242 		break;
   4243 	case AF_INET6:
   4244 		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY &&
   4245 		    spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
   4246 			return 0;
   4247 		/*
   4248 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4249 		 * as a wildcard scope, which matches any scope zone ID.
   4250 		 */
   4251 		if (spidx0->src.sin6.sin6_scope_id &&
   4252 		    spidx1->src.sin6.sin6_scope_id &&
   4253 		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
   4254 			return 0;
   4255 		if (!key_bb_match_withmask(&spidx0->src.sin6.sin6_addr,
   4256 		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
   4257 			return 0;
   4258 		break;
   4259 	default:
   4260 		/* XXX */
   4261 		if (memcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
   4262 			return 0;
   4263 		break;
   4264 	}
   4265 
   4266 	switch (spidx0->dst.sa.sa_family) {
   4267 	case AF_INET:
   4268 		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY &&
   4269 		    spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
   4270 			return 0;
   4271 		if (!key_bb_match_withmask(&spidx0->dst.sin.sin_addr,
   4272 		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
   4273 			return 0;
   4274 		break;
   4275 	case AF_INET6:
   4276 		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY &&
   4277 		    spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
   4278 			return 0;
   4279 		/*
   4280 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4281 		 * as a wildcard scope, which matches any scope zone ID.
   4282 		 */
   4283 		if (spidx0->src.sin6.sin6_scope_id &&
   4284 		    spidx1->src.sin6.sin6_scope_id &&
   4285 		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
   4286 			return 0;
   4287 		if (!key_bb_match_withmask(&spidx0->dst.sin6.sin6_addr,
   4288 		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
   4289 			return 0;
   4290 		break;
   4291 	default:
   4292 		/* XXX */
   4293 		if (memcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
   4294 			return 0;
   4295 		break;
   4296 	}
   4297 
   4298 	/* XXX Do we check other field ?  e.g. flowinfo */
   4299 
   4300 	return 1;
   4301 }
   4302 
   4303 /* returns 0 on match */
   4304 static int
   4305 key_portcomp(in_port_t port1, in_port_t port2, int howport)
   4306 {
   4307 	switch (howport) {
   4308 	case PORT_NONE:
   4309 		return 0;
   4310 	case PORT_LOOSE:
   4311 		if (port1 == 0 || port2 == 0)
   4312 			return 0;
   4313 		/*FALLTHROUGH*/
   4314 	case PORT_STRICT:
   4315 		if (port1 != port2) {
   4316 			KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4317 			    "port fail %d != %d\n", port1, port2);
   4318 			return 1;
   4319 		}
   4320 		return 0;
   4321 	default:
   4322 		KASSERT(0);
   4323 		return 1;
   4324 	}
   4325 }
   4326 
   4327 /* returns 1 on match */
   4328 static int
   4329 key_sockaddr_match(
   4330 	const struct sockaddr *sa1,
   4331 	const struct sockaddr *sa2,
   4332 	int howport)
   4333 {
   4334 	const struct sockaddr_in *sin1, *sin2;
   4335 	const struct sockaddr_in6 *sin61, *sin62;
   4336 
   4337 	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len) {
   4338 		KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4339 		    "fam/len fail %d != %d || %d != %d\n",
   4340 			sa1->sa_family, sa2->sa_family, sa1->sa_len,
   4341 			sa2->sa_len);
   4342 		return 0;
   4343 	}
   4344 
   4345 	switch (sa1->sa_family) {
   4346 	case AF_INET:
   4347 		if (sa1->sa_len != sizeof(struct sockaddr_in)) {
   4348 			KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4349 			    "len fail %d != %zu\n",
   4350 			    sa1->sa_len, sizeof(struct sockaddr_in));
   4351 			return 0;
   4352 		}
   4353 		sin1 = (const struct sockaddr_in *)sa1;
   4354 		sin2 = (const struct sockaddr_in *)sa2;
   4355 		if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr) {
   4356 			KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4357 			    "addr fail %#x != %#x\n",
   4358 			    sin1->sin_addr.s_addr, sin2->sin_addr.s_addr);
   4359 			return 0;
   4360 		}
   4361 		if (key_portcomp(sin1->sin_port, sin2->sin_port, howport)) {
   4362 			return 0;
   4363 		}
   4364 		KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
   4365 		    "addr success %#x[%d] == %#x[%d]\n",
   4366 		    sin1->sin_addr.s_addr, sin1->sin_port,
   4367 		    sin2->sin_addr.s_addr, sin2->sin_port);
   4368 		break;
   4369 	case AF_INET6:
   4370 		sin61 = (const struct sockaddr_in6 *)sa1;
   4371 		sin62 = (const struct sockaddr_in6 *)sa2;
   4372 		if (sa1->sa_len != sizeof(struct sockaddr_in6))
   4373 			return 0;	/*EINVAL*/
   4374 
   4375 		if (sin61->sin6_scope_id != sin62->sin6_scope_id) {
   4376 			return 0;
   4377 		}
   4378 		if (!IN6_ARE_ADDR_EQUAL(&sin61->sin6_addr, &sin62->sin6_addr)) {
   4379 			return 0;
   4380 		}
   4381 		if (key_portcomp(sin61->sin6_port, sin62->sin6_port, howport)) {
   4382 			return 0;
   4383 		}
   4384 		break;
   4385 	default:
   4386 		if (memcmp(sa1, sa2, sa1->sa_len) != 0)
   4387 			return 0;
   4388 		break;
   4389 	}
   4390 
   4391 	return 1;
   4392 }
   4393 
   4394 /*
   4395  * compare two buffers with mask.
   4396  * IN:
   4397  *	addr1: source
   4398  *	addr2: object
   4399  *	bits:  Number of bits to compare
   4400  * OUT:
   4401  *	1 : equal
   4402  *	0 : not equal
   4403  */
   4404 static int
   4405 key_bb_match_withmask(const void *a1, const void *a2, u_int bits)
   4406 {
   4407 	const unsigned char *p1 = a1;
   4408 	const unsigned char *p2 = a2;
   4409 
   4410 	/* XXX: This could be considerably faster if we compare a word
   4411 	 * at a time, but it is complicated on LSB Endian machines */
   4412 
   4413 	/* Handle null pointers */
   4414 	if (p1 == NULL || p2 == NULL)
   4415 		return (p1 == p2);
   4416 
   4417 	while (bits >= 8) {
   4418 		if (*p1++ != *p2++)
   4419 			return 0;
   4420 		bits -= 8;
   4421 	}
   4422 
   4423 	if (bits > 0) {
   4424 		u_int8_t mask = ~((1<<(8-bits))-1);
   4425 		if ((*p1 & mask) != (*p2 & mask))
   4426 			return 0;
   4427 	}
   4428 	return 1;	/* Match! */
   4429 }
   4430 
   4431 static void
   4432 key_timehandler_spd(time_t now)
   4433 {
   4434 	u_int dir;
   4435 	struct secpolicy *sp, *nextsp;
   4436 
   4437 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   4438 		LIST_FOREACH_SAFE(sp, &sptree[dir], chain, nextsp) {
   4439 			if (sp->state == IPSEC_SPSTATE_DEAD) {
   4440 				key_sp_unlink(sp);	/*XXX*/
   4441 
   4442 				/* 'sp' dead; continue transfers to
   4443 				 * 'sp = nextsp'
   4444 				 */
   4445 				continue;
   4446 			}
   4447 
   4448 			if (sp->lifetime == 0 && sp->validtime == 0)
   4449 				continue;
   4450 
   4451 			/* the deletion will occur next time */
   4452 			if ((sp->lifetime && now - sp->created > sp->lifetime) ||
   4453 			    (sp->validtime && now - sp->lastused > sp->validtime)) {
   4454 			  	key_sp_dead(sp);
   4455 				key_spdexpire(sp);
   4456 				continue;
   4457 			}
   4458 		}
   4459 	}
   4460 }
   4461 
   4462 static void
   4463 key_timehandler_sad(time_t now)
   4464 {
   4465 	struct secashead *sah, *nextsah;
   4466 	struct secasvar *sav, *nextsav;
   4467 
   4468 	LIST_FOREACH_SAFE(sah, &sahtree, chain, nextsah) {
   4469 		/* if sah has been dead, then delete it and process next sah. */
   4470 		if (sah->state == SADB_SASTATE_DEAD) {
   4471 			key_delsah(sah);
   4472 			continue;
   4473 		}
   4474 
   4475 		/* if LARVAL entry doesn't become MATURE, delete it. */
   4476 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL],
   4477 		    chain, nextsav) {
   4478 			if (now - sav->created > key_larval_lifetime) {
   4479 				KEY_FREESAV(&sav);
   4480 			}
   4481 		}
   4482 
   4483 		/*
   4484 		 * check MATURE entry to start to send expire message
   4485 		 * whether or not.
   4486 		 */
   4487 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE],
   4488 		    chain, nextsav) {
   4489 			/* we don't need to check. */
   4490 			if (sav->lft_s == NULL)
   4491 				continue;
   4492 
   4493 			/* sanity check */
   4494 			if (sav->lft_c == NULL) {
   4495 				IPSECLOG(LOG_DEBUG,
   4496 				    "There is no CURRENT time, why?\n");
   4497 				continue;
   4498 			}
   4499 
   4500 			/* check SOFT lifetime */
   4501 			if (sav->lft_s->sadb_lifetime_addtime != 0 &&
   4502 			    now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4503 				/*
   4504 				 * check SA to be used whether or not.
   4505 				 * when SA hasn't been used, delete it.
   4506 				 */
   4507 				if (sav->lft_c->sadb_lifetime_usetime == 0) {
   4508 					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4509 					KEY_FREESAV(&sav);
   4510 				} else {
   4511 					key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4512 					/*
   4513 					 * XXX If we keep to send expire
   4514 					 * message in the status of
   4515 					 * DYING. Do remove below code.
   4516 					 */
   4517 					key_expire(sav);
   4518 				}
   4519 			}
   4520 			/* check SOFT lifetime by bytes */
   4521 			/*
   4522 			 * XXX I don't know the way to delete this SA
   4523 			 * when new SA is installed.  Caution when it's
   4524 			 * installed too big lifetime by time.
   4525 			 */
   4526 			else if (sav->lft_s->sadb_lifetime_bytes != 0 &&
   4527 			         sav->lft_s->sadb_lifetime_bytes <
   4528 			         sav->lft_c->sadb_lifetime_bytes) {
   4529 
   4530 				key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4531 				/*
   4532 				 * XXX If we keep to send expire
   4533 				 * message in the status of
   4534 				 * DYING. Do remove below code.
   4535 				 */
   4536 				key_expire(sav);
   4537 			}
   4538 		}
   4539 
   4540 		/* check DYING entry to change status to DEAD. */
   4541 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING],
   4542 		    chain, nextsav) {
   4543 			/* we don't need to check. */
   4544 			if (sav->lft_h == NULL)
   4545 				continue;
   4546 
   4547 			/* sanity check */
   4548 			if (sav->lft_c == NULL) {
   4549 				IPSECLOG(LOG_DEBUG,
   4550 				    "There is no CURRENT time, why?\n");
   4551 				continue;
   4552 			}
   4553 
   4554 			if (sav->lft_h->sadb_lifetime_addtime != 0 &&
   4555 			    now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
   4556 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4557 				KEY_FREESAV(&sav);
   4558 			}
   4559 #if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
   4560 			else if (sav->lft_s != NULL
   4561 			      && sav->lft_s->sadb_lifetime_addtime != 0
   4562 			      && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4563 				/*
   4564 				 * XXX: should be checked to be
   4565 				 * installed the valid SA.
   4566 				 */
   4567 
   4568 				/*
   4569 				 * If there is no SA then sending
   4570 				 * expire message.
   4571 				 */
   4572 				key_expire(sav);
   4573 			}
   4574 #endif
   4575 			/* check HARD lifetime by bytes */
   4576 			else if (sav->lft_h->sadb_lifetime_bytes != 0 &&
   4577 			         sav->lft_h->sadb_lifetime_bytes <
   4578 			         sav->lft_c->sadb_lifetime_bytes) {
   4579 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4580 				KEY_FREESAV(&sav);
   4581 			}
   4582 		}
   4583 
   4584 		/* delete entry in DEAD */
   4585 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD],
   4586 		    chain, nextsav) {
   4587 			/* sanity check */
   4588 			if (sav->state != SADB_SASTATE_DEAD) {
   4589 				IPSECLOG(LOG_DEBUG,
   4590 				    "invalid sav->state (queue: %d SA: %d): "
   4591 				    "kill it anyway\n",
   4592 				    SADB_SASTATE_DEAD, sav->state);
   4593 			}
   4594 
   4595 			/*
   4596 			 * do not call key_freesav() here.
   4597 			 * sav should already be freed, and sav->refcnt
   4598 			 * shows other references to sav
   4599 			 * (such as from SPD).
   4600 			 */
   4601 		}
   4602 	}
   4603 }
   4604 
   4605 static void
   4606 key_timehandler_acq(time_t now)
   4607 {
   4608 #ifndef IPSEC_NONBLOCK_ACQUIRE
   4609 	struct secacq *acq, *nextacq;
   4610 
   4611     restart:
   4612 	mutex_enter(&key_mtx);
   4613 	LIST_FOREACH_SAFE(acq, &acqtree, chain, nextacq) {
   4614 		if (now - acq->created > key_blockacq_lifetime) {
   4615 			LIST_REMOVE(acq, chain);
   4616 			mutex_exit(&key_mtx);
   4617 			kmem_free(acq, sizeof(*acq));
   4618 			goto restart;
   4619 		}
   4620 	}
   4621 	mutex_exit(&key_mtx);
   4622 #endif
   4623 }
   4624 
   4625 static void
   4626 key_timehandler_spacq(time_t now)
   4627 {
   4628 #ifdef notyet
   4629 	struct secspacq *acq, *nextacq;
   4630 
   4631 	LIST_FOREACH_SAFE(acq, &spacqtree, chain, nextacq) {
   4632 		if (now - acq->created > key_blockacq_lifetime) {
   4633 			KASSERT(__LIST_CHAINED(acq));
   4634 			LIST_REMOVE(acq, chain);
   4635 			kmem_free(acq, sizeof(*acq));
   4636 		}
   4637 	}
   4638 #endif
   4639 }
   4640 
   4641 /*
   4642  * time handler.
   4643  * scanning SPD and SAD to check status for each entries,
   4644  * and do to remove or to expire.
   4645  */
   4646 static void
   4647 key_timehandler_work(struct work *wk, void *arg)
   4648 {
   4649 	int s;
   4650 	time_t now = time_uptime;
   4651 
   4652 	s = splsoftnet();
   4653 	mutex_enter(softnet_lock);
   4654 
   4655 	key_timehandler_spd(now);
   4656 	key_timehandler_sad(now);
   4657 	key_timehandler_acq(now);
   4658 	key_timehandler_spacq(now);
   4659 
   4660 	/* do exchange to tick time !! */
   4661 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   4662 
   4663 	mutex_exit(softnet_lock);
   4664 	splx(s);
   4665 	return;
   4666 }
   4667 
   4668 static void
   4669 key_timehandler(void *arg)
   4670 {
   4671 
   4672 	workqueue_enqueue(key_timehandler_wq, &key_timehandler_wk, NULL);
   4673 }
   4674 
   4675 u_long
   4676 key_random(void)
   4677 {
   4678 	u_long value;
   4679 
   4680 	key_randomfill(&value, sizeof(value));
   4681 	return value;
   4682 }
   4683 
   4684 void
   4685 key_randomfill(void *p, size_t l)
   4686 {
   4687 
   4688 	cprng_fast(p, l);
   4689 }
   4690 
   4691 /*
   4692  * map SADB_SATYPE_* to IPPROTO_*.
   4693  * if satype == SADB_SATYPE then satype is mapped to ~0.
   4694  * OUT:
   4695  *	0: invalid satype.
   4696  */
   4697 static u_int16_t
   4698 key_satype2proto(u_int8_t satype)
   4699 {
   4700 	switch (satype) {
   4701 	case SADB_SATYPE_UNSPEC:
   4702 		return IPSEC_PROTO_ANY;
   4703 	case SADB_SATYPE_AH:
   4704 		return IPPROTO_AH;
   4705 	case SADB_SATYPE_ESP:
   4706 		return IPPROTO_ESP;
   4707 	case SADB_X_SATYPE_IPCOMP:
   4708 		return IPPROTO_IPCOMP;
   4709 	case SADB_X_SATYPE_TCPSIGNATURE:
   4710 		return IPPROTO_TCP;
   4711 	default:
   4712 		return 0;
   4713 	}
   4714 	/* NOTREACHED */
   4715 }
   4716 
   4717 /*
   4718  * map IPPROTO_* to SADB_SATYPE_*
   4719  * OUT:
   4720  *	0: invalid protocol type.
   4721  */
   4722 static u_int8_t
   4723 key_proto2satype(u_int16_t proto)
   4724 {
   4725 	switch (proto) {
   4726 	case IPPROTO_AH:
   4727 		return SADB_SATYPE_AH;
   4728 	case IPPROTO_ESP:
   4729 		return SADB_SATYPE_ESP;
   4730 	case IPPROTO_IPCOMP:
   4731 		return SADB_X_SATYPE_IPCOMP;
   4732 	case IPPROTO_TCP:
   4733 		return SADB_X_SATYPE_TCPSIGNATURE;
   4734 	default:
   4735 		return 0;
   4736 	}
   4737 	/* NOTREACHED */
   4738 }
   4739 
   4740 static int
   4741 key_setsecasidx(int proto, int mode, int reqid,
   4742     const struct sockaddr *src, const struct sockaddr *dst,
   4743     struct secasindex * saidx)
   4744 {
   4745 	const union sockaddr_union *src_u = (const union sockaddr_union *)src;
   4746 	const union sockaddr_union *dst_u = (const union sockaddr_union *)dst;
   4747 
   4748 	/* sa len safety check */
   4749 	if (key_checksalen(src_u) != 0)
   4750 		return -1;
   4751 	if (key_checksalen(dst_u) != 0)
   4752 		return -1;
   4753 
   4754 	memset(saidx, 0, sizeof(*saidx));
   4755 	saidx->proto = proto;
   4756 	saidx->mode = mode;
   4757 	saidx->reqid = reqid;
   4758 	memcpy(&saidx->src, src_u, src_u->sa.sa_len);
   4759 	memcpy(&saidx->dst, dst_u, dst_u->sa.sa_len);
   4760 
   4761 	key_porttosaddr(&((saidx)->src), 0);
   4762 	key_porttosaddr(&((saidx)->dst), 0);
   4763 	return 0;
   4764 }
   4765 
   4766 static void
   4767 key_init_spidx_bymsghdr(struct secpolicyindex *spidx,
   4768     const struct sadb_msghdr *mhp)
   4769 {
   4770 	const struct sadb_address *src0, *dst0;
   4771 	const struct sockaddr *src, *dst;
   4772 	const struct sadb_x_policy *xpl0;
   4773 
   4774 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   4775 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   4776 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   4777 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   4778 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
   4779 
   4780 	memset(spidx, 0, sizeof(*spidx));
   4781 	spidx->dir = xpl0->sadb_x_policy_dir;
   4782 	spidx->prefs = src0->sadb_address_prefixlen;
   4783 	spidx->prefd = dst0->sadb_address_prefixlen;
   4784 	spidx->ul_proto = src0->sadb_address_proto;
   4785 	/* XXX boundary check against sa_len */
   4786 	memcpy(&spidx->src, src, src->sa_len);
   4787 	memcpy(&spidx->dst, dst, dst->sa_len);
   4788 }
   4789 
   4790 /* %%% PF_KEY */
   4791 /*
   4792  * SADB_GETSPI processing is to receive
   4793  *	<base, (SA2), src address, dst address, (SPI range)>
   4794  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
   4795  * tree with the status of LARVAL, and send
   4796  *	<base, SA(*), address(SD)>
   4797  * to the IKMPd.
   4798  *
   4799  * IN:	mhp: pointer to the pointer to each header.
   4800  * OUT:	NULL if fail.
   4801  *	other if success, return pointer to the message to send.
   4802  */
   4803 static int
   4804 key_api_getspi(struct socket *so, struct mbuf *m,
   4805 	   const struct sadb_msghdr *mhp)
   4806 {
   4807 	const struct sockaddr *src, *dst;
   4808 	struct secasindex saidx;
   4809 	struct secashead *newsah;
   4810 	struct secasvar *newsav;
   4811 	u_int8_t proto;
   4812 	u_int32_t spi;
   4813 	u_int8_t mode;
   4814 	u_int16_t reqid;
   4815 	int error;
   4816 
   4817 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   4818 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   4819 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   4820 		return key_senderror(so, m, EINVAL);
   4821 	}
   4822 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   4823 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   4824 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   4825 		return key_senderror(so, m, EINVAL);
   4826 	}
   4827 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   4828 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   4829 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   4830 	} else {
   4831 		mode = IPSEC_MODE_ANY;
   4832 		reqid = 0;
   4833 	}
   4834 
   4835 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   4836 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   4837 
   4838 	/* map satype to proto */
   4839 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   4840 	if (proto == 0) {
   4841 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   4842 		return key_senderror(so, m, EINVAL);
   4843 	}
   4844 
   4845 
   4846 	error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
   4847 	if (error != 0)
   4848 		return key_senderror(so, m, EINVAL);
   4849 
   4850 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   4851 	if (error != 0)
   4852 		return key_senderror(so, m, EINVAL);
   4853 
   4854 	/* SPI allocation */
   4855 	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
   4856 	    &saidx);
   4857 	if (spi == 0)
   4858 		return key_senderror(so, m, EINVAL);
   4859 
   4860 	/* get a SA index */
   4861 	newsah = key_getsah(&saidx, CMP_REQID);
   4862 	if (newsah == NULL) {
   4863 		/* create a new SA index */
   4864 		newsah = key_newsah(&saidx);
   4865 		if (newsah == NULL) {
   4866 			IPSECLOG(LOG_DEBUG, "No more memory.\n");
   4867 			return key_senderror(so, m, ENOBUFS);
   4868 		}
   4869 	}
   4870 
   4871 	/* get a new SA */
   4872 	/* XXX rewrite */
   4873 	newsav = KEY_NEWSAV(m, mhp, &error);
   4874 	if (newsav == NULL) {
   4875 		/* XXX don't free new SA index allocated in above. */
   4876 		return key_senderror(so, m, error);
   4877 	}
   4878 
   4879 	/* set spi */
   4880 	newsav->spi = htonl(spi);
   4881 
   4882 	/* add to satree */
   4883 	newsav->refcnt = 1;
   4884 	newsav->sah = newsah;
   4885 	newsav->state = SADB_SASTATE_LARVAL;
   4886 	LIST_INSERT_TAIL(&newsah->savtree[SADB_SASTATE_LARVAL], newsav,
   4887 	    secasvar, chain);
   4888 
   4889 #ifndef IPSEC_NONBLOCK_ACQUIRE
   4890 	/* delete the entry in acqtree */
   4891 	if (mhp->msg->sadb_msg_seq != 0) {
   4892 		struct secacq *acq;
   4893 		mutex_enter(&key_mtx);
   4894 		acq = key_getacqbyseq(mhp->msg->sadb_msg_seq);
   4895 		if (acq != NULL) {
   4896 			/* reset counter in order to deletion by timehandler. */
   4897 			acq->created = time_uptime;
   4898 			acq->count = 0;
   4899 		}
   4900 		mutex_exit(&key_mtx);
   4901 	}
   4902 #endif
   4903 
   4904     {
   4905 	struct mbuf *n, *nn;
   4906 	struct sadb_sa *m_sa;
   4907 	int off, len;
   4908 
   4909 	CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
   4910 	    PFKEY_ALIGN8(sizeof(struct sadb_sa)) <= MCLBYTES);
   4911 
   4912 	/* create new sadb_msg to reply. */
   4913 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
   4914 	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
   4915 
   4916 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   4917 	if (len > MHLEN) {
   4918 		MCLGET(n, M_DONTWAIT);
   4919 		if ((n->m_flags & M_EXT) == 0) {
   4920 			m_freem(n);
   4921 			n = NULL;
   4922 		}
   4923 	}
   4924 	if (!n)
   4925 		return key_senderror(so, m, ENOBUFS);
   4926 
   4927 	n->m_len = len;
   4928 	n->m_next = NULL;
   4929 	off = 0;
   4930 
   4931 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   4932 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   4933 
   4934 	m_sa = (struct sadb_sa *)(mtod(n, char *) + off);
   4935 	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
   4936 	m_sa->sadb_sa_exttype = SADB_EXT_SA;
   4937 	m_sa->sadb_sa_spi = htonl(spi);
   4938 	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
   4939 
   4940 	KASSERTMSG(off == len, "length inconsistency");
   4941 
   4942 	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
   4943 	    SADB_EXT_ADDRESS_DST);
   4944 	if (!n->m_next) {
   4945 		m_freem(n);
   4946 		return key_senderror(so, m, ENOBUFS);
   4947 	}
   4948 
   4949 	if (n->m_len < sizeof(struct sadb_msg)) {
   4950 		n = m_pullup(n, sizeof(struct sadb_msg));
   4951 		if (n == NULL)
   4952 			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   4953 	}
   4954 
   4955 	n->m_pkthdr.len = 0;
   4956 	for (nn = n; nn; nn = nn->m_next)
   4957 		n->m_pkthdr.len += nn->m_len;
   4958 
   4959 	key_fill_replymsg(n, newsav->seq);
   4960 
   4961 	m_freem(m);
   4962 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   4963     }
   4964 }
   4965 
   4966 /*
   4967  * allocating new SPI
   4968  * called by key_api_getspi().
   4969  * OUT:
   4970  *	0:	failure.
   4971  *	others: success.
   4972  */
   4973 static u_int32_t
   4974 key_do_getnewspi(const struct sadb_spirange *spirange,
   4975 		 const struct secasindex *saidx)
   4976 {
   4977 	u_int32_t newspi;
   4978 	u_int32_t spmin, spmax;
   4979 	int count = key_spi_trycnt;
   4980 
   4981 	/* set spi range to allocate */
   4982 	if (spirange != NULL) {
   4983 		spmin = spirange->sadb_spirange_min;
   4984 		spmax = spirange->sadb_spirange_max;
   4985 	} else {
   4986 		spmin = key_spi_minval;
   4987 		spmax = key_spi_maxval;
   4988 	}
   4989 	/* IPCOMP needs 2-byte SPI */
   4990 	if (saidx->proto == IPPROTO_IPCOMP) {
   4991 		u_int32_t t;
   4992 		if (spmin >= 0x10000)
   4993 			spmin = 0xffff;
   4994 		if (spmax >= 0x10000)
   4995 			spmax = 0xffff;
   4996 		if (spmin > spmax) {
   4997 			t = spmin; spmin = spmax; spmax = t;
   4998 		}
   4999 	}
   5000 
   5001 	if (spmin == spmax) {
   5002 		if (key_checkspidup(saidx, htonl(spmin))) {
   5003 			IPSECLOG(LOG_DEBUG, "SPI %u exists already.\n", spmin);
   5004 			return 0;
   5005 		}
   5006 
   5007 		count--; /* taking one cost. */
   5008 		newspi = spmin;
   5009 
   5010 	} else {
   5011 
   5012 		/* init SPI */
   5013 		newspi = 0;
   5014 
   5015 		/* when requesting to allocate spi ranged */
   5016 		while (count--) {
   5017 			/* generate pseudo-random SPI value ranged. */
   5018 			newspi = spmin + (key_random() % (spmax - spmin + 1));
   5019 
   5020 			if (!key_checkspidup(saidx, htonl(newspi)))
   5021 				break;
   5022 		}
   5023 
   5024 		if (count == 0 || newspi == 0) {
   5025 			IPSECLOG(LOG_DEBUG, "to allocate spi is failed.\n");
   5026 			return 0;
   5027 		}
   5028 	}
   5029 
   5030 	/* statistics */
   5031 	keystat.getspi_count =
   5032 	    (keystat.getspi_count + key_spi_trycnt - count) / 2;
   5033 
   5034 	return newspi;
   5035 }
   5036 
   5037 static int
   5038 key_handle_natt_info(struct secasvar *sav,
   5039       		     const struct sadb_msghdr *mhp)
   5040 {
   5041 	const char *msg = "?" ;
   5042 	struct sadb_x_nat_t_type *type;
   5043 	struct sadb_x_nat_t_port *sport, *dport;
   5044 	struct sadb_address *iaddr, *raddr;
   5045 	struct sadb_x_nat_t_frag *frag;
   5046 
   5047 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] == NULL ||
   5048 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] == NULL ||
   5049 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] == NULL)
   5050 		return 0;
   5051 
   5052 	if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) {
   5053 		msg = "TYPE";
   5054 		goto bad;
   5055 	}
   5056 
   5057 	if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) {
   5058 		msg = "SPORT";
   5059 		goto bad;
   5060 	}
   5061 
   5062 	if (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
   5063 		msg = "DPORT";
   5064 		goto bad;
   5065 	}
   5066 
   5067 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) {
   5068 		IPSECLOG(LOG_DEBUG, "NAT-T OAi present\n");
   5069 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr)) {
   5070 			msg = "OAI";
   5071 			goto bad;
   5072 		}
   5073 	}
   5074 
   5075 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
   5076 		IPSECLOG(LOG_DEBUG, "NAT-T OAr present\n");
   5077 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
   5078 			msg = "OAR";
   5079 			goto bad;
   5080 		}
   5081 	}
   5082 
   5083 	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
   5084 	    if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
   5085 		    msg = "FRAG";
   5086 		    goto bad;
   5087 	    }
   5088 	}
   5089 
   5090 	type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   5091 	sport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   5092 	dport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   5093 	iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
   5094 	raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
   5095 	frag = (struct sadb_x_nat_t_frag *)mhp->ext[SADB_X_EXT_NAT_T_FRAG];
   5096 
   5097 	IPSECLOG(LOG_DEBUG, "type %d, sport = %d, dport = %d\n",
   5098 	    type->sadb_x_nat_t_type_type,
   5099 	    ntohs(sport->sadb_x_nat_t_port_port),
   5100 	    ntohs(dport->sadb_x_nat_t_port_port));
   5101 
   5102 	sav->natt_type = type->sadb_x_nat_t_type_type;
   5103 	key_porttosaddr(&sav->sah->saidx.src, sport->sadb_x_nat_t_port_port);
   5104 	key_porttosaddr(&sav->sah->saidx.dst, dport->sadb_x_nat_t_port_port);
   5105 	if (frag)
   5106 		sav->esp_frag = frag->sadb_x_nat_t_frag_fraglen;
   5107 	else
   5108 		sav->esp_frag = IP_MAXPACKET;
   5109 
   5110 	return 0;
   5111 bad:
   5112 	IPSECLOG(LOG_DEBUG, "invalid message %s\n", msg);
   5113 	__USE(msg);
   5114 	return -1;
   5115 }
   5116 
   5117 /* Just update the IPSEC_NAT_T ports if present */
   5118 static int
   5119 key_set_natt_ports(union sockaddr_union *src, union sockaddr_union *dst,
   5120       		     const struct sadb_msghdr *mhp)
   5121 {
   5122 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
   5123 		IPSECLOG(LOG_DEBUG, "NAT-T OAi present\n");
   5124 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
   5125 		IPSECLOG(LOG_DEBUG, "NAT-T OAr present\n");
   5126 
   5127 	if ((mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL) &&
   5128 	    (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL) &&
   5129 	    (mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL)) {
   5130 		struct sadb_x_nat_t_type *type;
   5131 		struct sadb_x_nat_t_port *sport;
   5132 		struct sadb_x_nat_t_port *dport;
   5133 
   5134 		if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
   5135 		    (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
   5136 		    (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
   5137 			IPSECLOG(LOG_DEBUG, "invalid message\n");
   5138 			return -1;
   5139 		}
   5140 
   5141 		type = (struct sadb_x_nat_t_type *)
   5142 		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   5143 		sport = (struct sadb_x_nat_t_port *)
   5144 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   5145 		dport = (struct sadb_x_nat_t_port *)
   5146 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   5147 
   5148 		key_porttosaddr(src, sport->sadb_x_nat_t_port_port);
   5149 		key_porttosaddr(dst, dport->sadb_x_nat_t_port_port);
   5150 
   5151 		IPSECLOG(LOG_DEBUG, "type %d, sport = %d, dport = %d\n",
   5152 		    type->sadb_x_nat_t_type_type,
   5153 		    ntohs(sport->sadb_x_nat_t_port_port),
   5154 		    ntohs(dport->sadb_x_nat_t_port_port));
   5155 	}
   5156 
   5157 	return 0;
   5158 }
   5159 
   5160 
   5161 /*
   5162  * SADB_UPDATE processing
   5163  * receive
   5164  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5165  *       key(AE), (identity(SD),) (sensitivity)>
   5166  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
   5167  * and send
   5168  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5169  *       (identity(SD),) (sensitivity)>
   5170  * to the ikmpd.
   5171  *
   5172  * m will always be freed.
   5173  */
   5174 static int
   5175 key_api_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
   5176 {
   5177 	struct sadb_sa *sa0;
   5178 	const struct sockaddr *src, *dst;
   5179 	struct secasindex saidx;
   5180 	struct secashead *sah;
   5181 	struct secasvar *sav, *newsav;
   5182 	u_int16_t proto;
   5183 	u_int8_t mode;
   5184 	u_int16_t reqid;
   5185 	int error;
   5186 
   5187 	/* map satype to proto */
   5188 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   5189 	if (proto == 0) {
   5190 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5191 		return key_senderror(so, m, EINVAL);
   5192 	}
   5193 
   5194 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5195 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5196 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5197 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5198 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5199 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5200 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5201 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5202 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5203 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5204 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5205 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5206 		return key_senderror(so, m, EINVAL);
   5207 	}
   5208 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5209 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5210 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5211 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5212 		return key_senderror(so, m, EINVAL);
   5213 	}
   5214 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5215 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5216 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5217 	} else {
   5218 		mode = IPSEC_MODE_ANY;
   5219 		reqid = 0;
   5220 	}
   5221 	/* XXX boundary checking for other extensions */
   5222 
   5223 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5224 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5225 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5226 
   5227 	error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
   5228 	if (error != 0)
   5229 		return key_senderror(so, m, EINVAL);
   5230 
   5231 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5232 	if (error != 0)
   5233 		return key_senderror(so, m, EINVAL);
   5234 
   5235 	/* get a SA header */
   5236 	sah = key_getsah(&saidx, CMP_REQID);
   5237 	if (sah == NULL) {
   5238 		IPSECLOG(LOG_DEBUG, "no SA index found.\n");
   5239 		return key_senderror(so, m, ENOENT);
   5240 	}
   5241 
   5242 	/* set spidx if there */
   5243 	/* XXX rewrite */
   5244 	error = key_setident(sah, m, mhp);
   5245 	if (error)
   5246 		return key_senderror(so, m, error);
   5247 
   5248 	/* find a SA with sequence number. */
   5249 #ifdef IPSEC_DOSEQCHECK
   5250 	if (mhp->msg->sadb_msg_seq != 0) {
   5251 		sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq);
   5252 		if (sav == NULL) {
   5253 			IPSECLOG(LOG_DEBUG,
   5254 			    "no larval SA with sequence %u exists.\n",
   5255 			    mhp->msg->sadb_msg_seq);
   5256 			return key_senderror(so, m, ENOENT);
   5257 		}
   5258 	}
   5259 #else
   5260 	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5261 	if (sav == NULL) {
   5262 		IPSECLOG(LOG_DEBUG, "no such a SA found (spi:%u)\n",
   5263 		    (u_int32_t)ntohl(sa0->sadb_sa_spi));
   5264 		return key_senderror(so, m, EINVAL);
   5265 	}
   5266 #endif
   5267 
   5268 	/* validity check */
   5269 	if (sav->sah->saidx.proto != proto) {
   5270 		IPSECLOG(LOG_DEBUG, "protocol mismatched (DB=%u param=%u)\n",
   5271 		    sav->sah->saidx.proto, proto);
   5272 		error = EINVAL;
   5273 		goto error;
   5274 	}
   5275 #ifdef IPSEC_DOSEQCHECK
   5276 	if (sav->spi != sa0->sadb_sa_spi) {
   5277 		IPSECLOG(LOG_DEBUG, "SPI mismatched (DB:%u param:%u)\n",
   5278 		    (u_int32_t)ntohl(sav->spi),
   5279 		    (u_int32_t)ntohl(sa0->sadb_sa_spi));
   5280 		error = EINVAL;
   5281 		goto error;
   5282 	}
   5283 #endif
   5284 	if (sav->pid != mhp->msg->sadb_msg_pid) {
   5285 		IPSECLOG(LOG_DEBUG, "pid mismatched (DB:%u param:%u)\n",
   5286 		    sav->pid, mhp->msg->sadb_msg_pid);
   5287 		error = EINVAL;
   5288 		goto error;
   5289 	}
   5290 
   5291 	/*
   5292 	 * Allocate a new SA instead of modifying the existing SA directly
   5293 	 * to avoid race conditions.
   5294 	 */
   5295 	newsav = kmem_zalloc(sizeof(struct secasvar), KM_SLEEP);
   5296 
   5297 	/* copy sav values */
   5298 	newsav->spi = sav->spi;
   5299 	newsav->seq = sav->seq;
   5300 	newsav->created = sav->created;
   5301 	newsav->pid = sav->pid;
   5302 	newsav->sah = sav->sah;
   5303 
   5304 	error = key_setsaval(newsav, m, mhp);
   5305 	if (error) {
   5306 		key_delsav(newsav);
   5307 		goto error;
   5308 	}
   5309 
   5310 	error = key_handle_natt_info(newsav, mhp);
   5311 	if (error != 0) {
   5312 		key_delsav(newsav);
   5313 		goto error;
   5314 	}
   5315 
   5316 	error = key_init_xform(newsav);
   5317 	if (error != 0) {
   5318 		key_delsav(newsav);
   5319 		goto error;
   5320 	}
   5321 
   5322 	/* add to satree */
   5323 	newsav->refcnt = 1;
   5324 	newsav->state = SADB_SASTATE_MATURE;
   5325 	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_MATURE], newsav,
   5326 	    secasvar, chain);
   5327 
   5328 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5329 	KEY_FREESAV(&sav);
   5330 	KEY_FREESAV(&sav);
   5331 
   5332     {
   5333 	struct mbuf *n;
   5334 
   5335 	/* set msg buf from mhp */
   5336 	n = key_getmsgbuf_x1(m, mhp);
   5337 	if (n == NULL) {
   5338 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   5339 		return key_senderror(so, m, ENOBUFS);
   5340 	}
   5341 
   5342 	m_freem(m);
   5343 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5344     }
   5345 error:
   5346 	KEY_FREESAV(&sav);
   5347 	return key_senderror(so, m, error);
   5348 }
   5349 
   5350 /*
   5351  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
   5352  * only called by key_api_update().
   5353  * OUT:
   5354  *	NULL	: not found
   5355  *	others	: found, pointer to a SA.
   5356  */
   5357 #ifdef IPSEC_DOSEQCHECK
   5358 static struct secasvar *
   5359 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
   5360 {
   5361 	struct secasvar *sav;
   5362 	u_int state;
   5363 
   5364 	state = SADB_SASTATE_LARVAL;
   5365 
   5366 	/* search SAD with sequence number ? */
   5367 	LIST_FOREACH(sav, &sah->savtree[state], chain) {
   5368 
   5369 		KEY_CHKSASTATE(state, sav->state);
   5370 
   5371 		if (sav->seq == seq) {
   5372 			SA_ADDREF(sav);
   5373 			KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
   5374 			    "DP cause refcnt++:%d SA:%p\n",
   5375 			    sav->refcnt, sav);
   5376 			return sav;
   5377 		}
   5378 	}
   5379 
   5380 	return NULL;
   5381 }
   5382 #endif
   5383 
   5384 /*
   5385  * SADB_ADD processing
   5386  * add an entry to SA database, when received
   5387  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5388  *       key(AE), (identity(SD),) (sensitivity)>
   5389  * from the ikmpd,
   5390  * and send
   5391  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5392  *       (identity(SD),) (sensitivity)>
   5393  * to the ikmpd.
   5394  *
   5395  * IGNORE identity and sensitivity messages.
   5396  *
   5397  * m will always be freed.
   5398  */
   5399 static int
   5400 key_api_add(struct socket *so, struct mbuf *m,
   5401 	const struct sadb_msghdr *mhp)
   5402 {
   5403 	struct sadb_sa *sa0;
   5404 	const struct sockaddr *src, *dst;
   5405 	struct secasindex saidx;
   5406 	struct secashead *newsah;
   5407 	struct secasvar *newsav;
   5408 	u_int16_t proto;
   5409 	u_int8_t mode;
   5410 	u_int16_t reqid;
   5411 	int error;
   5412 
   5413 	/* map satype to proto */
   5414 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   5415 	if (proto == 0) {
   5416 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5417 		return key_senderror(so, m, EINVAL);
   5418 	}
   5419 
   5420 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5421 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5422 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5423 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5424 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5425 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5426 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5427 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5428 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5429 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5430 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5431 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5432 		return key_senderror(so, m, EINVAL);
   5433 	}
   5434 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5435 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5436 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5437 		/* XXX need more */
   5438 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5439 		return key_senderror(so, m, EINVAL);
   5440 	}
   5441 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5442 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5443 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5444 	} else {
   5445 		mode = IPSEC_MODE_ANY;
   5446 		reqid = 0;
   5447 	}
   5448 
   5449 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5450 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5451 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5452 
   5453 	error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
   5454 	if (error != 0)
   5455 		return key_senderror(so, m, EINVAL);
   5456 
   5457 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5458 	if (error != 0)
   5459 		return key_senderror(so, m, EINVAL);
   5460 
   5461 	/* get a SA header */
   5462 	newsah = key_getsah(&saidx, CMP_REQID);
   5463 	if (newsah == NULL) {
   5464 		/* create a new SA header */
   5465 		newsah = key_newsah(&saidx);
   5466 		if (newsah == NULL) {
   5467 			IPSECLOG(LOG_DEBUG, "No more memory.\n");
   5468 			return key_senderror(so, m, ENOBUFS);
   5469 		}
   5470 	}
   5471 
   5472 	/* set spidx if there */
   5473 	/* XXX rewrite */
   5474 	error = key_setident(newsah, m, mhp);
   5475 	if (error) {
   5476 		return key_senderror(so, m, error);
   5477 	}
   5478 
   5479     {
   5480 	struct secasvar *sav;
   5481 
   5482 	/* We can create new SA only if SPI is differenct. */
   5483 	sav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
   5484 	if (sav != NULL) {
   5485 		KEY_FREESAV(&sav);
   5486 		IPSECLOG(LOG_DEBUG, "SA already exists.\n");
   5487 		return key_senderror(so, m, EEXIST);
   5488 	}
   5489     }
   5490 
   5491 	/* create new SA entry. */
   5492 	newsav = KEY_NEWSAV(m, mhp, &error);
   5493 	if (newsav == NULL) {
   5494 		return key_senderror(so, m, error);
   5495 	}
   5496 	newsav->sah = newsah;
   5497 
   5498 	error = key_handle_natt_info(newsav, mhp);
   5499 	if (error != 0) {
   5500 		key_delsav(newsav);
   5501 		return key_senderror(so, m, EINVAL);
   5502 	}
   5503 
   5504 	error = key_init_xform(newsav);
   5505 	if (error != 0) {
   5506 		key_delsav(newsav);
   5507 		return key_senderror(so, m, error);
   5508 	}
   5509 
   5510 	/* add to satree */
   5511 	newsav->refcnt = 1;
   5512 	newsav->state = SADB_SASTATE_MATURE;
   5513 	LIST_INSERT_TAIL(&newsah->savtree[SADB_SASTATE_MATURE], newsav,
   5514 	    secasvar, chain);
   5515 
   5516 	/*
   5517 	 * don't call key_freesav() here, as we would like to keep the SA
   5518 	 * in the database on success.
   5519 	 */
   5520 
   5521     {
   5522 	struct mbuf *n;
   5523 
   5524 	/* set msg buf from mhp */
   5525 	n = key_getmsgbuf_x1(m, mhp);
   5526 	if (n == NULL) {
   5527 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   5528 		return key_senderror(so, m, ENOBUFS);
   5529 	}
   5530 
   5531 	m_freem(m);
   5532 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5533     }
   5534 }
   5535 
   5536 /* m is retained */
   5537 static int
   5538 key_setident(struct secashead *sah, struct mbuf *m,
   5539 	     const struct sadb_msghdr *mhp)
   5540 {
   5541 	const struct sadb_ident *idsrc, *iddst;
   5542 	int idsrclen, iddstlen;
   5543 
   5544 	KASSERT(!cpu_softintr_p());
   5545 	KASSERT(sah != NULL);
   5546 	KASSERT(m != NULL);
   5547 	KASSERT(mhp != NULL);
   5548 	KASSERT(mhp->msg != NULL);
   5549 
   5550 	/*
   5551 	 * Can be called with an existing sah from key_api_update().
   5552 	 */
   5553 	if (sah->idents != NULL) {
   5554 		kmem_free(sah->idents, sah->idents_len);
   5555 		sah->idents = NULL;
   5556 		sah->idents_len = 0;
   5557 	}
   5558 	if (sah->identd != NULL) {
   5559 		kmem_free(sah->identd, sah->identd_len);
   5560 		sah->identd = NULL;
   5561 		sah->identd_len = 0;
   5562 	}
   5563 
   5564 	/* don't make buffer if not there */
   5565 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
   5566 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5567 		sah->idents = NULL;
   5568 		sah->identd = NULL;
   5569 		return 0;
   5570 	}
   5571 
   5572 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
   5573 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5574 		IPSECLOG(LOG_DEBUG, "invalid identity.\n");
   5575 		return EINVAL;
   5576 	}
   5577 
   5578 	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
   5579 	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
   5580 	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
   5581 	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
   5582 
   5583 	/* validity check */
   5584 	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
   5585 		IPSECLOG(LOG_DEBUG, "ident type mismatch.\n");
   5586 		return EINVAL;
   5587 	}
   5588 
   5589 	switch (idsrc->sadb_ident_type) {
   5590 	case SADB_IDENTTYPE_PREFIX:
   5591 	case SADB_IDENTTYPE_FQDN:
   5592 	case SADB_IDENTTYPE_USERFQDN:
   5593 	default:
   5594 		/* XXX do nothing */
   5595 		sah->idents = NULL;
   5596 		sah->identd = NULL;
   5597 	 	return 0;
   5598 	}
   5599 
   5600 	/* make structure */
   5601 	sah->idents = kmem_alloc(idsrclen, KM_SLEEP);
   5602 	sah->idents_len = idsrclen;
   5603 	sah->identd = kmem_alloc(iddstlen, KM_SLEEP);
   5604 	sah->identd_len = iddstlen;
   5605 	memcpy(sah->idents, idsrc, idsrclen);
   5606 	memcpy(sah->identd, iddst, iddstlen);
   5607 
   5608 	return 0;
   5609 }
   5610 
   5611 /*
   5612  * m will not be freed on return.
   5613  * it is caller's responsibility to free the result.
   5614  */
   5615 static struct mbuf *
   5616 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
   5617 {
   5618 	struct mbuf *n;
   5619 
   5620 	KASSERT(m != NULL);
   5621 	KASSERT(mhp != NULL);
   5622 	KASSERT(mhp->msg != NULL);
   5623 
   5624 	/* create new sadb_msg to reply. */
   5625 	n = key_gather_mbuf(m, mhp, 1, 15, SADB_EXT_RESERVED,
   5626 	    SADB_EXT_SA, SADB_X_EXT_SA2,
   5627 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
   5628 	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
   5629 	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
   5630 	    SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
   5631 	    SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
   5632 	    SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NAT_T_FRAG);
   5633 	if (!n)
   5634 		return NULL;
   5635 
   5636 	if (n->m_len < sizeof(struct sadb_msg)) {
   5637 		n = m_pullup(n, sizeof(struct sadb_msg));
   5638 		if (n == NULL)
   5639 			return NULL;
   5640 	}
   5641 	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
   5642 	mtod(n, struct sadb_msg *)->sadb_msg_len =
   5643 	    PFKEY_UNIT64(n->m_pkthdr.len);
   5644 
   5645 	return n;
   5646 }
   5647 
   5648 static int key_delete_all (struct socket *, struct mbuf *,
   5649 			   const struct sadb_msghdr *, u_int16_t);
   5650 
   5651 /*
   5652  * SADB_DELETE processing
   5653  * receive
   5654  *   <base, SA(*), address(SD)>
   5655  * from the ikmpd, and set SADB_SASTATE_DEAD,
   5656  * and send,
   5657  *   <base, SA(*), address(SD)>
   5658  * to the ikmpd.
   5659  *
   5660  * m will always be freed.
   5661  */
   5662 static int
   5663 key_api_delete(struct socket *so, struct mbuf *m,
   5664 	   const struct sadb_msghdr *mhp)
   5665 {
   5666 	struct sadb_sa *sa0;
   5667 	const struct sockaddr *src, *dst;
   5668 	struct secasindex saidx;
   5669 	struct secashead *sah;
   5670 	struct secasvar *sav = NULL;
   5671 	u_int16_t proto;
   5672 	int error;
   5673 
   5674 	/* map satype to proto */
   5675 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   5676 	if (proto == 0) {
   5677 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5678 		return key_senderror(so, m, EINVAL);
   5679 	}
   5680 
   5681 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5682 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5683 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5684 		return key_senderror(so, m, EINVAL);
   5685 	}
   5686 
   5687 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5688 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5689 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5690 		return key_senderror(so, m, EINVAL);
   5691 	}
   5692 
   5693 	if (mhp->ext[SADB_EXT_SA] == NULL) {
   5694 		/*
   5695 		 * Caller wants us to delete all non-LARVAL SAs
   5696 		 * that match the src/dst.  This is used during
   5697 		 * IKE INITIAL-CONTACT.
   5698 		 */
   5699 		IPSECLOG(LOG_DEBUG, "doing delete all.\n");
   5700 		return key_delete_all(so, m, mhp, proto);
   5701 	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
   5702 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5703 		return key_senderror(so, m, EINVAL);
   5704 	}
   5705 
   5706 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5707 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5708 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5709 
   5710 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   5711 	if (error != 0)
   5712 		return key_senderror(so, m, EINVAL);
   5713 
   5714 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5715 	if (error != 0)
   5716 		return key_senderror(so, m, EINVAL);
   5717 
   5718 	/* get a SA header */
   5719 	sah = key_getsah(&saidx, CMP_HEAD);
   5720 	if (sah != NULL) {
   5721 		/* get a SA with SPI. */
   5722 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5723 	}
   5724 
   5725 	if (sav == NULL) {
   5726 		IPSECLOG(LOG_DEBUG, "no SA found.\n");
   5727 		return key_senderror(so, m, ENOENT);
   5728 	}
   5729 
   5730 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5731 	KEY_FREESAV(&sav);
   5732 	KEY_FREESAV(&sav);
   5733 
   5734     {
   5735 	struct mbuf *n;
   5736 
   5737 	/* create new sadb_msg to reply. */
   5738 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
   5739 	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5740 	if (!n)
   5741 		return key_senderror(so, m, ENOBUFS);
   5742 
   5743 	n = key_fill_replymsg(n, 0);
   5744 	if (n == NULL)
   5745 		return key_senderror(so, m, ENOBUFS);
   5746 
   5747 	m_freem(m);
   5748 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5749     }
   5750 }
   5751 
   5752 /*
   5753  * delete all SAs for src/dst.  Called from key_api_delete().
   5754  */
   5755 static int
   5756 key_delete_all(struct socket *so, struct mbuf *m,
   5757 	       const struct sadb_msghdr *mhp, u_int16_t proto)
   5758 {
   5759 	const struct sockaddr *src, *dst;
   5760 	struct secasindex saidx;
   5761 	struct secashead *sah;
   5762 	struct secasvar *sav, *nextsav;
   5763 	u_int state;
   5764 	int error;
   5765 
   5766 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5767 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5768 
   5769 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   5770 	if (error != 0)
   5771 		return key_senderror(so, m, EINVAL);
   5772 
   5773 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5774 	if (error != 0)
   5775 		return key_senderror(so, m, EINVAL);
   5776 
   5777 	sah = key_getsah(&saidx, CMP_HEAD);
   5778 	if (sah != NULL) {
   5779 		/* Delete all non-LARVAL SAs. */
   5780 		SASTATE_ALIVE_FOREACH(state) {
   5781 			if (state == SADB_SASTATE_LARVAL)
   5782 				continue;
   5783 			LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain,
   5784 			    nextsav) {
   5785 				/* sanity check */
   5786 				if (sav->state != state) {
   5787 					IPSECLOG(LOG_DEBUG,
   5788 					    "invalid sav->state "
   5789 					    "(queue: %d SA: %d)\n",
   5790 					    state, sav->state);
   5791 					continue;
   5792 				}
   5793 
   5794 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5795 				KEY_FREESAV(&sav);
   5796 			}
   5797 		}
   5798 	}
   5799     {
   5800 	struct mbuf *n;
   5801 
   5802 	/* create new sadb_msg to reply. */
   5803 	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
   5804 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5805 	if (!n)
   5806 		return key_senderror(so, m, ENOBUFS);
   5807 
   5808 	n = key_fill_replymsg(n, 0);
   5809 	if (n == NULL)
   5810 		return key_senderror(so, m, ENOBUFS);
   5811 
   5812 	m_freem(m);
   5813 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5814     }
   5815 }
   5816 
   5817 /*
   5818  * SADB_GET processing
   5819  * receive
   5820  *   <base, SA(*), address(SD)>
   5821  * from the ikmpd, and get a SP and a SA to respond,
   5822  * and send,
   5823  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
   5824  *       (identity(SD),) (sensitivity)>
   5825  * to the ikmpd.
   5826  *
   5827  * m will always be freed.
   5828  */
   5829 static int
   5830 key_api_get(struct socket *so, struct mbuf *m,
   5831 	const struct sadb_msghdr *mhp)
   5832 {
   5833 	struct sadb_sa *sa0;
   5834 	const struct sockaddr *src, *dst;
   5835 	struct secasindex saidx;
   5836 	struct secashead *sah;
   5837 	struct secasvar *sav = NULL;
   5838 	u_int16_t proto;
   5839 	int error;
   5840 
   5841 	/* map satype to proto */
   5842 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5843 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   5844 		return key_senderror(so, m, EINVAL);
   5845 	}
   5846 
   5847 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5848 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5849 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5850 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5851 		return key_senderror(so, m, EINVAL);
   5852 	}
   5853 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5854 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5855 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5856 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   5857 		return key_senderror(so, m, EINVAL);
   5858 	}
   5859 
   5860 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5861 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   5862 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   5863 
   5864 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   5865 	if (error != 0)
   5866 		return key_senderror(so, m, EINVAL);
   5867 
   5868 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   5869 	if (error != 0)
   5870 		return key_senderror(so, m, EINVAL);
   5871 
   5872 	/* get a SA header */
   5873 	sah = key_getsah(&saidx, CMP_HEAD);
   5874 	if (sah != NULL) {
   5875 		/* get a SA with SPI. */
   5876 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5877 	}
   5878 	if (sav == NULL) {
   5879 		IPSECLOG(LOG_DEBUG, "no SA found.\n");
   5880 		return key_senderror(so, m, ENOENT);
   5881 	}
   5882 
   5883     {
   5884 	struct mbuf *n;
   5885 	u_int8_t satype;
   5886 
   5887 	/* map proto to satype */
   5888 	satype = key_proto2satype(sah->saidx.proto);
   5889 	if (satype == 0) {
   5890 		KEY_FREESAV(&sav);
   5891 		IPSECLOG(LOG_DEBUG, "there was invalid proto in SAD.\n");
   5892 		return key_senderror(so, m, EINVAL);
   5893 	}
   5894 
   5895 	/* create new sadb_msg to reply. */
   5896 	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
   5897 	    mhp->msg->sadb_msg_pid);
   5898 	KEY_FREESAV(&sav);
   5899 	if (!n)
   5900 		return key_senderror(so, m, ENOBUFS);
   5901 
   5902 	m_freem(m);
   5903 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   5904     }
   5905 }
   5906 
   5907 /* XXX make it sysctl-configurable? */
   5908 static void
   5909 key_getcomb_setlifetime(struct sadb_comb *comb)
   5910 {
   5911 
   5912 	comb->sadb_comb_soft_allocations = 1;
   5913 	comb->sadb_comb_hard_allocations = 1;
   5914 	comb->sadb_comb_soft_bytes = 0;
   5915 	comb->sadb_comb_hard_bytes = 0;
   5916 	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
   5917 	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
   5918 	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
   5919 	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
   5920 }
   5921 
   5922 /*
   5923  * XXX reorder combinations by preference
   5924  * XXX no idea if the user wants ESP authentication or not
   5925  */
   5926 static struct mbuf *
   5927 key_getcomb_esp(void)
   5928 {
   5929 	struct sadb_comb *comb;
   5930 	const struct enc_xform *algo;
   5931 	struct mbuf *result = NULL, *m, *n;
   5932 	int encmin;
   5933 	int i, off, o;
   5934 	int totlen;
   5935 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   5936 
   5937 	m = NULL;
   5938 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   5939 		algo = esp_algorithm_lookup(i);
   5940 		if (algo == NULL)
   5941 			continue;
   5942 
   5943 		/* discard algorithms with key size smaller than system min */
   5944 		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
   5945 			continue;
   5946 		if (_BITS(algo->minkey) < ipsec_esp_keymin)
   5947 			encmin = ipsec_esp_keymin;
   5948 		else
   5949 			encmin = _BITS(algo->minkey);
   5950 
   5951 		if (ipsec_esp_auth)
   5952 			m = key_getcomb_ah();
   5953 		else {
   5954 			KASSERTMSG(l <= MLEN,
   5955 			    "l=%u > MLEN=%lu", l, (u_long) MLEN);
   5956 			MGET(m, M_DONTWAIT, MT_DATA);
   5957 			if (m) {
   5958 				M_ALIGN(m, l);
   5959 				m->m_len = l;
   5960 				m->m_next = NULL;
   5961 				memset(mtod(m, void *), 0, m->m_len);
   5962 			}
   5963 		}
   5964 		if (!m)
   5965 			goto fail;
   5966 
   5967 		totlen = 0;
   5968 		for (n = m; n; n = n->m_next)
   5969 			totlen += n->m_len;
   5970 		KASSERTMSG((totlen % l) == 0, "totlen=%u, l=%u", totlen, l);
   5971 
   5972 		for (off = 0; off < totlen; off += l) {
   5973 			n = m_pulldown(m, off, l, &o);
   5974 			if (!n) {
   5975 				/* m is already freed */
   5976 				goto fail;
   5977 			}
   5978 			comb = (struct sadb_comb *)(mtod(n, char *) + o);
   5979 			memset(comb, 0, sizeof(*comb));
   5980 			key_getcomb_setlifetime(comb);
   5981 			comb->sadb_comb_encrypt = i;
   5982 			comb->sadb_comb_encrypt_minbits = encmin;
   5983 			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
   5984 		}
   5985 
   5986 		if (!result)
   5987 			result = m;
   5988 		else
   5989 			m_cat(result, m);
   5990 	}
   5991 
   5992 	return result;
   5993 
   5994  fail:
   5995 	if (result)
   5996 		m_freem(result);
   5997 	return NULL;
   5998 }
   5999 
   6000 static void
   6001 key_getsizes_ah(const struct auth_hash *ah, int alg,
   6002 	        u_int16_t* ksmin, u_int16_t* ksmax)
   6003 {
   6004 	*ksmin = *ksmax = ah->keysize;
   6005 	if (ah->keysize == 0) {
   6006 		/*
   6007 		 * Transform takes arbitrary key size but algorithm
   6008 		 * key size is restricted.  Enforce this here.
   6009 		 */
   6010 		switch (alg) {
   6011 		case SADB_X_AALG_MD5:	*ksmin = *ksmax = 16; break;
   6012 		case SADB_X_AALG_SHA:	*ksmin = *ksmax = 20; break;
   6013 		case SADB_X_AALG_NULL:	*ksmin = 0; *ksmax = 256; break;
   6014 		default:
   6015 			IPSECLOG(LOG_DEBUG, "unknown AH algorithm %u\n", alg);
   6016 			break;
   6017 		}
   6018 	}
   6019 }
   6020 
   6021 /*
   6022  * XXX reorder combinations by preference
   6023  */
   6024 static struct mbuf *
   6025 key_getcomb_ah(void)
   6026 {
   6027 	struct sadb_comb *comb;
   6028 	const struct auth_hash *algo;
   6029 	struct mbuf *m;
   6030 	u_int16_t minkeysize, maxkeysize;
   6031 	int i;
   6032 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6033 
   6034 	m = NULL;
   6035 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   6036 #if 1
   6037 		/* we prefer HMAC algorithms, not old algorithms */
   6038 		if (i != SADB_AALG_SHA1HMAC &&
   6039 		    i != SADB_AALG_MD5HMAC &&
   6040 		    i != SADB_X_AALG_SHA2_256 &&
   6041 		    i != SADB_X_AALG_SHA2_384 &&
   6042 		    i != SADB_X_AALG_SHA2_512)
   6043 			continue;
   6044 #endif
   6045 		algo = ah_algorithm_lookup(i);
   6046 		if (!algo)
   6047 			continue;
   6048 		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
   6049 		/* discard algorithms with key size smaller than system min */
   6050 		if (_BITS(minkeysize) < ipsec_ah_keymin)
   6051 			continue;
   6052 
   6053 		if (!m) {
   6054 			KASSERTMSG(l <= MLEN,
   6055 			    "l=%u > MLEN=%lu", l, (u_long) MLEN);
   6056 			MGET(m, M_DONTWAIT, MT_DATA);
   6057 			if (m) {
   6058 				M_ALIGN(m, l);
   6059 				m->m_len = l;
   6060 				m->m_next = NULL;
   6061 			}
   6062 		} else
   6063 			M_PREPEND(m, l, M_DONTWAIT);
   6064 		if (!m)
   6065 			return NULL;
   6066 
   6067 		if (m->m_len < sizeof(struct sadb_comb)) {
   6068 			m = m_pullup(m, sizeof(struct sadb_comb));
   6069 			if (m == NULL)
   6070 				return NULL;
   6071 		}
   6072 
   6073 		comb = mtod(m, struct sadb_comb *);
   6074 		memset(comb, 0, sizeof(*comb));
   6075 		key_getcomb_setlifetime(comb);
   6076 		comb->sadb_comb_auth = i;
   6077 		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
   6078 		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
   6079 	}
   6080 
   6081 	return m;
   6082 }
   6083 
   6084 /*
   6085  * not really an official behavior.  discussed in pf_key (at) inner.net in Sep2000.
   6086  * XXX reorder combinations by preference
   6087  */
   6088 static struct mbuf *
   6089 key_getcomb_ipcomp(void)
   6090 {
   6091 	struct sadb_comb *comb;
   6092 	const struct comp_algo *algo;
   6093 	struct mbuf *m;
   6094 	int i;
   6095 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6096 
   6097 	m = NULL;
   6098 	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
   6099 		algo = ipcomp_algorithm_lookup(i);
   6100 		if (!algo)
   6101 			continue;
   6102 
   6103 		if (!m) {
   6104 			KASSERTMSG(l <= MLEN,
   6105 			    "l=%u > MLEN=%lu", l, (u_long) MLEN);
   6106 			MGET(m, M_DONTWAIT, MT_DATA);
   6107 			if (m) {
   6108 				M_ALIGN(m, l);
   6109 				m->m_len = l;
   6110 				m->m_next = NULL;
   6111 			}
   6112 		} else
   6113 			M_PREPEND(m, l, M_DONTWAIT);
   6114 		if (!m)
   6115 			return NULL;
   6116 
   6117 		if (m->m_len < sizeof(struct sadb_comb)) {
   6118 			m = m_pullup(m, sizeof(struct sadb_comb));
   6119 			if (m == NULL)
   6120 				return NULL;
   6121 		}
   6122 
   6123 		comb = mtod(m, struct sadb_comb *);
   6124 		memset(comb, 0, sizeof(*comb));
   6125 		key_getcomb_setlifetime(comb);
   6126 		comb->sadb_comb_encrypt = i;
   6127 		/* what should we set into sadb_comb_*_{min,max}bits? */
   6128 	}
   6129 
   6130 	return m;
   6131 }
   6132 
   6133 /*
   6134  * XXX no way to pass mode (transport/tunnel) to userland
   6135  * XXX replay checking?
   6136  * XXX sysctl interface to ipsec_{ah,esp}_keymin
   6137  */
   6138 static struct mbuf *
   6139 key_getprop(const struct secasindex *saidx)
   6140 {
   6141 	struct sadb_prop *prop;
   6142 	struct mbuf *m, *n;
   6143 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
   6144 	int totlen;
   6145 
   6146 	switch (saidx->proto)  {
   6147 	case IPPROTO_ESP:
   6148 		m = key_getcomb_esp();
   6149 		break;
   6150 	case IPPROTO_AH:
   6151 		m = key_getcomb_ah();
   6152 		break;
   6153 	case IPPROTO_IPCOMP:
   6154 		m = key_getcomb_ipcomp();
   6155 		break;
   6156 	default:
   6157 		return NULL;
   6158 	}
   6159 
   6160 	if (!m)
   6161 		return NULL;
   6162 	M_PREPEND(m, l, M_DONTWAIT);
   6163 	if (!m)
   6164 		return NULL;
   6165 
   6166 	totlen = 0;
   6167 	for (n = m; n; n = n->m_next)
   6168 		totlen += n->m_len;
   6169 
   6170 	prop = mtod(m, struct sadb_prop *);
   6171 	memset(prop, 0, sizeof(*prop));
   6172 	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
   6173 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
   6174 	prop->sadb_prop_replay = 32;	/* XXX */
   6175 
   6176 	return m;
   6177 }
   6178 
   6179 /*
   6180  * SADB_ACQUIRE processing called by key_checkrequest() and key_api_acquire().
   6181  * send
   6182  *   <base, SA, address(SD), (address(P)), x_policy,
   6183  *       (identity(SD),) (sensitivity,) proposal>
   6184  * to KMD, and expect to receive
   6185  *   <base> with SADB_ACQUIRE if error occurred,
   6186  * or
   6187  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
   6188  * from KMD by PF_KEY.
   6189  *
   6190  * XXX x_policy is outside of RFC2367 (KAME extension).
   6191  * XXX sensitivity is not supported.
   6192  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
   6193  * see comment for key_getcomb_ipcomp().
   6194  *
   6195  * OUT:
   6196  *    0     : succeed
   6197  *    others: error number
   6198  */
   6199 static int
   6200 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
   6201 {
   6202 	struct mbuf *result = NULL, *m;
   6203 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6204 	struct secacq *newacq;
   6205 #endif
   6206 	u_int8_t satype;
   6207 	int error = -1;
   6208 	u_int32_t seq;
   6209 
   6210 	/* sanity check */
   6211 	KASSERT(saidx != NULL);
   6212 	satype = key_proto2satype(saidx->proto);
   6213 	KASSERTMSG(satype != 0, "null satype, protocol %u", saidx->proto);
   6214 
   6215 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6216 	/*
   6217 	 * We never do anything about acquirng SA.  There is anather
   6218 	 * solution that kernel blocks to send SADB_ACQUIRE message until
   6219 	 * getting something message from IKEd.  In later case, to be
   6220 	 * managed with ACQUIRING list.
   6221 	 */
   6222 	/* Get an entry to check whether sending message or not. */
   6223 	mutex_enter(&key_mtx);
   6224 	newacq = key_getacq(saidx);
   6225 	if (newacq != NULL) {
   6226 		if (key_blockacq_count < newacq->count) {
   6227 			/* reset counter and do send message. */
   6228 			newacq->count = 0;
   6229 		} else {
   6230 			/* increment counter and do nothing. */
   6231 			newacq->count++;
   6232 			mutex_exit(&key_mtx);
   6233 			return 0;
   6234 		}
   6235 	} else {
   6236 		/* make new entry for blocking to send SADB_ACQUIRE. */
   6237 		newacq = key_newacq(saidx);
   6238 		if (newacq == NULL)
   6239 			return ENOBUFS;
   6240 
   6241 		/* add to acqtree */
   6242 		LIST_INSERT_HEAD(&acqtree, newacq, chain);
   6243 	}
   6244 
   6245 	seq = newacq->seq;
   6246 	mutex_exit(&key_mtx);
   6247 #else
   6248 	seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
   6249 #endif
   6250 	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
   6251 	if (!m) {
   6252 		error = ENOBUFS;
   6253 		goto fail;
   6254 	}
   6255 	result = m;
   6256 
   6257 	/* set sadb_address for saidx's. */
   6258 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &saidx->src.sa, FULLMASK,
   6259 	    IPSEC_ULPROTO_ANY);
   6260 	if (!m) {
   6261 		error = ENOBUFS;
   6262 		goto fail;
   6263 	}
   6264 	m_cat(result, m);
   6265 
   6266 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &saidx->dst.sa, FULLMASK,
   6267 	    IPSEC_ULPROTO_ANY);
   6268 	if (!m) {
   6269 		error = ENOBUFS;
   6270 		goto fail;
   6271 	}
   6272 	m_cat(result, m);
   6273 
   6274 	/* XXX proxy address (optional) */
   6275 
   6276 	/* set sadb_x_policy */
   6277 	if (sp) {
   6278 		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
   6279 		if (!m) {
   6280 			error = ENOBUFS;
   6281 			goto fail;
   6282 		}
   6283 		m_cat(result, m);
   6284 	}
   6285 
   6286 	/* XXX identity (optional) */
   6287 #if 0
   6288 	if (idexttype && fqdn) {
   6289 		/* create identity extension (FQDN) */
   6290 		struct sadb_ident *id;
   6291 		int fqdnlen;
   6292 
   6293 		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
   6294 		id = (struct sadb_ident *)p;
   6295 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6296 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6297 		id->sadb_ident_exttype = idexttype;
   6298 		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
   6299 		memcpy(id + 1, fqdn, fqdnlen);
   6300 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
   6301 	}
   6302 
   6303 	if (idexttype) {
   6304 		/* create identity extension (USERFQDN) */
   6305 		struct sadb_ident *id;
   6306 		int userfqdnlen;
   6307 
   6308 		if (userfqdn) {
   6309 			/* +1 for terminating-NUL */
   6310 			userfqdnlen = strlen(userfqdn) + 1;
   6311 		} else
   6312 			userfqdnlen = 0;
   6313 		id = (struct sadb_ident *)p;
   6314 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6315 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6316 		id->sadb_ident_exttype = idexttype;
   6317 		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
   6318 		/* XXX is it correct? */
   6319 		if (curlwp)
   6320 			id->sadb_ident_id = kauth_cred_getuid(curlwp->l_cred);
   6321 		if (userfqdn && userfqdnlen)
   6322 			memcpy(id + 1, userfqdn, userfqdnlen);
   6323 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
   6324 	}
   6325 #endif
   6326 
   6327 	/* XXX sensitivity (optional) */
   6328 
   6329 	/* create proposal/combination extension */
   6330 	m = key_getprop(saidx);
   6331 #if 0
   6332 	/*
   6333 	 * spec conformant: always attach proposal/combination extension,
   6334 	 * the problem is that we have no way to attach it for ipcomp,
   6335 	 * due to the way sadb_comb is declared in RFC2367.
   6336 	 */
   6337 	if (!m) {
   6338 		error = ENOBUFS;
   6339 		goto fail;
   6340 	}
   6341 	m_cat(result, m);
   6342 #else
   6343 	/*
   6344 	 * outside of spec; make proposal/combination extension optional.
   6345 	 */
   6346 	if (m)
   6347 		m_cat(result, m);
   6348 #endif
   6349 
   6350 	if ((result->m_flags & M_PKTHDR) == 0) {
   6351 		error = EINVAL;
   6352 		goto fail;
   6353 	}
   6354 
   6355 	if (result->m_len < sizeof(struct sadb_msg)) {
   6356 		result = m_pullup(result, sizeof(struct sadb_msg));
   6357 		if (result == NULL) {
   6358 			error = ENOBUFS;
   6359 			goto fail;
   6360 		}
   6361 	}
   6362 
   6363 	result->m_pkthdr.len = 0;
   6364 	for (m = result; m; m = m->m_next)
   6365 		result->m_pkthdr.len += m->m_len;
   6366 
   6367 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6368 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6369 
   6370 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   6371 
   6372  fail:
   6373 	if (result)
   6374 		m_freem(result);
   6375 	return error;
   6376 }
   6377 
   6378 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6379 static struct secacq *
   6380 key_newacq(const struct secasindex *saidx)
   6381 {
   6382 	struct secacq *newacq;
   6383 
   6384 	/* get new entry */
   6385 	newacq = kmem_intr_zalloc(sizeof(struct secacq), KM_NOSLEEP);
   6386 	if (newacq == NULL) {
   6387 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   6388 		return NULL;
   6389 	}
   6390 
   6391 	/* copy secindex */
   6392 	memcpy(&newacq->saidx, saidx, sizeof(newacq->saidx));
   6393 	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
   6394 	newacq->created = time_uptime;
   6395 	newacq->count = 0;
   6396 
   6397 	return newacq;
   6398 }
   6399 
   6400 static struct secacq *
   6401 key_getacq(const struct secasindex *saidx)
   6402 {
   6403 	struct secacq *acq;
   6404 
   6405 	KASSERT(mutex_owned(&key_mtx));
   6406 
   6407 	LIST_FOREACH(acq, &acqtree, chain) {
   6408 		if (key_saidx_match(saidx, &acq->saidx, CMP_EXACTLY))
   6409 			return acq;
   6410 	}
   6411 
   6412 	return NULL;
   6413 }
   6414 
   6415 static struct secacq *
   6416 key_getacqbyseq(u_int32_t seq)
   6417 {
   6418 	struct secacq *acq;
   6419 
   6420 	KASSERT(mutex_owned(&key_mtx));
   6421 
   6422 	LIST_FOREACH(acq, &acqtree, chain) {
   6423 		if (acq->seq == seq)
   6424 			return acq;
   6425 	}
   6426 
   6427 	return NULL;
   6428 }
   6429 #endif
   6430 
   6431 #ifdef notyet
   6432 static struct secspacq *
   6433 key_newspacq(const struct secpolicyindex *spidx)
   6434 {
   6435 	struct secspacq *acq;
   6436 
   6437 	/* get new entry */
   6438 	acq = kmem_intr_zalloc(sizeof(struct secspacq), KM_NOSLEEP);
   6439 	if (acq == NULL) {
   6440 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   6441 		return NULL;
   6442 	}
   6443 
   6444 	/* copy secindex */
   6445 	memcpy(&acq->spidx, spidx, sizeof(acq->spidx));
   6446 	acq->created = time_uptime;
   6447 	acq->count = 0;
   6448 
   6449 	return acq;
   6450 }
   6451 
   6452 static struct secspacq *
   6453 key_getspacq(const struct secpolicyindex *spidx)
   6454 {
   6455 	struct secspacq *acq;
   6456 
   6457 	LIST_FOREACH(acq, &spacqtree, chain) {
   6458 		if (key_spidx_match_exactly(spidx, &acq->spidx))
   6459 			return acq;
   6460 	}
   6461 
   6462 	return NULL;
   6463 }
   6464 #endif /* notyet */
   6465 
   6466 /*
   6467  * SADB_ACQUIRE processing,
   6468  * in first situation, is receiving
   6469  *   <base>
   6470  * from the ikmpd, and clear sequence of its secasvar entry.
   6471  *
   6472  * In second situation, is receiving
   6473  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6474  * from a user land process, and return
   6475  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6476  * to the socket.
   6477  *
   6478  * m will always be freed.
   6479  */
   6480 static int
   6481 key_api_acquire(struct socket *so, struct mbuf *m,
   6482       	     const struct sadb_msghdr *mhp)
   6483 {
   6484 	const struct sockaddr *src, *dst;
   6485 	struct secasindex saidx;
   6486 	struct secashead *sah;
   6487 	u_int16_t proto;
   6488 	int error;
   6489 
   6490 	/*
   6491 	 * Error message from KMd.
   6492 	 * We assume that if error was occurred in IKEd, the length of PFKEY
   6493 	 * message is equal to the size of sadb_msg structure.
   6494 	 * We do not raise error even if error occurred in this function.
   6495 	 */
   6496 	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
   6497 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6498 		struct secacq *acq;
   6499 
   6500 		/* check sequence number */
   6501 		if (mhp->msg->sadb_msg_seq == 0) {
   6502 			IPSECLOG(LOG_DEBUG, "must specify sequence number.\n");
   6503 			m_freem(m);
   6504 			return 0;
   6505 		}
   6506 
   6507 		mutex_enter(&key_mtx);
   6508 		acq = key_getacqbyseq(mhp->msg->sadb_msg_seq);
   6509 		if (acq == NULL) {
   6510 			mutex_exit(&key_mtx);
   6511 			/*
   6512 			 * the specified larval SA is already gone, or we got
   6513 			 * a bogus sequence number.  we can silently ignore it.
   6514 			 */
   6515 			m_freem(m);
   6516 			return 0;
   6517 		}
   6518 
   6519 		/* reset acq counter in order to deletion by timehander. */
   6520 		acq->created = time_uptime;
   6521 		acq->count = 0;
   6522 		mutex_exit(&key_mtx);
   6523 #endif
   6524 		m_freem(m);
   6525 		return 0;
   6526 	}
   6527 
   6528 	/*
   6529 	 * This message is from user land.
   6530 	 */
   6531 
   6532 	/* map satype to proto */
   6533 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   6534 	if (proto == 0) {
   6535 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   6536 		return key_senderror(so, m, EINVAL);
   6537 	}
   6538 
   6539 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   6540 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   6541 	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
   6542 		/* error */
   6543 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   6544 		return key_senderror(so, m, EINVAL);
   6545 	}
   6546 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   6547 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   6548 	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
   6549 		/* error */
   6550 		IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
   6551 		return key_senderror(so, m, EINVAL);
   6552 	}
   6553 
   6554 	src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
   6555 	dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
   6556 
   6557 	error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
   6558 	if (error != 0)
   6559 		return key_senderror(so, m, EINVAL);
   6560 
   6561 	error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
   6562 	if (error != 0)
   6563 		return key_senderror(so, m, EINVAL);
   6564 
   6565 	/* get a SA index */
   6566 	sah = key_getsah(&saidx, CMP_MODE_REQID);
   6567 	if (sah != NULL) {
   6568 		IPSECLOG(LOG_DEBUG, "a SA exists already.\n");
   6569 		return key_senderror(so, m, EEXIST);
   6570 	}
   6571 
   6572 	error = key_acquire(&saidx, NULL);
   6573 	if (error != 0) {
   6574 		IPSECLOG(LOG_DEBUG, "error %d returned from key_acquire.\n",
   6575 		    error);
   6576 		return key_senderror(so, m, error);
   6577 	}
   6578 
   6579 	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
   6580 }
   6581 
   6582 /*
   6583  * SADB_REGISTER processing.
   6584  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
   6585  * receive
   6586  *   <base>
   6587  * from the ikmpd, and register a socket to send PF_KEY messages,
   6588  * and send
   6589  *   <base, supported>
   6590  * to KMD by PF_KEY.
   6591  * If socket is detached, must free from regnode.
   6592  *
   6593  * m will always be freed.
   6594  */
   6595 static int
   6596 key_api_register(struct socket *so, struct mbuf *m,
   6597 	     const struct sadb_msghdr *mhp)
   6598 {
   6599 	struct secreg *reg, *newreg = 0;
   6600 
   6601 	/* check for invalid register message */
   6602 	if (mhp->msg->sadb_msg_satype >= __arraycount(regtree))
   6603 		return key_senderror(so, m, EINVAL);
   6604 
   6605 	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
   6606 	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
   6607 		goto setmsg;
   6608 
   6609 	/* Allocate regnode in advance, out of mutex */
   6610 	newreg = kmem_zalloc(sizeof(*newreg), KM_SLEEP);
   6611 
   6612 	/* check whether existing or not */
   6613 	mutex_enter(&key_mtx);
   6614 	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
   6615 		if (reg->so == so) {
   6616 			IPSECLOG(LOG_DEBUG, "socket exists already.\n");
   6617 			mutex_exit(&key_mtx);
   6618 			kmem_free(newreg, sizeof(*newreg));
   6619 			return key_senderror(so, m, EEXIST);
   6620 		}
   6621 	}
   6622 
   6623 	newreg->so = so;
   6624 	((struct keycb *)sotorawcb(so))->kp_registered++;
   6625 
   6626 	/* add regnode to regtree. */
   6627 	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
   6628 	mutex_exit(&key_mtx);
   6629 
   6630   setmsg:
   6631     {
   6632 	struct mbuf *n;
   6633 	struct sadb_supported *sup;
   6634 	u_int len, alen, elen;
   6635 	int off;
   6636 	int i;
   6637 	struct sadb_alg *alg;
   6638 
   6639 	/* create new sadb_msg to reply. */
   6640 	alen = 0;
   6641 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   6642 		if (ah_algorithm_lookup(i))
   6643 			alen += sizeof(struct sadb_alg);
   6644 	}
   6645 	if (alen)
   6646 		alen += sizeof(struct sadb_supported);
   6647 	elen = 0;
   6648 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   6649 		if (esp_algorithm_lookup(i))
   6650 			elen += sizeof(struct sadb_alg);
   6651 	}
   6652 	if (elen)
   6653 		elen += sizeof(struct sadb_supported);
   6654 
   6655 	len = sizeof(struct sadb_msg) + alen + elen;
   6656 
   6657 	if (len > MCLBYTES)
   6658 		return key_senderror(so, m, ENOBUFS);
   6659 
   6660 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   6661 	if (len > MHLEN) {
   6662 		MCLGET(n, M_DONTWAIT);
   6663 		if ((n->m_flags & M_EXT) == 0) {
   6664 			m_freem(n);
   6665 			n = NULL;
   6666 		}
   6667 	}
   6668 	if (!n)
   6669 		return key_senderror(so, m, ENOBUFS);
   6670 
   6671 	n->m_pkthdr.len = n->m_len = len;
   6672 	n->m_next = NULL;
   6673 	off = 0;
   6674 
   6675 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   6676 	n = key_fill_replymsg(n, 0);
   6677 	if (n == NULL)
   6678 		return key_senderror(so, m, ENOBUFS);
   6679 
   6680 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   6681 
   6682 	/* for authentication algorithm */
   6683 	if (alen) {
   6684 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6685 		sup->sadb_supported_len = PFKEY_UNIT64(alen);
   6686 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
   6687 		off += PFKEY_ALIGN8(sizeof(*sup));
   6688 
   6689 		for (i = 1; i <= SADB_AALG_MAX; i++) {
   6690 			const struct auth_hash *aalgo;
   6691 			u_int16_t minkeysize, maxkeysize;
   6692 
   6693 			aalgo = ah_algorithm_lookup(i);
   6694 			if (!aalgo)
   6695 				continue;
   6696 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6697 			alg->sadb_alg_id = i;
   6698 			alg->sadb_alg_ivlen = 0;
   6699 			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
   6700 			alg->sadb_alg_minbits = _BITS(minkeysize);
   6701 			alg->sadb_alg_maxbits = _BITS(maxkeysize);
   6702 			off += PFKEY_ALIGN8(sizeof(*alg));
   6703 		}
   6704 	}
   6705 
   6706 	/* for encryption algorithm */
   6707 	if (elen) {
   6708 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6709 		sup->sadb_supported_len = PFKEY_UNIT64(elen);
   6710 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
   6711 		off += PFKEY_ALIGN8(sizeof(*sup));
   6712 
   6713 		for (i = 1; i <= SADB_EALG_MAX; i++) {
   6714 			const struct enc_xform *ealgo;
   6715 
   6716 			ealgo = esp_algorithm_lookup(i);
   6717 			if (!ealgo)
   6718 				continue;
   6719 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6720 			alg->sadb_alg_id = i;
   6721 			alg->sadb_alg_ivlen = ealgo->blocksize;
   6722 			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
   6723 			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
   6724 			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
   6725 		}
   6726 	}
   6727 
   6728 	KASSERTMSG(off == len, "length inconsistency");
   6729 
   6730 	m_freem(m);
   6731 	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
   6732     }
   6733 }
   6734 
   6735 /*
   6736  * free secreg entry registered.
   6737  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
   6738  */
   6739 void
   6740 key_freereg(struct socket *so)
   6741 {
   6742 	struct secreg *reg;
   6743 	int i;
   6744 
   6745 	KASSERT(!cpu_softintr_p());
   6746 	KASSERT(so != NULL);
   6747 
   6748 	/*
   6749 	 * check whether existing or not.
   6750 	 * check all type of SA, because there is a potential that
   6751 	 * one socket is registered to multiple type of SA.
   6752 	 */
   6753 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   6754 		mutex_enter(&key_mtx);
   6755 		LIST_FOREACH(reg, &regtree[i], chain) {
   6756 			if (reg->so == so) {
   6757 				LIST_REMOVE(reg, chain);
   6758 				break;
   6759 			}
   6760 		}
   6761 		mutex_exit(&key_mtx);
   6762 		if (reg != NULL)
   6763 			kmem_free(reg, sizeof(*reg));
   6764 	}
   6765 
   6766 	return;
   6767 }
   6768 
   6769 /*
   6770  * SADB_EXPIRE processing
   6771  * send
   6772  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
   6773  * to KMD by PF_KEY.
   6774  * NOTE: We send only soft lifetime extension.
   6775  *
   6776  * OUT:	0	: succeed
   6777  *	others	: error number
   6778  */
   6779 static int
   6780 key_expire(struct secasvar *sav)
   6781 {
   6782 	int s;
   6783 	int satype;
   6784 	struct mbuf *result = NULL, *m;
   6785 	int len;
   6786 	int error = -1;
   6787 	struct sadb_lifetime *lt;
   6788 
   6789 	/* XXX: Why do we lock ? */
   6790 	s = splsoftnet();	/*called from softclock()*/
   6791 
   6792 	KASSERT(sav != NULL);
   6793 	KASSERT(sav->sah != NULL);
   6794 
   6795 	satype = key_proto2satype(sav->sah->saidx.proto);
   6796 	KASSERTMSG(satype != 0, "invalid proto is passed");
   6797 
   6798 	/* set msg header */
   6799 	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
   6800 	if (!m) {
   6801 		error = ENOBUFS;
   6802 		goto fail;
   6803 	}
   6804 	result = m;
   6805 
   6806 	/* create SA extension */
   6807 	m = key_setsadbsa(sav);
   6808 	if (!m) {
   6809 		error = ENOBUFS;
   6810 		goto fail;
   6811 	}
   6812 	m_cat(result, m);
   6813 
   6814 	/* create SA extension */
   6815 	m = key_setsadbxsa2(sav->sah->saidx.mode,
   6816 	    sav->replay ? sav->replay->count : 0, sav->sah->saidx.reqid);
   6817 	if (!m) {
   6818 		error = ENOBUFS;
   6819 		goto fail;
   6820 	}
   6821 	m_cat(result, m);
   6822 
   6823 	/* create lifetime extension (current and soft) */
   6824 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
   6825 	m = key_alloc_mbuf(len);
   6826 	if (!m || m->m_next) {	/*XXX*/
   6827 		if (m)
   6828 			m_freem(m);
   6829 		error = ENOBUFS;
   6830 		goto fail;
   6831 	}
   6832 	memset(mtod(m, void *), 0, len);
   6833 	lt = mtod(m, struct sadb_lifetime *);
   6834 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   6835 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   6836 	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
   6837 	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
   6838 	lt->sadb_lifetime_addtime =
   6839 	    time_mono_to_wall(sav->lft_c->sadb_lifetime_addtime);
   6840 	lt->sadb_lifetime_usetime =
   6841 	    time_mono_to_wall(sav->lft_c->sadb_lifetime_usetime);
   6842 	lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
   6843 	memcpy(lt, sav->lft_s, sizeof(*lt));
   6844 	m_cat(result, m);
   6845 
   6846 	/* set sadb_address for source */
   6847 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &sav->sah->saidx.src.sa,
   6848 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6849 	if (!m) {
   6850 		error = ENOBUFS;
   6851 		goto fail;
   6852 	}
   6853 	m_cat(result, m);
   6854 
   6855 	/* set sadb_address for destination */
   6856 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &sav->sah->saidx.dst.sa,
   6857 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6858 	if (!m) {
   6859 		error = ENOBUFS;
   6860 		goto fail;
   6861 	}
   6862 	m_cat(result, m);
   6863 
   6864 	if ((result->m_flags & M_PKTHDR) == 0) {
   6865 		error = EINVAL;
   6866 		goto fail;
   6867 	}
   6868 
   6869 	if (result->m_len < sizeof(struct sadb_msg)) {
   6870 		result = m_pullup(result, sizeof(struct sadb_msg));
   6871 		if (result == NULL) {
   6872 			error = ENOBUFS;
   6873 			goto fail;
   6874 		}
   6875 	}
   6876 
   6877 	result->m_pkthdr.len = 0;
   6878 	for (m = result; m; m = m->m_next)
   6879 		result->m_pkthdr.len += m->m_len;
   6880 
   6881 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6882 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6883 
   6884 	splx(s);
   6885 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   6886 
   6887  fail:
   6888 	if (result)
   6889 		m_freem(result);
   6890 	splx(s);
   6891 	return error;
   6892 }
   6893 
   6894 /*
   6895  * SADB_FLUSH processing
   6896  * receive
   6897  *   <base>
   6898  * from the ikmpd, and free all entries in secastree.
   6899  * and send,
   6900  *   <base>
   6901  * to the ikmpd.
   6902  * NOTE: to do is only marking SADB_SASTATE_DEAD.
   6903  *
   6904  * m will always be freed.
   6905  */
   6906 static int
   6907 key_api_flush(struct socket *so, struct mbuf *m,
   6908           const struct sadb_msghdr *mhp)
   6909 {
   6910 	struct sadb_msg *newmsg;
   6911 	struct secashead *sah;
   6912 	struct secasvar *sav, *nextsav;
   6913 	u_int16_t proto;
   6914 	u_int8_t state;
   6915 
   6916 	/* map satype to proto */
   6917 	proto = key_satype2proto(mhp->msg->sadb_msg_satype);
   6918 	if (proto == 0) {
   6919 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   6920 		return key_senderror(so, m, EINVAL);
   6921 	}
   6922 
   6923 	/* no SATYPE specified, i.e. flushing all SA. */
   6924 	LIST_FOREACH(sah, &sahtree, chain) {
   6925 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
   6926 		    proto != sah->saidx.proto)
   6927 			continue;
   6928 
   6929 		SASTATE_ALIVE_FOREACH(state) {
   6930 			LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain,
   6931 			    nextsav) {
   6932 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   6933 				KEY_FREESAV(&sav);
   6934 			}
   6935 		}
   6936 
   6937 		sah->state = SADB_SASTATE_DEAD;
   6938 	}
   6939 
   6940 	if (m->m_len < sizeof(struct sadb_msg) ||
   6941 	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
   6942 		IPSECLOG(LOG_DEBUG, "No more memory.\n");
   6943 		return key_senderror(so, m, ENOBUFS);
   6944 	}
   6945 
   6946 	if (m->m_next)
   6947 		m_freem(m->m_next);
   6948 	m->m_next = NULL;
   6949 	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
   6950 	newmsg = mtod(m, struct sadb_msg *);
   6951 	newmsg->sadb_msg_errno = 0;
   6952 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
   6953 
   6954 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   6955 }
   6956 
   6957 
   6958 static struct mbuf *
   6959 key_setdump_chain(u_int8_t req_satype, int *errorp, int *lenp, pid_t pid)
   6960 {
   6961 	struct secashead *sah;
   6962 	struct secasvar *sav;
   6963 	u_int16_t proto;
   6964 	u_int8_t satype;
   6965 	u_int8_t state;
   6966 	int cnt;
   6967 	struct mbuf *m, *n, *prev;
   6968 
   6969 	*lenp = 0;
   6970 
   6971 	/* map satype to proto */
   6972 	proto = key_satype2proto(req_satype);
   6973 	if (proto == 0) {
   6974 		*errorp = EINVAL;
   6975 		return (NULL);
   6976 	}
   6977 
   6978 	/* count sav entries to be sent to userland. */
   6979 	cnt = 0;
   6980 	LIST_FOREACH(sah, &sahtree, chain) {
   6981 		if (req_satype != SADB_SATYPE_UNSPEC &&
   6982 		    proto != sah->saidx.proto)
   6983 			continue;
   6984 
   6985 		SASTATE_ANY_FOREACH(state) {
   6986 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   6987 				cnt++;
   6988 			}
   6989 		}
   6990 	}
   6991 
   6992 	if (cnt == 0) {
   6993 		*errorp = ENOENT;
   6994 		return (NULL);
   6995 	}
   6996 
   6997 	/* send this to the userland, one at a time. */
   6998 	m = NULL;
   6999 	prev = m;
   7000 	LIST_FOREACH(sah, &sahtree, chain) {
   7001 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7002 		    proto != sah->saidx.proto)
   7003 			continue;
   7004 
   7005 		/* map proto to satype */
   7006 		satype = key_proto2satype(sah->saidx.proto);
   7007 		if (satype == 0) {
   7008 			m_freem(m);
   7009 			*errorp = EINVAL;
   7010 			return (NULL);
   7011 		}
   7012 
   7013 		SASTATE_ANY_FOREACH(state) {
   7014 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   7015 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   7016 				    --cnt, pid);
   7017 				if (!n) {
   7018 					m_freem(m);
   7019 					*errorp = ENOBUFS;
   7020 					return (NULL);
   7021 				}
   7022 
   7023 				if (!m)
   7024 					m = n;
   7025 				else
   7026 					prev->m_nextpkt = n;
   7027 				prev = n;
   7028 			}
   7029 		}
   7030 	}
   7031 
   7032 	if (!m) {
   7033 		*errorp = EINVAL;
   7034 		return (NULL);
   7035 	}
   7036 
   7037 	if ((m->m_flags & M_PKTHDR) != 0) {
   7038 		m->m_pkthdr.len = 0;
   7039 		for (n = m; n; n = n->m_next)
   7040 			m->m_pkthdr.len += n->m_len;
   7041 	}
   7042 
   7043 	*errorp = 0;
   7044 	return (m);
   7045 }
   7046 
   7047 /*
   7048  * SADB_DUMP processing
   7049  * dump all entries including status of DEAD in SAD.
   7050  * receive
   7051  *   <base>
   7052  * from the ikmpd, and dump all secasvar leaves
   7053  * and send,
   7054  *   <base> .....
   7055  * to the ikmpd.
   7056  *
   7057  * m will always be freed.
   7058  */
   7059 static int
   7060 key_api_dump(struct socket *so, struct mbuf *m0,
   7061 	 const struct sadb_msghdr *mhp)
   7062 {
   7063 	u_int16_t proto;
   7064 	u_int8_t satype;
   7065 	struct mbuf *n;
   7066 	int s;
   7067 	int error, len, ok;
   7068 
   7069 	/* map satype to proto */
   7070 	satype = mhp->msg->sadb_msg_satype;
   7071 	proto = key_satype2proto(satype);
   7072 	if (proto == 0) {
   7073 		IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
   7074 		return key_senderror(so, m0, EINVAL);
   7075 	}
   7076 
   7077 	/*
   7078 	 * If the requestor has insufficient socket-buffer space
   7079 	 * for the entire chain, nobody gets any response to the DUMP.
   7080 	 * XXX For now, only the requestor ever gets anything.
   7081 	 * Moreover, if the requestor has any space at all, they receive
   7082 	 * the entire chain, otherwise the request is refused with ENOBUFS.
   7083 	 */
   7084 	if (sbspace(&so->so_rcv) <= 0) {
   7085 		return key_senderror(so, m0, ENOBUFS);
   7086 	}
   7087 
   7088 	s = splsoftnet();
   7089 	n = key_setdump_chain(satype, &error, &len, mhp->msg->sadb_msg_pid);
   7090 	splx(s);
   7091 
   7092 	if (n == NULL) {
   7093 		return key_senderror(so, m0, ENOENT);
   7094 	}
   7095 	{
   7096 		uint64_t *ps = PFKEY_STAT_GETREF();
   7097 		ps[PFKEY_STAT_IN_TOTAL]++;
   7098 		ps[PFKEY_STAT_IN_BYTES] += len;
   7099 		PFKEY_STAT_PUTREF();
   7100 	}
   7101 
   7102 	/*
   7103 	 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
   7104 	 * The requestor receives either the entire chain, or an
   7105 	 * error message with ENOBUFS.
   7106 	 *
   7107 	 * sbappendaddrchain() takes the chain of entries, one
   7108 	 * packet-record per SPD entry, prepends the key_src sockaddr
   7109 	 * to each packet-record, links the sockaddr mbufs into a new
   7110 	 * list of records, then   appends the entire resulting
   7111 	 * list to the requesting socket.
   7112 	 */
   7113 	ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src, n,
   7114 	    SB_PRIO_ONESHOT_OVERFLOW);
   7115 
   7116 	if (!ok) {
   7117 		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
   7118 		m_freem(n);
   7119 		return key_senderror(so, m0, ENOBUFS);
   7120 	}
   7121 
   7122 	m_freem(m0);
   7123 	return 0;
   7124 }
   7125 
   7126 /*
   7127  * SADB_X_PROMISC processing
   7128  *
   7129  * m will always be freed.
   7130  */
   7131 static int
   7132 key_api_promisc(struct socket *so, struct mbuf *m,
   7133 	    const struct sadb_msghdr *mhp)
   7134 {
   7135 	int olen;
   7136 
   7137 	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   7138 
   7139 	if (olen < sizeof(struct sadb_msg)) {
   7140 #if 1
   7141 		return key_senderror(so, m, EINVAL);
   7142 #else
   7143 		m_freem(m);
   7144 		return 0;
   7145 #endif
   7146 	} else if (olen == sizeof(struct sadb_msg)) {
   7147 		/* enable/disable promisc mode */
   7148 		struct keycb *kp = (struct keycb *)sotorawcb(so);
   7149 		if (kp == NULL)
   7150 			return key_senderror(so, m, EINVAL);
   7151 		mhp->msg->sadb_msg_errno = 0;
   7152 		switch (mhp->msg->sadb_msg_satype) {
   7153 		case 0:
   7154 		case 1:
   7155 			kp->kp_promisc = mhp->msg->sadb_msg_satype;
   7156 			break;
   7157 		default:
   7158 			return key_senderror(so, m, EINVAL);
   7159 		}
   7160 
   7161 		/* send the original message back to everyone */
   7162 		mhp->msg->sadb_msg_errno = 0;
   7163 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7164 	} else {
   7165 		/* send packet as is */
   7166 
   7167 		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
   7168 
   7169 		/* TODO: if sadb_msg_seq is specified, send to specific pid */
   7170 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7171 	}
   7172 }
   7173 
   7174 static int (*key_api_typesw[]) (struct socket *, struct mbuf *,
   7175 		const struct sadb_msghdr *) = {
   7176 	NULL,			/* SADB_RESERVED */
   7177 	key_api_getspi,		/* SADB_GETSPI */
   7178 	key_api_update,		/* SADB_UPDATE */
   7179 	key_api_add,		/* SADB_ADD */
   7180 	key_api_delete,		/* SADB_DELETE */
   7181 	key_api_get,		/* SADB_GET */
   7182 	key_api_acquire,	/* SADB_ACQUIRE */
   7183 	key_api_register,	/* SADB_REGISTER */
   7184 	NULL,			/* SADB_EXPIRE */
   7185 	key_api_flush,		/* SADB_FLUSH */
   7186 	key_api_dump,		/* SADB_DUMP */
   7187 	key_api_promisc,	/* SADB_X_PROMISC */
   7188 	NULL,			/* SADB_X_PCHANGE */
   7189 	key_api_spdadd,		/* SADB_X_SPDUPDATE */
   7190 	key_api_spdadd,		/* SADB_X_SPDADD */
   7191 	key_api_spddelete,	/* SADB_X_SPDDELETE */
   7192 	key_api_spdget,		/* SADB_X_SPDGET */
   7193 	NULL,			/* SADB_X_SPDACQUIRE */
   7194 	key_api_spddump,	/* SADB_X_SPDDUMP */
   7195 	key_api_spdflush,	/* SADB_X_SPDFLUSH */
   7196 	key_api_spdadd,		/* SADB_X_SPDSETIDX */
   7197 	NULL,			/* SADB_X_SPDEXPIRE */
   7198 	key_api_spddelete2,	/* SADB_X_SPDDELETE2 */
   7199 	key_api_nat_map,	/* SADB_X_NAT_T_NEW_MAPPING */
   7200 };
   7201 
   7202 /*
   7203  * parse sadb_msg buffer to process PFKEYv2,
   7204  * and create a data to response if needed.
   7205  * I think to be dealed with mbuf directly.
   7206  * IN:
   7207  *     msgp  : pointer to pointer to a received buffer pulluped.
   7208  *             This is rewrited to response.
   7209  *     so    : pointer to socket.
   7210  * OUT:
   7211  *    length for buffer to send to user process.
   7212  */
   7213 int
   7214 key_parse(struct mbuf *m, struct socket *so)
   7215 {
   7216 	struct sadb_msg *msg;
   7217 	struct sadb_msghdr mh;
   7218 	u_int orglen;
   7219 	int error;
   7220 
   7221 	KASSERT(m != NULL);
   7222 	KASSERT(so != NULL);
   7223 
   7224 #if 0	/*kdebug_sadb assumes msg in linear buffer*/
   7225 	if (KEYDEBUG_ON(KEYDEBUG_KEY_DUMP)) {
   7226 		IPSECLOG(LOG_DEBUG, "passed sadb_msg\n");
   7227 		kdebug_sadb(msg);
   7228 	}
   7229 #endif
   7230 
   7231 	if (m->m_len < sizeof(struct sadb_msg)) {
   7232 		m = m_pullup(m, sizeof(struct sadb_msg));
   7233 		if (!m)
   7234 			return ENOBUFS;
   7235 	}
   7236 	msg = mtod(m, struct sadb_msg *);
   7237 	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
   7238 
   7239 	if ((m->m_flags & M_PKTHDR) == 0 ||
   7240 	    m->m_pkthdr.len != orglen) {
   7241 		IPSECLOG(LOG_DEBUG, "invalid message length.\n");
   7242 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7243 		error = EINVAL;
   7244 		goto senderror;
   7245 	}
   7246 
   7247 	if (msg->sadb_msg_version != PF_KEY_V2) {
   7248 		IPSECLOG(LOG_DEBUG, "PF_KEY version %u is mismatched.\n",
   7249 		    msg->sadb_msg_version);
   7250 		PFKEY_STATINC(PFKEY_STAT_OUT_INVVER);
   7251 		error = EINVAL;
   7252 		goto senderror;
   7253 	}
   7254 
   7255 	if (msg->sadb_msg_type > SADB_MAX) {
   7256 		IPSECLOG(LOG_DEBUG, "invalid type %u is passed.\n",
   7257 		    msg->sadb_msg_type);
   7258 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7259 		error = EINVAL;
   7260 		goto senderror;
   7261 	}
   7262 
   7263 	/* for old-fashioned code - should be nuked */
   7264 	if (m->m_pkthdr.len > MCLBYTES) {
   7265 		m_freem(m);
   7266 		return ENOBUFS;
   7267 	}
   7268 	if (m->m_next) {
   7269 		struct mbuf *n;
   7270 
   7271 		MGETHDR(n, M_DONTWAIT, MT_DATA);
   7272 		if (n && m->m_pkthdr.len > MHLEN) {
   7273 			MCLGET(n, M_DONTWAIT);
   7274 			if ((n->m_flags & M_EXT) == 0) {
   7275 				m_free(n);
   7276 				n = NULL;
   7277 			}
   7278 		}
   7279 		if (!n) {
   7280 			m_freem(m);
   7281 			return ENOBUFS;
   7282 		}
   7283 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, void *));
   7284 		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
   7285 		n->m_next = NULL;
   7286 		m_freem(m);
   7287 		m = n;
   7288 	}
   7289 
   7290 	/* align the mbuf chain so that extensions are in contiguous region. */
   7291 	error = key_align(m, &mh);
   7292 	if (error)
   7293 		return error;
   7294 
   7295 	if (m->m_next) {	/*XXX*/
   7296 		m_freem(m);
   7297 		return ENOBUFS;
   7298 	}
   7299 
   7300 	msg = mh.msg;
   7301 
   7302 	/* check SA type */
   7303 	switch (msg->sadb_msg_satype) {
   7304 	case SADB_SATYPE_UNSPEC:
   7305 		switch (msg->sadb_msg_type) {
   7306 		case SADB_GETSPI:
   7307 		case SADB_UPDATE:
   7308 		case SADB_ADD:
   7309 		case SADB_DELETE:
   7310 		case SADB_GET:
   7311 		case SADB_ACQUIRE:
   7312 		case SADB_EXPIRE:
   7313 			IPSECLOG(LOG_DEBUG,
   7314 			    "must specify satype when msg type=%u.\n",
   7315 			    msg->sadb_msg_type);
   7316 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7317 			error = EINVAL;
   7318 			goto senderror;
   7319 		}
   7320 		break;
   7321 	case SADB_SATYPE_AH:
   7322 	case SADB_SATYPE_ESP:
   7323 	case SADB_X_SATYPE_IPCOMP:
   7324 	case SADB_X_SATYPE_TCPSIGNATURE:
   7325 		switch (msg->sadb_msg_type) {
   7326 		case SADB_X_SPDADD:
   7327 		case SADB_X_SPDDELETE:
   7328 		case SADB_X_SPDGET:
   7329 		case SADB_X_SPDDUMP:
   7330 		case SADB_X_SPDFLUSH:
   7331 		case SADB_X_SPDSETIDX:
   7332 		case SADB_X_SPDUPDATE:
   7333 		case SADB_X_SPDDELETE2:
   7334 			IPSECLOG(LOG_DEBUG, "illegal satype=%u\n",
   7335 			    msg->sadb_msg_type);
   7336 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7337 			error = EINVAL;
   7338 			goto senderror;
   7339 		}
   7340 		break;
   7341 	case SADB_SATYPE_RSVP:
   7342 	case SADB_SATYPE_OSPFV2:
   7343 	case SADB_SATYPE_RIPV2:
   7344 	case SADB_SATYPE_MIP:
   7345 		IPSECLOG(LOG_DEBUG, "type %u isn't supported.\n",
   7346 		    msg->sadb_msg_satype);
   7347 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7348 		error = EOPNOTSUPP;
   7349 		goto senderror;
   7350 	case 1:	/* XXX: What does it do? */
   7351 		if (msg->sadb_msg_type == SADB_X_PROMISC)
   7352 			break;
   7353 		/*FALLTHROUGH*/
   7354 	default:
   7355 		IPSECLOG(LOG_DEBUG, "invalid type %u is passed.\n",
   7356 		    msg->sadb_msg_satype);
   7357 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7358 		error = EINVAL;
   7359 		goto senderror;
   7360 	}
   7361 
   7362 	/* check field of upper layer protocol and address family */
   7363 	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL &&
   7364 	    mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
   7365 		struct sadb_address *src0, *dst0;
   7366 		u_int plen;
   7367 
   7368 		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
   7369 		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
   7370 
   7371 		/* check upper layer protocol */
   7372 		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
   7373 			IPSECLOG(LOG_DEBUG, "upper layer protocol mismatched.\n");
   7374 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7375 			error = EINVAL;
   7376 			goto senderror;
   7377 		}
   7378 
   7379 		/* check family */
   7380 		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
   7381 		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
   7382 			IPSECLOG(LOG_DEBUG, "address family mismatched.\n");
   7383 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7384 			error = EINVAL;
   7385 			goto senderror;
   7386 		}
   7387 		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7388 		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
   7389 			IPSECLOG(LOG_DEBUG,
   7390 			    "address struct size mismatched.\n");
   7391 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7392 			error = EINVAL;
   7393 			goto senderror;
   7394 		}
   7395 
   7396 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7397 		case AF_INET:
   7398 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7399 			    sizeof(struct sockaddr_in)) {
   7400 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7401 				error = EINVAL;
   7402 				goto senderror;
   7403 			}
   7404 			break;
   7405 		case AF_INET6:
   7406 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7407 			    sizeof(struct sockaddr_in6)) {
   7408 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7409 				error = EINVAL;
   7410 				goto senderror;
   7411 			}
   7412 			break;
   7413 		default:
   7414 			IPSECLOG(LOG_DEBUG, "unsupported address family.\n");
   7415 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7416 			error = EAFNOSUPPORT;
   7417 			goto senderror;
   7418 		}
   7419 
   7420 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7421 		case AF_INET:
   7422 			plen = sizeof(struct in_addr) << 3;
   7423 			break;
   7424 		case AF_INET6:
   7425 			plen = sizeof(struct in6_addr) << 3;
   7426 			break;
   7427 		default:
   7428 			plen = 0;	/*fool gcc*/
   7429 			break;
   7430 		}
   7431 
   7432 		/* check max prefix length */
   7433 		if (src0->sadb_address_prefixlen > plen ||
   7434 		    dst0->sadb_address_prefixlen > plen) {
   7435 			IPSECLOG(LOG_DEBUG, "illegal prefixlen.\n");
   7436 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7437 			error = EINVAL;
   7438 			goto senderror;
   7439 		}
   7440 
   7441 		/*
   7442 		 * prefixlen == 0 is valid because there can be a case when
   7443 		 * all addresses are matched.
   7444 		 */
   7445 	}
   7446 
   7447 	if (msg->sadb_msg_type >= __arraycount(key_api_typesw) ||
   7448 	    key_api_typesw[msg->sadb_msg_type] == NULL) {
   7449 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7450 		error = EINVAL;
   7451 		goto senderror;
   7452 	}
   7453 
   7454 	return (*key_api_typesw[msg->sadb_msg_type])(so, m, &mh);
   7455 
   7456 senderror:
   7457 	return key_senderror(so, m, error);
   7458 }
   7459 
   7460 static int
   7461 key_senderror(struct socket *so, struct mbuf *m, int code)
   7462 {
   7463 	struct sadb_msg *msg;
   7464 
   7465 	KASSERT(m->m_len >= sizeof(struct sadb_msg));
   7466 
   7467 	msg = mtod(m, struct sadb_msg *);
   7468 	msg->sadb_msg_errno = code;
   7469 	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   7470 }
   7471 
   7472 /*
   7473  * set the pointer to each header into message buffer.
   7474  * m will be freed on error.
   7475  * XXX larger-than-MCLBYTES extension?
   7476  */
   7477 static int
   7478 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
   7479 {
   7480 	struct mbuf *n;
   7481 	struct sadb_ext *ext;
   7482 	size_t off, end;
   7483 	int extlen;
   7484 	int toff;
   7485 
   7486 	KASSERT(m != NULL);
   7487 	KASSERT(mhp != NULL);
   7488 	KASSERT(m->m_len >= sizeof(struct sadb_msg));
   7489 
   7490 	/* initialize */
   7491 	memset(mhp, 0, sizeof(*mhp));
   7492 
   7493 	mhp->msg = mtod(m, struct sadb_msg *);
   7494 	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
   7495 
   7496 	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   7497 	extlen = end;	/*just in case extlen is not updated*/
   7498 	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
   7499 		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
   7500 		if (!n) {
   7501 			/* m is already freed */
   7502 			return ENOBUFS;
   7503 		}
   7504 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7505 
   7506 		/* set pointer */
   7507 		switch (ext->sadb_ext_type) {
   7508 		case SADB_EXT_SA:
   7509 		case SADB_EXT_ADDRESS_SRC:
   7510 		case SADB_EXT_ADDRESS_DST:
   7511 		case SADB_EXT_ADDRESS_PROXY:
   7512 		case SADB_EXT_LIFETIME_CURRENT:
   7513 		case SADB_EXT_LIFETIME_HARD:
   7514 		case SADB_EXT_LIFETIME_SOFT:
   7515 		case SADB_EXT_KEY_AUTH:
   7516 		case SADB_EXT_KEY_ENCRYPT:
   7517 		case SADB_EXT_IDENTITY_SRC:
   7518 		case SADB_EXT_IDENTITY_DST:
   7519 		case SADB_EXT_SENSITIVITY:
   7520 		case SADB_EXT_PROPOSAL:
   7521 		case SADB_EXT_SUPPORTED_AUTH:
   7522 		case SADB_EXT_SUPPORTED_ENCRYPT:
   7523 		case SADB_EXT_SPIRANGE:
   7524 		case SADB_X_EXT_POLICY:
   7525 		case SADB_X_EXT_SA2:
   7526 		case SADB_X_EXT_NAT_T_TYPE:
   7527 		case SADB_X_EXT_NAT_T_SPORT:
   7528 		case SADB_X_EXT_NAT_T_DPORT:
   7529 		case SADB_X_EXT_NAT_T_OAI:
   7530 		case SADB_X_EXT_NAT_T_OAR:
   7531 		case SADB_X_EXT_NAT_T_FRAG:
   7532 			/* duplicate check */
   7533 			/*
   7534 			 * XXX Are there duplication payloads of either
   7535 			 * KEY_AUTH or KEY_ENCRYPT ?
   7536 			 */
   7537 			if (mhp->ext[ext->sadb_ext_type] != NULL) {
   7538 				IPSECLOG(LOG_DEBUG,
   7539 				    "duplicate ext_type %u is passed.\n",
   7540 				    ext->sadb_ext_type);
   7541 				m_freem(m);
   7542 				PFKEY_STATINC(PFKEY_STAT_OUT_DUPEXT);
   7543 				return EINVAL;
   7544 			}
   7545 			break;
   7546 		default:
   7547 			IPSECLOG(LOG_DEBUG, "invalid ext_type %u is passed.\n",
   7548 			    ext->sadb_ext_type);
   7549 			m_freem(m);
   7550 			PFKEY_STATINC(PFKEY_STAT_OUT_INVEXTTYPE);
   7551 			return EINVAL;
   7552 		}
   7553 
   7554 		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
   7555 
   7556 		if (key_validate_ext(ext, extlen)) {
   7557 			m_freem(m);
   7558 			PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7559 			return EINVAL;
   7560 		}
   7561 
   7562 		n = m_pulldown(m, off, extlen, &toff);
   7563 		if (!n) {
   7564 			/* m is already freed */
   7565 			return ENOBUFS;
   7566 		}
   7567 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7568 
   7569 		mhp->ext[ext->sadb_ext_type] = ext;
   7570 		mhp->extoff[ext->sadb_ext_type] = off;
   7571 		mhp->extlen[ext->sadb_ext_type] = extlen;
   7572 	}
   7573 
   7574 	if (off != end) {
   7575 		m_freem(m);
   7576 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7577 		return EINVAL;
   7578 	}
   7579 
   7580 	return 0;
   7581 }
   7582 
   7583 static int
   7584 key_validate_ext(const struct sadb_ext *ext, int len)
   7585 {
   7586 	const struct sockaddr *sa;
   7587 	enum { NONE, ADDR } checktype = NONE;
   7588 	int baselen = 0;
   7589 	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
   7590 
   7591 	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
   7592 		return EINVAL;
   7593 
   7594 	/* if it does not match minimum/maximum length, bail */
   7595 	if (ext->sadb_ext_type >= __arraycount(minsize) ||
   7596 	    ext->sadb_ext_type >= __arraycount(maxsize))
   7597 		return EINVAL;
   7598 	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
   7599 		return EINVAL;
   7600 	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
   7601 		return EINVAL;
   7602 
   7603 	/* more checks based on sadb_ext_type XXX need more */
   7604 	switch (ext->sadb_ext_type) {
   7605 	case SADB_EXT_ADDRESS_SRC:
   7606 	case SADB_EXT_ADDRESS_DST:
   7607 	case SADB_EXT_ADDRESS_PROXY:
   7608 		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
   7609 		checktype = ADDR;
   7610 		break;
   7611 	case SADB_EXT_IDENTITY_SRC:
   7612 	case SADB_EXT_IDENTITY_DST:
   7613 		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
   7614 		    SADB_X_IDENTTYPE_ADDR) {
   7615 			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
   7616 			checktype = ADDR;
   7617 		} else
   7618 			checktype = NONE;
   7619 		break;
   7620 	default:
   7621 		checktype = NONE;
   7622 		break;
   7623 	}
   7624 
   7625 	switch (checktype) {
   7626 	case NONE:
   7627 		break;
   7628 	case ADDR:
   7629 		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
   7630 		if (len < baselen + sal)
   7631 			return EINVAL;
   7632 		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
   7633 			return EINVAL;
   7634 		break;
   7635 	}
   7636 
   7637 	return 0;
   7638 }
   7639 
   7640 static int
   7641 key_do_init(void)
   7642 {
   7643 	int i, error;
   7644 
   7645 	mutex_init(&key_mtx, MUTEX_DEFAULT, IPL_NONE);
   7646 
   7647 	pfkeystat_percpu = percpu_alloc(sizeof(uint64_t) * PFKEY_NSTATS);
   7648 
   7649 	callout_init(&key_timehandler_ch, 0);
   7650 	error = workqueue_create(&key_timehandler_wq, "key_timehandler",
   7651 	    key_timehandler_work, NULL, PRI_SOFTNET, IPL_SOFTNET, WQ_MPSAFE);
   7652 	if (error != 0)
   7653 		panic("%s: workqueue_create failed (%d)\n", __func__, error);
   7654 
   7655 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
   7656 		LIST_INIT(&sptree[i]);
   7657 	}
   7658 
   7659 	LIST_INIT(&sahtree);
   7660 
   7661 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   7662 		LIST_INIT(&regtree[i]);
   7663 	}
   7664 
   7665 #ifndef IPSEC_NONBLOCK_ACQUIRE
   7666 	LIST_INIT(&acqtree);
   7667 #endif
   7668 #ifdef notyet
   7669 	LIST_INIT(&spacqtree);
   7670 #endif
   7671 
   7672 	/* system default */
   7673 	ip4_def_policy.policy = IPSEC_POLICY_NONE;
   7674 	ip4_def_policy.refcnt++;	/*never reclaim this*/
   7675 
   7676 #ifdef INET6
   7677 	ip6_def_policy.policy = IPSEC_POLICY_NONE;
   7678 	ip6_def_policy.refcnt++;	/*never reclaim this*/
   7679 #endif
   7680 
   7681 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   7682 
   7683 	/* initialize key statistics */
   7684 	keystat.getspi_count = 1;
   7685 
   7686 	aprint_verbose("IPsec: Initialized Security Association Processing.\n");
   7687 
   7688 	return (0);
   7689 }
   7690 
   7691 void
   7692 key_init(void)
   7693 {
   7694 	static ONCE_DECL(key_init_once);
   7695 
   7696 	sysctl_net_keyv2_setup(NULL);
   7697 	sysctl_net_key_compat_setup(NULL);
   7698 
   7699 	RUN_ONCE(&key_init_once, key_do_init);
   7700 }
   7701 
   7702 /*
   7703  * XXX: maybe This function is called after INBOUND IPsec processing.
   7704  *
   7705  * Special check for tunnel-mode packets.
   7706  * We must make some checks for consistency between inner and outer IP header.
   7707  *
   7708  * xxx more checks to be provided
   7709  */
   7710 int
   7711 key_checktunnelsanity(
   7712     struct secasvar *sav,
   7713     u_int family,
   7714     void *src,
   7715     void *dst
   7716 )
   7717 {
   7718 
   7719 	KASSERT(sav->sah != NULL);
   7720 
   7721 	/* XXX: check inner IP header */
   7722 
   7723 	return 1;
   7724 }
   7725 
   7726 #if 0
   7727 #define hostnamelen	strlen(hostname)
   7728 
   7729 /*
   7730  * Get FQDN for the host.
   7731  * If the administrator configured hostname (by hostname(1)) without
   7732  * domain name, returns nothing.
   7733  */
   7734 static const char *
   7735 key_getfqdn(void)
   7736 {
   7737 	int i;
   7738 	int hasdot;
   7739 	static char fqdn[MAXHOSTNAMELEN + 1];
   7740 
   7741 	if (!hostnamelen)
   7742 		return NULL;
   7743 
   7744 	/* check if it comes with domain name. */
   7745 	hasdot = 0;
   7746 	for (i = 0; i < hostnamelen; i++) {
   7747 		if (hostname[i] == '.')
   7748 			hasdot++;
   7749 	}
   7750 	if (!hasdot)
   7751 		return NULL;
   7752 
   7753 	/* NOTE: hostname may not be NUL-terminated. */
   7754 	memset(fqdn, 0, sizeof(fqdn));
   7755 	memcpy(fqdn, hostname, hostnamelen);
   7756 	fqdn[hostnamelen] = '\0';
   7757 	return fqdn;
   7758 }
   7759 
   7760 /*
   7761  * get username@FQDN for the host/user.
   7762  */
   7763 static const char *
   7764 key_getuserfqdn(void)
   7765 {
   7766 	const char *host;
   7767 	static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
   7768 	struct proc *p = curproc;
   7769 	char *q;
   7770 
   7771 	if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
   7772 		return NULL;
   7773 	if (!(host = key_getfqdn()))
   7774 		return NULL;
   7775 
   7776 	/* NOTE: s_login may not be-NUL terminated. */
   7777 	memset(userfqdn, 0, sizeof(userfqdn));
   7778 	memcpy(userfqdn, Mp->p_pgrp->pg_session->s_login, AXLOGNAME);
   7779 	userfqdn[MAXLOGNAME] = '\0';	/* safeguard */
   7780 	q = userfqdn + strlen(userfqdn);
   7781 	*q++ = '@';
   7782 	memcpy(q, host, strlen(host));
   7783 	q += strlen(host);
   7784 	*q++ = '\0';
   7785 
   7786 	return userfqdn;
   7787 }
   7788 #endif
   7789 
   7790 /* record data transfer on SA, and update timestamps */
   7791 void
   7792 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
   7793 {
   7794 
   7795 	KASSERT(sav != NULL);
   7796 	KASSERT(m != NULL);
   7797 	if (!sav->lft_c)
   7798 		return;
   7799 
   7800 	/*
   7801 	 * XXX Currently, there is a difference of bytes size
   7802 	 * between inbound and outbound processing.
   7803 	 */
   7804 	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
   7805 	/* to check bytes lifetime is done in key_timehandler(). */
   7806 
   7807 	/*
   7808 	 * We use the number of packets as the unit of
   7809 	 * sadb_lifetime_allocations.  We increment the variable
   7810 	 * whenever {esp,ah}_{in,out}put is called.
   7811 	 */
   7812 	sav->lft_c->sadb_lifetime_allocations++;
   7813 	/* XXX check for expires? */
   7814 
   7815 	/*
   7816 	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
   7817 	 * in seconds.  HARD and SOFT lifetime are measured by the time
   7818 	 * difference (again in seconds) from sadb_lifetime_usetime.
   7819 	 *
   7820 	 *	usetime
   7821 	 *	v     expire   expire
   7822 	 * -----+-----+--------+---> t
   7823 	 *	<--------------> HARD
   7824 	 *	<-----> SOFT
   7825 	 */
   7826 	sav->lft_c->sadb_lifetime_usetime = time_uptime;
   7827 	/* XXX check for expires? */
   7828 
   7829 	return;
   7830 }
   7831 
   7832 /* dumb version */
   7833 void
   7834 key_sa_routechange(struct sockaddr *dst)
   7835 {
   7836 	struct secashead *sah;
   7837 	struct route *ro;
   7838 	const struct sockaddr *sa;
   7839 
   7840 	LIST_FOREACH(sah, &sahtree, chain) {
   7841 		ro = &sah->sa_route;
   7842 		sa = rtcache_getdst(ro);
   7843 		if (sa != NULL && dst->sa_len == sa->sa_len &&
   7844 		    memcmp(dst, sa, dst->sa_len) == 0)
   7845 			rtcache_free(ro);
   7846 	}
   7847 
   7848 	return;
   7849 }
   7850 
   7851 static void
   7852 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
   7853 {
   7854 
   7855 	KASSERT(sav != NULL);
   7856 
   7857 	if (sav->state == state)
   7858 		return;
   7859 
   7860 	KASSERT(__LIST_CHAINED(sav));
   7861 	LIST_REMOVE(sav, chain);
   7862 
   7863 	sav->state = state;
   7864 	LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
   7865 }
   7866 
   7867 /* XXX too much? */
   7868 static struct mbuf *
   7869 key_alloc_mbuf(int l)
   7870 {
   7871 	struct mbuf *m = NULL, *n;
   7872 	int len, t;
   7873 
   7874 	len = l;
   7875 	while (len > 0) {
   7876 		MGET(n, M_DONTWAIT, MT_DATA);
   7877 		if (n && len > MLEN)
   7878 			MCLGET(n, M_DONTWAIT);
   7879 		if (!n) {
   7880 			m_freem(m);
   7881 			return NULL;
   7882 		}
   7883 
   7884 		n->m_next = NULL;
   7885 		n->m_len = 0;
   7886 		n->m_len = M_TRAILINGSPACE(n);
   7887 		/* use the bottom of mbuf, hoping we can prepend afterwards */
   7888 		if (n->m_len > len) {
   7889 			t = (n->m_len - len) & ~(sizeof(long) - 1);
   7890 			n->m_data += t;
   7891 			n->m_len = len;
   7892 		}
   7893 
   7894 		len -= n->m_len;
   7895 
   7896 		if (m)
   7897 			m_cat(m, n);
   7898 		else
   7899 			m = n;
   7900 	}
   7901 
   7902 	return m;
   7903 }
   7904 
   7905 static struct mbuf *
   7906 key_setdump(u_int8_t req_satype, int *errorp, uint32_t pid)
   7907 {
   7908 	struct secashead *sah;
   7909 	struct secasvar *sav;
   7910 	u_int16_t proto;
   7911 	u_int8_t satype;
   7912 	u_int8_t state;
   7913 	int cnt;
   7914 	struct mbuf *m, *n;
   7915 
   7916 	/* map satype to proto */
   7917 	proto = key_satype2proto(req_satype);
   7918 	if (proto == 0) {
   7919 		*errorp = EINVAL;
   7920 		return (NULL);
   7921 	}
   7922 
   7923 	/* count sav entries to be sent to the userland. */
   7924 	cnt = 0;
   7925 	LIST_FOREACH(sah, &sahtree, chain) {
   7926 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7927 		    proto != sah->saidx.proto)
   7928 			continue;
   7929 
   7930 		SASTATE_ANY_FOREACH(state) {
   7931 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   7932 				cnt++;
   7933 			}
   7934 		}
   7935 	}
   7936 
   7937 	if (cnt == 0) {
   7938 		*errorp = ENOENT;
   7939 		return (NULL);
   7940 	}
   7941 
   7942 	/* send this to the userland, one at a time. */
   7943 	m = NULL;
   7944 	LIST_FOREACH(sah, &sahtree, chain) {
   7945 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7946 		    proto != sah->saidx.proto)
   7947 			continue;
   7948 
   7949 		/* map proto to satype */
   7950 		satype = key_proto2satype(sah->saidx.proto);
   7951 		if (satype == 0) {
   7952 			m_freem(m);
   7953 			*errorp = EINVAL;
   7954 			return (NULL);
   7955 		}
   7956 
   7957 		SASTATE_ANY_FOREACH(state) {
   7958 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   7959 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   7960 				    --cnt, pid);
   7961 				if (!n) {
   7962 					m_freem(m);
   7963 					*errorp = ENOBUFS;
   7964 					return (NULL);
   7965 				}
   7966 
   7967 				if (!m)
   7968 					m = n;
   7969 				else
   7970 					m_cat(m, n);
   7971 			}
   7972 		}
   7973 	}
   7974 
   7975 	if (!m) {
   7976 		*errorp = EINVAL;
   7977 		return (NULL);
   7978 	}
   7979 
   7980 	if ((m->m_flags & M_PKTHDR) != 0) {
   7981 		m->m_pkthdr.len = 0;
   7982 		for (n = m; n; n = n->m_next)
   7983 			m->m_pkthdr.len += n->m_len;
   7984 	}
   7985 
   7986 	*errorp = 0;
   7987 	return (m);
   7988 }
   7989 
   7990 static struct mbuf *
   7991 key_setspddump(int *errorp, pid_t pid)
   7992 {
   7993 	struct secpolicy *sp;
   7994 	int cnt;
   7995 	u_int dir;
   7996 	struct mbuf *m, *n;
   7997 
   7998 	/* search SPD entry and get buffer size. */
   7999 	cnt = 0;
   8000 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   8001 		LIST_FOREACH(sp, &sptree[dir], chain) {
   8002 			cnt++;
   8003 		}
   8004 	}
   8005 
   8006 	if (cnt == 0) {
   8007 		*errorp = ENOENT;
   8008 		return (NULL);
   8009 	}
   8010 
   8011 	m = NULL;
   8012 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   8013 		LIST_FOREACH(sp, &sptree[dir], chain) {
   8014 			--cnt;
   8015 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
   8016 
   8017 			if (!n) {
   8018 				*errorp = ENOBUFS;
   8019 				m_freem(m);
   8020 				return (NULL);
   8021 			}
   8022 			if (!m)
   8023 				m = n;
   8024 			else {
   8025 				m->m_pkthdr.len += n->m_pkthdr.len;
   8026 				m_cat(m, n);
   8027 			}
   8028 		}
   8029 	}
   8030 
   8031 	*errorp = 0;
   8032 	return (m);
   8033 }
   8034 
   8035 int
   8036 key_get_used(void) {
   8037 	return !LIST_EMPTY(&sptree[IPSEC_DIR_INBOUND]) ||
   8038 	    !LIST_EMPTY(&sptree[IPSEC_DIR_OUTBOUND]);
   8039 }
   8040 
   8041 void
   8042 key_update_used(void)
   8043 {
   8044 	switch (ipsec_enabled) {
   8045 	default:
   8046 	case 0:
   8047 #ifdef notyet
   8048 		/* XXX: racy */
   8049 		ipsec_used = 0;
   8050 #endif
   8051 		break;
   8052 	case 1:
   8053 #ifndef notyet
   8054 		/* XXX: racy */
   8055 		if (!ipsec_used)
   8056 #endif
   8057 		ipsec_used = key_get_used();
   8058 		break;
   8059 	case 2:
   8060 		ipsec_used = 1;
   8061 		break;
   8062 	}
   8063 }
   8064 
   8065 static int
   8066 sysctl_net_key_dumpsa(SYSCTLFN_ARGS)
   8067 {
   8068 	struct mbuf *m, *n;
   8069 	int err2 = 0;
   8070 	char *p, *ep;
   8071 	size_t len;
   8072 	int s, error;
   8073 
   8074 	if (newp)
   8075 		return (EPERM);
   8076 	if (namelen != 1)
   8077 		return (EINVAL);
   8078 
   8079 	s = splsoftnet();
   8080 	m = key_setdump(name[0], &error, l->l_proc->p_pid);
   8081 	splx(s);
   8082 	if (!m)
   8083 		return (error);
   8084 	if (!oldp)
   8085 		*oldlenp = m->m_pkthdr.len;
   8086 	else {
   8087 		p = oldp;
   8088 		if (*oldlenp < m->m_pkthdr.len) {
   8089 			err2 = ENOMEM;
   8090 			ep = p + *oldlenp;
   8091 		} else {
   8092 			*oldlenp = m->m_pkthdr.len;
   8093 			ep = p + m->m_pkthdr.len;
   8094 		}
   8095 		for (n = m; n; n = n->m_next) {
   8096 			len =  (ep - p < n->m_len) ?
   8097 				ep - p : n->m_len;
   8098 			error = copyout(mtod(n, const void *), p, len);
   8099 			p += len;
   8100 			if (error)
   8101 				break;
   8102 		}
   8103 		if (error == 0)
   8104 			error = err2;
   8105 	}
   8106 	m_freem(m);
   8107 
   8108 	return (error);
   8109 }
   8110 
   8111 static int
   8112 sysctl_net_key_dumpsp(SYSCTLFN_ARGS)
   8113 {
   8114 	struct mbuf *m, *n;
   8115 	int err2 = 0;
   8116 	char *p, *ep;
   8117 	size_t len;
   8118 	int s, error;
   8119 
   8120 	if (newp)
   8121 		return (EPERM);
   8122 	if (namelen != 0)
   8123 		return (EINVAL);
   8124 
   8125 	s = splsoftnet();
   8126 	m = key_setspddump(&error, l->l_proc->p_pid);
   8127 	splx(s);
   8128 	if (!m)
   8129 		return (error);
   8130 	if (!oldp)
   8131 		*oldlenp = m->m_pkthdr.len;
   8132 	else {
   8133 		p = oldp;
   8134 		if (*oldlenp < m->m_pkthdr.len) {
   8135 			err2 = ENOMEM;
   8136 			ep = p + *oldlenp;
   8137 		} else {
   8138 			*oldlenp = m->m_pkthdr.len;
   8139 			ep = p + m->m_pkthdr.len;
   8140 		}
   8141 		for (n = m; n; n = n->m_next) {
   8142 			len = (ep - p < n->m_len) ? ep - p : n->m_len;
   8143 			error = copyout(mtod(n, const void *), p, len);
   8144 			p += len;
   8145 			if (error)
   8146 				break;
   8147 		}
   8148 		if (error == 0)
   8149 			error = err2;
   8150 	}
   8151 	m_freem(m);
   8152 
   8153 	return (error);
   8154 }
   8155 
   8156 /*
   8157  * Create sysctl tree for native IPSEC key knobs, originally
   8158  * under name "net.keyv2"  * with MIB number { CTL_NET, PF_KEY_V2. }.
   8159  * However, sysctl(8) never checked for nodes under { CTL_NET, PF_KEY_V2 };
   8160  * and in any case the part of our sysctl namespace used for dumping the
   8161  * SPD and SA database  *HAS* to be compatible with the KAME sysctl
   8162  * namespace, for API reasons.
   8163  *
   8164  * Pending a consensus on the right way  to fix this, add a level of
   8165  * indirection in how we number the `native' IPSEC key nodes;
   8166  * and (as requested by Andrew Brown)  move registration of the
   8167  * KAME-compatible names  to a separate function.
   8168  */
   8169 #if 0
   8170 #  define IPSEC_PFKEY PF_KEY_V2
   8171 # define IPSEC_PFKEY_NAME "keyv2"
   8172 #else
   8173 #  define IPSEC_PFKEY PF_KEY
   8174 # define IPSEC_PFKEY_NAME "key"
   8175 #endif
   8176 
   8177 static int
   8178 sysctl_net_key_stats(SYSCTLFN_ARGS)
   8179 {
   8180 
   8181 	return (NETSTAT_SYSCTL(pfkeystat_percpu, PFKEY_NSTATS));
   8182 }
   8183 
   8184 static void
   8185 sysctl_net_keyv2_setup(struct sysctllog **clog)
   8186 {
   8187 
   8188 	sysctl_createv(clog, 0, NULL, NULL,
   8189 		       CTLFLAG_PERMANENT,
   8190 		       CTLTYPE_NODE, IPSEC_PFKEY_NAME, NULL,
   8191 		       NULL, 0, NULL, 0,
   8192 		       CTL_NET, IPSEC_PFKEY, CTL_EOL);
   8193 
   8194 	sysctl_createv(clog, 0, NULL, NULL,
   8195 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8196 		       CTLTYPE_INT, "debug", NULL,
   8197 		       NULL, 0, &key_debug_level, 0,
   8198 		       CTL_NET, IPSEC_PFKEY, KEYCTL_DEBUG_LEVEL, CTL_EOL);
   8199 	sysctl_createv(clog, 0, NULL, NULL,
   8200 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8201 		       CTLTYPE_INT, "spi_try", NULL,
   8202 		       NULL, 0, &key_spi_trycnt, 0,
   8203 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_TRY, CTL_EOL);
   8204 	sysctl_createv(clog, 0, NULL, NULL,
   8205 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8206 		       CTLTYPE_INT, "spi_min_value", NULL,
   8207 		       NULL, 0, &key_spi_minval, 0,
   8208 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MIN_VALUE, CTL_EOL);
   8209 	sysctl_createv(clog, 0, NULL, NULL,
   8210 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8211 		       CTLTYPE_INT, "spi_max_value", NULL,
   8212 		       NULL, 0, &key_spi_maxval, 0,
   8213 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MAX_VALUE, CTL_EOL);
   8214 	sysctl_createv(clog, 0, NULL, NULL,
   8215 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8216 		       CTLTYPE_INT, "random_int", NULL,
   8217 		       NULL, 0, &key_int_random, 0,
   8218 		       CTL_NET, IPSEC_PFKEY, KEYCTL_RANDOM_INT, CTL_EOL);
   8219 	sysctl_createv(clog, 0, NULL, NULL,
   8220 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8221 		       CTLTYPE_INT, "larval_lifetime", NULL,
   8222 		       NULL, 0, &key_larval_lifetime, 0,
   8223 		       CTL_NET, IPSEC_PFKEY, KEYCTL_LARVAL_LIFETIME, CTL_EOL);
   8224 	sysctl_createv(clog, 0, NULL, NULL,
   8225 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8226 		       CTLTYPE_INT, "blockacq_count", NULL,
   8227 		       NULL, 0, &key_blockacq_count, 0,
   8228 		       CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_COUNT, CTL_EOL);
   8229 	sysctl_createv(clog, 0, NULL, NULL,
   8230 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8231 		       CTLTYPE_INT, "blockacq_lifetime", NULL,
   8232 		       NULL, 0, &key_blockacq_lifetime, 0,
   8233 		       CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_LIFETIME, CTL_EOL);
   8234 	sysctl_createv(clog, 0, NULL, NULL,
   8235 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8236 		       CTLTYPE_INT, "esp_keymin", NULL,
   8237 		       NULL, 0, &ipsec_esp_keymin, 0,
   8238 		       CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_KEYMIN, CTL_EOL);
   8239 	sysctl_createv(clog, 0, NULL, NULL,
   8240 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8241 		       CTLTYPE_INT, "prefered_oldsa", NULL,
   8242 		       NULL, 0, &key_prefered_oldsa, 0,
   8243 		       CTL_NET, PF_KEY, KEYCTL_PREFERED_OLDSA, CTL_EOL);
   8244 	sysctl_createv(clog, 0, NULL, NULL,
   8245 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8246 		       CTLTYPE_INT, "esp_auth", NULL,
   8247 		       NULL, 0, &ipsec_esp_auth, 0,
   8248 		       CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_AUTH, CTL_EOL);
   8249 	sysctl_createv(clog, 0, NULL, NULL,
   8250 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8251 		       CTLTYPE_INT, "ah_keymin", NULL,
   8252 		       NULL, 0, &ipsec_ah_keymin, 0,
   8253 		       CTL_NET, IPSEC_PFKEY, KEYCTL_AH_KEYMIN, CTL_EOL);
   8254 	sysctl_createv(clog, 0, NULL, NULL,
   8255 		       CTLFLAG_PERMANENT,
   8256 		       CTLTYPE_STRUCT, "stats",
   8257 		       SYSCTL_DESCR("PF_KEY statistics"),
   8258 		       sysctl_net_key_stats, 0, NULL, 0,
   8259 		       CTL_NET, IPSEC_PFKEY, CTL_CREATE, CTL_EOL);
   8260 }
   8261 
   8262 /*
   8263  * Register sysctl names used by setkey(8). For historical reasons,
   8264  * and to share a single API, these names appear under { CTL_NET, PF_KEY }
   8265  * for both IPSEC and KAME IPSEC.
   8266  */
   8267 static void
   8268 sysctl_net_key_compat_setup(struct sysctllog **clog)
   8269 {
   8270 
   8271 	sysctl_createv(clog, 0, NULL, NULL,
   8272 		       CTLFLAG_PERMANENT,
   8273 		       CTLTYPE_NODE, "key", NULL,
   8274 		       NULL, 0, NULL, 0,
   8275 		       CTL_NET, PF_KEY, CTL_EOL);
   8276 
   8277 	/* Register the net.key.dump{sa,sp} nodes used by setkey(8). */
   8278 	sysctl_createv(clog, 0, NULL, NULL,
   8279 		       CTLFLAG_PERMANENT,
   8280 		       CTLTYPE_STRUCT, "dumpsa", NULL,
   8281 		       sysctl_net_key_dumpsa, 0, NULL, 0,
   8282 		       CTL_NET, PF_KEY, KEYCTL_DUMPSA, CTL_EOL);
   8283 	sysctl_createv(clog, 0, NULL, NULL,
   8284 		       CTLFLAG_PERMANENT,
   8285 		       CTLTYPE_STRUCT, "dumpsp", NULL,
   8286 		       sysctl_net_key_dumpsp, 0, NULL, 0,
   8287 		       CTL_NET, PF_KEY, KEYCTL_DUMPSP, CTL_EOL);
   8288 }
   8289