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