Home | History | Annotate | Line # | Download | only in netipsec
key.c revision 1.69
      1 /*	$NetBSD: key.c,v 1.69 2011/05/18 18:36:15 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.69 2011/05/18 18:36:15 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_uptime;
    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_uptime;
    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_uptime;
    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_uptime;
   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_uptime;
   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 + time_second - time_uptime;
   2797 	lt->sadb_lifetime_usetime = sp->lastused + time_second - time_uptime;
   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_uptime;
   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_uptime;
   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_uptime;
   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 	struct sadb_lifetime lt;
   3557 	int dumporder[] = {
   3558 		SADB_EXT_SA, SADB_X_EXT_SA2,
   3559 		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
   3560 		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
   3561 		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
   3562 		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
   3563 		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
   3564 #ifdef IPSEC_NAT_T
   3565 		SADB_X_EXT_NAT_T_TYPE,
   3566 		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
   3567 		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
   3568 		SADB_X_EXT_NAT_T_FRAG,
   3569 #endif
   3570 
   3571 	};
   3572 
   3573 	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
   3574 	if (m == NULL)
   3575 		goto fail;
   3576 	result = m;
   3577 
   3578 	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
   3579 		m = NULL;
   3580 		p = NULL;
   3581 		switch (dumporder[i]) {
   3582 		case SADB_EXT_SA:
   3583 			m = key_setsadbsa(sav);
   3584 			break;
   3585 
   3586 		case SADB_X_EXT_SA2:
   3587 			m = key_setsadbxsa2(sav->sah->saidx.mode,
   3588 					sav->replay ? sav->replay->count : 0,
   3589 					sav->sah->saidx.reqid);
   3590 			break;
   3591 
   3592 		case SADB_EXT_ADDRESS_SRC:
   3593 			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   3594 			    &sav->sah->saidx.src.sa,
   3595 			    FULLMASK, IPSEC_ULPROTO_ANY);
   3596 			break;
   3597 
   3598 		case SADB_EXT_ADDRESS_DST:
   3599 			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   3600 			    &sav->sah->saidx.dst.sa,
   3601 			    FULLMASK, IPSEC_ULPROTO_ANY);
   3602 			break;
   3603 
   3604 		case SADB_EXT_KEY_AUTH:
   3605 			if (!sav->key_auth)
   3606 				continue;
   3607 			l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
   3608 			p = sav->key_auth;
   3609 			break;
   3610 
   3611 		case SADB_EXT_KEY_ENCRYPT:
   3612 			if (!sav->key_enc)
   3613 				continue;
   3614 			l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
   3615 			p = sav->key_enc;
   3616 			break;
   3617 
   3618 		case SADB_EXT_LIFETIME_CURRENT:
   3619 			if (!sav->lft_c)
   3620 				continue;
   3621 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
   3622 			memcpy(&lt, sav->lft_c, sizeof(struct sadb_lifetime));
   3623 			lt.sadb_lifetime_addtime += time_second - time_uptime;
   3624 			lt.sadb_lifetime_usetime += time_second - time_uptime;
   3625 			p = &lt;
   3626 			break;
   3627 
   3628 		case SADB_EXT_LIFETIME_HARD:
   3629 			if (!sav->lft_h)
   3630 				continue;
   3631 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
   3632 			p = sav->lft_h;
   3633 			break;
   3634 
   3635 		case SADB_EXT_LIFETIME_SOFT:
   3636 			if (!sav->lft_s)
   3637 				continue;
   3638 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
   3639 			p = sav->lft_s;
   3640 			break;
   3641 
   3642 #ifdef IPSEC_NAT_T
   3643 		case SADB_X_EXT_NAT_T_TYPE:
   3644 			m = key_setsadbxtype(sav->natt_type);
   3645 			break;
   3646 
   3647 		case SADB_X_EXT_NAT_T_DPORT:
   3648 			if (sav->natt_type == 0)
   3649 				continue;
   3650 			m = key_setsadbxport(
   3651 				key_portfromsaddr(&sav->sah->saidx.dst),
   3652 				SADB_X_EXT_NAT_T_DPORT);
   3653 			break;
   3654 
   3655 		case SADB_X_EXT_NAT_T_SPORT:
   3656 			if (sav->natt_type == 0)
   3657 				continue;
   3658 			m = key_setsadbxport(
   3659 				key_portfromsaddr(&sav->sah->saidx.src),
   3660 				SADB_X_EXT_NAT_T_SPORT);
   3661 			break;
   3662 
   3663 		case SADB_X_EXT_NAT_T_OAI:
   3664 		case SADB_X_EXT_NAT_T_OAR:
   3665 		case SADB_X_EXT_NAT_T_FRAG:
   3666 			continue;
   3667 #endif
   3668 
   3669 		case SADB_EXT_ADDRESS_PROXY:
   3670 		case SADB_EXT_IDENTITY_SRC:
   3671 		case SADB_EXT_IDENTITY_DST:
   3672 			/* XXX: should we brought from SPD ? */
   3673 		case SADB_EXT_SENSITIVITY:
   3674 		default:
   3675 			continue;
   3676 		}
   3677 
   3678 		KASSERT(!(m && p));
   3679 		if (!m && !p)
   3680 			goto fail;
   3681 		if (p && tres) {
   3682 			M_PREPEND(tres, l, M_DONTWAIT);
   3683 			if (!tres)
   3684 				goto fail;
   3685 			memcpy(mtod(tres, void *), p, l);
   3686 			continue;
   3687 		}
   3688 		if (p) {
   3689 			m = key_alloc_mbuf(l);
   3690 			if (!m)
   3691 				goto fail;
   3692 			m_copyback(m, 0, l, p);
   3693 		}
   3694 
   3695 		if (tres)
   3696 			m_cat(m, tres);
   3697 		tres = m;
   3698 	}
   3699 
   3700 	m_cat(result, tres);
   3701 	tres = NULL; /* avoid free on error below */
   3702 
   3703 	if (result->m_len < sizeof(struct sadb_msg)) {
   3704 		result = m_pullup(result, sizeof(struct sadb_msg));
   3705 		if (result == NULL)
   3706 			goto fail;
   3707 	}
   3708 
   3709 	result->m_pkthdr.len = 0;
   3710 	for (m = result; m; m = m->m_next)
   3711 		result->m_pkthdr.len += m->m_len;
   3712 
   3713 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   3714 	    PFKEY_UNIT64(result->m_pkthdr.len);
   3715 
   3716 	return result;
   3717 
   3718 fail:
   3719 	m_freem(result);
   3720 	m_freem(tres);
   3721 	return NULL;
   3722 }
   3723 
   3724 
   3725 #ifdef IPSEC_NAT_T
   3726 /*
   3727  * set a type in sadb_x_nat_t_type
   3728  */
   3729 static struct mbuf *
   3730 key_setsadbxtype(u_int16_t type)
   3731 {
   3732 	struct mbuf *m;
   3733 	size_t len;
   3734 	struct sadb_x_nat_t_type *p;
   3735 
   3736 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
   3737 
   3738 	m = key_alloc_mbuf(len);
   3739 	if (!m || m->m_next) {	/*XXX*/
   3740 		if (m)
   3741 			m_freem(m);
   3742 		return NULL;
   3743 	}
   3744 
   3745 	p = mtod(m, struct sadb_x_nat_t_type *);
   3746 
   3747 	memset(p, 0, len);
   3748 	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
   3749 	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
   3750 	p->sadb_x_nat_t_type_type = type;
   3751 
   3752 	return m;
   3753 }
   3754 /*
   3755  * set a port in sadb_x_nat_t_port. port is in network order
   3756  */
   3757 static struct mbuf *
   3758 key_setsadbxport(u_int16_t port, u_int16_t type)
   3759 {
   3760 	struct mbuf *m;
   3761 	size_t len;
   3762 	struct sadb_x_nat_t_port *p;
   3763 
   3764 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
   3765 
   3766 	m = key_alloc_mbuf(len);
   3767 	if (!m || m->m_next) {	/*XXX*/
   3768 		if (m)
   3769 			m_freem(m);
   3770 		return NULL;
   3771 	}
   3772 
   3773 	p = mtod(m, struct sadb_x_nat_t_port *);
   3774 
   3775 	memset(p, 0, len);
   3776 	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
   3777 	p->sadb_x_nat_t_port_exttype = type;
   3778 	p->sadb_x_nat_t_port_port = port;
   3779 
   3780 	return m;
   3781 }
   3782 
   3783 /*
   3784  * Get port from sockaddr, port is in network order
   3785  */
   3786 u_int16_t
   3787 key_portfromsaddr(const union sockaddr_union *saddr)
   3788 {
   3789 	u_int16_t port;
   3790 
   3791 	switch (saddr->sa.sa_family) {
   3792 	case AF_INET: {
   3793 		port = saddr->sin.sin_port;
   3794 		break;
   3795 	}
   3796 #ifdef INET6
   3797 	case AF_INET6: {
   3798 		port = saddr->sin6.sin6_port;
   3799 		break;
   3800 	}
   3801 #endif
   3802 	default:
   3803 		printf("key_portfromsaddr: unexpected address family\n");
   3804 		port = 0;
   3805 		break;
   3806 	}
   3807 
   3808 	return port;
   3809 }
   3810 
   3811 #endif /* IPSEC_NAT_T */
   3812 
   3813 /*
   3814  * Set port is struct sockaddr. port is in network order
   3815  */
   3816 static void
   3817 key_porttosaddr(union sockaddr_union *saddr, u_int16_t port)
   3818 {
   3819 	switch (saddr->sa.sa_family) {
   3820 	case AF_INET: {
   3821 		saddr->sin.sin_port = port;
   3822 		break;
   3823 	}
   3824 #ifdef INET6
   3825 	case AF_INET6: {
   3826 		saddr->sin6.sin6_port = port;
   3827 		break;
   3828 	}
   3829 #endif
   3830 	default:
   3831 		printf("key_porttosaddr: unexpected address family %d\n",
   3832 			saddr->sa.sa_family);
   3833 		break;
   3834 	}
   3835 
   3836 	return;
   3837 }
   3838 
   3839 /*
   3840  * Safety check sa_len
   3841  */
   3842 static int
   3843 key_checksalen(const union sockaddr_union *saddr)
   3844 {
   3845         switch (saddr->sa.sa_family) {
   3846         case AF_INET:
   3847                 if (saddr->sa.sa_len != sizeof(struct sockaddr_in))
   3848                         return -1;
   3849                 break;
   3850 #ifdef INET6
   3851         case AF_INET6:
   3852                 if (saddr->sa.sa_len != sizeof(struct sockaddr_in6))
   3853                         return -1;
   3854                 break;
   3855 #endif
   3856         default:
   3857                 printf("key_checksalen: unexpected sa_family %d\n",
   3858                     saddr->sa.sa_family);
   3859                 return -1;
   3860                 break;
   3861         }
   3862 	return 0;
   3863 }
   3864 
   3865 
   3866 /*
   3867  * set data into sadb_msg.
   3868  */
   3869 static struct mbuf *
   3870 key_setsadbmsg(u_int8_t type,  u_int16_t tlen, u_int8_t satype,
   3871 	       u_int32_t seq, pid_t pid, u_int16_t reserved)
   3872 {
   3873 	struct mbuf *m;
   3874 	struct sadb_msg *p;
   3875 	int len;
   3876 
   3877 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   3878 	if (len > MCLBYTES)
   3879 		return NULL;
   3880 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   3881 	if (m && len > MHLEN) {
   3882 		MCLGET(m, M_DONTWAIT);
   3883 		if ((m->m_flags & M_EXT) == 0) {
   3884 			m_freem(m);
   3885 			m = NULL;
   3886 		}
   3887 	}
   3888 	if (!m)
   3889 		return NULL;
   3890 	m->m_pkthdr.len = m->m_len = len;
   3891 	m->m_next = NULL;
   3892 
   3893 	p = mtod(m, struct sadb_msg *);
   3894 
   3895 	memset(p, 0, len);
   3896 	p->sadb_msg_version = PF_KEY_V2;
   3897 	p->sadb_msg_type = type;
   3898 	p->sadb_msg_errno = 0;
   3899 	p->sadb_msg_satype = satype;
   3900 	p->sadb_msg_len = PFKEY_UNIT64(tlen);
   3901 	p->sadb_msg_reserved = reserved;
   3902 	p->sadb_msg_seq = seq;
   3903 	p->sadb_msg_pid = (u_int32_t)pid;
   3904 
   3905 	return m;
   3906 }
   3907 
   3908 /*
   3909  * copy secasvar data into sadb_address.
   3910  */
   3911 static struct mbuf *
   3912 key_setsadbsa(struct secasvar *sav)
   3913 {
   3914 	struct mbuf *m;
   3915 	struct sadb_sa *p;
   3916 	int len;
   3917 
   3918 	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
   3919 	m = key_alloc_mbuf(len);
   3920 	if (!m || m->m_next) {	/*XXX*/
   3921 		if (m)
   3922 			m_freem(m);
   3923 		return NULL;
   3924 	}
   3925 
   3926 	p = mtod(m, struct sadb_sa *);
   3927 
   3928 	memset(p, 0, len);
   3929 	p->sadb_sa_len = PFKEY_UNIT64(len);
   3930 	p->sadb_sa_exttype = SADB_EXT_SA;
   3931 	p->sadb_sa_spi = sav->spi;
   3932 	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
   3933 	p->sadb_sa_state = sav->state;
   3934 	p->sadb_sa_auth = sav->alg_auth;
   3935 	p->sadb_sa_encrypt = sav->alg_enc;
   3936 	p->sadb_sa_flags = sav->flags;
   3937 
   3938 	return m;
   3939 }
   3940 
   3941 /*
   3942  * set data into sadb_address.
   3943  */
   3944 static struct mbuf *
   3945 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
   3946 		u_int8_t prefixlen, u_int16_t ul_proto)
   3947 {
   3948 	struct mbuf *m;
   3949 	struct sadb_address *p;
   3950 	size_t len;
   3951 
   3952 	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
   3953 	    PFKEY_ALIGN8(saddr->sa_len);
   3954 	m = key_alloc_mbuf(len);
   3955 	if (!m || m->m_next) {	/*XXX*/
   3956 		if (m)
   3957 			m_freem(m);
   3958 		return NULL;
   3959 	}
   3960 
   3961 	p = mtod(m, struct sadb_address *);
   3962 
   3963 	memset(p, 0, len);
   3964 	p->sadb_address_len = PFKEY_UNIT64(len);
   3965 	p->sadb_address_exttype = exttype;
   3966 	p->sadb_address_proto = ul_proto;
   3967 	if (prefixlen == FULLMASK) {
   3968 		switch (saddr->sa_family) {
   3969 		case AF_INET:
   3970 			prefixlen = sizeof(struct in_addr) << 3;
   3971 			break;
   3972 		case AF_INET6:
   3973 			prefixlen = sizeof(struct in6_addr) << 3;
   3974 			break;
   3975 		default:
   3976 			; /*XXX*/
   3977 		}
   3978 	}
   3979 	p->sadb_address_prefixlen = prefixlen;
   3980 	p->sadb_address_reserved = 0;
   3981 
   3982 	memcpy(mtod(m, char *) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
   3983 		   saddr, saddr->sa_len);
   3984 
   3985 	return m;
   3986 }
   3987 
   3988 #if 0
   3989 /*
   3990  * set data into sadb_ident.
   3991  */
   3992 static struct mbuf *
   3993 key_setsadbident(u_int16_t exttype, u_int16_t idtype,
   3994 		 void *string, int stringlen, u_int64_t id)
   3995 {
   3996 	struct mbuf *m;
   3997 	struct sadb_ident *p;
   3998 	size_t len;
   3999 
   4000 	len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
   4001 	m = key_alloc_mbuf(len);
   4002 	if (!m || m->m_next) {	/*XXX*/
   4003 		if (m)
   4004 			m_freem(m);
   4005 		return NULL;
   4006 	}
   4007 
   4008 	p = mtod(m, struct sadb_ident *);
   4009 
   4010 	memset(p, 0, len);
   4011 	p->sadb_ident_len = PFKEY_UNIT64(len);
   4012 	p->sadb_ident_exttype = exttype;
   4013 	p->sadb_ident_type = idtype;
   4014 	p->sadb_ident_reserved = 0;
   4015 	p->sadb_ident_id = id;
   4016 
   4017 	memcpy(mtod(m, void *) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
   4018 	   	   string, stringlen);
   4019 
   4020 	return m;
   4021 }
   4022 #endif
   4023 
   4024 /*
   4025  * set data into sadb_x_sa2.
   4026  */
   4027 static struct mbuf *
   4028 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int16_t reqid)
   4029 {
   4030 	struct mbuf *m;
   4031 	struct sadb_x_sa2 *p;
   4032 	size_t len;
   4033 
   4034 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
   4035 	m = key_alloc_mbuf(len);
   4036 	if (!m || m->m_next) {	/*XXX*/
   4037 		if (m)
   4038 			m_freem(m);
   4039 		return NULL;
   4040 	}
   4041 
   4042 	p = mtod(m, struct sadb_x_sa2 *);
   4043 
   4044 	memset(p, 0, len);
   4045 	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
   4046 	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
   4047 	p->sadb_x_sa2_mode = mode;
   4048 	p->sadb_x_sa2_reserved1 = 0;
   4049 	p->sadb_x_sa2_reserved2 = 0;
   4050 	p->sadb_x_sa2_sequence = seq;
   4051 	p->sadb_x_sa2_reqid = reqid;
   4052 
   4053 	return m;
   4054 }
   4055 
   4056 /*
   4057  * set data into sadb_x_policy
   4058  */
   4059 static struct mbuf *
   4060 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
   4061 {
   4062 	struct mbuf *m;
   4063 	struct sadb_x_policy *p;
   4064 	size_t len;
   4065 
   4066 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
   4067 	m = key_alloc_mbuf(len);
   4068 	if (!m || m->m_next) {	/*XXX*/
   4069 		if (m)
   4070 			m_freem(m);
   4071 		return NULL;
   4072 	}
   4073 
   4074 	p = mtod(m, struct sadb_x_policy *);
   4075 
   4076 	memset(p, 0, len);
   4077 	p->sadb_x_policy_len = PFKEY_UNIT64(len);
   4078 	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
   4079 	p->sadb_x_policy_type = type;
   4080 	p->sadb_x_policy_dir = dir;
   4081 	p->sadb_x_policy_id = id;
   4082 
   4083 	return m;
   4084 }
   4085 
   4086 /* %%% utilities */
   4087 /*
   4088  * copy a buffer into the new buffer allocated.
   4089  */
   4090 static void *
   4091 key_newbuf(const void *src, u_int len)
   4092 {
   4093 	void *new;
   4094 
   4095 	KMALLOC(new, void *, len);
   4096 	if (new == NULL) {
   4097 		ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
   4098 		return NULL;
   4099 	}
   4100 	memcpy(new, src, len);
   4101 
   4102 	return new;
   4103 }
   4104 
   4105 /* compare my own address
   4106  * OUT:	1: true, i.e. my address.
   4107  *	0: false
   4108  */
   4109 int
   4110 key_ismyaddr(const struct sockaddr *sa)
   4111 {
   4112 #ifdef INET
   4113 	const struct sockaddr_in *sin;
   4114 	const struct in_ifaddr *ia;
   4115 #endif
   4116 
   4117 	/* sanity check */
   4118 	if (sa == NULL)
   4119 		panic("key_ismyaddr: NULL pointer is passed");
   4120 
   4121 	switch (sa->sa_family) {
   4122 #ifdef INET
   4123 	case AF_INET:
   4124 		sin = (const struct sockaddr_in *)sa;
   4125 		for (ia = in_ifaddrhead.tqh_first; ia;
   4126 		     ia = ia->ia_link.tqe_next)
   4127 		{
   4128 			if (sin->sin_family == ia->ia_addr.sin_family &&
   4129 			    sin->sin_len == ia->ia_addr.sin_len &&
   4130 			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
   4131 			{
   4132 				return 1;
   4133 			}
   4134 		}
   4135 		break;
   4136 #endif
   4137 #ifdef INET6
   4138 	case AF_INET6:
   4139 		return key_ismyaddr6((const struct sockaddr_in6 *)sa);
   4140 #endif
   4141 	}
   4142 
   4143 	return 0;
   4144 }
   4145 
   4146 #ifdef INET6
   4147 /*
   4148  * compare my own address for IPv6.
   4149  * 1: ours
   4150  * 0: other
   4151  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
   4152  */
   4153 #include <netinet6/in6_var.h>
   4154 
   4155 static int
   4156 key_ismyaddr6(const struct sockaddr_in6 *sin6)
   4157 {
   4158 	const struct in6_ifaddr *ia;
   4159 	const struct in6_multi *in6m;
   4160 
   4161 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
   4162 		if (key_sockaddrcmp((const struct sockaddr *)&sin6,
   4163 		    (const struct sockaddr *)&ia->ia_addr, 0) == 0)
   4164 			return 1;
   4165 
   4166 		/*
   4167 		 * XXX Multicast
   4168 		 * XXX why do we care about multlicast here while we don't care
   4169 		 * about IPv4 multicast??
   4170 		 * XXX scope
   4171 		 */
   4172 		in6m = NULL;
   4173 #ifdef __FreeBSD__
   4174 		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
   4175 #else
   4176 		for ((in6m) = ia->ia6_multiaddrs.lh_first;
   4177 		     (in6m) != NULL &&
   4178 		     !IN6_ARE_ADDR_EQUAL(&(in6m)->in6m_addr, &sin6->sin6_addr);
   4179 		     (in6m) = in6m->in6m_entry.le_next)
   4180 			continue;
   4181 #endif
   4182 		if (in6m)
   4183 			return 1;
   4184 	}
   4185 
   4186 	/* loopback, just for safety */
   4187 	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
   4188 		return 1;
   4189 
   4190 	return 0;
   4191 }
   4192 #endif /*INET6*/
   4193 
   4194 /*
   4195  * compare two secasindex structure.
   4196  * flag can specify to compare 2 saidxes.
   4197  * compare two secasindex structure without both mode and reqid.
   4198  * don't compare port.
   4199  * IN:
   4200  *      saidx0: source, it can be in SAD.
   4201  *      saidx1: object.
   4202  * OUT:
   4203  *      1 : equal
   4204  *      0 : not equal
   4205  */
   4206 static int
   4207 key_cmpsaidx(
   4208 	const struct secasindex *saidx0,
   4209 	const struct secasindex *saidx1,
   4210 	int flag)
   4211 {
   4212 	int chkport = 0;
   4213 
   4214 	/* sanity */
   4215 	if (saidx0 == NULL && saidx1 == NULL)
   4216 		return 1;
   4217 
   4218 	if (saidx0 == NULL || saidx1 == NULL)
   4219 		return 0;
   4220 
   4221 	if (saidx0->proto != saidx1->proto)
   4222 		return 0;
   4223 
   4224 	if (flag == CMP_EXACTLY) {
   4225 		if (saidx0->mode != saidx1->mode)
   4226 			return 0;
   4227 		if (saidx0->reqid != saidx1->reqid)
   4228 			return 0;
   4229 		if (memcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
   4230 		    memcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
   4231 			return 0;
   4232 	} else {
   4233 
   4234 		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
   4235 		if (flag == CMP_MODE_REQID
   4236 		  ||flag == CMP_REQID) {
   4237 			/*
   4238 			 * If reqid of SPD is non-zero, unique SA is required.
   4239 			 * The result must be of same reqid in this case.
   4240 			 */
   4241 			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
   4242 				return 0;
   4243 		}
   4244 
   4245 		if (flag == CMP_MODE_REQID) {
   4246 			if (saidx0->mode != IPSEC_MODE_ANY
   4247 			 && saidx0->mode != saidx1->mode)
   4248 				return 0;
   4249 		}
   4250 
   4251 	/*
   4252 	 * If NAT-T is enabled, check ports for tunnel mode.
   4253 	 * Don't do it for transport mode, as there is no
   4254 	 * port information available in the SP.
   4255          * Also don't check ports if they are set to zero
   4256 	 * in the SPD: This means we have a non-generated
   4257 	 * SPD which can't know UDP ports.
   4258 	 */
   4259 #ifdef IPSEC_NAT_T
   4260 	if (saidx1->mode == IPSEC_MODE_TUNNEL &&
   4261 	    ((((const struct sockaddr *)(&saidx1->src))->sa_family == AF_INET &&
   4262 	      ((const struct sockaddr *)(&saidx1->dst))->sa_family == AF_INET &&
   4263 	      ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
   4264 	      ((const struct sockaddr_in *)(&saidx1->dst))->sin_port) ||
   4265              (((const struct sockaddr *)(&saidx1->src))->sa_family == AF_INET6 &&
   4266 	      ((const struct sockaddr *)(&saidx1->dst))->sa_family == AF_INET6 &&
   4267 	      ((const struct sockaddr_in6 *)(&saidx1->src))->sin6_port &&
   4268 	      ((const struct sockaddr_in6 *)(&saidx1->dst))->sin6_port)))
   4269 		chkport = 1;
   4270 #endif
   4271 
   4272 		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
   4273 			return 0;
   4274 		}
   4275 		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
   4276 			return 0;
   4277 		}
   4278 	}
   4279 
   4280 	return 1;
   4281 }
   4282 
   4283 /*
   4284  * compare two secindex structure exactly.
   4285  * IN:
   4286  *	spidx0: source, it is often in SPD.
   4287  *	spidx1: object, it is often from PFKEY message.
   4288  * OUT:
   4289  *	1 : equal
   4290  *	0 : not equal
   4291  */
   4292 int
   4293 key_cmpspidx_exactly(
   4294 	const struct secpolicyindex *spidx0,
   4295 	const struct secpolicyindex *spidx1)
   4296 {
   4297 	/* sanity */
   4298 	if (spidx0 == NULL && spidx1 == NULL)
   4299 		return 1;
   4300 
   4301 	if (spidx0 == NULL || spidx1 == NULL)
   4302 		return 0;
   4303 
   4304 	if (spidx0->prefs != spidx1->prefs
   4305 	 || spidx0->prefd != spidx1->prefd
   4306 	 || spidx0->ul_proto != spidx1->ul_proto)
   4307 		return 0;
   4308 
   4309 	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
   4310 	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
   4311 }
   4312 
   4313 /*
   4314  * compare two secindex structure with mask.
   4315  * IN:
   4316  *	spidx0: source, it is often in SPD.
   4317  *	spidx1: object, it is often from IP header.
   4318  * OUT:
   4319  *	1 : equal
   4320  *	0 : not equal
   4321  */
   4322 int
   4323 key_cmpspidx_withmask(
   4324 	const struct secpolicyindex *spidx0,
   4325 	const struct secpolicyindex *spidx1)
   4326 {
   4327 	/* sanity */
   4328 	if (spidx0 == NULL && spidx1 == NULL)
   4329 		return 1;
   4330 
   4331 	if (spidx0 == NULL || spidx1 == NULL)
   4332 		return 0;
   4333 
   4334 	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
   4335 	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
   4336 	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
   4337 	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
   4338 		return 0;
   4339 
   4340 	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
   4341 	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
   4342 	 && spidx0->ul_proto != spidx1->ul_proto)
   4343 		return 0;
   4344 
   4345 	switch (spidx0->src.sa.sa_family) {
   4346 	case AF_INET:
   4347 		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
   4348 		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
   4349 			return 0;
   4350 		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
   4351 		    &spidx1->src.sin.sin_addr, spidx0->prefs))
   4352 			return 0;
   4353 		break;
   4354 	case AF_INET6:
   4355 		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
   4356 		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
   4357 			return 0;
   4358 		/*
   4359 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4360 		 * as a wildcard scope, which matches any scope zone ID.
   4361 		 */
   4362 		if (spidx0->src.sin6.sin6_scope_id &&
   4363 		    spidx1->src.sin6.sin6_scope_id &&
   4364 		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
   4365 			return 0;
   4366 		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
   4367 		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
   4368 			return 0;
   4369 		break;
   4370 	default:
   4371 		/* XXX */
   4372 		if (memcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
   4373 			return 0;
   4374 		break;
   4375 	}
   4376 
   4377 	switch (spidx0->dst.sa.sa_family) {
   4378 	case AF_INET:
   4379 		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
   4380 		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
   4381 			return 0;
   4382 		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
   4383 		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
   4384 			return 0;
   4385 		break;
   4386 	case AF_INET6:
   4387 		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
   4388 		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
   4389 			return 0;
   4390 		/*
   4391 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4392 		 * as a wildcard scope, which matches any scope zone ID.
   4393 		 */
   4394 		if (spidx0->src.sin6.sin6_scope_id &&
   4395 		    spidx1->src.sin6.sin6_scope_id &&
   4396 		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
   4397 			return 0;
   4398 		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
   4399 		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
   4400 			return 0;
   4401 		break;
   4402 	default:
   4403 		/* XXX */
   4404 		if (memcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
   4405 			return 0;
   4406 		break;
   4407 	}
   4408 
   4409 	/* XXX Do we check other field ?  e.g. flowinfo */
   4410 
   4411 	return 1;
   4412 }
   4413 
   4414 /* returns 0 on match */
   4415 static int
   4416 key_sockaddrcmp(
   4417 	const struct sockaddr *sa1,
   4418 	const struct sockaddr *sa2,
   4419 	int port)
   4420 {
   4421 #ifdef satosin
   4422 #undef satosin
   4423 #endif
   4424 #define satosin(s) ((const struct sockaddr_in *)s)
   4425 #ifdef satosin6
   4426 #undef satosin6
   4427 #endif
   4428 #define satosin6(s) ((const struct sockaddr_in6 *)s)
   4429 	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
   4430 		return 1;
   4431 
   4432 	switch (sa1->sa_family) {
   4433 	case AF_INET:
   4434 		if (sa1->sa_len != sizeof(struct sockaddr_in))
   4435 			return 1;
   4436 		if (satosin(sa1)->sin_addr.s_addr !=
   4437 		    satosin(sa2)->sin_addr.s_addr) {
   4438 			return 1;
   4439 		}
   4440 		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
   4441 			return 1;
   4442 		break;
   4443 	case AF_INET6:
   4444 		if (sa1->sa_len != sizeof(struct sockaddr_in6))
   4445 			return 1;	/*EINVAL*/
   4446 		if (satosin6(sa1)->sin6_scope_id !=
   4447 		    satosin6(sa2)->sin6_scope_id) {
   4448 			return 1;
   4449 		}
   4450 		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
   4451 		    &satosin6(sa2)->sin6_addr)) {
   4452 			return 1;
   4453 		}
   4454 		if (port &&
   4455 		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
   4456 			return 1;
   4457 		}
   4458 		break;
   4459 	default:
   4460 		if (memcmp(sa1, sa2, sa1->sa_len) != 0)
   4461 			return 1;
   4462 		break;
   4463 	}
   4464 
   4465 	return 0;
   4466 #undef satosin
   4467 #undef satosin6
   4468 }
   4469 
   4470 /*
   4471  * compare two buffers with mask.
   4472  * IN:
   4473  *	addr1: source
   4474  *	addr2: object
   4475  *	bits:  Number of bits to compare
   4476  * OUT:
   4477  *	1 : equal
   4478  *	0 : not equal
   4479  */
   4480 static int
   4481 key_bbcmp(const void *a1, const void *a2, u_int bits)
   4482 {
   4483 	const unsigned char *p1 = a1;
   4484 	const unsigned char *p2 = a2;
   4485 
   4486 	/* XXX: This could be considerably faster if we compare a word
   4487 	 * at a time, but it is complicated on LSB Endian machines */
   4488 
   4489 	/* Handle null pointers */
   4490 	if (p1 == NULL || p2 == NULL)
   4491 		return (p1 == p2);
   4492 
   4493 	while (bits >= 8) {
   4494 		if (*p1++ != *p2++)
   4495 			return 0;
   4496 		bits -= 8;
   4497 	}
   4498 
   4499 	if (bits > 0) {
   4500 		u_int8_t mask = ~((1<<(8-bits))-1);
   4501 		if ((*p1 & mask) != (*p2 & mask))
   4502 			return 0;
   4503 	}
   4504 	return 1;	/* Match! */
   4505 }
   4506 
   4507 /*
   4508  * time handler.
   4509  * scanning SPD and SAD to check status for each entries,
   4510  * and do to remove or to expire.
   4511  */
   4512 void
   4513 key_timehandler(void* arg)
   4514 {
   4515 	u_int dir;
   4516 	int s;
   4517 	time_t now = time_uptime;
   4518 
   4519 	s = splsoftnet();	/*called from softclock()*/
   4520 	mutex_enter(softnet_lock);
   4521 
   4522 	/* SPD */
   4523     {
   4524 	struct secpolicy *sp, *nextsp;
   4525 
   4526 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   4527 		for (sp = LIST_FIRST(&sptree[dir]);
   4528 		     sp != NULL;
   4529 		     sp = nextsp) {
   4530 
   4531 			nextsp = LIST_NEXT(sp, chain);
   4532 
   4533 			if (sp->state == IPSEC_SPSTATE_DEAD) {
   4534 				key_sp_unlink(sp);	/*XXX*/
   4535 
   4536 				/* 'sp' dead; continue transfers to
   4537 				 * 'sp = nextsp'
   4538 				 */
   4539 				continue;
   4540 			}
   4541 
   4542 			if (sp->lifetime == 0 && sp->validtime == 0)
   4543 				continue;
   4544 
   4545 			/* the deletion will occur next time */
   4546 			if ((sp->lifetime && now - sp->created > sp->lifetime)
   4547 			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
   4548 			  	key_sp_dead(sp);
   4549 				key_spdexpire(sp);
   4550 				continue;
   4551 			}
   4552 		}
   4553 	}
   4554     }
   4555 
   4556 	/* SAD */
   4557     {
   4558 	struct secashead *sah, *nextsah;
   4559 	struct secasvar *sav, *nextsav;
   4560 
   4561 	for (sah = LIST_FIRST(&sahtree);
   4562 	     sah != NULL;
   4563 	     sah = nextsah) {
   4564 
   4565 		nextsah = LIST_NEXT(sah, chain);
   4566 
   4567 		/* if sah has been dead, then delete it and process next sah. */
   4568 		if (sah->state == SADB_SASTATE_DEAD) {
   4569 			key_delsah(sah);
   4570 			continue;
   4571 		}
   4572 
   4573 		/* if LARVAL entry doesn't become MATURE, delete it. */
   4574 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
   4575 		     sav != NULL;
   4576 		     sav = nextsav) {
   4577 
   4578 			nextsav = LIST_NEXT(sav, chain);
   4579 
   4580 			if (now - sav->created > key_larval_lifetime) {
   4581 				KEY_FREESAV(&sav);
   4582 			}
   4583 		}
   4584 
   4585 		/*
   4586 		 * check MATURE entry to start to send expire message
   4587 		 * whether or not.
   4588 		 */
   4589 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
   4590 		     sav != NULL;
   4591 		     sav = nextsav) {
   4592 
   4593 			nextsav = LIST_NEXT(sav, chain);
   4594 
   4595 			/* we don't need to check. */
   4596 			if (sav->lft_s == NULL)
   4597 				continue;
   4598 
   4599 			/* sanity check */
   4600 			if (sav->lft_c == NULL) {
   4601 				ipseclog((LOG_DEBUG,"key_timehandler: "
   4602 					"There is no CURRENT time, why?\n"));
   4603 				continue;
   4604 			}
   4605 
   4606 			/* check SOFT lifetime */
   4607 			if (sav->lft_s->sadb_lifetime_addtime != 0
   4608 			 && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4609 				/*
   4610 				 * check SA to be used whether or not.
   4611 				 * when SA hasn't been used, delete it.
   4612 				 */
   4613 				if (sav->lft_c->sadb_lifetime_usetime == 0) {
   4614 					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4615 					KEY_FREESAV(&sav);
   4616 				} else {
   4617 					key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4618 					/*
   4619 					 * XXX If we keep to send expire
   4620 					 * message in the status of
   4621 					 * DYING. Do remove below code.
   4622 					 */
   4623 					key_expire(sav);
   4624 				}
   4625 			}
   4626 			/* check SOFT lifetime by bytes */
   4627 			/*
   4628 			 * XXX I don't know the way to delete this SA
   4629 			 * when new SA is installed.  Caution when it's
   4630 			 * installed too big lifetime by time.
   4631 			 */
   4632 			else if (sav->lft_s->sadb_lifetime_bytes != 0
   4633 			      && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
   4634 
   4635 				key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4636 				/*
   4637 				 * XXX If we keep to send expire
   4638 				 * message in the status of
   4639 				 * DYING. Do remove below code.
   4640 				 */
   4641 				key_expire(sav);
   4642 			}
   4643 		}
   4644 
   4645 		/* check DYING entry to change status to DEAD. */
   4646 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
   4647 		     sav != NULL;
   4648 		     sav = nextsav) {
   4649 
   4650 			nextsav = LIST_NEXT(sav, chain);
   4651 
   4652 			/* we don't need to check. */
   4653 			if (sav->lft_h == NULL)
   4654 				continue;
   4655 
   4656 			/* sanity check */
   4657 			if (sav->lft_c == NULL) {
   4658 				ipseclog((LOG_DEBUG, "key_timehandler: "
   4659 					"There is no CURRENT time, why?\n"));
   4660 				continue;
   4661 			}
   4662 
   4663 			if (sav->lft_h->sadb_lifetime_addtime != 0
   4664 			 && now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
   4665 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4666 				KEY_FREESAV(&sav);
   4667 			}
   4668 #if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
   4669 			else if (sav->lft_s != NULL
   4670 			      && sav->lft_s->sadb_lifetime_addtime != 0
   4671 			      && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4672 				/*
   4673 				 * XXX: should be checked to be
   4674 				 * installed the valid SA.
   4675 				 */
   4676 
   4677 				/*
   4678 				 * If there is no SA then sending
   4679 				 * expire message.
   4680 				 */
   4681 				key_expire(sav);
   4682 			}
   4683 #endif
   4684 			/* check HARD lifetime by bytes */
   4685 			else if (sav->lft_h->sadb_lifetime_bytes != 0
   4686 			      && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
   4687 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4688 				KEY_FREESAV(&sav);
   4689 			}
   4690 		}
   4691 
   4692 		/* delete entry in DEAD */
   4693 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
   4694 		     sav != NULL;
   4695 		     sav = nextsav) {
   4696 
   4697 			nextsav = LIST_NEXT(sav, chain);
   4698 
   4699 			/* sanity check */
   4700 			if (sav->state != SADB_SASTATE_DEAD) {
   4701 				ipseclog((LOG_DEBUG, "key_timehandler: "
   4702 					"invalid sav->state "
   4703 					"(queue: %d SA: %d): "
   4704 					"kill it anyway\n",
   4705 					SADB_SASTATE_DEAD, sav->state));
   4706 			}
   4707 
   4708 			/*
   4709 			 * do not call key_freesav() here.
   4710 			 * sav should already be freed, and sav->refcnt
   4711 			 * shows other references to sav
   4712 			 * (such as from SPD).
   4713 			 */
   4714 		}
   4715 	}
   4716     }
   4717 
   4718 #ifndef IPSEC_NONBLOCK_ACQUIRE
   4719 	/* ACQ tree */
   4720     {
   4721 	struct secacq *acq, *nextacq;
   4722 
   4723 	for (acq = LIST_FIRST(&acqtree);
   4724 	     acq != NULL;
   4725 	     acq = nextacq) {
   4726 
   4727 		nextacq = LIST_NEXT(acq, chain);
   4728 
   4729 		if (now - acq->created > key_blockacq_lifetime
   4730 		 && __LIST_CHAINED(acq)) {
   4731 			LIST_REMOVE(acq, chain);
   4732 			KFREE(acq);
   4733 		}
   4734 	}
   4735     }
   4736 #endif
   4737 
   4738 	/* SP ACQ tree */
   4739     {
   4740 	struct secspacq *acq, *nextacq;
   4741 
   4742 	for (acq = LIST_FIRST(&spacqtree);
   4743 	     acq != NULL;
   4744 	     acq = nextacq) {
   4745 
   4746 		nextacq = LIST_NEXT(acq, chain);
   4747 
   4748 		if (now - acq->created > key_blockacq_lifetime
   4749 		 && __LIST_CHAINED(acq)) {
   4750 			LIST_REMOVE(acq, chain);
   4751 			KFREE(acq);
   4752 		}
   4753 	}
   4754     }
   4755 
   4756 	/* initialize random seed */
   4757 	if (key_tick_init_random++ > key_int_random) {
   4758 		key_tick_init_random = 0;
   4759 		key_srandom();
   4760 	}
   4761 
   4762 #ifndef IPSEC_DEBUG2
   4763 	/* do exchange to tick time !! */
   4764 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   4765 #endif /* IPSEC_DEBUG2 */
   4766 
   4767 	mutex_exit(softnet_lock);
   4768 	splx(s);
   4769 	return;
   4770 }
   4771 
   4772 #ifdef __NetBSD__
   4773 void srandom(int);
   4774 void srandom(int arg) {return;}
   4775 #endif
   4776 
   4777 /*
   4778  * to initialize a seed for random()
   4779  */
   4780 static void
   4781 key_srandom(void)
   4782 {
   4783 	srandom(time_second);
   4784 }
   4785 
   4786 u_long
   4787 key_random(void)
   4788 {
   4789 	u_long value;
   4790 
   4791 	key_randomfill(&value, sizeof(value));
   4792 	return value;
   4793 }
   4794 
   4795 void
   4796 key_randomfill(void *p, size_t l)
   4797 {
   4798 	size_t n;
   4799 	u_long v;
   4800 	static int warn = 1;
   4801 
   4802 	n = 0;
   4803 	n = (size_t)read_random(p, (u_int)l);
   4804 	/* last resort */
   4805 	while (n < l) {
   4806 		v = random();
   4807 		memcpy((u_int8_t *)p + n, &v,
   4808 		    l - n < sizeof(v) ? l - n : sizeof(v));
   4809 		n += sizeof(v);
   4810 
   4811 		if (warn) {
   4812 			printf("WARNING: pseudo-random number generator "
   4813 			    "used for IPsec processing\n");
   4814 			warn = 0;
   4815 		}
   4816 	}
   4817 }
   4818 
   4819 /*
   4820  * map SADB_SATYPE_* to IPPROTO_*.
   4821  * if satype == SADB_SATYPE then satype is mapped to ~0.
   4822  * OUT:
   4823  *	0: invalid satype.
   4824  */
   4825 static u_int16_t
   4826 key_satype2proto(u_int8_t satype)
   4827 {
   4828 	switch (satype) {
   4829 	case SADB_SATYPE_UNSPEC:
   4830 		return IPSEC_PROTO_ANY;
   4831 	case SADB_SATYPE_AH:
   4832 		return IPPROTO_AH;
   4833 	case SADB_SATYPE_ESP:
   4834 		return IPPROTO_ESP;
   4835 	case SADB_X_SATYPE_IPCOMP:
   4836 		return IPPROTO_IPCOMP;
   4837 	case SADB_X_SATYPE_TCPSIGNATURE:
   4838 		return IPPROTO_TCP;
   4839 	default:
   4840 		return 0;
   4841 	}
   4842 	/* NOTREACHED */
   4843 }
   4844 
   4845 /*
   4846  * map IPPROTO_* to SADB_SATYPE_*
   4847  * OUT:
   4848  *	0: invalid protocol type.
   4849  */
   4850 static u_int8_t
   4851 key_proto2satype(u_int16_t proto)
   4852 {
   4853 	switch (proto) {
   4854 	case IPPROTO_AH:
   4855 		return SADB_SATYPE_AH;
   4856 	case IPPROTO_ESP:
   4857 		return SADB_SATYPE_ESP;
   4858 	case IPPROTO_IPCOMP:
   4859 		return SADB_X_SATYPE_IPCOMP;
   4860 	case IPPROTO_TCP:
   4861 		return SADB_X_SATYPE_TCPSIGNATURE;
   4862 	default:
   4863 		return 0;
   4864 	}
   4865 	/* NOTREACHED */
   4866 }
   4867 
   4868 static int
   4869 key_setsecasidx(int proto, int mode, int reqid,
   4870 	        const struct sadb_address * src,
   4871 	 	const struct sadb_address * dst,
   4872 		struct secasindex * saidx)
   4873 {
   4874 	const union sockaddr_union * src_u =
   4875 		(const union sockaddr_union *) src;
   4876 	const union sockaddr_union * dst_u =
   4877 		(const union sockaddr_union *) dst;
   4878 
   4879 	/* sa len safety check */
   4880 	if (key_checksalen(src_u) != 0)
   4881 		return -1;
   4882 	if (key_checksalen(dst_u) != 0)
   4883 		return -1;
   4884 
   4885 	memset(saidx, 0, sizeof(*saidx));
   4886 	saidx->proto = proto;
   4887 	saidx->mode = mode;
   4888 	saidx->reqid = reqid;
   4889 	memcpy(&saidx->src, src_u, src_u->sa.sa_len);
   4890 	memcpy(&saidx->dst, dst_u, dst_u->sa.sa_len);
   4891 
   4892 #ifndef IPSEC_NAT_T
   4893 	key_porttosaddr(&((saidx)->src),0);
   4894 	key_porttosaddr(&((saidx)->dst),0);
   4895 #endif
   4896 	return 0;
   4897 }
   4898 
   4899 /* %%% PF_KEY */
   4900 /*
   4901  * SADB_GETSPI processing is to receive
   4902  *	<base, (SA2), src address, dst address, (SPI range)>
   4903  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
   4904  * tree with the status of LARVAL, and send
   4905  *	<base, SA(*), address(SD)>
   4906  * to the IKMPd.
   4907  *
   4908  * IN:	mhp: pointer to the pointer to each header.
   4909  * OUT:	NULL if fail.
   4910  *	other if success, return pointer to the message to send.
   4911  */
   4912 static int
   4913 key_getspi(struct socket *so, struct mbuf *m,
   4914 	   const struct sadb_msghdr *mhp)
   4915 {
   4916 	struct sadb_address *src0, *dst0;
   4917 	struct secasindex saidx;
   4918 	struct secashead *newsah;
   4919 	struct secasvar *newsav;
   4920 	u_int8_t proto;
   4921 	u_int32_t spi;
   4922 	u_int8_t mode;
   4923 	u_int16_t reqid;
   4924 	int error;
   4925 
   4926 	/* sanity check */
   4927 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   4928 		panic("key_getspi: NULL pointer is passed");
   4929 
   4930 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   4931 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   4932 		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
   4933 		return key_senderror(so, m, EINVAL);
   4934 	}
   4935 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   4936 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   4937 		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
   4938 		return key_senderror(so, m, EINVAL);
   4939 	}
   4940 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   4941 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   4942 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   4943 	} else {
   4944 		mode = IPSEC_MODE_ANY;
   4945 		reqid = 0;
   4946 	}
   4947 
   4948 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   4949 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   4950 
   4951 	/* map satype to proto */
   4952 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   4953 		ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
   4954 		return key_senderror(so, m, EINVAL);
   4955 	}
   4956 
   4957 
   4958 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
   4959 				     dst0 + 1, &saidx)) != 0)
   4960 		return key_senderror(so, m, EINVAL);
   4961 
   4962 #ifdef IPSEC_NAT_T
   4963 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   4964 		return key_senderror(so, m, EINVAL);
   4965 #endif
   4966 
   4967 	/* SPI allocation */
   4968 	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
   4969 	                       &saidx);
   4970 	if (spi == 0)
   4971 		return key_senderror(so, m, EINVAL);
   4972 
   4973 	/* get a SA index */
   4974 	if ((newsah = key_getsah(&saidx)) == NULL) {
   4975 		/* create a new SA index */
   4976 		if ((newsah = key_newsah(&saidx)) == NULL) {
   4977 			ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
   4978 			return key_senderror(so, m, ENOBUFS);
   4979 		}
   4980 	}
   4981 
   4982 	/* get a new SA */
   4983 	/* XXX rewrite */
   4984 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
   4985 	if (newsav == NULL) {
   4986 		/* XXX don't free new SA index allocated in above. */
   4987 		return key_senderror(so, m, error);
   4988 	}
   4989 
   4990 	/* set spi */
   4991 	newsav->spi = htonl(spi);
   4992 
   4993 #ifndef IPSEC_NONBLOCK_ACQUIRE
   4994 	/* delete the entry in acqtree */
   4995 	if (mhp->msg->sadb_msg_seq != 0) {
   4996 		struct secacq *acq;
   4997 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
   4998 			/* reset counter in order to deletion by timehandler. */
   4999 			acq->created = time_uptime;
   5000 			acq->count = 0;
   5001 		}
   5002     	}
   5003 #endif
   5004 
   5005     {
   5006 	struct mbuf *n, *nn;
   5007 	struct sadb_sa *m_sa;
   5008 	struct sadb_msg *newmsg;
   5009 	int off, len;
   5010 
   5011 	/* create new sadb_msg to reply. */
   5012 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
   5013 	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
   5014 	if (len > MCLBYTES)
   5015 		return key_senderror(so, m, ENOBUFS);
   5016 
   5017 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   5018 	if (len > MHLEN) {
   5019 		MCLGET(n, M_DONTWAIT);
   5020 		if ((n->m_flags & M_EXT) == 0) {
   5021 			m_freem(n);
   5022 			n = NULL;
   5023 		}
   5024 	}
   5025 	if (!n)
   5026 		return key_senderror(so, m, ENOBUFS);
   5027 
   5028 	n->m_len = len;
   5029 	n->m_next = NULL;
   5030 	off = 0;
   5031 
   5032 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   5033 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   5034 
   5035 	m_sa = (struct sadb_sa *)(mtod(n, char *) + off);
   5036 	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
   5037 	m_sa->sadb_sa_exttype = SADB_EXT_SA;
   5038 	m_sa->sadb_sa_spi = htonl(spi);
   5039 	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
   5040 
   5041 #ifdef DIAGNOSTIC
   5042 	if (off != len)
   5043 		panic("length inconsistency in key_getspi");
   5044 #endif
   5045 
   5046 	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
   5047 	    SADB_EXT_ADDRESS_DST);
   5048 	if (!n->m_next) {
   5049 		m_freem(n);
   5050 		return key_senderror(so, m, ENOBUFS);
   5051 	}
   5052 
   5053 	if (n->m_len < sizeof(struct sadb_msg)) {
   5054 		n = m_pullup(n, sizeof(struct sadb_msg));
   5055 		if (n == NULL)
   5056 			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   5057 	}
   5058 
   5059 	n->m_pkthdr.len = 0;
   5060 	for (nn = n; nn; nn = nn->m_next)
   5061 		n->m_pkthdr.len += nn->m_len;
   5062 
   5063 	newmsg = mtod(n, struct sadb_msg *);
   5064 	newmsg->sadb_msg_seq = newsav->seq;
   5065 	newmsg->sadb_msg_errno = 0;
   5066 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   5067 
   5068 	m_freem(m);
   5069 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   5070     }
   5071 }
   5072 
   5073 /*
   5074  * allocating new SPI
   5075  * called by key_getspi().
   5076  * OUT:
   5077  *	0:	failure.
   5078  *	others: success.
   5079  */
   5080 static u_int32_t
   5081 key_do_getnewspi(const struct sadb_spirange *spirange,
   5082 		 const struct secasindex *saidx)
   5083 {
   5084 	u_int32_t newspi;
   5085 	u_int32_t spmin, spmax;
   5086 	int count = key_spi_trycnt;
   5087 
   5088 	/* set spi range to allocate */
   5089 	if (spirange != NULL) {
   5090 		spmin = spirange->sadb_spirange_min;
   5091 		spmax = spirange->sadb_spirange_max;
   5092 	} else {
   5093 		spmin = key_spi_minval;
   5094 		spmax = key_spi_maxval;
   5095 	}
   5096 	/* IPCOMP needs 2-byte SPI */
   5097 	if (saidx->proto == IPPROTO_IPCOMP) {
   5098 		u_int32_t t;
   5099 		if (spmin >= 0x10000)
   5100 			spmin = 0xffff;
   5101 		if (spmax >= 0x10000)
   5102 			spmax = 0xffff;
   5103 		if (spmin > spmax) {
   5104 			t = spmin; spmin = spmax; spmax = t;
   5105 		}
   5106 	}
   5107 
   5108 	if (spmin == spmax) {
   5109 		if (key_checkspidup(saidx, htonl(spmin)) != NULL) {
   5110 			ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", spmin));
   5111 			return 0;
   5112 		}
   5113 
   5114 		count--; /* taking one cost. */
   5115 		newspi = spmin;
   5116 
   5117 	} else {
   5118 
   5119 		/* init SPI */
   5120 		newspi = 0;
   5121 
   5122 		/* when requesting to allocate spi ranged */
   5123 		while (count--) {
   5124 			/* generate pseudo-random SPI value ranged. */
   5125 			newspi = spmin + (key_random() % (spmax - spmin + 1));
   5126 
   5127 			if (key_checkspidup(saidx, htonl(newspi)) == NULL)
   5128 				break;
   5129 		}
   5130 
   5131 		if (count == 0 || newspi == 0) {
   5132 			ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
   5133 			return 0;
   5134 		}
   5135 	}
   5136 
   5137 	/* statistics */
   5138 	keystat.getspi_count =
   5139 		(keystat.getspi_count + key_spi_trycnt - count) / 2;
   5140 
   5141 	return newspi;
   5142 }
   5143 
   5144 #ifdef IPSEC_NAT_T
   5145 /* Handle IPSEC_NAT_T info if present */
   5146 static int
   5147 key_handle_natt_info(struct secasvar *sav,
   5148       		     const struct sadb_msghdr *mhp)
   5149 {
   5150 
   5151 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
   5152 		ipseclog((LOG_DEBUG,"update: NAT-T OAi present\n"));
   5153 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
   5154 		ipseclog((LOG_DEBUG,"update: NAT-T OAr present\n"));
   5155 
   5156 	if ((mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL) &&
   5157 	    (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL) &&
   5158 	    (mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL)) {
   5159 		struct sadb_x_nat_t_type *type;
   5160 		struct sadb_x_nat_t_port *sport;
   5161 		struct sadb_x_nat_t_port *dport;
   5162 		struct sadb_address *iaddr, *raddr;
   5163 		struct sadb_x_nat_t_frag *frag;
   5164 
   5165 		if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
   5166 		    (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
   5167 		    (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
   5168 			ipseclog((LOG_DEBUG, "key_update: "
   5169 			    "invalid message.\n"));
   5170 			return -1;
   5171 		}
   5172 
   5173 		if ((mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) &&
   5174 		    (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr))) {
   5175 			ipseclog((LOG_DEBUG, "key_update: invalid message\n"));
   5176 			return -1;
   5177 		}
   5178 
   5179 		if ((mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) &&
   5180 		    (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr))) {
   5181 			ipseclog((LOG_DEBUG, "key_update: invalid message\n"));
   5182 			return -1;
   5183 		}
   5184 
   5185 		if ((mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) &&
   5186 		    (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag))) {
   5187 			ipseclog((LOG_DEBUG, "key_update: invalid message\n"));
   5188 			return -1;
   5189 		}
   5190 
   5191 		type = (struct sadb_x_nat_t_type *)
   5192 		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   5193 		sport = (struct sadb_x_nat_t_port *)
   5194 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   5195 		dport = (struct sadb_x_nat_t_port *)
   5196 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   5197 		iaddr = (struct sadb_address *)
   5198 		    mhp->ext[SADB_X_EXT_NAT_T_OAI];
   5199 		raddr = (struct sadb_address *)
   5200 		    mhp->ext[SADB_X_EXT_NAT_T_OAR];
   5201 		frag = (struct sadb_x_nat_t_frag *)
   5202 		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
   5203 
   5204 		ipseclog((LOG_DEBUG,
   5205 			"key_update: type %d, sport = %d, dport = %d\n",
   5206 			type->sadb_x_nat_t_type_type,
   5207 			sport->sadb_x_nat_t_port_port,
   5208 			dport->sadb_x_nat_t_port_port));
   5209 
   5210 		if (type)
   5211 			sav->natt_type = type->sadb_x_nat_t_type_type;
   5212 		if (sport)
   5213 			key_porttosaddr(&sav->sah->saidx.src,
   5214 			    sport->sadb_x_nat_t_port_port);
   5215 		if (dport)
   5216 			key_porttosaddr(&sav->sah->saidx.dst,
   5217 			    dport->sadb_x_nat_t_port_port);
   5218 		if (frag)
   5219 			sav->esp_frag = frag->sadb_x_nat_t_frag_fraglen;
   5220 		else
   5221 			sav->esp_frag = IP_MAXPACKET;
   5222 	}
   5223 
   5224 	return 0;
   5225 }
   5226 
   5227 /* Just update the IPSEC_NAT_T ports if present */
   5228 static int
   5229 key_set_natt_ports(union sockaddr_union *src, union sockaddr_union *dst,
   5230       		     const struct sadb_msghdr *mhp)
   5231 {
   5232 
   5233 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
   5234 		ipseclog((LOG_DEBUG,"update: NAT-T OAi present\n"));
   5235 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
   5236 		ipseclog((LOG_DEBUG,"update: NAT-T OAr present\n"));
   5237 
   5238 	if ((mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL) &&
   5239 	    (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL) &&
   5240 	    (mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL)) {
   5241 		struct sadb_x_nat_t_type *type;
   5242 		struct sadb_x_nat_t_port *sport;
   5243 		struct sadb_x_nat_t_port *dport;
   5244 
   5245 		if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
   5246 		    (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
   5247 		    (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
   5248 			ipseclog((LOG_DEBUG, "key_update: "
   5249 			    "invalid message.\n"));
   5250 			return -1;
   5251 		}
   5252 
   5253 		sport = (struct sadb_x_nat_t_port *)
   5254 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   5255 		dport = (struct sadb_x_nat_t_port *)
   5256 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   5257 
   5258 		if (sport)
   5259 			key_porttosaddr(src,
   5260 			    sport->sadb_x_nat_t_port_port);
   5261 		if (dport)
   5262 			key_porttosaddr(dst,
   5263 			    dport->sadb_x_nat_t_port_port);
   5264 	}
   5265 
   5266 	return 0;
   5267 }
   5268 #endif
   5269 
   5270 
   5271 /*
   5272  * SADB_UPDATE processing
   5273  * receive
   5274  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5275  *       key(AE), (identity(SD),) (sensitivity)>
   5276  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
   5277  * and send
   5278  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5279  *       (identity(SD),) (sensitivity)>
   5280  * to the ikmpd.
   5281  *
   5282  * m will always be freed.
   5283  */
   5284 static int
   5285 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
   5286 {
   5287 	struct sadb_sa *sa0;
   5288 	struct sadb_address *src0, *dst0;
   5289 	struct secasindex saidx;
   5290 	struct secashead *sah;
   5291 	struct secasvar *sav;
   5292 	u_int16_t proto;
   5293 	u_int8_t mode;
   5294 	u_int16_t reqid;
   5295 	int error;
   5296 
   5297 	/* sanity check */
   5298 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5299 		panic("key_update: NULL pointer is passed");
   5300 
   5301 	/* map satype to proto */
   5302 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5303 		ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
   5304 		return key_senderror(so, m, EINVAL);
   5305 	}
   5306 
   5307 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5308 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5309 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5310 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5311 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5312 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5313 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5314 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5315 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5316 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5317 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5318 		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
   5319 		return key_senderror(so, m, EINVAL);
   5320 	}
   5321 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5322 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5323 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5324 		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
   5325 		return key_senderror(so, m, EINVAL);
   5326 	}
   5327 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5328 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5329 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5330 	} else {
   5331 		mode = IPSEC_MODE_ANY;
   5332 		reqid = 0;
   5333 	}
   5334 	/* XXX boundary checking for other extensions */
   5335 
   5336 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5337 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   5338 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   5339 
   5340 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
   5341 				     dst0 + 1, &saidx)) != 0)
   5342 		return key_senderror(so, m, EINVAL);
   5343 
   5344 #ifdef IPSEC_NAT_T
   5345 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5346 		return key_senderror(so, m, EINVAL);
   5347 #endif
   5348 
   5349 	/* get a SA header */
   5350 	if ((sah = key_getsah(&saidx)) == NULL) {
   5351 		ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
   5352 		return key_senderror(so, m, ENOENT);
   5353 	}
   5354 
   5355 	/* set spidx if there */
   5356 	/* XXX rewrite */
   5357 	error = key_setident(sah, m, mhp);
   5358 	if (error)
   5359 		return key_senderror(so, m, error);
   5360 
   5361 	/* find a SA with sequence number. */
   5362 #ifdef IPSEC_DOSEQCHECK
   5363 	if (mhp->msg->sadb_msg_seq != 0
   5364 	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
   5365 		ipseclog((LOG_DEBUG,
   5366 		    "key_update: no larval SA with sequence %u exists.\n",
   5367 		    mhp->msg->sadb_msg_seq));
   5368 		return key_senderror(so, m, ENOENT);
   5369 	}
   5370 #else
   5371 	if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
   5372 		ipseclog((LOG_DEBUG,
   5373 		    "key_update: no such a SA found (spi:%u)\n",
   5374 		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
   5375 		return key_senderror(so, m, EINVAL);
   5376 	}
   5377 #endif
   5378 
   5379 	/* validity check */
   5380 	if (sav->sah->saidx.proto != proto) {
   5381 		ipseclog((LOG_DEBUG,
   5382 		    "key_update: protocol mismatched (DB=%u param=%u)\n",
   5383 		    sav->sah->saidx.proto, proto));
   5384 		return key_senderror(so, m, EINVAL);
   5385 	}
   5386 #ifdef IPSEC_DOSEQCHECK
   5387 	if (sav->spi != sa0->sadb_sa_spi) {
   5388 		ipseclog((LOG_DEBUG,
   5389 		    "key_update: SPI mismatched (DB:%u param:%u)\n",
   5390 		    (u_int32_t)ntohl(sav->spi),
   5391 		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
   5392 		return key_senderror(so, m, EINVAL);
   5393 	}
   5394 #endif
   5395 	if (sav->pid != mhp->msg->sadb_msg_pid) {
   5396 		ipseclog((LOG_DEBUG,
   5397 		    "key_update: pid mismatched (DB:%u param:%u)\n",
   5398 		    sav->pid, mhp->msg->sadb_msg_pid));
   5399 		return key_senderror(so, m, EINVAL);
   5400 	}
   5401 
   5402 	/* copy sav values */
   5403 	error = key_setsaval(sav, m, mhp);
   5404 	if (error) {
   5405 		KEY_FREESAV(&sav);
   5406 		return key_senderror(so, m, error);
   5407 	}
   5408 
   5409 #ifdef IPSEC_NAT_T
   5410 	if ((error = key_handle_natt_info(sav,mhp)) != 0)
   5411 		return key_senderror(so, m, EINVAL);
   5412 #endif /* IPSEC_NAT_T */
   5413 
   5414 	/* check SA values to be mature. */
   5415 	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
   5416 		KEY_FREESAV(&sav);
   5417 		return key_senderror(so, m, 0);
   5418 	}
   5419 
   5420     {
   5421 	struct mbuf *n;
   5422 
   5423 	/* set msg buf from mhp */
   5424 	n = key_getmsgbuf_x1(m, mhp);
   5425 	if (n == NULL) {
   5426 		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
   5427 		return key_senderror(so, m, ENOBUFS);
   5428 	}
   5429 
   5430 	m_freem(m);
   5431 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5432     }
   5433 }
   5434 
   5435 /*
   5436  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
   5437  * only called by key_update().
   5438  * OUT:
   5439  *	NULL	: not found
   5440  *	others	: found, pointer to a SA.
   5441  */
   5442 #ifdef IPSEC_DOSEQCHECK
   5443 static struct secasvar *
   5444 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
   5445 {
   5446 	struct secasvar *sav;
   5447 	u_int state;
   5448 
   5449 	state = SADB_SASTATE_LARVAL;
   5450 
   5451 	/* search SAD with sequence number ? */
   5452 	LIST_FOREACH(sav, &sah->savtree[state], chain) {
   5453 
   5454 		KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
   5455 
   5456 		if (sav->seq == seq) {
   5457 			SA_ADDREF(sav);
   5458 			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
   5459 				printf("DP key_getsavbyseq cause "
   5460 					"refcnt++:%d SA:%p\n",
   5461 					sav->refcnt, sav));
   5462 			return sav;
   5463 		}
   5464 	}
   5465 
   5466 	return NULL;
   5467 }
   5468 #endif
   5469 
   5470 /*
   5471  * SADB_ADD processing
   5472  * add an entry to SA database, when received
   5473  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5474  *       key(AE), (identity(SD),) (sensitivity)>
   5475  * from the ikmpd,
   5476  * and send
   5477  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5478  *       (identity(SD),) (sensitivity)>
   5479  * to the ikmpd.
   5480  *
   5481  * IGNORE identity and sensitivity messages.
   5482  *
   5483  * m will always be freed.
   5484  */
   5485 static int
   5486 key_add(struct socket *so, struct mbuf *m,
   5487 	const struct sadb_msghdr *mhp)
   5488 {
   5489 	struct sadb_sa *sa0;
   5490 	struct sadb_address *src0, *dst0;
   5491 	struct secasindex saidx;
   5492 	struct secashead *newsah;
   5493 	struct secasvar *newsav;
   5494 	u_int16_t proto;
   5495 	u_int8_t mode;
   5496 	u_int16_t reqid;
   5497 	int error;
   5498 
   5499 	/* sanity check */
   5500 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5501 		panic("key_add: NULL pointer is passed");
   5502 
   5503 	/* map satype to proto */
   5504 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5505 		ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
   5506 		return key_senderror(so, m, EINVAL);
   5507 	}
   5508 
   5509 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5510 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5511 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5512 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5513 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5514 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5515 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5516 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5517 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5518 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5519 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5520 		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
   5521 		return key_senderror(so, m, EINVAL);
   5522 	}
   5523 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5524 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5525 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5526 		/* XXX need more */
   5527 		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
   5528 		return key_senderror(so, m, EINVAL);
   5529 	}
   5530 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5531 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5532 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5533 	} else {
   5534 		mode = IPSEC_MODE_ANY;
   5535 		reqid = 0;
   5536 	}
   5537 
   5538 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5539 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   5540 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   5541 
   5542 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
   5543 				     dst0 + 1, &saidx)) != 0)
   5544 		return key_senderror(so, m, EINVAL);
   5545 
   5546 #ifdef IPSEC_NAT_T
   5547 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5548 		return key_senderror(so, m, EINVAL);
   5549 #endif
   5550 
   5551 	/* get a SA header */
   5552 	if ((newsah = key_getsah(&saidx)) == NULL) {
   5553 		/* create a new SA header */
   5554 		if ((newsah = key_newsah(&saidx)) == NULL) {
   5555 			ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
   5556 			return key_senderror(so, m, ENOBUFS);
   5557 		}
   5558 	}
   5559 
   5560 	/* set spidx if there */
   5561 	/* XXX rewrite */
   5562 	error = key_setident(newsah, m, mhp);
   5563 	if (error) {
   5564 		return key_senderror(so, m, error);
   5565 	}
   5566 
   5567 	/* create new SA entry. */
   5568 	/* We can create new SA only if SPI is differenct. */
   5569 	if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
   5570 		ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
   5571 		return key_senderror(so, m, EEXIST);
   5572 	}
   5573 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
   5574 	if (newsav == NULL) {
   5575 		return key_senderror(so, m, error);
   5576 	}
   5577 
   5578 #ifdef IPSEC_NAT_T
   5579 	if ((error = key_handle_natt_info(newsav, mhp)) != 0)
   5580 		return key_senderror(so, m, EINVAL);
   5581 #endif /* IPSEC_NAT_T */
   5582 
   5583 	/* check SA values to be mature. */
   5584 	if ((error = key_mature(newsav)) != 0) {
   5585 		KEY_FREESAV(&newsav);
   5586 		return key_senderror(so, m, error);
   5587 	}
   5588 
   5589 	/*
   5590 	 * don't call key_freesav() here, as we would like to keep the SA
   5591 	 * in the database on success.
   5592 	 */
   5593 
   5594     {
   5595 	struct mbuf *n;
   5596 
   5597 	/* set msg buf from mhp */
   5598 	n = key_getmsgbuf_x1(m, mhp);
   5599 	if (n == NULL) {
   5600 		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
   5601 		return key_senderror(so, m, ENOBUFS);
   5602 	}
   5603 
   5604 	m_freem(m);
   5605 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5606     }
   5607 }
   5608 
   5609 /* m is retained */
   5610 static int
   5611 key_setident(struct secashead *sah, struct mbuf *m,
   5612 	     const struct sadb_msghdr *mhp)
   5613 {
   5614 	const struct sadb_ident *idsrc, *iddst;
   5615 	int idsrclen, iddstlen;
   5616 
   5617 	/* sanity check */
   5618 	if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5619 		panic("key_setident: NULL pointer is passed");
   5620 
   5621 	/* don't make buffer if not there */
   5622 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
   5623 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5624 		sah->idents = NULL;
   5625 		sah->identd = NULL;
   5626 		return 0;
   5627 	}
   5628 
   5629 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
   5630 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5631 		ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
   5632 		return EINVAL;
   5633 	}
   5634 
   5635 	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
   5636 	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
   5637 	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
   5638 	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
   5639 
   5640 	/* validity check */
   5641 	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
   5642 		ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
   5643 		return EINVAL;
   5644 	}
   5645 
   5646 	switch (idsrc->sadb_ident_type) {
   5647 	case SADB_IDENTTYPE_PREFIX:
   5648 	case SADB_IDENTTYPE_FQDN:
   5649 	case SADB_IDENTTYPE_USERFQDN:
   5650 	default:
   5651 		/* XXX do nothing */
   5652 		sah->idents = NULL;
   5653 		sah->identd = NULL;
   5654 	 	return 0;
   5655 	}
   5656 
   5657 	/* make structure */
   5658 	KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
   5659 	if (sah->idents == NULL) {
   5660 		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
   5661 		return ENOBUFS;
   5662 	}
   5663 	KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
   5664 	if (sah->identd == NULL) {
   5665 		KFREE(sah->idents);
   5666 		sah->idents = NULL;
   5667 		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
   5668 		return ENOBUFS;
   5669 	}
   5670 	memcpy(sah->idents, idsrc, idsrclen);
   5671 	memcpy(sah->identd, iddst, iddstlen);
   5672 
   5673 	return 0;
   5674 }
   5675 
   5676 /*
   5677  * m will not be freed on return.
   5678  * it is caller's responsibility to free the result.
   5679  */
   5680 static struct mbuf *
   5681 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
   5682 {
   5683 	struct mbuf *n;
   5684 
   5685 	/* sanity check */
   5686 	if (m == NULL || mhp == NULL || mhp->msg == NULL)
   5687 		panic("key_getmsgbuf_x1: NULL pointer is passed");
   5688 
   5689 	/* create new sadb_msg to reply. */
   5690 	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
   5691 	    SADB_EXT_SA, SADB_X_EXT_SA2,
   5692 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
   5693 	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
   5694 	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
   5695 	if (!n)
   5696 		return NULL;
   5697 
   5698 	if (n->m_len < sizeof(struct sadb_msg)) {
   5699 		n = m_pullup(n, sizeof(struct sadb_msg));
   5700 		if (n == NULL)
   5701 			return NULL;
   5702 	}
   5703 	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
   5704 	mtod(n, struct sadb_msg *)->sadb_msg_len =
   5705 	    PFKEY_UNIT64(n->m_pkthdr.len);
   5706 
   5707 	return n;
   5708 }
   5709 
   5710 static int key_delete_all (struct socket *, struct mbuf *,
   5711 			   const struct sadb_msghdr *, u_int16_t);
   5712 
   5713 /*
   5714  * SADB_DELETE processing
   5715  * receive
   5716  *   <base, SA(*), address(SD)>
   5717  * from the ikmpd, and set SADB_SASTATE_DEAD,
   5718  * and send,
   5719  *   <base, SA(*), address(SD)>
   5720  * to the ikmpd.
   5721  *
   5722  * m will always be freed.
   5723  */
   5724 static int
   5725 key_delete(struct socket *so, struct mbuf *m,
   5726 	   const struct sadb_msghdr *mhp)
   5727 {
   5728 	struct sadb_sa *sa0;
   5729 	struct sadb_address *src0, *dst0;
   5730 	struct secasindex saidx;
   5731 	struct secashead *sah;
   5732 	struct secasvar *sav = NULL;
   5733 	u_int16_t proto;
   5734 	int error;
   5735 
   5736 	/* sanity check */
   5737 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5738 		panic("key_delete: NULL pointer is passed");
   5739 
   5740 	/* map satype to proto */
   5741 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5742 		ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
   5743 		return key_senderror(so, m, EINVAL);
   5744 	}
   5745 
   5746 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5747 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5748 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
   5749 		return key_senderror(so, m, EINVAL);
   5750 	}
   5751 
   5752 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5753 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5754 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
   5755 		return key_senderror(so, m, EINVAL);
   5756 	}
   5757 
   5758 	if (mhp->ext[SADB_EXT_SA] == NULL) {
   5759 		/*
   5760 		 * Caller wants us to delete all non-LARVAL SAs
   5761 		 * that match the src/dst.  This is used during
   5762 		 * IKE INITIAL-CONTACT.
   5763 		 */
   5764 		ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
   5765 		return key_delete_all(so, m, mhp, proto);
   5766 	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
   5767 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
   5768 		return key_senderror(so, m, EINVAL);
   5769 	}
   5770 
   5771 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5772 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   5773 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   5774 
   5775 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   5776 				     dst0 + 1, &saidx)) != 0)
   5777 		return key_senderror(so, m, EINVAL);
   5778 
   5779 #ifdef IPSEC_NAT_T
   5780 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5781 		return key_senderror(so, m, EINVAL);
   5782 #endif
   5783 
   5784 	/* get a SA header */
   5785 	LIST_FOREACH(sah, &sahtree, chain) {
   5786 		if (sah->state == SADB_SASTATE_DEAD)
   5787 			continue;
   5788 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
   5789 			continue;
   5790 
   5791 		/* get a SA with SPI. */
   5792 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5793 		if (sav)
   5794 			break;
   5795 	}
   5796 	if (sah == NULL) {
   5797 		ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
   5798 		return key_senderror(so, m, ENOENT);
   5799 	}
   5800 
   5801 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5802 	KEY_FREESAV(&sav);
   5803 
   5804     {
   5805 	struct mbuf *n;
   5806 	struct sadb_msg *newmsg;
   5807 
   5808 	/* create new sadb_msg to reply. */
   5809 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
   5810 	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5811 	if (!n)
   5812 		return key_senderror(so, m, ENOBUFS);
   5813 
   5814 	if (n->m_len < sizeof(struct sadb_msg)) {
   5815 		n = m_pullup(n, sizeof(struct sadb_msg));
   5816 		if (n == NULL)
   5817 			return key_senderror(so, m, ENOBUFS);
   5818 	}
   5819 	newmsg = mtod(n, struct sadb_msg *);
   5820 	newmsg->sadb_msg_errno = 0;
   5821 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   5822 
   5823 	m_freem(m);
   5824 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5825     }
   5826 }
   5827 
   5828 /*
   5829  * delete all SAs for src/dst.  Called from key_delete().
   5830  */
   5831 static int
   5832 key_delete_all(struct socket *so, struct mbuf *m,
   5833 	       const struct sadb_msghdr *mhp, u_int16_t proto)
   5834 {
   5835 	struct sadb_address *src0, *dst0;
   5836 	struct secasindex saidx;
   5837 	struct secashead *sah;
   5838 	struct secasvar *sav, *nextsav;
   5839 	u_int stateidx, state;
   5840 	int error;
   5841 
   5842 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   5843 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   5844 
   5845 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   5846 				     dst0 + 1, &saidx)) != 0)
   5847 		return key_senderror(so, m, EINVAL);
   5848 
   5849 #ifdef IPSEC_NAT_T
   5850 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5851 		return key_senderror(so, m, EINVAL);
   5852 #endif
   5853 
   5854 	LIST_FOREACH(sah, &sahtree, chain) {
   5855 		if (sah->state == SADB_SASTATE_DEAD)
   5856 			continue;
   5857 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
   5858 			continue;
   5859 
   5860 		/* Delete all non-LARVAL SAs. */
   5861 		for (stateidx = 0;
   5862 		     stateidx < _ARRAYLEN(saorder_state_alive);
   5863 		     stateidx++) {
   5864 			state = saorder_state_alive[stateidx];
   5865 			if (state == SADB_SASTATE_LARVAL)
   5866 				continue;
   5867 			for (sav = LIST_FIRST(&sah->savtree[state]);
   5868 			     sav != NULL; sav = nextsav) {
   5869 				nextsav = LIST_NEXT(sav, chain);
   5870 				/* sanity check */
   5871 				if (sav->state != state) {
   5872 					ipseclog((LOG_DEBUG, "key_delete_all: "
   5873 					       "invalid sav->state "
   5874 					       "(queue: %d SA: %d)\n",
   5875 					       state, sav->state));
   5876 					continue;
   5877 				}
   5878 
   5879 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5880 				KEY_FREESAV(&sav);
   5881 			}
   5882 		}
   5883 	}
   5884     {
   5885 	struct mbuf *n;
   5886 	struct sadb_msg *newmsg;
   5887 
   5888 	/* create new sadb_msg to reply. */
   5889 	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
   5890 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5891 	if (!n)
   5892 		return key_senderror(so, m, ENOBUFS);
   5893 
   5894 	if (n->m_len < sizeof(struct sadb_msg)) {
   5895 		n = m_pullup(n, sizeof(struct sadb_msg));
   5896 		if (n == NULL)
   5897 			return key_senderror(so, m, ENOBUFS);
   5898 	}
   5899 	newmsg = mtod(n, struct sadb_msg *);
   5900 	newmsg->sadb_msg_errno = 0;
   5901 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   5902 
   5903 	m_freem(m);
   5904 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5905     }
   5906 }
   5907 
   5908 /*
   5909  * SADB_GET processing
   5910  * receive
   5911  *   <base, SA(*), address(SD)>
   5912  * from the ikmpd, and get a SP and a SA to respond,
   5913  * and send,
   5914  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
   5915  *       (identity(SD),) (sensitivity)>
   5916  * to the ikmpd.
   5917  *
   5918  * m will always be freed.
   5919  */
   5920 static int
   5921 key_get(struct socket *so, struct mbuf *m,
   5922      	const struct sadb_msghdr *mhp)
   5923 {
   5924 	struct sadb_sa *sa0;
   5925 	struct sadb_address *src0, *dst0;
   5926 	struct secasindex saidx;
   5927 	struct secashead *sah;
   5928 	struct secasvar *sav = NULL;
   5929 	u_int16_t proto;
   5930 	int error;
   5931 
   5932 	/* sanity check */
   5933 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5934 		panic("key_get: NULL pointer is passed");
   5935 
   5936 	/* map satype to proto */
   5937 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5938 		ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
   5939 		return key_senderror(so, m, EINVAL);
   5940 	}
   5941 
   5942 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5943 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5944 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5945 		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
   5946 		return key_senderror(so, m, EINVAL);
   5947 	}
   5948 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5949 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5950 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5951 		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
   5952 		return key_senderror(so, m, EINVAL);
   5953 	}
   5954 
   5955 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5956 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   5957 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   5958 
   5959 
   5960 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   5961 				     dst0 + 1, &saidx)) != 0)
   5962 		return key_senderror(so, m, EINVAL);
   5963 
   5964 #ifdef IPSEC_NAT_T
   5965 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5966 		return key_senderror(so, m, EINVAL);
   5967 #endif
   5968 
   5969 	/* get a SA header */
   5970 	LIST_FOREACH(sah, &sahtree, chain) {
   5971 		if (sah->state == SADB_SASTATE_DEAD)
   5972 			continue;
   5973 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
   5974 			continue;
   5975 
   5976 		/* get a SA with SPI. */
   5977 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5978 		if (sav)
   5979 			break;
   5980 	}
   5981 	if (sah == NULL) {
   5982 		ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
   5983 		return key_senderror(so, m, ENOENT);
   5984 	}
   5985 
   5986     {
   5987 	struct mbuf *n;
   5988 	u_int8_t satype;
   5989 
   5990 	/* map proto to satype */
   5991 	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
   5992 		ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
   5993 		return key_senderror(so, m, EINVAL);
   5994 	}
   5995 
   5996 	/* create new sadb_msg to reply. */
   5997 	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
   5998 	    mhp->msg->sadb_msg_pid);
   5999 	if (!n)
   6000 		return key_senderror(so, m, ENOBUFS);
   6001 
   6002 	m_freem(m);
   6003 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   6004     }
   6005 }
   6006 
   6007 /* XXX make it sysctl-configurable? */
   6008 static void
   6009 key_getcomb_setlifetime(struct sadb_comb *comb)
   6010 {
   6011 
   6012 	comb->sadb_comb_soft_allocations = 1;
   6013 	comb->sadb_comb_hard_allocations = 1;
   6014 	comb->sadb_comb_soft_bytes = 0;
   6015 	comb->sadb_comb_hard_bytes = 0;
   6016 	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
   6017 	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
   6018 	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
   6019 	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
   6020 }
   6021 
   6022 /*
   6023  * XXX reorder combinations by preference
   6024  * XXX no idea if the user wants ESP authentication or not
   6025  */
   6026 static struct mbuf *
   6027 key_getcomb_esp(void)
   6028 {
   6029 	struct sadb_comb *comb;
   6030 	const struct enc_xform *algo;
   6031 	struct mbuf *result = NULL, *m, *n;
   6032 	int encmin;
   6033 	int i, off, o;
   6034 	int totlen;
   6035 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6036 
   6037 	m = NULL;
   6038 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   6039 		algo = esp_algorithm_lookup(i);
   6040 		if (algo == NULL)
   6041 			continue;
   6042 
   6043 		/* discard algorithms with key size smaller than system min */
   6044 		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
   6045 			continue;
   6046 		if (_BITS(algo->minkey) < ipsec_esp_keymin)
   6047 			encmin = ipsec_esp_keymin;
   6048 		else
   6049 			encmin = _BITS(algo->minkey);
   6050 
   6051 		if (ipsec_esp_auth)
   6052 			m = key_getcomb_ah();
   6053 		else {
   6054 			IPSEC_ASSERT(l <= MLEN,
   6055 				("key_getcomb_esp: l=%u > MLEN=%lu",
   6056 				l, (u_long) MLEN));
   6057 			MGET(m, M_DONTWAIT, MT_DATA);
   6058 			if (m) {
   6059 				M_ALIGN(m, l);
   6060 				m->m_len = l;
   6061 				m->m_next = NULL;
   6062 				memset(mtod(m, void *), 0, m->m_len);
   6063 			}
   6064 		}
   6065 		if (!m)
   6066 			goto fail;
   6067 
   6068 		totlen = 0;
   6069 		for (n = m; n; n = n->m_next)
   6070 			totlen += n->m_len;
   6071 		IPSEC_ASSERT((totlen % l) == 0,
   6072 			("key_getcomb_esp: totlen=%u, l=%u", totlen, l));
   6073 
   6074 		for (off = 0; off < totlen; off += l) {
   6075 			n = m_pulldown(m, off, l, &o);
   6076 			if (!n) {
   6077 				/* m is already freed */
   6078 				goto fail;
   6079 			}
   6080 			comb = (struct sadb_comb *)(mtod(n, char *) + o);
   6081 			memset(comb, 0, sizeof(*comb));
   6082 			key_getcomb_setlifetime(comb);
   6083 			comb->sadb_comb_encrypt = i;
   6084 			comb->sadb_comb_encrypt_minbits = encmin;
   6085 			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
   6086 		}
   6087 
   6088 		if (!result)
   6089 			result = m;
   6090 		else
   6091 			m_cat(result, m);
   6092 	}
   6093 
   6094 	return result;
   6095 
   6096  fail:
   6097 	if (result)
   6098 		m_freem(result);
   6099 	return NULL;
   6100 }
   6101 
   6102 static void
   6103 key_getsizes_ah(const struct auth_hash *ah, int alg,
   6104 	        u_int16_t* ksmin, u_int16_t* ksmax)
   6105 {
   6106 	*ksmin = *ksmax = ah->keysize;
   6107 	if (ah->keysize == 0) {
   6108 		/*
   6109 		 * Transform takes arbitrary key size but algorithm
   6110 		 * key size is restricted.  Enforce this here.
   6111 		 */
   6112 		switch (alg) {
   6113 		case SADB_X_AALG_MD5:	*ksmin = *ksmax = 16; break;
   6114 		case SADB_X_AALG_SHA:	*ksmin = *ksmax = 20; break;
   6115 		case SADB_X_AALG_NULL:	*ksmin = 1; *ksmax = 256; break;
   6116 		default:
   6117 			DPRINTF(("key_getsizes_ah: unknown AH algorithm %u\n",
   6118 				alg));
   6119 			break;
   6120 		}
   6121 	}
   6122 }
   6123 
   6124 /*
   6125  * XXX reorder combinations by preference
   6126  */
   6127 static struct mbuf *
   6128 key_getcomb_ah(void)
   6129 {
   6130 	struct sadb_comb *comb;
   6131 	const struct auth_hash *algo;
   6132 	struct mbuf *m;
   6133 	u_int16_t minkeysize, maxkeysize;
   6134 	int i;
   6135 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6136 
   6137 	m = NULL;
   6138 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   6139 #if 1
   6140 		/* we prefer HMAC algorithms, not old algorithms */
   6141 		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
   6142 			continue;
   6143 #endif
   6144 		algo = ah_algorithm_lookup(i);
   6145 		if (!algo)
   6146 			continue;
   6147 		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
   6148 		/* discard algorithms with key size smaller than system min */
   6149 		if (_BITS(minkeysize) < ipsec_ah_keymin)
   6150 			continue;
   6151 
   6152 		if (!m) {
   6153 			IPSEC_ASSERT(l <= MLEN,
   6154 				("key_getcomb_ah: l=%u > MLEN=%lu",
   6155 				l, (u_long) MLEN));
   6156 			MGET(m, M_DONTWAIT, MT_DATA);
   6157 			if (m) {
   6158 				M_ALIGN(m, l);
   6159 				m->m_len = l;
   6160 				m->m_next = NULL;
   6161 			}
   6162 		} else
   6163 			M_PREPEND(m, l, M_DONTWAIT);
   6164 		if (!m)
   6165 			return NULL;
   6166 
   6167 		comb = mtod(m, struct sadb_comb *);
   6168 		memset(comb, 0, sizeof(*comb));
   6169 		key_getcomb_setlifetime(comb);
   6170 		comb->sadb_comb_auth = i;
   6171 		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
   6172 		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
   6173 	}
   6174 
   6175 	return m;
   6176 }
   6177 
   6178 /*
   6179  * not really an official behavior.  discussed in pf_key (at) inner.net in Sep2000.
   6180  * XXX reorder combinations by preference
   6181  */
   6182 static struct mbuf *
   6183 key_getcomb_ipcomp(void)
   6184 {
   6185 	struct sadb_comb *comb;
   6186 	const struct comp_algo *algo;
   6187 	struct mbuf *m;
   6188 	int i;
   6189 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6190 
   6191 	m = NULL;
   6192 	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
   6193 		algo = ipcomp_algorithm_lookup(i);
   6194 		if (!algo)
   6195 			continue;
   6196 
   6197 		if (!m) {
   6198 			IPSEC_ASSERT(l <= MLEN,
   6199 				("key_getcomb_ipcomp: l=%u > MLEN=%lu",
   6200 				l, (u_long) MLEN));
   6201 			MGET(m, M_DONTWAIT, MT_DATA);
   6202 			if (m) {
   6203 				M_ALIGN(m, l);
   6204 				m->m_len = l;
   6205 				m->m_next = NULL;
   6206 			}
   6207 		} else
   6208 			M_PREPEND(m, l, M_DONTWAIT);
   6209 		if (!m)
   6210 			return NULL;
   6211 
   6212 		comb = mtod(m, struct sadb_comb *);
   6213 		memset(comb, 0, sizeof(*comb));
   6214 		key_getcomb_setlifetime(comb);
   6215 		comb->sadb_comb_encrypt = i;
   6216 		/* what should we set into sadb_comb_*_{min,max}bits? */
   6217 	}
   6218 
   6219 	return m;
   6220 }
   6221 
   6222 /*
   6223  * XXX no way to pass mode (transport/tunnel) to userland
   6224  * XXX replay checking?
   6225  * XXX sysctl interface to ipsec_{ah,esp}_keymin
   6226  */
   6227 static struct mbuf *
   6228 key_getprop(const struct secasindex *saidx)
   6229 {
   6230 	struct sadb_prop *prop;
   6231 	struct mbuf *m, *n;
   6232 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
   6233 	int totlen;
   6234 
   6235 	switch (saidx->proto)  {
   6236 	case IPPROTO_ESP:
   6237 		m = key_getcomb_esp();
   6238 		break;
   6239 	case IPPROTO_AH:
   6240 		m = key_getcomb_ah();
   6241 		break;
   6242 	case IPPROTO_IPCOMP:
   6243 		m = key_getcomb_ipcomp();
   6244 		break;
   6245 	default:
   6246 		return NULL;
   6247 	}
   6248 
   6249 	if (!m)
   6250 		return NULL;
   6251 	M_PREPEND(m, l, M_DONTWAIT);
   6252 	if (!m)
   6253 		return NULL;
   6254 
   6255 	totlen = 0;
   6256 	for (n = m; n; n = n->m_next)
   6257 		totlen += n->m_len;
   6258 
   6259 	prop = mtod(m, struct sadb_prop *);
   6260 	memset(prop, 0, sizeof(*prop));
   6261 	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
   6262 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
   6263 	prop->sadb_prop_replay = 32;	/* XXX */
   6264 
   6265 	return m;
   6266 }
   6267 
   6268 /*
   6269  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
   6270  * send
   6271  *   <base, SA, address(SD), (address(P)), x_policy,
   6272  *       (identity(SD),) (sensitivity,) proposal>
   6273  * to KMD, and expect to receive
   6274  *   <base> with SADB_ACQUIRE if error occurred,
   6275  * or
   6276  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
   6277  * from KMD by PF_KEY.
   6278  *
   6279  * XXX x_policy is outside of RFC2367 (KAME extension).
   6280  * XXX sensitivity is not supported.
   6281  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
   6282  * see comment for key_getcomb_ipcomp().
   6283  *
   6284  * OUT:
   6285  *    0     : succeed
   6286  *    others: error number
   6287  */
   6288 static int
   6289 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
   6290 {
   6291 	struct mbuf *result = NULL, *m;
   6292 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6293 	struct secacq *newacq;
   6294 #endif
   6295 	u_int8_t satype;
   6296 	int error = -1;
   6297 	u_int32_t seq;
   6298 
   6299 	/* sanity check */
   6300 	IPSEC_ASSERT(saidx != NULL, ("key_acquire: null saidx"));
   6301 	satype = key_proto2satype(saidx->proto);
   6302 	IPSEC_ASSERT(satype != 0,
   6303 		("key_acquire: null satype, protocol %u", saidx->proto));
   6304 
   6305 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6306 	/*
   6307 	 * We never do anything about acquirng SA.  There is anather
   6308 	 * solution that kernel blocks to send SADB_ACQUIRE message until
   6309 	 * getting something message from IKEd.  In later case, to be
   6310 	 * managed with ACQUIRING list.
   6311 	 */
   6312 	/* Get an entry to check whether sending message or not. */
   6313 	if ((newacq = key_getacq(saidx)) != NULL) {
   6314 		if (key_blockacq_count < newacq->count) {
   6315 			/* reset counter and do send message. */
   6316 			newacq->count = 0;
   6317 		} else {
   6318 			/* increment counter and do nothing. */
   6319 			newacq->count++;
   6320 			return 0;
   6321 		}
   6322 	} else {
   6323 		/* make new entry for blocking to send SADB_ACQUIRE. */
   6324 		if ((newacq = key_newacq(saidx)) == NULL)
   6325 			return ENOBUFS;
   6326 
   6327 		/* add to acqtree */
   6328 		LIST_INSERT_HEAD(&acqtree, newacq, chain);
   6329 	}
   6330 #endif
   6331 
   6332 
   6333 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6334 	seq = newacq->seq;
   6335 #else
   6336 	seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
   6337 #endif
   6338 	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
   6339 	if (!m) {
   6340 		error = ENOBUFS;
   6341 		goto fail;
   6342 	}
   6343 	result = m;
   6344 
   6345 	/* set sadb_address for saidx's. */
   6346 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   6347 	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
   6348 	if (!m) {
   6349 		error = ENOBUFS;
   6350 		goto fail;
   6351 	}
   6352 	m_cat(result, m);
   6353 
   6354 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   6355 	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
   6356 	if (!m) {
   6357 		error = ENOBUFS;
   6358 		goto fail;
   6359 	}
   6360 	m_cat(result, m);
   6361 
   6362 	/* XXX proxy address (optional) */
   6363 
   6364 	/* set sadb_x_policy */
   6365 	if (sp) {
   6366 		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
   6367 		if (!m) {
   6368 			error = ENOBUFS;
   6369 			goto fail;
   6370 		}
   6371 		m_cat(result, m);
   6372 	}
   6373 
   6374 	/* XXX identity (optional) */
   6375 #if 0
   6376 	if (idexttype && fqdn) {
   6377 		/* create identity extension (FQDN) */
   6378 		struct sadb_ident *id;
   6379 		int fqdnlen;
   6380 
   6381 		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
   6382 		id = (struct sadb_ident *)p;
   6383 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6384 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6385 		id->sadb_ident_exttype = idexttype;
   6386 		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
   6387 		memcpy(id + 1, fqdn, fqdnlen);
   6388 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
   6389 	}
   6390 
   6391 	if (idexttype) {
   6392 		/* create identity extension (USERFQDN) */
   6393 		struct sadb_ident *id;
   6394 		int userfqdnlen;
   6395 
   6396 		if (userfqdn) {
   6397 			/* +1 for terminating-NUL */
   6398 			userfqdnlen = strlen(userfqdn) + 1;
   6399 		} else
   6400 			userfqdnlen = 0;
   6401 		id = (struct sadb_ident *)p;
   6402 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6403 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6404 		id->sadb_ident_exttype = idexttype;
   6405 		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
   6406 		/* XXX is it correct? */
   6407 		if (curlwp)
   6408 			id->sadb_ident_id = kauth_cred_getuid(curlwp->l_cred);
   6409 		if (userfqdn && userfqdnlen)
   6410 			memcpy(id + 1, userfqdn, userfqdnlen);
   6411 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
   6412 	}
   6413 #endif
   6414 
   6415 	/* XXX sensitivity (optional) */
   6416 
   6417 	/* create proposal/combination extension */
   6418 	m = key_getprop(saidx);
   6419 #if 0
   6420 	/*
   6421 	 * spec conformant: always attach proposal/combination extension,
   6422 	 * the problem is that we have no way to attach it for ipcomp,
   6423 	 * due to the way sadb_comb is declared in RFC2367.
   6424 	 */
   6425 	if (!m) {
   6426 		error = ENOBUFS;
   6427 		goto fail;
   6428 	}
   6429 	m_cat(result, m);
   6430 #else
   6431 	/*
   6432 	 * outside of spec; make proposal/combination extension optional.
   6433 	 */
   6434 	if (m)
   6435 		m_cat(result, m);
   6436 #endif
   6437 
   6438 	if ((result->m_flags & M_PKTHDR) == 0) {
   6439 		error = EINVAL;
   6440 		goto fail;
   6441 	}
   6442 
   6443 	if (result->m_len < sizeof(struct sadb_msg)) {
   6444 		result = m_pullup(result, sizeof(struct sadb_msg));
   6445 		if (result == NULL) {
   6446 			error = ENOBUFS;
   6447 			goto fail;
   6448 		}
   6449 	}
   6450 
   6451 	result->m_pkthdr.len = 0;
   6452 	for (m = result; m; m = m->m_next)
   6453 		result->m_pkthdr.len += m->m_len;
   6454 
   6455 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6456 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6457 
   6458 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   6459 
   6460  fail:
   6461 	if (result)
   6462 		m_freem(result);
   6463 	return error;
   6464 }
   6465 
   6466 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6467 static struct secacq *
   6468 key_newacq(const struct secasindex *saidx)
   6469 {
   6470 	struct secacq *newacq;
   6471 
   6472 	/* get new entry */
   6473 	KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
   6474 	if (newacq == NULL) {
   6475 		ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
   6476 		return NULL;
   6477 	}
   6478 	memset(newacq, 0, sizeof(*newacq));
   6479 
   6480 	/* copy secindex */
   6481 	memcpy(&newacq->saidx, saidx, sizeof(newacq->saidx));
   6482 	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
   6483 	newacq->created = time_uptime;
   6484 	newacq->count = 0;
   6485 
   6486 	return newacq;
   6487 }
   6488 
   6489 static struct secacq *
   6490 key_getacq(const struct secasindex *saidx)
   6491 {
   6492 	struct secacq *acq;
   6493 
   6494 	LIST_FOREACH(acq, &acqtree, chain) {
   6495 		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
   6496 			return acq;
   6497 	}
   6498 
   6499 	return NULL;
   6500 }
   6501 
   6502 static struct secacq *
   6503 key_getacqbyseq(u_int32_t seq)
   6504 {
   6505 	struct secacq *acq;
   6506 
   6507 	LIST_FOREACH(acq, &acqtree, chain) {
   6508 		if (acq->seq == seq)
   6509 			return acq;
   6510 	}
   6511 
   6512 	return NULL;
   6513 }
   6514 #endif
   6515 
   6516 static struct secspacq *
   6517 key_newspacq(const struct secpolicyindex *spidx)
   6518 {
   6519 	struct secspacq *acq;
   6520 
   6521 	/* get new entry */
   6522 	KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
   6523 	if (acq == NULL) {
   6524 		ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
   6525 		return NULL;
   6526 	}
   6527 	memset(acq, 0, sizeof(*acq));
   6528 
   6529 	/* copy secindex */
   6530 	memcpy(&acq->spidx, spidx, sizeof(acq->spidx));
   6531 	acq->created = time_uptime;
   6532 	acq->count = 0;
   6533 
   6534 	return acq;
   6535 }
   6536 
   6537 static struct secspacq *
   6538 key_getspacq(const struct secpolicyindex *spidx)
   6539 {
   6540 	struct secspacq *acq;
   6541 
   6542 	LIST_FOREACH(acq, &spacqtree, chain) {
   6543 		if (key_cmpspidx_exactly(spidx, &acq->spidx))
   6544 			return acq;
   6545 	}
   6546 
   6547 	return NULL;
   6548 }
   6549 
   6550 /*
   6551  * SADB_ACQUIRE processing,
   6552  * in first situation, is receiving
   6553  *   <base>
   6554  * from the ikmpd, and clear sequence of its secasvar entry.
   6555  *
   6556  * In second situation, is receiving
   6557  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6558  * from a user land process, and return
   6559  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6560  * to the socket.
   6561  *
   6562  * m will always be freed.
   6563  */
   6564 static int
   6565 key_acquire2(struct socket *so, struct mbuf *m,
   6566       	     const struct sadb_msghdr *mhp)
   6567 {
   6568 	const struct sadb_address *src0, *dst0;
   6569 	struct secasindex saidx;
   6570 	struct secashead *sah;
   6571 	u_int16_t proto;
   6572 	int error;
   6573 
   6574 	/* sanity check */
   6575 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   6576 		panic("key_acquire2: NULL pointer is passed");
   6577 
   6578 	/*
   6579 	 * Error message from KMd.
   6580 	 * We assume that if error was occurred in IKEd, the length of PFKEY
   6581 	 * message is equal to the size of sadb_msg structure.
   6582 	 * We do not raise error even if error occurred in this function.
   6583 	 */
   6584 	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
   6585 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6586 		struct secacq *acq;
   6587 
   6588 		/* check sequence number */
   6589 		if (mhp->msg->sadb_msg_seq == 0) {
   6590 			ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
   6591 			m_freem(m);
   6592 			return 0;
   6593 		}
   6594 
   6595 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
   6596 			/*
   6597 			 * the specified larval SA is already gone, or we got
   6598 			 * a bogus sequence number.  we can silently ignore it.
   6599 			 */
   6600 			m_freem(m);
   6601 			return 0;
   6602 		}
   6603 
   6604 		/* reset acq counter in order to deletion by timehander. */
   6605 		acq->created = time_uptime;
   6606 		acq->count = 0;
   6607 #endif
   6608 		m_freem(m);
   6609 		return 0;
   6610 	}
   6611 
   6612 	/*
   6613 	 * This message is from user land.
   6614 	 */
   6615 
   6616 	/* map satype to proto */
   6617 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   6618 		ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
   6619 		return key_senderror(so, m, EINVAL);
   6620 	}
   6621 
   6622 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   6623 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   6624 	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
   6625 		/* error */
   6626 		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
   6627 		return key_senderror(so, m, EINVAL);
   6628 	}
   6629 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   6630 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   6631 	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
   6632 		/* error */
   6633 		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
   6634 		return key_senderror(so, m, EINVAL);
   6635 	}
   6636 
   6637 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   6638 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   6639 
   6640 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   6641 				     dst0 + 1, &saidx)) != 0)
   6642 		return key_senderror(so, m, EINVAL);
   6643 
   6644 #ifdef IPSEC_NAT_T
   6645 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   6646 		return key_senderror(so, m, EINVAL);
   6647 #endif
   6648 
   6649 	/* get a SA index */
   6650 	LIST_FOREACH(sah, &sahtree, chain) {
   6651 		if (sah->state == SADB_SASTATE_DEAD)
   6652 			continue;
   6653 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
   6654 			break;
   6655 	}
   6656 	if (sah != NULL) {
   6657 		ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
   6658 		return key_senderror(so, m, EEXIST);
   6659 	}
   6660 
   6661 	error = key_acquire(&saidx, NULL);
   6662 	if (error != 0) {
   6663 		ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
   6664 			"from key_acquire.\n", mhp->msg->sadb_msg_errno));
   6665 		return key_senderror(so, m, error);
   6666 	}
   6667 
   6668 	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
   6669 }
   6670 
   6671 /*
   6672  * SADB_REGISTER processing.
   6673  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
   6674  * receive
   6675  *   <base>
   6676  * from the ikmpd, and register a socket to send PF_KEY messages,
   6677  * and send
   6678  *   <base, supported>
   6679  * to KMD by PF_KEY.
   6680  * If socket is detached, must free from regnode.
   6681  *
   6682  * m will always be freed.
   6683  */
   6684 static int
   6685 key_register(struct socket *so, struct mbuf *m,
   6686 	     const struct sadb_msghdr *mhp)
   6687 {
   6688 	struct secreg *reg, *newreg = 0;
   6689 
   6690 	/* sanity check */
   6691 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   6692 		panic("key_register: NULL pointer is passed");
   6693 
   6694 	/* check for invalid register message */
   6695 	if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
   6696 		return key_senderror(so, m, EINVAL);
   6697 
   6698 	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
   6699 	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
   6700 		goto setmsg;
   6701 
   6702 	/* check whether existing or not */
   6703 	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
   6704 		if (reg->so == so) {
   6705 			ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
   6706 			return key_senderror(so, m, EEXIST);
   6707 		}
   6708 	}
   6709 
   6710 	/* create regnode */
   6711 	KMALLOC(newreg, struct secreg *, sizeof(*newreg));
   6712 	if (newreg == NULL) {
   6713 		ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
   6714 		return key_senderror(so, m, ENOBUFS);
   6715 	}
   6716 	memset(newreg, 0, sizeof(*newreg));
   6717 
   6718 	newreg->so = so;
   6719 	((struct keycb *)sotorawcb(so))->kp_registered++;
   6720 
   6721 	/* add regnode to regtree. */
   6722 	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
   6723 
   6724   setmsg:
   6725     {
   6726 	struct mbuf *n;
   6727 	struct sadb_msg *newmsg;
   6728 	struct sadb_supported *sup;
   6729 	u_int len, alen, elen;
   6730 	int off;
   6731 	int i;
   6732 	struct sadb_alg *alg;
   6733 
   6734 	/* create new sadb_msg to reply. */
   6735 	alen = 0;
   6736 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   6737 		if (ah_algorithm_lookup(i))
   6738 			alen += sizeof(struct sadb_alg);
   6739 	}
   6740 	if (alen)
   6741 		alen += sizeof(struct sadb_supported);
   6742 	elen = 0;
   6743 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   6744 		if (esp_algorithm_lookup(i))
   6745 			elen += sizeof(struct sadb_alg);
   6746 	}
   6747 	if (elen)
   6748 		elen += sizeof(struct sadb_supported);
   6749 
   6750 	len = sizeof(struct sadb_msg) + alen + elen;
   6751 
   6752 	if (len > MCLBYTES)
   6753 		return key_senderror(so, m, ENOBUFS);
   6754 
   6755 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   6756 	if (len > MHLEN) {
   6757 		MCLGET(n, M_DONTWAIT);
   6758 		if ((n->m_flags & M_EXT) == 0) {
   6759 			m_freem(n);
   6760 			n = NULL;
   6761 		}
   6762 	}
   6763 	if (!n)
   6764 		return key_senderror(so, m, ENOBUFS);
   6765 
   6766 	n->m_pkthdr.len = n->m_len = len;
   6767 	n->m_next = NULL;
   6768 	off = 0;
   6769 
   6770 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   6771 	newmsg = mtod(n, struct sadb_msg *);
   6772 	newmsg->sadb_msg_errno = 0;
   6773 	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
   6774 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   6775 
   6776 	/* for authentication algorithm */
   6777 	if (alen) {
   6778 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6779 		sup->sadb_supported_len = PFKEY_UNIT64(alen);
   6780 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
   6781 		off += PFKEY_ALIGN8(sizeof(*sup));
   6782 
   6783 		for (i = 1; i <= SADB_AALG_MAX; i++) {
   6784 			const struct auth_hash *aalgo;
   6785 			u_int16_t minkeysize, maxkeysize;
   6786 
   6787 			aalgo = ah_algorithm_lookup(i);
   6788 			if (!aalgo)
   6789 				continue;
   6790 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6791 			alg->sadb_alg_id = i;
   6792 			alg->sadb_alg_ivlen = 0;
   6793 			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
   6794 			alg->sadb_alg_minbits = _BITS(minkeysize);
   6795 			alg->sadb_alg_maxbits = _BITS(maxkeysize);
   6796 			off += PFKEY_ALIGN8(sizeof(*alg));
   6797 		}
   6798 	}
   6799 
   6800 	/* for encryption algorithm */
   6801 	if (elen) {
   6802 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6803 		sup->sadb_supported_len = PFKEY_UNIT64(elen);
   6804 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
   6805 		off += PFKEY_ALIGN8(sizeof(*sup));
   6806 
   6807 		for (i = 1; i <= SADB_EALG_MAX; i++) {
   6808 			const struct enc_xform *ealgo;
   6809 
   6810 			ealgo = esp_algorithm_lookup(i);
   6811 			if (!ealgo)
   6812 				continue;
   6813 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6814 			alg->sadb_alg_id = i;
   6815 			alg->sadb_alg_ivlen = ealgo->blocksize;
   6816 			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
   6817 			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
   6818 			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
   6819 		}
   6820 	}
   6821 
   6822 #ifdef DIAGNOSTIC
   6823 	if (off != len)
   6824 		panic("length assumption failed in key_register");
   6825 #endif
   6826 
   6827 	m_freem(m);
   6828 	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
   6829     }
   6830 }
   6831 
   6832 /*
   6833  * free secreg entry registered.
   6834  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
   6835  */
   6836 void
   6837 key_freereg(struct socket *so)
   6838 {
   6839 	struct secreg *reg;
   6840 	int i;
   6841 
   6842 	/* sanity check */
   6843 	if (so == NULL)
   6844 		panic("key_freereg: NULL pointer is passed");
   6845 
   6846 	/*
   6847 	 * check whether existing or not.
   6848 	 * check all type of SA, because there is a potential that
   6849 	 * one socket is registered to multiple type of SA.
   6850 	 */
   6851 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   6852 		LIST_FOREACH(reg, &regtree[i], chain) {
   6853 			if (reg->so == so
   6854 			 && __LIST_CHAINED(reg)) {
   6855 				LIST_REMOVE(reg, chain);
   6856 				KFREE(reg);
   6857 				break;
   6858 			}
   6859 		}
   6860 	}
   6861 
   6862 	return;
   6863 }
   6864 
   6865 /*
   6866  * SADB_EXPIRE processing
   6867  * send
   6868  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
   6869  * to KMD by PF_KEY.
   6870  * NOTE: We send only soft lifetime extension.
   6871  *
   6872  * OUT:	0	: succeed
   6873  *	others	: error number
   6874  */
   6875 static int
   6876 key_expire(struct secasvar *sav)
   6877 {
   6878 	int s;
   6879 	int satype;
   6880 	struct mbuf *result = NULL, *m;
   6881 	int len;
   6882 	int error = -1;
   6883 	struct sadb_lifetime *lt;
   6884 
   6885 	/* XXX: Why do we lock ? */
   6886 	s = splsoftnet();	/*called from softclock()*/
   6887 
   6888 	/* sanity check */
   6889 	if (sav == NULL)
   6890 		panic("key_expire: NULL pointer is passed");
   6891 	if (sav->sah == NULL)
   6892 		panic("key_expire: Why was SA index in SA NULL");
   6893 	if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
   6894 		panic("key_expire: invalid proto is passed");
   6895 
   6896 	/* set msg header */
   6897 	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
   6898 	if (!m) {
   6899 		error = ENOBUFS;
   6900 		goto fail;
   6901 	}
   6902 	result = m;
   6903 
   6904 	/* create SA extension */
   6905 	m = key_setsadbsa(sav);
   6906 	if (!m) {
   6907 		error = ENOBUFS;
   6908 		goto fail;
   6909 	}
   6910 	m_cat(result, m);
   6911 
   6912 	/* create SA extension */
   6913 	m = key_setsadbxsa2(sav->sah->saidx.mode,
   6914 			sav->replay ? sav->replay->count : 0,
   6915 			sav->sah->saidx.reqid);
   6916 	if (!m) {
   6917 		error = ENOBUFS;
   6918 		goto fail;
   6919 	}
   6920 	m_cat(result, m);
   6921 
   6922 	/* create lifetime extension (current and soft) */
   6923 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
   6924 	m = key_alloc_mbuf(len);
   6925 	if (!m || m->m_next) {	/*XXX*/
   6926 		if (m)
   6927 			m_freem(m);
   6928 		error = ENOBUFS;
   6929 		goto fail;
   6930 	}
   6931 	memset(mtod(m, void *), 0, len);
   6932 	lt = mtod(m, struct sadb_lifetime *);
   6933 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   6934 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   6935 	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
   6936 	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
   6937 	lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime
   6938 		+ time_second - time_uptime;
   6939 	lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime
   6940 		+ time_second - time_uptime;
   6941 	lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
   6942 	memcpy(lt, sav->lft_s, sizeof(*lt));
   6943 	m_cat(result, m);
   6944 
   6945 	/* set sadb_address for source */
   6946 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   6947 	    &sav->sah->saidx.src.sa,
   6948 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6949 	if (!m) {
   6950 		error = ENOBUFS;
   6951 		goto fail;
   6952 	}
   6953 	m_cat(result, m);
   6954 
   6955 	/* set sadb_address for destination */
   6956 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   6957 	    &sav->sah->saidx.dst.sa,
   6958 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6959 	if (!m) {
   6960 		error = ENOBUFS;
   6961 		goto fail;
   6962 	}
   6963 	m_cat(result, m);
   6964 
   6965 	if ((result->m_flags & M_PKTHDR) == 0) {
   6966 		error = EINVAL;
   6967 		goto fail;
   6968 	}
   6969 
   6970 	if (result->m_len < sizeof(struct sadb_msg)) {
   6971 		result = m_pullup(result, sizeof(struct sadb_msg));
   6972 		if (result == NULL) {
   6973 			error = ENOBUFS;
   6974 			goto fail;
   6975 		}
   6976 	}
   6977 
   6978 	result->m_pkthdr.len = 0;
   6979 	for (m = result; m; m = m->m_next)
   6980 		result->m_pkthdr.len += m->m_len;
   6981 
   6982 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6983 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6984 
   6985 	splx(s);
   6986 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   6987 
   6988  fail:
   6989 	if (result)
   6990 		m_freem(result);
   6991 	splx(s);
   6992 	return error;
   6993 }
   6994 
   6995 /*
   6996  * SADB_FLUSH processing
   6997  * receive
   6998  *   <base>
   6999  * from the ikmpd, and free all entries in secastree.
   7000  * and send,
   7001  *   <base>
   7002  * to the ikmpd.
   7003  * NOTE: to do is only marking SADB_SASTATE_DEAD.
   7004  *
   7005  * m will always be freed.
   7006  */
   7007 static int
   7008 key_flush(struct socket *so, struct mbuf *m,
   7009           const struct sadb_msghdr *mhp)
   7010 {
   7011 	struct sadb_msg *newmsg;
   7012 	struct secashead *sah, *nextsah;
   7013 	struct secasvar *sav, *nextsav;
   7014 	u_int16_t proto;
   7015 	u_int8_t state;
   7016 	u_int stateidx;
   7017 
   7018 	/* sanity check */
   7019 	if (so == NULL || mhp == NULL || mhp->msg == NULL)
   7020 		panic("key_flush: NULL pointer is passed");
   7021 
   7022 	/* map satype to proto */
   7023 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   7024 		ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
   7025 		return key_senderror(so, m, EINVAL);
   7026 	}
   7027 
   7028 	/* no SATYPE specified, i.e. flushing all SA. */
   7029 	for (sah = LIST_FIRST(&sahtree);
   7030 	     sah != NULL;
   7031 	     sah = nextsah) {
   7032 		nextsah = LIST_NEXT(sah, chain);
   7033 
   7034 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
   7035 		 && proto != sah->saidx.proto)
   7036 			continue;
   7037 
   7038 		for (stateidx = 0;
   7039 		     stateidx < _ARRAYLEN(saorder_state_alive);
   7040 		     stateidx++) {
   7041 			state = saorder_state_any[stateidx];
   7042 			for (sav = LIST_FIRST(&sah->savtree[state]);
   7043 			     sav != NULL;
   7044 			     sav = nextsav) {
   7045 
   7046 				nextsav = LIST_NEXT(sav, chain);
   7047 
   7048 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   7049 				KEY_FREESAV(&sav);
   7050 			}
   7051 		}
   7052 
   7053 		sah->state = SADB_SASTATE_DEAD;
   7054 	}
   7055 
   7056 	if (m->m_len < sizeof(struct sadb_msg) ||
   7057 	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
   7058 		ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
   7059 		return key_senderror(so, m, ENOBUFS);
   7060 	}
   7061 
   7062 	if (m->m_next)
   7063 		m_freem(m->m_next);
   7064 	m->m_next = NULL;
   7065 	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
   7066 	newmsg = mtod(m, struct sadb_msg *);
   7067 	newmsg->sadb_msg_errno = 0;
   7068 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
   7069 
   7070 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7071 }
   7072 
   7073 
   7074 static struct mbuf *
   7075 key_setdump_chain(u_int8_t req_satype, int *errorp, int *lenp, pid_t pid)
   7076 {
   7077 	struct secashead *sah;
   7078 	struct secasvar *sav;
   7079 	u_int16_t proto;
   7080 	u_int stateidx;
   7081 	u_int8_t satype;
   7082 	u_int8_t state;
   7083 	int cnt;
   7084 	struct mbuf *m, *n, *prev;
   7085 	int totlen;
   7086 
   7087 	*lenp = 0;
   7088 
   7089 	/* map satype to proto */
   7090 	if ((proto = key_satype2proto(req_satype)) == 0) {
   7091 		*errorp = EINVAL;
   7092 		return (NULL);
   7093 	}
   7094 
   7095 	/* count sav entries to be sent to userland. */
   7096 	cnt = 0;
   7097 	LIST_FOREACH(sah, &sahtree, chain) {
   7098 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7099 		    proto != sah->saidx.proto)
   7100 			continue;
   7101 
   7102 		for (stateidx = 0;
   7103 		     stateidx < _ARRAYLEN(saorder_state_any);
   7104 		     stateidx++) {
   7105 			state = saorder_state_any[stateidx];
   7106 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   7107 				cnt++;
   7108 			}
   7109 		}
   7110 	}
   7111 
   7112 	if (cnt == 0) {
   7113 		*errorp = ENOENT;
   7114 		return (NULL);
   7115 	}
   7116 
   7117 	/* send this to the userland, one at a time. */
   7118 	m = NULL;
   7119 	prev = m;
   7120 	LIST_FOREACH(sah, &sahtree, chain) {
   7121 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7122 		    proto != sah->saidx.proto)
   7123 			continue;
   7124 
   7125 		/* map proto to satype */
   7126 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
   7127 			m_freem(m);
   7128 			*errorp = EINVAL;
   7129 			return (NULL);
   7130 		}
   7131 
   7132 		for (stateidx = 0;
   7133 		     stateidx < _ARRAYLEN(saorder_state_any);
   7134 		     stateidx++) {
   7135 			state = saorder_state_any[stateidx];
   7136 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   7137 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   7138 				    --cnt, pid);
   7139 				if (!n) {
   7140 					m_freem(m);
   7141 					*errorp = ENOBUFS;
   7142 					return (NULL);
   7143 				}
   7144 
   7145 				totlen += n->m_pkthdr.len;
   7146 				if (!m)
   7147 					m = n;
   7148 				else
   7149 					prev->m_nextpkt = n;
   7150 				prev = n;
   7151 			}
   7152 		}
   7153 	}
   7154 
   7155 	if (!m) {
   7156 		*errorp = EINVAL;
   7157 		return (NULL);
   7158 	}
   7159 
   7160 	if ((m->m_flags & M_PKTHDR) != 0) {
   7161 		m->m_pkthdr.len = 0;
   7162 		for (n = m; n; n = n->m_next)
   7163 			m->m_pkthdr.len += n->m_len;
   7164 	}
   7165 
   7166 	*errorp = 0;
   7167 	return (m);
   7168 }
   7169 
   7170 /*
   7171  * SADB_DUMP processing
   7172  * dump all entries including status of DEAD in SAD.
   7173  * receive
   7174  *   <base>
   7175  * from the ikmpd, and dump all secasvar leaves
   7176  * and send,
   7177  *   <base> .....
   7178  * to the ikmpd.
   7179  *
   7180  * m will always be freed.
   7181  */
   7182 static int
   7183 key_dump(struct socket *so, struct mbuf *m0,
   7184 	 const struct sadb_msghdr *mhp)
   7185 {
   7186 	u_int16_t proto;
   7187 	u_int8_t satype;
   7188 	struct mbuf *n;
   7189 	int s;
   7190 	int error, len, ok;
   7191 
   7192 	/* sanity check */
   7193 	if (so == NULL || m0 == NULL || mhp == NULL || mhp->msg == NULL)
   7194 		panic("key_dump: NULL pointer is passed");
   7195 
   7196 	/* map satype to proto */
   7197 	satype = mhp->msg->sadb_msg_satype;
   7198 	if ((proto = key_satype2proto(satype)) == 0) {
   7199 		ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
   7200 		return key_senderror(so, m0, EINVAL);
   7201 	}
   7202 
   7203 	/*
   7204 	 * If the requestor has insufficient socket-buffer space
   7205 	 * for the entire chain, nobody gets any response to the DUMP.
   7206 	 * XXX For now, only the requestor ever gets anything.
   7207 	 * Moreover, if the requestor has any space at all, they receive
   7208 	 * the entire chain, otherwise the request is refused with ENOBUFS.
   7209 	 */
   7210 	if (sbspace(&so->so_rcv) <= 0) {
   7211 		return key_senderror(so, m0, ENOBUFS);
   7212 	}
   7213 
   7214 	s = splsoftnet();
   7215 	n = key_setdump_chain(satype, &error, &len, mhp->msg->sadb_msg_pid);
   7216 	splx(s);
   7217 
   7218 	if (n == NULL) {
   7219 		return key_senderror(so, m0, ENOENT);
   7220 	}
   7221 	{
   7222 		uint64_t *ps = PFKEY_STAT_GETREF();
   7223 		ps[PFKEY_STAT_IN_TOTAL]++;
   7224 		ps[PFKEY_STAT_IN_BYTES] += len;
   7225 		PFKEY_STAT_PUTREF();
   7226 	}
   7227 
   7228 	/*
   7229 	 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
   7230 	 * The requestor receives either the entire chain, or an
   7231 	 * error message with ENOBUFS.
   7232 	 *
   7233 	 * sbappendaddrchain() takes the chain of entries, one
   7234 	 * packet-record per SPD entry, prepends the key_src sockaddr
   7235 	 * to each packet-record, links the sockaddr mbufs into a new
   7236 	 * list of records, then   appends the entire resulting
   7237 	 * list to the requesting socket.
   7238 	 */
   7239 	ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src,
   7240 	        n, SB_PRIO_ONESHOT_OVERFLOW);
   7241 
   7242 	if (!ok) {
   7243 		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
   7244 		m_freem(n);
   7245 		return key_senderror(so, m0, ENOBUFS);
   7246 	}
   7247 
   7248 	m_freem(m0);
   7249 	return 0;
   7250 }
   7251 
   7252 /*
   7253  * SADB_X_PROMISC processing
   7254  *
   7255  * m will always be freed.
   7256  */
   7257 static int
   7258 key_promisc(struct socket *so, struct mbuf *m,
   7259 	    const struct sadb_msghdr *mhp)
   7260 {
   7261 	int olen;
   7262 
   7263 	/* sanity check */
   7264 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   7265 		panic("key_promisc: NULL pointer is passed");
   7266 
   7267 	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   7268 
   7269 	if (olen < sizeof(struct sadb_msg)) {
   7270 #if 1
   7271 		return key_senderror(so, m, EINVAL);
   7272 #else
   7273 		m_freem(m);
   7274 		return 0;
   7275 #endif
   7276 	} else if (olen == sizeof(struct sadb_msg)) {
   7277 		/* enable/disable promisc mode */
   7278 		struct keycb *kp;
   7279 
   7280 		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
   7281 			return key_senderror(so, m, EINVAL);
   7282 		mhp->msg->sadb_msg_errno = 0;
   7283 		switch (mhp->msg->sadb_msg_satype) {
   7284 		case 0:
   7285 		case 1:
   7286 			kp->kp_promisc = mhp->msg->sadb_msg_satype;
   7287 			break;
   7288 		default:
   7289 			return key_senderror(so, m, EINVAL);
   7290 		}
   7291 
   7292 		/* send the original message back to everyone */
   7293 		mhp->msg->sadb_msg_errno = 0;
   7294 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7295 	} else {
   7296 		/* send packet as is */
   7297 
   7298 		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
   7299 
   7300 		/* TODO: if sadb_msg_seq is specified, send to specific pid */
   7301 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7302 	}
   7303 }
   7304 
   7305 static int (*key_typesw[]) (struct socket *, struct mbuf *,
   7306 		const struct sadb_msghdr *) = {
   7307 	NULL,		/* SADB_RESERVED */
   7308 	key_getspi,	/* SADB_GETSPI */
   7309 	key_update,	/* SADB_UPDATE */
   7310 	key_add,	/* SADB_ADD */
   7311 	key_delete,	/* SADB_DELETE */
   7312 	key_get,	/* SADB_GET */
   7313 	key_acquire2,	/* SADB_ACQUIRE */
   7314 	key_register,	/* SADB_REGISTER */
   7315 	NULL,		/* SADB_EXPIRE */
   7316 	key_flush,	/* SADB_FLUSH */
   7317 	key_dump,	/* SADB_DUMP */
   7318 	key_promisc,	/* SADB_X_PROMISC */
   7319 	NULL,		/* SADB_X_PCHANGE */
   7320 	key_spdadd,	/* SADB_X_SPDUPDATE */
   7321 	key_spdadd,	/* SADB_X_SPDADD */
   7322 	key_spddelete,	/* SADB_X_SPDDELETE */
   7323 	key_spdget,	/* SADB_X_SPDGET */
   7324 	NULL,		/* SADB_X_SPDACQUIRE */
   7325 	key_spddump,	/* SADB_X_SPDDUMP */
   7326 	key_spdflush,	/* SADB_X_SPDFLUSH */
   7327 	key_spdadd,	/* SADB_X_SPDSETIDX */
   7328 	NULL,		/* SADB_X_SPDEXPIRE */
   7329 	key_spddelete2,	/* SADB_X_SPDDELETE2 */
   7330 #ifdef IPSEC_NAT_T
   7331        key_nat_map,	/* SADB_X_NAT_T_NEW_MAPPING */
   7332 #endif
   7333 };
   7334 
   7335 /*
   7336  * parse sadb_msg buffer to process PFKEYv2,
   7337  * and create a data to response if needed.
   7338  * I think to be dealed with mbuf directly.
   7339  * IN:
   7340  *     msgp  : pointer to pointer to a received buffer pulluped.
   7341  *             This is rewrited to response.
   7342  *     so    : pointer to socket.
   7343  * OUT:
   7344  *    length for buffer to send to user process.
   7345  */
   7346 int
   7347 key_parse(struct mbuf *m, struct socket *so)
   7348 {
   7349 	struct sadb_msg *msg;
   7350 	struct sadb_msghdr mh;
   7351 	u_int orglen;
   7352 	int error;
   7353 	int target;
   7354 
   7355 	/* sanity check */
   7356 	if (m == NULL || so == NULL)
   7357 		panic("key_parse: NULL pointer is passed");
   7358 
   7359 #if 0	/*kdebug_sadb assumes msg in linear buffer*/
   7360 	KEYDEBUG(KEYDEBUG_KEY_DUMP,
   7361 		ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
   7362 		kdebug_sadb(msg));
   7363 #endif
   7364 
   7365 	if (m->m_len < sizeof(struct sadb_msg)) {
   7366 		m = m_pullup(m, sizeof(struct sadb_msg));
   7367 		if (!m)
   7368 			return ENOBUFS;
   7369 	}
   7370 	msg = mtod(m, struct sadb_msg *);
   7371 	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
   7372 	target = KEY_SENDUP_ONE;
   7373 
   7374 	if ((m->m_flags & M_PKTHDR) == 0 ||
   7375 	    m->m_pkthdr.len != m->m_pkthdr.len) {
   7376 		ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
   7377 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7378 		error = EINVAL;
   7379 		goto senderror;
   7380 	}
   7381 
   7382 	if (msg->sadb_msg_version != PF_KEY_V2) {
   7383 		ipseclog((LOG_DEBUG,
   7384 		    "key_parse: PF_KEY version %u is mismatched.\n",
   7385 		    msg->sadb_msg_version));
   7386 		PFKEY_STATINC(PFKEY_STAT_OUT_INVVER);
   7387 		error = EINVAL;
   7388 		goto senderror;
   7389 	}
   7390 
   7391 	if (msg->sadb_msg_type > SADB_MAX) {
   7392 		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
   7393 		    msg->sadb_msg_type));
   7394 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7395 		error = EINVAL;
   7396 		goto senderror;
   7397 	}
   7398 
   7399 	/* for old-fashioned code - should be nuked */
   7400 	if (m->m_pkthdr.len > MCLBYTES) {
   7401 		m_freem(m);
   7402 		return ENOBUFS;
   7403 	}
   7404 	if (m->m_next) {
   7405 		struct mbuf *n;
   7406 
   7407 		MGETHDR(n, M_DONTWAIT, MT_DATA);
   7408 		if (n && m->m_pkthdr.len > MHLEN) {
   7409 			MCLGET(n, M_DONTWAIT);
   7410 			if ((n->m_flags & M_EXT) == 0) {
   7411 				m_free(n);
   7412 				n = NULL;
   7413 			}
   7414 		}
   7415 		if (!n) {
   7416 			m_freem(m);
   7417 			return ENOBUFS;
   7418 		}
   7419 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, void *));
   7420 		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
   7421 		n->m_next = NULL;
   7422 		m_freem(m);
   7423 		m = n;
   7424 	}
   7425 
   7426 	/* align the mbuf chain so that extensions are in contiguous region. */
   7427 	error = key_align(m, &mh);
   7428 	if (error)
   7429 		return error;
   7430 
   7431 	if (m->m_next) {	/*XXX*/
   7432 		m_freem(m);
   7433 		return ENOBUFS;
   7434 	}
   7435 
   7436 	msg = mh.msg;
   7437 
   7438 	/* check SA type */
   7439 	switch (msg->sadb_msg_satype) {
   7440 	case SADB_SATYPE_UNSPEC:
   7441 		switch (msg->sadb_msg_type) {
   7442 		case SADB_GETSPI:
   7443 		case SADB_UPDATE:
   7444 		case SADB_ADD:
   7445 		case SADB_DELETE:
   7446 		case SADB_GET:
   7447 		case SADB_ACQUIRE:
   7448 		case SADB_EXPIRE:
   7449 			ipseclog((LOG_DEBUG, "key_parse: must specify satype "
   7450 			    "when msg type=%u.\n", msg->sadb_msg_type));
   7451 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7452 			error = EINVAL;
   7453 			goto senderror;
   7454 		}
   7455 		break;
   7456 	case SADB_SATYPE_AH:
   7457 	case SADB_SATYPE_ESP:
   7458 	case SADB_X_SATYPE_IPCOMP:
   7459 	case SADB_X_SATYPE_TCPSIGNATURE:
   7460 		switch (msg->sadb_msg_type) {
   7461 		case SADB_X_SPDADD:
   7462 		case SADB_X_SPDDELETE:
   7463 		case SADB_X_SPDGET:
   7464 		case SADB_X_SPDDUMP:
   7465 		case SADB_X_SPDFLUSH:
   7466 		case SADB_X_SPDSETIDX:
   7467 		case SADB_X_SPDUPDATE:
   7468 		case SADB_X_SPDDELETE2:
   7469 			ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
   7470 			    msg->sadb_msg_type));
   7471 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7472 			error = EINVAL;
   7473 			goto senderror;
   7474 		}
   7475 		break;
   7476 	case SADB_SATYPE_RSVP:
   7477 	case SADB_SATYPE_OSPFV2:
   7478 	case SADB_SATYPE_RIPV2:
   7479 	case SADB_SATYPE_MIP:
   7480 		ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
   7481 		    msg->sadb_msg_satype));
   7482 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7483 		error = EOPNOTSUPP;
   7484 		goto senderror;
   7485 	case 1:	/* XXX: What does it do? */
   7486 		if (msg->sadb_msg_type == SADB_X_PROMISC)
   7487 			break;
   7488 		/*FALLTHROUGH*/
   7489 	default:
   7490 		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
   7491 		    msg->sadb_msg_satype));
   7492 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7493 		error = EINVAL;
   7494 		goto senderror;
   7495 	}
   7496 
   7497 	/* check field of upper layer protocol and address family */
   7498 	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
   7499 	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
   7500 		struct sadb_address *src0, *dst0;
   7501 		u_int plen;
   7502 
   7503 		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
   7504 		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
   7505 
   7506 		/* check upper layer protocol */
   7507 		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
   7508 			ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
   7509 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7510 			error = EINVAL;
   7511 			goto senderror;
   7512 		}
   7513 
   7514 		/* check family */
   7515 		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
   7516 		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
   7517 			ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
   7518 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7519 			error = EINVAL;
   7520 			goto senderror;
   7521 		}
   7522 		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7523 		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
   7524 			ipseclog((LOG_DEBUG,
   7525 			    "key_parse: address struct size mismatched.\n"));
   7526 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7527 			error = EINVAL;
   7528 			goto senderror;
   7529 		}
   7530 
   7531 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7532 		case AF_INET:
   7533 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7534 			    sizeof(struct sockaddr_in)) {
   7535 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7536 				error = EINVAL;
   7537 				goto senderror;
   7538 			}
   7539 			break;
   7540 		case AF_INET6:
   7541 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7542 			    sizeof(struct sockaddr_in6)) {
   7543 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7544 				error = EINVAL;
   7545 				goto senderror;
   7546 			}
   7547 			break;
   7548 		default:
   7549 			ipseclog((LOG_DEBUG,
   7550 			    "key_parse: unsupported address family.\n"));
   7551 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7552 			error = EAFNOSUPPORT;
   7553 			goto senderror;
   7554 		}
   7555 
   7556 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7557 		case AF_INET:
   7558 			plen = sizeof(struct in_addr) << 3;
   7559 			break;
   7560 		case AF_INET6:
   7561 			plen = sizeof(struct in6_addr) << 3;
   7562 			break;
   7563 		default:
   7564 			plen = 0;	/*fool gcc*/
   7565 			break;
   7566 		}
   7567 
   7568 		/* check max prefix length */
   7569 		if (src0->sadb_address_prefixlen > plen ||
   7570 		    dst0->sadb_address_prefixlen > plen) {
   7571 			ipseclog((LOG_DEBUG,
   7572 			    "key_parse: illegal prefixlen.\n"));
   7573 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7574 			error = EINVAL;
   7575 			goto senderror;
   7576 		}
   7577 
   7578 		/*
   7579 		 * prefixlen == 0 is valid because there can be a case when
   7580 		 * all addresses are matched.
   7581 		 */
   7582 	}
   7583 
   7584 	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
   7585 	    key_typesw[msg->sadb_msg_type] == NULL) {
   7586 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7587 		error = EINVAL;
   7588 		goto senderror;
   7589 	}
   7590 
   7591 	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
   7592 
   7593 senderror:
   7594 	msg->sadb_msg_errno = error;
   7595 	return key_sendup_mbuf(so, m, target);
   7596 }
   7597 
   7598 static int
   7599 key_senderror(struct socket *so, struct mbuf *m, int code)
   7600 {
   7601 	struct sadb_msg *msg;
   7602 
   7603 	if (m->m_len < sizeof(struct sadb_msg))
   7604 		panic("invalid mbuf passed to key_senderror");
   7605 
   7606 	msg = mtod(m, struct sadb_msg *);
   7607 	msg->sadb_msg_errno = code;
   7608 	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   7609 }
   7610 
   7611 /*
   7612  * set the pointer to each header into message buffer.
   7613  * m will be freed on error.
   7614  * XXX larger-than-MCLBYTES extension?
   7615  */
   7616 static int
   7617 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
   7618 {
   7619 	struct mbuf *n;
   7620 	struct sadb_ext *ext;
   7621 	size_t off, end;
   7622 	int extlen;
   7623 	int toff;
   7624 
   7625 	/* sanity check */
   7626 	if (m == NULL || mhp == NULL)
   7627 		panic("key_align: NULL pointer is passed");
   7628 	if (m->m_len < sizeof(struct sadb_msg))
   7629 		panic("invalid mbuf passed to key_align");
   7630 
   7631 	/* initialize */
   7632 	memset(mhp, 0, sizeof(*mhp));
   7633 
   7634 	mhp->msg = mtod(m, struct sadb_msg *);
   7635 	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
   7636 
   7637 	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   7638 	extlen = end;	/*just in case extlen is not updated*/
   7639 	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
   7640 		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
   7641 		if (!n) {
   7642 			/* m is already freed */
   7643 			return ENOBUFS;
   7644 		}
   7645 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7646 
   7647 		/* set pointer */
   7648 		switch (ext->sadb_ext_type) {
   7649 		case SADB_EXT_SA:
   7650 		case SADB_EXT_ADDRESS_SRC:
   7651 		case SADB_EXT_ADDRESS_DST:
   7652 		case SADB_EXT_ADDRESS_PROXY:
   7653 		case SADB_EXT_LIFETIME_CURRENT:
   7654 		case SADB_EXT_LIFETIME_HARD:
   7655 		case SADB_EXT_LIFETIME_SOFT:
   7656 		case SADB_EXT_KEY_AUTH:
   7657 		case SADB_EXT_KEY_ENCRYPT:
   7658 		case SADB_EXT_IDENTITY_SRC:
   7659 		case SADB_EXT_IDENTITY_DST:
   7660 		case SADB_EXT_SENSITIVITY:
   7661 		case SADB_EXT_PROPOSAL:
   7662 		case SADB_EXT_SUPPORTED_AUTH:
   7663 		case SADB_EXT_SUPPORTED_ENCRYPT:
   7664 		case SADB_EXT_SPIRANGE:
   7665 		case SADB_X_EXT_POLICY:
   7666 		case SADB_X_EXT_SA2:
   7667 #ifdef IPSEC_NAT_T
   7668 		case SADB_X_EXT_NAT_T_TYPE:
   7669 		case SADB_X_EXT_NAT_T_SPORT:
   7670 		case SADB_X_EXT_NAT_T_DPORT:
   7671 		case SADB_X_EXT_NAT_T_OAI:
   7672 		case SADB_X_EXT_NAT_T_OAR:
   7673 		case SADB_X_EXT_NAT_T_FRAG:
   7674 #endif
   7675 			/* duplicate check */
   7676 			/*
   7677 			 * XXX Are there duplication payloads of either
   7678 			 * KEY_AUTH or KEY_ENCRYPT ?
   7679 			 */
   7680 			if (mhp->ext[ext->sadb_ext_type] != NULL) {
   7681 				ipseclog((LOG_DEBUG,
   7682 				    "key_align: duplicate ext_type %u "
   7683 				    "is passed.\n", ext->sadb_ext_type));
   7684 				m_freem(m);
   7685 				PFKEY_STATINC(PFKEY_STAT_OUT_DUPEXT);
   7686 				return EINVAL;
   7687 			}
   7688 			break;
   7689 		default:
   7690 			ipseclog((LOG_DEBUG,
   7691 			    "key_align: invalid ext_type %u is passed.\n",
   7692 			    ext->sadb_ext_type));
   7693 			m_freem(m);
   7694 			PFKEY_STATINC(PFKEY_STAT_OUT_INVEXTTYPE);
   7695 			return EINVAL;
   7696 		}
   7697 
   7698 		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
   7699 
   7700 		if (key_validate_ext(ext, extlen)) {
   7701 			m_freem(m);
   7702 			PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7703 			return EINVAL;
   7704 		}
   7705 
   7706 		n = m_pulldown(m, off, extlen, &toff);
   7707 		if (!n) {
   7708 			/* m is already freed */
   7709 			return ENOBUFS;
   7710 		}
   7711 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7712 
   7713 		mhp->ext[ext->sadb_ext_type] = ext;
   7714 		mhp->extoff[ext->sadb_ext_type] = off;
   7715 		mhp->extlen[ext->sadb_ext_type] = extlen;
   7716 	}
   7717 
   7718 	if (off != end) {
   7719 		m_freem(m);
   7720 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7721 		return EINVAL;
   7722 	}
   7723 
   7724 	return 0;
   7725 }
   7726 
   7727 static int
   7728 key_validate_ext(const struct sadb_ext *ext, int len)
   7729 {
   7730 	const struct sockaddr *sa;
   7731 	enum { NONE, ADDR } checktype = NONE;
   7732 	int baselen = 0;
   7733 	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
   7734 
   7735 	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
   7736 		return EINVAL;
   7737 
   7738 	/* if it does not match minimum/maximum length, bail */
   7739 	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
   7740 	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
   7741 		return EINVAL;
   7742 	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
   7743 		return EINVAL;
   7744 	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
   7745 		return EINVAL;
   7746 
   7747 	/* more checks based on sadb_ext_type XXX need more */
   7748 	switch (ext->sadb_ext_type) {
   7749 	case SADB_EXT_ADDRESS_SRC:
   7750 	case SADB_EXT_ADDRESS_DST:
   7751 	case SADB_EXT_ADDRESS_PROXY:
   7752 		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
   7753 		checktype = ADDR;
   7754 		break;
   7755 	case SADB_EXT_IDENTITY_SRC:
   7756 	case SADB_EXT_IDENTITY_DST:
   7757 		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
   7758 		    SADB_X_IDENTTYPE_ADDR) {
   7759 			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
   7760 			checktype = ADDR;
   7761 		} else
   7762 			checktype = NONE;
   7763 		break;
   7764 	default:
   7765 		checktype = NONE;
   7766 		break;
   7767 	}
   7768 
   7769 	switch (checktype) {
   7770 	case NONE:
   7771 		break;
   7772 	case ADDR:
   7773 		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
   7774 		if (len < baselen + sal)
   7775 			return EINVAL;
   7776 		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
   7777 			return EINVAL;
   7778 		break;
   7779 	}
   7780 
   7781 	return 0;
   7782 }
   7783 
   7784 static int
   7785 key_do_init(void)
   7786 {
   7787 	int i;
   7788 
   7789 	pfkeystat_percpu = percpu_alloc(sizeof(uint64_t) * PFKEY_NSTATS);
   7790 
   7791 	callout_init(&key_timehandler_ch, 0);
   7792 
   7793 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
   7794 		LIST_INIT(&sptree[i]);
   7795 	}
   7796 
   7797 	LIST_INIT(&sahtree);
   7798 
   7799 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   7800 		LIST_INIT(&regtree[i]);
   7801 	}
   7802 
   7803 #ifndef IPSEC_NONBLOCK_ACQUIRE
   7804 	LIST_INIT(&acqtree);
   7805 #endif
   7806 	LIST_INIT(&spacqtree);
   7807 
   7808 	/* system default */
   7809 	ip4_def_policy.policy = IPSEC_POLICY_NONE;
   7810 	ip4_def_policy.refcnt++;	/*never reclaim this*/
   7811 
   7812 #ifdef INET6
   7813 	ip6_def_policy.policy = IPSEC_POLICY_NONE;
   7814 	ip6_def_policy.refcnt++;	/*never reclaim this*/
   7815 #endif
   7816 
   7817 
   7818 #ifndef IPSEC_DEBUG2
   7819 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   7820 #endif /*IPSEC_DEBUG2*/
   7821 
   7822 	/* initialize key statistics */
   7823 	keystat.getspi_count = 1;
   7824 
   7825 	aprint_verbose("IPsec: Initialized Security Association Processing.\n");
   7826 
   7827 	return (0);
   7828 }
   7829 
   7830 void
   7831 key_init(void)
   7832 {
   7833 	static ONCE_DECL(key_init_once);
   7834 
   7835 	RUN_ONCE(&key_init_once, key_do_init);
   7836 }
   7837 
   7838 /*
   7839  * XXX: maybe This function is called after INBOUND IPsec processing.
   7840  *
   7841  * Special check for tunnel-mode packets.
   7842  * We must make some checks for consistency between inner and outer IP header.
   7843  *
   7844  * xxx more checks to be provided
   7845  */
   7846 int
   7847 key_checktunnelsanity(
   7848     struct secasvar *sav,
   7849     u_int family,
   7850     void *src,
   7851     void *dst
   7852 )
   7853 {
   7854 	/* sanity check */
   7855 	if (sav->sah == NULL)
   7856 		panic("sav->sah == NULL at key_checktunnelsanity");
   7857 
   7858 	/* XXX: check inner IP header */
   7859 
   7860 	return 1;
   7861 }
   7862 
   7863 #if 0
   7864 #define hostnamelen	strlen(hostname)
   7865 
   7866 /*
   7867  * Get FQDN for the host.
   7868  * If the administrator configured hostname (by hostname(1)) without
   7869  * domain name, returns nothing.
   7870  */
   7871 static const char *
   7872 key_getfqdn(void)
   7873 {
   7874 	int i;
   7875 	int hasdot;
   7876 	static char fqdn[MAXHOSTNAMELEN + 1];
   7877 
   7878 	if (!hostnamelen)
   7879 		return NULL;
   7880 
   7881 	/* check if it comes with domain name. */
   7882 	hasdot = 0;
   7883 	for (i = 0; i < hostnamelen; i++) {
   7884 		if (hostname[i] == '.')
   7885 			hasdot++;
   7886 	}
   7887 	if (!hasdot)
   7888 		return NULL;
   7889 
   7890 	/* NOTE: hostname may not be NUL-terminated. */
   7891 	memset(fqdn, 0, sizeof(fqdn));
   7892 	memcpy(fqdn, hostname, hostnamelen);
   7893 	fqdn[hostnamelen] = '\0';
   7894 	return fqdn;
   7895 }
   7896 
   7897 /*
   7898  * get username@FQDN for the host/user.
   7899  */
   7900 static const char *
   7901 key_getuserfqdn(void)
   7902 {
   7903 	const char *host;
   7904 	static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
   7905 	struct proc *p = curproc;
   7906 	char *q;
   7907 
   7908 	if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
   7909 		return NULL;
   7910 	if (!(host = key_getfqdn()))
   7911 		return NULL;
   7912 
   7913 	/* NOTE: s_login may not be-NUL terminated. */
   7914 	memset(userfqdn, 0, sizeof(userfqdn));
   7915 	memcpy(userfqdn, Mp->p_pgrp->pg_session->s_login, AXLOGNAME);
   7916 	userfqdn[MAXLOGNAME] = '\0';	/* safeguard */
   7917 	q = userfqdn + strlen(userfqdn);
   7918 	*q++ = '@';
   7919 	memcpy(q, host, strlen(host));
   7920 	q += strlen(host);
   7921 	*q++ = '\0';
   7922 
   7923 	return userfqdn;
   7924 }
   7925 #endif
   7926 
   7927 /* record data transfer on SA, and update timestamps */
   7928 void
   7929 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
   7930 {
   7931 	IPSEC_ASSERT(sav != NULL, ("key_sa_recordxfer: Null secasvar"));
   7932 	IPSEC_ASSERT(m != NULL, ("key_sa_recordxfer: Null mbuf"));
   7933 	if (!sav->lft_c)
   7934 		return;
   7935 
   7936 	/*
   7937 	 * XXX Currently, there is a difference of bytes size
   7938 	 * between inbound and outbound processing.
   7939 	 */
   7940 	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
   7941 	/* to check bytes lifetime is done in key_timehandler(). */
   7942 
   7943 	/*
   7944 	 * We use the number of packets as the unit of
   7945 	 * sadb_lifetime_allocations.  We increment the variable
   7946 	 * whenever {esp,ah}_{in,out}put is called.
   7947 	 */
   7948 	sav->lft_c->sadb_lifetime_allocations++;
   7949 	/* XXX check for expires? */
   7950 
   7951 	/*
   7952 	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
   7953 	 * in seconds.  HARD and SOFT lifetime are measured by the time
   7954 	 * difference (again in seconds) from sadb_lifetime_usetime.
   7955 	 *
   7956 	 *	usetime
   7957 	 *	v     expire   expire
   7958 	 * -----+-----+--------+---> t
   7959 	 *	<--------------> HARD
   7960 	 *	<-----> SOFT
   7961 	 */
   7962 	sav->lft_c->sadb_lifetime_usetime = time_uptime;
   7963 	/* XXX check for expires? */
   7964 
   7965 	return;
   7966 }
   7967 
   7968 /* dumb version */
   7969 void
   7970 key_sa_routechange(struct sockaddr *dst)
   7971 {
   7972 	struct secashead *sah;
   7973 	struct route *ro;
   7974 	const struct sockaddr *sa;
   7975 
   7976 	LIST_FOREACH(sah, &sahtree, chain) {
   7977 		ro = &sah->sa_route;
   7978 		sa = rtcache_getdst(ro);
   7979 		if (sa != NULL && dst->sa_len == sa->sa_len &&
   7980 		    memcmp(dst, sa, dst->sa_len) == 0)
   7981 			rtcache_free(ro);
   7982 	}
   7983 
   7984 	return;
   7985 }
   7986 
   7987 static void
   7988 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
   7989 {
   7990 	if (sav == NULL)
   7991 		panic("key_sa_chgstate called with sav == NULL");
   7992 
   7993 	if (sav->state == state)
   7994 		return;
   7995 
   7996 	if (__LIST_CHAINED(sav))
   7997 		LIST_REMOVE(sav, chain);
   7998 
   7999 	sav->state = state;
   8000 	LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
   8001 }
   8002 
   8003 void
   8004 key_sa_stir_iv(struct secasvar *sav)
   8005 {
   8006 
   8007 	if (!sav->iv)
   8008 		panic("key_sa_stir_iv called with sav == NULL");
   8009 	key_randomfill(sav->iv, sav->ivlen);
   8010 }
   8011 
   8012 /* XXX too much? */
   8013 static struct mbuf *
   8014 key_alloc_mbuf(int l)
   8015 {
   8016 	struct mbuf *m = NULL, *n;
   8017 	int len, t;
   8018 
   8019 	len = l;
   8020 	while (len > 0) {
   8021 		MGET(n, M_DONTWAIT, MT_DATA);
   8022 		if (n && len > MLEN)
   8023 			MCLGET(n, M_DONTWAIT);
   8024 		if (!n) {
   8025 			m_freem(m);
   8026 			return NULL;
   8027 		}
   8028 
   8029 		n->m_next = NULL;
   8030 		n->m_len = 0;
   8031 		n->m_len = M_TRAILINGSPACE(n);
   8032 		/* use the bottom of mbuf, hoping we can prepend afterwards */
   8033 		if (n->m_len > len) {
   8034 			t = (n->m_len - len) & ~(sizeof(long) - 1);
   8035 			n->m_data += t;
   8036 			n->m_len = len;
   8037 		}
   8038 
   8039 		len -= n->m_len;
   8040 
   8041 		if (m)
   8042 			m_cat(m, n);
   8043 		else
   8044 			m = n;
   8045 	}
   8046 
   8047 	return m;
   8048 }
   8049 
   8050 static struct mbuf *
   8051 key_setdump(u_int8_t req_satype, int *errorp, uint32_t pid)
   8052 {
   8053 	struct secashead *sah;
   8054 	struct secasvar *sav;
   8055 	u_int16_t proto;
   8056 	u_int stateidx;
   8057 	u_int8_t satype;
   8058 	u_int8_t state;
   8059 	int cnt;
   8060 	struct mbuf *m, *n;
   8061 
   8062 	/* map satype to proto */
   8063 	if ((proto = key_satype2proto(req_satype)) == 0) {
   8064 		*errorp = EINVAL;
   8065 		return (NULL);
   8066 	}
   8067 
   8068 	/* count sav entries to be sent to the userland. */
   8069 	cnt = 0;
   8070 	LIST_FOREACH(sah, &sahtree, chain) {
   8071 		if (req_satype != SADB_SATYPE_UNSPEC &&
   8072 		    proto != sah->saidx.proto)
   8073 			continue;
   8074 
   8075 		for (stateidx = 0;
   8076 		     stateidx < _ARRAYLEN(saorder_state_any);
   8077 		     stateidx++) {
   8078 			state = saorder_state_any[stateidx];
   8079 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   8080 				cnt++;
   8081 			}
   8082 		}
   8083 	}
   8084 
   8085 	if (cnt == 0) {
   8086 		*errorp = ENOENT;
   8087 		return (NULL);
   8088 	}
   8089 
   8090 	/* send this to the userland, one at a time. */
   8091 	m = NULL;
   8092 	LIST_FOREACH(sah, &sahtree, chain) {
   8093 		if (req_satype != SADB_SATYPE_UNSPEC &&
   8094 		    proto != sah->saidx.proto)
   8095 			continue;
   8096 
   8097 		/* map proto to satype */
   8098 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
   8099 			m_freem(m);
   8100 			*errorp = EINVAL;
   8101 			return (NULL);
   8102 		}
   8103 
   8104 		for (stateidx = 0;
   8105 		     stateidx < _ARRAYLEN(saorder_state_any);
   8106 		     stateidx++) {
   8107 			state = saorder_state_any[stateidx];
   8108 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   8109 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   8110 				    --cnt, pid);
   8111 				if (!n) {
   8112 					m_freem(m);
   8113 					*errorp = ENOBUFS;
   8114 					return (NULL);
   8115 				}
   8116 
   8117 				if (!m)
   8118 					m = n;
   8119 				else
   8120 					m_cat(m, n);
   8121 			}
   8122 		}
   8123 	}
   8124 
   8125 	if (!m) {
   8126 		*errorp = EINVAL;
   8127 		return (NULL);
   8128 	}
   8129 
   8130 	if ((m->m_flags & M_PKTHDR) != 0) {
   8131 		m->m_pkthdr.len = 0;
   8132 		for (n = m; n; n = n->m_next)
   8133 			m->m_pkthdr.len += n->m_len;
   8134 	}
   8135 
   8136 	*errorp = 0;
   8137 	return (m);
   8138 }
   8139 
   8140 static struct mbuf *
   8141 key_setspddump(int *errorp, pid_t pid)
   8142 {
   8143 	struct secpolicy *sp;
   8144 	int cnt;
   8145 	u_int dir;
   8146 	struct mbuf *m, *n;
   8147 
   8148 	/* search SPD entry and get buffer size. */
   8149 	cnt = 0;
   8150 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   8151 		LIST_FOREACH(sp, &sptree[dir], chain) {
   8152 			cnt++;
   8153 		}
   8154 	}
   8155 
   8156 	if (cnt == 0) {
   8157 		*errorp = ENOENT;
   8158 		return (NULL);
   8159 	}
   8160 
   8161 	m = NULL;
   8162 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   8163 		LIST_FOREACH(sp, &sptree[dir], chain) {
   8164 			--cnt;
   8165 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
   8166 
   8167 			if (!n) {
   8168 				*errorp = ENOBUFS;
   8169 				m_freem(m);
   8170 				return (NULL);
   8171 			}
   8172 			if (!m)
   8173 				m = n;
   8174 			else {
   8175 				m->m_pkthdr.len += n->m_pkthdr.len;
   8176 				m_cat(m, n);
   8177 			}
   8178 		}
   8179 	}
   8180 
   8181 	*errorp = 0;
   8182 	return (m);
   8183 }
   8184 
   8185 static int
   8186 sysctl_net_key_dumpsa(SYSCTLFN_ARGS)
   8187 {
   8188 	struct mbuf *m, *n;
   8189 	int err2 = 0;
   8190 	char *p, *ep;
   8191 	size_t len;
   8192 	int s, error;
   8193 
   8194 	if (newp)
   8195 		return (EPERM);
   8196 	if (namelen != 1)
   8197 		return (EINVAL);
   8198 
   8199 	s = splsoftnet();
   8200 	m = key_setdump(name[0], &error, l->l_proc->p_pid);
   8201 	splx(s);
   8202 	if (!m)
   8203 		return (error);
   8204 	if (!oldp)
   8205 		*oldlenp = m->m_pkthdr.len;
   8206 	else {
   8207 		p = oldp;
   8208 		if (*oldlenp < m->m_pkthdr.len) {
   8209 			err2 = ENOMEM;
   8210 			ep = p + *oldlenp;
   8211 		} else {
   8212 			*oldlenp = m->m_pkthdr.len;
   8213 			ep = p + m->m_pkthdr.len;
   8214 		}
   8215 		for (n = m; n; n = n->m_next) {
   8216 			len =  (ep - p < n->m_len) ?
   8217 				ep - p : n->m_len;
   8218 			error = copyout(mtod(n, const void *), p, len);
   8219 			p += len;
   8220 			if (error)
   8221 				break;
   8222 		}
   8223 		if (error == 0)
   8224 			error = err2;
   8225 	}
   8226 	m_freem(m);
   8227 
   8228 	return (error);
   8229 }
   8230 
   8231 static int
   8232 sysctl_net_key_dumpsp(SYSCTLFN_ARGS)
   8233 {
   8234 	struct mbuf *m, *n;
   8235 	int err2 = 0;
   8236 	char *p, *ep;
   8237 	size_t len;
   8238 	int s, error;
   8239 
   8240 	if (newp)
   8241 		return (EPERM);
   8242 	if (namelen != 0)
   8243 		return (EINVAL);
   8244 
   8245 	s = splsoftnet();
   8246 	m = key_setspddump(&error, l->l_proc->p_pid);
   8247 	splx(s);
   8248 	if (!m)
   8249 		return (error);
   8250 	if (!oldp)
   8251 		*oldlenp = m->m_pkthdr.len;
   8252 	else {
   8253 		p = oldp;
   8254 		if (*oldlenp < m->m_pkthdr.len) {
   8255 			err2 = ENOMEM;
   8256 			ep = p + *oldlenp;
   8257 		} else {
   8258 			*oldlenp = m->m_pkthdr.len;
   8259 			ep = p + m->m_pkthdr.len;
   8260 		}
   8261 		for (n = m; n; n = n->m_next) {
   8262 			len =  (ep - p < n->m_len) ?
   8263 				ep - p : n->m_len;
   8264 			error = copyout(mtod(n, const void *), p, len);
   8265 			p += len;
   8266 			if (error)
   8267 				break;
   8268 		}
   8269 		if (error == 0)
   8270 			error = err2;
   8271 	}
   8272 	m_freem(m);
   8273 
   8274 	return (error);
   8275 }
   8276 
   8277 /*
   8278  * Create sysctl tree for native FAST_IPSEC key knobs, originally
   8279  * under name "net.keyv2"  * with MIB number { CTL_NET, PF_KEY_V2. }.
   8280  * However, sysctl(8) never checked for nodes under { CTL_NET, PF_KEY_V2 };
   8281  * and in any case the part of our sysctl namespace used for dumping the
   8282  * SPD and SA database  *HAS* to be compatible with the KAME sysctl
   8283  * namespace, for API reasons.
   8284  *
   8285  * Pending a consensus on the right way  to fix this, add a level of
   8286  * indirection in how we number the `native' FAST_IPSEC key nodes;
   8287  * and (as requested by Andrew Brown)  move registration of the
   8288  * KAME-compatible names  to a separate function.
   8289  */
   8290 #if 0
   8291 #  define FAST_IPSEC_PFKEY PF_KEY_V2
   8292 # define FAST_IPSEC_PFKEY_NAME "keyv2"
   8293 #else
   8294 #  define FAST_IPSEC_PFKEY PF_KEY
   8295 # define FAST_IPSEC_PFKEY_NAME "key"
   8296 #endif
   8297 
   8298 static int
   8299 sysctl_net_key_stats(SYSCTLFN_ARGS)
   8300 {
   8301 
   8302 	return (NETSTAT_SYSCTL(pfkeystat_percpu, PFKEY_NSTATS));
   8303 }
   8304 
   8305 SYSCTL_SETUP(sysctl_net_keyv2_setup, "sysctl net.keyv2 subtree setup")
   8306 {
   8307 
   8308 	sysctl_createv(clog, 0, NULL, NULL,
   8309 		       CTLFLAG_PERMANENT,
   8310 		       CTLTYPE_NODE, "net", NULL,
   8311 		       NULL, 0, NULL, 0,
   8312 		       CTL_NET, CTL_EOL);
   8313 	sysctl_createv(clog, 0, NULL, NULL,
   8314 		       CTLFLAG_PERMANENT,
   8315 		       CTLTYPE_NODE, FAST_IPSEC_PFKEY_NAME, NULL,
   8316 		       NULL, 0, NULL, 0,
   8317 		       CTL_NET, FAST_IPSEC_PFKEY, CTL_EOL);
   8318 
   8319 	sysctl_createv(clog, 0, NULL, NULL,
   8320 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8321 		       CTLTYPE_INT, "debug", NULL,
   8322 		       NULL, 0, &key_debug_level, 0,
   8323 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_DEBUG_LEVEL, CTL_EOL);
   8324 	sysctl_createv(clog, 0, NULL, NULL,
   8325 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8326 		       CTLTYPE_INT, "spi_try", NULL,
   8327 		       NULL, 0, &key_spi_trycnt, 0,
   8328 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_TRY, CTL_EOL);
   8329 	sysctl_createv(clog, 0, NULL, NULL,
   8330 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8331 		       CTLTYPE_INT, "spi_min_value", NULL,
   8332 		       NULL, 0, &key_spi_minval, 0,
   8333 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_MIN_VALUE, CTL_EOL);
   8334 	sysctl_createv(clog, 0, NULL, NULL,
   8335 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8336 		       CTLTYPE_INT, "spi_max_value", NULL,
   8337 		       NULL, 0, &key_spi_maxval, 0,
   8338 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_MAX_VALUE, CTL_EOL);
   8339 	sysctl_createv(clog, 0, NULL, NULL,
   8340 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8341 		       CTLTYPE_INT, "random_int", NULL,
   8342 		       NULL, 0, &key_int_random, 0,
   8343 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_RANDOM_INT, CTL_EOL);
   8344 	sysctl_createv(clog, 0, NULL, NULL,
   8345 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8346 		       CTLTYPE_INT, "larval_lifetime", NULL,
   8347 		       NULL, 0, &key_larval_lifetime, 0,
   8348 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_LARVAL_LIFETIME, CTL_EOL);
   8349 	sysctl_createv(clog, 0, NULL, NULL,
   8350 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8351 		       CTLTYPE_INT, "blockacq_count", NULL,
   8352 		       NULL, 0, &key_blockacq_count, 0,
   8353 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_BLOCKACQ_COUNT, CTL_EOL);
   8354 	sysctl_createv(clog, 0, NULL, NULL,
   8355 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8356 		       CTLTYPE_INT, "blockacq_lifetime", NULL,
   8357 		       NULL, 0, &key_blockacq_lifetime, 0,
   8358 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_BLOCKACQ_LIFETIME, CTL_EOL);
   8359 	sysctl_createv(clog, 0, NULL, NULL,
   8360 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8361 		       CTLTYPE_INT, "esp_keymin", NULL,
   8362 		       NULL, 0, &ipsec_esp_keymin, 0,
   8363 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_ESP_KEYMIN, CTL_EOL);
   8364 	sysctl_createv(clog, 0, NULL, NULL,
   8365 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8366 		       CTLTYPE_INT, "prefered_oldsa", NULL,
   8367 		       NULL, 0, &key_prefered_oldsa, 0,
   8368 		       CTL_NET, PF_KEY, KEYCTL_PREFERED_OLDSA, CTL_EOL);
   8369 	sysctl_createv(clog, 0, NULL, NULL,
   8370 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8371 		       CTLTYPE_INT, "esp_auth", NULL,
   8372 		       NULL, 0, &ipsec_esp_auth, 0,
   8373 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_ESP_AUTH, CTL_EOL);
   8374 	sysctl_createv(clog, 0, NULL, NULL,
   8375 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8376 		       CTLTYPE_INT, "ah_keymin", NULL,
   8377 		       NULL, 0, &ipsec_ah_keymin, 0,
   8378 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_AH_KEYMIN, CTL_EOL);
   8379 	sysctl_createv(clog, 0, NULL, NULL,
   8380 		       CTLFLAG_PERMANENT,
   8381 		       CTLTYPE_STRUCT, "stats",
   8382 		       SYSCTL_DESCR("PF_KEY statistics"),
   8383 		       sysctl_net_key_stats, 0, NULL, 0,
   8384 		       CTL_NET, FAST_IPSEC_PFKEY, CTL_CREATE, CTL_EOL);
   8385 }
   8386 
   8387 /*
   8388  * Register sysctl names used by setkey(8). For historical reasons,
   8389  * and to share a single API, these names appear under { CTL_NET, PF_KEY }
   8390  * for both FAST_IPSEC and KAME IPSEC.
   8391  */
   8392 SYSCTL_SETUP(sysctl_net_key_compat_setup, "sysctl net.key subtree setup for FAST_IPSEC")
   8393 {
   8394 
   8395 	/* Make sure net.key exists before we register nodes underneath it. */
   8396 	sysctl_createv(clog, 0, NULL, NULL,
   8397 		       CTLFLAG_PERMANENT,
   8398 		       CTLTYPE_NODE, "net", NULL,
   8399 		       NULL, 0, NULL, 0,
   8400 		       CTL_NET, CTL_EOL);
   8401 	sysctl_createv(clog, 0, NULL, NULL,
   8402 		       CTLFLAG_PERMANENT,
   8403 		       CTLTYPE_NODE, "key", NULL,
   8404 		       NULL, 0, NULL, 0,
   8405 		       CTL_NET, PF_KEY, CTL_EOL);
   8406 
   8407 	/* Register the net.key.dump{sa,sp} nodes used by setkey(8). */
   8408 	sysctl_createv(clog, 0, NULL, NULL,
   8409 		       CTLFLAG_PERMANENT,
   8410 		       CTLTYPE_STRUCT, "dumpsa", NULL,
   8411 		       sysctl_net_key_dumpsa, 0, NULL, 0,
   8412 		       CTL_NET, PF_KEY, KEYCTL_DUMPSA, CTL_EOL);
   8413 	sysctl_createv(clog, 0, NULL, NULL,
   8414 		       CTLFLAG_PERMANENT,
   8415 		       CTLTYPE_STRUCT, "dumpsp", NULL,
   8416 		       sysctl_net_key_dumpsp, 0, NULL, 0,
   8417 		       CTL_NET, PF_KEY, KEYCTL_DUMPSP, CTL_EOL);
   8418 }
   8419