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