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