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