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