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