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