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