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