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