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