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