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