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