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