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