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