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