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