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