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