xref: /freebsd/sys/netipsec/key.c (revision 941e286383714ef25f1ffe9ba6ae5040afdd7060)
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 			newsp->state = IPSEC_SPSTATE_DEAD;
1886 			KEY_FREESP(&newsp);
1887 		}
1888 	} else {
1889 		if (newsp != NULL) {
1890 			KEY_FREESP(&newsp);
1891 			ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1892 				__func__));
1893 			return key_senderror(so, m, EEXIST);
1894 		}
1895 	}
1896 
1897 	/* allocation new SP entry */
1898 	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1899 		return key_senderror(so, m, error);
1900 	}
1901 
1902 	if ((newsp->id = key_getnewspid()) == 0) {
1903 		_key_delsp(newsp);
1904 		return key_senderror(so, m, ENOBUFS);
1905 	}
1906 
1907 	/* XXX boundary check against sa_len */
1908 	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1909 	                src0 + 1,
1910 	                dst0 + 1,
1911 	                src0->sadb_address_prefixlen,
1912 	                dst0->sadb_address_prefixlen,
1913 	                src0->sadb_address_proto,
1914 	                &newsp->spidx);
1915 
1916 	/* sanity check on addr pair */
1917 	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1918 			((struct sockaddr *)(dst0+ 1))->sa_family) {
1919 		_key_delsp(newsp);
1920 		return key_senderror(so, m, EINVAL);
1921 	}
1922 	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1923 			((struct sockaddr *)(dst0+ 1))->sa_len) {
1924 		_key_delsp(newsp);
1925 		return key_senderror(so, m, EINVAL);
1926 	}
1927 #if 1
1928 	if (newsp->req && newsp->req->saidx.src.sa.sa_family && newsp->req->saidx.dst.sa.sa_family) {
1929 		if (newsp->req->saidx.src.sa.sa_family != newsp->req->saidx.dst.sa.sa_family) {
1930 			_key_delsp(newsp);
1931 			return key_senderror(so, m, EINVAL);
1932 		}
1933 	}
1934 #endif
1935 
1936 	newsp->created = time_second;
1937 	newsp->lastused = newsp->created;
1938 	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1939 	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1940 
1941 	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1942 	newsp->state = IPSEC_SPSTATE_ALIVE;
1943 	LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1944 
1945 	/* delete the entry in spacqtree */
1946 	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1947 		struct secspacq *spacq = key_getspacq(&spidx);
1948 		if (spacq != NULL) {
1949 			/* reset counter in order to deletion by timehandler. */
1950 			spacq->created = time_second;
1951 			spacq->count = 0;
1952 			SPACQ_UNLOCK();
1953 		}
1954     	}
1955 
1956     {
1957 	struct mbuf *n, *mpolicy;
1958 	struct sadb_msg *newmsg;
1959 	int off;
1960 
1961 	/*
1962 	 * Note: do not send SADB_X_EXT_NAT_T_* here:
1963 	 * we are sending traffic endpoints.
1964 	 */
1965 
1966 	/* create new sadb_msg to reply. */
1967 	if (lft) {
1968 		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1969 		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1970 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1971 	} else {
1972 		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1973 		    SADB_X_EXT_POLICY,
1974 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1975 	}
1976 	if (!n)
1977 		return key_senderror(so, m, ENOBUFS);
1978 
1979 	if (n->m_len < sizeof(*newmsg)) {
1980 		n = m_pullup(n, sizeof(*newmsg));
1981 		if (!n)
1982 			return key_senderror(so, m, ENOBUFS);
1983 	}
1984 	newmsg = mtod(n, struct sadb_msg *);
1985 	newmsg->sadb_msg_errno = 0;
1986 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1987 
1988 	off = 0;
1989 	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1990 	    sizeof(*xpl), &off);
1991 	if (mpolicy == NULL) {
1992 		/* n is already freed */
1993 		return key_senderror(so, m, ENOBUFS);
1994 	}
1995 	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1996 	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1997 		m_freem(n);
1998 		return key_senderror(so, m, EINVAL);
1999 	}
2000 	xpl->sadb_x_policy_id = newsp->id;
2001 
2002 	m_freem(m);
2003 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2004     }
2005 }
2006 
2007 /*
2008  * get new policy id.
2009  * OUT:
2010  *	0:	failure.
2011  *	others: success.
2012  */
2013 static u_int32_t
2014 key_getnewspid()
2015 {
2016 	u_int32_t newid = 0;
2017 	int count = V_key_spi_trycnt;	/* XXX */
2018 	struct secpolicy *sp;
2019 
2020 	/* when requesting to allocate spi ranged */
2021 	while (count--) {
2022 		newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
2023 
2024 		if ((sp = key_getspbyid(newid)) == NULL)
2025 			break;
2026 
2027 		KEY_FREESP(&sp);
2028 	}
2029 
2030 	if (count == 0 || newid == 0) {
2031 		ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2032 			__func__));
2033 		return 0;
2034 	}
2035 
2036 	return newid;
2037 }
2038 
2039 /*
2040  * SADB_SPDDELETE processing
2041  * receive
2042  *   <base, address(SD), policy(*)>
2043  * from the user(?), and set SADB_SASTATE_DEAD,
2044  * and send,
2045  *   <base, address(SD), policy(*)>
2046  * to the ikmpd.
2047  * policy(*) including direction of policy.
2048  *
2049  * m will always be freed.
2050  */
2051 static int
2052 key_spddelete(so, m, mhp)
2053 	struct socket *so;
2054 	struct mbuf *m;
2055 	const struct sadb_msghdr *mhp;
2056 {
2057 	struct sadb_address *src0, *dst0;
2058 	struct sadb_x_policy *xpl0;
2059 	struct secpolicyindex spidx;
2060 	struct secpolicy *sp;
2061 
2062 	IPSEC_ASSERT(so != NULL, ("null so"));
2063 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2064 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2065 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2066 
2067 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2068 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2069 	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2070 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2071 			__func__));
2072 		return key_senderror(so, m, EINVAL);
2073 	}
2074 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2075 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2076 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2077 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2078 			__func__));
2079 		return key_senderror(so, m, EINVAL);
2080 	}
2081 
2082 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2083 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2084 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2085 
2086 	/*
2087 	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
2088 	 * we are processing traffic endpoints.
2089 	 */
2090 
2091 	/* make secindex */
2092 	/* XXX boundary check against sa_len */
2093 	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2094 	                src0 + 1,
2095 	                dst0 + 1,
2096 	                src0->sadb_address_prefixlen,
2097 	                dst0->sadb_address_prefixlen,
2098 	                src0->sadb_address_proto,
2099 	                &spidx);
2100 
2101 	/* checking the direciton. */
2102 	switch (xpl0->sadb_x_policy_dir) {
2103 	case IPSEC_DIR_INBOUND:
2104 	case IPSEC_DIR_OUTBOUND:
2105 		break;
2106 	default:
2107 		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2108 		return key_senderror(so, m, EINVAL);
2109 	}
2110 
2111 	/* Is there SP in SPD ? */
2112 	if ((sp = key_getsp(&spidx)) == NULL) {
2113 		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2114 		return key_senderror(so, m, EINVAL);
2115 	}
2116 
2117 	/* save policy id to buffer to be returned. */
2118 	xpl0->sadb_x_policy_id = sp->id;
2119 
2120 	sp->state = IPSEC_SPSTATE_DEAD;
2121 	KEY_FREESP(&sp);
2122 
2123     {
2124 	struct mbuf *n;
2125 	struct sadb_msg *newmsg;
2126 
2127 	/*
2128 	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2129 	 * we are sending traffic endpoints.
2130 	 */
2131 
2132 	/* create new sadb_msg to reply. */
2133 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2134 	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2135 	if (!n)
2136 		return key_senderror(so, m, ENOBUFS);
2137 
2138 	newmsg = mtod(n, struct sadb_msg *);
2139 	newmsg->sadb_msg_errno = 0;
2140 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2141 
2142 	m_freem(m);
2143 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2144     }
2145 }
2146 
2147 /*
2148  * SADB_SPDDELETE2 processing
2149  * receive
2150  *   <base, policy(*)>
2151  * from the user(?), and set SADB_SASTATE_DEAD,
2152  * and send,
2153  *   <base, policy(*)>
2154  * to the ikmpd.
2155  * policy(*) including direction of policy.
2156  *
2157  * m will always be freed.
2158  */
2159 static int
2160 key_spddelete2(so, m, mhp)
2161 	struct socket *so;
2162 	struct mbuf *m;
2163 	const struct sadb_msghdr *mhp;
2164 {
2165 	u_int32_t id;
2166 	struct secpolicy *sp;
2167 
2168 	IPSEC_ASSERT(so != NULL, ("null socket"));
2169 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2170 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2171 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2172 
2173 	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2174 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2175 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2176 		return key_senderror(so, m, EINVAL);
2177 	}
2178 
2179 	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2180 
2181 	/* Is there SP in SPD ? */
2182 	if ((sp = key_getspbyid(id)) == NULL) {
2183 		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2184 		return key_senderror(so, m, EINVAL);
2185 	}
2186 
2187 	sp->state = IPSEC_SPSTATE_DEAD;
2188 	KEY_FREESP(&sp);
2189 
2190     {
2191 	struct mbuf *n, *nn;
2192 	struct sadb_msg *newmsg;
2193 	int off, len;
2194 
2195 	/* create new sadb_msg to reply. */
2196 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2197 
2198 	MGETHDR(n, M_DONTWAIT, MT_DATA);
2199 	if (n && len > MHLEN) {
2200 		MCLGET(n, M_DONTWAIT);
2201 		if ((n->m_flags & M_EXT) == 0) {
2202 			m_freem(n);
2203 			n = NULL;
2204 		}
2205 	}
2206 	if (!n)
2207 		return key_senderror(so, m, ENOBUFS);
2208 
2209 	n->m_len = len;
2210 	n->m_next = NULL;
2211 	off = 0;
2212 
2213 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2214 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2215 
2216 	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2217 		off, len));
2218 
2219 	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2220 	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2221 	if (!n->m_next) {
2222 		m_freem(n);
2223 		return key_senderror(so, m, ENOBUFS);
2224 	}
2225 
2226 	n->m_pkthdr.len = 0;
2227 	for (nn = n; nn; nn = nn->m_next)
2228 		n->m_pkthdr.len += nn->m_len;
2229 
2230 	newmsg = mtod(n, struct sadb_msg *);
2231 	newmsg->sadb_msg_errno = 0;
2232 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2233 
2234 	m_freem(m);
2235 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2236     }
2237 }
2238 
2239 /*
2240  * SADB_X_GET processing
2241  * receive
2242  *   <base, policy(*)>
2243  * from the user(?),
2244  * and send,
2245  *   <base, address(SD), policy>
2246  * to the ikmpd.
2247  * policy(*) including direction of policy.
2248  *
2249  * m will always be freed.
2250  */
2251 static int
2252 key_spdget(so, m, mhp)
2253 	struct socket *so;
2254 	struct mbuf *m;
2255 	const struct sadb_msghdr *mhp;
2256 {
2257 	u_int32_t id;
2258 	struct secpolicy *sp;
2259 	struct mbuf *n;
2260 
2261 	IPSEC_ASSERT(so != NULL, ("null socket"));
2262 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2263 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2264 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2265 
2266 	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2267 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2268 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2269 			__func__));
2270 		return key_senderror(so, m, EINVAL);
2271 	}
2272 
2273 	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2274 
2275 	/* Is there SP in SPD ? */
2276 	if ((sp = key_getspbyid(id)) == NULL) {
2277 		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2278 		return key_senderror(so, m, ENOENT);
2279 	}
2280 
2281 	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2282 	if (n != NULL) {
2283 		m_freem(m);
2284 		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2285 	} else
2286 		return key_senderror(so, m, ENOBUFS);
2287 }
2288 
2289 /*
2290  * SADB_X_SPDACQUIRE processing.
2291  * Acquire policy and SA(s) for a *OUTBOUND* packet.
2292  * send
2293  *   <base, policy(*)>
2294  * to KMD, and expect to receive
2295  *   <base> with SADB_X_SPDACQUIRE if error occured,
2296  * or
2297  *   <base, policy>
2298  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2299  * policy(*) is without policy requests.
2300  *
2301  *    0     : succeed
2302  *    others: error number
2303  */
2304 int
2305 key_spdacquire(sp)
2306 	struct secpolicy *sp;
2307 {
2308 	struct mbuf *result = NULL, *m;
2309 	struct secspacq *newspacq;
2310 
2311 	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2312 	IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2313 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2314 		("policy not IPSEC %u", sp->policy));
2315 
2316 	/* Get an entry to check whether sent message or not. */
2317 	newspacq = key_getspacq(&sp->spidx);
2318 	if (newspacq != NULL) {
2319 		if (V_key_blockacq_count < newspacq->count) {
2320 			/* reset counter and do send message. */
2321 			newspacq->count = 0;
2322 		} else {
2323 			/* increment counter and do nothing. */
2324 			newspacq->count++;
2325 			return 0;
2326 		}
2327 		SPACQ_UNLOCK();
2328 	} else {
2329 		/* make new entry for blocking to send SADB_ACQUIRE. */
2330 		newspacq = key_newspacq(&sp->spidx);
2331 		if (newspacq == NULL)
2332 			return ENOBUFS;
2333 	}
2334 
2335 	/* create new sadb_msg to reply. */
2336 	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2337 	if (!m)
2338 		return ENOBUFS;
2339 
2340 	result = m;
2341 
2342 	result->m_pkthdr.len = 0;
2343 	for (m = result; m; m = m->m_next)
2344 		result->m_pkthdr.len += m->m_len;
2345 
2346 	mtod(result, struct sadb_msg *)->sadb_msg_len =
2347 	    PFKEY_UNIT64(result->m_pkthdr.len);
2348 
2349 	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2350 }
2351 
2352 /*
2353  * SADB_SPDFLUSH processing
2354  * receive
2355  *   <base>
2356  * from the user, and free all entries in secpctree.
2357  * and send,
2358  *   <base>
2359  * to the user.
2360  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2361  *
2362  * m will always be freed.
2363  */
2364 static int
2365 key_spdflush(so, m, mhp)
2366 	struct socket *so;
2367 	struct mbuf *m;
2368 	const struct sadb_msghdr *mhp;
2369 {
2370 	struct sadb_msg *newmsg;
2371 	struct secpolicy *sp;
2372 	u_int dir;
2373 
2374 	IPSEC_ASSERT(so != NULL, ("null socket"));
2375 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2376 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2377 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2378 
2379 	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2380 		return key_senderror(so, m, EINVAL);
2381 
2382 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2383 		SPTREE_LOCK();
2384 		LIST_FOREACH(sp, &V_sptree[dir], chain)
2385 			sp->state = IPSEC_SPSTATE_DEAD;
2386 		SPTREE_UNLOCK();
2387 	}
2388 
2389 	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2390 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2391 		return key_senderror(so, m, ENOBUFS);
2392 	}
2393 
2394 	if (m->m_next)
2395 		m_freem(m->m_next);
2396 	m->m_next = NULL;
2397 	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2398 	newmsg = mtod(m, struct sadb_msg *);
2399 	newmsg->sadb_msg_errno = 0;
2400 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2401 
2402 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2403 }
2404 
2405 /*
2406  * SADB_SPDDUMP processing
2407  * receive
2408  *   <base>
2409  * from the user, and dump all SP leaves
2410  * and send,
2411  *   <base> .....
2412  * to the ikmpd.
2413  *
2414  * m will always be freed.
2415  */
2416 static int
2417 key_spddump(so, m, mhp)
2418 	struct socket *so;
2419 	struct mbuf *m;
2420 	const struct sadb_msghdr *mhp;
2421 {
2422 	struct secpolicy *sp;
2423 	int cnt;
2424 	u_int dir;
2425 	struct mbuf *n;
2426 
2427 	IPSEC_ASSERT(so != NULL, ("null socket"));
2428 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2429 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2430 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2431 
2432 	/* search SPD entry and get buffer size. */
2433 	cnt = 0;
2434 	SPTREE_LOCK();
2435 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2436 		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2437 			cnt++;
2438 		}
2439 	}
2440 
2441 	if (cnt == 0) {
2442 		SPTREE_UNLOCK();
2443 		return key_senderror(so, m, ENOENT);
2444 	}
2445 
2446 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2447 		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2448 			--cnt;
2449 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2450 			    mhp->msg->sadb_msg_pid);
2451 
2452 			if (n)
2453 				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2454 		}
2455 	}
2456 
2457 	SPTREE_UNLOCK();
2458 	m_freem(m);
2459 	return 0;
2460 }
2461 
2462 static struct mbuf *
2463 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid)
2464 {
2465 	struct mbuf *result = NULL, *m;
2466 	struct seclifetime lt;
2467 
2468 	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2469 	if (!m)
2470 		goto fail;
2471 	result = m;
2472 
2473 	/*
2474 	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2475 	 * we are sending traffic endpoints.
2476 	 */
2477 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2478 	    &sp->spidx.src.sa, sp->spidx.prefs,
2479 	    sp->spidx.ul_proto);
2480 	if (!m)
2481 		goto fail;
2482 	m_cat(result, m);
2483 
2484 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2485 	    &sp->spidx.dst.sa, sp->spidx.prefd,
2486 	    sp->spidx.ul_proto);
2487 	if (!m)
2488 		goto fail;
2489 	m_cat(result, m);
2490 
2491 	m = key_sp2msg(sp);
2492 	if (!m)
2493 		goto fail;
2494 	m_cat(result, m);
2495 
2496 	if(sp->lifetime){
2497 		lt.addtime=sp->created;
2498 		lt.usetime= sp->lastused;
2499 		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_CURRENT);
2500 		if (!m)
2501 			goto fail;
2502 		m_cat(result, m);
2503 
2504 		lt.addtime=sp->lifetime;
2505 		lt.usetime= sp->validtime;
2506 		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_HARD);
2507 		if (!m)
2508 			goto fail;
2509 		m_cat(result, m);
2510 	}
2511 
2512 	if ((result->m_flags & M_PKTHDR) == 0)
2513 		goto fail;
2514 
2515 	if (result->m_len < sizeof(struct sadb_msg)) {
2516 		result = m_pullup(result, sizeof(struct sadb_msg));
2517 		if (result == NULL)
2518 			goto fail;
2519 	}
2520 
2521 	result->m_pkthdr.len = 0;
2522 	for (m = result; m; m = m->m_next)
2523 		result->m_pkthdr.len += m->m_len;
2524 
2525 	mtod(result, struct sadb_msg *)->sadb_msg_len =
2526 	    PFKEY_UNIT64(result->m_pkthdr.len);
2527 
2528 	return result;
2529 
2530 fail:
2531 	m_freem(result);
2532 	return NULL;
2533 }
2534 
2535 /*
2536  * get PFKEY message length for security policy and request.
2537  */
2538 static u_int
2539 key_getspreqmsglen(sp)
2540 	struct secpolicy *sp;
2541 {
2542 	u_int tlen;
2543 
2544 	tlen = sizeof(struct sadb_x_policy);
2545 
2546 	/* if is the policy for ipsec ? */
2547 	if (sp->policy != IPSEC_POLICY_IPSEC)
2548 		return tlen;
2549 
2550 	/* get length of ipsec requests */
2551     {
2552 	struct ipsecrequest *isr;
2553 	int len;
2554 
2555 	for (isr = sp->req; isr != NULL; isr = isr->next) {
2556 		len = sizeof(struct sadb_x_ipsecrequest)
2557 			+ isr->saidx.src.sa.sa_len
2558 			+ isr->saidx.dst.sa.sa_len;
2559 
2560 		tlen += PFKEY_ALIGN8(len);
2561 	}
2562     }
2563 
2564 	return tlen;
2565 }
2566 
2567 /*
2568  * SADB_SPDEXPIRE processing
2569  * send
2570  *   <base, address(SD), lifetime(CH), policy>
2571  * to KMD by PF_KEY.
2572  *
2573  * OUT:	0	: succeed
2574  *	others	: error number
2575  */
2576 static int
2577 key_spdexpire(sp)
2578 	struct secpolicy *sp;
2579 {
2580 	struct mbuf *result = NULL, *m;
2581 	int len;
2582 	int error = -1;
2583 	struct sadb_lifetime *lt;
2584 
2585 	/* XXX: Why do we lock ? */
2586 
2587 	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2588 
2589 	/* set msg header */
2590 	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2591 	if (!m) {
2592 		error = ENOBUFS;
2593 		goto fail;
2594 	}
2595 	result = m;
2596 
2597 	/* create lifetime extension (current and hard) */
2598 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2599 	m = key_alloc_mbuf(len);
2600 	if (!m || m->m_next) {	/*XXX*/
2601 		if (m)
2602 			m_freem(m);
2603 		error = ENOBUFS;
2604 		goto fail;
2605 	}
2606 	bzero(mtod(m, caddr_t), len);
2607 	lt = mtod(m, struct sadb_lifetime *);
2608 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2609 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2610 	lt->sadb_lifetime_allocations = 0;
2611 	lt->sadb_lifetime_bytes = 0;
2612 	lt->sadb_lifetime_addtime = sp->created;
2613 	lt->sadb_lifetime_usetime = sp->lastused;
2614 	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2615 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2616 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2617 	lt->sadb_lifetime_allocations = 0;
2618 	lt->sadb_lifetime_bytes = 0;
2619 	lt->sadb_lifetime_addtime = sp->lifetime;
2620 	lt->sadb_lifetime_usetime = sp->validtime;
2621 	m_cat(result, m);
2622 
2623 	/*
2624 	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2625 	 * we are sending traffic endpoints.
2626 	 */
2627 
2628 	/* set sadb_address for source */
2629 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2630 	    &sp->spidx.src.sa,
2631 	    sp->spidx.prefs, sp->spidx.ul_proto);
2632 	if (!m) {
2633 		error = ENOBUFS;
2634 		goto fail;
2635 	}
2636 	m_cat(result, m);
2637 
2638 	/* set sadb_address for destination */
2639 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2640 	    &sp->spidx.dst.sa,
2641 	    sp->spidx.prefd, sp->spidx.ul_proto);
2642 	if (!m) {
2643 		error = ENOBUFS;
2644 		goto fail;
2645 	}
2646 	m_cat(result, m);
2647 
2648 	/* set secpolicy */
2649 	m = key_sp2msg(sp);
2650 	if (!m) {
2651 		error = ENOBUFS;
2652 		goto fail;
2653 	}
2654 	m_cat(result, m);
2655 
2656 	if ((result->m_flags & M_PKTHDR) == 0) {
2657 		error = EINVAL;
2658 		goto fail;
2659 	}
2660 
2661 	if (result->m_len < sizeof(struct sadb_msg)) {
2662 		result = m_pullup(result, sizeof(struct sadb_msg));
2663 		if (result == NULL) {
2664 			error = ENOBUFS;
2665 			goto fail;
2666 		}
2667 	}
2668 
2669 	result->m_pkthdr.len = 0;
2670 	for (m = result; m; m = m->m_next)
2671 		result->m_pkthdr.len += m->m_len;
2672 
2673 	mtod(result, struct sadb_msg *)->sadb_msg_len =
2674 	    PFKEY_UNIT64(result->m_pkthdr.len);
2675 
2676 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2677 
2678  fail:
2679 	if (result)
2680 		m_freem(result);
2681 	return error;
2682 }
2683 
2684 /* %%% SAD management */
2685 /*
2686  * allocating a memory for new SA head, and copy from the values of mhp.
2687  * OUT:	NULL	: failure due to the lack of memory.
2688  *	others	: pointer to new SA head.
2689  */
2690 static struct secashead *
2691 key_newsah(saidx)
2692 	struct secasindex *saidx;
2693 {
2694 	struct secashead *newsah;
2695 
2696 	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2697 
2698 	newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2699 	if (newsah != NULL) {
2700 		int i;
2701 		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2702 			LIST_INIT(&newsah->savtree[i]);
2703 		newsah->saidx = *saidx;
2704 
2705 		/* add to saidxtree */
2706 		newsah->state = SADB_SASTATE_MATURE;
2707 
2708 		SAHTREE_LOCK();
2709 		LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2710 		SAHTREE_UNLOCK();
2711 	}
2712 	return(newsah);
2713 }
2714 
2715 /*
2716  * delete SA index and all SA registerd.
2717  */
2718 static void
2719 key_delsah(sah)
2720 	struct secashead *sah;
2721 {
2722 	struct secasvar *sav, *nextsav;
2723 	u_int stateidx;
2724 	int zombie = 0;
2725 
2726 	IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2727 	SAHTREE_LOCK_ASSERT();
2728 
2729 	/* searching all SA registerd in the secindex. */
2730 	for (stateidx = 0;
2731 	     stateidx < _ARRAYLEN(saorder_state_any);
2732 	     stateidx++) {
2733 		u_int state = saorder_state_any[stateidx];
2734 		LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2735 			if (sav->refcnt == 0) {
2736 				/* sanity check */
2737 				KEY_CHKSASTATE(state, sav->state, __func__);
2738 				/*
2739 				 * do NOT call KEY_FREESAV here:
2740 				 * it will only delete the sav if refcnt == 1,
2741 				 * where we already know that refcnt == 0
2742 				 */
2743 				key_delsav(sav);
2744 			} else {
2745 				/* give up to delete this sa */
2746 				zombie++;
2747 			}
2748 		}
2749 	}
2750 	if (!zombie) {		/* delete only if there are savs */
2751 		/* remove from tree of SA index */
2752 		if (__LIST_CHAINED(sah))
2753 			LIST_REMOVE(sah, chain);
2754 		if (sah->sa_route.ro_rt) {
2755 			RTFREE(sah->sa_route.ro_rt);
2756 			sah->sa_route.ro_rt = (struct rtentry *)NULL;
2757 		}
2758 		free(sah, M_IPSEC_SAH);
2759 	}
2760 }
2761 
2762 /*
2763  * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2764  * and copy the values of mhp into new buffer.
2765  * When SAD message type is GETSPI:
2766  *	to set sequence number from acq_seq++,
2767  *	to set zero to SPI.
2768  *	not to call key_setsava().
2769  * OUT:	NULL	: fail
2770  *	others	: pointer to new secasvar.
2771  *
2772  * does not modify mbuf.  does not free mbuf on error.
2773  */
2774 static struct secasvar *
2775 key_newsav(m, mhp, sah, errp, where, tag)
2776 	struct mbuf *m;
2777 	const struct sadb_msghdr *mhp;
2778 	struct secashead *sah;
2779 	int *errp;
2780 	const char* where;
2781 	int tag;
2782 {
2783 	struct secasvar *newsav;
2784 	const struct sadb_sa *xsa;
2785 
2786 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2787 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2788 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2789 	IPSEC_ASSERT(sah != NULL, ("null secashead"));
2790 
2791 	newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2792 	if (newsav == NULL) {
2793 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2794 		*errp = ENOBUFS;
2795 		goto done;
2796 	}
2797 
2798 	switch (mhp->msg->sadb_msg_type) {
2799 	case SADB_GETSPI:
2800 		newsav->spi = 0;
2801 
2802 #ifdef IPSEC_DOSEQCHECK
2803 		/* sync sequence number */
2804 		if (mhp->msg->sadb_msg_seq == 0)
2805 			newsav->seq =
2806 				(V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2807 		else
2808 #endif
2809 			newsav->seq = mhp->msg->sadb_msg_seq;
2810 		break;
2811 
2812 	case SADB_ADD:
2813 		/* sanity check */
2814 		if (mhp->ext[SADB_EXT_SA] == NULL) {
2815 			free(newsav, M_IPSEC_SA);
2816 			newsav = NULL;
2817 			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2818 				__func__));
2819 			*errp = EINVAL;
2820 			goto done;
2821 		}
2822 		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2823 		newsav->spi = xsa->sadb_sa_spi;
2824 		newsav->seq = mhp->msg->sadb_msg_seq;
2825 		break;
2826 	default:
2827 		free(newsav, M_IPSEC_SA);
2828 		newsav = NULL;
2829 		*errp = EINVAL;
2830 		goto done;
2831 	}
2832 
2833 
2834 	/* copy sav values */
2835 	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2836 		*errp = key_setsaval(newsav, m, mhp);
2837 		if (*errp) {
2838 			free(newsav, M_IPSEC_SA);
2839 			newsav = NULL;
2840 			goto done;
2841 		}
2842 	}
2843 
2844 	SECASVAR_LOCK_INIT(newsav);
2845 
2846 	/* reset created */
2847 	newsav->created = time_second;
2848 	newsav->pid = mhp->msg->sadb_msg_pid;
2849 
2850 	/* add to satree */
2851 	newsav->sah = sah;
2852 	sa_initref(newsav);
2853 	newsav->state = SADB_SASTATE_LARVAL;
2854 
2855 	SAHTREE_LOCK();
2856 	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2857 			secasvar, chain);
2858 	SAHTREE_UNLOCK();
2859 done:
2860 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2861 		printf("DP %s from %s:%u return SP:%p\n", __func__,
2862 			where, tag, newsav));
2863 
2864 	return newsav;
2865 }
2866 
2867 /*
2868  * free() SA variable entry.
2869  */
2870 static void
2871 key_cleansav(struct secasvar *sav)
2872 {
2873 	/*
2874 	 * Cleanup xform state.  Note that zeroize'ing causes the
2875 	 * keys to be cleared; otherwise we must do it ourself.
2876 	 */
2877 	if (sav->tdb_xform != NULL) {
2878 		sav->tdb_xform->xf_zeroize(sav);
2879 		sav->tdb_xform = NULL;
2880 	} else {
2881 		KASSERT(sav->iv == NULL, ("iv but no xform"));
2882 		if (sav->key_auth != NULL)
2883 			bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2884 		if (sav->key_enc != NULL)
2885 			bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2886 	}
2887 	if (sav->key_auth != NULL) {
2888 		if (sav->key_auth->key_data != NULL)
2889 			free(sav->key_auth->key_data, M_IPSEC_MISC);
2890 		free(sav->key_auth, M_IPSEC_MISC);
2891 		sav->key_auth = NULL;
2892 	}
2893 	if (sav->key_enc != NULL) {
2894 		if (sav->key_enc->key_data != NULL)
2895 			free(sav->key_enc->key_data, M_IPSEC_MISC);
2896 		free(sav->key_enc, M_IPSEC_MISC);
2897 		sav->key_enc = NULL;
2898 	}
2899 	if (sav->sched) {
2900 		bzero(sav->sched, sav->schedlen);
2901 		free(sav->sched, M_IPSEC_MISC);
2902 		sav->sched = NULL;
2903 	}
2904 	if (sav->replay != NULL) {
2905 		free(sav->replay, M_IPSEC_MISC);
2906 		sav->replay = NULL;
2907 	}
2908 	if (sav->lft_c != NULL) {
2909 		free(sav->lft_c, M_IPSEC_MISC);
2910 		sav->lft_c = NULL;
2911 	}
2912 	if (sav->lft_h != NULL) {
2913 		free(sav->lft_h, M_IPSEC_MISC);
2914 		sav->lft_h = NULL;
2915 	}
2916 	if (sav->lft_s != NULL) {
2917 		free(sav->lft_s, M_IPSEC_MISC);
2918 		sav->lft_s = NULL;
2919 	}
2920 }
2921 
2922 /*
2923  * free() SA variable entry.
2924  */
2925 static void
2926 key_delsav(sav)
2927 	struct secasvar *sav;
2928 {
2929 	IPSEC_ASSERT(sav != NULL, ("null sav"));
2930 	IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2931 
2932 	/* remove from SA header */
2933 	if (__LIST_CHAINED(sav))
2934 		LIST_REMOVE(sav, chain);
2935 	key_cleansav(sav);
2936 	SECASVAR_LOCK_DESTROY(sav);
2937 	free(sav, M_IPSEC_SA);
2938 }
2939 
2940 /*
2941  * search SAD.
2942  * OUT:
2943  *	NULL	: not found
2944  *	others	: found, pointer to a SA.
2945  */
2946 static struct secashead *
2947 key_getsah(saidx)
2948 	struct secasindex *saidx;
2949 {
2950 	struct secashead *sah;
2951 
2952 	SAHTREE_LOCK();
2953 	LIST_FOREACH(sah, &V_sahtree, chain) {
2954 		if (sah->state == SADB_SASTATE_DEAD)
2955 			continue;
2956 		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2957 			break;
2958 	}
2959 	SAHTREE_UNLOCK();
2960 
2961 	return sah;
2962 }
2963 
2964 /*
2965  * check not to be duplicated SPI.
2966  * NOTE: this function is too slow due to searching all SAD.
2967  * OUT:
2968  *	NULL	: not found
2969  *	others	: found, pointer to a SA.
2970  */
2971 static struct secasvar *
2972 key_checkspidup(saidx, spi)
2973 	struct secasindex *saidx;
2974 	u_int32_t spi;
2975 {
2976 	struct secashead *sah;
2977 	struct secasvar *sav;
2978 
2979 	/* check address family */
2980 	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2981 		ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2982 			__func__));
2983 		return NULL;
2984 	}
2985 
2986 	sav = NULL;
2987 	/* check all SAD */
2988 	SAHTREE_LOCK();
2989 	LIST_FOREACH(sah, &V_sahtree, chain) {
2990 		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2991 			continue;
2992 		sav = key_getsavbyspi(sah, spi);
2993 		if (sav != NULL)
2994 			break;
2995 	}
2996 	SAHTREE_UNLOCK();
2997 
2998 	return sav;
2999 }
3000 
3001 /*
3002  * search SAD litmited alive SA, protocol, SPI.
3003  * OUT:
3004  *	NULL	: not found
3005  *	others	: found, pointer to a SA.
3006  */
3007 static struct secasvar *
3008 key_getsavbyspi(sah, spi)
3009 	struct secashead *sah;
3010 	u_int32_t spi;
3011 {
3012 	struct secasvar *sav;
3013 	u_int stateidx, state;
3014 
3015 	sav = NULL;
3016 	SAHTREE_LOCK_ASSERT();
3017 	/* search all status */
3018 	for (stateidx = 0;
3019 	     stateidx < _ARRAYLEN(saorder_state_alive);
3020 	     stateidx++) {
3021 
3022 		state = saorder_state_alive[stateidx];
3023 		LIST_FOREACH(sav, &sah->savtree[state], chain) {
3024 
3025 			/* sanity check */
3026 			if (sav->state != state) {
3027 				ipseclog((LOG_DEBUG, "%s: "
3028 				    "invalid sav->state (queue: %d SA: %d)\n",
3029 				    __func__, state, sav->state));
3030 				continue;
3031 			}
3032 
3033 			if (sav->spi == spi)
3034 				return sav;
3035 		}
3036 	}
3037 
3038 	return NULL;
3039 }
3040 
3041 /*
3042  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3043  * You must update these if need.
3044  * OUT:	0:	success.
3045  *	!0:	failure.
3046  *
3047  * does not modify mbuf.  does not free mbuf on error.
3048  */
3049 static int
3050 key_setsaval(sav, m, mhp)
3051 	struct secasvar *sav;
3052 	struct mbuf *m;
3053 	const struct sadb_msghdr *mhp;
3054 {
3055 	int error = 0;
3056 
3057 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
3058 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3059 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3060 
3061 	/* initialization */
3062 	sav->replay = NULL;
3063 	sav->key_auth = NULL;
3064 	sav->key_enc = NULL;
3065 	sav->sched = NULL;
3066 	sav->schedlen = 0;
3067 	sav->iv = NULL;
3068 	sav->lft_c = NULL;
3069 	sav->lft_h = NULL;
3070 	sav->lft_s = NULL;
3071 	sav->tdb_xform = NULL;		/* transform */
3072 	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
3073 	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
3074 	sav->tdb_compalgxform = NULL;	/* compression algorithm */
3075 	/*  Initialize even if NAT-T not compiled in: */
3076 	sav->natt_type = 0;
3077 	sav->natt_esp_frag_len = 0;
3078 
3079 	/* SA */
3080 	if (mhp->ext[SADB_EXT_SA] != NULL) {
3081 		const struct sadb_sa *sa0;
3082 
3083 		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3084 		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3085 			error = EINVAL;
3086 			goto fail;
3087 		}
3088 
3089 		sav->alg_auth = sa0->sadb_sa_auth;
3090 		sav->alg_enc = sa0->sadb_sa_encrypt;
3091 		sav->flags = sa0->sadb_sa_flags;
3092 
3093 		/* replay window */
3094 		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3095 			sav->replay = (struct secreplay *)
3096 				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3097 			if (sav->replay == NULL) {
3098 				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3099 					__func__));
3100 				error = ENOBUFS;
3101 				goto fail;
3102 			}
3103 			if (sa0->sadb_sa_replay != 0)
3104 				sav->replay->bitmap = (caddr_t)(sav->replay+1);
3105 			sav->replay->wsize = sa0->sadb_sa_replay;
3106 		}
3107 	}
3108 
3109 	/* Authentication keys */
3110 	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3111 		const struct sadb_key *key0;
3112 		int len;
3113 
3114 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3115 		len = mhp->extlen[SADB_EXT_KEY_AUTH];
3116 
3117 		error = 0;
3118 		if (len < sizeof(*key0)) {
3119 			error = EINVAL;
3120 			goto fail;
3121 		}
3122 		switch (mhp->msg->sadb_msg_satype) {
3123 		case SADB_SATYPE_AH:
3124 		case SADB_SATYPE_ESP:
3125 		case SADB_X_SATYPE_TCPSIGNATURE:
3126 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3127 			    sav->alg_auth != SADB_X_AALG_NULL)
3128 				error = EINVAL;
3129 			break;
3130 		case SADB_X_SATYPE_IPCOMP:
3131 		default:
3132 			error = EINVAL;
3133 			break;
3134 		}
3135 		if (error) {
3136 			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3137 				__func__));
3138 			goto fail;
3139 		}
3140 
3141 		sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3142 								M_IPSEC_MISC);
3143 		if (sav->key_auth == NULL ) {
3144 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3145 				  __func__));
3146 			error = ENOBUFS;
3147 			goto fail;
3148 		}
3149 	}
3150 
3151 	/* Encryption key */
3152 	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3153 		const struct sadb_key *key0;
3154 		int len;
3155 
3156 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3157 		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3158 
3159 		error = 0;
3160 		if (len < sizeof(*key0)) {
3161 			error = EINVAL;
3162 			goto fail;
3163 		}
3164 		switch (mhp->msg->sadb_msg_satype) {
3165 		case SADB_SATYPE_ESP:
3166 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3167 			    sav->alg_enc != SADB_EALG_NULL) {
3168 				error = EINVAL;
3169 				break;
3170 			}
3171 			sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3172 								       len,
3173 								       M_IPSEC_MISC);
3174 			if (sav->key_enc == NULL) {
3175 				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3176 					__func__));
3177 				error = ENOBUFS;
3178 				goto fail;
3179 			}
3180 			break;
3181 		case SADB_X_SATYPE_IPCOMP:
3182 			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3183 				error = EINVAL;
3184 			sav->key_enc = NULL;	/*just in case*/
3185 			break;
3186 		case SADB_SATYPE_AH:
3187 		case SADB_X_SATYPE_TCPSIGNATURE:
3188 		default:
3189 			error = EINVAL;
3190 			break;
3191 		}
3192 		if (error) {
3193 			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3194 				__func__));
3195 			goto fail;
3196 		}
3197 	}
3198 
3199 	/* set iv */
3200 	sav->ivlen = 0;
3201 
3202 	switch (mhp->msg->sadb_msg_satype) {
3203 	case SADB_SATYPE_AH:
3204 		error = xform_init(sav, XF_AH);
3205 		break;
3206 	case SADB_SATYPE_ESP:
3207 		error = xform_init(sav, XF_ESP);
3208 		break;
3209 	case SADB_X_SATYPE_IPCOMP:
3210 		error = xform_init(sav, XF_IPCOMP);
3211 		break;
3212 	case SADB_X_SATYPE_TCPSIGNATURE:
3213 		error = xform_init(sav, XF_TCPSIGNATURE);
3214 		break;
3215 	}
3216 	if (error) {
3217 		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3218 		        __func__, mhp->msg->sadb_msg_satype));
3219 		goto fail;
3220 	}
3221 
3222 	/* reset created */
3223 	sav->created = time_second;
3224 
3225 	/* make lifetime for CURRENT */
3226 	sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3227 	if (sav->lft_c == NULL) {
3228 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3229 		error = ENOBUFS;
3230 		goto fail;
3231 	}
3232 
3233 	sav->lft_c->allocations = 0;
3234 	sav->lft_c->bytes = 0;
3235 	sav->lft_c->addtime = time_second;
3236 	sav->lft_c->usetime = 0;
3237 
3238 	/* lifetimes for HARD and SOFT */
3239     {
3240 	const struct sadb_lifetime *lft0;
3241 
3242 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3243 	if (lft0 != NULL) {
3244 		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3245 			error = EINVAL;
3246 			goto fail;
3247 		}
3248 		sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3249 		if (sav->lft_h == NULL) {
3250 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3251 			error = ENOBUFS;
3252 			goto fail;
3253 		}
3254 		/* to be initialize ? */
3255 	}
3256 
3257 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3258 	if (lft0 != NULL) {
3259 		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3260 			error = EINVAL;
3261 			goto fail;
3262 		}
3263 		sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3264 		if (sav->lft_s == NULL) {
3265 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3266 			error = ENOBUFS;
3267 			goto fail;
3268 		}
3269 		/* to be initialize ? */
3270 	}
3271     }
3272 
3273 	return 0;
3274 
3275  fail:
3276 	/* initialization */
3277 	key_cleansav(sav);
3278 
3279 	return error;
3280 }
3281 
3282 /*
3283  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3284  * OUT:	0:	valid
3285  *	other:	errno
3286  */
3287 static int
3288 key_mature(struct secasvar *sav)
3289 {
3290 	int error;
3291 
3292 	/* check SPI value */
3293 	switch (sav->sah->saidx.proto) {
3294 	case IPPROTO_ESP:
3295 	case IPPROTO_AH:
3296 		/*
3297 		 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3298 		 * 1-255 reserved by IANA for future use,
3299 		 * 0 for implementation specific, local use.
3300 		 */
3301 		if (ntohl(sav->spi) <= 255) {
3302 			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3303 			    __func__, (u_int32_t)ntohl(sav->spi)));
3304 			return EINVAL;
3305 		}
3306 		break;
3307 	}
3308 
3309 	/* check satype */
3310 	switch (sav->sah->saidx.proto) {
3311 	case IPPROTO_ESP:
3312 		/* check flags */
3313 		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3314 		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3315 			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3316 				"given to old-esp.\n", __func__));
3317 			return EINVAL;
3318 		}
3319 		error = xform_init(sav, XF_ESP);
3320 		break;
3321 	case IPPROTO_AH:
3322 		/* check flags */
3323 		if (sav->flags & SADB_X_EXT_DERIV) {
3324 			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3325 				"given to AH SA.\n", __func__));
3326 			return EINVAL;
3327 		}
3328 		if (sav->alg_enc != SADB_EALG_NONE) {
3329 			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3330 				"mismated.\n", __func__));
3331 			return(EINVAL);
3332 		}
3333 		error = xform_init(sav, XF_AH);
3334 		break;
3335 	case IPPROTO_IPCOMP:
3336 		if (sav->alg_auth != SADB_AALG_NONE) {
3337 			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3338 				"mismated.\n", __func__));
3339 			return(EINVAL);
3340 		}
3341 		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3342 		 && ntohl(sav->spi) >= 0x10000) {
3343 			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3344 				__func__));
3345 			return(EINVAL);
3346 		}
3347 		error = xform_init(sav, XF_IPCOMP);
3348 		break;
3349 	case IPPROTO_TCP:
3350 		if (sav->alg_enc != SADB_EALG_NONE) {
3351 			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3352 				"mismated.\n", __func__));
3353 			return(EINVAL);
3354 		}
3355 		error = xform_init(sav, XF_TCPSIGNATURE);
3356 		break;
3357 	default:
3358 		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3359 		error = EPROTONOSUPPORT;
3360 		break;
3361 	}
3362 	if (error == 0) {
3363 		SAHTREE_LOCK();
3364 		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3365 		SAHTREE_UNLOCK();
3366 	}
3367 	return (error);
3368 }
3369 
3370 /*
3371  * subroutine for SADB_GET and SADB_DUMP.
3372  */
3373 static struct mbuf *
3374 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3375     u_int32_t seq, u_int32_t pid)
3376 {
3377 	struct mbuf *result = NULL, *tres = NULL, *m;
3378 	int i;
3379 	int dumporder[] = {
3380 		SADB_EXT_SA, SADB_X_EXT_SA2,
3381 		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3382 		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3383 		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3384 		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3385 		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3386 #ifdef IPSEC_NAT_T
3387 		SADB_X_EXT_NAT_T_TYPE,
3388 		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3389 		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3390 		SADB_X_EXT_NAT_T_FRAG,
3391 #endif
3392 	};
3393 
3394 	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3395 	if (m == NULL)
3396 		goto fail;
3397 	result = m;
3398 
3399 	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3400 		m = NULL;
3401 		switch (dumporder[i]) {
3402 		case SADB_EXT_SA:
3403 			m = key_setsadbsa(sav);
3404 			if (!m)
3405 				goto fail;
3406 			break;
3407 
3408 		case SADB_X_EXT_SA2:
3409 			m = key_setsadbxsa2(sav->sah->saidx.mode,
3410 					sav->replay ? sav->replay->count : 0,
3411 					sav->sah->saidx.reqid);
3412 			if (!m)
3413 				goto fail;
3414 			break;
3415 
3416 		case SADB_EXT_ADDRESS_SRC:
3417 			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3418 			    &sav->sah->saidx.src.sa,
3419 			    FULLMASK, IPSEC_ULPROTO_ANY);
3420 			if (!m)
3421 				goto fail;
3422 			break;
3423 
3424 		case SADB_EXT_ADDRESS_DST:
3425 			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3426 			    &sav->sah->saidx.dst.sa,
3427 			    FULLMASK, IPSEC_ULPROTO_ANY);
3428 			if (!m)
3429 				goto fail;
3430 			break;
3431 
3432 		case SADB_EXT_KEY_AUTH:
3433 			if (!sav->key_auth)
3434 				continue;
3435 			m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3436 			if (!m)
3437 				goto fail;
3438 			break;
3439 
3440 		case SADB_EXT_KEY_ENCRYPT:
3441 			if (!sav->key_enc)
3442 				continue;
3443 			m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3444 			if (!m)
3445 				goto fail;
3446 			break;
3447 
3448 		case SADB_EXT_LIFETIME_CURRENT:
3449 			if (!sav->lft_c)
3450 				continue;
3451 			m = key_setlifetime(sav->lft_c,
3452 					    SADB_EXT_LIFETIME_CURRENT);
3453 			if (!m)
3454 				goto fail;
3455 			break;
3456 
3457 		case SADB_EXT_LIFETIME_HARD:
3458 			if (!sav->lft_h)
3459 				continue;
3460 			m = key_setlifetime(sav->lft_h,
3461 					    SADB_EXT_LIFETIME_HARD);
3462 			if (!m)
3463 				goto fail;
3464 			break;
3465 
3466 		case SADB_EXT_LIFETIME_SOFT:
3467 			if (!sav->lft_s)
3468 				continue;
3469 			m = key_setlifetime(sav->lft_s,
3470 					    SADB_EXT_LIFETIME_SOFT);
3471 
3472 			if (!m)
3473 				goto fail;
3474 			break;
3475 
3476 #ifdef IPSEC_NAT_T
3477 		case SADB_X_EXT_NAT_T_TYPE:
3478 			m = key_setsadbxtype(sav->natt_type);
3479 			if (!m)
3480 				goto fail;
3481 			break;
3482 
3483 		case SADB_X_EXT_NAT_T_DPORT:
3484 			m = key_setsadbxport(
3485 			    KEY_PORTFROMSADDR(&sav->sah->saidx.dst),
3486 			    SADB_X_EXT_NAT_T_DPORT);
3487 			if (!m)
3488 				goto fail;
3489 			break;
3490 
3491 		case SADB_X_EXT_NAT_T_SPORT:
3492 			m = key_setsadbxport(
3493 			    KEY_PORTFROMSADDR(&sav->sah->saidx.src),
3494 			    SADB_X_EXT_NAT_T_SPORT);
3495 			if (!m)
3496 				goto fail;
3497 			break;
3498 
3499 		case SADB_X_EXT_NAT_T_OAI:
3500 		case SADB_X_EXT_NAT_T_OAR:
3501 		case SADB_X_EXT_NAT_T_FRAG:
3502 			/* We do not (yet) support those. */
3503 			continue;
3504 #endif
3505 
3506 		case SADB_EXT_ADDRESS_PROXY:
3507 		case SADB_EXT_IDENTITY_SRC:
3508 		case SADB_EXT_IDENTITY_DST:
3509 			/* XXX: should we brought from SPD ? */
3510 		case SADB_EXT_SENSITIVITY:
3511 		default:
3512 			continue;
3513 		}
3514 
3515 		if (!m)
3516 			goto fail;
3517 		if (tres)
3518 			m_cat(m, tres);
3519 		tres = m;
3520 
3521 	}
3522 
3523 	m_cat(result, tres);
3524 	if (result->m_len < sizeof(struct sadb_msg)) {
3525 		result = m_pullup(result, sizeof(struct sadb_msg));
3526 		if (result == NULL)
3527 			goto fail;
3528 	}
3529 
3530 	result->m_pkthdr.len = 0;
3531 	for (m = result; m; m = m->m_next)
3532 		result->m_pkthdr.len += m->m_len;
3533 
3534 	mtod(result, struct sadb_msg *)->sadb_msg_len =
3535 	    PFKEY_UNIT64(result->m_pkthdr.len);
3536 
3537 	return result;
3538 
3539 fail:
3540 	m_freem(result);
3541 	m_freem(tres);
3542 	return NULL;
3543 }
3544 
3545 /*
3546  * set data into sadb_msg.
3547  */
3548 static struct mbuf *
3549 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3550     pid_t pid, u_int16_t reserved)
3551 {
3552 	struct mbuf *m;
3553 	struct sadb_msg *p;
3554 	int len;
3555 
3556 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3557 	if (len > MCLBYTES)
3558 		return NULL;
3559 	MGETHDR(m, M_DONTWAIT, MT_DATA);
3560 	if (m && len > MHLEN) {
3561 		MCLGET(m, M_DONTWAIT);
3562 		if ((m->m_flags & M_EXT) == 0) {
3563 			m_freem(m);
3564 			m = NULL;
3565 		}
3566 	}
3567 	if (!m)
3568 		return NULL;
3569 	m->m_pkthdr.len = m->m_len = len;
3570 	m->m_next = NULL;
3571 
3572 	p = mtod(m, struct sadb_msg *);
3573 
3574 	bzero(p, len);
3575 	p->sadb_msg_version = PF_KEY_V2;
3576 	p->sadb_msg_type = type;
3577 	p->sadb_msg_errno = 0;
3578 	p->sadb_msg_satype = satype;
3579 	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3580 	p->sadb_msg_reserved = reserved;
3581 	p->sadb_msg_seq = seq;
3582 	p->sadb_msg_pid = (u_int32_t)pid;
3583 
3584 	return m;
3585 }
3586 
3587 /*
3588  * copy secasvar data into sadb_address.
3589  */
3590 static struct mbuf *
3591 key_setsadbsa(sav)
3592 	struct secasvar *sav;
3593 {
3594 	struct mbuf *m;
3595 	struct sadb_sa *p;
3596 	int len;
3597 
3598 	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3599 	m = key_alloc_mbuf(len);
3600 	if (!m || m->m_next) {	/*XXX*/
3601 		if (m)
3602 			m_freem(m);
3603 		return NULL;
3604 	}
3605 
3606 	p = mtod(m, struct sadb_sa *);
3607 
3608 	bzero(p, len);
3609 	p->sadb_sa_len = PFKEY_UNIT64(len);
3610 	p->sadb_sa_exttype = SADB_EXT_SA;
3611 	p->sadb_sa_spi = sav->spi;
3612 	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3613 	p->sadb_sa_state = sav->state;
3614 	p->sadb_sa_auth = sav->alg_auth;
3615 	p->sadb_sa_encrypt = sav->alg_enc;
3616 	p->sadb_sa_flags = sav->flags;
3617 
3618 	return m;
3619 }
3620 
3621 /*
3622  * set data into sadb_address.
3623  */
3624 static struct mbuf *
3625 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto)
3626 {
3627 	struct mbuf *m;
3628 	struct sadb_address *p;
3629 	size_t len;
3630 
3631 	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3632 	    PFKEY_ALIGN8(saddr->sa_len);
3633 	m = key_alloc_mbuf(len);
3634 	if (!m || m->m_next) {	/*XXX*/
3635 		if (m)
3636 			m_freem(m);
3637 		return NULL;
3638 	}
3639 
3640 	p = mtod(m, struct sadb_address *);
3641 
3642 	bzero(p, len);
3643 	p->sadb_address_len = PFKEY_UNIT64(len);
3644 	p->sadb_address_exttype = exttype;
3645 	p->sadb_address_proto = ul_proto;
3646 	if (prefixlen == FULLMASK) {
3647 		switch (saddr->sa_family) {
3648 		case AF_INET:
3649 			prefixlen = sizeof(struct in_addr) << 3;
3650 			break;
3651 		case AF_INET6:
3652 			prefixlen = sizeof(struct in6_addr) << 3;
3653 			break;
3654 		default:
3655 			; /*XXX*/
3656 		}
3657 	}
3658 	p->sadb_address_prefixlen = prefixlen;
3659 	p->sadb_address_reserved = 0;
3660 
3661 	bcopy(saddr,
3662 	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3663 	    saddr->sa_len);
3664 
3665 	return m;
3666 }
3667 
3668 /*
3669  * set data into sadb_x_sa2.
3670  */
3671 static struct mbuf *
3672 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3673 {
3674 	struct mbuf *m;
3675 	struct sadb_x_sa2 *p;
3676 	size_t len;
3677 
3678 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3679 	m = key_alloc_mbuf(len);
3680 	if (!m || m->m_next) {	/*XXX*/
3681 		if (m)
3682 			m_freem(m);
3683 		return NULL;
3684 	}
3685 
3686 	p = mtod(m, struct sadb_x_sa2 *);
3687 
3688 	bzero(p, len);
3689 	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3690 	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3691 	p->sadb_x_sa2_mode = mode;
3692 	p->sadb_x_sa2_reserved1 = 0;
3693 	p->sadb_x_sa2_reserved2 = 0;
3694 	p->sadb_x_sa2_sequence = seq;
3695 	p->sadb_x_sa2_reqid = reqid;
3696 
3697 	return m;
3698 }
3699 
3700 #ifdef IPSEC_NAT_T
3701 /*
3702  * Set a type in sadb_x_nat_t_type.
3703  */
3704 static struct mbuf *
3705 key_setsadbxtype(u_int16_t type)
3706 {
3707 	struct mbuf *m;
3708 	size_t len;
3709 	struct sadb_x_nat_t_type *p;
3710 
3711 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3712 
3713 	m = key_alloc_mbuf(len);
3714 	if (!m || m->m_next) {	/*XXX*/
3715 		if (m)
3716 			m_freem(m);
3717 		return (NULL);
3718 	}
3719 
3720 	p = mtod(m, struct sadb_x_nat_t_type *);
3721 
3722 	bzero(p, len);
3723 	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3724 	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3725 	p->sadb_x_nat_t_type_type = type;
3726 
3727 	return (m);
3728 }
3729 /*
3730  * Set a port in sadb_x_nat_t_port.
3731  * In contrast to default RFC 2367 behaviour, port is in network byte order.
3732  */
3733 static struct mbuf *
3734 key_setsadbxport(u_int16_t port, u_int16_t type)
3735 {
3736 	struct mbuf *m;
3737 	size_t len;
3738 	struct sadb_x_nat_t_port *p;
3739 
3740 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3741 
3742 	m = key_alloc_mbuf(len);
3743 	if (!m || m->m_next) {	/*XXX*/
3744 		if (m)
3745 			m_freem(m);
3746 		return (NULL);
3747 	}
3748 
3749 	p = mtod(m, struct sadb_x_nat_t_port *);
3750 
3751 	bzero(p, len);
3752 	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3753 	p->sadb_x_nat_t_port_exttype = type;
3754 	p->sadb_x_nat_t_port_port = port;
3755 
3756 	return (m);
3757 }
3758 
3759 /*
3760  * Get port from sockaddr. Port is in network byte order.
3761  */
3762 u_int16_t
3763 key_portfromsaddr(struct sockaddr *sa)
3764 {
3765 
3766 	switch (sa->sa_family) {
3767 #ifdef INET
3768 	case AF_INET:
3769 		return ((struct sockaddr_in *)sa)->sin_port;
3770 #endif
3771 #ifdef INET6
3772 	case AF_INET6:
3773 		return ((struct sockaddr_in6 *)sa)->sin6_port;
3774 #endif
3775 	}
3776 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
3777 		printf("DP %s unexpected address family %d\n",
3778 			__func__, sa->sa_family));
3779 	return (0);
3780 }
3781 #endif /* IPSEC_NAT_T */
3782 
3783 /*
3784  * Set port in struct sockaddr. Port is in network byte order.
3785  */
3786 static void
3787 key_porttosaddr(struct sockaddr *sa, u_int16_t port)
3788 {
3789 
3790 	switch (sa->sa_family) {
3791 #ifdef INET
3792 	case AF_INET:
3793 		((struct sockaddr_in *)sa)->sin_port = port;
3794 		break;
3795 #endif
3796 #ifdef INET6
3797 	case AF_INET6:
3798 		((struct sockaddr_in6 *)sa)->sin6_port = port;
3799 		break;
3800 #endif
3801 	default:
3802 		ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
3803 			__func__, sa->sa_family));
3804 		break;
3805 	}
3806 }
3807 
3808 /*
3809  * set data into sadb_x_policy
3810  */
3811 static struct mbuf *
3812 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3813 {
3814 	struct mbuf *m;
3815 	struct sadb_x_policy *p;
3816 	size_t len;
3817 
3818 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3819 	m = key_alloc_mbuf(len);
3820 	if (!m || m->m_next) {	/*XXX*/
3821 		if (m)
3822 			m_freem(m);
3823 		return NULL;
3824 	}
3825 
3826 	p = mtod(m, struct sadb_x_policy *);
3827 
3828 	bzero(p, len);
3829 	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3830 	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3831 	p->sadb_x_policy_type = type;
3832 	p->sadb_x_policy_dir = dir;
3833 	p->sadb_x_policy_id = id;
3834 
3835 	return m;
3836 }
3837 
3838 /* %%% utilities */
3839 /* Take a key message (sadb_key) from the socket and turn it into one
3840  * of the kernel's key structures (seckey).
3841  *
3842  * IN: pointer to the src
3843  * OUT: NULL no more memory
3844  */
3845 struct seckey *
3846 key_dup_keymsg(const struct sadb_key *src, u_int len,
3847 	       struct malloc_type *type)
3848 {
3849 	struct seckey *dst;
3850 	dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3851 	if (dst != NULL) {
3852 		dst->bits = src->sadb_key_bits;
3853 		dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3854 		if (dst->key_data != NULL) {
3855 			bcopy((const char *)src + sizeof(struct sadb_key),
3856 			      dst->key_data, len);
3857 		} else {
3858 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3859 				  __func__));
3860 			free(dst, type);
3861 			dst = NULL;
3862 		}
3863 	} else {
3864 		ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3865 			  __func__));
3866 
3867 	}
3868 	return dst;
3869 }
3870 
3871 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
3872  * turn it into one of the kernel's lifetime structures (seclifetime).
3873  *
3874  * IN: pointer to the destination, source and malloc type
3875  * OUT: NULL, no more memory
3876  */
3877 
3878 static struct seclifetime *
3879 key_dup_lifemsg(const struct sadb_lifetime *src,
3880 		 struct malloc_type *type)
3881 {
3882 	struct seclifetime *dst = NULL;
3883 
3884 	dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3885 					   type, M_NOWAIT);
3886 	if (dst == NULL) {
3887 		/* XXX counter */
3888 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3889 	} else {
3890 		dst->allocations = src->sadb_lifetime_allocations;
3891 		dst->bytes = src->sadb_lifetime_bytes;
3892 		dst->addtime = src->sadb_lifetime_addtime;
3893 		dst->usetime = src->sadb_lifetime_usetime;
3894 	}
3895 	return dst;
3896 }
3897 
3898 /* compare my own address
3899  * OUT:	1: true, i.e. my address.
3900  *	0: false
3901  */
3902 int
3903 key_ismyaddr(sa)
3904 	struct sockaddr *sa;
3905 {
3906 #ifdef INET
3907 	struct sockaddr_in *sin;
3908 	struct in_ifaddr *ia;
3909 #endif
3910 
3911 	IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3912 
3913 	switch (sa->sa_family) {
3914 #ifdef INET
3915 	case AF_INET:
3916 		sin = (struct sockaddr_in *)sa;
3917 		IN_IFADDR_RLOCK();
3918 		for (ia = V_in_ifaddrhead.tqh_first; ia;
3919 		     ia = ia->ia_link.tqe_next)
3920 		{
3921 			if (sin->sin_family == ia->ia_addr.sin_family &&
3922 			    sin->sin_len == ia->ia_addr.sin_len &&
3923 			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3924 			{
3925 				IN_IFADDR_RUNLOCK();
3926 				return 1;
3927 			}
3928 		}
3929 		IN_IFADDR_RUNLOCK();
3930 		break;
3931 #endif
3932 #ifdef INET6
3933 	case AF_INET6:
3934 		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3935 #endif
3936 	}
3937 
3938 	return 0;
3939 }
3940 
3941 #ifdef INET6
3942 /*
3943  * compare my own address for IPv6.
3944  * 1: ours
3945  * 0: other
3946  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3947  */
3948 #include <netinet6/in6_var.h>
3949 
3950 static int
3951 key_ismyaddr6(sin6)
3952 	struct sockaddr_in6 *sin6;
3953 {
3954 	struct in6_ifaddr *ia;
3955 #if 0
3956 	struct in6_multi *in6m;
3957 #endif
3958 
3959 	IN6_IFADDR_RLOCK();
3960 	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
3961 		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3962 		    (struct sockaddr *)&ia->ia_addr, 0) == 0) {
3963 			IN6_IFADDR_RUNLOCK();
3964 			return 1;
3965 		}
3966 
3967 #if 0
3968 		/*
3969 		 * XXX Multicast
3970 		 * XXX why do we care about multlicast here while we don't care
3971 		 * about IPv4 multicast??
3972 		 * XXX scope
3973 		 */
3974 		in6m = NULL;
3975 		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3976 		if (in6m) {
3977 			IN6_IFADDR_RUNLOCK();
3978 			return 1;
3979 		}
3980 #endif
3981 	}
3982 	IN6_IFADDR_RUNLOCK();
3983 
3984 	/* loopback, just for safety */
3985 	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3986 		return 1;
3987 
3988 	return 0;
3989 }
3990 #endif /*INET6*/
3991 
3992 /*
3993  * compare two secasindex structure.
3994  * flag can specify to compare 2 saidxes.
3995  * compare two secasindex structure without both mode and reqid.
3996  * don't compare port.
3997  * IN:
3998  *      saidx0: source, it can be in SAD.
3999  *      saidx1: object.
4000  * OUT:
4001  *      1 : equal
4002  *      0 : not equal
4003  */
4004 static int
4005 key_cmpsaidx(
4006 	const struct secasindex *saidx0,
4007 	const struct secasindex *saidx1,
4008 	int flag)
4009 {
4010 	int chkport = 0;
4011 
4012 	/* sanity */
4013 	if (saidx0 == NULL && saidx1 == NULL)
4014 		return 1;
4015 
4016 	if (saidx0 == NULL || saidx1 == NULL)
4017 		return 0;
4018 
4019 	if (saidx0->proto != saidx1->proto)
4020 		return 0;
4021 
4022 	if (flag == CMP_EXACTLY) {
4023 		if (saidx0->mode != saidx1->mode)
4024 			return 0;
4025 		if (saidx0->reqid != saidx1->reqid)
4026 			return 0;
4027 		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4028 		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4029 			return 0;
4030 	} else {
4031 
4032 		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4033 		if (flag == CMP_MODE_REQID
4034 		  ||flag == CMP_REQID) {
4035 			/*
4036 			 * If reqid of SPD is non-zero, unique SA is required.
4037 			 * The result must be of same reqid in this case.
4038 			 */
4039 			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4040 				return 0;
4041 		}
4042 
4043 		if (flag == CMP_MODE_REQID) {
4044 			if (saidx0->mode != IPSEC_MODE_ANY
4045 			 && saidx0->mode != saidx1->mode)
4046 				return 0;
4047 		}
4048 
4049 #ifdef IPSEC_NAT_T
4050 		/*
4051 		 * If NAT-T is enabled, check ports for tunnel mode.
4052 		 * Do not check ports if they are set to zero in the SPD.
4053 		 * Also do not do it for transport mode, as there is no
4054 		 * port information available in the SP.
4055 		 */
4056 		if (saidx1->mode == IPSEC_MODE_TUNNEL &&
4057 		    saidx1->src.sa.sa_family == AF_INET &&
4058 		    saidx1->dst.sa.sa_family == AF_INET &&
4059 		    ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
4060 		    ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
4061 			chkport = 1;
4062 #endif /* IPSEC_NAT_T */
4063 
4064 		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
4065 			return 0;
4066 		}
4067 		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
4068 			return 0;
4069 		}
4070 	}
4071 
4072 	return 1;
4073 }
4074 
4075 /*
4076  * compare two secindex structure exactly.
4077  * IN:
4078  *	spidx0: source, it is often in SPD.
4079  *	spidx1: object, it is often from PFKEY message.
4080  * OUT:
4081  *	1 : equal
4082  *	0 : not equal
4083  */
4084 static int
4085 key_cmpspidx_exactly(
4086 	struct secpolicyindex *spidx0,
4087 	struct secpolicyindex *spidx1)
4088 {
4089 	/* sanity */
4090 	if (spidx0 == NULL && spidx1 == NULL)
4091 		return 1;
4092 
4093 	if (spidx0 == NULL || spidx1 == NULL)
4094 		return 0;
4095 
4096 	if (spidx0->prefs != spidx1->prefs
4097 	 || spidx0->prefd != spidx1->prefd
4098 	 || spidx0->ul_proto != spidx1->ul_proto)
4099 		return 0;
4100 
4101 	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4102 	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4103 }
4104 
4105 /*
4106  * compare two secindex structure with mask.
4107  * IN:
4108  *	spidx0: source, it is often in SPD.
4109  *	spidx1: object, it is often from IP header.
4110  * OUT:
4111  *	1 : equal
4112  *	0 : not equal
4113  */
4114 static int
4115 key_cmpspidx_withmask(
4116 	struct secpolicyindex *spidx0,
4117 	struct secpolicyindex *spidx1)
4118 {
4119 	/* sanity */
4120 	if (spidx0 == NULL && spidx1 == NULL)
4121 		return 1;
4122 
4123 	if (spidx0 == NULL || spidx1 == NULL)
4124 		return 0;
4125 
4126 	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4127 	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4128 	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4129 	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4130 		return 0;
4131 
4132 	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4133 	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4134 	 && spidx0->ul_proto != spidx1->ul_proto)
4135 		return 0;
4136 
4137 	switch (spidx0->src.sa.sa_family) {
4138 	case AF_INET:
4139 		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4140 		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4141 			return 0;
4142 		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4143 		    &spidx1->src.sin.sin_addr, spidx0->prefs))
4144 			return 0;
4145 		break;
4146 	case AF_INET6:
4147 		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4148 		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4149 			return 0;
4150 		/*
4151 		 * scope_id check. if sin6_scope_id is 0, we regard it
4152 		 * as a wildcard scope, which matches any scope zone ID.
4153 		 */
4154 		if (spidx0->src.sin6.sin6_scope_id &&
4155 		    spidx1->src.sin6.sin6_scope_id &&
4156 		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4157 			return 0;
4158 		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4159 		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4160 			return 0;
4161 		break;
4162 	default:
4163 		/* XXX */
4164 		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4165 			return 0;
4166 		break;
4167 	}
4168 
4169 	switch (spidx0->dst.sa.sa_family) {
4170 	case AF_INET:
4171 		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4172 		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4173 			return 0;
4174 		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4175 		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
4176 			return 0;
4177 		break;
4178 	case AF_INET6:
4179 		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4180 		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4181 			return 0;
4182 		/*
4183 		 * scope_id check. if sin6_scope_id is 0, we regard it
4184 		 * as a wildcard scope, which matches any scope zone ID.
4185 		 */
4186 		if (spidx0->dst.sin6.sin6_scope_id &&
4187 		    spidx1->dst.sin6.sin6_scope_id &&
4188 		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4189 			return 0;
4190 		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4191 		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4192 			return 0;
4193 		break;
4194 	default:
4195 		/* XXX */
4196 		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4197 			return 0;
4198 		break;
4199 	}
4200 
4201 	/* XXX Do we check other field ?  e.g. flowinfo */
4202 
4203 	return 1;
4204 }
4205 
4206 /* returns 0 on match */
4207 static int
4208 key_sockaddrcmp(
4209 	const struct sockaddr *sa1,
4210 	const struct sockaddr *sa2,
4211 	int port)
4212 {
4213 #ifdef satosin
4214 #undef satosin
4215 #endif
4216 #define satosin(s) ((const struct sockaddr_in *)s)
4217 #ifdef satosin6
4218 #undef satosin6
4219 #endif
4220 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4221 	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4222 		return 1;
4223 
4224 	switch (sa1->sa_family) {
4225 	case AF_INET:
4226 		if (sa1->sa_len != sizeof(struct sockaddr_in))
4227 			return 1;
4228 		if (satosin(sa1)->sin_addr.s_addr !=
4229 		    satosin(sa2)->sin_addr.s_addr) {
4230 			return 1;
4231 		}
4232 		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4233 			return 1;
4234 		break;
4235 	case AF_INET6:
4236 		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4237 			return 1;	/*EINVAL*/
4238 		if (satosin6(sa1)->sin6_scope_id !=
4239 		    satosin6(sa2)->sin6_scope_id) {
4240 			return 1;
4241 		}
4242 		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4243 		    &satosin6(sa2)->sin6_addr)) {
4244 			return 1;
4245 		}
4246 		if (port &&
4247 		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4248 			return 1;
4249 		}
4250 		break;
4251 	default:
4252 		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4253 			return 1;
4254 		break;
4255 	}
4256 
4257 	return 0;
4258 #undef satosin
4259 #undef satosin6
4260 }
4261 
4262 /*
4263  * compare two buffers with mask.
4264  * IN:
4265  *	addr1: source
4266  *	addr2: object
4267  *	bits:  Number of bits to compare
4268  * OUT:
4269  *	1 : equal
4270  *	0 : not equal
4271  */
4272 static int
4273 key_bbcmp(const void *a1, const void *a2, u_int bits)
4274 {
4275 	const unsigned char *p1 = a1;
4276 	const unsigned char *p2 = a2;
4277 
4278 	/* XXX: This could be considerably faster if we compare a word
4279 	 * at a time, but it is complicated on LSB Endian machines */
4280 
4281 	/* Handle null pointers */
4282 	if (p1 == NULL || p2 == NULL)
4283 		return (p1 == p2);
4284 
4285 	while (bits >= 8) {
4286 		if (*p1++ != *p2++)
4287 			return 0;
4288 		bits -= 8;
4289 	}
4290 
4291 	if (bits > 0) {
4292 		u_int8_t mask = ~((1<<(8-bits))-1);
4293 		if ((*p1 & mask) != (*p2 & mask))
4294 			return 0;
4295 	}
4296 	return 1;	/* Match! */
4297 }
4298 
4299 static void
4300 key_flush_spd(time_t now)
4301 {
4302 	static u_int16_t sptree_scangen = 0;
4303 	u_int16_t gen = sptree_scangen++;
4304 	struct secpolicy *sp;
4305 	u_int dir;
4306 
4307 	/* SPD */
4308 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4309 restart:
4310 		SPTREE_LOCK();
4311 		LIST_FOREACH(sp, &V_sptree[dir], chain) {
4312 			if (sp->scangen == gen)		/* previously handled */
4313 				continue;
4314 			sp->scangen = gen;
4315 			if (sp->state == IPSEC_SPSTATE_DEAD &&
4316 			    sp->refcnt == 1) {
4317 				/*
4318 				 * Ensure that we only decrease refcnt once,
4319 				 * when we're the last consumer.
4320 				 * Directly call SP_DELREF/key_delsp instead
4321 				 * of KEY_FREESP to avoid unlocking/relocking
4322 				 * SPTREE_LOCK before key_delsp: may refcnt
4323 				 * be increased again during that time ?
4324 				 * NB: also clean entries created by
4325 				 * key_spdflush
4326 				 */
4327 				SP_DELREF(sp);
4328 				key_delsp(sp);
4329 				SPTREE_UNLOCK();
4330 				goto restart;
4331 			}
4332 			if (sp->lifetime == 0 && sp->validtime == 0)
4333 				continue;
4334 			if ((sp->lifetime && now - sp->created > sp->lifetime)
4335 			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4336 				sp->state = IPSEC_SPSTATE_DEAD;
4337 				SPTREE_UNLOCK();
4338 				key_spdexpire(sp);
4339 				goto restart;
4340 			}
4341 		}
4342 		SPTREE_UNLOCK();
4343 	}
4344 }
4345 
4346 static void
4347 key_flush_sad(time_t now)
4348 {
4349 	struct secashead *sah, *nextsah;
4350 	struct secasvar *sav, *nextsav;
4351 
4352 	/* SAD */
4353 	SAHTREE_LOCK();
4354 	LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4355 		/* if sah has been dead, then delete it and process next sah. */
4356 		if (sah->state == SADB_SASTATE_DEAD) {
4357 			key_delsah(sah);
4358 			continue;
4359 		}
4360 
4361 		/* if LARVAL entry doesn't become MATURE, delete it. */
4362 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4363 			/* Need to also check refcnt for a larval SA ??? */
4364 			if (now - sav->created > V_key_larval_lifetime)
4365 				KEY_FREESAV(&sav);
4366 		}
4367 
4368 		/*
4369 		 * check MATURE entry to start to send expire message
4370 		 * whether or not.
4371 		 */
4372 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4373 			/* we don't need to check. */
4374 			if (sav->lft_s == NULL)
4375 				continue;
4376 
4377 			/* sanity check */
4378 			if (sav->lft_c == NULL) {
4379 				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4380 					"time, why?\n", __func__));
4381 				continue;
4382 			}
4383 
4384 			/* check SOFT lifetime */
4385 			if (sav->lft_s->addtime != 0 &&
4386 			    now - sav->created > sav->lft_s->addtime) {
4387 				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4388 				/*
4389 				 * Actually, only send expire message if
4390 				 * SA has been used, as it was done before,
4391 				 * but should we always send such message,
4392 				 * and let IKE daemon decide if it should be
4393 				 * renegotiated or not ?
4394 				 * XXX expire message will actually NOT be
4395 				 * sent if SA is only used after soft
4396 				 * lifetime has been reached, see below
4397 				 * (DYING state)
4398 				 */
4399 				if (sav->lft_c->usetime != 0)
4400 					key_expire(sav);
4401 			}
4402 			/* check SOFT lifetime by bytes */
4403 			/*
4404 			 * XXX I don't know the way to delete this SA
4405 			 * when new SA is installed.  Caution when it's
4406 			 * installed too big lifetime by time.
4407 			 */
4408 			else if (sav->lft_s->bytes != 0 &&
4409 			    sav->lft_s->bytes < sav->lft_c->bytes) {
4410 
4411 				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4412 				/*
4413 				 * XXX If we keep to send expire
4414 				 * message in the status of
4415 				 * DYING. Do remove below code.
4416 				 */
4417 				key_expire(sav);
4418 			}
4419 		}
4420 
4421 		/* check DYING entry to change status to DEAD. */
4422 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4423 			/* we don't need to check. */
4424 			if (sav->lft_h == NULL)
4425 				continue;
4426 
4427 			/* sanity check */
4428 			if (sav->lft_c == NULL) {
4429 				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4430 					"time, why?\n", __func__));
4431 				continue;
4432 			}
4433 
4434 			if (sav->lft_h->addtime != 0 &&
4435 			    now - sav->created > sav->lft_h->addtime) {
4436 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4437 				KEY_FREESAV(&sav);
4438 			}
4439 #if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4440 			else if (sav->lft_s != NULL
4441 			      && sav->lft_s->addtime != 0
4442 			      && now - sav->created > sav->lft_s->addtime) {
4443 				/*
4444 				 * XXX: should be checked to be
4445 				 * installed the valid SA.
4446 				 */
4447 
4448 				/*
4449 				 * If there is no SA then sending
4450 				 * expire message.
4451 				 */
4452 				key_expire(sav);
4453 			}
4454 #endif
4455 			/* check HARD lifetime by bytes */
4456 			else if (sav->lft_h->bytes != 0 &&
4457 			    sav->lft_h->bytes < sav->lft_c->bytes) {
4458 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4459 				KEY_FREESAV(&sav);
4460 			}
4461 		}
4462 
4463 		/* delete entry in DEAD */
4464 		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4465 			/* sanity check */
4466 			if (sav->state != SADB_SASTATE_DEAD) {
4467 				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4468 					"(queue: %d SA: %d): kill it anyway\n",
4469 					__func__,
4470 					SADB_SASTATE_DEAD, sav->state));
4471 			}
4472 			/*
4473 			 * do not call key_freesav() here.
4474 			 * sav should already be freed, and sav->refcnt
4475 			 * shows other references to sav
4476 			 * (such as from SPD).
4477 			 */
4478 		}
4479 	}
4480 	SAHTREE_UNLOCK();
4481 }
4482 
4483 static void
4484 key_flush_acq(time_t now)
4485 {
4486 	struct secacq *acq, *nextacq;
4487 
4488 	/* ACQ tree */
4489 	ACQ_LOCK();
4490 	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4491 		nextacq = LIST_NEXT(acq, chain);
4492 		if (now - acq->created > V_key_blockacq_lifetime
4493 		 && __LIST_CHAINED(acq)) {
4494 			LIST_REMOVE(acq, chain);
4495 			free(acq, M_IPSEC_SAQ);
4496 		}
4497 	}
4498 	ACQ_UNLOCK();
4499 }
4500 
4501 static void
4502 key_flush_spacq(time_t now)
4503 {
4504 	struct secspacq *acq, *nextacq;
4505 
4506 	/* SP ACQ tree */
4507 	SPACQ_LOCK();
4508 	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4509 		nextacq = LIST_NEXT(acq, chain);
4510 		if (now - acq->created > V_key_blockacq_lifetime
4511 		 && __LIST_CHAINED(acq)) {
4512 			LIST_REMOVE(acq, chain);
4513 			free(acq, M_IPSEC_SAQ);
4514 		}
4515 	}
4516 	SPACQ_UNLOCK();
4517 }
4518 
4519 /*
4520  * time handler.
4521  * scanning SPD and SAD to check status for each entries,
4522  * and do to remove or to expire.
4523  * XXX: year 2038 problem may remain.
4524  */
4525 void
4526 key_timehandler(void)
4527 {
4528 	VNET_ITERATOR_DECL(vnet_iter);
4529 	time_t now = time_second;
4530 
4531 	VNET_LIST_RLOCK_NOSLEEP();
4532 	VNET_FOREACH(vnet_iter) {
4533 		CURVNET_SET(vnet_iter);
4534 		key_flush_spd(now);
4535 		key_flush_sad(now);
4536 		key_flush_acq(now);
4537 		key_flush_spacq(now);
4538 		CURVNET_RESTORE();
4539 	}
4540 	VNET_LIST_RUNLOCK_NOSLEEP();
4541 
4542 #ifndef IPSEC_DEBUG2
4543 	/* do exchange to tick time !! */
4544 	(void)timeout((void *)key_timehandler, (void *)0, hz);
4545 #endif /* IPSEC_DEBUG2 */
4546 }
4547 
4548 u_long
4549 key_random()
4550 {
4551 	u_long value;
4552 
4553 	key_randomfill(&value, sizeof(value));
4554 	return value;
4555 }
4556 
4557 void
4558 key_randomfill(p, l)
4559 	void *p;
4560 	size_t l;
4561 {
4562 	size_t n;
4563 	u_long v;
4564 	static int warn = 1;
4565 
4566 	n = 0;
4567 	n = (size_t)read_random(p, (u_int)l);
4568 	/* last resort */
4569 	while (n < l) {
4570 		v = random();
4571 		bcopy(&v, (u_int8_t *)p + n,
4572 		    l - n < sizeof(v) ? l - n : sizeof(v));
4573 		n += sizeof(v);
4574 
4575 		if (warn) {
4576 			printf("WARNING: pseudo-random number generator "
4577 			    "used for IPsec processing\n");
4578 			warn = 0;
4579 		}
4580 	}
4581 }
4582 
4583 /*
4584  * map SADB_SATYPE_* to IPPROTO_*.
4585  * if satype == SADB_SATYPE then satype is mapped to ~0.
4586  * OUT:
4587  *	0: invalid satype.
4588  */
4589 static u_int16_t
4590 key_satype2proto(u_int8_t satype)
4591 {
4592 	switch (satype) {
4593 	case SADB_SATYPE_UNSPEC:
4594 		return IPSEC_PROTO_ANY;
4595 	case SADB_SATYPE_AH:
4596 		return IPPROTO_AH;
4597 	case SADB_SATYPE_ESP:
4598 		return IPPROTO_ESP;
4599 	case SADB_X_SATYPE_IPCOMP:
4600 		return IPPROTO_IPCOMP;
4601 	case SADB_X_SATYPE_TCPSIGNATURE:
4602 		return IPPROTO_TCP;
4603 	default:
4604 		return 0;
4605 	}
4606 	/* NOTREACHED */
4607 }
4608 
4609 /*
4610  * map IPPROTO_* to SADB_SATYPE_*
4611  * OUT:
4612  *	0: invalid protocol type.
4613  */
4614 static u_int8_t
4615 key_proto2satype(u_int16_t proto)
4616 {
4617 	switch (proto) {
4618 	case IPPROTO_AH:
4619 		return SADB_SATYPE_AH;
4620 	case IPPROTO_ESP:
4621 		return SADB_SATYPE_ESP;
4622 	case IPPROTO_IPCOMP:
4623 		return SADB_X_SATYPE_IPCOMP;
4624 	case IPPROTO_TCP:
4625 		return SADB_X_SATYPE_TCPSIGNATURE;
4626 	default:
4627 		return 0;
4628 	}
4629 	/* NOTREACHED */
4630 }
4631 
4632 /* %%% PF_KEY */
4633 /*
4634  * SADB_GETSPI processing is to receive
4635  *	<base, (SA2), src address, dst address, (SPI range)>
4636  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4637  * tree with the status of LARVAL, and send
4638  *	<base, SA(*), address(SD)>
4639  * to the IKMPd.
4640  *
4641  * IN:	mhp: pointer to the pointer to each header.
4642  * OUT:	NULL if fail.
4643  *	other if success, return pointer to the message to send.
4644  */
4645 static int
4646 key_getspi(so, m, mhp)
4647 	struct socket *so;
4648 	struct mbuf *m;
4649 	const struct sadb_msghdr *mhp;
4650 {
4651 	struct sadb_address *src0, *dst0;
4652 	struct secasindex saidx;
4653 	struct secashead *newsah;
4654 	struct secasvar *newsav;
4655 	u_int8_t proto;
4656 	u_int32_t spi;
4657 	u_int8_t mode;
4658 	u_int32_t reqid;
4659 	int error;
4660 
4661 	IPSEC_ASSERT(so != NULL, ("null socket"));
4662 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4663 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4664 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4665 
4666 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4667 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4668 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4669 			__func__));
4670 		return key_senderror(so, m, EINVAL);
4671 	}
4672 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4673 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4674 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4675 			__func__));
4676 		return key_senderror(so, m, EINVAL);
4677 	}
4678 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4679 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4680 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4681 	} else {
4682 		mode = IPSEC_MODE_ANY;
4683 		reqid = 0;
4684 	}
4685 
4686 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4687 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4688 
4689 	/* map satype to proto */
4690 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4691 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4692 			__func__));
4693 		return key_senderror(so, m, EINVAL);
4694 	}
4695 
4696 	/*
4697 	 * Make sure the port numbers are zero.
4698 	 * In case of NAT-T we will update them later if needed.
4699 	 */
4700 	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4701 	case AF_INET:
4702 		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4703 		    sizeof(struct sockaddr_in))
4704 			return key_senderror(so, m, EINVAL);
4705 		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4706 		break;
4707 	case AF_INET6:
4708 		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4709 		    sizeof(struct sockaddr_in6))
4710 			return key_senderror(so, m, EINVAL);
4711 		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4712 		break;
4713 	default:
4714 		; /*???*/
4715 	}
4716 	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4717 	case AF_INET:
4718 		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4719 		    sizeof(struct sockaddr_in))
4720 			return key_senderror(so, m, EINVAL);
4721 		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4722 		break;
4723 	case AF_INET6:
4724 		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4725 		    sizeof(struct sockaddr_in6))
4726 			return key_senderror(so, m, EINVAL);
4727 		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4728 		break;
4729 	default:
4730 		; /*???*/
4731 	}
4732 
4733 	/* XXX boundary check against sa_len */
4734 	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4735 
4736 #ifdef IPSEC_NAT_T
4737 	/*
4738 	 * Handle NAT-T info if present.
4739 	 * We made sure the port numbers are zero above, so we do
4740 	 * not have to worry in case we do not update them.
4741 	 */
4742 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4743 		ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4744 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4745 		ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4746 
4747 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4748 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4749 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4750 		struct sadb_x_nat_t_type *type;
4751 		struct sadb_x_nat_t_port *sport, *dport;
4752 
4753 		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4754 		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4755 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4756 			ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4757 			    "passed.\n", __func__));
4758 			return key_senderror(so, m, EINVAL);
4759 		}
4760 
4761 		sport = (struct sadb_x_nat_t_port *)
4762 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4763 		dport = (struct sadb_x_nat_t_port *)
4764 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4765 
4766 		if (sport)
4767 			KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4768 		if (dport)
4769 			KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4770 	}
4771 #endif
4772 
4773 	/* SPI allocation */
4774 	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4775 	                       &saidx);
4776 	if (spi == 0)
4777 		return key_senderror(so, m, EINVAL);
4778 
4779 	/* get a SA index */
4780 	if ((newsah = key_getsah(&saidx)) == NULL) {
4781 		/* create a new SA index */
4782 		if ((newsah = key_newsah(&saidx)) == NULL) {
4783 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4784 			return key_senderror(so, m, ENOBUFS);
4785 		}
4786 	}
4787 
4788 	/* get a new SA */
4789 	/* XXX rewrite */
4790 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4791 	if (newsav == NULL) {
4792 		/* XXX don't free new SA index allocated in above. */
4793 		return key_senderror(so, m, error);
4794 	}
4795 
4796 	/* set spi */
4797 	newsav->spi = htonl(spi);
4798 
4799 	/* delete the entry in acqtree */
4800 	if (mhp->msg->sadb_msg_seq != 0) {
4801 		struct secacq *acq;
4802 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4803 			/* reset counter in order to deletion by timehandler. */
4804 			acq->created = time_second;
4805 			acq->count = 0;
4806 		}
4807     	}
4808 
4809     {
4810 	struct mbuf *n, *nn;
4811 	struct sadb_sa *m_sa;
4812 	struct sadb_msg *newmsg;
4813 	int off, len;
4814 
4815 	/* create new sadb_msg to reply. */
4816 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4817 	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4818 
4819 	MGETHDR(n, M_DONTWAIT, MT_DATA);
4820 	if (len > MHLEN) {
4821 		MCLGET(n, M_DONTWAIT);
4822 		if ((n->m_flags & M_EXT) == 0) {
4823 			m_freem(n);
4824 			n = NULL;
4825 		}
4826 	}
4827 	if (!n)
4828 		return key_senderror(so, m, ENOBUFS);
4829 
4830 	n->m_len = len;
4831 	n->m_next = NULL;
4832 	off = 0;
4833 
4834 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4835 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4836 
4837 	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4838 	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4839 	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4840 	m_sa->sadb_sa_spi = htonl(spi);
4841 	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4842 
4843 	IPSEC_ASSERT(off == len,
4844 		("length inconsistency (off %u len %u)", off, len));
4845 
4846 	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4847 	    SADB_EXT_ADDRESS_DST);
4848 	if (!n->m_next) {
4849 		m_freem(n);
4850 		return key_senderror(so, m, ENOBUFS);
4851 	}
4852 
4853 	if (n->m_len < sizeof(struct sadb_msg)) {
4854 		n = m_pullup(n, sizeof(struct sadb_msg));
4855 		if (n == NULL)
4856 			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4857 	}
4858 
4859 	n->m_pkthdr.len = 0;
4860 	for (nn = n; nn; nn = nn->m_next)
4861 		n->m_pkthdr.len += nn->m_len;
4862 
4863 	newmsg = mtod(n, struct sadb_msg *);
4864 	newmsg->sadb_msg_seq = newsav->seq;
4865 	newmsg->sadb_msg_errno = 0;
4866 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4867 
4868 	m_freem(m);
4869 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4870     }
4871 }
4872 
4873 /*
4874  * allocating new SPI
4875  * called by key_getspi().
4876  * OUT:
4877  *	0:	failure.
4878  *	others: success.
4879  */
4880 static u_int32_t
4881 key_do_getnewspi(spirange, saidx)
4882 	struct sadb_spirange *spirange;
4883 	struct secasindex *saidx;
4884 {
4885 	u_int32_t newspi;
4886 	u_int32_t min, max;
4887 	int count = V_key_spi_trycnt;
4888 
4889 	/* set spi range to allocate */
4890 	if (spirange != NULL) {
4891 		min = spirange->sadb_spirange_min;
4892 		max = spirange->sadb_spirange_max;
4893 	} else {
4894 		min = V_key_spi_minval;
4895 		max = V_key_spi_maxval;
4896 	}
4897 	/* IPCOMP needs 2-byte SPI */
4898 	if (saidx->proto == IPPROTO_IPCOMP) {
4899 		u_int32_t t;
4900 		if (min >= 0x10000)
4901 			min = 0xffff;
4902 		if (max >= 0x10000)
4903 			max = 0xffff;
4904 		if (min > max) {
4905 			t = min; min = max; max = t;
4906 		}
4907 	}
4908 
4909 	if (min == max) {
4910 		if (key_checkspidup(saidx, min) != NULL) {
4911 			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4912 				__func__, min));
4913 			return 0;
4914 		}
4915 
4916 		count--; /* taking one cost. */
4917 		newspi = min;
4918 
4919 	} else {
4920 
4921 		/* init SPI */
4922 		newspi = 0;
4923 
4924 		/* when requesting to allocate spi ranged */
4925 		while (count--) {
4926 			/* generate pseudo-random SPI value ranged. */
4927 			newspi = min + (key_random() % (max - min + 1));
4928 
4929 			if (key_checkspidup(saidx, newspi) == NULL)
4930 				break;
4931 		}
4932 
4933 		if (count == 0 || newspi == 0) {
4934 			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4935 				__func__));
4936 			return 0;
4937 		}
4938 	}
4939 
4940 	/* statistics */
4941 	keystat.getspi_count =
4942 		(keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4943 
4944 	return newspi;
4945 }
4946 
4947 /*
4948  * SADB_UPDATE processing
4949  * receive
4950  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4951  *       key(AE), (identity(SD),) (sensitivity)>
4952  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4953  * and send
4954  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4955  *       (identity(SD),) (sensitivity)>
4956  * to the ikmpd.
4957  *
4958  * m will always be freed.
4959  */
4960 static int
4961 key_update(so, m, mhp)
4962 	struct socket *so;
4963 	struct mbuf *m;
4964 	const struct sadb_msghdr *mhp;
4965 {
4966 	struct sadb_sa *sa0;
4967 	struct sadb_address *src0, *dst0;
4968 #ifdef IPSEC_NAT_T
4969 	struct sadb_x_nat_t_type *type;
4970 	struct sadb_x_nat_t_port *sport, *dport;
4971 	struct sadb_address *iaddr, *raddr;
4972 	struct sadb_x_nat_t_frag *frag;
4973 #endif
4974 	struct secasindex saidx;
4975 	struct secashead *sah;
4976 	struct secasvar *sav;
4977 	u_int16_t proto;
4978 	u_int8_t mode;
4979 	u_int32_t reqid;
4980 	int error;
4981 
4982 	IPSEC_ASSERT(so != NULL, ("null socket"));
4983 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4984 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4985 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4986 
4987 	/* map satype to proto */
4988 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4989 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4990 			__func__));
4991 		return key_senderror(so, m, EINVAL);
4992 	}
4993 
4994 	if (mhp->ext[SADB_EXT_SA] == NULL ||
4995 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4996 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4997 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4998 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4999 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5000 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5001 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5002 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5003 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5004 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5005 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5006 			__func__));
5007 		return key_senderror(so, m, EINVAL);
5008 	}
5009 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5010 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5011 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5012 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5013 			__func__));
5014 		return key_senderror(so, m, EINVAL);
5015 	}
5016 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5017 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5018 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5019 	} else {
5020 		mode = IPSEC_MODE_ANY;
5021 		reqid = 0;
5022 	}
5023 	/* XXX boundary checking for other extensions */
5024 
5025 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5026 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5027 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5028 
5029 	/* XXX boundary check against sa_len */
5030 	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5031 
5032 	/*
5033 	 * Make sure the port numbers are zero.
5034 	 * In case of NAT-T we will update them later if needed.
5035 	 */
5036 	KEY_PORTTOSADDR(&saidx.src, 0);
5037 	KEY_PORTTOSADDR(&saidx.dst, 0);
5038 
5039 #ifdef IPSEC_NAT_T
5040 	/*
5041 	 * Handle NAT-T info if present.
5042 	 */
5043 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5044 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5045 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5046 
5047 		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5048 		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5049 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5050 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5051 			    __func__));
5052 			return key_senderror(so, m, EINVAL);
5053 		}
5054 
5055 		type = (struct sadb_x_nat_t_type *)
5056 		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5057 		sport = (struct sadb_x_nat_t_port *)
5058 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5059 		dport = (struct sadb_x_nat_t_port *)
5060 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5061 	} else {
5062 		type = 0;
5063 		sport = dport = 0;
5064 	}
5065 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5066 	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5067 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5068 		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5069 			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5070 			    __func__));
5071 			return key_senderror(so, m, EINVAL);
5072 		}
5073 		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5074 		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5075 		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5076 	} else {
5077 		iaddr = raddr = NULL;
5078 	}
5079 	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5080 		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5081 			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5082 			    __func__));
5083 			return key_senderror(so, m, EINVAL);
5084 		}
5085 		frag = (struct sadb_x_nat_t_frag *)
5086 		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5087 	} else {
5088 		frag = 0;
5089 	}
5090 #endif
5091 
5092 	/* get a SA header */
5093 	if ((sah = key_getsah(&saidx)) == NULL) {
5094 		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
5095 		return key_senderror(so, m, ENOENT);
5096 	}
5097 
5098 	/* set spidx if there */
5099 	/* XXX rewrite */
5100 	error = key_setident(sah, m, mhp);
5101 	if (error)
5102 		return key_senderror(so, m, error);
5103 
5104 	/* find a SA with sequence number. */
5105 #ifdef IPSEC_DOSEQCHECK
5106 	if (mhp->msg->sadb_msg_seq != 0
5107 	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
5108 		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
5109 			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
5110 		return key_senderror(so, m, ENOENT);
5111 	}
5112 #else
5113 	SAHTREE_LOCK();
5114 	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5115 	SAHTREE_UNLOCK();
5116 	if (sav == NULL) {
5117 		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
5118 			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5119 		return key_senderror(so, m, EINVAL);
5120 	}
5121 #endif
5122 
5123 	/* validity check */
5124 	if (sav->sah->saidx.proto != proto) {
5125 		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
5126 			"(DB=%u param=%u)\n", __func__,
5127 			sav->sah->saidx.proto, proto));
5128 		return key_senderror(so, m, EINVAL);
5129 	}
5130 #ifdef IPSEC_DOSEQCHECK
5131 	if (sav->spi != sa0->sadb_sa_spi) {
5132 		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
5133 		    __func__,
5134 		    (u_int32_t)ntohl(sav->spi),
5135 		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5136 		return key_senderror(so, m, EINVAL);
5137 	}
5138 #endif
5139 	if (sav->pid != mhp->msg->sadb_msg_pid) {
5140 		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
5141 		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
5142 		return key_senderror(so, m, EINVAL);
5143 	}
5144 
5145 	/* copy sav values */
5146 	error = key_setsaval(sav, m, mhp);
5147 	if (error) {
5148 		KEY_FREESAV(&sav);
5149 		return key_senderror(so, m, error);
5150 	}
5151 
5152 	/* check SA values to be mature. */
5153 	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5154 		KEY_FREESAV(&sav);
5155 		return key_senderror(so, m, 0);
5156 	}
5157 
5158 #ifdef IPSEC_NAT_T
5159 	/*
5160 	 * Handle more NAT-T info if present,
5161 	 * now that we have a sav to fill.
5162 	 */
5163 	if (type)
5164 		sav->natt_type = type->sadb_x_nat_t_type_type;
5165 
5166 	if (sport)
5167 		KEY_PORTTOSADDR(&sav->sah->saidx.src,
5168 		    sport->sadb_x_nat_t_port_port);
5169 	if (dport)
5170 		KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5171 		    dport->sadb_x_nat_t_port_port);
5172 
5173 #if 0
5174 	/*
5175 	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5176 	 * We should actually check for a minimum MTU here, if we
5177 	 * want to support it in ip_output.
5178 	 */
5179 	if (frag)
5180 		sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5181 #endif
5182 #endif
5183 
5184     {
5185 	struct mbuf *n;
5186 
5187 	/* set msg buf from mhp */
5188 	n = key_getmsgbuf_x1(m, mhp);
5189 	if (n == NULL) {
5190 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5191 		return key_senderror(so, m, ENOBUFS);
5192 	}
5193 
5194 	m_freem(m);
5195 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5196     }
5197 }
5198 
5199 /*
5200  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5201  * only called by key_update().
5202  * OUT:
5203  *	NULL	: not found
5204  *	others	: found, pointer to a SA.
5205  */
5206 #ifdef IPSEC_DOSEQCHECK
5207 static struct secasvar *
5208 key_getsavbyseq(sah, seq)
5209 	struct secashead *sah;
5210 	u_int32_t seq;
5211 {
5212 	struct secasvar *sav;
5213 	u_int state;
5214 
5215 	state = SADB_SASTATE_LARVAL;
5216 
5217 	/* search SAD with sequence number ? */
5218 	LIST_FOREACH(sav, &sah->savtree[state], chain) {
5219 
5220 		KEY_CHKSASTATE(state, sav->state, __func__);
5221 
5222 		if (sav->seq == seq) {
5223 			sa_addref(sav);
5224 			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5225 				printf("DP %s cause refcnt++:%d SA:%p\n",
5226 					__func__, sav->refcnt, sav));
5227 			return sav;
5228 		}
5229 	}
5230 
5231 	return NULL;
5232 }
5233 #endif
5234 
5235 /*
5236  * SADB_ADD processing
5237  * add an entry to SA database, when received
5238  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5239  *       key(AE), (identity(SD),) (sensitivity)>
5240  * from the ikmpd,
5241  * and send
5242  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5243  *       (identity(SD),) (sensitivity)>
5244  * to the ikmpd.
5245  *
5246  * IGNORE identity and sensitivity messages.
5247  *
5248  * m will always be freed.
5249  */
5250 static int
5251 key_add(so, m, mhp)
5252 	struct socket *so;
5253 	struct mbuf *m;
5254 	const struct sadb_msghdr *mhp;
5255 {
5256 	struct sadb_sa *sa0;
5257 	struct sadb_address *src0, *dst0;
5258 #ifdef IPSEC_NAT_T
5259 	struct sadb_x_nat_t_type *type;
5260 	struct sadb_address *iaddr, *raddr;
5261 	struct sadb_x_nat_t_frag *frag;
5262 #endif
5263 	struct secasindex saidx;
5264 	struct secashead *newsah;
5265 	struct secasvar *newsav;
5266 	u_int16_t proto;
5267 	u_int8_t mode;
5268 	u_int32_t reqid;
5269 	int error;
5270 
5271 	IPSEC_ASSERT(so != NULL, ("null socket"));
5272 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5273 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5274 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5275 
5276 	/* map satype to proto */
5277 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5278 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5279 			__func__));
5280 		return key_senderror(so, m, EINVAL);
5281 	}
5282 
5283 	if (mhp->ext[SADB_EXT_SA] == NULL ||
5284 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5285 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5286 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5287 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5288 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5289 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5290 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5291 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5292 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5293 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5294 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5295 			__func__));
5296 		return key_senderror(so, m, EINVAL);
5297 	}
5298 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5299 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5300 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5301 		/* XXX need more */
5302 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5303 			__func__));
5304 		return key_senderror(so, m, EINVAL);
5305 	}
5306 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5307 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5308 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5309 	} else {
5310 		mode = IPSEC_MODE_ANY;
5311 		reqid = 0;
5312 	}
5313 
5314 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5315 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5316 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5317 
5318 	/* XXX boundary check against sa_len */
5319 	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5320 
5321 	/*
5322 	 * Make sure the port numbers are zero.
5323 	 * In case of NAT-T we will update them later if needed.
5324 	 */
5325 	KEY_PORTTOSADDR(&saidx.src, 0);
5326 	KEY_PORTTOSADDR(&saidx.dst, 0);
5327 
5328 #ifdef IPSEC_NAT_T
5329 	/*
5330 	 * Handle NAT-T info if present.
5331 	 */
5332 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5333 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5334 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5335 		struct sadb_x_nat_t_port *sport, *dport;
5336 
5337 		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5338 		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5339 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5340 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5341 			    __func__));
5342 			return key_senderror(so, m, EINVAL);
5343 		}
5344 
5345 		type = (struct sadb_x_nat_t_type *)
5346 		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5347 		sport = (struct sadb_x_nat_t_port *)
5348 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5349 		dport = (struct sadb_x_nat_t_port *)
5350 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5351 
5352 		if (sport)
5353 			KEY_PORTTOSADDR(&saidx.src,
5354 			    sport->sadb_x_nat_t_port_port);
5355 		if (dport)
5356 			KEY_PORTTOSADDR(&saidx.dst,
5357 			    dport->sadb_x_nat_t_port_port);
5358 	} else {
5359 		type = 0;
5360 	}
5361 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5362 	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5363 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5364 		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5365 			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5366 			    __func__));
5367 			return key_senderror(so, m, EINVAL);
5368 		}
5369 		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5370 		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5371 		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5372 	} else {
5373 		iaddr = raddr = NULL;
5374 	}
5375 	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5376 		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5377 			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5378 			    __func__));
5379 			return key_senderror(so, m, EINVAL);
5380 		}
5381 		frag = (struct sadb_x_nat_t_frag *)
5382 		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5383 	} else {
5384 		frag = 0;
5385 	}
5386 #endif
5387 
5388 	/* get a SA header */
5389 	if ((newsah = key_getsah(&saidx)) == NULL) {
5390 		/* create a new SA header */
5391 		if ((newsah = key_newsah(&saidx)) == NULL) {
5392 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5393 			return key_senderror(so, m, ENOBUFS);
5394 		}
5395 	}
5396 
5397 	/* set spidx if there */
5398 	/* XXX rewrite */
5399 	error = key_setident(newsah, m, mhp);
5400 	if (error) {
5401 		return key_senderror(so, m, error);
5402 	}
5403 
5404 	/* create new SA entry. */
5405 	/* We can create new SA only if SPI is differenct. */
5406 	SAHTREE_LOCK();
5407 	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5408 	SAHTREE_UNLOCK();
5409 	if (newsav != NULL) {
5410 		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5411 		return key_senderror(so, m, EEXIST);
5412 	}
5413 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5414 	if (newsav == NULL) {
5415 		return key_senderror(so, m, error);
5416 	}
5417 
5418 	/* check SA values to be mature. */
5419 	if ((error = key_mature(newsav)) != 0) {
5420 		KEY_FREESAV(&newsav);
5421 		return key_senderror(so, m, error);
5422 	}
5423 
5424 #ifdef IPSEC_NAT_T
5425 	/*
5426 	 * Handle more NAT-T info if present,
5427 	 * now that we have a sav to fill.
5428 	 */
5429 	if (type)
5430 		newsav->natt_type = type->sadb_x_nat_t_type_type;
5431 
5432 #if 0
5433 	/*
5434 	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5435 	 * We should actually check for a minimum MTU here, if we
5436 	 * want to support it in ip_output.
5437 	 */
5438 	if (frag)
5439 		newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5440 #endif
5441 #endif
5442 
5443 	/*
5444 	 * don't call key_freesav() here, as we would like to keep the SA
5445 	 * in the database on success.
5446 	 */
5447 
5448     {
5449 	struct mbuf *n;
5450 
5451 	/* set msg buf from mhp */
5452 	n = key_getmsgbuf_x1(m, mhp);
5453 	if (n == NULL) {
5454 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5455 		return key_senderror(so, m, ENOBUFS);
5456 	}
5457 
5458 	m_freem(m);
5459 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5460     }
5461 }
5462 
5463 /* m is retained */
5464 static int
5465 key_setident(sah, m, mhp)
5466 	struct secashead *sah;
5467 	struct mbuf *m;
5468 	const struct sadb_msghdr *mhp;
5469 {
5470 	const struct sadb_ident *idsrc, *iddst;
5471 	int idsrclen, iddstlen;
5472 
5473 	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5474 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5475 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5476 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5477 
5478 	/* don't make buffer if not there */
5479 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5480 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5481 		sah->idents = NULL;
5482 		sah->identd = NULL;
5483 		return 0;
5484 	}
5485 
5486 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5487 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5488 		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5489 		return EINVAL;
5490 	}
5491 
5492 	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5493 	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5494 	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5495 	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5496 
5497 	/* validity check */
5498 	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5499 		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5500 		return EINVAL;
5501 	}
5502 
5503 	switch (idsrc->sadb_ident_type) {
5504 	case SADB_IDENTTYPE_PREFIX:
5505 	case SADB_IDENTTYPE_FQDN:
5506 	case SADB_IDENTTYPE_USERFQDN:
5507 	default:
5508 		/* XXX do nothing */
5509 		sah->idents = NULL;
5510 		sah->identd = NULL;
5511 	 	return 0;
5512 	}
5513 
5514 	/* make structure */
5515 	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5516 	if (sah->idents == NULL) {
5517 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5518 		return ENOBUFS;
5519 	}
5520 	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5521 	if (sah->identd == NULL) {
5522 		free(sah->idents, M_IPSEC_MISC);
5523 		sah->idents = NULL;
5524 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5525 		return ENOBUFS;
5526 	}
5527 	sah->idents->type = idsrc->sadb_ident_type;
5528 	sah->idents->id = idsrc->sadb_ident_id;
5529 
5530 	sah->identd->type = iddst->sadb_ident_type;
5531 	sah->identd->id = iddst->sadb_ident_id;
5532 
5533 	return 0;
5534 }
5535 
5536 /*
5537  * m will not be freed on return.
5538  * it is caller's responsibility to free the result.
5539  */
5540 static struct mbuf *
5541 key_getmsgbuf_x1(m, mhp)
5542 	struct mbuf *m;
5543 	const struct sadb_msghdr *mhp;
5544 {
5545 	struct mbuf *n;
5546 
5547 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5548 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5549 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5550 
5551 	/* create new sadb_msg to reply. */
5552 	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5553 	    SADB_EXT_SA, SADB_X_EXT_SA2,
5554 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5555 	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5556 	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5557 	if (!n)
5558 		return NULL;
5559 
5560 	if (n->m_len < sizeof(struct sadb_msg)) {
5561 		n = m_pullup(n, sizeof(struct sadb_msg));
5562 		if (n == NULL)
5563 			return NULL;
5564 	}
5565 	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5566 	mtod(n, struct sadb_msg *)->sadb_msg_len =
5567 	    PFKEY_UNIT64(n->m_pkthdr.len);
5568 
5569 	return n;
5570 }
5571 
5572 static int key_delete_all __P((struct socket *, struct mbuf *,
5573 	const struct sadb_msghdr *, u_int16_t));
5574 
5575 /*
5576  * SADB_DELETE processing
5577  * receive
5578  *   <base, SA(*), address(SD)>
5579  * from the ikmpd, and set SADB_SASTATE_DEAD,
5580  * and send,
5581  *   <base, SA(*), address(SD)>
5582  * to the ikmpd.
5583  *
5584  * m will always be freed.
5585  */
5586 static int
5587 key_delete(so, m, mhp)
5588 	struct socket *so;
5589 	struct mbuf *m;
5590 	const struct sadb_msghdr *mhp;
5591 {
5592 	struct sadb_sa *sa0;
5593 	struct sadb_address *src0, *dst0;
5594 	struct secasindex saidx;
5595 	struct secashead *sah;
5596 	struct secasvar *sav = NULL;
5597 	u_int16_t proto;
5598 
5599 	IPSEC_ASSERT(so != NULL, ("null socket"));
5600 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5601 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5602 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5603 
5604 	/* map satype to proto */
5605 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5606 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5607 			__func__));
5608 		return key_senderror(so, m, EINVAL);
5609 	}
5610 
5611 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5612 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5613 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5614 			__func__));
5615 		return key_senderror(so, m, EINVAL);
5616 	}
5617 
5618 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5619 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5620 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5621 			__func__));
5622 		return key_senderror(so, m, EINVAL);
5623 	}
5624 
5625 	if (mhp->ext[SADB_EXT_SA] == NULL) {
5626 		/*
5627 		 * Caller wants us to delete all non-LARVAL SAs
5628 		 * that match the src/dst.  This is used during
5629 		 * IKE INITIAL-CONTACT.
5630 		 */
5631 		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5632 		return key_delete_all(so, m, mhp, proto);
5633 	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5634 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5635 			__func__));
5636 		return key_senderror(so, m, EINVAL);
5637 	}
5638 
5639 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5640 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5641 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5642 
5643 	/* XXX boundary check against sa_len */
5644 	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5645 
5646 	/*
5647 	 * Make sure the port numbers are zero.
5648 	 * In case of NAT-T we will update them later if needed.
5649 	 */
5650 	KEY_PORTTOSADDR(&saidx.src, 0);
5651 	KEY_PORTTOSADDR(&saidx.dst, 0);
5652 
5653 #ifdef IPSEC_NAT_T
5654 	/*
5655 	 * Handle NAT-T info if present.
5656 	 */
5657 	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5658 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5659 		struct sadb_x_nat_t_port *sport, *dport;
5660 
5661 		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5662 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5663 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5664 			    __func__));
5665 			return key_senderror(so, m, EINVAL);
5666 		}
5667 
5668 		sport = (struct sadb_x_nat_t_port *)
5669 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5670 		dport = (struct sadb_x_nat_t_port *)
5671 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5672 
5673 		if (sport)
5674 			KEY_PORTTOSADDR(&saidx.src,
5675 			    sport->sadb_x_nat_t_port_port);
5676 		if (dport)
5677 			KEY_PORTTOSADDR(&saidx.dst,
5678 			    dport->sadb_x_nat_t_port_port);
5679 	}
5680 #endif
5681 
5682 	/* get a SA header */
5683 	SAHTREE_LOCK();
5684 	LIST_FOREACH(sah, &V_sahtree, chain) {
5685 		if (sah->state == SADB_SASTATE_DEAD)
5686 			continue;
5687 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5688 			continue;
5689 
5690 		/* get a SA with SPI. */
5691 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5692 		if (sav)
5693 			break;
5694 	}
5695 	if (sah == NULL) {
5696 		SAHTREE_UNLOCK();
5697 		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5698 		return key_senderror(so, m, ENOENT);
5699 	}
5700 
5701 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5702 	KEY_FREESAV(&sav);
5703 	SAHTREE_UNLOCK();
5704 
5705     {
5706 	struct mbuf *n;
5707 	struct sadb_msg *newmsg;
5708 
5709 	/* create new sadb_msg to reply. */
5710 	/* XXX-BZ NAT-T extensions? */
5711 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5712 	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5713 	if (!n)
5714 		return key_senderror(so, m, ENOBUFS);
5715 
5716 	if (n->m_len < sizeof(struct sadb_msg)) {
5717 		n = m_pullup(n, sizeof(struct sadb_msg));
5718 		if (n == NULL)
5719 			return key_senderror(so, m, ENOBUFS);
5720 	}
5721 	newmsg = mtod(n, struct sadb_msg *);
5722 	newmsg->sadb_msg_errno = 0;
5723 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5724 
5725 	m_freem(m);
5726 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5727     }
5728 }
5729 
5730 /*
5731  * delete all SAs for src/dst.  Called from key_delete().
5732  */
5733 static int
5734 key_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5735     u_int16_t proto)
5736 {
5737 	struct sadb_address *src0, *dst0;
5738 	struct secasindex saidx;
5739 	struct secashead *sah;
5740 	struct secasvar *sav, *nextsav;
5741 	u_int stateidx, state;
5742 
5743 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5744 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5745 
5746 	/* XXX boundary check against sa_len */
5747 	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5748 
5749 	/*
5750 	 * Make sure the port numbers are zero.
5751 	 * In case of NAT-T we will update them later if needed.
5752 	 */
5753 	KEY_PORTTOSADDR(&saidx.src, 0);
5754 	KEY_PORTTOSADDR(&saidx.dst, 0);
5755 
5756 #ifdef IPSEC_NAT_T
5757 	/*
5758 	 * Handle NAT-T info if present.
5759 	 */
5760 
5761 	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5762 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5763 		struct sadb_x_nat_t_port *sport, *dport;
5764 
5765 		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5766 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5767 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5768 			    __func__));
5769 			return key_senderror(so, m, EINVAL);
5770 		}
5771 
5772 		sport = (struct sadb_x_nat_t_port *)
5773 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5774 		dport = (struct sadb_x_nat_t_port *)
5775 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5776 
5777 		if (sport)
5778 			KEY_PORTTOSADDR(&saidx.src,
5779 			    sport->sadb_x_nat_t_port_port);
5780 		if (dport)
5781 			KEY_PORTTOSADDR(&saidx.dst,
5782 			    dport->sadb_x_nat_t_port_port);
5783 	}
5784 #endif
5785 
5786 	SAHTREE_LOCK();
5787 	LIST_FOREACH(sah, &V_sahtree, chain) {
5788 		if (sah->state == SADB_SASTATE_DEAD)
5789 			continue;
5790 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5791 			continue;
5792 
5793 		/* Delete all non-LARVAL SAs. */
5794 		for (stateidx = 0;
5795 		     stateidx < _ARRAYLEN(saorder_state_alive);
5796 		     stateidx++) {
5797 			state = saorder_state_alive[stateidx];
5798 			if (state == SADB_SASTATE_LARVAL)
5799 				continue;
5800 			for (sav = LIST_FIRST(&sah->savtree[state]);
5801 			     sav != NULL; sav = nextsav) {
5802 				nextsav = LIST_NEXT(sav, chain);
5803 				/* sanity check */
5804 				if (sav->state != state) {
5805 					ipseclog((LOG_DEBUG, "%s: invalid "
5806 						"sav->state (queue %d SA %d)\n",
5807 						__func__, state, sav->state));
5808 					continue;
5809 				}
5810 
5811 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5812 				KEY_FREESAV(&sav);
5813 			}
5814 		}
5815 	}
5816 	SAHTREE_UNLOCK();
5817     {
5818 	struct mbuf *n;
5819 	struct sadb_msg *newmsg;
5820 
5821 	/* create new sadb_msg to reply. */
5822 	/* XXX-BZ NAT-T extensions? */
5823 	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5824 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5825 	if (!n)
5826 		return key_senderror(so, m, ENOBUFS);
5827 
5828 	if (n->m_len < sizeof(struct sadb_msg)) {
5829 		n = m_pullup(n, sizeof(struct sadb_msg));
5830 		if (n == NULL)
5831 			return key_senderror(so, m, ENOBUFS);
5832 	}
5833 	newmsg = mtod(n, struct sadb_msg *);
5834 	newmsg->sadb_msg_errno = 0;
5835 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5836 
5837 	m_freem(m);
5838 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5839     }
5840 }
5841 
5842 /*
5843  * SADB_GET processing
5844  * receive
5845  *   <base, SA(*), address(SD)>
5846  * from the ikmpd, and get a SP and a SA to respond,
5847  * and send,
5848  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5849  *       (identity(SD),) (sensitivity)>
5850  * to the ikmpd.
5851  *
5852  * m will always be freed.
5853  */
5854 static int
5855 key_get(so, m, mhp)
5856 	struct socket *so;
5857 	struct mbuf *m;
5858 	const struct sadb_msghdr *mhp;
5859 {
5860 	struct sadb_sa *sa0;
5861 	struct sadb_address *src0, *dst0;
5862 	struct secasindex saidx;
5863 	struct secashead *sah;
5864 	struct secasvar *sav = NULL;
5865 	u_int16_t proto;
5866 
5867 	IPSEC_ASSERT(so != NULL, ("null socket"));
5868 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5869 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5870 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5871 
5872 	/* map satype to proto */
5873 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5874 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5875 			__func__));
5876 		return key_senderror(so, m, EINVAL);
5877 	}
5878 
5879 	if (mhp->ext[SADB_EXT_SA] == NULL ||
5880 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5881 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5882 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5883 			__func__));
5884 		return key_senderror(so, m, EINVAL);
5885 	}
5886 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5887 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5888 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5889 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5890 			__func__));
5891 		return key_senderror(so, m, EINVAL);
5892 	}
5893 
5894 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5895 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5896 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5897 
5898 	/* XXX boundary check against sa_len */
5899 	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5900 
5901 	/*
5902 	 * Make sure the port numbers are zero.
5903 	 * In case of NAT-T we will update them later if needed.
5904 	 */
5905 	KEY_PORTTOSADDR(&saidx.src, 0);
5906 	KEY_PORTTOSADDR(&saidx.dst, 0);
5907 
5908 #ifdef IPSEC_NAT_T
5909 	/*
5910 	 * Handle NAT-T info if present.
5911 	 */
5912 
5913 	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5914 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5915 		struct sadb_x_nat_t_port *sport, *dport;
5916 
5917 		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5918 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5919 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5920 			    __func__));
5921 			return key_senderror(so, m, EINVAL);
5922 		}
5923 
5924 		sport = (struct sadb_x_nat_t_port *)
5925 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5926 		dport = (struct sadb_x_nat_t_port *)
5927 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5928 
5929 		if (sport)
5930 			KEY_PORTTOSADDR(&saidx.src,
5931 			    sport->sadb_x_nat_t_port_port);
5932 		if (dport)
5933 			KEY_PORTTOSADDR(&saidx.dst,
5934 			    dport->sadb_x_nat_t_port_port);
5935 	}
5936 #endif
5937 
5938 	/* get a SA header */
5939 	SAHTREE_LOCK();
5940 	LIST_FOREACH(sah, &V_sahtree, chain) {
5941 		if (sah->state == SADB_SASTATE_DEAD)
5942 			continue;
5943 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5944 			continue;
5945 
5946 		/* get a SA with SPI. */
5947 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5948 		if (sav)
5949 			break;
5950 	}
5951 	SAHTREE_UNLOCK();
5952 	if (sah == NULL) {
5953 		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5954 		return key_senderror(so, m, ENOENT);
5955 	}
5956 
5957     {
5958 	struct mbuf *n;
5959 	u_int8_t satype;
5960 
5961 	/* map proto to satype */
5962 	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5963 		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5964 			__func__));
5965 		return key_senderror(so, m, EINVAL);
5966 	}
5967 
5968 	/* create new sadb_msg to reply. */
5969 	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5970 	    mhp->msg->sadb_msg_pid);
5971 	if (!n)
5972 		return key_senderror(so, m, ENOBUFS);
5973 
5974 	m_freem(m);
5975 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5976     }
5977 }
5978 
5979 /* XXX make it sysctl-configurable? */
5980 static void
5981 key_getcomb_setlifetime(comb)
5982 	struct sadb_comb *comb;
5983 {
5984 
5985 	comb->sadb_comb_soft_allocations = 1;
5986 	comb->sadb_comb_hard_allocations = 1;
5987 	comb->sadb_comb_soft_bytes = 0;
5988 	comb->sadb_comb_hard_bytes = 0;
5989 	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5990 	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5991 	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5992 	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5993 }
5994 
5995 /*
5996  * XXX reorder combinations by preference
5997  * XXX no idea if the user wants ESP authentication or not
5998  */
5999 static struct mbuf *
6000 key_getcomb_esp()
6001 {
6002 	struct sadb_comb *comb;
6003 	struct enc_xform *algo;
6004 	struct mbuf *result = NULL, *m, *n;
6005 	int encmin;
6006 	int i, off, o;
6007 	int totlen;
6008 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6009 
6010 	m = NULL;
6011 	for (i = 1; i <= SADB_EALG_MAX; i++) {
6012 		algo = esp_algorithm_lookup(i);
6013 		if (algo == NULL)
6014 			continue;
6015 
6016 		/* discard algorithms with key size smaller than system min */
6017 		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6018 			continue;
6019 		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6020 			encmin = V_ipsec_esp_keymin;
6021 		else
6022 			encmin = _BITS(algo->minkey);
6023 
6024 		if (V_ipsec_esp_auth)
6025 			m = key_getcomb_ah();
6026 		else {
6027 			IPSEC_ASSERT(l <= MLEN,
6028 				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6029 			MGET(m, M_DONTWAIT, MT_DATA);
6030 			if (m) {
6031 				M_ALIGN(m, l);
6032 				m->m_len = l;
6033 				m->m_next = NULL;
6034 				bzero(mtod(m, caddr_t), m->m_len);
6035 			}
6036 		}
6037 		if (!m)
6038 			goto fail;
6039 
6040 		totlen = 0;
6041 		for (n = m; n; n = n->m_next)
6042 			totlen += n->m_len;
6043 		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6044 
6045 		for (off = 0; off < totlen; off += l) {
6046 			n = m_pulldown(m, off, l, &o);
6047 			if (!n) {
6048 				/* m is already freed */
6049 				goto fail;
6050 			}
6051 			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6052 			bzero(comb, sizeof(*comb));
6053 			key_getcomb_setlifetime(comb);
6054 			comb->sadb_comb_encrypt = i;
6055 			comb->sadb_comb_encrypt_minbits = encmin;
6056 			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6057 		}
6058 
6059 		if (!result)
6060 			result = m;
6061 		else
6062 			m_cat(result, m);
6063 	}
6064 
6065 	return result;
6066 
6067  fail:
6068 	if (result)
6069 		m_freem(result);
6070 	return NULL;
6071 }
6072 
6073 static void
6074 key_getsizes_ah(
6075 	const struct auth_hash *ah,
6076 	int alg,
6077 	u_int16_t* min,
6078 	u_int16_t* max)
6079 {
6080 
6081 	*min = *max = ah->keysize;
6082 	if (ah->keysize == 0) {
6083 		/*
6084 		 * Transform takes arbitrary key size but algorithm
6085 		 * key size is restricted.  Enforce this here.
6086 		 */
6087 		switch (alg) {
6088 		case SADB_X_AALG_MD5:	*min = *max = 16; break;
6089 		case SADB_X_AALG_SHA:	*min = *max = 20; break;
6090 		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
6091 		default:
6092 			DPRINTF(("%s: unknown AH algorithm %u\n",
6093 				__func__, alg));
6094 			break;
6095 		}
6096 	}
6097 }
6098 
6099 /*
6100  * XXX reorder combinations by preference
6101  */
6102 static struct mbuf *
6103 key_getcomb_ah()
6104 {
6105 	struct sadb_comb *comb;
6106 	struct auth_hash *algo;
6107 	struct mbuf *m;
6108 	u_int16_t minkeysize, maxkeysize;
6109 	int i;
6110 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6111 
6112 	m = NULL;
6113 	for (i = 1; i <= SADB_AALG_MAX; i++) {
6114 #if 1
6115 		/* we prefer HMAC algorithms, not old algorithms */
6116 		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
6117 			continue;
6118 #endif
6119 		algo = ah_algorithm_lookup(i);
6120 		if (!algo)
6121 			continue;
6122 		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6123 		/* discard algorithms with key size smaller than system min */
6124 		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6125 			continue;
6126 
6127 		if (!m) {
6128 			IPSEC_ASSERT(l <= MLEN,
6129 				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6130 			MGET(m, M_DONTWAIT, MT_DATA);
6131 			if (m) {
6132 				M_ALIGN(m, l);
6133 				m->m_len = l;
6134 				m->m_next = NULL;
6135 			}
6136 		} else
6137 			M_PREPEND(m, l, M_DONTWAIT);
6138 		if (!m)
6139 			return NULL;
6140 
6141 		comb = mtod(m, struct sadb_comb *);
6142 		bzero(comb, sizeof(*comb));
6143 		key_getcomb_setlifetime(comb);
6144 		comb->sadb_comb_auth = i;
6145 		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6146 		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6147 	}
6148 
6149 	return m;
6150 }
6151 
6152 /*
6153  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6154  * XXX reorder combinations by preference
6155  */
6156 static struct mbuf *
6157 key_getcomb_ipcomp()
6158 {
6159 	struct sadb_comb *comb;
6160 	struct comp_algo *algo;
6161 	struct mbuf *m;
6162 	int i;
6163 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6164 
6165 	m = NULL;
6166 	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6167 		algo = ipcomp_algorithm_lookup(i);
6168 		if (!algo)
6169 			continue;
6170 
6171 		if (!m) {
6172 			IPSEC_ASSERT(l <= MLEN,
6173 				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6174 			MGET(m, M_DONTWAIT, MT_DATA);
6175 			if (m) {
6176 				M_ALIGN(m, l);
6177 				m->m_len = l;
6178 				m->m_next = NULL;
6179 			}
6180 		} else
6181 			M_PREPEND(m, l, M_DONTWAIT);
6182 		if (!m)
6183 			return NULL;
6184 
6185 		comb = mtod(m, struct sadb_comb *);
6186 		bzero(comb, sizeof(*comb));
6187 		key_getcomb_setlifetime(comb);
6188 		comb->sadb_comb_encrypt = i;
6189 		/* what should we set into sadb_comb_*_{min,max}bits? */
6190 	}
6191 
6192 	return m;
6193 }
6194 
6195 /*
6196  * XXX no way to pass mode (transport/tunnel) to userland
6197  * XXX replay checking?
6198  * XXX sysctl interface to ipsec_{ah,esp}_keymin
6199  */
6200 static struct mbuf *
6201 key_getprop(saidx)
6202 	const struct secasindex *saidx;
6203 {
6204 	struct sadb_prop *prop;
6205 	struct mbuf *m, *n;
6206 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6207 	int totlen;
6208 
6209 	switch (saidx->proto)  {
6210 	case IPPROTO_ESP:
6211 		m = key_getcomb_esp();
6212 		break;
6213 	case IPPROTO_AH:
6214 		m = key_getcomb_ah();
6215 		break;
6216 	case IPPROTO_IPCOMP:
6217 		m = key_getcomb_ipcomp();
6218 		break;
6219 	default:
6220 		return NULL;
6221 	}
6222 
6223 	if (!m)
6224 		return NULL;
6225 	M_PREPEND(m, l, M_DONTWAIT);
6226 	if (!m)
6227 		return NULL;
6228 
6229 	totlen = 0;
6230 	for (n = m; n; n = n->m_next)
6231 		totlen += n->m_len;
6232 
6233 	prop = mtod(m, struct sadb_prop *);
6234 	bzero(prop, sizeof(*prop));
6235 	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6236 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6237 	prop->sadb_prop_replay = 32;	/* XXX */
6238 
6239 	return m;
6240 }
6241 
6242 /*
6243  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6244  * send
6245  *   <base, SA, address(SD), (address(P)), x_policy,
6246  *       (identity(SD),) (sensitivity,) proposal>
6247  * to KMD, and expect to receive
6248  *   <base> with SADB_ACQUIRE if error occured,
6249  * or
6250  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6251  * from KMD by PF_KEY.
6252  *
6253  * XXX x_policy is outside of RFC2367 (KAME extension).
6254  * XXX sensitivity is not supported.
6255  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6256  * see comment for key_getcomb_ipcomp().
6257  *
6258  * OUT:
6259  *    0     : succeed
6260  *    others: error number
6261  */
6262 static int
6263 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6264 {
6265 	struct mbuf *result = NULL, *m;
6266 	struct secacq *newacq;
6267 	u_int8_t satype;
6268 	int error = -1;
6269 	u_int32_t seq;
6270 
6271 	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6272 	satype = key_proto2satype(saidx->proto);
6273 	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6274 
6275 	/*
6276 	 * We never do anything about acquirng SA.  There is anather
6277 	 * solution that kernel blocks to send SADB_ACQUIRE message until
6278 	 * getting something message from IKEd.  In later case, to be
6279 	 * managed with ACQUIRING list.
6280 	 */
6281 	/* Get an entry to check whether sending message or not. */
6282 	if ((newacq = key_getacq(saidx)) != NULL) {
6283 		if (V_key_blockacq_count < newacq->count) {
6284 			/* reset counter and do send message. */
6285 			newacq->count = 0;
6286 		} else {
6287 			/* increment counter and do nothing. */
6288 			newacq->count++;
6289 			return 0;
6290 		}
6291 	} else {
6292 		/* make new entry for blocking to send SADB_ACQUIRE. */
6293 		if ((newacq = key_newacq(saidx)) == NULL)
6294 			return ENOBUFS;
6295 	}
6296 
6297 
6298 	seq = newacq->seq;
6299 	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6300 	if (!m) {
6301 		error = ENOBUFS;
6302 		goto fail;
6303 	}
6304 	result = m;
6305 
6306 	/*
6307 	 * No SADB_X_EXT_NAT_T_* here: we do not know
6308 	 * anything related to NAT-T at this time.
6309 	 */
6310 
6311 	/* set sadb_address for saidx's. */
6312 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6313 	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6314 	if (!m) {
6315 		error = ENOBUFS;
6316 		goto fail;
6317 	}
6318 	m_cat(result, m);
6319 
6320 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6321 	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6322 	if (!m) {
6323 		error = ENOBUFS;
6324 		goto fail;
6325 	}
6326 	m_cat(result, m);
6327 
6328 	/* XXX proxy address (optional) */
6329 
6330 	/* set sadb_x_policy */
6331 	if (sp) {
6332 		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6333 		if (!m) {
6334 			error = ENOBUFS;
6335 			goto fail;
6336 		}
6337 		m_cat(result, m);
6338 	}
6339 
6340 	/* XXX identity (optional) */
6341 #if 0
6342 	if (idexttype && fqdn) {
6343 		/* create identity extension (FQDN) */
6344 		struct sadb_ident *id;
6345 		int fqdnlen;
6346 
6347 		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
6348 		id = (struct sadb_ident *)p;
6349 		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6350 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6351 		id->sadb_ident_exttype = idexttype;
6352 		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6353 		bcopy(fqdn, id + 1, fqdnlen);
6354 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6355 	}
6356 
6357 	if (idexttype) {
6358 		/* create identity extension (USERFQDN) */
6359 		struct sadb_ident *id;
6360 		int userfqdnlen;
6361 
6362 		if (userfqdn) {
6363 			/* +1 for terminating-NUL */
6364 			userfqdnlen = strlen(userfqdn) + 1;
6365 		} else
6366 			userfqdnlen = 0;
6367 		id = (struct sadb_ident *)p;
6368 		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6369 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6370 		id->sadb_ident_exttype = idexttype;
6371 		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6372 		/* XXX is it correct? */
6373 		if (curproc && curproc->p_cred)
6374 			id->sadb_ident_id = curproc->p_cred->p_ruid;
6375 		if (userfqdn && userfqdnlen)
6376 			bcopy(userfqdn, id + 1, userfqdnlen);
6377 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6378 	}
6379 #endif
6380 
6381 	/* XXX sensitivity (optional) */
6382 
6383 	/* create proposal/combination extension */
6384 	m = key_getprop(saidx);
6385 #if 0
6386 	/*
6387 	 * spec conformant: always attach proposal/combination extension,
6388 	 * the problem is that we have no way to attach it for ipcomp,
6389 	 * due to the way sadb_comb is declared in RFC2367.
6390 	 */
6391 	if (!m) {
6392 		error = ENOBUFS;
6393 		goto fail;
6394 	}
6395 	m_cat(result, m);
6396 #else
6397 	/*
6398 	 * outside of spec; make proposal/combination extension optional.
6399 	 */
6400 	if (m)
6401 		m_cat(result, m);
6402 #endif
6403 
6404 	if ((result->m_flags & M_PKTHDR) == 0) {
6405 		error = EINVAL;
6406 		goto fail;
6407 	}
6408 
6409 	if (result->m_len < sizeof(struct sadb_msg)) {
6410 		result = m_pullup(result, sizeof(struct sadb_msg));
6411 		if (result == NULL) {
6412 			error = ENOBUFS;
6413 			goto fail;
6414 		}
6415 	}
6416 
6417 	result->m_pkthdr.len = 0;
6418 	for (m = result; m; m = m->m_next)
6419 		result->m_pkthdr.len += m->m_len;
6420 
6421 	mtod(result, struct sadb_msg *)->sadb_msg_len =
6422 	    PFKEY_UNIT64(result->m_pkthdr.len);
6423 
6424 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6425 
6426  fail:
6427 	if (result)
6428 		m_freem(result);
6429 	return error;
6430 }
6431 
6432 static struct secacq *
6433 key_newacq(const struct secasindex *saidx)
6434 {
6435 	struct secacq *newacq;
6436 
6437 	/* get new entry */
6438 	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6439 	if (newacq == NULL) {
6440 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6441 		return NULL;
6442 	}
6443 
6444 	/* copy secindex */
6445 	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6446 	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6447 	newacq->created = time_second;
6448 	newacq->count = 0;
6449 
6450 	/* add to acqtree */
6451 	ACQ_LOCK();
6452 	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6453 	ACQ_UNLOCK();
6454 
6455 	return newacq;
6456 }
6457 
6458 static struct secacq *
6459 key_getacq(const struct secasindex *saidx)
6460 {
6461 	struct secacq *acq;
6462 
6463 	ACQ_LOCK();
6464 	LIST_FOREACH(acq, &V_acqtree, chain) {
6465 		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6466 			break;
6467 	}
6468 	ACQ_UNLOCK();
6469 
6470 	return acq;
6471 }
6472 
6473 static struct secacq *
6474 key_getacqbyseq(seq)
6475 	u_int32_t seq;
6476 {
6477 	struct secacq *acq;
6478 
6479 	ACQ_LOCK();
6480 	LIST_FOREACH(acq, &V_acqtree, chain) {
6481 		if (acq->seq == seq)
6482 			break;
6483 	}
6484 	ACQ_UNLOCK();
6485 
6486 	return acq;
6487 }
6488 
6489 static struct secspacq *
6490 key_newspacq(spidx)
6491 	struct secpolicyindex *spidx;
6492 {
6493 	struct secspacq *acq;
6494 
6495 	/* get new entry */
6496 	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6497 	if (acq == NULL) {
6498 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6499 		return NULL;
6500 	}
6501 
6502 	/* copy secindex */
6503 	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6504 	acq->created = time_second;
6505 	acq->count = 0;
6506 
6507 	/* add to spacqtree */
6508 	SPACQ_LOCK();
6509 	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6510 	SPACQ_UNLOCK();
6511 
6512 	return acq;
6513 }
6514 
6515 static struct secspacq *
6516 key_getspacq(spidx)
6517 	struct secpolicyindex *spidx;
6518 {
6519 	struct secspacq *acq;
6520 
6521 	SPACQ_LOCK();
6522 	LIST_FOREACH(acq, &V_spacqtree, chain) {
6523 		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6524 			/* NB: return holding spacq_lock */
6525 			return acq;
6526 		}
6527 	}
6528 	SPACQ_UNLOCK();
6529 
6530 	return NULL;
6531 }
6532 
6533 /*
6534  * SADB_ACQUIRE processing,
6535  * in first situation, is receiving
6536  *   <base>
6537  * from the ikmpd, and clear sequence of its secasvar entry.
6538  *
6539  * In second situation, is receiving
6540  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6541  * from a user land process, and return
6542  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6543  * to the socket.
6544  *
6545  * m will always be freed.
6546  */
6547 static int
6548 key_acquire2(so, m, mhp)
6549 	struct socket *so;
6550 	struct mbuf *m;
6551 	const struct sadb_msghdr *mhp;
6552 {
6553 	const struct sadb_address *src0, *dst0;
6554 	struct secasindex saidx;
6555 	struct secashead *sah;
6556 	u_int16_t proto;
6557 	int error;
6558 
6559 	IPSEC_ASSERT(so != NULL, ("null socket"));
6560 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6561 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6562 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6563 
6564 	/*
6565 	 * Error message from KMd.
6566 	 * We assume that if error was occured in IKEd, the length of PFKEY
6567 	 * message is equal to the size of sadb_msg structure.
6568 	 * We do not raise error even if error occured in this function.
6569 	 */
6570 	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6571 		struct secacq *acq;
6572 
6573 		/* check sequence number */
6574 		if (mhp->msg->sadb_msg_seq == 0) {
6575 			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6576 				"number.\n", __func__));
6577 			m_freem(m);
6578 			return 0;
6579 		}
6580 
6581 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6582 			/*
6583 			 * the specified larval SA is already gone, or we got
6584 			 * a bogus sequence number.  we can silently ignore it.
6585 			 */
6586 			m_freem(m);
6587 			return 0;
6588 		}
6589 
6590 		/* reset acq counter in order to deletion by timehander. */
6591 		acq->created = time_second;
6592 		acq->count = 0;
6593 		m_freem(m);
6594 		return 0;
6595 	}
6596 
6597 	/*
6598 	 * This message is from user land.
6599 	 */
6600 
6601 	/* map satype to proto */
6602 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6603 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6604 			__func__));
6605 		return key_senderror(so, m, EINVAL);
6606 	}
6607 
6608 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6609 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6610 	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6611 		/* error */
6612 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6613 			__func__));
6614 		return key_senderror(so, m, EINVAL);
6615 	}
6616 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6617 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6618 	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6619 		/* error */
6620 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6621 			__func__));
6622 		return key_senderror(so, m, EINVAL);
6623 	}
6624 
6625 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6626 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6627 
6628 	/* XXX boundary check against sa_len */
6629 	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6630 
6631 	/*
6632 	 * Make sure the port numbers are zero.
6633 	 * In case of NAT-T we will update them later if needed.
6634 	 */
6635 	KEY_PORTTOSADDR(&saidx.src, 0);
6636 	KEY_PORTTOSADDR(&saidx.dst, 0);
6637 
6638 #ifndef IPSEC_NAT_T
6639 	/*
6640 	 * Handle NAT-T info if present.
6641 	 */
6642 
6643 	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6644 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6645 		struct sadb_x_nat_t_port *sport, *dport;
6646 
6647 		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6648 		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6649 			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6650 			    __func__));
6651 			return key_senderror(so, m, EINVAL);
6652 		}
6653 
6654 		sport = (struct sadb_x_nat_t_port *)
6655 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6656 		dport = (struct sadb_x_nat_t_port *)
6657 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6658 
6659 		if (sport)
6660 			KEY_PORTTOSADDR(&saidx.src,
6661 			    sport->sadb_x_nat_t_port_port);
6662 		if (dport)
6663 			KEY_PORTTOSADDR(&saidx.dst,
6664 			    dport->sadb_x_nat_t_port_port);
6665 	}
6666 #endif
6667 
6668 	/* get a SA index */
6669 	SAHTREE_LOCK();
6670 	LIST_FOREACH(sah, &V_sahtree, chain) {
6671 		if (sah->state == SADB_SASTATE_DEAD)
6672 			continue;
6673 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6674 			break;
6675 	}
6676 	SAHTREE_UNLOCK();
6677 	if (sah != NULL) {
6678 		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6679 		return key_senderror(so, m, EEXIST);
6680 	}
6681 
6682 	error = key_acquire(&saidx, NULL);
6683 	if (error != 0) {
6684 		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6685 			__func__, mhp->msg->sadb_msg_errno));
6686 		return key_senderror(so, m, error);
6687 	}
6688 
6689 	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6690 }
6691 
6692 /*
6693  * SADB_REGISTER processing.
6694  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6695  * receive
6696  *   <base>
6697  * from the ikmpd, and register a socket to send PF_KEY messages,
6698  * and send
6699  *   <base, supported>
6700  * to KMD by PF_KEY.
6701  * If socket is detached, must free from regnode.
6702  *
6703  * m will always be freed.
6704  */
6705 static int
6706 key_register(so, m, mhp)
6707 	struct socket *so;
6708 	struct mbuf *m;
6709 	const struct sadb_msghdr *mhp;
6710 {
6711 	struct secreg *reg, *newreg = 0;
6712 
6713 	IPSEC_ASSERT(so != NULL, ("null socket"));
6714 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6715 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6716 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6717 
6718 	/* check for invalid register message */
6719 	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6720 		return key_senderror(so, m, EINVAL);
6721 
6722 	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6723 	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6724 		goto setmsg;
6725 
6726 	/* check whether existing or not */
6727 	REGTREE_LOCK();
6728 	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6729 		if (reg->so == so) {
6730 			REGTREE_UNLOCK();
6731 			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6732 				__func__));
6733 			return key_senderror(so, m, EEXIST);
6734 		}
6735 	}
6736 
6737 	/* create regnode */
6738 	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6739 	if (newreg == NULL) {
6740 		REGTREE_UNLOCK();
6741 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6742 		return key_senderror(so, m, ENOBUFS);
6743 	}
6744 
6745 	newreg->so = so;
6746 	((struct keycb *)sotorawcb(so))->kp_registered++;
6747 
6748 	/* add regnode to regtree. */
6749 	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6750 	REGTREE_UNLOCK();
6751 
6752   setmsg:
6753     {
6754 	struct mbuf *n;
6755 	struct sadb_msg *newmsg;
6756 	struct sadb_supported *sup;
6757 	u_int len, alen, elen;
6758 	int off;
6759 	int i;
6760 	struct sadb_alg *alg;
6761 
6762 	/* create new sadb_msg to reply. */
6763 	alen = 0;
6764 	for (i = 1; i <= SADB_AALG_MAX; i++) {
6765 		if (ah_algorithm_lookup(i))
6766 			alen += sizeof(struct sadb_alg);
6767 	}
6768 	if (alen)
6769 		alen += sizeof(struct sadb_supported);
6770 	elen = 0;
6771 	for (i = 1; i <= SADB_EALG_MAX; i++) {
6772 		if (esp_algorithm_lookup(i))
6773 			elen += sizeof(struct sadb_alg);
6774 	}
6775 	if (elen)
6776 		elen += sizeof(struct sadb_supported);
6777 
6778 	len = sizeof(struct sadb_msg) + alen + elen;
6779 
6780 	if (len > MCLBYTES)
6781 		return key_senderror(so, m, ENOBUFS);
6782 
6783 	MGETHDR(n, M_DONTWAIT, MT_DATA);
6784 	if (len > MHLEN) {
6785 		MCLGET(n, M_DONTWAIT);
6786 		if ((n->m_flags & M_EXT) == 0) {
6787 			m_freem(n);
6788 			n = NULL;
6789 		}
6790 	}
6791 	if (!n)
6792 		return key_senderror(so, m, ENOBUFS);
6793 
6794 	n->m_pkthdr.len = n->m_len = len;
6795 	n->m_next = NULL;
6796 	off = 0;
6797 
6798 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6799 	newmsg = mtod(n, struct sadb_msg *);
6800 	newmsg->sadb_msg_errno = 0;
6801 	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6802 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6803 
6804 	/* for authentication algorithm */
6805 	if (alen) {
6806 		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6807 		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6808 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6809 		off += PFKEY_ALIGN8(sizeof(*sup));
6810 
6811 		for (i = 1; i <= SADB_AALG_MAX; i++) {
6812 			struct auth_hash *aalgo;
6813 			u_int16_t minkeysize, maxkeysize;
6814 
6815 			aalgo = ah_algorithm_lookup(i);
6816 			if (!aalgo)
6817 				continue;
6818 			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6819 			alg->sadb_alg_id = i;
6820 			alg->sadb_alg_ivlen = 0;
6821 			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6822 			alg->sadb_alg_minbits = _BITS(minkeysize);
6823 			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6824 			off += PFKEY_ALIGN8(sizeof(*alg));
6825 		}
6826 	}
6827 
6828 	/* for encryption algorithm */
6829 	if (elen) {
6830 		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6831 		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6832 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6833 		off += PFKEY_ALIGN8(sizeof(*sup));
6834 
6835 		for (i = 1; i <= SADB_EALG_MAX; i++) {
6836 			struct enc_xform *ealgo;
6837 
6838 			ealgo = esp_algorithm_lookup(i);
6839 			if (!ealgo)
6840 				continue;
6841 			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6842 			alg->sadb_alg_id = i;
6843 			alg->sadb_alg_ivlen = ealgo->blocksize;
6844 			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6845 			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6846 			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6847 		}
6848 	}
6849 
6850 	IPSEC_ASSERT(off == len,
6851 		("length assumption failed (off %u len %u)", off, len));
6852 
6853 	m_freem(m);
6854 	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6855     }
6856 }
6857 
6858 /*
6859  * free secreg entry registered.
6860  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6861  */
6862 void
6863 key_freereg(struct socket *so)
6864 {
6865 	struct secreg *reg;
6866 	int i;
6867 
6868 	IPSEC_ASSERT(so != NULL, ("NULL so"));
6869 
6870 	/*
6871 	 * check whether existing or not.
6872 	 * check all type of SA, because there is a potential that
6873 	 * one socket is registered to multiple type of SA.
6874 	 */
6875 	REGTREE_LOCK();
6876 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6877 		LIST_FOREACH(reg, &V_regtree[i], chain) {
6878 			if (reg->so == so && __LIST_CHAINED(reg)) {
6879 				LIST_REMOVE(reg, chain);
6880 				free(reg, M_IPSEC_SAR);
6881 				break;
6882 			}
6883 		}
6884 	}
6885 	REGTREE_UNLOCK();
6886 }
6887 
6888 /*
6889  * SADB_EXPIRE processing
6890  * send
6891  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6892  * to KMD by PF_KEY.
6893  * NOTE: We send only soft lifetime extension.
6894  *
6895  * OUT:	0	: succeed
6896  *	others	: error number
6897  */
6898 static int
6899 key_expire(struct secasvar *sav)
6900 {
6901 	int s;
6902 	int satype;
6903 	struct mbuf *result = NULL, *m;
6904 	int len;
6905 	int error = -1;
6906 	struct sadb_lifetime *lt;
6907 
6908 	/* XXX: Why do we lock ? */
6909 	s = splnet();	/*called from softclock()*/
6910 
6911 	IPSEC_ASSERT (sav != NULL, ("null sav"));
6912 	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6913 
6914 	/* set msg header */
6915 	satype = key_proto2satype(sav->sah->saidx.proto);
6916 	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6917 	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6918 	if (!m) {
6919 		error = ENOBUFS;
6920 		goto fail;
6921 	}
6922 	result = m;
6923 
6924 	/* create SA extension */
6925 	m = key_setsadbsa(sav);
6926 	if (!m) {
6927 		error = ENOBUFS;
6928 		goto fail;
6929 	}
6930 	m_cat(result, m);
6931 
6932 	/* create SA extension */
6933 	m = key_setsadbxsa2(sav->sah->saidx.mode,
6934 			sav->replay ? sav->replay->count : 0,
6935 			sav->sah->saidx.reqid);
6936 	if (!m) {
6937 		error = ENOBUFS;
6938 		goto fail;
6939 	}
6940 	m_cat(result, m);
6941 
6942 	/* create lifetime extension (current and soft) */
6943 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6944 	m = key_alloc_mbuf(len);
6945 	if (!m || m->m_next) {	/*XXX*/
6946 		if (m)
6947 			m_freem(m);
6948 		error = ENOBUFS;
6949 		goto fail;
6950 	}
6951 	bzero(mtod(m, caddr_t), len);
6952 	lt = mtod(m, struct sadb_lifetime *);
6953 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6954 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6955 	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6956 	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6957 	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6958 	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6959 	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6960 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6961 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6962 	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6963 	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6964 	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6965 	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6966 	m_cat(result, m);
6967 
6968 	/* set sadb_address for source */
6969 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6970 	    &sav->sah->saidx.src.sa,
6971 	    FULLMASK, IPSEC_ULPROTO_ANY);
6972 	if (!m) {
6973 		error = ENOBUFS;
6974 		goto fail;
6975 	}
6976 	m_cat(result, m);
6977 
6978 	/* set sadb_address for destination */
6979 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6980 	    &sav->sah->saidx.dst.sa,
6981 	    FULLMASK, IPSEC_ULPROTO_ANY);
6982 	if (!m) {
6983 		error = ENOBUFS;
6984 		goto fail;
6985 	}
6986 	m_cat(result, m);
6987 
6988 	/*
6989 	 * XXX-BZ Handle NAT-T extensions here.
6990 	 */
6991 
6992 	if ((result->m_flags & M_PKTHDR) == 0) {
6993 		error = EINVAL;
6994 		goto fail;
6995 	}
6996 
6997 	if (result->m_len < sizeof(struct sadb_msg)) {
6998 		result = m_pullup(result, sizeof(struct sadb_msg));
6999 		if (result == NULL) {
7000 			error = ENOBUFS;
7001 			goto fail;
7002 		}
7003 	}
7004 
7005 	result->m_pkthdr.len = 0;
7006 	for (m = result; m; m = m->m_next)
7007 		result->m_pkthdr.len += m->m_len;
7008 
7009 	mtod(result, struct sadb_msg *)->sadb_msg_len =
7010 	    PFKEY_UNIT64(result->m_pkthdr.len);
7011 
7012 	splx(s);
7013 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7014 
7015  fail:
7016 	if (result)
7017 		m_freem(result);
7018 	splx(s);
7019 	return error;
7020 }
7021 
7022 /*
7023  * SADB_FLUSH processing
7024  * receive
7025  *   <base>
7026  * from the ikmpd, and free all entries in secastree.
7027  * and send,
7028  *   <base>
7029  * to the ikmpd.
7030  * NOTE: to do is only marking SADB_SASTATE_DEAD.
7031  *
7032  * m will always be freed.
7033  */
7034 static int
7035 key_flush(so, m, mhp)
7036 	struct socket *so;
7037 	struct mbuf *m;
7038 	const struct sadb_msghdr *mhp;
7039 {
7040 	struct sadb_msg *newmsg;
7041 	struct secashead *sah, *nextsah;
7042 	struct secasvar *sav, *nextsav;
7043 	u_int16_t proto;
7044 	u_int8_t state;
7045 	u_int stateidx;
7046 
7047 	IPSEC_ASSERT(so != NULL, ("null socket"));
7048 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7049 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7050 
7051 	/* map satype to proto */
7052 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7053 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7054 			__func__));
7055 		return key_senderror(so, m, EINVAL);
7056 	}
7057 
7058 	/* no SATYPE specified, i.e. flushing all SA. */
7059 	SAHTREE_LOCK();
7060 	for (sah = LIST_FIRST(&V_sahtree);
7061 	     sah != NULL;
7062 	     sah = nextsah) {
7063 		nextsah = LIST_NEXT(sah, chain);
7064 
7065 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7066 		 && proto != sah->saidx.proto)
7067 			continue;
7068 
7069 		for (stateidx = 0;
7070 		     stateidx < _ARRAYLEN(saorder_state_alive);
7071 		     stateidx++) {
7072 			state = saorder_state_any[stateidx];
7073 			for (sav = LIST_FIRST(&sah->savtree[state]);
7074 			     sav != NULL;
7075 			     sav = nextsav) {
7076 
7077 				nextsav = LIST_NEXT(sav, chain);
7078 
7079 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7080 				KEY_FREESAV(&sav);
7081 			}
7082 		}
7083 
7084 		sah->state = SADB_SASTATE_DEAD;
7085 	}
7086 	SAHTREE_UNLOCK();
7087 
7088 	if (m->m_len < sizeof(struct sadb_msg) ||
7089 	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7090 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7091 		return key_senderror(so, m, ENOBUFS);
7092 	}
7093 
7094 	if (m->m_next)
7095 		m_freem(m->m_next);
7096 	m->m_next = NULL;
7097 	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7098 	newmsg = mtod(m, struct sadb_msg *);
7099 	newmsg->sadb_msg_errno = 0;
7100 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7101 
7102 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7103 }
7104 
7105 /*
7106  * SADB_DUMP processing
7107  * dump all entries including status of DEAD in SAD.
7108  * receive
7109  *   <base>
7110  * from the ikmpd, and dump all secasvar leaves
7111  * and send,
7112  *   <base> .....
7113  * to the ikmpd.
7114  *
7115  * m will always be freed.
7116  */
7117 static int
7118 key_dump(so, m, mhp)
7119 	struct socket *so;
7120 	struct mbuf *m;
7121 	const struct sadb_msghdr *mhp;
7122 {
7123 	struct secashead *sah;
7124 	struct secasvar *sav;
7125 	u_int16_t proto;
7126 	u_int stateidx;
7127 	u_int8_t satype;
7128 	u_int8_t state;
7129 	int cnt;
7130 	struct sadb_msg *newmsg;
7131 	struct mbuf *n;
7132 
7133 	IPSEC_ASSERT(so != NULL, ("null socket"));
7134 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7135 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7136 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7137 
7138 	/* map satype to proto */
7139 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7140 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7141 			__func__));
7142 		return key_senderror(so, m, EINVAL);
7143 	}
7144 
7145 	/* count sav entries to be sent to the userland. */
7146 	cnt = 0;
7147 	SAHTREE_LOCK();
7148 	LIST_FOREACH(sah, &V_sahtree, chain) {
7149 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7150 		 && proto != sah->saidx.proto)
7151 			continue;
7152 
7153 		for (stateidx = 0;
7154 		     stateidx < _ARRAYLEN(saorder_state_any);
7155 		     stateidx++) {
7156 			state = saorder_state_any[stateidx];
7157 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7158 				cnt++;
7159 			}
7160 		}
7161 	}
7162 
7163 	if (cnt == 0) {
7164 		SAHTREE_UNLOCK();
7165 		return key_senderror(so, m, ENOENT);
7166 	}
7167 
7168 	/* send this to the userland, one at a time. */
7169 	newmsg = NULL;
7170 	LIST_FOREACH(sah, &V_sahtree, chain) {
7171 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7172 		 && proto != sah->saidx.proto)
7173 			continue;
7174 
7175 		/* map proto to satype */
7176 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7177 			SAHTREE_UNLOCK();
7178 			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7179 				"SAD.\n", __func__));
7180 			return key_senderror(so, m, EINVAL);
7181 		}
7182 
7183 		for (stateidx = 0;
7184 		     stateidx < _ARRAYLEN(saorder_state_any);
7185 		     stateidx++) {
7186 			state = saorder_state_any[stateidx];
7187 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7188 				n = key_setdumpsa(sav, SADB_DUMP, satype,
7189 				    --cnt, mhp->msg->sadb_msg_pid);
7190 				if (!n) {
7191 					SAHTREE_UNLOCK();
7192 					return key_senderror(so, m, ENOBUFS);
7193 				}
7194 				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7195 			}
7196 		}
7197 	}
7198 	SAHTREE_UNLOCK();
7199 
7200 	m_freem(m);
7201 	return 0;
7202 }
7203 
7204 /*
7205  * SADB_X_PROMISC processing
7206  *
7207  * m will always be freed.
7208  */
7209 static int
7210 key_promisc(so, m, mhp)
7211 	struct socket *so;
7212 	struct mbuf *m;
7213 	const struct sadb_msghdr *mhp;
7214 {
7215 	int olen;
7216 
7217 	IPSEC_ASSERT(so != NULL, ("null socket"));
7218 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7219 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7220 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7221 
7222 	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7223 
7224 	if (olen < sizeof(struct sadb_msg)) {
7225 #if 1
7226 		return key_senderror(so, m, EINVAL);
7227 #else
7228 		m_freem(m);
7229 		return 0;
7230 #endif
7231 	} else if (olen == sizeof(struct sadb_msg)) {
7232 		/* enable/disable promisc mode */
7233 		struct keycb *kp;
7234 
7235 		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7236 			return key_senderror(so, m, EINVAL);
7237 		mhp->msg->sadb_msg_errno = 0;
7238 		switch (mhp->msg->sadb_msg_satype) {
7239 		case 0:
7240 		case 1:
7241 			kp->kp_promisc = mhp->msg->sadb_msg_satype;
7242 			break;
7243 		default:
7244 			return key_senderror(so, m, EINVAL);
7245 		}
7246 
7247 		/* send the original message back to everyone */
7248 		mhp->msg->sadb_msg_errno = 0;
7249 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7250 	} else {
7251 		/* send packet as is */
7252 
7253 		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7254 
7255 		/* TODO: if sadb_msg_seq is specified, send to specific pid */
7256 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7257 	}
7258 }
7259 
7260 static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
7261 		const struct sadb_msghdr *)) = {
7262 	NULL,		/* SADB_RESERVED */
7263 	key_getspi,	/* SADB_GETSPI */
7264 	key_update,	/* SADB_UPDATE */
7265 	key_add,	/* SADB_ADD */
7266 	key_delete,	/* SADB_DELETE */
7267 	key_get,	/* SADB_GET */
7268 	key_acquire2,	/* SADB_ACQUIRE */
7269 	key_register,	/* SADB_REGISTER */
7270 	NULL,		/* SADB_EXPIRE */
7271 	key_flush,	/* SADB_FLUSH */
7272 	key_dump,	/* SADB_DUMP */
7273 	key_promisc,	/* SADB_X_PROMISC */
7274 	NULL,		/* SADB_X_PCHANGE */
7275 	key_spdadd,	/* SADB_X_SPDUPDATE */
7276 	key_spdadd,	/* SADB_X_SPDADD */
7277 	key_spddelete,	/* SADB_X_SPDDELETE */
7278 	key_spdget,	/* SADB_X_SPDGET */
7279 	NULL,		/* SADB_X_SPDACQUIRE */
7280 	key_spddump,	/* SADB_X_SPDDUMP */
7281 	key_spdflush,	/* SADB_X_SPDFLUSH */
7282 	key_spdadd,	/* SADB_X_SPDSETIDX */
7283 	NULL,		/* SADB_X_SPDEXPIRE */
7284 	key_spddelete2,	/* SADB_X_SPDDELETE2 */
7285 };
7286 
7287 /*
7288  * parse sadb_msg buffer to process PFKEYv2,
7289  * and create a data to response if needed.
7290  * I think to be dealed with mbuf directly.
7291  * IN:
7292  *     msgp  : pointer to pointer to a received buffer pulluped.
7293  *             This is rewrited to response.
7294  *     so    : pointer to socket.
7295  * OUT:
7296  *    length for buffer to send to user process.
7297  */
7298 int
7299 key_parse(m, so)
7300 	struct mbuf *m;
7301 	struct socket *so;
7302 {
7303 	struct sadb_msg *msg;
7304 	struct sadb_msghdr mh;
7305 	u_int orglen;
7306 	int error;
7307 	int target;
7308 
7309 	IPSEC_ASSERT(so != NULL, ("null socket"));
7310 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7311 
7312 #if 0	/*kdebug_sadb assumes msg in linear buffer*/
7313 	KEYDEBUG(KEYDEBUG_KEY_DUMP,
7314 		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7315 		kdebug_sadb(msg));
7316 #endif
7317 
7318 	if (m->m_len < sizeof(struct sadb_msg)) {
7319 		m = m_pullup(m, sizeof(struct sadb_msg));
7320 		if (!m)
7321 			return ENOBUFS;
7322 	}
7323 	msg = mtod(m, struct sadb_msg *);
7324 	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7325 	target = KEY_SENDUP_ONE;
7326 
7327 	if ((m->m_flags & M_PKTHDR) == 0 ||
7328 	    m->m_pkthdr.len != m->m_pkthdr.len) {
7329 		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7330 		V_pfkeystat.out_invlen++;
7331 		error = EINVAL;
7332 		goto senderror;
7333 	}
7334 
7335 	if (msg->sadb_msg_version != PF_KEY_V2) {
7336 		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7337 		    __func__, msg->sadb_msg_version));
7338 		V_pfkeystat.out_invver++;
7339 		error = EINVAL;
7340 		goto senderror;
7341 	}
7342 
7343 	if (msg->sadb_msg_type > SADB_MAX) {
7344 		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7345 		    __func__, msg->sadb_msg_type));
7346 		V_pfkeystat.out_invmsgtype++;
7347 		error = EINVAL;
7348 		goto senderror;
7349 	}
7350 
7351 	/* for old-fashioned code - should be nuked */
7352 	if (m->m_pkthdr.len > MCLBYTES) {
7353 		m_freem(m);
7354 		return ENOBUFS;
7355 	}
7356 	if (m->m_next) {
7357 		struct mbuf *n;
7358 
7359 		MGETHDR(n, M_DONTWAIT, MT_DATA);
7360 		if (n && m->m_pkthdr.len > MHLEN) {
7361 			MCLGET(n, M_DONTWAIT);
7362 			if ((n->m_flags & M_EXT) == 0) {
7363 				m_free(n);
7364 				n = NULL;
7365 			}
7366 		}
7367 		if (!n) {
7368 			m_freem(m);
7369 			return ENOBUFS;
7370 		}
7371 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7372 		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7373 		n->m_next = NULL;
7374 		m_freem(m);
7375 		m = n;
7376 	}
7377 
7378 	/* align the mbuf chain so that extensions are in contiguous region. */
7379 	error = key_align(m, &mh);
7380 	if (error)
7381 		return error;
7382 
7383 	msg = mh.msg;
7384 
7385 	/* check SA type */
7386 	switch (msg->sadb_msg_satype) {
7387 	case SADB_SATYPE_UNSPEC:
7388 		switch (msg->sadb_msg_type) {
7389 		case SADB_GETSPI:
7390 		case SADB_UPDATE:
7391 		case SADB_ADD:
7392 		case SADB_DELETE:
7393 		case SADB_GET:
7394 		case SADB_ACQUIRE:
7395 		case SADB_EXPIRE:
7396 			ipseclog((LOG_DEBUG, "%s: must specify satype "
7397 			    "when msg type=%u.\n", __func__,
7398 			    msg->sadb_msg_type));
7399 			V_pfkeystat.out_invsatype++;
7400 			error = EINVAL;
7401 			goto senderror;
7402 		}
7403 		break;
7404 	case SADB_SATYPE_AH:
7405 	case SADB_SATYPE_ESP:
7406 	case SADB_X_SATYPE_IPCOMP:
7407 	case SADB_X_SATYPE_TCPSIGNATURE:
7408 		switch (msg->sadb_msg_type) {
7409 		case SADB_X_SPDADD:
7410 		case SADB_X_SPDDELETE:
7411 		case SADB_X_SPDGET:
7412 		case SADB_X_SPDDUMP:
7413 		case SADB_X_SPDFLUSH:
7414 		case SADB_X_SPDSETIDX:
7415 		case SADB_X_SPDUPDATE:
7416 		case SADB_X_SPDDELETE2:
7417 			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7418 				__func__, msg->sadb_msg_type));
7419 			V_pfkeystat.out_invsatype++;
7420 			error = EINVAL;
7421 			goto senderror;
7422 		}
7423 		break;
7424 	case SADB_SATYPE_RSVP:
7425 	case SADB_SATYPE_OSPFV2:
7426 	case SADB_SATYPE_RIPV2:
7427 	case SADB_SATYPE_MIP:
7428 		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7429 			__func__, msg->sadb_msg_satype));
7430 		V_pfkeystat.out_invsatype++;
7431 		error = EOPNOTSUPP;
7432 		goto senderror;
7433 	case 1:	/* XXX: What does it do? */
7434 		if (msg->sadb_msg_type == SADB_X_PROMISC)
7435 			break;
7436 		/*FALLTHROUGH*/
7437 	default:
7438 		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7439 			__func__, msg->sadb_msg_satype));
7440 		V_pfkeystat.out_invsatype++;
7441 		error = EINVAL;
7442 		goto senderror;
7443 	}
7444 
7445 	/* check field of upper layer protocol and address family */
7446 	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7447 	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7448 		struct sadb_address *src0, *dst0;
7449 		u_int plen;
7450 
7451 		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7452 		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7453 
7454 		/* check upper layer protocol */
7455 		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7456 			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7457 				"mismatched.\n", __func__));
7458 			V_pfkeystat.out_invaddr++;
7459 			error = EINVAL;
7460 			goto senderror;
7461 		}
7462 
7463 		/* check family */
7464 		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7465 		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
7466 			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7467 				__func__));
7468 			V_pfkeystat.out_invaddr++;
7469 			error = EINVAL;
7470 			goto senderror;
7471 		}
7472 		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7473 		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
7474 			ipseclog((LOG_DEBUG, "%s: address struct size "
7475 				"mismatched.\n", __func__));
7476 			V_pfkeystat.out_invaddr++;
7477 			error = EINVAL;
7478 			goto senderror;
7479 		}
7480 
7481 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7482 		case AF_INET:
7483 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7484 			    sizeof(struct sockaddr_in)) {
7485 				V_pfkeystat.out_invaddr++;
7486 				error = EINVAL;
7487 				goto senderror;
7488 			}
7489 			break;
7490 		case AF_INET6:
7491 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7492 			    sizeof(struct sockaddr_in6)) {
7493 				V_pfkeystat.out_invaddr++;
7494 				error = EINVAL;
7495 				goto senderror;
7496 			}
7497 			break;
7498 		default:
7499 			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7500 				__func__));
7501 			V_pfkeystat.out_invaddr++;
7502 			error = EAFNOSUPPORT;
7503 			goto senderror;
7504 		}
7505 
7506 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7507 		case AF_INET:
7508 			plen = sizeof(struct in_addr) << 3;
7509 			break;
7510 		case AF_INET6:
7511 			plen = sizeof(struct in6_addr) << 3;
7512 			break;
7513 		default:
7514 			plen = 0;	/*fool gcc*/
7515 			break;
7516 		}
7517 
7518 		/* check max prefix length */
7519 		if (src0->sadb_address_prefixlen > plen ||
7520 		    dst0->sadb_address_prefixlen > plen) {
7521 			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7522 				__func__));
7523 			V_pfkeystat.out_invaddr++;
7524 			error = EINVAL;
7525 			goto senderror;
7526 		}
7527 
7528 		/*
7529 		 * prefixlen == 0 is valid because there can be a case when
7530 		 * all addresses are matched.
7531 		 */
7532 	}
7533 
7534 	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7535 	    key_typesw[msg->sadb_msg_type] == NULL) {
7536 		V_pfkeystat.out_invmsgtype++;
7537 		error = EINVAL;
7538 		goto senderror;
7539 	}
7540 
7541 	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7542 
7543 senderror:
7544 	msg->sadb_msg_errno = error;
7545 	return key_sendup_mbuf(so, m, target);
7546 }
7547 
7548 static int
7549 key_senderror(so, m, code)
7550 	struct socket *so;
7551 	struct mbuf *m;
7552 	int code;
7553 {
7554 	struct sadb_msg *msg;
7555 
7556 	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7557 		("mbuf too small, len %u", m->m_len));
7558 
7559 	msg = mtod(m, struct sadb_msg *);
7560 	msg->sadb_msg_errno = code;
7561 	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7562 }
7563 
7564 /*
7565  * set the pointer to each header into message buffer.
7566  * m will be freed on error.
7567  * XXX larger-than-MCLBYTES extension?
7568  */
7569 static int
7570 key_align(m, mhp)
7571 	struct mbuf *m;
7572 	struct sadb_msghdr *mhp;
7573 {
7574 	struct mbuf *n;
7575 	struct sadb_ext *ext;
7576 	size_t off, end;
7577 	int extlen;
7578 	int toff;
7579 
7580 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7581 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7582 	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7583 		("mbuf too small, len %u", m->m_len));
7584 
7585 	/* initialize */
7586 	bzero(mhp, sizeof(*mhp));
7587 
7588 	mhp->msg = mtod(m, struct sadb_msg *);
7589 	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7590 
7591 	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7592 	extlen = end;	/*just in case extlen is not updated*/
7593 	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7594 		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7595 		if (!n) {
7596 			/* m is already freed */
7597 			return ENOBUFS;
7598 		}
7599 		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7600 
7601 		/* set pointer */
7602 		switch (ext->sadb_ext_type) {
7603 		case SADB_EXT_SA:
7604 		case SADB_EXT_ADDRESS_SRC:
7605 		case SADB_EXT_ADDRESS_DST:
7606 		case SADB_EXT_ADDRESS_PROXY:
7607 		case SADB_EXT_LIFETIME_CURRENT:
7608 		case SADB_EXT_LIFETIME_HARD:
7609 		case SADB_EXT_LIFETIME_SOFT:
7610 		case SADB_EXT_KEY_AUTH:
7611 		case SADB_EXT_KEY_ENCRYPT:
7612 		case SADB_EXT_IDENTITY_SRC:
7613 		case SADB_EXT_IDENTITY_DST:
7614 		case SADB_EXT_SENSITIVITY:
7615 		case SADB_EXT_PROPOSAL:
7616 		case SADB_EXT_SUPPORTED_AUTH:
7617 		case SADB_EXT_SUPPORTED_ENCRYPT:
7618 		case SADB_EXT_SPIRANGE:
7619 		case SADB_X_EXT_POLICY:
7620 		case SADB_X_EXT_SA2:
7621 #ifdef IPSEC_NAT_T
7622 		case SADB_X_EXT_NAT_T_TYPE:
7623 		case SADB_X_EXT_NAT_T_SPORT:
7624 		case SADB_X_EXT_NAT_T_DPORT:
7625 		case SADB_X_EXT_NAT_T_OAI:
7626 		case SADB_X_EXT_NAT_T_OAR:
7627 		case SADB_X_EXT_NAT_T_FRAG:
7628 #endif
7629 			/* duplicate check */
7630 			/*
7631 			 * XXX Are there duplication payloads of either
7632 			 * KEY_AUTH or KEY_ENCRYPT ?
7633 			 */
7634 			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7635 				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7636 					"%u\n", __func__, ext->sadb_ext_type));
7637 				m_freem(m);
7638 				V_pfkeystat.out_dupext++;
7639 				return EINVAL;
7640 			}
7641 			break;
7642 		default:
7643 			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7644 				__func__, ext->sadb_ext_type));
7645 			m_freem(m);
7646 			V_pfkeystat.out_invexttype++;
7647 			return EINVAL;
7648 		}
7649 
7650 		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7651 
7652 		if (key_validate_ext(ext, extlen)) {
7653 			m_freem(m);
7654 			V_pfkeystat.out_invlen++;
7655 			return EINVAL;
7656 		}
7657 
7658 		n = m_pulldown(m, off, extlen, &toff);
7659 		if (!n) {
7660 			/* m is already freed */
7661 			return ENOBUFS;
7662 		}
7663 		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7664 
7665 		mhp->ext[ext->sadb_ext_type] = ext;
7666 		mhp->extoff[ext->sadb_ext_type] = off;
7667 		mhp->extlen[ext->sadb_ext_type] = extlen;
7668 	}
7669 
7670 	if (off != end) {
7671 		m_freem(m);
7672 		V_pfkeystat.out_invlen++;
7673 		return EINVAL;
7674 	}
7675 
7676 	return 0;
7677 }
7678 
7679 static int
7680 key_validate_ext(ext, len)
7681 	const struct sadb_ext *ext;
7682 	int len;
7683 {
7684 	const struct sockaddr *sa;
7685 	enum { NONE, ADDR } checktype = NONE;
7686 	int baselen = 0;
7687 	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7688 
7689 	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7690 		return EINVAL;
7691 
7692 	/* if it does not match minimum/maximum length, bail */
7693 	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7694 	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7695 		return EINVAL;
7696 	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7697 		return EINVAL;
7698 	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7699 		return EINVAL;
7700 
7701 	/* more checks based on sadb_ext_type XXX need more */
7702 	switch (ext->sadb_ext_type) {
7703 	case SADB_EXT_ADDRESS_SRC:
7704 	case SADB_EXT_ADDRESS_DST:
7705 	case SADB_EXT_ADDRESS_PROXY:
7706 		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7707 		checktype = ADDR;
7708 		break;
7709 	case SADB_EXT_IDENTITY_SRC:
7710 	case SADB_EXT_IDENTITY_DST:
7711 		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7712 		    SADB_X_IDENTTYPE_ADDR) {
7713 			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7714 			checktype = ADDR;
7715 		} else
7716 			checktype = NONE;
7717 		break;
7718 	default:
7719 		checktype = NONE;
7720 		break;
7721 	}
7722 
7723 	switch (checktype) {
7724 	case NONE:
7725 		break;
7726 	case ADDR:
7727 		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7728 		if (len < baselen + sal)
7729 			return EINVAL;
7730 		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7731 			return EINVAL;
7732 		break;
7733 	}
7734 
7735 	return 0;
7736 }
7737 
7738 void
7739 key_init(void)
7740 {
7741 	int i;
7742 
7743 	for (i = 0; i < IPSEC_DIR_MAX; i++)
7744 		LIST_INIT(&V_sptree[i]);
7745 
7746 	LIST_INIT(&V_sahtree);
7747 
7748 	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7749 		LIST_INIT(&V_regtree[i]);
7750 
7751 	LIST_INIT(&V_acqtree);
7752 	LIST_INIT(&V_spacqtree);
7753 
7754 	/* system default */
7755 	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7756 	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7757 
7758 	if (!IS_DEFAULT_VNET(curvnet))
7759 		return;
7760 
7761 	SPTREE_LOCK_INIT();
7762 	REGTREE_LOCK_INIT();
7763 	SAHTREE_LOCK_INIT();
7764 	ACQ_LOCK_INIT();
7765 	SPACQ_LOCK_INIT();
7766 
7767 #ifndef IPSEC_DEBUG2
7768 	timeout((void *)key_timehandler, (void *)0, hz);
7769 #endif /*IPSEC_DEBUG2*/
7770 
7771 	/* initialize key statistics */
7772 	keystat.getspi_count = 1;
7773 
7774 	printf("IPsec: Initialized Security Association Processing.\n");
7775 }
7776 
7777 #ifdef VIMAGE
7778 void
7779 key_destroy(void)
7780 {
7781 	struct secpolicy *sp, *nextsp;
7782 	struct secspacq *acq, *nextacq;
7783 	struct secashead *sah, *nextsah;
7784 	struct secreg *reg;
7785 	int i;
7786 
7787 	SPTREE_LOCK();
7788 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7789 		for (sp = LIST_FIRST(&V_sptree[i]);
7790 		    sp != NULL; sp = nextsp) {
7791 			nextsp = LIST_NEXT(sp, chain);
7792 			if (__LIST_CHAINED(sp)) {
7793 				LIST_REMOVE(sp, chain);
7794 				free(sp, M_IPSEC_SP);
7795 			}
7796 		}
7797 	}
7798 	SPTREE_UNLOCK();
7799 
7800 	SAHTREE_LOCK();
7801 	for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7802 		nextsah = LIST_NEXT(sah, chain);
7803 		if (__LIST_CHAINED(sah)) {
7804 			LIST_REMOVE(sah, chain);
7805 			free(sah, M_IPSEC_SAH);
7806 		}
7807 	}
7808 	SAHTREE_UNLOCK();
7809 
7810 	REGTREE_LOCK();
7811 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7812 		LIST_FOREACH(reg, &V_regtree[i], chain) {
7813 			if (__LIST_CHAINED(reg)) {
7814 				LIST_REMOVE(reg, chain);
7815 				free(reg, M_IPSEC_SAR);
7816 				break;
7817 			}
7818 		}
7819 	}
7820 	REGTREE_UNLOCK();
7821 
7822 	ACQ_LOCK();
7823 	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
7824 		nextacq = LIST_NEXT(acq, chain);
7825 		if (__LIST_CHAINED(acq)) {
7826 			LIST_REMOVE(acq, chain);
7827 			free(acq, M_IPSEC_SAQ);
7828 		}
7829 	}
7830 	ACQ_UNLOCK();
7831 
7832 	SPACQ_LOCK();
7833 	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
7834 		nextacq = LIST_NEXT(acq, chain);
7835 		if (__LIST_CHAINED(acq)) {
7836 			LIST_REMOVE(acq, chain);
7837 			free(acq, M_IPSEC_SAQ);
7838 		}
7839 	}
7840 	SPACQ_UNLOCK();
7841 }
7842 #endif
7843 
7844 /*
7845  * XXX: maybe This function is called after INBOUND IPsec processing.
7846  *
7847  * Special check for tunnel-mode packets.
7848  * We must make some checks for consistency between inner and outer IP header.
7849  *
7850  * xxx more checks to be provided
7851  */
7852 int
7853 key_checktunnelsanity(sav, family, src, dst)
7854 	struct secasvar *sav;
7855 	u_int family;
7856 	caddr_t src;
7857 	caddr_t dst;
7858 {
7859 	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7860 
7861 	/* XXX: check inner IP header */
7862 
7863 	return 1;
7864 }
7865 
7866 /* record data transfer on SA, and update timestamps */
7867 void
7868 key_sa_recordxfer(sav, m)
7869 	struct secasvar *sav;
7870 	struct mbuf *m;
7871 {
7872 	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7873 	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7874 	if (!sav->lft_c)
7875 		return;
7876 
7877 	/*
7878 	 * XXX Currently, there is a difference of bytes size
7879 	 * between inbound and outbound processing.
7880 	 */
7881 	sav->lft_c->bytes += m->m_pkthdr.len;
7882 	/* to check bytes lifetime is done in key_timehandler(). */
7883 
7884 	/*
7885 	 * We use the number of packets as the unit of
7886 	 * allocations.  We increment the variable
7887 	 * whenever {esp,ah}_{in,out}put is called.
7888 	 */
7889 	sav->lft_c->allocations++;
7890 	/* XXX check for expires? */
7891 
7892 	/*
7893 	 * NOTE: We record CURRENT usetime by using wall clock,
7894 	 * in seconds.  HARD and SOFT lifetime are measured by the time
7895 	 * difference (again in seconds) from usetime.
7896 	 *
7897 	 *	usetime
7898 	 *	v     expire   expire
7899 	 * -----+-----+--------+---> t
7900 	 *	<--------------> HARD
7901 	 *	<-----> SOFT
7902 	 */
7903 	sav->lft_c->usetime = time_second;
7904 	/* XXX check for expires? */
7905 
7906 	return;
7907 }
7908 
7909 /* dumb version */
7910 void
7911 key_sa_routechange(dst)
7912 	struct sockaddr *dst;
7913 {
7914 	struct secashead *sah;
7915 	struct route *ro;
7916 
7917 	SAHTREE_LOCK();
7918 	LIST_FOREACH(sah, &V_sahtree, chain) {
7919 		ro = &sah->sa_route;
7920 		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7921 		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7922 			RTFREE(ro->ro_rt);
7923 			ro->ro_rt = (struct rtentry *)NULL;
7924 		}
7925 	}
7926 	SAHTREE_UNLOCK();
7927 }
7928 
7929 static void
7930 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7931 {
7932 	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7933 	SAHTREE_LOCK_ASSERT();
7934 
7935 	if (sav->state != state) {
7936 		if (__LIST_CHAINED(sav))
7937 			LIST_REMOVE(sav, chain);
7938 		sav->state = state;
7939 		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7940 	}
7941 }
7942 
7943 void
7944 key_sa_stir_iv(sav)
7945 	struct secasvar *sav;
7946 {
7947 
7948 	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7949 	key_randomfill(sav->iv, sav->ivlen);
7950 }
7951 
7952 /* XXX too much? */
7953 static struct mbuf *
7954 key_alloc_mbuf(l)
7955 	int l;
7956 {
7957 	struct mbuf *m = NULL, *n;
7958 	int len, t;
7959 
7960 	len = l;
7961 	while (len > 0) {
7962 		MGET(n, M_DONTWAIT, MT_DATA);
7963 		if (n && len > MLEN)
7964 			MCLGET(n, M_DONTWAIT);
7965 		if (!n) {
7966 			m_freem(m);
7967 			return NULL;
7968 		}
7969 
7970 		n->m_next = NULL;
7971 		n->m_len = 0;
7972 		n->m_len = M_TRAILINGSPACE(n);
7973 		/* use the bottom of mbuf, hoping we can prepend afterwards */
7974 		if (n->m_len > len) {
7975 			t = (n->m_len - len) & ~(sizeof(long) - 1);
7976 			n->m_data += t;
7977 			n->m_len = len;
7978 		}
7979 
7980 		len -= n->m_len;
7981 
7982 		if (m)
7983 			m_cat(m, n);
7984 		else
7985 			m = n;
7986 	}
7987 
7988 	return m;
7989 }
7990 
7991 /*
7992  * Take one of the kernel's security keys and convert it into a PF_KEY
7993  * structure within an mbuf, suitable for sending up to a waiting
7994  * application in user land.
7995  *
7996  * IN:
7997  *    src: A pointer to a kernel security key.
7998  *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
7999  * OUT:
8000  *    a valid mbuf or NULL indicating an error
8001  *
8002  */
8003 
8004 static struct mbuf *
8005 key_setkey(struct seckey *src, u_int16_t exttype)
8006 {
8007 	struct mbuf *m;
8008 	struct sadb_key *p;
8009 	int len;
8010 
8011 	if (src == NULL)
8012 		return NULL;
8013 
8014 	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8015 	m = key_alloc_mbuf(len);
8016 	if (m == NULL)
8017 		return NULL;
8018 	p = mtod(m, struct sadb_key *);
8019 	bzero(p, len);
8020 	p->sadb_key_len = PFKEY_UNIT64(len);
8021 	p->sadb_key_exttype = exttype;
8022 	p->sadb_key_bits = src->bits;
8023 	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8024 
8025 	return m;
8026 }
8027 
8028 /*
8029  * Take one of the kernel's lifetime data structures and convert it
8030  * into a PF_KEY structure within an mbuf, suitable for sending up to
8031  * a waiting application in user land.
8032  *
8033  * IN:
8034  *    src: A pointer to a kernel lifetime structure.
8035  *    exttype: Which type of lifetime this is. Refer to the PF_KEY
8036  *             data structures for more information.
8037  * OUT:
8038  *    a valid mbuf or NULL indicating an error
8039  *
8040  */
8041 
8042 static struct mbuf *
8043 key_setlifetime(struct seclifetime *src, u_int16_t exttype)
8044 {
8045 	struct mbuf *m = NULL;
8046 	struct sadb_lifetime *p;
8047 	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8048 
8049 	if (src == NULL)
8050 		return NULL;
8051 
8052 	m = key_alloc_mbuf(len);
8053 	if (m == NULL)
8054 		return m;
8055 	p = mtod(m, struct sadb_lifetime *);
8056 
8057 	bzero(p, len);
8058 	p->sadb_lifetime_len = PFKEY_UNIT64(len);
8059 	p->sadb_lifetime_exttype = exttype;
8060 	p->sadb_lifetime_allocations = src->allocations;
8061 	p->sadb_lifetime_bytes = src->bytes;
8062 	p->sadb_lifetime_addtime = src->addtime;
8063 	p->sadb_lifetime_usetime = src->usetime;
8064 
8065 	return m;
8066 
8067 }
8068