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