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