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