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