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