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