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