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