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