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