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