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