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