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