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