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