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