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