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