key.c revision 189406
1/*	$FreeBSD: head/sys/netipsec/key.c 189406 2009-03-05 16:22:32Z vanhu $	*/
2/*	$KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $	*/
3
4/*-
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/*
34 * This code is referd to RFC 2367
35 */
36
37#include "opt_inet.h"
38#include "opt_inet6.h"
39#include "opt_ipsec.h"
40
41#include <sys/types.h>
42#include <sys/param.h>
43#include <sys/systm.h>
44#include <sys/kernel.h>
45#include <sys/lock.h>
46#include <sys/mutex.h>
47#include <sys/mbuf.h>
48#include <sys/domain.h>
49#include <sys/protosw.h>
50#include <sys/malloc.h>
51#include <sys/socket.h>
52#include <sys/socketvar.h>
53#include <sys/sysctl.h>
54#include <sys/errno.h>
55#include <sys/proc.h>
56#include <sys/queue.h>
57#include <sys/refcount.h>
58#include <sys/syslog.h>
59#include <sys/vimage.h>
60
61#include <net/if.h>
62#include <net/route.h>
63#include <net/raw_cb.h>
64
65#include <netinet/in.h>
66#include <netinet/in_systm.h>
67#include <netinet/ip.h>
68#include <netinet/in_var.h>
69
70#ifdef INET6
71#include <netinet/ip6.h>
72#include <netinet6/in6_var.h>
73#include <netinet6/ip6_var.h>
74#endif /* INET6 */
75
76#ifdef INET
77#include <netinet/in_pcb.h>
78#include <netinet/vinet.h>
79#endif
80#ifdef INET6
81#include <netinet6/in6_pcb.h>
82#include <netinet6/vinet6.h>
83#endif /* INET6 */
84
85#include <net/pfkeyv2.h>
86#include <netipsec/keydb.h>
87#include <netipsec/key.h>
88#include <netipsec/keysock.h>
89#include <netipsec/key_debug.h>
90
91#include <netipsec/ipsec.h>
92#ifdef INET6
93#include <netipsec/ipsec6.h>
94#endif
95
96#include <netipsec/xform.h>
97
98#include <machine/stdarg.h>
99
100/* randomness */
101#include <sys/random.h>
102#include <sys/vimage.h>
103
104#define FULLMASK	0xff
105#define	_BITS(bytes)	((bytes) << 3)
106
107/*
108 * Note on SA reference counting:
109 * - SAs that are not in DEAD state will have (total external reference + 1)
110 *   following value in reference count field.  they cannot be freed and are
111 *   referenced from SA header.
112 * - SAs that are in DEAD state will have (total external reference)
113 *   in reference count field.  they are ready to be freed.  reference from
114 *   SA header will be removed in key_delsav(), when the reference count
115 *   field hits 0 (= no external reference other than from SA header.
116 */
117
118#ifdef VIMAGE_GLOBALS
119u_int32_t key_debug_level;
120static u_int key_spi_trycnt;
121static u_int32_t key_spi_minval;
122static u_int32_t key_spi_maxval;
123static u_int32_t policy_id;
124static u_int key_int_random;
125static u_int key_larval_lifetime;
126static int key_blockacq_count;
127static int key_blockacq_lifetime;
128static int key_preferred_oldsa;
129
130static u_int32_t acq_seq;
131
132static int ipsec_esp_keymin;
133static int ipsec_esp_auth;
134static int ipsec_ah_keymin;
135
136static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];	/* SPD */
137static LIST_HEAD(_sahtree, secashead) sahtree;			/* SAD */
138static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
139static LIST_HEAD(_acqtree, secacq) acqtree;		/* acquiring list */
140static LIST_HEAD(_spacqtree, secspacq) spacqtree;	/* SP acquiring list */
141#endif /* VIMAGE_GLOBALS */
142
143static struct mtx sptree_lock;
144#define	SPTREE_LOCK_INIT() \
145	mtx_init(&sptree_lock, "sptree", \
146		"fast ipsec security policy database", MTX_DEF)
147#define	SPTREE_LOCK_DESTROY()	mtx_destroy(&sptree_lock)
148#define	SPTREE_LOCK()		mtx_lock(&sptree_lock)
149#define	SPTREE_UNLOCK()	mtx_unlock(&sptree_lock)
150#define	SPTREE_LOCK_ASSERT()	mtx_assert(&sptree_lock, MA_OWNED)
151
152static struct mtx sahtree_lock;
153#define	SAHTREE_LOCK_INIT() \
154	mtx_init(&sahtree_lock, "sahtree", \
155		"fast ipsec security association database", MTX_DEF)
156#define	SAHTREE_LOCK_DESTROY()	mtx_destroy(&sahtree_lock)
157#define	SAHTREE_LOCK()		mtx_lock(&sahtree_lock)
158#define	SAHTREE_UNLOCK()	mtx_unlock(&sahtree_lock)
159#define	SAHTREE_LOCK_ASSERT()	mtx_assert(&sahtree_lock, MA_OWNED)
160
161							/* registed list */
162static struct mtx regtree_lock;
163#define	REGTREE_LOCK_INIT() \
164	mtx_init(&regtree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
165#define	REGTREE_LOCK_DESTROY()	mtx_destroy(&regtree_lock)
166#define	REGTREE_LOCK()		mtx_lock(&regtree_lock)
167#define	REGTREE_UNLOCK()	mtx_unlock(&regtree_lock)
168#define	REGTREE_LOCK_ASSERT()	mtx_assert(&regtree_lock, MA_OWNED)
169
170static struct mtx acq_lock;
171#define	ACQ_LOCK_INIT() \
172	mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
173#define	ACQ_LOCK_DESTROY()	mtx_destroy(&acq_lock)
174#define	ACQ_LOCK()		mtx_lock(&acq_lock)
175#define	ACQ_UNLOCK()		mtx_unlock(&acq_lock)
176#define	ACQ_LOCK_ASSERT()	mtx_assert(&acq_lock, MA_OWNED)
177
178static struct mtx spacq_lock;
179#define	SPACQ_LOCK_INIT() \
180	mtx_init(&spacq_lock, "spacqtree", \
181		"fast ipsec security policy acquire list", MTX_DEF)
182#define	SPACQ_LOCK_DESTROY()	mtx_destroy(&spacq_lock)
183#define	SPACQ_LOCK()		mtx_lock(&spacq_lock)
184#define	SPACQ_UNLOCK()		mtx_unlock(&spacq_lock)
185#define	SPACQ_LOCK_ASSERT()	mtx_assert(&spacq_lock, MA_OWNED)
186
187/* search order for SAs */
188static const u_int saorder_state_valid_prefer_old[] = {
189	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
190};
191static const u_int saorder_state_valid_prefer_new[] = {
192	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
193};
194static const u_int saorder_state_alive[] = {
195	/* except DEAD */
196	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
197};
198static const u_int saorder_state_any[] = {
199	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
200	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
201};
202
203static const int minsize[] = {
204	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
205	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
206	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
207	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
208	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
209	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
210	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
211	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
212	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
213	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
214	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
215	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
216	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
217	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
218	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
219	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
220	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
221	0,				/* SADB_X_EXT_KMPRIVATE */
222	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
223	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
224};
225static const int maxsize[] = {
226	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
227	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
228	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
229	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
230	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
231	0,				/* SADB_EXT_ADDRESS_SRC */
232	0,				/* SADB_EXT_ADDRESS_DST */
233	0,				/* SADB_EXT_ADDRESS_PROXY */
234	0,				/* SADB_EXT_KEY_AUTH */
235	0,				/* SADB_EXT_KEY_ENCRYPT */
236	0,				/* SADB_EXT_IDENTITY_SRC */
237	0,				/* SADB_EXT_IDENTITY_DST */
238	0,				/* SADB_EXT_SENSITIVITY */
239	0,				/* SADB_EXT_PROPOSAL */
240	0,				/* SADB_EXT_SUPPORTED_AUTH */
241	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
242	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
243	0,				/* SADB_X_EXT_KMPRIVATE */
244	0,				/* SADB_X_EXT_POLICY */
245	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
246};
247
248#ifdef SYSCTL_DECL
249SYSCTL_DECL(_net_key);
250#endif
251
252SYSCTL_V_INT(V_NET, vnet_ipsec,_net_key, KEYCTL_DEBUG_LEVEL,	debug,
253	CTLFLAG_RW, key_debug_level,	0,	"");
254
255/* max count of trial for the decision of spi value */
256SYSCTL_V_INT(V_NET, vnet_ipsec,_net_key, KEYCTL_SPI_TRY, spi_trycnt,
257	CTLFLAG_RW, key_spi_trycnt,	0,	"");
258
259/* minimum spi value to allocate automatically. */
260SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_SPI_MIN_VALUE,
261	spi_minval,	CTLFLAG_RW, key_spi_minval,	0,	"");
262
263/* maximun spi value to allocate automatically. */
264SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_SPI_MAX_VALUE,
265	spi_maxval,	CTLFLAG_RW, key_spi_maxval,	0,	"");
266
267/* interval to initialize randseed */
268SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_RANDOM_INT,
269	int_random,	CTLFLAG_RW, key_int_random,	0,	"");
270
271/* lifetime for larval SA */
272SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_LARVAL_LIFETIME,
273	larval_lifetime, CTLFLAG_RW, key_larval_lifetime,	0,	"");
274
275/* counter for blocking to send SADB_ACQUIRE to IKEd */
276SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_BLOCKACQ_COUNT,
277	blockacq_count,	CTLFLAG_RW, key_blockacq_count,	0,	"");
278
279/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
280SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_BLOCKACQ_LIFETIME,
281	blockacq_lifetime, CTLFLAG_RW, key_blockacq_lifetime,	0, "");
282
283/* ESP auth */
284SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_ESP_AUTH,	esp_auth,
285	CTLFLAG_RW, ipsec_esp_auth,	0,	"");
286
287/* minimum ESP key length */
288SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_ESP_KEYMIN,
289	esp_keymin, CTLFLAG_RW, ipsec_esp_keymin,	0,	"");
290
291/* minimum AH key length */
292SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_AH_KEYMIN,	ah_keymin,
293	CTLFLAG_RW, ipsec_ah_keymin,	0,	"");
294
295/* perfered old SA rather than new SA */
296SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_PREFERED_OLDSA,
297	preferred_oldsa, CTLFLAG_RW, key_preferred_oldsa,	0,	"");
298
299#define __LIST_CHAINED(elm) \
300	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
301#define LIST_INSERT_TAIL(head, elm, type, field) \
302do {\
303	struct type *curelm = LIST_FIRST(head); \
304	if (curelm == NULL) {\
305		LIST_INSERT_HEAD(head, elm, field); \
306	} else { \
307		while (LIST_NEXT(curelm, field)) \
308			curelm = LIST_NEXT(curelm, field);\
309		LIST_INSERT_AFTER(curelm, elm, field);\
310	}\
311} while (0)
312
313#define KEY_CHKSASTATE(head, sav, name) \
314do { \
315	if ((head) != (sav)) {						\
316		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
317			(name), (head), (sav)));			\
318		continue;						\
319	}								\
320} while (0)
321
322#define KEY_CHKSPDIR(head, sp, name) \
323do { \
324	if ((head) != (sp)) {						\
325		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
326			"anyway continue.\n",				\
327			(name), (head), (sp)));				\
328	}								\
329} while (0)
330
331MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
332MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
333MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
334MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
335MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
336MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
337MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
338
339/*
340 * set parameters into secpolicyindex buffer.
341 * Must allocate secpolicyindex buffer passed to this function.
342 */
343#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
344do { \
345	bzero((idx), sizeof(struct secpolicyindex));                         \
346	(idx)->dir = (_dir);                                                 \
347	(idx)->prefs = (ps);                                                 \
348	(idx)->prefd = (pd);                                                 \
349	(idx)->ul_proto = (ulp);                                             \
350	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
351	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
352} while (0)
353
354/*
355 * set parameters into secasindex buffer.
356 * Must allocate secasindex buffer before calling this function.
357 */
358#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
359do { \
360	bzero((idx), sizeof(struct secasindex));                             \
361	(idx)->proto = (p);                                                  \
362	(idx)->mode = (m);                                                   \
363	(idx)->reqid = (r);                                                  \
364	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
365	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
366} while (0)
367
368/* key statistics */
369struct _keystat {
370	u_long getspi_count; /* the avarage of count to try to get new SPI */
371} keystat;
372
373struct sadb_msghdr {
374	struct sadb_msg *msg;
375	struct sadb_ext *ext[SADB_EXT_MAX + 1];
376	int extoff[SADB_EXT_MAX + 1];
377	int extlen[SADB_EXT_MAX + 1];
378};
379
380static struct secasvar *key_allocsa_policy __P((const struct secasindex *));
381static void key_freesp_so __P((struct secpolicy **));
382static struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
383static void key_delsp __P((struct secpolicy *));
384static struct secpolicy *key_getsp __P((struct secpolicyindex *));
385static void _key_delsp(struct secpolicy *sp);
386static struct secpolicy *key_getspbyid __P((u_int32_t));
387static u_int32_t key_newreqid __P((void));
388static struct mbuf *key_gather_mbuf __P((struct mbuf *,
389	const struct sadb_msghdr *, int, int, ...));
390static int key_spdadd __P((struct socket *, struct mbuf *,
391	const struct sadb_msghdr *));
392static u_int32_t key_getnewspid __P((void));
393static int key_spddelete __P((struct socket *, struct mbuf *,
394	const struct sadb_msghdr *));
395static int key_spddelete2 __P((struct socket *, struct mbuf *,
396	const struct sadb_msghdr *));
397static int key_spdget __P((struct socket *, struct mbuf *,
398	const struct sadb_msghdr *));
399static int key_spdflush __P((struct socket *, struct mbuf *,
400	const struct sadb_msghdr *));
401static int key_spddump __P((struct socket *, struct mbuf *,
402	const struct sadb_msghdr *));
403static struct mbuf *key_setdumpsp __P((struct secpolicy *,
404	u_int8_t, u_int32_t, u_int32_t));
405static u_int key_getspreqmsglen __P((struct secpolicy *));
406static int key_spdexpire __P((struct secpolicy *));
407static struct secashead *key_newsah __P((struct secasindex *));
408static void key_delsah __P((struct secashead *));
409static struct secasvar *key_newsav __P((struct mbuf *,
410	const struct sadb_msghdr *, struct secashead *, int *,
411	const char*, int));
412#define	KEY_NEWSAV(m, sadb, sah, e)				\
413	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
414static void key_delsav __P((struct secasvar *));
415static struct secashead *key_getsah __P((struct secasindex *));
416static struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
417static struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
418static int key_setsaval __P((struct secasvar *, struct mbuf *,
419	const struct sadb_msghdr *));
420static int key_mature __P((struct secasvar *));
421static struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
422	u_int8_t, u_int32_t, u_int32_t));
423static struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
424	u_int32_t, pid_t, u_int16_t));
425static struct mbuf *key_setsadbsa __P((struct secasvar *));
426static struct mbuf *key_setsadbaddr __P((u_int16_t,
427	const struct sockaddr *, u_int8_t, u_int16_t));
428static struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
429static struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
430	u_int32_t));
431static struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
432				     struct malloc_type *);
433static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
434					    struct malloc_type *type);
435#ifdef INET6
436static int key_ismyaddr6 __P((struct sockaddr_in6 *));
437#endif
438
439/* flags for key_cmpsaidx() */
440#define CMP_HEAD	1	/* protocol, addresses. */
441#define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
442#define CMP_REQID	3	/* additionally HEAD, reaid. */
443#define CMP_EXACTLY	4	/* all elements. */
444static int key_cmpsaidx
445	__P((const struct secasindex *, const struct secasindex *, int));
446
447static int key_cmpspidx_exactly
448	__P((struct secpolicyindex *, struct secpolicyindex *));
449static int key_cmpspidx_withmask
450	__P((struct secpolicyindex *, struct secpolicyindex *));
451static int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
452static int key_bbcmp __P((const void *, const void *, u_int));
453static u_int16_t key_satype2proto __P((u_int8_t));
454static u_int8_t key_proto2satype __P((u_int16_t));
455
456static int key_getspi __P((struct socket *, struct mbuf *,
457	const struct sadb_msghdr *));
458static u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
459					struct secasindex *));
460static int key_update __P((struct socket *, struct mbuf *,
461	const struct sadb_msghdr *));
462#ifdef IPSEC_DOSEQCHECK
463static struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
464#endif
465static int key_add __P((struct socket *, struct mbuf *,
466	const struct sadb_msghdr *));
467static int key_setident __P((struct secashead *, struct mbuf *,
468	const struct sadb_msghdr *));
469static struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
470	const struct sadb_msghdr *));
471static int key_delete __P((struct socket *, struct mbuf *,
472	const struct sadb_msghdr *));
473static int key_get __P((struct socket *, struct mbuf *,
474	const struct sadb_msghdr *));
475
476static void key_getcomb_setlifetime __P((struct sadb_comb *));
477static struct mbuf *key_getcomb_esp __P((void));
478static struct mbuf *key_getcomb_ah __P((void));
479static struct mbuf *key_getcomb_ipcomp __P((void));
480static struct mbuf *key_getprop __P((const struct secasindex *));
481
482static int key_acquire __P((const struct secasindex *, struct secpolicy *));
483static struct secacq *key_newacq __P((const struct secasindex *));
484static struct secacq *key_getacq __P((const struct secasindex *));
485static struct secacq *key_getacqbyseq __P((u_int32_t));
486static struct secspacq *key_newspacq __P((struct secpolicyindex *));
487static struct secspacq *key_getspacq __P((struct secpolicyindex *));
488static int key_acquire2 __P((struct socket *, struct mbuf *,
489	const struct sadb_msghdr *));
490static int key_register __P((struct socket *, struct mbuf *,
491	const struct sadb_msghdr *));
492static int key_expire __P((struct secasvar *));
493static int key_flush __P((struct socket *, struct mbuf *,
494	const struct sadb_msghdr *));
495static int key_dump __P((struct socket *, struct mbuf *,
496	const struct sadb_msghdr *));
497static int key_promisc __P((struct socket *, struct mbuf *,
498	const struct sadb_msghdr *));
499static int key_senderror __P((struct socket *, struct mbuf *, int));
500static int key_validate_ext __P((const struct sadb_ext *, int));
501static int key_align __P((struct mbuf *, struct sadb_msghdr *));
502static struct mbuf *key_setlifetime(struct seclifetime *src,
503				     u_int16_t exttype);
504static struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
505
506#if 0
507static const char *key_getfqdn __P((void));
508static const char *key_getuserfqdn __P((void));
509#endif
510static void key_sa_chgstate __P((struct secasvar *, u_int8_t));
511static struct mbuf *key_alloc_mbuf __P((int));
512
513static __inline void
514sa_initref(struct secasvar *sav)
515{
516
517	refcount_init(&sav->refcnt, 1);
518}
519static __inline void
520sa_addref(struct secasvar *sav)
521{
522
523	refcount_acquire(&sav->refcnt);
524	IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
525}
526static __inline int
527sa_delref(struct secasvar *sav)
528{
529
530	IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
531	return (refcount_release(&sav->refcnt));
532}
533
534#define	SP_ADDREF(p) do {						\
535	(p)->refcnt++;							\
536	IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));		\
537} while (0)
538#define	SP_DELREF(p) do {						\
539	IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));		\
540	(p)->refcnt--;							\
541} while (0)
542
543
544/*
545 * Update the refcnt while holding the SPTREE lock.
546 */
547void
548key_addref(struct secpolicy *sp)
549{
550	SPTREE_LOCK();
551	SP_ADDREF(sp);
552	SPTREE_UNLOCK();
553}
554
555/*
556 * Return 0 when there are known to be no SP's for the specified
557 * direction.  Otherwise return 1.  This is used by IPsec code
558 * to optimize performance.
559 */
560int
561key_havesp(u_int dir)
562{
563	INIT_VNET_IPSEC(curvnet);
564
565	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
566		LIST_FIRST(&V_sptree[dir]) != NULL : 1);
567}
568
569/* %%% IPsec policy management */
570/*
571 * allocating a SP for OUTBOUND or INBOUND packet.
572 * Must call key_freesp() later.
573 * OUT:	NULL:	not found
574 *	others:	found and return the pointer.
575 */
576struct secpolicy *
577key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
578{
579	INIT_VNET_IPSEC(curvnet);
580	struct secpolicy *sp;
581
582	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
583	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
584		("invalid direction %u", dir));
585
586	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
587		printf("DP %s from %s:%u\n", __func__, where, tag));
588
589	/* get a SP entry */
590	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
591		printf("*** objects\n");
592		kdebug_secpolicyindex(spidx));
593
594	SPTREE_LOCK();
595	LIST_FOREACH(sp, &V_sptree[dir], chain) {
596		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
597			printf("*** in SPD\n");
598			kdebug_secpolicyindex(&sp->spidx));
599
600		if (sp->state == IPSEC_SPSTATE_DEAD)
601			continue;
602		if (key_cmpspidx_withmask(&sp->spidx, spidx))
603			goto found;
604	}
605	sp = NULL;
606found:
607	if (sp) {
608		/* sanity check */
609		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
610
611		/* found a SPD entry */
612		sp->lastused = time_second;
613		SP_ADDREF(sp);
614	}
615	SPTREE_UNLOCK();
616
617	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
618		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
619			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
620	return sp;
621}
622
623/*
624 * allocating a SP for OUTBOUND or INBOUND packet.
625 * Must call key_freesp() later.
626 * OUT:	NULL:	not found
627 *	others:	found and return the pointer.
628 */
629struct secpolicy *
630key_allocsp2(u_int32_t spi,
631	     union sockaddr_union *dst,
632	     u_int8_t proto,
633	     u_int dir,
634	     const char* where, int tag)
635{
636	INIT_VNET_IPSEC(curvnet);
637	struct secpolicy *sp;
638
639	IPSEC_ASSERT(dst != NULL, ("null dst"));
640	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
641		("invalid direction %u", dir));
642
643	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
644		printf("DP %s from %s:%u\n", __func__, where, tag));
645
646	/* get a SP entry */
647	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
648		printf("*** objects\n");
649		printf("spi %u proto %u dir %u\n", spi, proto, dir);
650		kdebug_sockaddr(&dst->sa));
651
652	SPTREE_LOCK();
653	LIST_FOREACH(sp, &V_sptree[dir], chain) {
654		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
655			printf("*** in SPD\n");
656			kdebug_secpolicyindex(&sp->spidx));
657
658		if (sp->state == IPSEC_SPSTATE_DEAD)
659			continue;
660		/* compare simple values, then dst address */
661		if (sp->spidx.ul_proto != proto)
662			continue;
663		/* NB: spi's must exist and match */
664		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
665			continue;
666		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
667			goto found;
668	}
669	sp = NULL;
670found:
671	if (sp) {
672		/* sanity check */
673		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
674
675		/* found a SPD entry */
676		sp->lastused = time_second;
677		SP_ADDREF(sp);
678	}
679	SPTREE_UNLOCK();
680
681	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
682		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
683			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
684	return sp;
685}
686
687/*
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(struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid)
2423{
2424	struct mbuf *result = NULL, *m;
2425	struct seclifetime lt;
2426
2427	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2428	if (!m)
2429		goto fail;
2430	result = m;
2431
2432	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2433	    &sp->spidx.src.sa, sp->spidx.prefs,
2434	    sp->spidx.ul_proto);
2435	if (!m)
2436		goto fail;
2437	m_cat(result, m);
2438
2439	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2440	    &sp->spidx.dst.sa, sp->spidx.prefd,
2441	    sp->spidx.ul_proto);
2442	if (!m)
2443		goto fail;
2444	m_cat(result, m);
2445
2446	m = key_sp2msg(sp);
2447	if (!m)
2448		goto fail;
2449	m_cat(result, m);
2450
2451	if(sp->lifetime){
2452		lt.addtime=sp->created;
2453		lt.usetime= sp->lastused;
2454		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_CURRENT);
2455		if (!m)
2456			goto fail;
2457		m_cat(result, m);
2458
2459		lt.addtime=sp->lifetime;
2460		lt.usetime= sp->validtime;
2461		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_HARD);
2462		if (!m)
2463			goto fail;
2464		m_cat(result, m);
2465	}
2466
2467	if ((result->m_flags & M_PKTHDR) == 0)
2468		goto fail;
2469
2470	if (result->m_len < sizeof(struct sadb_msg)) {
2471		result = m_pullup(result, sizeof(struct sadb_msg));
2472		if (result == NULL)
2473			goto fail;
2474	}
2475
2476	result->m_pkthdr.len = 0;
2477	for (m = result; m; m = m->m_next)
2478		result->m_pkthdr.len += m->m_len;
2479
2480	mtod(result, struct sadb_msg *)->sadb_msg_len =
2481	    PFKEY_UNIT64(result->m_pkthdr.len);
2482
2483	return result;
2484
2485fail:
2486	m_freem(result);
2487	return NULL;
2488}
2489
2490/*
2491 * get PFKEY message length for security policy and request.
2492 */
2493static u_int
2494key_getspreqmsglen(sp)
2495	struct secpolicy *sp;
2496{
2497	u_int tlen;
2498
2499	tlen = sizeof(struct sadb_x_policy);
2500
2501	/* if is the policy for ipsec ? */
2502	if (sp->policy != IPSEC_POLICY_IPSEC)
2503		return tlen;
2504
2505	/* get length of ipsec requests */
2506    {
2507	struct ipsecrequest *isr;
2508	int len;
2509
2510	for (isr = sp->req; isr != NULL; isr = isr->next) {
2511		len = sizeof(struct sadb_x_ipsecrequest)
2512			+ isr->saidx.src.sa.sa_len
2513			+ isr->saidx.dst.sa.sa_len;
2514
2515		tlen += PFKEY_ALIGN8(len);
2516	}
2517    }
2518
2519	return tlen;
2520}
2521
2522/*
2523 * SADB_SPDEXPIRE processing
2524 * send
2525 *   <base, address(SD), lifetime(CH), policy>
2526 * to KMD by PF_KEY.
2527 *
2528 * OUT:	0	: succeed
2529 *	others	: error number
2530 */
2531static int
2532key_spdexpire(sp)
2533	struct secpolicy *sp;
2534{
2535	struct mbuf *result = NULL, *m;
2536	int len;
2537	int error = -1;
2538	struct sadb_lifetime *lt;
2539
2540	/* XXX: Why do we lock ? */
2541
2542	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2543
2544	/* set msg header */
2545	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2546	if (!m) {
2547		error = ENOBUFS;
2548		goto fail;
2549	}
2550	result = m;
2551
2552	/* create lifetime extension (current and hard) */
2553	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2554	m = key_alloc_mbuf(len);
2555	if (!m || m->m_next) {	/*XXX*/
2556		if (m)
2557			m_freem(m);
2558		error = ENOBUFS;
2559		goto fail;
2560	}
2561	bzero(mtod(m, caddr_t), len);
2562	lt = mtod(m, struct sadb_lifetime *);
2563	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2564	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2565	lt->sadb_lifetime_allocations = 0;
2566	lt->sadb_lifetime_bytes = 0;
2567	lt->sadb_lifetime_addtime = sp->created;
2568	lt->sadb_lifetime_usetime = sp->lastused;
2569	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2570	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2571	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2572	lt->sadb_lifetime_allocations = 0;
2573	lt->sadb_lifetime_bytes = 0;
2574	lt->sadb_lifetime_addtime = sp->lifetime;
2575	lt->sadb_lifetime_usetime = sp->validtime;
2576	m_cat(result, m);
2577
2578	/* set sadb_address for source */
2579	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2580	    &sp->spidx.src.sa,
2581	    sp->spidx.prefs, sp->spidx.ul_proto);
2582	if (!m) {
2583		error = ENOBUFS;
2584		goto fail;
2585	}
2586	m_cat(result, m);
2587
2588	/* set sadb_address for destination */
2589	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2590	    &sp->spidx.dst.sa,
2591	    sp->spidx.prefd, sp->spidx.ul_proto);
2592	if (!m) {
2593		error = ENOBUFS;
2594		goto fail;
2595	}
2596	m_cat(result, m);
2597
2598	/* set secpolicy */
2599	m = key_sp2msg(sp);
2600	if (!m) {
2601		error = ENOBUFS;
2602		goto fail;
2603	}
2604	m_cat(result, m);
2605
2606	if ((result->m_flags & M_PKTHDR) == 0) {
2607		error = EINVAL;
2608		goto fail;
2609	}
2610
2611	if (result->m_len < sizeof(struct sadb_msg)) {
2612		result = m_pullup(result, sizeof(struct sadb_msg));
2613		if (result == NULL) {
2614			error = ENOBUFS;
2615			goto fail;
2616		}
2617	}
2618
2619	result->m_pkthdr.len = 0;
2620	for (m = result; m; m = m->m_next)
2621		result->m_pkthdr.len += m->m_len;
2622
2623	mtod(result, struct sadb_msg *)->sadb_msg_len =
2624	    PFKEY_UNIT64(result->m_pkthdr.len);
2625
2626	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2627
2628 fail:
2629	if (result)
2630		m_freem(result);
2631	return error;
2632}
2633
2634/* %%% SAD management */
2635/*
2636 * allocating a memory for new SA head, and copy from the values of mhp.
2637 * OUT:	NULL	: failure due to the lack of memory.
2638 *	others	: pointer to new SA head.
2639 */
2640static struct secashead *
2641key_newsah(saidx)
2642	struct secasindex *saidx;
2643{
2644	INIT_VNET_IPSEC(curvnet);
2645	struct secashead *newsah;
2646
2647	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2648
2649	newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2650	if (newsah != NULL) {
2651		int i;
2652		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2653			LIST_INIT(&newsah->savtree[i]);
2654		newsah->saidx = *saidx;
2655
2656		/* add to saidxtree */
2657		newsah->state = SADB_SASTATE_MATURE;
2658
2659		SAHTREE_LOCK();
2660		LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2661		SAHTREE_UNLOCK();
2662	}
2663	return(newsah);
2664}
2665
2666/*
2667 * delete SA index and all SA registerd.
2668 */
2669static void
2670key_delsah(sah)
2671	struct secashead *sah;
2672{
2673	INIT_VNET_IPSEC(curvnet);
2674	struct secasvar *sav, *nextsav;
2675	u_int stateidx;
2676	int zombie = 0;
2677
2678	IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2679	SAHTREE_LOCK_ASSERT();
2680
2681	/* searching all SA registerd in the secindex. */
2682	for (stateidx = 0;
2683	     stateidx < _ARRAYLEN(saorder_state_any);
2684	     stateidx++) {
2685		u_int state = saorder_state_any[stateidx];
2686		LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2687			if (sav->refcnt == 0) {
2688				/* sanity check */
2689				KEY_CHKSASTATE(state, sav->state, __func__);
2690				KEY_FREESAV(&sav);
2691			} else {
2692				/* give up to delete this sa */
2693				zombie++;
2694			}
2695		}
2696	}
2697	if (!zombie) {		/* delete only if there are savs */
2698		/* remove from tree of SA index */
2699		if (__LIST_CHAINED(sah))
2700			LIST_REMOVE(sah, chain);
2701		if (sah->sa_route.ro_rt) {
2702			RTFREE(sah->sa_route.ro_rt);
2703			sah->sa_route.ro_rt = (struct rtentry *)NULL;
2704		}
2705		free(sah, M_IPSEC_SAH);
2706	}
2707}
2708
2709/*
2710 * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2711 * and copy the values of mhp into new buffer.
2712 * When SAD message type is GETSPI:
2713 *	to set sequence number from acq_seq++,
2714 *	to set zero to SPI.
2715 *	not to call key_setsava().
2716 * OUT:	NULL	: fail
2717 *	others	: pointer to new secasvar.
2718 *
2719 * does not modify mbuf.  does not free mbuf on error.
2720 */
2721static struct secasvar *
2722key_newsav(m, mhp, sah, errp, where, tag)
2723	struct mbuf *m;
2724	const struct sadb_msghdr *mhp;
2725	struct secashead *sah;
2726	int *errp;
2727	const char* where;
2728	int tag;
2729{
2730	INIT_VNET_IPSEC(curvnet);
2731	struct secasvar *newsav;
2732	const struct sadb_sa *xsa;
2733
2734	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2735	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2736	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2737	IPSEC_ASSERT(sah != NULL, ("null secashead"));
2738
2739	newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2740	if (newsav == NULL) {
2741		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2742		*errp = ENOBUFS;
2743		goto done;
2744	}
2745
2746	switch (mhp->msg->sadb_msg_type) {
2747	case SADB_GETSPI:
2748		newsav->spi = 0;
2749
2750#ifdef IPSEC_DOSEQCHECK
2751		/* sync sequence number */
2752		if (mhp->msg->sadb_msg_seq == 0)
2753			newsav->seq =
2754				(V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2755		else
2756#endif
2757			newsav->seq = mhp->msg->sadb_msg_seq;
2758		break;
2759
2760	case SADB_ADD:
2761		/* sanity check */
2762		if (mhp->ext[SADB_EXT_SA] == NULL) {
2763			free(newsav, M_IPSEC_SA);
2764			newsav = NULL;
2765			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2766				__func__));
2767			*errp = EINVAL;
2768			goto done;
2769		}
2770		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2771		newsav->spi = xsa->sadb_sa_spi;
2772		newsav->seq = mhp->msg->sadb_msg_seq;
2773		break;
2774	default:
2775		free(newsav, M_IPSEC_SA);
2776		newsav = NULL;
2777		*errp = EINVAL;
2778		goto done;
2779	}
2780
2781
2782	/* copy sav values */
2783	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2784		*errp = key_setsaval(newsav, m, mhp);
2785		if (*errp) {
2786			free(newsav, M_IPSEC_SA);
2787			newsav = NULL;
2788			goto done;
2789		}
2790	}
2791
2792	SECASVAR_LOCK_INIT(newsav);
2793
2794	/* reset created */
2795	newsav->created = time_second;
2796	newsav->pid = mhp->msg->sadb_msg_pid;
2797
2798	/* add to satree */
2799	newsav->sah = sah;
2800	sa_initref(newsav);
2801	newsav->state = SADB_SASTATE_LARVAL;
2802
2803	/* XXX locking??? */
2804	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2805			secasvar, chain);
2806done:
2807	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2808		printf("DP %s from %s:%u return SP:%p\n", __func__,
2809			where, tag, newsav));
2810
2811	return newsav;
2812}
2813
2814/*
2815 * free() SA variable entry.
2816 */
2817static void
2818key_cleansav(struct secasvar *sav)
2819{
2820	/*
2821	 * Cleanup xform state.  Note that zeroize'ing causes the
2822	 * keys to be cleared; otherwise we must do it ourself.
2823	 */
2824	if (sav->tdb_xform != NULL) {
2825		sav->tdb_xform->xf_zeroize(sav);
2826		sav->tdb_xform = NULL;
2827	} else {
2828		KASSERT(sav->iv == NULL, ("iv but no xform"));
2829		if (sav->key_auth != NULL)
2830			bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2831		if (sav->key_enc != NULL)
2832			bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2833	}
2834	if (sav->key_auth != NULL) {
2835		if (sav->key_auth->key_data != NULL)
2836			free(sav->key_auth->key_data, M_IPSEC_MISC);
2837		free(sav->key_auth, M_IPSEC_MISC);
2838		sav->key_auth = NULL;
2839	}
2840	if (sav->key_enc != NULL) {
2841		if (sav->key_enc->key_data != NULL)
2842			free(sav->key_enc->key_data, M_IPSEC_MISC);
2843		free(sav->key_enc, M_IPSEC_MISC);
2844		sav->key_enc = NULL;
2845	}
2846	if (sav->sched) {
2847		bzero(sav->sched, sav->schedlen);
2848		free(sav->sched, M_IPSEC_MISC);
2849		sav->sched = NULL;
2850	}
2851	if (sav->replay != NULL) {
2852		free(sav->replay, M_IPSEC_MISC);
2853		sav->replay = NULL;
2854	}
2855	if (sav->lft_c != NULL) {
2856		free(sav->lft_c, M_IPSEC_MISC);
2857		sav->lft_c = NULL;
2858	}
2859	if (sav->lft_h != NULL) {
2860		free(sav->lft_h, M_IPSEC_MISC);
2861		sav->lft_h = NULL;
2862	}
2863	if (sav->lft_s != NULL) {
2864		free(sav->lft_s, M_IPSEC_MISC);
2865		sav->lft_s = NULL;
2866	}
2867}
2868
2869/*
2870 * free() SA variable entry.
2871 */
2872static void
2873key_delsav(sav)
2874	struct secasvar *sav;
2875{
2876	IPSEC_ASSERT(sav != NULL, ("null sav"));
2877	IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2878
2879	/* remove from SA header */
2880	if (__LIST_CHAINED(sav))
2881		LIST_REMOVE(sav, chain);
2882	key_cleansav(sav);
2883	SECASVAR_LOCK_DESTROY(sav);
2884	free(sav, M_IPSEC_SA);
2885}
2886
2887/*
2888 * search SAD.
2889 * OUT:
2890 *	NULL	: not found
2891 *	others	: found, pointer to a SA.
2892 */
2893static struct secashead *
2894key_getsah(saidx)
2895	struct secasindex *saidx;
2896{
2897	INIT_VNET_IPSEC(curvnet);
2898	struct secashead *sah;
2899
2900	SAHTREE_LOCK();
2901	LIST_FOREACH(sah, &V_sahtree, chain) {
2902		if (sah->state == SADB_SASTATE_DEAD)
2903			continue;
2904		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2905			break;
2906	}
2907	SAHTREE_UNLOCK();
2908
2909	return sah;
2910}
2911
2912/*
2913 * check not to be duplicated SPI.
2914 * NOTE: this function is too slow due to searching all SAD.
2915 * OUT:
2916 *	NULL	: not found
2917 *	others	: found, pointer to a SA.
2918 */
2919static struct secasvar *
2920key_checkspidup(saidx, spi)
2921	struct secasindex *saidx;
2922	u_int32_t spi;
2923{
2924	INIT_VNET_IPSEC(curvnet);
2925	struct secashead *sah;
2926	struct secasvar *sav;
2927
2928	/* check address family */
2929	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2930		ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2931			__func__));
2932		return NULL;
2933	}
2934
2935	sav = NULL;
2936	/* check all SAD */
2937	SAHTREE_LOCK();
2938	LIST_FOREACH(sah, &V_sahtree, chain) {
2939		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2940			continue;
2941		sav = key_getsavbyspi(sah, spi);
2942		if (sav != NULL)
2943			break;
2944	}
2945	SAHTREE_UNLOCK();
2946
2947	return sav;
2948}
2949
2950/*
2951 * search SAD litmited alive SA, protocol, SPI.
2952 * OUT:
2953 *	NULL	: not found
2954 *	others	: found, pointer to a SA.
2955 */
2956static struct secasvar *
2957key_getsavbyspi(sah, spi)
2958	struct secashead *sah;
2959	u_int32_t spi;
2960{
2961	INIT_VNET_IPSEC(curvnet);
2962	struct secasvar *sav;
2963	u_int stateidx, state;
2964
2965	sav = NULL;
2966	SAHTREE_LOCK_ASSERT();
2967	/* search all status */
2968	for (stateidx = 0;
2969	     stateidx < _ARRAYLEN(saorder_state_alive);
2970	     stateidx++) {
2971
2972		state = saorder_state_alive[stateidx];
2973		LIST_FOREACH(sav, &sah->savtree[state], chain) {
2974
2975			/* sanity check */
2976			if (sav->state != state) {
2977				ipseclog((LOG_DEBUG, "%s: "
2978				    "invalid sav->state (queue: %d SA: %d)\n",
2979				    __func__, state, sav->state));
2980				continue;
2981			}
2982
2983			if (sav->spi == spi)
2984				return sav;
2985		}
2986	}
2987
2988	return NULL;
2989}
2990
2991/*
2992 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
2993 * You must update these if need.
2994 * OUT:	0:	success.
2995 *	!0:	failure.
2996 *
2997 * does not modify mbuf.  does not free mbuf on error.
2998 */
2999static int
3000key_setsaval(sav, m, mhp)
3001	struct secasvar *sav;
3002	struct mbuf *m;
3003	const struct sadb_msghdr *mhp;
3004{
3005	INIT_VNET_IPSEC(curvnet);
3006	int error = 0;
3007
3008	IPSEC_ASSERT(m != NULL, ("null mbuf"));
3009	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3010	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3011
3012	/* initialization */
3013	sav->replay = NULL;
3014	sav->key_auth = NULL;
3015	sav->key_enc = NULL;
3016	sav->sched = NULL;
3017	sav->schedlen = 0;
3018	sav->iv = NULL;
3019	sav->lft_c = NULL;
3020	sav->lft_h = NULL;
3021	sav->lft_s = NULL;
3022	sav->tdb_xform = NULL;		/* transform */
3023	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
3024	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
3025	sav->tdb_compalgxform = NULL;	/* compression algorithm */
3026
3027	/* SA */
3028	if (mhp->ext[SADB_EXT_SA] != NULL) {
3029		const struct sadb_sa *sa0;
3030
3031		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3032		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3033			error = EINVAL;
3034			goto fail;
3035		}
3036
3037		sav->alg_auth = sa0->sadb_sa_auth;
3038		sav->alg_enc = sa0->sadb_sa_encrypt;
3039		sav->flags = sa0->sadb_sa_flags;
3040
3041		/* replay window */
3042		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3043			sav->replay = (struct secreplay *)
3044				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3045			if (sav->replay == NULL) {
3046				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3047					__func__));
3048				error = ENOBUFS;
3049				goto fail;
3050			}
3051			if (sa0->sadb_sa_replay != 0)
3052				sav->replay->bitmap = (caddr_t)(sav->replay+1);
3053			sav->replay->wsize = sa0->sadb_sa_replay;
3054		}
3055	}
3056
3057	/* Authentication keys */
3058	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3059		const struct sadb_key *key0;
3060		int len;
3061
3062		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3063		len = mhp->extlen[SADB_EXT_KEY_AUTH];
3064
3065		error = 0;
3066		if (len < sizeof(*key0)) {
3067			error = EINVAL;
3068			goto fail;
3069		}
3070		switch (mhp->msg->sadb_msg_satype) {
3071		case SADB_SATYPE_AH:
3072		case SADB_SATYPE_ESP:
3073		case SADB_X_SATYPE_TCPSIGNATURE:
3074			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3075			    sav->alg_auth != SADB_X_AALG_NULL)
3076				error = EINVAL;
3077			break;
3078		case SADB_X_SATYPE_IPCOMP:
3079		default:
3080			error = EINVAL;
3081			break;
3082		}
3083		if (error) {
3084			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3085				__func__));
3086			goto fail;
3087		}
3088
3089		sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3090								M_IPSEC_MISC);
3091		if (sav->key_auth == NULL ) {
3092			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3093				  __func__));
3094			error = ENOBUFS;
3095			goto fail;
3096		}
3097	}
3098
3099	/* Encryption key */
3100	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3101		const struct sadb_key *key0;
3102		int len;
3103
3104		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3105		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3106
3107		error = 0;
3108		if (len < sizeof(*key0)) {
3109			error = EINVAL;
3110			goto fail;
3111		}
3112		switch (mhp->msg->sadb_msg_satype) {
3113		case SADB_SATYPE_ESP:
3114			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3115			    sav->alg_enc != SADB_EALG_NULL) {
3116				error = EINVAL;
3117				break;
3118			}
3119			sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3120								       len,
3121								       M_IPSEC_MISC);
3122			if (sav->key_enc == NULL) {
3123				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3124					__func__));
3125				error = ENOBUFS;
3126				goto fail;
3127			}
3128			break;
3129		case SADB_X_SATYPE_IPCOMP:
3130			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3131				error = EINVAL;
3132			sav->key_enc = NULL;	/*just in case*/
3133			break;
3134		case SADB_SATYPE_AH:
3135		case SADB_X_SATYPE_TCPSIGNATURE:
3136		default:
3137			error = EINVAL;
3138			break;
3139		}
3140		if (error) {
3141			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3142				__func__));
3143			goto fail;
3144		}
3145	}
3146
3147	/* set iv */
3148	sav->ivlen = 0;
3149
3150	switch (mhp->msg->sadb_msg_satype) {
3151	case SADB_SATYPE_AH:
3152		error = xform_init(sav, XF_AH);
3153		break;
3154	case SADB_SATYPE_ESP:
3155		error = xform_init(sav, XF_ESP);
3156		break;
3157	case SADB_X_SATYPE_IPCOMP:
3158		error = xform_init(sav, XF_IPCOMP);
3159		break;
3160	case SADB_X_SATYPE_TCPSIGNATURE:
3161		error = xform_init(sav, XF_TCPSIGNATURE);
3162		break;
3163	}
3164	if (error) {
3165		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3166		        __func__, mhp->msg->sadb_msg_satype));
3167		goto fail;
3168	}
3169
3170	/* reset created */
3171	sav->created = time_second;
3172
3173	/* make lifetime for CURRENT */
3174	sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3175	if (sav->lft_c == NULL) {
3176		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3177		error = ENOBUFS;
3178		goto fail;
3179	}
3180
3181	sav->lft_c->allocations = 0;
3182	sav->lft_c->bytes = 0;
3183	sav->lft_c->addtime = time_second;
3184	sav->lft_c->usetime = 0;
3185
3186	/* lifetimes for HARD and SOFT */
3187    {
3188	const struct sadb_lifetime *lft0;
3189
3190	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3191	if (lft0 != NULL) {
3192		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3193			error = EINVAL;
3194			goto fail;
3195		}
3196		sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3197		if (sav->lft_h == NULL) {
3198			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3199			error = ENOBUFS;
3200			goto fail;
3201		}
3202		/* to be initialize ? */
3203	}
3204
3205	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3206	if (lft0 != NULL) {
3207		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3208			error = EINVAL;
3209			goto fail;
3210		}
3211		sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3212		if (sav->lft_s == NULL) {
3213			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3214			error = ENOBUFS;
3215			goto fail;
3216		}
3217		/* to be initialize ? */
3218	}
3219    }
3220
3221	return 0;
3222
3223 fail:
3224	/* initialization */
3225	key_cleansav(sav);
3226
3227	return error;
3228}
3229
3230/*
3231 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3232 * OUT:	0:	valid
3233 *	other:	errno
3234 */
3235static int
3236key_mature(struct secasvar *sav)
3237{
3238	INIT_VNET_IPSEC(curvnet);
3239	int error;
3240
3241	/* check SPI value */
3242	switch (sav->sah->saidx.proto) {
3243	case IPPROTO_ESP:
3244	case IPPROTO_AH:
3245		/*
3246		 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3247		 * 1-255 reserved by IANA for future use,
3248		 * 0 for implementation specific, local use.
3249		 */
3250		if (ntohl(sav->spi) <= 255) {
3251			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3252			    __func__, (u_int32_t)ntohl(sav->spi)));
3253			return EINVAL;
3254		}
3255		break;
3256	}
3257
3258	/* check satype */
3259	switch (sav->sah->saidx.proto) {
3260	case IPPROTO_ESP:
3261		/* check flags */
3262		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3263		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3264			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3265				"given to old-esp.\n", __func__));
3266			return EINVAL;
3267		}
3268		error = xform_init(sav, XF_ESP);
3269		break;
3270	case IPPROTO_AH:
3271		/* check flags */
3272		if (sav->flags & SADB_X_EXT_DERIV) {
3273			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3274				"given to AH SA.\n", __func__));
3275			return EINVAL;
3276		}
3277		if (sav->alg_enc != SADB_EALG_NONE) {
3278			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3279				"mismated.\n", __func__));
3280			return(EINVAL);
3281		}
3282		error = xform_init(sav, XF_AH);
3283		break;
3284	case IPPROTO_IPCOMP:
3285		if (sav->alg_auth != SADB_AALG_NONE) {
3286			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3287				"mismated.\n", __func__));
3288			return(EINVAL);
3289		}
3290		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3291		 && ntohl(sav->spi) >= 0x10000) {
3292			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3293				__func__));
3294			return(EINVAL);
3295		}
3296		error = xform_init(sav, XF_IPCOMP);
3297		break;
3298	case IPPROTO_TCP:
3299		if (sav->alg_enc != SADB_EALG_NONE) {
3300			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3301				"mismated.\n", __func__));
3302			return(EINVAL);
3303		}
3304		error = xform_init(sav, XF_TCPSIGNATURE);
3305		break;
3306	default:
3307		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3308		error = EPROTONOSUPPORT;
3309		break;
3310	}
3311	if (error == 0) {
3312		SAHTREE_LOCK();
3313		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3314		SAHTREE_UNLOCK();
3315	}
3316	return (error);
3317}
3318
3319/*
3320 * subroutine for SADB_GET and SADB_DUMP.
3321 */
3322static struct mbuf *
3323key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3324    u_int32_t seq, u_int32_t pid)
3325{
3326	struct mbuf *result = NULL, *tres = NULL, *m;
3327	int i;
3328	int dumporder[] = {
3329		SADB_EXT_SA, SADB_X_EXT_SA2,
3330		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3331		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3332		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3333		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3334		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3335	};
3336
3337	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3338	if (m == NULL)
3339		goto fail;
3340	result = m;
3341
3342	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3343		m = NULL;
3344		switch (dumporder[i]) {
3345		case SADB_EXT_SA:
3346			m = key_setsadbsa(sav);
3347			if (!m)
3348				goto fail;
3349			break;
3350
3351		case SADB_X_EXT_SA2:
3352			m = key_setsadbxsa2(sav->sah->saidx.mode,
3353					sav->replay ? sav->replay->count : 0,
3354					sav->sah->saidx.reqid);
3355			if (!m)
3356				goto fail;
3357			break;
3358
3359		case SADB_EXT_ADDRESS_SRC:
3360			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3361			    &sav->sah->saidx.src.sa,
3362			    FULLMASK, IPSEC_ULPROTO_ANY);
3363			if (!m)
3364				goto fail;
3365			break;
3366
3367		case SADB_EXT_ADDRESS_DST:
3368			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3369			    &sav->sah->saidx.dst.sa,
3370			    FULLMASK, IPSEC_ULPROTO_ANY);
3371			if (!m)
3372				goto fail;
3373			break;
3374
3375		case SADB_EXT_KEY_AUTH:
3376			if (!sav->key_auth)
3377				continue;
3378			m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3379			if (!m)
3380				goto fail;
3381			break;
3382
3383		case SADB_EXT_KEY_ENCRYPT:
3384			if (!sav->key_enc)
3385				continue;
3386			m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3387			if (!m)
3388				goto fail;
3389			break;
3390
3391		case SADB_EXT_LIFETIME_CURRENT:
3392			if (!sav->lft_c)
3393				continue;
3394			m = key_setlifetime(sav->lft_c,
3395					    SADB_EXT_LIFETIME_CURRENT);
3396			if (!m)
3397				goto fail;
3398			break;
3399
3400		case SADB_EXT_LIFETIME_HARD:
3401			if (!sav->lft_h)
3402				continue;
3403			m = key_setlifetime(sav->lft_h,
3404					    SADB_EXT_LIFETIME_HARD);
3405			if (!m)
3406				goto fail;
3407			break;
3408
3409		case SADB_EXT_LIFETIME_SOFT:
3410			if (!sav->lft_s)
3411				continue;
3412			m = key_setlifetime(sav->lft_s,
3413					    SADB_EXT_LIFETIME_SOFT);
3414
3415			if (!m)
3416				goto fail;
3417			break;
3418
3419		case SADB_EXT_ADDRESS_PROXY:
3420		case SADB_EXT_IDENTITY_SRC:
3421		case SADB_EXT_IDENTITY_DST:
3422			/* XXX: should we brought from SPD ? */
3423		case SADB_EXT_SENSITIVITY:
3424		default:
3425			continue;
3426		}
3427
3428		if (!m)
3429			goto fail;
3430		if (tres)
3431			m_cat(m, tres);
3432		tres = m;
3433
3434	}
3435
3436	m_cat(result, tres);
3437	if (result->m_len < sizeof(struct sadb_msg)) {
3438		result = m_pullup(result, sizeof(struct sadb_msg));
3439		if (result == NULL)
3440			goto fail;
3441	}
3442
3443	result->m_pkthdr.len = 0;
3444	for (m = result; m; m = m->m_next)
3445		result->m_pkthdr.len += m->m_len;
3446
3447	mtod(result, struct sadb_msg *)->sadb_msg_len =
3448	    PFKEY_UNIT64(result->m_pkthdr.len);
3449
3450	return result;
3451
3452fail:
3453	m_freem(result);
3454	m_freem(tres);
3455	return NULL;
3456}
3457
3458/*
3459 * set data into sadb_msg.
3460 */
3461static struct mbuf *
3462key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3463    pid_t pid, u_int16_t reserved)
3464{
3465	struct mbuf *m;
3466	struct sadb_msg *p;
3467	int len;
3468
3469	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3470	if (len > MCLBYTES)
3471		return NULL;
3472	MGETHDR(m, M_DONTWAIT, MT_DATA);
3473	if (m && len > MHLEN) {
3474		MCLGET(m, M_DONTWAIT);
3475		if ((m->m_flags & M_EXT) == 0) {
3476			m_freem(m);
3477			m = NULL;
3478		}
3479	}
3480	if (!m)
3481		return NULL;
3482	m->m_pkthdr.len = m->m_len = len;
3483	m->m_next = NULL;
3484
3485	p = mtod(m, struct sadb_msg *);
3486
3487	bzero(p, len);
3488	p->sadb_msg_version = PF_KEY_V2;
3489	p->sadb_msg_type = type;
3490	p->sadb_msg_errno = 0;
3491	p->sadb_msg_satype = satype;
3492	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3493	p->sadb_msg_reserved = reserved;
3494	p->sadb_msg_seq = seq;
3495	p->sadb_msg_pid = (u_int32_t)pid;
3496
3497	return m;
3498}
3499
3500/*
3501 * copy secasvar data into sadb_address.
3502 */
3503static struct mbuf *
3504key_setsadbsa(sav)
3505	struct secasvar *sav;
3506{
3507	struct mbuf *m;
3508	struct sadb_sa *p;
3509	int len;
3510
3511	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3512	m = key_alloc_mbuf(len);
3513	if (!m || m->m_next) {	/*XXX*/
3514		if (m)
3515			m_freem(m);
3516		return NULL;
3517	}
3518
3519	p = mtod(m, struct sadb_sa *);
3520
3521	bzero(p, len);
3522	p->sadb_sa_len = PFKEY_UNIT64(len);
3523	p->sadb_sa_exttype = SADB_EXT_SA;
3524	p->sadb_sa_spi = sav->spi;
3525	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3526	p->sadb_sa_state = sav->state;
3527	p->sadb_sa_auth = sav->alg_auth;
3528	p->sadb_sa_encrypt = sav->alg_enc;
3529	p->sadb_sa_flags = sav->flags;
3530
3531	return m;
3532}
3533
3534/*
3535 * set data into sadb_address.
3536 */
3537static struct mbuf *
3538key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto)
3539{
3540	struct mbuf *m;
3541	struct sadb_address *p;
3542	size_t len;
3543
3544	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3545	    PFKEY_ALIGN8(saddr->sa_len);
3546	m = key_alloc_mbuf(len);
3547	if (!m || m->m_next) {	/*XXX*/
3548		if (m)
3549			m_freem(m);
3550		return NULL;
3551	}
3552
3553	p = mtod(m, struct sadb_address *);
3554
3555	bzero(p, len);
3556	p->sadb_address_len = PFKEY_UNIT64(len);
3557	p->sadb_address_exttype = exttype;
3558	p->sadb_address_proto = ul_proto;
3559	if (prefixlen == FULLMASK) {
3560		switch (saddr->sa_family) {
3561		case AF_INET:
3562			prefixlen = sizeof(struct in_addr) << 3;
3563			break;
3564		case AF_INET6:
3565			prefixlen = sizeof(struct in6_addr) << 3;
3566			break;
3567		default:
3568			; /*XXX*/
3569		}
3570	}
3571	p->sadb_address_prefixlen = prefixlen;
3572	p->sadb_address_reserved = 0;
3573
3574	bcopy(saddr,
3575	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3576	    saddr->sa_len);
3577
3578	return m;
3579}
3580
3581/*
3582 * set data into sadb_x_sa2.
3583 */
3584static struct mbuf *
3585key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3586{
3587	struct mbuf *m;
3588	struct sadb_x_sa2 *p;
3589	size_t len;
3590
3591	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3592	m = key_alloc_mbuf(len);
3593	if (!m || m->m_next) {	/*XXX*/
3594		if (m)
3595			m_freem(m);
3596		return NULL;
3597	}
3598
3599	p = mtod(m, struct sadb_x_sa2 *);
3600
3601	bzero(p, len);
3602	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3603	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3604	p->sadb_x_sa2_mode = mode;
3605	p->sadb_x_sa2_reserved1 = 0;
3606	p->sadb_x_sa2_reserved2 = 0;
3607	p->sadb_x_sa2_sequence = seq;
3608	p->sadb_x_sa2_reqid = reqid;
3609
3610	return m;
3611}
3612
3613/*
3614 * set data into sadb_x_policy
3615 */
3616static struct mbuf *
3617key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3618{
3619	struct mbuf *m;
3620	struct sadb_x_policy *p;
3621	size_t len;
3622
3623	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3624	m = key_alloc_mbuf(len);
3625	if (!m || m->m_next) {	/*XXX*/
3626		if (m)
3627			m_freem(m);
3628		return NULL;
3629	}
3630
3631	p = mtod(m, struct sadb_x_policy *);
3632
3633	bzero(p, len);
3634	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3635	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3636	p->sadb_x_policy_type = type;
3637	p->sadb_x_policy_dir = dir;
3638	p->sadb_x_policy_id = id;
3639
3640	return m;
3641}
3642
3643/* %%% utilities */
3644/* Take a key message (sadb_key) from the socket and turn it into one
3645 * of the kernel's key structures (seckey).
3646 *
3647 * IN: pointer to the src
3648 * OUT: NULL no more memory
3649 */
3650struct seckey *
3651key_dup_keymsg(const struct sadb_key *src, u_int len,
3652	       struct malloc_type *type)
3653{
3654	INIT_VNET_IPSEC(curvnet);
3655	struct seckey *dst;
3656	dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3657	if (dst != NULL) {
3658		dst->bits = src->sadb_key_bits;
3659		dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3660		if (dst->key_data != NULL) {
3661			bcopy((const char *)src + sizeof(struct sadb_key),
3662			      dst->key_data, len);
3663		} else {
3664			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3665				  __func__));
3666			free(dst, type);
3667			dst = NULL;
3668		}
3669	} else {
3670		ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3671			  __func__));
3672
3673	}
3674	return dst;
3675}
3676
3677/* Take a lifetime message (sadb_lifetime) passed in on a socket and
3678 * turn it into one of the kernel's lifetime structures (seclifetime).
3679 *
3680 * IN: pointer to the destination, source and malloc type
3681 * OUT: NULL, no more memory
3682 */
3683
3684static struct seclifetime *
3685key_dup_lifemsg(const struct sadb_lifetime *src,
3686		 struct malloc_type *type)
3687{
3688	INIT_VNET_IPSEC(curvnet);
3689	struct seclifetime *dst = NULL;
3690
3691	dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3692					   type, M_NOWAIT);
3693	if (dst == NULL) {
3694		/* XXX counter */
3695		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3696	} else {
3697		dst->allocations = src->sadb_lifetime_allocations;
3698		dst->bytes = src->sadb_lifetime_bytes;
3699		dst->addtime = src->sadb_lifetime_addtime;
3700		dst->usetime = src->sadb_lifetime_usetime;
3701	}
3702	return dst;
3703}
3704
3705/* compare my own address
3706 * OUT:	1: true, i.e. my address.
3707 *	0: false
3708 */
3709int
3710key_ismyaddr(sa)
3711	struct sockaddr *sa;
3712{
3713#ifdef INET
3714	INIT_VNET_INET(curvnet);
3715	struct sockaddr_in *sin;
3716	struct in_ifaddr *ia;
3717#endif
3718
3719	IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3720
3721	switch (sa->sa_family) {
3722#ifdef INET
3723	case AF_INET:
3724		sin = (struct sockaddr_in *)sa;
3725		for (ia = V_in_ifaddrhead.tqh_first; ia;
3726		     ia = ia->ia_link.tqe_next)
3727		{
3728			if (sin->sin_family == ia->ia_addr.sin_family &&
3729			    sin->sin_len == ia->ia_addr.sin_len &&
3730			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3731			{
3732				return 1;
3733			}
3734		}
3735		break;
3736#endif
3737#ifdef INET6
3738	case AF_INET6:
3739		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3740#endif
3741	}
3742
3743	return 0;
3744}
3745
3746#ifdef INET6
3747/*
3748 * compare my own address for IPv6.
3749 * 1: ours
3750 * 0: other
3751 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3752 */
3753#include <netinet6/in6_var.h>
3754
3755static int
3756key_ismyaddr6(sin6)
3757	struct sockaddr_in6 *sin6;
3758{
3759	INIT_VNET_INET6(curvnet);
3760	struct in6_ifaddr *ia;
3761	struct in6_multi *in6m;
3762
3763	for (ia = V_in6_ifaddr; ia; ia = ia->ia_next) {
3764		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3765		    (struct sockaddr *)&ia->ia_addr, 0) == 0)
3766			return 1;
3767
3768		/*
3769		 * XXX Multicast
3770		 * XXX why do we care about multlicast here while we don't care
3771		 * about IPv4 multicast??
3772		 * XXX scope
3773		 */
3774		in6m = NULL;
3775		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3776		if (in6m)
3777			return 1;
3778	}
3779
3780	/* loopback, just for safety */
3781	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3782		return 1;
3783
3784	return 0;
3785}
3786#endif /*INET6*/
3787
3788/*
3789 * compare two secasindex structure.
3790 * flag can specify to compare 2 saidxes.
3791 * compare two secasindex structure without both mode and reqid.
3792 * don't compare port.
3793 * IN:
3794 *      saidx0: source, it can be in SAD.
3795 *      saidx1: object.
3796 * OUT:
3797 *      1 : equal
3798 *      0 : not equal
3799 */
3800static int
3801key_cmpsaidx(
3802	const struct secasindex *saidx0,
3803	const struct secasindex *saidx1,
3804	int flag)
3805{
3806	/* sanity */
3807	if (saidx0 == NULL && saidx1 == NULL)
3808		return 1;
3809
3810	if (saidx0 == NULL || saidx1 == NULL)
3811		return 0;
3812
3813	if (saidx0->proto != saidx1->proto)
3814		return 0;
3815
3816	if (flag == CMP_EXACTLY) {
3817		if (saidx0->mode != saidx1->mode)
3818			return 0;
3819		if (saidx0->reqid != saidx1->reqid)
3820			return 0;
3821		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3822		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3823			return 0;
3824	} else {
3825
3826		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3827		if (flag == CMP_MODE_REQID
3828		  ||flag == CMP_REQID) {
3829			/*
3830			 * If reqid of SPD is non-zero, unique SA is required.
3831			 * The result must be of same reqid in this case.
3832			 */
3833			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3834				return 0;
3835		}
3836
3837		if (flag == CMP_MODE_REQID) {
3838			if (saidx0->mode != IPSEC_MODE_ANY
3839			 && saidx0->mode != saidx1->mode)
3840				return 0;
3841		}
3842
3843		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
3844			return 0;
3845		}
3846		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
3847			return 0;
3848		}
3849	}
3850
3851	return 1;
3852}
3853
3854/*
3855 * compare two secindex structure exactly.
3856 * IN:
3857 *	spidx0: source, it is often in SPD.
3858 *	spidx1: object, it is often from PFKEY message.
3859 * OUT:
3860 *	1 : equal
3861 *	0 : not equal
3862 */
3863static int
3864key_cmpspidx_exactly(
3865	struct secpolicyindex *spidx0,
3866	struct secpolicyindex *spidx1)
3867{
3868	/* sanity */
3869	if (spidx0 == NULL && spidx1 == NULL)
3870		return 1;
3871
3872	if (spidx0 == NULL || spidx1 == NULL)
3873		return 0;
3874
3875	if (spidx0->prefs != spidx1->prefs
3876	 || spidx0->prefd != spidx1->prefd
3877	 || spidx0->ul_proto != spidx1->ul_proto)
3878		return 0;
3879
3880	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3881	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3882}
3883
3884/*
3885 * compare two secindex structure with mask.
3886 * IN:
3887 *	spidx0: source, it is often in SPD.
3888 *	spidx1: object, it is often from IP header.
3889 * OUT:
3890 *	1 : equal
3891 *	0 : not equal
3892 */
3893static int
3894key_cmpspidx_withmask(
3895	struct secpolicyindex *spidx0,
3896	struct secpolicyindex *spidx1)
3897{
3898	/* sanity */
3899	if (spidx0 == NULL && spidx1 == NULL)
3900		return 1;
3901
3902	if (spidx0 == NULL || spidx1 == NULL)
3903		return 0;
3904
3905	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
3906	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
3907	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
3908	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
3909		return 0;
3910
3911	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3912	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3913	 && spidx0->ul_proto != spidx1->ul_proto)
3914		return 0;
3915
3916	switch (spidx0->src.sa.sa_family) {
3917	case AF_INET:
3918		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
3919		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
3920			return 0;
3921		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
3922		    &spidx1->src.sin.sin_addr, spidx0->prefs))
3923			return 0;
3924		break;
3925	case AF_INET6:
3926		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
3927		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
3928			return 0;
3929		/*
3930		 * scope_id check. if sin6_scope_id is 0, we regard it
3931		 * as a wildcard scope, which matches any scope zone ID.
3932		 */
3933		if (spidx0->src.sin6.sin6_scope_id &&
3934		    spidx1->src.sin6.sin6_scope_id &&
3935		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
3936			return 0;
3937		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
3938		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
3939			return 0;
3940		break;
3941	default:
3942		/* XXX */
3943		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
3944			return 0;
3945		break;
3946	}
3947
3948	switch (spidx0->dst.sa.sa_family) {
3949	case AF_INET:
3950		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
3951		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
3952			return 0;
3953		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
3954		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
3955			return 0;
3956		break;
3957	case AF_INET6:
3958		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
3959		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
3960			return 0;
3961		/*
3962		 * scope_id check. if sin6_scope_id is 0, we regard it
3963		 * as a wildcard scope, which matches any scope zone ID.
3964		 */
3965		if (spidx0->dst.sin6.sin6_scope_id &&
3966		    spidx1->dst.sin6.sin6_scope_id &&
3967		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
3968			return 0;
3969		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
3970		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
3971			return 0;
3972		break;
3973	default:
3974		/* XXX */
3975		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
3976			return 0;
3977		break;
3978	}
3979
3980	/* XXX Do we check other field ?  e.g. flowinfo */
3981
3982	return 1;
3983}
3984
3985/* returns 0 on match */
3986static int
3987key_sockaddrcmp(
3988	const struct sockaddr *sa1,
3989	const struct sockaddr *sa2,
3990	int port)
3991{
3992#ifdef satosin
3993#undef satosin
3994#endif
3995#define satosin(s) ((const struct sockaddr_in *)s)
3996#ifdef satosin6
3997#undef satosin6
3998#endif
3999#define satosin6(s) ((const struct sockaddr_in6 *)s)
4000	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4001		return 1;
4002
4003	switch (sa1->sa_family) {
4004	case AF_INET:
4005		if (sa1->sa_len != sizeof(struct sockaddr_in))
4006			return 1;
4007		if (satosin(sa1)->sin_addr.s_addr !=
4008		    satosin(sa2)->sin_addr.s_addr) {
4009			return 1;
4010		}
4011		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4012			return 1;
4013		break;
4014	case AF_INET6:
4015		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4016			return 1;	/*EINVAL*/
4017		if (satosin6(sa1)->sin6_scope_id !=
4018		    satosin6(sa2)->sin6_scope_id) {
4019			return 1;
4020		}
4021		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4022		    &satosin6(sa2)->sin6_addr)) {
4023			return 1;
4024		}
4025		if (port &&
4026		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4027			return 1;
4028		}
4029		break;
4030	default:
4031		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4032			return 1;
4033		break;
4034	}
4035
4036	return 0;
4037#undef satosin
4038#undef satosin6
4039}
4040
4041/*
4042 * compare two buffers with mask.
4043 * IN:
4044 *	addr1: source
4045 *	addr2: object
4046 *	bits:  Number of bits to compare
4047 * OUT:
4048 *	1 : equal
4049 *	0 : not equal
4050 */
4051static int
4052key_bbcmp(const void *a1, const void *a2, u_int bits)
4053{
4054	const unsigned char *p1 = a1;
4055	const unsigned char *p2 = a2;
4056
4057	/* XXX: This could be considerably faster if we compare a word
4058	 * at a time, but it is complicated on LSB Endian machines */
4059
4060	/* Handle null pointers */
4061	if (p1 == NULL || p2 == NULL)
4062		return (p1 == p2);
4063
4064	while (bits >= 8) {
4065		if (*p1++ != *p2++)
4066			return 0;
4067		bits -= 8;
4068	}
4069
4070	if (bits > 0) {
4071		u_int8_t mask = ~((1<<(8-bits))-1);
4072		if ((*p1 & mask) != (*p2 & mask))
4073			return 0;
4074	}
4075	return 1;	/* Match! */
4076}
4077
4078static void
4079key_flush_spd(time_t now)
4080{
4081	INIT_VNET_IPSEC(curvnet);
4082	static u_int16_t sptree_scangen = 0;
4083	u_int16_t gen = sptree_scangen++;
4084	struct secpolicy *sp;
4085	u_int dir;
4086
4087	/* SPD */
4088	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4089restart:
4090		SPTREE_LOCK();
4091		LIST_FOREACH(sp, &V_sptree[dir], chain) {
4092			if (sp->scangen == gen)		/* previously handled */
4093				continue;
4094			sp->scangen = gen;
4095			if (sp->state == IPSEC_SPSTATE_DEAD) {
4096				/* NB: clean entries created by key_spdflush */
4097				SPTREE_UNLOCK();
4098				KEY_FREESP(&sp);
4099				goto restart;
4100			}
4101			if (sp->lifetime == 0 && sp->validtime == 0)
4102				continue;
4103			if ((sp->lifetime && now - sp->created > sp->lifetime)
4104			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4105				sp->state = IPSEC_SPSTATE_DEAD;
4106				SPTREE_UNLOCK();
4107				key_spdexpire(sp);
4108				KEY_FREESP(&sp);
4109				goto restart;
4110			}
4111		}
4112		SPTREE_UNLOCK();
4113	}
4114}
4115
4116static void
4117key_flush_sad(time_t now)
4118{
4119	INIT_VNET_IPSEC(curvnet);
4120	struct secashead *sah, *nextsah;
4121	struct secasvar *sav, *nextsav;
4122
4123	/* SAD */
4124	SAHTREE_LOCK();
4125	LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4126		/* if sah has been dead, then delete it and process next sah. */
4127		if (sah->state == SADB_SASTATE_DEAD) {
4128			key_delsah(sah);
4129			continue;
4130		}
4131
4132		/* if LARVAL entry doesn't become MATURE, delete it. */
4133		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4134			if (now - sav->created > V_key_larval_lifetime)
4135				KEY_FREESAV(&sav);
4136		}
4137
4138		/*
4139		 * check MATURE entry to start to send expire message
4140		 * whether or not.
4141		 */
4142		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4143			/* we don't need to check. */
4144			if (sav->lft_s == NULL)
4145				continue;
4146
4147			/* sanity check */
4148			if (sav->lft_c == NULL) {
4149				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4150					"time, why?\n", __func__));
4151				continue;
4152			}
4153
4154			/* check SOFT lifetime */
4155			if (sav->lft_s->addtime != 0 &&
4156			    now - sav->created > sav->lft_s->addtime) {
4157				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4158				/* Actually, only send expire message if SA has been used, as it
4159				 * was done before, but should we always send such message, and let IKE
4160				 * daemon decide if it should be renegociated or not ?
4161				 * XXX expire message will actually NOT be sent if SA is only used
4162				 * after soft lifetime has been reached, see below (DYING state)
4163				 */
4164				if (sav->lft_c->usetime != 0)
4165					key_expire(sav);
4166			}
4167			/* check SOFT lifetime by bytes */
4168			/*
4169			 * XXX I don't know the way to delete this SA
4170			 * when new SA is installed.  Caution when it's
4171			 * installed too big lifetime by time.
4172			 */
4173			else if (sav->lft_s->bytes != 0 &&
4174			    sav->lft_s->bytes < sav->lft_c->bytes) {
4175
4176				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4177				/*
4178				 * XXX If we keep to send expire
4179				 * message in the status of
4180				 * DYING. Do remove below code.
4181				 */
4182				key_expire(sav);
4183			}
4184		}
4185
4186		/* check DYING entry to change status to DEAD. */
4187		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4188			/* we don't need to check. */
4189			if (sav->lft_h == NULL)
4190				continue;
4191
4192			/* sanity check */
4193			if (sav->lft_c == NULL) {
4194				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4195					"time, why?\n", __func__));
4196				continue;
4197			}
4198
4199			if (sav->lft_h->addtime != 0 &&
4200			    now - sav->created > sav->lft_h->addtime) {
4201				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4202				KEY_FREESAV(&sav);
4203			}
4204#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4205			else if (sav->lft_s != NULL
4206			      && sav->lft_s->addtime != 0
4207			      && now - sav->created > sav->lft_s->addtime) {
4208				/*
4209				 * XXX: should be checked to be
4210				 * installed the valid SA.
4211				 */
4212
4213				/*
4214				 * If there is no SA then sending
4215				 * expire message.
4216				 */
4217				key_expire(sav);
4218			}
4219#endif
4220			/* check HARD lifetime by bytes */
4221			else if (sav->lft_h->bytes != 0 &&
4222			    sav->lft_h->bytes < sav->lft_c->bytes) {
4223				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4224				KEY_FREESAV(&sav);
4225			}
4226		}
4227
4228		/* delete entry in DEAD */
4229		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4230			/* sanity check */
4231			if (sav->state != SADB_SASTATE_DEAD) {
4232				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4233					"(queue: %d SA: %d): kill it anyway\n",
4234					__func__,
4235					SADB_SASTATE_DEAD, sav->state));
4236			}
4237			/*
4238			 * do not call key_freesav() here.
4239			 * sav should already be freed, and sav->refcnt
4240			 * shows other references to sav
4241			 * (such as from SPD).
4242			 */
4243		}
4244	}
4245	SAHTREE_UNLOCK();
4246}
4247
4248static void
4249key_flush_acq(time_t now)
4250{
4251	INIT_VNET_IPSEC(curvnet);
4252	struct secacq *acq, *nextacq;
4253
4254	/* ACQ tree */
4255	ACQ_LOCK();
4256	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4257		nextacq = LIST_NEXT(acq, chain);
4258		if (now - acq->created > V_key_blockacq_lifetime
4259		 && __LIST_CHAINED(acq)) {
4260			LIST_REMOVE(acq, chain);
4261			free(acq, M_IPSEC_SAQ);
4262		}
4263	}
4264	ACQ_UNLOCK();
4265}
4266
4267static void
4268key_flush_spacq(time_t now)
4269{
4270	INIT_VNET_IPSEC(curvnet);
4271	struct secspacq *acq, *nextacq;
4272
4273	/* SP ACQ tree */
4274	SPACQ_LOCK();
4275	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4276		nextacq = LIST_NEXT(acq, chain);
4277		if (now - acq->created > V_key_blockacq_lifetime
4278		 && __LIST_CHAINED(acq)) {
4279			LIST_REMOVE(acq, chain);
4280			free(acq, M_IPSEC_SAQ);
4281		}
4282	}
4283	SPACQ_UNLOCK();
4284}
4285
4286/*
4287 * time handler.
4288 * scanning SPD and SAD to check status for each entries,
4289 * and do to remove or to expire.
4290 * XXX: year 2038 problem may remain.
4291 */
4292void
4293key_timehandler(void)
4294{
4295	VNET_ITERATOR_DECL(vnet_iter);
4296	time_t now = time_second;
4297
4298	VNET_LIST_RLOCK();
4299	VNET_FOREACH(vnet_iter) {
4300		CURVNET_SET(vnet_iter);
4301		key_flush_spd(now);
4302		key_flush_sad(now);
4303		key_flush_acq(now);
4304		key_flush_spacq(now);
4305		CURVNET_RESTORE();
4306	}
4307	VNET_LIST_RUNLOCK();
4308
4309#ifndef IPSEC_DEBUG2
4310	/* do exchange to tick time !! */
4311	(void)timeout((void *)key_timehandler, (void *)0, hz);
4312#endif /* IPSEC_DEBUG2 */
4313}
4314
4315u_long
4316key_random()
4317{
4318	u_long value;
4319
4320	key_randomfill(&value, sizeof(value));
4321	return value;
4322}
4323
4324void
4325key_randomfill(p, l)
4326	void *p;
4327	size_t l;
4328{
4329	size_t n;
4330	u_long v;
4331	static int warn = 1;
4332
4333	n = 0;
4334	n = (size_t)read_random(p, (u_int)l);
4335	/* last resort */
4336	while (n < l) {
4337		v = random();
4338		bcopy(&v, (u_int8_t *)p + n,
4339		    l - n < sizeof(v) ? l - n : sizeof(v));
4340		n += sizeof(v);
4341
4342		if (warn) {
4343			printf("WARNING: pseudo-random number generator "
4344			    "used for IPsec processing\n");
4345			warn = 0;
4346		}
4347	}
4348}
4349
4350/*
4351 * map SADB_SATYPE_* to IPPROTO_*.
4352 * if satype == SADB_SATYPE then satype is mapped to ~0.
4353 * OUT:
4354 *	0: invalid satype.
4355 */
4356static u_int16_t
4357key_satype2proto(u_int8_t satype)
4358{
4359	switch (satype) {
4360	case SADB_SATYPE_UNSPEC:
4361		return IPSEC_PROTO_ANY;
4362	case SADB_SATYPE_AH:
4363		return IPPROTO_AH;
4364	case SADB_SATYPE_ESP:
4365		return IPPROTO_ESP;
4366	case SADB_X_SATYPE_IPCOMP:
4367		return IPPROTO_IPCOMP;
4368	case SADB_X_SATYPE_TCPSIGNATURE:
4369		return IPPROTO_TCP;
4370	default:
4371		return 0;
4372	}
4373	/* NOTREACHED */
4374}
4375
4376/*
4377 * map IPPROTO_* to SADB_SATYPE_*
4378 * OUT:
4379 *	0: invalid protocol type.
4380 */
4381static u_int8_t
4382key_proto2satype(u_int16_t proto)
4383{
4384	switch (proto) {
4385	case IPPROTO_AH:
4386		return SADB_SATYPE_AH;
4387	case IPPROTO_ESP:
4388		return SADB_SATYPE_ESP;
4389	case IPPROTO_IPCOMP:
4390		return SADB_X_SATYPE_IPCOMP;
4391	case IPPROTO_TCP:
4392		return SADB_X_SATYPE_TCPSIGNATURE;
4393	default:
4394		return 0;
4395	}
4396	/* NOTREACHED */
4397}
4398
4399/* %%% PF_KEY */
4400/*
4401 * SADB_GETSPI processing is to receive
4402 *	<base, (SA2), src address, dst address, (SPI range)>
4403 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4404 * tree with the status of LARVAL, and send
4405 *	<base, SA(*), address(SD)>
4406 * to the IKMPd.
4407 *
4408 * IN:	mhp: pointer to the pointer to each header.
4409 * OUT:	NULL if fail.
4410 *	other if success, return pointer to the message to send.
4411 */
4412static int
4413key_getspi(so, m, mhp)
4414	struct socket *so;
4415	struct mbuf *m;
4416	const struct sadb_msghdr *mhp;
4417{
4418	INIT_VNET_IPSEC(curvnet);
4419	struct sadb_address *src0, *dst0;
4420	struct secasindex saidx;
4421	struct secashead *newsah;
4422	struct secasvar *newsav;
4423	u_int8_t proto;
4424	u_int32_t spi;
4425	u_int8_t mode;
4426	u_int32_t reqid;
4427	int error;
4428
4429	IPSEC_ASSERT(so != NULL, ("null socket"));
4430	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4431	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4432	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4433
4434	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4435	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4436		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4437			__func__));
4438		return key_senderror(so, m, EINVAL);
4439	}
4440	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4441	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4442		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4443			__func__));
4444		return key_senderror(so, m, EINVAL);
4445	}
4446	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4447		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4448		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4449	} else {
4450		mode = IPSEC_MODE_ANY;
4451		reqid = 0;
4452	}
4453
4454	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4455	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4456
4457	/* map satype to proto */
4458	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4459		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4460			__func__));
4461		return key_senderror(so, m, EINVAL);
4462	}
4463
4464	/* make sure if port number is zero. */
4465	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4466	case AF_INET:
4467		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4468		    sizeof(struct sockaddr_in))
4469			return key_senderror(so, m, EINVAL);
4470		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4471		break;
4472	case AF_INET6:
4473		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4474		    sizeof(struct sockaddr_in6))
4475			return key_senderror(so, m, EINVAL);
4476		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4477		break;
4478	default:
4479		; /*???*/
4480	}
4481	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4482	case AF_INET:
4483		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4484		    sizeof(struct sockaddr_in))
4485			return key_senderror(so, m, EINVAL);
4486		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4487		break;
4488	case AF_INET6:
4489		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4490		    sizeof(struct sockaddr_in6))
4491			return key_senderror(so, m, EINVAL);
4492		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4493		break;
4494	default:
4495		; /*???*/
4496	}
4497
4498	/* XXX boundary check against sa_len */
4499	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4500
4501	/* SPI allocation */
4502	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4503	                       &saidx);
4504	if (spi == 0)
4505		return key_senderror(so, m, EINVAL);
4506
4507	/* get a SA index */
4508	if ((newsah = key_getsah(&saidx)) == NULL) {
4509		/* create a new SA index */
4510		if ((newsah = key_newsah(&saidx)) == NULL) {
4511			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4512			return key_senderror(so, m, ENOBUFS);
4513		}
4514	}
4515
4516	/* get a new SA */
4517	/* XXX rewrite */
4518	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4519	if (newsav == NULL) {
4520		/* XXX don't free new SA index allocated in above. */
4521		return key_senderror(so, m, error);
4522	}
4523
4524	/* set spi */
4525	newsav->spi = htonl(spi);
4526
4527	/* delete the entry in acqtree */
4528	if (mhp->msg->sadb_msg_seq != 0) {
4529		struct secacq *acq;
4530		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4531			/* reset counter in order to deletion by timehandler. */
4532			acq->created = time_second;
4533			acq->count = 0;
4534		}
4535    	}
4536
4537    {
4538	struct mbuf *n, *nn;
4539	struct sadb_sa *m_sa;
4540	struct sadb_msg *newmsg;
4541	int off, len;
4542
4543	/* create new sadb_msg to reply. */
4544	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4545	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4546
4547	MGETHDR(n, M_DONTWAIT, MT_DATA);
4548	if (len > MHLEN) {
4549		MCLGET(n, M_DONTWAIT);
4550		if ((n->m_flags & M_EXT) == 0) {
4551			m_freem(n);
4552			n = NULL;
4553		}
4554	}
4555	if (!n)
4556		return key_senderror(so, m, ENOBUFS);
4557
4558	n->m_len = len;
4559	n->m_next = NULL;
4560	off = 0;
4561
4562	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4563	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4564
4565	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4566	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4567	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4568	m_sa->sadb_sa_spi = htonl(spi);
4569	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4570
4571	IPSEC_ASSERT(off == len,
4572		("length inconsistency (off %u len %u)", off, len));
4573
4574	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4575	    SADB_EXT_ADDRESS_DST);
4576	if (!n->m_next) {
4577		m_freem(n);
4578		return key_senderror(so, m, ENOBUFS);
4579	}
4580
4581	if (n->m_len < sizeof(struct sadb_msg)) {
4582		n = m_pullup(n, sizeof(struct sadb_msg));
4583		if (n == NULL)
4584			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4585	}
4586
4587	n->m_pkthdr.len = 0;
4588	for (nn = n; nn; nn = nn->m_next)
4589		n->m_pkthdr.len += nn->m_len;
4590
4591	newmsg = mtod(n, struct sadb_msg *);
4592	newmsg->sadb_msg_seq = newsav->seq;
4593	newmsg->sadb_msg_errno = 0;
4594	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4595
4596	m_freem(m);
4597	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4598    }
4599}
4600
4601/*
4602 * allocating new SPI
4603 * called by key_getspi().
4604 * OUT:
4605 *	0:	failure.
4606 *	others: success.
4607 */
4608static u_int32_t
4609key_do_getnewspi(spirange, saidx)
4610	struct sadb_spirange *spirange;
4611	struct secasindex *saidx;
4612{
4613	INIT_VNET_IPSEC(curvnet);
4614	u_int32_t newspi;
4615	u_int32_t min, max;
4616	int count = V_key_spi_trycnt;
4617
4618	/* set spi range to allocate */
4619	if (spirange != NULL) {
4620		min = spirange->sadb_spirange_min;
4621		max = spirange->sadb_spirange_max;
4622	} else {
4623		min = V_key_spi_minval;
4624		max = V_key_spi_maxval;
4625	}
4626	/* IPCOMP needs 2-byte SPI */
4627	if (saidx->proto == IPPROTO_IPCOMP) {
4628		u_int32_t t;
4629		if (min >= 0x10000)
4630			min = 0xffff;
4631		if (max >= 0x10000)
4632			max = 0xffff;
4633		if (min > max) {
4634			t = min; min = max; max = t;
4635		}
4636	}
4637
4638	if (min == max) {
4639		if (key_checkspidup(saidx, min) != NULL) {
4640			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4641				__func__, min));
4642			return 0;
4643		}
4644
4645		count--; /* taking one cost. */
4646		newspi = min;
4647
4648	} else {
4649
4650		/* init SPI */
4651		newspi = 0;
4652
4653		/* when requesting to allocate spi ranged */
4654		while (count--) {
4655			/* generate pseudo-random SPI value ranged. */
4656			newspi = min + (key_random() % (max - min + 1));
4657
4658			if (key_checkspidup(saidx, newspi) == NULL)
4659				break;
4660		}
4661
4662		if (count == 0 || newspi == 0) {
4663			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4664				__func__));
4665			return 0;
4666		}
4667	}
4668
4669	/* statistics */
4670	keystat.getspi_count =
4671		(keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4672
4673	return newspi;
4674}
4675
4676/*
4677 * SADB_UPDATE processing
4678 * receive
4679 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4680 *       key(AE), (identity(SD),) (sensitivity)>
4681 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4682 * and send
4683 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4684 *       (identity(SD),) (sensitivity)>
4685 * to the ikmpd.
4686 *
4687 * m will always be freed.
4688 */
4689static int
4690key_update(so, m, mhp)
4691	struct socket *so;
4692	struct mbuf *m;
4693	const struct sadb_msghdr *mhp;
4694{
4695	INIT_VNET_IPSEC(curvnet);
4696	struct sadb_sa *sa0;
4697	struct sadb_address *src0, *dst0;
4698	struct secasindex saidx;
4699	struct secashead *sah;
4700	struct secasvar *sav;
4701	u_int16_t proto;
4702	u_int8_t mode;
4703	u_int32_t reqid;
4704	int error;
4705
4706	IPSEC_ASSERT(so != NULL, ("null socket"));
4707	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4708	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4709	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4710
4711	/* map satype to proto */
4712	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4713		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4714			__func__));
4715		return key_senderror(so, m, EINVAL);
4716	}
4717
4718	if (mhp->ext[SADB_EXT_SA] == NULL ||
4719	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4720	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4721	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4722	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4723	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4724	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4725	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4726	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4727	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4728	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4729		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4730			__func__));
4731		return key_senderror(so, m, EINVAL);
4732	}
4733	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4734	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4735	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4736		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4737			__func__));
4738		return key_senderror(so, m, EINVAL);
4739	}
4740	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4741		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4742		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4743	} else {
4744		mode = IPSEC_MODE_ANY;
4745		reqid = 0;
4746	}
4747	/* XXX boundary checking for other extensions */
4748
4749	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4750	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4751	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4752
4753	/* XXX boundary check against sa_len */
4754	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4755
4756	/* get a SA header */
4757	if ((sah = key_getsah(&saidx)) == NULL) {
4758		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
4759		return key_senderror(so, m, ENOENT);
4760	}
4761
4762	/* set spidx if there */
4763	/* XXX rewrite */
4764	error = key_setident(sah, m, mhp);
4765	if (error)
4766		return key_senderror(so, m, error);
4767
4768	/* find a SA with sequence number. */
4769#ifdef IPSEC_DOSEQCHECK
4770	if (mhp->msg->sadb_msg_seq != 0
4771	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4772		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
4773			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
4774		return key_senderror(so, m, ENOENT);
4775	}
4776#else
4777	SAHTREE_LOCK();
4778	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4779	SAHTREE_UNLOCK();
4780	if (sav == NULL) {
4781		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
4782			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4783		return key_senderror(so, m, EINVAL);
4784	}
4785#endif
4786
4787	/* validity check */
4788	if (sav->sah->saidx.proto != proto) {
4789		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
4790			"(DB=%u param=%u)\n", __func__,
4791			sav->sah->saidx.proto, proto));
4792		return key_senderror(so, m, EINVAL);
4793	}
4794#ifdef IPSEC_DOSEQCHECK
4795	if (sav->spi != sa0->sadb_sa_spi) {
4796		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
4797		    __func__,
4798		    (u_int32_t)ntohl(sav->spi),
4799		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4800		return key_senderror(so, m, EINVAL);
4801	}
4802#endif
4803	if (sav->pid != mhp->msg->sadb_msg_pid) {
4804		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
4805		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
4806		return key_senderror(so, m, EINVAL);
4807	}
4808
4809	/* copy sav values */
4810	error = key_setsaval(sav, m, mhp);
4811	if (error) {
4812		KEY_FREESAV(&sav);
4813		return key_senderror(so, m, error);
4814	}
4815
4816	/* check SA values to be mature. */
4817	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4818		KEY_FREESAV(&sav);
4819		return key_senderror(so, m, 0);
4820	}
4821
4822    {
4823	struct mbuf *n;
4824
4825	/* set msg buf from mhp */
4826	n = key_getmsgbuf_x1(m, mhp);
4827	if (n == NULL) {
4828		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4829		return key_senderror(so, m, ENOBUFS);
4830	}
4831
4832	m_freem(m);
4833	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4834    }
4835}
4836
4837/*
4838 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4839 * only called by key_update().
4840 * OUT:
4841 *	NULL	: not found
4842 *	others	: found, pointer to a SA.
4843 */
4844#ifdef IPSEC_DOSEQCHECK
4845static struct secasvar *
4846key_getsavbyseq(sah, seq)
4847	struct secashead *sah;
4848	u_int32_t seq;
4849{
4850	struct secasvar *sav;
4851	u_int state;
4852
4853	state = SADB_SASTATE_LARVAL;
4854
4855	/* search SAD with sequence number ? */
4856	LIST_FOREACH(sav, &sah->savtree[state], chain) {
4857
4858		KEY_CHKSASTATE(state, sav->state, __func__);
4859
4860		if (sav->seq == seq) {
4861			sa_addref(sav);
4862			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4863				printf("DP %s cause refcnt++:%d SA:%p\n",
4864					__func__, sav->refcnt, sav));
4865			return sav;
4866		}
4867	}
4868
4869	return NULL;
4870}
4871#endif
4872
4873/*
4874 * SADB_ADD processing
4875 * add an entry to SA database, when received
4876 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4877 *       key(AE), (identity(SD),) (sensitivity)>
4878 * from the ikmpd,
4879 * and send
4880 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4881 *       (identity(SD),) (sensitivity)>
4882 * to the ikmpd.
4883 *
4884 * IGNORE identity and sensitivity messages.
4885 *
4886 * m will always be freed.
4887 */
4888static int
4889key_add(so, m, mhp)
4890	struct socket *so;
4891	struct mbuf *m;
4892	const struct sadb_msghdr *mhp;
4893{
4894	INIT_VNET_IPSEC(curvnet);
4895	struct sadb_sa *sa0;
4896	struct sadb_address *src0, *dst0;
4897	struct secasindex saidx;
4898	struct secashead *newsah;
4899	struct secasvar *newsav;
4900	u_int16_t proto;
4901	u_int8_t mode;
4902	u_int32_t reqid;
4903	int error;
4904
4905	IPSEC_ASSERT(so != NULL, ("null socket"));
4906	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4907	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4908	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4909
4910	/* map satype to proto */
4911	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4912		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4913			__func__));
4914		return key_senderror(so, m, EINVAL);
4915	}
4916
4917	if (mhp->ext[SADB_EXT_SA] == NULL ||
4918	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4919	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4920	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4921	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4922	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4923	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4924	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4925	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4926	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4927	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4928		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4929			__func__));
4930		return key_senderror(so, m, EINVAL);
4931	}
4932	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4933	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4934	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4935		/* XXX need more */
4936		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4937			__func__));
4938		return key_senderror(so, m, EINVAL);
4939	}
4940	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4941		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4942		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4943	} else {
4944		mode = IPSEC_MODE_ANY;
4945		reqid = 0;
4946	}
4947
4948	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4949	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4950	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4951
4952	/* XXX boundary check against sa_len */
4953	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4954
4955	/* get a SA header */
4956	if ((newsah = key_getsah(&saidx)) == NULL) {
4957		/* create a new SA header */
4958		if ((newsah = key_newsah(&saidx)) == NULL) {
4959			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4960			return key_senderror(so, m, ENOBUFS);
4961		}
4962	}
4963
4964	/* set spidx if there */
4965	/* XXX rewrite */
4966	error = key_setident(newsah, m, mhp);
4967	if (error) {
4968		return key_senderror(so, m, error);
4969	}
4970
4971	/* create new SA entry. */
4972	/* We can create new SA only if SPI is differenct. */
4973	SAHTREE_LOCK();
4974	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
4975	SAHTREE_UNLOCK();
4976	if (newsav != NULL) {
4977		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
4978		return key_senderror(so, m, EEXIST);
4979	}
4980	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4981	if (newsav == NULL) {
4982		return key_senderror(so, m, error);
4983	}
4984
4985	/* check SA values to be mature. */
4986	if ((error = key_mature(newsav)) != 0) {
4987		KEY_FREESAV(&newsav);
4988		return key_senderror(so, m, error);
4989	}
4990
4991	/*
4992	 * don't call key_freesav() here, as we would like to keep the SA
4993	 * in the database on success.
4994	 */
4995
4996    {
4997	struct mbuf *n;
4998
4999	/* set msg buf from mhp */
5000	n = key_getmsgbuf_x1(m, mhp);
5001	if (n == NULL) {
5002		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5003		return key_senderror(so, m, ENOBUFS);
5004	}
5005
5006	m_freem(m);
5007	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5008    }
5009}
5010
5011/* m is retained */
5012static int
5013key_setident(sah, m, mhp)
5014	struct secashead *sah;
5015	struct mbuf *m;
5016	const struct sadb_msghdr *mhp;
5017{
5018	INIT_VNET_IPSEC(curvnet);
5019	const struct sadb_ident *idsrc, *iddst;
5020	int idsrclen, iddstlen;
5021
5022	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5023	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5024	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5025	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5026
5027	/* don't make buffer if not there */
5028	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5029	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5030		sah->idents = NULL;
5031		sah->identd = NULL;
5032		return 0;
5033	}
5034
5035	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5036	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5037		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5038		return EINVAL;
5039	}
5040
5041	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5042	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5043	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5044	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5045
5046	/* validity check */
5047	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5048		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5049		return EINVAL;
5050	}
5051
5052	switch (idsrc->sadb_ident_type) {
5053	case SADB_IDENTTYPE_PREFIX:
5054	case SADB_IDENTTYPE_FQDN:
5055	case SADB_IDENTTYPE_USERFQDN:
5056	default:
5057		/* XXX do nothing */
5058		sah->idents = NULL;
5059		sah->identd = NULL;
5060	 	return 0;
5061	}
5062
5063	/* make structure */
5064	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5065	if (sah->idents == NULL) {
5066		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5067		return ENOBUFS;
5068	}
5069	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5070	if (sah->identd == NULL) {
5071		free(sah->idents, M_IPSEC_MISC);
5072		sah->idents = NULL;
5073		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5074		return ENOBUFS;
5075	}
5076	sah->idents->type = idsrc->sadb_ident_type;
5077	sah->idents->id = idsrc->sadb_ident_id;
5078
5079	sah->identd->type = iddst->sadb_ident_type;
5080	sah->identd->id = iddst->sadb_ident_id;
5081
5082	return 0;
5083}
5084
5085/*
5086 * m will not be freed on return.
5087 * it is caller's responsibility to free the result.
5088 */
5089static struct mbuf *
5090key_getmsgbuf_x1(m, mhp)
5091	struct mbuf *m;
5092	const struct sadb_msghdr *mhp;
5093{
5094	struct mbuf *n;
5095
5096	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5097	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5098	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5099
5100	/* create new sadb_msg to reply. */
5101	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5102	    SADB_EXT_SA, SADB_X_EXT_SA2,
5103	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5104	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5105	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5106	if (!n)
5107		return NULL;
5108
5109	if (n->m_len < sizeof(struct sadb_msg)) {
5110		n = m_pullup(n, sizeof(struct sadb_msg));
5111		if (n == NULL)
5112			return NULL;
5113	}
5114	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5115	mtod(n, struct sadb_msg *)->sadb_msg_len =
5116	    PFKEY_UNIT64(n->m_pkthdr.len);
5117
5118	return n;
5119}
5120
5121static int key_delete_all __P((struct socket *, struct mbuf *,
5122	const struct sadb_msghdr *, u_int16_t));
5123
5124/*
5125 * SADB_DELETE processing
5126 * receive
5127 *   <base, SA(*), address(SD)>
5128 * from the ikmpd, and set SADB_SASTATE_DEAD,
5129 * and send,
5130 *   <base, SA(*), address(SD)>
5131 * to the ikmpd.
5132 *
5133 * m will always be freed.
5134 */
5135static int
5136key_delete(so, m, mhp)
5137	struct socket *so;
5138	struct mbuf *m;
5139	const struct sadb_msghdr *mhp;
5140{
5141	INIT_VNET_IPSEC(curvnet);
5142	struct sadb_sa *sa0;
5143	struct sadb_address *src0, *dst0;
5144	struct secasindex saidx;
5145	struct secashead *sah;
5146	struct secasvar *sav = NULL;
5147	u_int16_t proto;
5148
5149	IPSEC_ASSERT(so != NULL, ("null socket"));
5150	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5151	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5152	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5153
5154	/* map satype to proto */
5155	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5156		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5157			__func__));
5158		return key_senderror(so, m, EINVAL);
5159	}
5160
5161	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5162	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5163		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5164			__func__));
5165		return key_senderror(so, m, EINVAL);
5166	}
5167
5168	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5169	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5170		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5171			__func__));
5172		return key_senderror(so, m, EINVAL);
5173	}
5174
5175	if (mhp->ext[SADB_EXT_SA] == NULL) {
5176		/*
5177		 * Caller wants us to delete all non-LARVAL SAs
5178		 * that match the src/dst.  This is used during
5179		 * IKE INITIAL-CONTACT.
5180		 */
5181		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5182		return key_delete_all(so, m, mhp, proto);
5183	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5184		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5185			__func__));
5186		return key_senderror(so, m, EINVAL);
5187	}
5188
5189	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5190	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5191	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5192
5193	/* XXX boundary check against sa_len */
5194	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5195
5196	/* get a SA header */
5197	SAHTREE_LOCK();
5198	LIST_FOREACH(sah, &V_sahtree, chain) {
5199		if (sah->state == SADB_SASTATE_DEAD)
5200			continue;
5201		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5202			continue;
5203
5204		/* get a SA with SPI. */
5205		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5206		if (sav)
5207			break;
5208	}
5209	if (sah == NULL) {
5210		SAHTREE_UNLOCK();
5211		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5212		return key_senderror(so, m, ENOENT);
5213	}
5214
5215	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5216	SAHTREE_UNLOCK();
5217	KEY_FREESAV(&sav);
5218
5219    {
5220	struct mbuf *n;
5221	struct sadb_msg *newmsg;
5222
5223	/* create new sadb_msg to reply. */
5224	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5225	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5226	if (!n)
5227		return key_senderror(so, m, ENOBUFS);
5228
5229	if (n->m_len < sizeof(struct sadb_msg)) {
5230		n = m_pullup(n, sizeof(struct sadb_msg));
5231		if (n == NULL)
5232			return key_senderror(so, m, ENOBUFS);
5233	}
5234	newmsg = mtod(n, struct sadb_msg *);
5235	newmsg->sadb_msg_errno = 0;
5236	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5237
5238	m_freem(m);
5239	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5240    }
5241}
5242
5243/*
5244 * delete all SAs for src/dst.  Called from key_delete().
5245 */
5246static int
5247key_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5248    u_int16_t proto)
5249{
5250	INIT_VNET_IPSEC(curvnet);
5251	struct sadb_address *src0, *dst0;
5252	struct secasindex saidx;
5253	struct secashead *sah;
5254	struct secasvar *sav, *nextsav;
5255	u_int stateidx, state;
5256
5257	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5258	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5259
5260	/* XXX boundary check against sa_len */
5261	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5262
5263	SAHTREE_LOCK();
5264	LIST_FOREACH(sah, &V_sahtree, chain) {
5265		if (sah->state == SADB_SASTATE_DEAD)
5266			continue;
5267		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5268			continue;
5269
5270		/* Delete all non-LARVAL SAs. */
5271		for (stateidx = 0;
5272		     stateidx < _ARRAYLEN(saorder_state_alive);
5273		     stateidx++) {
5274			state = saorder_state_alive[stateidx];
5275			if (state == SADB_SASTATE_LARVAL)
5276				continue;
5277			for (sav = LIST_FIRST(&sah->savtree[state]);
5278			     sav != NULL; sav = nextsav) {
5279				nextsav = LIST_NEXT(sav, chain);
5280				/* sanity check */
5281				if (sav->state != state) {
5282					ipseclog((LOG_DEBUG, "%s: invalid "
5283						"sav->state (queue %d SA %d)\n",
5284						__func__, state, sav->state));
5285					continue;
5286				}
5287
5288				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5289				KEY_FREESAV(&sav);
5290			}
5291		}
5292	}
5293	SAHTREE_UNLOCK();
5294    {
5295	struct mbuf *n;
5296	struct sadb_msg *newmsg;
5297
5298	/* create new sadb_msg to reply. */
5299	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5300	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5301	if (!n)
5302		return key_senderror(so, m, ENOBUFS);
5303
5304	if (n->m_len < sizeof(struct sadb_msg)) {
5305		n = m_pullup(n, sizeof(struct sadb_msg));
5306		if (n == NULL)
5307			return key_senderror(so, m, ENOBUFS);
5308	}
5309	newmsg = mtod(n, struct sadb_msg *);
5310	newmsg->sadb_msg_errno = 0;
5311	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5312
5313	m_freem(m);
5314	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5315    }
5316}
5317
5318/*
5319 * SADB_GET processing
5320 * receive
5321 *   <base, SA(*), address(SD)>
5322 * from the ikmpd, and get a SP and a SA to respond,
5323 * and send,
5324 *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5325 *       (identity(SD),) (sensitivity)>
5326 * to the ikmpd.
5327 *
5328 * m will always be freed.
5329 */
5330static int
5331key_get(so, m, mhp)
5332	struct socket *so;
5333	struct mbuf *m;
5334	const struct sadb_msghdr *mhp;
5335{
5336	INIT_VNET_IPSEC(curvnet);
5337	struct sadb_sa *sa0;
5338	struct sadb_address *src0, *dst0;
5339	struct secasindex saidx;
5340	struct secashead *sah;
5341	struct secasvar *sav = NULL;
5342	u_int16_t proto;
5343
5344	IPSEC_ASSERT(so != NULL, ("null socket"));
5345	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5346	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5347	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5348
5349	/* map satype to proto */
5350	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5351		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5352			__func__));
5353		return key_senderror(so, m, EINVAL);
5354	}
5355
5356	if (mhp->ext[SADB_EXT_SA] == NULL ||
5357	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5358	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5359		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5360			__func__));
5361		return key_senderror(so, m, EINVAL);
5362	}
5363	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5364	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5365	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5366		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5367			__func__));
5368		return key_senderror(so, m, EINVAL);
5369	}
5370
5371	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5372	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5373	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5374
5375	/* XXX boundary check against sa_len */
5376	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5377
5378	/* get a SA header */
5379	SAHTREE_LOCK();
5380	LIST_FOREACH(sah, &V_sahtree, chain) {
5381		if (sah->state == SADB_SASTATE_DEAD)
5382			continue;
5383		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5384			continue;
5385
5386		/* get a SA with SPI. */
5387		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5388		if (sav)
5389			break;
5390	}
5391	SAHTREE_UNLOCK();
5392	if (sah == NULL) {
5393		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5394		return key_senderror(so, m, ENOENT);
5395	}
5396
5397    {
5398	struct mbuf *n;
5399	u_int8_t satype;
5400
5401	/* map proto to satype */
5402	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5403		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5404			__func__));
5405		return key_senderror(so, m, EINVAL);
5406	}
5407
5408	/* create new sadb_msg to reply. */
5409	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5410	    mhp->msg->sadb_msg_pid);
5411	if (!n)
5412		return key_senderror(so, m, ENOBUFS);
5413
5414	m_freem(m);
5415	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5416    }
5417}
5418
5419/* XXX make it sysctl-configurable? */
5420static void
5421key_getcomb_setlifetime(comb)
5422	struct sadb_comb *comb;
5423{
5424
5425	comb->sadb_comb_soft_allocations = 1;
5426	comb->sadb_comb_hard_allocations = 1;
5427	comb->sadb_comb_soft_bytes = 0;
5428	comb->sadb_comb_hard_bytes = 0;
5429	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5430	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5431	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5432	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5433}
5434
5435/*
5436 * XXX reorder combinations by preference
5437 * XXX no idea if the user wants ESP authentication or not
5438 */
5439static struct mbuf *
5440key_getcomb_esp()
5441{
5442	INIT_VNET_IPSEC(curvnet);
5443	struct sadb_comb *comb;
5444	struct enc_xform *algo;
5445	struct mbuf *result = NULL, *m, *n;
5446	int encmin;
5447	int i, off, o;
5448	int totlen;
5449	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5450
5451	m = NULL;
5452	for (i = 1; i <= SADB_EALG_MAX; i++) {
5453		algo = esp_algorithm_lookup(i);
5454		if (algo == NULL)
5455			continue;
5456
5457		/* discard algorithms with key size smaller than system min */
5458		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
5459			continue;
5460		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
5461			encmin = V_ipsec_esp_keymin;
5462		else
5463			encmin = _BITS(algo->minkey);
5464
5465		if (V_ipsec_esp_auth)
5466			m = key_getcomb_ah();
5467		else {
5468			IPSEC_ASSERT(l <= MLEN,
5469				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5470			MGET(m, M_DONTWAIT, MT_DATA);
5471			if (m) {
5472				M_ALIGN(m, l);
5473				m->m_len = l;
5474				m->m_next = NULL;
5475				bzero(mtod(m, caddr_t), m->m_len);
5476			}
5477		}
5478		if (!m)
5479			goto fail;
5480
5481		totlen = 0;
5482		for (n = m; n; n = n->m_next)
5483			totlen += n->m_len;
5484		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
5485
5486		for (off = 0; off < totlen; off += l) {
5487			n = m_pulldown(m, off, l, &o);
5488			if (!n) {
5489				/* m is already freed */
5490				goto fail;
5491			}
5492			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5493			bzero(comb, sizeof(*comb));
5494			key_getcomb_setlifetime(comb);
5495			comb->sadb_comb_encrypt = i;
5496			comb->sadb_comb_encrypt_minbits = encmin;
5497			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5498		}
5499
5500		if (!result)
5501			result = m;
5502		else
5503			m_cat(result, m);
5504	}
5505
5506	return result;
5507
5508 fail:
5509	if (result)
5510		m_freem(result);
5511	return NULL;
5512}
5513
5514static void
5515key_getsizes_ah(
5516	const struct auth_hash *ah,
5517	int alg,
5518	u_int16_t* min,
5519	u_int16_t* max)
5520{
5521	INIT_VNET_IPSEC(curvnet);
5522
5523	*min = *max = ah->keysize;
5524	if (ah->keysize == 0) {
5525		/*
5526		 * Transform takes arbitrary key size but algorithm
5527		 * key size is restricted.  Enforce this here.
5528		 */
5529		switch (alg) {
5530		case SADB_X_AALG_MD5:	*min = *max = 16; break;
5531		case SADB_X_AALG_SHA:	*min = *max = 20; break;
5532		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
5533		default:
5534			DPRINTF(("%s: unknown AH algorithm %u\n",
5535				__func__, alg));
5536			break;
5537		}
5538	}
5539}
5540
5541/*
5542 * XXX reorder combinations by preference
5543 */
5544static struct mbuf *
5545key_getcomb_ah()
5546{
5547	INIT_VNET_IPSEC(curvnet);
5548	struct sadb_comb *comb;
5549	struct auth_hash *algo;
5550	struct mbuf *m;
5551	u_int16_t minkeysize, maxkeysize;
5552	int i;
5553	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5554
5555	m = NULL;
5556	for (i = 1; i <= SADB_AALG_MAX; i++) {
5557#if 1
5558		/* we prefer HMAC algorithms, not old algorithms */
5559		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5560			continue;
5561#endif
5562		algo = ah_algorithm_lookup(i);
5563		if (!algo)
5564			continue;
5565		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5566		/* discard algorithms with key size smaller than system min */
5567		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
5568			continue;
5569
5570		if (!m) {
5571			IPSEC_ASSERT(l <= MLEN,
5572				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5573			MGET(m, M_DONTWAIT, MT_DATA);
5574			if (m) {
5575				M_ALIGN(m, l);
5576				m->m_len = l;
5577				m->m_next = NULL;
5578			}
5579		} else
5580			M_PREPEND(m, l, M_DONTWAIT);
5581		if (!m)
5582			return NULL;
5583
5584		comb = mtod(m, struct sadb_comb *);
5585		bzero(comb, sizeof(*comb));
5586		key_getcomb_setlifetime(comb);
5587		comb->sadb_comb_auth = i;
5588		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5589		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5590	}
5591
5592	return m;
5593}
5594
5595/*
5596 * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5597 * XXX reorder combinations by preference
5598 */
5599static struct mbuf *
5600key_getcomb_ipcomp()
5601{
5602	struct sadb_comb *comb;
5603	struct comp_algo *algo;
5604	struct mbuf *m;
5605	int i;
5606	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5607
5608	m = NULL;
5609	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5610		algo = ipcomp_algorithm_lookup(i);
5611		if (!algo)
5612			continue;
5613
5614		if (!m) {
5615			IPSEC_ASSERT(l <= MLEN,
5616				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5617			MGET(m, M_DONTWAIT, MT_DATA);
5618			if (m) {
5619				M_ALIGN(m, l);
5620				m->m_len = l;
5621				m->m_next = NULL;
5622			}
5623		} else
5624			M_PREPEND(m, l, M_DONTWAIT);
5625		if (!m)
5626			return NULL;
5627
5628		comb = mtod(m, struct sadb_comb *);
5629		bzero(comb, sizeof(*comb));
5630		key_getcomb_setlifetime(comb);
5631		comb->sadb_comb_encrypt = i;
5632		/* what should we set into sadb_comb_*_{min,max}bits? */
5633	}
5634
5635	return m;
5636}
5637
5638/*
5639 * XXX no way to pass mode (transport/tunnel) to userland
5640 * XXX replay checking?
5641 * XXX sysctl interface to ipsec_{ah,esp}_keymin
5642 */
5643static struct mbuf *
5644key_getprop(saidx)
5645	const struct secasindex *saidx;
5646{
5647	struct sadb_prop *prop;
5648	struct mbuf *m, *n;
5649	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5650	int totlen;
5651
5652	switch (saidx->proto)  {
5653	case IPPROTO_ESP:
5654		m = key_getcomb_esp();
5655		break;
5656	case IPPROTO_AH:
5657		m = key_getcomb_ah();
5658		break;
5659	case IPPROTO_IPCOMP:
5660		m = key_getcomb_ipcomp();
5661		break;
5662	default:
5663		return NULL;
5664	}
5665
5666	if (!m)
5667		return NULL;
5668	M_PREPEND(m, l, M_DONTWAIT);
5669	if (!m)
5670		return NULL;
5671
5672	totlen = 0;
5673	for (n = m; n; n = n->m_next)
5674		totlen += n->m_len;
5675
5676	prop = mtod(m, struct sadb_prop *);
5677	bzero(prop, sizeof(*prop));
5678	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5679	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5680	prop->sadb_prop_replay = 32;	/* XXX */
5681
5682	return m;
5683}
5684
5685/*
5686 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5687 * send
5688 *   <base, SA, address(SD), (address(P)), x_policy,
5689 *       (identity(SD),) (sensitivity,) proposal>
5690 * to KMD, and expect to receive
5691 *   <base> with SADB_ACQUIRE if error occured,
5692 * or
5693 *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5694 * from KMD by PF_KEY.
5695 *
5696 * XXX x_policy is outside of RFC2367 (KAME extension).
5697 * XXX sensitivity is not supported.
5698 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5699 * see comment for key_getcomb_ipcomp().
5700 *
5701 * OUT:
5702 *    0     : succeed
5703 *    others: error number
5704 */
5705static int
5706key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5707{
5708	INIT_VNET_IPSEC(curvnet);
5709	struct mbuf *result = NULL, *m;
5710	struct secacq *newacq;
5711	u_int8_t satype;
5712	int error = -1;
5713	u_int32_t seq;
5714
5715	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
5716	satype = key_proto2satype(saidx->proto);
5717	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
5718
5719	/*
5720	 * We never do anything about acquirng SA.  There is anather
5721	 * solution that kernel blocks to send SADB_ACQUIRE message until
5722	 * getting something message from IKEd.  In later case, to be
5723	 * managed with ACQUIRING list.
5724	 */
5725	/* Get an entry to check whether sending message or not. */
5726	if ((newacq = key_getacq(saidx)) != NULL) {
5727		if (V_key_blockacq_count < newacq->count) {
5728			/* reset counter and do send message. */
5729			newacq->count = 0;
5730		} else {
5731			/* increment counter and do nothing. */
5732			newacq->count++;
5733			return 0;
5734		}
5735	} else {
5736		/* make new entry for blocking to send SADB_ACQUIRE. */
5737		if ((newacq = key_newacq(saidx)) == NULL)
5738			return ENOBUFS;
5739	}
5740
5741
5742	seq = newacq->seq;
5743	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5744	if (!m) {
5745		error = ENOBUFS;
5746		goto fail;
5747	}
5748	result = m;
5749
5750	/* set sadb_address for saidx's. */
5751	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5752	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5753	if (!m) {
5754		error = ENOBUFS;
5755		goto fail;
5756	}
5757	m_cat(result, m);
5758
5759	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5760	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5761	if (!m) {
5762		error = ENOBUFS;
5763		goto fail;
5764	}
5765	m_cat(result, m);
5766
5767	/* XXX proxy address (optional) */
5768
5769	/* set sadb_x_policy */
5770	if (sp) {
5771		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5772		if (!m) {
5773			error = ENOBUFS;
5774			goto fail;
5775		}
5776		m_cat(result, m);
5777	}
5778
5779	/* XXX identity (optional) */
5780#if 0
5781	if (idexttype && fqdn) {
5782		/* create identity extension (FQDN) */
5783		struct sadb_ident *id;
5784		int fqdnlen;
5785
5786		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
5787		id = (struct sadb_ident *)p;
5788		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5789		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5790		id->sadb_ident_exttype = idexttype;
5791		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5792		bcopy(fqdn, id + 1, fqdnlen);
5793		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5794	}
5795
5796	if (idexttype) {
5797		/* create identity extension (USERFQDN) */
5798		struct sadb_ident *id;
5799		int userfqdnlen;
5800
5801		if (userfqdn) {
5802			/* +1 for terminating-NUL */
5803			userfqdnlen = strlen(userfqdn) + 1;
5804		} else
5805			userfqdnlen = 0;
5806		id = (struct sadb_ident *)p;
5807		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5808		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5809		id->sadb_ident_exttype = idexttype;
5810		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5811		/* XXX is it correct? */
5812		if (curproc && curproc->p_cred)
5813			id->sadb_ident_id = curproc->p_cred->p_ruid;
5814		if (userfqdn && userfqdnlen)
5815			bcopy(userfqdn, id + 1, userfqdnlen);
5816		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5817	}
5818#endif
5819
5820	/* XXX sensitivity (optional) */
5821
5822	/* create proposal/combination extension */
5823	m = key_getprop(saidx);
5824#if 0
5825	/*
5826	 * spec conformant: always attach proposal/combination extension,
5827	 * the problem is that we have no way to attach it for ipcomp,
5828	 * due to the way sadb_comb is declared in RFC2367.
5829	 */
5830	if (!m) {
5831		error = ENOBUFS;
5832		goto fail;
5833	}
5834	m_cat(result, m);
5835#else
5836	/*
5837	 * outside of spec; make proposal/combination extension optional.
5838	 */
5839	if (m)
5840		m_cat(result, m);
5841#endif
5842
5843	if ((result->m_flags & M_PKTHDR) == 0) {
5844		error = EINVAL;
5845		goto fail;
5846	}
5847
5848	if (result->m_len < sizeof(struct sadb_msg)) {
5849		result = m_pullup(result, sizeof(struct sadb_msg));
5850		if (result == NULL) {
5851			error = ENOBUFS;
5852			goto fail;
5853		}
5854	}
5855
5856	result->m_pkthdr.len = 0;
5857	for (m = result; m; m = m->m_next)
5858		result->m_pkthdr.len += m->m_len;
5859
5860	mtod(result, struct sadb_msg *)->sadb_msg_len =
5861	    PFKEY_UNIT64(result->m_pkthdr.len);
5862
5863	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5864
5865 fail:
5866	if (result)
5867		m_freem(result);
5868	return error;
5869}
5870
5871static struct secacq *
5872key_newacq(const struct secasindex *saidx)
5873{
5874	INIT_VNET_IPSEC(curvnet);
5875	struct secacq *newacq;
5876
5877	/* get new entry */
5878	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5879	if (newacq == NULL) {
5880		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5881		return NULL;
5882	}
5883
5884	/* copy secindex */
5885	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5886	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
5887	newacq->created = time_second;
5888	newacq->count = 0;
5889
5890	/* add to acqtree */
5891	ACQ_LOCK();
5892	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
5893	ACQ_UNLOCK();
5894
5895	return newacq;
5896}
5897
5898static struct secacq *
5899key_getacq(const struct secasindex *saidx)
5900{
5901	INIT_VNET_IPSEC(curvnet);
5902	struct secacq *acq;
5903
5904	ACQ_LOCK();
5905	LIST_FOREACH(acq, &V_acqtree, chain) {
5906		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5907			break;
5908	}
5909	ACQ_UNLOCK();
5910
5911	return acq;
5912}
5913
5914static struct secacq *
5915key_getacqbyseq(seq)
5916	u_int32_t seq;
5917{
5918	INIT_VNET_IPSEC(curvnet);
5919	struct secacq *acq;
5920
5921	ACQ_LOCK();
5922	LIST_FOREACH(acq, &V_acqtree, chain) {
5923		if (acq->seq == seq)
5924			break;
5925	}
5926	ACQ_UNLOCK();
5927
5928	return acq;
5929}
5930
5931static struct secspacq *
5932key_newspacq(spidx)
5933	struct secpolicyindex *spidx;
5934{
5935	INIT_VNET_IPSEC(curvnet);
5936	struct secspacq *acq;
5937
5938	/* get new entry */
5939	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5940	if (acq == NULL) {
5941		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5942		return NULL;
5943	}
5944
5945	/* copy secindex */
5946	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5947	acq->created = time_second;
5948	acq->count = 0;
5949
5950	/* add to spacqtree */
5951	SPACQ_LOCK();
5952	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
5953	SPACQ_UNLOCK();
5954
5955	return acq;
5956}
5957
5958static struct secspacq *
5959key_getspacq(spidx)
5960	struct secpolicyindex *spidx;
5961{
5962	INIT_VNET_IPSEC(curvnet);
5963	struct secspacq *acq;
5964
5965	SPACQ_LOCK();
5966	LIST_FOREACH(acq, &V_spacqtree, chain) {
5967		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
5968			/* NB: return holding spacq_lock */
5969			return acq;
5970		}
5971	}
5972	SPACQ_UNLOCK();
5973
5974	return NULL;
5975}
5976
5977/*
5978 * SADB_ACQUIRE processing,
5979 * in first situation, is receiving
5980 *   <base>
5981 * from the ikmpd, and clear sequence of its secasvar entry.
5982 *
5983 * In second situation, is receiving
5984 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5985 * from a user land process, and return
5986 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5987 * to the socket.
5988 *
5989 * m will always be freed.
5990 */
5991static int
5992key_acquire2(so, m, mhp)
5993	struct socket *so;
5994	struct mbuf *m;
5995	const struct sadb_msghdr *mhp;
5996{
5997	INIT_VNET_IPSEC(curvnet);
5998	const struct sadb_address *src0, *dst0;
5999	struct secasindex saidx;
6000	struct secashead *sah;
6001	u_int16_t proto;
6002	int error;
6003
6004	IPSEC_ASSERT(so != NULL, ("null socket"));
6005	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6006	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6007	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6008
6009	/*
6010	 * Error message from KMd.
6011	 * We assume that if error was occured in IKEd, the length of PFKEY
6012	 * message is equal to the size of sadb_msg structure.
6013	 * We do not raise error even if error occured in this function.
6014	 */
6015	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6016		struct secacq *acq;
6017
6018		/* check sequence number */
6019		if (mhp->msg->sadb_msg_seq == 0) {
6020			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6021				"number.\n", __func__));
6022			m_freem(m);
6023			return 0;
6024		}
6025
6026		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6027			/*
6028			 * the specified larval SA is already gone, or we got
6029			 * a bogus sequence number.  we can silently ignore it.
6030			 */
6031			m_freem(m);
6032			return 0;
6033		}
6034
6035		/* reset acq counter in order to deletion by timehander. */
6036		acq->created = time_second;
6037		acq->count = 0;
6038		m_freem(m);
6039		return 0;
6040	}
6041
6042	/*
6043	 * This message is from user land.
6044	 */
6045
6046	/* map satype to proto */
6047	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6048		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6049			__func__));
6050		return key_senderror(so, m, EINVAL);
6051	}
6052
6053	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6054	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6055	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6056		/* error */
6057		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6058			__func__));
6059		return key_senderror(so, m, EINVAL);
6060	}
6061	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6062	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6063	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6064		/* error */
6065		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6066			__func__));
6067		return key_senderror(so, m, EINVAL);
6068	}
6069
6070	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6071	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6072
6073	/* XXX boundary check against sa_len */
6074	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6075
6076	/* get a SA index */
6077	SAHTREE_LOCK();
6078	LIST_FOREACH(sah, &V_sahtree, chain) {
6079		if (sah->state == SADB_SASTATE_DEAD)
6080			continue;
6081		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6082			break;
6083	}
6084	SAHTREE_UNLOCK();
6085	if (sah != NULL) {
6086		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6087		return key_senderror(so, m, EEXIST);
6088	}
6089
6090	error = key_acquire(&saidx, NULL);
6091	if (error != 0) {
6092		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6093			__func__, mhp->msg->sadb_msg_errno));
6094		return key_senderror(so, m, error);
6095	}
6096
6097	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6098}
6099
6100/*
6101 * SADB_REGISTER processing.
6102 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6103 * receive
6104 *   <base>
6105 * from the ikmpd, and register a socket to send PF_KEY messages,
6106 * and send
6107 *   <base, supported>
6108 * to KMD by PF_KEY.
6109 * If socket is detached, must free from regnode.
6110 *
6111 * m will always be freed.
6112 */
6113static int
6114key_register(so, m, mhp)
6115	struct socket *so;
6116	struct mbuf *m;
6117	const struct sadb_msghdr *mhp;
6118{
6119	INIT_VNET_IPSEC(curvnet);
6120	struct secreg *reg, *newreg = 0;
6121
6122	IPSEC_ASSERT(so != NULL, ("null socket"));
6123	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6124	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6125	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6126
6127	/* check for invalid register message */
6128	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6129		return key_senderror(so, m, EINVAL);
6130
6131	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6132	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6133		goto setmsg;
6134
6135	/* check whether existing or not */
6136	REGTREE_LOCK();
6137	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6138		if (reg->so == so) {
6139			REGTREE_UNLOCK();
6140			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6141				__func__));
6142			return key_senderror(so, m, EEXIST);
6143		}
6144	}
6145
6146	/* create regnode */
6147	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6148	if (newreg == NULL) {
6149		REGTREE_UNLOCK();
6150		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6151		return key_senderror(so, m, ENOBUFS);
6152	}
6153
6154	newreg->so = so;
6155	((struct keycb *)sotorawcb(so))->kp_registered++;
6156
6157	/* add regnode to regtree. */
6158	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6159	REGTREE_UNLOCK();
6160
6161  setmsg:
6162    {
6163	struct mbuf *n;
6164	struct sadb_msg *newmsg;
6165	struct sadb_supported *sup;
6166	u_int len, alen, elen;
6167	int off;
6168	int i;
6169	struct sadb_alg *alg;
6170
6171	/* create new sadb_msg to reply. */
6172	alen = 0;
6173	for (i = 1; i <= SADB_AALG_MAX; i++) {
6174		if (ah_algorithm_lookup(i))
6175			alen += sizeof(struct sadb_alg);
6176	}
6177	if (alen)
6178		alen += sizeof(struct sadb_supported);
6179	elen = 0;
6180	for (i = 1; i <= SADB_EALG_MAX; i++) {
6181		if (esp_algorithm_lookup(i))
6182			elen += sizeof(struct sadb_alg);
6183	}
6184	if (elen)
6185		elen += sizeof(struct sadb_supported);
6186
6187	len = sizeof(struct sadb_msg) + alen + elen;
6188
6189	if (len > MCLBYTES)
6190		return key_senderror(so, m, ENOBUFS);
6191
6192	MGETHDR(n, M_DONTWAIT, MT_DATA);
6193	if (len > MHLEN) {
6194		MCLGET(n, M_DONTWAIT);
6195		if ((n->m_flags & M_EXT) == 0) {
6196			m_freem(n);
6197			n = NULL;
6198		}
6199	}
6200	if (!n)
6201		return key_senderror(so, m, ENOBUFS);
6202
6203	n->m_pkthdr.len = n->m_len = len;
6204	n->m_next = NULL;
6205	off = 0;
6206
6207	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6208	newmsg = mtod(n, struct sadb_msg *);
6209	newmsg->sadb_msg_errno = 0;
6210	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6211	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6212
6213	/* for authentication algorithm */
6214	if (alen) {
6215		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6216		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6217		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6218		off += PFKEY_ALIGN8(sizeof(*sup));
6219
6220		for (i = 1; i <= SADB_AALG_MAX; i++) {
6221			struct auth_hash *aalgo;
6222			u_int16_t minkeysize, maxkeysize;
6223
6224			aalgo = ah_algorithm_lookup(i);
6225			if (!aalgo)
6226				continue;
6227			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6228			alg->sadb_alg_id = i;
6229			alg->sadb_alg_ivlen = 0;
6230			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6231			alg->sadb_alg_minbits = _BITS(minkeysize);
6232			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6233			off += PFKEY_ALIGN8(sizeof(*alg));
6234		}
6235	}
6236
6237	/* for encryption algorithm */
6238	if (elen) {
6239		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6240		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6241		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6242		off += PFKEY_ALIGN8(sizeof(*sup));
6243
6244		for (i = 1; i <= SADB_EALG_MAX; i++) {
6245			struct enc_xform *ealgo;
6246
6247			ealgo = esp_algorithm_lookup(i);
6248			if (!ealgo)
6249				continue;
6250			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6251			alg->sadb_alg_id = i;
6252			alg->sadb_alg_ivlen = ealgo->blocksize;
6253			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6254			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6255			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6256		}
6257	}
6258
6259	IPSEC_ASSERT(off == len,
6260		("length assumption failed (off %u len %u)", off, len));
6261
6262	m_freem(m);
6263	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6264    }
6265}
6266
6267/*
6268 * free secreg entry registered.
6269 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6270 */
6271void
6272key_freereg(struct socket *so)
6273{
6274	INIT_VNET_IPSEC(curvnet);
6275	struct secreg *reg;
6276	int i;
6277
6278	IPSEC_ASSERT(so != NULL, ("NULL so"));
6279
6280	/*
6281	 * check whether existing or not.
6282	 * check all type of SA, because there is a potential that
6283	 * one socket is registered to multiple type of SA.
6284	 */
6285	REGTREE_LOCK();
6286	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6287		LIST_FOREACH(reg, &V_regtree[i], chain) {
6288			if (reg->so == so && __LIST_CHAINED(reg)) {
6289				LIST_REMOVE(reg, chain);
6290				free(reg, M_IPSEC_SAR);
6291				break;
6292			}
6293		}
6294	}
6295	REGTREE_UNLOCK();
6296}
6297
6298/*
6299 * SADB_EXPIRE processing
6300 * send
6301 *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6302 * to KMD by PF_KEY.
6303 * NOTE: We send only soft lifetime extension.
6304 *
6305 * OUT:	0	: succeed
6306 *	others	: error number
6307 */
6308static int
6309key_expire(struct secasvar *sav)
6310{
6311	int s;
6312	int satype;
6313	struct mbuf *result = NULL, *m;
6314	int len;
6315	int error = -1;
6316	struct sadb_lifetime *lt;
6317
6318	/* XXX: Why do we lock ? */
6319	s = splnet();	/*called from softclock()*/
6320
6321	IPSEC_ASSERT (sav != NULL, ("null sav"));
6322	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6323
6324	/* set msg header */
6325	satype = key_proto2satype(sav->sah->saidx.proto);
6326	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6327	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6328	if (!m) {
6329		error = ENOBUFS;
6330		goto fail;
6331	}
6332	result = m;
6333
6334	/* create SA extension */
6335	m = key_setsadbsa(sav);
6336	if (!m) {
6337		error = ENOBUFS;
6338		goto fail;
6339	}
6340	m_cat(result, m);
6341
6342	/* create SA extension */
6343	m = key_setsadbxsa2(sav->sah->saidx.mode,
6344			sav->replay ? sav->replay->count : 0,
6345			sav->sah->saidx.reqid);
6346	if (!m) {
6347		error = ENOBUFS;
6348		goto fail;
6349	}
6350	m_cat(result, m);
6351
6352	/* create lifetime extension (current and soft) */
6353	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6354	m = key_alloc_mbuf(len);
6355	if (!m || m->m_next) {	/*XXX*/
6356		if (m)
6357			m_freem(m);
6358		error = ENOBUFS;
6359		goto fail;
6360	}
6361	bzero(mtod(m, caddr_t), len);
6362	lt = mtod(m, struct sadb_lifetime *);
6363	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6364	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6365	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6366	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6367	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6368	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6369	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6370	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6371	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6372	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6373	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6374	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6375	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6376	m_cat(result, m);
6377
6378	/* set sadb_address for source */
6379	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6380	    &sav->sah->saidx.src.sa,
6381	    FULLMASK, IPSEC_ULPROTO_ANY);
6382	if (!m) {
6383		error = ENOBUFS;
6384		goto fail;
6385	}
6386	m_cat(result, m);
6387
6388	/* set sadb_address for destination */
6389	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6390	    &sav->sah->saidx.dst.sa,
6391	    FULLMASK, IPSEC_ULPROTO_ANY);
6392	if (!m) {
6393		error = ENOBUFS;
6394		goto fail;
6395	}
6396	m_cat(result, m);
6397
6398	if ((result->m_flags & M_PKTHDR) == 0) {
6399		error = EINVAL;
6400		goto fail;
6401	}
6402
6403	if (result->m_len < sizeof(struct sadb_msg)) {
6404		result = m_pullup(result, sizeof(struct sadb_msg));
6405		if (result == NULL) {
6406			error = ENOBUFS;
6407			goto fail;
6408		}
6409	}
6410
6411	result->m_pkthdr.len = 0;
6412	for (m = result; m; m = m->m_next)
6413		result->m_pkthdr.len += m->m_len;
6414
6415	mtod(result, struct sadb_msg *)->sadb_msg_len =
6416	    PFKEY_UNIT64(result->m_pkthdr.len);
6417
6418	splx(s);
6419	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6420
6421 fail:
6422	if (result)
6423		m_freem(result);
6424	splx(s);
6425	return error;
6426}
6427
6428/*
6429 * SADB_FLUSH processing
6430 * receive
6431 *   <base>
6432 * from the ikmpd, and free all entries in secastree.
6433 * and send,
6434 *   <base>
6435 * to the ikmpd.
6436 * NOTE: to do is only marking SADB_SASTATE_DEAD.
6437 *
6438 * m will always be freed.
6439 */
6440static int
6441key_flush(so, m, mhp)
6442	struct socket *so;
6443	struct mbuf *m;
6444	const struct sadb_msghdr *mhp;
6445{
6446	INIT_VNET_IPSEC(curvnet);
6447	struct sadb_msg *newmsg;
6448	struct secashead *sah, *nextsah;
6449	struct secasvar *sav, *nextsav;
6450	u_int16_t proto;
6451	u_int8_t state;
6452	u_int stateidx;
6453
6454	IPSEC_ASSERT(so != NULL, ("null socket"));
6455	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6456	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6457
6458	/* map satype to proto */
6459	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6460		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6461			__func__));
6462		return key_senderror(so, m, EINVAL);
6463	}
6464
6465	/* no SATYPE specified, i.e. flushing all SA. */
6466	SAHTREE_LOCK();
6467	for (sah = LIST_FIRST(&V_sahtree);
6468	     sah != NULL;
6469	     sah = nextsah) {
6470		nextsah = LIST_NEXT(sah, chain);
6471
6472		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6473		 && proto != sah->saidx.proto)
6474			continue;
6475
6476		for (stateidx = 0;
6477		     stateidx < _ARRAYLEN(saorder_state_alive);
6478		     stateidx++) {
6479			state = saorder_state_any[stateidx];
6480			for (sav = LIST_FIRST(&sah->savtree[state]);
6481			     sav != NULL;
6482			     sav = nextsav) {
6483
6484				nextsav = LIST_NEXT(sav, chain);
6485
6486				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6487				KEY_FREESAV(&sav);
6488			}
6489		}
6490
6491		sah->state = SADB_SASTATE_DEAD;
6492	}
6493	SAHTREE_UNLOCK();
6494
6495	if (m->m_len < sizeof(struct sadb_msg) ||
6496	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6497		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6498		return key_senderror(so, m, ENOBUFS);
6499	}
6500
6501	if (m->m_next)
6502		m_freem(m->m_next);
6503	m->m_next = NULL;
6504	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6505	newmsg = mtod(m, struct sadb_msg *);
6506	newmsg->sadb_msg_errno = 0;
6507	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6508
6509	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6510}
6511
6512/*
6513 * SADB_DUMP processing
6514 * dump all entries including status of DEAD in SAD.
6515 * receive
6516 *   <base>
6517 * from the ikmpd, and dump all secasvar leaves
6518 * and send,
6519 *   <base> .....
6520 * to the ikmpd.
6521 *
6522 * m will always be freed.
6523 */
6524static int
6525key_dump(so, m, mhp)
6526	struct socket *so;
6527	struct mbuf *m;
6528	const struct sadb_msghdr *mhp;
6529{
6530	INIT_VNET_IPSEC(curvnet);
6531	struct secashead *sah;
6532	struct secasvar *sav;
6533	u_int16_t proto;
6534	u_int stateidx;
6535	u_int8_t satype;
6536	u_int8_t state;
6537	int cnt;
6538	struct sadb_msg *newmsg;
6539	struct mbuf *n;
6540
6541	IPSEC_ASSERT(so != NULL, ("null socket"));
6542	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6543	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6544	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6545
6546	/* map satype to proto */
6547	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6548		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6549			__func__));
6550		return key_senderror(so, m, EINVAL);
6551	}
6552
6553	/* count sav entries to be sent to the userland. */
6554	cnt = 0;
6555	SAHTREE_LOCK();
6556	LIST_FOREACH(sah, &V_sahtree, chain) {
6557		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6558		 && proto != sah->saidx.proto)
6559			continue;
6560
6561		for (stateidx = 0;
6562		     stateidx < _ARRAYLEN(saorder_state_any);
6563		     stateidx++) {
6564			state = saorder_state_any[stateidx];
6565			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6566				cnt++;
6567			}
6568		}
6569	}
6570
6571	if (cnt == 0) {
6572		SAHTREE_UNLOCK();
6573		return key_senderror(so, m, ENOENT);
6574	}
6575
6576	/* send this to the userland, one at a time. */
6577	newmsg = NULL;
6578	LIST_FOREACH(sah, &V_sahtree, chain) {
6579		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6580		 && proto != sah->saidx.proto)
6581			continue;
6582
6583		/* map proto to satype */
6584		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6585			SAHTREE_UNLOCK();
6586			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
6587				"SAD.\n", __func__));
6588			return key_senderror(so, m, EINVAL);
6589		}
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				n = key_setdumpsa(sav, SADB_DUMP, satype,
6597				    --cnt, mhp->msg->sadb_msg_pid);
6598				if (!n) {
6599					SAHTREE_UNLOCK();
6600					return key_senderror(so, m, ENOBUFS);
6601				}
6602				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6603			}
6604		}
6605	}
6606	SAHTREE_UNLOCK();
6607
6608	m_freem(m);
6609	return 0;
6610}
6611
6612/*
6613 * SADB_X_PROMISC processing
6614 *
6615 * m will always be freed.
6616 */
6617static int
6618key_promisc(so, m, mhp)
6619	struct socket *so;
6620	struct mbuf *m;
6621	const struct sadb_msghdr *mhp;
6622{
6623	int olen;
6624
6625	IPSEC_ASSERT(so != NULL, ("null socket"));
6626	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6627	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6628	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6629
6630	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6631
6632	if (olen < sizeof(struct sadb_msg)) {
6633#if 1
6634		return key_senderror(so, m, EINVAL);
6635#else
6636		m_freem(m);
6637		return 0;
6638#endif
6639	} else if (olen == sizeof(struct sadb_msg)) {
6640		/* enable/disable promisc mode */
6641		struct keycb *kp;
6642
6643		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6644			return key_senderror(so, m, EINVAL);
6645		mhp->msg->sadb_msg_errno = 0;
6646		switch (mhp->msg->sadb_msg_satype) {
6647		case 0:
6648		case 1:
6649			kp->kp_promisc = mhp->msg->sadb_msg_satype;
6650			break;
6651		default:
6652			return key_senderror(so, m, EINVAL);
6653		}
6654
6655		/* send the original message back to everyone */
6656		mhp->msg->sadb_msg_errno = 0;
6657		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6658	} else {
6659		/* send packet as is */
6660
6661		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6662
6663		/* TODO: if sadb_msg_seq is specified, send to specific pid */
6664		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6665	}
6666}
6667
6668static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
6669		const struct sadb_msghdr *)) = {
6670	NULL,		/* SADB_RESERVED */
6671	key_getspi,	/* SADB_GETSPI */
6672	key_update,	/* SADB_UPDATE */
6673	key_add,	/* SADB_ADD */
6674	key_delete,	/* SADB_DELETE */
6675	key_get,	/* SADB_GET */
6676	key_acquire2,	/* SADB_ACQUIRE */
6677	key_register,	/* SADB_REGISTER */
6678	NULL,		/* SADB_EXPIRE */
6679	key_flush,	/* SADB_FLUSH */
6680	key_dump,	/* SADB_DUMP */
6681	key_promisc,	/* SADB_X_PROMISC */
6682	NULL,		/* SADB_X_PCHANGE */
6683	key_spdadd,	/* SADB_X_SPDUPDATE */
6684	key_spdadd,	/* SADB_X_SPDADD */
6685	key_spddelete,	/* SADB_X_SPDDELETE */
6686	key_spdget,	/* SADB_X_SPDGET */
6687	NULL,		/* SADB_X_SPDACQUIRE */
6688	key_spddump,	/* SADB_X_SPDDUMP */
6689	key_spdflush,	/* SADB_X_SPDFLUSH */
6690	key_spdadd,	/* SADB_X_SPDSETIDX */
6691	NULL,		/* SADB_X_SPDEXPIRE */
6692	key_spddelete2,	/* SADB_X_SPDDELETE2 */
6693};
6694
6695/*
6696 * parse sadb_msg buffer to process PFKEYv2,
6697 * and create a data to response if needed.
6698 * I think to be dealed with mbuf directly.
6699 * IN:
6700 *     msgp  : pointer to pointer to a received buffer pulluped.
6701 *             This is rewrited to response.
6702 *     so    : pointer to socket.
6703 * OUT:
6704 *    length for buffer to send to user process.
6705 */
6706int
6707key_parse(m, so)
6708	struct mbuf *m;
6709	struct socket *so;
6710{
6711	INIT_VNET_IPSEC(curvnet);
6712	struct sadb_msg *msg;
6713	struct sadb_msghdr mh;
6714	u_int orglen;
6715	int error;
6716	int target;
6717
6718	IPSEC_ASSERT(so != NULL, ("null socket"));
6719	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6720
6721#if 0	/*kdebug_sadb assumes msg in linear buffer*/
6722	KEYDEBUG(KEYDEBUG_KEY_DUMP,
6723		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
6724		kdebug_sadb(msg));
6725#endif
6726
6727	if (m->m_len < sizeof(struct sadb_msg)) {
6728		m = m_pullup(m, sizeof(struct sadb_msg));
6729		if (!m)
6730			return ENOBUFS;
6731	}
6732	msg = mtod(m, struct sadb_msg *);
6733	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6734	target = KEY_SENDUP_ONE;
6735
6736	if ((m->m_flags & M_PKTHDR) == 0 ||
6737	    m->m_pkthdr.len != m->m_pkthdr.len) {
6738		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
6739		V_pfkeystat.out_invlen++;
6740		error = EINVAL;
6741		goto senderror;
6742	}
6743
6744	if (msg->sadb_msg_version != PF_KEY_V2) {
6745		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
6746		    __func__, msg->sadb_msg_version));
6747		V_pfkeystat.out_invver++;
6748		error = EINVAL;
6749		goto senderror;
6750	}
6751
6752	if (msg->sadb_msg_type > SADB_MAX) {
6753		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6754		    __func__, msg->sadb_msg_type));
6755		V_pfkeystat.out_invmsgtype++;
6756		error = EINVAL;
6757		goto senderror;
6758	}
6759
6760	/* for old-fashioned code - should be nuked */
6761	if (m->m_pkthdr.len > MCLBYTES) {
6762		m_freem(m);
6763		return ENOBUFS;
6764	}
6765	if (m->m_next) {
6766		struct mbuf *n;
6767
6768		MGETHDR(n, M_DONTWAIT, MT_DATA);
6769		if (n && m->m_pkthdr.len > MHLEN) {
6770			MCLGET(n, M_DONTWAIT);
6771			if ((n->m_flags & M_EXT) == 0) {
6772				m_free(n);
6773				n = NULL;
6774			}
6775		}
6776		if (!n) {
6777			m_freem(m);
6778			return ENOBUFS;
6779		}
6780		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6781		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6782		n->m_next = NULL;
6783		m_freem(m);
6784		m = n;
6785	}
6786
6787	/* align the mbuf chain so that extensions are in contiguous region. */
6788	error = key_align(m, &mh);
6789	if (error)
6790		return error;
6791
6792	msg = mh.msg;
6793
6794	/* check SA type */
6795	switch (msg->sadb_msg_satype) {
6796	case SADB_SATYPE_UNSPEC:
6797		switch (msg->sadb_msg_type) {
6798		case SADB_GETSPI:
6799		case SADB_UPDATE:
6800		case SADB_ADD:
6801		case SADB_DELETE:
6802		case SADB_GET:
6803		case SADB_ACQUIRE:
6804		case SADB_EXPIRE:
6805			ipseclog((LOG_DEBUG, "%s: must specify satype "
6806			    "when msg type=%u.\n", __func__,
6807			    msg->sadb_msg_type));
6808			V_pfkeystat.out_invsatype++;
6809			error = EINVAL;
6810			goto senderror;
6811		}
6812		break;
6813	case SADB_SATYPE_AH:
6814	case SADB_SATYPE_ESP:
6815	case SADB_X_SATYPE_IPCOMP:
6816	case SADB_X_SATYPE_TCPSIGNATURE:
6817		switch (msg->sadb_msg_type) {
6818		case SADB_X_SPDADD:
6819		case SADB_X_SPDDELETE:
6820		case SADB_X_SPDGET:
6821		case SADB_X_SPDDUMP:
6822		case SADB_X_SPDFLUSH:
6823		case SADB_X_SPDSETIDX:
6824		case SADB_X_SPDUPDATE:
6825		case SADB_X_SPDDELETE2:
6826			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
6827				__func__, msg->sadb_msg_type));
6828			V_pfkeystat.out_invsatype++;
6829			error = EINVAL;
6830			goto senderror;
6831		}
6832		break;
6833	case SADB_SATYPE_RSVP:
6834	case SADB_SATYPE_OSPFV2:
6835	case SADB_SATYPE_RIPV2:
6836	case SADB_SATYPE_MIP:
6837		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
6838			__func__, msg->sadb_msg_satype));
6839		V_pfkeystat.out_invsatype++;
6840		error = EOPNOTSUPP;
6841		goto senderror;
6842	case 1:	/* XXX: What does it do? */
6843		if (msg->sadb_msg_type == SADB_X_PROMISC)
6844			break;
6845		/*FALLTHROUGH*/
6846	default:
6847		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6848			__func__, msg->sadb_msg_satype));
6849		V_pfkeystat.out_invsatype++;
6850		error = EINVAL;
6851		goto senderror;
6852	}
6853
6854	/* check field of upper layer protocol and address family */
6855	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6856	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6857		struct sadb_address *src0, *dst0;
6858		u_int plen;
6859
6860		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6861		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6862
6863		/* check upper layer protocol */
6864		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6865			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
6866				"mismatched.\n", __func__));
6867			V_pfkeystat.out_invaddr++;
6868			error = EINVAL;
6869			goto senderror;
6870		}
6871
6872		/* check family */
6873		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6874		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
6875			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
6876				__func__));
6877			V_pfkeystat.out_invaddr++;
6878			error = EINVAL;
6879			goto senderror;
6880		}
6881		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6882		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
6883			ipseclog((LOG_DEBUG, "%s: address struct size "
6884				"mismatched.\n", __func__));
6885			V_pfkeystat.out_invaddr++;
6886			error = EINVAL;
6887			goto senderror;
6888		}
6889
6890		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6891		case AF_INET:
6892			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6893			    sizeof(struct sockaddr_in)) {
6894				V_pfkeystat.out_invaddr++;
6895				error = EINVAL;
6896				goto senderror;
6897			}
6898			break;
6899		case AF_INET6:
6900			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6901			    sizeof(struct sockaddr_in6)) {
6902				V_pfkeystat.out_invaddr++;
6903				error = EINVAL;
6904				goto senderror;
6905			}
6906			break;
6907		default:
6908			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
6909				__func__));
6910			V_pfkeystat.out_invaddr++;
6911			error = EAFNOSUPPORT;
6912			goto senderror;
6913		}
6914
6915		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6916		case AF_INET:
6917			plen = sizeof(struct in_addr) << 3;
6918			break;
6919		case AF_INET6:
6920			plen = sizeof(struct in6_addr) << 3;
6921			break;
6922		default:
6923			plen = 0;	/*fool gcc*/
6924			break;
6925		}
6926
6927		/* check max prefix length */
6928		if (src0->sadb_address_prefixlen > plen ||
6929		    dst0->sadb_address_prefixlen > plen) {
6930			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
6931				__func__));
6932			V_pfkeystat.out_invaddr++;
6933			error = EINVAL;
6934			goto senderror;
6935		}
6936
6937		/*
6938		 * prefixlen == 0 is valid because there can be a case when
6939		 * all addresses are matched.
6940		 */
6941	}
6942
6943	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
6944	    key_typesw[msg->sadb_msg_type] == NULL) {
6945		V_pfkeystat.out_invmsgtype++;
6946		error = EINVAL;
6947		goto senderror;
6948	}
6949
6950	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6951
6952senderror:
6953	msg->sadb_msg_errno = error;
6954	return key_sendup_mbuf(so, m, target);
6955}
6956
6957static int
6958key_senderror(so, m, code)
6959	struct socket *so;
6960	struct mbuf *m;
6961	int code;
6962{
6963	struct sadb_msg *msg;
6964
6965	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6966		("mbuf too small, len %u", m->m_len));
6967
6968	msg = mtod(m, struct sadb_msg *);
6969	msg->sadb_msg_errno = code;
6970	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
6971}
6972
6973/*
6974 * set the pointer to each header into message buffer.
6975 * m will be freed on error.
6976 * XXX larger-than-MCLBYTES extension?
6977 */
6978static int
6979key_align(m, mhp)
6980	struct mbuf *m;
6981	struct sadb_msghdr *mhp;
6982{
6983	INIT_VNET_IPSEC(curvnet);
6984	struct mbuf *n;
6985	struct sadb_ext *ext;
6986	size_t off, end;
6987	int extlen;
6988	int toff;
6989
6990	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6991	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6992	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6993		("mbuf too small, len %u", m->m_len));
6994
6995	/* initialize */
6996	bzero(mhp, sizeof(*mhp));
6997
6998	mhp->msg = mtod(m, struct sadb_msg *);
6999	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7000
7001	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7002	extlen = end;	/*just in case extlen is not updated*/
7003	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7004		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7005		if (!n) {
7006			/* m is already freed */
7007			return ENOBUFS;
7008		}
7009		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7010
7011		/* set pointer */
7012		switch (ext->sadb_ext_type) {
7013		case SADB_EXT_SA:
7014		case SADB_EXT_ADDRESS_SRC:
7015		case SADB_EXT_ADDRESS_DST:
7016		case SADB_EXT_ADDRESS_PROXY:
7017		case SADB_EXT_LIFETIME_CURRENT:
7018		case SADB_EXT_LIFETIME_HARD:
7019		case SADB_EXT_LIFETIME_SOFT:
7020		case SADB_EXT_KEY_AUTH:
7021		case SADB_EXT_KEY_ENCRYPT:
7022		case SADB_EXT_IDENTITY_SRC:
7023		case SADB_EXT_IDENTITY_DST:
7024		case SADB_EXT_SENSITIVITY:
7025		case SADB_EXT_PROPOSAL:
7026		case SADB_EXT_SUPPORTED_AUTH:
7027		case SADB_EXT_SUPPORTED_ENCRYPT:
7028		case SADB_EXT_SPIRANGE:
7029		case SADB_X_EXT_POLICY:
7030		case SADB_X_EXT_SA2:
7031			/* duplicate check */
7032			/*
7033			 * XXX Are there duplication payloads of either
7034			 * KEY_AUTH or KEY_ENCRYPT ?
7035			 */
7036			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7037				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7038					"%u\n", __func__, ext->sadb_ext_type));
7039				m_freem(m);
7040				V_pfkeystat.out_dupext++;
7041				return EINVAL;
7042			}
7043			break;
7044		default:
7045			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7046				__func__, ext->sadb_ext_type));
7047			m_freem(m);
7048			V_pfkeystat.out_invexttype++;
7049			return EINVAL;
7050		}
7051
7052		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7053
7054		if (key_validate_ext(ext, extlen)) {
7055			m_freem(m);
7056			V_pfkeystat.out_invlen++;
7057			return EINVAL;
7058		}
7059
7060		n = m_pulldown(m, off, extlen, &toff);
7061		if (!n) {
7062			/* m is already freed */
7063			return ENOBUFS;
7064		}
7065		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7066
7067		mhp->ext[ext->sadb_ext_type] = ext;
7068		mhp->extoff[ext->sadb_ext_type] = off;
7069		mhp->extlen[ext->sadb_ext_type] = extlen;
7070	}
7071
7072	if (off != end) {
7073		m_freem(m);
7074		V_pfkeystat.out_invlen++;
7075		return EINVAL;
7076	}
7077
7078	return 0;
7079}
7080
7081static int
7082key_validate_ext(ext, len)
7083	const struct sadb_ext *ext;
7084	int len;
7085{
7086	const struct sockaddr *sa;
7087	enum { NONE, ADDR } checktype = NONE;
7088	int baselen = 0;
7089	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7090
7091	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7092		return EINVAL;
7093
7094	/* if it does not match minimum/maximum length, bail */
7095	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7096	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7097		return EINVAL;
7098	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7099		return EINVAL;
7100	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7101		return EINVAL;
7102
7103	/* more checks based on sadb_ext_type XXX need more */
7104	switch (ext->sadb_ext_type) {
7105	case SADB_EXT_ADDRESS_SRC:
7106	case SADB_EXT_ADDRESS_DST:
7107	case SADB_EXT_ADDRESS_PROXY:
7108		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7109		checktype = ADDR;
7110		break;
7111	case SADB_EXT_IDENTITY_SRC:
7112	case SADB_EXT_IDENTITY_DST:
7113		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7114		    SADB_X_IDENTTYPE_ADDR) {
7115			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7116			checktype = ADDR;
7117		} else
7118			checktype = NONE;
7119		break;
7120	default:
7121		checktype = NONE;
7122		break;
7123	}
7124
7125	switch (checktype) {
7126	case NONE:
7127		break;
7128	case ADDR:
7129		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7130		if (len < baselen + sal)
7131			return EINVAL;
7132		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7133			return EINVAL;
7134		break;
7135	}
7136
7137	return 0;
7138}
7139
7140void
7141key_init(void)
7142{
7143	INIT_VNET_IPSEC(curvnet);
7144	int i;
7145
7146	V_key_debug_level = 0;
7147	V_key_spi_trycnt = 1000;
7148	V_key_spi_minval = 0x100;
7149	V_key_spi_maxval = 0x0fffffff;	/* XXX */
7150	V_policy_id = 0;
7151	V_key_int_random = 60;		/*interval to initialize randseed,1(m)*/
7152	V_key_larval_lifetime = 30;	/* interval to expire acquiring, 30(s)*/
7153	V_key_blockacq_count = 10;	/* counter for blocking SADB_ACQUIRE.*/
7154	V_key_blockacq_lifetime = 20;	/* lifetime for blocking SADB_ACQUIRE.*/
7155	V_key_preferred_oldsa = 1;	/* preferred old sa rather than new sa*/
7156
7157	V_acq_seq = 0;
7158
7159	V_ipsec_esp_keymin = 256;
7160	V_ipsec_esp_auth = 0;
7161	V_ipsec_ah_keymin = 128;
7162
7163	SPTREE_LOCK_INIT();
7164	REGTREE_LOCK_INIT();
7165	SAHTREE_LOCK_INIT();
7166	ACQ_LOCK_INIT();
7167	SPACQ_LOCK_INIT();
7168
7169	for (i = 0; i < IPSEC_DIR_MAX; i++)
7170		LIST_INIT(&V_sptree[i]);
7171
7172	LIST_INIT(&V_sahtree);
7173
7174	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7175		LIST_INIT(&V_regtree[i]);
7176
7177	LIST_INIT(&V_acqtree);
7178	LIST_INIT(&V_spacqtree);
7179
7180	/* system default */
7181	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7182	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7183
7184#ifndef IPSEC_DEBUG2
7185	timeout((void *)key_timehandler, (void *)0, hz);
7186#endif /*IPSEC_DEBUG2*/
7187
7188	/* initialize key statistics */
7189	keystat.getspi_count = 1;
7190
7191	printf("IPsec: Initialized Security Association Processing.\n");
7192
7193	return;
7194}
7195
7196/*
7197 * XXX: maybe This function is called after INBOUND IPsec processing.
7198 *
7199 * Special check for tunnel-mode packets.
7200 * We must make some checks for consistency between inner and outer IP header.
7201 *
7202 * xxx more checks to be provided
7203 */
7204int
7205key_checktunnelsanity(sav, family, src, dst)
7206	struct secasvar *sav;
7207	u_int family;
7208	caddr_t src;
7209	caddr_t dst;
7210{
7211	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7212
7213	/* XXX: check inner IP header */
7214
7215	return 1;
7216}
7217
7218/* record data transfer on SA, and update timestamps */
7219void
7220key_sa_recordxfer(sav, m)
7221	struct secasvar *sav;
7222	struct mbuf *m;
7223{
7224	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7225	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7226	if (!sav->lft_c)
7227		return;
7228
7229	/*
7230	 * XXX Currently, there is a difference of bytes size
7231	 * between inbound and outbound processing.
7232	 */
7233	sav->lft_c->bytes += m->m_pkthdr.len;
7234	/* to check bytes lifetime is done in key_timehandler(). */
7235
7236	/*
7237	 * We use the number of packets as the unit of
7238	 * allocations.  We increment the variable
7239	 * whenever {esp,ah}_{in,out}put is called.
7240	 */
7241	sav->lft_c->allocations++;
7242	/* XXX check for expires? */
7243
7244	/*
7245	 * NOTE: We record CURRENT usetime by using wall clock,
7246	 * in seconds.  HARD and SOFT lifetime are measured by the time
7247	 * difference (again in seconds) from usetime.
7248	 *
7249	 *	usetime
7250	 *	v     expire   expire
7251	 * -----+-----+--------+---> t
7252	 *	<--------------> HARD
7253	 *	<-----> SOFT
7254	 */
7255	sav->lft_c->usetime = time_second;
7256	/* XXX check for expires? */
7257
7258	return;
7259}
7260
7261/* dumb version */
7262void
7263key_sa_routechange(dst)
7264	struct sockaddr *dst;
7265{
7266	INIT_VNET_IPSEC(curvnet);
7267	struct secashead *sah;
7268	struct route *ro;
7269
7270	SAHTREE_LOCK();
7271	LIST_FOREACH(sah, &V_sahtree, chain) {
7272		ro = &sah->sa_route;
7273		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7274		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7275			RTFREE(ro->ro_rt);
7276			ro->ro_rt = (struct rtentry *)NULL;
7277		}
7278	}
7279	SAHTREE_UNLOCK();
7280}
7281
7282static void
7283key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7284{
7285	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7286	SAHTREE_LOCK_ASSERT();
7287
7288	if (sav->state != state) {
7289		if (__LIST_CHAINED(sav))
7290			LIST_REMOVE(sav, chain);
7291		sav->state = state;
7292		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7293	}
7294}
7295
7296void
7297key_sa_stir_iv(sav)
7298	struct secasvar *sav;
7299{
7300
7301	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7302	key_randomfill(sav->iv, sav->ivlen);
7303}
7304
7305/* XXX too much? */
7306static struct mbuf *
7307key_alloc_mbuf(l)
7308	int l;
7309{
7310	struct mbuf *m = NULL, *n;
7311	int len, t;
7312
7313	len = l;
7314	while (len > 0) {
7315		MGET(n, M_DONTWAIT, MT_DATA);
7316		if (n && len > MLEN)
7317			MCLGET(n, M_DONTWAIT);
7318		if (!n) {
7319			m_freem(m);
7320			return NULL;
7321		}
7322
7323		n->m_next = NULL;
7324		n->m_len = 0;
7325		n->m_len = M_TRAILINGSPACE(n);
7326		/* use the bottom of mbuf, hoping we can prepend afterwards */
7327		if (n->m_len > len) {
7328			t = (n->m_len - len) & ~(sizeof(long) - 1);
7329			n->m_data += t;
7330			n->m_len = len;
7331		}
7332
7333		len -= n->m_len;
7334
7335		if (m)
7336			m_cat(m, n);
7337		else
7338			m = n;
7339	}
7340
7341	return m;
7342}
7343
7344/*
7345 * Take one of the kernel's security keys and convert it into a PF_KEY
7346 * structure within an mbuf, suitable for sending up to a waiting
7347 * application in user land.
7348 *
7349 * IN:
7350 *    src: A pointer to a kernel security key.
7351 *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
7352 * OUT:
7353 *    a valid mbuf or NULL indicating an error
7354 *
7355 */
7356
7357static struct mbuf *
7358key_setkey(struct seckey *src, u_int16_t exttype)
7359{
7360	struct mbuf *m;
7361	struct sadb_key *p;
7362	int len;
7363
7364	if (src == NULL)
7365		return NULL;
7366
7367	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
7368	m = key_alloc_mbuf(len);
7369	if (m == NULL)
7370		return NULL;
7371	p = mtod(m, struct sadb_key *);
7372	bzero(p, len);
7373	p->sadb_key_len = PFKEY_UNIT64(len);
7374	p->sadb_key_exttype = exttype;
7375	p->sadb_key_bits = src->bits;
7376	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
7377
7378	return m;
7379}
7380
7381/*
7382 * Take one of the kernel's lifetime data structures and convert it
7383 * into a PF_KEY structure within an mbuf, suitable for sending up to
7384 * a waiting application in user land.
7385 *
7386 * IN:
7387 *    src: A pointer to a kernel lifetime structure.
7388 *    exttype: Which type of lifetime this is. Refer to the PF_KEY
7389 *             data structures for more information.
7390 * OUT:
7391 *    a valid mbuf or NULL indicating an error
7392 *
7393 */
7394
7395static struct mbuf *
7396key_setlifetime(struct seclifetime *src, u_int16_t exttype)
7397{
7398	struct mbuf *m = NULL;
7399	struct sadb_lifetime *p;
7400	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
7401
7402	if (src == NULL)
7403		return NULL;
7404
7405	m = key_alloc_mbuf(len);
7406	if (m == NULL)
7407		return m;
7408	p = mtod(m, struct sadb_lifetime *);
7409
7410	bzero(p, len);
7411	p->sadb_lifetime_len = PFKEY_UNIT64(len);
7412	p->sadb_lifetime_exttype = exttype;
7413	p->sadb_lifetime_allocations = src->allocations;
7414	p->sadb_lifetime_bytes = src->bytes;
7415	p->sadb_lifetime_addtime = src->addtime;
7416	p->sadb_lifetime_usetime = src->usetime;
7417
7418	return m;
7419
7420}
7421