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