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