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