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