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