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