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