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