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