key.c revision 125508
1/*	$FreeBSD: head/sys/netipsec/key.c 125508 2004-02-05 23:19:17Z sam $	*/
2/*	$KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $	*/
3
4/*
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/*
34 * This code is referd to RFC 2367
35 */
36
37#include "opt_inet.h"
38#include "opt_inet6.h"
39#include "opt_ipsec.h"
40
41#include <sys/types.h>
42#include <sys/param.h>
43#include <sys/systm.h>
44#include <sys/kernel.h>
45#include <sys/lock.h>
46#include <sys/mutex.h>
47#include <sys/mbuf.h>
48#include <sys/domain.h>
49#include <sys/protosw.h>
50#include <sys/malloc.h>
51#include <sys/socket.h>
52#include <sys/socketvar.h>
53#include <sys/sysctl.h>
54#include <sys/errno.h>
55#include <sys/proc.h>
56#include <sys/queue.h>
57#include <sys/syslog.h>
58
59#include <net/if.h>
60#include <net/route.h>
61#include <net/raw_cb.h>
62
63#include <netinet/in.h>
64#include <netinet/in_systm.h>
65#include <netinet/ip.h>
66#include <netinet/in_var.h>
67
68#ifdef INET6
69#include <netinet/ip6.h>
70#include <netinet6/in6_var.h>
71#include <netinet6/ip6_var.h>
72#endif /* INET6 */
73
74#ifdef INET
75#include <netinet/in_pcb.h>
76#endif
77#ifdef INET6
78#include <netinet6/in6_pcb.h>
79#endif /* INET6 */
80
81#include <net/pfkeyv2.h>
82#include <netipsec/keydb.h>
83#include <netipsec/key.h>
84#include <netipsec/keysock.h>
85#include <netipsec/key_debug.h>
86
87#include <netipsec/ipsec.h>
88#ifdef INET6
89#include <netipsec/ipsec6.h>
90#endif
91
92#include <netipsec/xform.h>
93
94#include <machine/stdarg.h>
95
96/* randomness */
97#include <sys/random.h>
98
99#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			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3007			    sav->alg_auth != SADB_X_AALG_NULL)
3008				error = EINVAL;
3009			break;
3010		case SADB_X_SATYPE_IPCOMP:
3011		default:
3012			error = EINVAL;
3013			break;
3014		}
3015		if (error) {
3016			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3017				__func__));
3018			goto fail;
3019		}
3020
3021		sav->key_auth = key_dup(key0, len, M_IPSEC_MISC);
3022		if (sav->key_auth == NULL) {
3023			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3024			error = ENOBUFS;
3025			goto fail;
3026		}
3027	}
3028
3029	/* Encryption key */
3030	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3031		const struct sadb_key *key0;
3032		int len;
3033
3034		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3035		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3036
3037		error = 0;
3038		if (len < sizeof(*key0)) {
3039			error = EINVAL;
3040			goto fail;
3041		}
3042		switch (mhp->msg->sadb_msg_satype) {
3043		case SADB_SATYPE_ESP:
3044			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3045			    sav->alg_enc != SADB_EALG_NULL) {
3046				error = EINVAL;
3047				break;
3048			}
3049			sav->key_enc = key_dup(key0, len, M_IPSEC_MISC);
3050			if (sav->key_enc == NULL) {
3051				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3052					__func__));
3053				error = ENOBUFS;
3054				goto fail;
3055			}
3056			break;
3057		case SADB_X_SATYPE_IPCOMP:
3058			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3059				error = EINVAL;
3060			sav->key_enc = NULL;	/*just in case*/
3061			break;
3062		case SADB_SATYPE_AH:
3063		default:
3064			error = EINVAL;
3065			break;
3066		}
3067		if (error) {
3068			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3069				__func__));
3070			goto fail;
3071		}
3072	}
3073
3074	/* set iv */
3075	sav->ivlen = 0;
3076
3077	switch (mhp->msg->sadb_msg_satype) {
3078	case SADB_SATYPE_AH:
3079		error = xform_init(sav, XF_AH);
3080		break;
3081	case SADB_SATYPE_ESP:
3082		error = xform_init(sav, XF_ESP);
3083		break;
3084	case SADB_X_SATYPE_IPCOMP:
3085		error = xform_init(sav, XF_IPCOMP);
3086		break;
3087	}
3088	if (error) {
3089		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3090		        __func__, mhp->msg->sadb_msg_satype));
3091		goto fail;
3092	}
3093
3094	/* reset created */
3095	sav->created = time_second;
3096
3097	/* make lifetime for CURRENT */
3098	sav->lft_c = malloc(sizeof(struct sadb_lifetime), M_IPSEC_MISC, M_NOWAIT);
3099	if (sav->lft_c == NULL) {
3100		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3101		error = ENOBUFS;
3102		goto fail;
3103	}
3104
3105	sav->lft_c->sadb_lifetime_len =
3106	    PFKEY_UNIT64(sizeof(struct sadb_lifetime));
3107	sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
3108	sav->lft_c->sadb_lifetime_allocations = 0;
3109	sav->lft_c->sadb_lifetime_bytes = 0;
3110	sav->lft_c->sadb_lifetime_addtime = time_second;
3111	sav->lft_c->sadb_lifetime_usetime = 0;
3112
3113	/* lifetimes for HARD and SOFT */
3114    {
3115	const struct sadb_lifetime *lft0;
3116
3117	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3118	if (lft0 != NULL) {
3119		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3120			error = EINVAL;
3121			goto fail;
3122		}
3123		sav->lft_h = key_dup(lft0, sizeof(*lft0), M_IPSEC_MISC);
3124		if (sav->lft_h == NULL) {
3125			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3126			error = ENOBUFS;
3127			goto fail;
3128		}
3129		/* to be initialize ? */
3130	}
3131
3132	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3133	if (lft0 != NULL) {
3134		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3135			error = EINVAL;
3136			goto fail;
3137		}
3138		sav->lft_s = key_dup(lft0, sizeof(*lft0), M_IPSEC_MISC);
3139		if (sav->lft_s == NULL) {
3140			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3141			error = ENOBUFS;
3142			goto fail;
3143		}
3144		/* to be initialize ? */
3145	}
3146    }
3147
3148	return 0;
3149
3150 fail:
3151	/* initialization */
3152	key_cleansav(sav);
3153
3154	return error;
3155}
3156
3157/*
3158 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3159 * OUT:	0:	valid
3160 *	other:	errno
3161 */
3162static int
3163key_mature(struct secasvar *sav)
3164{
3165	int error;
3166
3167	/* check SPI value */
3168	switch (sav->sah->saidx.proto) {
3169	case IPPROTO_ESP:
3170	case IPPROTO_AH:
3171		if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
3172			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3173			    __func__, (u_int32_t)ntohl(sav->spi)));
3174			return EINVAL;
3175		}
3176		break;
3177	}
3178
3179	/* check satype */
3180	switch (sav->sah->saidx.proto) {
3181	case IPPROTO_ESP:
3182		/* check flags */
3183		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3184		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3185			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3186				"given to old-esp.\n", __func__));
3187			return EINVAL;
3188		}
3189		error = xform_init(sav, XF_ESP);
3190		break;
3191	case IPPROTO_AH:
3192		/* check flags */
3193		if (sav->flags & SADB_X_EXT_DERIV) {
3194			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3195				"given to AH SA.\n", __func__));
3196			return EINVAL;
3197		}
3198		if (sav->alg_enc != SADB_EALG_NONE) {
3199			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3200				"mismated.\n", __func__));
3201			return(EINVAL);
3202		}
3203		error = xform_init(sav, XF_AH);
3204		break;
3205	case IPPROTO_IPCOMP:
3206		if (sav->alg_auth != SADB_AALG_NONE) {
3207			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3208				"mismated.\n", __func__));
3209			return(EINVAL);
3210		}
3211		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3212		 && ntohl(sav->spi) >= 0x10000) {
3213			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3214				__func__));
3215			return(EINVAL);
3216		}
3217		error = xform_init(sav, XF_IPCOMP);
3218		break;
3219	default:
3220		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3221		error = EPROTONOSUPPORT;
3222		break;
3223	}
3224	if (error == 0) {
3225		SAHTREE_LOCK();
3226		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3227		SAHTREE_UNLOCK();
3228	}
3229	return (error);
3230}
3231
3232/*
3233 * subroutine for SADB_GET and SADB_DUMP.
3234 */
3235static struct mbuf *
3236key_setdumpsa(sav, type, satype, seq, pid)
3237	struct secasvar *sav;
3238	u_int8_t type, satype;
3239	u_int32_t seq, pid;
3240{
3241	struct mbuf *result = NULL, *tres = NULL, *m;
3242	int l = 0;
3243	int i;
3244	void *p;
3245	int dumporder[] = {
3246		SADB_EXT_SA, SADB_X_EXT_SA2,
3247		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3248		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3249		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3250		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3251		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3252	};
3253
3254	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3255	if (m == NULL)
3256		goto fail;
3257	result = m;
3258
3259	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3260		m = NULL;
3261		p = NULL;
3262		switch (dumporder[i]) {
3263		case SADB_EXT_SA:
3264			m = key_setsadbsa(sav);
3265			if (!m)
3266				goto fail;
3267			break;
3268
3269		case SADB_X_EXT_SA2:
3270			m = key_setsadbxsa2(sav->sah->saidx.mode,
3271					sav->replay ? sav->replay->count : 0,
3272					sav->sah->saidx.reqid);
3273			if (!m)
3274				goto fail;
3275			break;
3276
3277		case SADB_EXT_ADDRESS_SRC:
3278			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3279			    &sav->sah->saidx.src.sa,
3280			    FULLMASK, IPSEC_ULPROTO_ANY);
3281			if (!m)
3282				goto fail;
3283			break;
3284
3285		case SADB_EXT_ADDRESS_DST:
3286			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3287			    &sav->sah->saidx.dst.sa,
3288			    FULLMASK, IPSEC_ULPROTO_ANY);
3289			if (!m)
3290				goto fail;
3291			break;
3292
3293		case SADB_EXT_KEY_AUTH:
3294			if (!sav->key_auth)
3295				continue;
3296			l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
3297			p = sav->key_auth;
3298			break;
3299
3300		case SADB_EXT_KEY_ENCRYPT:
3301			if (!sav->key_enc)
3302				continue;
3303			l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
3304			p = sav->key_enc;
3305			break;
3306
3307		case SADB_EXT_LIFETIME_CURRENT:
3308			if (!sav->lft_c)
3309				continue;
3310			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
3311			p = sav->lft_c;
3312			break;
3313
3314		case SADB_EXT_LIFETIME_HARD:
3315			if (!sav->lft_h)
3316				continue;
3317			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
3318			p = sav->lft_h;
3319			break;
3320
3321		case SADB_EXT_LIFETIME_SOFT:
3322			if (!sav->lft_s)
3323				continue;
3324			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
3325			p = sav->lft_s;
3326			break;
3327
3328		case SADB_EXT_ADDRESS_PROXY:
3329		case SADB_EXT_IDENTITY_SRC:
3330		case SADB_EXT_IDENTITY_DST:
3331			/* XXX: should we brought from SPD ? */
3332		case SADB_EXT_SENSITIVITY:
3333		default:
3334			continue;
3335		}
3336
3337		if ((!m && !p) || (m && p))
3338			goto fail;
3339		if (p && tres) {
3340			M_PREPEND(tres, l, M_DONTWAIT);
3341			if (!tres)
3342				goto fail;
3343			bcopy(p, mtod(tres, caddr_t), l);
3344			continue;
3345		}
3346		if (p) {
3347			m = key_alloc_mbuf(l);
3348			if (!m)
3349				goto fail;
3350			m_copyback(m, 0, l, p);
3351		}
3352
3353		if (tres)
3354			m_cat(m, tres);
3355		tres = m;
3356	}
3357
3358	m_cat(result, tres);
3359
3360	if (result->m_len < sizeof(struct sadb_msg)) {
3361		result = m_pullup(result, sizeof(struct sadb_msg));
3362		if (result == NULL)
3363			goto fail;
3364	}
3365
3366	result->m_pkthdr.len = 0;
3367	for (m = result; m; m = m->m_next)
3368		result->m_pkthdr.len += m->m_len;
3369
3370	mtod(result, struct sadb_msg *)->sadb_msg_len =
3371	    PFKEY_UNIT64(result->m_pkthdr.len);
3372
3373	return result;
3374
3375fail:
3376	m_freem(result);
3377	m_freem(tres);
3378	return NULL;
3379}
3380
3381/*
3382 * set data into sadb_msg.
3383 */
3384static struct mbuf *
3385key_setsadbmsg(type, tlen, satype, seq, pid, reserved)
3386	u_int8_t type, satype;
3387	u_int16_t tlen;
3388	u_int32_t seq;
3389	pid_t pid;
3390	u_int16_t reserved;
3391{
3392	struct mbuf *m;
3393	struct sadb_msg *p;
3394	int len;
3395
3396	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3397	if (len > MCLBYTES)
3398		return NULL;
3399	MGETHDR(m, M_DONTWAIT, MT_DATA);
3400	if (m && len > MHLEN) {
3401		MCLGET(m, M_DONTWAIT);
3402		if ((m->m_flags & M_EXT) == 0) {
3403			m_freem(m);
3404			m = NULL;
3405		}
3406	}
3407	if (!m)
3408		return NULL;
3409	m->m_pkthdr.len = m->m_len = len;
3410	m->m_next = NULL;
3411
3412	p = mtod(m, struct sadb_msg *);
3413
3414	bzero(p, len);
3415	p->sadb_msg_version = PF_KEY_V2;
3416	p->sadb_msg_type = type;
3417	p->sadb_msg_errno = 0;
3418	p->sadb_msg_satype = satype;
3419	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3420	p->sadb_msg_reserved = reserved;
3421	p->sadb_msg_seq = seq;
3422	p->sadb_msg_pid = (u_int32_t)pid;
3423
3424	return m;
3425}
3426
3427/*
3428 * copy secasvar data into sadb_address.
3429 */
3430static struct mbuf *
3431key_setsadbsa(sav)
3432	struct secasvar *sav;
3433{
3434	struct mbuf *m;
3435	struct sadb_sa *p;
3436	int len;
3437
3438	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3439	m = key_alloc_mbuf(len);
3440	if (!m || m->m_next) {	/*XXX*/
3441		if (m)
3442			m_freem(m);
3443		return NULL;
3444	}
3445
3446	p = mtod(m, struct sadb_sa *);
3447
3448	bzero(p, len);
3449	p->sadb_sa_len = PFKEY_UNIT64(len);
3450	p->sadb_sa_exttype = SADB_EXT_SA;
3451	p->sadb_sa_spi = sav->spi;
3452	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3453	p->sadb_sa_state = sav->state;
3454	p->sadb_sa_auth = sav->alg_auth;
3455	p->sadb_sa_encrypt = sav->alg_enc;
3456	p->sadb_sa_flags = sav->flags;
3457
3458	return m;
3459}
3460
3461/*
3462 * set data into sadb_address.
3463 */
3464static struct mbuf *
3465key_setsadbaddr(exttype, saddr, prefixlen, ul_proto)
3466	u_int16_t exttype;
3467	const struct sockaddr *saddr;
3468	u_int8_t prefixlen;
3469	u_int16_t ul_proto;
3470{
3471	struct mbuf *m;
3472	struct sadb_address *p;
3473	size_t len;
3474
3475	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3476	    PFKEY_ALIGN8(saddr->sa_len);
3477	m = key_alloc_mbuf(len);
3478	if (!m || m->m_next) {	/*XXX*/
3479		if (m)
3480			m_freem(m);
3481		return NULL;
3482	}
3483
3484	p = mtod(m, struct sadb_address *);
3485
3486	bzero(p, len);
3487	p->sadb_address_len = PFKEY_UNIT64(len);
3488	p->sadb_address_exttype = exttype;
3489	p->sadb_address_proto = ul_proto;
3490	if (prefixlen == FULLMASK) {
3491		switch (saddr->sa_family) {
3492		case AF_INET:
3493			prefixlen = sizeof(struct in_addr) << 3;
3494			break;
3495		case AF_INET6:
3496			prefixlen = sizeof(struct in6_addr) << 3;
3497			break;
3498		default:
3499			; /*XXX*/
3500		}
3501	}
3502	p->sadb_address_prefixlen = prefixlen;
3503	p->sadb_address_reserved = 0;
3504
3505	bcopy(saddr,
3506	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3507	    saddr->sa_len);
3508
3509	return m;
3510}
3511
3512/*
3513 * set data into sadb_x_sa2.
3514 */
3515static struct mbuf *
3516key_setsadbxsa2(mode, seq, reqid)
3517	u_int8_t mode;
3518	u_int32_t seq, reqid;
3519{
3520	struct mbuf *m;
3521	struct sadb_x_sa2 *p;
3522	size_t len;
3523
3524	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3525	m = key_alloc_mbuf(len);
3526	if (!m || m->m_next) {	/*XXX*/
3527		if (m)
3528			m_freem(m);
3529		return NULL;
3530	}
3531
3532	p = mtod(m, struct sadb_x_sa2 *);
3533
3534	bzero(p, len);
3535	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3536	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3537	p->sadb_x_sa2_mode = mode;
3538	p->sadb_x_sa2_reserved1 = 0;
3539	p->sadb_x_sa2_reserved2 = 0;
3540	p->sadb_x_sa2_sequence = seq;
3541	p->sadb_x_sa2_reqid = reqid;
3542
3543	return m;
3544}
3545
3546/*
3547 * set data into sadb_x_policy
3548 */
3549static struct mbuf *
3550key_setsadbxpolicy(type, dir, id)
3551	u_int16_t type;
3552	u_int8_t dir;
3553	u_int32_t id;
3554{
3555	struct mbuf *m;
3556	struct sadb_x_policy *p;
3557	size_t len;
3558
3559	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3560	m = key_alloc_mbuf(len);
3561	if (!m || m->m_next) {	/*XXX*/
3562		if (m)
3563			m_freem(m);
3564		return NULL;
3565	}
3566
3567	p = mtod(m, struct sadb_x_policy *);
3568
3569	bzero(p, len);
3570	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3571	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3572	p->sadb_x_policy_type = type;
3573	p->sadb_x_policy_dir = dir;
3574	p->sadb_x_policy_id = id;
3575
3576	return m;
3577}
3578
3579/* %%% utilities */
3580/*
3581 * copy a buffer into the new buffer allocated.
3582 */
3583static void *
3584key_dup(const void *src, u_int len, struct malloc_type *type)
3585{
3586	void *copy;
3587
3588	copy = malloc(len, type, M_NOWAIT);
3589	if (copy == NULL) {
3590		/* XXX counter */
3591		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3592	} else
3593		bcopy(src, copy, len);
3594	return copy;
3595}
3596
3597/* compare my own address
3598 * OUT:	1: true, i.e. my address.
3599 *	0: false
3600 */
3601int
3602key_ismyaddr(sa)
3603	struct sockaddr *sa;
3604{
3605#ifdef INET
3606	struct sockaddr_in *sin;
3607	struct in_ifaddr *ia;
3608#endif
3609
3610	IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3611
3612	switch (sa->sa_family) {
3613#ifdef INET
3614	case AF_INET:
3615		sin = (struct sockaddr_in *)sa;
3616		for (ia = in_ifaddrhead.tqh_first; ia;
3617		     ia = ia->ia_link.tqe_next)
3618		{
3619			if (sin->sin_family == ia->ia_addr.sin_family &&
3620			    sin->sin_len == ia->ia_addr.sin_len &&
3621			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3622			{
3623				return 1;
3624			}
3625		}
3626		break;
3627#endif
3628#ifdef INET6
3629	case AF_INET6:
3630		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3631#endif
3632	}
3633
3634	return 0;
3635}
3636
3637#ifdef INET6
3638/*
3639 * compare my own address for IPv6.
3640 * 1: ours
3641 * 0: other
3642 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3643 */
3644#include <netinet6/in6_var.h>
3645
3646static int
3647key_ismyaddr6(sin6)
3648	struct sockaddr_in6 *sin6;
3649{
3650	struct in6_ifaddr *ia;
3651	struct in6_multi *in6m;
3652
3653	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
3654		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3655		    (struct sockaddr *)&ia->ia_addr, 0) == 0)
3656			return 1;
3657
3658		/*
3659		 * XXX Multicast
3660		 * XXX why do we care about multlicast here while we don't care
3661		 * about IPv4 multicast??
3662		 * XXX scope
3663		 */
3664		in6m = NULL;
3665		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3666		if (in6m)
3667			return 1;
3668	}
3669
3670	/* loopback, just for safety */
3671	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3672		return 1;
3673
3674	return 0;
3675}
3676#endif /*INET6*/
3677
3678/*
3679 * compare two secasindex structure.
3680 * flag can specify to compare 2 saidxes.
3681 * compare two secasindex structure without both mode and reqid.
3682 * don't compare port.
3683 * IN:
3684 *      saidx0: source, it can be in SAD.
3685 *      saidx1: object.
3686 * OUT:
3687 *      1 : equal
3688 *      0 : not equal
3689 */
3690static int
3691key_cmpsaidx(
3692	const struct secasindex *saidx0,
3693	const struct secasindex *saidx1,
3694	int flag)
3695{
3696	/* sanity */
3697	if (saidx0 == NULL && saidx1 == NULL)
3698		return 1;
3699
3700	if (saidx0 == NULL || saidx1 == NULL)
3701		return 0;
3702
3703	if (saidx0->proto != saidx1->proto)
3704		return 0;
3705
3706	if (flag == CMP_EXACTLY) {
3707		if (saidx0->mode != saidx1->mode)
3708			return 0;
3709		if (saidx0->reqid != saidx1->reqid)
3710			return 0;
3711		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3712		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3713			return 0;
3714	} else {
3715
3716		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3717		if (flag == CMP_MODE_REQID
3718		  ||flag == CMP_REQID) {
3719			/*
3720			 * If reqid of SPD is non-zero, unique SA is required.
3721			 * The result must be of same reqid in this case.
3722			 */
3723			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3724				return 0;
3725		}
3726
3727		if (flag == CMP_MODE_REQID) {
3728			if (saidx0->mode != IPSEC_MODE_ANY
3729			 && saidx0->mode != saidx1->mode)
3730				return 0;
3731		}
3732
3733		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
3734			return 0;
3735		}
3736		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
3737			return 0;
3738		}
3739	}
3740
3741	return 1;
3742}
3743
3744/*
3745 * compare two secindex structure exactly.
3746 * IN:
3747 *	spidx0: source, it is often in SPD.
3748 *	spidx1: object, it is often from PFKEY message.
3749 * OUT:
3750 *	1 : equal
3751 *	0 : not equal
3752 */
3753static int
3754key_cmpspidx_exactly(
3755	struct secpolicyindex *spidx0,
3756	struct secpolicyindex *spidx1)
3757{
3758	/* sanity */
3759	if (spidx0 == NULL && spidx1 == NULL)
3760		return 1;
3761
3762	if (spidx0 == NULL || spidx1 == NULL)
3763		return 0;
3764
3765	if (spidx0->prefs != spidx1->prefs
3766	 || spidx0->prefd != spidx1->prefd
3767	 || spidx0->ul_proto != spidx1->ul_proto)
3768		return 0;
3769
3770	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3771	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3772}
3773
3774/*
3775 * compare two secindex structure with mask.
3776 * IN:
3777 *	spidx0: source, it is often in SPD.
3778 *	spidx1: object, it is often from IP header.
3779 * OUT:
3780 *	1 : equal
3781 *	0 : not equal
3782 */
3783static int
3784key_cmpspidx_withmask(
3785	struct secpolicyindex *spidx0,
3786	struct secpolicyindex *spidx1)
3787{
3788	/* sanity */
3789	if (spidx0 == NULL && spidx1 == NULL)
3790		return 1;
3791
3792	if (spidx0 == NULL || spidx1 == NULL)
3793		return 0;
3794
3795	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
3796	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
3797	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
3798	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
3799		return 0;
3800
3801	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3802	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3803	 && spidx0->ul_proto != spidx1->ul_proto)
3804		return 0;
3805
3806	switch (spidx0->src.sa.sa_family) {
3807	case AF_INET:
3808		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
3809		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
3810			return 0;
3811		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
3812		    &spidx1->src.sin.sin_addr, spidx0->prefs))
3813			return 0;
3814		break;
3815	case AF_INET6:
3816		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
3817		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
3818			return 0;
3819		/*
3820		 * scope_id check. if sin6_scope_id is 0, we regard it
3821		 * as a wildcard scope, which matches any scope zone ID.
3822		 */
3823		if (spidx0->src.sin6.sin6_scope_id &&
3824		    spidx1->src.sin6.sin6_scope_id &&
3825		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
3826			return 0;
3827		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
3828		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
3829			return 0;
3830		break;
3831	default:
3832		/* XXX */
3833		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
3834			return 0;
3835		break;
3836	}
3837
3838	switch (spidx0->dst.sa.sa_family) {
3839	case AF_INET:
3840		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
3841		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
3842			return 0;
3843		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
3844		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
3845			return 0;
3846		break;
3847	case AF_INET6:
3848		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
3849		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
3850			return 0;
3851		/*
3852		 * scope_id check. if sin6_scope_id is 0, we regard it
3853		 * as a wildcard scope, which matches any scope zone ID.
3854		 */
3855		if (spidx0->src.sin6.sin6_scope_id &&
3856		    spidx1->src.sin6.sin6_scope_id &&
3857		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
3858			return 0;
3859		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
3860		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
3861			return 0;
3862		break;
3863	default:
3864		/* XXX */
3865		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
3866			return 0;
3867		break;
3868	}
3869
3870	/* XXX Do we check other field ?  e.g. flowinfo */
3871
3872	return 1;
3873}
3874
3875/* returns 0 on match */
3876static int
3877key_sockaddrcmp(
3878	const struct sockaddr *sa1,
3879	const struct sockaddr *sa2,
3880	int port)
3881{
3882#ifdef satosin
3883#undef satosin
3884#endif
3885#define satosin(s) ((const struct sockaddr_in *)s)
3886#ifdef satosin6
3887#undef satosin6
3888#endif
3889#define satosin6(s) ((const struct sockaddr_in6 *)s)
3890	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
3891		return 1;
3892
3893	switch (sa1->sa_family) {
3894	case AF_INET:
3895		if (sa1->sa_len != sizeof(struct sockaddr_in))
3896			return 1;
3897		if (satosin(sa1)->sin_addr.s_addr !=
3898		    satosin(sa2)->sin_addr.s_addr) {
3899			return 1;
3900		}
3901		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
3902			return 1;
3903		break;
3904	case AF_INET6:
3905		if (sa1->sa_len != sizeof(struct sockaddr_in6))
3906			return 1;	/*EINVAL*/
3907		if (satosin6(sa1)->sin6_scope_id !=
3908		    satosin6(sa2)->sin6_scope_id) {
3909			return 1;
3910		}
3911		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
3912		    &satosin6(sa2)->sin6_addr)) {
3913			return 1;
3914		}
3915		if (port &&
3916		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
3917			return 1;
3918		}
3919	default:
3920		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
3921			return 1;
3922		break;
3923	}
3924
3925	return 0;
3926#undef satosin
3927#undef satosin6
3928}
3929
3930/*
3931 * compare two buffers with mask.
3932 * IN:
3933 *	addr1: source
3934 *	addr2: object
3935 *	bits:  Number of bits to compare
3936 * OUT:
3937 *	1 : equal
3938 *	0 : not equal
3939 */
3940static int
3941key_bbcmp(const void *a1, const void *a2, u_int bits)
3942{
3943	const unsigned char *p1 = a1;
3944	const unsigned char *p2 = a2;
3945
3946	/* XXX: This could be considerably faster if we compare a word
3947	 * at a time, but it is complicated on LSB Endian machines */
3948
3949	/* Handle null pointers */
3950	if (p1 == NULL || p2 == NULL)
3951		return (p1 == p2);
3952
3953	while (bits >= 8) {
3954		if (*p1++ != *p2++)
3955			return 0;
3956		bits -= 8;
3957	}
3958
3959	if (bits > 0) {
3960		u_int8_t mask = ~((1<<(8-bits))-1);
3961		if ((*p1 & mask) != (*p2 & mask))
3962			return 0;
3963	}
3964	return 1;	/* Match! */
3965}
3966
3967static void
3968key_flush_spd(time_t now)
3969{
3970	static u_int16_t sptree_scangen = 0;
3971	u_int16_t gen = sptree_scangen++;
3972	struct secpolicy *sp;
3973	u_int dir;
3974
3975	/* SPD */
3976	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
3977restart:
3978		SPTREE_LOCK();
3979		LIST_FOREACH(sp, &sptree[dir], chain) {
3980			if (sp->scangen == gen)		/* previously handled */
3981				continue;
3982			sp->scangen = gen;
3983			if (sp->state == IPSEC_SPSTATE_DEAD) {
3984				/* NB: clean entries created by key_spdflush */
3985				SPTREE_UNLOCK();
3986				KEY_FREESP(&sp);
3987				goto restart;
3988			}
3989			if (sp->lifetime == 0 && sp->validtime == 0)
3990				continue;
3991			if ((sp->lifetime && now - sp->created > sp->lifetime)
3992			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
3993				sp->state = IPSEC_SPSTATE_DEAD;
3994				SPTREE_UNLOCK();
3995				key_spdexpire(sp);
3996				KEY_FREESP(&sp);
3997				goto restart;
3998			}
3999		}
4000		SPTREE_UNLOCK();
4001	}
4002}
4003
4004static void
4005key_flush_sad(time_t now)
4006{
4007	struct secashead *sah, *nextsah;
4008	struct secasvar *sav, *nextsav;
4009
4010	/* SAD */
4011	SAHTREE_LOCK();
4012	LIST_FOREACH_SAFE(sah, &sahtree, chain, nextsah) {
4013		/* if sah has been dead, then delete it and process next sah. */
4014		if (sah->state == SADB_SASTATE_DEAD) {
4015			key_delsah(sah);
4016			continue;
4017		}
4018
4019		/* if LARVAL entry doesn't become MATURE, delete it. */
4020		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4021			if (now - sav->created > key_larval_lifetime)
4022				KEY_FREESAV(&sav);
4023		}
4024
4025		/*
4026		 * check MATURE entry to start to send expire message
4027		 * whether or not.
4028		 */
4029		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4030			/* we don't need to check. */
4031			if (sav->lft_s == NULL)
4032				continue;
4033
4034			/* sanity check */
4035			if (sav->lft_c == NULL) {
4036				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4037					"time, why?\n", __func__));
4038				continue;
4039			}
4040
4041			/* check SOFT lifetime */
4042			if (sav->lft_s->sadb_lifetime_addtime != 0 &&
4043			    now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4044				/*
4045				 * check SA to be used whether or not.
4046				 * when SA hasn't been used, delete it.
4047				 */
4048				if (sav->lft_c->sadb_lifetime_usetime == 0) {
4049					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4050					KEY_FREESAV(&sav);
4051				} else {
4052					key_sa_chgstate(sav, SADB_SASTATE_DYING);
4053					/*
4054					 * XXX If we keep to send expire
4055					 * message in the status of
4056					 * DYING. Do remove below code.
4057					 */
4058					key_expire(sav);
4059				}
4060			}
4061			/* check SOFT lifetime by bytes */
4062			/*
4063			 * XXX I don't know the way to delete this SA
4064			 * when new SA is installed.  Caution when it's
4065			 * installed too big lifetime by time.
4066			 */
4067			else if (sav->lft_s->sadb_lifetime_bytes != 0 &&
4068			    sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4069
4070				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4071				/*
4072				 * XXX If we keep to send expire
4073				 * message in the status of
4074				 * DYING. Do remove below code.
4075				 */
4076				key_expire(sav);
4077			}
4078		}
4079
4080		/* check DYING entry to change status to DEAD. */
4081		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4082			/* we don't need to check. */
4083			if (sav->lft_h == NULL)
4084				continue;
4085
4086			/* sanity check */
4087			if (sav->lft_c == NULL) {
4088				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4089					"time, why?\n", __func__));
4090				continue;
4091			}
4092
4093			if (sav->lft_h->sadb_lifetime_addtime != 0 &&
4094			    now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
4095				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4096				KEY_FREESAV(&sav);
4097			}
4098#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4099			else if (sav->lft_s != NULL
4100			      && sav->lft_s->sadb_lifetime_addtime != 0
4101			      && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4102				/*
4103				 * XXX: should be checked to be
4104				 * installed the valid SA.
4105				 */
4106
4107				/*
4108				 * If there is no SA then sending
4109				 * expire message.
4110				 */
4111				key_expire(sav);
4112			}
4113#endif
4114			/* check HARD lifetime by bytes */
4115			else if (sav->lft_h->sadb_lifetime_bytes != 0 &&
4116			    sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4117				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4118				KEY_FREESAV(&sav);
4119			}
4120		}
4121
4122		/* delete entry in DEAD */
4123		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4124			/* sanity check */
4125			if (sav->state != SADB_SASTATE_DEAD) {
4126				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4127					"(queue: %d SA: %d): kill it anyway\n",
4128					__func__,
4129					SADB_SASTATE_DEAD, sav->state));
4130			}
4131			/*
4132			 * do not call key_freesav() here.
4133			 * sav should already be freed, and sav->refcnt
4134			 * shows other references to sav
4135			 * (such as from SPD).
4136			 */
4137		}
4138	}
4139	SAHTREE_UNLOCK();
4140}
4141
4142static void
4143key_flush_acq(time_t now)
4144{
4145	struct secacq *acq, *nextacq;
4146
4147	/* ACQ tree */
4148	ACQ_LOCK();
4149	for (acq = LIST_FIRST(&acqtree); acq != NULL; acq = nextacq) {
4150		nextacq = LIST_NEXT(acq, chain);
4151		if (now - acq->created > key_blockacq_lifetime
4152		 && __LIST_CHAINED(acq)) {
4153			LIST_REMOVE(acq, chain);
4154			free(acq, M_IPSEC_SAQ);
4155		}
4156	}
4157	ACQ_UNLOCK();
4158}
4159
4160static void
4161key_flush_spacq(time_t now)
4162{
4163	struct secspacq *acq, *nextacq;
4164
4165	/* SP ACQ tree */
4166	SPACQ_LOCK();
4167	for (acq = LIST_FIRST(&spacqtree); acq != NULL; acq = nextacq) {
4168		nextacq = LIST_NEXT(acq, chain);
4169		if (now - acq->created > key_blockacq_lifetime
4170		 && __LIST_CHAINED(acq)) {
4171			LIST_REMOVE(acq, chain);
4172			free(acq, M_IPSEC_SAQ);
4173		}
4174	}
4175	SPACQ_UNLOCK();
4176}
4177
4178/*
4179 * time handler.
4180 * scanning SPD and SAD to check status for each entries,
4181 * and do to remove or to expire.
4182 * XXX: year 2038 problem may remain.
4183 */
4184void
4185key_timehandler(void)
4186{
4187	time_t now = time_second;
4188
4189	key_flush_spd(now);
4190	key_flush_sad(now);
4191	key_flush_acq(now);
4192	key_flush_spacq(now);
4193
4194#ifndef IPSEC_DEBUG2
4195	/* do exchange to tick time !! */
4196	(void)timeout((void *)key_timehandler, (void *)0, hz);
4197#endif /* IPSEC_DEBUG2 */
4198}
4199
4200u_long
4201key_random()
4202{
4203	u_long value;
4204
4205	key_randomfill(&value, sizeof(value));
4206	return value;
4207}
4208
4209void
4210key_randomfill(p, l)
4211	void *p;
4212	size_t l;
4213{
4214	size_t n;
4215	u_long v;
4216	static int warn = 1;
4217
4218	n = 0;
4219	n = (size_t)read_random(p, (u_int)l);
4220	/* last resort */
4221	while (n < l) {
4222		v = random();
4223		bcopy(&v, (u_int8_t *)p + n,
4224		    l - n < sizeof(v) ? l - n : sizeof(v));
4225		n += sizeof(v);
4226
4227		if (warn) {
4228			printf("WARNING: pseudo-random number generator "
4229			    "used for IPsec processing\n");
4230			warn = 0;
4231		}
4232	}
4233}
4234
4235/*
4236 * map SADB_SATYPE_* to IPPROTO_*.
4237 * if satype == SADB_SATYPE then satype is mapped to ~0.
4238 * OUT:
4239 *	0: invalid satype.
4240 */
4241static u_int16_t
4242key_satype2proto(satype)
4243	u_int8_t satype;
4244{
4245	switch (satype) {
4246	case SADB_SATYPE_UNSPEC:
4247		return IPSEC_PROTO_ANY;
4248	case SADB_SATYPE_AH:
4249		return IPPROTO_AH;
4250	case SADB_SATYPE_ESP:
4251		return IPPROTO_ESP;
4252	case SADB_X_SATYPE_IPCOMP:
4253		return IPPROTO_IPCOMP;
4254	default:
4255		return 0;
4256	}
4257	/* NOTREACHED */
4258}
4259
4260/*
4261 * map IPPROTO_* to SADB_SATYPE_*
4262 * OUT:
4263 *	0: invalid protocol type.
4264 */
4265static u_int8_t
4266key_proto2satype(proto)
4267	u_int16_t proto;
4268{
4269	switch (proto) {
4270	case IPPROTO_AH:
4271		return SADB_SATYPE_AH;
4272	case IPPROTO_ESP:
4273		return SADB_SATYPE_ESP;
4274	case IPPROTO_IPCOMP:
4275		return SADB_X_SATYPE_IPCOMP;
4276	default:
4277		return 0;
4278	}
4279	/* NOTREACHED */
4280}
4281
4282/* %%% PF_KEY */
4283/*
4284 * SADB_GETSPI processing is to receive
4285 *	<base, (SA2), src address, dst address, (SPI range)>
4286 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4287 * tree with the status of LARVAL, and send
4288 *	<base, SA(*), address(SD)>
4289 * to the IKMPd.
4290 *
4291 * IN:	mhp: pointer to the pointer to each header.
4292 * OUT:	NULL if fail.
4293 *	other if success, return pointer to the message to send.
4294 */
4295static int
4296key_getspi(so, m, mhp)
4297	struct socket *so;
4298	struct mbuf *m;
4299	const struct sadb_msghdr *mhp;
4300{
4301	struct sadb_address *src0, *dst0;
4302	struct secasindex saidx;
4303	struct secashead *newsah;
4304	struct secasvar *newsav;
4305	u_int8_t proto;
4306	u_int32_t spi;
4307	u_int8_t mode;
4308	u_int32_t reqid;
4309	int error;
4310
4311	IPSEC_ASSERT(so != NULL, ("null socket"));
4312	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4313	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4314	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4315
4316	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4317	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4318		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4319			__func__));
4320		return key_senderror(so, m, EINVAL);
4321	}
4322	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4323	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4324		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4325			__func__));
4326		return key_senderror(so, m, EINVAL);
4327	}
4328	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4329		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4330		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4331	} else {
4332		mode = IPSEC_MODE_ANY;
4333		reqid = 0;
4334	}
4335
4336	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4337	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4338
4339	/* map satype to proto */
4340	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4341		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4342			__func__));
4343		return key_senderror(so, m, EINVAL);
4344	}
4345
4346	/* make sure if port number is zero. */
4347	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4348	case AF_INET:
4349		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4350		    sizeof(struct sockaddr_in))
4351			return key_senderror(so, m, EINVAL);
4352		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4353		break;
4354	case AF_INET6:
4355		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4356		    sizeof(struct sockaddr_in6))
4357			return key_senderror(so, m, EINVAL);
4358		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4359		break;
4360	default:
4361		; /*???*/
4362	}
4363	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4364	case AF_INET:
4365		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4366		    sizeof(struct sockaddr_in))
4367			return key_senderror(so, m, EINVAL);
4368		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4369		break;
4370	case AF_INET6:
4371		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4372		    sizeof(struct sockaddr_in6))
4373			return key_senderror(so, m, EINVAL);
4374		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4375		break;
4376	default:
4377		; /*???*/
4378	}
4379
4380	/* XXX boundary check against sa_len */
4381	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4382
4383	/* SPI allocation */
4384	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4385	                       &saidx);
4386	if (spi == 0)
4387		return key_senderror(so, m, EINVAL);
4388
4389	/* get a SA index */
4390	if ((newsah = key_getsah(&saidx)) == NULL) {
4391		/* create a new SA index */
4392		if ((newsah = key_newsah(&saidx)) == NULL) {
4393			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4394			return key_senderror(so, m, ENOBUFS);
4395		}
4396	}
4397
4398	/* get a new SA */
4399	/* XXX rewrite */
4400	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4401	if (newsav == NULL) {
4402		/* XXX don't free new SA index allocated in above. */
4403		return key_senderror(so, m, error);
4404	}
4405
4406	/* set spi */
4407	newsav->spi = htonl(spi);
4408
4409	/* delete the entry in acqtree */
4410	if (mhp->msg->sadb_msg_seq != 0) {
4411		struct secacq *acq;
4412		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4413			/* reset counter in order to deletion by timehandler. */
4414			acq->created = time_second;
4415			acq->count = 0;
4416		}
4417    	}
4418
4419    {
4420	struct mbuf *n, *nn;
4421	struct sadb_sa *m_sa;
4422	struct sadb_msg *newmsg;
4423	int off, len;
4424
4425	/* create new sadb_msg to reply. */
4426	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4427	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4428	if (len > MCLBYTES)
4429		return key_senderror(so, m, ENOBUFS);
4430
4431	MGETHDR(n, M_DONTWAIT, MT_DATA);
4432	if (len > MHLEN) {
4433		MCLGET(n, M_DONTWAIT);
4434		if ((n->m_flags & M_EXT) == 0) {
4435			m_freem(n);
4436			n = NULL;
4437		}
4438	}
4439	if (!n)
4440		return key_senderror(so, m, ENOBUFS);
4441
4442	n->m_len = len;
4443	n->m_next = NULL;
4444	off = 0;
4445
4446	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4447	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4448
4449	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4450	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4451	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4452	m_sa->sadb_sa_spi = htonl(spi);
4453	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4454
4455	IPSEC_ASSERT(off == len,
4456		("length inconsistency (off %u len %u)", off, len));
4457
4458	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4459	    SADB_EXT_ADDRESS_DST);
4460	if (!n->m_next) {
4461		m_freem(n);
4462		return key_senderror(so, m, ENOBUFS);
4463	}
4464
4465	if (n->m_len < sizeof(struct sadb_msg)) {
4466		n = m_pullup(n, sizeof(struct sadb_msg));
4467		if (n == NULL)
4468			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4469	}
4470
4471	n->m_pkthdr.len = 0;
4472	for (nn = n; nn; nn = nn->m_next)
4473		n->m_pkthdr.len += nn->m_len;
4474
4475	newmsg = mtod(n, struct sadb_msg *);
4476	newmsg->sadb_msg_seq = newsav->seq;
4477	newmsg->sadb_msg_errno = 0;
4478	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4479
4480	m_freem(m);
4481	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4482    }
4483}
4484
4485/*
4486 * allocating new SPI
4487 * called by key_getspi().
4488 * OUT:
4489 *	0:	failure.
4490 *	others: success.
4491 */
4492static u_int32_t
4493key_do_getnewspi(spirange, saidx)
4494	struct sadb_spirange *spirange;
4495	struct secasindex *saidx;
4496{
4497	u_int32_t newspi;
4498	u_int32_t min, max;
4499	int count = key_spi_trycnt;
4500
4501	/* set spi range to allocate */
4502	if (spirange != NULL) {
4503		min = spirange->sadb_spirange_min;
4504		max = spirange->sadb_spirange_max;
4505	} else {
4506		min = key_spi_minval;
4507		max = key_spi_maxval;
4508	}
4509	/* IPCOMP needs 2-byte SPI */
4510	if (saidx->proto == IPPROTO_IPCOMP) {
4511		u_int32_t t;
4512		if (min >= 0x10000)
4513			min = 0xffff;
4514		if (max >= 0x10000)
4515			max = 0xffff;
4516		if (min > max) {
4517			t = min; min = max; max = t;
4518		}
4519	}
4520
4521	if (min == max) {
4522		if (key_checkspidup(saidx, min) != NULL) {
4523			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4524				__func__, min));
4525			return 0;
4526		}
4527
4528		count--; /* taking one cost. */
4529		newspi = min;
4530
4531	} else {
4532
4533		/* init SPI */
4534		newspi = 0;
4535
4536		/* when requesting to allocate spi ranged */
4537		while (count--) {
4538			/* generate pseudo-random SPI value ranged. */
4539			newspi = min + (key_random() % (max - min + 1));
4540
4541			if (key_checkspidup(saidx, newspi) == NULL)
4542				break;
4543		}
4544
4545		if (count == 0 || newspi == 0) {
4546			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4547				__func__));
4548			return 0;
4549		}
4550	}
4551
4552	/* statistics */
4553	keystat.getspi_count =
4554		(keystat.getspi_count + key_spi_trycnt - count) / 2;
4555
4556	return newspi;
4557}
4558
4559/*
4560 * SADB_UPDATE processing
4561 * receive
4562 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4563 *       key(AE), (identity(SD),) (sensitivity)>
4564 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4565 * and send
4566 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4567 *       (identity(SD),) (sensitivity)>
4568 * to the ikmpd.
4569 *
4570 * m will always be freed.
4571 */
4572static int
4573key_update(so, m, mhp)
4574	struct socket *so;
4575	struct mbuf *m;
4576	const struct sadb_msghdr *mhp;
4577{
4578	struct sadb_sa *sa0;
4579	struct sadb_address *src0, *dst0;
4580	struct secasindex saidx;
4581	struct secashead *sah;
4582	struct secasvar *sav;
4583	u_int16_t proto;
4584	u_int8_t mode;
4585	u_int32_t reqid;
4586	int error;
4587
4588	IPSEC_ASSERT(so != NULL, ("null socket"));
4589	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4590	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4591	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4592
4593	/* map satype to proto */
4594	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4595		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4596			__func__));
4597		return key_senderror(so, m, EINVAL);
4598	}
4599
4600	if (mhp->ext[SADB_EXT_SA] == NULL ||
4601	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4602	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4603	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4604	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4605	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4606	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4607	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4608	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4609	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4610	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4611		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4612			__func__));
4613		return key_senderror(so, m, EINVAL);
4614	}
4615	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4616	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4617	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4618		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4619			__func__));
4620		return key_senderror(so, m, EINVAL);
4621	}
4622	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4623		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4624		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4625	} else {
4626		mode = IPSEC_MODE_ANY;
4627		reqid = 0;
4628	}
4629	/* XXX boundary checking for other extensions */
4630
4631	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4632	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4633	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4634
4635	/* XXX boundary check against sa_len */
4636	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4637
4638	/* get a SA header */
4639	if ((sah = key_getsah(&saidx)) == NULL) {
4640		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
4641		return key_senderror(so, m, ENOENT);
4642	}
4643
4644	/* set spidx if there */
4645	/* XXX rewrite */
4646	error = key_setident(sah, m, mhp);
4647	if (error)
4648		return key_senderror(so, m, error);
4649
4650	/* find a SA with sequence number. */
4651#ifdef IPSEC_DOSEQCHECK
4652	if (mhp->msg->sadb_msg_seq != 0
4653	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4654		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
4655			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
4656		return key_senderror(so, m, ENOENT);
4657	}
4658#else
4659	SAHTREE_LOCK();
4660	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4661	SAHTREE_UNLOCK();
4662	if (sav == NULL) {
4663		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
4664			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4665		return key_senderror(so, m, EINVAL);
4666	}
4667#endif
4668
4669	/* validity check */
4670	if (sav->sah->saidx.proto != proto) {
4671		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
4672			"(DB=%u param=%u)\n", __func__,
4673			sav->sah->saidx.proto, proto));
4674		return key_senderror(so, m, EINVAL);
4675	}
4676#ifdef IPSEC_DOSEQCHECK
4677	if (sav->spi != sa0->sadb_sa_spi) {
4678		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
4679		    __func__,
4680		    (u_int32_t)ntohl(sav->spi),
4681		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4682		return key_senderror(so, m, EINVAL);
4683	}
4684#endif
4685	if (sav->pid != mhp->msg->sadb_msg_pid) {
4686		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
4687		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
4688		return key_senderror(so, m, EINVAL);
4689	}
4690
4691	/* copy sav values */
4692	error = key_setsaval(sav, m, mhp);
4693	if (error) {
4694		KEY_FREESAV(&sav);
4695		return key_senderror(so, m, error);
4696	}
4697
4698	/* check SA values to be mature. */
4699	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4700		KEY_FREESAV(&sav);
4701		return key_senderror(so, m, 0);
4702	}
4703
4704    {
4705	struct mbuf *n;
4706
4707	/* set msg buf from mhp */
4708	n = key_getmsgbuf_x1(m, mhp);
4709	if (n == NULL) {
4710		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4711		return key_senderror(so, m, ENOBUFS);
4712	}
4713
4714	m_freem(m);
4715	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4716    }
4717}
4718
4719/*
4720 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4721 * only called by key_update().
4722 * OUT:
4723 *	NULL	: not found
4724 *	others	: found, pointer to a SA.
4725 */
4726#ifdef IPSEC_DOSEQCHECK
4727static struct secasvar *
4728key_getsavbyseq(sah, seq)
4729	struct secashead *sah;
4730	u_int32_t seq;
4731{
4732	struct secasvar *sav;
4733	u_int state;
4734
4735	state = SADB_SASTATE_LARVAL;
4736
4737	/* search SAD with sequence number ? */
4738	LIST_FOREACH(sav, &sah->savtree[state], chain) {
4739
4740		KEY_CHKSASTATE(state, sav->state, __func__);
4741
4742		if (sav->seq == seq) {
4743			SA_ADDREF(sav);
4744			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4745				printf("DP %s cause refcnt++:%d SA:%p\n",
4746					__func__, sav->refcnt, sav));
4747			return sav;
4748		}
4749	}
4750
4751	return NULL;
4752}
4753#endif
4754
4755/*
4756 * SADB_ADD processing
4757 * add an entry to SA database, when received
4758 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4759 *       key(AE), (identity(SD),) (sensitivity)>
4760 * from the ikmpd,
4761 * and send
4762 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4763 *       (identity(SD),) (sensitivity)>
4764 * to the ikmpd.
4765 *
4766 * IGNORE identity and sensitivity messages.
4767 *
4768 * m will always be freed.
4769 */
4770static int
4771key_add(so, m, mhp)
4772	struct socket *so;
4773	struct mbuf *m;
4774	const struct sadb_msghdr *mhp;
4775{
4776	struct sadb_sa *sa0;
4777	struct sadb_address *src0, *dst0;
4778	struct secasindex saidx;
4779	struct secashead *newsah;
4780	struct secasvar *newsav;
4781	u_int16_t proto;
4782	u_int8_t mode;
4783	u_int32_t reqid;
4784	int error;
4785
4786	IPSEC_ASSERT(so != NULL, ("null socket"));
4787	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4788	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4789	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4790
4791	/* map satype to proto */
4792	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4793		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4794			__func__));
4795		return key_senderror(so, m, EINVAL);
4796	}
4797
4798	if (mhp->ext[SADB_EXT_SA] == NULL ||
4799	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4800	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4801	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4802	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4803	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4804	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4805	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4806	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4807	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4808	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4809		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4810			__func__));
4811		return key_senderror(so, m, EINVAL);
4812	}
4813	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4814	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4815	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4816		/* XXX need more */
4817		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4818			__func__));
4819		return key_senderror(so, m, EINVAL);
4820	}
4821	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4822		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4823		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4824	} else {
4825		mode = IPSEC_MODE_ANY;
4826		reqid = 0;
4827	}
4828
4829	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4830	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4831	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4832
4833	/* XXX boundary check against sa_len */
4834	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4835
4836	/* get a SA header */
4837	if ((newsah = key_getsah(&saidx)) == NULL) {
4838		/* create a new SA header */
4839		if ((newsah = key_newsah(&saidx)) == NULL) {
4840			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4841			return key_senderror(so, m, ENOBUFS);
4842		}
4843	}
4844
4845	/* set spidx if there */
4846	/* XXX rewrite */
4847	error = key_setident(newsah, m, mhp);
4848	if (error) {
4849		return key_senderror(so, m, error);
4850	}
4851
4852	/* create new SA entry. */
4853	/* We can create new SA only if SPI is differenct. */
4854	SAHTREE_LOCK();
4855	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
4856	SAHTREE_UNLOCK();
4857	if (newsav != NULL) {
4858		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
4859		return key_senderror(so, m, EEXIST);
4860	}
4861	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4862	if (newsav == NULL) {
4863		return key_senderror(so, m, error);
4864	}
4865
4866	/* check SA values to be mature. */
4867	if ((error = key_mature(newsav)) != 0) {
4868		KEY_FREESAV(&newsav);
4869		return key_senderror(so, m, error);
4870	}
4871
4872	/*
4873	 * don't call key_freesav() here, as we would like to keep the SA
4874	 * in the database on success.
4875	 */
4876
4877    {
4878	struct mbuf *n;
4879
4880	/* set msg buf from mhp */
4881	n = key_getmsgbuf_x1(m, mhp);
4882	if (n == NULL) {
4883		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4884		return key_senderror(so, m, ENOBUFS);
4885	}
4886
4887	m_freem(m);
4888	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4889    }
4890}
4891
4892/* m is retained */
4893static int
4894key_setident(sah, m, mhp)
4895	struct secashead *sah;
4896	struct mbuf *m;
4897	const struct sadb_msghdr *mhp;
4898{
4899	const struct sadb_ident *idsrc, *iddst;
4900	int idsrclen, iddstlen;
4901
4902	IPSEC_ASSERT(sah != NULL, ("null secashead"));
4903	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4904	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4905	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4906
4907	/* don't make buffer if not there */
4908	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
4909	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4910		sah->idents = NULL;
4911		sah->identd = NULL;
4912		return 0;
4913	}
4914
4915	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
4916	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4917		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
4918		return EINVAL;
4919	}
4920
4921	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
4922	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
4923	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
4924	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
4925
4926	/* validity check */
4927	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
4928		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
4929		return EINVAL;
4930	}
4931
4932	switch (idsrc->sadb_ident_type) {
4933	case SADB_IDENTTYPE_PREFIX:
4934	case SADB_IDENTTYPE_FQDN:
4935	case SADB_IDENTTYPE_USERFQDN:
4936	default:
4937		/* XXX do nothing */
4938		sah->idents = NULL;
4939		sah->identd = NULL;
4940	 	return 0;
4941	}
4942
4943	/* make structure */
4944	sah->idents = malloc(idsrclen, M_IPSEC_MISC, M_NOWAIT);
4945	if (sah->idents == NULL) {
4946		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4947		return ENOBUFS;
4948	}
4949	sah->identd = malloc(iddstlen, M_IPSEC_MISC, M_NOWAIT);
4950	if (sah->identd == NULL) {
4951		free(sah->idents, M_IPSEC_MISC);
4952		sah->idents = NULL;
4953		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4954		return ENOBUFS;
4955	}
4956	bcopy(idsrc, sah->idents, idsrclen);
4957	bcopy(iddst, sah->identd, iddstlen);
4958
4959	return 0;
4960}
4961
4962/*
4963 * m will not be freed on return.
4964 * it is caller's responsibility to free the result.
4965 */
4966static struct mbuf *
4967key_getmsgbuf_x1(m, mhp)
4968	struct mbuf *m;
4969	const struct sadb_msghdr *mhp;
4970{
4971	struct mbuf *n;
4972
4973	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4974	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4975	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4976
4977	/* create new sadb_msg to reply. */
4978	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
4979	    SADB_EXT_SA, SADB_X_EXT_SA2,
4980	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
4981	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
4982	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
4983	if (!n)
4984		return NULL;
4985
4986	if (n->m_len < sizeof(struct sadb_msg)) {
4987		n = m_pullup(n, sizeof(struct sadb_msg));
4988		if (n == NULL)
4989			return NULL;
4990	}
4991	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
4992	mtod(n, struct sadb_msg *)->sadb_msg_len =
4993	    PFKEY_UNIT64(n->m_pkthdr.len);
4994
4995	return n;
4996}
4997
4998static int key_delete_all __P((struct socket *, struct mbuf *,
4999	const struct sadb_msghdr *, u_int16_t));
5000
5001/*
5002 * SADB_DELETE processing
5003 * receive
5004 *   <base, SA(*), address(SD)>
5005 * from the ikmpd, and set SADB_SASTATE_DEAD,
5006 * and send,
5007 *   <base, SA(*), address(SD)>
5008 * to the ikmpd.
5009 *
5010 * m will always be freed.
5011 */
5012static int
5013key_delete(so, m, mhp)
5014	struct socket *so;
5015	struct mbuf *m;
5016	const struct sadb_msghdr *mhp;
5017{
5018	struct sadb_sa *sa0;
5019	struct sadb_address *src0, *dst0;
5020	struct secasindex saidx;
5021	struct secashead *sah;
5022	struct secasvar *sav = NULL;
5023	u_int16_t proto;
5024
5025	IPSEC_ASSERT(so != NULL, ("null socket"));
5026	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5027	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5028	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5029
5030	/* map satype to proto */
5031	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5032		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5033			__func__));
5034		return key_senderror(so, m, EINVAL);
5035	}
5036
5037	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5038	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5039		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5040			__func__));
5041		return key_senderror(so, m, EINVAL);
5042	}
5043
5044	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5045	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5046		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5047			__func__));
5048		return key_senderror(so, m, EINVAL);
5049	}
5050
5051	if (mhp->ext[SADB_EXT_SA] == NULL) {
5052		/*
5053		 * Caller wants us to delete all non-LARVAL SAs
5054		 * that match the src/dst.  This is used during
5055		 * IKE INITIAL-CONTACT.
5056		 */
5057		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5058		return key_delete_all(so, m, mhp, proto);
5059	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5060		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5061			__func__));
5062		return key_senderror(so, m, EINVAL);
5063	}
5064
5065	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5066	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5067	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5068
5069	/* XXX boundary check against sa_len */
5070	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5071
5072	/* get a SA header */
5073	SAHTREE_LOCK();
5074	LIST_FOREACH(sah, &sahtree, chain) {
5075		if (sah->state == SADB_SASTATE_DEAD)
5076			continue;
5077		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5078			continue;
5079
5080		/* get a SA with SPI. */
5081		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5082		if (sav)
5083			break;
5084	}
5085	if (sah == NULL) {
5086		SAHTREE_UNLOCK();
5087		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5088		return key_senderror(so, m, ENOENT);
5089	}
5090
5091	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5092	SAHTREE_UNLOCK();
5093	KEY_FREESAV(&sav);
5094
5095    {
5096	struct mbuf *n;
5097	struct sadb_msg *newmsg;
5098
5099	/* create new sadb_msg to reply. */
5100	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5101	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5102	if (!n)
5103		return key_senderror(so, m, ENOBUFS);
5104
5105	if (n->m_len < sizeof(struct sadb_msg)) {
5106		n = m_pullup(n, sizeof(struct sadb_msg));
5107		if (n == NULL)
5108			return key_senderror(so, m, ENOBUFS);
5109	}
5110	newmsg = mtod(n, struct sadb_msg *);
5111	newmsg->sadb_msg_errno = 0;
5112	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5113
5114	m_freem(m);
5115	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5116    }
5117}
5118
5119/*
5120 * delete all SAs for src/dst.  Called from key_delete().
5121 */
5122static int
5123key_delete_all(so, m, mhp, proto)
5124	struct socket *so;
5125	struct mbuf *m;
5126	const struct sadb_msghdr *mhp;
5127	u_int16_t proto;
5128{
5129	struct sadb_address *src0, *dst0;
5130	struct secasindex saidx;
5131	struct secashead *sah;
5132	struct secasvar *sav, *nextsav;
5133	u_int stateidx, state;
5134
5135	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5136	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5137
5138	/* XXX boundary check against sa_len */
5139	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5140
5141	SAHTREE_LOCK();
5142	LIST_FOREACH(sah, &sahtree, chain) {
5143		if (sah->state == SADB_SASTATE_DEAD)
5144			continue;
5145		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5146			continue;
5147
5148		/* Delete all non-LARVAL SAs. */
5149		for (stateidx = 0;
5150		     stateidx < _ARRAYLEN(saorder_state_alive);
5151		     stateidx++) {
5152			state = saorder_state_alive[stateidx];
5153			if (state == SADB_SASTATE_LARVAL)
5154				continue;
5155			for (sav = LIST_FIRST(&sah->savtree[state]);
5156			     sav != NULL; sav = nextsav) {
5157				nextsav = LIST_NEXT(sav, chain);
5158				/* sanity check */
5159				if (sav->state != state) {
5160					ipseclog((LOG_DEBUG, "%s: invalid "
5161						"sav->state (queue %d SA %d)\n",
5162						__func__, state, sav->state));
5163					continue;
5164				}
5165
5166				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5167				KEY_FREESAV(&sav);
5168			}
5169		}
5170	}
5171	SAHTREE_UNLOCK();
5172    {
5173	struct mbuf *n;
5174	struct sadb_msg *newmsg;
5175
5176	/* create new sadb_msg to reply. */
5177	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5178	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5179	if (!n)
5180		return key_senderror(so, m, ENOBUFS);
5181
5182	if (n->m_len < sizeof(struct sadb_msg)) {
5183		n = m_pullup(n, sizeof(struct sadb_msg));
5184		if (n == NULL)
5185			return key_senderror(so, m, ENOBUFS);
5186	}
5187	newmsg = mtod(n, struct sadb_msg *);
5188	newmsg->sadb_msg_errno = 0;
5189	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5190
5191	m_freem(m);
5192	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5193    }
5194}
5195
5196/*
5197 * SADB_GET processing
5198 * receive
5199 *   <base, SA(*), address(SD)>
5200 * from the ikmpd, and get a SP and a SA to respond,
5201 * and send,
5202 *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5203 *       (identity(SD),) (sensitivity)>
5204 * to the ikmpd.
5205 *
5206 * m will always be freed.
5207 */
5208static int
5209key_get(so, m, mhp)
5210	struct socket *so;
5211	struct mbuf *m;
5212	const struct sadb_msghdr *mhp;
5213{
5214	struct sadb_sa *sa0;
5215	struct sadb_address *src0, *dst0;
5216	struct secasindex saidx;
5217	struct secashead *sah;
5218	struct secasvar *sav = NULL;
5219	u_int16_t proto;
5220
5221	IPSEC_ASSERT(so != NULL, ("null socket"));
5222	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5223	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5224	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5225
5226	/* map satype to proto */
5227	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5228		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5229			__func__));
5230		return key_senderror(so, m, EINVAL);
5231	}
5232
5233	if (mhp->ext[SADB_EXT_SA] == NULL ||
5234	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5235	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5236		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5237			__func__));
5238		return key_senderror(so, m, EINVAL);
5239	}
5240	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5241	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5242	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5243		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5244			__func__));
5245		return key_senderror(so, m, EINVAL);
5246	}
5247
5248	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5249	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5250	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5251
5252	/* XXX boundary check against sa_len */
5253	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5254
5255	/* get a SA header */
5256	SAHTREE_LOCK();
5257	LIST_FOREACH(sah, &sahtree, chain) {
5258		if (sah->state == SADB_SASTATE_DEAD)
5259			continue;
5260		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5261			continue;
5262
5263		/* get a SA with SPI. */
5264		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5265		if (sav)
5266			break;
5267	}
5268	SAHTREE_UNLOCK();
5269	if (sah == NULL) {
5270		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5271		return key_senderror(so, m, ENOENT);
5272	}
5273
5274    {
5275	struct mbuf *n;
5276	u_int8_t satype;
5277
5278	/* map proto to satype */
5279	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5280		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5281			__func__));
5282		return key_senderror(so, m, EINVAL);
5283	}
5284
5285	/* create new sadb_msg to reply. */
5286	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5287	    mhp->msg->sadb_msg_pid);
5288	if (!n)
5289		return key_senderror(so, m, ENOBUFS);
5290
5291	m_freem(m);
5292	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5293    }
5294}
5295
5296/* XXX make it sysctl-configurable? */
5297static void
5298key_getcomb_setlifetime(comb)
5299	struct sadb_comb *comb;
5300{
5301
5302	comb->sadb_comb_soft_allocations = 1;
5303	comb->sadb_comb_hard_allocations = 1;
5304	comb->sadb_comb_soft_bytes = 0;
5305	comb->sadb_comb_hard_bytes = 0;
5306	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5307	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5308	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5309	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5310}
5311
5312/*
5313 * XXX reorder combinations by preference
5314 * XXX no idea if the user wants ESP authentication or not
5315 */
5316static struct mbuf *
5317key_getcomb_esp()
5318{
5319	struct sadb_comb *comb;
5320	struct enc_xform *algo;
5321	struct mbuf *result = NULL, *m, *n;
5322	int encmin;
5323	int i, off, o;
5324	int totlen;
5325	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5326
5327	m = NULL;
5328	for (i = 1; i <= SADB_EALG_MAX; i++) {
5329		algo = esp_algorithm_lookup(i);
5330		if (algo == NULL)
5331			continue;
5332
5333		/* discard algorithms with key size smaller than system min */
5334		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
5335			continue;
5336		if (_BITS(algo->minkey) < ipsec_esp_keymin)
5337			encmin = ipsec_esp_keymin;
5338		else
5339			encmin = _BITS(algo->minkey);
5340
5341		if (ipsec_esp_auth)
5342			m = key_getcomb_ah();
5343		else {
5344			IPSEC_ASSERT(l <= MLEN,
5345				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5346			MGET(m, M_DONTWAIT, MT_DATA);
5347			if (m) {
5348				M_ALIGN(m, l);
5349				m->m_len = l;
5350				m->m_next = NULL;
5351				bzero(mtod(m, caddr_t), m->m_len);
5352			}
5353		}
5354		if (!m)
5355			goto fail;
5356
5357		totlen = 0;
5358		for (n = m; n; n = n->m_next)
5359			totlen += n->m_len;
5360		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
5361
5362		for (off = 0; off < totlen; off += l) {
5363			n = m_pulldown(m, off, l, &o);
5364			if (!n) {
5365				/* m is already freed */
5366				goto fail;
5367			}
5368			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5369			bzero(comb, sizeof(*comb));
5370			key_getcomb_setlifetime(comb);
5371			comb->sadb_comb_encrypt = i;
5372			comb->sadb_comb_encrypt_minbits = encmin;
5373			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5374		}
5375
5376		if (!result)
5377			result = m;
5378		else
5379			m_cat(result, m);
5380	}
5381
5382	return result;
5383
5384 fail:
5385	if (result)
5386		m_freem(result);
5387	return NULL;
5388}
5389
5390static void
5391key_getsizes_ah(
5392	const struct auth_hash *ah,
5393	int alg,
5394	u_int16_t* min,
5395	u_int16_t* max)
5396{
5397	*min = *max = ah->keysize;
5398	if (ah->keysize == 0) {
5399		/*
5400		 * Transform takes arbitrary key size but algorithm
5401		 * key size is restricted.  Enforce this here.
5402		 */
5403		switch (alg) {
5404		case SADB_X_AALG_MD5:	*min = *max = 16; break;
5405		case SADB_X_AALG_SHA:	*min = *max = 20; break;
5406		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
5407		default:
5408			DPRINTF(("%s: unknown AH algorithm %u\n",
5409				__func__, alg));
5410			break;
5411		}
5412	}
5413}
5414
5415/*
5416 * XXX reorder combinations by preference
5417 */
5418static struct mbuf *
5419key_getcomb_ah()
5420{
5421	struct sadb_comb *comb;
5422	struct auth_hash *algo;
5423	struct mbuf *m;
5424	u_int16_t minkeysize, maxkeysize;
5425	int i;
5426	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5427
5428	m = NULL;
5429	for (i = 1; i <= SADB_AALG_MAX; i++) {
5430#if 1
5431		/* we prefer HMAC algorithms, not old algorithms */
5432		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5433			continue;
5434#endif
5435		algo = ah_algorithm_lookup(i);
5436		if (!algo)
5437			continue;
5438		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5439		/* discard algorithms with key size smaller than system min */
5440		if (_BITS(minkeysize) < ipsec_ah_keymin)
5441			continue;
5442
5443		if (!m) {
5444			IPSEC_ASSERT(l <= MLEN,
5445				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5446			MGET(m, M_DONTWAIT, MT_DATA);
5447			if (m) {
5448				M_ALIGN(m, l);
5449				m->m_len = l;
5450				m->m_next = NULL;
5451			}
5452		} else
5453			M_PREPEND(m, l, M_DONTWAIT);
5454		if (!m)
5455			return NULL;
5456
5457		comb = mtod(m, struct sadb_comb *);
5458		bzero(comb, sizeof(*comb));
5459		key_getcomb_setlifetime(comb);
5460		comb->sadb_comb_auth = i;
5461		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5462		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5463	}
5464
5465	return m;
5466}
5467
5468/*
5469 * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5470 * XXX reorder combinations by preference
5471 */
5472static struct mbuf *
5473key_getcomb_ipcomp()
5474{
5475	struct sadb_comb *comb;
5476	struct comp_algo *algo;
5477	struct mbuf *m;
5478	int i;
5479	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5480
5481	m = NULL;
5482	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5483		algo = ipcomp_algorithm_lookup(i);
5484		if (!algo)
5485			continue;
5486
5487		if (!m) {
5488			IPSEC_ASSERT(l <= MLEN,
5489				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5490			MGET(m, M_DONTWAIT, MT_DATA);
5491			if (m) {
5492				M_ALIGN(m, l);
5493				m->m_len = l;
5494				m->m_next = NULL;
5495			}
5496		} else
5497			M_PREPEND(m, l, M_DONTWAIT);
5498		if (!m)
5499			return NULL;
5500
5501		comb = mtod(m, struct sadb_comb *);
5502		bzero(comb, sizeof(*comb));
5503		key_getcomb_setlifetime(comb);
5504		comb->sadb_comb_encrypt = i;
5505		/* what should we set into sadb_comb_*_{min,max}bits? */
5506	}
5507
5508	return m;
5509}
5510
5511/*
5512 * XXX no way to pass mode (transport/tunnel) to userland
5513 * XXX replay checking?
5514 * XXX sysctl interface to ipsec_{ah,esp}_keymin
5515 */
5516static struct mbuf *
5517key_getprop(saidx)
5518	const struct secasindex *saidx;
5519{
5520	struct sadb_prop *prop;
5521	struct mbuf *m, *n;
5522	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5523	int totlen;
5524
5525	switch (saidx->proto)  {
5526	case IPPROTO_ESP:
5527		m = key_getcomb_esp();
5528		break;
5529	case IPPROTO_AH:
5530		m = key_getcomb_ah();
5531		break;
5532	case IPPROTO_IPCOMP:
5533		m = key_getcomb_ipcomp();
5534		break;
5535	default:
5536		return NULL;
5537	}
5538
5539	if (!m)
5540		return NULL;
5541	M_PREPEND(m, l, M_DONTWAIT);
5542	if (!m)
5543		return NULL;
5544
5545	totlen = 0;
5546	for (n = m; n; n = n->m_next)
5547		totlen += n->m_len;
5548
5549	prop = mtod(m, struct sadb_prop *);
5550	bzero(prop, sizeof(*prop));
5551	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5552	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5553	prop->sadb_prop_replay = 32;	/* XXX */
5554
5555	return m;
5556}
5557
5558/*
5559 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5560 * send
5561 *   <base, SA, address(SD), (address(P)), x_policy,
5562 *       (identity(SD),) (sensitivity,) proposal>
5563 * to KMD, and expect to receive
5564 *   <base> with SADB_ACQUIRE if error occured,
5565 * or
5566 *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5567 * from KMD by PF_KEY.
5568 *
5569 * XXX x_policy is outside of RFC2367 (KAME extension).
5570 * XXX sensitivity is not supported.
5571 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5572 * see comment for key_getcomb_ipcomp().
5573 *
5574 * OUT:
5575 *    0     : succeed
5576 *    others: error number
5577 */
5578static int
5579key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5580{
5581	struct mbuf *result = NULL, *m;
5582	struct secacq *newacq;
5583	u_int8_t satype;
5584	int error = -1;
5585	u_int32_t seq;
5586
5587	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
5588	satype = key_proto2satype(saidx->proto);
5589	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
5590
5591	/*
5592	 * We never do anything about acquirng SA.  There is anather
5593	 * solution that kernel blocks to send SADB_ACQUIRE message until
5594	 * getting something message from IKEd.  In later case, to be
5595	 * managed with ACQUIRING list.
5596	 */
5597	/* Get an entry to check whether sending message or not. */
5598	if ((newacq = key_getacq(saidx)) != NULL) {
5599		if (key_blockacq_count < newacq->count) {
5600			/* reset counter and do send message. */
5601			newacq->count = 0;
5602		} else {
5603			/* increment counter and do nothing. */
5604			newacq->count++;
5605			return 0;
5606		}
5607	} else {
5608		/* make new entry for blocking to send SADB_ACQUIRE. */
5609		if ((newacq = key_newacq(saidx)) == NULL)
5610			return ENOBUFS;
5611	}
5612
5613
5614	seq = newacq->seq;
5615	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5616	if (!m) {
5617		error = ENOBUFS;
5618		goto fail;
5619	}
5620	result = m;
5621
5622	/* set sadb_address for saidx's. */
5623	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5624	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5625	if (!m) {
5626		error = ENOBUFS;
5627		goto fail;
5628	}
5629	m_cat(result, m);
5630
5631	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5632	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5633	if (!m) {
5634		error = ENOBUFS;
5635		goto fail;
5636	}
5637	m_cat(result, m);
5638
5639	/* XXX proxy address (optional) */
5640
5641	/* set sadb_x_policy */
5642	if (sp) {
5643		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5644		if (!m) {
5645			error = ENOBUFS;
5646			goto fail;
5647		}
5648		m_cat(result, m);
5649	}
5650
5651	/* XXX identity (optional) */
5652#if 0
5653	if (idexttype && fqdn) {
5654		/* create identity extension (FQDN) */
5655		struct sadb_ident *id;
5656		int fqdnlen;
5657
5658		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
5659		id = (struct sadb_ident *)p;
5660		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5661		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5662		id->sadb_ident_exttype = idexttype;
5663		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5664		bcopy(fqdn, id + 1, fqdnlen);
5665		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5666	}
5667
5668	if (idexttype) {
5669		/* create identity extension (USERFQDN) */
5670		struct sadb_ident *id;
5671		int userfqdnlen;
5672
5673		if (userfqdn) {
5674			/* +1 for terminating-NUL */
5675			userfqdnlen = strlen(userfqdn) + 1;
5676		} else
5677			userfqdnlen = 0;
5678		id = (struct sadb_ident *)p;
5679		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5680		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5681		id->sadb_ident_exttype = idexttype;
5682		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5683		/* XXX is it correct? */
5684		if (curproc && curproc->p_cred)
5685			id->sadb_ident_id = curproc->p_cred->p_ruid;
5686		if (userfqdn && userfqdnlen)
5687			bcopy(userfqdn, id + 1, userfqdnlen);
5688		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5689	}
5690#endif
5691
5692	/* XXX sensitivity (optional) */
5693
5694	/* create proposal/combination extension */
5695	m = key_getprop(saidx);
5696#if 0
5697	/*
5698	 * spec conformant: always attach proposal/combination extension,
5699	 * the problem is that we have no way to attach it for ipcomp,
5700	 * due to the way sadb_comb is declared in RFC2367.
5701	 */
5702	if (!m) {
5703		error = ENOBUFS;
5704		goto fail;
5705	}
5706	m_cat(result, m);
5707#else
5708	/*
5709	 * outside of spec; make proposal/combination extension optional.
5710	 */
5711	if (m)
5712		m_cat(result, m);
5713#endif
5714
5715	if ((result->m_flags & M_PKTHDR) == 0) {
5716		error = EINVAL;
5717		goto fail;
5718	}
5719
5720	if (result->m_len < sizeof(struct sadb_msg)) {
5721		result = m_pullup(result, sizeof(struct sadb_msg));
5722		if (result == NULL) {
5723			error = ENOBUFS;
5724			goto fail;
5725		}
5726	}
5727
5728	result->m_pkthdr.len = 0;
5729	for (m = result; m; m = m->m_next)
5730		result->m_pkthdr.len += m->m_len;
5731
5732	mtod(result, struct sadb_msg *)->sadb_msg_len =
5733	    PFKEY_UNIT64(result->m_pkthdr.len);
5734
5735	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5736
5737 fail:
5738	if (result)
5739		m_freem(result);
5740	return error;
5741}
5742
5743static struct secacq *
5744key_newacq(const struct secasindex *saidx)
5745{
5746	struct secacq *newacq;
5747
5748	/* get new entry */
5749	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5750	if (newacq == NULL) {
5751		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5752		return NULL;
5753	}
5754
5755	/* copy secindex */
5756	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5757	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
5758	newacq->created = time_second;
5759	newacq->count = 0;
5760
5761	/* add to acqtree */
5762	ACQ_LOCK();
5763	LIST_INSERT_HEAD(&acqtree, newacq, chain);
5764	ACQ_UNLOCK();
5765
5766	return newacq;
5767}
5768
5769static struct secacq *
5770key_getacq(const struct secasindex *saidx)
5771{
5772	struct secacq *acq;
5773
5774	ACQ_LOCK();
5775	LIST_FOREACH(acq, &acqtree, chain) {
5776		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5777			break;
5778	}
5779	ACQ_UNLOCK();
5780
5781	return acq;
5782}
5783
5784static struct secacq *
5785key_getacqbyseq(seq)
5786	u_int32_t seq;
5787{
5788	struct secacq *acq;
5789
5790	ACQ_LOCK();
5791	LIST_FOREACH(acq, &acqtree, chain) {
5792		if (acq->seq == seq)
5793			break;
5794	}
5795	ACQ_UNLOCK();
5796
5797	return acq;
5798}
5799
5800static struct secspacq *
5801key_newspacq(spidx)
5802	struct secpolicyindex *spidx;
5803{
5804	struct secspacq *acq;
5805
5806	/* get new entry */
5807	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5808	if (acq == NULL) {
5809		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5810		return NULL;
5811	}
5812
5813	/* copy secindex */
5814	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5815	acq->created = time_second;
5816	acq->count = 0;
5817
5818	/* add to spacqtree */
5819	SPACQ_LOCK();
5820	LIST_INSERT_HEAD(&spacqtree, acq, chain);
5821	SPACQ_UNLOCK();
5822
5823	return acq;
5824}
5825
5826static struct secspacq *
5827key_getspacq(spidx)
5828	struct secpolicyindex *spidx;
5829{
5830	struct secspacq *acq;
5831
5832	SPACQ_LOCK();
5833	LIST_FOREACH(acq, &spacqtree, chain) {
5834		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
5835			/* NB: return holding spacq_lock */
5836			return acq;
5837		}
5838	}
5839	SPACQ_UNLOCK();
5840
5841	return NULL;
5842}
5843
5844/*
5845 * SADB_ACQUIRE processing,
5846 * in first situation, is receiving
5847 *   <base>
5848 * from the ikmpd, and clear sequence of its secasvar entry.
5849 *
5850 * In second situation, is receiving
5851 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5852 * from a user land process, and return
5853 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5854 * to the socket.
5855 *
5856 * m will always be freed.
5857 */
5858static int
5859key_acquire2(so, m, mhp)
5860	struct socket *so;
5861	struct mbuf *m;
5862	const struct sadb_msghdr *mhp;
5863{
5864	const struct sadb_address *src0, *dst0;
5865	struct secasindex saidx;
5866	struct secashead *sah;
5867	u_int16_t proto;
5868	int error;
5869
5870	IPSEC_ASSERT(so != NULL, ("null socket"));
5871	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5872	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5873	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5874
5875	/*
5876	 * Error message from KMd.
5877	 * We assume that if error was occured in IKEd, the length of PFKEY
5878	 * message is equal to the size of sadb_msg structure.
5879	 * We do not raise error even if error occured in this function.
5880	 */
5881	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
5882		struct secacq *acq;
5883
5884		/* check sequence number */
5885		if (mhp->msg->sadb_msg_seq == 0) {
5886			ipseclog((LOG_DEBUG, "%s: must specify sequence "
5887				"number.\n", __func__));
5888			m_freem(m);
5889			return 0;
5890		}
5891
5892		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
5893			/*
5894			 * the specified larval SA is already gone, or we got
5895			 * a bogus sequence number.  we can silently ignore it.
5896			 */
5897			m_freem(m);
5898			return 0;
5899		}
5900
5901		/* reset acq counter in order to deletion by timehander. */
5902		acq->created = time_second;
5903		acq->count = 0;
5904		m_freem(m);
5905		return 0;
5906	}
5907
5908	/*
5909	 * This message is from user land.
5910	 */
5911
5912	/* map satype to proto */
5913	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5914		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5915			__func__));
5916		return key_senderror(so, m, EINVAL);
5917	}
5918
5919	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5920	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5921	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
5922		/* error */
5923		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5924			__func__));
5925		return key_senderror(so, m, EINVAL);
5926	}
5927	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5928	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
5929	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
5930		/* error */
5931		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5932			__func__));
5933		return key_senderror(so, m, EINVAL);
5934	}
5935
5936	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5937	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5938
5939	/* XXX boundary check against sa_len */
5940	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5941
5942	/* get a SA index */
5943	SAHTREE_LOCK();
5944	LIST_FOREACH(sah, &sahtree, chain) {
5945		if (sah->state == SADB_SASTATE_DEAD)
5946			continue;
5947		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
5948			break;
5949	}
5950	SAHTREE_UNLOCK();
5951	if (sah != NULL) {
5952		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
5953		return key_senderror(so, m, EEXIST);
5954	}
5955
5956	error = key_acquire(&saidx, NULL);
5957	if (error != 0) {
5958		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
5959			__func__, mhp->msg->sadb_msg_errno));
5960		return key_senderror(so, m, error);
5961	}
5962
5963	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
5964}
5965
5966/*
5967 * SADB_REGISTER processing.
5968 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
5969 * receive
5970 *   <base>
5971 * from the ikmpd, and register a socket to send PF_KEY messages,
5972 * and send
5973 *   <base, supported>
5974 * to KMD by PF_KEY.
5975 * If socket is detached, must free from regnode.
5976 *
5977 * m will always be freed.
5978 */
5979static int
5980key_register(so, m, mhp)
5981	struct socket *so;
5982	struct mbuf *m;
5983	const struct sadb_msghdr *mhp;
5984{
5985	struct secreg *reg, *newreg = 0;
5986
5987	IPSEC_ASSERT(so != NULL, ("null socket"));
5988	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5989	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5990	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5991
5992	/* check for invalid register message */
5993	if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
5994		return key_senderror(so, m, EINVAL);
5995
5996	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
5997	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
5998		goto setmsg;
5999
6000	/* check whether existing or not */
6001	REGTREE_LOCK();
6002	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
6003		if (reg->so == so) {
6004			REGTREE_UNLOCK();
6005			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6006				__func__));
6007			return key_senderror(so, m, EEXIST);
6008		}
6009	}
6010
6011	/* create regnode */
6012	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6013	if (newreg == NULL) {
6014		REGTREE_UNLOCK();
6015		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6016		return key_senderror(so, m, ENOBUFS);
6017	}
6018
6019	newreg->so = so;
6020	((struct keycb *)sotorawcb(so))->kp_registered++;
6021
6022	/* add regnode to regtree. */
6023	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6024	REGTREE_UNLOCK();
6025
6026  setmsg:
6027    {
6028	struct mbuf *n;
6029	struct sadb_msg *newmsg;
6030	struct sadb_supported *sup;
6031	u_int len, alen, elen;
6032	int off;
6033	int i;
6034	struct sadb_alg *alg;
6035
6036	/* create new sadb_msg to reply. */
6037	alen = 0;
6038	for (i = 1; i <= SADB_AALG_MAX; i++) {
6039		if (ah_algorithm_lookup(i))
6040			alen += sizeof(struct sadb_alg);
6041	}
6042	if (alen)
6043		alen += sizeof(struct sadb_supported);
6044	elen = 0;
6045	for (i = 1; i <= SADB_EALG_MAX; i++) {
6046		if (esp_algorithm_lookup(i))
6047			elen += sizeof(struct sadb_alg);
6048	}
6049	if (elen)
6050		elen += sizeof(struct sadb_supported);
6051
6052	len = sizeof(struct sadb_msg) + alen + elen;
6053
6054	if (len > MCLBYTES)
6055		return key_senderror(so, m, ENOBUFS);
6056
6057	MGETHDR(n, M_DONTWAIT, MT_DATA);
6058	if (len > MHLEN) {
6059		MCLGET(n, M_DONTWAIT);
6060		if ((n->m_flags & M_EXT) == 0) {
6061			m_freem(n);
6062			n = NULL;
6063		}
6064	}
6065	if (!n)
6066		return key_senderror(so, m, ENOBUFS);
6067
6068	n->m_pkthdr.len = n->m_len = len;
6069	n->m_next = NULL;
6070	off = 0;
6071
6072	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6073	newmsg = mtod(n, struct sadb_msg *);
6074	newmsg->sadb_msg_errno = 0;
6075	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6076	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6077
6078	/* for authentication algorithm */
6079	if (alen) {
6080		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6081		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6082		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6083		off += PFKEY_ALIGN8(sizeof(*sup));
6084
6085		for (i = 1; i <= SADB_AALG_MAX; i++) {
6086			struct auth_hash *aalgo;
6087			u_int16_t minkeysize, maxkeysize;
6088
6089			aalgo = ah_algorithm_lookup(i);
6090			if (!aalgo)
6091				continue;
6092			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6093			alg->sadb_alg_id = i;
6094			alg->sadb_alg_ivlen = 0;
6095			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6096			alg->sadb_alg_minbits = _BITS(minkeysize);
6097			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6098			off += PFKEY_ALIGN8(sizeof(*alg));
6099		}
6100	}
6101
6102	/* for encryption algorithm */
6103	if (elen) {
6104		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6105		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6106		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6107		off += PFKEY_ALIGN8(sizeof(*sup));
6108
6109		for (i = 1; i <= SADB_EALG_MAX; i++) {
6110			struct enc_xform *ealgo;
6111
6112			ealgo = esp_algorithm_lookup(i);
6113			if (!ealgo)
6114				continue;
6115			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6116			alg->sadb_alg_id = i;
6117			alg->sadb_alg_ivlen = ealgo->blocksize;
6118			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6119			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6120			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6121		}
6122	}
6123
6124	IPSEC_ASSERT(off == len,
6125		("length assumption failed (off %u len %u)", off, len));
6126
6127	m_freem(m);
6128	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6129    }
6130}
6131
6132/*
6133 * free secreg entry registered.
6134 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6135 */
6136void
6137key_freereg(struct socket *so)
6138{
6139	struct secreg *reg;
6140	int i;
6141
6142	IPSEC_ASSERT(so != NULL, ("NULL so"));
6143
6144	/*
6145	 * check whether existing or not.
6146	 * check all type of SA, because there is a potential that
6147	 * one socket is registered to multiple type of SA.
6148	 */
6149	REGTREE_LOCK();
6150	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6151		LIST_FOREACH(reg, &regtree[i], chain) {
6152			if (reg->so == so && __LIST_CHAINED(reg)) {
6153				LIST_REMOVE(reg, chain);
6154				free(reg, M_IPSEC_SAR);
6155				break;
6156			}
6157		}
6158	}
6159	REGTREE_UNLOCK();
6160}
6161
6162/*
6163 * SADB_EXPIRE processing
6164 * send
6165 *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6166 * to KMD by PF_KEY.
6167 * NOTE: We send only soft lifetime extension.
6168 *
6169 * OUT:	0	: succeed
6170 *	others	: error number
6171 */
6172static int
6173key_expire(struct secasvar *sav)
6174{
6175	int s;
6176	int satype;
6177	struct mbuf *result = NULL, *m;
6178	int len;
6179	int error = -1;
6180	struct sadb_lifetime *lt;
6181
6182	/* XXX: Why do we lock ? */
6183	s = splnet();	/*called from softclock()*/
6184
6185	IPSEC_ASSERT (sav != NULL, ("null sav"));
6186	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6187
6188	/* set msg header */
6189	satype = key_proto2satype(sav->sah->saidx.proto);
6190	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6191	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6192	if (!m) {
6193		error = ENOBUFS;
6194		goto fail;
6195	}
6196	result = m;
6197
6198	/* create SA extension */
6199	m = key_setsadbsa(sav);
6200	if (!m) {
6201		error = ENOBUFS;
6202		goto fail;
6203	}
6204	m_cat(result, m);
6205
6206	/* create SA extension */
6207	m = key_setsadbxsa2(sav->sah->saidx.mode,
6208			sav->replay ? sav->replay->count : 0,
6209			sav->sah->saidx.reqid);
6210	if (!m) {
6211		error = ENOBUFS;
6212		goto fail;
6213	}
6214	m_cat(result, m);
6215
6216	/* create lifetime extension (current and soft) */
6217	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6218	m = key_alloc_mbuf(len);
6219	if (!m || m->m_next) {	/*XXX*/
6220		if (m)
6221			m_freem(m);
6222		error = ENOBUFS;
6223		goto fail;
6224	}
6225	bzero(mtod(m, caddr_t), len);
6226	lt = mtod(m, struct sadb_lifetime *);
6227	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6228	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6229	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6230	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6231	lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
6232	lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
6233	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6234	bcopy(sav->lft_s, lt, sizeof(*lt));
6235	m_cat(result, m);
6236
6237	/* set sadb_address for source */
6238	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6239	    &sav->sah->saidx.src.sa,
6240	    FULLMASK, IPSEC_ULPROTO_ANY);
6241	if (!m) {
6242		error = ENOBUFS;
6243		goto fail;
6244	}
6245	m_cat(result, m);
6246
6247	/* set sadb_address for destination */
6248	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6249	    &sav->sah->saidx.dst.sa,
6250	    FULLMASK, IPSEC_ULPROTO_ANY);
6251	if (!m) {
6252		error = ENOBUFS;
6253		goto fail;
6254	}
6255	m_cat(result, m);
6256
6257	if ((result->m_flags & M_PKTHDR) == 0) {
6258		error = EINVAL;
6259		goto fail;
6260	}
6261
6262	if (result->m_len < sizeof(struct sadb_msg)) {
6263		result = m_pullup(result, sizeof(struct sadb_msg));
6264		if (result == NULL) {
6265			error = ENOBUFS;
6266			goto fail;
6267		}
6268	}
6269
6270	result->m_pkthdr.len = 0;
6271	for (m = result; m; m = m->m_next)
6272		result->m_pkthdr.len += m->m_len;
6273
6274	mtod(result, struct sadb_msg *)->sadb_msg_len =
6275	    PFKEY_UNIT64(result->m_pkthdr.len);
6276
6277	splx(s);
6278	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6279
6280 fail:
6281	if (result)
6282		m_freem(result);
6283	splx(s);
6284	return error;
6285}
6286
6287/*
6288 * SADB_FLUSH processing
6289 * receive
6290 *   <base>
6291 * from the ikmpd, and free all entries in secastree.
6292 * and send,
6293 *   <base>
6294 * to the ikmpd.
6295 * NOTE: to do is only marking SADB_SASTATE_DEAD.
6296 *
6297 * m will always be freed.
6298 */
6299static int
6300key_flush(so, m, mhp)
6301	struct socket *so;
6302	struct mbuf *m;
6303	const struct sadb_msghdr *mhp;
6304{
6305	struct sadb_msg *newmsg;
6306	struct secashead *sah, *nextsah;
6307	struct secasvar *sav, *nextsav;
6308	u_int16_t proto;
6309	u_int8_t state;
6310	u_int stateidx;
6311
6312	IPSEC_ASSERT(so != NULL, ("null socket"));
6313	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6314	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6315
6316	/* map satype to proto */
6317	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6318		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6319			__func__));
6320		return key_senderror(so, m, EINVAL);
6321	}
6322
6323	/* no SATYPE specified, i.e. flushing all SA. */
6324	SAHTREE_LOCK();
6325	for (sah = LIST_FIRST(&sahtree);
6326	     sah != NULL;
6327	     sah = nextsah) {
6328		nextsah = LIST_NEXT(sah, chain);
6329
6330		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6331		 && proto != sah->saidx.proto)
6332			continue;
6333
6334		for (stateidx = 0;
6335		     stateidx < _ARRAYLEN(saorder_state_alive);
6336		     stateidx++) {
6337			state = saorder_state_any[stateidx];
6338			for (sav = LIST_FIRST(&sah->savtree[state]);
6339			     sav != NULL;
6340			     sav = nextsav) {
6341
6342				nextsav = LIST_NEXT(sav, chain);
6343
6344				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6345				KEY_FREESAV(&sav);
6346			}
6347		}
6348
6349		sah->state = SADB_SASTATE_DEAD;
6350	}
6351	SAHTREE_UNLOCK();
6352
6353	if (m->m_len < sizeof(struct sadb_msg) ||
6354	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6355		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6356		return key_senderror(so, m, ENOBUFS);
6357	}
6358
6359	if (m->m_next)
6360		m_freem(m->m_next);
6361	m->m_next = NULL;
6362	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6363	newmsg = mtod(m, struct sadb_msg *);
6364	newmsg->sadb_msg_errno = 0;
6365	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6366
6367	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6368}
6369
6370/*
6371 * SADB_DUMP processing
6372 * dump all entries including status of DEAD in SAD.
6373 * receive
6374 *   <base>
6375 * from the ikmpd, and dump all secasvar leaves
6376 * and send,
6377 *   <base> .....
6378 * to the ikmpd.
6379 *
6380 * m will always be freed.
6381 */
6382static int
6383key_dump(so, m, mhp)
6384	struct socket *so;
6385	struct mbuf *m;
6386	const struct sadb_msghdr *mhp;
6387{
6388	struct secashead *sah;
6389	struct secasvar *sav;
6390	u_int16_t proto;
6391	u_int stateidx;
6392	u_int8_t satype;
6393	u_int8_t state;
6394	int cnt;
6395	struct sadb_msg *newmsg;
6396	struct mbuf *n;
6397
6398	IPSEC_ASSERT(so != NULL, ("null socket"));
6399	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6400	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6401	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6402
6403	/* map satype to proto */
6404	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6405		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6406			__func__));
6407		return key_senderror(so, m, EINVAL);
6408	}
6409
6410	/* count sav entries to be sent to the userland. */
6411	cnt = 0;
6412	SAHTREE_LOCK();
6413	LIST_FOREACH(sah, &sahtree, chain) {
6414		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6415		 && proto != sah->saidx.proto)
6416			continue;
6417
6418		for (stateidx = 0;
6419		     stateidx < _ARRAYLEN(saorder_state_any);
6420		     stateidx++) {
6421			state = saorder_state_any[stateidx];
6422			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6423				cnt++;
6424			}
6425		}
6426	}
6427
6428	if (cnt == 0) {
6429		SAHTREE_UNLOCK();
6430		return key_senderror(so, m, ENOENT);
6431	}
6432
6433	/* send this to the userland, one at a time. */
6434	newmsg = NULL;
6435	LIST_FOREACH(sah, &sahtree, chain) {
6436		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6437		 && proto != sah->saidx.proto)
6438			continue;
6439
6440		/* map proto to satype */
6441		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6442			SAHTREE_UNLOCK();
6443			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
6444				"SAD.\n", __func__));
6445			return key_senderror(so, m, EINVAL);
6446		}
6447
6448		for (stateidx = 0;
6449		     stateidx < _ARRAYLEN(saorder_state_any);
6450		     stateidx++) {
6451			state = saorder_state_any[stateidx];
6452			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6453				n = key_setdumpsa(sav, SADB_DUMP, satype,
6454				    --cnt, mhp->msg->sadb_msg_pid);
6455				if (!n) {
6456					SAHTREE_UNLOCK();
6457					return key_senderror(so, m, ENOBUFS);
6458				}
6459				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6460			}
6461		}
6462	}
6463	SAHTREE_UNLOCK();
6464
6465	m_freem(m);
6466	return 0;
6467}
6468
6469/*
6470 * SADB_X_PROMISC processing
6471 *
6472 * m will always be freed.
6473 */
6474static int
6475key_promisc(so, m, mhp)
6476	struct socket *so;
6477	struct mbuf *m;
6478	const struct sadb_msghdr *mhp;
6479{
6480	int olen;
6481
6482	IPSEC_ASSERT(so != NULL, ("null socket"));
6483	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6484	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6485	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6486
6487	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6488
6489	if (olen < sizeof(struct sadb_msg)) {
6490#if 1
6491		return key_senderror(so, m, EINVAL);
6492#else
6493		m_freem(m);
6494		return 0;
6495#endif
6496	} else if (olen == sizeof(struct sadb_msg)) {
6497		/* enable/disable promisc mode */
6498		struct keycb *kp;
6499
6500		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6501			return key_senderror(so, m, EINVAL);
6502		mhp->msg->sadb_msg_errno = 0;
6503		switch (mhp->msg->sadb_msg_satype) {
6504		case 0:
6505		case 1:
6506			kp->kp_promisc = mhp->msg->sadb_msg_satype;
6507			break;
6508		default:
6509			return key_senderror(so, m, EINVAL);
6510		}
6511
6512		/* send the original message back to everyone */
6513		mhp->msg->sadb_msg_errno = 0;
6514		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6515	} else {
6516		/* send packet as is */
6517
6518		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6519
6520		/* TODO: if sadb_msg_seq is specified, send to specific pid */
6521		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6522	}
6523}
6524
6525static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
6526		const struct sadb_msghdr *)) = {
6527	NULL,		/* SADB_RESERVED */
6528	key_getspi,	/* SADB_GETSPI */
6529	key_update,	/* SADB_UPDATE */
6530	key_add,	/* SADB_ADD */
6531	key_delete,	/* SADB_DELETE */
6532	key_get,	/* SADB_GET */
6533	key_acquire2,	/* SADB_ACQUIRE */
6534	key_register,	/* SADB_REGISTER */
6535	NULL,		/* SADB_EXPIRE */
6536	key_flush,	/* SADB_FLUSH */
6537	key_dump,	/* SADB_DUMP */
6538	key_promisc,	/* SADB_X_PROMISC */
6539	NULL,		/* SADB_X_PCHANGE */
6540	key_spdadd,	/* SADB_X_SPDUPDATE */
6541	key_spdadd,	/* SADB_X_SPDADD */
6542	key_spddelete,	/* SADB_X_SPDDELETE */
6543	key_spdget,	/* SADB_X_SPDGET */
6544	NULL,		/* SADB_X_SPDACQUIRE */
6545	key_spddump,	/* SADB_X_SPDDUMP */
6546	key_spdflush,	/* SADB_X_SPDFLUSH */
6547	key_spdadd,	/* SADB_X_SPDSETIDX */
6548	NULL,		/* SADB_X_SPDEXPIRE */
6549	key_spddelete2,	/* SADB_X_SPDDELETE2 */
6550};
6551
6552/*
6553 * parse sadb_msg buffer to process PFKEYv2,
6554 * and create a data to response if needed.
6555 * I think to be dealed with mbuf directly.
6556 * IN:
6557 *     msgp  : pointer to pointer to a received buffer pulluped.
6558 *             This is rewrited to response.
6559 *     so    : pointer to socket.
6560 * OUT:
6561 *    length for buffer to send to user process.
6562 */
6563int
6564key_parse(m, so)
6565	struct mbuf *m;
6566	struct socket *so;
6567{
6568	struct sadb_msg *msg;
6569	struct sadb_msghdr mh;
6570	u_int orglen;
6571	int error;
6572	int target;
6573
6574	IPSEC_ASSERT(so != NULL, ("null socket"));
6575	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6576
6577#if 0	/*kdebug_sadb assumes msg in linear buffer*/
6578	KEYDEBUG(KEYDEBUG_KEY_DUMP,
6579		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
6580		kdebug_sadb(msg));
6581#endif
6582
6583	if (m->m_len < sizeof(struct sadb_msg)) {
6584		m = m_pullup(m, sizeof(struct sadb_msg));
6585		if (!m)
6586			return ENOBUFS;
6587	}
6588	msg = mtod(m, struct sadb_msg *);
6589	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6590	target = KEY_SENDUP_ONE;
6591
6592	if ((m->m_flags & M_PKTHDR) == 0 ||
6593	    m->m_pkthdr.len != m->m_pkthdr.len) {
6594		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
6595		pfkeystat.out_invlen++;
6596		error = EINVAL;
6597		goto senderror;
6598	}
6599
6600	if (msg->sadb_msg_version != PF_KEY_V2) {
6601		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
6602		    __func__, msg->sadb_msg_version));
6603		pfkeystat.out_invver++;
6604		error = EINVAL;
6605		goto senderror;
6606	}
6607
6608	if (msg->sadb_msg_type > SADB_MAX) {
6609		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6610		    __func__, msg->sadb_msg_type));
6611		pfkeystat.out_invmsgtype++;
6612		error = EINVAL;
6613		goto senderror;
6614	}
6615
6616	/* for old-fashioned code - should be nuked */
6617	if (m->m_pkthdr.len > MCLBYTES) {
6618		m_freem(m);
6619		return ENOBUFS;
6620	}
6621	if (m->m_next) {
6622		struct mbuf *n;
6623
6624		MGETHDR(n, M_DONTWAIT, MT_DATA);
6625		if (n && m->m_pkthdr.len > MHLEN) {
6626			MCLGET(n, M_DONTWAIT);
6627			if ((n->m_flags & M_EXT) == 0) {
6628				m_free(n);
6629				n = NULL;
6630			}
6631		}
6632		if (!n) {
6633			m_freem(m);
6634			return ENOBUFS;
6635		}
6636		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6637		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6638		n->m_next = NULL;
6639		m_freem(m);
6640		m = n;
6641	}
6642
6643	/* align the mbuf chain so that extensions are in contiguous region. */
6644	error = key_align(m, &mh);
6645	if (error)
6646		return error;
6647
6648	if (m->m_next) {	/*XXX*/
6649		m_freem(m);
6650		return ENOBUFS;
6651	}
6652
6653	msg = mh.msg;
6654
6655	/* check SA type */
6656	switch (msg->sadb_msg_satype) {
6657	case SADB_SATYPE_UNSPEC:
6658		switch (msg->sadb_msg_type) {
6659		case SADB_GETSPI:
6660		case SADB_UPDATE:
6661		case SADB_ADD:
6662		case SADB_DELETE:
6663		case SADB_GET:
6664		case SADB_ACQUIRE:
6665		case SADB_EXPIRE:
6666			ipseclog((LOG_DEBUG, "%s: must specify satype "
6667			    "when msg type=%u.\n", __func__,
6668			    msg->sadb_msg_type));
6669			pfkeystat.out_invsatype++;
6670			error = EINVAL;
6671			goto senderror;
6672		}
6673		break;
6674	case SADB_SATYPE_AH:
6675	case SADB_SATYPE_ESP:
6676	case SADB_X_SATYPE_IPCOMP:
6677		switch (msg->sadb_msg_type) {
6678		case SADB_X_SPDADD:
6679		case SADB_X_SPDDELETE:
6680		case SADB_X_SPDGET:
6681		case SADB_X_SPDDUMP:
6682		case SADB_X_SPDFLUSH:
6683		case SADB_X_SPDSETIDX:
6684		case SADB_X_SPDUPDATE:
6685		case SADB_X_SPDDELETE2:
6686			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
6687				__func__, msg->sadb_msg_type));
6688			pfkeystat.out_invsatype++;
6689			error = EINVAL;
6690			goto senderror;
6691		}
6692		break;
6693	case SADB_SATYPE_RSVP:
6694	case SADB_SATYPE_OSPFV2:
6695	case SADB_SATYPE_RIPV2:
6696	case SADB_SATYPE_MIP:
6697		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
6698			__func__, msg->sadb_msg_satype));
6699		pfkeystat.out_invsatype++;
6700		error = EOPNOTSUPP;
6701		goto senderror;
6702	case 1:	/* XXX: What does it do? */
6703		if (msg->sadb_msg_type == SADB_X_PROMISC)
6704			break;
6705		/*FALLTHROUGH*/
6706	default:
6707		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6708			__func__, msg->sadb_msg_satype));
6709		pfkeystat.out_invsatype++;
6710		error = EINVAL;
6711		goto senderror;
6712	}
6713
6714	/* check field of upper layer protocol and address family */
6715	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6716	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6717		struct sadb_address *src0, *dst0;
6718		u_int plen;
6719
6720		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6721		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6722
6723		/* check upper layer protocol */
6724		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6725			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
6726				"mismatched.\n", __func__));
6727			pfkeystat.out_invaddr++;
6728			error = EINVAL;
6729			goto senderror;
6730		}
6731
6732		/* check family */
6733		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6734		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
6735			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
6736				__func__));
6737			pfkeystat.out_invaddr++;
6738			error = EINVAL;
6739			goto senderror;
6740		}
6741		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6742		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
6743			ipseclog((LOG_DEBUG, "%s: address struct size "
6744				"mismatched.\n", __func__));
6745			pfkeystat.out_invaddr++;
6746			error = EINVAL;
6747			goto senderror;
6748		}
6749
6750		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6751		case AF_INET:
6752			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6753			    sizeof(struct sockaddr_in)) {
6754				pfkeystat.out_invaddr++;
6755				error = EINVAL;
6756				goto senderror;
6757			}
6758			break;
6759		case AF_INET6:
6760			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6761			    sizeof(struct sockaddr_in6)) {
6762				pfkeystat.out_invaddr++;
6763				error = EINVAL;
6764				goto senderror;
6765			}
6766			break;
6767		default:
6768			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
6769				__func__));
6770			pfkeystat.out_invaddr++;
6771			error = EAFNOSUPPORT;
6772			goto senderror;
6773		}
6774
6775		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6776		case AF_INET:
6777			plen = sizeof(struct in_addr) << 3;
6778			break;
6779		case AF_INET6:
6780			plen = sizeof(struct in6_addr) << 3;
6781			break;
6782		default:
6783			plen = 0;	/*fool gcc*/
6784			break;
6785		}
6786
6787		/* check max prefix length */
6788		if (src0->sadb_address_prefixlen > plen ||
6789		    dst0->sadb_address_prefixlen > plen) {
6790			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
6791				__func__));
6792			pfkeystat.out_invaddr++;
6793			error = EINVAL;
6794			goto senderror;
6795		}
6796
6797		/*
6798		 * prefixlen == 0 is valid because there can be a case when
6799		 * all addresses are matched.
6800		 */
6801	}
6802
6803	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
6804	    key_typesw[msg->sadb_msg_type] == NULL) {
6805		pfkeystat.out_invmsgtype++;
6806		error = EINVAL;
6807		goto senderror;
6808	}
6809
6810	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6811
6812senderror:
6813	msg->sadb_msg_errno = error;
6814	return key_sendup_mbuf(so, m, target);
6815}
6816
6817static int
6818key_senderror(so, m, code)
6819	struct socket *so;
6820	struct mbuf *m;
6821	int code;
6822{
6823	struct sadb_msg *msg;
6824
6825	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6826		("mbuf too small, len %u", m->m_len));
6827
6828	msg = mtod(m, struct sadb_msg *);
6829	msg->sadb_msg_errno = code;
6830	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
6831}
6832
6833/*
6834 * set the pointer to each header into message buffer.
6835 * m will be freed on error.
6836 * XXX larger-than-MCLBYTES extension?
6837 */
6838static int
6839key_align(m, mhp)
6840	struct mbuf *m;
6841	struct sadb_msghdr *mhp;
6842{
6843	struct mbuf *n;
6844	struct sadb_ext *ext;
6845	size_t off, end;
6846	int extlen;
6847	int toff;
6848
6849	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6850	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6851	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6852		("mbuf too small, len %u", m->m_len));
6853
6854	/* initialize */
6855	bzero(mhp, sizeof(*mhp));
6856
6857	mhp->msg = mtod(m, struct sadb_msg *);
6858	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
6859
6860	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6861	extlen = end;	/*just in case extlen is not updated*/
6862	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
6863		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
6864		if (!n) {
6865			/* m is already freed */
6866			return ENOBUFS;
6867		}
6868		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6869
6870		/* set pointer */
6871		switch (ext->sadb_ext_type) {
6872		case SADB_EXT_SA:
6873		case SADB_EXT_ADDRESS_SRC:
6874		case SADB_EXT_ADDRESS_DST:
6875		case SADB_EXT_ADDRESS_PROXY:
6876		case SADB_EXT_LIFETIME_CURRENT:
6877		case SADB_EXT_LIFETIME_HARD:
6878		case SADB_EXT_LIFETIME_SOFT:
6879		case SADB_EXT_KEY_AUTH:
6880		case SADB_EXT_KEY_ENCRYPT:
6881		case SADB_EXT_IDENTITY_SRC:
6882		case SADB_EXT_IDENTITY_DST:
6883		case SADB_EXT_SENSITIVITY:
6884		case SADB_EXT_PROPOSAL:
6885		case SADB_EXT_SUPPORTED_AUTH:
6886		case SADB_EXT_SUPPORTED_ENCRYPT:
6887		case SADB_EXT_SPIRANGE:
6888		case SADB_X_EXT_POLICY:
6889		case SADB_X_EXT_SA2:
6890			/* duplicate check */
6891			/*
6892			 * XXX Are there duplication payloads of either
6893			 * KEY_AUTH or KEY_ENCRYPT ?
6894			 */
6895			if (mhp->ext[ext->sadb_ext_type] != NULL) {
6896				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
6897					"%u\n", __func__, ext->sadb_ext_type));
6898				m_freem(m);
6899				pfkeystat.out_dupext++;
6900				return EINVAL;
6901			}
6902			break;
6903		default:
6904			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
6905				__func__, ext->sadb_ext_type));
6906			m_freem(m);
6907			pfkeystat.out_invexttype++;
6908			return EINVAL;
6909		}
6910
6911		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
6912
6913		if (key_validate_ext(ext, extlen)) {
6914			m_freem(m);
6915			pfkeystat.out_invlen++;
6916			return EINVAL;
6917		}
6918
6919		n = m_pulldown(m, off, extlen, &toff);
6920		if (!n) {
6921			/* m is already freed */
6922			return ENOBUFS;
6923		}
6924		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6925
6926		mhp->ext[ext->sadb_ext_type] = ext;
6927		mhp->extoff[ext->sadb_ext_type] = off;
6928		mhp->extlen[ext->sadb_ext_type] = extlen;
6929	}
6930
6931	if (off != end) {
6932		m_freem(m);
6933		pfkeystat.out_invlen++;
6934		return EINVAL;
6935	}
6936
6937	return 0;
6938}
6939
6940static int
6941key_validate_ext(ext, len)
6942	const struct sadb_ext *ext;
6943	int len;
6944{
6945	const struct sockaddr *sa;
6946	enum { NONE, ADDR } checktype = NONE;
6947	int baselen = 0;
6948	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
6949
6950	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
6951		return EINVAL;
6952
6953	/* if it does not match minimum/maximum length, bail */
6954	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
6955	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
6956		return EINVAL;
6957	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
6958		return EINVAL;
6959	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
6960		return EINVAL;
6961
6962	/* more checks based on sadb_ext_type XXX need more */
6963	switch (ext->sadb_ext_type) {
6964	case SADB_EXT_ADDRESS_SRC:
6965	case SADB_EXT_ADDRESS_DST:
6966	case SADB_EXT_ADDRESS_PROXY:
6967		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
6968		checktype = ADDR;
6969		break;
6970	case SADB_EXT_IDENTITY_SRC:
6971	case SADB_EXT_IDENTITY_DST:
6972		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
6973		    SADB_X_IDENTTYPE_ADDR) {
6974			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
6975			checktype = ADDR;
6976		} else
6977			checktype = NONE;
6978		break;
6979	default:
6980		checktype = NONE;
6981		break;
6982	}
6983
6984	switch (checktype) {
6985	case NONE:
6986		break;
6987	case ADDR:
6988		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
6989		if (len < baselen + sal)
6990			return EINVAL;
6991		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
6992			return EINVAL;
6993		break;
6994	}
6995
6996	return 0;
6997}
6998
6999void
7000key_init()
7001{
7002	int i;
7003
7004	SPTREE_LOCK_INIT();
7005	REGTREE_LOCK_INIT();
7006	SAHTREE_LOCK_INIT();
7007	ACQ_LOCK_INIT();
7008	SPACQ_LOCK_INIT();
7009
7010	for (i = 0; i < IPSEC_DIR_MAX; i++)
7011		LIST_INIT(&sptree[i]);
7012
7013	LIST_INIT(&sahtree);
7014
7015	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7016		LIST_INIT(&regtree[i]);
7017
7018	LIST_INIT(&acqtree);
7019	LIST_INIT(&spacqtree);
7020
7021	/* system default */
7022	ip4_def_policy.policy = IPSEC_POLICY_NONE;
7023	ip4_def_policy.refcnt++;	/*never reclaim this*/
7024
7025#ifndef IPSEC_DEBUG2
7026	timeout((void *)key_timehandler, (void *)0, hz);
7027#endif /*IPSEC_DEBUG2*/
7028
7029	/* initialize key statistics */
7030	keystat.getspi_count = 1;
7031
7032	printf("Fast IPsec: Initialized Security Association Processing.\n");
7033
7034	return;
7035}
7036
7037/*
7038 * XXX: maybe This function is called after INBOUND IPsec processing.
7039 *
7040 * Special check for tunnel-mode packets.
7041 * We must make some checks for consistency between inner and outer IP header.
7042 *
7043 * xxx more checks to be provided
7044 */
7045int
7046key_checktunnelsanity(sav, family, src, dst)
7047	struct secasvar *sav;
7048	u_int family;
7049	caddr_t src;
7050	caddr_t dst;
7051{
7052	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7053
7054	/* XXX: check inner IP header */
7055
7056	return 1;
7057}
7058
7059/* record data transfer on SA, and update timestamps */
7060void
7061key_sa_recordxfer(sav, m)
7062	struct secasvar *sav;
7063	struct mbuf *m;
7064{
7065	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7066	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7067	if (!sav->lft_c)
7068		return;
7069
7070	/*
7071	 * XXX Currently, there is a difference of bytes size
7072	 * between inbound and outbound processing.
7073	 */
7074	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
7075	/* to check bytes lifetime is done in key_timehandler(). */
7076
7077	/*
7078	 * We use the number of packets as the unit of
7079	 * sadb_lifetime_allocations.  We increment the variable
7080	 * whenever {esp,ah}_{in,out}put is called.
7081	 */
7082	sav->lft_c->sadb_lifetime_allocations++;
7083	/* XXX check for expires? */
7084
7085	/*
7086	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
7087	 * in seconds.  HARD and SOFT lifetime are measured by the time
7088	 * difference (again in seconds) from sadb_lifetime_usetime.
7089	 *
7090	 *	usetime
7091	 *	v     expire   expire
7092	 * -----+-----+--------+---> t
7093	 *	<--------------> HARD
7094	 *	<-----> SOFT
7095	 */
7096	sav->lft_c->sadb_lifetime_usetime = time_second;
7097	/* XXX check for expires? */
7098
7099	return;
7100}
7101
7102/* dumb version */
7103void
7104key_sa_routechange(dst)
7105	struct sockaddr *dst;
7106{
7107	struct secashead *sah;
7108	struct route *ro;
7109
7110	SAHTREE_LOCK();
7111	LIST_FOREACH(sah, &sahtree, chain) {
7112		ro = &sah->sa_route;
7113		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7114		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7115			RTFREE(ro->ro_rt);
7116			ro->ro_rt = (struct rtentry *)NULL;
7117		}
7118	}
7119	SAHTREE_UNLOCK();
7120}
7121
7122static void
7123key_sa_chgstate(sav, state)
7124	struct secasvar *sav;
7125	u_int8_t state;
7126{
7127	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7128	SAHTREE_LOCK_ASSERT();
7129
7130	if (sav->state != state) {
7131		if (__LIST_CHAINED(sav))
7132			LIST_REMOVE(sav, chain);
7133		sav->state = state;
7134		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7135	}
7136}
7137
7138void
7139key_sa_stir_iv(sav)
7140	struct secasvar *sav;
7141{
7142
7143	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7144	key_randomfill(sav->iv, sav->ivlen);
7145}
7146
7147/* XXX too much? */
7148static struct mbuf *
7149key_alloc_mbuf(l)
7150	int l;
7151{
7152	struct mbuf *m = NULL, *n;
7153	int len, t;
7154
7155	len = l;
7156	while (len > 0) {
7157		MGET(n, M_DONTWAIT, MT_DATA);
7158		if (n && len > MLEN)
7159			MCLGET(n, M_DONTWAIT);
7160		if (!n) {
7161			m_freem(m);
7162			return NULL;
7163		}
7164
7165		n->m_next = NULL;
7166		n->m_len = 0;
7167		n->m_len = M_TRAILINGSPACE(n);
7168		/* use the bottom of mbuf, hoping we can prepend afterwards */
7169		if (n->m_len > len) {
7170			t = (n->m_len - len) & ~(sizeof(long) - 1);
7171			n->m_data += t;
7172			n->m_len = len;
7173		}
7174
7175		len -= n->m_len;
7176
7177		if (m)
7178			m_cat(m, n);
7179		else
7180			m = n;
7181	}
7182
7183	return m;
7184}
7185