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