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