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