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