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