xref: /netbsd-src/sys/netipsec/key.c (revision 5bbd2a12505d72a8177929a37b5cee489d0a1cfd)
1 /*	$NetBSD: key.c,v 1.78 2012/08/30 12:16:49 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.78 2012/08/30 12:16:49 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 			explicit_bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
3044 		if (sav->key_enc != NULL)
3045 			explicit_bzero(_KEYBUF(sav->key_enc), _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->replay != NULL) {
3056 		KFREE(sav->replay);
3057 		sav->replay = NULL;
3058 	}
3059 	if (sav->lft_c != NULL) {
3060 		KFREE(sav->lft_c);
3061 		sav->lft_c = NULL;
3062 	}
3063 	if (sav->lft_h != NULL) {
3064 		KFREE(sav->lft_h);
3065 		sav->lft_h = NULL;
3066 	}
3067 	if (sav->lft_s != NULL) {
3068 		KFREE(sav->lft_s);
3069 		sav->lft_s = NULL;
3070 	}
3071 
3072 	KFREE(sav);
3073 
3074 	return;
3075 }
3076 
3077 /*
3078  * search SAD.
3079  * OUT:
3080  *	NULL	: not found
3081  *	others	: found, pointer to a SA.
3082  */
3083 static struct secashead *
3084 key_getsah(const struct secasindex *saidx)
3085 {
3086 	struct secashead *sah;
3087 
3088 	LIST_FOREACH(sah, &sahtree, chain) {
3089 		if (sah->state == SADB_SASTATE_DEAD)
3090 			continue;
3091 		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
3092 			return sah;
3093 	}
3094 
3095 	return NULL;
3096 }
3097 
3098 /*
3099  * check not to be duplicated SPI.
3100  * NOTE: this function is too slow due to searching all SAD.
3101  * OUT:
3102  *	NULL	: not found
3103  *	others	: found, pointer to a SA.
3104  */
3105 static struct secasvar *
3106 key_checkspidup(const struct secasindex *saidx, u_int32_t spi)
3107 {
3108 	struct secashead *sah;
3109 	struct secasvar *sav;
3110 
3111 	/* check address family */
3112 	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
3113 		ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n"));
3114 		return NULL;
3115 	}
3116 
3117 	/* check all SAD */
3118 	LIST_FOREACH(sah, &sahtree, chain) {
3119 		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
3120 			continue;
3121 		sav = key_getsavbyspi(sah, spi);
3122 		if (sav != NULL)
3123 			return sav;
3124 	}
3125 
3126 	return NULL;
3127 }
3128 
3129 /*
3130  * search SAD litmited alive SA, protocol, SPI.
3131  * OUT:
3132  *	NULL	: not found
3133  *	others	: found, pointer to a SA.
3134  */
3135 static struct secasvar *
3136 key_getsavbyspi(struct secashead *sah, u_int32_t spi)
3137 {
3138 	struct secasvar *sav;
3139 	u_int stateidx, state;
3140 
3141 	/* search all status */
3142 	for (stateidx = 0;
3143 	     stateidx < _ARRAYLEN(saorder_state_alive);
3144 	     stateidx++) {
3145 
3146 		state = saorder_state_alive[stateidx];
3147 		LIST_FOREACH(sav, &sah->savtree[state], chain) {
3148 
3149 			/* sanity check */
3150 			if (sav->state != state) {
3151 				ipseclog((LOG_DEBUG, "key_getsavbyspi: "
3152 				    "invalid sav->state (queue: %d SA: %d)\n",
3153 				    state, sav->state));
3154 				continue;
3155 			}
3156 
3157 			if (sav->spi == spi)
3158 				return sav;
3159 		}
3160 	}
3161 
3162 	return NULL;
3163 }
3164 
3165 /*
3166  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3167  * You must update these if need.
3168  * OUT:	0:	success.
3169  *	!0:	failure.
3170  *
3171  * does not modify mbuf.  does not free mbuf on error.
3172  */
3173 static int
3174 key_setsaval(struct secasvar *sav, struct mbuf *m,
3175 	     const struct sadb_msghdr *mhp)
3176 {
3177 	int error = 0;
3178 
3179 	/* sanity check */
3180 	if (m == NULL || mhp == NULL || mhp->msg == NULL)
3181 		panic("key_setsaval: NULL pointer is passed");
3182 
3183 	/* initialization */
3184 	sav->replay = NULL;
3185 	sav->key_auth = NULL;
3186 	sav->key_enc = NULL;
3187 	sav->lft_c = NULL;
3188 	sav->lft_h = NULL;
3189 	sav->lft_s = NULL;
3190 	sav->tdb_xform = NULL;		/* transform */
3191 	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
3192 	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
3193 	sav->tdb_compalgxform = NULL;	/* compression algorithm */
3194 #ifdef IPSEC_NAT_T
3195 	sav->natt_type = 0;
3196 	sav->esp_frag = 0;
3197 #endif
3198 
3199 	/* SA */
3200 	if (mhp->ext[SADB_EXT_SA] != NULL) {
3201 		const struct sadb_sa *sa0;
3202 
3203 		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3204 		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3205 			error = EINVAL;
3206 			goto fail;
3207 		}
3208 
3209 		sav->alg_auth = sa0->sadb_sa_auth;
3210 		sav->alg_enc = sa0->sadb_sa_encrypt;
3211 		sav->flags = sa0->sadb_sa_flags;
3212 
3213 		/* replay window */
3214 		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3215 			sav->replay = (struct secreplay *)
3216 				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_SECA, M_NOWAIT|M_ZERO);
3217 			if (sav->replay == NULL) {
3218 				ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3219 				error = ENOBUFS;
3220 				goto fail;
3221 			}
3222 			if (sa0->sadb_sa_replay != 0)
3223 				sav->replay->bitmap = (char*)(sav->replay+1);
3224 			sav->replay->wsize = sa0->sadb_sa_replay;
3225 		}
3226 	}
3227 
3228 	/* Authentication keys */
3229 	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3230 		const struct sadb_key *key0;
3231 		int len;
3232 
3233 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3234 		len = mhp->extlen[SADB_EXT_KEY_AUTH];
3235 
3236 		error = 0;
3237 		if (len < sizeof(*key0)) {
3238 			error = EINVAL;
3239 			goto fail;
3240 		}
3241 		switch (mhp->msg->sadb_msg_satype) {
3242 		case SADB_SATYPE_AH:
3243 		case SADB_SATYPE_ESP:
3244 		case SADB_X_SATYPE_TCPSIGNATURE:
3245 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3246 			    sav->alg_auth != SADB_X_AALG_NULL)
3247 				error = EINVAL;
3248 			break;
3249 		case SADB_X_SATYPE_IPCOMP:
3250 		default:
3251 			error = EINVAL;
3252 			break;
3253 		}
3254 		if (error) {
3255 			ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n"));
3256 			goto fail;
3257 		}
3258 
3259 		sav->key_auth = (struct sadb_key *)key_newbuf(key0, len);
3260 		if (sav->key_auth == NULL) {
3261 			ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3262 			error = ENOBUFS;
3263 			goto fail;
3264 		}
3265 	}
3266 
3267 	/* Encryption key */
3268 	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3269 		const struct sadb_key *key0;
3270 		int len;
3271 
3272 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3273 		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3274 
3275 		error = 0;
3276 		if (len < sizeof(*key0)) {
3277 			error = EINVAL;
3278 			goto fail;
3279 		}
3280 		switch (mhp->msg->sadb_msg_satype) {
3281 		case SADB_SATYPE_ESP:
3282 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3283 			    sav->alg_enc != SADB_EALG_NULL) {
3284 				error = EINVAL;
3285 				break;
3286 			}
3287 			sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
3288 			if (sav->key_enc == NULL) {
3289 				ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3290 				error = ENOBUFS;
3291 				goto fail;
3292 			}
3293 			break;
3294 		case SADB_X_SATYPE_IPCOMP:
3295 			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3296 				error = EINVAL;
3297 			sav->key_enc = NULL;	/*just in case*/
3298 			break;
3299 		case SADB_SATYPE_AH:
3300 		case SADB_X_SATYPE_TCPSIGNATURE:
3301 		default:
3302 			error = EINVAL;
3303 			break;
3304 		}
3305 		if (error) {
3306 			ipseclog((LOG_DEBUG, "key_setsatval: invalid key_enc value.\n"));
3307 			goto fail;
3308 		}
3309 	}
3310 
3311 	/* set iv */
3312 	sav->ivlen = 0;
3313 
3314 	switch (mhp->msg->sadb_msg_satype) {
3315 	case SADB_SATYPE_AH:
3316 		error = xform_init(sav, XF_AH);
3317 		break;
3318 	case SADB_SATYPE_ESP:
3319 		error = xform_init(sav, XF_ESP);
3320 		break;
3321 	case SADB_X_SATYPE_IPCOMP:
3322 		error = xform_init(sav, XF_IPCOMP);
3323 		break;
3324 	case SADB_X_SATYPE_TCPSIGNATURE:
3325 		error = xform_init(sav, XF_TCPSIGNATURE);
3326 		break;
3327 	}
3328 	if (error) {
3329 		ipseclog((LOG_DEBUG,
3330 			"key_setsaval: unable to initialize SA type %u.\n",
3331 		        mhp->msg->sadb_msg_satype));
3332 		goto fail;
3333 	}
3334 
3335 	/* reset created */
3336 	sav->created = time_uptime;
3337 
3338 	/* make lifetime for CURRENT */
3339 	KMALLOC(sav->lft_c, struct sadb_lifetime *,
3340 	    sizeof(struct sadb_lifetime));
3341 	if (sav->lft_c == NULL) {
3342 		ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3343 		error = ENOBUFS;
3344 		goto fail;
3345 	}
3346 
3347 	sav->lft_c->sadb_lifetime_len =
3348 	    PFKEY_UNIT64(sizeof(struct sadb_lifetime));
3349 	sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
3350 	sav->lft_c->sadb_lifetime_allocations = 0;
3351 	sav->lft_c->sadb_lifetime_bytes = 0;
3352 	sav->lft_c->sadb_lifetime_addtime = time_uptime;
3353 	sav->lft_c->sadb_lifetime_usetime = 0;
3354 
3355 	/* lifetimes for HARD and SOFT */
3356     {
3357 	const struct sadb_lifetime *lft0;
3358 
3359 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3360 	if (lft0 != NULL) {
3361 		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3362 			error = EINVAL;
3363 			goto fail;
3364 		}
3365 		sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0,
3366 		    sizeof(*lft0));
3367 		if (sav->lft_h == NULL) {
3368 			ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3369 			error = ENOBUFS;
3370 			goto fail;
3371 		}
3372 		/* to be initialize ? */
3373 	}
3374 
3375 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3376 	if (lft0 != NULL) {
3377 		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3378 			error = EINVAL;
3379 			goto fail;
3380 		}
3381 		sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0,
3382 		    sizeof(*lft0));
3383 		if (sav->lft_s == NULL) {
3384 			ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3385 			error = ENOBUFS;
3386 			goto fail;
3387 		}
3388 		/* to be initialize ? */
3389 	}
3390     }
3391 
3392 	return 0;
3393 
3394  fail:
3395 	/* initialization */
3396 	if (sav->replay != NULL) {
3397 		KFREE(sav->replay);
3398 		sav->replay = NULL;
3399 	}
3400 	if (sav->key_auth != NULL) {
3401 		KFREE(sav->key_auth);
3402 		sav->key_auth = NULL;
3403 	}
3404 	if (sav->key_enc != NULL) {
3405 		KFREE(sav->key_enc);
3406 		sav->key_enc = NULL;
3407 	}
3408 	if (sav->lft_c != NULL) {
3409 		KFREE(sav->lft_c);
3410 		sav->lft_c = NULL;
3411 	}
3412 	if (sav->lft_h != NULL) {
3413 		KFREE(sav->lft_h);
3414 		sav->lft_h = NULL;
3415 	}
3416 	if (sav->lft_s != NULL) {
3417 		KFREE(sav->lft_s);
3418 		sav->lft_s = NULL;
3419 	}
3420 
3421 	return error;
3422 }
3423 
3424 /*
3425  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3426  * OUT:	0:	valid
3427  *	other:	errno
3428  */
3429 static int
3430 key_mature(struct secasvar *sav)
3431 {
3432 	int error;
3433 
3434 	/* check SPI value */
3435 	switch (sav->sah->saidx.proto) {
3436 	case IPPROTO_ESP:
3437 	case IPPROTO_AH:
3438 		if (ntohl(sav->spi) <= 255) {
3439 			ipseclog((LOG_DEBUG,
3440 			    "key_mature: illegal range of SPI %u.\n",
3441 			    (u_int32_t)ntohl(sav->spi)));
3442 			return EINVAL;
3443 		}
3444 		break;
3445 	}
3446 
3447 	/* check satype */
3448 	switch (sav->sah->saidx.proto) {
3449 	case IPPROTO_ESP:
3450 		/* check flags */
3451 		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3452 		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3453 			ipseclog((LOG_DEBUG, "key_mature: "
3454 			    "invalid flag (derived) given to old-esp.\n"));
3455 			return EINVAL;
3456 		}
3457 		error = xform_init(sav, XF_ESP);
3458 		break;
3459 	case IPPROTO_AH:
3460 		/* check flags */
3461 		if (sav->flags & SADB_X_EXT_DERIV) {
3462 			ipseclog((LOG_DEBUG, "key_mature: "
3463 			    "invalid flag (derived) given to AH SA.\n"));
3464 			return EINVAL;
3465 		}
3466 		if (sav->alg_enc != SADB_EALG_NONE) {
3467 			ipseclog((LOG_DEBUG, "key_mature: "
3468 			    "protocol and algorithm mismated.\n"));
3469 			return(EINVAL);
3470 		}
3471 		error = xform_init(sav, XF_AH);
3472 		break;
3473 	case IPPROTO_IPCOMP:
3474 		if (sav->alg_auth != SADB_AALG_NONE) {
3475 			ipseclog((LOG_DEBUG, "key_mature: "
3476 				"protocol and algorithm mismated.\n"));
3477 			return(EINVAL);
3478 		}
3479 		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3480 		 && ntohl(sav->spi) >= 0x10000) {
3481 			ipseclog((LOG_DEBUG, "key_mature: invalid cpi for IPComp.\n"));
3482 			return(EINVAL);
3483 		}
3484 		error = xform_init(sav, XF_IPCOMP);
3485 		break;
3486 	case IPPROTO_TCP:
3487 		if (sav->alg_enc != SADB_EALG_NONE) {
3488 			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3489 				"mismated.\n", __func__));
3490 			return(EINVAL);
3491 		}
3492 		error = xform_init(sav, XF_TCPSIGNATURE);
3493 		break;
3494 	default:
3495 		ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n"));
3496 		error = EPROTONOSUPPORT;
3497 		break;
3498 	}
3499 	if (error == 0)
3500 		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3501 	return (error);
3502 }
3503 
3504 /*
3505  * subroutine for SADB_GET and SADB_DUMP.
3506  */
3507 static struct mbuf *
3508 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3509 	      u_int32_t seq, u_int32_t pid)
3510 {
3511 	struct mbuf *result = NULL, *tres = NULL, *m;
3512 	int l = 0;
3513 	int i;
3514 	void *p;
3515 	struct sadb_lifetime lt;
3516 	int dumporder[] = {
3517 		SADB_EXT_SA, SADB_X_EXT_SA2,
3518 		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3519 		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3520 		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3521 		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3522 		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3523 #ifdef IPSEC_NAT_T
3524 		SADB_X_EXT_NAT_T_TYPE,
3525 		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3526 		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3527 		SADB_X_EXT_NAT_T_FRAG,
3528 #endif
3529 
3530 	};
3531 
3532 	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3533 	if (m == NULL)
3534 		goto fail;
3535 	result = m;
3536 
3537 	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3538 		m = NULL;
3539 		p = NULL;
3540 		switch (dumporder[i]) {
3541 		case SADB_EXT_SA:
3542 			m = key_setsadbsa(sav);
3543 			break;
3544 
3545 		case SADB_X_EXT_SA2:
3546 			m = key_setsadbxsa2(sav->sah->saidx.mode,
3547 					sav->replay ? sav->replay->count : 0,
3548 					sav->sah->saidx.reqid);
3549 			break;
3550 
3551 		case SADB_EXT_ADDRESS_SRC:
3552 			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3553 			    &sav->sah->saidx.src.sa,
3554 			    FULLMASK, IPSEC_ULPROTO_ANY);
3555 			break;
3556 
3557 		case SADB_EXT_ADDRESS_DST:
3558 			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3559 			    &sav->sah->saidx.dst.sa,
3560 			    FULLMASK, IPSEC_ULPROTO_ANY);
3561 			break;
3562 
3563 		case SADB_EXT_KEY_AUTH:
3564 			if (!sav->key_auth)
3565 				continue;
3566 			l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
3567 			p = sav->key_auth;
3568 			break;
3569 
3570 		case SADB_EXT_KEY_ENCRYPT:
3571 			if (!sav->key_enc)
3572 				continue;
3573 			l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
3574 			p = sav->key_enc;
3575 			break;
3576 
3577 		case SADB_EXT_LIFETIME_CURRENT:
3578 			if (!sav->lft_c)
3579 				continue;
3580 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
3581 			memcpy(&lt, sav->lft_c, sizeof(struct sadb_lifetime));
3582 			lt.sadb_lifetime_addtime += time_second - time_uptime;
3583 			lt.sadb_lifetime_usetime += time_second - time_uptime;
3584 			p = &lt;
3585 			break;
3586 
3587 		case SADB_EXT_LIFETIME_HARD:
3588 			if (!sav->lft_h)
3589 				continue;
3590 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
3591 			p = sav->lft_h;
3592 			break;
3593 
3594 		case SADB_EXT_LIFETIME_SOFT:
3595 			if (!sav->lft_s)
3596 				continue;
3597 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
3598 			p = sav->lft_s;
3599 			break;
3600 
3601 #ifdef IPSEC_NAT_T
3602 		case SADB_X_EXT_NAT_T_TYPE:
3603 			m = key_setsadbxtype(sav->natt_type);
3604 			break;
3605 
3606 		case SADB_X_EXT_NAT_T_DPORT:
3607 			if (sav->natt_type == 0)
3608 				continue;
3609 			m = key_setsadbxport(
3610 				key_portfromsaddr(&sav->sah->saidx.dst),
3611 				SADB_X_EXT_NAT_T_DPORT);
3612 			break;
3613 
3614 		case SADB_X_EXT_NAT_T_SPORT:
3615 			if (sav->natt_type == 0)
3616 				continue;
3617 			m = key_setsadbxport(
3618 				key_portfromsaddr(&sav->sah->saidx.src),
3619 				SADB_X_EXT_NAT_T_SPORT);
3620 			break;
3621 
3622 		case SADB_X_EXT_NAT_T_FRAG:
3623 			/* don't send frag info if not set */
3624 			if (sav->natt_type == 0 || sav->esp_frag == IP_MAXPACKET)
3625 				continue;
3626 			m = key_setsadbxfrag(sav->esp_frag);
3627 			break;
3628 
3629 		case SADB_X_EXT_NAT_T_OAI:
3630 		case SADB_X_EXT_NAT_T_OAR:
3631 			continue;
3632 #endif
3633 
3634 		case SADB_EXT_ADDRESS_PROXY:
3635 		case SADB_EXT_IDENTITY_SRC:
3636 		case SADB_EXT_IDENTITY_DST:
3637 			/* XXX: should we brought from SPD ? */
3638 		case SADB_EXT_SENSITIVITY:
3639 		default:
3640 			continue;
3641 		}
3642 
3643 		KASSERT(!(m && p));
3644 		if (!m && !p)
3645 			goto fail;
3646 		if (p && tres) {
3647 			M_PREPEND(tres, l, M_DONTWAIT);
3648 			if (!tres)
3649 				goto fail;
3650 			memcpy(mtod(tres, void *), p, l);
3651 			continue;
3652 		}
3653 		if (p) {
3654 			m = key_alloc_mbuf(l);
3655 			if (!m)
3656 				goto fail;
3657 			m_copyback(m, 0, l, p);
3658 		}
3659 
3660 		if (tres)
3661 			m_cat(m, tres);
3662 		tres = m;
3663 	}
3664 
3665 	m_cat(result, tres);
3666 	tres = NULL; /* avoid free on error below */
3667 
3668 	if (result->m_len < sizeof(struct sadb_msg)) {
3669 		result = m_pullup(result, sizeof(struct sadb_msg));
3670 		if (result == NULL)
3671 			goto fail;
3672 	}
3673 
3674 	result->m_pkthdr.len = 0;
3675 	for (m = result; m; m = m->m_next)
3676 		result->m_pkthdr.len += m->m_len;
3677 
3678 	mtod(result, struct sadb_msg *)->sadb_msg_len =
3679 	    PFKEY_UNIT64(result->m_pkthdr.len);
3680 
3681 	return result;
3682 
3683 fail:
3684 	m_freem(result);
3685 	m_freem(tres);
3686 	return NULL;
3687 }
3688 
3689 
3690 #ifdef IPSEC_NAT_T
3691 /*
3692  * set a type in sadb_x_nat_t_type
3693  */
3694 static struct mbuf *
3695 key_setsadbxtype(u_int16_t type)
3696 {
3697 	struct mbuf *m;
3698 	size_t len;
3699 	struct sadb_x_nat_t_type *p;
3700 
3701 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3702 
3703 	m = key_alloc_mbuf(len);
3704 	if (!m || m->m_next) {	/*XXX*/
3705 		if (m)
3706 			m_freem(m);
3707 		return NULL;
3708 	}
3709 
3710 	p = mtod(m, struct sadb_x_nat_t_type *);
3711 
3712 	memset(p, 0, len);
3713 	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3714 	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3715 	p->sadb_x_nat_t_type_type = type;
3716 
3717 	return m;
3718 }
3719 /*
3720  * set a port in sadb_x_nat_t_port. port is in network order
3721  */
3722 static struct mbuf *
3723 key_setsadbxport(u_int16_t port, u_int16_t type)
3724 {
3725 	struct mbuf *m;
3726 	size_t len;
3727 	struct sadb_x_nat_t_port *p;
3728 
3729 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3730 
3731 	m = key_alloc_mbuf(len);
3732 	if (!m || m->m_next) {	/*XXX*/
3733 		if (m)
3734 			m_freem(m);
3735 		return NULL;
3736 	}
3737 
3738 	p = mtod(m, struct sadb_x_nat_t_port *);
3739 
3740 	memset(p, 0, len);
3741 	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3742 	p->sadb_x_nat_t_port_exttype = type;
3743 	p->sadb_x_nat_t_port_port = port;
3744 
3745 	return m;
3746 }
3747 
3748 /*
3749  * set fragmentation info in sadb_x_nat_t_frag
3750  */
3751 static struct mbuf *
3752 key_setsadbxfrag(u_int16_t flen)
3753 {
3754 	struct mbuf *m;
3755 	size_t len;
3756 	struct sadb_x_nat_t_frag *p;
3757 
3758 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_frag));
3759 
3760 	m = key_alloc_mbuf(len);
3761 	if (!m || m->m_next) {  /*XXX*/
3762 		if (m)
3763 			m_freem(m);
3764 		return NULL;
3765 	}
3766 
3767 	p = mtod(m, struct sadb_x_nat_t_frag *);
3768 
3769 	memset(p, 0, len);
3770 	p->sadb_x_nat_t_frag_len = PFKEY_UNIT64(len);
3771 	p->sadb_x_nat_t_frag_exttype = SADB_X_EXT_NAT_T_FRAG;
3772 	p->sadb_x_nat_t_frag_fraglen = flen;
3773 
3774 	return m;
3775 }
3776 
3777 /*
3778  * Get port from sockaddr, port is in network order
3779  */
3780 u_int16_t
3781 key_portfromsaddr(const union sockaddr_union *saddr)
3782 {
3783 	u_int16_t port;
3784 
3785 	switch (saddr->sa.sa_family) {
3786 	case AF_INET: {
3787 		port = saddr->sin.sin_port;
3788 		break;
3789 	}
3790 #ifdef INET6
3791 	case AF_INET6: {
3792 		port = saddr->sin6.sin6_port;
3793 		break;
3794 	}
3795 #endif
3796 	default:
3797 		printf("key_portfromsaddr: unexpected address family\n");
3798 		port = 0;
3799 		break;
3800 	}
3801 
3802 	return port;
3803 }
3804 
3805 #endif /* IPSEC_NAT_T */
3806 
3807 /*
3808  * Set port is struct sockaddr. port is in network order
3809  */
3810 static void
3811 key_porttosaddr(union sockaddr_union *saddr, u_int16_t port)
3812 {
3813 	switch (saddr->sa.sa_family) {
3814 	case AF_INET: {
3815 		saddr->sin.sin_port = port;
3816 		break;
3817 	}
3818 #ifdef INET6
3819 	case AF_INET6: {
3820 		saddr->sin6.sin6_port = port;
3821 		break;
3822 	}
3823 #endif
3824 	default:
3825 		printf("key_porttosaddr: unexpected address family %d\n",
3826 			saddr->sa.sa_family);
3827 		break;
3828 	}
3829 
3830 	return;
3831 }
3832 
3833 /*
3834  * Safety check sa_len
3835  */
3836 static int
3837 key_checksalen(const union sockaddr_union *saddr)
3838 {
3839         switch (saddr->sa.sa_family) {
3840         case AF_INET:
3841                 if (saddr->sa.sa_len != sizeof(struct sockaddr_in))
3842                         return -1;
3843                 break;
3844 #ifdef INET6
3845         case AF_INET6:
3846                 if (saddr->sa.sa_len != sizeof(struct sockaddr_in6))
3847                         return -1;
3848                 break;
3849 #endif
3850         default:
3851                 printf("key_checksalen: unexpected sa_family %d\n",
3852                     saddr->sa.sa_family);
3853                 return -1;
3854                 break;
3855         }
3856 	return 0;
3857 }
3858 
3859 
3860 /*
3861  * set data into sadb_msg.
3862  */
3863 static struct mbuf *
3864 key_setsadbmsg(u_int8_t type,  u_int16_t tlen, u_int8_t satype,
3865 	       u_int32_t seq, pid_t pid, u_int16_t reserved)
3866 {
3867 	struct mbuf *m;
3868 	struct sadb_msg *p;
3869 	int len;
3870 
3871 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3872 	if (len > MCLBYTES)
3873 		return NULL;
3874 	MGETHDR(m, M_DONTWAIT, MT_DATA);
3875 	if (m && len > MHLEN) {
3876 		MCLGET(m, M_DONTWAIT);
3877 		if ((m->m_flags & M_EXT) == 0) {
3878 			m_freem(m);
3879 			m = NULL;
3880 		}
3881 	}
3882 	if (!m)
3883 		return NULL;
3884 	m->m_pkthdr.len = m->m_len = len;
3885 	m->m_next = NULL;
3886 
3887 	p = mtod(m, struct sadb_msg *);
3888 
3889 	memset(p, 0, len);
3890 	p->sadb_msg_version = PF_KEY_V2;
3891 	p->sadb_msg_type = type;
3892 	p->sadb_msg_errno = 0;
3893 	p->sadb_msg_satype = satype;
3894 	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3895 	p->sadb_msg_reserved = reserved;
3896 	p->sadb_msg_seq = seq;
3897 	p->sadb_msg_pid = (u_int32_t)pid;
3898 
3899 	return m;
3900 }
3901 
3902 /*
3903  * copy secasvar data into sadb_address.
3904  */
3905 static struct mbuf *
3906 key_setsadbsa(struct secasvar *sav)
3907 {
3908 	struct mbuf *m;
3909 	struct sadb_sa *p;
3910 	int len;
3911 
3912 	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3913 	m = key_alloc_mbuf(len);
3914 	if (!m || m->m_next) {	/*XXX*/
3915 		if (m)
3916 			m_freem(m);
3917 		return NULL;
3918 	}
3919 
3920 	p = mtod(m, struct sadb_sa *);
3921 
3922 	memset(p, 0, len);
3923 	p->sadb_sa_len = PFKEY_UNIT64(len);
3924 	p->sadb_sa_exttype = SADB_EXT_SA;
3925 	p->sadb_sa_spi = sav->spi;
3926 	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3927 	p->sadb_sa_state = sav->state;
3928 	p->sadb_sa_auth = sav->alg_auth;
3929 	p->sadb_sa_encrypt = sav->alg_enc;
3930 	p->sadb_sa_flags = sav->flags;
3931 
3932 	return m;
3933 }
3934 
3935 /*
3936  * set data into sadb_address.
3937  */
3938 static struct mbuf *
3939 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3940 		u_int8_t prefixlen, u_int16_t ul_proto)
3941 {
3942 	struct mbuf *m;
3943 	struct sadb_address *p;
3944 	size_t len;
3945 
3946 	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3947 	    PFKEY_ALIGN8(saddr->sa_len);
3948 	m = key_alloc_mbuf(len);
3949 	if (!m || m->m_next) {	/*XXX*/
3950 		if (m)
3951 			m_freem(m);
3952 		return NULL;
3953 	}
3954 
3955 	p = mtod(m, struct sadb_address *);
3956 
3957 	memset(p, 0, len);
3958 	p->sadb_address_len = PFKEY_UNIT64(len);
3959 	p->sadb_address_exttype = exttype;
3960 	p->sadb_address_proto = ul_proto;
3961 	if (prefixlen == FULLMASK) {
3962 		switch (saddr->sa_family) {
3963 		case AF_INET:
3964 			prefixlen = sizeof(struct in_addr) << 3;
3965 			break;
3966 		case AF_INET6:
3967 			prefixlen = sizeof(struct in6_addr) << 3;
3968 			break;
3969 		default:
3970 			; /*XXX*/
3971 		}
3972 	}
3973 	p->sadb_address_prefixlen = prefixlen;
3974 	p->sadb_address_reserved = 0;
3975 
3976 	memcpy(mtod(m, char *) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3977 		   saddr, saddr->sa_len);
3978 
3979 	return m;
3980 }
3981 
3982 #if 0
3983 /*
3984  * set data into sadb_ident.
3985  */
3986 static struct mbuf *
3987 key_setsadbident(u_int16_t exttype, u_int16_t idtype,
3988 		 void *string, int stringlen, u_int64_t id)
3989 {
3990 	struct mbuf *m;
3991 	struct sadb_ident *p;
3992 	size_t len;
3993 
3994 	len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
3995 	m = key_alloc_mbuf(len);
3996 	if (!m || m->m_next) {	/*XXX*/
3997 		if (m)
3998 			m_freem(m);
3999 		return NULL;
4000 	}
4001 
4002 	p = mtod(m, struct sadb_ident *);
4003 
4004 	memset(p, 0, len);
4005 	p->sadb_ident_len = PFKEY_UNIT64(len);
4006 	p->sadb_ident_exttype = exttype;
4007 	p->sadb_ident_type = idtype;
4008 	p->sadb_ident_reserved = 0;
4009 	p->sadb_ident_id = id;
4010 
4011 	memcpy(mtod(m, void *) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
4012 	   	   string, stringlen);
4013 
4014 	return m;
4015 }
4016 #endif
4017 
4018 /*
4019  * set data into sadb_x_sa2.
4020  */
4021 static struct mbuf *
4022 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int16_t reqid)
4023 {
4024 	struct mbuf *m;
4025 	struct sadb_x_sa2 *p;
4026 	size_t len;
4027 
4028 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
4029 	m = key_alloc_mbuf(len);
4030 	if (!m || m->m_next) {	/*XXX*/
4031 		if (m)
4032 			m_freem(m);
4033 		return NULL;
4034 	}
4035 
4036 	p = mtod(m, struct sadb_x_sa2 *);
4037 
4038 	memset(p, 0, len);
4039 	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
4040 	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
4041 	p->sadb_x_sa2_mode = mode;
4042 	p->sadb_x_sa2_reserved1 = 0;
4043 	p->sadb_x_sa2_reserved2 = 0;
4044 	p->sadb_x_sa2_sequence = seq;
4045 	p->sadb_x_sa2_reqid = reqid;
4046 
4047 	return m;
4048 }
4049 
4050 /*
4051  * set data into sadb_x_policy
4052  */
4053 static struct mbuf *
4054 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
4055 {
4056 	struct mbuf *m;
4057 	struct sadb_x_policy *p;
4058 	size_t len;
4059 
4060 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
4061 	m = key_alloc_mbuf(len);
4062 	if (!m || m->m_next) {	/*XXX*/
4063 		if (m)
4064 			m_freem(m);
4065 		return NULL;
4066 	}
4067 
4068 	p = mtod(m, struct sadb_x_policy *);
4069 
4070 	memset(p, 0, len);
4071 	p->sadb_x_policy_len = PFKEY_UNIT64(len);
4072 	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
4073 	p->sadb_x_policy_type = type;
4074 	p->sadb_x_policy_dir = dir;
4075 	p->sadb_x_policy_id = id;
4076 
4077 	return m;
4078 }
4079 
4080 /* %%% utilities */
4081 /*
4082  * copy a buffer into the new buffer allocated.
4083  */
4084 static void *
4085 key_newbuf(const void *src, u_int len)
4086 {
4087 	void *new;
4088 
4089 	KMALLOC(new, void *, len);
4090 	if (new == NULL) {
4091 		ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
4092 		return NULL;
4093 	}
4094 	memcpy(new, src, len);
4095 
4096 	return new;
4097 }
4098 
4099 /* compare my own address
4100  * OUT:	1: true, i.e. my address.
4101  *	0: false
4102  */
4103 int
4104 key_ismyaddr(const struct sockaddr *sa)
4105 {
4106 #ifdef INET
4107 	const struct sockaddr_in *sin;
4108 	const struct in_ifaddr *ia;
4109 #endif
4110 
4111 	/* sanity check */
4112 	if (sa == NULL)
4113 		panic("key_ismyaddr: NULL pointer is passed");
4114 
4115 	switch (sa->sa_family) {
4116 #ifdef INET
4117 	case AF_INET:
4118 		sin = (const struct sockaddr_in *)sa;
4119 		for (ia = in_ifaddrhead.tqh_first; ia;
4120 		     ia = ia->ia_link.tqe_next)
4121 		{
4122 			if (sin->sin_family == ia->ia_addr.sin_family &&
4123 			    sin->sin_len == ia->ia_addr.sin_len &&
4124 			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
4125 			{
4126 				return 1;
4127 			}
4128 		}
4129 		break;
4130 #endif
4131 #ifdef INET6
4132 	case AF_INET6:
4133 		return key_ismyaddr6((const struct sockaddr_in6 *)sa);
4134 #endif
4135 	}
4136 
4137 	return 0;
4138 }
4139 
4140 #ifdef INET6
4141 /*
4142  * compare my own address for IPv6.
4143  * 1: ours
4144  * 0: other
4145  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
4146  */
4147 #include <netinet6/in6_var.h>
4148 
4149 static int
4150 key_ismyaddr6(const struct sockaddr_in6 *sin6)
4151 {
4152 	const struct in6_ifaddr *ia;
4153 	const struct in6_multi *in6m;
4154 
4155 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
4156 		if (key_sockaddrcmp((const struct sockaddr *)&sin6,
4157 		    (const struct sockaddr *)&ia->ia_addr, 0) == 0)
4158 			return 1;
4159 
4160 		/*
4161 		 * XXX Multicast
4162 		 * XXX why do we care about multlicast here while we don't care
4163 		 * about IPv4 multicast??
4164 		 * XXX scope
4165 		 */
4166 		in6m = NULL;
4167 #ifdef __FreeBSD__
4168 		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
4169 #else
4170 		for ((in6m) = ia->ia6_multiaddrs.lh_first;
4171 		     (in6m) != NULL &&
4172 		     !IN6_ARE_ADDR_EQUAL(&(in6m)->in6m_addr, &sin6->sin6_addr);
4173 		     (in6m) = in6m->in6m_entry.le_next)
4174 			continue;
4175 #endif
4176 		if (in6m)
4177 			return 1;
4178 	}
4179 
4180 	/* loopback, just for safety */
4181 	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
4182 		return 1;
4183 
4184 	return 0;
4185 }
4186 #endif /*INET6*/
4187 
4188 /*
4189  * compare two secasindex structure.
4190  * flag can specify to compare 2 saidxes.
4191  * compare two secasindex structure without both mode and reqid.
4192  * don't compare port.
4193  * IN:
4194  *      saidx0: source, it can be in SAD.
4195  *      saidx1: object.
4196  * OUT:
4197  *      1 : equal
4198  *      0 : not equal
4199  */
4200 static int
4201 key_cmpsaidx(
4202 	const struct secasindex *saidx0,
4203 	const struct secasindex *saidx1,
4204 	int flag)
4205 {
4206 	int chkport = 0;
4207 
4208 	/* sanity */
4209 	if (saidx0 == NULL && saidx1 == NULL)
4210 		return 1;
4211 
4212 	if (saidx0 == NULL || saidx1 == NULL)
4213 		return 0;
4214 
4215 	if (saidx0->proto != saidx1->proto)
4216 		return 0;
4217 
4218 	if (flag == CMP_EXACTLY) {
4219 		if (saidx0->mode != saidx1->mode)
4220 			return 0;
4221 		if (saidx0->reqid != saidx1->reqid)
4222 			return 0;
4223 		if (memcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4224 		    memcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4225 			return 0;
4226 	} else {
4227 
4228 		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4229 		if (flag == CMP_MODE_REQID
4230 		  ||flag == CMP_REQID) {
4231 			/*
4232 			 * If reqid of SPD is non-zero, unique SA is required.
4233 			 * The result must be of same reqid in this case.
4234 			 */
4235 			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4236 				return 0;
4237 		}
4238 
4239 		if (flag == CMP_MODE_REQID) {
4240 			if (saidx0->mode != IPSEC_MODE_ANY
4241 			 && saidx0->mode != saidx1->mode)
4242 				return 0;
4243 		}
4244 
4245 	/*
4246 	 * If NAT-T is enabled, check ports for tunnel mode.
4247 	 * Don't do it for transport mode, as there is no
4248 	 * port information available in the SP.
4249          * Also don't check ports if they are set to zero
4250 	 * in the SPD: This means we have a non-generated
4251 	 * SPD which can't know UDP ports.
4252 	 */
4253 #ifdef IPSEC_NAT_T
4254 	if (saidx1->mode == IPSEC_MODE_TUNNEL &&
4255 	    ((((const struct sockaddr *)(&saidx1->src))->sa_family == AF_INET &&
4256 	      ((const struct sockaddr *)(&saidx1->dst))->sa_family == AF_INET &&
4257 	      ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
4258 	      ((const struct sockaddr_in *)(&saidx1->dst))->sin_port) ||
4259              (((const struct sockaddr *)(&saidx1->src))->sa_family == AF_INET6 &&
4260 	      ((const struct sockaddr *)(&saidx1->dst))->sa_family == AF_INET6 &&
4261 	      ((const struct sockaddr_in6 *)(&saidx1->src))->sin6_port &&
4262 	      ((const struct sockaddr_in6 *)(&saidx1->dst))->sin6_port)))
4263 		chkport = 1;
4264 #endif
4265 
4266 		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
4267 			return 0;
4268 		}
4269 		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
4270 			return 0;
4271 		}
4272 	}
4273 
4274 	return 1;
4275 }
4276 
4277 /*
4278  * compare two secindex structure exactly.
4279  * IN:
4280  *	spidx0: source, it is often in SPD.
4281  *	spidx1: object, it is often from PFKEY message.
4282  * OUT:
4283  *	1 : equal
4284  *	0 : not equal
4285  */
4286 int
4287 key_cmpspidx_exactly(
4288 	const struct secpolicyindex *spidx0,
4289 	const struct secpolicyindex *spidx1)
4290 {
4291 	/* sanity */
4292 	if (spidx0 == NULL && spidx1 == NULL)
4293 		return 1;
4294 
4295 	if (spidx0 == NULL || spidx1 == NULL)
4296 		return 0;
4297 
4298 	if (spidx0->prefs != spidx1->prefs
4299 	 || spidx0->prefd != spidx1->prefd
4300 	 || spidx0->ul_proto != spidx1->ul_proto)
4301 		return 0;
4302 
4303 	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4304 	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4305 }
4306 
4307 /*
4308  * compare two secindex structure with mask.
4309  * IN:
4310  *	spidx0: source, it is often in SPD.
4311  *	spidx1: object, it is often from IP header.
4312  * OUT:
4313  *	1 : equal
4314  *	0 : not equal
4315  */
4316 int
4317 key_cmpspidx_withmask(
4318 	const struct secpolicyindex *spidx0,
4319 	const struct secpolicyindex *spidx1)
4320 {
4321 	/* sanity */
4322 	if (spidx0 == NULL && spidx1 == NULL)
4323 		return 1;
4324 
4325 	if (spidx0 == NULL || spidx1 == NULL)
4326 		return 0;
4327 
4328 	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4329 	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4330 	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4331 	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4332 		return 0;
4333 
4334 	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4335 	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4336 	 && spidx0->ul_proto != spidx1->ul_proto)
4337 		return 0;
4338 
4339 	switch (spidx0->src.sa.sa_family) {
4340 	case AF_INET:
4341 		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4342 		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4343 			return 0;
4344 		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4345 		    &spidx1->src.sin.sin_addr, spidx0->prefs))
4346 			return 0;
4347 		break;
4348 	case AF_INET6:
4349 		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4350 		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4351 			return 0;
4352 		/*
4353 		 * scope_id check. if sin6_scope_id is 0, we regard it
4354 		 * as a wildcard scope, which matches any scope zone ID.
4355 		 */
4356 		if (spidx0->src.sin6.sin6_scope_id &&
4357 		    spidx1->src.sin6.sin6_scope_id &&
4358 		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4359 			return 0;
4360 		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4361 		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4362 			return 0;
4363 		break;
4364 	default:
4365 		/* XXX */
4366 		if (memcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4367 			return 0;
4368 		break;
4369 	}
4370 
4371 	switch (spidx0->dst.sa.sa_family) {
4372 	case AF_INET:
4373 		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4374 		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4375 			return 0;
4376 		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4377 		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
4378 			return 0;
4379 		break;
4380 	case AF_INET6:
4381 		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4382 		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4383 			return 0;
4384 		/*
4385 		 * scope_id check. if sin6_scope_id is 0, we regard it
4386 		 * as a wildcard scope, which matches any scope zone ID.
4387 		 */
4388 		if (spidx0->src.sin6.sin6_scope_id &&
4389 		    spidx1->src.sin6.sin6_scope_id &&
4390 		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4391 			return 0;
4392 		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4393 		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4394 			return 0;
4395 		break;
4396 	default:
4397 		/* XXX */
4398 		if (memcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4399 			return 0;
4400 		break;
4401 	}
4402 
4403 	/* XXX Do we check other field ?  e.g. flowinfo */
4404 
4405 	return 1;
4406 }
4407 
4408 /* returns 0 on match */
4409 static int
4410 key_sockaddrcmp(
4411 	const struct sockaddr *sa1,
4412 	const struct sockaddr *sa2,
4413 	int port)
4414 {
4415 #ifdef satosin
4416 #undef satosin
4417 #endif
4418 #define satosin(s) ((const struct sockaddr_in *)s)
4419 #ifdef satosin6
4420 #undef satosin6
4421 #endif
4422 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4423 	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4424 		return 1;
4425 
4426 	switch (sa1->sa_family) {
4427 	case AF_INET:
4428 		if (sa1->sa_len != sizeof(struct sockaddr_in))
4429 			return 1;
4430 		if (satosin(sa1)->sin_addr.s_addr !=
4431 		    satosin(sa2)->sin_addr.s_addr) {
4432 			return 1;
4433 		}
4434 		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4435 			return 1;
4436 		break;
4437 	case AF_INET6:
4438 		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4439 			return 1;	/*EINVAL*/
4440 		if (satosin6(sa1)->sin6_scope_id !=
4441 		    satosin6(sa2)->sin6_scope_id) {
4442 			return 1;
4443 		}
4444 		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4445 		    &satosin6(sa2)->sin6_addr)) {
4446 			return 1;
4447 		}
4448 		if (port &&
4449 		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4450 			return 1;
4451 		}
4452 		break;
4453 	default:
4454 		if (memcmp(sa1, sa2, sa1->sa_len) != 0)
4455 			return 1;
4456 		break;
4457 	}
4458 
4459 	return 0;
4460 #undef satosin
4461 #undef satosin6
4462 }
4463 
4464 /*
4465  * compare two buffers with mask.
4466  * IN:
4467  *	addr1: source
4468  *	addr2: object
4469  *	bits:  Number of bits to compare
4470  * OUT:
4471  *	1 : equal
4472  *	0 : not equal
4473  */
4474 static int
4475 key_bbcmp(const void *a1, const void *a2, u_int bits)
4476 {
4477 	const unsigned char *p1 = a1;
4478 	const unsigned char *p2 = a2;
4479 
4480 	/* XXX: This could be considerably faster if we compare a word
4481 	 * at a time, but it is complicated on LSB Endian machines */
4482 
4483 	/* Handle null pointers */
4484 	if (p1 == NULL || p2 == NULL)
4485 		return (p1 == p2);
4486 
4487 	while (bits >= 8) {
4488 		if (*p1++ != *p2++)
4489 			return 0;
4490 		bits -= 8;
4491 	}
4492 
4493 	if (bits > 0) {
4494 		u_int8_t mask = ~((1<<(8-bits))-1);
4495 		if ((*p1 & mask) != (*p2 & mask))
4496 			return 0;
4497 	}
4498 	return 1;	/* Match! */
4499 }
4500 
4501 /*
4502  * time handler.
4503  * scanning SPD and SAD to check status for each entries,
4504  * and do to remove or to expire.
4505  */
4506 void
4507 key_timehandler(void* arg)
4508 {
4509 	u_int dir;
4510 	int s;
4511 	time_t now = time_uptime;
4512 
4513 	s = splsoftnet();	/*called from softclock()*/
4514 	mutex_enter(softnet_lock);
4515 
4516 	/* SPD */
4517     {
4518 	struct secpolicy *sp, *nextsp;
4519 
4520 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4521 		for (sp = LIST_FIRST(&sptree[dir]);
4522 		     sp != NULL;
4523 		     sp = nextsp) {
4524 
4525 			nextsp = LIST_NEXT(sp, chain);
4526 
4527 			if (sp->state == IPSEC_SPSTATE_DEAD) {
4528 				key_sp_unlink(sp);	/*XXX*/
4529 
4530 				/* 'sp' dead; continue transfers to
4531 				 * 'sp = nextsp'
4532 				 */
4533 				continue;
4534 			}
4535 
4536 			if (sp->lifetime == 0 && sp->validtime == 0)
4537 				continue;
4538 
4539 			/* the deletion will occur next time */
4540 			if ((sp->lifetime && now - sp->created > sp->lifetime)
4541 			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4542 			  	key_sp_dead(sp);
4543 				key_spdexpire(sp);
4544 				continue;
4545 			}
4546 		}
4547 	}
4548     }
4549 
4550 	/* SAD */
4551     {
4552 	struct secashead *sah, *nextsah;
4553 	struct secasvar *sav, *nextsav;
4554 
4555 	for (sah = LIST_FIRST(&sahtree);
4556 	     sah != NULL;
4557 	     sah = nextsah) {
4558 
4559 		nextsah = LIST_NEXT(sah, chain);
4560 
4561 		/* if sah has been dead, then delete it and process next sah. */
4562 		if (sah->state == SADB_SASTATE_DEAD) {
4563 			key_delsah(sah);
4564 			continue;
4565 		}
4566 
4567 		/* if LARVAL entry doesn't become MATURE, delete it. */
4568 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
4569 		     sav != NULL;
4570 		     sav = nextsav) {
4571 
4572 			nextsav = LIST_NEXT(sav, chain);
4573 
4574 			if (now - sav->created > key_larval_lifetime) {
4575 				KEY_FREESAV(&sav);
4576 			}
4577 		}
4578 
4579 		/*
4580 		 * check MATURE entry to start to send expire message
4581 		 * whether or not.
4582 		 */
4583 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
4584 		     sav != NULL;
4585 		     sav = nextsav) {
4586 
4587 			nextsav = LIST_NEXT(sav, chain);
4588 
4589 			/* we don't need to check. */
4590 			if (sav->lft_s == NULL)
4591 				continue;
4592 
4593 			/* sanity check */
4594 			if (sav->lft_c == NULL) {
4595 				ipseclog((LOG_DEBUG,"key_timehandler: "
4596 					"There is no CURRENT time, why?\n"));
4597 				continue;
4598 			}
4599 
4600 			/* check SOFT lifetime */
4601 			if (sav->lft_s->sadb_lifetime_addtime != 0
4602 			 && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4603 				/*
4604 				 * check SA to be used whether or not.
4605 				 * when SA hasn't been used, delete it.
4606 				 */
4607 				if (sav->lft_c->sadb_lifetime_usetime == 0) {
4608 					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4609 					KEY_FREESAV(&sav);
4610 				} else {
4611 					key_sa_chgstate(sav, SADB_SASTATE_DYING);
4612 					/*
4613 					 * XXX If we keep to send expire
4614 					 * message in the status of
4615 					 * DYING. Do remove below code.
4616 					 */
4617 					key_expire(sav);
4618 				}
4619 			}
4620 			/* check SOFT lifetime by bytes */
4621 			/*
4622 			 * XXX I don't know the way to delete this SA
4623 			 * when new SA is installed.  Caution when it's
4624 			 * installed too big lifetime by time.
4625 			 */
4626 			else if (sav->lft_s->sadb_lifetime_bytes != 0
4627 			      && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4628 
4629 				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4630 				/*
4631 				 * XXX If we keep to send expire
4632 				 * message in the status of
4633 				 * DYING. Do remove below code.
4634 				 */
4635 				key_expire(sav);
4636 			}
4637 		}
4638 
4639 		/* check DYING entry to change status to DEAD. */
4640 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
4641 		     sav != NULL;
4642 		     sav = nextsav) {
4643 
4644 			nextsav = LIST_NEXT(sav, chain);
4645 
4646 			/* we don't need to check. */
4647 			if (sav->lft_h == NULL)
4648 				continue;
4649 
4650 			/* sanity check */
4651 			if (sav->lft_c == NULL) {
4652 				ipseclog((LOG_DEBUG, "key_timehandler: "
4653 					"There is no CURRENT time, why?\n"));
4654 				continue;
4655 			}
4656 
4657 			if (sav->lft_h->sadb_lifetime_addtime != 0
4658 			 && now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
4659 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4660 				KEY_FREESAV(&sav);
4661 			}
4662 #if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4663 			else if (sav->lft_s != NULL
4664 			      && sav->lft_s->sadb_lifetime_addtime != 0
4665 			      && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4666 				/*
4667 				 * XXX: should be checked to be
4668 				 * installed the valid SA.
4669 				 */
4670 
4671 				/*
4672 				 * If there is no SA then sending
4673 				 * expire message.
4674 				 */
4675 				key_expire(sav);
4676 			}
4677 #endif
4678 			/* check HARD lifetime by bytes */
4679 			else if (sav->lft_h->sadb_lifetime_bytes != 0
4680 			      && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4681 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4682 				KEY_FREESAV(&sav);
4683 			}
4684 		}
4685 
4686 		/* delete entry in DEAD */
4687 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
4688 		     sav != NULL;
4689 		     sav = nextsav) {
4690 
4691 			nextsav = LIST_NEXT(sav, chain);
4692 
4693 			/* sanity check */
4694 			if (sav->state != SADB_SASTATE_DEAD) {
4695 				ipseclog((LOG_DEBUG, "key_timehandler: "
4696 					"invalid sav->state "
4697 					"(queue: %d SA: %d): "
4698 					"kill it anyway\n",
4699 					SADB_SASTATE_DEAD, sav->state));
4700 			}
4701 
4702 			/*
4703 			 * do not call key_freesav() here.
4704 			 * sav should already be freed, and sav->refcnt
4705 			 * shows other references to sav
4706 			 * (such as from SPD).
4707 			 */
4708 		}
4709 	}
4710     }
4711 
4712 #ifndef IPSEC_NONBLOCK_ACQUIRE
4713 	/* ACQ tree */
4714     {
4715 	struct secacq *acq, *nextacq;
4716 
4717 	for (acq = LIST_FIRST(&acqtree);
4718 	     acq != NULL;
4719 	     acq = nextacq) {
4720 
4721 		nextacq = LIST_NEXT(acq, chain);
4722 
4723 		if (now - acq->created > key_blockacq_lifetime
4724 		 && __LIST_CHAINED(acq)) {
4725 			LIST_REMOVE(acq, chain);
4726 			KFREE(acq);
4727 		}
4728 	}
4729     }
4730 #endif
4731 
4732 	/* SP ACQ tree */
4733     {
4734 	struct secspacq *acq, *nextacq;
4735 
4736 	for (acq = LIST_FIRST(&spacqtree);
4737 	     acq != NULL;
4738 	     acq = nextacq) {
4739 
4740 		nextacq = LIST_NEXT(acq, chain);
4741 
4742 		if (now - acq->created > key_blockacq_lifetime
4743 		 && __LIST_CHAINED(acq)) {
4744 			LIST_REMOVE(acq, chain);
4745 			KFREE(acq);
4746 		}
4747 	}
4748     }
4749 
4750 #ifndef IPSEC_DEBUG2
4751 	/* do exchange to tick time !! */
4752 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
4753 #endif /* IPSEC_DEBUG2 */
4754 
4755 	mutex_exit(softnet_lock);
4756 	splx(s);
4757 	return;
4758 }
4759 
4760 u_long
4761 key_random(void)
4762 {
4763 	u_long value;
4764 
4765 	key_randomfill(&value, sizeof(value));
4766 	return value;
4767 }
4768 
4769 void
4770 key_randomfill(void *p, size_t l)
4771 {
4772 
4773 	cprng_fast(p, l);
4774 }
4775 
4776 /*
4777  * map SADB_SATYPE_* to IPPROTO_*.
4778  * if satype == SADB_SATYPE then satype is mapped to ~0.
4779  * OUT:
4780  *	0: invalid satype.
4781  */
4782 static u_int16_t
4783 key_satype2proto(u_int8_t satype)
4784 {
4785 	switch (satype) {
4786 	case SADB_SATYPE_UNSPEC:
4787 		return IPSEC_PROTO_ANY;
4788 	case SADB_SATYPE_AH:
4789 		return IPPROTO_AH;
4790 	case SADB_SATYPE_ESP:
4791 		return IPPROTO_ESP;
4792 	case SADB_X_SATYPE_IPCOMP:
4793 		return IPPROTO_IPCOMP;
4794 	case SADB_X_SATYPE_TCPSIGNATURE:
4795 		return IPPROTO_TCP;
4796 	default:
4797 		return 0;
4798 	}
4799 	/* NOTREACHED */
4800 }
4801 
4802 /*
4803  * map IPPROTO_* to SADB_SATYPE_*
4804  * OUT:
4805  *	0: invalid protocol type.
4806  */
4807 static u_int8_t
4808 key_proto2satype(u_int16_t proto)
4809 {
4810 	switch (proto) {
4811 	case IPPROTO_AH:
4812 		return SADB_SATYPE_AH;
4813 	case IPPROTO_ESP:
4814 		return SADB_SATYPE_ESP;
4815 	case IPPROTO_IPCOMP:
4816 		return SADB_X_SATYPE_IPCOMP;
4817 	case IPPROTO_TCP:
4818 		return SADB_X_SATYPE_TCPSIGNATURE;
4819 	default:
4820 		return 0;
4821 	}
4822 	/* NOTREACHED */
4823 }
4824 
4825 static int
4826 key_setsecasidx(int proto, int mode, int reqid,
4827 	        const struct sadb_address * src,
4828 	 	const struct sadb_address * dst,
4829 		struct secasindex * saidx)
4830 {
4831 	const union sockaddr_union * src_u =
4832 		(const union sockaddr_union *) src;
4833 	const union sockaddr_union * dst_u =
4834 		(const union sockaddr_union *) dst;
4835 
4836 	/* sa len safety check */
4837 	if (key_checksalen(src_u) != 0)
4838 		return -1;
4839 	if (key_checksalen(dst_u) != 0)
4840 		return -1;
4841 
4842 	memset(saidx, 0, sizeof(*saidx));
4843 	saidx->proto = proto;
4844 	saidx->mode = mode;
4845 	saidx->reqid = reqid;
4846 	memcpy(&saidx->src, src_u, src_u->sa.sa_len);
4847 	memcpy(&saidx->dst, dst_u, dst_u->sa.sa_len);
4848 
4849 #ifndef IPSEC_NAT_T
4850 	key_porttosaddr(&((saidx)->src),0);
4851 	key_porttosaddr(&((saidx)->dst),0);
4852 #endif
4853 	return 0;
4854 }
4855 
4856 /* %%% PF_KEY */
4857 /*
4858  * SADB_GETSPI processing is to receive
4859  *	<base, (SA2), src address, dst address, (SPI range)>
4860  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4861  * tree with the status of LARVAL, and send
4862  *	<base, SA(*), address(SD)>
4863  * to the IKMPd.
4864  *
4865  * IN:	mhp: pointer to the pointer to each header.
4866  * OUT:	NULL if fail.
4867  *	other if success, return pointer to the message to send.
4868  */
4869 static int
4870 key_getspi(struct socket *so, struct mbuf *m,
4871 	   const struct sadb_msghdr *mhp)
4872 {
4873 	struct sadb_address *src0, *dst0;
4874 	struct secasindex saidx;
4875 	struct secashead *newsah;
4876 	struct secasvar *newsav;
4877 	u_int8_t proto;
4878 	u_int32_t spi;
4879 	u_int8_t mode;
4880 	u_int16_t reqid;
4881 	int error;
4882 
4883 	/* sanity check */
4884 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4885 		panic("key_getspi: NULL pointer is passed");
4886 
4887 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4888 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4889 		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4890 		return key_senderror(so, m, EINVAL);
4891 	}
4892 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4893 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4894 		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4895 		return key_senderror(so, m, EINVAL);
4896 	}
4897 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4898 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4899 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4900 	} else {
4901 		mode = IPSEC_MODE_ANY;
4902 		reqid = 0;
4903 	}
4904 
4905 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4906 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4907 
4908 	/* map satype to proto */
4909 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4910 		ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
4911 		return key_senderror(so, m, EINVAL);
4912 	}
4913 
4914 
4915 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
4916 				     dst0 + 1, &saidx)) != 0)
4917 		return key_senderror(so, m, EINVAL);
4918 
4919 #ifdef IPSEC_NAT_T
4920 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
4921 		return key_senderror(so, m, EINVAL);
4922 #endif
4923 
4924 	/* SPI allocation */
4925 	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4926 	                       &saidx);
4927 	if (spi == 0)
4928 		return key_senderror(so, m, EINVAL);
4929 
4930 	/* get a SA index */
4931 	if ((newsah = key_getsah(&saidx)) == NULL) {
4932 		/* create a new SA index */
4933 		if ((newsah = key_newsah(&saidx)) == NULL) {
4934 			ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
4935 			return key_senderror(so, m, ENOBUFS);
4936 		}
4937 	}
4938 
4939 	/* get a new SA */
4940 	/* XXX rewrite */
4941 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4942 	if (newsav == NULL) {
4943 		/* XXX don't free new SA index allocated in above. */
4944 		return key_senderror(so, m, error);
4945 	}
4946 
4947 	/* set spi */
4948 	newsav->spi = htonl(spi);
4949 
4950 #ifndef IPSEC_NONBLOCK_ACQUIRE
4951 	/* delete the entry in acqtree */
4952 	if (mhp->msg->sadb_msg_seq != 0) {
4953 		struct secacq *acq;
4954 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4955 			/* reset counter in order to deletion by timehandler. */
4956 			acq->created = time_uptime;
4957 			acq->count = 0;
4958 		}
4959     	}
4960 #endif
4961 
4962     {
4963 	struct mbuf *n, *nn;
4964 	struct sadb_sa *m_sa;
4965 	struct sadb_msg *newmsg;
4966 	int off, len;
4967 
4968 	/* create new sadb_msg to reply. */
4969 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4970 	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4971 	if (len > MCLBYTES)
4972 		return key_senderror(so, m, ENOBUFS);
4973 
4974 	MGETHDR(n, M_DONTWAIT, MT_DATA);
4975 	if (len > MHLEN) {
4976 		MCLGET(n, M_DONTWAIT);
4977 		if ((n->m_flags & M_EXT) == 0) {
4978 			m_freem(n);
4979 			n = NULL;
4980 		}
4981 	}
4982 	if (!n)
4983 		return key_senderror(so, m, ENOBUFS);
4984 
4985 	n->m_len = len;
4986 	n->m_next = NULL;
4987 	off = 0;
4988 
4989 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
4990 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4991 
4992 	m_sa = (struct sadb_sa *)(mtod(n, char *) + off);
4993 	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4994 	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4995 	m_sa->sadb_sa_spi = htonl(spi);
4996 	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4997 
4998 #ifdef DIAGNOSTIC
4999 	if (off != len)
5000 		panic("length inconsistency in key_getspi");
5001 #endif
5002 
5003 	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
5004 	    SADB_EXT_ADDRESS_DST);
5005 	if (!n->m_next) {
5006 		m_freem(n);
5007 		return key_senderror(so, m, ENOBUFS);
5008 	}
5009 
5010 	if (n->m_len < sizeof(struct sadb_msg)) {
5011 		n = m_pullup(n, sizeof(struct sadb_msg));
5012 		if (n == NULL)
5013 			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
5014 	}
5015 
5016 	n->m_pkthdr.len = 0;
5017 	for (nn = n; nn; nn = nn->m_next)
5018 		n->m_pkthdr.len += nn->m_len;
5019 
5020 	newmsg = mtod(n, struct sadb_msg *);
5021 	newmsg->sadb_msg_seq = newsav->seq;
5022 	newmsg->sadb_msg_errno = 0;
5023 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5024 
5025 	m_freem(m);
5026 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5027     }
5028 }
5029 
5030 /*
5031  * allocating new SPI
5032  * called by key_getspi().
5033  * OUT:
5034  *	0:	failure.
5035  *	others: success.
5036  */
5037 static u_int32_t
5038 key_do_getnewspi(const struct sadb_spirange *spirange,
5039 		 const struct secasindex *saidx)
5040 {
5041 	u_int32_t newspi;
5042 	u_int32_t spmin, spmax;
5043 	int count = key_spi_trycnt;
5044 
5045 	/* set spi range to allocate */
5046 	if (spirange != NULL) {
5047 		spmin = spirange->sadb_spirange_min;
5048 		spmax = spirange->sadb_spirange_max;
5049 	} else {
5050 		spmin = key_spi_minval;
5051 		spmax = key_spi_maxval;
5052 	}
5053 	/* IPCOMP needs 2-byte SPI */
5054 	if (saidx->proto == IPPROTO_IPCOMP) {
5055 		u_int32_t t;
5056 		if (spmin >= 0x10000)
5057 			spmin = 0xffff;
5058 		if (spmax >= 0x10000)
5059 			spmax = 0xffff;
5060 		if (spmin > spmax) {
5061 			t = spmin; spmin = spmax; spmax = t;
5062 		}
5063 	}
5064 
5065 	if (spmin == spmax) {
5066 		if (key_checkspidup(saidx, htonl(spmin)) != NULL) {
5067 			ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", spmin));
5068 			return 0;
5069 		}
5070 
5071 		count--; /* taking one cost. */
5072 		newspi = spmin;
5073 
5074 	} else {
5075 
5076 		/* init SPI */
5077 		newspi = 0;
5078 
5079 		/* when requesting to allocate spi ranged */
5080 		while (count--) {
5081 			/* generate pseudo-random SPI value ranged. */
5082 			newspi = spmin + (key_random() % (spmax - spmin + 1));
5083 
5084 			if (key_checkspidup(saidx, htonl(newspi)) == NULL)
5085 				break;
5086 		}
5087 
5088 		if (count == 0 || newspi == 0) {
5089 			ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
5090 			return 0;
5091 		}
5092 	}
5093 
5094 	/* statistics */
5095 	keystat.getspi_count =
5096 		(keystat.getspi_count + key_spi_trycnt - count) / 2;
5097 
5098 	return newspi;
5099 }
5100 
5101 #ifdef IPSEC_NAT_T
5102 /* Handle IPSEC_NAT_T info if present */
5103 static int
5104 key_handle_natt_info(struct secasvar *sav,
5105       		     const struct sadb_msghdr *mhp)
5106 {
5107 
5108 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
5109 		ipseclog((LOG_DEBUG,"update: NAT-T OAi present\n"));
5110 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
5111 		ipseclog((LOG_DEBUG,"update: NAT-T OAr present\n"));
5112 
5113 	if ((mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL) &&
5114 	    (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL) &&
5115 	    (mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL)) {
5116 		struct sadb_x_nat_t_type *type;
5117 		struct sadb_x_nat_t_port *sport;
5118 		struct sadb_x_nat_t_port *dport;
5119 		struct sadb_address *iaddr, *raddr;
5120 		struct sadb_x_nat_t_frag *frag;
5121 
5122 		if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
5123 		    (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
5124 		    (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
5125 			ipseclog((LOG_DEBUG, "key_update: "
5126 			    "invalid message.\n"));
5127 			return -1;
5128 		}
5129 
5130 		if ((mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) &&
5131 		    (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr))) {
5132 			ipseclog((LOG_DEBUG, "key_update: invalid message\n"));
5133 			return -1;
5134 		}
5135 
5136 		if ((mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) &&
5137 		    (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr))) {
5138 			ipseclog((LOG_DEBUG, "key_update: invalid message\n"));
5139 			return -1;
5140 		}
5141 
5142 		if ((mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) &&
5143 		    (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag))) {
5144 			ipseclog((LOG_DEBUG, "key_update: invalid message\n"));
5145 			return -1;
5146 		}
5147 
5148 		type = (struct sadb_x_nat_t_type *)
5149 		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5150 		sport = (struct sadb_x_nat_t_port *)
5151 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5152 		dport = (struct sadb_x_nat_t_port *)
5153 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5154 		iaddr = (struct sadb_address *)
5155 		    mhp->ext[SADB_X_EXT_NAT_T_OAI];
5156 		raddr = (struct sadb_address *)
5157 		    mhp->ext[SADB_X_EXT_NAT_T_OAR];
5158 		frag = (struct sadb_x_nat_t_frag *)
5159 		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5160 
5161 		ipseclog((LOG_DEBUG,
5162 			"key_update: type %d, sport = %d, dport = %d\n",
5163 			type->sadb_x_nat_t_type_type,
5164 			sport->sadb_x_nat_t_port_port,
5165 			dport->sadb_x_nat_t_port_port));
5166 
5167 		if (type)
5168 			sav->natt_type = type->sadb_x_nat_t_type_type;
5169 		if (sport)
5170 			key_porttosaddr(&sav->sah->saidx.src,
5171 			    sport->sadb_x_nat_t_port_port);
5172 		if (dport)
5173 			key_porttosaddr(&sav->sah->saidx.dst,
5174 			    dport->sadb_x_nat_t_port_port);
5175 		if (frag)
5176 			sav->esp_frag = frag->sadb_x_nat_t_frag_fraglen;
5177 		else
5178 			sav->esp_frag = IP_MAXPACKET;
5179 	}
5180 
5181 	return 0;
5182 }
5183 
5184 /* Just update the IPSEC_NAT_T ports if present */
5185 static int
5186 key_set_natt_ports(union sockaddr_union *src, union sockaddr_union *dst,
5187       		     const struct sadb_msghdr *mhp)
5188 {
5189 
5190 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
5191 		ipseclog((LOG_DEBUG,"update: NAT-T OAi present\n"));
5192 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
5193 		ipseclog((LOG_DEBUG,"update: NAT-T OAr present\n"));
5194 
5195 	if ((mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL) &&
5196 	    (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL) &&
5197 	    (mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL)) {
5198 		struct sadb_x_nat_t_type *type;
5199 		struct sadb_x_nat_t_port *sport;
5200 		struct sadb_x_nat_t_port *dport;
5201 
5202 		if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
5203 		    (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
5204 		    (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
5205 			ipseclog((LOG_DEBUG, "key_update: "
5206 			    "invalid message.\n"));
5207 			return -1;
5208 		}
5209 
5210 		sport = (struct sadb_x_nat_t_port *)
5211 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5212 		dport = (struct sadb_x_nat_t_port *)
5213 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5214 
5215 		if (sport)
5216 			key_porttosaddr(src,
5217 			    sport->sadb_x_nat_t_port_port);
5218 		if (dport)
5219 			key_porttosaddr(dst,
5220 			    dport->sadb_x_nat_t_port_port);
5221 	}
5222 
5223 	return 0;
5224 }
5225 #endif
5226 
5227 
5228 /*
5229  * SADB_UPDATE processing
5230  * receive
5231  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5232  *       key(AE), (identity(SD),) (sensitivity)>
5233  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
5234  * and send
5235  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5236  *       (identity(SD),) (sensitivity)>
5237  * to the ikmpd.
5238  *
5239  * m will always be freed.
5240  */
5241 static int
5242 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5243 {
5244 	struct sadb_sa *sa0;
5245 	struct sadb_address *src0, *dst0;
5246 	struct secasindex saidx;
5247 	struct secashead *sah;
5248 	struct secasvar *sav;
5249 	u_int16_t proto;
5250 	u_int8_t mode;
5251 	u_int16_t reqid;
5252 	int error;
5253 
5254 	/* sanity check */
5255 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5256 		panic("key_update: NULL pointer is passed");
5257 
5258 	/* map satype to proto */
5259 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5260 		ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
5261 		return key_senderror(so, m, EINVAL);
5262 	}
5263 
5264 	if (mhp->ext[SADB_EXT_SA] == NULL ||
5265 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5266 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5267 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5268 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5269 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5270 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5271 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5272 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5273 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5274 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5275 		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
5276 		return key_senderror(so, m, EINVAL);
5277 	}
5278 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5279 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5280 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5281 		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
5282 		return key_senderror(so, m, EINVAL);
5283 	}
5284 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5285 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5286 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5287 	} else {
5288 		mode = IPSEC_MODE_ANY;
5289 		reqid = 0;
5290 	}
5291 	/* XXX boundary checking for other extensions */
5292 
5293 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5294 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5295 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5296 
5297 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
5298 				     dst0 + 1, &saidx)) != 0)
5299 		return key_senderror(so, m, EINVAL);
5300 
5301 #ifdef IPSEC_NAT_T
5302 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
5303 		return key_senderror(so, m, EINVAL);
5304 #endif
5305 
5306 	/* get a SA header */
5307 	if ((sah = key_getsah(&saidx)) == NULL) {
5308 		ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
5309 		return key_senderror(so, m, ENOENT);
5310 	}
5311 
5312 	/* set spidx if there */
5313 	/* XXX rewrite */
5314 	error = key_setident(sah, m, mhp);
5315 	if (error)
5316 		return key_senderror(so, m, error);
5317 
5318 	/* find a SA with sequence number. */
5319 #ifdef IPSEC_DOSEQCHECK
5320 	if (mhp->msg->sadb_msg_seq != 0
5321 	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
5322 		ipseclog((LOG_DEBUG,
5323 		    "key_update: no larval SA with sequence %u exists.\n",
5324 		    mhp->msg->sadb_msg_seq));
5325 		return key_senderror(so, m, ENOENT);
5326 	}
5327 #else
5328 	if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
5329 		ipseclog((LOG_DEBUG,
5330 		    "key_update: no such a SA found (spi:%u)\n",
5331 		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5332 		return key_senderror(so, m, EINVAL);
5333 	}
5334 #endif
5335 
5336 	/* validity check */
5337 	if (sav->sah->saidx.proto != proto) {
5338 		ipseclog((LOG_DEBUG,
5339 		    "key_update: protocol mismatched (DB=%u param=%u)\n",
5340 		    sav->sah->saidx.proto, proto));
5341 		return key_senderror(so, m, EINVAL);
5342 	}
5343 #ifdef IPSEC_DOSEQCHECK
5344 	if (sav->spi != sa0->sadb_sa_spi) {
5345 		ipseclog((LOG_DEBUG,
5346 		    "key_update: SPI mismatched (DB:%u param:%u)\n",
5347 		    (u_int32_t)ntohl(sav->spi),
5348 		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5349 		return key_senderror(so, m, EINVAL);
5350 	}
5351 #endif
5352 	if (sav->pid != mhp->msg->sadb_msg_pid) {
5353 		ipseclog((LOG_DEBUG,
5354 		    "key_update: pid mismatched (DB:%u param:%u)\n",
5355 		    sav->pid, mhp->msg->sadb_msg_pid));
5356 		return key_senderror(so, m, EINVAL);
5357 	}
5358 
5359 	/* copy sav values */
5360 	error = key_setsaval(sav, m, mhp);
5361 	if (error) {
5362 		KEY_FREESAV(&sav);
5363 		return key_senderror(so, m, error);
5364 	}
5365 
5366 #ifdef IPSEC_NAT_T
5367 	if ((error = key_handle_natt_info(sav,mhp)) != 0)
5368 		return key_senderror(so, m, EINVAL);
5369 #endif /* IPSEC_NAT_T */
5370 
5371 	/* check SA values to be mature. */
5372 	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5373 		KEY_FREESAV(&sav);
5374 		return key_senderror(so, m, 0);
5375 	}
5376 
5377     {
5378 	struct mbuf *n;
5379 
5380 	/* set msg buf from mhp */
5381 	n = key_getmsgbuf_x1(m, mhp);
5382 	if (n == NULL) {
5383 		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
5384 		return key_senderror(so, m, ENOBUFS);
5385 	}
5386 
5387 	m_freem(m);
5388 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5389     }
5390 }
5391 
5392 /*
5393  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5394  * only called by key_update().
5395  * OUT:
5396  *	NULL	: not found
5397  *	others	: found, pointer to a SA.
5398  */
5399 #ifdef IPSEC_DOSEQCHECK
5400 static struct secasvar *
5401 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
5402 {
5403 	struct secasvar *sav;
5404 	u_int state;
5405 
5406 	state = SADB_SASTATE_LARVAL;
5407 
5408 	/* search SAD with sequence number ? */
5409 	LIST_FOREACH(sav, &sah->savtree[state], chain) {
5410 
5411 		KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
5412 
5413 		if (sav->seq == seq) {
5414 			SA_ADDREF(sav);
5415 			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5416 				printf("DP key_getsavbyseq cause "
5417 					"refcnt++:%d SA:%p\n",
5418 					sav->refcnt, sav));
5419 			return sav;
5420 		}
5421 	}
5422 
5423 	return NULL;
5424 }
5425 #endif
5426 
5427 /*
5428  * SADB_ADD processing
5429  * add an entry to SA database, when received
5430  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5431  *       key(AE), (identity(SD),) (sensitivity)>
5432  * from the ikmpd,
5433  * and send
5434  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5435  *       (identity(SD),) (sensitivity)>
5436  * to the ikmpd.
5437  *
5438  * IGNORE identity and sensitivity messages.
5439  *
5440  * m will always be freed.
5441  */
5442 static int
5443 key_add(struct socket *so, struct mbuf *m,
5444 	const struct sadb_msghdr *mhp)
5445 {
5446 	struct sadb_sa *sa0;
5447 	struct sadb_address *src0, *dst0;
5448 	struct secasindex saidx;
5449 	struct secashead *newsah;
5450 	struct secasvar *newsav;
5451 	u_int16_t proto;
5452 	u_int8_t mode;
5453 	u_int16_t reqid;
5454 	int error;
5455 
5456 	/* sanity check */
5457 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5458 		panic("key_add: NULL pointer is passed");
5459 
5460 	/* map satype to proto */
5461 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5462 		ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
5463 		return key_senderror(so, m, EINVAL);
5464 	}
5465 
5466 	if (mhp->ext[SADB_EXT_SA] == NULL ||
5467 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5468 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5469 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5470 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5471 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5472 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5473 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5474 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5475 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5476 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5477 		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
5478 		return key_senderror(so, m, EINVAL);
5479 	}
5480 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5481 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5482 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5483 		/* XXX need more */
5484 		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
5485 		return key_senderror(so, m, EINVAL);
5486 	}
5487 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5488 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5489 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5490 	} else {
5491 		mode = IPSEC_MODE_ANY;
5492 		reqid = 0;
5493 	}
5494 
5495 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5496 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5497 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5498 
5499 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
5500 				     dst0 + 1, &saidx)) != 0)
5501 		return key_senderror(so, m, EINVAL);
5502 
5503 #ifdef IPSEC_NAT_T
5504 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
5505 		return key_senderror(so, m, EINVAL);
5506 #endif
5507 
5508 	/* get a SA header */
5509 	if ((newsah = key_getsah(&saidx)) == NULL) {
5510 		/* create a new SA header */
5511 		if ((newsah = key_newsah(&saidx)) == NULL) {
5512 			ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
5513 			return key_senderror(so, m, ENOBUFS);
5514 		}
5515 	}
5516 
5517 	/* set spidx if there */
5518 	/* XXX rewrite */
5519 	error = key_setident(newsah, m, mhp);
5520 	if (error) {
5521 		return key_senderror(so, m, error);
5522 	}
5523 
5524 	/* create new SA entry. */
5525 	/* We can create new SA only if SPI is differenct. */
5526 	if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
5527 		ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
5528 		return key_senderror(so, m, EEXIST);
5529 	}
5530 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5531 	if (newsav == NULL) {
5532 		return key_senderror(so, m, error);
5533 	}
5534 
5535 #ifdef IPSEC_NAT_T
5536 	if ((error = key_handle_natt_info(newsav, mhp)) != 0)
5537 		return key_senderror(so, m, EINVAL);
5538 #endif /* IPSEC_NAT_T */
5539 
5540 	/* check SA values to be mature. */
5541 	if ((error = key_mature(newsav)) != 0) {
5542 		KEY_FREESAV(&newsav);
5543 		return key_senderror(so, m, error);
5544 	}
5545 
5546 	/*
5547 	 * don't call key_freesav() here, as we would like to keep the SA
5548 	 * in the database on success.
5549 	 */
5550 
5551     {
5552 	struct mbuf *n;
5553 
5554 	/* set msg buf from mhp */
5555 	n = key_getmsgbuf_x1(m, mhp);
5556 	if (n == NULL) {
5557 		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
5558 		return key_senderror(so, m, ENOBUFS);
5559 	}
5560 
5561 	m_freem(m);
5562 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5563     }
5564 }
5565 
5566 /* m is retained */
5567 static int
5568 key_setident(struct secashead *sah, struct mbuf *m,
5569 	     const struct sadb_msghdr *mhp)
5570 {
5571 	const struct sadb_ident *idsrc, *iddst;
5572 	int idsrclen, iddstlen;
5573 
5574 	/* sanity check */
5575 	if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5576 		panic("key_setident: NULL pointer is passed");
5577 
5578 	/* don't make buffer if not there */
5579 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5580 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5581 		sah->idents = NULL;
5582 		sah->identd = NULL;
5583 		return 0;
5584 	}
5585 
5586 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5587 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5588 		ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
5589 		return EINVAL;
5590 	}
5591 
5592 	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5593 	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5594 	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5595 	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5596 
5597 	/* validity check */
5598 	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5599 		ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
5600 		return EINVAL;
5601 	}
5602 
5603 	switch (idsrc->sadb_ident_type) {
5604 	case SADB_IDENTTYPE_PREFIX:
5605 	case SADB_IDENTTYPE_FQDN:
5606 	case SADB_IDENTTYPE_USERFQDN:
5607 	default:
5608 		/* XXX do nothing */
5609 		sah->idents = NULL;
5610 		sah->identd = NULL;
5611 	 	return 0;
5612 	}
5613 
5614 	/* make structure */
5615 	KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
5616 	if (sah->idents == NULL) {
5617 		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5618 		return ENOBUFS;
5619 	}
5620 	KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
5621 	if (sah->identd == NULL) {
5622 		KFREE(sah->idents);
5623 		sah->idents = NULL;
5624 		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5625 		return ENOBUFS;
5626 	}
5627 	memcpy(sah->idents, idsrc, idsrclen);
5628 	memcpy(sah->identd, iddst, iddstlen);
5629 
5630 	return 0;
5631 }
5632 
5633 /*
5634  * m will not be freed on return.
5635  * it is caller's responsibility to free the result.
5636  */
5637 static struct mbuf *
5638 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5639 {
5640 	struct mbuf *n;
5641 
5642 	/* sanity check */
5643 	if (m == NULL || mhp == NULL || mhp->msg == NULL)
5644 		panic("key_getmsgbuf_x1: NULL pointer is passed");
5645 
5646 	/* create new sadb_msg to reply. */
5647 	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5648 	    SADB_EXT_SA, SADB_X_EXT_SA2,
5649 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5650 	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5651 	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5652 	if (!n)
5653 		return NULL;
5654 
5655 	if (n->m_len < sizeof(struct sadb_msg)) {
5656 		n = m_pullup(n, sizeof(struct sadb_msg));
5657 		if (n == NULL)
5658 			return NULL;
5659 	}
5660 	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5661 	mtod(n, struct sadb_msg *)->sadb_msg_len =
5662 	    PFKEY_UNIT64(n->m_pkthdr.len);
5663 
5664 	return n;
5665 }
5666 
5667 static int key_delete_all (struct socket *, struct mbuf *,
5668 			   const struct sadb_msghdr *, u_int16_t);
5669 
5670 /*
5671  * SADB_DELETE processing
5672  * receive
5673  *   <base, SA(*), address(SD)>
5674  * from the ikmpd, and set SADB_SASTATE_DEAD,
5675  * and send,
5676  *   <base, SA(*), address(SD)>
5677  * to the ikmpd.
5678  *
5679  * m will always be freed.
5680  */
5681 static int
5682 key_delete(struct socket *so, struct mbuf *m,
5683 	   const struct sadb_msghdr *mhp)
5684 {
5685 	struct sadb_sa *sa0;
5686 	struct sadb_address *src0, *dst0;
5687 	struct secasindex saidx;
5688 	struct secashead *sah;
5689 	struct secasvar *sav = NULL;
5690 	u_int16_t proto;
5691 	int error;
5692 
5693 	/* sanity check */
5694 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5695 		panic("key_delete: NULL pointer is passed");
5696 
5697 	/* map satype to proto */
5698 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5699 		ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
5700 		return key_senderror(so, m, EINVAL);
5701 	}
5702 
5703 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5704 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5705 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5706 		return key_senderror(so, m, EINVAL);
5707 	}
5708 
5709 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5710 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5711 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5712 		return key_senderror(so, m, EINVAL);
5713 	}
5714 
5715 	if (mhp->ext[SADB_EXT_SA] == NULL) {
5716 		/*
5717 		 * Caller wants us to delete all non-LARVAL SAs
5718 		 * that match the src/dst.  This is used during
5719 		 * IKE INITIAL-CONTACT.
5720 		 */
5721 		ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
5722 		return key_delete_all(so, m, mhp, proto);
5723 	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5724 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5725 		return key_senderror(so, m, EINVAL);
5726 	}
5727 
5728 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5729 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5730 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5731 
5732 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
5733 				     dst0 + 1, &saidx)) != 0)
5734 		return key_senderror(so, m, EINVAL);
5735 
5736 #ifdef IPSEC_NAT_T
5737 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
5738 		return key_senderror(so, m, EINVAL);
5739 #endif
5740 
5741 	/* get a SA header */
5742 	LIST_FOREACH(sah, &sahtree, chain) {
5743 		if (sah->state == SADB_SASTATE_DEAD)
5744 			continue;
5745 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5746 			continue;
5747 
5748 		/* get a SA with SPI. */
5749 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5750 		if (sav)
5751 			break;
5752 	}
5753 	if (sah == NULL) {
5754 		ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
5755 		return key_senderror(so, m, ENOENT);
5756 	}
5757 
5758 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5759 	KEY_FREESAV(&sav);
5760 
5761     {
5762 	struct mbuf *n;
5763 	struct sadb_msg *newmsg;
5764 
5765 	/* create new sadb_msg to reply. */
5766 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5767 	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5768 	if (!n)
5769 		return key_senderror(so, m, ENOBUFS);
5770 
5771 	if (n->m_len < sizeof(struct sadb_msg)) {
5772 		n = m_pullup(n, sizeof(struct sadb_msg));
5773 		if (n == NULL)
5774 			return key_senderror(so, m, ENOBUFS);
5775 	}
5776 	newmsg = mtod(n, struct sadb_msg *);
5777 	newmsg->sadb_msg_errno = 0;
5778 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5779 
5780 	m_freem(m);
5781 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5782     }
5783 }
5784 
5785 /*
5786  * delete all SAs for src/dst.  Called from key_delete().
5787  */
5788 static int
5789 key_delete_all(struct socket *so, struct mbuf *m,
5790 	       const struct sadb_msghdr *mhp, u_int16_t proto)
5791 {
5792 	struct sadb_address *src0, *dst0;
5793 	struct secasindex saidx;
5794 	struct secashead *sah;
5795 	struct secasvar *sav, *nextsav;
5796 	u_int stateidx, state;
5797 	int error;
5798 
5799 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5800 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5801 
5802 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
5803 				     dst0 + 1, &saidx)) != 0)
5804 		return key_senderror(so, m, EINVAL);
5805 
5806 #ifdef IPSEC_NAT_T
5807 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
5808 		return key_senderror(so, m, EINVAL);
5809 #endif
5810 
5811 	LIST_FOREACH(sah, &sahtree, chain) {
5812 		if (sah->state == SADB_SASTATE_DEAD)
5813 			continue;
5814 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5815 			continue;
5816 
5817 		/* Delete all non-LARVAL SAs. */
5818 		for (stateidx = 0;
5819 		     stateidx < _ARRAYLEN(saorder_state_alive);
5820 		     stateidx++) {
5821 			state = saorder_state_alive[stateidx];
5822 			if (state == SADB_SASTATE_LARVAL)
5823 				continue;
5824 			for (sav = LIST_FIRST(&sah->savtree[state]);
5825 			     sav != NULL; sav = nextsav) {
5826 				nextsav = LIST_NEXT(sav, chain);
5827 				/* sanity check */
5828 				if (sav->state != state) {
5829 					ipseclog((LOG_DEBUG, "key_delete_all: "
5830 					       "invalid sav->state "
5831 					       "(queue: %d SA: %d)\n",
5832 					       state, sav->state));
5833 					continue;
5834 				}
5835 
5836 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5837 				KEY_FREESAV(&sav);
5838 			}
5839 		}
5840 	}
5841     {
5842 	struct mbuf *n;
5843 	struct sadb_msg *newmsg;
5844 
5845 	/* create new sadb_msg to reply. */
5846 	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5847 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5848 	if (!n)
5849 		return key_senderror(so, m, ENOBUFS);
5850 
5851 	if (n->m_len < sizeof(struct sadb_msg)) {
5852 		n = m_pullup(n, sizeof(struct sadb_msg));
5853 		if (n == NULL)
5854 			return key_senderror(so, m, ENOBUFS);
5855 	}
5856 	newmsg = mtod(n, struct sadb_msg *);
5857 	newmsg->sadb_msg_errno = 0;
5858 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5859 
5860 	m_freem(m);
5861 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5862     }
5863 }
5864 
5865 /*
5866  * SADB_GET processing
5867  * receive
5868  *   <base, SA(*), address(SD)>
5869  * from the ikmpd, and get a SP and a SA to respond,
5870  * and send,
5871  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5872  *       (identity(SD),) (sensitivity)>
5873  * to the ikmpd.
5874  *
5875  * m will always be freed.
5876  */
5877 static int
5878 key_get(struct socket *so, struct mbuf *m,
5879      	const struct sadb_msghdr *mhp)
5880 {
5881 	struct sadb_sa *sa0;
5882 	struct sadb_address *src0, *dst0;
5883 	struct secasindex saidx;
5884 	struct secashead *sah;
5885 	struct secasvar *sav = NULL;
5886 	u_int16_t proto;
5887 	int error;
5888 
5889 	/* sanity check */
5890 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5891 		panic("key_get: NULL pointer is passed");
5892 
5893 	/* map satype to proto */
5894 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5895 		ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
5896 		return key_senderror(so, m, EINVAL);
5897 	}
5898 
5899 	if (mhp->ext[SADB_EXT_SA] == NULL ||
5900 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5901 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5902 		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5903 		return key_senderror(so, m, EINVAL);
5904 	}
5905 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5906 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5907 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5908 		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5909 		return key_senderror(so, m, EINVAL);
5910 	}
5911 
5912 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5913 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5914 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5915 
5916 
5917 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
5918 				     dst0 + 1, &saidx)) != 0)
5919 		return key_senderror(so, m, EINVAL);
5920 
5921 #ifdef IPSEC_NAT_T
5922 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
5923 		return key_senderror(so, m, EINVAL);
5924 #endif
5925 
5926 	/* get a SA header */
5927 	LIST_FOREACH(sah, &sahtree, chain) {
5928 		if (sah->state == SADB_SASTATE_DEAD)
5929 			continue;
5930 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5931 			continue;
5932 
5933 		/* get a SA with SPI. */
5934 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5935 		if (sav)
5936 			break;
5937 	}
5938 	if (sah == NULL) {
5939 		ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
5940 		return key_senderror(so, m, ENOENT);
5941 	}
5942 
5943     {
5944 	struct mbuf *n;
5945 	u_int8_t satype;
5946 
5947 	/* map proto to satype */
5948 	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5949 		ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
5950 		return key_senderror(so, m, EINVAL);
5951 	}
5952 
5953 	/* create new sadb_msg to reply. */
5954 	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5955 	    mhp->msg->sadb_msg_pid);
5956 	if (!n)
5957 		return key_senderror(so, m, ENOBUFS);
5958 
5959 	m_freem(m);
5960 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5961     }
5962 }
5963 
5964 /* XXX make it sysctl-configurable? */
5965 static void
5966 key_getcomb_setlifetime(struct sadb_comb *comb)
5967 {
5968 
5969 	comb->sadb_comb_soft_allocations = 1;
5970 	comb->sadb_comb_hard_allocations = 1;
5971 	comb->sadb_comb_soft_bytes = 0;
5972 	comb->sadb_comb_hard_bytes = 0;
5973 	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5974 	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5975 	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5976 	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5977 }
5978 
5979 /*
5980  * XXX reorder combinations by preference
5981  * XXX no idea if the user wants ESP authentication or not
5982  */
5983 static struct mbuf *
5984 key_getcomb_esp(void)
5985 {
5986 	struct sadb_comb *comb;
5987 	const struct enc_xform *algo;
5988 	struct mbuf *result = NULL, *m, *n;
5989 	int encmin;
5990 	int i, off, o;
5991 	int totlen;
5992 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5993 
5994 	m = NULL;
5995 	for (i = 1; i <= SADB_EALG_MAX; i++) {
5996 		algo = esp_algorithm_lookup(i);
5997 		if (algo == NULL)
5998 			continue;
5999 
6000 		/* discard algorithms with key size smaller than system min */
6001 		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
6002 			continue;
6003 		if (_BITS(algo->minkey) < ipsec_esp_keymin)
6004 			encmin = ipsec_esp_keymin;
6005 		else
6006 			encmin = _BITS(algo->minkey);
6007 
6008 		if (ipsec_esp_auth)
6009 			m = key_getcomb_ah();
6010 		else {
6011 			IPSEC_ASSERT(l <= MLEN,
6012 				("key_getcomb_esp: l=%u > MLEN=%lu",
6013 				l, (u_long) MLEN));
6014 			MGET(m, M_DONTWAIT, MT_DATA);
6015 			if (m) {
6016 				M_ALIGN(m, l);
6017 				m->m_len = l;
6018 				m->m_next = NULL;
6019 				memset(mtod(m, void *), 0, m->m_len);
6020 			}
6021 		}
6022 		if (!m)
6023 			goto fail;
6024 
6025 		totlen = 0;
6026 		for (n = m; n; n = n->m_next)
6027 			totlen += n->m_len;
6028 		IPSEC_ASSERT((totlen % l) == 0,
6029 			("key_getcomb_esp: totlen=%u, l=%u", totlen, l));
6030 
6031 		for (off = 0; off < totlen; off += l) {
6032 			n = m_pulldown(m, off, l, &o);
6033 			if (!n) {
6034 				/* m is already freed */
6035 				goto fail;
6036 			}
6037 			comb = (struct sadb_comb *)(mtod(n, char *) + o);
6038 			memset(comb, 0, sizeof(*comb));
6039 			key_getcomb_setlifetime(comb);
6040 			comb->sadb_comb_encrypt = i;
6041 			comb->sadb_comb_encrypt_minbits = encmin;
6042 			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6043 		}
6044 
6045 		if (!result)
6046 			result = m;
6047 		else
6048 			m_cat(result, m);
6049 	}
6050 
6051 	return result;
6052 
6053  fail:
6054 	if (result)
6055 		m_freem(result);
6056 	return NULL;
6057 }
6058 
6059 static void
6060 key_getsizes_ah(const struct auth_hash *ah, int alg,
6061 	        u_int16_t* ksmin, u_int16_t* ksmax)
6062 {
6063 	*ksmin = *ksmax = ah->keysize;
6064 	if (ah->keysize == 0) {
6065 		/*
6066 		 * Transform takes arbitrary key size but algorithm
6067 		 * key size is restricted.  Enforce this here.
6068 		 */
6069 		switch (alg) {
6070 		case SADB_X_AALG_MD5:	*ksmin = *ksmax = 16; break;
6071 		case SADB_X_AALG_SHA:	*ksmin = *ksmax = 20; break;
6072 		case SADB_X_AALG_NULL:	*ksmin = 1; *ksmax = 256; break;
6073 		default:
6074 			DPRINTF(("key_getsizes_ah: unknown AH algorithm %u\n",
6075 				alg));
6076 			break;
6077 		}
6078 	}
6079 }
6080 
6081 /*
6082  * XXX reorder combinations by preference
6083  */
6084 static struct mbuf *
6085 key_getcomb_ah(void)
6086 {
6087 	struct sadb_comb *comb;
6088 	const struct auth_hash *algo;
6089 	struct mbuf *m;
6090 	u_int16_t minkeysize, maxkeysize;
6091 	int i;
6092 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6093 
6094 	m = NULL;
6095 	for (i = 1; i <= SADB_AALG_MAX; i++) {
6096 #if 1
6097 		/* we prefer HMAC algorithms, not old algorithms */
6098 		if (i != SADB_AALG_SHA1HMAC &&
6099 		    i != SADB_AALG_MD5HMAC &&
6100 		    i != SADB_X_AALG_SHA2_256 &&
6101 		    i != SADB_X_AALG_SHA2_384 &&
6102 		    i != SADB_X_AALG_SHA2_512)
6103 			continue;
6104 #endif
6105 		algo = ah_algorithm_lookup(i);
6106 		if (!algo)
6107 			continue;
6108 		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6109 		/* discard algorithms with key size smaller than system min */
6110 		if (_BITS(minkeysize) < ipsec_ah_keymin)
6111 			continue;
6112 
6113 		if (!m) {
6114 			IPSEC_ASSERT(l <= MLEN,
6115 				("key_getcomb_ah: l=%u > MLEN=%lu",
6116 				l, (u_long) MLEN));
6117 			MGET(m, M_DONTWAIT, MT_DATA);
6118 			if (m) {
6119 				M_ALIGN(m, l);
6120 				m->m_len = l;
6121 				m->m_next = NULL;
6122 			}
6123 		} else
6124 			M_PREPEND(m, l, M_DONTWAIT);
6125 		if (!m)
6126 			return NULL;
6127 
6128 		comb = mtod(m, struct sadb_comb *);
6129 		memset(comb, 0, sizeof(*comb));
6130 		key_getcomb_setlifetime(comb);
6131 		comb->sadb_comb_auth = i;
6132 		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6133 		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6134 	}
6135 
6136 	return m;
6137 }
6138 
6139 /*
6140  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6141  * XXX reorder combinations by preference
6142  */
6143 static struct mbuf *
6144 key_getcomb_ipcomp(void)
6145 {
6146 	struct sadb_comb *comb;
6147 	const struct comp_algo *algo;
6148 	struct mbuf *m;
6149 	int i;
6150 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6151 
6152 	m = NULL;
6153 	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6154 		algo = ipcomp_algorithm_lookup(i);
6155 		if (!algo)
6156 			continue;
6157 
6158 		if (!m) {
6159 			IPSEC_ASSERT(l <= MLEN,
6160 				("key_getcomb_ipcomp: l=%u > MLEN=%lu",
6161 				l, (u_long) MLEN));
6162 			MGET(m, M_DONTWAIT, MT_DATA);
6163 			if (m) {
6164 				M_ALIGN(m, l);
6165 				m->m_len = l;
6166 				m->m_next = NULL;
6167 			}
6168 		} else
6169 			M_PREPEND(m, l, M_DONTWAIT);
6170 		if (!m)
6171 			return NULL;
6172 
6173 		comb = mtod(m, struct sadb_comb *);
6174 		memset(comb, 0, sizeof(*comb));
6175 		key_getcomb_setlifetime(comb);
6176 		comb->sadb_comb_encrypt = i;
6177 		/* what should we set into sadb_comb_*_{min,max}bits? */
6178 	}
6179 
6180 	return m;
6181 }
6182 
6183 /*
6184  * XXX no way to pass mode (transport/tunnel) to userland
6185  * XXX replay checking?
6186  * XXX sysctl interface to ipsec_{ah,esp}_keymin
6187  */
6188 static struct mbuf *
6189 key_getprop(const struct secasindex *saidx)
6190 {
6191 	struct sadb_prop *prop;
6192 	struct mbuf *m, *n;
6193 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6194 	int totlen;
6195 
6196 	switch (saidx->proto)  {
6197 	case IPPROTO_ESP:
6198 		m = key_getcomb_esp();
6199 		break;
6200 	case IPPROTO_AH:
6201 		m = key_getcomb_ah();
6202 		break;
6203 	case IPPROTO_IPCOMP:
6204 		m = key_getcomb_ipcomp();
6205 		break;
6206 	default:
6207 		return NULL;
6208 	}
6209 
6210 	if (!m)
6211 		return NULL;
6212 	M_PREPEND(m, l, M_DONTWAIT);
6213 	if (!m)
6214 		return NULL;
6215 
6216 	totlen = 0;
6217 	for (n = m; n; n = n->m_next)
6218 		totlen += n->m_len;
6219 
6220 	prop = mtod(m, struct sadb_prop *);
6221 	memset(prop, 0, sizeof(*prop));
6222 	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6223 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6224 	prop->sadb_prop_replay = 32;	/* XXX */
6225 
6226 	return m;
6227 }
6228 
6229 /*
6230  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6231  * send
6232  *   <base, SA, address(SD), (address(P)), x_policy,
6233  *       (identity(SD),) (sensitivity,) proposal>
6234  * to KMD, and expect to receive
6235  *   <base> with SADB_ACQUIRE if error occurred,
6236  * or
6237  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6238  * from KMD by PF_KEY.
6239  *
6240  * XXX x_policy is outside of RFC2367 (KAME extension).
6241  * XXX sensitivity is not supported.
6242  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6243  * see comment for key_getcomb_ipcomp().
6244  *
6245  * OUT:
6246  *    0     : succeed
6247  *    others: error number
6248  */
6249 static int
6250 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6251 {
6252 	struct mbuf *result = NULL, *m;
6253 #ifndef IPSEC_NONBLOCK_ACQUIRE
6254 	struct secacq *newacq;
6255 #endif
6256 	u_int8_t satype;
6257 	int error = -1;
6258 	u_int32_t seq;
6259 
6260 	/* sanity check */
6261 	IPSEC_ASSERT(saidx != NULL, ("key_acquire: null saidx"));
6262 	satype = key_proto2satype(saidx->proto);
6263 	IPSEC_ASSERT(satype != 0,
6264 		("key_acquire: null satype, protocol %u", saidx->proto));
6265 
6266 #ifndef IPSEC_NONBLOCK_ACQUIRE
6267 	/*
6268 	 * We never do anything about acquirng SA.  There is anather
6269 	 * solution that kernel blocks to send SADB_ACQUIRE message until
6270 	 * getting something message from IKEd.  In later case, to be
6271 	 * managed with ACQUIRING list.
6272 	 */
6273 	/* Get an entry to check whether sending message or not. */
6274 	if ((newacq = key_getacq(saidx)) != NULL) {
6275 		if (key_blockacq_count < newacq->count) {
6276 			/* reset counter and do send message. */
6277 			newacq->count = 0;
6278 		} else {
6279 			/* increment counter and do nothing. */
6280 			newacq->count++;
6281 			return 0;
6282 		}
6283 	} else {
6284 		/* make new entry for blocking to send SADB_ACQUIRE. */
6285 		if ((newacq = key_newacq(saidx)) == NULL)
6286 			return ENOBUFS;
6287 
6288 		/* add to acqtree */
6289 		LIST_INSERT_HEAD(&acqtree, newacq, chain);
6290 	}
6291 #endif
6292 
6293 
6294 #ifndef IPSEC_NONBLOCK_ACQUIRE
6295 	seq = newacq->seq;
6296 #else
6297 	seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
6298 #endif
6299 	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6300 	if (!m) {
6301 		error = ENOBUFS;
6302 		goto fail;
6303 	}
6304 	result = m;
6305 
6306 	/* set sadb_address for saidx's. */
6307 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6308 	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6309 	if (!m) {
6310 		error = ENOBUFS;
6311 		goto fail;
6312 	}
6313 	m_cat(result, m);
6314 
6315 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6316 	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6317 	if (!m) {
6318 		error = ENOBUFS;
6319 		goto fail;
6320 	}
6321 	m_cat(result, m);
6322 
6323 	/* XXX proxy address (optional) */
6324 
6325 	/* set sadb_x_policy */
6326 	if (sp) {
6327 		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6328 		if (!m) {
6329 			error = ENOBUFS;
6330 			goto fail;
6331 		}
6332 		m_cat(result, m);
6333 	}
6334 
6335 	/* XXX identity (optional) */
6336 #if 0
6337 	if (idexttype && fqdn) {
6338 		/* create identity extension (FQDN) */
6339 		struct sadb_ident *id;
6340 		int fqdnlen;
6341 
6342 		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
6343 		id = (struct sadb_ident *)p;
6344 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6345 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6346 		id->sadb_ident_exttype = idexttype;
6347 		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6348 		memcpy(id + 1, fqdn, fqdnlen);
6349 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6350 	}
6351 
6352 	if (idexttype) {
6353 		/* create identity extension (USERFQDN) */
6354 		struct sadb_ident *id;
6355 		int userfqdnlen;
6356 
6357 		if (userfqdn) {
6358 			/* +1 for terminating-NUL */
6359 			userfqdnlen = strlen(userfqdn) + 1;
6360 		} else
6361 			userfqdnlen = 0;
6362 		id = (struct sadb_ident *)p;
6363 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6364 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6365 		id->sadb_ident_exttype = idexttype;
6366 		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6367 		/* XXX is it correct? */
6368 		if (curlwp)
6369 			id->sadb_ident_id = kauth_cred_getuid(curlwp->l_cred);
6370 		if (userfqdn && userfqdnlen)
6371 			memcpy(id + 1, userfqdn, userfqdnlen);
6372 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6373 	}
6374 #endif
6375 
6376 	/* XXX sensitivity (optional) */
6377 
6378 	/* create proposal/combination extension */
6379 	m = key_getprop(saidx);
6380 #if 0
6381 	/*
6382 	 * spec conformant: always attach proposal/combination extension,
6383 	 * the problem is that we have no way to attach it for ipcomp,
6384 	 * due to the way sadb_comb is declared in RFC2367.
6385 	 */
6386 	if (!m) {
6387 		error = ENOBUFS;
6388 		goto fail;
6389 	}
6390 	m_cat(result, m);
6391 #else
6392 	/*
6393 	 * outside of spec; make proposal/combination extension optional.
6394 	 */
6395 	if (m)
6396 		m_cat(result, m);
6397 #endif
6398 
6399 	if ((result->m_flags & M_PKTHDR) == 0) {
6400 		error = EINVAL;
6401 		goto fail;
6402 	}
6403 
6404 	if (result->m_len < sizeof(struct sadb_msg)) {
6405 		result = m_pullup(result, sizeof(struct sadb_msg));
6406 		if (result == NULL) {
6407 			error = ENOBUFS;
6408 			goto fail;
6409 		}
6410 	}
6411 
6412 	result->m_pkthdr.len = 0;
6413 	for (m = result; m; m = m->m_next)
6414 		result->m_pkthdr.len += m->m_len;
6415 
6416 	mtod(result, struct sadb_msg *)->sadb_msg_len =
6417 	    PFKEY_UNIT64(result->m_pkthdr.len);
6418 
6419 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6420 
6421  fail:
6422 	if (result)
6423 		m_freem(result);
6424 	return error;
6425 }
6426 
6427 #ifndef IPSEC_NONBLOCK_ACQUIRE
6428 static struct secacq *
6429 key_newacq(const struct secasindex *saidx)
6430 {
6431 	struct secacq *newacq;
6432 
6433 	/* get new entry */
6434 	KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
6435 	if (newacq == NULL) {
6436 		ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
6437 		return NULL;
6438 	}
6439 	memset(newacq, 0, sizeof(*newacq));
6440 
6441 	/* copy secindex */
6442 	memcpy(&newacq->saidx, saidx, sizeof(newacq->saidx));
6443 	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
6444 	newacq->created = time_uptime;
6445 	newacq->count = 0;
6446 
6447 	return newacq;
6448 }
6449 
6450 static struct secacq *
6451 key_getacq(const struct secasindex *saidx)
6452 {
6453 	struct secacq *acq;
6454 
6455 	LIST_FOREACH(acq, &acqtree, chain) {
6456 		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6457 			return acq;
6458 	}
6459 
6460 	return NULL;
6461 }
6462 
6463 static struct secacq *
6464 key_getacqbyseq(u_int32_t seq)
6465 {
6466 	struct secacq *acq;
6467 
6468 	LIST_FOREACH(acq, &acqtree, chain) {
6469 		if (acq->seq == seq)
6470 			return acq;
6471 	}
6472 
6473 	return NULL;
6474 }
6475 #endif
6476 
6477 static struct secspacq *
6478 key_newspacq(const struct secpolicyindex *spidx)
6479 {
6480 	struct secspacq *acq;
6481 
6482 	/* get new entry */
6483 	KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
6484 	if (acq == NULL) {
6485 		ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
6486 		return NULL;
6487 	}
6488 	memset(acq, 0, sizeof(*acq));
6489 
6490 	/* copy secindex */
6491 	memcpy(&acq->spidx, spidx, sizeof(acq->spidx));
6492 	acq->created = time_uptime;
6493 	acq->count = 0;
6494 
6495 	return acq;
6496 }
6497 
6498 static struct secspacq *
6499 key_getspacq(const struct secpolicyindex *spidx)
6500 {
6501 	struct secspacq *acq;
6502 
6503 	LIST_FOREACH(acq, &spacqtree, chain) {
6504 		if (key_cmpspidx_exactly(spidx, &acq->spidx))
6505 			return acq;
6506 	}
6507 
6508 	return NULL;
6509 }
6510 
6511 /*
6512  * SADB_ACQUIRE processing,
6513  * in first situation, is receiving
6514  *   <base>
6515  * from the ikmpd, and clear sequence of its secasvar entry.
6516  *
6517  * In second situation, is receiving
6518  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6519  * from a user land process, and return
6520  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6521  * to the socket.
6522  *
6523  * m will always be freed.
6524  */
6525 static int
6526 key_acquire2(struct socket *so, struct mbuf *m,
6527       	     const struct sadb_msghdr *mhp)
6528 {
6529 	const struct sadb_address *src0, *dst0;
6530 	struct secasindex saidx;
6531 	struct secashead *sah;
6532 	u_int16_t proto;
6533 	int error;
6534 
6535 	/* sanity check */
6536 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6537 		panic("key_acquire2: NULL pointer is passed");
6538 
6539 	/*
6540 	 * Error message from KMd.
6541 	 * We assume that if error was occurred in IKEd, the length of PFKEY
6542 	 * message is equal to the size of sadb_msg structure.
6543 	 * We do not raise error even if error occurred in this function.
6544 	 */
6545 	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6546 #ifndef IPSEC_NONBLOCK_ACQUIRE
6547 		struct secacq *acq;
6548 
6549 		/* check sequence number */
6550 		if (mhp->msg->sadb_msg_seq == 0) {
6551 			ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
6552 			m_freem(m);
6553 			return 0;
6554 		}
6555 
6556 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6557 			/*
6558 			 * the specified larval SA is already gone, or we got
6559 			 * a bogus sequence number.  we can silently ignore it.
6560 			 */
6561 			m_freem(m);
6562 			return 0;
6563 		}
6564 
6565 		/* reset acq counter in order to deletion by timehander. */
6566 		acq->created = time_uptime;
6567 		acq->count = 0;
6568 #endif
6569 		m_freem(m);
6570 		return 0;
6571 	}
6572 
6573 	/*
6574 	 * This message is from user land.
6575 	 */
6576 
6577 	/* map satype to proto */
6578 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6579 		ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
6580 		return key_senderror(so, m, EINVAL);
6581 	}
6582 
6583 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6584 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6585 	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6586 		/* error */
6587 		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
6588 		return key_senderror(so, m, EINVAL);
6589 	}
6590 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6591 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6592 	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6593 		/* error */
6594 		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
6595 		return key_senderror(so, m, EINVAL);
6596 	}
6597 
6598 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6599 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6600 
6601 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
6602 				     dst0 + 1, &saidx)) != 0)
6603 		return key_senderror(so, m, EINVAL);
6604 
6605 #ifdef IPSEC_NAT_T
6606 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
6607 		return key_senderror(so, m, EINVAL);
6608 #endif
6609 
6610 	/* get a SA index */
6611 	LIST_FOREACH(sah, &sahtree, chain) {
6612 		if (sah->state == SADB_SASTATE_DEAD)
6613 			continue;
6614 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6615 			break;
6616 	}
6617 	if (sah != NULL) {
6618 		ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
6619 		return key_senderror(so, m, EEXIST);
6620 	}
6621 
6622 	error = key_acquire(&saidx, NULL);
6623 	if (error != 0) {
6624 		ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
6625 			"from key_acquire.\n", mhp->msg->sadb_msg_errno));
6626 		return key_senderror(so, m, error);
6627 	}
6628 
6629 	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6630 }
6631 
6632 /*
6633  * SADB_REGISTER processing.
6634  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6635  * receive
6636  *   <base>
6637  * from the ikmpd, and register a socket to send PF_KEY messages,
6638  * and send
6639  *   <base, supported>
6640  * to KMD by PF_KEY.
6641  * If socket is detached, must free from regnode.
6642  *
6643  * m will always be freed.
6644  */
6645 static int
6646 key_register(struct socket *so, struct mbuf *m,
6647 	     const struct sadb_msghdr *mhp)
6648 {
6649 	struct secreg *reg, *newreg = 0;
6650 
6651 	/* sanity check */
6652 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6653 		panic("key_register: NULL pointer is passed");
6654 
6655 	/* check for invalid register message */
6656 	if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
6657 		return key_senderror(so, m, EINVAL);
6658 
6659 	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6660 	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6661 		goto setmsg;
6662 
6663 	/* check whether existing or not */
6664 	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
6665 		if (reg->so == so) {
6666 			ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
6667 			return key_senderror(so, m, EEXIST);
6668 		}
6669 	}
6670 
6671 	/* create regnode */
6672 	KMALLOC(newreg, struct secreg *, sizeof(*newreg));
6673 	if (newreg == NULL) {
6674 		ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
6675 		return key_senderror(so, m, ENOBUFS);
6676 	}
6677 	memset(newreg, 0, sizeof(*newreg));
6678 
6679 	newreg->so = so;
6680 	((struct keycb *)sotorawcb(so))->kp_registered++;
6681 
6682 	/* add regnode to regtree. */
6683 	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6684 
6685   setmsg:
6686     {
6687 	struct mbuf *n;
6688 	struct sadb_msg *newmsg;
6689 	struct sadb_supported *sup;
6690 	u_int len, alen, elen;
6691 	int off;
6692 	int i;
6693 	struct sadb_alg *alg;
6694 
6695 	/* create new sadb_msg to reply. */
6696 	alen = 0;
6697 	for (i = 1; i <= SADB_AALG_MAX; i++) {
6698 		if (ah_algorithm_lookup(i))
6699 			alen += sizeof(struct sadb_alg);
6700 	}
6701 	if (alen)
6702 		alen += sizeof(struct sadb_supported);
6703 	elen = 0;
6704 	for (i = 1; i <= SADB_EALG_MAX; i++) {
6705 		if (esp_algorithm_lookup(i))
6706 			elen += sizeof(struct sadb_alg);
6707 	}
6708 	if (elen)
6709 		elen += sizeof(struct sadb_supported);
6710 
6711 	len = sizeof(struct sadb_msg) + alen + elen;
6712 
6713 	if (len > MCLBYTES)
6714 		return key_senderror(so, m, ENOBUFS);
6715 
6716 	MGETHDR(n, M_DONTWAIT, MT_DATA);
6717 	if (len > MHLEN) {
6718 		MCLGET(n, M_DONTWAIT);
6719 		if ((n->m_flags & M_EXT) == 0) {
6720 			m_freem(n);
6721 			n = NULL;
6722 		}
6723 	}
6724 	if (!n)
6725 		return key_senderror(so, m, ENOBUFS);
6726 
6727 	n->m_pkthdr.len = n->m_len = len;
6728 	n->m_next = NULL;
6729 	off = 0;
6730 
6731 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
6732 	newmsg = mtod(n, struct sadb_msg *);
6733 	newmsg->sadb_msg_errno = 0;
6734 	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6735 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6736 
6737 	/* for authentication algorithm */
6738 	if (alen) {
6739 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
6740 		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6741 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6742 		off += PFKEY_ALIGN8(sizeof(*sup));
6743 
6744 		for (i = 1; i <= SADB_AALG_MAX; i++) {
6745 			const struct auth_hash *aalgo;
6746 			u_int16_t minkeysize, maxkeysize;
6747 
6748 			aalgo = ah_algorithm_lookup(i);
6749 			if (!aalgo)
6750 				continue;
6751 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
6752 			alg->sadb_alg_id = i;
6753 			alg->sadb_alg_ivlen = 0;
6754 			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6755 			alg->sadb_alg_minbits = _BITS(minkeysize);
6756 			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6757 			off += PFKEY_ALIGN8(sizeof(*alg));
6758 		}
6759 	}
6760 
6761 	/* for encryption algorithm */
6762 	if (elen) {
6763 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
6764 		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6765 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6766 		off += PFKEY_ALIGN8(sizeof(*sup));
6767 
6768 		for (i = 1; i <= SADB_EALG_MAX; i++) {
6769 			const struct enc_xform *ealgo;
6770 
6771 			ealgo = esp_algorithm_lookup(i);
6772 			if (!ealgo)
6773 				continue;
6774 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
6775 			alg->sadb_alg_id = i;
6776 			alg->sadb_alg_ivlen = ealgo->blocksize;
6777 			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6778 			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6779 			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6780 		}
6781 	}
6782 
6783 #ifdef DIAGNOSTIC
6784 	if (off != len)
6785 		panic("length assumption failed in key_register");
6786 #endif
6787 
6788 	m_freem(m);
6789 	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6790     }
6791 }
6792 
6793 /*
6794  * free secreg entry registered.
6795  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6796  */
6797 void
6798 key_freereg(struct socket *so)
6799 {
6800 	struct secreg *reg;
6801 	int i;
6802 
6803 	/* sanity check */
6804 	if (so == NULL)
6805 		panic("key_freereg: NULL pointer is passed");
6806 
6807 	/*
6808 	 * check whether existing or not.
6809 	 * check all type of SA, because there is a potential that
6810 	 * one socket is registered to multiple type of SA.
6811 	 */
6812 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6813 		LIST_FOREACH(reg, &regtree[i], chain) {
6814 			if (reg->so == so
6815 			 && __LIST_CHAINED(reg)) {
6816 				LIST_REMOVE(reg, chain);
6817 				KFREE(reg);
6818 				break;
6819 			}
6820 		}
6821 	}
6822 
6823 	return;
6824 }
6825 
6826 /*
6827  * SADB_EXPIRE processing
6828  * send
6829  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6830  * to KMD by PF_KEY.
6831  * NOTE: We send only soft lifetime extension.
6832  *
6833  * OUT:	0	: succeed
6834  *	others	: error number
6835  */
6836 static int
6837 key_expire(struct secasvar *sav)
6838 {
6839 	int s;
6840 	int satype;
6841 	struct mbuf *result = NULL, *m;
6842 	int len;
6843 	int error = -1;
6844 	struct sadb_lifetime *lt;
6845 
6846 	/* XXX: Why do we lock ? */
6847 	s = splsoftnet();	/*called from softclock()*/
6848 
6849 	/* sanity check */
6850 	if (sav == NULL)
6851 		panic("key_expire: NULL pointer is passed");
6852 	if (sav->sah == NULL)
6853 		panic("key_expire: Why was SA index in SA NULL");
6854 	if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
6855 		panic("key_expire: invalid proto is passed");
6856 
6857 	/* set msg header */
6858 	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6859 	if (!m) {
6860 		error = ENOBUFS;
6861 		goto fail;
6862 	}
6863 	result = m;
6864 
6865 	/* create SA extension */
6866 	m = key_setsadbsa(sav);
6867 	if (!m) {
6868 		error = ENOBUFS;
6869 		goto fail;
6870 	}
6871 	m_cat(result, m);
6872 
6873 	/* create SA extension */
6874 	m = key_setsadbxsa2(sav->sah->saidx.mode,
6875 			sav->replay ? sav->replay->count : 0,
6876 			sav->sah->saidx.reqid);
6877 	if (!m) {
6878 		error = ENOBUFS;
6879 		goto fail;
6880 	}
6881 	m_cat(result, m);
6882 
6883 	/* create lifetime extension (current and soft) */
6884 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6885 	m = key_alloc_mbuf(len);
6886 	if (!m || m->m_next) {	/*XXX*/
6887 		if (m)
6888 			m_freem(m);
6889 		error = ENOBUFS;
6890 		goto fail;
6891 	}
6892 	memset(mtod(m, void *), 0, len);
6893 	lt = mtod(m, struct sadb_lifetime *);
6894 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6895 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6896 	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6897 	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6898 	lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime
6899 		+ time_second - time_uptime;
6900 	lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime
6901 		+ time_second - time_uptime;
6902 	lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
6903 	memcpy(lt, sav->lft_s, sizeof(*lt));
6904 	m_cat(result, m);
6905 
6906 	/* set sadb_address for source */
6907 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6908 	    &sav->sah->saidx.src.sa,
6909 	    FULLMASK, IPSEC_ULPROTO_ANY);
6910 	if (!m) {
6911 		error = ENOBUFS;
6912 		goto fail;
6913 	}
6914 	m_cat(result, m);
6915 
6916 	/* set sadb_address for destination */
6917 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6918 	    &sav->sah->saidx.dst.sa,
6919 	    FULLMASK, IPSEC_ULPROTO_ANY);
6920 	if (!m) {
6921 		error = ENOBUFS;
6922 		goto fail;
6923 	}
6924 	m_cat(result, m);
6925 
6926 	if ((result->m_flags & M_PKTHDR) == 0) {
6927 		error = EINVAL;
6928 		goto fail;
6929 	}
6930 
6931 	if (result->m_len < sizeof(struct sadb_msg)) {
6932 		result = m_pullup(result, sizeof(struct sadb_msg));
6933 		if (result == NULL) {
6934 			error = ENOBUFS;
6935 			goto fail;
6936 		}
6937 	}
6938 
6939 	result->m_pkthdr.len = 0;
6940 	for (m = result; m; m = m->m_next)
6941 		result->m_pkthdr.len += m->m_len;
6942 
6943 	mtod(result, struct sadb_msg *)->sadb_msg_len =
6944 	    PFKEY_UNIT64(result->m_pkthdr.len);
6945 
6946 	splx(s);
6947 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6948 
6949  fail:
6950 	if (result)
6951 		m_freem(result);
6952 	splx(s);
6953 	return error;
6954 }
6955 
6956 /*
6957  * SADB_FLUSH processing
6958  * receive
6959  *   <base>
6960  * from the ikmpd, and free all entries in secastree.
6961  * and send,
6962  *   <base>
6963  * to the ikmpd.
6964  * NOTE: to do is only marking SADB_SASTATE_DEAD.
6965  *
6966  * m will always be freed.
6967  */
6968 static int
6969 key_flush(struct socket *so, struct mbuf *m,
6970           const struct sadb_msghdr *mhp)
6971 {
6972 	struct sadb_msg *newmsg;
6973 	struct secashead *sah, *nextsah;
6974 	struct secasvar *sav, *nextsav;
6975 	u_int16_t proto;
6976 	u_int8_t state;
6977 	u_int stateidx;
6978 
6979 	/* sanity check */
6980 	if (so == NULL || mhp == NULL || mhp->msg == NULL)
6981 		panic("key_flush: NULL pointer is passed");
6982 
6983 	/* map satype to proto */
6984 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6985 		ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
6986 		return key_senderror(so, m, EINVAL);
6987 	}
6988 
6989 	/* no SATYPE specified, i.e. flushing all SA. */
6990 	for (sah = LIST_FIRST(&sahtree);
6991 	     sah != NULL;
6992 	     sah = nextsah) {
6993 		nextsah = LIST_NEXT(sah, chain);
6994 
6995 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6996 		 && proto != sah->saidx.proto)
6997 			continue;
6998 
6999 		for (stateidx = 0;
7000 		     stateidx < _ARRAYLEN(saorder_state_alive);
7001 		     stateidx++) {
7002 			state = saorder_state_any[stateidx];
7003 			for (sav = LIST_FIRST(&sah->savtree[state]);
7004 			     sav != NULL;
7005 			     sav = nextsav) {
7006 
7007 				nextsav = LIST_NEXT(sav, chain);
7008 
7009 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7010 				KEY_FREESAV(&sav);
7011 			}
7012 		}
7013 
7014 		sah->state = SADB_SASTATE_DEAD;
7015 	}
7016 
7017 	if (m->m_len < sizeof(struct sadb_msg) ||
7018 	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7019 		ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
7020 		return key_senderror(so, m, ENOBUFS);
7021 	}
7022 
7023 	if (m->m_next)
7024 		m_freem(m->m_next);
7025 	m->m_next = NULL;
7026 	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7027 	newmsg = mtod(m, struct sadb_msg *);
7028 	newmsg->sadb_msg_errno = 0;
7029 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7030 
7031 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7032 }
7033 
7034 
7035 static struct mbuf *
7036 key_setdump_chain(u_int8_t req_satype, int *errorp, int *lenp, pid_t pid)
7037 {
7038 	struct secashead *sah;
7039 	struct secasvar *sav;
7040 	u_int16_t proto;
7041 	u_int stateidx;
7042 	u_int8_t satype;
7043 	u_int8_t state;
7044 	int cnt;
7045 	struct mbuf *m, *n, *prev;
7046 	int totlen;
7047 
7048 	*lenp = 0;
7049 
7050 	/* map satype to proto */
7051 	if ((proto = key_satype2proto(req_satype)) == 0) {
7052 		*errorp = EINVAL;
7053 		return (NULL);
7054 	}
7055 
7056 	/* count sav entries to be sent to userland. */
7057 	cnt = 0;
7058 	LIST_FOREACH(sah, &sahtree, chain) {
7059 		if (req_satype != SADB_SATYPE_UNSPEC &&
7060 		    proto != sah->saidx.proto)
7061 			continue;
7062 
7063 		for (stateidx = 0;
7064 		     stateidx < _ARRAYLEN(saorder_state_any);
7065 		     stateidx++) {
7066 			state = saorder_state_any[stateidx];
7067 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7068 				cnt++;
7069 			}
7070 		}
7071 	}
7072 
7073 	if (cnt == 0) {
7074 		*errorp = ENOENT;
7075 		return (NULL);
7076 	}
7077 
7078 	/* send this to the userland, one at a time. */
7079 	m = NULL;
7080 	prev = m;
7081 	LIST_FOREACH(sah, &sahtree, chain) {
7082 		if (req_satype != SADB_SATYPE_UNSPEC &&
7083 		    proto != sah->saidx.proto)
7084 			continue;
7085 
7086 		/* map proto to satype */
7087 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7088 			m_freem(m);
7089 			*errorp = EINVAL;
7090 			return (NULL);
7091 		}
7092 
7093 		for (stateidx = 0;
7094 		     stateidx < _ARRAYLEN(saorder_state_any);
7095 		     stateidx++) {
7096 			state = saorder_state_any[stateidx];
7097 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7098 				n = key_setdumpsa(sav, SADB_DUMP, satype,
7099 				    --cnt, pid);
7100 				if (!n) {
7101 					m_freem(m);
7102 					*errorp = ENOBUFS;
7103 					return (NULL);
7104 				}
7105 
7106 				totlen += n->m_pkthdr.len;
7107 				if (!m)
7108 					m = n;
7109 				else
7110 					prev->m_nextpkt = n;
7111 				prev = n;
7112 			}
7113 		}
7114 	}
7115 
7116 	if (!m) {
7117 		*errorp = EINVAL;
7118 		return (NULL);
7119 	}
7120 
7121 	if ((m->m_flags & M_PKTHDR) != 0) {
7122 		m->m_pkthdr.len = 0;
7123 		for (n = m; n; n = n->m_next)
7124 			m->m_pkthdr.len += n->m_len;
7125 	}
7126 
7127 	*errorp = 0;
7128 	return (m);
7129 }
7130 
7131 /*
7132  * SADB_DUMP processing
7133  * dump all entries including status of DEAD in SAD.
7134  * receive
7135  *   <base>
7136  * from the ikmpd, and dump all secasvar leaves
7137  * and send,
7138  *   <base> .....
7139  * to the ikmpd.
7140  *
7141  * m will always be freed.
7142  */
7143 static int
7144 key_dump(struct socket *so, struct mbuf *m0,
7145 	 const struct sadb_msghdr *mhp)
7146 {
7147 	u_int16_t proto;
7148 	u_int8_t satype;
7149 	struct mbuf *n;
7150 	int s;
7151 	int error, len, ok;
7152 
7153 	/* sanity check */
7154 	if (so == NULL || m0 == NULL || mhp == NULL || mhp->msg == NULL)
7155 		panic("key_dump: NULL pointer is passed");
7156 
7157 	/* map satype to proto */
7158 	satype = mhp->msg->sadb_msg_satype;
7159 	if ((proto = key_satype2proto(satype)) == 0) {
7160 		ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
7161 		return key_senderror(so, m0, EINVAL);
7162 	}
7163 
7164 	/*
7165 	 * If the requestor has insufficient socket-buffer space
7166 	 * for the entire chain, nobody gets any response to the DUMP.
7167 	 * XXX For now, only the requestor ever gets anything.
7168 	 * Moreover, if the requestor has any space at all, they receive
7169 	 * the entire chain, otherwise the request is refused with ENOBUFS.
7170 	 */
7171 	if (sbspace(&so->so_rcv) <= 0) {
7172 		return key_senderror(so, m0, ENOBUFS);
7173 	}
7174 
7175 	s = splsoftnet();
7176 	n = key_setdump_chain(satype, &error, &len, mhp->msg->sadb_msg_pid);
7177 	splx(s);
7178 
7179 	if (n == NULL) {
7180 		return key_senderror(so, m0, ENOENT);
7181 	}
7182 	{
7183 		uint64_t *ps = PFKEY_STAT_GETREF();
7184 		ps[PFKEY_STAT_IN_TOTAL]++;
7185 		ps[PFKEY_STAT_IN_BYTES] += len;
7186 		PFKEY_STAT_PUTREF();
7187 	}
7188 
7189 	/*
7190 	 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
7191 	 * The requestor receives either the entire chain, or an
7192 	 * error message with ENOBUFS.
7193 	 *
7194 	 * sbappendaddrchain() takes the chain of entries, one
7195 	 * packet-record per SPD entry, prepends the key_src sockaddr
7196 	 * to each packet-record, links the sockaddr mbufs into a new
7197 	 * list of records, then   appends the entire resulting
7198 	 * list to the requesting socket.
7199 	 */
7200 	ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src,
7201 	        n, SB_PRIO_ONESHOT_OVERFLOW);
7202 
7203 	if (!ok) {
7204 		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
7205 		m_freem(n);
7206 		return key_senderror(so, m0, ENOBUFS);
7207 	}
7208 
7209 	m_freem(m0);
7210 	return 0;
7211 }
7212 
7213 /*
7214  * SADB_X_PROMISC processing
7215  *
7216  * m will always be freed.
7217  */
7218 static int
7219 key_promisc(struct socket *so, struct mbuf *m,
7220 	    const struct sadb_msghdr *mhp)
7221 {
7222 	int olen;
7223 
7224 	/* sanity check */
7225 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
7226 		panic("key_promisc: NULL pointer is passed");
7227 
7228 	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7229 
7230 	if (olen < sizeof(struct sadb_msg)) {
7231 #if 1
7232 		return key_senderror(so, m, EINVAL);
7233 #else
7234 		m_freem(m);
7235 		return 0;
7236 #endif
7237 	} else if (olen == sizeof(struct sadb_msg)) {
7238 		/* enable/disable promisc mode */
7239 		struct keycb *kp;
7240 
7241 		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7242 			return key_senderror(so, m, EINVAL);
7243 		mhp->msg->sadb_msg_errno = 0;
7244 		switch (mhp->msg->sadb_msg_satype) {
7245 		case 0:
7246 		case 1:
7247 			kp->kp_promisc = mhp->msg->sadb_msg_satype;
7248 			break;
7249 		default:
7250 			return key_senderror(so, m, EINVAL);
7251 		}
7252 
7253 		/* send the original message back to everyone */
7254 		mhp->msg->sadb_msg_errno = 0;
7255 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7256 	} else {
7257 		/* send packet as is */
7258 
7259 		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7260 
7261 		/* TODO: if sadb_msg_seq is specified, send to specific pid */
7262 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7263 	}
7264 }
7265 
7266 static int (*key_typesw[]) (struct socket *, struct mbuf *,
7267 		const struct sadb_msghdr *) = {
7268 	NULL,		/* SADB_RESERVED */
7269 	key_getspi,	/* SADB_GETSPI */
7270 	key_update,	/* SADB_UPDATE */
7271 	key_add,	/* SADB_ADD */
7272 	key_delete,	/* SADB_DELETE */
7273 	key_get,	/* SADB_GET */
7274 	key_acquire2,	/* SADB_ACQUIRE */
7275 	key_register,	/* SADB_REGISTER */
7276 	NULL,		/* SADB_EXPIRE */
7277 	key_flush,	/* SADB_FLUSH */
7278 	key_dump,	/* SADB_DUMP */
7279 	key_promisc,	/* SADB_X_PROMISC */
7280 	NULL,		/* SADB_X_PCHANGE */
7281 	key_spdadd,	/* SADB_X_SPDUPDATE */
7282 	key_spdadd,	/* SADB_X_SPDADD */
7283 	key_spddelete,	/* SADB_X_SPDDELETE */
7284 	key_spdget,	/* SADB_X_SPDGET */
7285 	NULL,		/* SADB_X_SPDACQUIRE */
7286 	key_spddump,	/* SADB_X_SPDDUMP */
7287 	key_spdflush,	/* SADB_X_SPDFLUSH */
7288 	key_spdadd,	/* SADB_X_SPDSETIDX */
7289 	NULL,		/* SADB_X_SPDEXPIRE */
7290 	key_spddelete2,	/* SADB_X_SPDDELETE2 */
7291 #ifdef IPSEC_NAT_T
7292        key_nat_map,	/* SADB_X_NAT_T_NEW_MAPPING */
7293 #endif
7294 };
7295 
7296 /*
7297  * parse sadb_msg buffer to process PFKEYv2,
7298  * and create a data to response if needed.
7299  * I think to be dealed with mbuf directly.
7300  * IN:
7301  *     msgp  : pointer to pointer to a received buffer pulluped.
7302  *             This is rewrited to response.
7303  *     so    : pointer to socket.
7304  * OUT:
7305  *    length for buffer to send to user process.
7306  */
7307 int
7308 key_parse(struct mbuf *m, struct socket *so)
7309 {
7310 	struct sadb_msg *msg;
7311 	struct sadb_msghdr mh;
7312 	u_int orglen;
7313 	int error;
7314 	int target;
7315 
7316 	/* sanity check */
7317 	if (m == NULL || so == NULL)
7318 		panic("key_parse: NULL pointer is passed");
7319 
7320 #if 0	/*kdebug_sadb assumes msg in linear buffer*/
7321 	KEYDEBUG(KEYDEBUG_KEY_DUMP,
7322 		ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
7323 		kdebug_sadb(msg));
7324 #endif
7325 
7326 	if (m->m_len < sizeof(struct sadb_msg)) {
7327 		m = m_pullup(m, sizeof(struct sadb_msg));
7328 		if (!m)
7329 			return ENOBUFS;
7330 	}
7331 	msg = mtod(m, struct sadb_msg *);
7332 	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7333 	target = KEY_SENDUP_ONE;
7334 
7335 	if ((m->m_flags & M_PKTHDR) == 0 ||
7336 	    m->m_pkthdr.len != m->m_pkthdr.len) {
7337 		ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
7338 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
7339 		error = EINVAL;
7340 		goto senderror;
7341 	}
7342 
7343 	if (msg->sadb_msg_version != PF_KEY_V2) {
7344 		ipseclog((LOG_DEBUG,
7345 		    "key_parse: PF_KEY version %u is mismatched.\n",
7346 		    msg->sadb_msg_version));
7347 		PFKEY_STATINC(PFKEY_STAT_OUT_INVVER);
7348 		error = EINVAL;
7349 		goto senderror;
7350 	}
7351 
7352 	if (msg->sadb_msg_type > SADB_MAX) {
7353 		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
7354 		    msg->sadb_msg_type));
7355 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
7356 		error = EINVAL;
7357 		goto senderror;
7358 	}
7359 
7360 	/* for old-fashioned code - should be nuked */
7361 	if (m->m_pkthdr.len > MCLBYTES) {
7362 		m_freem(m);
7363 		return ENOBUFS;
7364 	}
7365 	if (m->m_next) {
7366 		struct mbuf *n;
7367 
7368 		MGETHDR(n, M_DONTWAIT, MT_DATA);
7369 		if (n && m->m_pkthdr.len > MHLEN) {
7370 			MCLGET(n, M_DONTWAIT);
7371 			if ((n->m_flags & M_EXT) == 0) {
7372 				m_free(n);
7373 				n = NULL;
7374 			}
7375 		}
7376 		if (!n) {
7377 			m_freem(m);
7378 			return ENOBUFS;
7379 		}
7380 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, void *));
7381 		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7382 		n->m_next = NULL;
7383 		m_freem(m);
7384 		m = n;
7385 	}
7386 
7387 	/* align the mbuf chain so that extensions are in contiguous region. */
7388 	error = key_align(m, &mh);
7389 	if (error)
7390 		return error;
7391 
7392 	if (m->m_next) {	/*XXX*/
7393 		m_freem(m);
7394 		return ENOBUFS;
7395 	}
7396 
7397 	msg = mh.msg;
7398 
7399 	/* check SA type */
7400 	switch (msg->sadb_msg_satype) {
7401 	case SADB_SATYPE_UNSPEC:
7402 		switch (msg->sadb_msg_type) {
7403 		case SADB_GETSPI:
7404 		case SADB_UPDATE:
7405 		case SADB_ADD:
7406 		case SADB_DELETE:
7407 		case SADB_GET:
7408 		case SADB_ACQUIRE:
7409 		case SADB_EXPIRE:
7410 			ipseclog((LOG_DEBUG, "key_parse: must specify satype "
7411 			    "when msg type=%u.\n", msg->sadb_msg_type));
7412 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7413 			error = EINVAL;
7414 			goto senderror;
7415 		}
7416 		break;
7417 	case SADB_SATYPE_AH:
7418 	case SADB_SATYPE_ESP:
7419 	case SADB_X_SATYPE_IPCOMP:
7420 	case SADB_X_SATYPE_TCPSIGNATURE:
7421 		switch (msg->sadb_msg_type) {
7422 		case SADB_X_SPDADD:
7423 		case SADB_X_SPDDELETE:
7424 		case SADB_X_SPDGET:
7425 		case SADB_X_SPDDUMP:
7426 		case SADB_X_SPDFLUSH:
7427 		case SADB_X_SPDSETIDX:
7428 		case SADB_X_SPDUPDATE:
7429 		case SADB_X_SPDDELETE2:
7430 			ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
7431 			    msg->sadb_msg_type));
7432 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7433 			error = EINVAL;
7434 			goto senderror;
7435 		}
7436 		break;
7437 	case SADB_SATYPE_RSVP:
7438 	case SADB_SATYPE_OSPFV2:
7439 	case SADB_SATYPE_RIPV2:
7440 	case SADB_SATYPE_MIP:
7441 		ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
7442 		    msg->sadb_msg_satype));
7443 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7444 		error = EOPNOTSUPP;
7445 		goto senderror;
7446 	case 1:	/* XXX: What does it do? */
7447 		if (msg->sadb_msg_type == SADB_X_PROMISC)
7448 			break;
7449 		/*FALLTHROUGH*/
7450 	default:
7451 		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
7452 		    msg->sadb_msg_satype));
7453 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7454 		error = EINVAL;
7455 		goto senderror;
7456 	}
7457 
7458 	/* check field of upper layer protocol and address family */
7459 	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7460 	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7461 		struct sadb_address *src0, *dst0;
7462 		u_int plen;
7463 
7464 		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7465 		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7466 
7467 		/* check upper layer protocol */
7468 		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7469 			ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
7470 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7471 			error = EINVAL;
7472 			goto senderror;
7473 		}
7474 
7475 		/* check family */
7476 		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7477 		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
7478 			ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
7479 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7480 			error = EINVAL;
7481 			goto senderror;
7482 		}
7483 		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7484 		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
7485 			ipseclog((LOG_DEBUG,
7486 			    "key_parse: address struct size mismatched.\n"));
7487 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7488 			error = EINVAL;
7489 			goto senderror;
7490 		}
7491 
7492 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7493 		case AF_INET:
7494 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7495 			    sizeof(struct sockaddr_in)) {
7496 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7497 				error = EINVAL;
7498 				goto senderror;
7499 			}
7500 			break;
7501 		case AF_INET6:
7502 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7503 			    sizeof(struct sockaddr_in6)) {
7504 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7505 				error = EINVAL;
7506 				goto senderror;
7507 			}
7508 			break;
7509 		default:
7510 			ipseclog((LOG_DEBUG,
7511 			    "key_parse: unsupported address family.\n"));
7512 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7513 			error = EAFNOSUPPORT;
7514 			goto senderror;
7515 		}
7516 
7517 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7518 		case AF_INET:
7519 			plen = sizeof(struct in_addr) << 3;
7520 			break;
7521 		case AF_INET6:
7522 			plen = sizeof(struct in6_addr) << 3;
7523 			break;
7524 		default:
7525 			plen = 0;	/*fool gcc*/
7526 			break;
7527 		}
7528 
7529 		/* check max prefix length */
7530 		if (src0->sadb_address_prefixlen > plen ||
7531 		    dst0->sadb_address_prefixlen > plen) {
7532 			ipseclog((LOG_DEBUG,
7533 			    "key_parse: illegal prefixlen.\n"));
7534 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7535 			error = EINVAL;
7536 			goto senderror;
7537 		}
7538 
7539 		/*
7540 		 * prefixlen == 0 is valid because there can be a case when
7541 		 * all addresses are matched.
7542 		 */
7543 	}
7544 
7545 	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7546 	    key_typesw[msg->sadb_msg_type] == NULL) {
7547 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
7548 		error = EINVAL;
7549 		goto senderror;
7550 	}
7551 
7552 	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7553 
7554 senderror:
7555 	msg->sadb_msg_errno = error;
7556 	return key_sendup_mbuf(so, m, target);
7557 }
7558 
7559 static int
7560 key_senderror(struct socket *so, struct mbuf *m, int code)
7561 {
7562 	struct sadb_msg *msg;
7563 
7564 	if (m->m_len < sizeof(struct sadb_msg))
7565 		panic("invalid mbuf passed to key_senderror");
7566 
7567 	msg = mtod(m, struct sadb_msg *);
7568 	msg->sadb_msg_errno = code;
7569 	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7570 }
7571 
7572 /*
7573  * set the pointer to each header into message buffer.
7574  * m will be freed on error.
7575  * XXX larger-than-MCLBYTES extension?
7576  */
7577 static int
7578 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
7579 {
7580 	struct mbuf *n;
7581 	struct sadb_ext *ext;
7582 	size_t off, end;
7583 	int extlen;
7584 	int toff;
7585 
7586 	/* sanity check */
7587 	if (m == NULL || mhp == NULL)
7588 		panic("key_align: NULL pointer is passed");
7589 	if (m->m_len < sizeof(struct sadb_msg))
7590 		panic("invalid mbuf passed to key_align");
7591 
7592 	/* initialize */
7593 	memset(mhp, 0, sizeof(*mhp));
7594 
7595 	mhp->msg = mtod(m, struct sadb_msg *);
7596 	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7597 
7598 	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7599 	extlen = end;	/*just in case extlen is not updated*/
7600 	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7601 		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7602 		if (!n) {
7603 			/* m is already freed */
7604 			return ENOBUFS;
7605 		}
7606 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
7607 
7608 		/* set pointer */
7609 		switch (ext->sadb_ext_type) {
7610 		case SADB_EXT_SA:
7611 		case SADB_EXT_ADDRESS_SRC:
7612 		case SADB_EXT_ADDRESS_DST:
7613 		case SADB_EXT_ADDRESS_PROXY:
7614 		case SADB_EXT_LIFETIME_CURRENT:
7615 		case SADB_EXT_LIFETIME_HARD:
7616 		case SADB_EXT_LIFETIME_SOFT:
7617 		case SADB_EXT_KEY_AUTH:
7618 		case SADB_EXT_KEY_ENCRYPT:
7619 		case SADB_EXT_IDENTITY_SRC:
7620 		case SADB_EXT_IDENTITY_DST:
7621 		case SADB_EXT_SENSITIVITY:
7622 		case SADB_EXT_PROPOSAL:
7623 		case SADB_EXT_SUPPORTED_AUTH:
7624 		case SADB_EXT_SUPPORTED_ENCRYPT:
7625 		case SADB_EXT_SPIRANGE:
7626 		case SADB_X_EXT_POLICY:
7627 		case SADB_X_EXT_SA2:
7628 #ifdef IPSEC_NAT_T
7629 		case SADB_X_EXT_NAT_T_TYPE:
7630 		case SADB_X_EXT_NAT_T_SPORT:
7631 		case SADB_X_EXT_NAT_T_DPORT:
7632 		case SADB_X_EXT_NAT_T_OAI:
7633 		case SADB_X_EXT_NAT_T_OAR:
7634 		case SADB_X_EXT_NAT_T_FRAG:
7635 #endif
7636 			/* duplicate check */
7637 			/*
7638 			 * XXX Are there duplication payloads of either
7639 			 * KEY_AUTH or KEY_ENCRYPT ?
7640 			 */
7641 			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7642 				ipseclog((LOG_DEBUG,
7643 				    "key_align: duplicate ext_type %u "
7644 				    "is passed.\n", ext->sadb_ext_type));
7645 				m_freem(m);
7646 				PFKEY_STATINC(PFKEY_STAT_OUT_DUPEXT);
7647 				return EINVAL;
7648 			}
7649 			break;
7650 		default:
7651 			ipseclog((LOG_DEBUG,
7652 			    "key_align: invalid ext_type %u is passed.\n",
7653 			    ext->sadb_ext_type));
7654 			m_freem(m);
7655 			PFKEY_STATINC(PFKEY_STAT_OUT_INVEXTTYPE);
7656 			return EINVAL;
7657 		}
7658 
7659 		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7660 
7661 		if (key_validate_ext(ext, extlen)) {
7662 			m_freem(m);
7663 			PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
7664 			return EINVAL;
7665 		}
7666 
7667 		n = m_pulldown(m, off, extlen, &toff);
7668 		if (!n) {
7669 			/* m is already freed */
7670 			return ENOBUFS;
7671 		}
7672 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
7673 
7674 		mhp->ext[ext->sadb_ext_type] = ext;
7675 		mhp->extoff[ext->sadb_ext_type] = off;
7676 		mhp->extlen[ext->sadb_ext_type] = extlen;
7677 	}
7678 
7679 	if (off != end) {
7680 		m_freem(m);
7681 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
7682 		return EINVAL;
7683 	}
7684 
7685 	return 0;
7686 }
7687 
7688 static int
7689 key_validate_ext(const struct sadb_ext *ext, int len)
7690 {
7691 	const struct sockaddr *sa;
7692 	enum { NONE, ADDR } checktype = NONE;
7693 	int baselen = 0;
7694 	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7695 
7696 	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7697 		return EINVAL;
7698 
7699 	/* if it does not match minimum/maximum length, bail */
7700 	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7701 	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7702 		return EINVAL;
7703 	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7704 		return EINVAL;
7705 	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7706 		return EINVAL;
7707 
7708 	/* more checks based on sadb_ext_type XXX need more */
7709 	switch (ext->sadb_ext_type) {
7710 	case SADB_EXT_ADDRESS_SRC:
7711 	case SADB_EXT_ADDRESS_DST:
7712 	case SADB_EXT_ADDRESS_PROXY:
7713 		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7714 		checktype = ADDR;
7715 		break;
7716 	case SADB_EXT_IDENTITY_SRC:
7717 	case SADB_EXT_IDENTITY_DST:
7718 		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7719 		    SADB_X_IDENTTYPE_ADDR) {
7720 			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7721 			checktype = ADDR;
7722 		} else
7723 			checktype = NONE;
7724 		break;
7725 	default:
7726 		checktype = NONE;
7727 		break;
7728 	}
7729 
7730 	switch (checktype) {
7731 	case NONE:
7732 		break;
7733 	case ADDR:
7734 		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7735 		if (len < baselen + sal)
7736 			return EINVAL;
7737 		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7738 			return EINVAL;
7739 		break;
7740 	}
7741 
7742 	return 0;
7743 }
7744 
7745 static int
7746 key_do_init(void)
7747 {
7748 	int i;
7749 
7750 	pfkeystat_percpu = percpu_alloc(sizeof(uint64_t) * PFKEY_NSTATS);
7751 
7752 	callout_init(&key_timehandler_ch, 0);
7753 
7754 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7755 		LIST_INIT(&sptree[i]);
7756 	}
7757 
7758 	LIST_INIT(&sahtree);
7759 
7760 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7761 		LIST_INIT(&regtree[i]);
7762 	}
7763 
7764 #ifndef IPSEC_NONBLOCK_ACQUIRE
7765 	LIST_INIT(&acqtree);
7766 #endif
7767 	LIST_INIT(&spacqtree);
7768 
7769 	/* system default */
7770 	ip4_def_policy.policy = IPSEC_POLICY_NONE;
7771 	ip4_def_policy.refcnt++;	/*never reclaim this*/
7772 
7773 #ifdef INET6
7774 	ip6_def_policy.policy = IPSEC_POLICY_NONE;
7775 	ip6_def_policy.refcnt++;	/*never reclaim this*/
7776 #endif
7777 
7778 
7779 #ifndef IPSEC_DEBUG2
7780 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
7781 #endif /*IPSEC_DEBUG2*/
7782 
7783 	/* initialize key statistics */
7784 	keystat.getspi_count = 1;
7785 
7786 	aprint_verbose("IPsec: Initialized Security Association Processing.\n");
7787 
7788 	return (0);
7789 }
7790 
7791 void
7792 key_init(void)
7793 {
7794 	static ONCE_DECL(key_init_once);
7795 
7796 	RUN_ONCE(&key_init_once, key_do_init);
7797 }
7798 
7799 /*
7800  * XXX: maybe This function is called after INBOUND IPsec processing.
7801  *
7802  * Special check for tunnel-mode packets.
7803  * We must make some checks for consistency between inner and outer IP header.
7804  *
7805  * xxx more checks to be provided
7806  */
7807 int
7808 key_checktunnelsanity(
7809     struct secasvar *sav,
7810     u_int family,
7811     void *src,
7812     void *dst
7813 )
7814 {
7815 	/* sanity check */
7816 	if (sav->sah == NULL)
7817 		panic("sav->sah == NULL at key_checktunnelsanity");
7818 
7819 	/* XXX: check inner IP header */
7820 
7821 	return 1;
7822 }
7823 
7824 #if 0
7825 #define hostnamelen	strlen(hostname)
7826 
7827 /*
7828  * Get FQDN for the host.
7829  * If the administrator configured hostname (by hostname(1)) without
7830  * domain name, returns nothing.
7831  */
7832 static const char *
7833 key_getfqdn(void)
7834 {
7835 	int i;
7836 	int hasdot;
7837 	static char fqdn[MAXHOSTNAMELEN + 1];
7838 
7839 	if (!hostnamelen)
7840 		return NULL;
7841 
7842 	/* check if it comes with domain name. */
7843 	hasdot = 0;
7844 	for (i = 0; i < hostnamelen; i++) {
7845 		if (hostname[i] == '.')
7846 			hasdot++;
7847 	}
7848 	if (!hasdot)
7849 		return NULL;
7850 
7851 	/* NOTE: hostname may not be NUL-terminated. */
7852 	memset(fqdn, 0, sizeof(fqdn));
7853 	memcpy(fqdn, hostname, hostnamelen);
7854 	fqdn[hostnamelen] = '\0';
7855 	return fqdn;
7856 }
7857 
7858 /*
7859  * get username@FQDN for the host/user.
7860  */
7861 static const char *
7862 key_getuserfqdn(void)
7863 {
7864 	const char *host;
7865 	static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
7866 	struct proc *p = curproc;
7867 	char *q;
7868 
7869 	if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
7870 		return NULL;
7871 	if (!(host = key_getfqdn()))
7872 		return NULL;
7873 
7874 	/* NOTE: s_login may not be-NUL terminated. */
7875 	memset(userfqdn, 0, sizeof(userfqdn));
7876 	memcpy(userfqdn, Mp->p_pgrp->pg_session->s_login, AXLOGNAME);
7877 	userfqdn[MAXLOGNAME] = '\0';	/* safeguard */
7878 	q = userfqdn + strlen(userfqdn);
7879 	*q++ = '@';
7880 	memcpy(q, host, strlen(host));
7881 	q += strlen(host);
7882 	*q++ = '\0';
7883 
7884 	return userfqdn;
7885 }
7886 #endif
7887 
7888 /* record data transfer on SA, and update timestamps */
7889 void
7890 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
7891 {
7892 	IPSEC_ASSERT(sav != NULL, ("key_sa_recordxfer: Null secasvar"));
7893 	IPSEC_ASSERT(m != NULL, ("key_sa_recordxfer: Null mbuf"));
7894 	if (!sav->lft_c)
7895 		return;
7896 
7897 	/*
7898 	 * XXX Currently, there is a difference of bytes size
7899 	 * between inbound and outbound processing.
7900 	 */
7901 	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
7902 	/* to check bytes lifetime is done in key_timehandler(). */
7903 
7904 	/*
7905 	 * We use the number of packets as the unit of
7906 	 * sadb_lifetime_allocations.  We increment the variable
7907 	 * whenever {esp,ah}_{in,out}put is called.
7908 	 */
7909 	sav->lft_c->sadb_lifetime_allocations++;
7910 	/* XXX check for expires? */
7911 
7912 	/*
7913 	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
7914 	 * in seconds.  HARD and SOFT lifetime are measured by the time
7915 	 * difference (again in seconds) from sadb_lifetime_usetime.
7916 	 *
7917 	 *	usetime
7918 	 *	v     expire   expire
7919 	 * -----+-----+--------+---> t
7920 	 *	<--------------> HARD
7921 	 *	<-----> SOFT
7922 	 */
7923 	sav->lft_c->sadb_lifetime_usetime = time_uptime;
7924 	/* XXX check for expires? */
7925 
7926 	return;
7927 }
7928 
7929 /* dumb version */
7930 void
7931 key_sa_routechange(struct sockaddr *dst)
7932 {
7933 	struct secashead *sah;
7934 	struct route *ro;
7935 	const struct sockaddr *sa;
7936 
7937 	LIST_FOREACH(sah, &sahtree, chain) {
7938 		ro = &sah->sa_route;
7939 		sa = rtcache_getdst(ro);
7940 		if (sa != NULL && dst->sa_len == sa->sa_len &&
7941 		    memcmp(dst, sa, dst->sa_len) == 0)
7942 			rtcache_free(ro);
7943 	}
7944 
7945 	return;
7946 }
7947 
7948 static void
7949 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7950 {
7951 	if (sav == NULL)
7952 		panic("key_sa_chgstate called with sav == NULL");
7953 
7954 	if (sav->state == state)
7955 		return;
7956 
7957 	if (__LIST_CHAINED(sav))
7958 		LIST_REMOVE(sav, chain);
7959 
7960 	sav->state = state;
7961 	LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7962 }
7963 
7964 /* XXX too much? */
7965 static struct mbuf *
7966 key_alloc_mbuf(int l)
7967 {
7968 	struct mbuf *m = NULL, *n;
7969 	int len, t;
7970 
7971 	len = l;
7972 	while (len > 0) {
7973 		MGET(n, M_DONTWAIT, MT_DATA);
7974 		if (n && len > MLEN)
7975 			MCLGET(n, M_DONTWAIT);
7976 		if (!n) {
7977 			m_freem(m);
7978 			return NULL;
7979 		}
7980 
7981 		n->m_next = NULL;
7982 		n->m_len = 0;
7983 		n->m_len = M_TRAILINGSPACE(n);
7984 		/* use the bottom of mbuf, hoping we can prepend afterwards */
7985 		if (n->m_len > len) {
7986 			t = (n->m_len - len) & ~(sizeof(long) - 1);
7987 			n->m_data += t;
7988 			n->m_len = len;
7989 		}
7990 
7991 		len -= n->m_len;
7992 
7993 		if (m)
7994 			m_cat(m, n);
7995 		else
7996 			m = n;
7997 	}
7998 
7999 	return m;
8000 }
8001 
8002 static struct mbuf *
8003 key_setdump(u_int8_t req_satype, int *errorp, uint32_t pid)
8004 {
8005 	struct secashead *sah;
8006 	struct secasvar *sav;
8007 	u_int16_t proto;
8008 	u_int stateidx;
8009 	u_int8_t satype;
8010 	u_int8_t state;
8011 	int cnt;
8012 	struct mbuf *m, *n;
8013 
8014 	/* map satype to proto */
8015 	if ((proto = key_satype2proto(req_satype)) == 0) {
8016 		*errorp = EINVAL;
8017 		return (NULL);
8018 	}
8019 
8020 	/* count sav entries to be sent to the userland. */
8021 	cnt = 0;
8022 	LIST_FOREACH(sah, &sahtree, chain) {
8023 		if (req_satype != SADB_SATYPE_UNSPEC &&
8024 		    proto != sah->saidx.proto)
8025 			continue;
8026 
8027 		for (stateidx = 0;
8028 		     stateidx < _ARRAYLEN(saorder_state_any);
8029 		     stateidx++) {
8030 			state = saorder_state_any[stateidx];
8031 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
8032 				cnt++;
8033 			}
8034 		}
8035 	}
8036 
8037 	if (cnt == 0) {
8038 		*errorp = ENOENT;
8039 		return (NULL);
8040 	}
8041 
8042 	/* send this to the userland, one at a time. */
8043 	m = NULL;
8044 	LIST_FOREACH(sah, &sahtree, chain) {
8045 		if (req_satype != SADB_SATYPE_UNSPEC &&
8046 		    proto != sah->saidx.proto)
8047 			continue;
8048 
8049 		/* map proto to satype */
8050 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
8051 			m_freem(m);
8052 			*errorp = EINVAL;
8053 			return (NULL);
8054 		}
8055 
8056 		for (stateidx = 0;
8057 		     stateidx < _ARRAYLEN(saorder_state_any);
8058 		     stateidx++) {
8059 			state = saorder_state_any[stateidx];
8060 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
8061 				n = key_setdumpsa(sav, SADB_DUMP, satype,
8062 				    --cnt, pid);
8063 				if (!n) {
8064 					m_freem(m);
8065 					*errorp = ENOBUFS;
8066 					return (NULL);
8067 				}
8068 
8069 				if (!m)
8070 					m = n;
8071 				else
8072 					m_cat(m, n);
8073 			}
8074 		}
8075 	}
8076 
8077 	if (!m) {
8078 		*errorp = EINVAL;
8079 		return (NULL);
8080 	}
8081 
8082 	if ((m->m_flags & M_PKTHDR) != 0) {
8083 		m->m_pkthdr.len = 0;
8084 		for (n = m; n; n = n->m_next)
8085 			m->m_pkthdr.len += n->m_len;
8086 	}
8087 
8088 	*errorp = 0;
8089 	return (m);
8090 }
8091 
8092 static struct mbuf *
8093 key_setspddump(int *errorp, pid_t pid)
8094 {
8095 	struct secpolicy *sp;
8096 	int cnt;
8097 	u_int dir;
8098 	struct mbuf *m, *n;
8099 
8100 	/* search SPD entry and get buffer size. */
8101 	cnt = 0;
8102 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
8103 		LIST_FOREACH(sp, &sptree[dir], chain) {
8104 			cnt++;
8105 		}
8106 	}
8107 
8108 	if (cnt == 0) {
8109 		*errorp = ENOENT;
8110 		return (NULL);
8111 	}
8112 
8113 	m = NULL;
8114 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
8115 		LIST_FOREACH(sp, &sptree[dir], chain) {
8116 			--cnt;
8117 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
8118 
8119 			if (!n) {
8120 				*errorp = ENOBUFS;
8121 				m_freem(m);
8122 				return (NULL);
8123 			}
8124 			if (!m)
8125 				m = n;
8126 			else {
8127 				m->m_pkthdr.len += n->m_pkthdr.len;
8128 				m_cat(m, n);
8129 			}
8130 		}
8131 	}
8132 
8133 	*errorp = 0;
8134 	return (m);
8135 }
8136 
8137 static int
8138 sysctl_net_key_dumpsa(SYSCTLFN_ARGS)
8139 {
8140 	struct mbuf *m, *n;
8141 	int err2 = 0;
8142 	char *p, *ep;
8143 	size_t len;
8144 	int s, error;
8145 
8146 	if (newp)
8147 		return (EPERM);
8148 	if (namelen != 1)
8149 		return (EINVAL);
8150 
8151 	s = splsoftnet();
8152 	m = key_setdump(name[0], &error, l->l_proc->p_pid);
8153 	splx(s);
8154 	if (!m)
8155 		return (error);
8156 	if (!oldp)
8157 		*oldlenp = m->m_pkthdr.len;
8158 	else {
8159 		p = oldp;
8160 		if (*oldlenp < m->m_pkthdr.len) {
8161 			err2 = ENOMEM;
8162 			ep = p + *oldlenp;
8163 		} else {
8164 			*oldlenp = m->m_pkthdr.len;
8165 			ep = p + m->m_pkthdr.len;
8166 		}
8167 		for (n = m; n; n = n->m_next) {
8168 			len =  (ep - p < n->m_len) ?
8169 				ep - p : n->m_len;
8170 			error = copyout(mtod(n, const void *), p, len);
8171 			p += len;
8172 			if (error)
8173 				break;
8174 		}
8175 		if (error == 0)
8176 			error = err2;
8177 	}
8178 	m_freem(m);
8179 
8180 	return (error);
8181 }
8182 
8183 static int
8184 sysctl_net_key_dumpsp(SYSCTLFN_ARGS)
8185 {
8186 	struct mbuf *m, *n;
8187 	int err2 = 0;
8188 	char *p, *ep;
8189 	size_t len;
8190 	int s, error;
8191 
8192 	if (newp)
8193 		return (EPERM);
8194 	if (namelen != 0)
8195 		return (EINVAL);
8196 
8197 	s = splsoftnet();
8198 	m = key_setspddump(&error, l->l_proc->p_pid);
8199 	splx(s);
8200 	if (!m)
8201 		return (error);
8202 	if (!oldp)
8203 		*oldlenp = m->m_pkthdr.len;
8204 	else {
8205 		p = oldp;
8206 		if (*oldlenp < m->m_pkthdr.len) {
8207 			err2 = ENOMEM;
8208 			ep = p + *oldlenp;
8209 		} else {
8210 			*oldlenp = m->m_pkthdr.len;
8211 			ep = p + m->m_pkthdr.len;
8212 		}
8213 		for (n = m; n; n = n->m_next) {
8214 			len =  (ep - p < n->m_len) ?
8215 				ep - p : n->m_len;
8216 			error = copyout(mtod(n, const void *), p, len);
8217 			p += len;
8218 			if (error)
8219 				break;
8220 		}
8221 		if (error == 0)
8222 			error = err2;
8223 	}
8224 	m_freem(m);
8225 
8226 	return (error);
8227 }
8228 
8229 /*
8230  * Create sysctl tree for native FAST_IPSEC key knobs, originally
8231  * under name "net.keyv2"  * with MIB number { CTL_NET, PF_KEY_V2. }.
8232  * However, sysctl(8) never checked for nodes under { CTL_NET, PF_KEY_V2 };
8233  * and in any case the part of our sysctl namespace used for dumping the
8234  * SPD and SA database  *HAS* to be compatible with the KAME sysctl
8235  * namespace, for API reasons.
8236  *
8237  * Pending a consensus on the right way  to fix this, add a level of
8238  * indirection in how we number the `native' FAST_IPSEC key nodes;
8239  * and (as requested by Andrew Brown)  move registration of the
8240  * KAME-compatible names  to a separate function.
8241  */
8242 #if 0
8243 #  define FAST_IPSEC_PFKEY PF_KEY_V2
8244 # define FAST_IPSEC_PFKEY_NAME "keyv2"
8245 #else
8246 #  define FAST_IPSEC_PFKEY PF_KEY
8247 # define FAST_IPSEC_PFKEY_NAME "key"
8248 #endif
8249 
8250 static int
8251 sysctl_net_key_stats(SYSCTLFN_ARGS)
8252 {
8253 
8254 	return (NETSTAT_SYSCTL(pfkeystat_percpu, PFKEY_NSTATS));
8255 }
8256 
8257 SYSCTL_SETUP(sysctl_net_keyv2_setup, "sysctl net.keyv2 subtree setup")
8258 {
8259 
8260 	sysctl_createv(clog, 0, NULL, NULL,
8261 		       CTLFLAG_PERMANENT,
8262 		       CTLTYPE_NODE, "net", NULL,
8263 		       NULL, 0, NULL, 0,
8264 		       CTL_NET, CTL_EOL);
8265 	sysctl_createv(clog, 0, NULL, NULL,
8266 		       CTLFLAG_PERMANENT,
8267 		       CTLTYPE_NODE, FAST_IPSEC_PFKEY_NAME, NULL,
8268 		       NULL, 0, NULL, 0,
8269 		       CTL_NET, FAST_IPSEC_PFKEY, CTL_EOL);
8270 
8271 	sysctl_createv(clog, 0, NULL, NULL,
8272 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8273 		       CTLTYPE_INT, "debug", NULL,
8274 		       NULL, 0, &key_debug_level, 0,
8275 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_DEBUG_LEVEL, CTL_EOL);
8276 	sysctl_createv(clog, 0, NULL, NULL,
8277 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8278 		       CTLTYPE_INT, "spi_try", NULL,
8279 		       NULL, 0, &key_spi_trycnt, 0,
8280 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_TRY, CTL_EOL);
8281 	sysctl_createv(clog, 0, NULL, NULL,
8282 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8283 		       CTLTYPE_INT, "spi_min_value", NULL,
8284 		       NULL, 0, &key_spi_minval, 0,
8285 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_MIN_VALUE, CTL_EOL);
8286 	sysctl_createv(clog, 0, NULL, NULL,
8287 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8288 		       CTLTYPE_INT, "spi_max_value", NULL,
8289 		       NULL, 0, &key_spi_maxval, 0,
8290 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_MAX_VALUE, CTL_EOL);
8291 	sysctl_createv(clog, 0, NULL, NULL,
8292 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8293 		       CTLTYPE_INT, "random_int", NULL,
8294 		       NULL, 0, &key_int_random, 0,
8295 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_RANDOM_INT, CTL_EOL);
8296 	sysctl_createv(clog, 0, NULL, NULL,
8297 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8298 		       CTLTYPE_INT, "larval_lifetime", NULL,
8299 		       NULL, 0, &key_larval_lifetime, 0,
8300 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_LARVAL_LIFETIME, CTL_EOL);
8301 	sysctl_createv(clog, 0, NULL, NULL,
8302 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8303 		       CTLTYPE_INT, "blockacq_count", NULL,
8304 		       NULL, 0, &key_blockacq_count, 0,
8305 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_BLOCKACQ_COUNT, CTL_EOL);
8306 	sysctl_createv(clog, 0, NULL, NULL,
8307 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8308 		       CTLTYPE_INT, "blockacq_lifetime", NULL,
8309 		       NULL, 0, &key_blockacq_lifetime, 0,
8310 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_BLOCKACQ_LIFETIME, CTL_EOL);
8311 	sysctl_createv(clog, 0, NULL, NULL,
8312 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8313 		       CTLTYPE_INT, "esp_keymin", NULL,
8314 		       NULL, 0, &ipsec_esp_keymin, 0,
8315 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_ESP_KEYMIN, CTL_EOL);
8316 	sysctl_createv(clog, 0, NULL, NULL,
8317 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8318 		       CTLTYPE_INT, "prefered_oldsa", NULL,
8319 		       NULL, 0, &key_prefered_oldsa, 0,
8320 		       CTL_NET, PF_KEY, KEYCTL_PREFERED_OLDSA, CTL_EOL);
8321 	sysctl_createv(clog, 0, NULL, NULL,
8322 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8323 		       CTLTYPE_INT, "esp_auth", NULL,
8324 		       NULL, 0, &ipsec_esp_auth, 0,
8325 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_ESP_AUTH, CTL_EOL);
8326 	sysctl_createv(clog, 0, NULL, NULL,
8327 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8328 		       CTLTYPE_INT, "ah_keymin", NULL,
8329 		       NULL, 0, &ipsec_ah_keymin, 0,
8330 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_AH_KEYMIN, CTL_EOL);
8331 	sysctl_createv(clog, 0, NULL, NULL,
8332 		       CTLFLAG_PERMANENT,
8333 		       CTLTYPE_STRUCT, "stats",
8334 		       SYSCTL_DESCR("PF_KEY statistics"),
8335 		       sysctl_net_key_stats, 0, NULL, 0,
8336 		       CTL_NET, FAST_IPSEC_PFKEY, CTL_CREATE, CTL_EOL);
8337 }
8338 
8339 /*
8340  * Register sysctl names used by setkey(8). For historical reasons,
8341  * and to share a single API, these names appear under { CTL_NET, PF_KEY }
8342  * for both FAST_IPSEC and KAME IPSEC.
8343  */
8344 SYSCTL_SETUP(sysctl_net_key_compat_setup, "sysctl net.key subtree setup for FAST_IPSEC")
8345 {
8346 
8347 	/* Make sure net.key exists before we register nodes underneath it. */
8348 	sysctl_createv(clog, 0, NULL, NULL,
8349 		       CTLFLAG_PERMANENT,
8350 		       CTLTYPE_NODE, "net", NULL,
8351 		       NULL, 0, NULL, 0,
8352 		       CTL_NET, CTL_EOL);
8353 	sysctl_createv(clog, 0, NULL, NULL,
8354 		       CTLFLAG_PERMANENT,
8355 		       CTLTYPE_NODE, "key", NULL,
8356 		       NULL, 0, NULL, 0,
8357 		       CTL_NET, PF_KEY, CTL_EOL);
8358 
8359 	/* Register the net.key.dump{sa,sp} nodes used by setkey(8). */
8360 	sysctl_createv(clog, 0, NULL, NULL,
8361 		       CTLFLAG_PERMANENT,
8362 		       CTLTYPE_STRUCT, "dumpsa", NULL,
8363 		       sysctl_net_key_dumpsa, 0, NULL, 0,
8364 		       CTL_NET, PF_KEY, KEYCTL_DUMPSA, CTL_EOL);
8365 	sysctl_createv(clog, 0, NULL, NULL,
8366 		       CTLFLAG_PERMANENT,
8367 		       CTLTYPE_STRUCT, "dumpsp", NULL,
8368 		       sysctl_net_key_dumpsp, 0, NULL, 0,
8369 		       CTL_NET, PF_KEY, KEYCTL_DUMPSP, CTL_EOL);
8370 }
8371