key.c revision 191663
1/*	$FreeBSD: head/sys/netipsec/key.c 191663 2009-04-29 11:15:58Z bms $	*/
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				/* NB: clean entries created by key_spdflush */
4108				SPTREE_UNLOCK();
4109				KEY_FREESP(&sp);
4110				goto restart;
4111			}
4112			if (sp->lifetime == 0 && sp->validtime == 0)
4113				continue;
4114			if ((sp->lifetime && now - sp->created > sp->lifetime)
4115			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4116				sp->state = IPSEC_SPSTATE_DEAD;
4117				SPTREE_UNLOCK();
4118				key_spdexpire(sp);
4119				KEY_FREESP(&sp);
4120				goto restart;
4121			}
4122		}
4123		SPTREE_UNLOCK();
4124	}
4125}
4126
4127static void
4128key_flush_sad(time_t now)
4129{
4130	INIT_VNET_IPSEC(curvnet);
4131	struct secashead *sah, *nextsah;
4132	struct secasvar *sav, *nextsav;
4133
4134	/* SAD */
4135	SAHTREE_LOCK();
4136	LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4137		/* if sah has been dead, then delete it and process next sah. */
4138		if (sah->state == SADB_SASTATE_DEAD) {
4139			key_delsah(sah);
4140			continue;
4141		}
4142
4143		/* if LARVAL entry doesn't become MATURE, delete it. */
4144		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4145			/* Need to also check refcnt for a larval SA ??? */
4146			if (now - sav->created > V_key_larval_lifetime)
4147				KEY_FREESAV(&sav);
4148		}
4149
4150		/*
4151		 * check MATURE entry to start to send expire message
4152		 * whether or not.
4153		 */
4154		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4155			/* we don't need to check. */
4156			if (sav->lft_s == NULL)
4157				continue;
4158
4159			/* sanity check */
4160			if (sav->lft_c == NULL) {
4161				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4162					"time, why?\n", __func__));
4163				continue;
4164			}
4165
4166			/* check SOFT lifetime */
4167			if (sav->lft_s->addtime != 0 &&
4168			    now - sav->created > sav->lft_s->addtime) {
4169				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4170				/*
4171				 * Actually, only send expire message if
4172				 * SA has been used, as it was done before,
4173				 * but should we always send such message,
4174				 * and let IKE daemon decide if it should be
4175				 * renegotiated or not ?
4176				 * XXX expire message will actually NOT be
4177				 * sent if SA is only used after soft
4178				 * lifetime has been reached, see below
4179				 * (DYING state)
4180				 */
4181				if (sav->lft_c->usetime != 0)
4182					key_expire(sav);
4183			}
4184			/* check SOFT lifetime by bytes */
4185			/*
4186			 * XXX I don't know the way to delete this SA
4187			 * when new SA is installed.  Caution when it's
4188			 * installed too big lifetime by time.
4189			 */
4190			else if (sav->lft_s->bytes != 0 &&
4191			    sav->lft_s->bytes < sav->lft_c->bytes) {
4192
4193				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4194				/*
4195				 * XXX If we keep to send expire
4196				 * message in the status of
4197				 * DYING. Do remove below code.
4198				 */
4199				key_expire(sav);
4200			}
4201		}
4202
4203		/* check DYING entry to change status to DEAD. */
4204		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4205			/* we don't need to check. */
4206			if (sav->lft_h == NULL)
4207				continue;
4208
4209			/* sanity check */
4210			if (sav->lft_c == NULL) {
4211				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4212					"time, why?\n", __func__));
4213				continue;
4214			}
4215
4216			if (sav->lft_h->addtime != 0 &&
4217			    now - sav->created > sav->lft_h->addtime) {
4218				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4219				KEY_FREESAV(&sav);
4220			}
4221#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4222			else if (sav->lft_s != NULL
4223			      && sav->lft_s->addtime != 0
4224			      && now - sav->created > sav->lft_s->addtime) {
4225				/*
4226				 * XXX: should be checked to be
4227				 * installed the valid SA.
4228				 */
4229
4230				/*
4231				 * If there is no SA then sending
4232				 * expire message.
4233				 */
4234				key_expire(sav);
4235			}
4236#endif
4237			/* check HARD lifetime by bytes */
4238			else if (sav->lft_h->bytes != 0 &&
4239			    sav->lft_h->bytes < sav->lft_c->bytes) {
4240				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4241				KEY_FREESAV(&sav);
4242			}
4243		}
4244
4245		/* delete entry in DEAD */
4246		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4247			/* sanity check */
4248			if (sav->state != SADB_SASTATE_DEAD) {
4249				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4250					"(queue: %d SA: %d): kill it anyway\n",
4251					__func__,
4252					SADB_SASTATE_DEAD, sav->state));
4253			}
4254			/*
4255			 * do not call key_freesav() here.
4256			 * sav should already be freed, and sav->refcnt
4257			 * shows other references to sav
4258			 * (such as from SPD).
4259			 */
4260		}
4261	}
4262	SAHTREE_UNLOCK();
4263}
4264
4265static void
4266key_flush_acq(time_t now)
4267{
4268	INIT_VNET_IPSEC(curvnet);
4269	struct secacq *acq, *nextacq;
4270
4271	/* ACQ tree */
4272	ACQ_LOCK();
4273	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4274		nextacq = LIST_NEXT(acq, chain);
4275		if (now - acq->created > V_key_blockacq_lifetime
4276		 && __LIST_CHAINED(acq)) {
4277			LIST_REMOVE(acq, chain);
4278			free(acq, M_IPSEC_SAQ);
4279		}
4280	}
4281	ACQ_UNLOCK();
4282}
4283
4284static void
4285key_flush_spacq(time_t now)
4286{
4287	INIT_VNET_IPSEC(curvnet);
4288	struct secspacq *acq, *nextacq;
4289
4290	/* SP ACQ tree */
4291	SPACQ_LOCK();
4292	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4293		nextacq = LIST_NEXT(acq, chain);
4294		if (now - acq->created > V_key_blockacq_lifetime
4295		 && __LIST_CHAINED(acq)) {
4296			LIST_REMOVE(acq, chain);
4297			free(acq, M_IPSEC_SAQ);
4298		}
4299	}
4300	SPACQ_UNLOCK();
4301}
4302
4303/*
4304 * time handler.
4305 * scanning SPD and SAD to check status for each entries,
4306 * and do to remove or to expire.
4307 * XXX: year 2038 problem may remain.
4308 */
4309void
4310key_timehandler(void)
4311{
4312	VNET_ITERATOR_DECL(vnet_iter);
4313	time_t now = time_second;
4314
4315	VNET_LIST_RLOCK();
4316	VNET_FOREACH(vnet_iter) {
4317		CURVNET_SET(vnet_iter);
4318		key_flush_spd(now);
4319		key_flush_sad(now);
4320		key_flush_acq(now);
4321		key_flush_spacq(now);
4322		CURVNET_RESTORE();
4323	}
4324	VNET_LIST_RUNLOCK();
4325
4326#ifndef IPSEC_DEBUG2
4327	/* do exchange to tick time !! */
4328	(void)timeout((void *)key_timehandler, (void *)0, hz);
4329#endif /* IPSEC_DEBUG2 */
4330}
4331
4332u_long
4333key_random()
4334{
4335	u_long value;
4336
4337	key_randomfill(&value, sizeof(value));
4338	return value;
4339}
4340
4341void
4342key_randomfill(p, l)
4343	void *p;
4344	size_t l;
4345{
4346	size_t n;
4347	u_long v;
4348	static int warn = 1;
4349
4350	n = 0;
4351	n = (size_t)read_random(p, (u_int)l);
4352	/* last resort */
4353	while (n < l) {
4354		v = random();
4355		bcopy(&v, (u_int8_t *)p + n,
4356		    l - n < sizeof(v) ? l - n : sizeof(v));
4357		n += sizeof(v);
4358
4359		if (warn) {
4360			printf("WARNING: pseudo-random number generator "
4361			    "used for IPsec processing\n");
4362			warn = 0;
4363		}
4364	}
4365}
4366
4367/*
4368 * map SADB_SATYPE_* to IPPROTO_*.
4369 * if satype == SADB_SATYPE then satype is mapped to ~0.
4370 * OUT:
4371 *	0: invalid satype.
4372 */
4373static u_int16_t
4374key_satype2proto(u_int8_t satype)
4375{
4376	switch (satype) {
4377	case SADB_SATYPE_UNSPEC:
4378		return IPSEC_PROTO_ANY;
4379	case SADB_SATYPE_AH:
4380		return IPPROTO_AH;
4381	case SADB_SATYPE_ESP:
4382		return IPPROTO_ESP;
4383	case SADB_X_SATYPE_IPCOMP:
4384		return IPPROTO_IPCOMP;
4385	case SADB_X_SATYPE_TCPSIGNATURE:
4386		return IPPROTO_TCP;
4387	default:
4388		return 0;
4389	}
4390	/* NOTREACHED */
4391}
4392
4393/*
4394 * map IPPROTO_* to SADB_SATYPE_*
4395 * OUT:
4396 *	0: invalid protocol type.
4397 */
4398static u_int8_t
4399key_proto2satype(u_int16_t proto)
4400{
4401	switch (proto) {
4402	case IPPROTO_AH:
4403		return SADB_SATYPE_AH;
4404	case IPPROTO_ESP:
4405		return SADB_SATYPE_ESP;
4406	case IPPROTO_IPCOMP:
4407		return SADB_X_SATYPE_IPCOMP;
4408	case IPPROTO_TCP:
4409		return SADB_X_SATYPE_TCPSIGNATURE;
4410	default:
4411		return 0;
4412	}
4413	/* NOTREACHED */
4414}
4415
4416/* %%% PF_KEY */
4417/*
4418 * SADB_GETSPI processing is to receive
4419 *	<base, (SA2), src address, dst address, (SPI range)>
4420 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4421 * tree with the status of LARVAL, and send
4422 *	<base, SA(*), address(SD)>
4423 * to the IKMPd.
4424 *
4425 * IN:	mhp: pointer to the pointer to each header.
4426 * OUT:	NULL if fail.
4427 *	other if success, return pointer to the message to send.
4428 */
4429static int
4430key_getspi(so, m, mhp)
4431	struct socket *so;
4432	struct mbuf *m;
4433	const struct sadb_msghdr *mhp;
4434{
4435	INIT_VNET_IPSEC(curvnet);
4436	struct sadb_address *src0, *dst0;
4437	struct secasindex saidx;
4438	struct secashead *newsah;
4439	struct secasvar *newsav;
4440	u_int8_t proto;
4441	u_int32_t spi;
4442	u_int8_t mode;
4443	u_int32_t reqid;
4444	int error;
4445
4446	IPSEC_ASSERT(so != NULL, ("null socket"));
4447	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4448	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4449	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4450
4451	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4452	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4453		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4454			__func__));
4455		return key_senderror(so, m, EINVAL);
4456	}
4457	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4458	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4459		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4460			__func__));
4461		return key_senderror(so, m, EINVAL);
4462	}
4463	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4464		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4465		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4466	} else {
4467		mode = IPSEC_MODE_ANY;
4468		reqid = 0;
4469	}
4470
4471	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4472	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4473
4474	/* map satype to proto */
4475	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4476		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4477			__func__));
4478		return key_senderror(so, m, EINVAL);
4479	}
4480
4481	/* make sure if port number is zero. */
4482	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4483	case AF_INET:
4484		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4485		    sizeof(struct sockaddr_in))
4486			return key_senderror(so, m, EINVAL);
4487		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4488		break;
4489	case AF_INET6:
4490		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4491		    sizeof(struct sockaddr_in6))
4492			return key_senderror(so, m, EINVAL);
4493		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4494		break;
4495	default:
4496		; /*???*/
4497	}
4498	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4499	case AF_INET:
4500		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4501		    sizeof(struct sockaddr_in))
4502			return key_senderror(so, m, EINVAL);
4503		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4504		break;
4505	case AF_INET6:
4506		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4507		    sizeof(struct sockaddr_in6))
4508			return key_senderror(so, m, EINVAL);
4509		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4510		break;
4511	default:
4512		; /*???*/
4513	}
4514
4515	/* XXX boundary check against sa_len */
4516	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4517
4518	/* SPI allocation */
4519	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4520	                       &saidx);
4521	if (spi == 0)
4522		return key_senderror(so, m, EINVAL);
4523
4524	/* get a SA index */
4525	if ((newsah = key_getsah(&saidx)) == NULL) {
4526		/* create a new SA index */
4527		if ((newsah = key_newsah(&saidx)) == NULL) {
4528			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4529			return key_senderror(so, m, ENOBUFS);
4530		}
4531	}
4532
4533	/* get a new SA */
4534	/* XXX rewrite */
4535	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4536	if (newsav == NULL) {
4537		/* XXX don't free new SA index allocated in above. */
4538		return key_senderror(so, m, error);
4539	}
4540
4541	/* set spi */
4542	newsav->spi = htonl(spi);
4543
4544	/* delete the entry in acqtree */
4545	if (mhp->msg->sadb_msg_seq != 0) {
4546		struct secacq *acq;
4547		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4548			/* reset counter in order to deletion by timehandler. */
4549			acq->created = time_second;
4550			acq->count = 0;
4551		}
4552    	}
4553
4554    {
4555	struct mbuf *n, *nn;
4556	struct sadb_sa *m_sa;
4557	struct sadb_msg *newmsg;
4558	int off, len;
4559
4560	/* create new sadb_msg to reply. */
4561	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4562	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4563
4564	MGETHDR(n, M_DONTWAIT, MT_DATA);
4565	if (len > MHLEN) {
4566		MCLGET(n, M_DONTWAIT);
4567		if ((n->m_flags & M_EXT) == 0) {
4568			m_freem(n);
4569			n = NULL;
4570		}
4571	}
4572	if (!n)
4573		return key_senderror(so, m, ENOBUFS);
4574
4575	n->m_len = len;
4576	n->m_next = NULL;
4577	off = 0;
4578
4579	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4580	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4581
4582	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4583	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4584	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4585	m_sa->sadb_sa_spi = htonl(spi);
4586	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4587
4588	IPSEC_ASSERT(off == len,
4589		("length inconsistency (off %u len %u)", off, len));
4590
4591	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4592	    SADB_EXT_ADDRESS_DST);
4593	if (!n->m_next) {
4594		m_freem(n);
4595		return key_senderror(so, m, ENOBUFS);
4596	}
4597
4598	if (n->m_len < sizeof(struct sadb_msg)) {
4599		n = m_pullup(n, sizeof(struct sadb_msg));
4600		if (n == NULL)
4601			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4602	}
4603
4604	n->m_pkthdr.len = 0;
4605	for (nn = n; nn; nn = nn->m_next)
4606		n->m_pkthdr.len += nn->m_len;
4607
4608	newmsg = mtod(n, struct sadb_msg *);
4609	newmsg->sadb_msg_seq = newsav->seq;
4610	newmsg->sadb_msg_errno = 0;
4611	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4612
4613	m_freem(m);
4614	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4615    }
4616}
4617
4618/*
4619 * allocating new SPI
4620 * called by key_getspi().
4621 * OUT:
4622 *	0:	failure.
4623 *	others: success.
4624 */
4625static u_int32_t
4626key_do_getnewspi(spirange, saidx)
4627	struct sadb_spirange *spirange;
4628	struct secasindex *saidx;
4629{
4630	INIT_VNET_IPSEC(curvnet);
4631	u_int32_t newspi;
4632	u_int32_t min, max;
4633	int count = V_key_spi_trycnt;
4634
4635	/* set spi range to allocate */
4636	if (spirange != NULL) {
4637		min = spirange->sadb_spirange_min;
4638		max = spirange->sadb_spirange_max;
4639	} else {
4640		min = V_key_spi_minval;
4641		max = V_key_spi_maxval;
4642	}
4643	/* IPCOMP needs 2-byte SPI */
4644	if (saidx->proto == IPPROTO_IPCOMP) {
4645		u_int32_t t;
4646		if (min >= 0x10000)
4647			min = 0xffff;
4648		if (max >= 0x10000)
4649			max = 0xffff;
4650		if (min > max) {
4651			t = min; min = max; max = t;
4652		}
4653	}
4654
4655	if (min == max) {
4656		if (key_checkspidup(saidx, min) != NULL) {
4657			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4658				__func__, min));
4659			return 0;
4660		}
4661
4662		count--; /* taking one cost. */
4663		newspi = min;
4664
4665	} else {
4666
4667		/* init SPI */
4668		newspi = 0;
4669
4670		/* when requesting to allocate spi ranged */
4671		while (count--) {
4672			/* generate pseudo-random SPI value ranged. */
4673			newspi = min + (key_random() % (max - min + 1));
4674
4675			if (key_checkspidup(saidx, newspi) == NULL)
4676				break;
4677		}
4678
4679		if (count == 0 || newspi == 0) {
4680			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4681				__func__));
4682			return 0;
4683		}
4684	}
4685
4686	/* statistics */
4687	keystat.getspi_count =
4688		(keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4689
4690	return newspi;
4691}
4692
4693/*
4694 * SADB_UPDATE processing
4695 * receive
4696 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4697 *       key(AE), (identity(SD),) (sensitivity)>
4698 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4699 * and send
4700 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4701 *       (identity(SD),) (sensitivity)>
4702 * to the ikmpd.
4703 *
4704 * m will always be freed.
4705 */
4706static int
4707key_update(so, m, mhp)
4708	struct socket *so;
4709	struct mbuf *m;
4710	const struct sadb_msghdr *mhp;
4711{
4712	INIT_VNET_IPSEC(curvnet);
4713	struct sadb_sa *sa0;
4714	struct sadb_address *src0, *dst0;
4715	struct secasindex saidx;
4716	struct secashead *sah;
4717	struct secasvar *sav;
4718	u_int16_t proto;
4719	u_int8_t mode;
4720	u_int32_t reqid;
4721	int error;
4722
4723	IPSEC_ASSERT(so != NULL, ("null socket"));
4724	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4725	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4726	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4727
4728	/* map satype to proto */
4729	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4730		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4731			__func__));
4732		return key_senderror(so, m, EINVAL);
4733	}
4734
4735	if (mhp->ext[SADB_EXT_SA] == NULL ||
4736	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4737	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4738	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4739	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4740	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4741	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4742	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4743	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4744	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4745	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4746		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4747			__func__));
4748		return key_senderror(so, m, EINVAL);
4749	}
4750	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4751	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4752	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4753		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4754			__func__));
4755		return key_senderror(so, m, EINVAL);
4756	}
4757	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4758		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4759		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4760	} else {
4761		mode = IPSEC_MODE_ANY;
4762		reqid = 0;
4763	}
4764	/* XXX boundary checking for other extensions */
4765
4766	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4767	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4768	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4769
4770	/* XXX boundary check against sa_len */
4771	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4772
4773	/* get a SA header */
4774	if ((sah = key_getsah(&saidx)) == NULL) {
4775		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
4776		return key_senderror(so, m, ENOENT);
4777	}
4778
4779	/* set spidx if there */
4780	/* XXX rewrite */
4781	error = key_setident(sah, m, mhp);
4782	if (error)
4783		return key_senderror(so, m, error);
4784
4785	/* find a SA with sequence number. */
4786#ifdef IPSEC_DOSEQCHECK
4787	if (mhp->msg->sadb_msg_seq != 0
4788	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4789		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
4790			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
4791		return key_senderror(so, m, ENOENT);
4792	}
4793#else
4794	SAHTREE_LOCK();
4795	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4796	SAHTREE_UNLOCK();
4797	if (sav == NULL) {
4798		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
4799			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4800		return key_senderror(so, m, EINVAL);
4801	}
4802#endif
4803
4804	/* validity check */
4805	if (sav->sah->saidx.proto != proto) {
4806		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
4807			"(DB=%u param=%u)\n", __func__,
4808			sav->sah->saidx.proto, proto));
4809		return key_senderror(so, m, EINVAL);
4810	}
4811#ifdef IPSEC_DOSEQCHECK
4812	if (sav->spi != sa0->sadb_sa_spi) {
4813		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
4814		    __func__,
4815		    (u_int32_t)ntohl(sav->spi),
4816		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4817		return key_senderror(so, m, EINVAL);
4818	}
4819#endif
4820	if (sav->pid != mhp->msg->sadb_msg_pid) {
4821		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
4822		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
4823		return key_senderror(so, m, EINVAL);
4824	}
4825
4826	/* copy sav values */
4827	error = key_setsaval(sav, m, mhp);
4828	if (error) {
4829		KEY_FREESAV(&sav);
4830		return key_senderror(so, m, error);
4831	}
4832
4833	/* check SA values to be mature. */
4834	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4835		KEY_FREESAV(&sav);
4836		return key_senderror(so, m, 0);
4837	}
4838
4839    {
4840	struct mbuf *n;
4841
4842	/* set msg buf from mhp */
4843	n = key_getmsgbuf_x1(m, mhp);
4844	if (n == NULL) {
4845		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4846		return key_senderror(so, m, ENOBUFS);
4847	}
4848
4849	m_freem(m);
4850	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4851    }
4852}
4853
4854/*
4855 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4856 * only called by key_update().
4857 * OUT:
4858 *	NULL	: not found
4859 *	others	: found, pointer to a SA.
4860 */
4861#ifdef IPSEC_DOSEQCHECK
4862static struct secasvar *
4863key_getsavbyseq(sah, seq)
4864	struct secashead *sah;
4865	u_int32_t seq;
4866{
4867	struct secasvar *sav;
4868	u_int state;
4869
4870	state = SADB_SASTATE_LARVAL;
4871
4872	/* search SAD with sequence number ? */
4873	LIST_FOREACH(sav, &sah->savtree[state], chain) {
4874
4875		KEY_CHKSASTATE(state, sav->state, __func__);
4876
4877		if (sav->seq == seq) {
4878			sa_addref(sav);
4879			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4880				printf("DP %s cause refcnt++:%d SA:%p\n",
4881					__func__, sav->refcnt, sav));
4882			return sav;
4883		}
4884	}
4885
4886	return NULL;
4887}
4888#endif
4889
4890/*
4891 * SADB_ADD processing
4892 * add an entry to SA database, when received
4893 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4894 *       key(AE), (identity(SD),) (sensitivity)>
4895 * from the ikmpd,
4896 * and send
4897 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4898 *       (identity(SD),) (sensitivity)>
4899 * to the ikmpd.
4900 *
4901 * IGNORE identity and sensitivity messages.
4902 *
4903 * m will always be freed.
4904 */
4905static int
4906key_add(so, m, mhp)
4907	struct socket *so;
4908	struct mbuf *m;
4909	const struct sadb_msghdr *mhp;
4910{
4911	INIT_VNET_IPSEC(curvnet);
4912	struct sadb_sa *sa0;
4913	struct sadb_address *src0, *dst0;
4914	struct secasindex saidx;
4915	struct secashead *newsah;
4916	struct secasvar *newsav;
4917	u_int16_t proto;
4918	u_int8_t mode;
4919	u_int32_t reqid;
4920	int error;
4921
4922	IPSEC_ASSERT(so != NULL, ("null socket"));
4923	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4924	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4925	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4926
4927	/* map satype to proto */
4928	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4929		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4930			__func__));
4931		return key_senderror(so, m, EINVAL);
4932	}
4933
4934	if (mhp->ext[SADB_EXT_SA] == NULL ||
4935	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4936	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4937	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4938	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4939	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4940	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4941	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4942	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4943	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4944	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4945		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4946			__func__));
4947		return key_senderror(so, m, EINVAL);
4948	}
4949	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4950	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4951	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4952		/* XXX need more */
4953		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4954			__func__));
4955		return key_senderror(so, m, EINVAL);
4956	}
4957	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4958		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4959		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4960	} else {
4961		mode = IPSEC_MODE_ANY;
4962		reqid = 0;
4963	}
4964
4965	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4966	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4967	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4968
4969	/* XXX boundary check against sa_len */
4970	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4971
4972	/* get a SA header */
4973	if ((newsah = key_getsah(&saidx)) == NULL) {
4974		/* create a new SA header */
4975		if ((newsah = key_newsah(&saidx)) == NULL) {
4976			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4977			return key_senderror(so, m, ENOBUFS);
4978		}
4979	}
4980
4981	/* set spidx if there */
4982	/* XXX rewrite */
4983	error = key_setident(newsah, m, mhp);
4984	if (error) {
4985		return key_senderror(so, m, error);
4986	}
4987
4988	/* create new SA entry. */
4989	/* We can create new SA only if SPI is differenct. */
4990	SAHTREE_LOCK();
4991	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
4992	SAHTREE_UNLOCK();
4993	if (newsav != NULL) {
4994		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
4995		return key_senderror(so, m, EEXIST);
4996	}
4997	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4998	if (newsav == NULL) {
4999		return key_senderror(so, m, error);
5000	}
5001
5002	/* check SA values to be mature. */
5003	if ((error = key_mature(newsav)) != 0) {
5004		KEY_FREESAV(&newsav);
5005		return key_senderror(so, m, error);
5006	}
5007
5008	/*
5009	 * don't call key_freesav() here, as we would like to keep the SA
5010	 * in the database on success.
5011	 */
5012
5013    {
5014	struct mbuf *n;
5015
5016	/* set msg buf from mhp */
5017	n = key_getmsgbuf_x1(m, mhp);
5018	if (n == NULL) {
5019		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5020		return key_senderror(so, m, ENOBUFS);
5021	}
5022
5023	m_freem(m);
5024	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5025    }
5026}
5027
5028/* m is retained */
5029static int
5030key_setident(sah, m, mhp)
5031	struct secashead *sah;
5032	struct mbuf *m;
5033	const struct sadb_msghdr *mhp;
5034{
5035	INIT_VNET_IPSEC(curvnet);
5036	const struct sadb_ident *idsrc, *iddst;
5037	int idsrclen, iddstlen;
5038
5039	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5040	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5041	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5042	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5043
5044	/* don't make buffer if not there */
5045	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5046	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5047		sah->idents = NULL;
5048		sah->identd = NULL;
5049		return 0;
5050	}
5051
5052	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5053	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5054		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5055		return EINVAL;
5056	}
5057
5058	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5059	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5060	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5061	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5062
5063	/* validity check */
5064	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5065		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5066		return EINVAL;
5067	}
5068
5069	switch (idsrc->sadb_ident_type) {
5070	case SADB_IDENTTYPE_PREFIX:
5071	case SADB_IDENTTYPE_FQDN:
5072	case SADB_IDENTTYPE_USERFQDN:
5073	default:
5074		/* XXX do nothing */
5075		sah->idents = NULL;
5076		sah->identd = NULL;
5077	 	return 0;
5078	}
5079
5080	/* make structure */
5081	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5082	if (sah->idents == NULL) {
5083		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5084		return ENOBUFS;
5085	}
5086	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5087	if (sah->identd == NULL) {
5088		free(sah->idents, M_IPSEC_MISC);
5089		sah->idents = NULL;
5090		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5091		return ENOBUFS;
5092	}
5093	sah->idents->type = idsrc->sadb_ident_type;
5094	sah->idents->id = idsrc->sadb_ident_id;
5095
5096	sah->identd->type = iddst->sadb_ident_type;
5097	sah->identd->id = iddst->sadb_ident_id;
5098
5099	return 0;
5100}
5101
5102/*
5103 * m will not be freed on return.
5104 * it is caller's responsibility to free the result.
5105 */
5106static struct mbuf *
5107key_getmsgbuf_x1(m, mhp)
5108	struct mbuf *m;
5109	const struct sadb_msghdr *mhp;
5110{
5111	struct mbuf *n;
5112
5113	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5114	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5115	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5116
5117	/* create new sadb_msg to reply. */
5118	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5119	    SADB_EXT_SA, SADB_X_EXT_SA2,
5120	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5121	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5122	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5123	if (!n)
5124		return NULL;
5125
5126	if (n->m_len < sizeof(struct sadb_msg)) {
5127		n = m_pullup(n, sizeof(struct sadb_msg));
5128		if (n == NULL)
5129			return NULL;
5130	}
5131	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5132	mtod(n, struct sadb_msg *)->sadb_msg_len =
5133	    PFKEY_UNIT64(n->m_pkthdr.len);
5134
5135	return n;
5136}
5137
5138static int key_delete_all __P((struct socket *, struct mbuf *,
5139	const struct sadb_msghdr *, u_int16_t));
5140
5141/*
5142 * SADB_DELETE processing
5143 * receive
5144 *   <base, SA(*), address(SD)>
5145 * from the ikmpd, and set SADB_SASTATE_DEAD,
5146 * and send,
5147 *   <base, SA(*), address(SD)>
5148 * to the ikmpd.
5149 *
5150 * m will always be freed.
5151 */
5152static int
5153key_delete(so, m, mhp)
5154	struct socket *so;
5155	struct mbuf *m;
5156	const struct sadb_msghdr *mhp;
5157{
5158	INIT_VNET_IPSEC(curvnet);
5159	struct sadb_sa *sa0;
5160	struct sadb_address *src0, *dst0;
5161	struct secasindex saidx;
5162	struct secashead *sah;
5163	struct secasvar *sav = NULL;
5164	u_int16_t proto;
5165
5166	IPSEC_ASSERT(so != NULL, ("null socket"));
5167	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5168	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5169	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5170
5171	/* map satype to proto */
5172	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5173		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5174			__func__));
5175		return key_senderror(so, m, EINVAL);
5176	}
5177
5178	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5179	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5180		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5181			__func__));
5182		return key_senderror(so, m, EINVAL);
5183	}
5184
5185	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5186	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5187		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5188			__func__));
5189		return key_senderror(so, m, EINVAL);
5190	}
5191
5192	if (mhp->ext[SADB_EXT_SA] == NULL) {
5193		/*
5194		 * Caller wants us to delete all non-LARVAL SAs
5195		 * that match the src/dst.  This is used during
5196		 * IKE INITIAL-CONTACT.
5197		 */
5198		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5199		return key_delete_all(so, m, mhp, proto);
5200	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5201		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5202			__func__));
5203		return key_senderror(so, m, EINVAL);
5204	}
5205
5206	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5207	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5208	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5209
5210	/* XXX boundary check against sa_len */
5211	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5212
5213	/* get a SA header */
5214	SAHTREE_LOCK();
5215	LIST_FOREACH(sah, &V_sahtree, chain) {
5216		if (sah->state == SADB_SASTATE_DEAD)
5217			continue;
5218		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5219			continue;
5220
5221		/* get a SA with SPI. */
5222		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5223		if (sav)
5224			break;
5225	}
5226	if (sah == NULL) {
5227		SAHTREE_UNLOCK();
5228		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5229		return key_senderror(so, m, ENOENT);
5230	}
5231
5232	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5233	SAHTREE_UNLOCK();
5234	KEY_FREESAV(&sav);
5235
5236    {
5237	struct mbuf *n;
5238	struct sadb_msg *newmsg;
5239
5240	/* create new sadb_msg to reply. */
5241	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5242	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5243	if (!n)
5244		return key_senderror(so, m, ENOBUFS);
5245
5246	if (n->m_len < sizeof(struct sadb_msg)) {
5247		n = m_pullup(n, sizeof(struct sadb_msg));
5248		if (n == NULL)
5249			return key_senderror(so, m, ENOBUFS);
5250	}
5251	newmsg = mtod(n, struct sadb_msg *);
5252	newmsg->sadb_msg_errno = 0;
5253	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5254
5255	m_freem(m);
5256	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5257    }
5258}
5259
5260/*
5261 * delete all SAs for src/dst.  Called from key_delete().
5262 */
5263static int
5264key_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5265    u_int16_t proto)
5266{
5267	INIT_VNET_IPSEC(curvnet);
5268	struct sadb_address *src0, *dst0;
5269	struct secasindex saidx;
5270	struct secashead *sah;
5271	struct secasvar *sav, *nextsav;
5272	u_int stateidx, state;
5273
5274	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5275	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5276
5277	/* XXX boundary check against sa_len */
5278	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5279
5280	SAHTREE_LOCK();
5281	LIST_FOREACH(sah, &V_sahtree, chain) {
5282		if (sah->state == SADB_SASTATE_DEAD)
5283			continue;
5284		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5285			continue;
5286
5287		/* Delete all non-LARVAL SAs. */
5288		for (stateidx = 0;
5289		     stateidx < _ARRAYLEN(saorder_state_alive);
5290		     stateidx++) {
5291			state = saorder_state_alive[stateidx];
5292			if (state == SADB_SASTATE_LARVAL)
5293				continue;
5294			for (sav = LIST_FIRST(&sah->savtree[state]);
5295			     sav != NULL; sav = nextsav) {
5296				nextsav = LIST_NEXT(sav, chain);
5297				/* sanity check */
5298				if (sav->state != state) {
5299					ipseclog((LOG_DEBUG, "%s: invalid "
5300						"sav->state (queue %d SA %d)\n",
5301						__func__, state, sav->state));
5302					continue;
5303				}
5304
5305				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5306				KEY_FREESAV(&sav);
5307			}
5308		}
5309	}
5310	SAHTREE_UNLOCK();
5311    {
5312	struct mbuf *n;
5313	struct sadb_msg *newmsg;
5314
5315	/* create new sadb_msg to reply. */
5316	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5317	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5318	if (!n)
5319		return key_senderror(so, m, ENOBUFS);
5320
5321	if (n->m_len < sizeof(struct sadb_msg)) {
5322		n = m_pullup(n, sizeof(struct sadb_msg));
5323		if (n == NULL)
5324			return key_senderror(so, m, ENOBUFS);
5325	}
5326	newmsg = mtod(n, struct sadb_msg *);
5327	newmsg->sadb_msg_errno = 0;
5328	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5329
5330	m_freem(m);
5331	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5332    }
5333}
5334
5335/*
5336 * SADB_GET processing
5337 * receive
5338 *   <base, SA(*), address(SD)>
5339 * from the ikmpd, and get a SP and a SA to respond,
5340 * and send,
5341 *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5342 *       (identity(SD),) (sensitivity)>
5343 * to the ikmpd.
5344 *
5345 * m will always be freed.
5346 */
5347static int
5348key_get(so, m, mhp)
5349	struct socket *so;
5350	struct mbuf *m;
5351	const struct sadb_msghdr *mhp;
5352{
5353	INIT_VNET_IPSEC(curvnet);
5354	struct sadb_sa *sa0;
5355	struct sadb_address *src0, *dst0;
5356	struct secasindex saidx;
5357	struct secashead *sah;
5358	struct secasvar *sav = NULL;
5359	u_int16_t proto;
5360
5361	IPSEC_ASSERT(so != NULL, ("null socket"));
5362	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5363	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5364	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5365
5366	/* map satype to proto */
5367	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5368		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5369			__func__));
5370		return key_senderror(so, m, EINVAL);
5371	}
5372
5373	if (mhp->ext[SADB_EXT_SA] == NULL ||
5374	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5375	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5376		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5377			__func__));
5378		return key_senderror(so, m, EINVAL);
5379	}
5380	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5381	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5382	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5383		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5384			__func__));
5385		return key_senderror(so, m, EINVAL);
5386	}
5387
5388	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5389	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5390	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5391
5392	/* XXX boundary check against sa_len */
5393	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5394
5395	/* get a SA header */
5396	SAHTREE_LOCK();
5397	LIST_FOREACH(sah, &V_sahtree, chain) {
5398		if (sah->state == SADB_SASTATE_DEAD)
5399			continue;
5400		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5401			continue;
5402
5403		/* get a SA with SPI. */
5404		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5405		if (sav)
5406			break;
5407	}
5408	SAHTREE_UNLOCK();
5409	if (sah == NULL) {
5410		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5411		return key_senderror(so, m, ENOENT);
5412	}
5413
5414    {
5415	struct mbuf *n;
5416	u_int8_t satype;
5417
5418	/* map proto to satype */
5419	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5420		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5421			__func__));
5422		return key_senderror(so, m, EINVAL);
5423	}
5424
5425	/* create new sadb_msg to reply. */
5426	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5427	    mhp->msg->sadb_msg_pid);
5428	if (!n)
5429		return key_senderror(so, m, ENOBUFS);
5430
5431	m_freem(m);
5432	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5433    }
5434}
5435
5436/* XXX make it sysctl-configurable? */
5437static void
5438key_getcomb_setlifetime(comb)
5439	struct sadb_comb *comb;
5440{
5441
5442	comb->sadb_comb_soft_allocations = 1;
5443	comb->sadb_comb_hard_allocations = 1;
5444	comb->sadb_comb_soft_bytes = 0;
5445	comb->sadb_comb_hard_bytes = 0;
5446	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5447	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5448	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5449	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5450}
5451
5452/*
5453 * XXX reorder combinations by preference
5454 * XXX no idea if the user wants ESP authentication or not
5455 */
5456static struct mbuf *
5457key_getcomb_esp()
5458{
5459	INIT_VNET_IPSEC(curvnet);
5460	struct sadb_comb *comb;
5461	struct enc_xform *algo;
5462	struct mbuf *result = NULL, *m, *n;
5463	int encmin;
5464	int i, off, o;
5465	int totlen;
5466	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5467
5468	m = NULL;
5469	for (i = 1; i <= SADB_EALG_MAX; i++) {
5470		algo = esp_algorithm_lookup(i);
5471		if (algo == NULL)
5472			continue;
5473
5474		/* discard algorithms with key size smaller than system min */
5475		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
5476			continue;
5477		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
5478			encmin = V_ipsec_esp_keymin;
5479		else
5480			encmin = _BITS(algo->minkey);
5481
5482		if (V_ipsec_esp_auth)
5483			m = key_getcomb_ah();
5484		else {
5485			IPSEC_ASSERT(l <= MLEN,
5486				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5487			MGET(m, M_DONTWAIT, MT_DATA);
5488			if (m) {
5489				M_ALIGN(m, l);
5490				m->m_len = l;
5491				m->m_next = NULL;
5492				bzero(mtod(m, caddr_t), m->m_len);
5493			}
5494		}
5495		if (!m)
5496			goto fail;
5497
5498		totlen = 0;
5499		for (n = m; n; n = n->m_next)
5500			totlen += n->m_len;
5501		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
5502
5503		for (off = 0; off < totlen; off += l) {
5504			n = m_pulldown(m, off, l, &o);
5505			if (!n) {
5506				/* m is already freed */
5507				goto fail;
5508			}
5509			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5510			bzero(comb, sizeof(*comb));
5511			key_getcomb_setlifetime(comb);
5512			comb->sadb_comb_encrypt = i;
5513			comb->sadb_comb_encrypt_minbits = encmin;
5514			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5515		}
5516
5517		if (!result)
5518			result = m;
5519		else
5520			m_cat(result, m);
5521	}
5522
5523	return result;
5524
5525 fail:
5526	if (result)
5527		m_freem(result);
5528	return NULL;
5529}
5530
5531static void
5532key_getsizes_ah(
5533	const struct auth_hash *ah,
5534	int alg,
5535	u_int16_t* min,
5536	u_int16_t* max)
5537{
5538	INIT_VNET_IPSEC(curvnet);
5539
5540	*min = *max = ah->keysize;
5541	if (ah->keysize == 0) {
5542		/*
5543		 * Transform takes arbitrary key size but algorithm
5544		 * key size is restricted.  Enforce this here.
5545		 */
5546		switch (alg) {
5547		case SADB_X_AALG_MD5:	*min = *max = 16; break;
5548		case SADB_X_AALG_SHA:	*min = *max = 20; break;
5549		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
5550		default:
5551			DPRINTF(("%s: unknown AH algorithm %u\n",
5552				__func__, alg));
5553			break;
5554		}
5555	}
5556}
5557
5558/*
5559 * XXX reorder combinations by preference
5560 */
5561static struct mbuf *
5562key_getcomb_ah()
5563{
5564	INIT_VNET_IPSEC(curvnet);
5565	struct sadb_comb *comb;
5566	struct auth_hash *algo;
5567	struct mbuf *m;
5568	u_int16_t minkeysize, maxkeysize;
5569	int i;
5570	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5571
5572	m = NULL;
5573	for (i = 1; i <= SADB_AALG_MAX; i++) {
5574#if 1
5575		/* we prefer HMAC algorithms, not old algorithms */
5576		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5577			continue;
5578#endif
5579		algo = ah_algorithm_lookup(i);
5580		if (!algo)
5581			continue;
5582		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5583		/* discard algorithms with key size smaller than system min */
5584		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
5585			continue;
5586
5587		if (!m) {
5588			IPSEC_ASSERT(l <= MLEN,
5589				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5590			MGET(m, M_DONTWAIT, MT_DATA);
5591			if (m) {
5592				M_ALIGN(m, l);
5593				m->m_len = l;
5594				m->m_next = NULL;
5595			}
5596		} else
5597			M_PREPEND(m, l, M_DONTWAIT);
5598		if (!m)
5599			return NULL;
5600
5601		comb = mtod(m, struct sadb_comb *);
5602		bzero(comb, sizeof(*comb));
5603		key_getcomb_setlifetime(comb);
5604		comb->sadb_comb_auth = i;
5605		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5606		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5607	}
5608
5609	return m;
5610}
5611
5612/*
5613 * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5614 * XXX reorder combinations by preference
5615 */
5616static struct mbuf *
5617key_getcomb_ipcomp()
5618{
5619	struct sadb_comb *comb;
5620	struct comp_algo *algo;
5621	struct mbuf *m;
5622	int i;
5623	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5624
5625	m = NULL;
5626	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5627		algo = ipcomp_algorithm_lookup(i);
5628		if (!algo)
5629			continue;
5630
5631		if (!m) {
5632			IPSEC_ASSERT(l <= MLEN,
5633				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5634			MGET(m, M_DONTWAIT, MT_DATA);
5635			if (m) {
5636				M_ALIGN(m, l);
5637				m->m_len = l;
5638				m->m_next = NULL;
5639			}
5640		} else
5641			M_PREPEND(m, l, M_DONTWAIT);
5642		if (!m)
5643			return NULL;
5644
5645		comb = mtod(m, struct sadb_comb *);
5646		bzero(comb, sizeof(*comb));
5647		key_getcomb_setlifetime(comb);
5648		comb->sadb_comb_encrypt = i;
5649		/* what should we set into sadb_comb_*_{min,max}bits? */
5650	}
5651
5652	return m;
5653}
5654
5655/*
5656 * XXX no way to pass mode (transport/tunnel) to userland
5657 * XXX replay checking?
5658 * XXX sysctl interface to ipsec_{ah,esp}_keymin
5659 */
5660static struct mbuf *
5661key_getprop(saidx)
5662	const struct secasindex *saidx;
5663{
5664	struct sadb_prop *prop;
5665	struct mbuf *m, *n;
5666	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5667	int totlen;
5668
5669	switch (saidx->proto)  {
5670	case IPPROTO_ESP:
5671		m = key_getcomb_esp();
5672		break;
5673	case IPPROTO_AH:
5674		m = key_getcomb_ah();
5675		break;
5676	case IPPROTO_IPCOMP:
5677		m = key_getcomb_ipcomp();
5678		break;
5679	default:
5680		return NULL;
5681	}
5682
5683	if (!m)
5684		return NULL;
5685	M_PREPEND(m, l, M_DONTWAIT);
5686	if (!m)
5687		return NULL;
5688
5689	totlen = 0;
5690	for (n = m; n; n = n->m_next)
5691		totlen += n->m_len;
5692
5693	prop = mtod(m, struct sadb_prop *);
5694	bzero(prop, sizeof(*prop));
5695	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5696	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5697	prop->sadb_prop_replay = 32;	/* XXX */
5698
5699	return m;
5700}
5701
5702/*
5703 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5704 * send
5705 *   <base, SA, address(SD), (address(P)), x_policy,
5706 *       (identity(SD),) (sensitivity,) proposal>
5707 * to KMD, and expect to receive
5708 *   <base> with SADB_ACQUIRE if error occured,
5709 * or
5710 *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5711 * from KMD by PF_KEY.
5712 *
5713 * XXX x_policy is outside of RFC2367 (KAME extension).
5714 * XXX sensitivity is not supported.
5715 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5716 * see comment for key_getcomb_ipcomp().
5717 *
5718 * OUT:
5719 *    0     : succeed
5720 *    others: error number
5721 */
5722static int
5723key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5724{
5725	INIT_VNET_IPSEC(curvnet);
5726	struct mbuf *result = NULL, *m;
5727	struct secacq *newacq;
5728	u_int8_t satype;
5729	int error = -1;
5730	u_int32_t seq;
5731
5732	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
5733	satype = key_proto2satype(saidx->proto);
5734	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
5735
5736	/*
5737	 * We never do anything about acquirng SA.  There is anather
5738	 * solution that kernel blocks to send SADB_ACQUIRE message until
5739	 * getting something message from IKEd.  In later case, to be
5740	 * managed with ACQUIRING list.
5741	 */
5742	/* Get an entry to check whether sending message or not. */
5743	if ((newacq = key_getacq(saidx)) != NULL) {
5744		if (V_key_blockacq_count < newacq->count) {
5745			/* reset counter and do send message. */
5746			newacq->count = 0;
5747		} else {
5748			/* increment counter and do nothing. */
5749			newacq->count++;
5750			return 0;
5751		}
5752	} else {
5753		/* make new entry for blocking to send SADB_ACQUIRE. */
5754		if ((newacq = key_newacq(saidx)) == NULL)
5755			return ENOBUFS;
5756	}
5757
5758
5759	seq = newacq->seq;
5760	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5761	if (!m) {
5762		error = ENOBUFS;
5763		goto fail;
5764	}
5765	result = m;
5766
5767	/* set sadb_address for saidx's. */
5768	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5769	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5770	if (!m) {
5771		error = ENOBUFS;
5772		goto fail;
5773	}
5774	m_cat(result, m);
5775
5776	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5777	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5778	if (!m) {
5779		error = ENOBUFS;
5780		goto fail;
5781	}
5782	m_cat(result, m);
5783
5784	/* XXX proxy address (optional) */
5785
5786	/* set sadb_x_policy */
5787	if (sp) {
5788		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5789		if (!m) {
5790			error = ENOBUFS;
5791			goto fail;
5792		}
5793		m_cat(result, m);
5794	}
5795
5796	/* XXX identity (optional) */
5797#if 0
5798	if (idexttype && fqdn) {
5799		/* create identity extension (FQDN) */
5800		struct sadb_ident *id;
5801		int fqdnlen;
5802
5803		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
5804		id = (struct sadb_ident *)p;
5805		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5806		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5807		id->sadb_ident_exttype = idexttype;
5808		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5809		bcopy(fqdn, id + 1, fqdnlen);
5810		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5811	}
5812
5813	if (idexttype) {
5814		/* create identity extension (USERFQDN) */
5815		struct sadb_ident *id;
5816		int userfqdnlen;
5817
5818		if (userfqdn) {
5819			/* +1 for terminating-NUL */
5820			userfqdnlen = strlen(userfqdn) + 1;
5821		} else
5822			userfqdnlen = 0;
5823		id = (struct sadb_ident *)p;
5824		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5825		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5826		id->sadb_ident_exttype = idexttype;
5827		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5828		/* XXX is it correct? */
5829		if (curproc && curproc->p_cred)
5830			id->sadb_ident_id = curproc->p_cred->p_ruid;
5831		if (userfqdn && userfqdnlen)
5832			bcopy(userfqdn, id + 1, userfqdnlen);
5833		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5834	}
5835#endif
5836
5837	/* XXX sensitivity (optional) */
5838
5839	/* create proposal/combination extension */
5840	m = key_getprop(saidx);
5841#if 0
5842	/*
5843	 * spec conformant: always attach proposal/combination extension,
5844	 * the problem is that we have no way to attach it for ipcomp,
5845	 * due to the way sadb_comb is declared in RFC2367.
5846	 */
5847	if (!m) {
5848		error = ENOBUFS;
5849		goto fail;
5850	}
5851	m_cat(result, m);
5852#else
5853	/*
5854	 * outside of spec; make proposal/combination extension optional.
5855	 */
5856	if (m)
5857		m_cat(result, m);
5858#endif
5859
5860	if ((result->m_flags & M_PKTHDR) == 0) {
5861		error = EINVAL;
5862		goto fail;
5863	}
5864
5865	if (result->m_len < sizeof(struct sadb_msg)) {
5866		result = m_pullup(result, sizeof(struct sadb_msg));
5867		if (result == NULL) {
5868			error = ENOBUFS;
5869			goto fail;
5870		}
5871	}
5872
5873	result->m_pkthdr.len = 0;
5874	for (m = result; m; m = m->m_next)
5875		result->m_pkthdr.len += m->m_len;
5876
5877	mtod(result, struct sadb_msg *)->sadb_msg_len =
5878	    PFKEY_UNIT64(result->m_pkthdr.len);
5879
5880	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5881
5882 fail:
5883	if (result)
5884		m_freem(result);
5885	return error;
5886}
5887
5888static struct secacq *
5889key_newacq(const struct secasindex *saidx)
5890{
5891	INIT_VNET_IPSEC(curvnet);
5892	struct secacq *newacq;
5893
5894	/* get new entry */
5895	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5896	if (newacq == NULL) {
5897		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5898		return NULL;
5899	}
5900
5901	/* copy secindex */
5902	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5903	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
5904	newacq->created = time_second;
5905	newacq->count = 0;
5906
5907	/* add to acqtree */
5908	ACQ_LOCK();
5909	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
5910	ACQ_UNLOCK();
5911
5912	return newacq;
5913}
5914
5915static struct secacq *
5916key_getacq(const struct secasindex *saidx)
5917{
5918	INIT_VNET_IPSEC(curvnet);
5919	struct secacq *acq;
5920
5921	ACQ_LOCK();
5922	LIST_FOREACH(acq, &V_acqtree, chain) {
5923		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5924			break;
5925	}
5926	ACQ_UNLOCK();
5927
5928	return acq;
5929}
5930
5931static struct secacq *
5932key_getacqbyseq(seq)
5933	u_int32_t seq;
5934{
5935	INIT_VNET_IPSEC(curvnet);
5936	struct secacq *acq;
5937
5938	ACQ_LOCK();
5939	LIST_FOREACH(acq, &V_acqtree, chain) {
5940		if (acq->seq == seq)
5941			break;
5942	}
5943	ACQ_UNLOCK();
5944
5945	return acq;
5946}
5947
5948static struct secspacq *
5949key_newspacq(spidx)
5950	struct secpolicyindex *spidx;
5951{
5952	INIT_VNET_IPSEC(curvnet);
5953	struct secspacq *acq;
5954
5955	/* get new entry */
5956	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5957	if (acq == NULL) {
5958		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5959		return NULL;
5960	}
5961
5962	/* copy secindex */
5963	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5964	acq->created = time_second;
5965	acq->count = 0;
5966
5967	/* add to spacqtree */
5968	SPACQ_LOCK();
5969	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
5970	SPACQ_UNLOCK();
5971
5972	return acq;
5973}
5974
5975static struct secspacq *
5976key_getspacq(spidx)
5977	struct secpolicyindex *spidx;
5978{
5979	INIT_VNET_IPSEC(curvnet);
5980	struct secspacq *acq;
5981
5982	SPACQ_LOCK();
5983	LIST_FOREACH(acq, &V_spacqtree, chain) {
5984		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
5985			/* NB: return holding spacq_lock */
5986			return acq;
5987		}
5988	}
5989	SPACQ_UNLOCK();
5990
5991	return NULL;
5992}
5993
5994/*
5995 * SADB_ACQUIRE processing,
5996 * in first situation, is receiving
5997 *   <base>
5998 * from the ikmpd, and clear sequence of its secasvar entry.
5999 *
6000 * In second situation, is receiving
6001 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6002 * from a user land process, and return
6003 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6004 * to the socket.
6005 *
6006 * m will always be freed.
6007 */
6008static int
6009key_acquire2(so, m, mhp)
6010	struct socket *so;
6011	struct mbuf *m;
6012	const struct sadb_msghdr *mhp;
6013{
6014	INIT_VNET_IPSEC(curvnet);
6015	const struct sadb_address *src0, *dst0;
6016	struct secasindex saidx;
6017	struct secashead *sah;
6018	u_int16_t proto;
6019	int error;
6020
6021	IPSEC_ASSERT(so != NULL, ("null socket"));
6022	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6023	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6024	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6025
6026	/*
6027	 * Error message from KMd.
6028	 * We assume that if error was occured in IKEd, the length of PFKEY
6029	 * message is equal to the size of sadb_msg structure.
6030	 * We do not raise error even if error occured in this function.
6031	 */
6032	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6033		struct secacq *acq;
6034
6035		/* check sequence number */
6036		if (mhp->msg->sadb_msg_seq == 0) {
6037			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6038				"number.\n", __func__));
6039			m_freem(m);
6040			return 0;
6041		}
6042
6043		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6044			/*
6045			 * the specified larval SA is already gone, or we got
6046			 * a bogus sequence number.  we can silently ignore it.
6047			 */
6048			m_freem(m);
6049			return 0;
6050		}
6051
6052		/* reset acq counter in order to deletion by timehander. */
6053		acq->created = time_second;
6054		acq->count = 0;
6055		m_freem(m);
6056		return 0;
6057	}
6058
6059	/*
6060	 * This message is from user land.
6061	 */
6062
6063	/* map satype to proto */
6064	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6065		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6066			__func__));
6067		return key_senderror(so, m, EINVAL);
6068	}
6069
6070	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6071	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6072	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6073		/* error */
6074		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6075			__func__));
6076		return key_senderror(so, m, EINVAL);
6077	}
6078	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6079	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6080	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6081		/* error */
6082		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6083			__func__));
6084		return key_senderror(so, m, EINVAL);
6085	}
6086
6087	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6088	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6089
6090	/* XXX boundary check against sa_len */
6091	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6092
6093	/* get a SA index */
6094	SAHTREE_LOCK();
6095	LIST_FOREACH(sah, &V_sahtree, chain) {
6096		if (sah->state == SADB_SASTATE_DEAD)
6097			continue;
6098		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6099			break;
6100	}
6101	SAHTREE_UNLOCK();
6102	if (sah != NULL) {
6103		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6104		return key_senderror(so, m, EEXIST);
6105	}
6106
6107	error = key_acquire(&saidx, NULL);
6108	if (error != 0) {
6109		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6110			__func__, mhp->msg->sadb_msg_errno));
6111		return key_senderror(so, m, error);
6112	}
6113
6114	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6115}
6116
6117/*
6118 * SADB_REGISTER processing.
6119 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6120 * receive
6121 *   <base>
6122 * from the ikmpd, and register a socket to send PF_KEY messages,
6123 * and send
6124 *   <base, supported>
6125 * to KMD by PF_KEY.
6126 * If socket is detached, must free from regnode.
6127 *
6128 * m will always be freed.
6129 */
6130static int
6131key_register(so, m, mhp)
6132	struct socket *so;
6133	struct mbuf *m;
6134	const struct sadb_msghdr *mhp;
6135{
6136	INIT_VNET_IPSEC(curvnet);
6137	struct secreg *reg, *newreg = 0;
6138
6139	IPSEC_ASSERT(so != NULL, ("null socket"));
6140	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6141	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6142	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6143
6144	/* check for invalid register message */
6145	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6146		return key_senderror(so, m, EINVAL);
6147
6148	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6149	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6150		goto setmsg;
6151
6152	/* check whether existing or not */
6153	REGTREE_LOCK();
6154	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6155		if (reg->so == so) {
6156			REGTREE_UNLOCK();
6157			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6158				__func__));
6159			return key_senderror(so, m, EEXIST);
6160		}
6161	}
6162
6163	/* create regnode */
6164	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6165	if (newreg == NULL) {
6166		REGTREE_UNLOCK();
6167		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6168		return key_senderror(so, m, ENOBUFS);
6169	}
6170
6171	newreg->so = so;
6172	((struct keycb *)sotorawcb(so))->kp_registered++;
6173
6174	/* add regnode to regtree. */
6175	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6176	REGTREE_UNLOCK();
6177
6178  setmsg:
6179    {
6180	struct mbuf *n;
6181	struct sadb_msg *newmsg;
6182	struct sadb_supported *sup;
6183	u_int len, alen, elen;
6184	int off;
6185	int i;
6186	struct sadb_alg *alg;
6187
6188	/* create new sadb_msg to reply. */
6189	alen = 0;
6190	for (i = 1; i <= SADB_AALG_MAX; i++) {
6191		if (ah_algorithm_lookup(i))
6192			alen += sizeof(struct sadb_alg);
6193	}
6194	if (alen)
6195		alen += sizeof(struct sadb_supported);
6196	elen = 0;
6197	for (i = 1; i <= SADB_EALG_MAX; i++) {
6198		if (esp_algorithm_lookup(i))
6199			elen += sizeof(struct sadb_alg);
6200	}
6201	if (elen)
6202		elen += sizeof(struct sadb_supported);
6203
6204	len = sizeof(struct sadb_msg) + alen + elen;
6205
6206	if (len > MCLBYTES)
6207		return key_senderror(so, m, ENOBUFS);
6208
6209	MGETHDR(n, M_DONTWAIT, MT_DATA);
6210	if (len > MHLEN) {
6211		MCLGET(n, M_DONTWAIT);
6212		if ((n->m_flags & M_EXT) == 0) {
6213			m_freem(n);
6214			n = NULL;
6215		}
6216	}
6217	if (!n)
6218		return key_senderror(so, m, ENOBUFS);
6219
6220	n->m_pkthdr.len = n->m_len = len;
6221	n->m_next = NULL;
6222	off = 0;
6223
6224	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6225	newmsg = mtod(n, struct sadb_msg *);
6226	newmsg->sadb_msg_errno = 0;
6227	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6228	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6229
6230	/* for authentication algorithm */
6231	if (alen) {
6232		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6233		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6234		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6235		off += PFKEY_ALIGN8(sizeof(*sup));
6236
6237		for (i = 1; i <= SADB_AALG_MAX; i++) {
6238			struct auth_hash *aalgo;
6239			u_int16_t minkeysize, maxkeysize;
6240
6241			aalgo = ah_algorithm_lookup(i);
6242			if (!aalgo)
6243				continue;
6244			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6245			alg->sadb_alg_id = i;
6246			alg->sadb_alg_ivlen = 0;
6247			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6248			alg->sadb_alg_minbits = _BITS(minkeysize);
6249			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6250			off += PFKEY_ALIGN8(sizeof(*alg));
6251		}
6252	}
6253
6254	/* for encryption algorithm */
6255	if (elen) {
6256		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6257		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6258		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6259		off += PFKEY_ALIGN8(sizeof(*sup));
6260
6261		for (i = 1; i <= SADB_EALG_MAX; i++) {
6262			struct enc_xform *ealgo;
6263
6264			ealgo = esp_algorithm_lookup(i);
6265			if (!ealgo)
6266				continue;
6267			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6268			alg->sadb_alg_id = i;
6269			alg->sadb_alg_ivlen = ealgo->blocksize;
6270			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6271			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6272			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6273		}
6274	}
6275
6276	IPSEC_ASSERT(off == len,
6277		("length assumption failed (off %u len %u)", off, len));
6278
6279	m_freem(m);
6280	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6281    }
6282}
6283
6284/*
6285 * free secreg entry registered.
6286 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6287 */
6288void
6289key_freereg(struct socket *so)
6290{
6291	INIT_VNET_IPSEC(curvnet);
6292	struct secreg *reg;
6293	int i;
6294
6295	IPSEC_ASSERT(so != NULL, ("NULL so"));
6296
6297	/*
6298	 * check whether existing or not.
6299	 * check all type of SA, because there is a potential that
6300	 * one socket is registered to multiple type of SA.
6301	 */
6302	REGTREE_LOCK();
6303	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6304		LIST_FOREACH(reg, &V_regtree[i], chain) {
6305			if (reg->so == so && __LIST_CHAINED(reg)) {
6306				LIST_REMOVE(reg, chain);
6307				free(reg, M_IPSEC_SAR);
6308				break;
6309			}
6310		}
6311	}
6312	REGTREE_UNLOCK();
6313}
6314
6315/*
6316 * SADB_EXPIRE processing
6317 * send
6318 *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6319 * to KMD by PF_KEY.
6320 * NOTE: We send only soft lifetime extension.
6321 *
6322 * OUT:	0	: succeed
6323 *	others	: error number
6324 */
6325static int
6326key_expire(struct secasvar *sav)
6327{
6328	int s;
6329	int satype;
6330	struct mbuf *result = NULL, *m;
6331	int len;
6332	int error = -1;
6333	struct sadb_lifetime *lt;
6334
6335	/* XXX: Why do we lock ? */
6336	s = splnet();	/*called from softclock()*/
6337
6338	IPSEC_ASSERT (sav != NULL, ("null sav"));
6339	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6340
6341	/* set msg header */
6342	satype = key_proto2satype(sav->sah->saidx.proto);
6343	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6344	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6345	if (!m) {
6346		error = ENOBUFS;
6347		goto fail;
6348	}
6349	result = m;
6350
6351	/* create SA extension */
6352	m = key_setsadbsa(sav);
6353	if (!m) {
6354		error = ENOBUFS;
6355		goto fail;
6356	}
6357	m_cat(result, m);
6358
6359	/* create SA extension */
6360	m = key_setsadbxsa2(sav->sah->saidx.mode,
6361			sav->replay ? sav->replay->count : 0,
6362			sav->sah->saidx.reqid);
6363	if (!m) {
6364		error = ENOBUFS;
6365		goto fail;
6366	}
6367	m_cat(result, m);
6368
6369	/* create lifetime extension (current and soft) */
6370	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6371	m = key_alloc_mbuf(len);
6372	if (!m || m->m_next) {	/*XXX*/
6373		if (m)
6374			m_freem(m);
6375		error = ENOBUFS;
6376		goto fail;
6377	}
6378	bzero(mtod(m, caddr_t), len);
6379	lt = mtod(m, struct sadb_lifetime *);
6380	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6381	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6382	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6383	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6384	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6385	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6386	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6387	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6388	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6389	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6390	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6391	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6392	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6393	m_cat(result, m);
6394
6395	/* set sadb_address for source */
6396	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6397	    &sav->sah->saidx.src.sa,
6398	    FULLMASK, IPSEC_ULPROTO_ANY);
6399	if (!m) {
6400		error = ENOBUFS;
6401		goto fail;
6402	}
6403	m_cat(result, m);
6404
6405	/* set sadb_address for destination */
6406	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6407	    &sav->sah->saidx.dst.sa,
6408	    FULLMASK, IPSEC_ULPROTO_ANY);
6409	if (!m) {
6410		error = ENOBUFS;
6411		goto fail;
6412	}
6413	m_cat(result, m);
6414
6415	if ((result->m_flags & M_PKTHDR) == 0) {
6416		error = EINVAL;
6417		goto fail;
6418	}
6419
6420	if (result->m_len < sizeof(struct sadb_msg)) {
6421		result = m_pullup(result, sizeof(struct sadb_msg));
6422		if (result == NULL) {
6423			error = ENOBUFS;
6424			goto fail;
6425		}
6426	}
6427
6428	result->m_pkthdr.len = 0;
6429	for (m = result; m; m = m->m_next)
6430		result->m_pkthdr.len += m->m_len;
6431
6432	mtod(result, struct sadb_msg *)->sadb_msg_len =
6433	    PFKEY_UNIT64(result->m_pkthdr.len);
6434
6435	splx(s);
6436	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6437
6438 fail:
6439	if (result)
6440		m_freem(result);
6441	splx(s);
6442	return error;
6443}
6444
6445/*
6446 * SADB_FLUSH processing
6447 * receive
6448 *   <base>
6449 * from the ikmpd, and free all entries in secastree.
6450 * and send,
6451 *   <base>
6452 * to the ikmpd.
6453 * NOTE: to do is only marking SADB_SASTATE_DEAD.
6454 *
6455 * m will always be freed.
6456 */
6457static int
6458key_flush(so, m, mhp)
6459	struct socket *so;
6460	struct mbuf *m;
6461	const struct sadb_msghdr *mhp;
6462{
6463	INIT_VNET_IPSEC(curvnet);
6464	struct sadb_msg *newmsg;
6465	struct secashead *sah, *nextsah;
6466	struct secasvar *sav, *nextsav;
6467	u_int16_t proto;
6468	u_int8_t state;
6469	u_int stateidx;
6470
6471	IPSEC_ASSERT(so != NULL, ("null socket"));
6472	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6473	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6474
6475	/* map satype to proto */
6476	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6477		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6478			__func__));
6479		return key_senderror(so, m, EINVAL);
6480	}
6481
6482	/* no SATYPE specified, i.e. flushing all SA. */
6483	SAHTREE_LOCK();
6484	for (sah = LIST_FIRST(&V_sahtree);
6485	     sah != NULL;
6486	     sah = nextsah) {
6487		nextsah = LIST_NEXT(sah, chain);
6488
6489		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6490		 && proto != sah->saidx.proto)
6491			continue;
6492
6493		for (stateidx = 0;
6494		     stateidx < _ARRAYLEN(saorder_state_alive);
6495		     stateidx++) {
6496			state = saorder_state_any[stateidx];
6497			for (sav = LIST_FIRST(&sah->savtree[state]);
6498			     sav != NULL;
6499			     sav = nextsav) {
6500
6501				nextsav = LIST_NEXT(sav, chain);
6502
6503				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6504				KEY_FREESAV(&sav);
6505			}
6506		}
6507
6508		sah->state = SADB_SASTATE_DEAD;
6509	}
6510	SAHTREE_UNLOCK();
6511
6512	if (m->m_len < sizeof(struct sadb_msg) ||
6513	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6514		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6515		return key_senderror(so, m, ENOBUFS);
6516	}
6517
6518	if (m->m_next)
6519		m_freem(m->m_next);
6520	m->m_next = NULL;
6521	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6522	newmsg = mtod(m, struct sadb_msg *);
6523	newmsg->sadb_msg_errno = 0;
6524	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6525
6526	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6527}
6528
6529/*
6530 * SADB_DUMP processing
6531 * dump all entries including status of DEAD in SAD.
6532 * receive
6533 *   <base>
6534 * from the ikmpd, and dump all secasvar leaves
6535 * and send,
6536 *   <base> .....
6537 * to the ikmpd.
6538 *
6539 * m will always be freed.
6540 */
6541static int
6542key_dump(so, m, mhp)
6543	struct socket *so;
6544	struct mbuf *m;
6545	const struct sadb_msghdr *mhp;
6546{
6547	INIT_VNET_IPSEC(curvnet);
6548	struct secashead *sah;
6549	struct secasvar *sav;
6550	u_int16_t proto;
6551	u_int stateidx;
6552	u_int8_t satype;
6553	u_int8_t state;
6554	int cnt;
6555	struct sadb_msg *newmsg;
6556	struct mbuf *n;
6557
6558	IPSEC_ASSERT(so != NULL, ("null socket"));
6559	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6560	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6561	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6562
6563	/* map satype to proto */
6564	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6565		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6566			__func__));
6567		return key_senderror(so, m, EINVAL);
6568	}
6569
6570	/* count sav entries to be sent to the userland. */
6571	cnt = 0;
6572	SAHTREE_LOCK();
6573	LIST_FOREACH(sah, &V_sahtree, chain) {
6574		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6575		 && proto != sah->saidx.proto)
6576			continue;
6577
6578		for (stateidx = 0;
6579		     stateidx < _ARRAYLEN(saorder_state_any);
6580		     stateidx++) {
6581			state = saorder_state_any[stateidx];
6582			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6583				cnt++;
6584			}
6585		}
6586	}
6587
6588	if (cnt == 0) {
6589		SAHTREE_UNLOCK();
6590		return key_senderror(so, m, ENOENT);
6591	}
6592
6593	/* send this to the userland, one at a time. */
6594	newmsg = NULL;
6595	LIST_FOREACH(sah, &V_sahtree, chain) {
6596		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6597		 && proto != sah->saidx.proto)
6598			continue;
6599
6600		/* map proto to satype */
6601		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6602			SAHTREE_UNLOCK();
6603			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
6604				"SAD.\n", __func__));
6605			return key_senderror(so, m, EINVAL);
6606		}
6607
6608		for (stateidx = 0;
6609		     stateidx < _ARRAYLEN(saorder_state_any);
6610		     stateidx++) {
6611			state = saorder_state_any[stateidx];
6612			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6613				n = key_setdumpsa(sav, SADB_DUMP, satype,
6614				    --cnt, mhp->msg->sadb_msg_pid);
6615				if (!n) {
6616					SAHTREE_UNLOCK();
6617					return key_senderror(so, m, ENOBUFS);
6618				}
6619				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6620			}
6621		}
6622	}
6623	SAHTREE_UNLOCK();
6624
6625	m_freem(m);
6626	return 0;
6627}
6628
6629/*
6630 * SADB_X_PROMISC processing
6631 *
6632 * m will always be freed.
6633 */
6634static int
6635key_promisc(so, m, mhp)
6636	struct socket *so;
6637	struct mbuf *m;
6638	const struct sadb_msghdr *mhp;
6639{
6640	int olen;
6641
6642	IPSEC_ASSERT(so != NULL, ("null socket"));
6643	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6644	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6645	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6646
6647	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6648
6649	if (olen < sizeof(struct sadb_msg)) {
6650#if 1
6651		return key_senderror(so, m, EINVAL);
6652#else
6653		m_freem(m);
6654		return 0;
6655#endif
6656	} else if (olen == sizeof(struct sadb_msg)) {
6657		/* enable/disable promisc mode */
6658		struct keycb *kp;
6659
6660		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6661			return key_senderror(so, m, EINVAL);
6662		mhp->msg->sadb_msg_errno = 0;
6663		switch (mhp->msg->sadb_msg_satype) {
6664		case 0:
6665		case 1:
6666			kp->kp_promisc = mhp->msg->sadb_msg_satype;
6667			break;
6668		default:
6669			return key_senderror(so, m, EINVAL);
6670		}
6671
6672		/* send the original message back to everyone */
6673		mhp->msg->sadb_msg_errno = 0;
6674		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6675	} else {
6676		/* send packet as is */
6677
6678		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6679
6680		/* TODO: if sadb_msg_seq is specified, send to specific pid */
6681		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6682	}
6683}
6684
6685static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
6686		const struct sadb_msghdr *)) = {
6687	NULL,		/* SADB_RESERVED */
6688	key_getspi,	/* SADB_GETSPI */
6689	key_update,	/* SADB_UPDATE */
6690	key_add,	/* SADB_ADD */
6691	key_delete,	/* SADB_DELETE */
6692	key_get,	/* SADB_GET */
6693	key_acquire2,	/* SADB_ACQUIRE */
6694	key_register,	/* SADB_REGISTER */
6695	NULL,		/* SADB_EXPIRE */
6696	key_flush,	/* SADB_FLUSH */
6697	key_dump,	/* SADB_DUMP */
6698	key_promisc,	/* SADB_X_PROMISC */
6699	NULL,		/* SADB_X_PCHANGE */
6700	key_spdadd,	/* SADB_X_SPDUPDATE */
6701	key_spdadd,	/* SADB_X_SPDADD */
6702	key_spddelete,	/* SADB_X_SPDDELETE */
6703	key_spdget,	/* SADB_X_SPDGET */
6704	NULL,		/* SADB_X_SPDACQUIRE */
6705	key_spddump,	/* SADB_X_SPDDUMP */
6706	key_spdflush,	/* SADB_X_SPDFLUSH */
6707	key_spdadd,	/* SADB_X_SPDSETIDX */
6708	NULL,		/* SADB_X_SPDEXPIRE */
6709	key_spddelete2,	/* SADB_X_SPDDELETE2 */
6710};
6711
6712/*
6713 * parse sadb_msg buffer to process PFKEYv2,
6714 * and create a data to response if needed.
6715 * I think to be dealed with mbuf directly.
6716 * IN:
6717 *     msgp  : pointer to pointer to a received buffer pulluped.
6718 *             This is rewrited to response.
6719 *     so    : pointer to socket.
6720 * OUT:
6721 *    length for buffer to send to user process.
6722 */
6723int
6724key_parse(m, so)
6725	struct mbuf *m;
6726	struct socket *so;
6727{
6728	INIT_VNET_IPSEC(curvnet);
6729	struct sadb_msg *msg;
6730	struct sadb_msghdr mh;
6731	u_int orglen;
6732	int error;
6733	int target;
6734
6735	IPSEC_ASSERT(so != NULL, ("null socket"));
6736	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6737
6738#if 0	/*kdebug_sadb assumes msg in linear buffer*/
6739	KEYDEBUG(KEYDEBUG_KEY_DUMP,
6740		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
6741		kdebug_sadb(msg));
6742#endif
6743
6744	if (m->m_len < sizeof(struct sadb_msg)) {
6745		m = m_pullup(m, sizeof(struct sadb_msg));
6746		if (!m)
6747			return ENOBUFS;
6748	}
6749	msg = mtod(m, struct sadb_msg *);
6750	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6751	target = KEY_SENDUP_ONE;
6752
6753	if ((m->m_flags & M_PKTHDR) == 0 ||
6754	    m->m_pkthdr.len != m->m_pkthdr.len) {
6755		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
6756		V_pfkeystat.out_invlen++;
6757		error = EINVAL;
6758		goto senderror;
6759	}
6760
6761	if (msg->sadb_msg_version != PF_KEY_V2) {
6762		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
6763		    __func__, msg->sadb_msg_version));
6764		V_pfkeystat.out_invver++;
6765		error = EINVAL;
6766		goto senderror;
6767	}
6768
6769	if (msg->sadb_msg_type > SADB_MAX) {
6770		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6771		    __func__, msg->sadb_msg_type));
6772		V_pfkeystat.out_invmsgtype++;
6773		error = EINVAL;
6774		goto senderror;
6775	}
6776
6777	/* for old-fashioned code - should be nuked */
6778	if (m->m_pkthdr.len > MCLBYTES) {
6779		m_freem(m);
6780		return ENOBUFS;
6781	}
6782	if (m->m_next) {
6783		struct mbuf *n;
6784
6785		MGETHDR(n, M_DONTWAIT, MT_DATA);
6786		if (n && m->m_pkthdr.len > MHLEN) {
6787			MCLGET(n, M_DONTWAIT);
6788			if ((n->m_flags & M_EXT) == 0) {
6789				m_free(n);
6790				n = NULL;
6791			}
6792		}
6793		if (!n) {
6794			m_freem(m);
6795			return ENOBUFS;
6796		}
6797		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6798		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6799		n->m_next = NULL;
6800		m_freem(m);
6801		m = n;
6802	}
6803
6804	/* align the mbuf chain so that extensions are in contiguous region. */
6805	error = key_align(m, &mh);
6806	if (error)
6807		return error;
6808
6809	msg = mh.msg;
6810
6811	/* check SA type */
6812	switch (msg->sadb_msg_satype) {
6813	case SADB_SATYPE_UNSPEC:
6814		switch (msg->sadb_msg_type) {
6815		case SADB_GETSPI:
6816		case SADB_UPDATE:
6817		case SADB_ADD:
6818		case SADB_DELETE:
6819		case SADB_GET:
6820		case SADB_ACQUIRE:
6821		case SADB_EXPIRE:
6822			ipseclog((LOG_DEBUG, "%s: must specify satype "
6823			    "when msg type=%u.\n", __func__,
6824			    msg->sadb_msg_type));
6825			V_pfkeystat.out_invsatype++;
6826			error = EINVAL;
6827			goto senderror;
6828		}
6829		break;
6830	case SADB_SATYPE_AH:
6831	case SADB_SATYPE_ESP:
6832	case SADB_X_SATYPE_IPCOMP:
6833	case SADB_X_SATYPE_TCPSIGNATURE:
6834		switch (msg->sadb_msg_type) {
6835		case SADB_X_SPDADD:
6836		case SADB_X_SPDDELETE:
6837		case SADB_X_SPDGET:
6838		case SADB_X_SPDDUMP:
6839		case SADB_X_SPDFLUSH:
6840		case SADB_X_SPDSETIDX:
6841		case SADB_X_SPDUPDATE:
6842		case SADB_X_SPDDELETE2:
6843			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
6844				__func__, msg->sadb_msg_type));
6845			V_pfkeystat.out_invsatype++;
6846			error = EINVAL;
6847			goto senderror;
6848		}
6849		break;
6850	case SADB_SATYPE_RSVP:
6851	case SADB_SATYPE_OSPFV2:
6852	case SADB_SATYPE_RIPV2:
6853	case SADB_SATYPE_MIP:
6854		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
6855			__func__, msg->sadb_msg_satype));
6856		V_pfkeystat.out_invsatype++;
6857		error = EOPNOTSUPP;
6858		goto senderror;
6859	case 1:	/* XXX: What does it do? */
6860		if (msg->sadb_msg_type == SADB_X_PROMISC)
6861			break;
6862		/*FALLTHROUGH*/
6863	default:
6864		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6865			__func__, msg->sadb_msg_satype));
6866		V_pfkeystat.out_invsatype++;
6867		error = EINVAL;
6868		goto senderror;
6869	}
6870
6871	/* check field of upper layer protocol and address family */
6872	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6873	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6874		struct sadb_address *src0, *dst0;
6875		u_int plen;
6876
6877		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6878		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6879
6880		/* check upper layer protocol */
6881		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6882			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
6883				"mismatched.\n", __func__));
6884			V_pfkeystat.out_invaddr++;
6885			error = EINVAL;
6886			goto senderror;
6887		}
6888
6889		/* check family */
6890		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6891		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
6892			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
6893				__func__));
6894			V_pfkeystat.out_invaddr++;
6895			error = EINVAL;
6896			goto senderror;
6897		}
6898		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6899		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
6900			ipseclog((LOG_DEBUG, "%s: address struct size "
6901				"mismatched.\n", __func__));
6902			V_pfkeystat.out_invaddr++;
6903			error = EINVAL;
6904			goto senderror;
6905		}
6906
6907		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6908		case AF_INET:
6909			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6910			    sizeof(struct sockaddr_in)) {
6911				V_pfkeystat.out_invaddr++;
6912				error = EINVAL;
6913				goto senderror;
6914			}
6915			break;
6916		case AF_INET6:
6917			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6918			    sizeof(struct sockaddr_in6)) {
6919				V_pfkeystat.out_invaddr++;
6920				error = EINVAL;
6921				goto senderror;
6922			}
6923			break;
6924		default:
6925			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
6926				__func__));
6927			V_pfkeystat.out_invaddr++;
6928			error = EAFNOSUPPORT;
6929			goto senderror;
6930		}
6931
6932		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6933		case AF_INET:
6934			plen = sizeof(struct in_addr) << 3;
6935			break;
6936		case AF_INET6:
6937			plen = sizeof(struct in6_addr) << 3;
6938			break;
6939		default:
6940			plen = 0;	/*fool gcc*/
6941			break;
6942		}
6943
6944		/* check max prefix length */
6945		if (src0->sadb_address_prefixlen > plen ||
6946		    dst0->sadb_address_prefixlen > plen) {
6947			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
6948				__func__));
6949			V_pfkeystat.out_invaddr++;
6950			error = EINVAL;
6951			goto senderror;
6952		}
6953
6954		/*
6955		 * prefixlen == 0 is valid because there can be a case when
6956		 * all addresses are matched.
6957		 */
6958	}
6959
6960	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
6961	    key_typesw[msg->sadb_msg_type] == NULL) {
6962		V_pfkeystat.out_invmsgtype++;
6963		error = EINVAL;
6964		goto senderror;
6965	}
6966
6967	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6968
6969senderror:
6970	msg->sadb_msg_errno = error;
6971	return key_sendup_mbuf(so, m, target);
6972}
6973
6974static int
6975key_senderror(so, m, code)
6976	struct socket *so;
6977	struct mbuf *m;
6978	int code;
6979{
6980	struct sadb_msg *msg;
6981
6982	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6983		("mbuf too small, len %u", m->m_len));
6984
6985	msg = mtod(m, struct sadb_msg *);
6986	msg->sadb_msg_errno = code;
6987	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
6988}
6989
6990/*
6991 * set the pointer to each header into message buffer.
6992 * m will be freed on error.
6993 * XXX larger-than-MCLBYTES extension?
6994 */
6995static int
6996key_align(m, mhp)
6997	struct mbuf *m;
6998	struct sadb_msghdr *mhp;
6999{
7000	INIT_VNET_IPSEC(curvnet);
7001	struct mbuf *n;
7002	struct sadb_ext *ext;
7003	size_t off, end;
7004	int extlen;
7005	int toff;
7006
7007	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7008	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7009	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7010		("mbuf too small, len %u", m->m_len));
7011
7012	/* initialize */
7013	bzero(mhp, sizeof(*mhp));
7014
7015	mhp->msg = mtod(m, struct sadb_msg *);
7016	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7017
7018	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7019	extlen = end;	/*just in case extlen is not updated*/
7020	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7021		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7022		if (!n) {
7023			/* m is already freed */
7024			return ENOBUFS;
7025		}
7026		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7027
7028		/* set pointer */
7029		switch (ext->sadb_ext_type) {
7030		case SADB_EXT_SA:
7031		case SADB_EXT_ADDRESS_SRC:
7032		case SADB_EXT_ADDRESS_DST:
7033		case SADB_EXT_ADDRESS_PROXY:
7034		case SADB_EXT_LIFETIME_CURRENT:
7035		case SADB_EXT_LIFETIME_HARD:
7036		case SADB_EXT_LIFETIME_SOFT:
7037		case SADB_EXT_KEY_AUTH:
7038		case SADB_EXT_KEY_ENCRYPT:
7039		case SADB_EXT_IDENTITY_SRC:
7040		case SADB_EXT_IDENTITY_DST:
7041		case SADB_EXT_SENSITIVITY:
7042		case SADB_EXT_PROPOSAL:
7043		case SADB_EXT_SUPPORTED_AUTH:
7044		case SADB_EXT_SUPPORTED_ENCRYPT:
7045		case SADB_EXT_SPIRANGE:
7046		case SADB_X_EXT_POLICY:
7047		case SADB_X_EXT_SA2:
7048			/* duplicate check */
7049			/*
7050			 * XXX Are there duplication payloads of either
7051			 * KEY_AUTH or KEY_ENCRYPT ?
7052			 */
7053			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7054				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7055					"%u\n", __func__, ext->sadb_ext_type));
7056				m_freem(m);
7057				V_pfkeystat.out_dupext++;
7058				return EINVAL;
7059			}
7060			break;
7061		default:
7062			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7063				__func__, ext->sadb_ext_type));
7064			m_freem(m);
7065			V_pfkeystat.out_invexttype++;
7066			return EINVAL;
7067		}
7068
7069		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7070
7071		if (key_validate_ext(ext, extlen)) {
7072			m_freem(m);
7073			V_pfkeystat.out_invlen++;
7074			return EINVAL;
7075		}
7076
7077		n = m_pulldown(m, off, extlen, &toff);
7078		if (!n) {
7079			/* m is already freed */
7080			return ENOBUFS;
7081		}
7082		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7083
7084		mhp->ext[ext->sadb_ext_type] = ext;
7085		mhp->extoff[ext->sadb_ext_type] = off;
7086		mhp->extlen[ext->sadb_ext_type] = extlen;
7087	}
7088
7089	if (off != end) {
7090		m_freem(m);
7091		V_pfkeystat.out_invlen++;
7092		return EINVAL;
7093	}
7094
7095	return 0;
7096}
7097
7098static int
7099key_validate_ext(ext, len)
7100	const struct sadb_ext *ext;
7101	int len;
7102{
7103	const struct sockaddr *sa;
7104	enum { NONE, ADDR } checktype = NONE;
7105	int baselen = 0;
7106	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7107
7108	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7109		return EINVAL;
7110
7111	/* if it does not match minimum/maximum length, bail */
7112	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7113	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7114		return EINVAL;
7115	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7116		return EINVAL;
7117	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7118		return EINVAL;
7119
7120	/* more checks based on sadb_ext_type XXX need more */
7121	switch (ext->sadb_ext_type) {
7122	case SADB_EXT_ADDRESS_SRC:
7123	case SADB_EXT_ADDRESS_DST:
7124	case SADB_EXT_ADDRESS_PROXY:
7125		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7126		checktype = ADDR;
7127		break;
7128	case SADB_EXT_IDENTITY_SRC:
7129	case SADB_EXT_IDENTITY_DST:
7130		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7131		    SADB_X_IDENTTYPE_ADDR) {
7132			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7133			checktype = ADDR;
7134		} else
7135			checktype = NONE;
7136		break;
7137	default:
7138		checktype = NONE;
7139		break;
7140	}
7141
7142	switch (checktype) {
7143	case NONE:
7144		break;
7145	case ADDR:
7146		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7147		if (len < baselen + sal)
7148			return EINVAL;
7149		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7150			return EINVAL;
7151		break;
7152	}
7153
7154	return 0;
7155}
7156
7157void
7158key_init(void)
7159{
7160	INIT_VNET_IPSEC(curvnet);
7161	int i;
7162
7163	V_key_debug_level = 0;
7164	V_key_spi_trycnt = 1000;
7165	V_key_spi_minval = 0x100;
7166	V_key_spi_maxval = 0x0fffffff;	/* XXX */
7167	V_policy_id = 0;
7168	V_key_int_random = 60;		/*interval to initialize randseed,1(m)*/
7169	V_key_larval_lifetime = 30;	/* interval to expire acquiring, 30(s)*/
7170	V_key_blockacq_count = 10;	/* counter for blocking SADB_ACQUIRE.*/
7171	V_key_blockacq_lifetime = 20;	/* lifetime for blocking SADB_ACQUIRE.*/
7172	V_key_preferred_oldsa = 1;	/* preferred old sa rather than new sa*/
7173
7174	V_acq_seq = 0;
7175
7176	V_ipsec_esp_keymin = 256;
7177	V_ipsec_esp_auth = 0;
7178	V_ipsec_ah_keymin = 128;
7179
7180	for (i = 0; i < IPSEC_DIR_MAX; i++)
7181		LIST_INIT(&V_sptree[i]);
7182
7183	LIST_INIT(&V_sahtree);
7184
7185	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7186		LIST_INIT(&V_regtree[i]);
7187
7188	LIST_INIT(&V_acqtree);
7189	LIST_INIT(&V_spacqtree);
7190
7191	/* system default */
7192	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7193	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7194
7195	if (!IS_DEFAULT_VNET(curvnet))
7196		return;
7197
7198	SPTREE_LOCK_INIT();
7199	REGTREE_LOCK_INIT();
7200	SAHTREE_LOCK_INIT();
7201	ACQ_LOCK_INIT();
7202	SPACQ_LOCK_INIT();
7203
7204#ifndef IPSEC_DEBUG2
7205	timeout((void *)key_timehandler, (void *)0, hz);
7206#endif /*IPSEC_DEBUG2*/
7207
7208	/* initialize key statistics */
7209	keystat.getspi_count = 1;
7210
7211	printf("IPsec: Initialized Security Association Processing.\n");
7212
7213	return;
7214}
7215
7216/*
7217 * XXX: maybe This function is called after INBOUND IPsec processing.
7218 *
7219 * Special check for tunnel-mode packets.
7220 * We must make some checks for consistency between inner and outer IP header.
7221 *
7222 * xxx more checks to be provided
7223 */
7224int
7225key_checktunnelsanity(sav, family, src, dst)
7226	struct secasvar *sav;
7227	u_int family;
7228	caddr_t src;
7229	caddr_t dst;
7230{
7231	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7232
7233	/* XXX: check inner IP header */
7234
7235	return 1;
7236}
7237
7238/* record data transfer on SA, and update timestamps */
7239void
7240key_sa_recordxfer(sav, m)
7241	struct secasvar *sav;
7242	struct mbuf *m;
7243{
7244	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7245	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7246	if (!sav->lft_c)
7247		return;
7248
7249	/*
7250	 * XXX Currently, there is a difference of bytes size
7251	 * between inbound and outbound processing.
7252	 */
7253	sav->lft_c->bytes += m->m_pkthdr.len;
7254	/* to check bytes lifetime is done in key_timehandler(). */
7255
7256	/*
7257	 * We use the number of packets as the unit of
7258	 * allocations.  We increment the variable
7259	 * whenever {esp,ah}_{in,out}put is called.
7260	 */
7261	sav->lft_c->allocations++;
7262	/* XXX check for expires? */
7263
7264	/*
7265	 * NOTE: We record CURRENT usetime by using wall clock,
7266	 * in seconds.  HARD and SOFT lifetime are measured by the time
7267	 * difference (again in seconds) from usetime.
7268	 *
7269	 *	usetime
7270	 *	v     expire   expire
7271	 * -----+-----+--------+---> t
7272	 *	<--------------> HARD
7273	 *	<-----> SOFT
7274	 */
7275	sav->lft_c->usetime = time_second;
7276	/* XXX check for expires? */
7277
7278	return;
7279}
7280
7281/* dumb version */
7282void
7283key_sa_routechange(dst)
7284	struct sockaddr *dst;
7285{
7286	INIT_VNET_IPSEC(curvnet);
7287	struct secashead *sah;
7288	struct route *ro;
7289
7290	SAHTREE_LOCK();
7291	LIST_FOREACH(sah, &V_sahtree, chain) {
7292		ro = &sah->sa_route;
7293		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7294		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7295			RTFREE(ro->ro_rt);
7296			ro->ro_rt = (struct rtentry *)NULL;
7297		}
7298	}
7299	SAHTREE_UNLOCK();
7300}
7301
7302static void
7303key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7304{
7305	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7306	SAHTREE_LOCK_ASSERT();
7307
7308	if (sav->state != state) {
7309		if (__LIST_CHAINED(sav))
7310			LIST_REMOVE(sav, chain);
7311		sav->state = state;
7312		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7313	}
7314}
7315
7316void
7317key_sa_stir_iv(sav)
7318	struct secasvar *sav;
7319{
7320
7321	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7322	key_randomfill(sav->iv, sav->ivlen);
7323}
7324
7325/* XXX too much? */
7326static struct mbuf *
7327key_alloc_mbuf(l)
7328	int l;
7329{
7330	struct mbuf *m = NULL, *n;
7331	int len, t;
7332
7333	len = l;
7334	while (len > 0) {
7335		MGET(n, M_DONTWAIT, MT_DATA);
7336		if (n && len > MLEN)
7337			MCLGET(n, M_DONTWAIT);
7338		if (!n) {
7339			m_freem(m);
7340			return NULL;
7341		}
7342
7343		n->m_next = NULL;
7344		n->m_len = 0;
7345		n->m_len = M_TRAILINGSPACE(n);
7346		/* use the bottom of mbuf, hoping we can prepend afterwards */
7347		if (n->m_len > len) {
7348			t = (n->m_len - len) & ~(sizeof(long) - 1);
7349			n->m_data += t;
7350			n->m_len = len;
7351		}
7352
7353		len -= n->m_len;
7354
7355		if (m)
7356			m_cat(m, n);
7357		else
7358			m = n;
7359	}
7360
7361	return m;
7362}
7363
7364/*
7365 * Take one of the kernel's security keys and convert it into a PF_KEY
7366 * structure within an mbuf, suitable for sending up to a waiting
7367 * application in user land.
7368 *
7369 * IN:
7370 *    src: A pointer to a kernel security key.
7371 *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
7372 * OUT:
7373 *    a valid mbuf or NULL indicating an error
7374 *
7375 */
7376
7377static struct mbuf *
7378key_setkey(struct seckey *src, u_int16_t exttype)
7379{
7380	struct mbuf *m;
7381	struct sadb_key *p;
7382	int len;
7383
7384	if (src == NULL)
7385		return NULL;
7386
7387	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
7388	m = key_alloc_mbuf(len);
7389	if (m == NULL)
7390		return NULL;
7391	p = mtod(m, struct sadb_key *);
7392	bzero(p, len);
7393	p->sadb_key_len = PFKEY_UNIT64(len);
7394	p->sadb_key_exttype = exttype;
7395	p->sadb_key_bits = src->bits;
7396	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
7397
7398	return m;
7399}
7400
7401/*
7402 * Take one of the kernel's lifetime data structures and convert it
7403 * into a PF_KEY structure within an mbuf, suitable for sending up to
7404 * a waiting application in user land.
7405 *
7406 * IN:
7407 *    src: A pointer to a kernel lifetime structure.
7408 *    exttype: Which type of lifetime this is. Refer to the PF_KEY
7409 *             data structures for more information.
7410 * OUT:
7411 *    a valid mbuf or NULL indicating an error
7412 *
7413 */
7414
7415static struct mbuf *
7416key_setlifetime(struct seclifetime *src, u_int16_t exttype)
7417{
7418	struct mbuf *m = NULL;
7419	struct sadb_lifetime *p;
7420	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
7421
7422	if (src == NULL)
7423		return NULL;
7424
7425	m = key_alloc_mbuf(len);
7426	if (m == NULL)
7427		return m;
7428	p = mtod(m, struct sadb_lifetime *);
7429
7430	bzero(p, len);
7431	p->sadb_lifetime_len = PFKEY_UNIT64(len);
7432	p->sadb_lifetime_exttype = exttype;
7433	p->sadb_lifetime_allocations = src->allocations;
7434	p->sadb_lifetime_bytes = src->bytes;
7435	p->sadb_lifetime_addtime = src->addtime;
7436	p->sadb_lifetime_usetime = src->usetime;
7437
7438	return m;
7439
7440}
7441