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