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