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