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