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