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