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