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