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