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