xref: /freebsd/sys/netipsec/key.c (revision d8b878873e7aa8df1972cc6a642804b17eb61087)
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 #ifdef INET
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 #define	V_key_spi_trycnt	VNET(key_spi_trycnt)
118 static VNET_DEFINE(u_int32_t, key_spi_minval) = 0x100;
119 #define	V_key_spi_minval	VNET(key_spi_minval)
120 static VNET_DEFINE(u_int32_t, key_spi_maxval) = 0x0fffffff;	/* XXX */
121 #define	V_key_spi_maxval	VNET(key_spi_maxval)
122 static VNET_DEFINE(u_int32_t, policy_id) = 0;
123 #define	V_policy_id		VNET(policy_id)
124 /*interval to initialize randseed,1(m)*/
125 static VNET_DEFINE(u_int, key_int_random) = 60;
126 #define	V_key_int_random	VNET(key_int_random)
127 /* interval to expire acquiring, 30(s)*/
128 static VNET_DEFINE(u_int, key_larval_lifetime) = 30;
129 #define	V_key_larval_lifetime	VNET(key_larval_lifetime)
130 /* counter for blocking SADB_ACQUIRE.*/
131 static VNET_DEFINE(int, key_blockacq_count) = 10;
132 #define	V_key_blockacq_count	VNET(key_blockacq_count)
133 /* lifetime for blocking SADB_ACQUIRE.*/
134 static VNET_DEFINE(int, key_blockacq_lifetime) = 20;
135 #define	V_key_blockacq_lifetime	VNET(key_blockacq_lifetime)
136 /* preferred old sa rather than new sa.*/
137 static VNET_DEFINE(int, key_preferred_oldsa) = 1;
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 #define	V_ipsec_esp_keymin	VNET(ipsec_esp_keymin)
274 static VNET_DEFINE(int, ipsec_esp_auth) = 0;
275 #define	V_ipsec_esp_auth	VNET(ipsec_esp_auth)
276 static VNET_DEFINE(int, ipsec_ah_keymin) = 128;
277 #define	V_ipsec_ah_keymin	VNET(ipsec_ah_keymin)
278 
279 #ifdef SYSCTL_DECL
280 SYSCTL_DECL(_net_key);
281 #endif
282 
283 SYSCTL_VNET_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,
284 	CTLFLAG_RW, &VNET_NAME(key_debug_level),	0,	"");
285 
286 /* max count of trial for the decision of spi value */
287 SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
288 	CTLFLAG_RW, &VNET_NAME(key_spi_trycnt),	0,	"");
289 
290 /* minimum spi value to allocate automatically. */
291 SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MIN_VALUE,
292 	spi_minval,	CTLFLAG_RW, &VNET_NAME(key_spi_minval),	0,	"");
293 
294 /* maximun spi value to allocate automatically. */
295 SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MAX_VALUE,
296 	spi_maxval,	CTLFLAG_RW, &VNET_NAME(key_spi_maxval),	0,	"");
297 
298 /* interval to initialize randseed */
299 SYSCTL_VNET_INT(_net_key, KEYCTL_RANDOM_INT,
300 	int_random,	CTLFLAG_RW, &VNET_NAME(key_int_random),	0,	"");
301 
302 /* lifetime for larval SA */
303 SYSCTL_VNET_INT(_net_key, KEYCTL_LARVAL_LIFETIME,
304 	larval_lifetime, CTLFLAG_RW, &VNET_NAME(key_larval_lifetime),	0, "");
305 
306 /* counter for blocking to send SADB_ACQUIRE to IKEd */
307 SYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,
308 	blockacq_count,	CTLFLAG_RW, &VNET_NAME(key_blockacq_count),	0, "");
309 
310 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
311 SYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,
312 	blockacq_lifetime, CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
313 
314 /* ESP auth */
315 SYSCTL_VNET_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth,
316 	CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth),	0,	"");
317 
318 /* minimum ESP key length */
319 SYSCTL_VNET_INT(_net_key, KEYCTL_ESP_KEYMIN,
320 	esp_keymin, CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin),	0,	"");
321 
322 /* minimum AH key length */
323 SYSCTL_VNET_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin,
324 	CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin),	0,	"");
325 
326 /* perfered old SA rather than new SA */
327 SYSCTL_VNET_INT(_net_key, KEYCTL_PREFERED_OLDSA,
328 	preferred_oldsa, CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa),	0, "");
329 
330 #define __LIST_CHAINED(elm) \
331 	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
332 #define LIST_INSERT_TAIL(head, elm, type, field) \
333 do {\
334 	struct type *curelm = LIST_FIRST(head); \
335 	if (curelm == NULL) {\
336 		LIST_INSERT_HEAD(head, elm, field); \
337 	} else { \
338 		while (LIST_NEXT(curelm, field)) \
339 			curelm = LIST_NEXT(curelm, field);\
340 		LIST_INSERT_AFTER(curelm, elm, field);\
341 	}\
342 } while (0)
343 
344 #define KEY_CHKSASTATE(head, sav, name) \
345 do { \
346 	if ((head) != (sav)) {						\
347 		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
348 			(name), (head), (sav)));			\
349 		continue;						\
350 	}								\
351 } while (0)
352 
353 #define KEY_CHKSPDIR(head, sp, name) \
354 do { \
355 	if ((head) != (sp)) {						\
356 		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
357 			"anyway continue.\n",				\
358 			(name), (head), (sp)));				\
359 	}								\
360 } while (0)
361 
362 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
363 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
364 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
365 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
366 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
367 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
368 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
369 
370 /*
371  * set parameters into secpolicyindex buffer.
372  * Must allocate secpolicyindex buffer passed to this function.
373  */
374 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
375 do { \
376 	bzero((idx), sizeof(struct secpolicyindex));                         \
377 	(idx)->dir = (_dir);                                                 \
378 	(idx)->prefs = (ps);                                                 \
379 	(idx)->prefd = (pd);                                                 \
380 	(idx)->ul_proto = (ulp);                                             \
381 	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
382 	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
383 } while (0)
384 
385 /*
386  * set parameters into secasindex buffer.
387  * Must allocate secasindex buffer before calling this function.
388  */
389 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
390 do { \
391 	bzero((idx), sizeof(struct secasindex));                             \
392 	(idx)->proto = (p);                                                  \
393 	(idx)->mode = (m);                                                   \
394 	(idx)->reqid = (r);                                                  \
395 	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
396 	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
397 } while (0)
398 
399 /* key statistics */
400 struct _keystat {
401 	u_long getspi_count; /* the avarage of count to try to get new SPI */
402 } keystat;
403 
404 struct sadb_msghdr {
405 	struct sadb_msg *msg;
406 	struct sadb_ext *ext[SADB_EXT_MAX + 1];
407 	int extoff[SADB_EXT_MAX + 1];
408 	int extlen[SADB_EXT_MAX + 1];
409 };
410 
411 static struct secasvar *key_allocsa_policy __P((const struct secasindex *));
412 static void key_freesp_so __P((struct secpolicy **));
413 static struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
414 static void key_delsp __P((struct secpolicy *));
415 static struct secpolicy *key_getsp __P((struct secpolicyindex *));
416 static void _key_delsp(struct secpolicy *sp);
417 static struct secpolicy *key_getspbyid __P((u_int32_t));
418 static u_int32_t key_newreqid __P((void));
419 static struct mbuf *key_gather_mbuf __P((struct mbuf *,
420 	const struct sadb_msghdr *, int, int, ...));
421 static int key_spdadd __P((struct socket *, struct mbuf *,
422 	const struct sadb_msghdr *));
423 static u_int32_t key_getnewspid __P((void));
424 static int key_spddelete __P((struct socket *, struct mbuf *,
425 	const struct sadb_msghdr *));
426 static int key_spddelete2 __P((struct socket *, struct mbuf *,
427 	const struct sadb_msghdr *));
428 static int key_spdget __P((struct socket *, struct mbuf *,
429 	const struct sadb_msghdr *));
430 static int key_spdflush __P((struct socket *, struct mbuf *,
431 	const struct sadb_msghdr *));
432 static int key_spddump __P((struct socket *, struct mbuf *,
433 	const struct sadb_msghdr *));
434 static struct mbuf *key_setdumpsp __P((struct secpolicy *,
435 	u_int8_t, u_int32_t, u_int32_t));
436 static u_int key_getspreqmsglen __P((struct secpolicy *));
437 static int key_spdexpire __P((struct secpolicy *));
438 static struct secashead *key_newsah __P((struct secasindex *));
439 static void key_delsah __P((struct secashead *));
440 static struct secasvar *key_newsav __P((struct mbuf *,
441 	const struct sadb_msghdr *, struct secashead *, int *,
442 	const char*, int));
443 #define	KEY_NEWSAV(m, sadb, sah, e)				\
444 	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
445 static void key_delsav __P((struct secasvar *));
446 static struct secashead *key_getsah __P((struct secasindex *));
447 static struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
448 static struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
449 static int key_setsaval __P((struct secasvar *, struct mbuf *,
450 	const struct sadb_msghdr *));
451 static int key_mature __P((struct secasvar *));
452 static struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
453 	u_int8_t, u_int32_t, u_int32_t));
454 static struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
455 	u_int32_t, pid_t, u_int16_t));
456 static struct mbuf *key_setsadbsa __P((struct secasvar *));
457 static struct mbuf *key_setsadbaddr __P((u_int16_t,
458 	const struct sockaddr *, u_int8_t, u_int16_t));
459 #ifdef IPSEC_NAT_T
460 static struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
461 static struct mbuf *key_setsadbxtype(u_int16_t);
462 #endif
463 static void key_porttosaddr(struct sockaddr *, u_int16_t);
464 #define	KEY_PORTTOSADDR(saddr, port)				\
465 	key_porttosaddr((struct sockaddr *)(saddr), (port))
466 static struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
467 static struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
468 	u_int32_t));
469 static struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
470 				     struct malloc_type *);
471 static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
472 					    struct malloc_type *type);
473 #ifdef INET6
474 static int key_ismyaddr6 __P((struct sockaddr_in6 *));
475 #endif
476 
477 /* flags for key_cmpsaidx() */
478 #define CMP_HEAD	1	/* protocol, addresses. */
479 #define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
480 #define CMP_REQID	3	/* additionally HEAD, reaid. */
481 #define CMP_EXACTLY	4	/* all elements. */
482 static int key_cmpsaidx
483 	__P((const struct secasindex *, const struct secasindex *, int));
484 
485 static int key_cmpspidx_exactly
486 	__P((struct secpolicyindex *, struct secpolicyindex *));
487 static int key_cmpspidx_withmask
488 	__P((struct secpolicyindex *, struct secpolicyindex *));
489 static int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
490 static int key_bbcmp __P((const void *, const void *, u_int));
491 static u_int16_t key_satype2proto __P((u_int8_t));
492 static u_int8_t key_proto2satype __P((u_int16_t));
493 
494 static int key_getspi __P((struct socket *, struct mbuf *,
495 	const struct sadb_msghdr *));
496 static u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
497 					struct secasindex *));
498 static int key_update __P((struct socket *, struct mbuf *,
499 	const struct sadb_msghdr *));
500 #ifdef IPSEC_DOSEQCHECK
501 static struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
502 #endif
503 static int key_add __P((struct socket *, struct mbuf *,
504 	const struct sadb_msghdr *));
505 static int key_setident __P((struct secashead *, struct mbuf *,
506 	const struct sadb_msghdr *));
507 static struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
508 	const struct sadb_msghdr *));
509 static int key_delete __P((struct socket *, struct mbuf *,
510 	const struct sadb_msghdr *));
511 static int key_get __P((struct socket *, struct mbuf *,
512 	const struct sadb_msghdr *));
513 
514 static void key_getcomb_setlifetime __P((struct sadb_comb *));
515 static struct mbuf *key_getcomb_esp __P((void));
516 static struct mbuf *key_getcomb_ah __P((void));
517 static struct mbuf *key_getcomb_ipcomp __P((void));
518 static struct mbuf *key_getprop __P((const struct secasindex *));
519 
520 static int key_acquire __P((const struct secasindex *, struct secpolicy *));
521 static struct secacq *key_newacq __P((const struct secasindex *));
522 static struct secacq *key_getacq __P((const struct secasindex *));
523 static struct secacq *key_getacqbyseq __P((u_int32_t));
524 static struct secspacq *key_newspacq __P((struct secpolicyindex *));
525 static struct secspacq *key_getspacq __P((struct secpolicyindex *));
526 static int key_acquire2 __P((struct socket *, struct mbuf *,
527 	const struct sadb_msghdr *));
528 static int key_register __P((struct socket *, struct mbuf *,
529 	const struct sadb_msghdr *));
530 static int key_expire __P((struct secasvar *));
531 static int key_flush __P((struct socket *, struct mbuf *,
532 	const struct sadb_msghdr *));
533 static int key_dump __P((struct socket *, struct mbuf *,
534 	const struct sadb_msghdr *));
535 static int key_promisc __P((struct socket *, struct mbuf *,
536 	const struct sadb_msghdr *));
537 static int key_senderror __P((struct socket *, struct mbuf *, int));
538 static int key_validate_ext __P((const struct sadb_ext *, int));
539 static int key_align __P((struct mbuf *, struct sadb_msghdr *));
540 static struct mbuf *key_setlifetime(struct seclifetime *src,
541 				     u_int16_t exttype);
542 static struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
543 
544 #if 0
545 static const char *key_getfqdn __P((void));
546 static const char *key_getuserfqdn __P((void));
547 #endif
548 static void key_sa_chgstate __P((struct secasvar *, u_int8_t));
549 static struct mbuf *key_alloc_mbuf __P((int));
550 
551 static __inline void
552 sa_initref(struct secasvar *sav)
553 {
554 
555 	refcount_init(&sav->refcnt, 1);
556 }
557 static __inline void
558 sa_addref(struct secasvar *sav)
559 {
560 
561 	refcount_acquire(&sav->refcnt);
562 	IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
563 }
564 static __inline int
565 sa_delref(struct secasvar *sav)
566 {
567 
568 	IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
569 	return (refcount_release(&sav->refcnt));
570 }
571 
572 #define	SP_ADDREF(p) do {						\
573 	(p)->refcnt++;							\
574 	IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));		\
575 } while (0)
576 #define	SP_DELREF(p) do {						\
577 	IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));		\
578 	(p)->refcnt--;							\
579 } while (0)
580 
581 
582 /*
583  * Update the refcnt while holding the SPTREE lock.
584  */
585 void
586 key_addref(struct secpolicy *sp)
587 {
588 	SPTREE_LOCK();
589 	SP_ADDREF(sp);
590 	SPTREE_UNLOCK();
591 }
592 
593 /*
594  * Return 0 when there are known to be no SP's for the specified
595  * direction.  Otherwise return 1.  This is used by IPsec code
596  * to optimize performance.
597  */
598 int
599 key_havesp(u_int dir)
600 {
601 
602 	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
603 		LIST_FIRST(&V_sptree[dir]) != NULL : 1);
604 }
605 
606 /* %%% IPsec policy management */
607 /*
608  * allocating a SP for OUTBOUND or INBOUND packet.
609  * Must call key_freesp() later.
610  * OUT:	NULL:	not found
611  *	others:	found and return the pointer.
612  */
613 struct secpolicy *
614 key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
615 {
616 	struct secpolicy *sp;
617 
618 	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
619 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
620 		("invalid direction %u", dir));
621 
622 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
623 		printf("DP %s from %s:%u\n", __func__, where, tag));
624 
625 	/* get a SP entry */
626 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
627 		printf("*** objects\n");
628 		kdebug_secpolicyindex(spidx));
629 
630 	SPTREE_LOCK();
631 	LIST_FOREACH(sp, &V_sptree[dir], chain) {
632 		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
633 			printf("*** in SPD\n");
634 			kdebug_secpolicyindex(&sp->spidx));
635 
636 		if (sp->state == IPSEC_SPSTATE_DEAD)
637 			continue;
638 		if (key_cmpspidx_withmask(&sp->spidx, spidx))
639 			goto found;
640 	}
641 	sp = NULL;
642 found:
643 	if (sp) {
644 		/* sanity check */
645 		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
646 
647 		/* found a SPD entry */
648 		sp->lastused = time_second;
649 		SP_ADDREF(sp);
650 	}
651 	SPTREE_UNLOCK();
652 
653 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
654 		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
655 			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
656 	return sp;
657 }
658 
659 /*
660  * allocating a SP for OUTBOUND or INBOUND packet.
661  * Must call key_freesp() later.
662  * OUT:	NULL:	not found
663  *	others:	found and return the pointer.
664  */
665 struct secpolicy *
666 key_allocsp2(u_int32_t spi,
667 	     union sockaddr_union *dst,
668 	     u_int8_t proto,
669 	     u_int dir,
670 	     const char* where, int tag)
671 {
672 	struct secpolicy *sp;
673 
674 	IPSEC_ASSERT(dst != NULL, ("null dst"));
675 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
676 		("invalid direction %u", dir));
677 
678 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
679 		printf("DP %s from %s:%u\n", __func__, where, tag));
680 
681 	/* get a SP entry */
682 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
683 		printf("*** objects\n");
684 		printf("spi %u proto %u dir %u\n", spi, proto, dir);
685 		kdebug_sockaddr(&dst->sa));
686 
687 	SPTREE_LOCK();
688 	LIST_FOREACH(sp, &V_sptree[dir], chain) {
689 		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
690 			printf("*** in SPD\n");
691 			kdebug_secpolicyindex(&sp->spidx));
692 
693 		if (sp->state == IPSEC_SPSTATE_DEAD)
694 			continue;
695 		/* compare simple values, then dst address */
696 		if (sp->spidx.ul_proto != proto)
697 			continue;
698 		/* NB: spi's must exist and match */
699 		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
700 			continue;
701 		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
702 			goto found;
703 	}
704 	sp = NULL;
705 found:
706 	if (sp) {
707 		/* sanity check */
708 		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
709 
710 		/* found a SPD entry */
711 		sp->lastused = time_second;
712 		SP_ADDREF(sp);
713 	}
714 	SPTREE_UNLOCK();
715 
716 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
717 		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
718 			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
719 	return sp;
720 }
721 
722 #if 0
723 /*
724  * return a policy that matches this particular inbound packet.
725  * XXX slow
726  */
727 struct secpolicy *
728 key_gettunnel(const struct sockaddr *osrc,
729 	      const struct sockaddr *odst,
730 	      const struct sockaddr *isrc,
731 	      const struct sockaddr *idst,
732 	      const char* where, int tag)
733 {
734 	struct secpolicy *sp;
735 	const int dir = IPSEC_DIR_INBOUND;
736 	struct ipsecrequest *r1, *r2, *p;
737 	struct secpolicyindex spidx;
738 
739 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
740 		printf("DP %s from %s:%u\n", __func__, where, tag));
741 
742 	if (isrc->sa_family != idst->sa_family) {
743 		ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
744 			__func__, isrc->sa_family, idst->sa_family));
745 		sp = NULL;
746 		goto done;
747 	}
748 
749 	SPTREE_LOCK();
750 	LIST_FOREACH(sp, &V_sptree[dir], chain) {
751 		if (sp->state == IPSEC_SPSTATE_DEAD)
752 			continue;
753 
754 		r1 = r2 = NULL;
755 		for (p = sp->req; p; p = p->next) {
756 			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
757 				continue;
758 
759 			r1 = r2;
760 			r2 = p;
761 
762 			if (!r1) {
763 				/* here we look at address matches only */
764 				spidx = sp->spidx;
765 				if (isrc->sa_len > sizeof(spidx.src) ||
766 				    idst->sa_len > sizeof(spidx.dst))
767 					continue;
768 				bcopy(isrc, &spidx.src, isrc->sa_len);
769 				bcopy(idst, &spidx.dst, idst->sa_len);
770 				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
771 					continue;
772 			} else {
773 				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
774 				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
775 					continue;
776 			}
777 
778 			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
779 			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
780 				continue;
781 
782 			goto found;
783 		}
784 	}
785 	sp = NULL;
786 found:
787 	if (sp) {
788 		sp->lastused = time_second;
789 		SP_ADDREF(sp);
790 	}
791 	SPTREE_UNLOCK();
792 done:
793 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
794 		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
795 			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
796 	return sp;
797 }
798 #endif
799 
800 /*
801  * allocating an SA entry for an *OUTBOUND* packet.
802  * checking each request entries in SP, and acquire an SA if need.
803  * OUT:	0: there are valid requests.
804  *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
805  */
806 int
807 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
808 {
809 	u_int level;
810 	int error;
811 
812 	IPSEC_ASSERT(isr != NULL, ("null isr"));
813 	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
814 	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
815 		saidx->mode == IPSEC_MODE_TUNNEL,
816 		("unexpected policy %u", saidx->mode));
817 
818 	/*
819 	 * XXX guard against protocol callbacks from the crypto
820 	 * thread as they reference ipsecrequest.sav which we
821 	 * temporarily null out below.  Need to rethink how we
822 	 * handle bundled SA's in the callback thread.
823 	 */
824 	IPSECREQUEST_LOCK_ASSERT(isr);
825 
826 	/* get current level */
827 	level = ipsec_get_reqlevel(isr);
828 #if 0
829 	/*
830 	 * We do allocate new SA only if the state of SA in the holder is
831 	 * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
832 	 */
833 	if (isr->sav != NULL) {
834 		if (isr->sav->sah == NULL)
835 			panic("%s: sah is null.\n", __func__);
836 		if (isr->sav == (struct secasvar *)LIST_FIRST(
837 			    &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
838 			KEY_FREESAV(&isr->sav);
839 			isr->sav = NULL;
840 		}
841 	}
842 #else
843 	/*
844 	 * we free any SA stashed in the IPsec request because a different
845 	 * SA may be involved each time this request is checked, either
846 	 * because new SAs are being configured, or this request is
847 	 * associated with an unconnected datagram socket, or this request
848 	 * is associated with a system default policy.
849 	 *
850 	 * The operation may have negative impact to performance.  We may
851 	 * want to check cached SA carefully, rather than picking new SA
852 	 * every time.
853 	 */
854 	if (isr->sav != NULL) {
855 		KEY_FREESAV(&isr->sav);
856 		isr->sav = NULL;
857 	}
858 #endif
859 
860 	/*
861 	 * new SA allocation if no SA found.
862 	 * key_allocsa_policy should allocate the oldest SA available.
863 	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
864 	 */
865 	if (isr->sav == NULL)
866 		isr->sav = key_allocsa_policy(saidx);
867 
868 	/* When there is SA. */
869 	if (isr->sav != NULL) {
870 		if (isr->sav->state != SADB_SASTATE_MATURE &&
871 		    isr->sav->state != SADB_SASTATE_DYING)
872 			return EINVAL;
873 		return 0;
874 	}
875 
876 	/* there is no SA */
877 	error = key_acquire(saidx, isr->sp);
878 	if (error != 0) {
879 		/* XXX What should I do ? */
880 		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
881 			__func__, error));
882 		return error;
883 	}
884 
885 	if (level != IPSEC_LEVEL_REQUIRE) {
886 		/* XXX sigh, the interface to this routine is botched */
887 		IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
888 		return 0;
889 	} else {
890 		return ENOENT;
891 	}
892 }
893 
894 /*
895  * allocating a SA for policy entry from SAD.
896  * NOTE: searching SAD of aliving state.
897  * OUT:	NULL:	not found.
898  *	others:	found and return the pointer.
899  */
900 static struct secasvar *
901 key_allocsa_policy(const struct secasindex *saidx)
902 {
903 #define	N(a)	_ARRAYLEN(a)
904 	struct secashead *sah;
905 	struct secasvar *sav;
906 	u_int stateidx, arraysize;
907 	const u_int *state_valid;
908 
909 	state_valid = NULL;	/* silence gcc */
910 	arraysize = 0;		/* silence gcc */
911 
912 	SAHTREE_LOCK();
913 	LIST_FOREACH(sah, &V_sahtree, chain) {
914 		if (sah->state == SADB_SASTATE_DEAD)
915 			continue;
916 		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
917 			if (V_key_preferred_oldsa) {
918 				state_valid = saorder_state_valid_prefer_old;
919 				arraysize = N(saorder_state_valid_prefer_old);
920 			} else {
921 				state_valid = saorder_state_valid_prefer_new;
922 				arraysize = N(saorder_state_valid_prefer_new);
923 			}
924 			break;
925 		}
926 	}
927 	SAHTREE_UNLOCK();
928 	if (sah == NULL)
929 		return NULL;
930 
931 	/* search valid state */
932 	for (stateidx = 0; stateidx < arraysize; stateidx++) {
933 		sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
934 		if (sav != NULL)
935 			return sav;
936 	}
937 
938 	return NULL;
939 #undef N
940 }
941 
942 /*
943  * searching SAD with direction, protocol, mode and state.
944  * called by key_allocsa_policy().
945  * OUT:
946  *	NULL	: not found
947  *	others	: found, pointer to a SA.
948  */
949 static struct secasvar *
950 key_do_allocsa_policy(struct secashead *sah, u_int state)
951 {
952 	struct secasvar *sav, *nextsav, *candidate, *d;
953 
954 	/* initilize */
955 	candidate = NULL;
956 
957 	SAHTREE_LOCK();
958 	for (sav = LIST_FIRST(&sah->savtree[state]);
959 	     sav != NULL;
960 	     sav = nextsav) {
961 
962 		nextsav = LIST_NEXT(sav, chain);
963 
964 		/* sanity check */
965 		KEY_CHKSASTATE(sav->state, state, __func__);
966 
967 		/* initialize */
968 		if (candidate == NULL) {
969 			candidate = sav;
970 			continue;
971 		}
972 
973 		/* Which SA is the better ? */
974 
975 		IPSEC_ASSERT(candidate->lft_c != NULL,
976 			("null candidate lifetime"));
977 		IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
978 
979 		/* What the best method is to compare ? */
980 		if (V_key_preferred_oldsa) {
981 			if (candidate->lft_c->addtime >
982 					sav->lft_c->addtime) {
983 				candidate = sav;
984 			}
985 			continue;
986 			/*NOTREACHED*/
987 		}
988 
989 		/* preferred new sa rather than old sa */
990 		if (candidate->lft_c->addtime <
991 				sav->lft_c->addtime) {
992 			d = candidate;
993 			candidate = sav;
994 		} else
995 			d = sav;
996 
997 		/*
998 		 * prepared to delete the SA when there is more
999 		 * suitable candidate and the lifetime of the SA is not
1000 		 * permanent.
1001 		 */
1002 		if (d->lft_h->addtime != 0) {
1003 			struct mbuf *m, *result;
1004 			u_int8_t satype;
1005 
1006 			key_sa_chgstate(d, SADB_SASTATE_DEAD);
1007 
1008 			IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
1009 
1010 			satype = key_proto2satype(d->sah->saidx.proto);
1011 			if (satype == 0)
1012 				goto msgfail;
1013 
1014 			m = key_setsadbmsg(SADB_DELETE, 0,
1015 			    satype, 0, 0, d->refcnt - 1);
1016 			if (!m)
1017 				goto msgfail;
1018 			result = m;
1019 
1020 			/* set sadb_address for saidx's. */
1021 			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
1022 				&d->sah->saidx.src.sa,
1023 				d->sah->saidx.src.sa.sa_len << 3,
1024 				IPSEC_ULPROTO_ANY);
1025 			if (!m)
1026 				goto msgfail;
1027 			m_cat(result, m);
1028 
1029 			/* set sadb_address for saidx's. */
1030 			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
1031 				&d->sah->saidx.dst.sa,
1032 				d->sah->saidx.dst.sa.sa_len << 3,
1033 				IPSEC_ULPROTO_ANY);
1034 			if (!m)
1035 				goto msgfail;
1036 			m_cat(result, m);
1037 
1038 			/* create SA extension */
1039 			m = key_setsadbsa(d);
1040 			if (!m)
1041 				goto msgfail;
1042 			m_cat(result, m);
1043 
1044 			if (result->m_len < sizeof(struct sadb_msg)) {
1045 				result = m_pullup(result,
1046 						sizeof(struct sadb_msg));
1047 				if (result == NULL)
1048 					goto msgfail;
1049 			}
1050 
1051 			result->m_pkthdr.len = 0;
1052 			for (m = result; m; m = m->m_next)
1053 				result->m_pkthdr.len += m->m_len;
1054 			mtod(result, struct sadb_msg *)->sadb_msg_len =
1055 				PFKEY_UNIT64(result->m_pkthdr.len);
1056 
1057 			if (key_sendup_mbuf(NULL, result,
1058 					KEY_SENDUP_REGISTERED))
1059 				goto msgfail;
1060 		 msgfail:
1061 			KEY_FREESAV(&d);
1062 		}
1063 	}
1064 	if (candidate) {
1065 		sa_addref(candidate);
1066 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1067 			printf("DP %s cause refcnt++:%d SA:%p\n",
1068 				__func__, candidate->refcnt, candidate));
1069 	}
1070 	SAHTREE_UNLOCK();
1071 
1072 	return candidate;
1073 }
1074 
1075 /*
1076  * allocating a usable SA entry for a *INBOUND* packet.
1077  * Must call key_freesav() later.
1078  * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
1079  *	NULL:		not found, or error occured.
1080  *
1081  * In the comparison, no source address is used--for RFC2401 conformance.
1082  * To quote, from section 4.1:
1083  *	A security association is uniquely identified by a triple consisting
1084  *	of a Security Parameter Index (SPI), an IP Destination Address, and a
1085  *	security protocol (AH or ESP) identifier.
1086  * Note that, however, we do need to keep source address in IPsec SA.
1087  * IKE specification and PF_KEY specification do assume that we
1088  * keep source address in IPsec SA.  We see a tricky situation here.
1089  */
1090 struct secasvar *
1091 key_allocsa(
1092 	union sockaddr_union *dst,
1093 	u_int proto,
1094 	u_int32_t spi,
1095 	const char* where, int tag)
1096 {
1097 	struct secashead *sah;
1098 	struct secasvar *sav;
1099 	u_int stateidx, arraysize, state;
1100 	const u_int *saorder_state_valid;
1101 	int chkport;
1102 
1103 	IPSEC_ASSERT(dst != NULL, ("null dst address"));
1104 
1105 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1106 		printf("DP %s from %s:%u\n", __func__, where, tag));
1107 
1108 #ifdef IPSEC_NAT_T
1109         chkport = (dst->sa.sa_family == AF_INET &&
1110 	    dst->sa.sa_len == sizeof(struct sockaddr_in) &&
1111 	    dst->sin.sin_port != 0);
1112 #else
1113 	chkport = 0;
1114 #endif
1115 
1116 	/*
1117 	 * searching SAD.
1118 	 * XXX: to be checked internal IP header somewhere.  Also when
1119 	 * IPsec tunnel packet is received.  But ESP tunnel mode is
1120 	 * encrypted so we can't check internal IP header.
1121 	 */
1122 	SAHTREE_LOCK();
1123 	if (V_key_preferred_oldsa) {
1124 		saorder_state_valid = saorder_state_valid_prefer_old;
1125 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1126 	} else {
1127 		saorder_state_valid = saorder_state_valid_prefer_new;
1128 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1129 	}
1130 	LIST_FOREACH(sah, &V_sahtree, chain) {
1131 		/* search valid state */
1132 		for (stateidx = 0; stateidx < arraysize; stateidx++) {
1133 			state = saorder_state_valid[stateidx];
1134 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
1135 				/* sanity check */
1136 				KEY_CHKSASTATE(sav->state, state, __func__);
1137 				/* do not return entries w/ unusable state */
1138 				if (sav->state != SADB_SASTATE_MATURE &&
1139 				    sav->state != SADB_SASTATE_DYING)
1140 					continue;
1141 				if (proto != sav->sah->saidx.proto)
1142 					continue;
1143 				if (spi != sav->spi)
1144 					continue;
1145 #if 0	/* don't check src */
1146 				/* check src address */
1147 				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, chkport) != 0)
1148 					continue;
1149 #endif
1150 				/* check dst address */
1151 				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, chkport) != 0)
1152 					continue;
1153 				sa_addref(sav);
1154 				goto done;
1155 			}
1156 		}
1157 	}
1158 	sav = NULL;
1159 done:
1160 	SAHTREE_UNLOCK();
1161 
1162 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1163 		printf("DP %s return SA:%p; refcnt %u\n", __func__,
1164 			sav, sav ? sav->refcnt : 0));
1165 	return sav;
1166 }
1167 
1168 /*
1169  * Must be called after calling key_allocsp().
1170  * For both the packet without socket and key_freeso().
1171  */
1172 void
1173 _key_freesp(struct secpolicy **spp, const char* where, int tag)
1174 {
1175 	struct secpolicy *sp = *spp;
1176 
1177 	IPSEC_ASSERT(sp != NULL, ("null sp"));
1178 
1179 	SPTREE_LOCK();
1180 	SP_DELREF(sp);
1181 
1182 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1183 		printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1184 			__func__, sp, sp->id, where, tag, sp->refcnt));
1185 
1186 	if (sp->refcnt == 0) {
1187 		*spp = NULL;
1188 		key_delsp(sp);
1189 	}
1190 	SPTREE_UNLOCK();
1191 }
1192 
1193 /*
1194  * Must be called after calling key_allocsp().
1195  * For the packet with socket.
1196  */
1197 void
1198 key_freeso(struct socket *so)
1199 {
1200 	IPSEC_ASSERT(so != NULL, ("null so"));
1201 
1202 	switch (so->so_proto->pr_domain->dom_family) {
1203 #if defined(INET) || defined(INET6)
1204 #ifdef INET
1205 	case PF_INET:
1206 #endif
1207 #ifdef INET6
1208 	case PF_INET6:
1209 #endif
1210 	    {
1211 		struct inpcb *pcb = sotoinpcb(so);
1212 
1213 		/* Does it have a PCB ? */
1214 		if (pcb == NULL)
1215 			return;
1216 		key_freesp_so(&pcb->inp_sp->sp_in);
1217 		key_freesp_so(&pcb->inp_sp->sp_out);
1218 	    }
1219 		break;
1220 #endif /* INET || INET6 */
1221 	default:
1222 		ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1223 		    __func__, so->so_proto->pr_domain->dom_family));
1224 		return;
1225 	}
1226 }
1227 
1228 static void
1229 key_freesp_so(struct secpolicy **sp)
1230 {
1231 	IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1232 
1233 	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1234 	    (*sp)->policy == IPSEC_POLICY_BYPASS)
1235 		return;
1236 
1237 	IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1238 		("invalid policy %u", (*sp)->policy));
1239 	KEY_FREESP(sp);
1240 }
1241 
1242 /*
1243  * Must be called after calling key_allocsa().
1244  * This function is called by key_freesp() to free some SA allocated
1245  * for a policy.
1246  */
1247 void
1248 key_freesav(struct secasvar **psav, const char* where, int tag)
1249 {
1250 	struct secasvar *sav = *psav;
1251 
1252 	IPSEC_ASSERT(sav != NULL, ("null sav"));
1253 
1254 	if (sa_delref(sav)) {
1255 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1256 			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1257 				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1258 		*psav = NULL;
1259 		key_delsav(sav);
1260 	} else {
1261 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1262 			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1263 				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1264 	}
1265 }
1266 
1267 /* %%% SPD management */
1268 /*
1269  * free security policy entry.
1270  */
1271 static void
1272 key_delsp(struct secpolicy *sp)
1273 {
1274 	struct ipsecrequest *isr, *nextisr;
1275 
1276 	IPSEC_ASSERT(sp != NULL, ("null sp"));
1277 	SPTREE_LOCK_ASSERT();
1278 
1279 	sp->state = IPSEC_SPSTATE_DEAD;
1280 
1281 	IPSEC_ASSERT(sp->refcnt == 0,
1282 		("SP with references deleted (refcnt %u)", sp->refcnt));
1283 
1284 	/* remove from SP index */
1285 	if (__LIST_CHAINED(sp))
1286 		LIST_REMOVE(sp, chain);
1287 
1288 	for (isr = sp->req; isr != NULL; isr = nextisr) {
1289 		if (isr->sav != NULL) {
1290 			KEY_FREESAV(&isr->sav);
1291 			isr->sav = NULL;
1292 		}
1293 
1294 		nextisr = isr->next;
1295 		ipsec_delisr(isr);
1296 	}
1297 	_key_delsp(sp);
1298 }
1299 
1300 /*
1301  * search SPD
1302  * OUT:	NULL	: not found
1303  *	others	: found, pointer to a SP.
1304  */
1305 static struct secpolicy *
1306 key_getsp(struct secpolicyindex *spidx)
1307 {
1308 	struct secpolicy *sp;
1309 
1310 	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1311 
1312 	SPTREE_LOCK();
1313 	LIST_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1314 		if (sp->state == IPSEC_SPSTATE_DEAD)
1315 			continue;
1316 		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1317 			SP_ADDREF(sp);
1318 			break;
1319 		}
1320 	}
1321 	SPTREE_UNLOCK();
1322 
1323 	return sp;
1324 }
1325 
1326 /*
1327  * get SP by index.
1328  * OUT:	NULL	: not found
1329  *	others	: found, pointer to a SP.
1330  */
1331 static struct secpolicy *
1332 key_getspbyid(u_int32_t id)
1333 {
1334 	struct secpolicy *sp;
1335 
1336 	SPTREE_LOCK();
1337 	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
1338 		if (sp->state == IPSEC_SPSTATE_DEAD)
1339 			continue;
1340 		if (sp->id == id) {
1341 			SP_ADDREF(sp);
1342 			goto done;
1343 		}
1344 	}
1345 
1346 	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
1347 		if (sp->state == IPSEC_SPSTATE_DEAD)
1348 			continue;
1349 		if (sp->id == id) {
1350 			SP_ADDREF(sp);
1351 			goto done;
1352 		}
1353 	}
1354 done:
1355 	SPTREE_UNLOCK();
1356 
1357 	return sp;
1358 }
1359 
1360 struct secpolicy *
1361 key_newsp(const char* where, int tag)
1362 {
1363 	struct secpolicy *newsp = NULL;
1364 
1365 	newsp = (struct secpolicy *)
1366 		malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1367 	if (newsp) {
1368 		SECPOLICY_LOCK_INIT(newsp);
1369 		newsp->refcnt = 1;
1370 		newsp->req = NULL;
1371 	}
1372 
1373 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1374 		printf("DP %s from %s:%u return SP:%p\n", __func__,
1375 			where, tag, newsp));
1376 	return newsp;
1377 }
1378 
1379 static void
1380 _key_delsp(struct secpolicy *sp)
1381 {
1382 	SECPOLICY_LOCK_DESTROY(sp);
1383 	free(sp, M_IPSEC_SP);
1384 }
1385 
1386 /*
1387  * create secpolicy structure from sadb_x_policy structure.
1388  * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1389  * so must be set properly later.
1390  */
1391 struct secpolicy *
1392 key_msg2sp(xpl0, len, error)
1393 	struct sadb_x_policy *xpl0;
1394 	size_t len;
1395 	int *error;
1396 {
1397 	struct secpolicy *newsp;
1398 
1399 	IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1400 	IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1401 
1402 	if (len != PFKEY_EXTLEN(xpl0)) {
1403 		ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1404 		*error = EINVAL;
1405 		return NULL;
1406 	}
1407 
1408 	if ((newsp = KEY_NEWSP()) == NULL) {
1409 		*error = ENOBUFS;
1410 		return NULL;
1411 	}
1412 
1413 	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1414 	newsp->policy = xpl0->sadb_x_policy_type;
1415 
1416 	/* check policy */
1417 	switch (xpl0->sadb_x_policy_type) {
1418 	case IPSEC_POLICY_DISCARD:
1419 	case IPSEC_POLICY_NONE:
1420 	case IPSEC_POLICY_ENTRUST:
1421 	case IPSEC_POLICY_BYPASS:
1422 		newsp->req = NULL;
1423 		break;
1424 
1425 	case IPSEC_POLICY_IPSEC:
1426 	    {
1427 		int tlen;
1428 		struct sadb_x_ipsecrequest *xisr;
1429 		struct ipsecrequest **p_isr = &newsp->req;
1430 
1431 		/* validity check */
1432 		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1433 			ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1434 				__func__));
1435 			KEY_FREESP(&newsp);
1436 			*error = EINVAL;
1437 			return NULL;
1438 		}
1439 
1440 		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1441 		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1442 
1443 		while (tlen > 0) {
1444 			/* length check */
1445 			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1446 				ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1447 					"length.\n", __func__));
1448 				KEY_FREESP(&newsp);
1449 				*error = EINVAL;
1450 				return NULL;
1451 			}
1452 
1453 			/* allocate request buffer */
1454 			/* NB: data structure is zero'd */
1455 			*p_isr = ipsec_newisr();
1456 			if ((*p_isr) == NULL) {
1457 				ipseclog((LOG_DEBUG,
1458 				    "%s: No more memory.\n", __func__));
1459 				KEY_FREESP(&newsp);
1460 				*error = ENOBUFS;
1461 				return NULL;
1462 			}
1463 
1464 			/* set values */
1465 			switch (xisr->sadb_x_ipsecrequest_proto) {
1466 			case IPPROTO_ESP:
1467 			case IPPROTO_AH:
1468 			case IPPROTO_IPCOMP:
1469 				break;
1470 			default:
1471 				ipseclog((LOG_DEBUG,
1472 				    "%s: invalid proto type=%u\n", __func__,
1473 				    xisr->sadb_x_ipsecrequest_proto));
1474 				KEY_FREESP(&newsp);
1475 				*error = EPROTONOSUPPORT;
1476 				return NULL;
1477 			}
1478 			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1479 
1480 			switch (xisr->sadb_x_ipsecrequest_mode) {
1481 			case IPSEC_MODE_TRANSPORT:
1482 			case IPSEC_MODE_TUNNEL:
1483 				break;
1484 			case IPSEC_MODE_ANY:
1485 			default:
1486 				ipseclog((LOG_DEBUG,
1487 				    "%s: invalid mode=%u\n", __func__,
1488 				    xisr->sadb_x_ipsecrequest_mode));
1489 				KEY_FREESP(&newsp);
1490 				*error = EINVAL;
1491 				return NULL;
1492 			}
1493 			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1494 
1495 			switch (xisr->sadb_x_ipsecrequest_level) {
1496 			case IPSEC_LEVEL_DEFAULT:
1497 			case IPSEC_LEVEL_USE:
1498 			case IPSEC_LEVEL_REQUIRE:
1499 				break;
1500 			case IPSEC_LEVEL_UNIQUE:
1501 				/* validity check */
1502 				/*
1503 				 * If range violation of reqid, kernel will
1504 				 * update it, don't refuse it.
1505 				 */
1506 				if (xisr->sadb_x_ipsecrequest_reqid
1507 						> IPSEC_MANUAL_REQID_MAX) {
1508 					ipseclog((LOG_DEBUG,
1509 					    "%s: reqid=%d range "
1510 					    "violation, updated by kernel.\n",
1511 					    __func__,
1512 					    xisr->sadb_x_ipsecrequest_reqid));
1513 					xisr->sadb_x_ipsecrequest_reqid = 0;
1514 				}
1515 
1516 				/* allocate new reqid id if reqid is zero. */
1517 				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1518 					u_int32_t reqid;
1519 					if ((reqid = key_newreqid()) == 0) {
1520 						KEY_FREESP(&newsp);
1521 						*error = ENOBUFS;
1522 						return NULL;
1523 					}
1524 					(*p_isr)->saidx.reqid = reqid;
1525 					xisr->sadb_x_ipsecrequest_reqid = reqid;
1526 				} else {
1527 				/* set it for manual keying. */
1528 					(*p_isr)->saidx.reqid =
1529 						xisr->sadb_x_ipsecrequest_reqid;
1530 				}
1531 				break;
1532 
1533 			default:
1534 				ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1535 					__func__,
1536 					xisr->sadb_x_ipsecrequest_level));
1537 				KEY_FREESP(&newsp);
1538 				*error = EINVAL;
1539 				return NULL;
1540 			}
1541 			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1542 
1543 			/* set IP addresses if there */
1544 			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1545 				struct sockaddr *paddr;
1546 
1547 				paddr = (struct sockaddr *)(xisr + 1);
1548 
1549 				/* validity check */
1550 				if (paddr->sa_len
1551 				    > sizeof((*p_isr)->saidx.src)) {
1552 					ipseclog((LOG_DEBUG, "%s: invalid "
1553 						"request address length.\n",
1554 						__func__));
1555 					KEY_FREESP(&newsp);
1556 					*error = EINVAL;
1557 					return NULL;
1558 				}
1559 				bcopy(paddr, &(*p_isr)->saidx.src,
1560 					paddr->sa_len);
1561 
1562 				paddr = (struct sockaddr *)((caddr_t)paddr
1563 							+ paddr->sa_len);
1564 
1565 				/* validity check */
1566 				if (paddr->sa_len
1567 				    > sizeof((*p_isr)->saidx.dst)) {
1568 					ipseclog((LOG_DEBUG, "%s: invalid "
1569 						"request address length.\n",
1570 						__func__));
1571 					KEY_FREESP(&newsp);
1572 					*error = EINVAL;
1573 					return NULL;
1574 				}
1575 				bcopy(paddr, &(*p_isr)->saidx.dst,
1576 					paddr->sa_len);
1577 			}
1578 
1579 			(*p_isr)->sp = newsp;
1580 
1581 			/* initialization for the next. */
1582 			p_isr = &(*p_isr)->next;
1583 			tlen -= xisr->sadb_x_ipsecrequest_len;
1584 
1585 			/* validity check */
1586 			if (tlen < 0) {
1587 				ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1588 					__func__));
1589 				KEY_FREESP(&newsp);
1590 				*error = EINVAL;
1591 				return NULL;
1592 			}
1593 
1594 			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1595 			                 + xisr->sadb_x_ipsecrequest_len);
1596 		}
1597 	    }
1598 		break;
1599 	default:
1600 		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1601 		KEY_FREESP(&newsp);
1602 		*error = EINVAL;
1603 		return NULL;
1604 	}
1605 
1606 	*error = 0;
1607 	return newsp;
1608 }
1609 
1610 static u_int32_t
1611 key_newreqid()
1612 {
1613 	static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1614 
1615 	auto_reqid = (auto_reqid == ~0
1616 			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1617 
1618 	/* XXX should be unique check */
1619 
1620 	return auto_reqid;
1621 }
1622 
1623 /*
1624  * copy secpolicy struct to sadb_x_policy structure indicated.
1625  */
1626 struct mbuf *
1627 key_sp2msg(sp)
1628 	struct secpolicy *sp;
1629 {
1630 	struct sadb_x_policy *xpl;
1631 	int tlen;
1632 	caddr_t p;
1633 	struct mbuf *m;
1634 
1635 	IPSEC_ASSERT(sp != NULL, ("null policy"));
1636 
1637 	tlen = key_getspreqmsglen(sp);
1638 
1639 	m = key_alloc_mbuf(tlen);
1640 	if (!m || m->m_next) {	/*XXX*/
1641 		if (m)
1642 			m_freem(m);
1643 		return NULL;
1644 	}
1645 
1646 	m->m_len = tlen;
1647 	m->m_next = NULL;
1648 	xpl = mtod(m, struct sadb_x_policy *);
1649 	bzero(xpl, tlen);
1650 
1651 	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1652 	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1653 	xpl->sadb_x_policy_type = sp->policy;
1654 	xpl->sadb_x_policy_dir = sp->spidx.dir;
1655 	xpl->sadb_x_policy_id = sp->id;
1656 	p = (caddr_t)xpl + sizeof(*xpl);
1657 
1658 	/* if is the policy for ipsec ? */
1659 	if (sp->policy == IPSEC_POLICY_IPSEC) {
1660 		struct sadb_x_ipsecrequest *xisr;
1661 		struct ipsecrequest *isr;
1662 
1663 		for (isr = sp->req; isr != NULL; isr = isr->next) {
1664 
1665 			xisr = (struct sadb_x_ipsecrequest *)p;
1666 
1667 			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1668 			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1669 			xisr->sadb_x_ipsecrequest_level = isr->level;
1670 			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1671 
1672 			p += sizeof(*xisr);
1673 			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1674 			p += isr->saidx.src.sa.sa_len;
1675 			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1676 			p += isr->saidx.src.sa.sa_len;
1677 
1678 			xisr->sadb_x_ipsecrequest_len =
1679 				PFKEY_ALIGN8(sizeof(*xisr)
1680 					+ isr->saidx.src.sa.sa_len
1681 					+ isr->saidx.dst.sa.sa_len);
1682 		}
1683 	}
1684 
1685 	return m;
1686 }
1687 
1688 /* m will not be freed nor modified */
1689 static struct mbuf *
1690 #ifdef __STDC__
1691 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1692 	int ndeep, int nitem, ...)
1693 #else
1694 key_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1695 	struct mbuf *m;
1696 	const struct sadb_msghdr *mhp;
1697 	int ndeep;
1698 	int nitem;
1699 	va_dcl
1700 #endif
1701 {
1702 	va_list ap;
1703 	int idx;
1704 	int i;
1705 	struct mbuf *result = NULL, *n;
1706 	int len;
1707 
1708 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1709 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1710 
1711 	va_start(ap, nitem);
1712 	for (i = 0; i < nitem; i++) {
1713 		idx = va_arg(ap, int);
1714 		if (idx < 0 || idx > SADB_EXT_MAX)
1715 			goto fail;
1716 		/* don't attempt to pull empty extension */
1717 		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1718 			continue;
1719 		if (idx != SADB_EXT_RESERVED  &&
1720 		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1721 			continue;
1722 
1723 		if (idx == SADB_EXT_RESERVED) {
1724 			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1725 
1726 			IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1727 
1728 			MGETHDR(n, M_DONTWAIT, MT_DATA);
1729 			if (!n)
1730 				goto fail;
1731 			n->m_len = len;
1732 			n->m_next = NULL;
1733 			m_copydata(m, 0, sizeof(struct sadb_msg),
1734 			    mtod(n, caddr_t));
1735 		} else if (i < ndeep) {
1736 			len = mhp->extlen[idx];
1737 			n = key_alloc_mbuf(len);
1738 			if (!n || n->m_next) {	/*XXX*/
1739 				if (n)
1740 					m_freem(n);
1741 				goto fail;
1742 			}
1743 			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1744 			    mtod(n, caddr_t));
1745 		} else {
1746 			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1747 			    M_DONTWAIT);
1748 		}
1749 		if (n == NULL)
1750 			goto fail;
1751 
1752 		if (result)
1753 			m_cat(result, n);
1754 		else
1755 			result = n;
1756 	}
1757 	va_end(ap);
1758 
1759 	if ((result->m_flags & M_PKTHDR) != 0) {
1760 		result->m_pkthdr.len = 0;
1761 		for (n = result; n; n = n->m_next)
1762 			result->m_pkthdr.len += n->m_len;
1763 	}
1764 
1765 	return result;
1766 
1767 fail:
1768 	m_freem(result);
1769 	return NULL;
1770 }
1771 
1772 /*
1773  * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1774  * add an entry to SP database, when received
1775  *   <base, address(SD), (lifetime(H),) policy>
1776  * from the user(?).
1777  * Adding to SP database,
1778  * and send
1779  *   <base, address(SD), (lifetime(H),) policy>
1780  * to the socket which was send.
1781  *
1782  * SPDADD set a unique policy entry.
1783  * SPDSETIDX like SPDADD without a part of policy requests.
1784  * SPDUPDATE replace a unique policy entry.
1785  *
1786  * m will always be freed.
1787  */
1788 static int
1789 key_spdadd(so, m, mhp)
1790 	struct socket *so;
1791 	struct mbuf *m;
1792 	const struct sadb_msghdr *mhp;
1793 {
1794 	struct sadb_address *src0, *dst0;
1795 	struct sadb_x_policy *xpl0, *xpl;
1796 	struct sadb_lifetime *lft = NULL;
1797 	struct secpolicyindex spidx;
1798 	struct secpolicy *newsp;
1799 	int error;
1800 
1801 	IPSEC_ASSERT(so != NULL, ("null socket"));
1802 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1803 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1804 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1805 
1806 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1807 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1808 	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1809 		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1810 		return key_senderror(so, m, EINVAL);
1811 	}
1812 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1813 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1814 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1815 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1816 			__func__));
1817 		return key_senderror(so, m, EINVAL);
1818 	}
1819 	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1820 		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1821 			< sizeof(struct sadb_lifetime)) {
1822 			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1823 				__func__));
1824 			return key_senderror(so, m, EINVAL);
1825 		}
1826 		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1827 	}
1828 
1829 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1830 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1831 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1832 
1833 	/*
1834 	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
1835 	 * we are processing traffic endpoints.
1836 	 */
1837 
1838 	/* make secindex */
1839 	/* XXX boundary check against sa_len */
1840 	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1841 	                src0 + 1,
1842 	                dst0 + 1,
1843 	                src0->sadb_address_prefixlen,
1844 	                dst0->sadb_address_prefixlen,
1845 	                src0->sadb_address_proto,
1846 	                &spidx);
1847 
1848 	/* checking the direciton. */
1849 	switch (xpl0->sadb_x_policy_dir) {
1850 	case IPSEC_DIR_INBOUND:
1851 	case IPSEC_DIR_OUTBOUND:
1852 		break;
1853 	default:
1854 		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1855 		mhp->msg->sadb_msg_errno = EINVAL;
1856 		return 0;
1857 	}
1858 
1859 	/* check policy */
1860 	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1861 	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1862 	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1863 		ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1864 		return key_senderror(so, m, EINVAL);
1865 	}
1866 
1867 	/* policy requests are mandatory when action is ipsec. */
1868         if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1869 	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1870 	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1871 		ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1872 			__func__));
1873 		return key_senderror(so, m, EINVAL);
1874 	}
1875 
1876 	/*
1877 	 * checking there is SP already or not.
1878 	 * SPDUPDATE doesn't depend on whether there is a SP or not.
1879 	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1880 	 * then error.
1881 	 */
1882 	newsp = key_getsp(&spidx);
1883 	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1884 		if (newsp) {
1885 			SPTREE_LOCK();
1886 			newsp->state = IPSEC_SPSTATE_DEAD;
1887 			SPTREE_UNLOCK();
1888 			KEY_FREESP(&newsp);
1889 		}
1890 	} else {
1891 		if (newsp != NULL) {
1892 			KEY_FREESP(&newsp);
1893 			ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1894 				__func__));
1895 			return key_senderror(so, m, EEXIST);
1896 		}
1897 	}
1898 
1899 	/* allocation new SP entry */
1900 	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1901 		return key_senderror(so, m, error);
1902 	}
1903 
1904 	if ((newsp->id = key_getnewspid()) == 0) {
1905 		_key_delsp(newsp);
1906 		return key_senderror(so, m, ENOBUFS);
1907 	}
1908 
1909 	/* XXX boundary check against sa_len */
1910 	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1911 	                src0 + 1,
1912 	                dst0 + 1,
1913 	                src0->sadb_address_prefixlen,
1914 	                dst0->sadb_address_prefixlen,
1915 	                src0->sadb_address_proto,
1916 	                &newsp->spidx);
1917 
1918 	/* sanity check on addr pair */
1919 	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1920 			((struct sockaddr *)(dst0+ 1))->sa_family) {
1921 		_key_delsp(newsp);
1922 		return key_senderror(so, m, EINVAL);
1923 	}
1924 	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1925 			((struct sockaddr *)(dst0+ 1))->sa_len) {
1926 		_key_delsp(newsp);
1927 		return key_senderror(so, m, EINVAL);
1928 	}
1929 #if 1
1930 	if (newsp->req && newsp->req->saidx.src.sa.sa_family && newsp->req->saidx.dst.sa.sa_family) {
1931 		if (newsp->req->saidx.src.sa.sa_family != newsp->req->saidx.dst.sa.sa_family) {
1932 			_key_delsp(newsp);
1933 			return key_senderror(so, m, EINVAL);
1934 		}
1935 	}
1936 #endif
1937 
1938 	newsp->created = time_second;
1939 	newsp->lastused = newsp->created;
1940 	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1941 	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1942 
1943 	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1944 	newsp->state = IPSEC_SPSTATE_ALIVE;
1945 	LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1946 
1947 	/* delete the entry in spacqtree */
1948 	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1949 		struct secspacq *spacq = key_getspacq(&spidx);
1950 		if (spacq != NULL) {
1951 			/* reset counter in order to deletion by timehandler. */
1952 			spacq->created = time_second;
1953 			spacq->count = 0;
1954 			SPACQ_UNLOCK();
1955 		}
1956     	}
1957 
1958     {
1959 	struct mbuf *n, *mpolicy;
1960 	struct sadb_msg *newmsg;
1961 	int off;
1962 
1963 	/*
1964 	 * Note: do not send SADB_X_EXT_NAT_T_* here:
1965 	 * we are sending traffic endpoints.
1966 	 */
1967 
1968 	/* create new sadb_msg to reply. */
1969 	if (lft) {
1970 		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1971 		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1972 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1973 	} else {
1974 		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1975 		    SADB_X_EXT_POLICY,
1976 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1977 	}
1978 	if (!n)
1979 		return key_senderror(so, m, ENOBUFS);
1980 
1981 	if (n->m_len < sizeof(*newmsg)) {
1982 		n = m_pullup(n, sizeof(*newmsg));
1983 		if (!n)
1984 			return key_senderror(so, m, ENOBUFS);
1985 	}
1986 	newmsg = mtod(n, struct sadb_msg *);
1987 	newmsg->sadb_msg_errno = 0;
1988 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1989 
1990 	off = 0;
1991 	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1992 	    sizeof(*xpl), &off);
1993 	if (mpolicy == NULL) {
1994 		/* n is already freed */
1995 		return key_senderror(so, m, ENOBUFS);
1996 	}
1997 	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1998 	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1999 		m_freem(n);
2000 		return key_senderror(so, m, EINVAL);
2001 	}
2002 	xpl->sadb_x_policy_id = newsp->id;
2003 
2004 	m_freem(m);
2005 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2006     }
2007 }
2008 
2009 /*
2010  * get new policy id.
2011  * OUT:
2012  *	0:	failure.
2013  *	others: success.
2014  */
2015 static u_int32_t
2016 key_getnewspid()
2017 {
2018 	u_int32_t newid = 0;
2019 	int count = V_key_spi_trycnt;	/* XXX */
2020 	struct secpolicy *sp;
2021 
2022 	/* when requesting to allocate spi ranged */
2023 	while (count--) {
2024 		newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
2025 
2026 		if ((sp = key_getspbyid(newid)) == NULL)
2027 			break;
2028 
2029 		KEY_FREESP(&sp);
2030 	}
2031 
2032 	if (count == 0 || newid == 0) {
2033 		ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2034 			__func__));
2035 		return 0;
2036 	}
2037 
2038 	return newid;
2039 }
2040 
2041 /*
2042  * SADB_SPDDELETE processing
2043  * receive
2044  *   <base, address(SD), policy(*)>
2045  * from the user(?), and set SADB_SASTATE_DEAD,
2046  * and send,
2047  *   <base, address(SD), policy(*)>
2048  * to the ikmpd.
2049  * policy(*) including direction of policy.
2050  *
2051  * m will always be freed.
2052  */
2053 static int
2054 key_spddelete(so, m, mhp)
2055 	struct socket *so;
2056 	struct mbuf *m;
2057 	const struct sadb_msghdr *mhp;
2058 {
2059 	struct sadb_address *src0, *dst0;
2060 	struct sadb_x_policy *xpl0;
2061 	struct secpolicyindex spidx;
2062 	struct secpolicy *sp;
2063 
2064 	IPSEC_ASSERT(so != NULL, ("null so"));
2065 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2066 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2067 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2068 
2069 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2070 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2071 	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2072 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2073 			__func__));
2074 		return key_senderror(so, m, EINVAL);
2075 	}
2076 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2077 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2078 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2079 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2080 			__func__));
2081 		return key_senderror(so, m, EINVAL);
2082 	}
2083 
2084 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2085 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2086 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2087 
2088 	/*
2089 	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
2090 	 * we are processing traffic endpoints.
2091 	 */
2092 
2093 	/* make secindex */
2094 	/* XXX boundary check against sa_len */
2095 	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2096 	                src0 + 1,
2097 	                dst0 + 1,
2098 	                src0->sadb_address_prefixlen,
2099 	                dst0->sadb_address_prefixlen,
2100 	                src0->sadb_address_proto,
2101 	                &spidx);
2102 
2103 	/* checking the direciton. */
2104 	switch (xpl0->sadb_x_policy_dir) {
2105 	case IPSEC_DIR_INBOUND:
2106 	case IPSEC_DIR_OUTBOUND:
2107 		break;
2108 	default:
2109 		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2110 		return key_senderror(so, m, EINVAL);
2111 	}
2112 
2113 	/* Is there SP in SPD ? */
2114 	if ((sp = key_getsp(&spidx)) == NULL) {
2115 		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2116 		return key_senderror(so, m, EINVAL);
2117 	}
2118 
2119 	/* save policy id to buffer to be returned. */
2120 	xpl0->sadb_x_policy_id = sp->id;
2121 
2122 	SPTREE_LOCK();
2123 	sp->state = IPSEC_SPSTATE_DEAD;
2124 	SPTREE_UNLOCK();
2125 	KEY_FREESP(&sp);
2126 
2127     {
2128 	struct mbuf *n;
2129 	struct sadb_msg *newmsg;
2130 
2131 	/*
2132 	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2133 	 * we are sending traffic endpoints.
2134 	 */
2135 
2136 	/* create new sadb_msg to reply. */
2137 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2138 	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2139 	if (!n)
2140 		return key_senderror(so, m, ENOBUFS);
2141 
2142 	newmsg = mtod(n, struct sadb_msg *);
2143 	newmsg->sadb_msg_errno = 0;
2144 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2145 
2146 	m_freem(m);
2147 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2148     }
2149 }
2150 
2151 /*
2152  * SADB_SPDDELETE2 processing
2153  * receive
2154  *   <base, policy(*)>
2155  * from the user(?), and set SADB_SASTATE_DEAD,
2156  * and send,
2157  *   <base, policy(*)>
2158  * to the ikmpd.
2159  * policy(*) including direction of policy.
2160  *
2161  * m will always be freed.
2162  */
2163 static int
2164 key_spddelete2(so, m, mhp)
2165 	struct socket *so;
2166 	struct mbuf *m;
2167 	const struct sadb_msghdr *mhp;
2168 {
2169 	u_int32_t id;
2170 	struct secpolicy *sp;
2171 
2172 	IPSEC_ASSERT(so != NULL, ("null socket"));
2173 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2174 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2175 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2176 
2177 	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2178 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2179 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2180 		return key_senderror(so, m, EINVAL);
2181 	}
2182 
2183 	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2184 
2185 	/* Is there SP in SPD ? */
2186 	if ((sp = key_getspbyid(id)) == NULL) {
2187 		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2188 		return key_senderror(so, m, EINVAL);
2189 	}
2190 
2191 	SPTREE_LOCK();
2192 	sp->state = IPSEC_SPSTATE_DEAD;
2193 	SPTREE_UNLOCK();
2194 	KEY_FREESP(&sp);
2195 
2196     {
2197 	struct mbuf *n, *nn;
2198 	struct sadb_msg *newmsg;
2199 	int off, len;
2200 
2201 	/* create new sadb_msg to reply. */
2202 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2203 
2204 	MGETHDR(n, M_DONTWAIT, MT_DATA);
2205 	if (n && len > MHLEN) {
2206 		MCLGET(n, M_DONTWAIT);
2207 		if ((n->m_flags & M_EXT) == 0) {
2208 			m_freem(n);
2209 			n = NULL;
2210 		}
2211 	}
2212 	if (!n)
2213 		return key_senderror(so, m, ENOBUFS);
2214 
2215 	n->m_len = len;
2216 	n->m_next = NULL;
2217 	off = 0;
2218 
2219 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2220 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2221 
2222 	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2223 		off, len));
2224 
2225 	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2226 	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2227 	if (!n->m_next) {
2228 		m_freem(n);
2229 		return key_senderror(so, m, ENOBUFS);
2230 	}
2231 
2232 	n->m_pkthdr.len = 0;
2233 	for (nn = n; nn; nn = nn->m_next)
2234 		n->m_pkthdr.len += nn->m_len;
2235 
2236 	newmsg = mtod(n, struct sadb_msg *);
2237 	newmsg->sadb_msg_errno = 0;
2238 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2239 
2240 	m_freem(m);
2241 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2242     }
2243 }
2244 
2245 /*
2246  * SADB_X_GET processing
2247  * receive
2248  *   <base, policy(*)>
2249  * from the user(?),
2250  * and send,
2251  *   <base, address(SD), policy>
2252  * to the ikmpd.
2253  * policy(*) including direction of policy.
2254  *
2255  * m will always be freed.
2256  */
2257 static int
2258 key_spdget(so, m, mhp)
2259 	struct socket *so;
2260 	struct mbuf *m;
2261 	const struct sadb_msghdr *mhp;
2262 {
2263 	u_int32_t id;
2264 	struct secpolicy *sp;
2265 	struct mbuf *n;
2266 
2267 	IPSEC_ASSERT(so != NULL, ("null socket"));
2268 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2269 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2270 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2271 
2272 	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2273 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2274 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2275 			__func__));
2276 		return key_senderror(so, m, EINVAL);
2277 	}
2278 
2279 	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2280 
2281 	/* Is there SP in SPD ? */
2282 	if ((sp = key_getspbyid(id)) == NULL) {
2283 		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2284 		return key_senderror(so, m, ENOENT);
2285 	}
2286 
2287 	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
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->sa_route.ro_rt) {
2761 			RTFREE(sah->sa_route.ro_rt);
2762 			sah->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_DONTWAIT, MT_DATA);
3566 	if (m && len > MHLEN) {
3567 		MCLGET(m, M_DONTWAIT);
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 		for (ia = V_in_ifaddrhead.tqh_first; ia;
3925 		     ia = ia->ia_link.tqe_next)
3926 		{
3927 			if (sin->sin_family == ia->ia_addr.sin_family &&
3928 			    sin->sin_len == ia->ia_addr.sin_len &&
3929 			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3930 			{
3931 				IN_IFADDR_RUNLOCK();
3932 				return 1;
3933 			}
3934 		}
3935 		IN_IFADDR_RUNLOCK();
3936 		break;
3937 #endif
3938 #ifdef INET6
3939 	case AF_INET6:
3940 		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3941 #endif
3942 	}
3943 
3944 	return 0;
3945 }
3946 
3947 #ifdef INET6
3948 /*
3949  * compare my own address for IPv6.
3950  * 1: ours
3951  * 0: other
3952  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3953  */
3954 #include <netinet6/in6_var.h>
3955 
3956 static int
3957 key_ismyaddr6(sin6)
3958 	struct sockaddr_in6 *sin6;
3959 {
3960 	struct in6_ifaddr *ia;
3961 #if 0
3962 	struct in6_multi *in6m;
3963 #endif
3964 
3965 	IN6_IFADDR_RLOCK();
3966 	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
3967 		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3968 		    (struct sockaddr *)&ia->ia_addr, 0) == 0) {
3969 			IN6_IFADDR_RUNLOCK();
3970 			return 1;
3971 		}
3972 
3973 #if 0
3974 		/*
3975 		 * XXX Multicast
3976 		 * XXX why do we care about multlicast here while we don't care
3977 		 * about IPv4 multicast??
3978 		 * XXX scope
3979 		 */
3980 		in6m = NULL;
3981 		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3982 		if (in6m) {
3983 			IN6_IFADDR_RUNLOCK();
3984 			return 1;
3985 		}
3986 #endif
3987 	}
3988 	IN6_IFADDR_RUNLOCK();
3989 
3990 	/* loopback, just for safety */
3991 	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3992 		return 1;
3993 
3994 	return 0;
3995 }
3996 #endif /*INET6*/
3997 
3998 /*
3999  * compare two secasindex structure.
4000  * flag can specify to compare 2 saidxes.
4001  * compare two secasindex structure without both mode and reqid.
4002  * don't compare port.
4003  * IN:
4004  *      saidx0: source, it can be in SAD.
4005  *      saidx1: object.
4006  * OUT:
4007  *      1 : equal
4008  *      0 : not equal
4009  */
4010 static int
4011 key_cmpsaidx(
4012 	const struct secasindex *saidx0,
4013 	const struct secasindex *saidx1,
4014 	int flag)
4015 {
4016 	int chkport = 0;
4017 
4018 	/* sanity */
4019 	if (saidx0 == NULL && saidx1 == NULL)
4020 		return 1;
4021 
4022 	if (saidx0 == NULL || saidx1 == NULL)
4023 		return 0;
4024 
4025 	if (saidx0->proto != saidx1->proto)
4026 		return 0;
4027 
4028 	if (flag == CMP_EXACTLY) {
4029 		if (saidx0->mode != saidx1->mode)
4030 			return 0;
4031 		if (saidx0->reqid != saidx1->reqid)
4032 			return 0;
4033 		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4034 		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4035 			return 0;
4036 	} else {
4037 
4038 		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4039 		if (flag == CMP_MODE_REQID
4040 		  ||flag == CMP_REQID) {
4041 			/*
4042 			 * If reqid of SPD is non-zero, unique SA is required.
4043 			 * The result must be of same reqid in this case.
4044 			 */
4045 			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4046 				return 0;
4047 		}
4048 
4049 		if (flag == CMP_MODE_REQID) {
4050 			if (saidx0->mode != IPSEC_MODE_ANY
4051 			 && saidx0->mode != saidx1->mode)
4052 				return 0;
4053 		}
4054 
4055 #ifdef IPSEC_NAT_T
4056 		/*
4057 		 * If NAT-T is enabled, check ports for tunnel mode.
4058 		 * Do not check ports if they are set to zero in the SPD.
4059 		 * Also do not do it for transport mode, as there is no
4060 		 * port information available in the SP.
4061 		 */
4062 		if (saidx1->mode == IPSEC_MODE_TUNNEL &&
4063 		    saidx1->src.sa.sa_family == AF_INET &&
4064 		    saidx1->dst.sa.sa_family == AF_INET &&
4065 		    ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
4066 		    ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
4067 			chkport = 1;
4068 #endif /* IPSEC_NAT_T */
4069 
4070 		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
4071 			return 0;
4072 		}
4073 		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
4074 			return 0;
4075 		}
4076 	}
4077 
4078 	return 1;
4079 }
4080 
4081 /*
4082  * compare two secindex structure exactly.
4083  * IN:
4084  *	spidx0: source, it is often in SPD.
4085  *	spidx1: object, it is often from PFKEY message.
4086  * OUT:
4087  *	1 : equal
4088  *	0 : not equal
4089  */
4090 static int
4091 key_cmpspidx_exactly(
4092 	struct secpolicyindex *spidx0,
4093 	struct secpolicyindex *spidx1)
4094 {
4095 	/* sanity */
4096 	if (spidx0 == NULL && spidx1 == NULL)
4097 		return 1;
4098 
4099 	if (spidx0 == NULL || spidx1 == NULL)
4100 		return 0;
4101 
4102 	if (spidx0->prefs != spidx1->prefs
4103 	 || spidx0->prefd != spidx1->prefd
4104 	 || spidx0->ul_proto != spidx1->ul_proto)
4105 		return 0;
4106 
4107 	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4108 	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4109 }
4110 
4111 /*
4112  * compare two secindex structure with mask.
4113  * IN:
4114  *	spidx0: source, it is often in SPD.
4115  *	spidx1: object, it is often from IP header.
4116  * OUT:
4117  *	1 : equal
4118  *	0 : not equal
4119  */
4120 static int
4121 key_cmpspidx_withmask(
4122 	struct secpolicyindex *spidx0,
4123 	struct secpolicyindex *spidx1)
4124 {
4125 	/* sanity */
4126 	if (spidx0 == NULL && spidx1 == NULL)
4127 		return 1;
4128 
4129 	if (spidx0 == NULL || spidx1 == NULL)
4130 		return 0;
4131 
4132 	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4133 	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4134 	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4135 	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4136 		return 0;
4137 
4138 	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4139 	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4140 	 && spidx0->ul_proto != spidx1->ul_proto)
4141 		return 0;
4142 
4143 	switch (spidx0->src.sa.sa_family) {
4144 	case AF_INET:
4145 		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4146 		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4147 			return 0;
4148 		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4149 		    &spidx1->src.sin.sin_addr, spidx0->prefs))
4150 			return 0;
4151 		break;
4152 	case AF_INET6:
4153 		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4154 		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4155 			return 0;
4156 		/*
4157 		 * scope_id check. if sin6_scope_id is 0, we regard it
4158 		 * as a wildcard scope, which matches any scope zone ID.
4159 		 */
4160 		if (spidx0->src.sin6.sin6_scope_id &&
4161 		    spidx1->src.sin6.sin6_scope_id &&
4162 		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4163 			return 0;
4164 		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4165 		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4166 			return 0;
4167 		break;
4168 	default:
4169 		/* XXX */
4170 		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4171 			return 0;
4172 		break;
4173 	}
4174 
4175 	switch (spidx0->dst.sa.sa_family) {
4176 	case AF_INET:
4177 		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4178 		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4179 			return 0;
4180 		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4181 		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
4182 			return 0;
4183 		break;
4184 	case AF_INET6:
4185 		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4186 		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4187 			return 0;
4188 		/*
4189 		 * scope_id check. if sin6_scope_id is 0, we regard it
4190 		 * as a wildcard scope, which matches any scope zone ID.
4191 		 */
4192 		if (spidx0->dst.sin6.sin6_scope_id &&
4193 		    spidx1->dst.sin6.sin6_scope_id &&
4194 		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4195 			return 0;
4196 		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4197 		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4198 			return 0;
4199 		break;
4200 	default:
4201 		/* XXX */
4202 		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4203 			return 0;
4204 		break;
4205 	}
4206 
4207 	/* XXX Do we check other field ?  e.g. flowinfo */
4208 
4209 	return 1;
4210 }
4211 
4212 /* returns 0 on match */
4213 static int
4214 key_sockaddrcmp(
4215 	const struct sockaddr *sa1,
4216 	const struct sockaddr *sa2,
4217 	int port)
4218 {
4219 #ifdef satosin
4220 #undef satosin
4221 #endif
4222 #define satosin(s) ((const struct sockaddr_in *)s)
4223 #ifdef satosin6
4224 #undef satosin6
4225 #endif
4226 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4227 	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4228 		return 1;
4229 
4230 	switch (sa1->sa_family) {
4231 	case AF_INET:
4232 		if (sa1->sa_len != sizeof(struct sockaddr_in))
4233 			return 1;
4234 		if (satosin(sa1)->sin_addr.s_addr !=
4235 		    satosin(sa2)->sin_addr.s_addr) {
4236 			return 1;
4237 		}
4238 		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4239 			return 1;
4240 		break;
4241 	case AF_INET6:
4242 		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4243 			return 1;	/*EINVAL*/
4244 		if (satosin6(sa1)->sin6_scope_id !=
4245 		    satosin6(sa2)->sin6_scope_id) {
4246 			return 1;
4247 		}
4248 		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4249 		    &satosin6(sa2)->sin6_addr)) {
4250 			return 1;
4251 		}
4252 		if (port &&
4253 		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4254 			return 1;
4255 		}
4256 		break;
4257 	default:
4258 		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4259 			return 1;
4260 		break;
4261 	}
4262 
4263 	return 0;
4264 #undef satosin
4265 #undef satosin6
4266 }
4267 
4268 /*
4269  * compare two buffers with mask.
4270  * IN:
4271  *	addr1: source
4272  *	addr2: object
4273  *	bits:  Number of bits to compare
4274  * OUT:
4275  *	1 : equal
4276  *	0 : not equal
4277  */
4278 static int
4279 key_bbcmp(const void *a1, const void *a2, u_int bits)
4280 {
4281 	const unsigned char *p1 = a1;
4282 	const unsigned char *p2 = a2;
4283 
4284 	/* XXX: This could be considerably faster if we compare a word
4285 	 * at a time, but it is complicated on LSB Endian machines */
4286 
4287 	/* Handle null pointers */
4288 	if (p1 == NULL || p2 == NULL)
4289 		return (p1 == p2);
4290 
4291 	while (bits >= 8) {
4292 		if (*p1++ != *p2++)
4293 			return 0;
4294 		bits -= 8;
4295 	}
4296 
4297 	if (bits > 0) {
4298 		u_int8_t mask = ~((1<<(8-bits))-1);
4299 		if ((*p1 & mask) != (*p2 & mask))
4300 			return 0;
4301 	}
4302 	return 1;	/* Match! */
4303 }
4304 
4305 static void
4306 key_flush_spd(time_t now)
4307 {
4308 	static u_int16_t sptree_scangen = 0;
4309 	u_int16_t gen = sptree_scangen++;
4310 	struct secpolicy *sp;
4311 	u_int dir;
4312 
4313 	/* SPD */
4314 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4315 restart:
4316 		SPTREE_LOCK();
4317 		LIST_FOREACH(sp, &V_sptree[dir], chain) {
4318 			if (sp->scangen == gen)		/* previously handled */
4319 				continue;
4320 			sp->scangen = gen;
4321 			if (sp->state == IPSEC_SPSTATE_DEAD &&
4322 			    sp->refcnt == 1) {
4323 				/*
4324 				 * Ensure that we only decrease refcnt once,
4325 				 * when we're the last consumer.
4326 				 * Directly call SP_DELREF/key_delsp instead
4327 				 * of KEY_FREESP to avoid unlocking/relocking
4328 				 * SPTREE_LOCK before key_delsp: may refcnt
4329 				 * be increased again during that time ?
4330 				 * NB: also clean entries created by
4331 				 * key_spdflush
4332 				 */
4333 				SP_DELREF(sp);
4334 				key_delsp(sp);
4335 				SPTREE_UNLOCK();
4336 				goto restart;
4337 			}
4338 			if (sp->lifetime == 0 && sp->validtime == 0)
4339 				continue;
4340 			if ((sp->lifetime && now - sp->created > sp->lifetime)
4341 			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4342 				sp->state = IPSEC_SPSTATE_DEAD;
4343 				SPTREE_UNLOCK();
4344 				key_spdexpire(sp);
4345 				goto restart;
4346 			}
4347 		}
4348 		SPTREE_UNLOCK();
4349 	}
4350 }
4351 
4352 static void
4353 key_flush_sad(time_t now)
4354 {
4355 	struct secashead *sah, *nextsah;
4356 	struct secasvar *sav, *nextsav;
4357 
4358 	/* SAD */
4359 	SAHTREE_LOCK();
4360 	LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4361 		/* if sah has been dead, then delete it and process next sah. */
4362 		if (sah->state == SADB_SASTATE_DEAD) {
4363 			key_delsah(sah);
4364 			continue;
4365 		}
4366 
4367 		/* if LARVAL entry doesn't become MATURE, delete it. */
4368 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4369 			/* Need to also check refcnt for a larval SA ??? */
4370 			if (now - sav->created > V_key_larval_lifetime)
4371 				KEY_FREESAV(&sav);
4372 		}
4373 
4374 		/*
4375 		 * check MATURE entry to start to send expire message
4376 		 * whether or not.
4377 		 */
4378 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4379 			/* we don't need to check. */
4380 			if (sav->lft_s == NULL)
4381 				continue;
4382 
4383 			/* sanity check */
4384 			if (sav->lft_c == NULL) {
4385 				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4386 					"time, why?\n", __func__));
4387 				continue;
4388 			}
4389 
4390 			/* check SOFT lifetime */
4391 			if (sav->lft_s->addtime != 0 &&
4392 			    now - sav->created > sav->lft_s->addtime) {
4393 				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4394 				/*
4395 				 * Actually, only send expire message if
4396 				 * SA has been used, as it was done before,
4397 				 * but should we always send such message,
4398 				 * and let IKE daemon decide if it should be
4399 				 * renegotiated or not ?
4400 				 * XXX expire message will actually NOT be
4401 				 * sent if SA is only used after soft
4402 				 * lifetime has been reached, see below
4403 				 * (DYING state)
4404 				 */
4405 				if (sav->lft_c->usetime != 0)
4406 					key_expire(sav);
4407 			}
4408 			/* check SOFT lifetime by bytes */
4409 			/*
4410 			 * XXX I don't know the way to delete this SA
4411 			 * when new SA is installed.  Caution when it's
4412 			 * installed too big lifetime by time.
4413 			 */
4414 			else if (sav->lft_s->bytes != 0 &&
4415 			    sav->lft_s->bytes < sav->lft_c->bytes) {
4416 
4417 				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4418 				/*
4419 				 * XXX If we keep to send expire
4420 				 * message in the status of
4421 				 * DYING. Do remove below code.
4422 				 */
4423 				key_expire(sav);
4424 			}
4425 		}
4426 
4427 		/* check DYING entry to change status to DEAD. */
4428 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4429 			/* we don't need to check. */
4430 			if (sav->lft_h == NULL)
4431 				continue;
4432 
4433 			/* sanity check */
4434 			if (sav->lft_c == NULL) {
4435 				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4436 					"time, why?\n", __func__));
4437 				continue;
4438 			}
4439 
4440 			if (sav->lft_h->addtime != 0 &&
4441 			    now - sav->created > sav->lft_h->addtime) {
4442 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4443 				KEY_FREESAV(&sav);
4444 			}
4445 #if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4446 			else if (sav->lft_s != NULL
4447 			      && sav->lft_s->addtime != 0
4448 			      && now - sav->created > sav->lft_s->addtime) {
4449 				/*
4450 				 * XXX: should be checked to be
4451 				 * installed the valid SA.
4452 				 */
4453 
4454 				/*
4455 				 * If there is no SA then sending
4456 				 * expire message.
4457 				 */
4458 				key_expire(sav);
4459 			}
4460 #endif
4461 			/* check HARD lifetime by bytes */
4462 			else if (sav->lft_h->bytes != 0 &&
4463 			    sav->lft_h->bytes < sav->lft_c->bytes) {
4464 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4465 				KEY_FREESAV(&sav);
4466 			}
4467 		}
4468 
4469 		/* delete entry in DEAD */
4470 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4471 			/* sanity check */
4472 			if (sav->state != SADB_SASTATE_DEAD) {
4473 				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4474 					"(queue: %d SA: %d): kill it anyway\n",
4475 					__func__,
4476 					SADB_SASTATE_DEAD, sav->state));
4477 			}
4478 			/*
4479 			 * do not call key_freesav() here.
4480 			 * sav should already be freed, and sav->refcnt
4481 			 * shows other references to sav
4482 			 * (such as from SPD).
4483 			 */
4484 		}
4485 	}
4486 	SAHTREE_UNLOCK();
4487 }
4488 
4489 static void
4490 key_flush_acq(time_t now)
4491 {
4492 	struct secacq *acq, *nextacq;
4493 
4494 	/* ACQ tree */
4495 	ACQ_LOCK();
4496 	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4497 		nextacq = LIST_NEXT(acq, chain);
4498 		if (now - acq->created > V_key_blockacq_lifetime
4499 		 && __LIST_CHAINED(acq)) {
4500 			LIST_REMOVE(acq, chain);
4501 			free(acq, M_IPSEC_SAQ);
4502 		}
4503 	}
4504 	ACQ_UNLOCK();
4505 }
4506 
4507 static void
4508 key_flush_spacq(time_t now)
4509 {
4510 	struct secspacq *acq, *nextacq;
4511 
4512 	/* SP ACQ tree */
4513 	SPACQ_LOCK();
4514 	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4515 		nextacq = LIST_NEXT(acq, chain);
4516 		if (now - acq->created > V_key_blockacq_lifetime
4517 		 && __LIST_CHAINED(acq)) {
4518 			LIST_REMOVE(acq, chain);
4519 			free(acq, M_IPSEC_SAQ);
4520 		}
4521 	}
4522 	SPACQ_UNLOCK();
4523 }
4524 
4525 /*
4526  * time handler.
4527  * scanning SPD and SAD to check status for each entries,
4528  * and do to remove or to expire.
4529  * XXX: year 2038 problem may remain.
4530  */
4531 void
4532 key_timehandler(void)
4533 {
4534 	VNET_ITERATOR_DECL(vnet_iter);
4535 	time_t now = time_second;
4536 
4537 	VNET_LIST_RLOCK_NOSLEEP();
4538 	VNET_FOREACH(vnet_iter) {
4539 		CURVNET_SET(vnet_iter);
4540 		key_flush_spd(now);
4541 		key_flush_sad(now);
4542 		key_flush_acq(now);
4543 		key_flush_spacq(now);
4544 		CURVNET_RESTORE();
4545 	}
4546 	VNET_LIST_RUNLOCK_NOSLEEP();
4547 
4548 #ifndef IPSEC_DEBUG2
4549 	/* do exchange to tick time !! */
4550 	(void)timeout((void *)key_timehandler, (void *)0, hz);
4551 #endif /* IPSEC_DEBUG2 */
4552 }
4553 
4554 u_long
4555 key_random()
4556 {
4557 	u_long value;
4558 
4559 	key_randomfill(&value, sizeof(value));
4560 	return value;
4561 }
4562 
4563 void
4564 key_randomfill(p, l)
4565 	void *p;
4566 	size_t l;
4567 {
4568 	size_t n;
4569 	u_long v;
4570 	static int warn = 1;
4571 
4572 	n = 0;
4573 	n = (size_t)read_random(p, (u_int)l);
4574 	/* last resort */
4575 	while (n < l) {
4576 		v = random();
4577 		bcopy(&v, (u_int8_t *)p + n,
4578 		    l - n < sizeof(v) ? l - n : sizeof(v));
4579 		n += sizeof(v);
4580 
4581 		if (warn) {
4582 			printf("WARNING: pseudo-random number generator "
4583 			    "used for IPsec processing\n");
4584 			warn = 0;
4585 		}
4586 	}
4587 }
4588 
4589 /*
4590  * map SADB_SATYPE_* to IPPROTO_*.
4591  * if satype == SADB_SATYPE then satype is mapped to ~0.
4592  * OUT:
4593  *	0: invalid satype.
4594  */
4595 static u_int16_t
4596 key_satype2proto(u_int8_t satype)
4597 {
4598 	switch (satype) {
4599 	case SADB_SATYPE_UNSPEC:
4600 		return IPSEC_PROTO_ANY;
4601 	case SADB_SATYPE_AH:
4602 		return IPPROTO_AH;
4603 	case SADB_SATYPE_ESP:
4604 		return IPPROTO_ESP;
4605 	case SADB_X_SATYPE_IPCOMP:
4606 		return IPPROTO_IPCOMP;
4607 	case SADB_X_SATYPE_TCPSIGNATURE:
4608 		return IPPROTO_TCP;
4609 	default:
4610 		return 0;
4611 	}
4612 	/* NOTREACHED */
4613 }
4614 
4615 /*
4616  * map IPPROTO_* to SADB_SATYPE_*
4617  * OUT:
4618  *	0: invalid protocol type.
4619  */
4620 static u_int8_t
4621 key_proto2satype(u_int16_t proto)
4622 {
4623 	switch (proto) {
4624 	case IPPROTO_AH:
4625 		return SADB_SATYPE_AH;
4626 	case IPPROTO_ESP:
4627 		return SADB_SATYPE_ESP;
4628 	case IPPROTO_IPCOMP:
4629 		return SADB_X_SATYPE_IPCOMP;
4630 	case IPPROTO_TCP:
4631 		return SADB_X_SATYPE_TCPSIGNATURE;
4632 	default:
4633 		return 0;
4634 	}
4635 	/* NOTREACHED */
4636 }
4637 
4638 /* %%% PF_KEY */
4639 /*
4640  * SADB_GETSPI processing is to receive
4641  *	<base, (SA2), src address, dst address, (SPI range)>
4642  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4643  * tree with the status of LARVAL, and send
4644  *	<base, SA(*), address(SD)>
4645  * to the IKMPd.
4646  *
4647  * IN:	mhp: pointer to the pointer to each header.
4648  * OUT:	NULL if fail.
4649  *	other if success, return pointer to the message to send.
4650  */
4651 static int
4652 key_getspi(so, m, mhp)
4653 	struct socket *so;
4654 	struct mbuf *m;
4655 	const struct sadb_msghdr *mhp;
4656 {
4657 	struct sadb_address *src0, *dst0;
4658 	struct secasindex saidx;
4659 	struct secashead *newsah;
4660 	struct secasvar *newsav;
4661 	u_int8_t proto;
4662 	u_int32_t spi;
4663 	u_int8_t mode;
4664 	u_int32_t reqid;
4665 	int error;
4666 
4667 	IPSEC_ASSERT(so != NULL, ("null socket"));
4668 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4669 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4670 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4671 
4672 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4673 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4674 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4675 			__func__));
4676 		return key_senderror(so, m, EINVAL);
4677 	}
4678 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4679 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4680 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4681 			__func__));
4682 		return key_senderror(so, m, EINVAL);
4683 	}
4684 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4685 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4686 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4687 	} else {
4688 		mode = IPSEC_MODE_ANY;
4689 		reqid = 0;
4690 	}
4691 
4692 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4693 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4694 
4695 	/* map satype to proto */
4696 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4697 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4698 			__func__));
4699 		return key_senderror(so, m, EINVAL);
4700 	}
4701 
4702 	/*
4703 	 * Make sure the port numbers are zero.
4704 	 * In case of NAT-T we will update them later if needed.
4705 	 */
4706 	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4707 	case AF_INET:
4708 		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4709 		    sizeof(struct sockaddr_in))
4710 			return key_senderror(so, m, EINVAL);
4711 		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4712 		break;
4713 	case AF_INET6:
4714 		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4715 		    sizeof(struct sockaddr_in6))
4716 			return key_senderror(so, m, EINVAL);
4717 		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4718 		break;
4719 	default:
4720 		; /*???*/
4721 	}
4722 	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4723 	case AF_INET:
4724 		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4725 		    sizeof(struct sockaddr_in))
4726 			return key_senderror(so, m, EINVAL);
4727 		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4728 		break;
4729 	case AF_INET6:
4730 		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4731 		    sizeof(struct sockaddr_in6))
4732 			return key_senderror(so, m, EINVAL);
4733 		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4734 		break;
4735 	default:
4736 		; /*???*/
4737 	}
4738 
4739 	/* XXX boundary check against sa_len */
4740 	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4741 
4742 #ifdef IPSEC_NAT_T
4743 	/*
4744 	 * Handle NAT-T info if present.
4745 	 * We made sure the port numbers are zero above, so we do
4746 	 * not have to worry in case we do not update them.
4747 	 */
4748 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4749 		ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4750 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4751 		ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4752 
4753 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4754 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4755 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4756 		struct sadb_x_nat_t_type *type;
4757 		struct sadb_x_nat_t_port *sport, *dport;
4758 
4759 		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4760 		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4761 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4762 			ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4763 			    "passed.\n", __func__));
4764 			return key_senderror(so, m, EINVAL);
4765 		}
4766 
4767 		sport = (struct sadb_x_nat_t_port *)
4768 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4769 		dport = (struct sadb_x_nat_t_port *)
4770 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4771 
4772 		if (sport)
4773 			KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4774 		if (dport)
4775 			KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4776 	}
4777 #endif
4778 
4779 	/* SPI allocation */
4780 	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4781 	                       &saidx);
4782 	if (spi == 0)
4783 		return key_senderror(so, m, EINVAL);
4784 
4785 	/* get a SA index */
4786 	if ((newsah = key_getsah(&saidx)) == NULL) {
4787 		/* create a new SA index */
4788 		if ((newsah = key_newsah(&saidx)) == NULL) {
4789 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4790 			return key_senderror(so, m, ENOBUFS);
4791 		}
4792 	}
4793 
4794 	/* get a new SA */
4795 	/* XXX rewrite */
4796 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4797 	if (newsav == NULL) {
4798 		/* XXX don't free new SA index allocated in above. */
4799 		return key_senderror(so, m, error);
4800 	}
4801 
4802 	/* set spi */
4803 	newsav->spi = htonl(spi);
4804 
4805 	/* delete the entry in acqtree */
4806 	if (mhp->msg->sadb_msg_seq != 0) {
4807 		struct secacq *acq;
4808 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4809 			/* reset counter in order to deletion by timehandler. */
4810 			acq->created = time_second;
4811 			acq->count = 0;
4812 		}
4813     	}
4814 
4815     {
4816 	struct mbuf *n, *nn;
4817 	struct sadb_sa *m_sa;
4818 	struct sadb_msg *newmsg;
4819 	int off, len;
4820 
4821 	/* create new sadb_msg to reply. */
4822 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4823 	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4824 
4825 	MGETHDR(n, M_DONTWAIT, MT_DATA);
4826 	if (len > MHLEN) {
4827 		MCLGET(n, M_DONTWAIT);
4828 		if ((n->m_flags & M_EXT) == 0) {
4829 			m_freem(n);
4830 			n = NULL;
4831 		}
4832 	}
4833 	if (!n)
4834 		return key_senderror(so, m, ENOBUFS);
4835 
4836 	n->m_len = len;
4837 	n->m_next = NULL;
4838 	off = 0;
4839 
4840 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4841 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4842 
4843 	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4844 	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4845 	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4846 	m_sa->sadb_sa_spi = htonl(spi);
4847 	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4848 
4849 	IPSEC_ASSERT(off == len,
4850 		("length inconsistency (off %u len %u)", off, len));
4851 
4852 	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4853 	    SADB_EXT_ADDRESS_DST);
4854 	if (!n->m_next) {
4855 		m_freem(n);
4856 		return key_senderror(so, m, ENOBUFS);
4857 	}
4858 
4859 	if (n->m_len < sizeof(struct sadb_msg)) {
4860 		n = m_pullup(n, sizeof(struct sadb_msg));
4861 		if (n == NULL)
4862 			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4863 	}
4864 
4865 	n->m_pkthdr.len = 0;
4866 	for (nn = n; nn; nn = nn->m_next)
4867 		n->m_pkthdr.len += nn->m_len;
4868 
4869 	newmsg = mtod(n, struct sadb_msg *);
4870 	newmsg->sadb_msg_seq = newsav->seq;
4871 	newmsg->sadb_msg_errno = 0;
4872 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4873 
4874 	m_freem(m);
4875 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4876     }
4877 }
4878 
4879 /*
4880  * allocating new SPI
4881  * called by key_getspi().
4882  * OUT:
4883  *	0:	failure.
4884  *	others: success.
4885  */
4886 static u_int32_t
4887 key_do_getnewspi(spirange, saidx)
4888 	struct sadb_spirange *spirange;
4889 	struct secasindex *saidx;
4890 {
4891 	u_int32_t newspi;
4892 	u_int32_t min, max;
4893 	int count = V_key_spi_trycnt;
4894 
4895 	/* set spi range to allocate */
4896 	if (spirange != NULL) {
4897 		min = spirange->sadb_spirange_min;
4898 		max = spirange->sadb_spirange_max;
4899 	} else {
4900 		min = V_key_spi_minval;
4901 		max = V_key_spi_maxval;
4902 	}
4903 	/* IPCOMP needs 2-byte SPI */
4904 	if (saidx->proto == IPPROTO_IPCOMP) {
4905 		u_int32_t t;
4906 		if (min >= 0x10000)
4907 			min = 0xffff;
4908 		if (max >= 0x10000)
4909 			max = 0xffff;
4910 		if (min > max) {
4911 			t = min; min = max; max = t;
4912 		}
4913 	}
4914 
4915 	if (min == max) {
4916 		if (key_checkspidup(saidx, min) != NULL) {
4917 			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4918 				__func__, min));
4919 			return 0;
4920 		}
4921 
4922 		count--; /* taking one cost. */
4923 		newspi = min;
4924 
4925 	} else {
4926 
4927 		/* init SPI */
4928 		newspi = 0;
4929 
4930 		/* when requesting to allocate spi ranged */
4931 		while (count--) {
4932 			/* generate pseudo-random SPI value ranged. */
4933 			newspi = min + (key_random() % (max - min + 1));
4934 
4935 			if (key_checkspidup(saidx, newspi) == NULL)
4936 				break;
4937 		}
4938 
4939 		if (count == 0 || newspi == 0) {
4940 			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4941 				__func__));
4942 			return 0;
4943 		}
4944 	}
4945 
4946 	/* statistics */
4947 	keystat.getspi_count =
4948 		(keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4949 
4950 	return newspi;
4951 }
4952 
4953 /*
4954  * SADB_UPDATE processing
4955  * receive
4956  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4957  *       key(AE), (identity(SD),) (sensitivity)>
4958  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4959  * and send
4960  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4961  *       (identity(SD),) (sensitivity)>
4962  * to the ikmpd.
4963  *
4964  * m will always be freed.
4965  */
4966 static int
4967 key_update(so, m, mhp)
4968 	struct socket *so;
4969 	struct mbuf *m;
4970 	const struct sadb_msghdr *mhp;
4971 {
4972 	struct sadb_sa *sa0;
4973 	struct sadb_address *src0, *dst0;
4974 #ifdef IPSEC_NAT_T
4975 	struct sadb_x_nat_t_type *type;
4976 	struct sadb_x_nat_t_port *sport, *dport;
4977 	struct sadb_address *iaddr, *raddr;
4978 	struct sadb_x_nat_t_frag *frag;
4979 #endif
4980 	struct secasindex saidx;
4981 	struct secashead *sah;
4982 	struct secasvar *sav;
4983 	u_int16_t proto;
4984 	u_int8_t mode;
4985 	u_int32_t reqid;
4986 	int error;
4987 
4988 	IPSEC_ASSERT(so != NULL, ("null socket"));
4989 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4990 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4991 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4992 
4993 	/* map satype to proto */
4994 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4995 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4996 			__func__));
4997 		return key_senderror(so, m, EINVAL);
4998 	}
4999 
5000 	if (mhp->ext[SADB_EXT_SA] == NULL ||
5001 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5002 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5003 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5004 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5005 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5006 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5007 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5008 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5009 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5010 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5011 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5012 			__func__));
5013 		return key_senderror(so, m, EINVAL);
5014 	}
5015 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5016 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5017 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5018 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5019 			__func__));
5020 		return key_senderror(so, m, EINVAL);
5021 	}
5022 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5023 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5024 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5025 	} else {
5026 		mode = IPSEC_MODE_ANY;
5027 		reqid = 0;
5028 	}
5029 	/* XXX boundary checking for other extensions */
5030 
5031 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5032 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5033 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5034 
5035 	/* XXX boundary check against sa_len */
5036 	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5037 
5038 	/*
5039 	 * Make sure the port numbers are zero.
5040 	 * In case of NAT-T we will update them later if needed.
5041 	 */
5042 	KEY_PORTTOSADDR(&saidx.src, 0);
5043 	KEY_PORTTOSADDR(&saidx.dst, 0);
5044 
5045 #ifdef IPSEC_NAT_T
5046 	/*
5047 	 * Handle NAT-T info if present.
5048 	 */
5049 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5050 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5051 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5052 
5053 		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5054 		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5055 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5056 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5057 			    __func__));
5058 			return key_senderror(so, m, EINVAL);
5059 		}
5060 
5061 		type = (struct sadb_x_nat_t_type *)
5062 		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5063 		sport = (struct sadb_x_nat_t_port *)
5064 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5065 		dport = (struct sadb_x_nat_t_port *)
5066 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5067 	} else {
5068 		type = 0;
5069 		sport = dport = 0;
5070 	}
5071 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5072 	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5073 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5074 		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5075 			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5076 			    __func__));
5077 			return key_senderror(so, m, EINVAL);
5078 		}
5079 		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5080 		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5081 		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5082 	} else {
5083 		iaddr = raddr = NULL;
5084 	}
5085 	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5086 		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5087 			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5088 			    __func__));
5089 			return key_senderror(so, m, EINVAL);
5090 		}
5091 		frag = (struct sadb_x_nat_t_frag *)
5092 		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5093 	} else {
5094 		frag = 0;
5095 	}
5096 #endif
5097 
5098 	/* get a SA header */
5099 	if ((sah = key_getsah(&saidx)) == NULL) {
5100 		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
5101 		return key_senderror(so, m, ENOENT);
5102 	}
5103 
5104 	/* set spidx if there */
5105 	/* XXX rewrite */
5106 	error = key_setident(sah, m, mhp);
5107 	if (error)
5108 		return key_senderror(so, m, error);
5109 
5110 	/* find a SA with sequence number. */
5111 #ifdef IPSEC_DOSEQCHECK
5112 	if (mhp->msg->sadb_msg_seq != 0
5113 	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
5114 		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
5115 			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
5116 		return key_senderror(so, m, ENOENT);
5117 	}
5118 #else
5119 	SAHTREE_LOCK();
5120 	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5121 	SAHTREE_UNLOCK();
5122 	if (sav == NULL) {
5123 		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
5124 			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5125 		return key_senderror(so, m, EINVAL);
5126 	}
5127 #endif
5128 
5129 	/* validity check */
5130 	if (sav->sah->saidx.proto != proto) {
5131 		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
5132 			"(DB=%u param=%u)\n", __func__,
5133 			sav->sah->saidx.proto, proto));
5134 		return key_senderror(so, m, EINVAL);
5135 	}
5136 #ifdef IPSEC_DOSEQCHECK
5137 	if (sav->spi != sa0->sadb_sa_spi) {
5138 		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
5139 		    __func__,
5140 		    (u_int32_t)ntohl(sav->spi),
5141 		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5142 		return key_senderror(so, m, EINVAL);
5143 	}
5144 #endif
5145 	if (sav->pid != mhp->msg->sadb_msg_pid) {
5146 		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
5147 		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
5148 		return key_senderror(so, m, EINVAL);
5149 	}
5150 
5151 	/* copy sav values */
5152 	error = key_setsaval(sav, m, mhp);
5153 	if (error) {
5154 		KEY_FREESAV(&sav);
5155 		return key_senderror(so, m, error);
5156 	}
5157 
5158 	/* check SA values to be mature. */
5159 	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5160 		KEY_FREESAV(&sav);
5161 		return key_senderror(so, m, 0);
5162 	}
5163 
5164 #ifdef IPSEC_NAT_T
5165 	/*
5166 	 * Handle more NAT-T info if present,
5167 	 * now that we have a sav to fill.
5168 	 */
5169 	if (type)
5170 		sav->natt_type = type->sadb_x_nat_t_type_type;
5171 
5172 	if (sport)
5173 		KEY_PORTTOSADDR(&sav->sah->saidx.src,
5174 		    sport->sadb_x_nat_t_port_port);
5175 	if (dport)
5176 		KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5177 		    dport->sadb_x_nat_t_port_port);
5178 
5179 #if 0
5180 	/*
5181 	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5182 	 * We should actually check for a minimum MTU here, if we
5183 	 * want to support it in ip_output.
5184 	 */
5185 	if (frag)
5186 		sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5187 #endif
5188 #endif
5189 
5190     {
5191 	struct mbuf *n;
5192 
5193 	/* set msg buf from mhp */
5194 	n = key_getmsgbuf_x1(m, mhp);
5195 	if (n == NULL) {
5196 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5197 		return key_senderror(so, m, ENOBUFS);
5198 	}
5199 
5200 	m_freem(m);
5201 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5202     }
5203 }
5204 
5205 /*
5206  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5207  * only called by key_update().
5208  * OUT:
5209  *	NULL	: not found
5210  *	others	: found, pointer to a SA.
5211  */
5212 #ifdef IPSEC_DOSEQCHECK
5213 static struct secasvar *
5214 key_getsavbyseq(sah, seq)
5215 	struct secashead *sah;
5216 	u_int32_t seq;
5217 {
5218 	struct secasvar *sav;
5219 	u_int state;
5220 
5221 	state = SADB_SASTATE_LARVAL;
5222 
5223 	/* search SAD with sequence number ? */
5224 	LIST_FOREACH(sav, &sah->savtree[state], chain) {
5225 
5226 		KEY_CHKSASTATE(state, sav->state, __func__);
5227 
5228 		if (sav->seq == seq) {
5229 			sa_addref(sav);
5230 			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5231 				printf("DP %s cause refcnt++:%d SA:%p\n",
5232 					__func__, sav->refcnt, sav));
5233 			return sav;
5234 		}
5235 	}
5236 
5237 	return NULL;
5238 }
5239 #endif
5240 
5241 /*
5242  * SADB_ADD processing
5243  * add an entry to SA database, when received
5244  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5245  *       key(AE), (identity(SD),) (sensitivity)>
5246  * from the ikmpd,
5247  * and send
5248  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5249  *       (identity(SD),) (sensitivity)>
5250  * to the ikmpd.
5251  *
5252  * IGNORE identity and sensitivity messages.
5253  *
5254  * m will always be freed.
5255  */
5256 static int
5257 key_add(so, m, mhp)
5258 	struct socket *so;
5259 	struct mbuf *m;
5260 	const struct sadb_msghdr *mhp;
5261 {
5262 	struct sadb_sa *sa0;
5263 	struct sadb_address *src0, *dst0;
5264 #ifdef IPSEC_NAT_T
5265 	struct sadb_x_nat_t_type *type;
5266 	struct sadb_address *iaddr, *raddr;
5267 	struct sadb_x_nat_t_frag *frag;
5268 #endif
5269 	struct secasindex saidx;
5270 	struct secashead *newsah;
5271 	struct secasvar *newsav;
5272 	u_int16_t proto;
5273 	u_int8_t mode;
5274 	u_int32_t reqid;
5275 	int error;
5276 
5277 	IPSEC_ASSERT(so != NULL, ("null socket"));
5278 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5279 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5280 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5281 
5282 	/* map satype to proto */
5283 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5284 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5285 			__func__));
5286 		return key_senderror(so, m, EINVAL);
5287 	}
5288 
5289 	if (mhp->ext[SADB_EXT_SA] == NULL ||
5290 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5291 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5292 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5293 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5294 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5295 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5296 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5297 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5298 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5299 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5300 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5301 			__func__));
5302 		return key_senderror(so, m, EINVAL);
5303 	}
5304 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5305 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5306 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5307 		/* XXX need more */
5308 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5309 			__func__));
5310 		return key_senderror(so, m, EINVAL);
5311 	}
5312 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5313 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5314 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5315 	} else {
5316 		mode = IPSEC_MODE_ANY;
5317 		reqid = 0;
5318 	}
5319 
5320 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5321 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5322 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5323 
5324 	/* XXX boundary check against sa_len */
5325 	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5326 
5327 	/*
5328 	 * Make sure the port numbers are zero.
5329 	 * In case of NAT-T we will update them later if needed.
5330 	 */
5331 	KEY_PORTTOSADDR(&saidx.src, 0);
5332 	KEY_PORTTOSADDR(&saidx.dst, 0);
5333 
5334 #ifdef IPSEC_NAT_T
5335 	/*
5336 	 * Handle NAT-T info if present.
5337 	 */
5338 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5339 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5340 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5341 		struct sadb_x_nat_t_port *sport, *dport;
5342 
5343 		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5344 		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5345 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5346 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5347 			    __func__));
5348 			return key_senderror(so, m, EINVAL);
5349 		}
5350 
5351 		type = (struct sadb_x_nat_t_type *)
5352 		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5353 		sport = (struct sadb_x_nat_t_port *)
5354 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5355 		dport = (struct sadb_x_nat_t_port *)
5356 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5357 
5358 		if (sport)
5359 			KEY_PORTTOSADDR(&saidx.src,
5360 			    sport->sadb_x_nat_t_port_port);
5361 		if (dport)
5362 			KEY_PORTTOSADDR(&saidx.dst,
5363 			    dport->sadb_x_nat_t_port_port);
5364 	} else {
5365 		type = 0;
5366 	}
5367 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5368 	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5369 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5370 		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5371 			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5372 			    __func__));
5373 			return key_senderror(so, m, EINVAL);
5374 		}
5375 		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5376 		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5377 		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5378 	} else {
5379 		iaddr = raddr = NULL;
5380 	}
5381 	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5382 		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5383 			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5384 			    __func__));
5385 			return key_senderror(so, m, EINVAL);
5386 		}
5387 		frag = (struct sadb_x_nat_t_frag *)
5388 		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5389 	} else {
5390 		frag = 0;
5391 	}
5392 #endif
5393 
5394 	/* get a SA header */
5395 	if ((newsah = key_getsah(&saidx)) == NULL) {
5396 		/* create a new SA header */
5397 		if ((newsah = key_newsah(&saidx)) == NULL) {
5398 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5399 			return key_senderror(so, m, ENOBUFS);
5400 		}
5401 	}
5402 
5403 	/* set spidx if there */
5404 	/* XXX rewrite */
5405 	error = key_setident(newsah, m, mhp);
5406 	if (error) {
5407 		return key_senderror(so, m, error);
5408 	}
5409 
5410 	/* create new SA entry. */
5411 	/* We can create new SA only if SPI is differenct. */
5412 	SAHTREE_LOCK();
5413 	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5414 	SAHTREE_UNLOCK();
5415 	if (newsav != NULL) {
5416 		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5417 		return key_senderror(so, m, EEXIST);
5418 	}
5419 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5420 	if (newsav == NULL) {
5421 		return key_senderror(so, m, error);
5422 	}
5423 
5424 	/* check SA values to be mature. */
5425 	if ((error = key_mature(newsav)) != 0) {
5426 		KEY_FREESAV(&newsav);
5427 		return key_senderror(so, m, error);
5428 	}
5429 
5430 #ifdef IPSEC_NAT_T
5431 	/*
5432 	 * Handle more NAT-T info if present,
5433 	 * now that we have a sav to fill.
5434 	 */
5435 	if (type)
5436 		newsav->natt_type = type->sadb_x_nat_t_type_type;
5437 
5438 #if 0
5439 	/*
5440 	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5441 	 * We should actually check for a minimum MTU here, if we
5442 	 * want to support it in ip_output.
5443 	 */
5444 	if (frag)
5445 		newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5446 #endif
5447 #endif
5448 
5449 	/*
5450 	 * don't call key_freesav() here, as we would like to keep the SA
5451 	 * in the database on success.
5452 	 */
5453 
5454     {
5455 	struct mbuf *n;
5456 
5457 	/* set msg buf from mhp */
5458 	n = key_getmsgbuf_x1(m, mhp);
5459 	if (n == NULL) {
5460 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5461 		return key_senderror(so, m, ENOBUFS);
5462 	}
5463 
5464 	m_freem(m);
5465 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5466     }
5467 }
5468 
5469 /* m is retained */
5470 static int
5471 key_setident(sah, m, mhp)
5472 	struct secashead *sah;
5473 	struct mbuf *m;
5474 	const struct sadb_msghdr *mhp;
5475 {
5476 	const struct sadb_ident *idsrc, *iddst;
5477 	int idsrclen, iddstlen;
5478 
5479 	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5480 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5481 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5482 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5483 
5484 	/* don't make buffer if not there */
5485 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5486 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5487 		sah->idents = NULL;
5488 		sah->identd = NULL;
5489 		return 0;
5490 	}
5491 
5492 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5493 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5494 		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5495 		return EINVAL;
5496 	}
5497 
5498 	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5499 	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5500 	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5501 	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5502 
5503 	/* validity check */
5504 	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5505 		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5506 		return EINVAL;
5507 	}
5508 
5509 	switch (idsrc->sadb_ident_type) {
5510 	case SADB_IDENTTYPE_PREFIX:
5511 	case SADB_IDENTTYPE_FQDN:
5512 	case SADB_IDENTTYPE_USERFQDN:
5513 	default:
5514 		/* XXX do nothing */
5515 		sah->idents = NULL;
5516 		sah->identd = NULL;
5517 	 	return 0;
5518 	}
5519 
5520 	/* make structure */
5521 	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5522 	if (sah->idents == NULL) {
5523 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5524 		return ENOBUFS;
5525 	}
5526 	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5527 	if (sah->identd == NULL) {
5528 		free(sah->idents, M_IPSEC_MISC);
5529 		sah->idents = NULL;
5530 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5531 		return ENOBUFS;
5532 	}
5533 	sah->idents->type = idsrc->sadb_ident_type;
5534 	sah->idents->id = idsrc->sadb_ident_id;
5535 
5536 	sah->identd->type = iddst->sadb_ident_type;
5537 	sah->identd->id = iddst->sadb_ident_id;
5538 
5539 	return 0;
5540 }
5541 
5542 /*
5543  * m will not be freed on return.
5544  * it is caller's responsibility to free the result.
5545  */
5546 static struct mbuf *
5547 key_getmsgbuf_x1(m, mhp)
5548 	struct mbuf *m;
5549 	const struct sadb_msghdr *mhp;
5550 {
5551 	struct mbuf *n;
5552 
5553 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5554 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5555 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5556 
5557 	/* create new sadb_msg to reply. */
5558 	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5559 	    SADB_EXT_SA, SADB_X_EXT_SA2,
5560 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5561 	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5562 	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5563 	if (!n)
5564 		return NULL;
5565 
5566 	if (n->m_len < sizeof(struct sadb_msg)) {
5567 		n = m_pullup(n, sizeof(struct sadb_msg));
5568 		if (n == NULL)
5569 			return NULL;
5570 	}
5571 	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5572 	mtod(n, struct sadb_msg *)->sadb_msg_len =
5573 	    PFKEY_UNIT64(n->m_pkthdr.len);
5574 
5575 	return n;
5576 }
5577 
5578 static int key_delete_all __P((struct socket *, struct mbuf *,
5579 	const struct sadb_msghdr *, u_int16_t));
5580 
5581 /*
5582  * SADB_DELETE processing
5583  * receive
5584  *   <base, SA(*), address(SD)>
5585  * from the ikmpd, and set SADB_SASTATE_DEAD,
5586  * and send,
5587  *   <base, SA(*), address(SD)>
5588  * to the ikmpd.
5589  *
5590  * m will always be freed.
5591  */
5592 static int
5593 key_delete(so, m, mhp)
5594 	struct socket *so;
5595 	struct mbuf *m;
5596 	const struct sadb_msghdr *mhp;
5597 {
5598 	struct sadb_sa *sa0;
5599 	struct sadb_address *src0, *dst0;
5600 	struct secasindex saidx;
5601 	struct secashead *sah;
5602 	struct secasvar *sav = NULL;
5603 	u_int16_t proto;
5604 
5605 	IPSEC_ASSERT(so != NULL, ("null socket"));
5606 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5607 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5608 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5609 
5610 	/* map satype to proto */
5611 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5612 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5613 			__func__));
5614 		return key_senderror(so, m, EINVAL);
5615 	}
5616 
5617 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5618 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5619 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5620 			__func__));
5621 		return key_senderror(so, m, EINVAL);
5622 	}
5623 
5624 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5625 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5626 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5627 			__func__));
5628 		return key_senderror(so, m, EINVAL);
5629 	}
5630 
5631 	if (mhp->ext[SADB_EXT_SA] == NULL) {
5632 		/*
5633 		 * Caller wants us to delete all non-LARVAL SAs
5634 		 * that match the src/dst.  This is used during
5635 		 * IKE INITIAL-CONTACT.
5636 		 */
5637 		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5638 		return key_delete_all(so, m, mhp, proto);
5639 	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5640 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5641 			__func__));
5642 		return key_senderror(so, m, EINVAL);
5643 	}
5644 
5645 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5646 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5647 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5648 
5649 	/* XXX boundary check against sa_len */
5650 	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5651 
5652 	/*
5653 	 * Make sure the port numbers are zero.
5654 	 * In case of NAT-T we will update them later if needed.
5655 	 */
5656 	KEY_PORTTOSADDR(&saidx.src, 0);
5657 	KEY_PORTTOSADDR(&saidx.dst, 0);
5658 
5659 #ifdef IPSEC_NAT_T
5660 	/*
5661 	 * Handle NAT-T info if present.
5662 	 */
5663 	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5664 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5665 		struct sadb_x_nat_t_port *sport, *dport;
5666 
5667 		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5668 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5669 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5670 			    __func__));
5671 			return key_senderror(so, m, EINVAL);
5672 		}
5673 
5674 		sport = (struct sadb_x_nat_t_port *)
5675 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5676 		dport = (struct sadb_x_nat_t_port *)
5677 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5678 
5679 		if (sport)
5680 			KEY_PORTTOSADDR(&saidx.src,
5681 			    sport->sadb_x_nat_t_port_port);
5682 		if (dport)
5683 			KEY_PORTTOSADDR(&saidx.dst,
5684 			    dport->sadb_x_nat_t_port_port);
5685 	}
5686 #endif
5687 
5688 	/* get a SA header */
5689 	SAHTREE_LOCK();
5690 	LIST_FOREACH(sah, &V_sahtree, chain) {
5691 		if (sah->state == SADB_SASTATE_DEAD)
5692 			continue;
5693 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5694 			continue;
5695 
5696 		/* get a SA with SPI. */
5697 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5698 		if (sav)
5699 			break;
5700 	}
5701 	if (sah == NULL) {
5702 		SAHTREE_UNLOCK();
5703 		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5704 		return key_senderror(so, m, ENOENT);
5705 	}
5706 
5707 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5708 	KEY_FREESAV(&sav);
5709 	SAHTREE_UNLOCK();
5710 
5711     {
5712 	struct mbuf *n;
5713 	struct sadb_msg *newmsg;
5714 
5715 	/* create new sadb_msg to reply. */
5716 	/* XXX-BZ NAT-T extensions? */
5717 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5718 	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5719 	if (!n)
5720 		return key_senderror(so, m, ENOBUFS);
5721 
5722 	if (n->m_len < sizeof(struct sadb_msg)) {
5723 		n = m_pullup(n, sizeof(struct sadb_msg));
5724 		if (n == NULL)
5725 			return key_senderror(so, m, ENOBUFS);
5726 	}
5727 	newmsg = mtod(n, struct sadb_msg *);
5728 	newmsg->sadb_msg_errno = 0;
5729 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5730 
5731 	m_freem(m);
5732 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5733     }
5734 }
5735 
5736 /*
5737  * delete all SAs for src/dst.  Called from key_delete().
5738  */
5739 static int
5740 key_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5741     u_int16_t proto)
5742 {
5743 	struct sadb_address *src0, *dst0;
5744 	struct secasindex saidx;
5745 	struct secashead *sah;
5746 	struct secasvar *sav, *nextsav;
5747 	u_int stateidx, state;
5748 
5749 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5750 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5751 
5752 	/* XXX boundary check against sa_len */
5753 	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5754 
5755 	/*
5756 	 * Make sure the port numbers are zero.
5757 	 * In case of NAT-T we will update them later if needed.
5758 	 */
5759 	KEY_PORTTOSADDR(&saidx.src, 0);
5760 	KEY_PORTTOSADDR(&saidx.dst, 0);
5761 
5762 #ifdef IPSEC_NAT_T
5763 	/*
5764 	 * Handle NAT-T info if present.
5765 	 */
5766 
5767 	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5768 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5769 		struct sadb_x_nat_t_port *sport, *dport;
5770 
5771 		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5772 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5773 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5774 			    __func__));
5775 			return key_senderror(so, m, EINVAL);
5776 		}
5777 
5778 		sport = (struct sadb_x_nat_t_port *)
5779 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5780 		dport = (struct sadb_x_nat_t_port *)
5781 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5782 
5783 		if (sport)
5784 			KEY_PORTTOSADDR(&saidx.src,
5785 			    sport->sadb_x_nat_t_port_port);
5786 		if (dport)
5787 			KEY_PORTTOSADDR(&saidx.dst,
5788 			    dport->sadb_x_nat_t_port_port);
5789 	}
5790 #endif
5791 
5792 	SAHTREE_LOCK();
5793 	LIST_FOREACH(sah, &V_sahtree, chain) {
5794 		if (sah->state == SADB_SASTATE_DEAD)
5795 			continue;
5796 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5797 			continue;
5798 
5799 		/* Delete all non-LARVAL SAs. */
5800 		for (stateidx = 0;
5801 		     stateidx < _ARRAYLEN(saorder_state_alive);
5802 		     stateidx++) {
5803 			state = saorder_state_alive[stateidx];
5804 			if (state == SADB_SASTATE_LARVAL)
5805 				continue;
5806 			for (sav = LIST_FIRST(&sah->savtree[state]);
5807 			     sav != NULL; sav = nextsav) {
5808 				nextsav = LIST_NEXT(sav, chain);
5809 				/* sanity check */
5810 				if (sav->state != state) {
5811 					ipseclog((LOG_DEBUG, "%s: invalid "
5812 						"sav->state (queue %d SA %d)\n",
5813 						__func__, state, sav->state));
5814 					continue;
5815 				}
5816 
5817 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5818 				KEY_FREESAV(&sav);
5819 			}
5820 		}
5821 	}
5822 	SAHTREE_UNLOCK();
5823     {
5824 	struct mbuf *n;
5825 	struct sadb_msg *newmsg;
5826 
5827 	/* create new sadb_msg to reply. */
5828 	/* XXX-BZ NAT-T extensions? */
5829 	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5830 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5831 	if (!n)
5832 		return key_senderror(so, m, ENOBUFS);
5833 
5834 	if (n->m_len < sizeof(struct sadb_msg)) {
5835 		n = m_pullup(n, sizeof(struct sadb_msg));
5836 		if (n == NULL)
5837 			return key_senderror(so, m, ENOBUFS);
5838 	}
5839 	newmsg = mtod(n, struct sadb_msg *);
5840 	newmsg->sadb_msg_errno = 0;
5841 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5842 
5843 	m_freem(m);
5844 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5845     }
5846 }
5847 
5848 /*
5849  * SADB_GET processing
5850  * receive
5851  *   <base, SA(*), address(SD)>
5852  * from the ikmpd, and get a SP and a SA to respond,
5853  * and send,
5854  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5855  *       (identity(SD),) (sensitivity)>
5856  * to the ikmpd.
5857  *
5858  * m will always be freed.
5859  */
5860 static int
5861 key_get(so, m, mhp)
5862 	struct socket *so;
5863 	struct mbuf *m;
5864 	const struct sadb_msghdr *mhp;
5865 {
5866 	struct sadb_sa *sa0;
5867 	struct sadb_address *src0, *dst0;
5868 	struct secasindex saidx;
5869 	struct secashead *sah;
5870 	struct secasvar *sav = NULL;
5871 	u_int16_t proto;
5872 
5873 	IPSEC_ASSERT(so != NULL, ("null socket"));
5874 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5875 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5876 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5877 
5878 	/* map satype to proto */
5879 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5880 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5881 			__func__));
5882 		return key_senderror(so, m, EINVAL);
5883 	}
5884 
5885 	if (mhp->ext[SADB_EXT_SA] == NULL ||
5886 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5887 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5888 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5889 			__func__));
5890 		return key_senderror(so, m, EINVAL);
5891 	}
5892 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5893 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5894 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5895 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5896 			__func__));
5897 		return key_senderror(so, m, EINVAL);
5898 	}
5899 
5900 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5901 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5902 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5903 
5904 	/* XXX boundary check against sa_len */
5905 	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5906 
5907 	/*
5908 	 * Make sure the port numbers are zero.
5909 	 * In case of NAT-T we will update them later if needed.
5910 	 */
5911 	KEY_PORTTOSADDR(&saidx.src, 0);
5912 	KEY_PORTTOSADDR(&saidx.dst, 0);
5913 
5914 #ifdef IPSEC_NAT_T
5915 	/*
5916 	 * Handle NAT-T info if present.
5917 	 */
5918 
5919 	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5920 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5921 		struct sadb_x_nat_t_port *sport, *dport;
5922 
5923 		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5924 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5925 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5926 			    __func__));
5927 			return key_senderror(so, m, EINVAL);
5928 		}
5929 
5930 		sport = (struct sadb_x_nat_t_port *)
5931 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5932 		dport = (struct sadb_x_nat_t_port *)
5933 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5934 
5935 		if (sport)
5936 			KEY_PORTTOSADDR(&saidx.src,
5937 			    sport->sadb_x_nat_t_port_port);
5938 		if (dport)
5939 			KEY_PORTTOSADDR(&saidx.dst,
5940 			    dport->sadb_x_nat_t_port_port);
5941 	}
5942 #endif
5943 
5944 	/* get a SA header */
5945 	SAHTREE_LOCK();
5946 	LIST_FOREACH(sah, &V_sahtree, chain) {
5947 		if (sah->state == SADB_SASTATE_DEAD)
5948 			continue;
5949 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5950 			continue;
5951 
5952 		/* get a SA with SPI. */
5953 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5954 		if (sav)
5955 			break;
5956 	}
5957 	SAHTREE_UNLOCK();
5958 	if (sah == NULL) {
5959 		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5960 		return key_senderror(so, m, ENOENT);
5961 	}
5962 
5963     {
5964 	struct mbuf *n;
5965 	u_int8_t satype;
5966 
5967 	/* map proto to satype */
5968 	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5969 		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5970 			__func__));
5971 		return key_senderror(so, m, EINVAL);
5972 	}
5973 
5974 	/* create new sadb_msg to reply. */
5975 	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5976 	    mhp->msg->sadb_msg_pid);
5977 	if (!n)
5978 		return key_senderror(so, m, ENOBUFS);
5979 
5980 	m_freem(m);
5981 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5982     }
5983 }
5984 
5985 /* XXX make it sysctl-configurable? */
5986 static void
5987 key_getcomb_setlifetime(comb)
5988 	struct sadb_comb *comb;
5989 {
5990 
5991 	comb->sadb_comb_soft_allocations = 1;
5992 	comb->sadb_comb_hard_allocations = 1;
5993 	comb->sadb_comb_soft_bytes = 0;
5994 	comb->sadb_comb_hard_bytes = 0;
5995 	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5996 	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5997 	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5998 	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5999 }
6000 
6001 /*
6002  * XXX reorder combinations by preference
6003  * XXX no idea if the user wants ESP authentication or not
6004  */
6005 static struct mbuf *
6006 key_getcomb_esp()
6007 {
6008 	struct sadb_comb *comb;
6009 	struct enc_xform *algo;
6010 	struct mbuf *result = NULL, *m, *n;
6011 	int encmin;
6012 	int i, off, o;
6013 	int totlen;
6014 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6015 
6016 	m = NULL;
6017 	for (i = 1; i <= SADB_EALG_MAX; i++) {
6018 		algo = esp_algorithm_lookup(i);
6019 		if (algo == NULL)
6020 			continue;
6021 
6022 		/* discard algorithms with key size smaller than system min */
6023 		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6024 			continue;
6025 		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6026 			encmin = V_ipsec_esp_keymin;
6027 		else
6028 			encmin = _BITS(algo->minkey);
6029 
6030 		if (V_ipsec_esp_auth)
6031 			m = key_getcomb_ah();
6032 		else {
6033 			IPSEC_ASSERT(l <= MLEN,
6034 				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6035 			MGET(m, M_DONTWAIT, MT_DATA);
6036 			if (m) {
6037 				M_ALIGN(m, l);
6038 				m->m_len = l;
6039 				m->m_next = NULL;
6040 				bzero(mtod(m, caddr_t), m->m_len);
6041 			}
6042 		}
6043 		if (!m)
6044 			goto fail;
6045 
6046 		totlen = 0;
6047 		for (n = m; n; n = n->m_next)
6048 			totlen += n->m_len;
6049 		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6050 
6051 		for (off = 0; off < totlen; off += l) {
6052 			n = m_pulldown(m, off, l, &o);
6053 			if (!n) {
6054 				/* m is already freed */
6055 				goto fail;
6056 			}
6057 			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6058 			bzero(comb, sizeof(*comb));
6059 			key_getcomb_setlifetime(comb);
6060 			comb->sadb_comb_encrypt = i;
6061 			comb->sadb_comb_encrypt_minbits = encmin;
6062 			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6063 		}
6064 
6065 		if (!result)
6066 			result = m;
6067 		else
6068 			m_cat(result, m);
6069 	}
6070 
6071 	return result;
6072 
6073  fail:
6074 	if (result)
6075 		m_freem(result);
6076 	return NULL;
6077 }
6078 
6079 static void
6080 key_getsizes_ah(
6081 	const struct auth_hash *ah,
6082 	int alg,
6083 	u_int16_t* min,
6084 	u_int16_t* max)
6085 {
6086 
6087 	*min = *max = ah->keysize;
6088 	if (ah->keysize == 0) {
6089 		/*
6090 		 * Transform takes arbitrary key size but algorithm
6091 		 * key size is restricted.  Enforce this here.
6092 		 */
6093 		switch (alg) {
6094 		case SADB_X_AALG_MD5:	*min = *max = 16; break;
6095 		case SADB_X_AALG_SHA:	*min = *max = 20; break;
6096 		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
6097 		default:
6098 			DPRINTF(("%s: unknown AH algorithm %u\n",
6099 				__func__, alg));
6100 			break;
6101 		}
6102 	}
6103 }
6104 
6105 /*
6106  * XXX reorder combinations by preference
6107  */
6108 static struct mbuf *
6109 key_getcomb_ah()
6110 {
6111 	struct sadb_comb *comb;
6112 	struct auth_hash *algo;
6113 	struct mbuf *m;
6114 	u_int16_t minkeysize, maxkeysize;
6115 	int i;
6116 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6117 
6118 	m = NULL;
6119 	for (i = 1; i <= SADB_AALG_MAX; i++) {
6120 #if 1
6121 		/* we prefer HMAC algorithms, not old algorithms */
6122 		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
6123 			continue;
6124 #endif
6125 		algo = ah_algorithm_lookup(i);
6126 		if (!algo)
6127 			continue;
6128 		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6129 		/* discard algorithms with key size smaller than system min */
6130 		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6131 			continue;
6132 
6133 		if (!m) {
6134 			IPSEC_ASSERT(l <= MLEN,
6135 				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6136 			MGET(m, M_DONTWAIT, MT_DATA);
6137 			if (m) {
6138 				M_ALIGN(m, l);
6139 				m->m_len = l;
6140 				m->m_next = NULL;
6141 			}
6142 		} else
6143 			M_PREPEND(m, l, M_DONTWAIT);
6144 		if (!m)
6145 			return NULL;
6146 
6147 		comb = mtod(m, struct sadb_comb *);
6148 		bzero(comb, sizeof(*comb));
6149 		key_getcomb_setlifetime(comb);
6150 		comb->sadb_comb_auth = i;
6151 		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6152 		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6153 	}
6154 
6155 	return m;
6156 }
6157 
6158 /*
6159  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6160  * XXX reorder combinations by preference
6161  */
6162 static struct mbuf *
6163 key_getcomb_ipcomp()
6164 {
6165 	struct sadb_comb *comb;
6166 	struct comp_algo *algo;
6167 	struct mbuf *m;
6168 	int i;
6169 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6170 
6171 	m = NULL;
6172 	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6173 		algo = ipcomp_algorithm_lookup(i);
6174 		if (!algo)
6175 			continue;
6176 
6177 		if (!m) {
6178 			IPSEC_ASSERT(l <= MLEN,
6179 				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6180 			MGET(m, M_DONTWAIT, MT_DATA);
6181 			if (m) {
6182 				M_ALIGN(m, l);
6183 				m->m_len = l;
6184 				m->m_next = NULL;
6185 			}
6186 		} else
6187 			M_PREPEND(m, l, M_DONTWAIT);
6188 		if (!m)
6189 			return NULL;
6190 
6191 		comb = mtod(m, struct sadb_comb *);
6192 		bzero(comb, sizeof(*comb));
6193 		key_getcomb_setlifetime(comb);
6194 		comb->sadb_comb_encrypt = i;
6195 		/* what should we set into sadb_comb_*_{min,max}bits? */
6196 	}
6197 
6198 	return m;
6199 }
6200 
6201 /*
6202  * XXX no way to pass mode (transport/tunnel) to userland
6203  * XXX replay checking?
6204  * XXX sysctl interface to ipsec_{ah,esp}_keymin
6205  */
6206 static struct mbuf *
6207 key_getprop(saidx)
6208 	const struct secasindex *saidx;
6209 {
6210 	struct sadb_prop *prop;
6211 	struct mbuf *m, *n;
6212 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6213 	int totlen;
6214 
6215 	switch (saidx->proto)  {
6216 	case IPPROTO_ESP:
6217 		m = key_getcomb_esp();
6218 		break;
6219 	case IPPROTO_AH:
6220 		m = key_getcomb_ah();
6221 		break;
6222 	case IPPROTO_IPCOMP:
6223 		m = key_getcomb_ipcomp();
6224 		break;
6225 	default:
6226 		return NULL;
6227 	}
6228 
6229 	if (!m)
6230 		return NULL;
6231 	M_PREPEND(m, l, M_DONTWAIT);
6232 	if (!m)
6233 		return NULL;
6234 
6235 	totlen = 0;
6236 	for (n = m; n; n = n->m_next)
6237 		totlen += n->m_len;
6238 
6239 	prop = mtod(m, struct sadb_prop *);
6240 	bzero(prop, sizeof(*prop));
6241 	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6242 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6243 	prop->sadb_prop_replay = 32;	/* XXX */
6244 
6245 	return m;
6246 }
6247 
6248 /*
6249  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6250  * send
6251  *   <base, SA, address(SD), (address(P)), x_policy,
6252  *       (identity(SD),) (sensitivity,) proposal>
6253  * to KMD, and expect to receive
6254  *   <base> with SADB_ACQUIRE if error occured,
6255  * or
6256  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6257  * from KMD by PF_KEY.
6258  *
6259  * XXX x_policy is outside of RFC2367 (KAME extension).
6260  * XXX sensitivity is not supported.
6261  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6262  * see comment for key_getcomb_ipcomp().
6263  *
6264  * OUT:
6265  *    0     : succeed
6266  *    others: error number
6267  */
6268 static int
6269 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6270 {
6271 	struct mbuf *result = NULL, *m;
6272 	struct secacq *newacq;
6273 	u_int8_t satype;
6274 	int error = -1;
6275 	u_int32_t seq;
6276 
6277 	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6278 	satype = key_proto2satype(saidx->proto);
6279 	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6280 
6281 	/*
6282 	 * We never do anything about acquirng SA.  There is anather
6283 	 * solution that kernel blocks to send SADB_ACQUIRE message until
6284 	 * getting something message from IKEd.  In later case, to be
6285 	 * managed with ACQUIRING list.
6286 	 */
6287 	/* Get an entry to check whether sending message or not. */
6288 	if ((newacq = key_getacq(saidx)) != NULL) {
6289 		if (V_key_blockacq_count < newacq->count) {
6290 			/* reset counter and do send message. */
6291 			newacq->count = 0;
6292 		} else {
6293 			/* increment counter and do nothing. */
6294 			newacq->count++;
6295 			return 0;
6296 		}
6297 	} else {
6298 		/* make new entry for blocking to send SADB_ACQUIRE. */
6299 		if ((newacq = key_newacq(saidx)) == NULL)
6300 			return ENOBUFS;
6301 	}
6302 
6303 
6304 	seq = newacq->seq;
6305 	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6306 	if (!m) {
6307 		error = ENOBUFS;
6308 		goto fail;
6309 	}
6310 	result = m;
6311 
6312 	/*
6313 	 * No SADB_X_EXT_NAT_T_* here: we do not know
6314 	 * anything related to NAT-T at this time.
6315 	 */
6316 
6317 	/* set sadb_address for saidx's. */
6318 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6319 	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6320 	if (!m) {
6321 		error = ENOBUFS;
6322 		goto fail;
6323 	}
6324 	m_cat(result, m);
6325 
6326 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6327 	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6328 	if (!m) {
6329 		error = ENOBUFS;
6330 		goto fail;
6331 	}
6332 	m_cat(result, m);
6333 
6334 	/* XXX proxy address (optional) */
6335 
6336 	/* set sadb_x_policy */
6337 	if (sp) {
6338 		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6339 		if (!m) {
6340 			error = ENOBUFS;
6341 			goto fail;
6342 		}
6343 		m_cat(result, m);
6344 	}
6345 
6346 	/* XXX identity (optional) */
6347 #if 0
6348 	if (idexttype && fqdn) {
6349 		/* create identity extension (FQDN) */
6350 		struct sadb_ident *id;
6351 		int fqdnlen;
6352 
6353 		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
6354 		id = (struct sadb_ident *)p;
6355 		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6356 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6357 		id->sadb_ident_exttype = idexttype;
6358 		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6359 		bcopy(fqdn, id + 1, fqdnlen);
6360 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6361 	}
6362 
6363 	if (idexttype) {
6364 		/* create identity extension (USERFQDN) */
6365 		struct sadb_ident *id;
6366 		int userfqdnlen;
6367 
6368 		if (userfqdn) {
6369 			/* +1 for terminating-NUL */
6370 			userfqdnlen = strlen(userfqdn) + 1;
6371 		} else
6372 			userfqdnlen = 0;
6373 		id = (struct sadb_ident *)p;
6374 		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6375 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6376 		id->sadb_ident_exttype = idexttype;
6377 		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6378 		/* XXX is it correct? */
6379 		if (curproc && curproc->p_cred)
6380 			id->sadb_ident_id = curproc->p_cred->p_ruid;
6381 		if (userfqdn && userfqdnlen)
6382 			bcopy(userfqdn, id + 1, userfqdnlen);
6383 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6384 	}
6385 #endif
6386 
6387 	/* XXX sensitivity (optional) */
6388 
6389 	/* create proposal/combination extension */
6390 	m = key_getprop(saidx);
6391 #if 0
6392 	/*
6393 	 * spec conformant: always attach proposal/combination extension,
6394 	 * the problem is that we have no way to attach it for ipcomp,
6395 	 * due to the way sadb_comb is declared in RFC2367.
6396 	 */
6397 	if (!m) {
6398 		error = ENOBUFS;
6399 		goto fail;
6400 	}
6401 	m_cat(result, m);
6402 #else
6403 	/*
6404 	 * outside of spec; make proposal/combination extension optional.
6405 	 */
6406 	if (m)
6407 		m_cat(result, m);
6408 #endif
6409 
6410 	if ((result->m_flags & M_PKTHDR) == 0) {
6411 		error = EINVAL;
6412 		goto fail;
6413 	}
6414 
6415 	if (result->m_len < sizeof(struct sadb_msg)) {
6416 		result = m_pullup(result, sizeof(struct sadb_msg));
6417 		if (result == NULL) {
6418 			error = ENOBUFS;
6419 			goto fail;
6420 		}
6421 	}
6422 
6423 	result->m_pkthdr.len = 0;
6424 	for (m = result; m; m = m->m_next)
6425 		result->m_pkthdr.len += m->m_len;
6426 
6427 	mtod(result, struct sadb_msg *)->sadb_msg_len =
6428 	    PFKEY_UNIT64(result->m_pkthdr.len);
6429 
6430 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6431 
6432  fail:
6433 	if (result)
6434 		m_freem(result);
6435 	return error;
6436 }
6437 
6438 static struct secacq *
6439 key_newacq(const struct secasindex *saidx)
6440 {
6441 	struct secacq *newacq;
6442 
6443 	/* get new entry */
6444 	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6445 	if (newacq == NULL) {
6446 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6447 		return NULL;
6448 	}
6449 
6450 	/* copy secindex */
6451 	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6452 	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6453 	newacq->created = time_second;
6454 	newacq->count = 0;
6455 
6456 	/* add to acqtree */
6457 	ACQ_LOCK();
6458 	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6459 	ACQ_UNLOCK();
6460 
6461 	return newacq;
6462 }
6463 
6464 static struct secacq *
6465 key_getacq(const struct secasindex *saidx)
6466 {
6467 	struct secacq *acq;
6468 
6469 	ACQ_LOCK();
6470 	LIST_FOREACH(acq, &V_acqtree, chain) {
6471 		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6472 			break;
6473 	}
6474 	ACQ_UNLOCK();
6475 
6476 	return acq;
6477 }
6478 
6479 static struct secacq *
6480 key_getacqbyseq(seq)
6481 	u_int32_t seq;
6482 {
6483 	struct secacq *acq;
6484 
6485 	ACQ_LOCK();
6486 	LIST_FOREACH(acq, &V_acqtree, chain) {
6487 		if (acq->seq == seq)
6488 			break;
6489 	}
6490 	ACQ_UNLOCK();
6491 
6492 	return acq;
6493 }
6494 
6495 static struct secspacq *
6496 key_newspacq(spidx)
6497 	struct secpolicyindex *spidx;
6498 {
6499 	struct secspacq *acq;
6500 
6501 	/* get new entry */
6502 	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6503 	if (acq == NULL) {
6504 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6505 		return NULL;
6506 	}
6507 
6508 	/* copy secindex */
6509 	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6510 	acq->created = time_second;
6511 	acq->count = 0;
6512 
6513 	/* add to spacqtree */
6514 	SPACQ_LOCK();
6515 	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6516 	SPACQ_UNLOCK();
6517 
6518 	return acq;
6519 }
6520 
6521 static struct secspacq *
6522 key_getspacq(spidx)
6523 	struct secpolicyindex *spidx;
6524 {
6525 	struct secspacq *acq;
6526 
6527 	SPACQ_LOCK();
6528 	LIST_FOREACH(acq, &V_spacqtree, chain) {
6529 		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6530 			/* NB: return holding spacq_lock */
6531 			return acq;
6532 		}
6533 	}
6534 	SPACQ_UNLOCK();
6535 
6536 	return NULL;
6537 }
6538 
6539 /*
6540  * SADB_ACQUIRE processing,
6541  * in first situation, is receiving
6542  *   <base>
6543  * from the ikmpd, and clear sequence of its secasvar entry.
6544  *
6545  * In second situation, is receiving
6546  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6547  * from a user land process, and return
6548  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6549  * to the socket.
6550  *
6551  * m will always be freed.
6552  */
6553 static int
6554 key_acquire2(so, m, mhp)
6555 	struct socket *so;
6556 	struct mbuf *m;
6557 	const struct sadb_msghdr *mhp;
6558 {
6559 	const struct sadb_address *src0, *dst0;
6560 	struct secasindex saidx;
6561 	struct secashead *sah;
6562 	u_int16_t proto;
6563 	int error;
6564 
6565 	IPSEC_ASSERT(so != NULL, ("null socket"));
6566 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6567 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6568 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6569 
6570 	/*
6571 	 * Error message from KMd.
6572 	 * We assume that if error was occured in IKEd, the length of PFKEY
6573 	 * message is equal to the size of sadb_msg structure.
6574 	 * We do not raise error even if error occured in this function.
6575 	 */
6576 	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6577 		struct secacq *acq;
6578 
6579 		/* check sequence number */
6580 		if (mhp->msg->sadb_msg_seq == 0) {
6581 			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6582 				"number.\n", __func__));
6583 			m_freem(m);
6584 			return 0;
6585 		}
6586 
6587 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6588 			/*
6589 			 * the specified larval SA is already gone, or we got
6590 			 * a bogus sequence number.  we can silently ignore it.
6591 			 */
6592 			m_freem(m);
6593 			return 0;
6594 		}
6595 
6596 		/* reset acq counter in order to deletion by timehander. */
6597 		acq->created = time_second;
6598 		acq->count = 0;
6599 		m_freem(m);
6600 		return 0;
6601 	}
6602 
6603 	/*
6604 	 * This message is from user land.
6605 	 */
6606 
6607 	/* map satype to proto */
6608 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6609 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6610 			__func__));
6611 		return key_senderror(so, m, EINVAL);
6612 	}
6613 
6614 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6615 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6616 	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6617 		/* error */
6618 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6619 			__func__));
6620 		return key_senderror(so, m, EINVAL);
6621 	}
6622 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6623 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6624 	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6625 		/* error */
6626 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6627 			__func__));
6628 		return key_senderror(so, m, EINVAL);
6629 	}
6630 
6631 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6632 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6633 
6634 	/* XXX boundary check against sa_len */
6635 	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6636 
6637 	/*
6638 	 * Make sure the port numbers are zero.
6639 	 * In case of NAT-T we will update them later if needed.
6640 	 */
6641 	KEY_PORTTOSADDR(&saidx.src, 0);
6642 	KEY_PORTTOSADDR(&saidx.dst, 0);
6643 
6644 #ifndef IPSEC_NAT_T
6645 	/*
6646 	 * Handle NAT-T info if present.
6647 	 */
6648 
6649 	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6650 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6651 		struct sadb_x_nat_t_port *sport, *dport;
6652 
6653 		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6654 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6655 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6656 			    __func__));
6657 			return key_senderror(so, m, EINVAL);
6658 		}
6659 
6660 		sport = (struct sadb_x_nat_t_port *)
6661 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6662 		dport = (struct sadb_x_nat_t_port *)
6663 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6664 
6665 		if (sport)
6666 			KEY_PORTTOSADDR(&saidx.src,
6667 			    sport->sadb_x_nat_t_port_port);
6668 		if (dport)
6669 			KEY_PORTTOSADDR(&saidx.dst,
6670 			    dport->sadb_x_nat_t_port_port);
6671 	}
6672 #endif
6673 
6674 	/* get a SA index */
6675 	SAHTREE_LOCK();
6676 	LIST_FOREACH(sah, &V_sahtree, chain) {
6677 		if (sah->state == SADB_SASTATE_DEAD)
6678 			continue;
6679 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6680 			break;
6681 	}
6682 	SAHTREE_UNLOCK();
6683 	if (sah != NULL) {
6684 		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6685 		return key_senderror(so, m, EEXIST);
6686 	}
6687 
6688 	error = key_acquire(&saidx, NULL);
6689 	if (error != 0) {
6690 		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6691 			__func__, mhp->msg->sadb_msg_errno));
6692 		return key_senderror(so, m, error);
6693 	}
6694 
6695 	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6696 }
6697 
6698 /*
6699  * SADB_REGISTER processing.
6700  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6701  * receive
6702  *   <base>
6703  * from the ikmpd, and register a socket to send PF_KEY messages,
6704  * and send
6705  *   <base, supported>
6706  * to KMD by PF_KEY.
6707  * If socket is detached, must free from regnode.
6708  *
6709  * m will always be freed.
6710  */
6711 static int
6712 key_register(so, m, mhp)
6713 	struct socket *so;
6714 	struct mbuf *m;
6715 	const struct sadb_msghdr *mhp;
6716 {
6717 	struct secreg *reg, *newreg = 0;
6718 
6719 	IPSEC_ASSERT(so != NULL, ("null socket"));
6720 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6721 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6722 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6723 
6724 	/* check for invalid register message */
6725 	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6726 		return key_senderror(so, m, EINVAL);
6727 
6728 	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6729 	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6730 		goto setmsg;
6731 
6732 	/* check whether existing or not */
6733 	REGTREE_LOCK();
6734 	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6735 		if (reg->so == so) {
6736 			REGTREE_UNLOCK();
6737 			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6738 				__func__));
6739 			return key_senderror(so, m, EEXIST);
6740 		}
6741 	}
6742 
6743 	/* create regnode */
6744 	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6745 	if (newreg == NULL) {
6746 		REGTREE_UNLOCK();
6747 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6748 		return key_senderror(so, m, ENOBUFS);
6749 	}
6750 
6751 	newreg->so = so;
6752 	((struct keycb *)sotorawcb(so))->kp_registered++;
6753 
6754 	/* add regnode to regtree. */
6755 	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6756 	REGTREE_UNLOCK();
6757 
6758   setmsg:
6759     {
6760 	struct mbuf *n;
6761 	struct sadb_msg *newmsg;
6762 	struct sadb_supported *sup;
6763 	u_int len, alen, elen;
6764 	int off;
6765 	int i;
6766 	struct sadb_alg *alg;
6767 
6768 	/* create new sadb_msg to reply. */
6769 	alen = 0;
6770 	for (i = 1; i <= SADB_AALG_MAX; i++) {
6771 		if (ah_algorithm_lookup(i))
6772 			alen += sizeof(struct sadb_alg);
6773 	}
6774 	if (alen)
6775 		alen += sizeof(struct sadb_supported);
6776 	elen = 0;
6777 	for (i = 1; i <= SADB_EALG_MAX; i++) {
6778 		if (esp_algorithm_lookup(i))
6779 			elen += sizeof(struct sadb_alg);
6780 	}
6781 	if (elen)
6782 		elen += sizeof(struct sadb_supported);
6783 
6784 	len = sizeof(struct sadb_msg) + alen + elen;
6785 
6786 	if (len > MCLBYTES)
6787 		return key_senderror(so, m, ENOBUFS);
6788 
6789 	MGETHDR(n, M_DONTWAIT, MT_DATA);
6790 	if (len > MHLEN) {
6791 		MCLGET(n, M_DONTWAIT);
6792 		if ((n->m_flags & M_EXT) == 0) {
6793 			m_freem(n);
6794 			n = NULL;
6795 		}
6796 	}
6797 	if (!n)
6798 		return key_senderror(so, m, ENOBUFS);
6799 
6800 	n->m_pkthdr.len = n->m_len = len;
6801 	n->m_next = NULL;
6802 	off = 0;
6803 
6804 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6805 	newmsg = mtod(n, struct sadb_msg *);
6806 	newmsg->sadb_msg_errno = 0;
6807 	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6808 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6809 
6810 	/* for authentication algorithm */
6811 	if (alen) {
6812 		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6813 		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6814 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6815 		off += PFKEY_ALIGN8(sizeof(*sup));
6816 
6817 		for (i = 1; i <= SADB_AALG_MAX; i++) {
6818 			struct auth_hash *aalgo;
6819 			u_int16_t minkeysize, maxkeysize;
6820 
6821 			aalgo = ah_algorithm_lookup(i);
6822 			if (!aalgo)
6823 				continue;
6824 			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6825 			alg->sadb_alg_id = i;
6826 			alg->sadb_alg_ivlen = 0;
6827 			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6828 			alg->sadb_alg_minbits = _BITS(minkeysize);
6829 			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6830 			off += PFKEY_ALIGN8(sizeof(*alg));
6831 		}
6832 	}
6833 
6834 	/* for encryption algorithm */
6835 	if (elen) {
6836 		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6837 		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6838 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6839 		off += PFKEY_ALIGN8(sizeof(*sup));
6840 
6841 		for (i = 1; i <= SADB_EALG_MAX; i++) {
6842 			struct enc_xform *ealgo;
6843 
6844 			ealgo = esp_algorithm_lookup(i);
6845 			if (!ealgo)
6846 				continue;
6847 			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6848 			alg->sadb_alg_id = i;
6849 			alg->sadb_alg_ivlen = ealgo->blocksize;
6850 			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6851 			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6852 			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6853 		}
6854 	}
6855 
6856 	IPSEC_ASSERT(off == len,
6857 		("length assumption failed (off %u len %u)", off, len));
6858 
6859 	m_freem(m);
6860 	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6861     }
6862 }
6863 
6864 /*
6865  * free secreg entry registered.
6866  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6867  */
6868 void
6869 key_freereg(struct socket *so)
6870 {
6871 	struct secreg *reg;
6872 	int i;
6873 
6874 	IPSEC_ASSERT(so != NULL, ("NULL so"));
6875 
6876 	/*
6877 	 * check whether existing or not.
6878 	 * check all type of SA, because there is a potential that
6879 	 * one socket is registered to multiple type of SA.
6880 	 */
6881 	REGTREE_LOCK();
6882 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6883 		LIST_FOREACH(reg, &V_regtree[i], chain) {
6884 			if (reg->so == so && __LIST_CHAINED(reg)) {
6885 				LIST_REMOVE(reg, chain);
6886 				free(reg, M_IPSEC_SAR);
6887 				break;
6888 			}
6889 		}
6890 	}
6891 	REGTREE_UNLOCK();
6892 }
6893 
6894 /*
6895  * SADB_EXPIRE processing
6896  * send
6897  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6898  * to KMD by PF_KEY.
6899  * NOTE: We send only soft lifetime extension.
6900  *
6901  * OUT:	0	: succeed
6902  *	others	: error number
6903  */
6904 static int
6905 key_expire(struct secasvar *sav)
6906 {
6907 	int s;
6908 	int satype;
6909 	struct mbuf *result = NULL, *m;
6910 	int len;
6911 	int error = -1;
6912 	struct sadb_lifetime *lt;
6913 
6914 	/* XXX: Why do we lock ? */
6915 	s = splnet();	/*called from softclock()*/
6916 
6917 	IPSEC_ASSERT (sav != NULL, ("null sav"));
6918 	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6919 
6920 	/* set msg header */
6921 	satype = key_proto2satype(sav->sah->saidx.proto);
6922 	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6923 	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6924 	if (!m) {
6925 		error = ENOBUFS;
6926 		goto fail;
6927 	}
6928 	result = m;
6929 
6930 	/* create SA extension */
6931 	m = key_setsadbsa(sav);
6932 	if (!m) {
6933 		error = ENOBUFS;
6934 		goto fail;
6935 	}
6936 	m_cat(result, m);
6937 
6938 	/* create SA extension */
6939 	m = key_setsadbxsa2(sav->sah->saidx.mode,
6940 			sav->replay ? sav->replay->count : 0,
6941 			sav->sah->saidx.reqid);
6942 	if (!m) {
6943 		error = ENOBUFS;
6944 		goto fail;
6945 	}
6946 	m_cat(result, m);
6947 
6948 	/* create lifetime extension (current and soft) */
6949 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6950 	m = key_alloc_mbuf(len);
6951 	if (!m || m->m_next) {	/*XXX*/
6952 		if (m)
6953 			m_freem(m);
6954 		error = ENOBUFS;
6955 		goto fail;
6956 	}
6957 	bzero(mtod(m, caddr_t), len);
6958 	lt = mtod(m, struct sadb_lifetime *);
6959 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6960 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6961 	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6962 	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6963 	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6964 	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6965 	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6966 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6967 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6968 	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6969 	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6970 	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6971 	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6972 	m_cat(result, m);
6973 
6974 	/* set sadb_address for source */
6975 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6976 	    &sav->sah->saidx.src.sa,
6977 	    FULLMASK, IPSEC_ULPROTO_ANY);
6978 	if (!m) {
6979 		error = ENOBUFS;
6980 		goto fail;
6981 	}
6982 	m_cat(result, m);
6983 
6984 	/* set sadb_address for destination */
6985 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6986 	    &sav->sah->saidx.dst.sa,
6987 	    FULLMASK, IPSEC_ULPROTO_ANY);
6988 	if (!m) {
6989 		error = ENOBUFS;
6990 		goto fail;
6991 	}
6992 	m_cat(result, m);
6993 
6994 	/*
6995 	 * XXX-BZ Handle NAT-T extensions here.
6996 	 */
6997 
6998 	if ((result->m_flags & M_PKTHDR) == 0) {
6999 		error = EINVAL;
7000 		goto fail;
7001 	}
7002 
7003 	if (result->m_len < sizeof(struct sadb_msg)) {
7004 		result = m_pullup(result, sizeof(struct sadb_msg));
7005 		if (result == NULL) {
7006 			error = ENOBUFS;
7007 			goto fail;
7008 		}
7009 	}
7010 
7011 	result->m_pkthdr.len = 0;
7012 	for (m = result; m; m = m->m_next)
7013 		result->m_pkthdr.len += m->m_len;
7014 
7015 	mtod(result, struct sadb_msg *)->sadb_msg_len =
7016 	    PFKEY_UNIT64(result->m_pkthdr.len);
7017 
7018 	splx(s);
7019 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7020 
7021  fail:
7022 	if (result)
7023 		m_freem(result);
7024 	splx(s);
7025 	return error;
7026 }
7027 
7028 /*
7029  * SADB_FLUSH processing
7030  * receive
7031  *   <base>
7032  * from the ikmpd, and free all entries in secastree.
7033  * and send,
7034  *   <base>
7035  * to the ikmpd.
7036  * NOTE: to do is only marking SADB_SASTATE_DEAD.
7037  *
7038  * m will always be freed.
7039  */
7040 static int
7041 key_flush(so, m, mhp)
7042 	struct socket *so;
7043 	struct mbuf *m;
7044 	const struct sadb_msghdr *mhp;
7045 {
7046 	struct sadb_msg *newmsg;
7047 	struct secashead *sah, *nextsah;
7048 	struct secasvar *sav, *nextsav;
7049 	u_int16_t proto;
7050 	u_int8_t state;
7051 	u_int stateidx;
7052 
7053 	IPSEC_ASSERT(so != NULL, ("null socket"));
7054 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7055 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7056 
7057 	/* map satype to proto */
7058 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7059 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7060 			__func__));
7061 		return key_senderror(so, m, EINVAL);
7062 	}
7063 
7064 	/* no SATYPE specified, i.e. flushing all SA. */
7065 	SAHTREE_LOCK();
7066 	for (sah = LIST_FIRST(&V_sahtree);
7067 	     sah != NULL;
7068 	     sah = nextsah) {
7069 		nextsah = LIST_NEXT(sah, chain);
7070 
7071 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7072 		 && proto != sah->saidx.proto)
7073 			continue;
7074 
7075 		for (stateidx = 0;
7076 		     stateidx < _ARRAYLEN(saorder_state_alive);
7077 		     stateidx++) {
7078 			state = saorder_state_any[stateidx];
7079 			for (sav = LIST_FIRST(&sah->savtree[state]);
7080 			     sav != NULL;
7081 			     sav = nextsav) {
7082 
7083 				nextsav = LIST_NEXT(sav, chain);
7084 
7085 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7086 				KEY_FREESAV(&sav);
7087 			}
7088 		}
7089 
7090 		sah->state = SADB_SASTATE_DEAD;
7091 	}
7092 	SAHTREE_UNLOCK();
7093 
7094 	if (m->m_len < sizeof(struct sadb_msg) ||
7095 	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7096 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7097 		return key_senderror(so, m, ENOBUFS);
7098 	}
7099 
7100 	if (m->m_next)
7101 		m_freem(m->m_next);
7102 	m->m_next = NULL;
7103 	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7104 	newmsg = mtod(m, struct sadb_msg *);
7105 	newmsg->sadb_msg_errno = 0;
7106 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7107 
7108 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7109 }
7110 
7111 /*
7112  * SADB_DUMP processing
7113  * dump all entries including status of DEAD in SAD.
7114  * receive
7115  *   <base>
7116  * from the ikmpd, and dump all secasvar leaves
7117  * and send,
7118  *   <base> .....
7119  * to the ikmpd.
7120  *
7121  * m will always be freed.
7122  */
7123 static int
7124 key_dump(so, m, mhp)
7125 	struct socket *so;
7126 	struct mbuf *m;
7127 	const struct sadb_msghdr *mhp;
7128 {
7129 	struct secashead *sah;
7130 	struct secasvar *sav;
7131 	u_int16_t proto;
7132 	u_int stateidx;
7133 	u_int8_t satype;
7134 	u_int8_t state;
7135 	int cnt;
7136 	struct sadb_msg *newmsg;
7137 	struct mbuf *n;
7138 
7139 	IPSEC_ASSERT(so != NULL, ("null socket"));
7140 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7141 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7142 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7143 
7144 	/* map satype to proto */
7145 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7146 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7147 			__func__));
7148 		return key_senderror(so, m, EINVAL);
7149 	}
7150 
7151 	/* count sav entries to be sent to the userland. */
7152 	cnt = 0;
7153 	SAHTREE_LOCK();
7154 	LIST_FOREACH(sah, &V_sahtree, chain) {
7155 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7156 		 && proto != sah->saidx.proto)
7157 			continue;
7158 
7159 		for (stateidx = 0;
7160 		     stateidx < _ARRAYLEN(saorder_state_any);
7161 		     stateidx++) {
7162 			state = saorder_state_any[stateidx];
7163 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7164 				cnt++;
7165 			}
7166 		}
7167 	}
7168 
7169 	if (cnt == 0) {
7170 		SAHTREE_UNLOCK();
7171 		return key_senderror(so, m, ENOENT);
7172 	}
7173 
7174 	/* send this to the userland, one at a time. */
7175 	newmsg = NULL;
7176 	LIST_FOREACH(sah, &V_sahtree, chain) {
7177 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7178 		 && proto != sah->saidx.proto)
7179 			continue;
7180 
7181 		/* map proto to satype */
7182 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7183 			SAHTREE_UNLOCK();
7184 			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7185 				"SAD.\n", __func__));
7186 			return key_senderror(so, m, EINVAL);
7187 		}
7188 
7189 		for (stateidx = 0;
7190 		     stateidx < _ARRAYLEN(saorder_state_any);
7191 		     stateidx++) {
7192 			state = saorder_state_any[stateidx];
7193 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7194 				n = key_setdumpsa(sav, SADB_DUMP, satype,
7195 				    --cnt, mhp->msg->sadb_msg_pid);
7196 				if (!n) {
7197 					SAHTREE_UNLOCK();
7198 					return key_senderror(so, m, ENOBUFS);
7199 				}
7200 				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7201 			}
7202 		}
7203 	}
7204 	SAHTREE_UNLOCK();
7205 
7206 	m_freem(m);
7207 	return 0;
7208 }
7209 
7210 /*
7211  * SADB_X_PROMISC processing
7212  *
7213  * m will always be freed.
7214  */
7215 static int
7216 key_promisc(so, m, mhp)
7217 	struct socket *so;
7218 	struct mbuf *m;
7219 	const struct sadb_msghdr *mhp;
7220 {
7221 	int olen;
7222 
7223 	IPSEC_ASSERT(so != NULL, ("null socket"));
7224 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7225 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7226 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7227 
7228 	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7229 
7230 	if (olen < sizeof(struct sadb_msg)) {
7231 #if 1
7232 		return key_senderror(so, m, EINVAL);
7233 #else
7234 		m_freem(m);
7235 		return 0;
7236 #endif
7237 	} else if (olen == sizeof(struct sadb_msg)) {
7238 		/* enable/disable promisc mode */
7239 		struct keycb *kp;
7240 
7241 		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7242 			return key_senderror(so, m, EINVAL);
7243 		mhp->msg->sadb_msg_errno = 0;
7244 		switch (mhp->msg->sadb_msg_satype) {
7245 		case 0:
7246 		case 1:
7247 			kp->kp_promisc = mhp->msg->sadb_msg_satype;
7248 			break;
7249 		default:
7250 			return key_senderror(so, m, EINVAL);
7251 		}
7252 
7253 		/* send the original message back to everyone */
7254 		mhp->msg->sadb_msg_errno = 0;
7255 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7256 	} else {
7257 		/* send packet as is */
7258 
7259 		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7260 
7261 		/* TODO: if sadb_msg_seq is specified, send to specific pid */
7262 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7263 	}
7264 }
7265 
7266 static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
7267 		const struct sadb_msghdr *)) = {
7268 	NULL,		/* SADB_RESERVED */
7269 	key_getspi,	/* SADB_GETSPI */
7270 	key_update,	/* SADB_UPDATE */
7271 	key_add,	/* SADB_ADD */
7272 	key_delete,	/* SADB_DELETE */
7273 	key_get,	/* SADB_GET */
7274 	key_acquire2,	/* SADB_ACQUIRE */
7275 	key_register,	/* SADB_REGISTER */
7276 	NULL,		/* SADB_EXPIRE */
7277 	key_flush,	/* SADB_FLUSH */
7278 	key_dump,	/* SADB_DUMP */
7279 	key_promisc,	/* SADB_X_PROMISC */
7280 	NULL,		/* SADB_X_PCHANGE */
7281 	key_spdadd,	/* SADB_X_SPDUPDATE */
7282 	key_spdadd,	/* SADB_X_SPDADD */
7283 	key_spddelete,	/* SADB_X_SPDDELETE */
7284 	key_spdget,	/* SADB_X_SPDGET */
7285 	NULL,		/* SADB_X_SPDACQUIRE */
7286 	key_spddump,	/* SADB_X_SPDDUMP */
7287 	key_spdflush,	/* SADB_X_SPDFLUSH */
7288 	key_spdadd,	/* SADB_X_SPDSETIDX */
7289 	NULL,		/* SADB_X_SPDEXPIRE */
7290 	key_spddelete2,	/* SADB_X_SPDDELETE2 */
7291 };
7292 
7293 /*
7294  * parse sadb_msg buffer to process PFKEYv2,
7295  * and create a data to response if needed.
7296  * I think to be dealed with mbuf directly.
7297  * IN:
7298  *     msgp  : pointer to pointer to a received buffer pulluped.
7299  *             This is rewrited to response.
7300  *     so    : pointer to socket.
7301  * OUT:
7302  *    length for buffer to send to user process.
7303  */
7304 int
7305 key_parse(m, so)
7306 	struct mbuf *m;
7307 	struct socket *so;
7308 {
7309 	struct sadb_msg *msg;
7310 	struct sadb_msghdr mh;
7311 	u_int orglen;
7312 	int error;
7313 	int target;
7314 
7315 	IPSEC_ASSERT(so != NULL, ("null socket"));
7316 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7317 
7318 #if 0	/*kdebug_sadb assumes msg in linear buffer*/
7319 	KEYDEBUG(KEYDEBUG_KEY_DUMP,
7320 		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7321 		kdebug_sadb(msg));
7322 #endif
7323 
7324 	if (m->m_len < sizeof(struct sadb_msg)) {
7325 		m = m_pullup(m, sizeof(struct sadb_msg));
7326 		if (!m)
7327 			return ENOBUFS;
7328 	}
7329 	msg = mtod(m, struct sadb_msg *);
7330 	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7331 	target = KEY_SENDUP_ONE;
7332 
7333 	if ((m->m_flags & M_PKTHDR) == 0 ||
7334 	    m->m_pkthdr.len != m->m_pkthdr.len) {
7335 		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7336 		V_pfkeystat.out_invlen++;
7337 		error = EINVAL;
7338 		goto senderror;
7339 	}
7340 
7341 	if (msg->sadb_msg_version != PF_KEY_V2) {
7342 		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7343 		    __func__, msg->sadb_msg_version));
7344 		V_pfkeystat.out_invver++;
7345 		error = EINVAL;
7346 		goto senderror;
7347 	}
7348 
7349 	if (msg->sadb_msg_type > SADB_MAX) {
7350 		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7351 		    __func__, msg->sadb_msg_type));
7352 		V_pfkeystat.out_invmsgtype++;
7353 		error = EINVAL;
7354 		goto senderror;
7355 	}
7356 
7357 	/* for old-fashioned code - should be nuked */
7358 	if (m->m_pkthdr.len > MCLBYTES) {
7359 		m_freem(m);
7360 		return ENOBUFS;
7361 	}
7362 	if (m->m_next) {
7363 		struct mbuf *n;
7364 
7365 		MGETHDR(n, M_DONTWAIT, MT_DATA);
7366 		if (n && m->m_pkthdr.len > MHLEN) {
7367 			MCLGET(n, M_DONTWAIT);
7368 			if ((n->m_flags & M_EXT) == 0) {
7369 				m_free(n);
7370 				n = NULL;
7371 			}
7372 		}
7373 		if (!n) {
7374 			m_freem(m);
7375 			return ENOBUFS;
7376 		}
7377 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7378 		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7379 		n->m_next = NULL;
7380 		m_freem(m);
7381 		m = n;
7382 	}
7383 
7384 	/* align the mbuf chain so that extensions are in contiguous region. */
7385 	error = key_align(m, &mh);
7386 	if (error)
7387 		return error;
7388 
7389 	msg = mh.msg;
7390 
7391 	/* check SA type */
7392 	switch (msg->sadb_msg_satype) {
7393 	case SADB_SATYPE_UNSPEC:
7394 		switch (msg->sadb_msg_type) {
7395 		case SADB_GETSPI:
7396 		case SADB_UPDATE:
7397 		case SADB_ADD:
7398 		case SADB_DELETE:
7399 		case SADB_GET:
7400 		case SADB_ACQUIRE:
7401 		case SADB_EXPIRE:
7402 			ipseclog((LOG_DEBUG, "%s: must specify satype "
7403 			    "when msg type=%u.\n", __func__,
7404 			    msg->sadb_msg_type));
7405 			V_pfkeystat.out_invsatype++;
7406 			error = EINVAL;
7407 			goto senderror;
7408 		}
7409 		break;
7410 	case SADB_SATYPE_AH:
7411 	case SADB_SATYPE_ESP:
7412 	case SADB_X_SATYPE_IPCOMP:
7413 	case SADB_X_SATYPE_TCPSIGNATURE:
7414 		switch (msg->sadb_msg_type) {
7415 		case SADB_X_SPDADD:
7416 		case SADB_X_SPDDELETE:
7417 		case SADB_X_SPDGET:
7418 		case SADB_X_SPDDUMP:
7419 		case SADB_X_SPDFLUSH:
7420 		case SADB_X_SPDSETIDX:
7421 		case SADB_X_SPDUPDATE:
7422 		case SADB_X_SPDDELETE2:
7423 			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7424 				__func__, msg->sadb_msg_type));
7425 			V_pfkeystat.out_invsatype++;
7426 			error = EINVAL;
7427 			goto senderror;
7428 		}
7429 		break;
7430 	case SADB_SATYPE_RSVP:
7431 	case SADB_SATYPE_OSPFV2:
7432 	case SADB_SATYPE_RIPV2:
7433 	case SADB_SATYPE_MIP:
7434 		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7435 			__func__, msg->sadb_msg_satype));
7436 		V_pfkeystat.out_invsatype++;
7437 		error = EOPNOTSUPP;
7438 		goto senderror;
7439 	case 1:	/* XXX: What does it do? */
7440 		if (msg->sadb_msg_type == SADB_X_PROMISC)
7441 			break;
7442 		/*FALLTHROUGH*/
7443 	default:
7444 		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7445 			__func__, msg->sadb_msg_satype));
7446 		V_pfkeystat.out_invsatype++;
7447 		error = EINVAL;
7448 		goto senderror;
7449 	}
7450 
7451 	/* check field of upper layer protocol and address family */
7452 	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7453 	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7454 		struct sadb_address *src0, *dst0;
7455 		u_int plen;
7456 
7457 		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7458 		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7459 
7460 		/* check upper layer protocol */
7461 		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7462 			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7463 				"mismatched.\n", __func__));
7464 			V_pfkeystat.out_invaddr++;
7465 			error = EINVAL;
7466 			goto senderror;
7467 		}
7468 
7469 		/* check family */
7470 		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7471 		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
7472 			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7473 				__func__));
7474 			V_pfkeystat.out_invaddr++;
7475 			error = EINVAL;
7476 			goto senderror;
7477 		}
7478 		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7479 		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
7480 			ipseclog((LOG_DEBUG, "%s: address struct size "
7481 				"mismatched.\n", __func__));
7482 			V_pfkeystat.out_invaddr++;
7483 			error = EINVAL;
7484 			goto senderror;
7485 		}
7486 
7487 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7488 		case AF_INET:
7489 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7490 			    sizeof(struct sockaddr_in)) {
7491 				V_pfkeystat.out_invaddr++;
7492 				error = EINVAL;
7493 				goto senderror;
7494 			}
7495 			break;
7496 		case AF_INET6:
7497 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7498 			    sizeof(struct sockaddr_in6)) {
7499 				V_pfkeystat.out_invaddr++;
7500 				error = EINVAL;
7501 				goto senderror;
7502 			}
7503 			break;
7504 		default:
7505 			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7506 				__func__));
7507 			V_pfkeystat.out_invaddr++;
7508 			error = EAFNOSUPPORT;
7509 			goto senderror;
7510 		}
7511 
7512 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7513 		case AF_INET:
7514 			plen = sizeof(struct in_addr) << 3;
7515 			break;
7516 		case AF_INET6:
7517 			plen = sizeof(struct in6_addr) << 3;
7518 			break;
7519 		default:
7520 			plen = 0;	/*fool gcc*/
7521 			break;
7522 		}
7523 
7524 		/* check max prefix length */
7525 		if (src0->sadb_address_prefixlen > plen ||
7526 		    dst0->sadb_address_prefixlen > plen) {
7527 			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7528 				__func__));
7529 			V_pfkeystat.out_invaddr++;
7530 			error = EINVAL;
7531 			goto senderror;
7532 		}
7533 
7534 		/*
7535 		 * prefixlen == 0 is valid because there can be a case when
7536 		 * all addresses are matched.
7537 		 */
7538 	}
7539 
7540 	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7541 	    key_typesw[msg->sadb_msg_type] == NULL) {
7542 		V_pfkeystat.out_invmsgtype++;
7543 		error = EINVAL;
7544 		goto senderror;
7545 	}
7546 
7547 	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7548 
7549 senderror:
7550 	msg->sadb_msg_errno = error;
7551 	return key_sendup_mbuf(so, m, target);
7552 }
7553 
7554 static int
7555 key_senderror(so, m, code)
7556 	struct socket *so;
7557 	struct mbuf *m;
7558 	int code;
7559 {
7560 	struct sadb_msg *msg;
7561 
7562 	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7563 		("mbuf too small, len %u", m->m_len));
7564 
7565 	msg = mtod(m, struct sadb_msg *);
7566 	msg->sadb_msg_errno = code;
7567 	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7568 }
7569 
7570 /*
7571  * set the pointer to each header into message buffer.
7572  * m will be freed on error.
7573  * XXX larger-than-MCLBYTES extension?
7574  */
7575 static int
7576 key_align(m, mhp)
7577 	struct mbuf *m;
7578 	struct sadb_msghdr *mhp;
7579 {
7580 	struct mbuf *n;
7581 	struct sadb_ext *ext;
7582 	size_t off, end;
7583 	int extlen;
7584 	int toff;
7585 
7586 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7587 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7588 	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7589 		("mbuf too small, len %u", m->m_len));
7590 
7591 	/* initialize */
7592 	bzero(mhp, sizeof(*mhp));
7593 
7594 	mhp->msg = mtod(m, struct sadb_msg *);
7595 	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7596 
7597 	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7598 	extlen = end;	/*just in case extlen is not updated*/
7599 	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7600 		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7601 		if (!n) {
7602 			/* m is already freed */
7603 			return ENOBUFS;
7604 		}
7605 		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7606 
7607 		/* set pointer */
7608 		switch (ext->sadb_ext_type) {
7609 		case SADB_EXT_SA:
7610 		case SADB_EXT_ADDRESS_SRC:
7611 		case SADB_EXT_ADDRESS_DST:
7612 		case SADB_EXT_ADDRESS_PROXY:
7613 		case SADB_EXT_LIFETIME_CURRENT:
7614 		case SADB_EXT_LIFETIME_HARD:
7615 		case SADB_EXT_LIFETIME_SOFT:
7616 		case SADB_EXT_KEY_AUTH:
7617 		case SADB_EXT_KEY_ENCRYPT:
7618 		case SADB_EXT_IDENTITY_SRC:
7619 		case SADB_EXT_IDENTITY_DST:
7620 		case SADB_EXT_SENSITIVITY:
7621 		case SADB_EXT_PROPOSAL:
7622 		case SADB_EXT_SUPPORTED_AUTH:
7623 		case SADB_EXT_SUPPORTED_ENCRYPT:
7624 		case SADB_EXT_SPIRANGE:
7625 		case SADB_X_EXT_POLICY:
7626 		case SADB_X_EXT_SA2:
7627 #ifdef IPSEC_NAT_T
7628 		case SADB_X_EXT_NAT_T_TYPE:
7629 		case SADB_X_EXT_NAT_T_SPORT:
7630 		case SADB_X_EXT_NAT_T_DPORT:
7631 		case SADB_X_EXT_NAT_T_OAI:
7632 		case SADB_X_EXT_NAT_T_OAR:
7633 		case SADB_X_EXT_NAT_T_FRAG:
7634 #endif
7635 			/* duplicate check */
7636 			/*
7637 			 * XXX Are there duplication payloads of either
7638 			 * KEY_AUTH or KEY_ENCRYPT ?
7639 			 */
7640 			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7641 				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7642 					"%u\n", __func__, ext->sadb_ext_type));
7643 				m_freem(m);
7644 				V_pfkeystat.out_dupext++;
7645 				return EINVAL;
7646 			}
7647 			break;
7648 		default:
7649 			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7650 				__func__, ext->sadb_ext_type));
7651 			m_freem(m);
7652 			V_pfkeystat.out_invexttype++;
7653 			return EINVAL;
7654 		}
7655 
7656 		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7657 
7658 		if (key_validate_ext(ext, extlen)) {
7659 			m_freem(m);
7660 			V_pfkeystat.out_invlen++;
7661 			return EINVAL;
7662 		}
7663 
7664 		n = m_pulldown(m, off, extlen, &toff);
7665 		if (!n) {
7666 			/* m is already freed */
7667 			return ENOBUFS;
7668 		}
7669 		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7670 
7671 		mhp->ext[ext->sadb_ext_type] = ext;
7672 		mhp->extoff[ext->sadb_ext_type] = off;
7673 		mhp->extlen[ext->sadb_ext_type] = extlen;
7674 	}
7675 
7676 	if (off != end) {
7677 		m_freem(m);
7678 		V_pfkeystat.out_invlen++;
7679 		return EINVAL;
7680 	}
7681 
7682 	return 0;
7683 }
7684 
7685 static int
7686 key_validate_ext(ext, len)
7687 	const struct sadb_ext *ext;
7688 	int len;
7689 {
7690 	const struct sockaddr *sa;
7691 	enum { NONE, ADDR } checktype = NONE;
7692 	int baselen = 0;
7693 	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7694 
7695 	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7696 		return EINVAL;
7697 
7698 	/* if it does not match minimum/maximum length, bail */
7699 	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7700 	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7701 		return EINVAL;
7702 	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7703 		return EINVAL;
7704 	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7705 		return EINVAL;
7706 
7707 	/* more checks based on sadb_ext_type XXX need more */
7708 	switch (ext->sadb_ext_type) {
7709 	case SADB_EXT_ADDRESS_SRC:
7710 	case SADB_EXT_ADDRESS_DST:
7711 	case SADB_EXT_ADDRESS_PROXY:
7712 		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7713 		checktype = ADDR;
7714 		break;
7715 	case SADB_EXT_IDENTITY_SRC:
7716 	case SADB_EXT_IDENTITY_DST:
7717 		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7718 		    SADB_X_IDENTTYPE_ADDR) {
7719 			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7720 			checktype = ADDR;
7721 		} else
7722 			checktype = NONE;
7723 		break;
7724 	default:
7725 		checktype = NONE;
7726 		break;
7727 	}
7728 
7729 	switch (checktype) {
7730 	case NONE:
7731 		break;
7732 	case ADDR:
7733 		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7734 		if (len < baselen + sal)
7735 			return EINVAL;
7736 		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7737 			return EINVAL;
7738 		break;
7739 	}
7740 
7741 	return 0;
7742 }
7743 
7744 void
7745 key_init(void)
7746 {
7747 	int i;
7748 
7749 	for (i = 0; i < IPSEC_DIR_MAX; i++)
7750 		LIST_INIT(&V_sptree[i]);
7751 
7752 	LIST_INIT(&V_sahtree);
7753 
7754 	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7755 		LIST_INIT(&V_regtree[i]);
7756 
7757 	LIST_INIT(&V_acqtree);
7758 	LIST_INIT(&V_spacqtree);
7759 
7760 	/* system default */
7761 	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7762 	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7763 
7764 	if (!IS_DEFAULT_VNET(curvnet))
7765 		return;
7766 
7767 	SPTREE_LOCK_INIT();
7768 	REGTREE_LOCK_INIT();
7769 	SAHTREE_LOCK_INIT();
7770 	ACQ_LOCK_INIT();
7771 	SPACQ_LOCK_INIT();
7772 
7773 #ifndef IPSEC_DEBUG2
7774 	timeout((void *)key_timehandler, (void *)0, hz);
7775 #endif /*IPSEC_DEBUG2*/
7776 
7777 	/* initialize key statistics */
7778 	keystat.getspi_count = 1;
7779 
7780 	printf("IPsec: Initialized Security Association Processing.\n");
7781 }
7782 
7783 #ifdef VIMAGE
7784 void
7785 key_destroy(void)
7786 {
7787 	struct secpolicy *sp, *nextsp;
7788 	struct secacq *acq, *nextacq;
7789 	struct secspacq *spacq, *nextspacq;
7790 	struct secashead *sah, *nextsah;
7791 	struct secreg *reg;
7792 	int i;
7793 
7794 	SPTREE_LOCK();
7795 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7796 		for (sp = LIST_FIRST(&V_sptree[i]);
7797 		    sp != NULL; sp = nextsp) {
7798 			nextsp = LIST_NEXT(sp, chain);
7799 			if (__LIST_CHAINED(sp)) {
7800 				LIST_REMOVE(sp, chain);
7801 				free(sp, M_IPSEC_SP);
7802 			}
7803 		}
7804 	}
7805 	SPTREE_UNLOCK();
7806 
7807 	SAHTREE_LOCK();
7808 	for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7809 		nextsah = LIST_NEXT(sah, chain);
7810 		if (__LIST_CHAINED(sah)) {
7811 			LIST_REMOVE(sah, chain);
7812 			free(sah, M_IPSEC_SAH);
7813 		}
7814 	}
7815 	SAHTREE_UNLOCK();
7816 
7817 	REGTREE_LOCK();
7818 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7819 		LIST_FOREACH(reg, &V_regtree[i], chain) {
7820 			if (__LIST_CHAINED(reg)) {
7821 				LIST_REMOVE(reg, chain);
7822 				free(reg, M_IPSEC_SAR);
7823 				break;
7824 			}
7825 		}
7826 	}
7827 	REGTREE_UNLOCK();
7828 
7829 	ACQ_LOCK();
7830 	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
7831 		nextacq = LIST_NEXT(acq, chain);
7832 		if (__LIST_CHAINED(acq)) {
7833 			LIST_REMOVE(acq, chain);
7834 			free(acq, M_IPSEC_SAQ);
7835 		}
7836 	}
7837 	ACQ_UNLOCK();
7838 
7839 	SPACQ_LOCK();
7840 	for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
7841 	    spacq = nextspacq) {
7842 		nextspacq = LIST_NEXT(spacq, chain);
7843 		if (__LIST_CHAINED(spacq)) {
7844 			LIST_REMOVE(spacq, chain);
7845 			free(spacq, M_IPSEC_SAQ);
7846 		}
7847 	}
7848 	SPACQ_UNLOCK();
7849 }
7850 #endif
7851 
7852 /*
7853  * XXX: maybe This function is called after INBOUND IPsec processing.
7854  *
7855  * Special check for tunnel-mode packets.
7856  * We must make some checks for consistency between inner and outer IP header.
7857  *
7858  * xxx more checks to be provided
7859  */
7860 int
7861 key_checktunnelsanity(sav, family, src, dst)
7862 	struct secasvar *sav;
7863 	u_int family;
7864 	caddr_t src;
7865 	caddr_t dst;
7866 {
7867 	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7868 
7869 	/* XXX: check inner IP header */
7870 
7871 	return 1;
7872 }
7873 
7874 /* record data transfer on SA, and update timestamps */
7875 void
7876 key_sa_recordxfer(sav, m)
7877 	struct secasvar *sav;
7878 	struct mbuf *m;
7879 {
7880 	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7881 	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7882 	if (!sav->lft_c)
7883 		return;
7884 
7885 	/*
7886 	 * XXX Currently, there is a difference of bytes size
7887 	 * between inbound and outbound processing.
7888 	 */
7889 	sav->lft_c->bytes += m->m_pkthdr.len;
7890 	/* to check bytes lifetime is done in key_timehandler(). */
7891 
7892 	/*
7893 	 * We use the number of packets as the unit of
7894 	 * allocations.  We increment the variable
7895 	 * whenever {esp,ah}_{in,out}put is called.
7896 	 */
7897 	sav->lft_c->allocations++;
7898 	/* XXX check for expires? */
7899 
7900 	/*
7901 	 * NOTE: We record CURRENT usetime by using wall clock,
7902 	 * in seconds.  HARD and SOFT lifetime are measured by the time
7903 	 * difference (again in seconds) from usetime.
7904 	 *
7905 	 *	usetime
7906 	 *	v     expire   expire
7907 	 * -----+-----+--------+---> t
7908 	 *	<--------------> HARD
7909 	 *	<-----> SOFT
7910 	 */
7911 	sav->lft_c->usetime = time_second;
7912 	/* XXX check for expires? */
7913 
7914 	return;
7915 }
7916 
7917 /* dumb version */
7918 void
7919 key_sa_routechange(dst)
7920 	struct sockaddr *dst;
7921 {
7922 	struct secashead *sah;
7923 	struct route *ro;
7924 
7925 	SAHTREE_LOCK();
7926 	LIST_FOREACH(sah, &V_sahtree, chain) {
7927 		ro = &sah->sa_route;
7928 		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7929 		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7930 			RTFREE(ro->ro_rt);
7931 			ro->ro_rt = (struct rtentry *)NULL;
7932 		}
7933 	}
7934 	SAHTREE_UNLOCK();
7935 }
7936 
7937 static void
7938 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7939 {
7940 	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7941 	SAHTREE_LOCK_ASSERT();
7942 
7943 	if (sav->state != state) {
7944 		if (__LIST_CHAINED(sav))
7945 			LIST_REMOVE(sav, chain);
7946 		sav->state = state;
7947 		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7948 	}
7949 }
7950 
7951 void
7952 key_sa_stir_iv(sav)
7953 	struct secasvar *sav;
7954 {
7955 
7956 	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7957 	key_randomfill(sav->iv, sav->ivlen);
7958 }
7959 
7960 /* XXX too much? */
7961 static struct mbuf *
7962 key_alloc_mbuf(l)
7963 	int l;
7964 {
7965 	struct mbuf *m = NULL, *n;
7966 	int len, t;
7967 
7968 	len = l;
7969 	while (len > 0) {
7970 		MGET(n, M_DONTWAIT, MT_DATA);
7971 		if (n && len > MLEN)
7972 			MCLGET(n, M_DONTWAIT);
7973 		if (!n) {
7974 			m_freem(m);
7975 			return NULL;
7976 		}
7977 
7978 		n->m_next = NULL;
7979 		n->m_len = 0;
7980 		n->m_len = M_TRAILINGSPACE(n);
7981 		/* use the bottom of mbuf, hoping we can prepend afterwards */
7982 		if (n->m_len > len) {
7983 			t = (n->m_len - len) & ~(sizeof(long) - 1);
7984 			n->m_data += t;
7985 			n->m_len = len;
7986 		}
7987 
7988 		len -= n->m_len;
7989 
7990 		if (m)
7991 			m_cat(m, n);
7992 		else
7993 			m = n;
7994 	}
7995 
7996 	return m;
7997 }
7998 
7999 /*
8000  * Take one of the kernel's security keys and convert it into a PF_KEY
8001  * structure within an mbuf, suitable for sending up to a waiting
8002  * application in user land.
8003  *
8004  * IN:
8005  *    src: A pointer to a kernel security key.
8006  *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
8007  * OUT:
8008  *    a valid mbuf or NULL indicating an error
8009  *
8010  */
8011 
8012 static struct mbuf *
8013 key_setkey(struct seckey *src, u_int16_t exttype)
8014 {
8015 	struct mbuf *m;
8016 	struct sadb_key *p;
8017 	int len;
8018 
8019 	if (src == NULL)
8020 		return NULL;
8021 
8022 	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8023 	m = key_alloc_mbuf(len);
8024 	if (m == NULL)
8025 		return NULL;
8026 	p = mtod(m, struct sadb_key *);
8027 	bzero(p, len);
8028 	p->sadb_key_len = PFKEY_UNIT64(len);
8029 	p->sadb_key_exttype = exttype;
8030 	p->sadb_key_bits = src->bits;
8031 	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8032 
8033 	return m;
8034 }
8035 
8036 /*
8037  * Take one of the kernel's lifetime data structures and convert it
8038  * into a PF_KEY structure within an mbuf, suitable for sending up to
8039  * a waiting application in user land.
8040  *
8041  * IN:
8042  *    src: A pointer to a kernel lifetime structure.
8043  *    exttype: Which type of lifetime this is. Refer to the PF_KEY
8044  *             data structures for more information.
8045  * OUT:
8046  *    a valid mbuf or NULL indicating an error
8047  *
8048  */
8049 
8050 static struct mbuf *
8051 key_setlifetime(struct seclifetime *src, u_int16_t exttype)
8052 {
8053 	struct mbuf *m = NULL;
8054 	struct sadb_lifetime *p;
8055 	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8056 
8057 	if (src == NULL)
8058 		return NULL;
8059 
8060 	m = key_alloc_mbuf(len);
8061 	if (m == NULL)
8062 		return m;
8063 	p = mtod(m, struct sadb_lifetime *);
8064 
8065 	bzero(p, len);
8066 	p->sadb_lifetime_len = PFKEY_UNIT64(len);
8067 	p->sadb_lifetime_exttype = exttype;
8068 	p->sadb_lifetime_allocations = src->allocations;
8069 	p->sadb_lifetime_bytes = src->bytes;
8070 	p->sadb_lifetime_addtime = src->addtime;
8071 	p->sadb_lifetime_usetime = src->usetime;
8072 
8073 	return m;
8074 
8075 }
8076