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