xref: /netbsd-src/sys/netipsec/key.c (revision ba65fde2d7fefa7d39838fa5fa855e62bd606b5e)
1 /*	$NetBSD: key.c,v 1.79 2012/09/20 23:50:05 gdt 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.79 2012/09/20 23:50:05 gdt 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 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
5917 				     dst0 + 1, &saidx)) != 0)
5918 		return key_senderror(so, m, EINVAL);
5919 
5920 #ifdef IPSEC_NAT_T
5921 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
5922 		return key_senderror(so, m, EINVAL);
5923 #endif
5924 
5925 	/* get a SA header */
5926 	LIST_FOREACH(sah, &sahtree, chain) {
5927 		if (sah->state == SADB_SASTATE_DEAD)
5928 			continue;
5929 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5930 			continue;
5931 
5932 		/* get a SA with SPI. */
5933 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5934 		if (sav)
5935 			break;
5936 	}
5937 	if (sah == NULL) {
5938 		ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
5939 		return key_senderror(so, m, ENOENT);
5940 	}
5941 
5942     {
5943 	struct mbuf *n;
5944 	u_int8_t satype;
5945 
5946 	/* map proto to satype */
5947 	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5948 		ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
5949 		return key_senderror(so, m, EINVAL);
5950 	}
5951 
5952 	/* create new sadb_msg to reply. */
5953 	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5954 	    mhp->msg->sadb_msg_pid);
5955 	if (!n)
5956 		return key_senderror(so, m, ENOBUFS);
5957 
5958 	m_freem(m);
5959 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5960     }
5961 }
5962 
5963 /* XXX make it sysctl-configurable? */
5964 static void
5965 key_getcomb_setlifetime(struct sadb_comb *comb)
5966 {
5967 
5968 	comb->sadb_comb_soft_allocations = 1;
5969 	comb->sadb_comb_hard_allocations = 1;
5970 	comb->sadb_comb_soft_bytes = 0;
5971 	comb->sadb_comb_hard_bytes = 0;
5972 	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5973 	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5974 	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5975 	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5976 }
5977 
5978 /*
5979  * XXX reorder combinations by preference
5980  * XXX no idea if the user wants ESP authentication or not
5981  */
5982 static struct mbuf *
5983 key_getcomb_esp(void)
5984 {
5985 	struct sadb_comb *comb;
5986 	const struct enc_xform *algo;
5987 	struct mbuf *result = NULL, *m, *n;
5988 	int encmin;
5989 	int i, off, o;
5990 	int totlen;
5991 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5992 
5993 	m = NULL;
5994 	for (i = 1; i <= SADB_EALG_MAX; i++) {
5995 		algo = esp_algorithm_lookup(i);
5996 		if (algo == NULL)
5997 			continue;
5998 
5999 		/* discard algorithms with key size smaller than system min */
6000 		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
6001 			continue;
6002 		if (_BITS(algo->minkey) < ipsec_esp_keymin)
6003 			encmin = ipsec_esp_keymin;
6004 		else
6005 			encmin = _BITS(algo->minkey);
6006 
6007 		if (ipsec_esp_auth)
6008 			m = key_getcomb_ah();
6009 		else {
6010 			IPSEC_ASSERT(l <= MLEN,
6011 				("key_getcomb_esp: l=%u > MLEN=%lu",
6012 				l, (u_long) MLEN));
6013 			MGET(m, M_DONTWAIT, MT_DATA);
6014 			if (m) {
6015 				M_ALIGN(m, l);
6016 				m->m_len = l;
6017 				m->m_next = NULL;
6018 				memset(mtod(m, void *), 0, m->m_len);
6019 			}
6020 		}
6021 		if (!m)
6022 			goto fail;
6023 
6024 		totlen = 0;
6025 		for (n = m; n; n = n->m_next)
6026 			totlen += n->m_len;
6027 		IPSEC_ASSERT((totlen % l) == 0,
6028 			("key_getcomb_esp: totlen=%u, l=%u", totlen, l));
6029 
6030 		for (off = 0; off < totlen; off += l) {
6031 			n = m_pulldown(m, off, l, &o);
6032 			if (!n) {
6033 				/* m is already freed */
6034 				goto fail;
6035 			}
6036 			comb = (struct sadb_comb *)(mtod(n, char *) + o);
6037 			memset(comb, 0, sizeof(*comb));
6038 			key_getcomb_setlifetime(comb);
6039 			comb->sadb_comb_encrypt = i;
6040 			comb->sadb_comb_encrypt_minbits = encmin;
6041 			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6042 		}
6043 
6044 		if (!result)
6045 			result = m;
6046 		else
6047 			m_cat(result, m);
6048 	}
6049 
6050 	return result;
6051 
6052  fail:
6053 	if (result)
6054 		m_freem(result);
6055 	return NULL;
6056 }
6057 
6058 static void
6059 key_getsizes_ah(const struct auth_hash *ah, int alg,
6060 	        u_int16_t* ksmin, u_int16_t* ksmax)
6061 {
6062 	*ksmin = *ksmax = ah->keysize;
6063 	if (ah->keysize == 0) {
6064 		/*
6065 		 * Transform takes arbitrary key size but algorithm
6066 		 * key size is restricted.  Enforce this here.
6067 		 */
6068 		switch (alg) {
6069 		case SADB_X_AALG_MD5:	*ksmin = *ksmax = 16; break;
6070 		case SADB_X_AALG_SHA:	*ksmin = *ksmax = 20; break;
6071 		case SADB_X_AALG_NULL:	*ksmin = 1; *ksmax = 256; break;
6072 		default:
6073 			DPRINTF(("key_getsizes_ah: unknown AH algorithm %u\n",
6074 				alg));
6075 			break;
6076 		}
6077 	}
6078 }
6079 
6080 /*
6081  * XXX reorder combinations by preference
6082  */
6083 static struct mbuf *
6084 key_getcomb_ah(void)
6085 {
6086 	struct sadb_comb *comb;
6087 	const struct auth_hash *algo;
6088 	struct mbuf *m;
6089 	u_int16_t minkeysize, maxkeysize;
6090 	int i;
6091 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6092 
6093 	m = NULL;
6094 	for (i = 1; i <= SADB_AALG_MAX; i++) {
6095 #if 1
6096 		/* we prefer HMAC algorithms, not old algorithms */
6097 		if (i != SADB_AALG_SHA1HMAC &&
6098 		    i != SADB_AALG_MD5HMAC &&
6099 		    i != SADB_X_AALG_SHA2_256 &&
6100 		    i != SADB_X_AALG_SHA2_384 &&
6101 		    i != SADB_X_AALG_SHA2_512)
6102 			continue;
6103 #endif
6104 		algo = ah_algorithm_lookup(i);
6105 		if (!algo)
6106 			continue;
6107 		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6108 		/* discard algorithms with key size smaller than system min */
6109 		if (_BITS(minkeysize) < ipsec_ah_keymin)
6110 			continue;
6111 
6112 		if (!m) {
6113 			IPSEC_ASSERT(l <= MLEN,
6114 				("key_getcomb_ah: l=%u > MLEN=%lu",
6115 				l, (u_long) MLEN));
6116 			MGET(m, M_DONTWAIT, MT_DATA);
6117 			if (m) {
6118 				M_ALIGN(m, l);
6119 				m->m_len = l;
6120 				m->m_next = NULL;
6121 			}
6122 		} else
6123 			M_PREPEND(m, l, M_DONTWAIT);
6124 		if (!m)
6125 			return NULL;
6126 
6127 		comb = mtod(m, struct sadb_comb *);
6128 		memset(comb, 0, sizeof(*comb));
6129 		key_getcomb_setlifetime(comb);
6130 		comb->sadb_comb_auth = i;
6131 		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6132 		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6133 	}
6134 
6135 	return m;
6136 }
6137 
6138 /*
6139  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6140  * XXX reorder combinations by preference
6141  */
6142 static struct mbuf *
6143 key_getcomb_ipcomp(void)
6144 {
6145 	struct sadb_comb *comb;
6146 	const struct comp_algo *algo;
6147 	struct mbuf *m;
6148 	int i;
6149 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6150 
6151 	m = NULL;
6152 	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6153 		algo = ipcomp_algorithm_lookup(i);
6154 		if (!algo)
6155 			continue;
6156 
6157 		if (!m) {
6158 			IPSEC_ASSERT(l <= MLEN,
6159 				("key_getcomb_ipcomp: l=%u > MLEN=%lu",
6160 				l, (u_long) MLEN));
6161 			MGET(m, M_DONTWAIT, MT_DATA);
6162 			if (m) {
6163 				M_ALIGN(m, l);
6164 				m->m_len = l;
6165 				m->m_next = NULL;
6166 			}
6167 		} else
6168 			M_PREPEND(m, l, M_DONTWAIT);
6169 		if (!m)
6170 			return NULL;
6171 
6172 		comb = mtod(m, struct sadb_comb *);
6173 		memset(comb, 0, sizeof(*comb));
6174 		key_getcomb_setlifetime(comb);
6175 		comb->sadb_comb_encrypt = i;
6176 		/* what should we set into sadb_comb_*_{min,max}bits? */
6177 	}
6178 
6179 	return m;
6180 }
6181 
6182 /*
6183  * XXX no way to pass mode (transport/tunnel) to userland
6184  * XXX replay checking?
6185  * XXX sysctl interface to ipsec_{ah,esp}_keymin
6186  */
6187 static struct mbuf *
6188 key_getprop(const struct secasindex *saidx)
6189 {
6190 	struct sadb_prop *prop;
6191 	struct mbuf *m, *n;
6192 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6193 	int totlen;
6194 
6195 	switch (saidx->proto)  {
6196 	case IPPROTO_ESP:
6197 		m = key_getcomb_esp();
6198 		break;
6199 	case IPPROTO_AH:
6200 		m = key_getcomb_ah();
6201 		break;
6202 	case IPPROTO_IPCOMP:
6203 		m = key_getcomb_ipcomp();
6204 		break;
6205 	default:
6206 		return NULL;
6207 	}
6208 
6209 	if (!m)
6210 		return NULL;
6211 	M_PREPEND(m, l, M_DONTWAIT);
6212 	if (!m)
6213 		return NULL;
6214 
6215 	totlen = 0;
6216 	for (n = m; n; n = n->m_next)
6217 		totlen += n->m_len;
6218 
6219 	prop = mtod(m, struct sadb_prop *);
6220 	memset(prop, 0, sizeof(*prop));
6221 	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6222 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6223 	prop->sadb_prop_replay = 32;	/* XXX */
6224 
6225 	return m;
6226 }
6227 
6228 /*
6229  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6230  * send
6231  *   <base, SA, address(SD), (address(P)), x_policy,
6232  *       (identity(SD),) (sensitivity,) proposal>
6233  * to KMD, and expect to receive
6234  *   <base> with SADB_ACQUIRE if error occurred,
6235  * or
6236  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6237  * from KMD by PF_KEY.
6238  *
6239  * XXX x_policy is outside of RFC2367 (KAME extension).
6240  * XXX sensitivity is not supported.
6241  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6242  * see comment for key_getcomb_ipcomp().
6243  *
6244  * OUT:
6245  *    0     : succeed
6246  *    others: error number
6247  */
6248 static int
6249 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6250 {
6251 	struct mbuf *result = NULL, *m;
6252 #ifndef IPSEC_NONBLOCK_ACQUIRE
6253 	struct secacq *newacq;
6254 #endif
6255 	u_int8_t satype;
6256 	int error = -1;
6257 	u_int32_t seq;
6258 
6259 	/* sanity check */
6260 	IPSEC_ASSERT(saidx != NULL, ("key_acquire: null saidx"));
6261 	satype = key_proto2satype(saidx->proto);
6262 	IPSEC_ASSERT(satype != 0,
6263 		("key_acquire: null satype, protocol %u", saidx->proto));
6264 
6265 #ifndef IPSEC_NONBLOCK_ACQUIRE
6266 	/*
6267 	 * We never do anything about acquirng SA.  There is anather
6268 	 * solution that kernel blocks to send SADB_ACQUIRE message until
6269 	 * getting something message from IKEd.  In later case, to be
6270 	 * managed with ACQUIRING list.
6271 	 */
6272 	/* Get an entry to check whether sending message or not. */
6273 	if ((newacq = key_getacq(saidx)) != NULL) {
6274 		if (key_blockacq_count < newacq->count) {
6275 			/* reset counter and do send message. */
6276 			newacq->count = 0;
6277 		} else {
6278 			/* increment counter and do nothing. */
6279 			newacq->count++;
6280 			return 0;
6281 		}
6282 	} else {
6283 		/* make new entry for blocking to send SADB_ACQUIRE. */
6284 		if ((newacq = key_newacq(saidx)) == NULL)
6285 			return ENOBUFS;
6286 
6287 		/* add to acqtree */
6288 		LIST_INSERT_HEAD(&acqtree, newacq, chain);
6289 	}
6290 #endif
6291 
6292 
6293 #ifndef IPSEC_NONBLOCK_ACQUIRE
6294 	seq = newacq->seq;
6295 #else
6296 	seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
6297 #endif
6298 	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6299 	if (!m) {
6300 		error = ENOBUFS;
6301 		goto fail;
6302 	}
6303 	result = m;
6304 
6305 	/* set sadb_address for saidx's. */
6306 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6307 	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6308 	if (!m) {
6309 		error = ENOBUFS;
6310 		goto fail;
6311 	}
6312 	m_cat(result, m);
6313 
6314 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6315 	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6316 	if (!m) {
6317 		error = ENOBUFS;
6318 		goto fail;
6319 	}
6320 	m_cat(result, m);
6321 
6322 	/* XXX proxy address (optional) */
6323 
6324 	/* set sadb_x_policy */
6325 	if (sp) {
6326 		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6327 		if (!m) {
6328 			error = ENOBUFS;
6329 			goto fail;
6330 		}
6331 		m_cat(result, m);
6332 	}
6333 
6334 	/* XXX identity (optional) */
6335 #if 0
6336 	if (idexttype && fqdn) {
6337 		/* create identity extension (FQDN) */
6338 		struct sadb_ident *id;
6339 		int fqdnlen;
6340 
6341 		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
6342 		id = (struct sadb_ident *)p;
6343 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6344 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6345 		id->sadb_ident_exttype = idexttype;
6346 		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6347 		memcpy(id + 1, fqdn, fqdnlen);
6348 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6349 	}
6350 
6351 	if (idexttype) {
6352 		/* create identity extension (USERFQDN) */
6353 		struct sadb_ident *id;
6354 		int userfqdnlen;
6355 
6356 		if (userfqdn) {
6357 			/* +1 for terminating-NUL */
6358 			userfqdnlen = strlen(userfqdn) + 1;
6359 		} else
6360 			userfqdnlen = 0;
6361 		id = (struct sadb_ident *)p;
6362 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6363 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6364 		id->sadb_ident_exttype = idexttype;
6365 		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6366 		/* XXX is it correct? */
6367 		if (curlwp)
6368 			id->sadb_ident_id = kauth_cred_getuid(curlwp->l_cred);
6369 		if (userfqdn && userfqdnlen)
6370 			memcpy(id + 1, userfqdn, userfqdnlen);
6371 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6372 	}
6373 #endif
6374 
6375 	/* XXX sensitivity (optional) */
6376 
6377 	/* create proposal/combination extension */
6378 	m = key_getprop(saidx);
6379 #if 0
6380 	/*
6381 	 * spec conformant: always attach proposal/combination extension,
6382 	 * the problem is that we have no way to attach it for ipcomp,
6383 	 * due to the way sadb_comb is declared in RFC2367.
6384 	 */
6385 	if (!m) {
6386 		error = ENOBUFS;
6387 		goto fail;
6388 	}
6389 	m_cat(result, m);
6390 #else
6391 	/*
6392 	 * outside of spec; make proposal/combination extension optional.
6393 	 */
6394 	if (m)
6395 		m_cat(result, m);
6396 #endif
6397 
6398 	if ((result->m_flags & M_PKTHDR) == 0) {
6399 		error = EINVAL;
6400 		goto fail;
6401 	}
6402 
6403 	if (result->m_len < sizeof(struct sadb_msg)) {
6404 		result = m_pullup(result, sizeof(struct sadb_msg));
6405 		if (result == NULL) {
6406 			error = ENOBUFS;
6407 			goto fail;
6408 		}
6409 	}
6410 
6411 	result->m_pkthdr.len = 0;
6412 	for (m = result; m; m = m->m_next)
6413 		result->m_pkthdr.len += m->m_len;
6414 
6415 	mtod(result, struct sadb_msg *)->sadb_msg_len =
6416 	    PFKEY_UNIT64(result->m_pkthdr.len);
6417 
6418 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6419 
6420  fail:
6421 	if (result)
6422 		m_freem(result);
6423 	return error;
6424 }
6425 
6426 #ifndef IPSEC_NONBLOCK_ACQUIRE
6427 static struct secacq *
6428 key_newacq(const struct secasindex *saidx)
6429 {
6430 	struct secacq *newacq;
6431 
6432 	/* get new entry */
6433 	KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
6434 	if (newacq == NULL) {
6435 		ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
6436 		return NULL;
6437 	}
6438 	memset(newacq, 0, sizeof(*newacq));
6439 
6440 	/* copy secindex */
6441 	memcpy(&newacq->saidx, saidx, sizeof(newacq->saidx));
6442 	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
6443 	newacq->created = time_uptime;
6444 	newacq->count = 0;
6445 
6446 	return newacq;
6447 }
6448 
6449 static struct secacq *
6450 key_getacq(const struct secasindex *saidx)
6451 {
6452 	struct secacq *acq;
6453 
6454 	LIST_FOREACH(acq, &acqtree, chain) {
6455 		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6456 			return acq;
6457 	}
6458 
6459 	return NULL;
6460 }
6461 
6462 static struct secacq *
6463 key_getacqbyseq(u_int32_t seq)
6464 {
6465 	struct secacq *acq;
6466 
6467 	LIST_FOREACH(acq, &acqtree, chain) {
6468 		if (acq->seq == seq)
6469 			return acq;
6470 	}
6471 
6472 	return NULL;
6473 }
6474 #endif
6475 
6476 static struct secspacq *
6477 key_newspacq(const struct secpolicyindex *spidx)
6478 {
6479 	struct secspacq *acq;
6480 
6481 	/* get new entry */
6482 	KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
6483 	if (acq == NULL) {
6484 		ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
6485 		return NULL;
6486 	}
6487 	memset(acq, 0, sizeof(*acq));
6488 
6489 	/* copy secindex */
6490 	memcpy(&acq->spidx, spidx, sizeof(acq->spidx));
6491 	acq->created = time_uptime;
6492 	acq->count = 0;
6493 
6494 	return acq;
6495 }
6496 
6497 static struct secspacq *
6498 key_getspacq(const struct secpolicyindex *spidx)
6499 {
6500 	struct secspacq *acq;
6501 
6502 	LIST_FOREACH(acq, &spacqtree, chain) {
6503 		if (key_cmpspidx_exactly(spidx, &acq->spidx))
6504 			return acq;
6505 	}
6506 
6507 	return NULL;
6508 }
6509 
6510 /*
6511  * SADB_ACQUIRE processing,
6512  * in first situation, is receiving
6513  *   <base>
6514  * from the ikmpd, and clear sequence of its secasvar entry.
6515  *
6516  * In second situation, is receiving
6517  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6518  * from a user land process, and return
6519  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6520  * to the socket.
6521  *
6522  * m will always be freed.
6523  */
6524 static int
6525 key_acquire2(struct socket *so, struct mbuf *m,
6526       	     const struct sadb_msghdr *mhp)
6527 {
6528 	const struct sadb_address *src0, *dst0;
6529 	struct secasindex saidx;
6530 	struct secashead *sah;
6531 	u_int16_t proto;
6532 	int error;
6533 
6534 	/* sanity check */
6535 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6536 		panic("key_acquire2: NULL pointer is passed");
6537 
6538 	/*
6539 	 * Error message from KMd.
6540 	 * We assume that if error was occurred in IKEd, the length of PFKEY
6541 	 * message is equal to the size of sadb_msg structure.
6542 	 * We do not raise error even if error occurred in this function.
6543 	 */
6544 	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6545 #ifndef IPSEC_NONBLOCK_ACQUIRE
6546 		struct secacq *acq;
6547 
6548 		/* check sequence number */
6549 		if (mhp->msg->sadb_msg_seq == 0) {
6550 			ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
6551 			m_freem(m);
6552 			return 0;
6553 		}
6554 
6555 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6556 			/*
6557 			 * the specified larval SA is already gone, or we got
6558 			 * a bogus sequence number.  we can silently ignore it.
6559 			 */
6560 			m_freem(m);
6561 			return 0;
6562 		}
6563 
6564 		/* reset acq counter in order to deletion by timehander. */
6565 		acq->created = time_uptime;
6566 		acq->count = 0;
6567 #endif
6568 		m_freem(m);
6569 		return 0;
6570 	}
6571 
6572 	/*
6573 	 * This message is from user land.
6574 	 */
6575 
6576 	/* map satype to proto */
6577 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6578 		ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
6579 		return key_senderror(so, m, EINVAL);
6580 	}
6581 
6582 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6583 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6584 	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6585 		/* error */
6586 		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
6587 		return key_senderror(so, m, EINVAL);
6588 	}
6589 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6590 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6591 	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6592 		/* error */
6593 		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
6594 		return key_senderror(so, m, EINVAL);
6595 	}
6596 
6597 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6598 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6599 
6600 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
6601 				     dst0 + 1, &saidx)) != 0)
6602 		return key_senderror(so, m, EINVAL);
6603 
6604 #ifdef IPSEC_NAT_T
6605 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
6606 		return key_senderror(so, m, EINVAL);
6607 #endif
6608 
6609 	/* get a SA index */
6610 	LIST_FOREACH(sah, &sahtree, chain) {
6611 		if (sah->state == SADB_SASTATE_DEAD)
6612 			continue;
6613 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6614 			break;
6615 	}
6616 	if (sah != NULL) {
6617 		ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
6618 		return key_senderror(so, m, EEXIST);
6619 	}
6620 
6621 	error = key_acquire(&saidx, NULL);
6622 	if (error != 0) {
6623 		ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
6624 			"from key_acquire.\n", mhp->msg->sadb_msg_errno));
6625 		return key_senderror(so, m, error);
6626 	}
6627 
6628 	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6629 }
6630 
6631 /*
6632  * SADB_REGISTER processing.
6633  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6634  * receive
6635  *   <base>
6636  * from the ikmpd, and register a socket to send PF_KEY messages,
6637  * and send
6638  *   <base, supported>
6639  * to KMD by PF_KEY.
6640  * If socket is detached, must free from regnode.
6641  *
6642  * m will always be freed.
6643  */
6644 static int
6645 key_register(struct socket *so, struct mbuf *m,
6646 	     const struct sadb_msghdr *mhp)
6647 {
6648 	struct secreg *reg, *newreg = 0;
6649 
6650 	/* sanity check */
6651 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6652 		panic("key_register: NULL pointer is passed");
6653 
6654 	/* check for invalid register message */
6655 	if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
6656 		return key_senderror(so, m, EINVAL);
6657 
6658 	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6659 	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6660 		goto setmsg;
6661 
6662 	/* check whether existing or not */
6663 	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
6664 		if (reg->so == so) {
6665 			ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
6666 			return key_senderror(so, m, EEXIST);
6667 		}
6668 	}
6669 
6670 	/* create regnode */
6671 	KMALLOC(newreg, struct secreg *, sizeof(*newreg));
6672 	if (newreg == NULL) {
6673 		ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
6674 		return key_senderror(so, m, ENOBUFS);
6675 	}
6676 	memset(newreg, 0, sizeof(*newreg));
6677 
6678 	newreg->so = so;
6679 	((struct keycb *)sotorawcb(so))->kp_registered++;
6680 
6681 	/* add regnode to regtree. */
6682 	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6683 
6684   setmsg:
6685     {
6686 	struct mbuf *n;
6687 	struct sadb_msg *newmsg;
6688 	struct sadb_supported *sup;
6689 	u_int len, alen, elen;
6690 	int off;
6691 	int i;
6692 	struct sadb_alg *alg;
6693 
6694 	/* create new sadb_msg to reply. */
6695 	alen = 0;
6696 	for (i = 1; i <= SADB_AALG_MAX; i++) {
6697 		if (ah_algorithm_lookup(i))
6698 			alen += sizeof(struct sadb_alg);
6699 	}
6700 	if (alen)
6701 		alen += sizeof(struct sadb_supported);
6702 	elen = 0;
6703 	for (i = 1; i <= SADB_EALG_MAX; i++) {
6704 		if (esp_algorithm_lookup(i))
6705 			elen += sizeof(struct sadb_alg);
6706 	}
6707 	if (elen)
6708 		elen += sizeof(struct sadb_supported);
6709 
6710 	len = sizeof(struct sadb_msg) + alen + elen;
6711 
6712 	if (len > MCLBYTES)
6713 		return key_senderror(so, m, ENOBUFS);
6714 
6715 	MGETHDR(n, M_DONTWAIT, MT_DATA);
6716 	if (len > MHLEN) {
6717 		MCLGET(n, M_DONTWAIT);
6718 		if ((n->m_flags & M_EXT) == 0) {
6719 			m_freem(n);
6720 			n = NULL;
6721 		}
6722 	}
6723 	if (!n)
6724 		return key_senderror(so, m, ENOBUFS);
6725 
6726 	n->m_pkthdr.len = n->m_len = len;
6727 	n->m_next = NULL;
6728 	off = 0;
6729 
6730 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
6731 	newmsg = mtod(n, struct sadb_msg *);
6732 	newmsg->sadb_msg_errno = 0;
6733 	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6734 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6735 
6736 	/* for authentication algorithm */
6737 	if (alen) {
6738 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
6739 		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6740 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6741 		off += PFKEY_ALIGN8(sizeof(*sup));
6742 
6743 		for (i = 1; i <= SADB_AALG_MAX; i++) {
6744 			const struct auth_hash *aalgo;
6745 			u_int16_t minkeysize, maxkeysize;
6746 
6747 			aalgo = ah_algorithm_lookup(i);
6748 			if (!aalgo)
6749 				continue;
6750 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
6751 			alg->sadb_alg_id = i;
6752 			alg->sadb_alg_ivlen = 0;
6753 			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6754 			alg->sadb_alg_minbits = _BITS(minkeysize);
6755 			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6756 			off += PFKEY_ALIGN8(sizeof(*alg));
6757 		}
6758 	}
6759 
6760 	/* for encryption algorithm */
6761 	if (elen) {
6762 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
6763 		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6764 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6765 		off += PFKEY_ALIGN8(sizeof(*sup));
6766 
6767 		for (i = 1; i <= SADB_EALG_MAX; i++) {
6768 			const struct enc_xform *ealgo;
6769 
6770 			ealgo = esp_algorithm_lookup(i);
6771 			if (!ealgo)
6772 				continue;
6773 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
6774 			alg->sadb_alg_id = i;
6775 			alg->sadb_alg_ivlen = ealgo->blocksize;
6776 			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6777 			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6778 			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6779 		}
6780 	}
6781 
6782 #ifdef DIAGNOSTIC
6783 	if (off != len)
6784 		panic("length assumption failed in key_register");
6785 #endif
6786 
6787 	m_freem(m);
6788 	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6789     }
6790 }
6791 
6792 /*
6793  * free secreg entry registered.
6794  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6795  */
6796 void
6797 key_freereg(struct socket *so)
6798 {
6799 	struct secreg *reg;
6800 	int i;
6801 
6802 	/* sanity check */
6803 	if (so == NULL)
6804 		panic("key_freereg: NULL pointer is passed");
6805 
6806 	/*
6807 	 * check whether existing or not.
6808 	 * check all type of SA, because there is a potential that
6809 	 * one socket is registered to multiple type of SA.
6810 	 */
6811 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6812 		LIST_FOREACH(reg, &regtree[i], chain) {
6813 			if (reg->so == so
6814 			 && __LIST_CHAINED(reg)) {
6815 				LIST_REMOVE(reg, chain);
6816 				KFREE(reg);
6817 				break;
6818 			}
6819 		}
6820 	}
6821 
6822 	return;
6823 }
6824 
6825 /*
6826  * SADB_EXPIRE processing
6827  * send
6828  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6829  * to KMD by PF_KEY.
6830  * NOTE: We send only soft lifetime extension.
6831  *
6832  * OUT:	0	: succeed
6833  *	others	: error number
6834  */
6835 static int
6836 key_expire(struct secasvar *sav)
6837 {
6838 	int s;
6839 	int satype;
6840 	struct mbuf *result = NULL, *m;
6841 	int len;
6842 	int error = -1;
6843 	struct sadb_lifetime *lt;
6844 
6845 	/* XXX: Why do we lock ? */
6846 	s = splsoftnet();	/*called from softclock()*/
6847 
6848 	/* sanity check */
6849 	if (sav == NULL)
6850 		panic("key_expire: NULL pointer is passed");
6851 	if (sav->sah == NULL)
6852 		panic("key_expire: Why was SA index in SA NULL");
6853 	if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
6854 		panic("key_expire: invalid proto is passed");
6855 
6856 	/* set msg header */
6857 	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6858 	if (!m) {
6859 		error = ENOBUFS;
6860 		goto fail;
6861 	}
6862 	result = m;
6863 
6864 	/* create SA extension */
6865 	m = key_setsadbsa(sav);
6866 	if (!m) {
6867 		error = ENOBUFS;
6868 		goto fail;
6869 	}
6870 	m_cat(result, m);
6871 
6872 	/* create SA extension */
6873 	m = key_setsadbxsa2(sav->sah->saidx.mode,
6874 			sav->replay ? sav->replay->count : 0,
6875 			sav->sah->saidx.reqid);
6876 	if (!m) {
6877 		error = ENOBUFS;
6878 		goto fail;
6879 	}
6880 	m_cat(result, m);
6881 
6882 	/* create lifetime extension (current and soft) */
6883 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6884 	m = key_alloc_mbuf(len);
6885 	if (!m || m->m_next) {	/*XXX*/
6886 		if (m)
6887 			m_freem(m);
6888 		error = ENOBUFS;
6889 		goto fail;
6890 	}
6891 	memset(mtod(m, void *), 0, len);
6892 	lt = mtod(m, struct sadb_lifetime *);
6893 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6894 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6895 	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6896 	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6897 	lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime
6898 		+ time_second - time_uptime;
6899 	lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime
6900 		+ time_second - time_uptime;
6901 	lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
6902 	memcpy(lt, sav->lft_s, sizeof(*lt));
6903 	m_cat(result, m);
6904 
6905 	/* set sadb_address for source */
6906 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6907 	    &sav->sah->saidx.src.sa,
6908 	    FULLMASK, IPSEC_ULPROTO_ANY);
6909 	if (!m) {
6910 		error = ENOBUFS;
6911 		goto fail;
6912 	}
6913 	m_cat(result, m);
6914 
6915 	/* set sadb_address for destination */
6916 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6917 	    &sav->sah->saidx.dst.sa,
6918 	    FULLMASK, IPSEC_ULPROTO_ANY);
6919 	if (!m) {
6920 		error = ENOBUFS;
6921 		goto fail;
6922 	}
6923 	m_cat(result, m);
6924 
6925 	if ((result->m_flags & M_PKTHDR) == 0) {
6926 		error = EINVAL;
6927 		goto fail;
6928 	}
6929 
6930 	if (result->m_len < sizeof(struct sadb_msg)) {
6931 		result = m_pullup(result, sizeof(struct sadb_msg));
6932 		if (result == NULL) {
6933 			error = ENOBUFS;
6934 			goto fail;
6935 		}
6936 	}
6937 
6938 	result->m_pkthdr.len = 0;
6939 	for (m = result; m; m = m->m_next)
6940 		result->m_pkthdr.len += m->m_len;
6941 
6942 	mtod(result, struct sadb_msg *)->sadb_msg_len =
6943 	    PFKEY_UNIT64(result->m_pkthdr.len);
6944 
6945 	splx(s);
6946 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6947 
6948  fail:
6949 	if (result)
6950 		m_freem(result);
6951 	splx(s);
6952 	return error;
6953 }
6954 
6955 /*
6956  * SADB_FLUSH processing
6957  * receive
6958  *   <base>
6959  * from the ikmpd, and free all entries in secastree.
6960  * and send,
6961  *   <base>
6962  * to the ikmpd.
6963  * NOTE: to do is only marking SADB_SASTATE_DEAD.
6964  *
6965  * m will always be freed.
6966  */
6967 static int
6968 key_flush(struct socket *so, struct mbuf *m,
6969           const struct sadb_msghdr *mhp)
6970 {
6971 	struct sadb_msg *newmsg;
6972 	struct secashead *sah, *nextsah;
6973 	struct secasvar *sav, *nextsav;
6974 	u_int16_t proto;
6975 	u_int8_t state;
6976 	u_int stateidx;
6977 
6978 	/* sanity check */
6979 	if (so == NULL || mhp == NULL || mhp->msg == NULL)
6980 		panic("key_flush: NULL pointer is passed");
6981 
6982 	/* map satype to proto */
6983 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6984 		ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
6985 		return key_senderror(so, m, EINVAL);
6986 	}
6987 
6988 	/* no SATYPE specified, i.e. flushing all SA. */
6989 	for (sah = LIST_FIRST(&sahtree);
6990 	     sah != NULL;
6991 	     sah = nextsah) {
6992 		nextsah = LIST_NEXT(sah, chain);
6993 
6994 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6995 		 && proto != sah->saidx.proto)
6996 			continue;
6997 
6998 		for (stateidx = 0;
6999 		     stateidx < _ARRAYLEN(saorder_state_alive);
7000 		     stateidx++) {
7001 			state = saorder_state_any[stateidx];
7002 			for (sav = LIST_FIRST(&sah->savtree[state]);
7003 			     sav != NULL;
7004 			     sav = nextsav) {
7005 
7006 				nextsav = LIST_NEXT(sav, chain);
7007 
7008 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7009 				KEY_FREESAV(&sav);
7010 			}
7011 		}
7012 
7013 		sah->state = SADB_SASTATE_DEAD;
7014 	}
7015 
7016 	if (m->m_len < sizeof(struct sadb_msg) ||
7017 	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7018 		ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
7019 		return key_senderror(so, m, ENOBUFS);
7020 	}
7021 
7022 	if (m->m_next)
7023 		m_freem(m->m_next);
7024 	m->m_next = NULL;
7025 	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7026 	newmsg = mtod(m, struct sadb_msg *);
7027 	newmsg->sadb_msg_errno = 0;
7028 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7029 
7030 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7031 }
7032 
7033 
7034 static struct mbuf *
7035 key_setdump_chain(u_int8_t req_satype, int *errorp, int *lenp, pid_t pid)
7036 {
7037 	struct secashead *sah;
7038 	struct secasvar *sav;
7039 	u_int16_t proto;
7040 	u_int stateidx;
7041 	u_int8_t satype;
7042 	u_int8_t state;
7043 	int cnt;
7044 	struct mbuf *m, *n, *prev;
7045 	int totlen;
7046 
7047 	*lenp = 0;
7048 
7049 	/* map satype to proto */
7050 	if ((proto = key_satype2proto(req_satype)) == 0) {
7051 		*errorp = EINVAL;
7052 		return (NULL);
7053 	}
7054 
7055 	/* count sav entries to be sent to userland. */
7056 	cnt = 0;
7057 	LIST_FOREACH(sah, &sahtree, chain) {
7058 		if (req_satype != SADB_SATYPE_UNSPEC &&
7059 		    proto != sah->saidx.proto)
7060 			continue;
7061 
7062 		for (stateidx = 0;
7063 		     stateidx < _ARRAYLEN(saorder_state_any);
7064 		     stateidx++) {
7065 			state = saorder_state_any[stateidx];
7066 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7067 				cnt++;
7068 			}
7069 		}
7070 	}
7071 
7072 	if (cnt == 0) {
7073 		*errorp = ENOENT;
7074 		return (NULL);
7075 	}
7076 
7077 	/* send this to the userland, one at a time. */
7078 	m = NULL;
7079 	prev = m;
7080 	LIST_FOREACH(sah, &sahtree, chain) {
7081 		if (req_satype != SADB_SATYPE_UNSPEC &&
7082 		    proto != sah->saidx.proto)
7083 			continue;
7084 
7085 		/* map proto to satype */
7086 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7087 			m_freem(m);
7088 			*errorp = EINVAL;
7089 			return (NULL);
7090 		}
7091 
7092 		for (stateidx = 0;
7093 		     stateidx < _ARRAYLEN(saorder_state_any);
7094 		     stateidx++) {
7095 			state = saorder_state_any[stateidx];
7096 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7097 				n = key_setdumpsa(sav, SADB_DUMP, satype,
7098 				    --cnt, pid);
7099 				if (!n) {
7100 					m_freem(m);
7101 					*errorp = ENOBUFS;
7102 					return (NULL);
7103 				}
7104 
7105 				totlen += n->m_pkthdr.len;
7106 				if (!m)
7107 					m = n;
7108 				else
7109 					prev->m_nextpkt = n;
7110 				prev = n;
7111 			}
7112 		}
7113 	}
7114 
7115 	if (!m) {
7116 		*errorp = EINVAL;
7117 		return (NULL);
7118 	}
7119 
7120 	if ((m->m_flags & M_PKTHDR) != 0) {
7121 		m->m_pkthdr.len = 0;
7122 		for (n = m; n; n = n->m_next)
7123 			m->m_pkthdr.len += n->m_len;
7124 	}
7125 
7126 	*errorp = 0;
7127 	return (m);
7128 }
7129 
7130 /*
7131  * SADB_DUMP processing
7132  * dump all entries including status of DEAD in SAD.
7133  * receive
7134  *   <base>
7135  * from the ikmpd, and dump all secasvar leaves
7136  * and send,
7137  *   <base> .....
7138  * to the ikmpd.
7139  *
7140  * m will always be freed.
7141  */
7142 static int
7143 key_dump(struct socket *so, struct mbuf *m0,
7144 	 const struct sadb_msghdr *mhp)
7145 {
7146 	u_int16_t proto;
7147 	u_int8_t satype;
7148 	struct mbuf *n;
7149 	int s;
7150 	int error, len, ok;
7151 
7152 	/* sanity check */
7153 	if (so == NULL || m0 == NULL || mhp == NULL || mhp->msg == NULL)
7154 		panic("key_dump: NULL pointer is passed");
7155 
7156 	/* map satype to proto */
7157 	satype = mhp->msg->sadb_msg_satype;
7158 	if ((proto = key_satype2proto(satype)) == 0) {
7159 		ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
7160 		return key_senderror(so, m0, EINVAL);
7161 	}
7162 
7163 	/*
7164 	 * If the requestor has insufficient socket-buffer space
7165 	 * for the entire chain, nobody gets any response to the DUMP.
7166 	 * XXX For now, only the requestor ever gets anything.
7167 	 * Moreover, if the requestor has any space at all, they receive
7168 	 * the entire chain, otherwise the request is refused with ENOBUFS.
7169 	 */
7170 	if (sbspace(&so->so_rcv) <= 0) {
7171 		return key_senderror(so, m0, ENOBUFS);
7172 	}
7173 
7174 	s = splsoftnet();
7175 	n = key_setdump_chain(satype, &error, &len, mhp->msg->sadb_msg_pid);
7176 	splx(s);
7177 
7178 	if (n == NULL) {
7179 		return key_senderror(so, m0, ENOENT);
7180 	}
7181 	{
7182 		uint64_t *ps = PFKEY_STAT_GETREF();
7183 		ps[PFKEY_STAT_IN_TOTAL]++;
7184 		ps[PFKEY_STAT_IN_BYTES] += len;
7185 		PFKEY_STAT_PUTREF();
7186 	}
7187 
7188 	/*
7189 	 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
7190 	 * The requestor receives either the entire chain, or an
7191 	 * error message with ENOBUFS.
7192 	 *
7193 	 * sbappendaddrchain() takes the chain of entries, one
7194 	 * packet-record per SPD entry, prepends the key_src sockaddr
7195 	 * to each packet-record, links the sockaddr mbufs into a new
7196 	 * list of records, then   appends the entire resulting
7197 	 * list to the requesting socket.
7198 	 */
7199 	ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src,
7200 	        n, SB_PRIO_ONESHOT_OVERFLOW);
7201 
7202 	if (!ok) {
7203 		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
7204 		m_freem(n);
7205 		return key_senderror(so, m0, ENOBUFS);
7206 	}
7207 
7208 	m_freem(m0);
7209 	return 0;
7210 }
7211 
7212 /*
7213  * SADB_X_PROMISC processing
7214  *
7215  * m will always be freed.
7216  */
7217 static int
7218 key_promisc(struct socket *so, struct mbuf *m,
7219 	    const struct sadb_msghdr *mhp)
7220 {
7221 	int olen;
7222 
7223 	/* sanity check */
7224 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
7225 		panic("key_promisc: NULL pointer is passed");
7226 
7227 	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7228 
7229 	if (olen < sizeof(struct sadb_msg)) {
7230 #if 1
7231 		return key_senderror(so, m, EINVAL);
7232 #else
7233 		m_freem(m);
7234 		return 0;
7235 #endif
7236 	} else if (olen == sizeof(struct sadb_msg)) {
7237 		/* enable/disable promisc mode */
7238 		struct keycb *kp;
7239 
7240 		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7241 			return key_senderror(so, m, EINVAL);
7242 		mhp->msg->sadb_msg_errno = 0;
7243 		switch (mhp->msg->sadb_msg_satype) {
7244 		case 0:
7245 		case 1:
7246 			kp->kp_promisc = mhp->msg->sadb_msg_satype;
7247 			break;
7248 		default:
7249 			return key_senderror(so, m, EINVAL);
7250 		}
7251 
7252 		/* send the original message back to everyone */
7253 		mhp->msg->sadb_msg_errno = 0;
7254 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7255 	} else {
7256 		/* send packet as is */
7257 
7258 		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7259 
7260 		/* TODO: if sadb_msg_seq is specified, send to specific pid */
7261 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7262 	}
7263 }
7264 
7265 static int (*key_typesw[]) (struct socket *, struct mbuf *,
7266 		const struct sadb_msghdr *) = {
7267 	NULL,		/* SADB_RESERVED */
7268 	key_getspi,	/* SADB_GETSPI */
7269 	key_update,	/* SADB_UPDATE */
7270 	key_add,	/* SADB_ADD */
7271 	key_delete,	/* SADB_DELETE */
7272 	key_get,	/* SADB_GET */
7273 	key_acquire2,	/* SADB_ACQUIRE */
7274 	key_register,	/* SADB_REGISTER */
7275 	NULL,		/* SADB_EXPIRE */
7276 	key_flush,	/* SADB_FLUSH */
7277 	key_dump,	/* SADB_DUMP */
7278 	key_promisc,	/* SADB_X_PROMISC */
7279 	NULL,		/* SADB_X_PCHANGE */
7280 	key_spdadd,	/* SADB_X_SPDUPDATE */
7281 	key_spdadd,	/* SADB_X_SPDADD */
7282 	key_spddelete,	/* SADB_X_SPDDELETE */
7283 	key_spdget,	/* SADB_X_SPDGET */
7284 	NULL,		/* SADB_X_SPDACQUIRE */
7285 	key_spddump,	/* SADB_X_SPDDUMP */
7286 	key_spdflush,	/* SADB_X_SPDFLUSH */
7287 	key_spdadd,	/* SADB_X_SPDSETIDX */
7288 	NULL,		/* SADB_X_SPDEXPIRE */
7289 	key_spddelete2,	/* SADB_X_SPDDELETE2 */
7290 #ifdef IPSEC_NAT_T
7291        key_nat_map,	/* SADB_X_NAT_T_NEW_MAPPING */
7292 #endif
7293 };
7294 
7295 /*
7296  * parse sadb_msg buffer to process PFKEYv2,
7297  * and create a data to response if needed.
7298  * I think to be dealed with mbuf directly.
7299  * IN:
7300  *     msgp  : pointer to pointer to a received buffer pulluped.
7301  *             This is rewrited to response.
7302  *     so    : pointer to socket.
7303  * OUT:
7304  *    length for buffer to send to user process.
7305  */
7306 int
7307 key_parse(struct mbuf *m, struct socket *so)
7308 {
7309 	struct sadb_msg *msg;
7310 	struct sadb_msghdr mh;
7311 	u_int orglen;
7312 	int error;
7313 	int target;
7314 
7315 	/* sanity check */
7316 	if (m == NULL || so == NULL)
7317 		panic("key_parse: NULL pointer is passed");
7318 
7319 #if 0	/*kdebug_sadb assumes msg in linear buffer*/
7320 	KEYDEBUG(KEYDEBUG_KEY_DUMP,
7321 		ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
7322 		kdebug_sadb(msg));
7323 #endif
7324 
7325 	if (m->m_len < sizeof(struct sadb_msg)) {
7326 		m = m_pullup(m, sizeof(struct sadb_msg));
7327 		if (!m)
7328 			return ENOBUFS;
7329 	}
7330 	msg = mtod(m, struct sadb_msg *);
7331 	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7332 	target = KEY_SENDUP_ONE;
7333 
7334 	if ((m->m_flags & M_PKTHDR) == 0 ||
7335 	    m->m_pkthdr.len != m->m_pkthdr.len) {
7336 		ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
7337 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
7338 		error = EINVAL;
7339 		goto senderror;
7340 	}
7341 
7342 	if (msg->sadb_msg_version != PF_KEY_V2) {
7343 		ipseclog((LOG_DEBUG,
7344 		    "key_parse: PF_KEY version %u is mismatched.\n",
7345 		    msg->sadb_msg_version));
7346 		PFKEY_STATINC(PFKEY_STAT_OUT_INVVER);
7347 		error = EINVAL;
7348 		goto senderror;
7349 	}
7350 
7351 	if (msg->sadb_msg_type > SADB_MAX) {
7352 		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
7353 		    msg->sadb_msg_type));
7354 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
7355 		error = EINVAL;
7356 		goto senderror;
7357 	}
7358 
7359 	/* for old-fashioned code - should be nuked */
7360 	if (m->m_pkthdr.len > MCLBYTES) {
7361 		m_freem(m);
7362 		return ENOBUFS;
7363 	}
7364 	if (m->m_next) {
7365 		struct mbuf *n;
7366 
7367 		MGETHDR(n, M_DONTWAIT, MT_DATA);
7368 		if (n && m->m_pkthdr.len > MHLEN) {
7369 			MCLGET(n, M_DONTWAIT);
7370 			if ((n->m_flags & M_EXT) == 0) {
7371 				m_free(n);
7372 				n = NULL;
7373 			}
7374 		}
7375 		if (!n) {
7376 			m_freem(m);
7377 			return ENOBUFS;
7378 		}
7379 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, void *));
7380 		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7381 		n->m_next = NULL;
7382 		m_freem(m);
7383 		m = n;
7384 	}
7385 
7386 	/* align the mbuf chain so that extensions are in contiguous region. */
7387 	error = key_align(m, &mh);
7388 	if (error)
7389 		return error;
7390 
7391 	if (m->m_next) {	/*XXX*/
7392 		m_freem(m);
7393 		return ENOBUFS;
7394 	}
7395 
7396 	msg = mh.msg;
7397 
7398 	/* check SA type */
7399 	switch (msg->sadb_msg_satype) {
7400 	case SADB_SATYPE_UNSPEC:
7401 		switch (msg->sadb_msg_type) {
7402 		case SADB_GETSPI:
7403 		case SADB_UPDATE:
7404 		case SADB_ADD:
7405 		case SADB_DELETE:
7406 		case SADB_GET:
7407 		case SADB_ACQUIRE:
7408 		case SADB_EXPIRE:
7409 			ipseclog((LOG_DEBUG, "key_parse: must specify satype "
7410 			    "when msg type=%u.\n", msg->sadb_msg_type));
7411 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7412 			error = EINVAL;
7413 			goto senderror;
7414 		}
7415 		break;
7416 	case SADB_SATYPE_AH:
7417 	case SADB_SATYPE_ESP:
7418 	case SADB_X_SATYPE_IPCOMP:
7419 	case SADB_X_SATYPE_TCPSIGNATURE:
7420 		switch (msg->sadb_msg_type) {
7421 		case SADB_X_SPDADD:
7422 		case SADB_X_SPDDELETE:
7423 		case SADB_X_SPDGET:
7424 		case SADB_X_SPDDUMP:
7425 		case SADB_X_SPDFLUSH:
7426 		case SADB_X_SPDSETIDX:
7427 		case SADB_X_SPDUPDATE:
7428 		case SADB_X_SPDDELETE2:
7429 			ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
7430 			    msg->sadb_msg_type));
7431 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7432 			error = EINVAL;
7433 			goto senderror;
7434 		}
7435 		break;
7436 	case SADB_SATYPE_RSVP:
7437 	case SADB_SATYPE_OSPFV2:
7438 	case SADB_SATYPE_RIPV2:
7439 	case SADB_SATYPE_MIP:
7440 		ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
7441 		    msg->sadb_msg_satype));
7442 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7443 		error = EOPNOTSUPP;
7444 		goto senderror;
7445 	case 1:	/* XXX: What does it do? */
7446 		if (msg->sadb_msg_type == SADB_X_PROMISC)
7447 			break;
7448 		/*FALLTHROUGH*/
7449 	default:
7450 		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
7451 		    msg->sadb_msg_satype));
7452 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7453 		error = EINVAL;
7454 		goto senderror;
7455 	}
7456 
7457 	/* check field of upper layer protocol and address family */
7458 	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7459 	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7460 		struct sadb_address *src0, *dst0;
7461 		u_int plen;
7462 
7463 		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7464 		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7465 
7466 		/* check upper layer protocol */
7467 		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7468 			ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
7469 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7470 			error = EINVAL;
7471 			goto senderror;
7472 		}
7473 
7474 		/* check family */
7475 		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7476 		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
7477 			ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
7478 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7479 			error = EINVAL;
7480 			goto senderror;
7481 		}
7482 		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7483 		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
7484 			ipseclog((LOG_DEBUG,
7485 			    "key_parse: address struct size mismatched.\n"));
7486 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7487 			error = EINVAL;
7488 			goto senderror;
7489 		}
7490 
7491 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7492 		case AF_INET:
7493 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7494 			    sizeof(struct sockaddr_in)) {
7495 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7496 				error = EINVAL;
7497 				goto senderror;
7498 			}
7499 			break;
7500 		case AF_INET6:
7501 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7502 			    sizeof(struct sockaddr_in6)) {
7503 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7504 				error = EINVAL;
7505 				goto senderror;
7506 			}
7507 			break;
7508 		default:
7509 			ipseclog((LOG_DEBUG,
7510 			    "key_parse: unsupported address family.\n"));
7511 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7512 			error = EAFNOSUPPORT;
7513 			goto senderror;
7514 		}
7515 
7516 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7517 		case AF_INET:
7518 			plen = sizeof(struct in_addr) << 3;
7519 			break;
7520 		case AF_INET6:
7521 			plen = sizeof(struct in6_addr) << 3;
7522 			break;
7523 		default:
7524 			plen = 0;	/*fool gcc*/
7525 			break;
7526 		}
7527 
7528 		/* check max prefix length */
7529 		if (src0->sadb_address_prefixlen > plen ||
7530 		    dst0->sadb_address_prefixlen > plen) {
7531 			ipseclog((LOG_DEBUG,
7532 			    "key_parse: illegal prefixlen.\n"));
7533 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7534 			error = EINVAL;
7535 			goto senderror;
7536 		}
7537 
7538 		/*
7539 		 * prefixlen == 0 is valid because there can be a case when
7540 		 * all addresses are matched.
7541 		 */
7542 	}
7543 
7544 	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7545 	    key_typesw[msg->sadb_msg_type] == NULL) {
7546 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
7547 		error = EINVAL;
7548 		goto senderror;
7549 	}
7550 
7551 	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7552 
7553 senderror:
7554 	msg->sadb_msg_errno = error;
7555 	return key_sendup_mbuf(so, m, target);
7556 }
7557 
7558 static int
7559 key_senderror(struct socket *so, struct mbuf *m, int code)
7560 {
7561 	struct sadb_msg *msg;
7562 
7563 	if (m->m_len < sizeof(struct sadb_msg))
7564 		panic("invalid mbuf passed to key_senderror");
7565 
7566 	msg = mtod(m, struct sadb_msg *);
7567 	msg->sadb_msg_errno = code;
7568 	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7569 }
7570 
7571 /*
7572  * set the pointer to each header into message buffer.
7573  * m will be freed on error.
7574  * XXX larger-than-MCLBYTES extension?
7575  */
7576 static int
7577 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
7578 {
7579 	struct mbuf *n;
7580 	struct sadb_ext *ext;
7581 	size_t off, end;
7582 	int extlen;
7583 	int toff;
7584 
7585 	/* sanity check */
7586 	if (m == NULL || mhp == NULL)
7587 		panic("key_align: NULL pointer is passed");
7588 	if (m->m_len < sizeof(struct sadb_msg))
7589 		panic("invalid mbuf passed to key_align");
7590 
7591 	/* initialize */
7592 	memset(mhp, 0, sizeof(*mhp));
7593 
7594 	mhp->msg = mtod(m, struct sadb_msg *);
7595 	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7596 
7597 	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7598 	extlen = end;	/*just in case extlen is not updated*/
7599 	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7600 		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7601 		if (!n) {
7602 			/* m is already freed */
7603 			return ENOBUFS;
7604 		}
7605 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
7606 
7607 		/* set pointer */
7608 		switch (ext->sadb_ext_type) {
7609 		case SADB_EXT_SA:
7610 		case SADB_EXT_ADDRESS_SRC:
7611 		case SADB_EXT_ADDRESS_DST:
7612 		case SADB_EXT_ADDRESS_PROXY:
7613 		case SADB_EXT_LIFETIME_CURRENT:
7614 		case SADB_EXT_LIFETIME_HARD:
7615 		case SADB_EXT_LIFETIME_SOFT:
7616 		case SADB_EXT_KEY_AUTH:
7617 		case SADB_EXT_KEY_ENCRYPT:
7618 		case SADB_EXT_IDENTITY_SRC:
7619 		case SADB_EXT_IDENTITY_DST:
7620 		case SADB_EXT_SENSITIVITY:
7621 		case SADB_EXT_PROPOSAL:
7622 		case SADB_EXT_SUPPORTED_AUTH:
7623 		case SADB_EXT_SUPPORTED_ENCRYPT:
7624 		case SADB_EXT_SPIRANGE:
7625 		case SADB_X_EXT_POLICY:
7626 		case SADB_X_EXT_SA2:
7627 #ifdef IPSEC_NAT_T
7628 		case SADB_X_EXT_NAT_T_TYPE:
7629 		case SADB_X_EXT_NAT_T_SPORT:
7630 		case SADB_X_EXT_NAT_T_DPORT:
7631 		case SADB_X_EXT_NAT_T_OAI:
7632 		case SADB_X_EXT_NAT_T_OAR:
7633 		case SADB_X_EXT_NAT_T_FRAG:
7634 #endif
7635 			/* duplicate check */
7636 			/*
7637 			 * XXX Are there duplication payloads of either
7638 			 * KEY_AUTH or KEY_ENCRYPT ?
7639 			 */
7640 			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7641 				ipseclog((LOG_DEBUG,
7642 				    "key_align: duplicate ext_type %u "
7643 				    "is passed.\n", ext->sadb_ext_type));
7644 				m_freem(m);
7645 				PFKEY_STATINC(PFKEY_STAT_OUT_DUPEXT);
7646 				return EINVAL;
7647 			}
7648 			break;
7649 		default:
7650 			ipseclog((LOG_DEBUG,
7651 			    "key_align: invalid ext_type %u is passed.\n",
7652 			    ext->sadb_ext_type));
7653 			m_freem(m);
7654 			PFKEY_STATINC(PFKEY_STAT_OUT_INVEXTTYPE);
7655 			return EINVAL;
7656 		}
7657 
7658 		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7659 
7660 		if (key_validate_ext(ext, extlen)) {
7661 			m_freem(m);
7662 			PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
7663 			return EINVAL;
7664 		}
7665 
7666 		n = m_pulldown(m, off, extlen, &toff);
7667 		if (!n) {
7668 			/* m is already freed */
7669 			return ENOBUFS;
7670 		}
7671 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
7672 
7673 		mhp->ext[ext->sadb_ext_type] = ext;
7674 		mhp->extoff[ext->sadb_ext_type] = off;
7675 		mhp->extlen[ext->sadb_ext_type] = extlen;
7676 	}
7677 
7678 	if (off != end) {
7679 		m_freem(m);
7680 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
7681 		return EINVAL;
7682 	}
7683 
7684 	return 0;
7685 }
7686 
7687 static int
7688 key_validate_ext(const struct sadb_ext *ext, int len)
7689 {
7690 	const struct sockaddr *sa;
7691 	enum { NONE, ADDR } checktype = NONE;
7692 	int baselen = 0;
7693 	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7694 
7695 	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7696 		return EINVAL;
7697 
7698 	/* if it does not match minimum/maximum length, bail */
7699 	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7700 	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7701 		return EINVAL;
7702 	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7703 		return EINVAL;
7704 	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7705 		return EINVAL;
7706 
7707 	/* more checks based on sadb_ext_type XXX need more */
7708 	switch (ext->sadb_ext_type) {
7709 	case SADB_EXT_ADDRESS_SRC:
7710 	case SADB_EXT_ADDRESS_DST:
7711 	case SADB_EXT_ADDRESS_PROXY:
7712 		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7713 		checktype = ADDR;
7714 		break;
7715 	case SADB_EXT_IDENTITY_SRC:
7716 	case SADB_EXT_IDENTITY_DST:
7717 		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7718 		    SADB_X_IDENTTYPE_ADDR) {
7719 			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7720 			checktype = ADDR;
7721 		} else
7722 			checktype = NONE;
7723 		break;
7724 	default:
7725 		checktype = NONE;
7726 		break;
7727 	}
7728 
7729 	switch (checktype) {
7730 	case NONE:
7731 		break;
7732 	case ADDR:
7733 		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7734 		if (len < baselen + sal)
7735 			return EINVAL;
7736 		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7737 			return EINVAL;
7738 		break;
7739 	}
7740 
7741 	return 0;
7742 }
7743 
7744 static int
7745 key_do_init(void)
7746 {
7747 	int i;
7748 
7749 	pfkeystat_percpu = percpu_alloc(sizeof(uint64_t) * PFKEY_NSTATS);
7750 
7751 	callout_init(&key_timehandler_ch, 0);
7752 
7753 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7754 		LIST_INIT(&sptree[i]);
7755 	}
7756 
7757 	LIST_INIT(&sahtree);
7758 
7759 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7760 		LIST_INIT(&regtree[i]);
7761 	}
7762 
7763 #ifndef IPSEC_NONBLOCK_ACQUIRE
7764 	LIST_INIT(&acqtree);
7765 #endif
7766 	LIST_INIT(&spacqtree);
7767 
7768 	/* system default */
7769 	ip4_def_policy.policy = IPSEC_POLICY_NONE;
7770 	ip4_def_policy.refcnt++;	/*never reclaim this*/
7771 
7772 #ifdef INET6
7773 	ip6_def_policy.policy = IPSEC_POLICY_NONE;
7774 	ip6_def_policy.refcnt++;	/*never reclaim this*/
7775 #endif
7776 
7777 
7778 #ifndef IPSEC_DEBUG2
7779 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
7780 #endif /*IPSEC_DEBUG2*/
7781 
7782 	/* initialize key statistics */
7783 	keystat.getspi_count = 1;
7784 
7785 	aprint_verbose("IPsec: Initialized Security Association Processing.\n");
7786 
7787 	return (0);
7788 }
7789 
7790 void
7791 key_init(void)
7792 {
7793 	static ONCE_DECL(key_init_once);
7794 
7795 	RUN_ONCE(&key_init_once, key_do_init);
7796 }
7797 
7798 /*
7799  * XXX: maybe This function is called after INBOUND IPsec processing.
7800  *
7801  * Special check for tunnel-mode packets.
7802  * We must make some checks for consistency between inner and outer IP header.
7803  *
7804  * xxx more checks to be provided
7805  */
7806 int
7807 key_checktunnelsanity(
7808     struct secasvar *sav,
7809     u_int family,
7810     void *src,
7811     void *dst
7812 )
7813 {
7814 	/* sanity check */
7815 	if (sav->sah == NULL)
7816 		panic("sav->sah == NULL at key_checktunnelsanity");
7817 
7818 	/* XXX: check inner IP header */
7819 
7820 	return 1;
7821 }
7822 
7823 #if 0
7824 #define hostnamelen	strlen(hostname)
7825 
7826 /*
7827  * Get FQDN for the host.
7828  * If the administrator configured hostname (by hostname(1)) without
7829  * domain name, returns nothing.
7830  */
7831 static const char *
7832 key_getfqdn(void)
7833 {
7834 	int i;
7835 	int hasdot;
7836 	static char fqdn[MAXHOSTNAMELEN + 1];
7837 
7838 	if (!hostnamelen)
7839 		return NULL;
7840 
7841 	/* check if it comes with domain name. */
7842 	hasdot = 0;
7843 	for (i = 0; i < hostnamelen; i++) {
7844 		if (hostname[i] == '.')
7845 			hasdot++;
7846 	}
7847 	if (!hasdot)
7848 		return NULL;
7849 
7850 	/* NOTE: hostname may not be NUL-terminated. */
7851 	memset(fqdn, 0, sizeof(fqdn));
7852 	memcpy(fqdn, hostname, hostnamelen);
7853 	fqdn[hostnamelen] = '\0';
7854 	return fqdn;
7855 }
7856 
7857 /*
7858  * get username@FQDN for the host/user.
7859  */
7860 static const char *
7861 key_getuserfqdn(void)
7862 {
7863 	const char *host;
7864 	static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
7865 	struct proc *p = curproc;
7866 	char *q;
7867 
7868 	if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
7869 		return NULL;
7870 	if (!(host = key_getfqdn()))
7871 		return NULL;
7872 
7873 	/* NOTE: s_login may not be-NUL terminated. */
7874 	memset(userfqdn, 0, sizeof(userfqdn));
7875 	memcpy(userfqdn, Mp->p_pgrp->pg_session->s_login, AXLOGNAME);
7876 	userfqdn[MAXLOGNAME] = '\0';	/* safeguard */
7877 	q = userfqdn + strlen(userfqdn);
7878 	*q++ = '@';
7879 	memcpy(q, host, strlen(host));
7880 	q += strlen(host);
7881 	*q++ = '\0';
7882 
7883 	return userfqdn;
7884 }
7885 #endif
7886 
7887 /* record data transfer on SA, and update timestamps */
7888 void
7889 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
7890 {
7891 	IPSEC_ASSERT(sav != NULL, ("key_sa_recordxfer: Null secasvar"));
7892 	IPSEC_ASSERT(m != NULL, ("key_sa_recordxfer: Null mbuf"));
7893 	if (!sav->lft_c)
7894 		return;
7895 
7896 	/*
7897 	 * XXX Currently, there is a difference of bytes size
7898 	 * between inbound and outbound processing.
7899 	 */
7900 	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
7901 	/* to check bytes lifetime is done in key_timehandler(). */
7902 
7903 	/*
7904 	 * We use the number of packets as the unit of
7905 	 * sadb_lifetime_allocations.  We increment the variable
7906 	 * whenever {esp,ah}_{in,out}put is called.
7907 	 */
7908 	sav->lft_c->sadb_lifetime_allocations++;
7909 	/* XXX check for expires? */
7910 
7911 	/*
7912 	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
7913 	 * in seconds.  HARD and SOFT lifetime are measured by the time
7914 	 * difference (again in seconds) from sadb_lifetime_usetime.
7915 	 *
7916 	 *	usetime
7917 	 *	v     expire   expire
7918 	 * -----+-----+--------+---> t
7919 	 *	<--------------> HARD
7920 	 *	<-----> SOFT
7921 	 */
7922 	sav->lft_c->sadb_lifetime_usetime = time_uptime;
7923 	/* XXX check for expires? */
7924 
7925 	return;
7926 }
7927 
7928 /* dumb version */
7929 void
7930 key_sa_routechange(struct sockaddr *dst)
7931 {
7932 	struct secashead *sah;
7933 	struct route *ro;
7934 	const struct sockaddr *sa;
7935 
7936 	LIST_FOREACH(sah, &sahtree, chain) {
7937 		ro = &sah->sa_route;
7938 		sa = rtcache_getdst(ro);
7939 		if (sa != NULL && dst->sa_len == sa->sa_len &&
7940 		    memcmp(dst, sa, dst->sa_len) == 0)
7941 			rtcache_free(ro);
7942 	}
7943 
7944 	return;
7945 }
7946 
7947 static void
7948 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7949 {
7950 	if (sav == NULL)
7951 		panic("key_sa_chgstate called with sav == NULL");
7952 
7953 	if (sav->state == state)
7954 		return;
7955 
7956 	if (__LIST_CHAINED(sav))
7957 		LIST_REMOVE(sav, chain);
7958 
7959 	sav->state = state;
7960 	LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7961 }
7962 
7963 /* XXX too much? */
7964 static struct mbuf *
7965 key_alloc_mbuf(int l)
7966 {
7967 	struct mbuf *m = NULL, *n;
7968 	int len, t;
7969 
7970 	len = l;
7971 	while (len > 0) {
7972 		MGET(n, M_DONTWAIT, MT_DATA);
7973 		if (n && len > MLEN)
7974 			MCLGET(n, M_DONTWAIT);
7975 		if (!n) {
7976 			m_freem(m);
7977 			return NULL;
7978 		}
7979 
7980 		n->m_next = NULL;
7981 		n->m_len = 0;
7982 		n->m_len = M_TRAILINGSPACE(n);
7983 		/* use the bottom of mbuf, hoping we can prepend afterwards */
7984 		if (n->m_len > len) {
7985 			t = (n->m_len - len) & ~(sizeof(long) - 1);
7986 			n->m_data += t;
7987 			n->m_len = len;
7988 		}
7989 
7990 		len -= n->m_len;
7991 
7992 		if (m)
7993 			m_cat(m, n);
7994 		else
7995 			m = n;
7996 	}
7997 
7998 	return m;
7999 }
8000 
8001 static struct mbuf *
8002 key_setdump(u_int8_t req_satype, int *errorp, uint32_t pid)
8003 {
8004 	struct secashead *sah;
8005 	struct secasvar *sav;
8006 	u_int16_t proto;
8007 	u_int stateidx;
8008 	u_int8_t satype;
8009 	u_int8_t state;
8010 	int cnt;
8011 	struct mbuf *m, *n;
8012 
8013 	/* map satype to proto */
8014 	if ((proto = key_satype2proto(req_satype)) == 0) {
8015 		*errorp = EINVAL;
8016 		return (NULL);
8017 	}
8018 
8019 	/* count sav entries to be sent to the userland. */
8020 	cnt = 0;
8021 	LIST_FOREACH(sah, &sahtree, chain) {
8022 		if (req_satype != SADB_SATYPE_UNSPEC &&
8023 		    proto != sah->saidx.proto)
8024 			continue;
8025 
8026 		for (stateidx = 0;
8027 		     stateidx < _ARRAYLEN(saorder_state_any);
8028 		     stateidx++) {
8029 			state = saorder_state_any[stateidx];
8030 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
8031 				cnt++;
8032 			}
8033 		}
8034 	}
8035 
8036 	if (cnt == 0) {
8037 		*errorp = ENOENT;
8038 		return (NULL);
8039 	}
8040 
8041 	/* send this to the userland, one at a time. */
8042 	m = NULL;
8043 	LIST_FOREACH(sah, &sahtree, chain) {
8044 		if (req_satype != SADB_SATYPE_UNSPEC &&
8045 		    proto != sah->saidx.proto)
8046 			continue;
8047 
8048 		/* map proto to satype */
8049 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
8050 			m_freem(m);
8051 			*errorp = EINVAL;
8052 			return (NULL);
8053 		}
8054 
8055 		for (stateidx = 0;
8056 		     stateidx < _ARRAYLEN(saorder_state_any);
8057 		     stateidx++) {
8058 			state = saorder_state_any[stateidx];
8059 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
8060 				n = key_setdumpsa(sav, SADB_DUMP, satype,
8061 				    --cnt, pid);
8062 				if (!n) {
8063 					m_freem(m);
8064 					*errorp = ENOBUFS;
8065 					return (NULL);
8066 				}
8067 
8068 				if (!m)
8069 					m = n;
8070 				else
8071 					m_cat(m, n);
8072 			}
8073 		}
8074 	}
8075 
8076 	if (!m) {
8077 		*errorp = EINVAL;
8078 		return (NULL);
8079 	}
8080 
8081 	if ((m->m_flags & M_PKTHDR) != 0) {
8082 		m->m_pkthdr.len = 0;
8083 		for (n = m; n; n = n->m_next)
8084 			m->m_pkthdr.len += n->m_len;
8085 	}
8086 
8087 	*errorp = 0;
8088 	return (m);
8089 }
8090 
8091 static struct mbuf *
8092 key_setspddump(int *errorp, pid_t pid)
8093 {
8094 	struct secpolicy *sp;
8095 	int cnt;
8096 	u_int dir;
8097 	struct mbuf *m, *n;
8098 
8099 	/* search SPD entry and get buffer size. */
8100 	cnt = 0;
8101 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
8102 		LIST_FOREACH(sp, &sptree[dir], chain) {
8103 			cnt++;
8104 		}
8105 	}
8106 
8107 	if (cnt == 0) {
8108 		*errorp = ENOENT;
8109 		return (NULL);
8110 	}
8111 
8112 	m = NULL;
8113 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
8114 		LIST_FOREACH(sp, &sptree[dir], chain) {
8115 			--cnt;
8116 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
8117 
8118 			if (!n) {
8119 				*errorp = ENOBUFS;
8120 				m_freem(m);
8121 				return (NULL);
8122 			}
8123 			if (!m)
8124 				m = n;
8125 			else {
8126 				m->m_pkthdr.len += n->m_pkthdr.len;
8127 				m_cat(m, n);
8128 			}
8129 		}
8130 	}
8131 
8132 	*errorp = 0;
8133 	return (m);
8134 }
8135 
8136 static int
8137 sysctl_net_key_dumpsa(SYSCTLFN_ARGS)
8138 {
8139 	struct mbuf *m, *n;
8140 	int err2 = 0;
8141 	char *p, *ep;
8142 	size_t len;
8143 	int s, error;
8144 
8145 	if (newp)
8146 		return (EPERM);
8147 	if (namelen != 1)
8148 		return (EINVAL);
8149 
8150 	s = splsoftnet();
8151 	m = key_setdump(name[0], &error, l->l_proc->p_pid);
8152 	splx(s);
8153 	if (!m)
8154 		return (error);
8155 	if (!oldp)
8156 		*oldlenp = m->m_pkthdr.len;
8157 	else {
8158 		p = oldp;
8159 		if (*oldlenp < m->m_pkthdr.len) {
8160 			err2 = ENOMEM;
8161 			ep = p + *oldlenp;
8162 		} else {
8163 			*oldlenp = m->m_pkthdr.len;
8164 			ep = p + m->m_pkthdr.len;
8165 		}
8166 		for (n = m; n; n = n->m_next) {
8167 			len =  (ep - p < n->m_len) ?
8168 				ep - p : n->m_len;
8169 			error = copyout(mtod(n, const void *), p, len);
8170 			p += len;
8171 			if (error)
8172 				break;
8173 		}
8174 		if (error == 0)
8175 			error = err2;
8176 	}
8177 	m_freem(m);
8178 
8179 	return (error);
8180 }
8181 
8182 static int
8183 sysctl_net_key_dumpsp(SYSCTLFN_ARGS)
8184 {
8185 	struct mbuf *m, *n;
8186 	int err2 = 0;
8187 	char *p, *ep;
8188 	size_t len;
8189 	int s, error;
8190 
8191 	if (newp)
8192 		return (EPERM);
8193 	if (namelen != 0)
8194 		return (EINVAL);
8195 
8196 	s = splsoftnet();
8197 	m = key_setspddump(&error, l->l_proc->p_pid);
8198 	splx(s);
8199 	if (!m)
8200 		return (error);
8201 	if (!oldp)
8202 		*oldlenp = m->m_pkthdr.len;
8203 	else {
8204 		p = oldp;
8205 		if (*oldlenp < m->m_pkthdr.len) {
8206 			err2 = ENOMEM;
8207 			ep = p + *oldlenp;
8208 		} else {
8209 			*oldlenp = m->m_pkthdr.len;
8210 			ep = p + m->m_pkthdr.len;
8211 		}
8212 		for (n = m; n; n = n->m_next) {
8213 			len =  (ep - p < n->m_len) ?
8214 				ep - p : n->m_len;
8215 			error = copyout(mtod(n, const void *), p, len);
8216 			p += len;
8217 			if (error)
8218 				break;
8219 		}
8220 		if (error == 0)
8221 			error = err2;
8222 	}
8223 	m_freem(m);
8224 
8225 	return (error);
8226 }
8227 
8228 /*
8229  * Create sysctl tree for native FAST_IPSEC key knobs, originally
8230  * under name "net.keyv2"  * with MIB number { CTL_NET, PF_KEY_V2. }.
8231  * However, sysctl(8) never checked for nodes under { CTL_NET, PF_KEY_V2 };
8232  * and in any case the part of our sysctl namespace used for dumping the
8233  * SPD and SA database  *HAS* to be compatible with the KAME sysctl
8234  * namespace, for API reasons.
8235  *
8236  * Pending a consensus on the right way  to fix this, add a level of
8237  * indirection in how we number the `native' FAST_IPSEC key nodes;
8238  * and (as requested by Andrew Brown)  move registration of the
8239  * KAME-compatible names  to a separate function.
8240  */
8241 #if 0
8242 #  define FAST_IPSEC_PFKEY PF_KEY_V2
8243 # define FAST_IPSEC_PFKEY_NAME "keyv2"
8244 #else
8245 #  define FAST_IPSEC_PFKEY PF_KEY
8246 # define FAST_IPSEC_PFKEY_NAME "key"
8247 #endif
8248 
8249 static int
8250 sysctl_net_key_stats(SYSCTLFN_ARGS)
8251 {
8252 
8253 	return (NETSTAT_SYSCTL(pfkeystat_percpu, PFKEY_NSTATS));
8254 }
8255 
8256 SYSCTL_SETUP(sysctl_net_keyv2_setup, "sysctl net.keyv2 subtree setup")
8257 {
8258 
8259 	sysctl_createv(clog, 0, NULL, NULL,
8260 		       CTLFLAG_PERMANENT,
8261 		       CTLTYPE_NODE, "net", NULL,
8262 		       NULL, 0, NULL, 0,
8263 		       CTL_NET, CTL_EOL);
8264 	sysctl_createv(clog, 0, NULL, NULL,
8265 		       CTLFLAG_PERMANENT,
8266 		       CTLTYPE_NODE, FAST_IPSEC_PFKEY_NAME, NULL,
8267 		       NULL, 0, NULL, 0,
8268 		       CTL_NET, FAST_IPSEC_PFKEY, CTL_EOL);
8269 
8270 	sysctl_createv(clog, 0, NULL, NULL,
8271 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8272 		       CTLTYPE_INT, "debug", NULL,
8273 		       NULL, 0, &key_debug_level, 0,
8274 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_DEBUG_LEVEL, CTL_EOL);
8275 	sysctl_createv(clog, 0, NULL, NULL,
8276 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8277 		       CTLTYPE_INT, "spi_try", NULL,
8278 		       NULL, 0, &key_spi_trycnt, 0,
8279 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_TRY, CTL_EOL);
8280 	sysctl_createv(clog, 0, NULL, NULL,
8281 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8282 		       CTLTYPE_INT, "spi_min_value", NULL,
8283 		       NULL, 0, &key_spi_minval, 0,
8284 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_MIN_VALUE, CTL_EOL);
8285 	sysctl_createv(clog, 0, NULL, NULL,
8286 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8287 		       CTLTYPE_INT, "spi_max_value", NULL,
8288 		       NULL, 0, &key_spi_maxval, 0,
8289 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_MAX_VALUE, CTL_EOL);
8290 	sysctl_createv(clog, 0, NULL, NULL,
8291 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8292 		       CTLTYPE_INT, "random_int", NULL,
8293 		       NULL, 0, &key_int_random, 0,
8294 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_RANDOM_INT, CTL_EOL);
8295 	sysctl_createv(clog, 0, NULL, NULL,
8296 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8297 		       CTLTYPE_INT, "larval_lifetime", NULL,
8298 		       NULL, 0, &key_larval_lifetime, 0,
8299 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_LARVAL_LIFETIME, CTL_EOL);
8300 	sysctl_createv(clog, 0, NULL, NULL,
8301 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8302 		       CTLTYPE_INT, "blockacq_count", NULL,
8303 		       NULL, 0, &key_blockacq_count, 0,
8304 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_BLOCKACQ_COUNT, CTL_EOL);
8305 	sysctl_createv(clog, 0, NULL, NULL,
8306 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8307 		       CTLTYPE_INT, "blockacq_lifetime", NULL,
8308 		       NULL, 0, &key_blockacq_lifetime, 0,
8309 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_BLOCKACQ_LIFETIME, CTL_EOL);
8310 	sysctl_createv(clog, 0, NULL, NULL,
8311 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8312 		       CTLTYPE_INT, "esp_keymin", NULL,
8313 		       NULL, 0, &ipsec_esp_keymin, 0,
8314 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_ESP_KEYMIN, CTL_EOL);
8315 	sysctl_createv(clog, 0, NULL, NULL,
8316 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8317 		       CTLTYPE_INT, "prefered_oldsa", NULL,
8318 		       NULL, 0, &key_prefered_oldsa, 0,
8319 		       CTL_NET, PF_KEY, KEYCTL_PREFERED_OLDSA, CTL_EOL);
8320 	sysctl_createv(clog, 0, NULL, NULL,
8321 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8322 		       CTLTYPE_INT, "esp_auth", NULL,
8323 		       NULL, 0, &ipsec_esp_auth, 0,
8324 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_ESP_AUTH, CTL_EOL);
8325 	sysctl_createv(clog, 0, NULL, NULL,
8326 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8327 		       CTLTYPE_INT, "ah_keymin", NULL,
8328 		       NULL, 0, &ipsec_ah_keymin, 0,
8329 		       CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_AH_KEYMIN, CTL_EOL);
8330 	sysctl_createv(clog, 0, NULL, NULL,
8331 		       CTLFLAG_PERMANENT,
8332 		       CTLTYPE_STRUCT, "stats",
8333 		       SYSCTL_DESCR("PF_KEY statistics"),
8334 		       sysctl_net_key_stats, 0, NULL, 0,
8335 		       CTL_NET, FAST_IPSEC_PFKEY, CTL_CREATE, CTL_EOL);
8336 }
8337 
8338 /*
8339  * Register sysctl names used by setkey(8). For historical reasons,
8340  * and to share a single API, these names appear under { CTL_NET, PF_KEY }
8341  * for both FAST_IPSEC and KAME IPSEC.
8342  */
8343 SYSCTL_SETUP(sysctl_net_key_compat_setup, "sysctl net.key subtree setup for FAST_IPSEC")
8344 {
8345 
8346 	/* Make sure net.key exists before we register nodes underneath it. */
8347 	sysctl_createv(clog, 0, NULL, NULL,
8348 		       CTLFLAG_PERMANENT,
8349 		       CTLTYPE_NODE, "net", NULL,
8350 		       NULL, 0, NULL, 0,
8351 		       CTL_NET, CTL_EOL);
8352 	sysctl_createv(clog, 0, NULL, NULL,
8353 		       CTLFLAG_PERMANENT,
8354 		       CTLTYPE_NODE, "key", NULL,
8355 		       NULL, 0, NULL, 0,
8356 		       CTL_NET, PF_KEY, CTL_EOL);
8357 
8358 	/* Register the net.key.dump{sa,sp} nodes used by setkey(8). */
8359 	sysctl_createv(clog, 0, NULL, NULL,
8360 		       CTLFLAG_PERMANENT,
8361 		       CTLTYPE_STRUCT, "dumpsa", NULL,
8362 		       sysctl_net_key_dumpsa, 0, NULL, 0,
8363 		       CTL_NET, PF_KEY, KEYCTL_DUMPSA, CTL_EOL);
8364 	sysctl_createv(clog, 0, NULL, NULL,
8365 		       CTLFLAG_PERMANENT,
8366 		       CTLTYPE_STRUCT, "dumpsp", NULL,
8367 		       sysctl_net_key_dumpsp, 0, NULL, 0,
8368 		       CTL_NET, PF_KEY, KEYCTL_DUMPSP, CTL_EOL);
8369 }
8370