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