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