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