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