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