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