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