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