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