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