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