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