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