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