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