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