Home | History | Annotate | Line # | Download | only in netipsec
key.c revision 1.95
      1 /*	$NetBSD: key.c,v 1.95 2016/03/05 20:26:07 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.95 2016/03/05 20:26:07 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 static in_port_t
   4195 key_getport(const void *v)
   4196 {
   4197 	const struct sockaddr *sa = v;
   4198 	switch (sa->sa_family) {
   4199 	case AF_INET:
   4200 		return ((const struct sockaddr_in *)v)->sin_port;
   4201 	case AF_INET6:
   4202 		return ((const struct sockaddr_in6 *)v)->sin6_port;
   4203 	default:
   4204 		return 0;
   4205 	}
   4206 }
   4207 /*
   4208  * compare two secasindex structure.
   4209  * flag can specify to compare 2 saidxes.
   4210  * compare two secasindex structure without both mode and reqid.
   4211  * don't compare port.
   4212  * IN:
   4213  *      saidx0: source, it can be in SAD.
   4214  *      saidx1: object.
   4215  * OUT:
   4216  *      1 : equal
   4217  *      0 : not equal
   4218  */
   4219 static int
   4220 key_cmpsaidx(
   4221 	const struct secasindex *saidx0,
   4222 	const struct secasindex *saidx1,
   4223 	int flag)
   4224 {
   4225 	int chkport = 0;
   4226 	const struct sockaddr *sa0src, *sa0dst, *sa1src, *sa1dst;
   4227 
   4228 	/* sanity */
   4229 	if (saidx0 == NULL && saidx1 == NULL)
   4230 		return 1;
   4231 
   4232 	if (saidx0 == NULL || saidx1 == NULL)
   4233 		return 0;
   4234 
   4235 	if (saidx0->proto != saidx1->proto)
   4236 		return 0;
   4237 
   4238 	if (flag == CMP_EXACTLY) {
   4239 		if (saidx0->mode != saidx1->mode)
   4240 			return 0;
   4241 		if (saidx0->reqid != saidx1->reqid)
   4242 			return 0;
   4243 		if (memcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
   4244 		    memcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
   4245 			return 0;
   4246 	} else {
   4247 
   4248 		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
   4249 		if (flag == CMP_MODE_REQID
   4250 		  ||flag == CMP_REQID) {
   4251 			/*
   4252 			 * If reqid of SPD is non-zero, unique SA is required.
   4253 			 * The result must be of same reqid in this case.
   4254 			 */
   4255 			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
   4256 				return 0;
   4257 		}
   4258 
   4259 		if (flag == CMP_MODE_REQID) {
   4260 			if (saidx0->mode != IPSEC_MODE_ANY
   4261 			 && saidx0->mode != saidx1->mode)
   4262 				return 0;
   4263 		}
   4264 
   4265 
   4266 		sa0src = &saidx0->src.sa;
   4267 		sa0dst = &saidx0->dst.sa;
   4268 		sa1src = &saidx1->src.sa;
   4269 		sa1dst = &saidx1->dst.sa;
   4270 		/*
   4271 		 * If NAT-T is enabled, check ports for tunnel mode.
   4272 		 * Don't do it for transport mode, as there is no
   4273 		 * port information available in the SP.
   4274 		 * Also don't check ports if they are set to zero
   4275 		 * in the SPD: This means we have a non-generated
   4276 		 * SPD which can't know UDP ports.
   4277 		 */
   4278 		if (saidx1->mode == IPSEC_MODE_TUNNEL) {
   4279 			chkport = key_getport(sa0src) && key_getport(sa0dst) &&
   4280 			    key_getport(sa1src) && key_getport(sa1dst);
   4281 		}
   4282 
   4283 		if (key_sockaddrcmp(sa0src, sa1src, chkport) != 0) {
   4284 			return 0;
   4285 		}
   4286 		if (key_sockaddrcmp(sa0dst, sa1dst, chkport) != 0) {
   4287 			return 0;
   4288 		}
   4289 	}
   4290 
   4291 	return 1;
   4292 }
   4293 
   4294 /*
   4295  * compare two secindex structure exactly.
   4296  * IN:
   4297  *	spidx0: source, it is often in SPD.
   4298  *	spidx1: object, it is often from PFKEY message.
   4299  * OUT:
   4300  *	1 : equal
   4301  *	0 : not equal
   4302  */
   4303 int
   4304 key_cmpspidx_exactly(
   4305 	const struct secpolicyindex *spidx0,
   4306 	const struct secpolicyindex *spidx1)
   4307 {
   4308 	/* sanity */
   4309 	if (spidx0 == NULL && spidx1 == NULL)
   4310 		return 1;
   4311 
   4312 	if (spidx0 == NULL || spidx1 == NULL)
   4313 		return 0;
   4314 
   4315 	if (spidx0->prefs != spidx1->prefs
   4316 	 || spidx0->prefd != spidx1->prefd
   4317 	 || spidx0->ul_proto != spidx1->ul_proto)
   4318 		return 0;
   4319 
   4320 	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
   4321 	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
   4322 }
   4323 
   4324 /*
   4325  * compare two secindex structure with mask.
   4326  * IN:
   4327  *	spidx0: source, it is often in SPD.
   4328  *	spidx1: object, it is often from IP header.
   4329  * OUT:
   4330  *	1 : equal
   4331  *	0 : not equal
   4332  */
   4333 int
   4334 key_cmpspidx_withmask(
   4335 	const struct secpolicyindex *spidx0,
   4336 	const struct secpolicyindex *spidx1)
   4337 {
   4338 	/* sanity */
   4339 	if (spidx0 == NULL && spidx1 == NULL)
   4340 		return 1;
   4341 
   4342 	if (spidx0 == NULL || spidx1 == NULL)
   4343 		return 0;
   4344 
   4345 	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
   4346 	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
   4347 	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
   4348 	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
   4349 		return 0;
   4350 
   4351 	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
   4352 	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
   4353 	 && spidx0->ul_proto != spidx1->ul_proto)
   4354 		return 0;
   4355 
   4356 	switch (spidx0->src.sa.sa_family) {
   4357 	case AF_INET:
   4358 		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
   4359 		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
   4360 			return 0;
   4361 		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
   4362 		    &spidx1->src.sin.sin_addr, spidx0->prefs))
   4363 			return 0;
   4364 		break;
   4365 	case AF_INET6:
   4366 		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
   4367 		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
   4368 			return 0;
   4369 		/*
   4370 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4371 		 * as a wildcard scope, which matches any scope zone ID.
   4372 		 */
   4373 		if (spidx0->src.sin6.sin6_scope_id &&
   4374 		    spidx1->src.sin6.sin6_scope_id &&
   4375 		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
   4376 			return 0;
   4377 		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
   4378 		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
   4379 			return 0;
   4380 		break;
   4381 	default:
   4382 		/* XXX */
   4383 		if (memcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
   4384 			return 0;
   4385 		break;
   4386 	}
   4387 
   4388 	switch (spidx0->dst.sa.sa_family) {
   4389 	case AF_INET:
   4390 		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
   4391 		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
   4392 			return 0;
   4393 		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
   4394 		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
   4395 			return 0;
   4396 		break;
   4397 	case AF_INET6:
   4398 		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
   4399 		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
   4400 			return 0;
   4401 		/*
   4402 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4403 		 * as a wildcard scope, which matches any scope zone ID.
   4404 		 */
   4405 		if (spidx0->src.sin6.sin6_scope_id &&
   4406 		    spidx1->src.sin6.sin6_scope_id &&
   4407 		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
   4408 			return 0;
   4409 		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
   4410 		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
   4411 			return 0;
   4412 		break;
   4413 	default:
   4414 		/* XXX */
   4415 		if (memcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
   4416 			return 0;
   4417 		break;
   4418 	}
   4419 
   4420 	/* XXX Do we check other field ?  e.g. flowinfo */
   4421 
   4422 	return 1;
   4423 }
   4424 
   4425 /* returns 0 on match */
   4426 static int
   4427 key_sockaddrcmp(
   4428 	const struct sockaddr *sa1,
   4429 	const struct sockaddr *sa2,
   4430 	int port)
   4431 {
   4432 #ifdef satosin
   4433 #undef satosin
   4434 #endif
   4435 #define satosin(s) ((const struct sockaddr_in *)s)
   4436 #ifdef satosin6
   4437 #undef satosin6
   4438 #endif
   4439 #define satosin6(s) ((const struct sockaddr_in6 *)s)
   4440 	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len) {
   4441 		KEYDEBUG(KEYDEBUG_MATCH,
   4442 		    printf("fam/len fail %d != %d || %d != %d\n",
   4443 			sa1->sa_family, sa2->sa_family, sa1->sa_len,
   4444 			sa2->sa_len));
   4445 		return 1;
   4446 	}
   4447 
   4448 	switch (sa1->sa_family) {
   4449 	case AF_INET:
   4450 		if (sa1->sa_len != sizeof(struct sockaddr_in)) {
   4451 			KEYDEBUG(KEYDEBUG_MATCH,
   4452 			    printf("len fail %d != %zu\n",
   4453 				sa1->sa_len, sizeof(struct sockaddr_in)));
   4454 			return 1;
   4455 		}
   4456 		if (satosin(sa1)->sin_addr.s_addr !=
   4457 		    satosin(sa2)->sin_addr.s_addr) {
   4458 			KEYDEBUG(KEYDEBUG_MATCH,
   4459 			    printf("addr fail %#x != %#x\n",
   4460 				satosin(sa1)->sin_addr.s_addr,
   4461 				satosin(sa2)->sin_addr.s_addr));
   4462 			return 1;
   4463 		}
   4464 		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port) {
   4465 			KEYDEBUG(KEYDEBUG_MATCH,
   4466 			    printf("port fail %d != %d\n",
   4467 				satosin(sa1)->sin_port,
   4468 				satosin(sa2)->sin_port));
   4469 			return 1;
   4470 		}
   4471 		KEYDEBUG(KEYDEBUG_MATCH,
   4472 		    printf("addr success %#x[%d] == %#x[%d]\n",
   4473 			satosin(sa1)->sin_addr.s_addr,
   4474 			satosin(sa1)->sin_port,
   4475 			satosin(sa2)->sin_addr.s_addr,
   4476 			satosin(sa2)->sin_port));
   4477 		break;
   4478 	case AF_INET6:
   4479 		if (sa1->sa_len != sizeof(struct sockaddr_in6))
   4480 			return 1;	/*EINVAL*/
   4481 		if (satosin6(sa1)->sin6_scope_id !=
   4482 		    satosin6(sa2)->sin6_scope_id) {
   4483 			return 1;
   4484 		}
   4485 		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
   4486 		    &satosin6(sa2)->sin6_addr)) {
   4487 			return 1;
   4488 		}
   4489 		if (port &&
   4490 		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
   4491 			return 1;
   4492 		}
   4493 		break;
   4494 	default:
   4495 		if (memcmp(sa1, sa2, sa1->sa_len) != 0)
   4496 			return 1;
   4497 		break;
   4498 	}
   4499 
   4500 	return 0;
   4501 #undef satosin
   4502 #undef satosin6
   4503 }
   4504 
   4505 /*
   4506  * compare two buffers with mask.
   4507  * IN:
   4508  *	addr1: source
   4509  *	addr2: object
   4510  *	bits:  Number of bits to compare
   4511  * OUT:
   4512  *	1 : equal
   4513  *	0 : not equal
   4514  */
   4515 static int
   4516 key_bbcmp(const void *a1, const void *a2, u_int bits)
   4517 {
   4518 	const unsigned char *p1 = a1;
   4519 	const unsigned char *p2 = a2;
   4520 
   4521 	/* XXX: This could be considerably faster if we compare a word
   4522 	 * at a time, but it is complicated on LSB Endian machines */
   4523 
   4524 	/* Handle null pointers */
   4525 	if (p1 == NULL || p2 == NULL)
   4526 		return (p1 == p2);
   4527 
   4528 	while (bits >= 8) {
   4529 		if (*p1++ != *p2++)
   4530 			return 0;
   4531 		bits -= 8;
   4532 	}
   4533 
   4534 	if (bits > 0) {
   4535 		u_int8_t mask = ~((1<<(8-bits))-1);
   4536 		if ((*p1 & mask) != (*p2 & mask))
   4537 			return 0;
   4538 	}
   4539 	return 1;	/* Match! */
   4540 }
   4541 
   4542 /*
   4543  * time handler.
   4544  * scanning SPD and SAD to check status for each entries,
   4545  * and do to remove or to expire.
   4546  */
   4547 void
   4548 key_timehandler(void* arg)
   4549 {
   4550 	u_int dir;
   4551 	int s;
   4552 	time_t now = time_uptime;
   4553 
   4554 	s = splsoftnet();	/*called from softclock()*/
   4555 	mutex_enter(softnet_lock);
   4556 
   4557 	/* SPD */
   4558     {
   4559 	struct secpolicy *sp, *nextsp;
   4560 
   4561 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   4562 		for (sp = LIST_FIRST(&sptree[dir]);
   4563 		     sp != NULL;
   4564 		     sp = nextsp) {
   4565 
   4566 			nextsp = LIST_NEXT(sp, chain);
   4567 
   4568 			if (sp->state == IPSEC_SPSTATE_DEAD) {
   4569 				key_sp_unlink(sp);	/*XXX*/
   4570 
   4571 				/* 'sp' dead; continue transfers to
   4572 				 * 'sp = nextsp'
   4573 				 */
   4574 				continue;
   4575 			}
   4576 
   4577 			if (sp->lifetime == 0 && sp->validtime == 0)
   4578 				continue;
   4579 
   4580 			/* the deletion will occur next time */
   4581 			if ((sp->lifetime && now - sp->created > sp->lifetime)
   4582 			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
   4583 			  	key_sp_dead(sp);
   4584 				key_spdexpire(sp);
   4585 				continue;
   4586 			}
   4587 		}
   4588 	}
   4589     }
   4590 
   4591 	/* SAD */
   4592     {
   4593 	struct secashead *sah, *nextsah;
   4594 	struct secasvar *sav, *nextsav;
   4595 
   4596 	for (sah = LIST_FIRST(&sahtree);
   4597 	     sah != NULL;
   4598 	     sah = nextsah) {
   4599 
   4600 		nextsah = LIST_NEXT(sah, chain);
   4601 
   4602 		/* if sah has been dead, then delete it and process next sah. */
   4603 		if (sah->state == SADB_SASTATE_DEAD) {
   4604 			key_delsah(sah);
   4605 			continue;
   4606 		}
   4607 
   4608 		/* if LARVAL entry doesn't become MATURE, delete it. */
   4609 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
   4610 		     sav != NULL;
   4611 		     sav = nextsav) {
   4612 
   4613 			nextsav = LIST_NEXT(sav, chain);
   4614 
   4615 			if (now - sav->created > key_larval_lifetime) {
   4616 				KEY_FREESAV(&sav);
   4617 			}
   4618 		}
   4619 
   4620 		/*
   4621 		 * check MATURE entry to start to send expire message
   4622 		 * whether or not.
   4623 		 */
   4624 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
   4625 		     sav != NULL;
   4626 		     sav = nextsav) {
   4627 
   4628 			nextsav = LIST_NEXT(sav, chain);
   4629 
   4630 			/* we don't need to check. */
   4631 			if (sav->lft_s == NULL)
   4632 				continue;
   4633 
   4634 			/* sanity check */
   4635 			if (sav->lft_c == NULL) {
   4636 				ipseclog((LOG_DEBUG,"key_timehandler: "
   4637 					"There is no CURRENT time, why?\n"));
   4638 				continue;
   4639 			}
   4640 
   4641 			/* check SOFT lifetime */
   4642 			if (sav->lft_s->sadb_lifetime_addtime != 0
   4643 			 && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4644 				/*
   4645 				 * check SA to be used whether or not.
   4646 				 * when SA hasn't been used, delete it.
   4647 				 */
   4648 				if (sav->lft_c->sadb_lifetime_usetime == 0) {
   4649 					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4650 					KEY_FREESAV(&sav);
   4651 				} else {
   4652 					key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4653 					/*
   4654 					 * XXX If we keep to send expire
   4655 					 * message in the status of
   4656 					 * DYING. Do remove below code.
   4657 					 */
   4658 					key_expire(sav);
   4659 				}
   4660 			}
   4661 			/* check SOFT lifetime by bytes */
   4662 			/*
   4663 			 * XXX I don't know the way to delete this SA
   4664 			 * when new SA is installed.  Caution when it's
   4665 			 * installed too big lifetime by time.
   4666 			 */
   4667 			else if (sav->lft_s->sadb_lifetime_bytes != 0
   4668 			      && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
   4669 
   4670 				key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4671 				/*
   4672 				 * XXX If we keep to send expire
   4673 				 * message in the status of
   4674 				 * DYING. Do remove below code.
   4675 				 */
   4676 				key_expire(sav);
   4677 			}
   4678 		}
   4679 
   4680 		/* check DYING entry to change status to DEAD. */
   4681 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
   4682 		     sav != NULL;
   4683 		     sav = nextsav) {
   4684 
   4685 			nextsav = LIST_NEXT(sav, chain);
   4686 
   4687 			/* we don't need to check. */
   4688 			if (sav->lft_h == NULL)
   4689 				continue;
   4690 
   4691 			/* sanity check */
   4692 			if (sav->lft_c == NULL) {
   4693 				ipseclog((LOG_DEBUG, "key_timehandler: "
   4694 					"There is no CURRENT time, why?\n"));
   4695 				continue;
   4696 			}
   4697 
   4698 			if (sav->lft_h->sadb_lifetime_addtime != 0
   4699 			 && now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
   4700 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4701 				KEY_FREESAV(&sav);
   4702 			}
   4703 #if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
   4704 			else if (sav->lft_s != NULL
   4705 			      && sav->lft_s->sadb_lifetime_addtime != 0
   4706 			      && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4707 				/*
   4708 				 * XXX: should be checked to be
   4709 				 * installed the valid SA.
   4710 				 */
   4711 
   4712 				/*
   4713 				 * If there is no SA then sending
   4714 				 * expire message.
   4715 				 */
   4716 				key_expire(sav);
   4717 			}
   4718 #endif
   4719 			/* check HARD lifetime by bytes */
   4720 			else if (sav->lft_h->sadb_lifetime_bytes != 0
   4721 			      && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
   4722 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4723 				KEY_FREESAV(&sav);
   4724 			}
   4725 		}
   4726 
   4727 		/* delete entry in DEAD */
   4728 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
   4729 		     sav != NULL;
   4730 		     sav = nextsav) {
   4731 
   4732 			nextsav = LIST_NEXT(sav, chain);
   4733 
   4734 			/* sanity check */
   4735 			if (sav->state != SADB_SASTATE_DEAD) {
   4736 				ipseclog((LOG_DEBUG, "key_timehandler: "
   4737 					"invalid sav->state "
   4738 					"(queue: %d SA: %d): "
   4739 					"kill it anyway\n",
   4740 					SADB_SASTATE_DEAD, sav->state));
   4741 			}
   4742 
   4743 			/*
   4744 			 * do not call key_freesav() here.
   4745 			 * sav should already be freed, and sav->refcnt
   4746 			 * shows other references to sav
   4747 			 * (such as from SPD).
   4748 			 */
   4749 		}
   4750 	}
   4751     }
   4752 
   4753 #ifndef IPSEC_NONBLOCK_ACQUIRE
   4754 	/* ACQ tree */
   4755     {
   4756 	struct secacq *acq, *nextacq;
   4757 
   4758 	for (acq = LIST_FIRST(&acqtree);
   4759 	     acq != NULL;
   4760 	     acq = nextacq) {
   4761 
   4762 		nextacq = LIST_NEXT(acq, chain);
   4763 
   4764 		if (now - acq->created > key_blockacq_lifetime
   4765 		 && __LIST_CHAINED(acq)) {
   4766 			LIST_REMOVE(acq, chain);
   4767 			KFREE(acq);
   4768 		}
   4769 	}
   4770     }
   4771 #endif
   4772 
   4773 	/* SP ACQ tree */
   4774     {
   4775 	struct secspacq *acq, *nextacq;
   4776 
   4777 	for (acq = LIST_FIRST(&spacqtree);
   4778 	     acq != NULL;
   4779 	     acq = nextacq) {
   4780 
   4781 		nextacq = LIST_NEXT(acq, chain);
   4782 
   4783 		if (now - acq->created > key_blockacq_lifetime
   4784 		 && __LIST_CHAINED(acq)) {
   4785 			LIST_REMOVE(acq, chain);
   4786 			KFREE(acq);
   4787 		}
   4788 	}
   4789     }
   4790 
   4791 #ifndef IPSEC_DEBUG2
   4792 	/* do exchange to tick time !! */
   4793 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   4794 #endif /* IPSEC_DEBUG2 */
   4795 
   4796 	mutex_exit(softnet_lock);
   4797 	splx(s);
   4798 	return;
   4799 }
   4800 
   4801 u_long
   4802 key_random(void)
   4803 {
   4804 	u_long value;
   4805 
   4806 	key_randomfill(&value, sizeof(value));
   4807 	return value;
   4808 }
   4809 
   4810 void
   4811 key_randomfill(void *p, size_t l)
   4812 {
   4813 
   4814 	cprng_fast(p, l);
   4815 }
   4816 
   4817 /*
   4818  * map SADB_SATYPE_* to IPPROTO_*.
   4819  * if satype == SADB_SATYPE then satype is mapped to ~0.
   4820  * OUT:
   4821  *	0: invalid satype.
   4822  */
   4823 static u_int16_t
   4824 key_satype2proto(u_int8_t satype)
   4825 {
   4826 	switch (satype) {
   4827 	case SADB_SATYPE_UNSPEC:
   4828 		return IPSEC_PROTO_ANY;
   4829 	case SADB_SATYPE_AH:
   4830 		return IPPROTO_AH;
   4831 	case SADB_SATYPE_ESP:
   4832 		return IPPROTO_ESP;
   4833 	case SADB_X_SATYPE_IPCOMP:
   4834 		return IPPROTO_IPCOMP;
   4835 	case SADB_X_SATYPE_TCPSIGNATURE:
   4836 		return IPPROTO_TCP;
   4837 	default:
   4838 		return 0;
   4839 	}
   4840 	/* NOTREACHED */
   4841 }
   4842 
   4843 /*
   4844  * map IPPROTO_* to SADB_SATYPE_*
   4845  * OUT:
   4846  *	0: invalid protocol type.
   4847  */
   4848 static u_int8_t
   4849 key_proto2satype(u_int16_t proto)
   4850 {
   4851 	switch (proto) {
   4852 	case IPPROTO_AH:
   4853 		return SADB_SATYPE_AH;
   4854 	case IPPROTO_ESP:
   4855 		return SADB_SATYPE_ESP;
   4856 	case IPPROTO_IPCOMP:
   4857 		return SADB_X_SATYPE_IPCOMP;
   4858 	case IPPROTO_TCP:
   4859 		return SADB_X_SATYPE_TCPSIGNATURE;
   4860 	default:
   4861 		return 0;
   4862 	}
   4863 	/* NOTREACHED */
   4864 }
   4865 
   4866 static int
   4867 key_setsecasidx(int proto, int mode, int reqid,
   4868 	        const struct sadb_address * src,
   4869 	 	const struct sadb_address * dst,
   4870 		struct secasindex * saidx)
   4871 {
   4872 	const union sockaddr_union * src_u =
   4873 		(const union sockaddr_union *) src;
   4874 	const union sockaddr_union * dst_u =
   4875 		(const union sockaddr_union *) dst;
   4876 
   4877 	/* sa len safety check */
   4878 	if (key_checksalen(src_u) != 0)
   4879 		return -1;
   4880 	if (key_checksalen(dst_u) != 0)
   4881 		return -1;
   4882 
   4883 	memset(saidx, 0, sizeof(*saidx));
   4884 	saidx->proto = proto;
   4885 	saidx->mode = mode;
   4886 	saidx->reqid = reqid;
   4887 	memcpy(&saidx->src, src_u, src_u->sa.sa_len);
   4888 	memcpy(&saidx->dst, dst_u, dst_u->sa.sa_len);
   4889 
   4890 	key_porttosaddr(&((saidx)->src),0);
   4891 	key_porttosaddr(&((saidx)->dst),0);
   4892 	return 0;
   4893 }
   4894 
   4895 /* %%% PF_KEY */
   4896 /*
   4897  * SADB_GETSPI processing is to receive
   4898  *	<base, (SA2), src address, dst address, (SPI range)>
   4899  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
   4900  * tree with the status of LARVAL, and send
   4901  *	<base, SA(*), address(SD)>
   4902  * to the IKMPd.
   4903  *
   4904  * IN:	mhp: pointer to the pointer to each header.
   4905  * OUT:	NULL if fail.
   4906  *	other if success, return pointer to the message to send.
   4907  */
   4908 static int
   4909 key_getspi(struct socket *so, struct mbuf *m,
   4910 	   const struct sadb_msghdr *mhp)
   4911 {
   4912 	struct sadb_address *src0, *dst0;
   4913 	struct secasindex saidx;
   4914 	struct secashead *newsah;
   4915 	struct secasvar *newsav;
   4916 	u_int8_t proto;
   4917 	u_int32_t spi;
   4918 	u_int8_t mode;
   4919 	u_int16_t reqid;
   4920 	int error;
   4921 
   4922 	/* sanity check */
   4923 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   4924 		panic("key_getspi: NULL pointer is passed");
   4925 
   4926 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   4927 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   4928 		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
   4929 		return key_senderror(so, m, EINVAL);
   4930 	}
   4931 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   4932 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   4933 		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
   4934 		return key_senderror(so, m, EINVAL);
   4935 	}
   4936 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   4937 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   4938 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   4939 	} else {
   4940 		mode = IPSEC_MODE_ANY;
   4941 		reqid = 0;
   4942 	}
   4943 
   4944 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   4945 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   4946 
   4947 	/* map satype to proto */
   4948 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   4949 		ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
   4950 		return key_senderror(so, m, EINVAL);
   4951 	}
   4952 
   4953 
   4954 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
   4955 				     dst0 + 1, &saidx)) != 0)
   4956 		return key_senderror(so, m, EINVAL);
   4957 
   4958 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   4959 		return key_senderror(so, m, EINVAL);
   4960 
   4961 	/* SPI allocation */
   4962 	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
   4963 	                       &saidx);
   4964 	if (spi == 0)
   4965 		return key_senderror(so, m, EINVAL);
   4966 
   4967 	/* get a SA index */
   4968 	if ((newsah = key_getsah(&saidx)) == NULL) {
   4969 		/* create a new SA index */
   4970 		if ((newsah = key_newsah(&saidx)) == NULL) {
   4971 			ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
   4972 			return key_senderror(so, m, ENOBUFS);
   4973 		}
   4974 	}
   4975 
   4976 	/* get a new SA */
   4977 	/* XXX rewrite */
   4978 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
   4979 	if (newsav == NULL) {
   4980 		/* XXX don't free new SA index allocated in above. */
   4981 		return key_senderror(so, m, error);
   4982 	}
   4983 
   4984 	/* set spi */
   4985 	newsav->spi = htonl(spi);
   4986 
   4987 #ifndef IPSEC_NONBLOCK_ACQUIRE
   4988 	/* delete the entry in acqtree */
   4989 	if (mhp->msg->sadb_msg_seq != 0) {
   4990 		struct secacq *acq;
   4991 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
   4992 			/* reset counter in order to deletion by timehandler. */
   4993 			acq->created = time_uptime;
   4994 			acq->count = 0;
   4995 		}
   4996     	}
   4997 #endif
   4998 
   4999     {
   5000 	struct mbuf *n, *nn;
   5001 	struct sadb_sa *m_sa;
   5002 	struct sadb_msg *newmsg;
   5003 	int off, len;
   5004 
   5005 	/* create new sadb_msg to reply. */
   5006 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
   5007 	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
   5008 	if (len > MCLBYTES)
   5009 		return key_senderror(so, m, ENOBUFS);
   5010 
   5011 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   5012 	if (len > MHLEN) {
   5013 		MCLGET(n, M_DONTWAIT);
   5014 		if ((n->m_flags & M_EXT) == 0) {
   5015 			m_freem(n);
   5016 			n = NULL;
   5017 		}
   5018 	}
   5019 	if (!n)
   5020 		return key_senderror(so, m, ENOBUFS);
   5021 
   5022 	n->m_len = len;
   5023 	n->m_next = NULL;
   5024 	off = 0;
   5025 
   5026 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   5027 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   5028 
   5029 	m_sa = (struct sadb_sa *)(mtod(n, char *) + off);
   5030 	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
   5031 	m_sa->sadb_sa_exttype = SADB_EXT_SA;
   5032 	m_sa->sadb_sa_spi = htonl(spi);
   5033 	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
   5034 
   5035 #ifdef DIAGNOSTIC
   5036 	if (off != len)
   5037 		panic("length inconsistency in key_getspi");
   5038 #endif
   5039 
   5040 	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
   5041 	    SADB_EXT_ADDRESS_DST);
   5042 	if (!n->m_next) {
   5043 		m_freem(n);
   5044 		return key_senderror(so, m, ENOBUFS);
   5045 	}
   5046 
   5047 	if (n->m_len < sizeof(struct sadb_msg)) {
   5048 		n = m_pullup(n, sizeof(struct sadb_msg));
   5049 		if (n == NULL)
   5050 			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   5051 	}
   5052 
   5053 	n->m_pkthdr.len = 0;
   5054 	for (nn = n; nn; nn = nn->m_next)
   5055 		n->m_pkthdr.len += nn->m_len;
   5056 
   5057 	newmsg = mtod(n, struct sadb_msg *);
   5058 	newmsg->sadb_msg_seq = newsav->seq;
   5059 	newmsg->sadb_msg_errno = 0;
   5060 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   5061 
   5062 	m_freem(m);
   5063 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   5064     }
   5065 }
   5066 
   5067 /*
   5068  * allocating new SPI
   5069  * called by key_getspi().
   5070  * OUT:
   5071  *	0:	failure.
   5072  *	others: success.
   5073  */
   5074 static u_int32_t
   5075 key_do_getnewspi(const struct sadb_spirange *spirange,
   5076 		 const struct secasindex *saidx)
   5077 {
   5078 	u_int32_t newspi;
   5079 	u_int32_t spmin, spmax;
   5080 	int count = key_spi_trycnt;
   5081 
   5082 	/* set spi range to allocate */
   5083 	if (spirange != NULL) {
   5084 		spmin = spirange->sadb_spirange_min;
   5085 		spmax = spirange->sadb_spirange_max;
   5086 	} else {
   5087 		spmin = key_spi_minval;
   5088 		spmax = key_spi_maxval;
   5089 	}
   5090 	/* IPCOMP needs 2-byte SPI */
   5091 	if (saidx->proto == IPPROTO_IPCOMP) {
   5092 		u_int32_t t;
   5093 		if (spmin >= 0x10000)
   5094 			spmin = 0xffff;
   5095 		if (spmax >= 0x10000)
   5096 			spmax = 0xffff;
   5097 		if (spmin > spmax) {
   5098 			t = spmin; spmin = spmax; spmax = t;
   5099 		}
   5100 	}
   5101 
   5102 	if (spmin == spmax) {
   5103 		if (key_checkspidup(saidx, htonl(spmin)) != NULL) {
   5104 			ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", spmin));
   5105 			return 0;
   5106 		}
   5107 
   5108 		count--; /* taking one cost. */
   5109 		newspi = spmin;
   5110 
   5111 	} else {
   5112 
   5113 		/* init SPI */
   5114 		newspi = 0;
   5115 
   5116 		/* when requesting to allocate spi ranged */
   5117 		while (count--) {
   5118 			/* generate pseudo-random SPI value ranged. */
   5119 			newspi = spmin + (key_random() % (spmax - spmin + 1));
   5120 
   5121 			if (key_checkspidup(saidx, htonl(newspi)) == NULL)
   5122 				break;
   5123 		}
   5124 
   5125 		if (count == 0 || newspi == 0) {
   5126 			ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
   5127 			return 0;
   5128 		}
   5129 	}
   5130 
   5131 	/* statistics */
   5132 	keystat.getspi_count =
   5133 		(keystat.getspi_count + key_spi_trycnt - count) / 2;
   5134 
   5135 	return newspi;
   5136 }
   5137 
   5138 static int
   5139 key_handle_natt_info(struct secasvar *sav,
   5140       		     const struct sadb_msghdr *mhp)
   5141 {
   5142 	const char *msg = "?" ;
   5143 	struct sadb_x_nat_t_type *type;
   5144 	struct sadb_x_nat_t_port *sport, *dport;
   5145 	struct sadb_address *iaddr, *raddr;
   5146 	struct sadb_x_nat_t_frag *frag;
   5147 
   5148 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] == NULL ||
   5149 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] == NULL ||
   5150 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] == NULL)
   5151 		return 0;
   5152 
   5153 	if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) {
   5154 		msg = "TYPE";
   5155 		goto bad;
   5156 	}
   5157 
   5158 	if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) {
   5159 		msg = "SPORT";
   5160 		goto bad;
   5161 	}
   5162 
   5163 	if (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
   5164 		msg = "DPORT";
   5165 		goto bad;
   5166 	}
   5167 
   5168 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) {
   5169 		ipseclog((LOG_DEBUG,"%s: NAT-T OAi present\n", __func__));
   5170 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr)) {
   5171 			msg = "OAI";
   5172 			goto bad;
   5173 		}
   5174 	}
   5175 
   5176 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
   5177 		ipseclog((LOG_DEBUG,"%s: NAT-T OAr present\n", __func__));
   5178 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
   5179 			msg = "OAR";
   5180 			goto bad;
   5181 		}
   5182 	}
   5183 
   5184 	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
   5185 	    if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
   5186 		    msg = "FRAG";
   5187 		    goto bad;
   5188 	    }
   5189 	}
   5190 
   5191 	type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   5192 	sport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   5193 	dport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   5194 	iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
   5195 	raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
   5196 	frag = (struct sadb_x_nat_t_frag *)mhp->ext[SADB_X_EXT_NAT_T_FRAG];
   5197 
   5198 	ipseclog((LOG_DEBUG, "%s: type %d, sport = %d, dport = %d\n",
   5199 	    __func__, type->sadb_x_nat_t_type_type,
   5200 	    ntohs(sport->sadb_x_nat_t_port_port),
   5201 	    ntohs(dport->sadb_x_nat_t_port_port)));
   5202 
   5203 	sav->natt_type = type->sadb_x_nat_t_type_type;
   5204 	key_porttosaddr(&sav->sah->saidx.src,
   5205 	    sport->sadb_x_nat_t_port_port);
   5206 	key_porttosaddr(&sav->sah->saidx.dst,
   5207 	    dport->sadb_x_nat_t_port_port);
   5208 	if (frag)
   5209 		sav->esp_frag = frag->sadb_x_nat_t_frag_fraglen;
   5210 	else
   5211 		sav->esp_frag = IP_MAXPACKET;
   5212 
   5213 	return 0;
   5214 bad:
   5215 	ipseclog((LOG_DEBUG, "%s: invalid message %s\n", __func__, msg));
   5216 	__USE(msg);
   5217 	return -1;
   5218 }
   5219 
   5220 /* Just update the IPSEC_NAT_T ports if present */
   5221 static int
   5222 key_set_natt_ports(union sockaddr_union *src, union sockaddr_union *dst,
   5223       		     const struct sadb_msghdr *mhp)
   5224 {
   5225 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
   5226 		ipseclog((LOG_DEBUG,"%s: NAT-T OAi present\n", __func__));
   5227 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
   5228 		ipseclog((LOG_DEBUG,"%s: NAT-T OAr present\n", __func__));
   5229 
   5230 	if ((mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL) &&
   5231 	    (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL) &&
   5232 	    (mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL)) {
   5233 		struct sadb_x_nat_t_type *type;
   5234 		struct sadb_x_nat_t_port *sport;
   5235 		struct sadb_x_nat_t_port *dport;
   5236 
   5237 		if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
   5238 		    (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
   5239 		    (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
   5240 			ipseclog((LOG_DEBUG, "%s: invalid message\n",
   5241 			    __func__));
   5242 			return -1;
   5243 		}
   5244 
   5245 		type = (struct sadb_x_nat_t_type *)
   5246 		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   5247 		sport = (struct sadb_x_nat_t_port *)
   5248 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   5249 		dport = (struct sadb_x_nat_t_port *)
   5250 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   5251 
   5252 		key_porttosaddr(src, sport->sadb_x_nat_t_port_port);
   5253 		key_porttosaddr(dst, dport->sadb_x_nat_t_port_port);
   5254 
   5255 		ipseclog((LOG_DEBUG, "%s: type %d, sport = %d, dport = %d\n",
   5256 		    __func__, type->sadb_x_nat_t_type_type,
   5257 		    ntohs(sport->sadb_x_nat_t_port_port),
   5258 		    ntohs(dport->sadb_x_nat_t_port_port)));
   5259 	}
   5260 
   5261 	return 0;
   5262 }
   5263 
   5264 
   5265 /*
   5266  * SADB_UPDATE processing
   5267  * receive
   5268  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5269  *       key(AE), (identity(SD),) (sensitivity)>
   5270  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
   5271  * and send
   5272  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5273  *       (identity(SD),) (sensitivity)>
   5274  * to the ikmpd.
   5275  *
   5276  * m will always be freed.
   5277  */
   5278 static int
   5279 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
   5280 {
   5281 	struct sadb_sa *sa0;
   5282 	struct sadb_address *src0, *dst0;
   5283 	struct secasindex saidx;
   5284 	struct secashead *sah;
   5285 	struct secasvar *sav;
   5286 	u_int16_t proto;
   5287 	u_int8_t mode;
   5288 	u_int16_t reqid;
   5289 	int error;
   5290 
   5291 	/* sanity check */
   5292 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5293 		panic("key_update: NULL pointer is passed");
   5294 
   5295 	/* map satype to proto */
   5296 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5297 		ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
   5298 		return key_senderror(so, m, EINVAL);
   5299 	}
   5300 
   5301 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5302 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5303 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5304 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5305 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5306 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5307 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5308 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5309 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5310 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5311 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5312 		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
   5313 		return key_senderror(so, m, EINVAL);
   5314 	}
   5315 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5316 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5317 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5318 		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
   5319 		return key_senderror(so, m, EINVAL);
   5320 	}
   5321 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5322 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5323 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5324 	} else {
   5325 		mode = IPSEC_MODE_ANY;
   5326 		reqid = 0;
   5327 	}
   5328 	/* XXX boundary checking for other extensions */
   5329 
   5330 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5331 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   5332 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   5333 
   5334 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
   5335 				     dst0 + 1, &saidx)) != 0)
   5336 		return key_senderror(so, m, EINVAL);
   5337 
   5338 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5339 		return key_senderror(so, m, EINVAL);
   5340 
   5341 	/* get a SA header */
   5342 	if ((sah = key_getsah(&saidx)) == NULL) {
   5343 		ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
   5344 		return key_senderror(so, m, ENOENT);
   5345 	}
   5346 
   5347 	/* set spidx if there */
   5348 	/* XXX rewrite */
   5349 	error = key_setident(sah, m, mhp);
   5350 	if (error)
   5351 		return key_senderror(so, m, error);
   5352 
   5353 	/* find a SA with sequence number. */
   5354 #ifdef IPSEC_DOSEQCHECK
   5355 	if (mhp->msg->sadb_msg_seq != 0
   5356 	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
   5357 		ipseclog((LOG_DEBUG,
   5358 		    "key_update: no larval SA with sequence %u exists.\n",
   5359 		    mhp->msg->sadb_msg_seq));
   5360 		return key_senderror(so, m, ENOENT);
   5361 	}
   5362 #else
   5363 	if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
   5364 		ipseclog((LOG_DEBUG,
   5365 		    "key_update: no such a SA found (spi:%u)\n",
   5366 		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
   5367 		return key_senderror(so, m, EINVAL);
   5368 	}
   5369 #endif
   5370 
   5371 	/* validity check */
   5372 	if (sav->sah->saidx.proto != proto) {
   5373 		ipseclog((LOG_DEBUG,
   5374 		    "key_update: protocol mismatched (DB=%u param=%u)\n",
   5375 		    sav->sah->saidx.proto, proto));
   5376 		return key_senderror(so, m, EINVAL);
   5377 	}
   5378 #ifdef IPSEC_DOSEQCHECK
   5379 	if (sav->spi != sa0->sadb_sa_spi) {
   5380 		ipseclog((LOG_DEBUG,
   5381 		    "key_update: SPI mismatched (DB:%u param:%u)\n",
   5382 		    (u_int32_t)ntohl(sav->spi),
   5383 		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
   5384 		return key_senderror(so, m, EINVAL);
   5385 	}
   5386 #endif
   5387 	if (sav->pid != mhp->msg->sadb_msg_pid) {
   5388 		ipseclog((LOG_DEBUG,
   5389 		    "key_update: pid mismatched (DB:%u param:%u)\n",
   5390 		    sav->pid, mhp->msg->sadb_msg_pid));
   5391 		return key_senderror(so, m, EINVAL);
   5392 	}
   5393 
   5394 	/* copy sav values */
   5395 	error = key_setsaval(sav, m, mhp);
   5396 	if (error) {
   5397 		KEY_FREESAV(&sav);
   5398 		return key_senderror(so, m, error);
   5399 	}
   5400 
   5401 	if ((error = key_handle_natt_info(sav,mhp)) != 0)
   5402 		return key_senderror(so, m, EINVAL);
   5403 
   5404 	/* check SA values to be mature. */
   5405 	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
   5406 		KEY_FREESAV(&sav);
   5407 		return key_senderror(so, m, 0);
   5408 	}
   5409 
   5410     {
   5411 	struct mbuf *n;
   5412 
   5413 	/* set msg buf from mhp */
   5414 	n = key_getmsgbuf_x1(m, mhp);
   5415 	if (n == NULL) {
   5416 		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
   5417 		return key_senderror(so, m, ENOBUFS);
   5418 	}
   5419 
   5420 	m_freem(m);
   5421 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5422     }
   5423 }
   5424 
   5425 /*
   5426  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
   5427  * only called by key_update().
   5428  * OUT:
   5429  *	NULL	: not found
   5430  *	others	: found, pointer to a SA.
   5431  */
   5432 #ifdef IPSEC_DOSEQCHECK
   5433 static struct secasvar *
   5434 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
   5435 {
   5436 	struct secasvar *sav;
   5437 	u_int state;
   5438 
   5439 	state = SADB_SASTATE_LARVAL;
   5440 
   5441 	/* search SAD with sequence number ? */
   5442 	LIST_FOREACH(sav, &sah->savtree[state], chain) {
   5443 
   5444 		KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
   5445 
   5446 		if (sav->seq == seq) {
   5447 			SA_ADDREF(sav);
   5448 			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
   5449 				printf("DP %s cause refcnt++:%d SA:%p\n",
   5450 				    __func__, sav->refcnt, sav));
   5451 			return sav;
   5452 		}
   5453 	}
   5454 
   5455 	return NULL;
   5456 }
   5457 #endif
   5458 
   5459 /*
   5460  * SADB_ADD processing
   5461  * add an entry to SA database, when received
   5462  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5463  *       key(AE), (identity(SD),) (sensitivity)>
   5464  * from the ikmpd,
   5465  * and send
   5466  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5467  *       (identity(SD),) (sensitivity)>
   5468  * to the ikmpd.
   5469  *
   5470  * IGNORE identity and sensitivity messages.
   5471  *
   5472  * m will always be freed.
   5473  */
   5474 static int
   5475 key_add(struct socket *so, struct mbuf *m,
   5476 	const struct sadb_msghdr *mhp)
   5477 {
   5478 	struct sadb_sa *sa0;
   5479 	struct sadb_address *src0, *dst0;
   5480 	struct secasindex saidx;
   5481 	struct secashead *newsah;
   5482 	struct secasvar *newsav;
   5483 	u_int16_t proto;
   5484 	u_int8_t mode;
   5485 	u_int16_t reqid;
   5486 	int error;
   5487 
   5488 	/* sanity check */
   5489 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5490 		panic("key_add: NULL pointer is passed");
   5491 
   5492 	/* map satype to proto */
   5493 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5494 		ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
   5495 		return key_senderror(so, m, EINVAL);
   5496 	}
   5497 
   5498 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5499 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5500 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5501 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5502 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5503 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5504 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5505 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5506 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5507 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5508 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5509 		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
   5510 		return key_senderror(so, m, EINVAL);
   5511 	}
   5512 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5513 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5514 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5515 		/* XXX need more */
   5516 		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
   5517 		return key_senderror(so, m, EINVAL);
   5518 	}
   5519 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5520 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5521 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5522 	} else {
   5523 		mode = IPSEC_MODE_ANY;
   5524 		reqid = 0;
   5525 	}
   5526 
   5527 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5528 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   5529 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   5530 
   5531 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
   5532 				     dst0 + 1, &saidx)) != 0)
   5533 		return key_senderror(so, m, EINVAL);
   5534 
   5535 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5536 		return key_senderror(so, m, EINVAL);
   5537 
   5538 	/* get a SA header */
   5539 	if ((newsah = key_getsah(&saidx)) == NULL) {
   5540 		/* create a new SA header */
   5541 		if ((newsah = key_newsah(&saidx)) == NULL) {
   5542 			ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
   5543 			return key_senderror(so, m, ENOBUFS);
   5544 		}
   5545 	}
   5546 
   5547 	/* set spidx if there */
   5548 	/* XXX rewrite */
   5549 	error = key_setident(newsah, m, mhp);
   5550 	if (error) {
   5551 		return key_senderror(so, m, error);
   5552 	}
   5553 
   5554 	/* create new SA entry. */
   5555 	/* We can create new SA only if SPI is differenct. */
   5556 	if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
   5557 		ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
   5558 		return key_senderror(so, m, EEXIST);
   5559 	}
   5560 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
   5561 	if (newsav == NULL) {
   5562 		return key_senderror(so, m, error);
   5563 	}
   5564 
   5565 	if ((error = key_handle_natt_info(newsav, mhp)) != 0)
   5566 		return key_senderror(so, m, EINVAL);
   5567 
   5568 	/* check SA values to be mature. */
   5569 	if ((error = key_mature(newsav)) != 0) {
   5570 		KEY_FREESAV(&newsav);
   5571 		return key_senderror(so, m, error);
   5572 	}
   5573 
   5574 	/*
   5575 	 * don't call key_freesav() here, as we would like to keep the SA
   5576 	 * in the database on success.
   5577 	 */
   5578 
   5579     {
   5580 	struct mbuf *n;
   5581 
   5582 	/* set msg buf from mhp */
   5583 	n = key_getmsgbuf_x1(m, mhp);
   5584 	if (n == NULL) {
   5585 		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
   5586 		return key_senderror(so, m, ENOBUFS);
   5587 	}
   5588 
   5589 	m_freem(m);
   5590 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5591     }
   5592 }
   5593 
   5594 /* m is retained */
   5595 static int
   5596 key_setident(struct secashead *sah, struct mbuf *m,
   5597 	     const struct sadb_msghdr *mhp)
   5598 {
   5599 	const struct sadb_ident *idsrc, *iddst;
   5600 	int idsrclen, iddstlen;
   5601 
   5602 	/* sanity check */
   5603 	if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5604 		panic("key_setident: NULL pointer is passed");
   5605 
   5606 	/* don't make buffer if not there */
   5607 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
   5608 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5609 		sah->idents = NULL;
   5610 		sah->identd = NULL;
   5611 		return 0;
   5612 	}
   5613 
   5614 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
   5615 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5616 		ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
   5617 		return EINVAL;
   5618 	}
   5619 
   5620 	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
   5621 	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
   5622 	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
   5623 	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
   5624 
   5625 	/* validity check */
   5626 	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
   5627 		ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
   5628 		return EINVAL;
   5629 	}
   5630 
   5631 	switch (idsrc->sadb_ident_type) {
   5632 	case SADB_IDENTTYPE_PREFIX:
   5633 	case SADB_IDENTTYPE_FQDN:
   5634 	case SADB_IDENTTYPE_USERFQDN:
   5635 	default:
   5636 		/* XXX do nothing */
   5637 		sah->idents = NULL;
   5638 		sah->identd = NULL;
   5639 	 	return 0;
   5640 	}
   5641 
   5642 	/* make structure */
   5643 	KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
   5644 	if (sah->idents == NULL) {
   5645 		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
   5646 		return ENOBUFS;
   5647 	}
   5648 	KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
   5649 	if (sah->identd == NULL) {
   5650 		KFREE(sah->idents);
   5651 		sah->idents = NULL;
   5652 		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
   5653 		return ENOBUFS;
   5654 	}
   5655 	memcpy(sah->idents, idsrc, idsrclen);
   5656 	memcpy(sah->identd, iddst, iddstlen);
   5657 
   5658 	return 0;
   5659 }
   5660 
   5661 /*
   5662  * m will not be freed on return.
   5663  * it is caller's responsibility to free the result.
   5664  */
   5665 static struct mbuf *
   5666 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
   5667 {
   5668 	struct mbuf *n;
   5669 
   5670 	/* sanity check */
   5671 	if (m == NULL || mhp == NULL || mhp->msg == NULL)
   5672 		panic("key_getmsgbuf_x1: NULL pointer is passed");
   5673 
   5674 	/* create new sadb_msg to reply. */
   5675 	n = key_gather_mbuf(m, mhp, 1, 15, SADB_EXT_RESERVED,
   5676 	    SADB_EXT_SA, SADB_X_EXT_SA2,
   5677 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
   5678 	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
   5679 	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
   5680 	    SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
   5681 	    SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
   5682 	    SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NAT_T_FRAG);
   5683 	if (!n)
   5684 		return NULL;
   5685 
   5686 	if (n->m_len < sizeof(struct sadb_msg)) {
   5687 		n = m_pullup(n, sizeof(struct sadb_msg));
   5688 		if (n == NULL)
   5689 			return NULL;
   5690 	}
   5691 	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
   5692 	mtod(n, struct sadb_msg *)->sadb_msg_len =
   5693 	    PFKEY_UNIT64(n->m_pkthdr.len);
   5694 
   5695 	return n;
   5696 }
   5697 
   5698 static int key_delete_all (struct socket *, struct mbuf *,
   5699 			   const struct sadb_msghdr *, u_int16_t);
   5700 
   5701 /*
   5702  * SADB_DELETE processing
   5703  * receive
   5704  *   <base, SA(*), address(SD)>
   5705  * from the ikmpd, and set SADB_SASTATE_DEAD,
   5706  * and send,
   5707  *   <base, SA(*), address(SD)>
   5708  * to the ikmpd.
   5709  *
   5710  * m will always be freed.
   5711  */
   5712 static int
   5713 key_delete(struct socket *so, struct mbuf *m,
   5714 	   const struct sadb_msghdr *mhp)
   5715 {
   5716 	struct sadb_sa *sa0;
   5717 	struct sadb_address *src0, *dst0;
   5718 	struct secasindex saidx;
   5719 	struct secashead *sah;
   5720 	struct secasvar *sav = NULL;
   5721 	u_int16_t proto;
   5722 	int error;
   5723 
   5724 	/* sanity check */
   5725 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5726 		panic("key_delete: NULL pointer is passed");
   5727 
   5728 	/* map satype to proto */
   5729 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5730 		ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
   5731 		return key_senderror(so, m, EINVAL);
   5732 	}
   5733 
   5734 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5735 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5736 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
   5737 		return key_senderror(so, m, EINVAL);
   5738 	}
   5739 
   5740 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5741 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5742 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
   5743 		return key_senderror(so, m, EINVAL);
   5744 	}
   5745 
   5746 	if (mhp->ext[SADB_EXT_SA] == NULL) {
   5747 		/*
   5748 		 * Caller wants us to delete all non-LARVAL SAs
   5749 		 * that match the src/dst.  This is used during
   5750 		 * IKE INITIAL-CONTACT.
   5751 		 */
   5752 		ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
   5753 		return key_delete_all(so, m, mhp, proto);
   5754 	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
   5755 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
   5756 		return key_senderror(so, m, EINVAL);
   5757 	}
   5758 
   5759 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5760 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   5761 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   5762 
   5763 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   5764 				     dst0 + 1, &saidx)) != 0)
   5765 		return key_senderror(so, m, EINVAL);
   5766 
   5767 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5768 		return key_senderror(so, m, EINVAL);
   5769 
   5770 	/* get a SA header */
   5771 	LIST_FOREACH(sah, &sahtree, chain) {
   5772 		if (sah->state == SADB_SASTATE_DEAD)
   5773 			continue;
   5774 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
   5775 			continue;
   5776 
   5777 		/* get a SA with SPI. */
   5778 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5779 		if (sav)
   5780 			break;
   5781 	}
   5782 	if (sah == NULL) {
   5783 		ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
   5784 		return key_senderror(so, m, ENOENT);
   5785 	}
   5786 
   5787 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5788 	KEY_FREESAV(&sav);
   5789 
   5790     {
   5791 	struct mbuf *n;
   5792 	struct sadb_msg *newmsg;
   5793 
   5794 	/* create new sadb_msg to reply. */
   5795 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
   5796 	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5797 	if (!n)
   5798 		return key_senderror(so, m, ENOBUFS);
   5799 
   5800 	if (n->m_len < sizeof(struct sadb_msg)) {
   5801 		n = m_pullup(n, sizeof(struct sadb_msg));
   5802 		if (n == NULL)
   5803 			return key_senderror(so, m, ENOBUFS);
   5804 	}
   5805 	newmsg = mtod(n, struct sadb_msg *);
   5806 	newmsg->sadb_msg_errno = 0;
   5807 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   5808 
   5809 	m_freem(m);
   5810 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5811     }
   5812 }
   5813 
   5814 /*
   5815  * delete all SAs for src/dst.  Called from key_delete().
   5816  */
   5817 static int
   5818 key_delete_all(struct socket *so, struct mbuf *m,
   5819 	       const struct sadb_msghdr *mhp, u_int16_t proto)
   5820 {
   5821 	struct sadb_address *src0, *dst0;
   5822 	struct secasindex saidx;
   5823 	struct secashead *sah;
   5824 	struct secasvar *sav, *nextsav;
   5825 	u_int stateidx, state;
   5826 	int error;
   5827 
   5828 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   5829 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   5830 
   5831 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   5832 				     dst0 + 1, &saidx)) != 0)
   5833 		return key_senderror(so, m, EINVAL);
   5834 
   5835 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5836 		return key_senderror(so, m, EINVAL);
   5837 
   5838 	LIST_FOREACH(sah, &sahtree, chain) {
   5839 		if (sah->state == SADB_SASTATE_DEAD)
   5840 			continue;
   5841 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
   5842 			continue;
   5843 
   5844 		/* Delete all non-LARVAL SAs. */
   5845 		for (stateidx = 0;
   5846 		     stateidx < _ARRAYLEN(saorder_state_alive);
   5847 		     stateidx++) {
   5848 			state = saorder_state_alive[stateidx];
   5849 			if (state == SADB_SASTATE_LARVAL)
   5850 				continue;
   5851 			for (sav = LIST_FIRST(&sah->savtree[state]);
   5852 			     sav != NULL; sav = nextsav) {
   5853 				nextsav = LIST_NEXT(sav, chain);
   5854 				/* sanity check */
   5855 				if (sav->state != state) {
   5856 					ipseclog((LOG_DEBUG, "key_delete_all: "
   5857 					       "invalid sav->state "
   5858 					       "(queue: %d SA: %d)\n",
   5859 					       state, sav->state));
   5860 					continue;
   5861 				}
   5862 
   5863 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5864 				KEY_FREESAV(&sav);
   5865 			}
   5866 		}
   5867 	}
   5868     {
   5869 	struct mbuf *n;
   5870 	struct sadb_msg *newmsg;
   5871 
   5872 	/* create new sadb_msg to reply. */
   5873 	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
   5874 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5875 	if (!n)
   5876 		return key_senderror(so, m, ENOBUFS);
   5877 
   5878 	if (n->m_len < sizeof(struct sadb_msg)) {
   5879 		n = m_pullup(n, sizeof(struct sadb_msg));
   5880 		if (n == NULL)
   5881 			return key_senderror(so, m, ENOBUFS);
   5882 	}
   5883 	newmsg = mtod(n, struct sadb_msg *);
   5884 	newmsg->sadb_msg_errno = 0;
   5885 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   5886 
   5887 	m_freem(m);
   5888 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5889     }
   5890 }
   5891 
   5892 /*
   5893  * SADB_GET processing
   5894  * receive
   5895  *   <base, SA(*), address(SD)>
   5896  * from the ikmpd, and get a SP and a SA to respond,
   5897  * and send,
   5898  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
   5899  *       (identity(SD),) (sensitivity)>
   5900  * to the ikmpd.
   5901  *
   5902  * m will always be freed.
   5903  */
   5904 static int
   5905 key_get(struct socket *so, struct mbuf *m,
   5906 	const struct sadb_msghdr *mhp)
   5907 {
   5908 	struct sadb_sa *sa0;
   5909 	struct sadb_address *src0, *dst0;
   5910 	struct secasindex saidx;
   5911 	struct secashead *sah;
   5912 	struct secasvar *sav = NULL;
   5913 	u_int16_t proto;
   5914 	int error;
   5915 
   5916 	/* sanity check */
   5917 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5918 		panic("key_get: NULL pointer is passed");
   5919 
   5920 	/* map satype to proto */
   5921 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5922 		ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
   5923 		return key_senderror(so, m, EINVAL);
   5924 	}
   5925 
   5926 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5927 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5928 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5929 		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
   5930 		return key_senderror(so, m, EINVAL);
   5931 	}
   5932 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5933 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5934 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5935 		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
   5936 		return key_senderror(so, m, EINVAL);
   5937 	}
   5938 
   5939 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5940 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   5941 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   5942 
   5943 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   5944 				     dst0 + 1, &saidx)) != 0)
   5945 		return key_senderror(so, m, EINVAL);
   5946 
   5947 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5948 		return key_senderror(so, m, EINVAL);
   5949 
   5950 	/* get a SA header */
   5951 	LIST_FOREACH(sah, &sahtree, chain) {
   5952 		if (sah->state == SADB_SASTATE_DEAD)
   5953 			continue;
   5954 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
   5955 			continue;
   5956 
   5957 		/* get a SA with SPI. */
   5958 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5959 		if (sav)
   5960 			break;
   5961 	}
   5962 	if (sah == NULL) {
   5963 		ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
   5964 		return key_senderror(so, m, ENOENT);
   5965 	}
   5966 
   5967     {
   5968 	struct mbuf *n;
   5969 	u_int8_t satype;
   5970 
   5971 	/* map proto to satype */
   5972 	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
   5973 		ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
   5974 		return key_senderror(so, m, EINVAL);
   5975 	}
   5976 
   5977 	/* create new sadb_msg to reply. */
   5978 	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
   5979 	    mhp->msg->sadb_msg_pid);
   5980 	if (!n)
   5981 		return key_senderror(so, m, ENOBUFS);
   5982 
   5983 	m_freem(m);
   5984 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   5985     }
   5986 }
   5987 
   5988 /* XXX make it sysctl-configurable? */
   5989 static void
   5990 key_getcomb_setlifetime(struct sadb_comb *comb)
   5991 {
   5992 
   5993 	comb->sadb_comb_soft_allocations = 1;
   5994 	comb->sadb_comb_hard_allocations = 1;
   5995 	comb->sadb_comb_soft_bytes = 0;
   5996 	comb->sadb_comb_hard_bytes = 0;
   5997 	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
   5998 	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
   5999 	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
   6000 	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
   6001 }
   6002 
   6003 /*
   6004  * XXX reorder combinations by preference
   6005  * XXX no idea if the user wants ESP authentication or not
   6006  */
   6007 static struct mbuf *
   6008 key_getcomb_esp(void)
   6009 {
   6010 	struct sadb_comb *comb;
   6011 	const struct enc_xform *algo;
   6012 	struct mbuf *result = NULL, *m, *n;
   6013 	int encmin;
   6014 	int i, off, o;
   6015 	int totlen;
   6016 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6017 
   6018 	m = NULL;
   6019 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   6020 		algo = esp_algorithm_lookup(i);
   6021 		if (algo == NULL)
   6022 			continue;
   6023 
   6024 		/* discard algorithms with key size smaller than system min */
   6025 		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
   6026 			continue;
   6027 		if (_BITS(algo->minkey) < ipsec_esp_keymin)
   6028 			encmin = ipsec_esp_keymin;
   6029 		else
   6030 			encmin = _BITS(algo->minkey);
   6031 
   6032 		if (ipsec_esp_auth)
   6033 			m = key_getcomb_ah();
   6034 		else {
   6035 			IPSEC_ASSERT(l <= MLEN,
   6036 				("key_getcomb_esp: l=%u > MLEN=%lu",
   6037 				l, (u_long) MLEN));
   6038 			MGET(m, M_DONTWAIT, MT_DATA);
   6039 			if (m) {
   6040 				M_ALIGN(m, l);
   6041 				m->m_len = l;
   6042 				m->m_next = NULL;
   6043 				memset(mtod(m, void *), 0, m->m_len);
   6044 			}
   6045 		}
   6046 		if (!m)
   6047 			goto fail;
   6048 
   6049 		totlen = 0;
   6050 		for (n = m; n; n = n->m_next)
   6051 			totlen += n->m_len;
   6052 		IPSEC_ASSERT((totlen % l) == 0,
   6053 			("key_getcomb_esp: totlen=%u, l=%u", totlen, l));
   6054 
   6055 		for (off = 0; off < totlen; off += l) {
   6056 			n = m_pulldown(m, off, l, &o);
   6057 			if (!n) {
   6058 				/* m is already freed */
   6059 				goto fail;
   6060 			}
   6061 			comb = (struct sadb_comb *)(mtod(n, char *) + o);
   6062 			memset(comb, 0, sizeof(*comb));
   6063 			key_getcomb_setlifetime(comb);
   6064 			comb->sadb_comb_encrypt = i;
   6065 			comb->sadb_comb_encrypt_minbits = encmin;
   6066 			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
   6067 		}
   6068 
   6069 		if (!result)
   6070 			result = m;
   6071 		else
   6072 			m_cat(result, m);
   6073 	}
   6074 
   6075 	return result;
   6076 
   6077  fail:
   6078 	if (result)
   6079 		m_freem(result);
   6080 	return NULL;
   6081 }
   6082 
   6083 static void
   6084 key_getsizes_ah(const struct auth_hash *ah, int alg,
   6085 	        u_int16_t* ksmin, u_int16_t* ksmax)
   6086 {
   6087 	*ksmin = *ksmax = ah->keysize;
   6088 	if (ah->keysize == 0) {
   6089 		/*
   6090 		 * Transform takes arbitrary key size but algorithm
   6091 		 * key size is restricted.  Enforce this here.
   6092 		 */
   6093 		switch (alg) {
   6094 		case SADB_X_AALG_MD5:	*ksmin = *ksmax = 16; break;
   6095 		case SADB_X_AALG_SHA:	*ksmin = *ksmax = 20; break;
   6096 		case SADB_X_AALG_NULL:	*ksmin = 1; *ksmax = 256; break;
   6097 		default:
   6098 			DPRINTF(("key_getsizes_ah: unknown AH algorithm %u\n",
   6099 				alg));
   6100 			break;
   6101 		}
   6102 	}
   6103 }
   6104 
   6105 /*
   6106  * XXX reorder combinations by preference
   6107  */
   6108 static struct mbuf *
   6109 key_getcomb_ah(void)
   6110 {
   6111 	struct sadb_comb *comb;
   6112 	const struct auth_hash *algo;
   6113 	struct mbuf *m;
   6114 	u_int16_t minkeysize, maxkeysize;
   6115 	int i;
   6116 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6117 
   6118 	m = NULL;
   6119 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   6120 #if 1
   6121 		/* we prefer HMAC algorithms, not old algorithms */
   6122 		if (i != SADB_AALG_SHA1HMAC &&
   6123 		    i != SADB_AALG_MD5HMAC &&
   6124 		    i != SADB_X_AALG_SHA2_256 &&
   6125 		    i != SADB_X_AALG_SHA2_384 &&
   6126 		    i != SADB_X_AALG_SHA2_512)
   6127 			continue;
   6128 #endif
   6129 		algo = ah_algorithm_lookup(i);
   6130 		if (!algo)
   6131 			continue;
   6132 		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
   6133 		/* discard algorithms with key size smaller than system min */
   6134 		if (_BITS(minkeysize) < ipsec_ah_keymin)
   6135 			continue;
   6136 
   6137 		if (!m) {
   6138 			IPSEC_ASSERT(l <= MLEN,
   6139 				("key_getcomb_ah: l=%u > MLEN=%lu",
   6140 				l, (u_long) MLEN));
   6141 			MGET(m, M_DONTWAIT, MT_DATA);
   6142 			if (m) {
   6143 				M_ALIGN(m, l);
   6144 				m->m_len = l;
   6145 				m->m_next = NULL;
   6146 			}
   6147 		} else
   6148 			M_PREPEND(m, l, M_DONTWAIT);
   6149 		if (!m)
   6150 			return NULL;
   6151 
   6152 		comb = mtod(m, struct sadb_comb *);
   6153 		memset(comb, 0, sizeof(*comb));
   6154 		key_getcomb_setlifetime(comb);
   6155 		comb->sadb_comb_auth = i;
   6156 		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
   6157 		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
   6158 	}
   6159 
   6160 	return m;
   6161 }
   6162 
   6163 /*
   6164  * not really an official behavior.  discussed in pf_key (at) inner.net in Sep2000.
   6165  * XXX reorder combinations by preference
   6166  */
   6167 static struct mbuf *
   6168 key_getcomb_ipcomp(void)
   6169 {
   6170 	struct sadb_comb *comb;
   6171 	const struct comp_algo *algo;
   6172 	struct mbuf *m;
   6173 	int i;
   6174 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6175 
   6176 	m = NULL;
   6177 	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
   6178 		algo = ipcomp_algorithm_lookup(i);
   6179 		if (!algo)
   6180 			continue;
   6181 
   6182 		if (!m) {
   6183 			IPSEC_ASSERT(l <= MLEN,
   6184 				("key_getcomb_ipcomp: l=%u > MLEN=%lu",
   6185 				l, (u_long) MLEN));
   6186 			MGET(m, M_DONTWAIT, MT_DATA);
   6187 			if (m) {
   6188 				M_ALIGN(m, l);
   6189 				m->m_len = l;
   6190 				m->m_next = NULL;
   6191 			}
   6192 		} else
   6193 			M_PREPEND(m, l, M_DONTWAIT);
   6194 		if (!m)
   6195 			return NULL;
   6196 
   6197 		comb = mtod(m, struct sadb_comb *);
   6198 		memset(comb, 0, sizeof(*comb));
   6199 		key_getcomb_setlifetime(comb);
   6200 		comb->sadb_comb_encrypt = i;
   6201 		/* what should we set into sadb_comb_*_{min,max}bits? */
   6202 	}
   6203 
   6204 	return m;
   6205 }
   6206 
   6207 /*
   6208  * XXX no way to pass mode (transport/tunnel) to userland
   6209  * XXX replay checking?
   6210  * XXX sysctl interface to ipsec_{ah,esp}_keymin
   6211  */
   6212 static struct mbuf *
   6213 key_getprop(const struct secasindex *saidx)
   6214 {
   6215 	struct sadb_prop *prop;
   6216 	struct mbuf *m, *n;
   6217 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
   6218 	int totlen;
   6219 
   6220 	switch (saidx->proto)  {
   6221 	case IPPROTO_ESP:
   6222 		m = key_getcomb_esp();
   6223 		break;
   6224 	case IPPROTO_AH:
   6225 		m = key_getcomb_ah();
   6226 		break;
   6227 	case IPPROTO_IPCOMP:
   6228 		m = key_getcomb_ipcomp();
   6229 		break;
   6230 	default:
   6231 		return NULL;
   6232 	}
   6233 
   6234 	if (!m)
   6235 		return NULL;
   6236 	M_PREPEND(m, l, M_DONTWAIT);
   6237 	if (!m)
   6238 		return NULL;
   6239 
   6240 	totlen = 0;
   6241 	for (n = m; n; n = n->m_next)
   6242 		totlen += n->m_len;
   6243 
   6244 	prop = mtod(m, struct sadb_prop *);
   6245 	memset(prop, 0, sizeof(*prop));
   6246 	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
   6247 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
   6248 	prop->sadb_prop_replay = 32;	/* XXX */
   6249 
   6250 	return m;
   6251 }
   6252 
   6253 /*
   6254  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
   6255  * send
   6256  *   <base, SA, address(SD), (address(P)), x_policy,
   6257  *       (identity(SD),) (sensitivity,) proposal>
   6258  * to KMD, and expect to receive
   6259  *   <base> with SADB_ACQUIRE if error occurred,
   6260  * or
   6261  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
   6262  * from KMD by PF_KEY.
   6263  *
   6264  * XXX x_policy is outside of RFC2367 (KAME extension).
   6265  * XXX sensitivity is not supported.
   6266  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
   6267  * see comment for key_getcomb_ipcomp().
   6268  *
   6269  * OUT:
   6270  *    0     : succeed
   6271  *    others: error number
   6272  */
   6273 static int
   6274 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
   6275 {
   6276 	struct mbuf *result = NULL, *m;
   6277 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6278 	struct secacq *newacq;
   6279 #endif
   6280 	u_int8_t satype;
   6281 	int error = -1;
   6282 	u_int32_t seq;
   6283 
   6284 	/* sanity check */
   6285 	IPSEC_ASSERT(saidx != NULL, ("key_acquire: null saidx"));
   6286 	satype = key_proto2satype(saidx->proto);
   6287 	IPSEC_ASSERT(satype != 0,
   6288 		("key_acquire: null satype, protocol %u", saidx->proto));
   6289 
   6290 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6291 	/*
   6292 	 * We never do anything about acquirng SA.  There is anather
   6293 	 * solution that kernel blocks to send SADB_ACQUIRE message until
   6294 	 * getting something message from IKEd.  In later case, to be
   6295 	 * managed with ACQUIRING list.
   6296 	 */
   6297 	/* Get an entry to check whether sending message or not. */
   6298 	if ((newacq = key_getacq(saidx)) != NULL) {
   6299 		if (key_blockacq_count < newacq->count) {
   6300 			/* reset counter and do send message. */
   6301 			newacq->count = 0;
   6302 		} else {
   6303 			/* increment counter and do nothing. */
   6304 			newacq->count++;
   6305 			return 0;
   6306 		}
   6307 	} else {
   6308 		/* make new entry for blocking to send SADB_ACQUIRE. */
   6309 		if ((newacq = key_newacq(saidx)) == NULL)
   6310 			return ENOBUFS;
   6311 
   6312 		/* add to acqtree */
   6313 		LIST_INSERT_HEAD(&acqtree, newacq, chain);
   6314 	}
   6315 #endif
   6316 
   6317 
   6318 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6319 	seq = newacq->seq;
   6320 #else
   6321 	seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
   6322 #endif
   6323 	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
   6324 	if (!m) {
   6325 		error = ENOBUFS;
   6326 		goto fail;
   6327 	}
   6328 	result = m;
   6329 
   6330 	/* set sadb_address for saidx's. */
   6331 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   6332 	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
   6333 	if (!m) {
   6334 		error = ENOBUFS;
   6335 		goto fail;
   6336 	}
   6337 	m_cat(result, m);
   6338 
   6339 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   6340 	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
   6341 	if (!m) {
   6342 		error = ENOBUFS;
   6343 		goto fail;
   6344 	}
   6345 	m_cat(result, m);
   6346 
   6347 	/* XXX proxy address (optional) */
   6348 
   6349 	/* set sadb_x_policy */
   6350 	if (sp) {
   6351 		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
   6352 		if (!m) {
   6353 			error = ENOBUFS;
   6354 			goto fail;
   6355 		}
   6356 		m_cat(result, m);
   6357 	}
   6358 
   6359 	/* XXX identity (optional) */
   6360 #if 0
   6361 	if (idexttype && fqdn) {
   6362 		/* create identity extension (FQDN) */
   6363 		struct sadb_ident *id;
   6364 		int fqdnlen;
   6365 
   6366 		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
   6367 		id = (struct sadb_ident *)p;
   6368 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6369 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6370 		id->sadb_ident_exttype = idexttype;
   6371 		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
   6372 		memcpy(id + 1, fqdn, fqdnlen);
   6373 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
   6374 	}
   6375 
   6376 	if (idexttype) {
   6377 		/* create identity extension (USERFQDN) */
   6378 		struct sadb_ident *id;
   6379 		int userfqdnlen;
   6380 
   6381 		if (userfqdn) {
   6382 			/* +1 for terminating-NUL */
   6383 			userfqdnlen = strlen(userfqdn) + 1;
   6384 		} else
   6385 			userfqdnlen = 0;
   6386 		id = (struct sadb_ident *)p;
   6387 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6388 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6389 		id->sadb_ident_exttype = idexttype;
   6390 		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
   6391 		/* XXX is it correct? */
   6392 		if (curlwp)
   6393 			id->sadb_ident_id = kauth_cred_getuid(curlwp->l_cred);
   6394 		if (userfqdn && userfqdnlen)
   6395 			memcpy(id + 1, userfqdn, userfqdnlen);
   6396 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
   6397 	}
   6398 #endif
   6399 
   6400 	/* XXX sensitivity (optional) */
   6401 
   6402 	/* create proposal/combination extension */
   6403 	m = key_getprop(saidx);
   6404 #if 0
   6405 	/*
   6406 	 * spec conformant: always attach proposal/combination extension,
   6407 	 * the problem is that we have no way to attach it for ipcomp,
   6408 	 * due to the way sadb_comb is declared in RFC2367.
   6409 	 */
   6410 	if (!m) {
   6411 		error = ENOBUFS;
   6412 		goto fail;
   6413 	}
   6414 	m_cat(result, m);
   6415 #else
   6416 	/*
   6417 	 * outside of spec; make proposal/combination extension optional.
   6418 	 */
   6419 	if (m)
   6420 		m_cat(result, m);
   6421 #endif
   6422 
   6423 	if ((result->m_flags & M_PKTHDR) == 0) {
   6424 		error = EINVAL;
   6425 		goto fail;
   6426 	}
   6427 
   6428 	if (result->m_len < sizeof(struct sadb_msg)) {
   6429 		result = m_pullup(result, sizeof(struct sadb_msg));
   6430 		if (result == NULL) {
   6431 			error = ENOBUFS;
   6432 			goto fail;
   6433 		}
   6434 	}
   6435 
   6436 	result->m_pkthdr.len = 0;
   6437 	for (m = result; m; m = m->m_next)
   6438 		result->m_pkthdr.len += m->m_len;
   6439 
   6440 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6441 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6442 
   6443 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   6444 
   6445  fail:
   6446 	if (result)
   6447 		m_freem(result);
   6448 	return error;
   6449 }
   6450 
   6451 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6452 static struct secacq *
   6453 key_newacq(const struct secasindex *saidx)
   6454 {
   6455 	struct secacq *newacq;
   6456 
   6457 	/* get new entry */
   6458 	KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
   6459 	if (newacq == NULL) {
   6460 		ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
   6461 		return NULL;
   6462 	}
   6463 	memset(newacq, 0, sizeof(*newacq));
   6464 
   6465 	/* copy secindex */
   6466 	memcpy(&newacq->saidx, saidx, sizeof(newacq->saidx));
   6467 	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
   6468 	newacq->created = time_uptime;
   6469 	newacq->count = 0;
   6470 
   6471 	return newacq;
   6472 }
   6473 
   6474 static struct secacq *
   6475 key_getacq(const struct secasindex *saidx)
   6476 {
   6477 	struct secacq *acq;
   6478 
   6479 	LIST_FOREACH(acq, &acqtree, chain) {
   6480 		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
   6481 			return acq;
   6482 	}
   6483 
   6484 	return NULL;
   6485 }
   6486 
   6487 static struct secacq *
   6488 key_getacqbyseq(u_int32_t seq)
   6489 {
   6490 	struct secacq *acq;
   6491 
   6492 	LIST_FOREACH(acq, &acqtree, chain) {
   6493 		if (acq->seq == seq)
   6494 			return acq;
   6495 	}
   6496 
   6497 	return NULL;
   6498 }
   6499 #endif
   6500 
   6501 static struct secspacq *
   6502 key_newspacq(const struct secpolicyindex *spidx)
   6503 {
   6504 	struct secspacq *acq;
   6505 
   6506 	/* get new entry */
   6507 	KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
   6508 	if (acq == NULL) {
   6509 		ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
   6510 		return NULL;
   6511 	}
   6512 	memset(acq, 0, sizeof(*acq));
   6513 
   6514 	/* copy secindex */
   6515 	memcpy(&acq->spidx, spidx, sizeof(acq->spidx));
   6516 	acq->created = time_uptime;
   6517 	acq->count = 0;
   6518 
   6519 	return acq;
   6520 }
   6521 
   6522 static struct secspacq *
   6523 key_getspacq(const struct secpolicyindex *spidx)
   6524 {
   6525 	struct secspacq *acq;
   6526 
   6527 	LIST_FOREACH(acq, &spacqtree, chain) {
   6528 		if (key_cmpspidx_exactly(spidx, &acq->spidx))
   6529 			return acq;
   6530 	}
   6531 
   6532 	return NULL;
   6533 }
   6534 
   6535 /*
   6536  * SADB_ACQUIRE processing,
   6537  * in first situation, is receiving
   6538  *   <base>
   6539  * from the ikmpd, and clear sequence of its secasvar entry.
   6540  *
   6541  * In second situation, is receiving
   6542  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6543  * from a user land process, and return
   6544  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6545  * to the socket.
   6546  *
   6547  * m will always be freed.
   6548  */
   6549 static int
   6550 key_acquire2(struct socket *so, struct mbuf *m,
   6551       	     const struct sadb_msghdr *mhp)
   6552 {
   6553 	const struct sadb_address *src0, *dst0;
   6554 	struct secasindex saidx;
   6555 	struct secashead *sah;
   6556 	u_int16_t proto;
   6557 	int error;
   6558 
   6559 	/* sanity check */
   6560 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   6561 		panic("key_acquire2: NULL pointer is passed");
   6562 
   6563 	/*
   6564 	 * Error message from KMd.
   6565 	 * We assume that if error was occurred in IKEd, the length of PFKEY
   6566 	 * message is equal to the size of sadb_msg structure.
   6567 	 * We do not raise error even if error occurred in this function.
   6568 	 */
   6569 	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
   6570 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6571 		struct secacq *acq;
   6572 
   6573 		/* check sequence number */
   6574 		if (mhp->msg->sadb_msg_seq == 0) {
   6575 			ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
   6576 			m_freem(m);
   6577 			return 0;
   6578 		}
   6579 
   6580 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
   6581 			/*
   6582 			 * the specified larval SA is already gone, or we got
   6583 			 * a bogus sequence number.  we can silently ignore it.
   6584 			 */
   6585 			m_freem(m);
   6586 			return 0;
   6587 		}
   6588 
   6589 		/* reset acq counter in order to deletion by timehander. */
   6590 		acq->created = time_uptime;
   6591 		acq->count = 0;
   6592 #endif
   6593 		m_freem(m);
   6594 		return 0;
   6595 	}
   6596 
   6597 	/*
   6598 	 * This message is from user land.
   6599 	 */
   6600 
   6601 	/* map satype to proto */
   6602 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   6603 		ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
   6604 		return key_senderror(so, m, EINVAL);
   6605 	}
   6606 
   6607 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   6608 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   6609 	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
   6610 		/* error */
   6611 		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
   6612 		return key_senderror(so, m, EINVAL);
   6613 	}
   6614 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   6615 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   6616 	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
   6617 		/* error */
   6618 		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
   6619 		return key_senderror(so, m, EINVAL);
   6620 	}
   6621 
   6622 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   6623 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   6624 
   6625 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   6626 				     dst0 + 1, &saidx)) != 0)
   6627 		return key_senderror(so, m, EINVAL);
   6628 
   6629 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   6630 		return key_senderror(so, m, EINVAL);
   6631 
   6632 	/* get a SA index */
   6633 	LIST_FOREACH(sah, &sahtree, chain) {
   6634 		if (sah->state == SADB_SASTATE_DEAD)
   6635 			continue;
   6636 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
   6637 			break;
   6638 	}
   6639 	if (sah != NULL) {
   6640 		ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
   6641 		return key_senderror(so, m, EEXIST);
   6642 	}
   6643 
   6644 	error = key_acquire(&saidx, NULL);
   6645 	if (error != 0) {
   6646 		ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
   6647 			"from key_acquire.\n", mhp->msg->sadb_msg_errno));
   6648 		return key_senderror(so, m, error);
   6649 	}
   6650 
   6651 	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
   6652 }
   6653 
   6654 /*
   6655  * SADB_REGISTER processing.
   6656  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
   6657  * receive
   6658  *   <base>
   6659  * from the ikmpd, and register a socket to send PF_KEY messages,
   6660  * and send
   6661  *   <base, supported>
   6662  * to KMD by PF_KEY.
   6663  * If socket is detached, must free from regnode.
   6664  *
   6665  * m will always be freed.
   6666  */
   6667 static int
   6668 key_register(struct socket *so, struct mbuf *m,
   6669 	     const struct sadb_msghdr *mhp)
   6670 {
   6671 	struct secreg *reg, *newreg = 0;
   6672 
   6673 	/* sanity check */
   6674 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   6675 		panic("key_register: NULL pointer is passed");
   6676 
   6677 	/* check for invalid register message */
   6678 	if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
   6679 		return key_senderror(so, m, EINVAL);
   6680 
   6681 	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
   6682 	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
   6683 		goto setmsg;
   6684 
   6685 	/* check whether existing or not */
   6686 	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
   6687 		if (reg->so == so) {
   6688 			ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
   6689 			return key_senderror(so, m, EEXIST);
   6690 		}
   6691 	}
   6692 
   6693 	/* create regnode */
   6694 	KMALLOC(newreg, struct secreg *, sizeof(*newreg));
   6695 	if (newreg == NULL) {
   6696 		ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
   6697 		return key_senderror(so, m, ENOBUFS);
   6698 	}
   6699 	memset(newreg, 0, sizeof(*newreg));
   6700 
   6701 	newreg->so = so;
   6702 	((struct keycb *)sotorawcb(so))->kp_registered++;
   6703 
   6704 	/* add regnode to regtree. */
   6705 	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
   6706 
   6707   setmsg:
   6708     {
   6709 	struct mbuf *n;
   6710 	struct sadb_msg *newmsg;
   6711 	struct sadb_supported *sup;
   6712 	u_int len, alen, elen;
   6713 	int off;
   6714 	int i;
   6715 	struct sadb_alg *alg;
   6716 
   6717 	/* create new sadb_msg to reply. */
   6718 	alen = 0;
   6719 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   6720 		if (ah_algorithm_lookup(i))
   6721 			alen += sizeof(struct sadb_alg);
   6722 	}
   6723 	if (alen)
   6724 		alen += sizeof(struct sadb_supported);
   6725 	elen = 0;
   6726 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   6727 		if (esp_algorithm_lookup(i))
   6728 			elen += sizeof(struct sadb_alg);
   6729 	}
   6730 	if (elen)
   6731 		elen += sizeof(struct sadb_supported);
   6732 
   6733 	len = sizeof(struct sadb_msg) + alen + elen;
   6734 
   6735 	if (len > MCLBYTES)
   6736 		return key_senderror(so, m, ENOBUFS);
   6737 
   6738 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   6739 	if (len > MHLEN) {
   6740 		MCLGET(n, M_DONTWAIT);
   6741 		if ((n->m_flags & M_EXT) == 0) {
   6742 			m_freem(n);
   6743 			n = NULL;
   6744 		}
   6745 	}
   6746 	if (!n)
   6747 		return key_senderror(so, m, ENOBUFS);
   6748 
   6749 	n->m_pkthdr.len = n->m_len = len;
   6750 	n->m_next = NULL;
   6751 	off = 0;
   6752 
   6753 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   6754 	newmsg = mtod(n, struct sadb_msg *);
   6755 	newmsg->sadb_msg_errno = 0;
   6756 	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
   6757 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   6758 
   6759 	/* for authentication algorithm */
   6760 	if (alen) {
   6761 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6762 		sup->sadb_supported_len = PFKEY_UNIT64(alen);
   6763 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
   6764 		off += PFKEY_ALIGN8(sizeof(*sup));
   6765 
   6766 		for (i = 1; i <= SADB_AALG_MAX; i++) {
   6767 			const struct auth_hash *aalgo;
   6768 			u_int16_t minkeysize, maxkeysize;
   6769 
   6770 			aalgo = ah_algorithm_lookup(i);
   6771 			if (!aalgo)
   6772 				continue;
   6773 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6774 			alg->sadb_alg_id = i;
   6775 			alg->sadb_alg_ivlen = 0;
   6776 			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
   6777 			alg->sadb_alg_minbits = _BITS(minkeysize);
   6778 			alg->sadb_alg_maxbits = _BITS(maxkeysize);
   6779 			off += PFKEY_ALIGN8(sizeof(*alg));
   6780 		}
   6781 	}
   6782 
   6783 	/* for encryption algorithm */
   6784 	if (elen) {
   6785 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6786 		sup->sadb_supported_len = PFKEY_UNIT64(elen);
   6787 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
   6788 		off += PFKEY_ALIGN8(sizeof(*sup));
   6789 
   6790 		for (i = 1; i <= SADB_EALG_MAX; i++) {
   6791 			const struct enc_xform *ealgo;
   6792 
   6793 			ealgo = esp_algorithm_lookup(i);
   6794 			if (!ealgo)
   6795 				continue;
   6796 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6797 			alg->sadb_alg_id = i;
   6798 			alg->sadb_alg_ivlen = ealgo->blocksize;
   6799 			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
   6800 			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
   6801 			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
   6802 		}
   6803 	}
   6804 
   6805 #ifdef DIAGNOSTIC
   6806 	if (off != len)
   6807 		panic("length assumption failed in key_register");
   6808 #endif
   6809 
   6810 	m_freem(m);
   6811 	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
   6812     }
   6813 }
   6814 
   6815 /*
   6816  * free secreg entry registered.
   6817  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
   6818  */
   6819 void
   6820 key_freereg(struct socket *so)
   6821 {
   6822 	struct secreg *reg;
   6823 	int i;
   6824 
   6825 	/* sanity check */
   6826 	if (so == NULL)
   6827 		panic("key_freereg: NULL pointer is passed");
   6828 
   6829 	/*
   6830 	 * check whether existing or not.
   6831 	 * check all type of SA, because there is a potential that
   6832 	 * one socket is registered to multiple type of SA.
   6833 	 */
   6834 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   6835 		LIST_FOREACH(reg, &regtree[i], chain) {
   6836 			if (reg->so == so
   6837 			 && __LIST_CHAINED(reg)) {
   6838 				LIST_REMOVE(reg, chain);
   6839 				KFREE(reg);
   6840 				break;
   6841 			}
   6842 		}
   6843 	}
   6844 
   6845 	return;
   6846 }
   6847 
   6848 /*
   6849  * SADB_EXPIRE processing
   6850  * send
   6851  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
   6852  * to KMD by PF_KEY.
   6853  * NOTE: We send only soft lifetime extension.
   6854  *
   6855  * OUT:	0	: succeed
   6856  *	others	: error number
   6857  */
   6858 static int
   6859 key_expire(struct secasvar *sav)
   6860 {
   6861 	int s;
   6862 	int satype;
   6863 	struct mbuf *result = NULL, *m;
   6864 	int len;
   6865 	int error = -1;
   6866 	struct sadb_lifetime *lt;
   6867 
   6868 	/* XXX: Why do we lock ? */
   6869 	s = splsoftnet();	/*called from softclock()*/
   6870 
   6871 	/* sanity check */
   6872 	if (sav == NULL)
   6873 		panic("key_expire: NULL pointer is passed");
   6874 	if (sav->sah == NULL)
   6875 		panic("key_expire: Why was SA index in SA NULL");
   6876 	if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
   6877 		panic("key_expire: invalid proto is passed");
   6878 
   6879 	/* set msg header */
   6880 	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
   6881 	if (!m) {
   6882 		error = ENOBUFS;
   6883 		goto fail;
   6884 	}
   6885 	result = m;
   6886 
   6887 	/* create SA extension */
   6888 	m = key_setsadbsa(sav);
   6889 	if (!m) {
   6890 		error = ENOBUFS;
   6891 		goto fail;
   6892 	}
   6893 	m_cat(result, m);
   6894 
   6895 	/* create SA extension */
   6896 	m = key_setsadbxsa2(sav->sah->saidx.mode,
   6897 			sav->replay ? sav->replay->count : 0,
   6898 			sav->sah->saidx.reqid);
   6899 	if (!m) {
   6900 		error = ENOBUFS;
   6901 		goto fail;
   6902 	}
   6903 	m_cat(result, m);
   6904 
   6905 	/* create lifetime extension (current and soft) */
   6906 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
   6907 	m = key_alloc_mbuf(len);
   6908 	if (!m || m->m_next) {	/*XXX*/
   6909 		if (m)
   6910 			m_freem(m);
   6911 		error = ENOBUFS;
   6912 		goto fail;
   6913 	}
   6914 	memset(mtod(m, void *), 0, len);
   6915 	lt = mtod(m, struct sadb_lifetime *);
   6916 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   6917 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   6918 	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
   6919 	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
   6920 	lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime
   6921 		+ time_second - time_uptime;
   6922 	lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime
   6923 		+ time_second - time_uptime;
   6924 	lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
   6925 	memcpy(lt, sav->lft_s, sizeof(*lt));
   6926 	m_cat(result, m);
   6927 
   6928 	/* set sadb_address for source */
   6929 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   6930 	    &sav->sah->saidx.src.sa,
   6931 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6932 	if (!m) {
   6933 		error = ENOBUFS;
   6934 		goto fail;
   6935 	}
   6936 	m_cat(result, m);
   6937 
   6938 	/* set sadb_address for destination */
   6939 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   6940 	    &sav->sah->saidx.dst.sa,
   6941 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6942 	if (!m) {
   6943 		error = ENOBUFS;
   6944 		goto fail;
   6945 	}
   6946 	m_cat(result, m);
   6947 
   6948 	if ((result->m_flags & M_PKTHDR) == 0) {
   6949 		error = EINVAL;
   6950 		goto fail;
   6951 	}
   6952 
   6953 	if (result->m_len < sizeof(struct sadb_msg)) {
   6954 		result = m_pullup(result, sizeof(struct sadb_msg));
   6955 		if (result == NULL) {
   6956 			error = ENOBUFS;
   6957 			goto fail;
   6958 		}
   6959 	}
   6960 
   6961 	result->m_pkthdr.len = 0;
   6962 	for (m = result; m; m = m->m_next)
   6963 		result->m_pkthdr.len += m->m_len;
   6964 
   6965 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6966 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6967 
   6968 	splx(s);
   6969 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   6970 
   6971  fail:
   6972 	if (result)
   6973 		m_freem(result);
   6974 	splx(s);
   6975 	return error;
   6976 }
   6977 
   6978 /*
   6979  * SADB_FLUSH processing
   6980  * receive
   6981  *   <base>
   6982  * from the ikmpd, and free all entries in secastree.
   6983  * and send,
   6984  *   <base>
   6985  * to the ikmpd.
   6986  * NOTE: to do is only marking SADB_SASTATE_DEAD.
   6987  *
   6988  * m will always be freed.
   6989  */
   6990 static int
   6991 key_flush(struct socket *so, struct mbuf *m,
   6992           const struct sadb_msghdr *mhp)
   6993 {
   6994 	struct sadb_msg *newmsg;
   6995 	struct secashead *sah, *nextsah;
   6996 	struct secasvar *sav, *nextsav;
   6997 	u_int16_t proto;
   6998 	u_int8_t state;
   6999 	u_int stateidx;
   7000 
   7001 	/* sanity check */
   7002 	if (so == NULL || mhp == NULL || mhp->msg == NULL)
   7003 		panic("key_flush: NULL pointer is passed");
   7004 
   7005 	/* map satype to proto */
   7006 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   7007 		ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
   7008 		return key_senderror(so, m, EINVAL);
   7009 	}
   7010 
   7011 	/* no SATYPE specified, i.e. flushing all SA. */
   7012 	for (sah = LIST_FIRST(&sahtree);
   7013 	     sah != NULL;
   7014 	     sah = nextsah) {
   7015 		nextsah = LIST_NEXT(sah, chain);
   7016 
   7017 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
   7018 		 && proto != sah->saidx.proto)
   7019 			continue;
   7020 
   7021 		for (stateidx = 0;
   7022 		     stateidx < _ARRAYLEN(saorder_state_alive);
   7023 		     stateidx++) {
   7024 			state = saorder_state_any[stateidx];
   7025 			for (sav = LIST_FIRST(&sah->savtree[state]);
   7026 			     sav != NULL;
   7027 			     sav = nextsav) {
   7028 
   7029 				nextsav = LIST_NEXT(sav, chain);
   7030 
   7031 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   7032 				KEY_FREESAV(&sav);
   7033 			}
   7034 		}
   7035 
   7036 		sah->state = SADB_SASTATE_DEAD;
   7037 	}
   7038 
   7039 	if (m->m_len < sizeof(struct sadb_msg) ||
   7040 	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
   7041 		ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
   7042 		return key_senderror(so, m, ENOBUFS);
   7043 	}
   7044 
   7045 	if (m->m_next)
   7046 		m_freem(m->m_next);
   7047 	m->m_next = NULL;
   7048 	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
   7049 	newmsg = mtod(m, struct sadb_msg *);
   7050 	newmsg->sadb_msg_errno = 0;
   7051 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
   7052 
   7053 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7054 }
   7055 
   7056 
   7057 static struct mbuf *
   7058 key_setdump_chain(u_int8_t req_satype, int *errorp, int *lenp, pid_t pid)
   7059 {
   7060 	struct secashead *sah;
   7061 	struct secasvar *sav;
   7062 	u_int16_t proto;
   7063 	u_int stateidx;
   7064 	u_int8_t satype;
   7065 	u_int8_t state;
   7066 	int cnt;
   7067 	struct mbuf *m, *n, *prev;
   7068 
   7069 	*lenp = 0;
   7070 
   7071 	/* map satype to proto */
   7072 	if ((proto = key_satype2proto(req_satype)) == 0) {
   7073 		*errorp = EINVAL;
   7074 		return (NULL);
   7075 	}
   7076 
   7077 	/* count sav entries to be sent to userland. */
   7078 	cnt = 0;
   7079 	LIST_FOREACH(sah, &sahtree, chain) {
   7080 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7081 		    proto != sah->saidx.proto)
   7082 			continue;
   7083 
   7084 		for (stateidx = 0;
   7085 		     stateidx < _ARRAYLEN(saorder_state_any);
   7086 		     stateidx++) {
   7087 			state = saorder_state_any[stateidx];
   7088 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   7089 				cnt++;
   7090 			}
   7091 		}
   7092 	}
   7093 
   7094 	if (cnt == 0) {
   7095 		*errorp = ENOENT;
   7096 		return (NULL);
   7097 	}
   7098 
   7099 	/* send this to the userland, one at a time. */
   7100 	m = NULL;
   7101 	prev = m;
   7102 	LIST_FOREACH(sah, &sahtree, chain) {
   7103 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7104 		    proto != sah->saidx.proto)
   7105 			continue;
   7106 
   7107 		/* map proto to satype */
   7108 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
   7109 			m_freem(m);
   7110 			*errorp = EINVAL;
   7111 			return (NULL);
   7112 		}
   7113 
   7114 		for (stateidx = 0;
   7115 		     stateidx < _ARRAYLEN(saorder_state_any);
   7116 		     stateidx++) {
   7117 			state = saorder_state_any[stateidx];
   7118 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   7119 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   7120 				    --cnt, pid);
   7121 				if (!n) {
   7122 					m_freem(m);
   7123 					*errorp = ENOBUFS;
   7124 					return (NULL);
   7125 				}
   7126 
   7127 				if (!m)
   7128 					m = n;
   7129 				else
   7130 					prev->m_nextpkt = n;
   7131 				prev = n;
   7132 			}
   7133 		}
   7134 	}
   7135 
   7136 	if (!m) {
   7137 		*errorp = EINVAL;
   7138 		return (NULL);
   7139 	}
   7140 
   7141 	if ((m->m_flags & M_PKTHDR) != 0) {
   7142 		m->m_pkthdr.len = 0;
   7143 		for (n = m; n; n = n->m_next)
   7144 			m->m_pkthdr.len += n->m_len;
   7145 	}
   7146 
   7147 	*errorp = 0;
   7148 	return (m);
   7149 }
   7150 
   7151 /*
   7152  * SADB_DUMP processing
   7153  * dump all entries including status of DEAD in SAD.
   7154  * receive
   7155  *   <base>
   7156  * from the ikmpd, and dump all secasvar leaves
   7157  * and send,
   7158  *   <base> .....
   7159  * to the ikmpd.
   7160  *
   7161  * m will always be freed.
   7162  */
   7163 static int
   7164 key_dump(struct socket *so, struct mbuf *m0,
   7165 	 const struct sadb_msghdr *mhp)
   7166 {
   7167 	u_int16_t proto;
   7168 	u_int8_t satype;
   7169 	struct mbuf *n;
   7170 	int s;
   7171 	int error, len, ok;
   7172 
   7173 	/* sanity check */
   7174 	if (so == NULL || m0 == NULL || mhp == NULL || mhp->msg == NULL)
   7175 		panic("key_dump: NULL pointer is passed");
   7176 
   7177 	/* map satype to proto */
   7178 	satype = mhp->msg->sadb_msg_satype;
   7179 	if ((proto = key_satype2proto(satype)) == 0) {
   7180 		ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
   7181 		return key_senderror(so, m0, EINVAL);
   7182 	}
   7183 
   7184 	/*
   7185 	 * If the requestor has insufficient socket-buffer space
   7186 	 * for the entire chain, nobody gets any response to the DUMP.
   7187 	 * XXX For now, only the requestor ever gets anything.
   7188 	 * Moreover, if the requestor has any space at all, they receive
   7189 	 * the entire chain, otherwise the request is refused with ENOBUFS.
   7190 	 */
   7191 	if (sbspace(&so->so_rcv) <= 0) {
   7192 		return key_senderror(so, m0, ENOBUFS);
   7193 	}
   7194 
   7195 	s = splsoftnet();
   7196 	n = key_setdump_chain(satype, &error, &len, mhp->msg->sadb_msg_pid);
   7197 	splx(s);
   7198 
   7199 	if (n == NULL) {
   7200 		return key_senderror(so, m0, ENOENT);
   7201 	}
   7202 	{
   7203 		uint64_t *ps = PFKEY_STAT_GETREF();
   7204 		ps[PFKEY_STAT_IN_TOTAL]++;
   7205 		ps[PFKEY_STAT_IN_BYTES] += len;
   7206 		PFKEY_STAT_PUTREF();
   7207 	}
   7208 
   7209 	/*
   7210 	 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
   7211 	 * The requestor receives either the entire chain, or an
   7212 	 * error message with ENOBUFS.
   7213 	 *
   7214 	 * sbappendaddrchain() takes the chain of entries, one
   7215 	 * packet-record per SPD entry, prepends the key_src sockaddr
   7216 	 * to each packet-record, links the sockaddr mbufs into a new
   7217 	 * list of records, then   appends the entire resulting
   7218 	 * list to the requesting socket.
   7219 	 */
   7220 	ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src,
   7221 	        n, SB_PRIO_ONESHOT_OVERFLOW);
   7222 
   7223 	if (!ok) {
   7224 		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
   7225 		m_freem(n);
   7226 		return key_senderror(so, m0, ENOBUFS);
   7227 	}
   7228 
   7229 	m_freem(m0);
   7230 	return 0;
   7231 }
   7232 
   7233 /*
   7234  * SADB_X_PROMISC processing
   7235  *
   7236  * m will always be freed.
   7237  */
   7238 static int
   7239 key_promisc(struct socket *so, struct mbuf *m,
   7240 	    const struct sadb_msghdr *mhp)
   7241 {
   7242 	int olen;
   7243 
   7244 	/* sanity check */
   7245 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   7246 		panic("key_promisc: NULL pointer is passed");
   7247 
   7248 	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   7249 
   7250 	if (olen < sizeof(struct sadb_msg)) {
   7251 #if 1
   7252 		return key_senderror(so, m, EINVAL);
   7253 #else
   7254 		m_freem(m);
   7255 		return 0;
   7256 #endif
   7257 	} else if (olen == sizeof(struct sadb_msg)) {
   7258 		/* enable/disable promisc mode */
   7259 		struct keycb *kp;
   7260 
   7261 		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
   7262 			return key_senderror(so, m, EINVAL);
   7263 		mhp->msg->sadb_msg_errno = 0;
   7264 		switch (mhp->msg->sadb_msg_satype) {
   7265 		case 0:
   7266 		case 1:
   7267 			kp->kp_promisc = mhp->msg->sadb_msg_satype;
   7268 			break;
   7269 		default:
   7270 			return key_senderror(so, m, EINVAL);
   7271 		}
   7272 
   7273 		/* send the original message back to everyone */
   7274 		mhp->msg->sadb_msg_errno = 0;
   7275 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7276 	} else {
   7277 		/* send packet as is */
   7278 
   7279 		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
   7280 
   7281 		/* TODO: if sadb_msg_seq is specified, send to specific pid */
   7282 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7283 	}
   7284 }
   7285 
   7286 static int (*key_typesw[]) (struct socket *, struct mbuf *,
   7287 		const struct sadb_msghdr *) = {
   7288 	NULL,		/* SADB_RESERVED */
   7289 	key_getspi,	/* SADB_GETSPI */
   7290 	key_update,	/* SADB_UPDATE */
   7291 	key_add,	/* SADB_ADD */
   7292 	key_delete,	/* SADB_DELETE */
   7293 	key_get,	/* SADB_GET */
   7294 	key_acquire2,	/* SADB_ACQUIRE */
   7295 	key_register,	/* SADB_REGISTER */
   7296 	NULL,		/* SADB_EXPIRE */
   7297 	key_flush,	/* SADB_FLUSH */
   7298 	key_dump,	/* SADB_DUMP */
   7299 	key_promisc,	/* SADB_X_PROMISC */
   7300 	NULL,		/* SADB_X_PCHANGE */
   7301 	key_spdadd,	/* SADB_X_SPDUPDATE */
   7302 	key_spdadd,	/* SADB_X_SPDADD */
   7303 	key_spddelete,	/* SADB_X_SPDDELETE */
   7304 	key_spdget,	/* SADB_X_SPDGET */
   7305 	NULL,		/* SADB_X_SPDACQUIRE */
   7306 	key_spddump,	/* SADB_X_SPDDUMP */
   7307 	key_spdflush,	/* SADB_X_SPDFLUSH */
   7308 	key_spdadd,	/* SADB_X_SPDSETIDX */
   7309 	NULL,		/* SADB_X_SPDEXPIRE */
   7310 	key_spddelete2,	/* SADB_X_SPDDELETE2 */
   7311 	key_nat_map,	/* SADB_X_NAT_T_NEW_MAPPING */
   7312 };
   7313 
   7314 /*
   7315  * parse sadb_msg buffer to process PFKEYv2,
   7316  * and create a data to response if needed.
   7317  * I think to be dealed with mbuf directly.
   7318  * IN:
   7319  *     msgp  : pointer to pointer to a received buffer pulluped.
   7320  *             This is rewrited to response.
   7321  *     so    : pointer to socket.
   7322  * OUT:
   7323  *    length for buffer to send to user process.
   7324  */
   7325 int
   7326 key_parse(struct mbuf *m, struct socket *so)
   7327 {
   7328 	struct sadb_msg *msg;
   7329 	struct sadb_msghdr mh;
   7330 	int error;
   7331 	int target;
   7332 
   7333 	/* sanity check */
   7334 	if (m == NULL || so == NULL)
   7335 		panic("key_parse: NULL pointer is passed");
   7336 
   7337 #if 0	/*kdebug_sadb assumes msg in linear buffer*/
   7338 	KEYDEBUG(KEYDEBUG_KEY_DUMP,
   7339 		ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
   7340 		kdebug_sadb(msg));
   7341 #endif
   7342 
   7343 	if (m->m_len < sizeof(struct sadb_msg)) {
   7344 		m = m_pullup(m, sizeof(struct sadb_msg));
   7345 		if (!m)
   7346 			return ENOBUFS;
   7347 	}
   7348 	msg = mtod(m, struct sadb_msg *);
   7349 	target = KEY_SENDUP_ONE;
   7350 
   7351 	if ((m->m_flags & M_PKTHDR) == 0 ||
   7352 	    m->m_pkthdr.len != m->m_pkthdr.len) {
   7353 		ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
   7354 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7355 		error = EINVAL;
   7356 		goto senderror;
   7357 	}
   7358 
   7359 	if (msg->sadb_msg_version != PF_KEY_V2) {
   7360 		ipseclog((LOG_DEBUG,
   7361 		    "key_parse: PF_KEY version %u is mismatched.\n",
   7362 		    msg->sadb_msg_version));
   7363 		PFKEY_STATINC(PFKEY_STAT_OUT_INVVER);
   7364 		error = EINVAL;
   7365 		goto senderror;
   7366 	}
   7367 
   7368 	if (msg->sadb_msg_type > SADB_MAX) {
   7369 		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
   7370 		    msg->sadb_msg_type));
   7371 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7372 		error = EINVAL;
   7373 		goto senderror;
   7374 	}
   7375 
   7376 	/* for old-fashioned code - should be nuked */
   7377 	if (m->m_pkthdr.len > MCLBYTES) {
   7378 		m_freem(m);
   7379 		return ENOBUFS;
   7380 	}
   7381 	if (m->m_next) {
   7382 		struct mbuf *n;
   7383 
   7384 		MGETHDR(n, M_DONTWAIT, MT_DATA);
   7385 		if (n && m->m_pkthdr.len > MHLEN) {
   7386 			MCLGET(n, M_DONTWAIT);
   7387 			if ((n->m_flags & M_EXT) == 0) {
   7388 				m_free(n);
   7389 				n = NULL;
   7390 			}
   7391 		}
   7392 		if (!n) {
   7393 			m_freem(m);
   7394 			return ENOBUFS;
   7395 		}
   7396 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, void *));
   7397 		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
   7398 		n->m_next = NULL;
   7399 		m_freem(m);
   7400 		m = n;
   7401 	}
   7402 
   7403 	/* align the mbuf chain so that extensions are in contiguous region. */
   7404 	error = key_align(m, &mh);
   7405 	if (error)
   7406 		return error;
   7407 
   7408 	if (m->m_next) {	/*XXX*/
   7409 		m_freem(m);
   7410 		return ENOBUFS;
   7411 	}
   7412 
   7413 	msg = mh.msg;
   7414 
   7415 	/* check SA type */
   7416 	switch (msg->sadb_msg_satype) {
   7417 	case SADB_SATYPE_UNSPEC:
   7418 		switch (msg->sadb_msg_type) {
   7419 		case SADB_GETSPI:
   7420 		case SADB_UPDATE:
   7421 		case SADB_ADD:
   7422 		case SADB_DELETE:
   7423 		case SADB_GET:
   7424 		case SADB_ACQUIRE:
   7425 		case SADB_EXPIRE:
   7426 			ipseclog((LOG_DEBUG, "key_parse: must specify satype "
   7427 			    "when msg type=%u.\n", msg->sadb_msg_type));
   7428 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7429 			error = EINVAL;
   7430 			goto senderror;
   7431 		}
   7432 		break;
   7433 	case SADB_SATYPE_AH:
   7434 	case SADB_SATYPE_ESP:
   7435 	case SADB_X_SATYPE_IPCOMP:
   7436 	case SADB_X_SATYPE_TCPSIGNATURE:
   7437 		switch (msg->sadb_msg_type) {
   7438 		case SADB_X_SPDADD:
   7439 		case SADB_X_SPDDELETE:
   7440 		case SADB_X_SPDGET:
   7441 		case SADB_X_SPDDUMP:
   7442 		case SADB_X_SPDFLUSH:
   7443 		case SADB_X_SPDSETIDX:
   7444 		case SADB_X_SPDUPDATE:
   7445 		case SADB_X_SPDDELETE2:
   7446 			ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
   7447 			    msg->sadb_msg_type));
   7448 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7449 			error = EINVAL;
   7450 			goto senderror;
   7451 		}
   7452 		break;
   7453 	case SADB_SATYPE_RSVP:
   7454 	case SADB_SATYPE_OSPFV2:
   7455 	case SADB_SATYPE_RIPV2:
   7456 	case SADB_SATYPE_MIP:
   7457 		ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
   7458 		    msg->sadb_msg_satype));
   7459 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7460 		error = EOPNOTSUPP;
   7461 		goto senderror;
   7462 	case 1:	/* XXX: What does it do? */
   7463 		if (msg->sadb_msg_type == SADB_X_PROMISC)
   7464 			break;
   7465 		/*FALLTHROUGH*/
   7466 	default:
   7467 		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
   7468 		    msg->sadb_msg_satype));
   7469 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7470 		error = EINVAL;
   7471 		goto senderror;
   7472 	}
   7473 
   7474 	/* check field of upper layer protocol and address family */
   7475 	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
   7476 	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
   7477 		struct sadb_address *src0, *dst0;
   7478 		u_int plen;
   7479 
   7480 		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
   7481 		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
   7482 
   7483 		/* check upper layer protocol */
   7484 		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
   7485 			ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
   7486 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7487 			error = EINVAL;
   7488 			goto senderror;
   7489 		}
   7490 
   7491 		/* check family */
   7492 		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
   7493 		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
   7494 			ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
   7495 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7496 			error = EINVAL;
   7497 			goto senderror;
   7498 		}
   7499 		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7500 		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
   7501 			ipseclog((LOG_DEBUG,
   7502 			    "key_parse: address struct size mismatched.\n"));
   7503 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7504 			error = EINVAL;
   7505 			goto senderror;
   7506 		}
   7507 
   7508 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7509 		case AF_INET:
   7510 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7511 			    sizeof(struct sockaddr_in)) {
   7512 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7513 				error = EINVAL;
   7514 				goto senderror;
   7515 			}
   7516 			break;
   7517 		case AF_INET6:
   7518 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7519 			    sizeof(struct sockaddr_in6)) {
   7520 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7521 				error = EINVAL;
   7522 				goto senderror;
   7523 			}
   7524 			break;
   7525 		default:
   7526 			ipseclog((LOG_DEBUG,
   7527 			    "key_parse: unsupported address family.\n"));
   7528 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7529 			error = EAFNOSUPPORT;
   7530 			goto senderror;
   7531 		}
   7532 
   7533 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7534 		case AF_INET:
   7535 			plen = sizeof(struct in_addr) << 3;
   7536 			break;
   7537 		case AF_INET6:
   7538 			plen = sizeof(struct in6_addr) << 3;
   7539 			break;
   7540 		default:
   7541 			plen = 0;	/*fool gcc*/
   7542 			break;
   7543 		}
   7544 
   7545 		/* check max prefix length */
   7546 		if (src0->sadb_address_prefixlen > plen ||
   7547 		    dst0->sadb_address_prefixlen > plen) {
   7548 			ipseclog((LOG_DEBUG,
   7549 			    "key_parse: illegal prefixlen.\n"));
   7550 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7551 			error = EINVAL;
   7552 			goto senderror;
   7553 		}
   7554 
   7555 		/*
   7556 		 * prefixlen == 0 is valid because there can be a case when
   7557 		 * all addresses are matched.
   7558 		 */
   7559 	}
   7560 
   7561 	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
   7562 	    key_typesw[msg->sadb_msg_type] == NULL) {
   7563 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7564 		error = EINVAL;
   7565 		goto senderror;
   7566 	}
   7567 
   7568 	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
   7569 
   7570 senderror:
   7571 	msg->sadb_msg_errno = error;
   7572 	return key_sendup_mbuf(so, m, target);
   7573 }
   7574 
   7575 static int
   7576 key_senderror(struct socket *so, struct mbuf *m, int code)
   7577 {
   7578 	struct sadb_msg *msg;
   7579 
   7580 	if (m->m_len < sizeof(struct sadb_msg))
   7581 		panic("invalid mbuf passed to key_senderror");
   7582 
   7583 	msg = mtod(m, struct sadb_msg *);
   7584 	msg->sadb_msg_errno = code;
   7585 	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   7586 }
   7587 
   7588 /*
   7589  * set the pointer to each header into message buffer.
   7590  * m will be freed on error.
   7591  * XXX larger-than-MCLBYTES extension?
   7592  */
   7593 static int
   7594 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
   7595 {
   7596 	struct mbuf *n;
   7597 	struct sadb_ext *ext;
   7598 	size_t off, end;
   7599 	int extlen;
   7600 	int toff;
   7601 
   7602 	/* sanity check */
   7603 	if (m == NULL || mhp == NULL)
   7604 		panic("key_align: NULL pointer is passed");
   7605 	if (m->m_len < sizeof(struct sadb_msg))
   7606 		panic("invalid mbuf passed to key_align");
   7607 
   7608 	/* initialize */
   7609 	memset(mhp, 0, sizeof(*mhp));
   7610 
   7611 	mhp->msg = mtod(m, struct sadb_msg *);
   7612 	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
   7613 
   7614 	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   7615 	extlen = end;	/*just in case extlen is not updated*/
   7616 	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
   7617 		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
   7618 		if (!n) {
   7619 			/* m is already freed */
   7620 			return ENOBUFS;
   7621 		}
   7622 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7623 
   7624 		/* set pointer */
   7625 		switch (ext->sadb_ext_type) {
   7626 		case SADB_EXT_SA:
   7627 		case SADB_EXT_ADDRESS_SRC:
   7628 		case SADB_EXT_ADDRESS_DST:
   7629 		case SADB_EXT_ADDRESS_PROXY:
   7630 		case SADB_EXT_LIFETIME_CURRENT:
   7631 		case SADB_EXT_LIFETIME_HARD:
   7632 		case SADB_EXT_LIFETIME_SOFT:
   7633 		case SADB_EXT_KEY_AUTH:
   7634 		case SADB_EXT_KEY_ENCRYPT:
   7635 		case SADB_EXT_IDENTITY_SRC:
   7636 		case SADB_EXT_IDENTITY_DST:
   7637 		case SADB_EXT_SENSITIVITY:
   7638 		case SADB_EXT_PROPOSAL:
   7639 		case SADB_EXT_SUPPORTED_AUTH:
   7640 		case SADB_EXT_SUPPORTED_ENCRYPT:
   7641 		case SADB_EXT_SPIRANGE:
   7642 		case SADB_X_EXT_POLICY:
   7643 		case SADB_X_EXT_SA2:
   7644 		case SADB_X_EXT_NAT_T_TYPE:
   7645 		case SADB_X_EXT_NAT_T_SPORT:
   7646 		case SADB_X_EXT_NAT_T_DPORT:
   7647 		case SADB_X_EXT_NAT_T_OAI:
   7648 		case SADB_X_EXT_NAT_T_OAR:
   7649 		case SADB_X_EXT_NAT_T_FRAG:
   7650 			/* duplicate check */
   7651 			/*
   7652 			 * XXX Are there duplication payloads of either
   7653 			 * KEY_AUTH or KEY_ENCRYPT ?
   7654 			 */
   7655 			if (mhp->ext[ext->sadb_ext_type] != NULL) {
   7656 				ipseclog((LOG_DEBUG,
   7657 				    "key_align: duplicate ext_type %u "
   7658 				    "is passed.\n", ext->sadb_ext_type));
   7659 				m_freem(m);
   7660 				PFKEY_STATINC(PFKEY_STAT_OUT_DUPEXT);
   7661 				return EINVAL;
   7662 			}
   7663 			break;
   7664 		default:
   7665 			ipseclog((LOG_DEBUG,
   7666 			    "key_align: invalid ext_type %u is passed.\n",
   7667 			    ext->sadb_ext_type));
   7668 			m_freem(m);
   7669 			PFKEY_STATINC(PFKEY_STAT_OUT_INVEXTTYPE);
   7670 			return EINVAL;
   7671 		}
   7672 
   7673 		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
   7674 
   7675 		if (key_validate_ext(ext, extlen)) {
   7676 			m_freem(m);
   7677 			PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7678 			return EINVAL;
   7679 		}
   7680 
   7681 		n = m_pulldown(m, off, extlen, &toff);
   7682 		if (!n) {
   7683 			/* m is already freed */
   7684 			return ENOBUFS;
   7685 		}
   7686 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7687 
   7688 		mhp->ext[ext->sadb_ext_type] = ext;
   7689 		mhp->extoff[ext->sadb_ext_type] = off;
   7690 		mhp->extlen[ext->sadb_ext_type] = extlen;
   7691 	}
   7692 
   7693 	if (off != end) {
   7694 		m_freem(m);
   7695 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7696 		return EINVAL;
   7697 	}
   7698 
   7699 	return 0;
   7700 }
   7701 
   7702 static int
   7703 key_validate_ext(const struct sadb_ext *ext, int len)
   7704 {
   7705 	const struct sockaddr *sa;
   7706 	enum { NONE, ADDR } checktype = NONE;
   7707 	int baselen = 0;
   7708 	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
   7709 
   7710 	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
   7711 		return EINVAL;
   7712 
   7713 	/* if it does not match minimum/maximum length, bail */
   7714 	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
   7715 	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
   7716 		return EINVAL;
   7717 	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
   7718 		return EINVAL;
   7719 	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
   7720 		return EINVAL;
   7721 
   7722 	/* more checks based on sadb_ext_type XXX need more */
   7723 	switch (ext->sadb_ext_type) {
   7724 	case SADB_EXT_ADDRESS_SRC:
   7725 	case SADB_EXT_ADDRESS_DST:
   7726 	case SADB_EXT_ADDRESS_PROXY:
   7727 		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
   7728 		checktype = ADDR;
   7729 		break;
   7730 	case SADB_EXT_IDENTITY_SRC:
   7731 	case SADB_EXT_IDENTITY_DST:
   7732 		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
   7733 		    SADB_X_IDENTTYPE_ADDR) {
   7734 			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
   7735 			checktype = ADDR;
   7736 		} else
   7737 			checktype = NONE;
   7738 		break;
   7739 	default:
   7740 		checktype = NONE;
   7741 		break;
   7742 	}
   7743 
   7744 	switch (checktype) {
   7745 	case NONE:
   7746 		break;
   7747 	case ADDR:
   7748 		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
   7749 		if (len < baselen + sal)
   7750 			return EINVAL;
   7751 		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
   7752 			return EINVAL;
   7753 		break;
   7754 	}
   7755 
   7756 	return 0;
   7757 }
   7758 
   7759 static int
   7760 key_do_init(void)
   7761 {
   7762 	int i;
   7763 
   7764 	pfkeystat_percpu = percpu_alloc(sizeof(uint64_t) * PFKEY_NSTATS);
   7765 
   7766 	callout_init(&key_timehandler_ch, 0);
   7767 
   7768 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
   7769 		LIST_INIT(&sptree[i]);
   7770 	}
   7771 
   7772 	LIST_INIT(&sahtree);
   7773 
   7774 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   7775 		LIST_INIT(&regtree[i]);
   7776 	}
   7777 
   7778 #ifndef IPSEC_NONBLOCK_ACQUIRE
   7779 	LIST_INIT(&acqtree);
   7780 #endif
   7781 	LIST_INIT(&spacqtree);
   7782 
   7783 	/* system default */
   7784 	ip4_def_policy.policy = IPSEC_POLICY_NONE;
   7785 	ip4_def_policy.refcnt++;	/*never reclaim this*/
   7786 
   7787 #ifdef INET6
   7788 	ip6_def_policy.policy = IPSEC_POLICY_NONE;
   7789 	ip6_def_policy.refcnt++;	/*never reclaim this*/
   7790 #endif
   7791 
   7792 
   7793 #ifndef IPSEC_DEBUG2
   7794 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   7795 #endif /*IPSEC_DEBUG2*/
   7796 
   7797 	/* initialize key statistics */
   7798 	keystat.getspi_count = 1;
   7799 
   7800 	aprint_verbose("IPsec: Initialized Security Association Processing.\n");
   7801 
   7802 	return (0);
   7803 }
   7804 
   7805 void
   7806 key_init(void)
   7807 {
   7808 	static ONCE_DECL(key_init_once);
   7809 
   7810 	RUN_ONCE(&key_init_once, key_do_init);
   7811 }
   7812 
   7813 /*
   7814  * XXX: maybe This function is called after INBOUND IPsec processing.
   7815  *
   7816  * Special check for tunnel-mode packets.
   7817  * We must make some checks for consistency between inner and outer IP header.
   7818  *
   7819  * xxx more checks to be provided
   7820  */
   7821 int
   7822 key_checktunnelsanity(
   7823     struct secasvar *sav,
   7824     u_int family,
   7825     void *src,
   7826     void *dst
   7827 )
   7828 {
   7829 	/* sanity check */
   7830 	if (sav->sah == NULL)
   7831 		panic("sav->sah == NULL at key_checktunnelsanity");
   7832 
   7833 	/* XXX: check inner IP header */
   7834 
   7835 	return 1;
   7836 }
   7837 
   7838 #if 0
   7839 #define hostnamelen	strlen(hostname)
   7840 
   7841 /*
   7842  * Get FQDN for the host.
   7843  * If the administrator configured hostname (by hostname(1)) without
   7844  * domain name, returns nothing.
   7845  */
   7846 static const char *
   7847 key_getfqdn(void)
   7848 {
   7849 	int i;
   7850 	int hasdot;
   7851 	static char fqdn[MAXHOSTNAMELEN + 1];
   7852 
   7853 	if (!hostnamelen)
   7854 		return NULL;
   7855 
   7856 	/* check if it comes with domain name. */
   7857 	hasdot = 0;
   7858 	for (i = 0; i < hostnamelen; i++) {
   7859 		if (hostname[i] == '.')
   7860 			hasdot++;
   7861 	}
   7862 	if (!hasdot)
   7863 		return NULL;
   7864 
   7865 	/* NOTE: hostname may not be NUL-terminated. */
   7866 	memset(fqdn, 0, sizeof(fqdn));
   7867 	memcpy(fqdn, hostname, hostnamelen);
   7868 	fqdn[hostnamelen] = '\0';
   7869 	return fqdn;
   7870 }
   7871 
   7872 /*
   7873  * get username@FQDN for the host/user.
   7874  */
   7875 static const char *
   7876 key_getuserfqdn(void)
   7877 {
   7878 	const char *host;
   7879 	static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
   7880 	struct proc *p = curproc;
   7881 	char *q;
   7882 
   7883 	if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
   7884 		return NULL;
   7885 	if (!(host = key_getfqdn()))
   7886 		return NULL;
   7887 
   7888 	/* NOTE: s_login may not be-NUL terminated. */
   7889 	memset(userfqdn, 0, sizeof(userfqdn));
   7890 	memcpy(userfqdn, Mp->p_pgrp->pg_session->s_login, AXLOGNAME);
   7891 	userfqdn[MAXLOGNAME] = '\0';	/* safeguard */
   7892 	q = userfqdn + strlen(userfqdn);
   7893 	*q++ = '@';
   7894 	memcpy(q, host, strlen(host));
   7895 	q += strlen(host);
   7896 	*q++ = '\0';
   7897 
   7898 	return userfqdn;
   7899 }
   7900 #endif
   7901 
   7902 /* record data transfer on SA, and update timestamps */
   7903 void
   7904 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
   7905 {
   7906 	IPSEC_ASSERT(sav != NULL, ("key_sa_recordxfer: Null secasvar"));
   7907 	IPSEC_ASSERT(m != NULL, ("key_sa_recordxfer: Null mbuf"));
   7908 	if (!sav->lft_c)
   7909 		return;
   7910 
   7911 	/*
   7912 	 * XXX Currently, there is a difference of bytes size
   7913 	 * between inbound and outbound processing.
   7914 	 */
   7915 	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
   7916 	/* to check bytes lifetime is done in key_timehandler(). */
   7917 
   7918 	/*
   7919 	 * We use the number of packets as the unit of
   7920 	 * sadb_lifetime_allocations.  We increment the variable
   7921 	 * whenever {esp,ah}_{in,out}put is called.
   7922 	 */
   7923 	sav->lft_c->sadb_lifetime_allocations++;
   7924 	/* XXX check for expires? */
   7925 
   7926 	/*
   7927 	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
   7928 	 * in seconds.  HARD and SOFT lifetime are measured by the time
   7929 	 * difference (again in seconds) from sadb_lifetime_usetime.
   7930 	 *
   7931 	 *	usetime
   7932 	 *	v     expire   expire
   7933 	 * -----+-----+--------+---> t
   7934 	 *	<--------------> HARD
   7935 	 *	<-----> SOFT
   7936 	 */
   7937 	sav->lft_c->sadb_lifetime_usetime = time_uptime;
   7938 	/* XXX check for expires? */
   7939 
   7940 	return;
   7941 }
   7942 
   7943 /* dumb version */
   7944 void
   7945 key_sa_routechange(struct sockaddr *dst)
   7946 {
   7947 	struct secashead *sah;
   7948 	struct route *ro;
   7949 	const struct sockaddr *sa;
   7950 
   7951 	LIST_FOREACH(sah, &sahtree, chain) {
   7952 		ro = &sah->sa_route;
   7953 		sa = rtcache_getdst(ro);
   7954 		if (sa != NULL && dst->sa_len == sa->sa_len &&
   7955 		    memcmp(dst, sa, dst->sa_len) == 0)
   7956 			rtcache_free(ro);
   7957 	}
   7958 
   7959 	return;
   7960 }
   7961 
   7962 static void
   7963 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
   7964 {
   7965 	if (sav == NULL)
   7966 		panic("key_sa_chgstate called with sav == NULL");
   7967 
   7968 	if (sav->state == state)
   7969 		return;
   7970 
   7971 	if (__LIST_CHAINED(sav))
   7972 		LIST_REMOVE(sav, chain);
   7973 
   7974 	sav->state = state;
   7975 	LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
   7976 }
   7977 
   7978 /* XXX too much? */
   7979 static struct mbuf *
   7980 key_alloc_mbuf(int l)
   7981 {
   7982 	struct mbuf *m = NULL, *n;
   7983 	int len, t;
   7984 
   7985 	len = l;
   7986 	while (len > 0) {
   7987 		MGET(n, M_DONTWAIT, MT_DATA);
   7988 		if (n && len > MLEN)
   7989 			MCLGET(n, M_DONTWAIT);
   7990 		if (!n) {
   7991 			m_freem(m);
   7992 			return NULL;
   7993 		}
   7994 
   7995 		n->m_next = NULL;
   7996 		n->m_len = 0;
   7997 		n->m_len = M_TRAILINGSPACE(n);
   7998 		/* use the bottom of mbuf, hoping we can prepend afterwards */
   7999 		if (n->m_len > len) {
   8000 			t = (n->m_len - len) & ~(sizeof(long) - 1);
   8001 			n->m_data += t;
   8002 			n->m_len = len;
   8003 		}
   8004 
   8005 		len -= n->m_len;
   8006 
   8007 		if (m)
   8008 			m_cat(m, n);
   8009 		else
   8010 			m = n;
   8011 	}
   8012 
   8013 	return m;
   8014 }
   8015 
   8016 static struct mbuf *
   8017 key_setdump(u_int8_t req_satype, int *errorp, uint32_t pid)
   8018 {
   8019 	struct secashead *sah;
   8020 	struct secasvar *sav;
   8021 	u_int16_t proto;
   8022 	u_int stateidx;
   8023 	u_int8_t satype;
   8024 	u_int8_t state;
   8025 	int cnt;
   8026 	struct mbuf *m, *n;
   8027 
   8028 	/* map satype to proto */
   8029 	if ((proto = key_satype2proto(req_satype)) == 0) {
   8030 		*errorp = EINVAL;
   8031 		return (NULL);
   8032 	}
   8033 
   8034 	/* count sav entries to be sent to the userland. */
   8035 	cnt = 0;
   8036 	LIST_FOREACH(sah, &sahtree, chain) {
   8037 		if (req_satype != SADB_SATYPE_UNSPEC &&
   8038 		    proto != sah->saidx.proto)
   8039 			continue;
   8040 
   8041 		for (stateidx = 0;
   8042 		     stateidx < _ARRAYLEN(saorder_state_any);
   8043 		     stateidx++) {
   8044 			state = saorder_state_any[stateidx];
   8045 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   8046 				cnt++;
   8047 			}
   8048 		}
   8049 	}
   8050 
   8051 	if (cnt == 0) {
   8052 		*errorp = ENOENT;
   8053 		return (NULL);
   8054 	}
   8055 
   8056 	/* send this to the userland, one at a time. */
   8057 	m = NULL;
   8058 	LIST_FOREACH(sah, &sahtree, chain) {
   8059 		if (req_satype != SADB_SATYPE_UNSPEC &&
   8060 		    proto != sah->saidx.proto)
   8061 			continue;
   8062 
   8063 		/* map proto to satype */
   8064 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
   8065 			m_freem(m);
   8066 			*errorp = EINVAL;
   8067 			return (NULL);
   8068 		}
   8069 
   8070 		for (stateidx = 0;
   8071 		     stateidx < _ARRAYLEN(saorder_state_any);
   8072 		     stateidx++) {
   8073 			state = saorder_state_any[stateidx];
   8074 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   8075 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   8076 				    --cnt, pid);
   8077 				if (!n) {
   8078 					m_freem(m);
   8079 					*errorp = ENOBUFS;
   8080 					return (NULL);
   8081 				}
   8082 
   8083 				if (!m)
   8084 					m = n;
   8085 				else
   8086 					m_cat(m, n);
   8087 			}
   8088 		}
   8089 	}
   8090 
   8091 	if (!m) {
   8092 		*errorp = EINVAL;
   8093 		return (NULL);
   8094 	}
   8095 
   8096 	if ((m->m_flags & M_PKTHDR) != 0) {
   8097 		m->m_pkthdr.len = 0;
   8098 		for (n = m; n; n = n->m_next)
   8099 			m->m_pkthdr.len += n->m_len;
   8100 	}
   8101 
   8102 	*errorp = 0;
   8103 	return (m);
   8104 }
   8105 
   8106 static struct mbuf *
   8107 key_setspddump(int *errorp, pid_t pid)
   8108 {
   8109 	struct secpolicy *sp;
   8110 	int cnt;
   8111 	u_int dir;
   8112 	struct mbuf *m, *n;
   8113 
   8114 	/* search SPD entry and get buffer size. */
   8115 	cnt = 0;
   8116 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   8117 		LIST_FOREACH(sp, &sptree[dir], chain) {
   8118 			cnt++;
   8119 		}
   8120 	}
   8121 
   8122 	if (cnt == 0) {
   8123 		*errorp = ENOENT;
   8124 		return (NULL);
   8125 	}
   8126 
   8127 	m = NULL;
   8128 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   8129 		LIST_FOREACH(sp, &sptree[dir], chain) {
   8130 			--cnt;
   8131 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
   8132 
   8133 			if (!n) {
   8134 				*errorp = ENOBUFS;
   8135 				m_freem(m);
   8136 				return (NULL);
   8137 			}
   8138 			if (!m)
   8139 				m = n;
   8140 			else {
   8141 				m->m_pkthdr.len += n->m_pkthdr.len;
   8142 				m_cat(m, n);
   8143 			}
   8144 		}
   8145 	}
   8146 
   8147 	*errorp = 0;
   8148 	return (m);
   8149 }
   8150 
   8151 int
   8152 key_get_used(void) {
   8153 	return !LIST_EMPTY(&sptree[IPSEC_DIR_INBOUND]) ||
   8154 	    !LIST_EMPTY(&sptree[IPSEC_DIR_OUTBOUND]);
   8155 }
   8156 
   8157 void
   8158 key_update_used(void)
   8159 {
   8160 	switch (ipsec_enabled) {
   8161 	default:
   8162 	case 0:
   8163 #ifdef notyet
   8164 		/* XXX: racy */
   8165 		ipsec_used = 0;
   8166 #endif
   8167 		break;
   8168 	case 1:
   8169 #ifndef notyet
   8170 		/* XXX: racy */
   8171 		if (!ipsec_used)
   8172 #endif
   8173 		ipsec_used = key_get_used();
   8174 		break;
   8175 	case 2:
   8176 		ipsec_used = 1;
   8177 		break;
   8178 	}
   8179 }
   8180 
   8181 static int
   8182 sysctl_net_key_dumpsa(SYSCTLFN_ARGS)
   8183 {
   8184 	struct mbuf *m, *n;
   8185 	int err2 = 0;
   8186 	char *p, *ep;
   8187 	size_t len;
   8188 	int s, error;
   8189 
   8190 	if (newp)
   8191 		return (EPERM);
   8192 	if (namelen != 1)
   8193 		return (EINVAL);
   8194 
   8195 	s = splsoftnet();
   8196 	m = key_setdump(name[0], &error, l->l_proc->p_pid);
   8197 	splx(s);
   8198 	if (!m)
   8199 		return (error);
   8200 	if (!oldp)
   8201 		*oldlenp = m->m_pkthdr.len;
   8202 	else {
   8203 		p = oldp;
   8204 		if (*oldlenp < m->m_pkthdr.len) {
   8205 			err2 = ENOMEM;
   8206 			ep = p + *oldlenp;
   8207 		} else {
   8208 			*oldlenp = m->m_pkthdr.len;
   8209 			ep = p + m->m_pkthdr.len;
   8210 		}
   8211 		for (n = m; n; n = n->m_next) {
   8212 			len =  (ep - p < n->m_len) ?
   8213 				ep - p : n->m_len;
   8214 			error = copyout(mtod(n, const void *), p, len);
   8215 			p += len;
   8216 			if (error)
   8217 				break;
   8218 		}
   8219 		if (error == 0)
   8220 			error = err2;
   8221 	}
   8222 	m_freem(m);
   8223 
   8224 	return (error);
   8225 }
   8226 
   8227 static int
   8228 sysctl_net_key_dumpsp(SYSCTLFN_ARGS)
   8229 {
   8230 	struct mbuf *m, *n;
   8231 	int err2 = 0;
   8232 	char *p, *ep;
   8233 	size_t len;
   8234 	int s, error;
   8235 
   8236 	if (newp)
   8237 		return (EPERM);
   8238 	if (namelen != 0)
   8239 		return (EINVAL);
   8240 
   8241 	s = splsoftnet();
   8242 	m = key_setspddump(&error, l->l_proc->p_pid);
   8243 	splx(s);
   8244 	if (!m)
   8245 		return (error);
   8246 	if (!oldp)
   8247 		*oldlenp = m->m_pkthdr.len;
   8248 	else {
   8249 		p = oldp;
   8250 		if (*oldlenp < m->m_pkthdr.len) {
   8251 			err2 = ENOMEM;
   8252 			ep = p + *oldlenp;
   8253 		} else {
   8254 			*oldlenp = m->m_pkthdr.len;
   8255 			ep = p + m->m_pkthdr.len;
   8256 		}
   8257 		for (n = m; n; n = n->m_next) {
   8258 			len =  (ep - p < n->m_len) ?
   8259 				ep - p : n->m_len;
   8260 			error = copyout(mtod(n, const void *), p, len);
   8261 			p += len;
   8262 			if (error)
   8263 				break;
   8264 		}
   8265 		if (error == 0)
   8266 			error = err2;
   8267 	}
   8268 	m_freem(m);
   8269 
   8270 	return (error);
   8271 }
   8272 
   8273 /*
   8274  * Create sysctl tree for native IPSEC key knobs, originally
   8275  * under name "net.keyv2"  * with MIB number { CTL_NET, PF_KEY_V2. }.
   8276  * However, sysctl(8) never checked for nodes under { CTL_NET, PF_KEY_V2 };
   8277  * and in any case the part of our sysctl namespace used for dumping the
   8278  * SPD and SA database  *HAS* to be compatible with the KAME sysctl
   8279  * namespace, for API reasons.
   8280  *
   8281  * Pending a consensus on the right way  to fix this, add a level of
   8282  * indirection in how we number the `native' IPSEC key nodes;
   8283  * and (as requested by Andrew Brown)  move registration of the
   8284  * KAME-compatible names  to a separate function.
   8285  */
   8286 #if 0
   8287 #  define IPSEC_PFKEY PF_KEY_V2
   8288 # define IPSEC_PFKEY_NAME "keyv2"
   8289 #else
   8290 #  define IPSEC_PFKEY PF_KEY
   8291 # define IPSEC_PFKEY_NAME "key"
   8292 #endif
   8293 
   8294 static int
   8295 sysctl_net_key_stats(SYSCTLFN_ARGS)
   8296 {
   8297 
   8298 	return (NETSTAT_SYSCTL(pfkeystat_percpu, PFKEY_NSTATS));
   8299 }
   8300 
   8301 SYSCTL_SETUP(sysctl_net_keyv2_setup, "sysctl net.keyv2 subtree setup")
   8302 {
   8303 
   8304 	sysctl_createv(clog, 0, NULL, NULL,
   8305 		       CTLFLAG_PERMANENT,
   8306 		       CTLTYPE_NODE, IPSEC_PFKEY_NAME, NULL,
   8307 		       NULL, 0, NULL, 0,
   8308 		       CTL_NET, IPSEC_PFKEY, CTL_EOL);
   8309 
   8310 	sysctl_createv(clog, 0, NULL, NULL,
   8311 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8312 		       CTLTYPE_INT, "debug", NULL,
   8313 		       NULL, 0, &key_debug_level, 0,
   8314 		       CTL_NET, IPSEC_PFKEY, KEYCTL_DEBUG_LEVEL, CTL_EOL);
   8315 	sysctl_createv(clog, 0, NULL, NULL,
   8316 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8317 		       CTLTYPE_INT, "spi_try", NULL,
   8318 		       NULL, 0, &key_spi_trycnt, 0,
   8319 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_TRY, CTL_EOL);
   8320 	sysctl_createv(clog, 0, NULL, NULL,
   8321 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8322 		       CTLTYPE_INT, "spi_min_value", NULL,
   8323 		       NULL, 0, &key_spi_minval, 0,
   8324 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MIN_VALUE, CTL_EOL);
   8325 	sysctl_createv(clog, 0, NULL, NULL,
   8326 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8327 		       CTLTYPE_INT, "spi_max_value", NULL,
   8328 		       NULL, 0, &key_spi_maxval, 0,
   8329 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MAX_VALUE, CTL_EOL);
   8330 	sysctl_createv(clog, 0, NULL, NULL,
   8331 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8332 		       CTLTYPE_INT, "random_int", NULL,
   8333 		       NULL, 0, &key_int_random, 0,
   8334 		       CTL_NET, IPSEC_PFKEY, KEYCTL_RANDOM_INT, CTL_EOL);
   8335 	sysctl_createv(clog, 0, NULL, NULL,
   8336 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8337 		       CTLTYPE_INT, "larval_lifetime", NULL,
   8338 		       NULL, 0, &key_larval_lifetime, 0,
   8339 		       CTL_NET, IPSEC_PFKEY, KEYCTL_LARVAL_LIFETIME, CTL_EOL);
   8340 	sysctl_createv(clog, 0, NULL, NULL,
   8341 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8342 		       CTLTYPE_INT, "blockacq_count", NULL,
   8343 		       NULL, 0, &key_blockacq_count, 0,
   8344 		       CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_COUNT, CTL_EOL);
   8345 	sysctl_createv(clog, 0, NULL, NULL,
   8346 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8347 		       CTLTYPE_INT, "blockacq_lifetime", NULL,
   8348 		       NULL, 0, &key_blockacq_lifetime, 0,
   8349 		       CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_LIFETIME, CTL_EOL);
   8350 	sysctl_createv(clog, 0, NULL, NULL,
   8351 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8352 		       CTLTYPE_INT, "esp_keymin", NULL,
   8353 		       NULL, 0, &ipsec_esp_keymin, 0,
   8354 		       CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_KEYMIN, CTL_EOL);
   8355 	sysctl_createv(clog, 0, NULL, NULL,
   8356 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8357 		       CTLTYPE_INT, "prefered_oldsa", NULL,
   8358 		       NULL, 0, &key_prefered_oldsa, 0,
   8359 		       CTL_NET, PF_KEY, KEYCTL_PREFERED_OLDSA, CTL_EOL);
   8360 	sysctl_createv(clog, 0, NULL, NULL,
   8361 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8362 		       CTLTYPE_INT, "esp_auth", NULL,
   8363 		       NULL, 0, &ipsec_esp_auth, 0,
   8364 		       CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_AUTH, CTL_EOL);
   8365 	sysctl_createv(clog, 0, NULL, NULL,
   8366 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8367 		       CTLTYPE_INT, "ah_keymin", NULL,
   8368 		       NULL, 0, &ipsec_ah_keymin, 0,
   8369 		       CTL_NET, IPSEC_PFKEY, KEYCTL_AH_KEYMIN, CTL_EOL);
   8370 	sysctl_createv(clog, 0, NULL, NULL,
   8371 		       CTLFLAG_PERMANENT,
   8372 		       CTLTYPE_STRUCT, "stats",
   8373 		       SYSCTL_DESCR("PF_KEY statistics"),
   8374 		       sysctl_net_key_stats, 0, NULL, 0,
   8375 		       CTL_NET, IPSEC_PFKEY, CTL_CREATE, CTL_EOL);
   8376 }
   8377 
   8378 /*
   8379  * Register sysctl names used by setkey(8). For historical reasons,
   8380  * and to share a single API, these names appear under { CTL_NET, PF_KEY }
   8381  * for both IPSEC and KAME IPSEC.
   8382  */
   8383 SYSCTL_SETUP(sysctl_net_key_compat_setup, "sysctl net.key subtree setup for IPSEC")
   8384 {
   8385 
   8386 	sysctl_createv(clog, 0, NULL, NULL,
   8387 		       CTLFLAG_PERMANENT,
   8388 		       CTLTYPE_NODE, "key", NULL,
   8389 		       NULL, 0, NULL, 0,
   8390 		       CTL_NET, PF_KEY, CTL_EOL);
   8391 
   8392 	/* Register the net.key.dump{sa,sp} nodes used by setkey(8). */
   8393 	sysctl_createv(clog, 0, NULL, NULL,
   8394 		       CTLFLAG_PERMANENT,
   8395 		       CTLTYPE_STRUCT, "dumpsa", NULL,
   8396 		       sysctl_net_key_dumpsa, 0, NULL, 0,
   8397 		       CTL_NET, PF_KEY, KEYCTL_DUMPSA, CTL_EOL);
   8398 	sysctl_createv(clog, 0, NULL, NULL,
   8399 		       CTLFLAG_PERMANENT,
   8400 		       CTLTYPE_STRUCT, "dumpsp", NULL,
   8401 		       sysctl_net_key_dumpsp, 0, NULL, 0,
   8402 		       CTL_NET, PF_KEY, KEYCTL_DUMPSP, CTL_EOL);
   8403 }
   8404