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