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