key.c revision 117051
1105197Ssam/*	$FreeBSD: head/sys/netipsec/key.c 117051 2003-06-29 23:58:38Z sam $	*/
2105197Ssam/*	$KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $	*/
3105197Ssam
4105197Ssam/*
5105197Ssam * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6105197Ssam * All rights reserved.
7105197Ssam *
8105197Ssam * Redistribution and use in source and binary forms, with or without
9105197Ssam * modification, are permitted provided that the following conditions
10105197Ssam * are met:
11105197Ssam * 1. Redistributions of source code must retain the above copyright
12105197Ssam *    notice, this list of conditions and the following disclaimer.
13105197Ssam * 2. Redistributions in binary form must reproduce the above copyright
14105197Ssam *    notice, this list of conditions and the following disclaimer in the
15105197Ssam *    documentation and/or other materials provided with the distribution.
16105197Ssam * 3. Neither the name of the project nor the names of its contributors
17105197Ssam *    may be used to endorse or promote products derived from this software
18105197Ssam *    without specific prior written permission.
19105197Ssam *
20105197Ssam * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21105197Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22105197Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23105197Ssam * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24105197Ssam * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25105197Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26105197Ssam * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27105197Ssam * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28105197Ssam * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29105197Ssam * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30105197Ssam * SUCH DAMAGE.
31105197Ssam */
32105197Ssam
33105197Ssam/*
34105197Ssam * This code is referd to RFC 2367
35105197Ssam */
36105197Ssam
37105197Ssam#include "opt_inet.h"
38105197Ssam#include "opt_inet6.h"
39105197Ssam#include "opt_ipsec.h"
40105197Ssam
41105197Ssam#include <sys/types.h>
42105197Ssam#include <sys/param.h>
43105197Ssam#include <sys/systm.h>
44105197Ssam#include <sys/kernel.h>
45105197Ssam#include <sys/mbuf.h>
46105197Ssam#include <sys/domain.h>
47105197Ssam#include <sys/protosw.h>
48105197Ssam#include <sys/malloc.h>
49105197Ssam#include <sys/socket.h>
50105197Ssam#include <sys/socketvar.h>
51105197Ssam#include <sys/sysctl.h>
52105197Ssam#include <sys/errno.h>
53105197Ssam#include <sys/proc.h>
54105197Ssam#include <sys/queue.h>
55105197Ssam#include <sys/syslog.h>
56105197Ssam
57105197Ssam#include <net/if.h>
58105197Ssam#include <net/route.h>
59105197Ssam#include <net/raw_cb.h>
60105197Ssam
61105197Ssam#include <netinet/in.h>
62105197Ssam#include <netinet/in_systm.h>
63105197Ssam#include <netinet/ip.h>
64105197Ssam#include <netinet/in_var.h>
65105197Ssam
66105197Ssam#ifdef INET6
67105197Ssam#include <netinet/ip6.h>
68105197Ssam#include <netinet6/in6_var.h>
69105197Ssam#include <netinet6/ip6_var.h>
70105197Ssam#endif /* INET6 */
71105197Ssam
72105197Ssam#ifdef INET
73105197Ssam#include <netinet/in_pcb.h>
74105197Ssam#endif
75105197Ssam#ifdef INET6
76105197Ssam#include <netinet6/in6_pcb.h>
77105197Ssam#endif /* INET6 */
78105197Ssam
79105197Ssam#include <net/pfkeyv2.h>
80105197Ssam#include <netipsec/keydb.h>
81105197Ssam#include <netipsec/key.h>
82105197Ssam#include <netipsec/keysock.h>
83105197Ssam#include <netipsec/key_debug.h>
84105197Ssam
85105197Ssam#include <netipsec/ipsec.h>
86105197Ssam#ifdef INET6
87105197Ssam#include <netipsec/ipsec6.h>
88105197Ssam#endif
89105197Ssam
90105197Ssam#include <netipsec/xform.h>
91105197Ssam
92105197Ssam#include <machine/stdarg.h>
93105197Ssam
94105197Ssam/* randomness */
95105197Ssam#include <sys/random.h>
96105197Ssam
97105197Ssam#include <net/net_osdep.h>
98105197Ssam
99105197Ssam#define FULLMASK	0xff
100105197Ssam#define	_BITS(bytes)	((bytes) << 3)
101105197Ssam
102105197Ssam/*
103105197Ssam * Note on SA reference counting:
104105197Ssam * - SAs that are not in DEAD state will have (total external reference + 1)
105105197Ssam *   following value in reference count field.  they cannot be freed and are
106105197Ssam *   referenced from SA header.
107105197Ssam * - SAs that are in DEAD state will have (total external reference)
108105197Ssam *   in reference count field.  they are ready to be freed.  reference from
109105197Ssam *   SA header will be removed in key_delsav(), when the reference count
110105197Ssam *   field hits 0 (= no external reference other than from SA header.
111105197Ssam */
112105197Ssam
113105197Ssamu_int32_t key_debug_level = 0;
114105197Ssamstatic u_int key_spi_trycnt = 1000;
115105197Ssamstatic u_int32_t key_spi_minval = 0x100;
116105197Ssamstatic u_int32_t key_spi_maxval = 0x0fffffff;	/* XXX */
117105197Ssamstatic u_int32_t policy_id = 0;
118105197Ssamstatic u_int key_int_random = 60;	/*interval to initialize randseed,1(m)*/
119105197Ssamstatic u_int key_larval_lifetime = 30;	/* interval to expire acquiring, 30(s)*/
120105197Ssamstatic int key_blockacq_count = 10;	/* counter for blocking SADB_ACQUIRE.*/
121105197Ssamstatic int key_blockacq_lifetime = 20;	/* lifetime for blocking SADB_ACQUIRE.*/
122105197Ssamstatic int key_prefered_oldsa = 1;	/* prefered old sa rather than new sa.*/
123105197Ssam
124105197Ssamstatic u_int32_t acq_seq = 0;
125105197Ssamstatic int key_tick_init_random = 0;
126105197Ssam
127105197Ssamstatic LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];	/* SPD */
128105197Ssamstatic LIST_HEAD(_sahtree, secashead) sahtree;			/* SAD */
129105197Ssamstatic LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
130105197Ssam							/* registed list */
131105197Ssam#ifndef IPSEC_NONBLOCK_ACQUIRE
132105197Ssamstatic LIST_HEAD(_acqtree, secacq) acqtree;		/* acquiring list */
133105197Ssam#endif
134105197Ssamstatic LIST_HEAD(_spacqtree, secspacq) spacqtree;	/* SP acquiring list */
135105197Ssam
136105197Ssam/* search order for SAs */
137105197Ssamstatic u_int saorder_state_valid[] = {
138105197Ssam	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
139105197Ssam	/*
140108533Sschweikh	 * This order is important because we must select the oldest SA
141105197Ssam	 * for outbound processing.  For inbound, This is not important.
142105197Ssam	 */
143105197Ssam};
144105197Ssamstatic u_int saorder_state_alive[] = {
145105197Ssam	/* except DEAD */
146105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
147105197Ssam};
148105197Ssamstatic u_int saorder_state_any[] = {
149105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
150105197Ssam	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
151105197Ssam};
152105197Ssam
153105197Ssamstatic const int minsize[] = {
154105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
155105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
156105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
157105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
158105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
159105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
160105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
161105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
162105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
163105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
164105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
165105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
166105197Ssam	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
167105197Ssam	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
168105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
169105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
170105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
171105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
172105197Ssam	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
173105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
174105197Ssam};
175105197Ssamstatic const int maxsize[] = {
176105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
177105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
178105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
179105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
180105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
181105197Ssam	0,				/* SADB_EXT_ADDRESS_SRC */
182105197Ssam	0,				/* SADB_EXT_ADDRESS_DST */
183105197Ssam	0,				/* SADB_EXT_ADDRESS_PROXY */
184105197Ssam	0,				/* SADB_EXT_KEY_AUTH */
185105197Ssam	0,				/* SADB_EXT_KEY_ENCRYPT */
186105197Ssam	0,				/* SADB_EXT_IDENTITY_SRC */
187105197Ssam	0,				/* SADB_EXT_IDENTITY_DST */
188105197Ssam	0,				/* SADB_EXT_SENSITIVITY */
189105197Ssam	0,				/* SADB_EXT_PROPOSAL */
190105197Ssam	0,				/* SADB_EXT_SUPPORTED_AUTH */
191105197Ssam	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
192105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
193105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
194105197Ssam	0,				/* SADB_X_EXT_POLICY */
195105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
196105197Ssam};
197105197Ssam
198105197Ssamstatic int ipsec_esp_keymin = 256;
199105197Ssamstatic int ipsec_esp_auth = 0;
200105197Ssamstatic int ipsec_ah_keymin = 128;
201105197Ssam
202105197Ssam#ifdef SYSCTL_DECL
203105197SsamSYSCTL_DECL(_net_key);
204105197Ssam#endif
205105197Ssam
206105197SsamSYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,	CTLFLAG_RW, \
207105197Ssam	&key_debug_level,	0,	"");
208105197Ssam
209105197Ssam/* max count of trial for the decision of spi value */
210105197SsamSYSCTL_INT(_net_key, KEYCTL_SPI_TRY,		spi_trycnt,	CTLFLAG_RW, \
211105197Ssam	&key_spi_trycnt,	0,	"");
212105197Ssam
213105197Ssam/* minimum spi value to allocate automatically. */
214105197SsamSYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,	spi_minval,	CTLFLAG_RW, \
215105197Ssam	&key_spi_minval,	0,	"");
216105197Ssam
217105197Ssam/* maximun spi value to allocate automatically. */
218105197SsamSYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,	spi_maxval,	CTLFLAG_RW, \
219105197Ssam	&key_spi_maxval,	0,	"");
220105197Ssam
221105197Ssam/* interval to initialize randseed */
222105197SsamSYSCTL_INT(_net_key, KEYCTL_RANDOM_INT,	int_random,	CTLFLAG_RW, \
223105197Ssam	&key_int_random,	0,	"");
224105197Ssam
225105197Ssam/* lifetime for larval SA */
226105197SsamSYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,	larval_lifetime, CTLFLAG_RW, \
227105197Ssam	&key_larval_lifetime,	0,	"");
228105197Ssam
229105197Ssam/* counter for blocking to send SADB_ACQUIRE to IKEd */
230105197SsamSYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,	blockacq_count,	CTLFLAG_RW, \
231105197Ssam	&key_blockacq_count,	0,	"");
232105197Ssam
233105197Ssam/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
234105197SsamSYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,	blockacq_lifetime, CTLFLAG_RW, \
235105197Ssam	&key_blockacq_lifetime,	0,	"");
236105197Ssam
237105197Ssam/* ESP auth */
238105197SsamSYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth, CTLFLAG_RW, \
239105197Ssam	&ipsec_esp_auth,	0,	"");
240105197Ssam
241105197Ssam/* minimum ESP key length */
242105197SsamSYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN,	esp_keymin, CTLFLAG_RW, \
243105197Ssam	&ipsec_esp_keymin,	0,	"");
244105197Ssam
245105197Ssam/* minimum AH key length */
246105197SsamSYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin, CTLFLAG_RW, \
247105197Ssam	&ipsec_ah_keymin,	0,	"");
248105197Ssam
249105197Ssam/* perfered old SA rather than new SA */
250105197SsamSYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,	prefered_oldsa, CTLFLAG_RW,\
251105197Ssam	&key_prefered_oldsa,	0,	"");
252105197Ssam
253105197Ssam#ifndef LIST_FOREACH
254105197Ssam#define LIST_FOREACH(elm, head, field)                                     \
255105197Ssam	for (elm = LIST_FIRST(head); elm; elm = LIST_NEXT(elm, field))
256105197Ssam#endif
257105197Ssam#define __LIST_CHAINED(elm) \
258105197Ssam	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
259105197Ssam#define LIST_INSERT_TAIL(head, elm, type, field) \
260105197Ssamdo {\
261105197Ssam	struct type *curelm = LIST_FIRST(head); \
262105197Ssam	if (curelm == NULL) {\
263105197Ssam		LIST_INSERT_HEAD(head, elm, field); \
264105197Ssam	} else { \
265105197Ssam		while (LIST_NEXT(curelm, field)) \
266105197Ssam			curelm = LIST_NEXT(curelm, field);\
267105197Ssam		LIST_INSERT_AFTER(curelm, elm, field);\
268105197Ssam	}\
269105197Ssam} while (0)
270105197Ssam
271105197Ssam#define KEY_CHKSASTATE(head, sav, name) \
272105197Ssamdo { \
273105197Ssam	if ((head) != (sav)) {						\
274105197Ssam		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
275105197Ssam			(name), (head), (sav)));			\
276105197Ssam		continue;						\
277105197Ssam	}								\
278105197Ssam} while (0)
279105197Ssam
280105197Ssam#define KEY_CHKSPDIR(head, sp, name) \
281105197Ssamdo { \
282105197Ssam	if ((head) != (sp)) {						\
283105197Ssam		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
284105197Ssam			"anyway continue.\n",				\
285105197Ssam			(name), (head), (sp)));				\
286105197Ssam	}								\
287105197Ssam} while (0)
288105197Ssam
289105197SsamMALLOC_DEFINE(M_SECA, "key mgmt", "security associations, key management");
290105197Ssam
291105197Ssam#if 1
292105197Ssam#define KMALLOC(p, t, n)                                                     \
293105197Ssam	((p) = (t) malloc((unsigned long)(n), M_SECA, M_NOWAIT))
294105197Ssam#define KFREE(p)                                                             \
295105197Ssam	free((caddr_t)(p), M_SECA)
296105197Ssam#else
297105197Ssam#define KMALLOC(p, t, n) \
298105197Ssamdo { \
299105197Ssam	((p) = (t)malloc((unsigned long)(n), M_SECA, M_NOWAIT));             \
300105197Ssam	printf("%s %d: %p <- KMALLOC(%s, %d)\n",                             \
301105197Ssam		__FILE__, __LINE__, (p), #t, n);                             \
302105197Ssam} while (0)
303105197Ssam
304105197Ssam#define KFREE(p)                                                             \
305105197Ssam	do {                                                                 \
306105197Ssam		printf("%s %d: %p -> KFREE()\n", __FILE__, __LINE__, (p));   \
307105197Ssam		free((caddr_t)(p), M_SECA);                                  \
308105197Ssam	} while (0)
309105197Ssam#endif
310105197Ssam
311105197Ssam/*
312105197Ssam * set parameters into secpolicyindex buffer.
313105197Ssam * Must allocate secpolicyindex buffer passed to this function.
314105197Ssam */
315105197Ssam#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
316105197Ssamdo { \
317105197Ssam	bzero((idx), sizeof(struct secpolicyindex));                         \
318105197Ssam	(idx)->dir = (_dir);                                                 \
319105197Ssam	(idx)->prefs = (ps);                                                 \
320105197Ssam	(idx)->prefd = (pd);                                                 \
321105197Ssam	(idx)->ul_proto = (ulp);                                             \
322105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
323105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
324105197Ssam} while (0)
325105197Ssam
326105197Ssam/*
327105197Ssam * set parameters into secasindex buffer.
328105197Ssam * Must allocate secasindex buffer before calling this function.
329105197Ssam */
330105197Ssam#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
331105197Ssamdo { \
332105197Ssam	bzero((idx), sizeof(struct secasindex));                             \
333105197Ssam	(idx)->proto = (p);                                                  \
334105197Ssam	(idx)->mode = (m);                                                   \
335105197Ssam	(idx)->reqid = (r);                                                  \
336105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
337105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
338105197Ssam} while (0)
339105197Ssam
340105197Ssam/* key statistics */
341105197Ssamstruct _keystat {
342105197Ssam	u_long getspi_count; /* the avarage of count to try to get new SPI */
343105197Ssam} keystat;
344105197Ssam
345105197Ssamstruct sadb_msghdr {
346105197Ssam	struct sadb_msg *msg;
347105197Ssam	struct sadb_ext *ext[SADB_EXT_MAX + 1];
348105197Ssam	int extoff[SADB_EXT_MAX + 1];
349105197Ssam	int extlen[SADB_EXT_MAX + 1];
350105197Ssam};
351105197Ssam
352105197Ssamstatic struct secasvar *key_allocsa_policy __P((const struct secasindex *));
353105197Ssamstatic void key_freesp_so __P((struct secpolicy **));
354105197Ssamstatic struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
355105197Ssamstatic void key_delsp __P((struct secpolicy *));
356105197Ssamstatic struct secpolicy *key_getsp __P((struct secpolicyindex *));
357105197Ssamstatic struct secpolicy *key_getspbyid __P((u_int32_t));
358105197Ssamstatic u_int32_t key_newreqid __P((void));
359105197Ssamstatic struct mbuf *key_gather_mbuf __P((struct mbuf *,
360105197Ssam	const struct sadb_msghdr *, int, int, ...));
361105197Ssamstatic int key_spdadd __P((struct socket *, struct mbuf *,
362105197Ssam	const struct sadb_msghdr *));
363105197Ssamstatic u_int32_t key_getnewspid __P((void));
364105197Ssamstatic int key_spddelete __P((struct socket *, struct mbuf *,
365105197Ssam	const struct sadb_msghdr *));
366105197Ssamstatic int key_spddelete2 __P((struct socket *, struct mbuf *,
367105197Ssam	const struct sadb_msghdr *));
368105197Ssamstatic int key_spdget __P((struct socket *, struct mbuf *,
369105197Ssam	const struct sadb_msghdr *));
370105197Ssamstatic int key_spdflush __P((struct socket *, struct mbuf *,
371105197Ssam	const struct sadb_msghdr *));
372105197Ssamstatic int key_spddump __P((struct socket *, struct mbuf *,
373105197Ssam	const struct sadb_msghdr *));
374105197Ssamstatic struct mbuf *key_setdumpsp __P((struct secpolicy *,
375105197Ssam	u_int8_t, u_int32_t, u_int32_t));
376105197Ssamstatic u_int key_getspreqmsglen __P((struct secpolicy *));
377105197Ssamstatic int key_spdexpire __P((struct secpolicy *));
378105197Ssamstatic struct secashead *key_newsah __P((struct secasindex *));
379105197Ssamstatic void key_delsah __P((struct secashead *));
380105197Ssamstatic struct secasvar *key_newsav __P((struct mbuf *,
381105197Ssam	const struct sadb_msghdr *, struct secashead *, int *,
382105197Ssam	const char*, int));
383105197Ssam#define	KEY_NEWSAV(m, sadb, sah, e)				\
384105197Ssam	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
385105197Ssamstatic void key_delsav __P((struct secasvar *));
386105197Ssamstatic struct secashead *key_getsah __P((struct secasindex *));
387105197Ssamstatic struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
388105197Ssamstatic struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
389105197Ssamstatic int key_setsaval __P((struct secasvar *, struct mbuf *,
390105197Ssam	const struct sadb_msghdr *));
391105197Ssamstatic int key_mature __P((struct secasvar *));
392105197Ssamstatic struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
393105197Ssam	u_int8_t, u_int32_t, u_int32_t));
394105197Ssamstatic struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
395105197Ssam	u_int32_t, pid_t, u_int16_t));
396105197Ssamstatic struct mbuf *key_setsadbsa __P((struct secasvar *));
397105197Ssamstatic struct mbuf *key_setsadbaddr __P((u_int16_t,
398105197Ssam	const struct sockaddr *, u_int8_t, u_int16_t));
399105197Ssam#if 0
400105197Ssamstatic struct mbuf *key_setsadbident __P((u_int16_t, u_int16_t, caddr_t,
401105197Ssam	int, u_int64_t));
402105197Ssam#endif
403105197Ssamstatic struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
404105197Ssamstatic struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
405105197Ssam	u_int32_t));
406105197Ssamstatic void *key_newbuf __P((const void *, u_int));
407105197Ssam#ifdef INET6
408105197Ssamstatic int key_ismyaddr6 __P((struct sockaddr_in6 *));
409105197Ssam#endif
410105197Ssam
411105197Ssam/* flags for key_cmpsaidx() */
412105197Ssam#define CMP_HEAD	1	/* protocol, addresses. */
413105197Ssam#define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
414105197Ssam#define CMP_REQID	3	/* additionally HEAD, reaid. */
415105197Ssam#define CMP_EXACTLY	4	/* all elements. */
416105197Ssamstatic int key_cmpsaidx
417105197Ssam	__P((const struct secasindex *, const struct secasindex *, int));
418105197Ssam
419105197Ssamstatic int key_cmpspidx_exactly
420105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
421105197Ssamstatic int key_cmpspidx_withmask
422105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
423105197Ssamstatic int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
424105197Ssamstatic int key_bbcmp __P((const void *, const void *, u_int));
425105197Ssamstatic void key_srandom __P((void));
426105197Ssamstatic u_int16_t key_satype2proto __P((u_int8_t));
427105197Ssamstatic u_int8_t key_proto2satype __P((u_int16_t));
428105197Ssam
429105197Ssamstatic int key_getspi __P((struct socket *, struct mbuf *,
430105197Ssam	const struct sadb_msghdr *));
431105197Ssamstatic u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
432105197Ssam					struct secasindex *));
433105197Ssamstatic int key_update __P((struct socket *, struct mbuf *,
434105197Ssam	const struct sadb_msghdr *));
435105197Ssam#ifdef IPSEC_DOSEQCHECK
436105197Ssamstatic struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
437105197Ssam#endif
438105197Ssamstatic int key_add __P((struct socket *, struct mbuf *,
439105197Ssam	const struct sadb_msghdr *));
440105197Ssamstatic int key_setident __P((struct secashead *, struct mbuf *,
441105197Ssam	const struct sadb_msghdr *));
442105197Ssamstatic struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
443105197Ssam	const struct sadb_msghdr *));
444105197Ssamstatic int key_delete __P((struct socket *, struct mbuf *,
445105197Ssam	const struct sadb_msghdr *));
446105197Ssamstatic int key_get __P((struct socket *, struct mbuf *,
447105197Ssam	const struct sadb_msghdr *));
448105197Ssam
449105197Ssamstatic void key_getcomb_setlifetime __P((struct sadb_comb *));
450105197Ssamstatic struct mbuf *key_getcomb_esp __P((void));
451105197Ssamstatic struct mbuf *key_getcomb_ah __P((void));
452105197Ssamstatic struct mbuf *key_getcomb_ipcomp __P((void));
453105197Ssamstatic struct mbuf *key_getprop __P((const struct secasindex *));
454105197Ssam
455105197Ssamstatic int key_acquire __P((const struct secasindex *, struct secpolicy *));
456105197Ssam#ifndef IPSEC_NONBLOCK_ACQUIRE
457105197Ssamstatic struct secacq *key_newacq __P((const struct secasindex *));
458105197Ssamstatic struct secacq *key_getacq __P((const struct secasindex *));
459105197Ssamstatic struct secacq *key_getacqbyseq __P((u_int32_t));
460105197Ssam#endif
461105197Ssamstatic struct secspacq *key_newspacq __P((struct secpolicyindex *));
462105197Ssamstatic struct secspacq *key_getspacq __P((struct secpolicyindex *));
463105197Ssamstatic int key_acquire2 __P((struct socket *, struct mbuf *,
464105197Ssam	const struct sadb_msghdr *));
465105197Ssamstatic int key_register __P((struct socket *, struct mbuf *,
466105197Ssam	const struct sadb_msghdr *));
467105197Ssamstatic int key_expire __P((struct secasvar *));
468105197Ssamstatic int key_flush __P((struct socket *, struct mbuf *,
469105197Ssam	const struct sadb_msghdr *));
470105197Ssamstatic int key_dump __P((struct socket *, struct mbuf *,
471105197Ssam	const struct sadb_msghdr *));
472105197Ssamstatic int key_promisc __P((struct socket *, struct mbuf *,
473105197Ssam	const struct sadb_msghdr *));
474105197Ssamstatic int key_senderror __P((struct socket *, struct mbuf *, int));
475105197Ssamstatic int key_validate_ext __P((const struct sadb_ext *, int));
476105197Ssamstatic int key_align __P((struct mbuf *, struct sadb_msghdr *));
477105197Ssam#if 0
478105197Ssamstatic const char *key_getfqdn __P((void));
479105197Ssamstatic const char *key_getuserfqdn __P((void));
480105197Ssam#endif
481105197Ssamstatic void key_sa_chgstate __P((struct secasvar *, u_int8_t));
482105197Ssamstatic struct mbuf *key_alloc_mbuf __P((int));
483105197Ssam
484105197Ssam#define	SA_ADDREF(p) do {						\
485105197Ssam	(p)->refcnt++;							\
486105197Ssam	KASSERT((p)->refcnt != 0,					\
487105197Ssam		("SA refcnt overflow at %s:%u", __FILE__, __LINE__));	\
488105197Ssam} while (0)
489105197Ssam#define	SA_DELREF(p) do {						\
490105197Ssam	KASSERT((p)->refcnt > 0,					\
491105197Ssam		("SA refcnt underflow at %s:%u", __FILE__, __LINE__));	\
492105197Ssam	(p)->refcnt--;							\
493105197Ssam} while (0)
494105197Ssam
495105197Ssam#define	SP_ADDREF(p) do {						\
496105197Ssam	(p)->refcnt++;							\
497105197Ssam	KASSERT((p)->refcnt != 0,					\
498105197Ssam		("SP refcnt overflow at %s:%u", __FILE__, __LINE__));	\
499105197Ssam} while (0)
500105197Ssam#define	SP_DELREF(p) do {						\
501105197Ssam	KASSERT((p)->refcnt > 0,					\
502105197Ssam		("SP refcnt underflow at %s:%u", __FILE__, __LINE__));	\
503105197Ssam	(p)->refcnt--;							\
504105197Ssam} while (0)
505105197Ssam
506105197Ssam/*
507105197Ssam * Return 0 when there are known to be no SP's for the specified
508105197Ssam * direction.  Otherwise return 1.  This is used by IPsec code
509105197Ssam * to optimize performance.
510105197Ssam */
511105197Ssamint
512105197Ssamkey_havesp(u_int dir)
513105197Ssam{
514105197Ssam	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
515105197Ssam		LIST_FIRST(&sptree[dir]) != NULL : 1);
516105197Ssam}
517105197Ssam
518105197Ssam/* %%% IPsec policy management */
519105197Ssam/*
520105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
521105197Ssam * Must call key_freesp() later.
522105197Ssam * OUT:	NULL:	not found
523105197Ssam *	others:	found and return the pointer.
524105197Ssam */
525105197Ssamstruct secpolicy *
526105197Ssamkey_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
527105197Ssam{
528105197Ssam	struct secpolicy *sp;
529105197Ssam	int s;
530105197Ssam
531105197Ssam	KASSERT(spidx != NULL, ("key_allocsp: null spidx"));
532105197Ssam	KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
533105197Ssam		("key_allocsp: invalid direction %u", dir));
534105197Ssam
535105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
536105197Ssam		printf("DP key_allocsp from %s:%u\n", where, tag));
537105197Ssam
538105197Ssam	/* get a SP entry */
539105197Ssam	s = splnet();	/*called from softclock()*/
540105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
541105197Ssam		printf("*** objects\n");
542105197Ssam		kdebug_secpolicyindex(spidx));
543105197Ssam
544105197Ssam	LIST_FOREACH(sp, &sptree[dir], chain) {
545105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
546105197Ssam			printf("*** in SPD\n");
547105197Ssam			kdebug_secpolicyindex(&sp->spidx));
548105197Ssam
549105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
550105197Ssam			continue;
551105197Ssam		if (key_cmpspidx_withmask(&sp->spidx, spidx))
552105197Ssam			goto found;
553105197Ssam	}
554105197Ssam	sp = NULL;
555105197Ssamfound:
556105197Ssam	if (sp) {
557105197Ssam		/* sanity check */
558105197Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp");
559105197Ssam
560105197Ssam		/* found a SPD entry */
561105197Ssam		sp->lastused = time_second;
562105197Ssam		SP_ADDREF(sp);
563105197Ssam	}
564105197Ssam	splx(s);
565105197Ssam
566105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
567105197Ssam		printf("DP key_allocsp return SP:%p (ID=%u) refcnt %u\n",
568105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
569105197Ssam	return sp;
570105197Ssam}
571105197Ssam
572105197Ssam/*
573105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
574105197Ssam * Must call key_freesp() later.
575105197Ssam * OUT:	NULL:	not found
576105197Ssam *	others:	found and return the pointer.
577105197Ssam */
578105197Ssamstruct secpolicy *
579105197Ssamkey_allocsp2(u_int32_t spi,
580105197Ssam	     union sockaddr_union *dst,
581105197Ssam	     u_int8_t proto,
582105197Ssam	     u_int dir,
583105197Ssam	     const char* where, int tag)
584105197Ssam{
585105197Ssam	struct secpolicy *sp;
586105197Ssam	int s;
587105197Ssam
588105197Ssam	KASSERT(dst != NULL, ("key_allocsp2: null dst"));
589105197Ssam	KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
590105197Ssam		("key_allocsp2: invalid direction %u", dir));
591105197Ssam
592105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
593105197Ssam		printf("DP key_allocsp2 from %s:%u\n", where, tag));
594105197Ssam
595105197Ssam	/* get a SP entry */
596105197Ssam	s = splnet();	/*called from softclock()*/
597105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
598105197Ssam		printf("*** objects\n");
599105197Ssam		printf("spi %u proto %u dir %u\n", spi, proto, dir);
600105197Ssam		kdebug_sockaddr(&dst->sa));
601105197Ssam
602105197Ssam	LIST_FOREACH(sp, &sptree[dir], chain) {
603105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
604105197Ssam			printf("*** in SPD\n");
605105197Ssam			kdebug_secpolicyindex(&sp->spidx));
606105197Ssam
607105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
608105197Ssam			continue;
609105197Ssam		/* compare simple values, then dst address */
610105197Ssam		if (sp->spidx.ul_proto != proto)
611105197Ssam			continue;
612105197Ssam		/* NB: spi's must exist and match */
613105197Ssam		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
614105197Ssam			continue;
615105197Ssam		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
616105197Ssam			goto found;
617105197Ssam	}
618105197Ssam	sp = NULL;
619105197Ssamfound:
620105197Ssam	if (sp) {
621105197Ssam		/* sanity check */
622105197Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp2");
623105197Ssam
624105197Ssam		/* found a SPD entry */
625105197Ssam		sp->lastused = time_second;
626105197Ssam		SP_ADDREF(sp);
627105197Ssam	}
628105197Ssam	splx(s);
629105197Ssam
630105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
631105197Ssam		printf("DP key_allocsp2 return SP:%p (ID=%u) refcnt %u\n",
632105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
633105197Ssam	return sp;
634105197Ssam}
635105197Ssam
636105197Ssam/*
637105197Ssam * return a policy that matches this particular inbound packet.
638105197Ssam * XXX slow
639105197Ssam */
640105197Ssamstruct secpolicy *
641105197Ssamkey_gettunnel(const struct sockaddr *osrc,
642105197Ssam	      const struct sockaddr *odst,
643105197Ssam	      const struct sockaddr *isrc,
644105197Ssam	      const struct sockaddr *idst,
645105197Ssam	      const char* where, int tag)
646105197Ssam{
647105197Ssam	struct secpolicy *sp;
648105197Ssam	const int dir = IPSEC_DIR_INBOUND;
649105197Ssam	int s;
650105197Ssam	struct ipsecrequest *r1, *r2, *p;
651105197Ssam	struct secpolicyindex spidx;
652105197Ssam
653105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
654105197Ssam		printf("DP key_gettunnel from %s:%u\n", where, tag));
655105197Ssam
656105197Ssam	if (isrc->sa_family != idst->sa_family) {
657105197Ssam		ipseclog((LOG_ERR, "protocol family mismatched %d != %d\n.",
658105197Ssam			isrc->sa_family, idst->sa_family));
659105197Ssam		sp = NULL;
660105197Ssam		goto done;
661105197Ssam	}
662105197Ssam
663105197Ssam	s = splnet();	/*called from softclock()*/
664105197Ssam	LIST_FOREACH(sp, &sptree[dir], chain) {
665105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
666105197Ssam			continue;
667105197Ssam
668105197Ssam		r1 = r2 = NULL;
669105197Ssam		for (p = sp->req; p; p = p->next) {
670105197Ssam			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
671105197Ssam				continue;
672105197Ssam
673105197Ssam			r1 = r2;
674105197Ssam			r2 = p;
675105197Ssam
676105197Ssam			if (!r1) {
677105197Ssam				/* here we look at address matches only */
678105197Ssam				spidx = sp->spidx;
679105197Ssam				if (isrc->sa_len > sizeof(spidx.src) ||
680105197Ssam				    idst->sa_len > sizeof(spidx.dst))
681105197Ssam					continue;
682105197Ssam				bcopy(isrc, &spidx.src, isrc->sa_len);
683105197Ssam				bcopy(idst, &spidx.dst, idst->sa_len);
684105197Ssam				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
685105197Ssam					continue;
686105197Ssam			} else {
687105197Ssam				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
688105197Ssam				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
689105197Ssam					continue;
690105197Ssam			}
691105197Ssam
692105197Ssam			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
693105197Ssam			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
694105197Ssam				continue;
695105197Ssam
696105197Ssam			goto found;
697105197Ssam		}
698105197Ssam	}
699105197Ssam	sp = NULL;
700105197Ssamfound:
701105197Ssam	if (sp) {
702105197Ssam		sp->lastused = time_second;
703105197Ssam		SP_ADDREF(sp);
704105197Ssam	}
705105197Ssam	splx(s);
706105197Ssamdone:
707105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
708105197Ssam		printf("DP key_gettunnel return SP:%p (ID=%u) refcnt %u\n",
709105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
710105197Ssam	return sp;
711105197Ssam}
712105197Ssam
713105197Ssam/*
714105197Ssam * allocating an SA entry for an *OUTBOUND* packet.
715105197Ssam * checking each request entries in SP, and acquire an SA if need.
716105197Ssam * OUT:	0: there are valid requests.
717105197Ssam *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
718105197Ssam */
719105197Ssamint
720105197Ssamkey_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
721105197Ssam{
722105197Ssam	u_int level;
723105197Ssam	int error;
724105197Ssam
725105197Ssam	KASSERT(isr != NULL, ("key_checkrequest: null isr"));
726105197Ssam	KASSERT(saidx != NULL, ("key_checkrequest: null saidx"));
727105197Ssam	KASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
728105197Ssam		saidx->mode == IPSEC_MODE_TUNNEL,
729105197Ssam		("key_checkrequest: unexpected policy %u", saidx->mode));
730105197Ssam
731105197Ssam	/* get current level */
732105197Ssam	level = ipsec_get_reqlevel(isr);
733105197Ssam
734105197Ssam	/*
735105197Ssam	 * XXX guard against protocol callbacks from the crypto
736105197Ssam	 * thread as they reference ipsecrequest.sav which we
737105197Ssam	 * temporarily null out below.  Need to rethink how we
738105197Ssam	 * handle bundled SA's in the callback thread.
739105197Ssam	 */
740105197Ssam#if 0
741105197Ssam	SPLASSERT(net, "key_checkrequest");
742105197Ssam#endif
743105197Ssam#if 0
744105197Ssam	/*
745105197Ssam	 * We do allocate new SA only if the state of SA in the holder is
746105197Ssam	 * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
747105197Ssam	 */
748105197Ssam	if (isr->sav != NULL) {
749105197Ssam		if (isr->sav->sah == NULL)
750105197Ssam			panic("key_checkrequest: sah is null.\n");
751105197Ssam		if (isr->sav == (struct secasvar *)LIST_FIRST(
752105197Ssam			    &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
753105197Ssam			KEY_FREESAV(&isr->sav);
754105197Ssam			isr->sav = NULL;
755105197Ssam		}
756105197Ssam	}
757105197Ssam#else
758105197Ssam	/*
759105197Ssam	 * we free any SA stashed in the IPsec request because a different
760105197Ssam	 * SA may be involved each time this request is checked, either
761105197Ssam	 * because new SAs are being configured, or this request is
762105197Ssam	 * associated with an unconnected datagram socket, or this request
763105197Ssam	 * is associated with a system default policy.
764105197Ssam	 *
765105197Ssam	 * The operation may have negative impact to performance.  We may
766105197Ssam	 * want to check cached SA carefully, rather than picking new SA
767105197Ssam	 * every time.
768105197Ssam	 */
769105197Ssam	if (isr->sav != NULL) {
770105197Ssam		KEY_FREESAV(&isr->sav);
771105197Ssam		isr->sav = NULL;
772105197Ssam	}
773105197Ssam#endif
774105197Ssam
775105197Ssam	/*
776105197Ssam	 * new SA allocation if no SA found.
777105197Ssam	 * key_allocsa_policy should allocate the oldest SA available.
778105197Ssam	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
779105197Ssam	 */
780105197Ssam	if (isr->sav == NULL)
781105197Ssam		isr->sav = key_allocsa_policy(saidx);
782105197Ssam
783105197Ssam	/* When there is SA. */
784105197Ssam	if (isr->sav != NULL) {
785105197Ssam		if (isr->sav->state != SADB_SASTATE_MATURE &&
786105197Ssam		    isr->sav->state != SADB_SASTATE_DYING)
787105197Ssam			return EINVAL;
788105197Ssam		return 0;
789105197Ssam	}
790105197Ssam
791105197Ssam	/* there is no SA */
792105197Ssam	error = key_acquire(saidx, isr->sp);
793105197Ssam	if (error != 0) {
794105197Ssam		/* XXX What should I do ? */
795105197Ssam		ipseclog((LOG_DEBUG, "key_checkrequest: error %d returned "
796105197Ssam			"from key_acquire.\n", error));
797105197Ssam		return error;
798105197Ssam	}
799105197Ssam
800105197Ssam	if (level != IPSEC_LEVEL_REQUIRE) {
801105197Ssam		/* XXX sigh, the interface to this routine is botched */
802105197Ssam		KASSERT(isr->sav == NULL, ("key_checkrequest: unexpected SA"));
803105197Ssam		return 0;
804105197Ssam	} else {
805105197Ssam		return ENOENT;
806105197Ssam	}
807105197Ssam}
808105197Ssam
809105197Ssam/*
810105197Ssam * allocating a SA for policy entry from SAD.
811105197Ssam * NOTE: searching SAD of aliving state.
812105197Ssam * OUT:	NULL:	not found.
813105197Ssam *	others:	found and return the pointer.
814105197Ssam */
815105197Ssamstatic struct secasvar *
816105197Ssamkey_allocsa_policy(const struct secasindex *saidx)
817105197Ssam{
818105197Ssam	struct secashead *sah;
819105197Ssam	struct secasvar *sav;
820105197Ssam	u_int stateidx, state;
821105197Ssam
822105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
823105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
824105197Ssam			continue;
825105197Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
826105197Ssam			goto found;
827105197Ssam	}
828105197Ssam
829105197Ssam	return NULL;
830105197Ssam
831105197Ssam    found:
832105197Ssam
833105197Ssam	/* search valid state */
834105197Ssam	for (stateidx = 0;
835105197Ssam	     stateidx < _ARRAYLEN(saorder_state_valid);
836105197Ssam	     stateidx++) {
837105197Ssam
838105197Ssam		state = saorder_state_valid[stateidx];
839105197Ssam
840105197Ssam		sav = key_do_allocsa_policy(sah, state);
841105197Ssam		if (sav != NULL)
842105197Ssam			return sav;
843105197Ssam	}
844105197Ssam
845105197Ssam	return NULL;
846105197Ssam}
847105197Ssam
848105197Ssam/*
849105197Ssam * searching SAD with direction, protocol, mode and state.
850105197Ssam * called by key_allocsa_policy().
851105197Ssam * OUT:
852105197Ssam *	NULL	: not found
853105197Ssam *	others	: found, pointer to a SA.
854105197Ssam */
855105197Ssamstatic struct secasvar *
856105197Ssamkey_do_allocsa_policy(struct secashead *sah, u_int state)
857105197Ssam{
858105197Ssam	struct secasvar *sav, *nextsav, *candidate, *d;
859105197Ssam
860105197Ssam	/* initilize */
861105197Ssam	candidate = NULL;
862105197Ssam
863105197Ssam	for (sav = LIST_FIRST(&sah->savtree[state]);
864105197Ssam	     sav != NULL;
865105197Ssam	     sav = nextsav) {
866105197Ssam
867105197Ssam		nextsav = LIST_NEXT(sav, chain);
868105197Ssam
869105197Ssam		/* sanity check */
870105197Ssam		KEY_CHKSASTATE(sav->state, state, "key_do_allocsa_policy");
871105197Ssam
872105197Ssam		/* initialize */
873105197Ssam		if (candidate == NULL) {
874105197Ssam			candidate = sav;
875105197Ssam			continue;
876105197Ssam		}
877105197Ssam
878105197Ssam		/* Which SA is the better ? */
879105197Ssam
880105197Ssam		/* sanity check 2 */
881105197Ssam		if (candidate->lft_c == NULL || sav->lft_c == NULL)
882105197Ssam			panic("key_do_allocsa_policy: "
883105197Ssam				"lifetime_current is NULL.\n");
884105197Ssam
885105197Ssam		/* What the best method is to compare ? */
886105197Ssam		if (key_prefered_oldsa) {
887105197Ssam			if (candidate->lft_c->sadb_lifetime_addtime >
888105197Ssam					sav->lft_c->sadb_lifetime_addtime) {
889105197Ssam				candidate = sav;
890105197Ssam			}
891105197Ssam			continue;
892105197Ssam			/*NOTREACHED*/
893105197Ssam		}
894105197Ssam
895105197Ssam		/* prefered new sa rather than old sa */
896105197Ssam		if (candidate->lft_c->sadb_lifetime_addtime <
897105197Ssam				sav->lft_c->sadb_lifetime_addtime) {
898105197Ssam			d = candidate;
899105197Ssam			candidate = sav;
900105197Ssam		} else
901105197Ssam			d = sav;
902105197Ssam
903105197Ssam		/*
904105197Ssam		 * prepared to delete the SA when there is more
905105197Ssam		 * suitable candidate and the lifetime of the SA is not
906105197Ssam		 * permanent.
907105197Ssam		 */
908105197Ssam		if (d->lft_c->sadb_lifetime_addtime != 0) {
909105197Ssam			struct mbuf *m, *result;
910105197Ssam
911105197Ssam			key_sa_chgstate(d, SADB_SASTATE_DEAD);
912105197Ssam
913105197Ssam			KASSERT(d->refcnt > 0,
914105197Ssam				("key_do_allocsa_policy: bogus ref count"));
915105197Ssam			m = key_setsadbmsg(SADB_DELETE, 0,
916105197Ssam			    d->sah->saidx.proto, 0, 0, d->refcnt - 1);
917105197Ssam			if (!m)
918105197Ssam				goto msgfail;
919105197Ssam			result = m;
920105197Ssam
921105197Ssam			/* set sadb_address for saidx's. */
922105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
923105197Ssam				&d->sah->saidx.src.sa,
924105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
925105197Ssam				IPSEC_ULPROTO_ANY);
926105197Ssam			if (!m)
927105197Ssam				goto msgfail;
928105197Ssam			m_cat(result, m);
929105197Ssam
930105197Ssam			/* set sadb_address for saidx's. */
931105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
932105197Ssam				&d->sah->saidx.src.sa,
933105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
934105197Ssam				IPSEC_ULPROTO_ANY);
935105197Ssam			if (!m)
936105197Ssam				goto msgfail;
937105197Ssam			m_cat(result, m);
938105197Ssam
939105197Ssam			/* create SA extension */
940105197Ssam			m = key_setsadbsa(d);
941105197Ssam			if (!m)
942105197Ssam				goto msgfail;
943105197Ssam			m_cat(result, m);
944105197Ssam
945105197Ssam			if (result->m_len < sizeof(struct sadb_msg)) {
946105197Ssam				result = m_pullup(result,
947105197Ssam						sizeof(struct sadb_msg));
948105197Ssam				if (result == NULL)
949105197Ssam					goto msgfail;
950105197Ssam			}
951105197Ssam
952105197Ssam			result->m_pkthdr.len = 0;
953105197Ssam			for (m = result; m; m = m->m_next)
954105197Ssam				result->m_pkthdr.len += m->m_len;
955105197Ssam			mtod(result, struct sadb_msg *)->sadb_msg_len =
956105197Ssam				PFKEY_UNIT64(result->m_pkthdr.len);
957105197Ssam
958105197Ssam			if (key_sendup_mbuf(NULL, result,
959105197Ssam					KEY_SENDUP_REGISTERED))
960105197Ssam				goto msgfail;
961105197Ssam		 msgfail:
962105197Ssam			KEY_FREESAV(&d);
963105197Ssam		}
964105197Ssam	}
965105197Ssam
966105197Ssam	if (candidate) {
967105197Ssam		SA_ADDREF(candidate);
968105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
969105197Ssam			printf("DP allocsa_policy cause "
970105197Ssam				"refcnt++:%d SA:%p\n",
971105197Ssam				candidate->refcnt, candidate));
972105197Ssam	}
973105197Ssam	return candidate;
974105197Ssam}
975105197Ssam
976105197Ssam/*
977105197Ssam * allocating a usable SA entry for a *INBOUND* packet.
978105197Ssam * Must call key_freesav() later.
979105197Ssam * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
980105197Ssam *	NULL:		not found, or error occured.
981105197Ssam *
982105197Ssam * In the comparison, no source address is used--for RFC2401 conformance.
983105197Ssam * To quote, from section 4.1:
984105197Ssam *	A security association is uniquely identified by a triple consisting
985105197Ssam *	of a Security Parameter Index (SPI), an IP Destination Address, and a
986105197Ssam *	security protocol (AH or ESP) identifier.
987105197Ssam * Note that, however, we do need to keep source address in IPsec SA.
988105197Ssam * IKE specification and PF_KEY specification do assume that we
989105197Ssam * keep source address in IPsec SA.  We see a tricky situation here.
990105197Ssam */
991105197Ssamstruct secasvar *
992105197Ssamkey_allocsa(
993105197Ssam	union sockaddr_union *dst,
994105197Ssam	u_int proto,
995105197Ssam	u_int32_t spi,
996105197Ssam	const char* where, int tag)
997105197Ssam{
998105197Ssam	struct secashead *sah;
999105197Ssam	struct secasvar *sav;
1000105197Ssam	u_int stateidx, state;
1001105197Ssam	int s;
1002105197Ssam
1003105197Ssam	KASSERT(dst != NULL, ("key_allocsa: null dst address"));
1004105197Ssam
1005105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1006105197Ssam		printf("DP key_allocsa from %s:%u\n", where, tag));
1007105197Ssam
1008105197Ssam	/*
1009105197Ssam	 * searching SAD.
1010105197Ssam	 * XXX: to be checked internal IP header somewhere.  Also when
1011105197Ssam	 * IPsec tunnel packet is received.  But ESP tunnel mode is
1012105197Ssam	 * encrypted so we can't check internal IP header.
1013105197Ssam	 */
1014105197Ssam	s = splnet();	/*called from softclock()*/
1015105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
1016105197Ssam		/* search valid state */
1017105197Ssam		for (stateidx = 0;
1018105197Ssam		     stateidx < _ARRAYLEN(saorder_state_valid);
1019105197Ssam		     stateidx++) {
1020105197Ssam			state = saorder_state_valid[stateidx];
1021105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
1022105197Ssam				/* sanity check */
1023105197Ssam				KEY_CHKSASTATE(sav->state, state, "key_allocsav");
1024105197Ssam				/* do not return entries w/ unusable state */
1025105197Ssam				if (sav->state != SADB_SASTATE_MATURE &&
1026105197Ssam				    sav->state != SADB_SASTATE_DYING)
1027105197Ssam					continue;
1028105197Ssam				if (proto != sav->sah->saidx.proto)
1029105197Ssam					continue;
1030105197Ssam				if (spi != sav->spi)
1031105197Ssam					continue;
1032105197Ssam#if 0	/* don't check src */
1033105197Ssam				/* check src address */
1034105197Ssam				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, 0) != 0)
1035105197Ssam					continue;
1036105197Ssam#endif
1037105197Ssam				/* check dst address */
1038105197Ssam				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, 0) != 0)
1039105197Ssam					continue;
1040105197Ssam				SA_ADDREF(sav);
1041105197Ssam				goto done;
1042105197Ssam			}
1043105197Ssam		}
1044105197Ssam	}
1045105197Ssam	sav = NULL;
1046105197Ssamdone:
1047105197Ssam	splx(s);
1048105197Ssam
1049105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1050105197Ssam		printf("DP key_allocsa return SA:%p; refcnt %u\n",
1051105197Ssam			sav, sav ? sav->refcnt : 0));
1052105197Ssam	return sav;
1053105197Ssam}
1054105197Ssam
1055105197Ssam/*
1056105197Ssam * Must be called after calling key_allocsp().
1057105197Ssam * For both the packet without socket and key_freeso().
1058105197Ssam */
1059105197Ssamvoid
1060105197Ssam_key_freesp(struct secpolicy **spp, const char* where, int tag)
1061105197Ssam{
1062105197Ssam	struct secpolicy *sp = *spp;
1063105197Ssam
1064105197Ssam	KASSERT(sp != NULL, ("key_freesp: null sp"));
1065105197Ssam
1066105197Ssam	SP_DELREF(sp);
1067105197Ssam
1068105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1069105197Ssam		printf("DP key_freesp SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1070105197Ssam			sp, sp->id, where, tag, sp->refcnt));
1071105197Ssam
1072105197Ssam	if (sp->refcnt == 0) {
1073105197Ssam		*spp = NULL;
1074105197Ssam		key_delsp(sp);
1075105197Ssam	}
1076105197Ssam}
1077105197Ssam
1078105197Ssam/*
1079105197Ssam * Must be called after calling key_allocsp().
1080105197Ssam * For the packet with socket.
1081105197Ssam */
1082105197Ssamvoid
1083105197Ssamkey_freeso(struct socket *so)
1084105197Ssam{
1085105197Ssam	/* sanity check */
1086105197Ssam	KASSERT(so != NULL, ("key_freeso: null so"));
1087105197Ssam
1088105197Ssam	switch (so->so_proto->pr_domain->dom_family) {
1089105197Ssam#ifdef INET
1090105197Ssam	case PF_INET:
1091105197Ssam	    {
1092105197Ssam		struct inpcb *pcb = sotoinpcb(so);
1093105197Ssam
1094105197Ssam		/* Does it have a PCB ? */
1095105197Ssam		if (pcb == NULL)
1096105197Ssam			return;
1097105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1098105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1099105197Ssam	    }
1100105197Ssam		break;
1101105197Ssam#endif
1102105197Ssam#ifdef INET6
1103105197Ssam	case PF_INET6:
1104105197Ssam	    {
1105105197Ssam#ifdef HAVE_NRL_INPCB
1106105197Ssam		struct inpcb *pcb  = sotoinpcb(so);
1107105197Ssam
1108105197Ssam		/* Does it have a PCB ? */
1109105197Ssam		if (pcb == NULL)
1110105197Ssam			return;
1111105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1112105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1113105197Ssam#else
1114105197Ssam		struct in6pcb *pcb  = sotoin6pcb(so);
1115105197Ssam
1116105197Ssam		/* Does it have a PCB ? */
1117105197Ssam		if (pcb == NULL)
1118105197Ssam			return;
1119105197Ssam		key_freesp_so(&pcb->in6p_sp->sp_in);
1120105197Ssam		key_freesp_so(&pcb->in6p_sp->sp_out);
1121105197Ssam#endif
1122105197Ssam	    }
1123105197Ssam		break;
1124105197Ssam#endif /* INET6 */
1125105197Ssam	default:
1126105197Ssam		ipseclog((LOG_DEBUG, "key_freeso: unknown address family=%d.\n",
1127105197Ssam		    so->so_proto->pr_domain->dom_family));
1128105197Ssam		return;
1129105197Ssam	}
1130105197Ssam}
1131105197Ssam
1132105197Ssamstatic void
1133105197Ssamkey_freesp_so(struct secpolicy **sp)
1134105197Ssam{
1135105197Ssam	KASSERT(sp != NULL && *sp != NULL, ("key_freesp_so: null sp"));
1136105197Ssam
1137105197Ssam	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1138105197Ssam	    (*sp)->policy == IPSEC_POLICY_BYPASS)
1139105197Ssam		return;
1140105197Ssam
1141105197Ssam	KASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1142105197Ssam		("key_freesp_so: invalid policy %u", (*sp)->policy));
1143105197Ssam	KEY_FREESP(sp);
1144105197Ssam}
1145105197Ssam
1146105197Ssam/*
1147105197Ssam * Must be called after calling key_allocsa().
1148105197Ssam * This function is called by key_freesp() to free some SA allocated
1149105197Ssam * for a policy.
1150105197Ssam */
1151105197Ssamvoid
1152105197Ssamkey_freesav(struct secasvar **psav, const char* where, int tag)
1153105197Ssam{
1154105197Ssam	struct secasvar *sav = *psav;
1155105197Ssam
1156105197Ssam	KASSERT(sav != NULL, ("key_freesav: null sav"));
1157105197Ssam
1158105197Ssam	SA_DELREF(sav);
1159105197Ssam
1160105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1161105197Ssam		printf("DP key_freesav SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1162105197Ssam			sav, ntohl(sav->spi), where, tag, sav->refcnt));
1163105197Ssam
1164105197Ssam	if (sav->refcnt == 0) {
1165105197Ssam		*psav = NULL;
1166105197Ssam		key_delsav(sav);
1167105197Ssam	}
1168105197Ssam}
1169105197Ssam
1170105197Ssam/* %%% SPD management */
1171105197Ssam/*
1172105197Ssam * free security policy entry.
1173105197Ssam */
1174105197Ssamstatic void
1175105197Ssamkey_delsp(struct secpolicy *sp)
1176105197Ssam{
1177105197Ssam	int s;
1178105197Ssam
1179105197Ssam	KASSERT(sp != NULL, ("key_delsp: null sp"));
1180105197Ssam
1181105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
1182105197Ssam
1183105197Ssam	KASSERT(sp->refcnt == 0,
1184105197Ssam		("key_delsp: SP with references deleted (refcnt %u)",
1185105197Ssam		sp->refcnt));
1186105197Ssam
1187105197Ssam	s = splnet();	/*called from softclock()*/
1188105197Ssam	/* remove from SP index */
1189105197Ssam	if (__LIST_CHAINED(sp))
1190105197Ssam		LIST_REMOVE(sp, chain);
1191105197Ssam
1192105197Ssam    {
1193105197Ssam	struct ipsecrequest *isr = sp->req, *nextisr;
1194105197Ssam
1195105197Ssam	while (isr != NULL) {
1196105197Ssam		if (isr->sav != NULL) {
1197105197Ssam			KEY_FREESAV(&isr->sav);
1198105197Ssam			isr->sav = NULL;
1199105197Ssam		}
1200105197Ssam
1201105197Ssam		nextisr = isr->next;
1202105197Ssam		KFREE(isr);
1203105197Ssam		isr = nextisr;
1204105197Ssam	}
1205105197Ssam    }
1206105197Ssam
1207105197Ssam	KFREE(sp);
1208105197Ssam
1209105197Ssam	splx(s);
1210105197Ssam}
1211105197Ssam
1212105197Ssam/*
1213105197Ssam * search SPD
1214105197Ssam * OUT:	NULL	: not found
1215105197Ssam *	others	: found, pointer to a SP.
1216105197Ssam */
1217105197Ssamstatic struct secpolicy *
1218105197Ssamkey_getsp(struct secpolicyindex *spidx)
1219105197Ssam{
1220105197Ssam	struct secpolicy *sp;
1221105197Ssam
1222105197Ssam	KASSERT(spidx != NULL, ("key_getsp: null spidx"));
1223105197Ssam
1224105197Ssam	LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
1225105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1226105197Ssam			continue;
1227105197Ssam		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1228105197Ssam			SP_ADDREF(sp);
1229105197Ssam			return sp;
1230105197Ssam		}
1231105197Ssam	}
1232105197Ssam
1233105197Ssam	return NULL;
1234105197Ssam}
1235105197Ssam
1236105197Ssam/*
1237105197Ssam * get SP by index.
1238105197Ssam * OUT:	NULL	: not found
1239105197Ssam *	others	: found, pointer to a SP.
1240105197Ssam */
1241105197Ssamstatic struct secpolicy *
1242105197Ssamkey_getspbyid(u_int32_t id)
1243105197Ssam{
1244105197Ssam	struct secpolicy *sp;
1245105197Ssam
1246105197Ssam	LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
1247105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1248105197Ssam			continue;
1249105197Ssam		if (sp->id == id) {
1250105197Ssam			SP_ADDREF(sp);
1251105197Ssam			return sp;
1252105197Ssam		}
1253105197Ssam	}
1254105197Ssam
1255105197Ssam	LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
1256105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1257105197Ssam			continue;
1258105197Ssam		if (sp->id == id) {
1259105197Ssam			SP_ADDREF(sp);
1260105197Ssam			return sp;
1261105197Ssam		}
1262105197Ssam	}
1263105197Ssam
1264105197Ssam	return NULL;
1265105197Ssam}
1266105197Ssam
1267105197Ssamstruct secpolicy *
1268105197Ssamkey_newsp(const char* where, int tag)
1269105197Ssam{
1270105197Ssam	struct secpolicy *newsp = NULL;
1271105197Ssam
1272105197Ssam	newsp = (struct secpolicy *)
1273105197Ssam		malloc(sizeof(struct secpolicy), M_SECA, M_NOWAIT|M_ZERO);
1274105197Ssam	if (newsp) {
1275105197Ssam		newsp->refcnt = 1;
1276105197Ssam		newsp->req = NULL;
1277105197Ssam	}
1278105197Ssam
1279105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1280105197Ssam		printf("DP key_newsp from %s:%u return SP:%p\n",
1281105197Ssam			where, tag, newsp));
1282105197Ssam	return newsp;
1283105197Ssam}
1284105197Ssam
1285105197Ssam/*
1286105197Ssam * create secpolicy structure from sadb_x_policy structure.
1287105197Ssam * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1288105197Ssam * so must be set properly later.
1289105197Ssam */
1290105197Ssamstruct secpolicy *
1291105197Ssamkey_msg2sp(xpl0, len, error)
1292105197Ssam	struct sadb_x_policy *xpl0;
1293105197Ssam	size_t len;
1294105197Ssam	int *error;
1295105197Ssam{
1296105197Ssam	struct secpolicy *newsp;
1297105197Ssam
1298105197Ssam	/* sanity check */
1299105197Ssam	if (xpl0 == NULL)
1300105197Ssam		panic("key_msg2sp: NULL pointer was passed.\n");
1301105197Ssam	if (len < sizeof(*xpl0))
1302105197Ssam		panic("key_msg2sp: invalid length.\n");
1303105197Ssam	if (len != PFKEY_EXTLEN(xpl0)) {
1304105197Ssam		ipseclog((LOG_DEBUG, "key_msg2sp: Invalid msg length.\n"));
1305105197Ssam		*error = EINVAL;
1306105197Ssam		return NULL;
1307105197Ssam	}
1308105197Ssam
1309105197Ssam	if ((newsp = KEY_NEWSP()) == NULL) {
1310105197Ssam		*error = ENOBUFS;
1311105197Ssam		return NULL;
1312105197Ssam	}
1313105197Ssam
1314105197Ssam	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1315105197Ssam	newsp->policy = xpl0->sadb_x_policy_type;
1316105197Ssam
1317105197Ssam	/* check policy */
1318105197Ssam	switch (xpl0->sadb_x_policy_type) {
1319105197Ssam	case IPSEC_POLICY_DISCARD:
1320105197Ssam	case IPSEC_POLICY_NONE:
1321105197Ssam	case IPSEC_POLICY_ENTRUST:
1322105197Ssam	case IPSEC_POLICY_BYPASS:
1323105197Ssam		newsp->req = NULL;
1324105197Ssam		break;
1325105197Ssam
1326105197Ssam	case IPSEC_POLICY_IPSEC:
1327105197Ssam	    {
1328105197Ssam		int tlen;
1329105197Ssam		struct sadb_x_ipsecrequest *xisr;
1330105197Ssam		struct ipsecrequest **p_isr = &newsp->req;
1331105197Ssam
1332105197Ssam		/* validity check */
1333105197Ssam		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1334105197Ssam			ipseclog((LOG_DEBUG,
1335105197Ssam			    "key_msg2sp: Invalid msg length.\n"));
1336105197Ssam			KEY_FREESP(&newsp);
1337105197Ssam			*error = EINVAL;
1338105197Ssam			return NULL;
1339105197Ssam		}
1340105197Ssam
1341105197Ssam		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1342105197Ssam		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1343105197Ssam
1344105197Ssam		while (tlen > 0) {
1345105197Ssam			/* length check */
1346105197Ssam			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1347105197Ssam				ipseclog((LOG_DEBUG, "key_msg2sp: "
1348105197Ssam					"invalid ipsecrequest length.\n"));
1349105197Ssam				KEY_FREESP(&newsp);
1350105197Ssam				*error = EINVAL;
1351105197Ssam				return NULL;
1352105197Ssam			}
1353105197Ssam
1354105197Ssam			/* allocate request buffer */
1355105197Ssam			KMALLOC(*p_isr, struct ipsecrequest *, sizeof(**p_isr));
1356105197Ssam			if ((*p_isr) == NULL) {
1357105197Ssam				ipseclog((LOG_DEBUG,
1358105197Ssam				    "key_msg2sp: No more memory.\n"));
1359105197Ssam				KEY_FREESP(&newsp);
1360105197Ssam				*error = ENOBUFS;
1361105197Ssam				return NULL;
1362105197Ssam			}
1363105197Ssam			bzero(*p_isr, sizeof(**p_isr));
1364105197Ssam
1365105197Ssam			/* set values */
1366105197Ssam			(*p_isr)->next = NULL;
1367105197Ssam
1368105197Ssam			switch (xisr->sadb_x_ipsecrequest_proto) {
1369105197Ssam			case IPPROTO_ESP:
1370105197Ssam			case IPPROTO_AH:
1371105197Ssam			case IPPROTO_IPCOMP:
1372105197Ssam				break;
1373105197Ssam			default:
1374105197Ssam				ipseclog((LOG_DEBUG,
1375105197Ssam				    "key_msg2sp: invalid proto type=%u\n",
1376105197Ssam				    xisr->sadb_x_ipsecrequest_proto));
1377105197Ssam				KEY_FREESP(&newsp);
1378105197Ssam				*error = EPROTONOSUPPORT;
1379105197Ssam				return NULL;
1380105197Ssam			}
1381105197Ssam			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1382105197Ssam
1383105197Ssam			switch (xisr->sadb_x_ipsecrequest_mode) {
1384105197Ssam			case IPSEC_MODE_TRANSPORT:
1385105197Ssam			case IPSEC_MODE_TUNNEL:
1386105197Ssam				break;
1387105197Ssam			case IPSEC_MODE_ANY:
1388105197Ssam			default:
1389105197Ssam				ipseclog((LOG_DEBUG,
1390105197Ssam				    "key_msg2sp: invalid mode=%u\n",
1391105197Ssam				    xisr->sadb_x_ipsecrequest_mode));
1392105197Ssam				KEY_FREESP(&newsp);
1393105197Ssam				*error = EINVAL;
1394105197Ssam				return NULL;
1395105197Ssam			}
1396105197Ssam			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1397105197Ssam
1398105197Ssam			switch (xisr->sadb_x_ipsecrequest_level) {
1399105197Ssam			case IPSEC_LEVEL_DEFAULT:
1400105197Ssam			case IPSEC_LEVEL_USE:
1401105197Ssam			case IPSEC_LEVEL_REQUIRE:
1402105197Ssam				break;
1403105197Ssam			case IPSEC_LEVEL_UNIQUE:
1404105197Ssam				/* validity check */
1405105197Ssam				/*
1406105197Ssam				 * If range violation of reqid, kernel will
1407105197Ssam				 * update it, don't refuse it.
1408105197Ssam				 */
1409105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid
1410105197Ssam						> IPSEC_MANUAL_REQID_MAX) {
1411105197Ssam					ipseclog((LOG_DEBUG,
1412105197Ssam					    "key_msg2sp: reqid=%d range "
1413105197Ssam					    "violation, updated by kernel.\n",
1414105197Ssam					    xisr->sadb_x_ipsecrequest_reqid));
1415105197Ssam					xisr->sadb_x_ipsecrequest_reqid = 0;
1416105197Ssam				}
1417105197Ssam
1418105197Ssam				/* allocate new reqid id if reqid is zero. */
1419105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1420105197Ssam					u_int32_t reqid;
1421105197Ssam					if ((reqid = key_newreqid()) == 0) {
1422105197Ssam						KEY_FREESP(&newsp);
1423105197Ssam						*error = ENOBUFS;
1424105197Ssam						return NULL;
1425105197Ssam					}
1426105197Ssam					(*p_isr)->saidx.reqid = reqid;
1427105197Ssam					xisr->sadb_x_ipsecrequest_reqid = reqid;
1428105197Ssam				} else {
1429105197Ssam				/* set it for manual keying. */
1430105197Ssam					(*p_isr)->saidx.reqid =
1431105197Ssam						xisr->sadb_x_ipsecrequest_reqid;
1432105197Ssam				}
1433105197Ssam				break;
1434105197Ssam
1435105197Ssam			default:
1436105197Ssam				ipseclog((LOG_DEBUG, "key_msg2sp: invalid level=%u\n",
1437105197Ssam					xisr->sadb_x_ipsecrequest_level));
1438105197Ssam				KEY_FREESP(&newsp);
1439105197Ssam				*error = EINVAL;
1440105197Ssam				return NULL;
1441105197Ssam			}
1442105197Ssam			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1443105197Ssam
1444105197Ssam			/* set IP addresses if there */
1445105197Ssam			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1446105197Ssam				struct sockaddr *paddr;
1447105197Ssam
1448105197Ssam				paddr = (struct sockaddr *)(xisr + 1);
1449105197Ssam
1450105197Ssam				/* validity check */
1451105197Ssam				if (paddr->sa_len
1452105197Ssam				    > sizeof((*p_isr)->saidx.src)) {
1453105197Ssam					ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
1454105197Ssam						"address length.\n"));
1455105197Ssam					KEY_FREESP(&newsp);
1456105197Ssam					*error = EINVAL;
1457105197Ssam					return NULL;
1458105197Ssam				}
1459105197Ssam				bcopy(paddr, &(*p_isr)->saidx.src,
1460105197Ssam					paddr->sa_len);
1461105197Ssam
1462105197Ssam				paddr = (struct sockaddr *)((caddr_t)paddr
1463105197Ssam							+ paddr->sa_len);
1464105197Ssam
1465105197Ssam				/* validity check */
1466105197Ssam				if (paddr->sa_len
1467105197Ssam				    > sizeof((*p_isr)->saidx.dst)) {
1468105197Ssam					ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
1469105197Ssam						"address length.\n"));
1470105197Ssam					KEY_FREESP(&newsp);
1471105197Ssam					*error = EINVAL;
1472105197Ssam					return NULL;
1473105197Ssam				}
1474105197Ssam				bcopy(paddr, &(*p_isr)->saidx.dst,
1475105197Ssam					paddr->sa_len);
1476105197Ssam			}
1477105197Ssam
1478105197Ssam			(*p_isr)->sav = NULL;
1479105197Ssam			(*p_isr)->sp = newsp;
1480105197Ssam
1481105197Ssam			/* initialization for the next. */
1482105197Ssam			p_isr = &(*p_isr)->next;
1483105197Ssam			tlen -= xisr->sadb_x_ipsecrequest_len;
1484105197Ssam
1485105197Ssam			/* validity check */
1486105197Ssam			if (tlen < 0) {
1487105197Ssam				ipseclog((LOG_DEBUG, "key_msg2sp: becoming tlen < 0.\n"));
1488105197Ssam				KEY_FREESP(&newsp);
1489105197Ssam				*error = EINVAL;
1490105197Ssam				return NULL;
1491105197Ssam			}
1492105197Ssam
1493105197Ssam			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1494105197Ssam			                 + xisr->sadb_x_ipsecrequest_len);
1495105197Ssam		}
1496105197Ssam	    }
1497105197Ssam		break;
1498105197Ssam	default:
1499105197Ssam		ipseclog((LOG_DEBUG, "key_msg2sp: invalid policy type.\n"));
1500105197Ssam		KEY_FREESP(&newsp);
1501105197Ssam		*error = EINVAL;
1502105197Ssam		return NULL;
1503105197Ssam	}
1504105197Ssam
1505105197Ssam	*error = 0;
1506105197Ssam	return newsp;
1507105197Ssam}
1508105197Ssam
1509105197Ssamstatic u_int32_t
1510105197Ssamkey_newreqid()
1511105197Ssam{
1512105197Ssam	static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1513105197Ssam
1514105197Ssam	auto_reqid = (auto_reqid == ~0
1515105197Ssam			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1516105197Ssam
1517105197Ssam	/* XXX should be unique check */
1518105197Ssam
1519105197Ssam	return auto_reqid;
1520105197Ssam}
1521105197Ssam
1522105197Ssam/*
1523105197Ssam * copy secpolicy struct to sadb_x_policy structure indicated.
1524105197Ssam */
1525105197Ssamstruct mbuf *
1526105197Ssamkey_sp2msg(sp)
1527105197Ssam	struct secpolicy *sp;
1528105197Ssam{
1529105197Ssam	struct sadb_x_policy *xpl;
1530105197Ssam	int tlen;
1531105197Ssam	caddr_t p;
1532105197Ssam	struct mbuf *m;
1533105197Ssam
1534105197Ssam	/* sanity check. */
1535105197Ssam	if (sp == NULL)
1536105197Ssam		panic("key_sp2msg: NULL pointer was passed.\n");
1537105197Ssam
1538105197Ssam	tlen = key_getspreqmsglen(sp);
1539105197Ssam
1540105197Ssam	m = key_alloc_mbuf(tlen);
1541105197Ssam	if (!m || m->m_next) {	/*XXX*/
1542105197Ssam		if (m)
1543105197Ssam			m_freem(m);
1544105197Ssam		return NULL;
1545105197Ssam	}
1546105197Ssam
1547105197Ssam	m->m_len = tlen;
1548105197Ssam	m->m_next = NULL;
1549105197Ssam	xpl = mtod(m, struct sadb_x_policy *);
1550105197Ssam	bzero(xpl, tlen);
1551105197Ssam
1552105197Ssam	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1553105197Ssam	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1554105197Ssam	xpl->sadb_x_policy_type = sp->policy;
1555105197Ssam	xpl->sadb_x_policy_dir = sp->spidx.dir;
1556105197Ssam	xpl->sadb_x_policy_id = sp->id;
1557105197Ssam	p = (caddr_t)xpl + sizeof(*xpl);
1558105197Ssam
1559105197Ssam	/* if is the policy for ipsec ? */
1560105197Ssam	if (sp->policy == IPSEC_POLICY_IPSEC) {
1561105197Ssam		struct sadb_x_ipsecrequest *xisr;
1562105197Ssam		struct ipsecrequest *isr;
1563105197Ssam
1564105197Ssam		for (isr = sp->req; isr != NULL; isr = isr->next) {
1565105197Ssam
1566105197Ssam			xisr = (struct sadb_x_ipsecrequest *)p;
1567105197Ssam
1568105197Ssam			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1569105197Ssam			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1570105197Ssam			xisr->sadb_x_ipsecrequest_level = isr->level;
1571105197Ssam			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1572105197Ssam
1573105197Ssam			p += sizeof(*xisr);
1574105197Ssam			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1575105197Ssam			p += isr->saidx.src.sa.sa_len;
1576105197Ssam			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1577105197Ssam			p += isr->saidx.src.sa.sa_len;
1578105197Ssam
1579105197Ssam			xisr->sadb_x_ipsecrequest_len =
1580105197Ssam				PFKEY_ALIGN8(sizeof(*xisr)
1581105197Ssam					+ isr->saidx.src.sa.sa_len
1582105197Ssam					+ isr->saidx.dst.sa.sa_len);
1583105197Ssam		}
1584105197Ssam	}
1585105197Ssam
1586105197Ssam	return m;
1587105197Ssam}
1588105197Ssam
1589105197Ssam/* m will not be freed nor modified */
1590105197Ssamstatic struct mbuf *
1591105197Ssam#ifdef __STDC__
1592105197Ssamkey_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1593105197Ssam	int ndeep, int nitem, ...)
1594105197Ssam#else
1595105197Ssamkey_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1596105197Ssam	struct mbuf *m;
1597105197Ssam	const struct sadb_msghdr *mhp;
1598105197Ssam	int ndeep;
1599105197Ssam	int nitem;
1600105197Ssam	va_dcl
1601105197Ssam#endif
1602105197Ssam{
1603105197Ssam	va_list ap;
1604105197Ssam	int idx;
1605105197Ssam	int i;
1606105197Ssam	struct mbuf *result = NULL, *n;
1607105197Ssam	int len;
1608105197Ssam
1609105197Ssam	if (m == NULL || mhp == NULL)
1610105197Ssam		panic("null pointer passed to key_gather");
1611105197Ssam
1612105197Ssam	va_start(ap, nitem);
1613105197Ssam	for (i = 0; i < nitem; i++) {
1614105197Ssam		idx = va_arg(ap, int);
1615105197Ssam		if (idx < 0 || idx > SADB_EXT_MAX)
1616105197Ssam			goto fail;
1617105197Ssam		/* don't attempt to pull empty extension */
1618105197Ssam		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1619105197Ssam			continue;
1620105197Ssam		if (idx != SADB_EXT_RESERVED  &&
1621105197Ssam		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1622105197Ssam			continue;
1623105197Ssam
1624105197Ssam		if (idx == SADB_EXT_RESERVED) {
1625105197Ssam			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1626105197Ssam#ifdef DIAGNOSTIC
1627105197Ssam			if (len > MHLEN)
1628105197Ssam				panic("assumption failed");
1629105197Ssam#endif
1630111119Simp			MGETHDR(n, M_DONTWAIT, MT_DATA);
1631105197Ssam			if (!n)
1632105197Ssam				goto fail;
1633105197Ssam			n->m_len = len;
1634105197Ssam			n->m_next = NULL;
1635105197Ssam			m_copydata(m, 0, sizeof(struct sadb_msg),
1636105197Ssam			    mtod(n, caddr_t));
1637105197Ssam		} else if (i < ndeep) {
1638105197Ssam			len = mhp->extlen[idx];
1639105197Ssam			n = key_alloc_mbuf(len);
1640105197Ssam			if (!n || n->m_next) {	/*XXX*/
1641105197Ssam				if (n)
1642105197Ssam					m_freem(n);
1643105197Ssam				goto fail;
1644105197Ssam			}
1645105197Ssam			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1646105197Ssam			    mtod(n, caddr_t));
1647105197Ssam		} else {
1648105197Ssam			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1649111119Simp			    M_DONTWAIT);
1650105197Ssam		}
1651105197Ssam		if (n == NULL)
1652105197Ssam			goto fail;
1653105197Ssam
1654105197Ssam		if (result)
1655105197Ssam			m_cat(result, n);
1656105197Ssam		else
1657105197Ssam			result = n;
1658105197Ssam	}
1659105197Ssam	va_end(ap);
1660105197Ssam
1661105197Ssam	if ((result->m_flags & M_PKTHDR) != 0) {
1662105197Ssam		result->m_pkthdr.len = 0;
1663105197Ssam		for (n = result; n; n = n->m_next)
1664105197Ssam			result->m_pkthdr.len += n->m_len;
1665105197Ssam	}
1666105197Ssam
1667105197Ssam	return result;
1668105197Ssam
1669105197Ssamfail:
1670105197Ssam	m_freem(result);
1671105197Ssam	return NULL;
1672105197Ssam}
1673105197Ssam
1674105197Ssam/*
1675105197Ssam * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1676108533Sschweikh * add an entry to SP database, when received
1677105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1678105197Ssam * from the user(?).
1679105197Ssam * Adding to SP database,
1680105197Ssam * and send
1681105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1682105197Ssam * to the socket which was send.
1683105197Ssam *
1684105197Ssam * SPDADD set a unique policy entry.
1685105197Ssam * SPDSETIDX like SPDADD without a part of policy requests.
1686105197Ssam * SPDUPDATE replace a unique policy entry.
1687105197Ssam *
1688105197Ssam * m will always be freed.
1689105197Ssam */
1690105197Ssamstatic int
1691105197Ssamkey_spdadd(so, m, mhp)
1692105197Ssam	struct socket *so;
1693105197Ssam	struct mbuf *m;
1694105197Ssam	const struct sadb_msghdr *mhp;
1695105197Ssam{
1696105197Ssam	struct sadb_address *src0, *dst0;
1697105197Ssam	struct sadb_x_policy *xpl0, *xpl;
1698105197Ssam	struct sadb_lifetime *lft = NULL;
1699105197Ssam	struct secpolicyindex spidx;
1700105197Ssam	struct secpolicy *newsp;
1701105197Ssam	int error;
1702105197Ssam
1703105197Ssam	/* sanity check */
1704105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
1705105197Ssam		panic("key_spdadd: NULL pointer is passed.\n");
1706105197Ssam
1707105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1708105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1709105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1710105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1711105197Ssam		return key_senderror(so, m, EINVAL);
1712105197Ssam	}
1713105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1714105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1715105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1716105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1717105197Ssam		return key_senderror(so, m, EINVAL);
1718105197Ssam	}
1719105197Ssam	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1720105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1721105197Ssam			< sizeof(struct sadb_lifetime)) {
1722105197Ssam			ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1723105197Ssam			return key_senderror(so, m, EINVAL);
1724105197Ssam		}
1725105197Ssam		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1726105197Ssam	}
1727105197Ssam
1728105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1729105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1730105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1731105197Ssam
1732105197Ssam	/* make secindex */
1733105197Ssam	/* XXX boundary check against sa_len */
1734105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1735105197Ssam	                src0 + 1,
1736105197Ssam	                dst0 + 1,
1737105197Ssam	                src0->sadb_address_prefixlen,
1738105197Ssam	                dst0->sadb_address_prefixlen,
1739105197Ssam	                src0->sadb_address_proto,
1740105197Ssam	                &spidx);
1741105197Ssam
1742105197Ssam	/* checking the direciton. */
1743105197Ssam	switch (xpl0->sadb_x_policy_dir) {
1744105197Ssam	case IPSEC_DIR_INBOUND:
1745105197Ssam	case IPSEC_DIR_OUTBOUND:
1746105197Ssam		break;
1747105197Ssam	default:
1748105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: Invalid SP direction.\n"));
1749105197Ssam		mhp->msg->sadb_msg_errno = EINVAL;
1750105197Ssam		return 0;
1751105197Ssam	}
1752105197Ssam
1753105197Ssam	/* check policy */
1754105197Ssam	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1755105197Ssam	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1756105197Ssam	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1757105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: Invalid policy type.\n"));
1758105197Ssam		return key_senderror(so, m, EINVAL);
1759105197Ssam	}
1760105197Ssam
1761105197Ssam	/* policy requests are mandatory when action is ipsec. */
1762105197Ssam        if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1763105197Ssam	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1764105197Ssam	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1765105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: some policy requests part required.\n"));
1766105197Ssam		return key_senderror(so, m, EINVAL);
1767105197Ssam	}
1768105197Ssam
1769105197Ssam	/*
1770105197Ssam	 * checking there is SP already or not.
1771105197Ssam	 * SPDUPDATE doesn't depend on whether there is a SP or not.
1772105197Ssam	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1773105197Ssam	 * then error.
1774105197Ssam	 */
1775105197Ssam	newsp = key_getsp(&spidx);
1776105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1777105197Ssam		if (newsp) {
1778105197Ssam			newsp->state = IPSEC_SPSTATE_DEAD;
1779105197Ssam			KEY_FREESP(&newsp);
1780105197Ssam		}
1781105197Ssam	} else {
1782105197Ssam		if (newsp != NULL) {
1783105197Ssam			KEY_FREESP(&newsp);
1784105197Ssam			ipseclog((LOG_DEBUG, "key_spdadd: a SP entry exists already.\n"));
1785105197Ssam			return key_senderror(so, m, EEXIST);
1786105197Ssam		}
1787105197Ssam	}
1788105197Ssam
1789105197Ssam	/* allocation new SP entry */
1790105197Ssam	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1791105197Ssam		return key_senderror(so, m, error);
1792105197Ssam	}
1793105197Ssam
1794105197Ssam	if ((newsp->id = key_getnewspid()) == 0) {
1795105197Ssam		KFREE(newsp);
1796105197Ssam		return key_senderror(so, m, ENOBUFS);
1797105197Ssam	}
1798105197Ssam
1799105197Ssam	/* XXX boundary check against sa_len */
1800105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1801105197Ssam	                src0 + 1,
1802105197Ssam	                dst0 + 1,
1803105197Ssam	                src0->sadb_address_prefixlen,
1804105197Ssam	                dst0->sadb_address_prefixlen,
1805105197Ssam	                src0->sadb_address_proto,
1806105197Ssam	                &newsp->spidx);
1807105197Ssam
1808105197Ssam	/* sanity check on addr pair */
1809105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1810105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_family) {
1811105197Ssam		KFREE(newsp);
1812105197Ssam		return key_senderror(so, m, EINVAL);
1813105197Ssam	}
1814105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1815105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_len) {
1816105197Ssam		KFREE(newsp);
1817105197Ssam		return key_senderror(so, m, EINVAL);
1818105197Ssam	}
1819105197Ssam#if 1
1820105197Ssam	if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
1821105197Ssam		struct sockaddr *sa;
1822105197Ssam		sa = (struct sockaddr *)(src0 + 1);
1823105197Ssam		if (sa->sa_family != newsp->req->saidx.src.sa.sa_family) {
1824105197Ssam			KFREE(newsp);
1825105197Ssam			return key_senderror(so, m, EINVAL);
1826105197Ssam		}
1827105197Ssam	}
1828105197Ssam	if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
1829105197Ssam		struct sockaddr *sa;
1830105197Ssam		sa = (struct sockaddr *)(dst0 + 1);
1831105197Ssam		if (sa->sa_family != newsp->req->saidx.dst.sa.sa_family) {
1832105197Ssam			KFREE(newsp);
1833105197Ssam			return key_senderror(so, m, EINVAL);
1834105197Ssam		}
1835105197Ssam	}
1836105197Ssam#endif
1837105197Ssam
1838105197Ssam	newsp->created = time_second;
1839105197Ssam	newsp->lastused = newsp->created;
1840105197Ssam	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1841105197Ssam	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1842105197Ssam
1843105197Ssam	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1844105197Ssam	newsp->state = IPSEC_SPSTATE_ALIVE;
1845105197Ssam	LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1846105197Ssam
1847105197Ssam	/* delete the entry in spacqtree */
1848105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1849105197Ssam		struct secspacq *spacq;
1850105197Ssam		if ((spacq = key_getspacq(&spidx)) != NULL) {
1851105197Ssam			/* reset counter in order to deletion by timehandler. */
1852105197Ssam			spacq->created = time_second;
1853105197Ssam			spacq->count = 0;
1854105197Ssam		}
1855105197Ssam    	}
1856105197Ssam
1857105197Ssam    {
1858105197Ssam	struct mbuf *n, *mpolicy;
1859105197Ssam	struct sadb_msg *newmsg;
1860105197Ssam	int off;
1861105197Ssam
1862105197Ssam	/* create new sadb_msg to reply. */
1863105197Ssam	if (lft) {
1864105197Ssam		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1865105197Ssam		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1866105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1867105197Ssam	} else {
1868105197Ssam		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1869105197Ssam		    SADB_X_EXT_POLICY,
1870105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1871105197Ssam	}
1872105197Ssam	if (!n)
1873105197Ssam		return key_senderror(so, m, ENOBUFS);
1874105197Ssam
1875105197Ssam	if (n->m_len < sizeof(*newmsg)) {
1876105197Ssam		n = m_pullup(n, sizeof(*newmsg));
1877105197Ssam		if (!n)
1878105197Ssam			return key_senderror(so, m, ENOBUFS);
1879105197Ssam	}
1880105197Ssam	newmsg = mtod(n, struct sadb_msg *);
1881105197Ssam	newmsg->sadb_msg_errno = 0;
1882105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1883105197Ssam
1884105197Ssam	off = 0;
1885105197Ssam	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1886105197Ssam	    sizeof(*xpl), &off);
1887105197Ssam	if (mpolicy == NULL) {
1888105197Ssam		/* n is already freed */
1889105197Ssam		return key_senderror(so, m, ENOBUFS);
1890105197Ssam	}
1891105197Ssam	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1892105197Ssam	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1893105197Ssam		m_freem(n);
1894105197Ssam		return key_senderror(so, m, EINVAL);
1895105197Ssam	}
1896105197Ssam	xpl->sadb_x_policy_id = newsp->id;
1897105197Ssam
1898105197Ssam	m_freem(m);
1899105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1900105197Ssam    }
1901105197Ssam}
1902105197Ssam
1903105197Ssam/*
1904105197Ssam * get new policy id.
1905105197Ssam * OUT:
1906105197Ssam *	0:	failure.
1907105197Ssam *	others: success.
1908105197Ssam */
1909105197Ssamstatic u_int32_t
1910105197Ssamkey_getnewspid()
1911105197Ssam{
1912105197Ssam	u_int32_t newid = 0;
1913105197Ssam	int count = key_spi_trycnt;	/* XXX */
1914105197Ssam	struct secpolicy *sp;
1915105197Ssam
1916105197Ssam	/* when requesting to allocate spi ranged */
1917105197Ssam	while (count--) {
1918105197Ssam		newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
1919105197Ssam
1920105197Ssam		if ((sp = key_getspbyid(newid)) == NULL)
1921105197Ssam			break;
1922105197Ssam
1923105197Ssam		KEY_FREESP(&sp);
1924105197Ssam	}
1925105197Ssam
1926105197Ssam	if (count == 0 || newid == 0) {
1927105197Ssam		ipseclog((LOG_DEBUG, "key_getnewspid: to allocate policy id is failed.\n"));
1928105197Ssam		return 0;
1929105197Ssam	}
1930105197Ssam
1931105197Ssam	return newid;
1932105197Ssam}
1933105197Ssam
1934105197Ssam/*
1935105197Ssam * SADB_SPDDELETE processing
1936105197Ssam * receive
1937105197Ssam *   <base, address(SD), policy(*)>
1938105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
1939105197Ssam * and send,
1940105197Ssam *   <base, address(SD), policy(*)>
1941105197Ssam * to the ikmpd.
1942105197Ssam * policy(*) including direction of policy.
1943105197Ssam *
1944105197Ssam * m will always be freed.
1945105197Ssam */
1946105197Ssamstatic int
1947105197Ssamkey_spddelete(so, m, mhp)
1948105197Ssam	struct socket *so;
1949105197Ssam	struct mbuf *m;
1950105197Ssam	const struct sadb_msghdr *mhp;
1951105197Ssam{
1952105197Ssam	struct sadb_address *src0, *dst0;
1953105197Ssam	struct sadb_x_policy *xpl0;
1954105197Ssam	struct secpolicyindex spidx;
1955105197Ssam	struct secpolicy *sp;
1956105197Ssam
1957105197Ssam	/* sanity check */
1958105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
1959105197Ssam		panic("key_spddelete: NULL pointer is passed.\n");
1960105197Ssam
1961105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1962105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1963105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1964105197Ssam		ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
1965105197Ssam		return key_senderror(so, m, EINVAL);
1966105197Ssam	}
1967105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1968105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1969105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1970105197Ssam		ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
1971105197Ssam		return key_senderror(so, m, EINVAL);
1972105197Ssam	}
1973105197Ssam
1974105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1975105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1976105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1977105197Ssam
1978105197Ssam	/* make secindex */
1979105197Ssam	/* XXX boundary check against sa_len */
1980105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1981105197Ssam	                src0 + 1,
1982105197Ssam	                dst0 + 1,
1983105197Ssam	                src0->sadb_address_prefixlen,
1984105197Ssam	                dst0->sadb_address_prefixlen,
1985105197Ssam	                src0->sadb_address_proto,
1986105197Ssam	                &spidx);
1987105197Ssam
1988105197Ssam	/* checking the direciton. */
1989105197Ssam	switch (xpl0->sadb_x_policy_dir) {
1990105197Ssam	case IPSEC_DIR_INBOUND:
1991105197Ssam	case IPSEC_DIR_OUTBOUND:
1992105197Ssam		break;
1993105197Ssam	default:
1994105197Ssam		ipseclog((LOG_DEBUG, "key_spddelete: Invalid SP direction.\n"));
1995105197Ssam		return key_senderror(so, m, EINVAL);
1996105197Ssam	}
1997105197Ssam
1998105197Ssam	/* Is there SP in SPD ? */
1999105197Ssam	if ((sp = key_getsp(&spidx)) == NULL) {
2000105197Ssam		ipseclog((LOG_DEBUG, "key_spddelete: no SP found.\n"));
2001105197Ssam		return key_senderror(so, m, EINVAL);
2002105197Ssam	}
2003105197Ssam
2004105197Ssam	/* save policy id to buffer to be returned. */
2005105197Ssam	xpl0->sadb_x_policy_id = sp->id;
2006105197Ssam
2007105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2008105197Ssam	KEY_FREESP(&sp);
2009105197Ssam
2010105197Ssam    {
2011105197Ssam	struct mbuf *n;
2012105197Ssam	struct sadb_msg *newmsg;
2013105197Ssam
2014105197Ssam	/* create new sadb_msg to reply. */
2015105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2016105197Ssam	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2017105197Ssam	if (!n)
2018105197Ssam		return key_senderror(so, m, ENOBUFS);
2019105197Ssam
2020105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2021105197Ssam	newmsg->sadb_msg_errno = 0;
2022105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2023105197Ssam
2024105197Ssam	m_freem(m);
2025105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2026105197Ssam    }
2027105197Ssam}
2028105197Ssam
2029105197Ssam/*
2030105197Ssam * SADB_SPDDELETE2 processing
2031105197Ssam * receive
2032105197Ssam *   <base, policy(*)>
2033105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2034105197Ssam * and send,
2035105197Ssam *   <base, policy(*)>
2036105197Ssam * to the ikmpd.
2037105197Ssam * policy(*) including direction of policy.
2038105197Ssam *
2039105197Ssam * m will always be freed.
2040105197Ssam */
2041105197Ssamstatic int
2042105197Ssamkey_spddelete2(so, m, mhp)
2043105197Ssam	struct socket *so;
2044105197Ssam	struct mbuf *m;
2045105197Ssam	const struct sadb_msghdr *mhp;
2046105197Ssam{
2047105197Ssam	u_int32_t id;
2048105197Ssam	struct secpolicy *sp;
2049105197Ssam
2050105197Ssam	/* sanity check */
2051105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2052105197Ssam		panic("key_spddelete2: NULL pointer is passed.\n");
2053105197Ssam
2054105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2055105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2056105197Ssam		ipseclog((LOG_DEBUG, "key_spddelete2: invalid message is passed.\n"));
2057105197Ssam		key_senderror(so, m, EINVAL);
2058105197Ssam		return 0;
2059105197Ssam	}
2060105197Ssam
2061105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2062105197Ssam
2063105197Ssam	/* Is there SP in SPD ? */
2064105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2065105197Ssam		ipseclog((LOG_DEBUG, "key_spddelete2: no SP found id:%u.\n", id));
2066105197Ssam		key_senderror(so, m, EINVAL);
2067105197Ssam	}
2068105197Ssam
2069105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2070105197Ssam	KEY_FREESP(&sp);
2071105197Ssam
2072105197Ssam    {
2073105197Ssam	struct mbuf *n, *nn;
2074105197Ssam	struct sadb_msg *newmsg;
2075105197Ssam	int off, len;
2076105197Ssam
2077105197Ssam	/* create new sadb_msg to reply. */
2078105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2079105197Ssam
2080105197Ssam	if (len > MCLBYTES)
2081105197Ssam		return key_senderror(so, m, ENOBUFS);
2082111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
2083105197Ssam	if (n && len > MHLEN) {
2084111119Simp		MCLGET(n, M_DONTWAIT);
2085105197Ssam		if ((n->m_flags & M_EXT) == 0) {
2086105197Ssam			m_freem(n);
2087105197Ssam			n = NULL;
2088105197Ssam		}
2089105197Ssam	}
2090105197Ssam	if (!n)
2091105197Ssam		return key_senderror(so, m, ENOBUFS);
2092105197Ssam
2093105197Ssam	n->m_len = len;
2094105197Ssam	n->m_next = NULL;
2095105197Ssam	off = 0;
2096105197Ssam
2097105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2098105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2099105197Ssam
2100105197Ssam#ifdef DIAGNOSTIC
2101105197Ssam	if (off != len)
2102105197Ssam		panic("length inconsistency in key_spddelete2");
2103105197Ssam#endif
2104105197Ssam
2105105197Ssam	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2106111119Simp	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2107105197Ssam	if (!n->m_next) {
2108105197Ssam		m_freem(n);
2109105197Ssam		return key_senderror(so, m, ENOBUFS);
2110105197Ssam	}
2111105197Ssam
2112105197Ssam	n->m_pkthdr.len = 0;
2113105197Ssam	for (nn = n; nn; nn = nn->m_next)
2114105197Ssam		n->m_pkthdr.len += nn->m_len;
2115105197Ssam
2116105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2117105197Ssam	newmsg->sadb_msg_errno = 0;
2118105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2119105197Ssam
2120105197Ssam	m_freem(m);
2121105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2122105197Ssam    }
2123105197Ssam}
2124105197Ssam
2125105197Ssam/*
2126105197Ssam * SADB_X_GET processing
2127105197Ssam * receive
2128105197Ssam *   <base, policy(*)>
2129105197Ssam * from the user(?),
2130105197Ssam * and send,
2131105197Ssam *   <base, address(SD), policy>
2132105197Ssam * to the ikmpd.
2133105197Ssam * policy(*) including direction of policy.
2134105197Ssam *
2135105197Ssam * m will always be freed.
2136105197Ssam */
2137105197Ssamstatic int
2138105197Ssamkey_spdget(so, m, mhp)
2139105197Ssam	struct socket *so;
2140105197Ssam	struct mbuf *m;
2141105197Ssam	const struct sadb_msghdr *mhp;
2142105197Ssam{
2143105197Ssam	u_int32_t id;
2144105197Ssam	struct secpolicy *sp;
2145105197Ssam	struct mbuf *n;
2146105197Ssam
2147105197Ssam	/* sanity check */
2148105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2149105197Ssam		panic("key_spdget: NULL pointer is passed.\n");
2150105197Ssam
2151105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2152105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2153105197Ssam		ipseclog((LOG_DEBUG, "key_spdget: invalid message is passed.\n"));
2154105197Ssam		return key_senderror(so, m, EINVAL);
2155105197Ssam	}
2156105197Ssam
2157105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2158105197Ssam
2159105197Ssam	/* Is there SP in SPD ? */
2160105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2161105197Ssam		ipseclog((LOG_DEBUG, "key_spdget: no SP found id:%u.\n", id));
2162105197Ssam		return key_senderror(so, m, ENOENT);
2163105197Ssam	}
2164105197Ssam
2165105197Ssam	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2166105197Ssam	if (n != NULL) {
2167105197Ssam		m_freem(m);
2168105197Ssam		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2169105197Ssam	} else
2170105197Ssam		return key_senderror(so, m, ENOBUFS);
2171105197Ssam}
2172105197Ssam
2173105197Ssam/*
2174105197Ssam * SADB_X_SPDACQUIRE processing.
2175105197Ssam * Acquire policy and SA(s) for a *OUTBOUND* packet.
2176105197Ssam * send
2177105197Ssam *   <base, policy(*)>
2178105197Ssam * to KMD, and expect to receive
2179105197Ssam *   <base> with SADB_X_SPDACQUIRE if error occured,
2180105197Ssam * or
2181105197Ssam *   <base, policy>
2182105197Ssam * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2183105197Ssam * policy(*) is without policy requests.
2184105197Ssam *
2185105197Ssam *    0     : succeed
2186105197Ssam *    others: error number
2187105197Ssam */
2188105197Ssamint
2189105197Ssamkey_spdacquire(sp)
2190105197Ssam	struct secpolicy *sp;
2191105197Ssam{
2192105197Ssam	struct mbuf *result = NULL, *m;
2193105197Ssam	struct secspacq *newspacq;
2194105197Ssam	int error;
2195105197Ssam
2196105197Ssam	/* sanity check */
2197105197Ssam	if (sp == NULL)
2198105197Ssam		panic("key_spdacquire: NULL pointer is passed.\n");
2199105197Ssam	if (sp->req != NULL)
2200105197Ssam		panic("key_spdacquire: called but there is request.\n");
2201105197Ssam	if (sp->policy != IPSEC_POLICY_IPSEC)
2202105197Ssam		panic("key_spdacquire: policy mismathed. IPsec is expected.\n");
2203105197Ssam
2204108533Sschweikh	/* Get an entry to check whether sent message or not. */
2205105197Ssam	if ((newspacq = key_getspacq(&sp->spidx)) != NULL) {
2206105197Ssam		if (key_blockacq_count < newspacq->count) {
2207105197Ssam			/* reset counter and do send message. */
2208105197Ssam			newspacq->count = 0;
2209105197Ssam		} else {
2210105197Ssam			/* increment counter and do nothing. */
2211105197Ssam			newspacq->count++;
2212105197Ssam			return 0;
2213105197Ssam		}
2214105197Ssam	} else {
2215105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
2216105197Ssam		if ((newspacq = key_newspacq(&sp->spidx)) == NULL)
2217105197Ssam			return ENOBUFS;
2218105197Ssam
2219105197Ssam		/* add to acqtree */
2220105197Ssam		LIST_INSERT_HEAD(&spacqtree, newspacq, chain);
2221105197Ssam	}
2222105197Ssam
2223105197Ssam	/* create new sadb_msg to reply. */
2224105197Ssam	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2225105197Ssam	if (!m) {
2226105197Ssam		error = ENOBUFS;
2227105197Ssam		goto fail;
2228105197Ssam	}
2229105197Ssam	result = m;
2230105197Ssam
2231105197Ssam	result->m_pkthdr.len = 0;
2232105197Ssam	for (m = result; m; m = m->m_next)
2233105197Ssam		result->m_pkthdr.len += m->m_len;
2234105197Ssam
2235105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2236105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2237105197Ssam
2238105197Ssam	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2239105197Ssam
2240105197Ssamfail:
2241105197Ssam	if (result)
2242105197Ssam		m_freem(result);
2243105197Ssam	return error;
2244105197Ssam}
2245105197Ssam
2246105197Ssam/*
2247105197Ssam * SADB_SPDFLUSH processing
2248105197Ssam * receive
2249105197Ssam *   <base>
2250105197Ssam * from the user, and free all entries in secpctree.
2251105197Ssam * and send,
2252105197Ssam *   <base>
2253105197Ssam * to the user.
2254105197Ssam * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2255105197Ssam *
2256105197Ssam * m will always be freed.
2257105197Ssam */
2258105197Ssamstatic int
2259105197Ssamkey_spdflush(so, m, mhp)
2260105197Ssam	struct socket *so;
2261105197Ssam	struct mbuf *m;
2262105197Ssam	const struct sadb_msghdr *mhp;
2263105197Ssam{
2264105197Ssam	struct sadb_msg *newmsg;
2265105197Ssam	struct secpolicy *sp;
2266105197Ssam	u_int dir;
2267105197Ssam
2268105197Ssam	/* sanity check */
2269105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2270105197Ssam		panic("key_spdflush: NULL pointer is passed.\n");
2271105197Ssam
2272105197Ssam	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2273105197Ssam		return key_senderror(so, m, EINVAL);
2274105197Ssam
2275105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2276105197Ssam		LIST_FOREACH(sp, &sptree[dir], chain) {
2277105197Ssam			sp->state = IPSEC_SPSTATE_DEAD;
2278105197Ssam		}
2279105197Ssam	}
2280105197Ssam
2281105197Ssam	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2282105197Ssam		ipseclog((LOG_DEBUG, "key_spdflush: No more memory.\n"));
2283105197Ssam		return key_senderror(so, m, ENOBUFS);
2284105197Ssam	}
2285105197Ssam
2286105197Ssam	if (m->m_next)
2287105197Ssam		m_freem(m->m_next);
2288105197Ssam	m->m_next = NULL;
2289105197Ssam	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2290105197Ssam	newmsg = mtod(m, struct sadb_msg *);
2291105197Ssam	newmsg->sadb_msg_errno = 0;
2292105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2293105197Ssam
2294105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2295105197Ssam}
2296105197Ssam
2297105197Ssam/*
2298105197Ssam * SADB_SPDDUMP processing
2299105197Ssam * receive
2300105197Ssam *   <base>
2301105197Ssam * from the user, and dump all SP leaves
2302105197Ssam * and send,
2303105197Ssam *   <base> .....
2304105197Ssam * to the ikmpd.
2305105197Ssam *
2306105197Ssam * m will always be freed.
2307105197Ssam */
2308105197Ssamstatic int
2309105197Ssamkey_spddump(so, m, mhp)
2310105197Ssam	struct socket *so;
2311105197Ssam	struct mbuf *m;
2312105197Ssam	const struct sadb_msghdr *mhp;
2313105197Ssam{
2314105197Ssam	struct secpolicy *sp;
2315105197Ssam	int cnt;
2316105197Ssam	u_int dir;
2317105197Ssam	struct mbuf *n;
2318105197Ssam
2319105197Ssam	/* sanity check */
2320105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2321105197Ssam		panic("key_spddump: NULL pointer is passed.\n");
2322105197Ssam
2323105197Ssam	/* search SPD entry and get buffer size. */
2324105197Ssam	cnt = 0;
2325105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2326105197Ssam		LIST_FOREACH(sp, &sptree[dir], chain) {
2327105197Ssam			cnt++;
2328105197Ssam		}
2329105197Ssam	}
2330105197Ssam
2331105197Ssam	if (cnt == 0)
2332105197Ssam		return key_senderror(so, m, ENOENT);
2333105197Ssam
2334105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2335105197Ssam		LIST_FOREACH(sp, &sptree[dir], chain) {
2336105197Ssam			--cnt;
2337105197Ssam			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2338105197Ssam			    mhp->msg->sadb_msg_pid);
2339105197Ssam
2340105197Ssam			if (n)
2341105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2342105197Ssam		}
2343105197Ssam	}
2344105197Ssam
2345105197Ssam	m_freem(m);
2346105197Ssam	return 0;
2347105197Ssam}
2348105197Ssam
2349105197Ssamstatic struct mbuf *
2350105197Ssamkey_setdumpsp(sp, type, seq, pid)
2351105197Ssam	struct secpolicy *sp;
2352105197Ssam	u_int8_t type;
2353105197Ssam	u_int32_t seq, pid;
2354105197Ssam{
2355105197Ssam	struct mbuf *result = NULL, *m;
2356105197Ssam
2357105197Ssam	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2358105197Ssam	if (!m)
2359105197Ssam		goto fail;
2360105197Ssam	result = m;
2361105197Ssam
2362105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2363105197Ssam	    &sp->spidx.src.sa, sp->spidx.prefs,
2364105197Ssam	    sp->spidx.ul_proto);
2365105197Ssam	if (!m)
2366105197Ssam		goto fail;
2367105197Ssam	m_cat(result, m);
2368105197Ssam
2369105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2370105197Ssam	    &sp->spidx.dst.sa, sp->spidx.prefd,
2371105197Ssam	    sp->spidx.ul_proto);
2372105197Ssam	if (!m)
2373105197Ssam		goto fail;
2374105197Ssam	m_cat(result, m);
2375105197Ssam
2376105197Ssam	m = key_sp2msg(sp);
2377105197Ssam	if (!m)
2378105197Ssam		goto fail;
2379105197Ssam	m_cat(result, m);
2380105197Ssam
2381105197Ssam	if ((result->m_flags & M_PKTHDR) == 0)
2382105197Ssam		goto fail;
2383105197Ssam
2384105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2385105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2386105197Ssam		if (result == NULL)
2387105197Ssam			goto fail;
2388105197Ssam	}
2389105197Ssam
2390105197Ssam	result->m_pkthdr.len = 0;
2391105197Ssam	for (m = result; m; m = m->m_next)
2392105197Ssam		result->m_pkthdr.len += m->m_len;
2393105197Ssam
2394105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2395105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2396105197Ssam
2397105197Ssam	return result;
2398105197Ssam
2399105197Ssamfail:
2400105197Ssam	m_freem(result);
2401105197Ssam	return NULL;
2402105197Ssam}
2403105197Ssam
2404105197Ssam/*
2405105197Ssam * get PFKEY message length for security policy and request.
2406105197Ssam */
2407105197Ssamstatic u_int
2408105197Ssamkey_getspreqmsglen(sp)
2409105197Ssam	struct secpolicy *sp;
2410105197Ssam{
2411105197Ssam	u_int tlen;
2412105197Ssam
2413105197Ssam	tlen = sizeof(struct sadb_x_policy);
2414105197Ssam
2415105197Ssam	/* if is the policy for ipsec ? */
2416105197Ssam	if (sp->policy != IPSEC_POLICY_IPSEC)
2417105197Ssam		return tlen;
2418105197Ssam
2419105197Ssam	/* get length of ipsec requests */
2420105197Ssam    {
2421105197Ssam	struct ipsecrequest *isr;
2422105197Ssam	int len;
2423105197Ssam
2424105197Ssam	for (isr = sp->req; isr != NULL; isr = isr->next) {
2425105197Ssam		len = sizeof(struct sadb_x_ipsecrequest)
2426105197Ssam			+ isr->saidx.src.sa.sa_len
2427105197Ssam			+ isr->saidx.dst.sa.sa_len;
2428105197Ssam
2429105197Ssam		tlen += PFKEY_ALIGN8(len);
2430105197Ssam	}
2431105197Ssam    }
2432105197Ssam
2433105197Ssam	return tlen;
2434105197Ssam}
2435105197Ssam
2436105197Ssam/*
2437105197Ssam * SADB_SPDEXPIRE processing
2438105197Ssam * send
2439105197Ssam *   <base, address(SD), lifetime(CH), policy>
2440105197Ssam * to KMD by PF_KEY.
2441105197Ssam *
2442105197Ssam * OUT:	0	: succeed
2443105197Ssam *	others	: error number
2444105197Ssam */
2445105197Ssamstatic int
2446105197Ssamkey_spdexpire(sp)
2447105197Ssam	struct secpolicy *sp;
2448105197Ssam{
2449105197Ssam	int s;
2450105197Ssam	struct mbuf *result = NULL, *m;
2451105197Ssam	int len;
2452105197Ssam	int error = -1;
2453105197Ssam	struct sadb_lifetime *lt;
2454105197Ssam
2455105197Ssam	/* XXX: Why do we lock ? */
2456105197Ssam	s = splnet();	/*called from softclock()*/
2457105197Ssam
2458105197Ssam	/* sanity check */
2459105197Ssam	if (sp == NULL)
2460105197Ssam		panic("key_spdexpire: NULL pointer is passed.\n");
2461105197Ssam
2462105197Ssam	/* set msg header */
2463105197Ssam	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2464105197Ssam	if (!m) {
2465105197Ssam		error = ENOBUFS;
2466105197Ssam		goto fail;
2467105197Ssam	}
2468105197Ssam	result = m;
2469105197Ssam
2470105197Ssam	/* create lifetime extension (current and hard) */
2471105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2472105197Ssam	m = key_alloc_mbuf(len);
2473105197Ssam	if (!m || m->m_next) {	/*XXX*/
2474105197Ssam		if (m)
2475105197Ssam			m_freem(m);
2476105197Ssam		error = ENOBUFS;
2477105197Ssam		goto fail;
2478105197Ssam	}
2479105197Ssam	bzero(mtod(m, caddr_t), len);
2480105197Ssam	lt = mtod(m, struct sadb_lifetime *);
2481105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2482105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2483105197Ssam	lt->sadb_lifetime_allocations = 0;
2484105197Ssam	lt->sadb_lifetime_bytes = 0;
2485105197Ssam	lt->sadb_lifetime_addtime = sp->created;
2486105197Ssam	lt->sadb_lifetime_usetime = sp->lastused;
2487105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2488105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2489105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2490105197Ssam	lt->sadb_lifetime_allocations = 0;
2491105197Ssam	lt->sadb_lifetime_bytes = 0;
2492105197Ssam	lt->sadb_lifetime_addtime = sp->lifetime;
2493105197Ssam	lt->sadb_lifetime_usetime = sp->validtime;
2494105197Ssam	m_cat(result, m);
2495105197Ssam
2496105197Ssam	/* set sadb_address for source */
2497105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2498105197Ssam	    &sp->spidx.src.sa,
2499105197Ssam	    sp->spidx.prefs, sp->spidx.ul_proto);
2500105197Ssam	if (!m) {
2501105197Ssam		error = ENOBUFS;
2502105197Ssam		goto fail;
2503105197Ssam	}
2504105197Ssam	m_cat(result, m);
2505105197Ssam
2506105197Ssam	/* set sadb_address for destination */
2507105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2508105197Ssam	    &sp->spidx.dst.sa,
2509105197Ssam	    sp->spidx.prefd, sp->spidx.ul_proto);
2510105197Ssam	if (!m) {
2511105197Ssam		error = ENOBUFS;
2512105197Ssam		goto fail;
2513105197Ssam	}
2514105197Ssam	m_cat(result, m);
2515105197Ssam
2516105197Ssam	/* set secpolicy */
2517105197Ssam	m = key_sp2msg(sp);
2518105197Ssam	if (!m) {
2519105197Ssam		error = ENOBUFS;
2520105197Ssam		goto fail;
2521105197Ssam	}
2522105197Ssam	m_cat(result, m);
2523105197Ssam
2524105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
2525105197Ssam		error = EINVAL;
2526105197Ssam		goto fail;
2527105197Ssam	}
2528105197Ssam
2529105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2530105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2531105197Ssam		if (result == NULL) {
2532105197Ssam			error = ENOBUFS;
2533105197Ssam			goto fail;
2534105197Ssam		}
2535105197Ssam	}
2536105197Ssam
2537105197Ssam	result->m_pkthdr.len = 0;
2538105197Ssam	for (m = result; m; m = m->m_next)
2539105197Ssam		result->m_pkthdr.len += m->m_len;
2540105197Ssam
2541105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2542105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2543105197Ssam
2544105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2545105197Ssam
2546105197Ssam fail:
2547105197Ssam	if (result)
2548105197Ssam		m_freem(result);
2549105197Ssam	splx(s);
2550105197Ssam	return error;
2551105197Ssam}
2552105197Ssam
2553105197Ssam/* %%% SAD management */
2554105197Ssam/*
2555105197Ssam * allocating a memory for new SA head, and copy from the values of mhp.
2556105197Ssam * OUT:	NULL	: failure due to the lack of memory.
2557105197Ssam *	others	: pointer to new SA head.
2558105197Ssam */
2559105197Ssamstatic struct secashead *
2560105197Ssamkey_newsah(saidx)
2561105197Ssam	struct secasindex *saidx;
2562105197Ssam{
2563105197Ssam	struct secashead *newsah;
2564105197Ssam
2565105197Ssam	KASSERT(saidx != NULL, ("key_newsaidx: null saidx"));
2566105197Ssam
2567105197Ssam	newsah = (struct secashead *)
2568105197Ssam		malloc(sizeof(struct secashead), M_SECA, M_NOWAIT|M_ZERO);
2569105197Ssam	if (newsah != NULL) {
2570105197Ssam		int i;
2571105197Ssam		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2572105197Ssam			LIST_INIT(&newsah->savtree[i]);
2573105197Ssam		newsah->saidx = *saidx;
2574105197Ssam
2575105197Ssam		/* add to saidxtree */
2576105197Ssam		newsah->state = SADB_SASTATE_MATURE;
2577105197Ssam		LIST_INSERT_HEAD(&sahtree, newsah, chain);
2578105197Ssam	}
2579105197Ssam	return(newsah);
2580105197Ssam}
2581105197Ssam
2582105197Ssam/*
2583105197Ssam * delete SA index and all SA registerd.
2584105197Ssam */
2585105197Ssamstatic void
2586105197Ssamkey_delsah(sah)
2587105197Ssam	struct secashead *sah;
2588105197Ssam{
2589105197Ssam	struct secasvar *sav, *nextsav;
2590105197Ssam	u_int stateidx, state;
2591105197Ssam	int s;
2592105197Ssam	int zombie = 0;
2593105197Ssam
2594105197Ssam	/* sanity check */
2595105197Ssam	if (sah == NULL)
2596105197Ssam		panic("key_delsah: NULL pointer is passed.\n");
2597105197Ssam
2598105197Ssam	s = splnet();	/*called from softclock()*/
2599105197Ssam
2600105197Ssam	/* searching all SA registerd in the secindex. */
2601105197Ssam	for (stateidx = 0;
2602105197Ssam	     stateidx < _ARRAYLEN(saorder_state_any);
2603105197Ssam	     stateidx++) {
2604105197Ssam
2605105197Ssam		state = saorder_state_any[stateidx];
2606105197Ssam		for (sav = (struct secasvar *)LIST_FIRST(&sah->savtree[state]);
2607105197Ssam		     sav != NULL;
2608105197Ssam		     sav = nextsav) {
2609105197Ssam
2610105197Ssam			nextsav = LIST_NEXT(sav, chain);
2611105197Ssam
2612105197Ssam			if (sav->refcnt == 0) {
2613105197Ssam				/* sanity check */
2614105197Ssam				KEY_CHKSASTATE(state, sav->state, "key_delsah");
2615105197Ssam				KEY_FREESAV(&sav);
2616105197Ssam			} else {
2617105197Ssam				/* give up to delete this sa */
2618105197Ssam				zombie++;
2619105197Ssam			}
2620105197Ssam		}
2621105197Ssam	}
2622105197Ssam
2623105197Ssam	/* don't delete sah only if there are savs. */
2624105197Ssam	if (zombie) {
2625105197Ssam		splx(s);
2626105197Ssam		return;
2627105197Ssam	}
2628105197Ssam
2629105197Ssam	if (sah->sa_route.ro_rt) {
2630105197Ssam		RTFREE(sah->sa_route.ro_rt);
2631105197Ssam		sah->sa_route.ro_rt = (struct rtentry *)NULL;
2632105197Ssam	}
2633105197Ssam
2634105197Ssam	/* remove from tree of SA index */
2635105197Ssam	if (__LIST_CHAINED(sah))
2636105197Ssam		LIST_REMOVE(sah, chain);
2637105197Ssam
2638105197Ssam	KFREE(sah);
2639105197Ssam
2640105197Ssam	splx(s);
2641105197Ssam	return;
2642105197Ssam}
2643105197Ssam
2644105197Ssam/*
2645105197Ssam * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2646105197Ssam * and copy the values of mhp into new buffer.
2647105197Ssam * When SAD message type is GETSPI:
2648105197Ssam *	to set sequence number from acq_seq++,
2649105197Ssam *	to set zero to SPI.
2650105197Ssam *	not to call key_setsava().
2651105197Ssam * OUT:	NULL	: fail
2652105197Ssam *	others	: pointer to new secasvar.
2653105197Ssam *
2654105197Ssam * does not modify mbuf.  does not free mbuf on error.
2655105197Ssam */
2656105197Ssamstatic struct secasvar *
2657105197Ssamkey_newsav(m, mhp, sah, errp, where, tag)
2658105197Ssam	struct mbuf *m;
2659105197Ssam	const struct sadb_msghdr *mhp;
2660105197Ssam	struct secashead *sah;
2661105197Ssam	int *errp;
2662105197Ssam	const char* where;
2663105197Ssam	int tag;
2664105197Ssam{
2665105197Ssam	struct secasvar *newsav;
2666105197Ssam	const struct sadb_sa *xsa;
2667105197Ssam
2668105197Ssam	/* sanity check */
2669105197Ssam	if (m == NULL || mhp == NULL || mhp->msg == NULL || sah == NULL)
2670105197Ssam		panic("key_newsa: NULL pointer is passed.\n");
2671105197Ssam
2672105197Ssam	KMALLOC(newsav, struct secasvar *, sizeof(struct secasvar));
2673105197Ssam	if (newsav == NULL) {
2674105197Ssam		ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n"));
2675105197Ssam		*errp = ENOBUFS;
2676105197Ssam		goto done;
2677105197Ssam	}
2678105197Ssam	bzero((caddr_t)newsav, sizeof(struct secasvar));
2679105197Ssam
2680105197Ssam	switch (mhp->msg->sadb_msg_type) {
2681105197Ssam	case SADB_GETSPI:
2682105197Ssam		newsav->spi = 0;
2683105197Ssam
2684105197Ssam#ifdef IPSEC_DOSEQCHECK
2685105197Ssam		/* sync sequence number */
2686105197Ssam		if (mhp->msg->sadb_msg_seq == 0)
2687105197Ssam			newsav->seq =
2688105197Ssam				(acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
2689105197Ssam		else
2690105197Ssam#endif
2691105197Ssam			newsav->seq = mhp->msg->sadb_msg_seq;
2692105197Ssam		break;
2693105197Ssam
2694105197Ssam	case SADB_ADD:
2695105197Ssam		/* sanity check */
2696105197Ssam		if (mhp->ext[SADB_EXT_SA] == NULL) {
2697105197Ssam			KFREE(newsav), newsav = NULL;
2698105197Ssam			ipseclog((LOG_DEBUG, "key_newsa: invalid message is passed.\n"));
2699105197Ssam			*errp = EINVAL;
2700105197Ssam			goto done;
2701105197Ssam		}
2702105197Ssam		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2703105197Ssam		newsav->spi = xsa->sadb_sa_spi;
2704105197Ssam		newsav->seq = mhp->msg->sadb_msg_seq;
2705105197Ssam		break;
2706105197Ssam	default:
2707105197Ssam		KFREE(newsav), newsav = NULL;
2708105197Ssam		*errp = EINVAL;
2709105197Ssam		goto done;
2710105197Ssam	}
2711105197Ssam
2712105197Ssam	/* copy sav values */
2713105197Ssam	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2714105197Ssam		*errp = key_setsaval(newsav, m, mhp);
2715105197Ssam		if (*errp) {
2716105197Ssam			KFREE(newsav), newsav = NULL;
2717105197Ssam			goto done;
2718105197Ssam		}
2719105197Ssam	}
2720105197Ssam
2721105197Ssam	/* reset created */
2722105197Ssam	newsav->created = time_second;
2723105197Ssam	newsav->pid = mhp->msg->sadb_msg_pid;
2724105197Ssam
2725105197Ssam	/* add to satree */
2726105197Ssam	newsav->sah = sah;
2727105197Ssam	newsav->refcnt = 1;
2728105197Ssam	newsav->state = SADB_SASTATE_LARVAL;
2729105197Ssam	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2730105197Ssam			secasvar, chain);
2731105197Ssamdone:
2732105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2733105197Ssam		printf("DP key_newsav from %s:%u return SP:%p\n",
2734105197Ssam			where, tag, newsav));
2735105197Ssam
2736105197Ssam	return newsav;
2737105197Ssam}
2738105197Ssam
2739105197Ssam/*
2740105197Ssam * free() SA variable entry.
2741105197Ssam */
2742105197Ssamstatic void
2743105197Ssamkey_delsav(sav)
2744105197Ssam	struct secasvar *sav;
2745105197Ssam{
2746105197Ssam	KASSERT(sav != NULL, ("key_delsav: null sav"));
2747105197Ssam	KASSERT(sav->refcnt == 0,
2748105197Ssam		("key_delsav: reference count %u > 0", sav->refcnt));
2749105197Ssam
2750105197Ssam	/* remove from SA header */
2751105197Ssam	if (__LIST_CHAINED(sav))
2752105197Ssam		LIST_REMOVE(sav, chain);
2753105197Ssam
2754117051Ssam	/*
2755117051Ssam	 * Cleanup xform state.  Note that zeroize'ing causes the
2756117051Ssam	 * keys to be cleared; otherwise we must do it ourself.
2757117051Ssam	 */
2758117051Ssam	if (sav->tdb_xform != NULL) {
2759117051Ssam		sav->tdb_xform->xf_zeroize(sav);
2760117051Ssam		sav->tdb_xform = NULL;
2761117051Ssam	} else {
2762117051Ssam		if (sav->key_auth != NULL)
2763117051Ssam			bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2764117051Ssam		if (sav->key_enc != NULL)
2765117051Ssam			bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
2766117051Ssam	}
2767105197Ssam	if (sav->key_auth != NULL) {
2768105197Ssam		KFREE(sav->key_auth);
2769105197Ssam		sav->key_auth = NULL;
2770105197Ssam	}
2771105197Ssam	if (sav->key_enc != NULL) {
2772105197Ssam		KFREE(sav->key_enc);
2773105197Ssam		sav->key_enc = NULL;
2774105197Ssam	}
2775105197Ssam	if (sav->sched) {
2776105197Ssam		bzero(sav->sched, sav->schedlen);
2777105197Ssam		KFREE(sav->sched);
2778105197Ssam		sav->sched = NULL;
2779105197Ssam	}
2780105197Ssam	if (sav->replay != NULL) {
2781105197Ssam		KFREE(sav->replay);
2782105197Ssam		sav->replay = NULL;
2783105197Ssam	}
2784105197Ssam	if (sav->lft_c != NULL) {
2785105197Ssam		KFREE(sav->lft_c);
2786105197Ssam		sav->lft_c = NULL;
2787105197Ssam	}
2788105197Ssam	if (sav->lft_h != NULL) {
2789105197Ssam		KFREE(sav->lft_h);
2790105197Ssam		sav->lft_h = NULL;
2791105197Ssam	}
2792105197Ssam	if (sav->lft_s != NULL) {
2793105197Ssam		KFREE(sav->lft_s);
2794105197Ssam		sav->lft_s = NULL;
2795105197Ssam	}
2796105197Ssam	if (sav->iv != NULL) {
2797105197Ssam		KFREE(sav->iv);
2798105197Ssam		sav->iv = NULL;
2799105197Ssam	}
2800105197Ssam
2801105197Ssam	KFREE(sav);
2802105197Ssam
2803105197Ssam	return;
2804105197Ssam}
2805105197Ssam
2806105197Ssam/*
2807105197Ssam * search SAD.
2808105197Ssam * OUT:
2809105197Ssam *	NULL	: not found
2810105197Ssam *	others	: found, pointer to a SA.
2811105197Ssam */
2812105197Ssamstatic struct secashead *
2813105197Ssamkey_getsah(saidx)
2814105197Ssam	struct secasindex *saidx;
2815105197Ssam{
2816105197Ssam	struct secashead *sah;
2817105197Ssam
2818105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
2819105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
2820105197Ssam			continue;
2821105197Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2822105197Ssam			return sah;
2823105197Ssam	}
2824105197Ssam
2825105197Ssam	return NULL;
2826105197Ssam}
2827105197Ssam
2828105197Ssam/*
2829105197Ssam * check not to be duplicated SPI.
2830105197Ssam * NOTE: this function is too slow due to searching all SAD.
2831105197Ssam * OUT:
2832105197Ssam *	NULL	: not found
2833105197Ssam *	others	: found, pointer to a SA.
2834105197Ssam */
2835105197Ssamstatic struct secasvar *
2836105197Ssamkey_checkspidup(saidx, spi)
2837105197Ssam	struct secasindex *saidx;
2838105197Ssam	u_int32_t spi;
2839105197Ssam{
2840105197Ssam	struct secashead *sah;
2841105197Ssam	struct secasvar *sav;
2842105197Ssam
2843105197Ssam	/* check address family */
2844105197Ssam	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2845105197Ssam		ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n"));
2846105197Ssam		return NULL;
2847105197Ssam	}
2848105197Ssam
2849105197Ssam	/* check all SAD */
2850105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
2851105197Ssam		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2852105197Ssam			continue;
2853105197Ssam		sav = key_getsavbyspi(sah, spi);
2854105197Ssam		if (sav != NULL)
2855105197Ssam			return sav;
2856105197Ssam	}
2857105197Ssam
2858105197Ssam	return NULL;
2859105197Ssam}
2860105197Ssam
2861105197Ssam/*
2862105197Ssam * search SAD litmited alive SA, protocol, SPI.
2863105197Ssam * OUT:
2864105197Ssam *	NULL	: not found
2865105197Ssam *	others	: found, pointer to a SA.
2866105197Ssam */
2867105197Ssamstatic struct secasvar *
2868105197Ssamkey_getsavbyspi(sah, spi)
2869105197Ssam	struct secashead *sah;
2870105197Ssam	u_int32_t spi;
2871105197Ssam{
2872105197Ssam	struct secasvar *sav;
2873105197Ssam	u_int stateidx, state;
2874105197Ssam
2875105197Ssam	/* search all status */
2876105197Ssam	for (stateidx = 0;
2877105197Ssam	     stateidx < _ARRAYLEN(saorder_state_alive);
2878105197Ssam	     stateidx++) {
2879105197Ssam
2880105197Ssam		state = saorder_state_alive[stateidx];
2881105197Ssam		LIST_FOREACH(sav, &sah->savtree[state], chain) {
2882105197Ssam
2883105197Ssam			/* sanity check */
2884105197Ssam			if (sav->state != state) {
2885105197Ssam				ipseclog((LOG_DEBUG, "key_getsavbyspi: "
2886105197Ssam				    "invalid sav->state (queue: %d SA: %d)\n",
2887105197Ssam				    state, sav->state));
2888105197Ssam				continue;
2889105197Ssam			}
2890105197Ssam
2891105197Ssam			if (sav->spi == spi)
2892105197Ssam				return sav;
2893105197Ssam		}
2894105197Ssam	}
2895105197Ssam
2896105197Ssam	return NULL;
2897105197Ssam}
2898105197Ssam
2899105197Ssam/*
2900105197Ssam * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
2901105197Ssam * You must update these if need.
2902105197Ssam * OUT:	0:	success.
2903105197Ssam *	!0:	failure.
2904105197Ssam *
2905105197Ssam * does not modify mbuf.  does not free mbuf on error.
2906105197Ssam */
2907105197Ssamstatic int
2908105197Ssamkey_setsaval(sav, m, mhp)
2909105197Ssam	struct secasvar *sav;
2910105197Ssam	struct mbuf *m;
2911105197Ssam	const struct sadb_msghdr *mhp;
2912105197Ssam{
2913105197Ssam	int error = 0;
2914105197Ssam
2915105197Ssam	/* sanity check */
2916105197Ssam	if (m == NULL || mhp == NULL || mhp->msg == NULL)
2917105197Ssam		panic("key_setsaval: NULL pointer is passed.\n");
2918105197Ssam
2919105197Ssam	/* initialization */
2920105197Ssam	sav->replay = NULL;
2921105197Ssam	sav->key_auth = NULL;
2922105197Ssam	sav->key_enc = NULL;
2923105197Ssam	sav->sched = NULL;
2924105197Ssam	sav->schedlen = 0;
2925105197Ssam	sav->iv = NULL;
2926105197Ssam	sav->lft_c = NULL;
2927105197Ssam	sav->lft_h = NULL;
2928105197Ssam	sav->lft_s = NULL;
2929105197Ssam	sav->tdb_xform = NULL;		/* transform */
2930105197Ssam	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
2931105197Ssam	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
2932105197Ssam	sav->tdb_compalgxform = NULL;	/* compression algorithm */
2933105197Ssam
2934105197Ssam	/* SA */
2935105197Ssam	if (mhp->ext[SADB_EXT_SA] != NULL) {
2936105197Ssam		const struct sadb_sa *sa0;
2937105197Ssam
2938105197Ssam		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2939105197Ssam		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
2940105197Ssam			error = EINVAL;
2941105197Ssam			goto fail;
2942105197Ssam		}
2943105197Ssam
2944105197Ssam		sav->alg_auth = sa0->sadb_sa_auth;
2945105197Ssam		sav->alg_enc = sa0->sadb_sa_encrypt;
2946105197Ssam		sav->flags = sa0->sadb_sa_flags;
2947105197Ssam
2948105197Ssam		/* replay window */
2949105197Ssam		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
2950105197Ssam			sav->replay = (struct secreplay *)
2951105197Ssam				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_SECA, M_NOWAIT|M_ZERO);
2952105197Ssam			if (sav->replay == NULL) {
2953105197Ssam				ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2954105197Ssam				error = ENOBUFS;
2955105197Ssam				goto fail;
2956105197Ssam			}
2957105197Ssam			if (sa0->sadb_sa_replay != 0)
2958105197Ssam				sav->replay->bitmap = (caddr_t)(sav->replay+1);
2959105197Ssam			sav->replay->wsize = sa0->sadb_sa_replay;
2960105197Ssam		}
2961105197Ssam	}
2962105197Ssam
2963105197Ssam	/* Authentication keys */
2964105197Ssam	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
2965105197Ssam		const struct sadb_key *key0;
2966105197Ssam		int len;
2967105197Ssam
2968105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
2969105197Ssam		len = mhp->extlen[SADB_EXT_KEY_AUTH];
2970105197Ssam
2971105197Ssam		error = 0;
2972105197Ssam		if (len < sizeof(*key0)) {
2973105197Ssam			error = EINVAL;
2974105197Ssam			goto fail;
2975105197Ssam		}
2976105197Ssam		switch (mhp->msg->sadb_msg_satype) {
2977105197Ssam		case SADB_SATYPE_AH:
2978105197Ssam		case SADB_SATYPE_ESP:
2979105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
2980105197Ssam			    sav->alg_auth != SADB_X_AALG_NULL)
2981105197Ssam				error = EINVAL;
2982105197Ssam			break;
2983105197Ssam		case SADB_X_SATYPE_IPCOMP:
2984105197Ssam		default:
2985105197Ssam			error = EINVAL;
2986105197Ssam			break;
2987105197Ssam		}
2988105197Ssam		if (error) {
2989105197Ssam			ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n"));
2990105197Ssam			goto fail;
2991105197Ssam		}
2992105197Ssam
2993105197Ssam		sav->key_auth = (struct sadb_key *)key_newbuf(key0, len);
2994105197Ssam		if (sav->key_auth == NULL) {
2995105197Ssam			ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2996105197Ssam			error = ENOBUFS;
2997105197Ssam			goto fail;
2998105197Ssam		}
2999105197Ssam	}
3000105197Ssam
3001105197Ssam	/* Encryption key */
3002105197Ssam	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3003105197Ssam		const struct sadb_key *key0;
3004105197Ssam		int len;
3005105197Ssam
3006105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3007105197Ssam		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3008105197Ssam
3009105197Ssam		error = 0;
3010105197Ssam		if (len < sizeof(*key0)) {
3011105197Ssam			error = EINVAL;
3012105197Ssam			goto fail;
3013105197Ssam		}
3014105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3015105197Ssam		case SADB_SATYPE_ESP:
3016105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3017105197Ssam			    sav->alg_enc != SADB_EALG_NULL) {
3018105197Ssam				error = EINVAL;
3019105197Ssam				break;
3020105197Ssam			}
3021105197Ssam			sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
3022105197Ssam			if (sav->key_enc == NULL) {
3023105197Ssam				ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3024105197Ssam				error = ENOBUFS;
3025105197Ssam				goto fail;
3026105197Ssam			}
3027105197Ssam			break;
3028105197Ssam		case SADB_X_SATYPE_IPCOMP:
3029105197Ssam			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3030105197Ssam				error = EINVAL;
3031105197Ssam			sav->key_enc = NULL;	/*just in case*/
3032105197Ssam			break;
3033105197Ssam		case SADB_SATYPE_AH:
3034105197Ssam		default:
3035105197Ssam			error = EINVAL;
3036105197Ssam			break;
3037105197Ssam		}
3038105197Ssam		if (error) {
3039105197Ssam			ipseclog((LOG_DEBUG, "key_setsatval: invalid key_enc value.\n"));
3040105197Ssam			goto fail;
3041105197Ssam		}
3042105197Ssam	}
3043105197Ssam
3044105197Ssam	/* set iv */
3045105197Ssam	sav->ivlen = 0;
3046105197Ssam
3047105197Ssam	switch (mhp->msg->sadb_msg_satype) {
3048105197Ssam	case SADB_SATYPE_AH:
3049105197Ssam		error = xform_init(sav, XF_AH);
3050105197Ssam		break;
3051105197Ssam	case SADB_SATYPE_ESP:
3052105197Ssam		error = xform_init(sav, XF_ESP);
3053105197Ssam		break;
3054105197Ssam	case SADB_X_SATYPE_IPCOMP:
3055105197Ssam		error = xform_init(sav, XF_IPCOMP);
3056105197Ssam		break;
3057105197Ssam	}
3058105197Ssam	if (error) {
3059105197Ssam		ipseclog((LOG_DEBUG,
3060105197Ssam			"key_setsaval: unable to initialize SA type %u.\n",
3061105197Ssam		        mhp->msg->sadb_msg_satype));
3062105197Ssam		goto fail;
3063105197Ssam	}
3064105197Ssam
3065105197Ssam	/* reset created */
3066105197Ssam	sav->created = time_second;
3067105197Ssam
3068105197Ssam	/* make lifetime for CURRENT */
3069105197Ssam	KMALLOC(sav->lft_c, struct sadb_lifetime *,
3070105197Ssam	    sizeof(struct sadb_lifetime));
3071105197Ssam	if (sav->lft_c == NULL) {
3072105197Ssam		ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3073105197Ssam		error = ENOBUFS;
3074105197Ssam		goto fail;
3075105197Ssam	}
3076105197Ssam
3077105197Ssam	sav->lft_c->sadb_lifetime_len =
3078105197Ssam	    PFKEY_UNIT64(sizeof(struct sadb_lifetime));
3079105197Ssam	sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
3080105197Ssam	sav->lft_c->sadb_lifetime_allocations = 0;
3081105197Ssam	sav->lft_c->sadb_lifetime_bytes = 0;
3082105197Ssam	sav->lft_c->sadb_lifetime_addtime = time_second;
3083105197Ssam	sav->lft_c->sadb_lifetime_usetime = 0;
3084105197Ssam
3085105197Ssam	/* lifetimes for HARD and SOFT */
3086105197Ssam    {
3087105197Ssam	const struct sadb_lifetime *lft0;
3088105197Ssam
3089105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3090105197Ssam	if (lft0 != NULL) {
3091105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3092105197Ssam			error = EINVAL;
3093105197Ssam			goto fail;
3094105197Ssam		}
3095105197Ssam		sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0,
3096105197Ssam		    sizeof(*lft0));
3097105197Ssam		if (sav->lft_h == NULL) {
3098105197Ssam			ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3099105197Ssam			error = ENOBUFS;
3100105197Ssam			goto fail;
3101105197Ssam		}
3102105197Ssam		/* to be initialize ? */
3103105197Ssam	}
3104105197Ssam
3105105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3106105197Ssam	if (lft0 != NULL) {
3107105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3108105197Ssam			error = EINVAL;
3109105197Ssam			goto fail;
3110105197Ssam		}
3111105197Ssam		sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0,
3112105197Ssam		    sizeof(*lft0));
3113105197Ssam		if (sav->lft_s == NULL) {
3114105197Ssam			ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3115105197Ssam			error = ENOBUFS;
3116105197Ssam			goto fail;
3117105197Ssam		}
3118105197Ssam		/* to be initialize ? */
3119105197Ssam	}
3120105197Ssam    }
3121105197Ssam
3122105197Ssam	return 0;
3123105197Ssam
3124105197Ssam fail:
3125105197Ssam	/* initialization */
3126105197Ssam	if (sav->replay != NULL) {
3127105197Ssam		KFREE(sav->replay);
3128105197Ssam		sav->replay = NULL;
3129105197Ssam	}
3130105197Ssam	if (sav->key_auth != NULL) {
3131105197Ssam		KFREE(sav->key_auth);
3132105197Ssam		sav->key_auth = NULL;
3133105197Ssam	}
3134105197Ssam	if (sav->key_enc != NULL) {
3135105197Ssam		KFREE(sav->key_enc);
3136105197Ssam		sav->key_enc = NULL;
3137105197Ssam	}
3138105197Ssam	if (sav->sched) {
3139105197Ssam		KFREE(sav->sched);
3140105197Ssam		sav->sched = NULL;
3141105197Ssam	}
3142105197Ssam	if (sav->iv != NULL) {
3143105197Ssam		KFREE(sav->iv);
3144105197Ssam		sav->iv = NULL;
3145105197Ssam	}
3146105197Ssam	if (sav->lft_c != NULL) {
3147105197Ssam		KFREE(sav->lft_c);
3148105197Ssam		sav->lft_c = NULL;
3149105197Ssam	}
3150105197Ssam	if (sav->lft_h != NULL) {
3151105197Ssam		KFREE(sav->lft_h);
3152105197Ssam		sav->lft_h = NULL;
3153105197Ssam	}
3154105197Ssam	if (sav->lft_s != NULL) {
3155105197Ssam		KFREE(sav->lft_s);
3156105197Ssam		sav->lft_s = NULL;
3157105197Ssam	}
3158105197Ssam
3159105197Ssam	return error;
3160105197Ssam}
3161105197Ssam
3162105197Ssam/*
3163105197Ssam * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3164105197Ssam * OUT:	0:	valid
3165105197Ssam *	other:	errno
3166105197Ssam */
3167105197Ssamstatic int
3168105197Ssamkey_mature(sav)
3169105197Ssam	struct secasvar *sav;
3170105197Ssam{
3171105197Ssam	int error;
3172105197Ssam
3173105197Ssam	/* check SPI value */
3174105197Ssam	switch (sav->sah->saidx.proto) {
3175105197Ssam	case IPPROTO_ESP:
3176105197Ssam	case IPPROTO_AH:
3177105197Ssam		if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
3178105197Ssam			ipseclog((LOG_DEBUG,
3179105197Ssam			    "key_mature: illegal range of SPI %u.\n",
3180105197Ssam			    (u_int32_t)ntohl(sav->spi)));
3181105197Ssam			return EINVAL;
3182105197Ssam		}
3183105197Ssam		break;
3184105197Ssam	}
3185105197Ssam
3186105197Ssam	/* check satype */
3187105197Ssam	switch (sav->sah->saidx.proto) {
3188105197Ssam	case IPPROTO_ESP:
3189105197Ssam		/* check flags */
3190105197Ssam		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3191105197Ssam		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3192105197Ssam			ipseclog((LOG_DEBUG, "key_mature: "
3193105197Ssam			    "invalid flag (derived) given to old-esp.\n"));
3194105197Ssam			return EINVAL;
3195105197Ssam		}
3196105197Ssam		error = xform_init(sav, XF_ESP);
3197105197Ssam		break;
3198105197Ssam	case IPPROTO_AH:
3199105197Ssam		/* check flags */
3200105197Ssam		if (sav->flags & SADB_X_EXT_DERIV) {
3201105197Ssam			ipseclog((LOG_DEBUG, "key_mature: "
3202105197Ssam			    "invalid flag (derived) given to AH SA.\n"));
3203105197Ssam			return EINVAL;
3204105197Ssam		}
3205105197Ssam		if (sav->alg_enc != SADB_EALG_NONE) {
3206105197Ssam			ipseclog((LOG_DEBUG, "key_mature: "
3207105197Ssam			    "protocol and algorithm mismated.\n"));
3208105197Ssam			return(EINVAL);
3209105197Ssam		}
3210105197Ssam		error = xform_init(sav, XF_AH);
3211105197Ssam		break;
3212105197Ssam	case IPPROTO_IPCOMP:
3213105197Ssam		if (sav->alg_auth != SADB_AALG_NONE) {
3214105197Ssam			ipseclog((LOG_DEBUG, "key_mature: "
3215105197Ssam				"protocol and algorithm mismated.\n"));
3216105197Ssam			return(EINVAL);
3217105197Ssam		}
3218105197Ssam		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3219105197Ssam		 && ntohl(sav->spi) >= 0x10000) {
3220105197Ssam			ipseclog((LOG_DEBUG, "key_mature: invalid cpi for IPComp.\n"));
3221105197Ssam			return(EINVAL);
3222105197Ssam		}
3223105197Ssam		error = xform_init(sav, XF_IPCOMP);
3224105197Ssam		break;
3225105197Ssam	default:
3226105197Ssam		ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n"));
3227105197Ssam		error = EPROTONOSUPPORT;
3228105197Ssam		break;
3229105197Ssam	}
3230105197Ssam	if (error == 0)
3231105197Ssam		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3232105197Ssam	return (error);
3233105197Ssam}
3234105197Ssam
3235105197Ssam/*
3236105197Ssam * subroutine for SADB_GET and SADB_DUMP.
3237105197Ssam */
3238105197Ssamstatic struct mbuf *
3239105197Ssamkey_setdumpsa(sav, type, satype, seq, pid)
3240105197Ssam	struct secasvar *sav;
3241105197Ssam	u_int8_t type, satype;
3242105197Ssam	u_int32_t seq, pid;
3243105197Ssam{
3244105197Ssam	struct mbuf *result = NULL, *tres = NULL, *m;
3245105197Ssam	int l = 0;
3246105197Ssam	int i;
3247105197Ssam	void *p;
3248105197Ssam	int dumporder[] = {
3249105197Ssam		SADB_EXT_SA, SADB_X_EXT_SA2,
3250105197Ssam		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3251105197Ssam		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3252105197Ssam		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3253105197Ssam		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3254105197Ssam		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3255105197Ssam	};
3256105197Ssam
3257105197Ssam	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3258105197Ssam	if (m == NULL)
3259105197Ssam		goto fail;
3260105197Ssam	result = m;
3261105197Ssam
3262105197Ssam	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3263105197Ssam		m = NULL;
3264105197Ssam		p = NULL;
3265105197Ssam		switch (dumporder[i]) {
3266105197Ssam		case SADB_EXT_SA:
3267105197Ssam			m = key_setsadbsa(sav);
3268105197Ssam			if (!m)
3269105197Ssam				goto fail;
3270105197Ssam			break;
3271105197Ssam
3272105197Ssam		case SADB_X_EXT_SA2:
3273105197Ssam			m = key_setsadbxsa2(sav->sah->saidx.mode,
3274105197Ssam					sav->replay ? sav->replay->count : 0,
3275105197Ssam					sav->sah->saidx.reqid);
3276105197Ssam			if (!m)
3277105197Ssam				goto fail;
3278105197Ssam			break;
3279105197Ssam
3280105197Ssam		case SADB_EXT_ADDRESS_SRC:
3281105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3282105197Ssam			    &sav->sah->saidx.src.sa,
3283105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3284105197Ssam			if (!m)
3285105197Ssam				goto fail;
3286105197Ssam			break;
3287105197Ssam
3288105197Ssam		case SADB_EXT_ADDRESS_DST:
3289105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3290105197Ssam			    &sav->sah->saidx.dst.sa,
3291105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3292105197Ssam			if (!m)
3293105197Ssam				goto fail;
3294105197Ssam			break;
3295105197Ssam
3296105197Ssam		case SADB_EXT_KEY_AUTH:
3297105197Ssam			if (!sav->key_auth)
3298105197Ssam				continue;
3299105197Ssam			l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
3300105197Ssam			p = sav->key_auth;
3301105197Ssam			break;
3302105197Ssam
3303105197Ssam		case SADB_EXT_KEY_ENCRYPT:
3304105197Ssam			if (!sav->key_enc)
3305105197Ssam				continue;
3306105197Ssam			l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
3307105197Ssam			p = sav->key_enc;
3308105197Ssam			break;
3309105197Ssam
3310105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
3311105197Ssam			if (!sav->lft_c)
3312105197Ssam				continue;
3313105197Ssam			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
3314105197Ssam			p = sav->lft_c;
3315105197Ssam			break;
3316105197Ssam
3317105197Ssam		case SADB_EXT_LIFETIME_HARD:
3318105197Ssam			if (!sav->lft_h)
3319105197Ssam				continue;
3320105197Ssam			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
3321105197Ssam			p = sav->lft_h;
3322105197Ssam			break;
3323105197Ssam
3324105197Ssam		case SADB_EXT_LIFETIME_SOFT:
3325105197Ssam			if (!sav->lft_s)
3326105197Ssam				continue;
3327105197Ssam			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
3328105197Ssam			p = sav->lft_s;
3329105197Ssam			break;
3330105197Ssam
3331105197Ssam		case SADB_EXT_ADDRESS_PROXY:
3332105197Ssam		case SADB_EXT_IDENTITY_SRC:
3333105197Ssam		case SADB_EXT_IDENTITY_DST:
3334105197Ssam			/* XXX: should we brought from SPD ? */
3335105197Ssam		case SADB_EXT_SENSITIVITY:
3336105197Ssam		default:
3337105197Ssam			continue;
3338105197Ssam		}
3339105197Ssam
3340105197Ssam		if ((!m && !p) || (m && p))
3341105197Ssam			goto fail;
3342105197Ssam		if (p && tres) {
3343111119Simp			M_PREPEND(tres, l, M_DONTWAIT);
3344105197Ssam			if (!tres)
3345105197Ssam				goto fail;
3346105197Ssam			bcopy(p, mtod(tres, caddr_t), l);
3347105197Ssam			continue;
3348105197Ssam		}
3349105197Ssam		if (p) {
3350105197Ssam			m = key_alloc_mbuf(l);
3351105197Ssam			if (!m)
3352105197Ssam				goto fail;
3353105197Ssam			m_copyback(m, 0, l, p);
3354105197Ssam		}
3355105197Ssam
3356105197Ssam		if (tres)
3357105197Ssam			m_cat(m, tres);
3358105197Ssam		tres = m;
3359105197Ssam	}
3360105197Ssam
3361105197Ssam	m_cat(result, tres);
3362105197Ssam
3363105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
3364105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
3365105197Ssam		if (result == NULL)
3366105197Ssam			goto fail;
3367105197Ssam	}
3368105197Ssam
3369105197Ssam	result->m_pkthdr.len = 0;
3370105197Ssam	for (m = result; m; m = m->m_next)
3371105197Ssam		result->m_pkthdr.len += m->m_len;
3372105197Ssam
3373105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
3374105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
3375105197Ssam
3376105197Ssam	return result;
3377105197Ssam
3378105197Ssamfail:
3379105197Ssam	m_freem(result);
3380105197Ssam	m_freem(tres);
3381105197Ssam	return NULL;
3382105197Ssam}
3383105197Ssam
3384105197Ssam/*
3385105197Ssam * set data into sadb_msg.
3386105197Ssam */
3387105197Ssamstatic struct mbuf *
3388105197Ssamkey_setsadbmsg(type, tlen, satype, seq, pid, reserved)
3389105197Ssam	u_int8_t type, satype;
3390105197Ssam	u_int16_t tlen;
3391105197Ssam	u_int32_t seq;
3392105197Ssam	pid_t pid;
3393105197Ssam	u_int16_t reserved;
3394105197Ssam{
3395105197Ssam	struct mbuf *m;
3396105197Ssam	struct sadb_msg *p;
3397105197Ssam	int len;
3398105197Ssam
3399105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3400105197Ssam	if (len > MCLBYTES)
3401105197Ssam		return NULL;
3402111119Simp	MGETHDR(m, M_DONTWAIT, MT_DATA);
3403105197Ssam	if (m && len > MHLEN) {
3404111119Simp		MCLGET(m, M_DONTWAIT);
3405105197Ssam		if ((m->m_flags & M_EXT) == 0) {
3406105197Ssam			m_freem(m);
3407105197Ssam			m = NULL;
3408105197Ssam		}
3409105197Ssam	}
3410105197Ssam	if (!m)
3411105197Ssam		return NULL;
3412105197Ssam	m->m_pkthdr.len = m->m_len = len;
3413105197Ssam	m->m_next = NULL;
3414105197Ssam
3415105197Ssam	p = mtod(m, struct sadb_msg *);
3416105197Ssam
3417105197Ssam	bzero(p, len);
3418105197Ssam	p->sadb_msg_version = PF_KEY_V2;
3419105197Ssam	p->sadb_msg_type = type;
3420105197Ssam	p->sadb_msg_errno = 0;
3421105197Ssam	p->sadb_msg_satype = satype;
3422105197Ssam	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3423105197Ssam	p->sadb_msg_reserved = reserved;
3424105197Ssam	p->sadb_msg_seq = seq;
3425105197Ssam	p->sadb_msg_pid = (u_int32_t)pid;
3426105197Ssam
3427105197Ssam	return m;
3428105197Ssam}
3429105197Ssam
3430105197Ssam/*
3431105197Ssam * copy secasvar data into sadb_address.
3432105197Ssam */
3433105197Ssamstatic struct mbuf *
3434105197Ssamkey_setsadbsa(sav)
3435105197Ssam	struct secasvar *sav;
3436105197Ssam{
3437105197Ssam	struct mbuf *m;
3438105197Ssam	struct sadb_sa *p;
3439105197Ssam	int len;
3440105197Ssam
3441105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3442105197Ssam	m = key_alloc_mbuf(len);
3443105197Ssam	if (!m || m->m_next) {	/*XXX*/
3444105197Ssam		if (m)
3445105197Ssam			m_freem(m);
3446105197Ssam		return NULL;
3447105197Ssam	}
3448105197Ssam
3449105197Ssam	p = mtod(m, struct sadb_sa *);
3450105197Ssam
3451105197Ssam	bzero(p, len);
3452105197Ssam	p->sadb_sa_len = PFKEY_UNIT64(len);
3453105197Ssam	p->sadb_sa_exttype = SADB_EXT_SA;
3454105197Ssam	p->sadb_sa_spi = sav->spi;
3455105197Ssam	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3456105197Ssam	p->sadb_sa_state = sav->state;
3457105197Ssam	p->sadb_sa_auth = sav->alg_auth;
3458105197Ssam	p->sadb_sa_encrypt = sav->alg_enc;
3459105197Ssam	p->sadb_sa_flags = sav->flags;
3460105197Ssam
3461105197Ssam	return m;
3462105197Ssam}
3463105197Ssam
3464105197Ssam/*
3465105197Ssam * set data into sadb_address.
3466105197Ssam */
3467105197Ssamstatic struct mbuf *
3468105197Ssamkey_setsadbaddr(exttype, saddr, prefixlen, ul_proto)
3469105197Ssam	u_int16_t exttype;
3470105197Ssam	const struct sockaddr *saddr;
3471105197Ssam	u_int8_t prefixlen;
3472105197Ssam	u_int16_t ul_proto;
3473105197Ssam{
3474105197Ssam	struct mbuf *m;
3475105197Ssam	struct sadb_address *p;
3476105197Ssam	size_t len;
3477105197Ssam
3478105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3479105197Ssam	    PFKEY_ALIGN8(saddr->sa_len);
3480105197Ssam	m = key_alloc_mbuf(len);
3481105197Ssam	if (!m || m->m_next) {	/*XXX*/
3482105197Ssam		if (m)
3483105197Ssam			m_freem(m);
3484105197Ssam		return NULL;
3485105197Ssam	}
3486105197Ssam
3487105197Ssam	p = mtod(m, struct sadb_address *);
3488105197Ssam
3489105197Ssam	bzero(p, len);
3490105197Ssam	p->sadb_address_len = PFKEY_UNIT64(len);
3491105197Ssam	p->sadb_address_exttype = exttype;
3492105197Ssam	p->sadb_address_proto = ul_proto;
3493105197Ssam	if (prefixlen == FULLMASK) {
3494105197Ssam		switch (saddr->sa_family) {
3495105197Ssam		case AF_INET:
3496105197Ssam			prefixlen = sizeof(struct in_addr) << 3;
3497105197Ssam			break;
3498105197Ssam		case AF_INET6:
3499105197Ssam			prefixlen = sizeof(struct in6_addr) << 3;
3500105197Ssam			break;
3501105197Ssam		default:
3502105197Ssam			; /*XXX*/
3503105197Ssam		}
3504105197Ssam	}
3505105197Ssam	p->sadb_address_prefixlen = prefixlen;
3506105197Ssam	p->sadb_address_reserved = 0;
3507105197Ssam
3508105197Ssam	bcopy(saddr,
3509105197Ssam	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3510105197Ssam	    saddr->sa_len);
3511105197Ssam
3512105197Ssam	return m;
3513105197Ssam}
3514105197Ssam
3515105197Ssam#if 0
3516105197Ssam/*
3517105197Ssam * set data into sadb_ident.
3518105197Ssam */
3519105197Ssamstatic struct mbuf *
3520105197Ssamkey_setsadbident(exttype, idtype, string, stringlen, id)
3521105197Ssam	u_int16_t exttype, idtype;
3522105197Ssam	caddr_t string;
3523105197Ssam	int stringlen;
3524105197Ssam	u_int64_t id;
3525105197Ssam{
3526105197Ssam	struct mbuf *m;
3527105197Ssam	struct sadb_ident *p;
3528105197Ssam	size_t len;
3529105197Ssam
3530105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
3531105197Ssam	m = key_alloc_mbuf(len);
3532105197Ssam	if (!m || m->m_next) {	/*XXX*/
3533105197Ssam		if (m)
3534105197Ssam			m_freem(m);
3535105197Ssam		return NULL;
3536105197Ssam	}
3537105197Ssam
3538105197Ssam	p = mtod(m, struct sadb_ident *);
3539105197Ssam
3540105197Ssam	bzero(p, len);
3541105197Ssam	p->sadb_ident_len = PFKEY_UNIT64(len);
3542105197Ssam	p->sadb_ident_exttype = exttype;
3543105197Ssam	p->sadb_ident_type = idtype;
3544105197Ssam	p->sadb_ident_reserved = 0;
3545105197Ssam	p->sadb_ident_id = id;
3546105197Ssam
3547105197Ssam	bcopy(string,
3548105197Ssam	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
3549105197Ssam	    stringlen);
3550105197Ssam
3551105197Ssam	return m;
3552105197Ssam}
3553105197Ssam#endif
3554105197Ssam
3555105197Ssam/*
3556105197Ssam * set data into sadb_x_sa2.
3557105197Ssam */
3558105197Ssamstatic struct mbuf *
3559105197Ssamkey_setsadbxsa2(mode, seq, reqid)
3560105197Ssam	u_int8_t mode;
3561105197Ssam	u_int32_t seq, reqid;
3562105197Ssam{
3563105197Ssam	struct mbuf *m;
3564105197Ssam	struct sadb_x_sa2 *p;
3565105197Ssam	size_t len;
3566105197Ssam
3567105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3568105197Ssam	m = key_alloc_mbuf(len);
3569105197Ssam	if (!m || m->m_next) {	/*XXX*/
3570105197Ssam		if (m)
3571105197Ssam			m_freem(m);
3572105197Ssam		return NULL;
3573105197Ssam	}
3574105197Ssam
3575105197Ssam	p = mtod(m, struct sadb_x_sa2 *);
3576105197Ssam
3577105197Ssam	bzero(p, len);
3578105197Ssam	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3579105197Ssam	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3580105197Ssam	p->sadb_x_sa2_mode = mode;
3581105197Ssam	p->sadb_x_sa2_reserved1 = 0;
3582105197Ssam	p->sadb_x_sa2_reserved2 = 0;
3583105197Ssam	p->sadb_x_sa2_sequence = seq;
3584105197Ssam	p->sadb_x_sa2_reqid = reqid;
3585105197Ssam
3586105197Ssam	return m;
3587105197Ssam}
3588105197Ssam
3589105197Ssam/*
3590105197Ssam * set data into sadb_x_policy
3591105197Ssam */
3592105197Ssamstatic struct mbuf *
3593105197Ssamkey_setsadbxpolicy(type, dir, id)
3594105197Ssam	u_int16_t type;
3595105197Ssam	u_int8_t dir;
3596105197Ssam	u_int32_t id;
3597105197Ssam{
3598105197Ssam	struct mbuf *m;
3599105197Ssam	struct sadb_x_policy *p;
3600105197Ssam	size_t len;
3601105197Ssam
3602105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3603105197Ssam	m = key_alloc_mbuf(len);
3604105197Ssam	if (!m || m->m_next) {	/*XXX*/
3605105197Ssam		if (m)
3606105197Ssam			m_freem(m);
3607105197Ssam		return NULL;
3608105197Ssam	}
3609105197Ssam
3610105197Ssam	p = mtod(m, struct sadb_x_policy *);
3611105197Ssam
3612105197Ssam	bzero(p, len);
3613105197Ssam	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3614105197Ssam	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3615105197Ssam	p->sadb_x_policy_type = type;
3616105197Ssam	p->sadb_x_policy_dir = dir;
3617105197Ssam	p->sadb_x_policy_id = id;
3618105197Ssam
3619105197Ssam	return m;
3620105197Ssam}
3621105197Ssam
3622105197Ssam/* %%% utilities */
3623105197Ssam/*
3624105197Ssam * copy a buffer into the new buffer allocated.
3625105197Ssam */
3626105197Ssamstatic void *
3627105197Ssamkey_newbuf(src, len)
3628105197Ssam	const void *src;
3629105197Ssam	u_int len;
3630105197Ssam{
3631105197Ssam	caddr_t new;
3632105197Ssam
3633105197Ssam	KMALLOC(new, caddr_t, len);
3634105197Ssam	if (new == NULL) {
3635105197Ssam		ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
3636105197Ssam		return NULL;
3637105197Ssam	}
3638105197Ssam	bcopy(src, new, len);
3639105197Ssam
3640105197Ssam	return new;
3641105197Ssam}
3642105197Ssam
3643105197Ssam/* compare my own address
3644105197Ssam * OUT:	1: true, i.e. my address.
3645105197Ssam *	0: false
3646105197Ssam */
3647105197Ssamint
3648105197Ssamkey_ismyaddr(sa)
3649105197Ssam	struct sockaddr *sa;
3650105197Ssam{
3651105197Ssam#ifdef INET
3652105197Ssam	struct sockaddr_in *sin;
3653105197Ssam	struct in_ifaddr *ia;
3654105197Ssam#endif
3655105197Ssam
3656105197Ssam	/* sanity check */
3657105197Ssam	if (sa == NULL)
3658105197Ssam		panic("key_ismyaddr: NULL pointer is passed.\n");
3659105197Ssam
3660105197Ssam	switch (sa->sa_family) {
3661105197Ssam#ifdef INET
3662105197Ssam	case AF_INET:
3663105197Ssam		sin = (struct sockaddr_in *)sa;
3664105197Ssam		for (ia = in_ifaddrhead.tqh_first; ia;
3665105197Ssam		     ia = ia->ia_link.tqe_next)
3666105197Ssam		{
3667105197Ssam			if (sin->sin_family == ia->ia_addr.sin_family &&
3668105197Ssam			    sin->sin_len == ia->ia_addr.sin_len &&
3669105197Ssam			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3670105197Ssam			{
3671105197Ssam				return 1;
3672105197Ssam			}
3673105197Ssam		}
3674105197Ssam		break;
3675105197Ssam#endif
3676105197Ssam#ifdef INET6
3677105197Ssam	case AF_INET6:
3678105197Ssam		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3679105197Ssam#endif
3680105197Ssam	}
3681105197Ssam
3682105197Ssam	return 0;
3683105197Ssam}
3684105197Ssam
3685105197Ssam#ifdef INET6
3686105197Ssam/*
3687105197Ssam * compare my own address for IPv6.
3688105197Ssam * 1: ours
3689105197Ssam * 0: other
3690105197Ssam * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3691105197Ssam */
3692105197Ssam#include <netinet6/in6_var.h>
3693105197Ssam
3694105197Ssamstatic int
3695105197Ssamkey_ismyaddr6(sin6)
3696105197Ssam	struct sockaddr_in6 *sin6;
3697105197Ssam{
3698105197Ssam	struct in6_ifaddr *ia;
3699105197Ssam	struct in6_multi *in6m;
3700105197Ssam
3701105197Ssam	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
3702105197Ssam		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3703105197Ssam		    (struct sockaddr *)&ia->ia_addr, 0) == 0)
3704105197Ssam			return 1;
3705105197Ssam
3706105197Ssam		/*
3707105197Ssam		 * XXX Multicast
3708105197Ssam		 * XXX why do we care about multlicast here while we don't care
3709105197Ssam		 * about IPv4 multicast??
3710105197Ssam		 * XXX scope
3711105197Ssam		 */
3712105197Ssam		in6m = NULL;
3713105197Ssam		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3714105197Ssam		if (in6m)
3715105197Ssam			return 1;
3716105197Ssam	}
3717105197Ssam
3718105197Ssam	/* loopback, just for safety */
3719105197Ssam	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3720105197Ssam		return 1;
3721105197Ssam
3722105197Ssam	return 0;
3723105197Ssam}
3724105197Ssam#endif /*INET6*/
3725105197Ssam
3726105197Ssam/*
3727105197Ssam * compare two secasindex structure.
3728105197Ssam * flag can specify to compare 2 saidxes.
3729105197Ssam * compare two secasindex structure without both mode and reqid.
3730105197Ssam * don't compare port.
3731105197Ssam * IN:
3732105197Ssam *      saidx0: source, it can be in SAD.
3733105197Ssam *      saidx1: object.
3734105197Ssam * OUT:
3735105197Ssam *      1 : equal
3736105197Ssam *      0 : not equal
3737105197Ssam */
3738105197Ssamstatic int
3739105197Ssamkey_cmpsaidx(
3740105197Ssam	const struct secasindex *saidx0,
3741105197Ssam	const struct secasindex *saidx1,
3742105197Ssam	int flag)
3743105197Ssam{
3744105197Ssam	/* sanity */
3745105197Ssam	if (saidx0 == NULL && saidx1 == NULL)
3746105197Ssam		return 1;
3747105197Ssam
3748105197Ssam	if (saidx0 == NULL || saidx1 == NULL)
3749105197Ssam		return 0;
3750105197Ssam
3751105197Ssam	if (saidx0->proto != saidx1->proto)
3752105197Ssam		return 0;
3753105197Ssam
3754105197Ssam	if (flag == CMP_EXACTLY) {
3755105197Ssam		if (saidx0->mode != saidx1->mode)
3756105197Ssam			return 0;
3757105197Ssam		if (saidx0->reqid != saidx1->reqid)
3758105197Ssam			return 0;
3759105197Ssam		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3760105197Ssam		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3761105197Ssam			return 0;
3762105197Ssam	} else {
3763105197Ssam
3764105197Ssam		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3765105197Ssam		if (flag == CMP_MODE_REQID
3766105197Ssam		  ||flag == CMP_REQID) {
3767105197Ssam			/*
3768105197Ssam			 * If reqid of SPD is non-zero, unique SA is required.
3769105197Ssam			 * The result must be of same reqid in this case.
3770105197Ssam			 */
3771105197Ssam			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3772105197Ssam				return 0;
3773105197Ssam		}
3774105197Ssam
3775105197Ssam		if (flag == CMP_MODE_REQID) {
3776105197Ssam			if (saidx0->mode != IPSEC_MODE_ANY
3777105197Ssam			 && saidx0->mode != saidx1->mode)
3778105197Ssam				return 0;
3779105197Ssam		}
3780105197Ssam
3781105197Ssam		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
3782105197Ssam			return 0;
3783105197Ssam		}
3784105197Ssam		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
3785105197Ssam			return 0;
3786105197Ssam		}
3787105197Ssam	}
3788105197Ssam
3789105197Ssam	return 1;
3790105197Ssam}
3791105197Ssam
3792105197Ssam/*
3793105197Ssam * compare two secindex structure exactly.
3794105197Ssam * IN:
3795105197Ssam *	spidx0: source, it is often in SPD.
3796105197Ssam *	spidx1: object, it is often from PFKEY message.
3797105197Ssam * OUT:
3798105197Ssam *	1 : equal
3799105197Ssam *	0 : not equal
3800105197Ssam */
3801105197Ssamstatic int
3802105197Ssamkey_cmpspidx_exactly(
3803105197Ssam	struct secpolicyindex *spidx0,
3804105197Ssam	struct secpolicyindex *spidx1)
3805105197Ssam{
3806105197Ssam	/* sanity */
3807105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
3808105197Ssam		return 1;
3809105197Ssam
3810105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
3811105197Ssam		return 0;
3812105197Ssam
3813105197Ssam	if (spidx0->prefs != spidx1->prefs
3814105197Ssam	 || spidx0->prefd != spidx1->prefd
3815105197Ssam	 || spidx0->ul_proto != spidx1->ul_proto)
3816105197Ssam		return 0;
3817105197Ssam
3818105197Ssam	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3819105197Ssam	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3820105197Ssam}
3821105197Ssam
3822105197Ssam/*
3823105197Ssam * compare two secindex structure with mask.
3824105197Ssam * IN:
3825105197Ssam *	spidx0: source, it is often in SPD.
3826105197Ssam *	spidx1: object, it is often from IP header.
3827105197Ssam * OUT:
3828105197Ssam *	1 : equal
3829105197Ssam *	0 : not equal
3830105197Ssam */
3831105197Ssamstatic int
3832105197Ssamkey_cmpspidx_withmask(
3833105197Ssam	struct secpolicyindex *spidx0,
3834105197Ssam	struct secpolicyindex *spidx1)
3835105197Ssam{
3836105197Ssam	/* sanity */
3837105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
3838105197Ssam		return 1;
3839105197Ssam
3840105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
3841105197Ssam		return 0;
3842105197Ssam
3843105197Ssam	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
3844105197Ssam	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
3845105197Ssam	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
3846105197Ssam	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
3847105197Ssam		return 0;
3848105197Ssam
3849105197Ssam	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3850105197Ssam	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3851105197Ssam	 && spidx0->ul_proto != spidx1->ul_proto)
3852105197Ssam		return 0;
3853105197Ssam
3854105197Ssam	switch (spidx0->src.sa.sa_family) {
3855105197Ssam	case AF_INET:
3856105197Ssam		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
3857105197Ssam		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
3858105197Ssam			return 0;
3859105197Ssam		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
3860105197Ssam		    &spidx1->src.sin.sin_addr, spidx0->prefs))
3861105197Ssam			return 0;
3862105197Ssam		break;
3863105197Ssam	case AF_INET6:
3864105197Ssam		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
3865105197Ssam		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
3866105197Ssam			return 0;
3867105197Ssam		/*
3868105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
3869105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
3870105197Ssam		 */
3871105197Ssam		if (spidx0->src.sin6.sin6_scope_id &&
3872105197Ssam		    spidx1->src.sin6.sin6_scope_id &&
3873105197Ssam		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
3874105197Ssam			return 0;
3875105197Ssam		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
3876105197Ssam		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
3877105197Ssam			return 0;
3878105197Ssam		break;
3879105197Ssam	default:
3880105197Ssam		/* XXX */
3881105197Ssam		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
3882105197Ssam			return 0;
3883105197Ssam		break;
3884105197Ssam	}
3885105197Ssam
3886105197Ssam	switch (spidx0->dst.sa.sa_family) {
3887105197Ssam	case AF_INET:
3888105197Ssam		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
3889105197Ssam		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
3890105197Ssam			return 0;
3891105197Ssam		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
3892105197Ssam		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
3893105197Ssam			return 0;
3894105197Ssam		break;
3895105197Ssam	case AF_INET6:
3896105197Ssam		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
3897105197Ssam		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
3898105197Ssam			return 0;
3899105197Ssam		/*
3900105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
3901105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
3902105197Ssam		 */
3903105197Ssam		if (spidx0->src.sin6.sin6_scope_id &&
3904105197Ssam		    spidx1->src.sin6.sin6_scope_id &&
3905105197Ssam		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
3906105197Ssam			return 0;
3907105197Ssam		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
3908105197Ssam		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
3909105197Ssam			return 0;
3910105197Ssam		break;
3911105197Ssam	default:
3912105197Ssam		/* XXX */
3913105197Ssam		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
3914105197Ssam			return 0;
3915105197Ssam		break;
3916105197Ssam	}
3917105197Ssam
3918105197Ssam	/* XXX Do we check other field ?  e.g. flowinfo */
3919105197Ssam
3920105197Ssam	return 1;
3921105197Ssam}
3922105197Ssam
3923105197Ssam/* returns 0 on match */
3924105197Ssamstatic int
3925105197Ssamkey_sockaddrcmp(
3926105197Ssam	const struct sockaddr *sa1,
3927105197Ssam	const struct sockaddr *sa2,
3928105197Ssam	int port)
3929105197Ssam{
3930105197Ssam#ifdef satosin
3931105197Ssam#undef satosin
3932105197Ssam#endif
3933105197Ssam#define satosin(s) ((const struct sockaddr_in *)s)
3934105197Ssam#ifdef satosin6
3935105197Ssam#undef satosin6
3936105197Ssam#endif
3937105197Ssam#define satosin6(s) ((const struct sockaddr_in6 *)s)
3938105197Ssam	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
3939105197Ssam		return 1;
3940105197Ssam
3941105197Ssam	switch (sa1->sa_family) {
3942105197Ssam	case AF_INET:
3943105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in))
3944105197Ssam			return 1;
3945105197Ssam		if (satosin(sa1)->sin_addr.s_addr !=
3946105197Ssam		    satosin(sa2)->sin_addr.s_addr) {
3947105197Ssam			return 1;
3948105197Ssam		}
3949105197Ssam		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
3950105197Ssam			return 1;
3951105197Ssam		break;
3952105197Ssam	case AF_INET6:
3953105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in6))
3954105197Ssam			return 1;	/*EINVAL*/
3955105197Ssam		if (satosin6(sa1)->sin6_scope_id !=
3956105197Ssam		    satosin6(sa2)->sin6_scope_id) {
3957105197Ssam			return 1;
3958105197Ssam		}
3959105197Ssam		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
3960105197Ssam		    &satosin6(sa2)->sin6_addr)) {
3961105197Ssam			return 1;
3962105197Ssam		}
3963105197Ssam		if (port &&
3964105197Ssam		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
3965105197Ssam			return 1;
3966105197Ssam		}
3967105197Ssam	default:
3968105197Ssam		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
3969105197Ssam			return 1;
3970105197Ssam		break;
3971105197Ssam	}
3972105197Ssam
3973105197Ssam	return 0;
3974105197Ssam#undef satosin
3975105197Ssam#undef satosin6
3976105197Ssam}
3977105197Ssam
3978105197Ssam/*
3979105197Ssam * compare two buffers with mask.
3980105197Ssam * IN:
3981105197Ssam *	addr1: source
3982105197Ssam *	addr2: object
3983105197Ssam *	bits:  Number of bits to compare
3984105197Ssam * OUT:
3985105197Ssam *	1 : equal
3986105197Ssam *	0 : not equal
3987105197Ssam */
3988105197Ssamstatic int
3989105197Ssamkey_bbcmp(const void *a1, const void *a2, u_int bits)
3990105197Ssam{
3991105197Ssam	const unsigned char *p1 = a1;
3992105197Ssam	const unsigned char *p2 = a2;
3993105197Ssam
3994105197Ssam	/* XXX: This could be considerably faster if we compare a word
3995105197Ssam	 * at a time, but it is complicated on LSB Endian machines */
3996105197Ssam
3997105197Ssam	/* Handle null pointers */
3998105197Ssam	if (p1 == NULL || p2 == NULL)
3999105197Ssam		return (p1 == p2);
4000105197Ssam
4001105197Ssam	while (bits >= 8) {
4002105197Ssam		if (*p1++ != *p2++)
4003105197Ssam			return 0;
4004105197Ssam		bits -= 8;
4005105197Ssam	}
4006105197Ssam
4007105197Ssam	if (bits > 0) {
4008105197Ssam		u_int8_t mask = ~((1<<(8-bits))-1);
4009105197Ssam		if ((*p1 & mask) != (*p2 & mask))
4010105197Ssam			return 0;
4011105197Ssam	}
4012105197Ssam	return 1;	/* Match! */
4013105197Ssam}
4014105197Ssam
4015105197Ssam/*
4016105197Ssam * time handler.
4017105197Ssam * scanning SPD and SAD to check status for each entries,
4018105197Ssam * and do to remove or to expire.
4019105197Ssam * XXX: year 2038 problem may remain.
4020105197Ssam */
4021105197Ssamvoid
4022105197Ssamkey_timehandler(void)
4023105197Ssam{
4024105197Ssam	u_int dir;
4025105197Ssam	int s;
4026105197Ssam	time_t now = time_second;
4027105197Ssam
4028105197Ssam	s = splnet();	/*called from softclock()*/
4029105197Ssam
4030105197Ssam	/* SPD */
4031105197Ssam    {
4032105197Ssam	struct secpolicy *sp, *nextsp;
4033105197Ssam
4034105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4035105197Ssam		for (sp = LIST_FIRST(&sptree[dir]);
4036105197Ssam		     sp != NULL;
4037105197Ssam		     sp = nextsp) {
4038105197Ssam
4039105197Ssam			nextsp = LIST_NEXT(sp, chain);
4040105197Ssam
4041105197Ssam			if (sp->state == IPSEC_SPSTATE_DEAD) {
4042105197Ssam				KEY_FREESP(&sp);
4043105197Ssam				continue;
4044105197Ssam			}
4045105197Ssam
4046105197Ssam			if (sp->lifetime == 0 && sp->validtime == 0)
4047105197Ssam				continue;
4048105197Ssam
4049105197Ssam			/* the deletion will occur next time */
4050105197Ssam			if ((sp->lifetime && now - sp->created > sp->lifetime)
4051105197Ssam			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4052105197Ssam				sp->state = IPSEC_SPSTATE_DEAD;
4053105197Ssam				key_spdexpire(sp);
4054105197Ssam				continue;
4055105197Ssam			}
4056105197Ssam		}
4057105197Ssam	}
4058105197Ssam    }
4059105197Ssam
4060105197Ssam	/* SAD */
4061105197Ssam    {
4062105197Ssam	struct secashead *sah, *nextsah;
4063105197Ssam	struct secasvar *sav, *nextsav;
4064105197Ssam
4065105197Ssam	for (sah = LIST_FIRST(&sahtree);
4066105197Ssam	     sah != NULL;
4067105197Ssam	     sah = nextsah) {
4068105197Ssam
4069105197Ssam		nextsah = LIST_NEXT(sah, chain);
4070105197Ssam
4071105197Ssam		/* if sah has been dead, then delete it and process next sah. */
4072105197Ssam		if (sah->state == SADB_SASTATE_DEAD) {
4073105197Ssam			key_delsah(sah);
4074105197Ssam			continue;
4075105197Ssam		}
4076105197Ssam
4077105197Ssam		/* if LARVAL entry doesn't become MATURE, delete it. */
4078105197Ssam		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
4079105197Ssam		     sav != NULL;
4080105197Ssam		     sav = nextsav) {
4081105197Ssam
4082105197Ssam			nextsav = LIST_NEXT(sav, chain);
4083105197Ssam
4084105197Ssam			if (now - sav->created > key_larval_lifetime) {
4085105197Ssam				KEY_FREESAV(&sav);
4086105197Ssam			}
4087105197Ssam		}
4088105197Ssam
4089105197Ssam		/*
4090105197Ssam		 * check MATURE entry to start to send expire message
4091105197Ssam		 * whether or not.
4092105197Ssam		 */
4093105197Ssam		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
4094105197Ssam		     sav != NULL;
4095105197Ssam		     sav = nextsav) {
4096105197Ssam
4097105197Ssam			nextsav = LIST_NEXT(sav, chain);
4098105197Ssam
4099105197Ssam			/* we don't need to check. */
4100105197Ssam			if (sav->lft_s == NULL)
4101105197Ssam				continue;
4102105197Ssam
4103105197Ssam			/* sanity check */
4104105197Ssam			if (sav->lft_c == NULL) {
4105105197Ssam				ipseclog((LOG_DEBUG,"key_timehandler: "
4106105197Ssam					"There is no CURRENT time, why?\n"));
4107105197Ssam				continue;
4108105197Ssam			}
4109105197Ssam
4110105197Ssam			/* check SOFT lifetime */
4111105197Ssam			if (sav->lft_s->sadb_lifetime_addtime != 0
4112105197Ssam			 && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4113105197Ssam				/*
4114105197Ssam				 * check SA to be used whether or not.
4115105197Ssam				 * when SA hasn't been used, delete it.
4116105197Ssam				 */
4117105197Ssam				if (sav->lft_c->sadb_lifetime_usetime == 0) {
4118105197Ssam					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4119105197Ssam					KEY_FREESAV(&sav);
4120105197Ssam				} else {
4121105197Ssam					key_sa_chgstate(sav, SADB_SASTATE_DYING);
4122105197Ssam					/*
4123105197Ssam					 * XXX If we keep to send expire
4124105197Ssam					 * message in the status of
4125105197Ssam					 * DYING. Do remove below code.
4126105197Ssam					 */
4127105197Ssam					key_expire(sav);
4128105197Ssam				}
4129105197Ssam			}
4130105197Ssam			/* check SOFT lifetime by bytes */
4131105197Ssam			/*
4132105197Ssam			 * XXX I don't know the way to delete this SA
4133105197Ssam			 * when new SA is installed.  Caution when it's
4134105197Ssam			 * installed too big lifetime by time.
4135105197Ssam			 */
4136105197Ssam			else if (sav->lft_s->sadb_lifetime_bytes != 0
4137105197Ssam			      && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4138105197Ssam
4139105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4140105197Ssam				/*
4141105197Ssam				 * XXX If we keep to send expire
4142105197Ssam				 * message in the status of
4143105197Ssam				 * DYING. Do remove below code.
4144105197Ssam				 */
4145105197Ssam				key_expire(sav);
4146105197Ssam			}
4147105197Ssam		}
4148105197Ssam
4149105197Ssam		/* check DYING entry to change status to DEAD. */
4150105197Ssam		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
4151105197Ssam		     sav != NULL;
4152105197Ssam		     sav = nextsav) {
4153105197Ssam
4154105197Ssam			nextsav = LIST_NEXT(sav, chain);
4155105197Ssam
4156105197Ssam			/* we don't need to check. */
4157105197Ssam			if (sav->lft_h == NULL)
4158105197Ssam				continue;
4159105197Ssam
4160105197Ssam			/* sanity check */
4161105197Ssam			if (sav->lft_c == NULL) {
4162105197Ssam				ipseclog((LOG_DEBUG, "key_timehandler: "
4163105197Ssam					"There is no CURRENT time, why?\n"));
4164105197Ssam				continue;
4165105197Ssam			}
4166105197Ssam
4167105197Ssam			if (sav->lft_h->sadb_lifetime_addtime != 0
4168105197Ssam			 && now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
4169105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4170105197Ssam				KEY_FREESAV(&sav);
4171105197Ssam			}
4172105197Ssam#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4173105197Ssam			else if (sav->lft_s != NULL
4174105197Ssam			      && sav->lft_s->sadb_lifetime_addtime != 0
4175105197Ssam			      && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4176105197Ssam				/*
4177105197Ssam				 * XXX: should be checked to be
4178105197Ssam				 * installed the valid SA.
4179105197Ssam				 */
4180105197Ssam
4181105197Ssam				/*
4182105197Ssam				 * If there is no SA then sending
4183105197Ssam				 * expire message.
4184105197Ssam				 */
4185105197Ssam				key_expire(sav);
4186105197Ssam			}
4187105197Ssam#endif
4188105197Ssam			/* check HARD lifetime by bytes */
4189105197Ssam			else if (sav->lft_h->sadb_lifetime_bytes != 0
4190105197Ssam			      && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4191105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4192105197Ssam				KEY_FREESAV(&sav);
4193105197Ssam			}
4194105197Ssam		}
4195105197Ssam
4196105197Ssam		/* delete entry in DEAD */
4197105197Ssam		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
4198105197Ssam		     sav != NULL;
4199105197Ssam		     sav = nextsav) {
4200105197Ssam
4201105197Ssam			nextsav = LIST_NEXT(sav, chain);
4202105197Ssam
4203105197Ssam			/* sanity check */
4204105197Ssam			if (sav->state != SADB_SASTATE_DEAD) {
4205105197Ssam				ipseclog((LOG_DEBUG, "key_timehandler: "
4206105197Ssam					"invalid sav->state "
4207105197Ssam					"(queue: %d SA: %d): "
4208105197Ssam					"kill it anyway\n",
4209105197Ssam					SADB_SASTATE_DEAD, sav->state));
4210105197Ssam			}
4211105197Ssam
4212105197Ssam			/*
4213105197Ssam			 * do not call key_freesav() here.
4214105197Ssam			 * sav should already be freed, and sav->refcnt
4215105197Ssam			 * shows other references to sav
4216105197Ssam			 * (such as from SPD).
4217105197Ssam			 */
4218105197Ssam		}
4219105197Ssam	}
4220105197Ssam    }
4221105197Ssam
4222105197Ssam#ifndef IPSEC_NONBLOCK_ACQUIRE
4223105197Ssam	/* ACQ tree */
4224105197Ssam    {
4225105197Ssam	struct secacq *acq, *nextacq;
4226105197Ssam
4227105197Ssam	for (acq = LIST_FIRST(&acqtree);
4228105197Ssam	     acq != NULL;
4229105197Ssam	     acq = nextacq) {
4230105197Ssam
4231105197Ssam		nextacq = LIST_NEXT(acq, chain);
4232105197Ssam
4233105197Ssam		if (now - acq->created > key_blockacq_lifetime
4234105197Ssam		 && __LIST_CHAINED(acq)) {
4235105197Ssam			LIST_REMOVE(acq, chain);
4236105197Ssam			KFREE(acq);
4237105197Ssam		}
4238105197Ssam	}
4239105197Ssam    }
4240105197Ssam#endif
4241105197Ssam
4242105197Ssam	/* SP ACQ tree */
4243105197Ssam    {
4244105197Ssam	struct secspacq *acq, *nextacq;
4245105197Ssam
4246105197Ssam	for (acq = LIST_FIRST(&spacqtree);
4247105197Ssam	     acq != NULL;
4248105197Ssam	     acq = nextacq) {
4249105197Ssam
4250105197Ssam		nextacq = LIST_NEXT(acq, chain);
4251105197Ssam
4252105197Ssam		if (now - acq->created > key_blockacq_lifetime
4253105197Ssam		 && __LIST_CHAINED(acq)) {
4254105197Ssam			LIST_REMOVE(acq, chain);
4255105197Ssam			KFREE(acq);
4256105197Ssam		}
4257105197Ssam	}
4258105197Ssam    }
4259105197Ssam
4260105197Ssam	/* initialize random seed */
4261105197Ssam	if (key_tick_init_random++ > key_int_random) {
4262105197Ssam		key_tick_init_random = 0;
4263105197Ssam		key_srandom();
4264105197Ssam	}
4265105197Ssam
4266105197Ssam#ifndef IPSEC_DEBUG2
4267105197Ssam	/* do exchange to tick time !! */
4268105197Ssam	(void)timeout((void *)key_timehandler, (void *)0, hz);
4269105197Ssam#endif /* IPSEC_DEBUG2 */
4270105197Ssam
4271105197Ssam	splx(s);
4272105197Ssam	return;
4273105197Ssam}
4274105197Ssam
4275105197Ssam/*
4276105197Ssam * to initialize a seed for random()
4277105197Ssam */
4278105197Ssamstatic void
4279105197Ssamkey_srandom()
4280105197Ssam{
4281110403Sache#if 0   /* Already called in kern/init_main.c:proc0_post() */
4282105197Ssam	srandom(time_second);
4283110403Sache#endif
4284105197Ssam}
4285105197Ssam
4286105197Ssamu_long
4287105197Ssamkey_random()
4288105197Ssam{
4289105197Ssam	u_long value;
4290105197Ssam
4291105197Ssam	key_randomfill(&value, sizeof(value));
4292105197Ssam	return value;
4293105197Ssam}
4294105197Ssam
4295105197Ssamvoid
4296105197Ssamkey_randomfill(p, l)
4297105197Ssam	void *p;
4298105197Ssam	size_t l;
4299105197Ssam{
4300105197Ssam	size_t n;
4301105197Ssam	u_long v;
4302105197Ssam	static int warn = 1;
4303105197Ssam
4304105197Ssam	n = 0;
4305105197Ssam	n = (size_t)read_random(p, (u_int)l);
4306105197Ssam	/* last resort */
4307105197Ssam	while (n < l) {
4308105197Ssam		v = random();
4309105197Ssam		bcopy(&v, (u_int8_t *)p + n,
4310105197Ssam		    l - n < sizeof(v) ? l - n : sizeof(v));
4311105197Ssam		n += sizeof(v);
4312105197Ssam
4313105197Ssam		if (warn) {
4314105197Ssam			printf("WARNING: pseudo-random number generator "
4315105197Ssam			    "used for IPsec processing\n");
4316105197Ssam			warn = 0;
4317105197Ssam		}
4318105197Ssam	}
4319105197Ssam}
4320105197Ssam
4321105197Ssam/*
4322105197Ssam * map SADB_SATYPE_* to IPPROTO_*.
4323105197Ssam * if satype == SADB_SATYPE then satype is mapped to ~0.
4324105197Ssam * OUT:
4325105197Ssam *	0: invalid satype.
4326105197Ssam */
4327105197Ssamstatic u_int16_t
4328105197Ssamkey_satype2proto(satype)
4329105197Ssam	u_int8_t satype;
4330105197Ssam{
4331105197Ssam	switch (satype) {
4332105197Ssam	case SADB_SATYPE_UNSPEC:
4333105197Ssam		return IPSEC_PROTO_ANY;
4334105197Ssam	case SADB_SATYPE_AH:
4335105197Ssam		return IPPROTO_AH;
4336105197Ssam	case SADB_SATYPE_ESP:
4337105197Ssam		return IPPROTO_ESP;
4338105197Ssam	case SADB_X_SATYPE_IPCOMP:
4339105197Ssam		return IPPROTO_IPCOMP;
4340105197Ssam	default:
4341105197Ssam		return 0;
4342105197Ssam	}
4343105197Ssam	/* NOTREACHED */
4344105197Ssam}
4345105197Ssam
4346105197Ssam/*
4347105197Ssam * map IPPROTO_* to SADB_SATYPE_*
4348105197Ssam * OUT:
4349105197Ssam *	0: invalid protocol type.
4350105197Ssam */
4351105197Ssamstatic u_int8_t
4352105197Ssamkey_proto2satype(proto)
4353105197Ssam	u_int16_t proto;
4354105197Ssam{
4355105197Ssam	switch (proto) {
4356105197Ssam	case IPPROTO_AH:
4357105197Ssam		return SADB_SATYPE_AH;
4358105197Ssam	case IPPROTO_ESP:
4359105197Ssam		return SADB_SATYPE_ESP;
4360105197Ssam	case IPPROTO_IPCOMP:
4361105197Ssam		return SADB_X_SATYPE_IPCOMP;
4362105197Ssam	default:
4363105197Ssam		return 0;
4364105197Ssam	}
4365105197Ssam	/* NOTREACHED */
4366105197Ssam}
4367105197Ssam
4368105197Ssam/* %%% PF_KEY */
4369105197Ssam/*
4370105197Ssam * SADB_GETSPI processing is to receive
4371105197Ssam *	<base, (SA2), src address, dst address, (SPI range)>
4372105197Ssam * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4373105197Ssam * tree with the status of LARVAL, and send
4374105197Ssam *	<base, SA(*), address(SD)>
4375105197Ssam * to the IKMPd.
4376105197Ssam *
4377105197Ssam * IN:	mhp: pointer to the pointer to each header.
4378105197Ssam * OUT:	NULL if fail.
4379105197Ssam *	other if success, return pointer to the message to send.
4380105197Ssam */
4381105197Ssamstatic int
4382105197Ssamkey_getspi(so, m, mhp)
4383105197Ssam	struct socket *so;
4384105197Ssam	struct mbuf *m;
4385105197Ssam	const struct sadb_msghdr *mhp;
4386105197Ssam{
4387105197Ssam	struct sadb_address *src0, *dst0;
4388105197Ssam	struct secasindex saidx;
4389105197Ssam	struct secashead *newsah;
4390105197Ssam	struct secasvar *newsav;
4391105197Ssam	u_int8_t proto;
4392105197Ssam	u_int32_t spi;
4393105197Ssam	u_int8_t mode;
4394105197Ssam	u_int32_t reqid;
4395105197Ssam	int error;
4396105197Ssam
4397105197Ssam	/* sanity check */
4398105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4399105197Ssam		panic("key_getspi: NULL pointer is passed.\n");
4400105197Ssam
4401105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4402105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4403105197Ssam		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4404105197Ssam		return key_senderror(so, m, EINVAL);
4405105197Ssam	}
4406105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4407105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4408105197Ssam		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4409105197Ssam		return key_senderror(so, m, EINVAL);
4410105197Ssam	}
4411105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4412105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4413105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4414105197Ssam	} else {
4415105197Ssam		mode = IPSEC_MODE_ANY;
4416105197Ssam		reqid = 0;
4417105197Ssam	}
4418105197Ssam
4419105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4420105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4421105197Ssam
4422105197Ssam	/* map satype to proto */
4423105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4424105197Ssam		ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
4425105197Ssam		return key_senderror(so, m, EINVAL);
4426105197Ssam	}
4427105197Ssam
4428105197Ssam	/* make sure if port number is zero. */
4429105197Ssam	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4430105197Ssam	case AF_INET:
4431105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4432105197Ssam		    sizeof(struct sockaddr_in))
4433105197Ssam			return key_senderror(so, m, EINVAL);
4434105197Ssam		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4435105197Ssam		break;
4436105197Ssam	case AF_INET6:
4437105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4438105197Ssam		    sizeof(struct sockaddr_in6))
4439105197Ssam			return key_senderror(so, m, EINVAL);
4440105197Ssam		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4441105197Ssam		break;
4442105197Ssam	default:
4443105197Ssam		; /*???*/
4444105197Ssam	}
4445105197Ssam	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4446105197Ssam	case AF_INET:
4447105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4448105197Ssam		    sizeof(struct sockaddr_in))
4449105197Ssam			return key_senderror(so, m, EINVAL);
4450105197Ssam		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4451105197Ssam		break;
4452105197Ssam	case AF_INET6:
4453105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4454105197Ssam		    sizeof(struct sockaddr_in6))
4455105197Ssam			return key_senderror(so, m, EINVAL);
4456105197Ssam		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4457105197Ssam		break;
4458105197Ssam	default:
4459105197Ssam		; /*???*/
4460105197Ssam	}
4461105197Ssam
4462105197Ssam	/* XXX boundary check against sa_len */
4463105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4464105197Ssam
4465105197Ssam	/* SPI allocation */
4466105197Ssam	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4467105197Ssam	                       &saidx);
4468105197Ssam	if (spi == 0)
4469105197Ssam		return key_senderror(so, m, EINVAL);
4470105197Ssam
4471105197Ssam	/* get a SA index */
4472105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4473105197Ssam		/* create a new SA index */
4474105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4475105197Ssam			ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
4476105197Ssam			return key_senderror(so, m, ENOBUFS);
4477105197Ssam		}
4478105197Ssam	}
4479105197Ssam
4480105197Ssam	/* get a new SA */
4481105197Ssam	/* XXX rewrite */
4482105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4483105197Ssam	if (newsav == NULL) {
4484105197Ssam		/* XXX don't free new SA index allocated in above. */
4485105197Ssam		return key_senderror(so, m, error);
4486105197Ssam	}
4487105197Ssam
4488105197Ssam	/* set spi */
4489105197Ssam	newsav->spi = htonl(spi);
4490105197Ssam
4491105197Ssam#ifndef IPSEC_NONBLOCK_ACQUIRE
4492105197Ssam	/* delete the entry in acqtree */
4493105197Ssam	if (mhp->msg->sadb_msg_seq != 0) {
4494105197Ssam		struct secacq *acq;
4495105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4496105197Ssam			/* reset counter in order to deletion by timehandler. */
4497105197Ssam			acq->created = time_second;
4498105197Ssam			acq->count = 0;
4499105197Ssam		}
4500105197Ssam    	}
4501105197Ssam#endif
4502105197Ssam
4503105197Ssam    {
4504105197Ssam	struct mbuf *n, *nn;
4505105197Ssam	struct sadb_sa *m_sa;
4506105197Ssam	struct sadb_msg *newmsg;
4507105197Ssam	int off, len;
4508105197Ssam
4509105197Ssam	/* create new sadb_msg to reply. */
4510105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4511105197Ssam	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4512105197Ssam	if (len > MCLBYTES)
4513105197Ssam		return key_senderror(so, m, ENOBUFS);
4514105197Ssam
4515111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
4516105197Ssam	if (len > MHLEN) {
4517111119Simp		MCLGET(n, M_DONTWAIT);
4518105197Ssam		if ((n->m_flags & M_EXT) == 0) {
4519105197Ssam			m_freem(n);
4520105197Ssam			n = NULL;
4521105197Ssam		}
4522105197Ssam	}
4523105197Ssam	if (!n)
4524105197Ssam		return key_senderror(so, m, ENOBUFS);
4525105197Ssam
4526105197Ssam	n->m_len = len;
4527105197Ssam	n->m_next = NULL;
4528105197Ssam	off = 0;
4529105197Ssam
4530105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4531105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4532105197Ssam
4533105197Ssam	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4534105197Ssam	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4535105197Ssam	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4536105197Ssam	m_sa->sadb_sa_spi = htonl(spi);
4537105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4538105197Ssam
4539105197Ssam#ifdef DIAGNOSTIC
4540105197Ssam	if (off != len)
4541105197Ssam		panic("length inconsistency in key_getspi");
4542105197Ssam#endif
4543105197Ssam
4544105197Ssam	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4545105197Ssam	    SADB_EXT_ADDRESS_DST);
4546105197Ssam	if (!n->m_next) {
4547105197Ssam		m_freem(n);
4548105197Ssam		return key_senderror(so, m, ENOBUFS);
4549105197Ssam	}
4550105197Ssam
4551105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
4552105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
4553105197Ssam		if (n == NULL)
4554105197Ssam			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4555105197Ssam	}
4556105197Ssam
4557105197Ssam	n->m_pkthdr.len = 0;
4558105197Ssam	for (nn = n; nn; nn = nn->m_next)
4559105197Ssam		n->m_pkthdr.len += nn->m_len;
4560105197Ssam
4561105197Ssam	newmsg = mtod(n, struct sadb_msg *);
4562105197Ssam	newmsg->sadb_msg_seq = newsav->seq;
4563105197Ssam	newmsg->sadb_msg_errno = 0;
4564105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4565105197Ssam
4566105197Ssam	m_freem(m);
4567105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4568105197Ssam    }
4569105197Ssam}
4570105197Ssam
4571105197Ssam/*
4572105197Ssam * allocating new SPI
4573105197Ssam * called by key_getspi().
4574105197Ssam * OUT:
4575105197Ssam *	0:	failure.
4576105197Ssam *	others: success.
4577105197Ssam */
4578105197Ssamstatic u_int32_t
4579105197Ssamkey_do_getnewspi(spirange, saidx)
4580105197Ssam	struct sadb_spirange *spirange;
4581105197Ssam	struct secasindex *saidx;
4582105197Ssam{
4583105197Ssam	u_int32_t newspi;
4584105197Ssam	u_int32_t min, max;
4585105197Ssam	int count = key_spi_trycnt;
4586105197Ssam
4587105197Ssam	/* set spi range to allocate */
4588105197Ssam	if (spirange != NULL) {
4589105197Ssam		min = spirange->sadb_spirange_min;
4590105197Ssam		max = spirange->sadb_spirange_max;
4591105197Ssam	} else {
4592105197Ssam		min = key_spi_minval;
4593105197Ssam		max = key_spi_maxval;
4594105197Ssam	}
4595105197Ssam	/* IPCOMP needs 2-byte SPI */
4596105197Ssam	if (saidx->proto == IPPROTO_IPCOMP) {
4597105197Ssam		u_int32_t t;
4598105197Ssam		if (min >= 0x10000)
4599105197Ssam			min = 0xffff;
4600105197Ssam		if (max >= 0x10000)
4601105197Ssam			max = 0xffff;
4602105197Ssam		if (min > max) {
4603105197Ssam			t = min; min = max; max = t;
4604105197Ssam		}
4605105197Ssam	}
4606105197Ssam
4607105197Ssam	if (min == max) {
4608105197Ssam		if (key_checkspidup(saidx, min) != NULL) {
4609105197Ssam			ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", min));
4610105197Ssam			return 0;
4611105197Ssam		}
4612105197Ssam
4613105197Ssam		count--; /* taking one cost. */
4614105197Ssam		newspi = min;
4615105197Ssam
4616105197Ssam	} else {
4617105197Ssam
4618105197Ssam		/* init SPI */
4619105197Ssam		newspi = 0;
4620105197Ssam
4621105197Ssam		/* when requesting to allocate spi ranged */
4622105197Ssam		while (count--) {
4623105197Ssam			/* generate pseudo-random SPI value ranged. */
4624105197Ssam			newspi = min + (key_random() % (max - min + 1));
4625105197Ssam
4626105197Ssam			if (key_checkspidup(saidx, newspi) == NULL)
4627105197Ssam				break;
4628105197Ssam		}
4629105197Ssam
4630105197Ssam		if (count == 0 || newspi == 0) {
4631105197Ssam			ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
4632105197Ssam			return 0;
4633105197Ssam		}
4634105197Ssam	}
4635105197Ssam
4636105197Ssam	/* statistics */
4637105197Ssam	keystat.getspi_count =
4638105197Ssam		(keystat.getspi_count + key_spi_trycnt - count) / 2;
4639105197Ssam
4640105197Ssam	return newspi;
4641105197Ssam}
4642105197Ssam
4643105197Ssam/*
4644105197Ssam * SADB_UPDATE processing
4645105197Ssam * receive
4646105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4647105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4648105197Ssam * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4649105197Ssam * and send
4650105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4651105197Ssam *       (identity(SD),) (sensitivity)>
4652105197Ssam * to the ikmpd.
4653105197Ssam *
4654105197Ssam * m will always be freed.
4655105197Ssam */
4656105197Ssamstatic int
4657105197Ssamkey_update(so, m, mhp)
4658105197Ssam	struct socket *so;
4659105197Ssam	struct mbuf *m;
4660105197Ssam	const struct sadb_msghdr *mhp;
4661105197Ssam{
4662105197Ssam	struct sadb_sa *sa0;
4663105197Ssam	struct sadb_address *src0, *dst0;
4664105197Ssam	struct secasindex saidx;
4665105197Ssam	struct secashead *sah;
4666105197Ssam	struct secasvar *sav;
4667105197Ssam	u_int16_t proto;
4668105197Ssam	u_int8_t mode;
4669105197Ssam	u_int32_t reqid;
4670105197Ssam	int error;
4671105197Ssam
4672105197Ssam	/* sanity check */
4673105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4674105197Ssam		panic("key_update: NULL pointer is passed.\n");
4675105197Ssam
4676105197Ssam	/* map satype to proto */
4677105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4678105197Ssam		ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
4679105197Ssam		return key_senderror(so, m, EINVAL);
4680105197Ssam	}
4681105197Ssam
4682105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
4683105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4684105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4685105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4686105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4687105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4688105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4689105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4690105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4691105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4692105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4693105197Ssam		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4694105197Ssam		return key_senderror(so, m, EINVAL);
4695105197Ssam	}
4696105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4697105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4698105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4699105197Ssam		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4700105197Ssam		return key_senderror(so, m, EINVAL);
4701105197Ssam	}
4702105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4703105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4704105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4705105197Ssam	} else {
4706105197Ssam		mode = IPSEC_MODE_ANY;
4707105197Ssam		reqid = 0;
4708105197Ssam	}
4709105197Ssam	/* XXX boundary checking for other extensions */
4710105197Ssam
4711105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4712105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4713105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4714105197Ssam
4715105197Ssam	/* XXX boundary check against sa_len */
4716105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4717105197Ssam
4718105197Ssam	/* get a SA header */
4719105197Ssam	if ((sah = key_getsah(&saidx)) == NULL) {
4720105197Ssam		ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
4721105197Ssam		return key_senderror(so, m, ENOENT);
4722105197Ssam	}
4723105197Ssam
4724105197Ssam	/* set spidx if there */
4725105197Ssam	/* XXX rewrite */
4726105197Ssam	error = key_setident(sah, m, mhp);
4727105197Ssam	if (error)
4728105197Ssam		return key_senderror(so, m, error);
4729105197Ssam
4730105197Ssam	/* find a SA with sequence number. */
4731105197Ssam#ifdef IPSEC_DOSEQCHECK
4732105197Ssam	if (mhp->msg->sadb_msg_seq != 0
4733105197Ssam	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4734105197Ssam		ipseclog((LOG_DEBUG,
4735105197Ssam		    "key_update: no larval SA with sequence %u exists.\n",
4736105197Ssam		    mhp->msg->sadb_msg_seq));
4737105197Ssam		return key_senderror(so, m, ENOENT);
4738105197Ssam	}
4739105197Ssam#else
4740105197Ssam	if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
4741105197Ssam		ipseclog((LOG_DEBUG,
4742105197Ssam		    "key_update: no such a SA found (spi:%u)\n",
4743105197Ssam		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4744105197Ssam		return key_senderror(so, m, EINVAL);
4745105197Ssam	}
4746105197Ssam#endif
4747105197Ssam
4748105197Ssam	/* validity check */
4749105197Ssam	if (sav->sah->saidx.proto != proto) {
4750105197Ssam		ipseclog((LOG_DEBUG,
4751105197Ssam		    "key_update: protocol mismatched (DB=%u param=%u)\n",
4752105197Ssam		    sav->sah->saidx.proto, proto));
4753105197Ssam		return key_senderror(so, m, EINVAL);
4754105197Ssam	}
4755105197Ssam#ifdef IPSEC_DOSEQCHECK
4756105197Ssam	if (sav->spi != sa0->sadb_sa_spi) {
4757105197Ssam		ipseclog((LOG_DEBUG,
4758105197Ssam		    "key_update: SPI mismatched (DB:%u param:%u)\n",
4759105197Ssam		    (u_int32_t)ntohl(sav->spi),
4760105197Ssam		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4761105197Ssam		return key_senderror(so, m, EINVAL);
4762105197Ssam	}
4763105197Ssam#endif
4764105197Ssam	if (sav->pid != mhp->msg->sadb_msg_pid) {
4765105197Ssam		ipseclog((LOG_DEBUG,
4766105197Ssam		    "key_update: pid mismatched (DB:%u param:%u)\n",
4767105197Ssam		    sav->pid, mhp->msg->sadb_msg_pid));
4768105197Ssam		return key_senderror(so, m, EINVAL);
4769105197Ssam	}
4770105197Ssam
4771105197Ssam	/* copy sav values */
4772105197Ssam	error = key_setsaval(sav, m, mhp);
4773105197Ssam	if (error) {
4774105197Ssam		KEY_FREESAV(&sav);
4775105197Ssam		return key_senderror(so, m, error);
4776105197Ssam	}
4777105197Ssam
4778105197Ssam	/* check SA values to be mature. */
4779105197Ssam	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4780105197Ssam		KEY_FREESAV(&sav);
4781105197Ssam		return key_senderror(so, m, 0);
4782105197Ssam	}
4783105197Ssam
4784105197Ssam    {
4785105197Ssam	struct mbuf *n;
4786105197Ssam
4787105197Ssam	/* set msg buf from mhp */
4788105197Ssam	n = key_getmsgbuf_x1(m, mhp);
4789105197Ssam	if (n == NULL) {
4790105197Ssam		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
4791105197Ssam		return key_senderror(so, m, ENOBUFS);
4792105197Ssam	}
4793105197Ssam
4794105197Ssam	m_freem(m);
4795105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4796105197Ssam    }
4797105197Ssam}
4798105197Ssam
4799105197Ssam/*
4800105197Ssam * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4801105197Ssam * only called by key_update().
4802105197Ssam * OUT:
4803105197Ssam *	NULL	: not found
4804105197Ssam *	others	: found, pointer to a SA.
4805105197Ssam */
4806105197Ssam#ifdef IPSEC_DOSEQCHECK
4807105197Ssamstatic struct secasvar *
4808105197Ssamkey_getsavbyseq(sah, seq)
4809105197Ssam	struct secashead *sah;
4810105197Ssam	u_int32_t seq;
4811105197Ssam{
4812105197Ssam	struct secasvar *sav;
4813105197Ssam	u_int state;
4814105197Ssam
4815105197Ssam	state = SADB_SASTATE_LARVAL;
4816105197Ssam
4817105197Ssam	/* search SAD with sequence number ? */
4818105197Ssam	LIST_FOREACH(sav, &sah->savtree[state], chain) {
4819105197Ssam
4820105197Ssam		KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
4821105197Ssam
4822105197Ssam		if (sav->seq == seq) {
4823105197Ssam			SA_ADDREF(sav);
4824105197Ssam			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4825105197Ssam				printf("DP key_getsavbyseq cause "
4826105197Ssam					"refcnt++:%d SA:%p\n",
4827105197Ssam					sav->refcnt, sav));
4828105197Ssam			return sav;
4829105197Ssam		}
4830105197Ssam	}
4831105197Ssam
4832105197Ssam	return NULL;
4833105197Ssam}
4834105197Ssam#endif
4835105197Ssam
4836105197Ssam/*
4837105197Ssam * SADB_ADD processing
4838108533Sschweikh * add an entry to SA database, when received
4839105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4840105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4841105197Ssam * from the ikmpd,
4842105197Ssam * and send
4843105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4844105197Ssam *       (identity(SD),) (sensitivity)>
4845105197Ssam * to the ikmpd.
4846105197Ssam *
4847105197Ssam * IGNORE identity and sensitivity messages.
4848105197Ssam *
4849105197Ssam * m will always be freed.
4850105197Ssam */
4851105197Ssamstatic int
4852105197Ssamkey_add(so, m, mhp)
4853105197Ssam	struct socket *so;
4854105197Ssam	struct mbuf *m;
4855105197Ssam	const struct sadb_msghdr *mhp;
4856105197Ssam{
4857105197Ssam	struct sadb_sa *sa0;
4858105197Ssam	struct sadb_address *src0, *dst0;
4859105197Ssam	struct secasindex saidx;
4860105197Ssam	struct secashead *newsah;
4861105197Ssam	struct secasvar *newsav;
4862105197Ssam	u_int16_t proto;
4863105197Ssam	u_int8_t mode;
4864105197Ssam	u_int32_t reqid;
4865105197Ssam	int error;
4866105197Ssam
4867105197Ssam	/* sanity check */
4868105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4869105197Ssam		panic("key_add: NULL pointer is passed.\n");
4870105197Ssam
4871105197Ssam	/* map satype to proto */
4872105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4873105197Ssam		ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
4874105197Ssam		return key_senderror(so, m, EINVAL);
4875105197Ssam	}
4876105197Ssam
4877105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
4878105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4879105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4880105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4881105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4882105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4883105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4884105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4885105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4886105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4887105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4888105197Ssam		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
4889105197Ssam		return key_senderror(so, m, EINVAL);
4890105197Ssam	}
4891105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4892105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4893105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4894105197Ssam		/* XXX need more */
4895105197Ssam		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
4896105197Ssam		return key_senderror(so, m, EINVAL);
4897105197Ssam	}
4898105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4899105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4900105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4901105197Ssam	} else {
4902105197Ssam		mode = IPSEC_MODE_ANY;
4903105197Ssam		reqid = 0;
4904105197Ssam	}
4905105197Ssam
4906105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4907105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4908105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4909105197Ssam
4910105197Ssam	/* XXX boundary check against sa_len */
4911105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4912105197Ssam
4913105197Ssam	/* get a SA header */
4914105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4915105197Ssam		/* create a new SA header */
4916105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4917105197Ssam			ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
4918105197Ssam			return key_senderror(so, m, ENOBUFS);
4919105197Ssam		}
4920105197Ssam	}
4921105197Ssam
4922105197Ssam	/* set spidx if there */
4923105197Ssam	/* XXX rewrite */
4924105197Ssam	error = key_setident(newsah, m, mhp);
4925105197Ssam	if (error) {
4926105197Ssam		return key_senderror(so, m, error);
4927105197Ssam	}
4928105197Ssam
4929105197Ssam	/* create new SA entry. */
4930105197Ssam	/* We can create new SA only if SPI is differenct. */
4931105197Ssam	if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
4932105197Ssam		ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
4933105197Ssam		return key_senderror(so, m, EEXIST);
4934105197Ssam	}
4935105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4936105197Ssam	if (newsav == NULL) {
4937105197Ssam		return key_senderror(so, m, error);
4938105197Ssam	}
4939105197Ssam
4940105197Ssam	/* check SA values to be mature. */
4941105197Ssam	if ((error = key_mature(newsav)) != 0) {
4942105197Ssam		KEY_FREESAV(&newsav);
4943105197Ssam		return key_senderror(so, m, error);
4944105197Ssam	}
4945105197Ssam
4946105197Ssam	/*
4947105197Ssam	 * don't call key_freesav() here, as we would like to keep the SA
4948105197Ssam	 * in the database on success.
4949105197Ssam	 */
4950105197Ssam
4951105197Ssam    {
4952105197Ssam	struct mbuf *n;
4953105197Ssam
4954105197Ssam	/* set msg buf from mhp */
4955105197Ssam	n = key_getmsgbuf_x1(m, mhp);
4956105197Ssam	if (n == NULL) {
4957105197Ssam		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
4958105197Ssam		return key_senderror(so, m, ENOBUFS);
4959105197Ssam	}
4960105197Ssam
4961105197Ssam	m_freem(m);
4962105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4963105197Ssam    }
4964105197Ssam}
4965105197Ssam
4966105197Ssam/* m is retained */
4967105197Ssamstatic int
4968105197Ssamkey_setident(sah, m, mhp)
4969105197Ssam	struct secashead *sah;
4970105197Ssam	struct mbuf *m;
4971105197Ssam	const struct sadb_msghdr *mhp;
4972105197Ssam{
4973105197Ssam	const struct sadb_ident *idsrc, *iddst;
4974105197Ssam	int idsrclen, iddstlen;
4975105197Ssam
4976105197Ssam	/* sanity check */
4977105197Ssam	if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4978105197Ssam		panic("key_setident: NULL pointer is passed.\n");
4979105197Ssam
4980105197Ssam	/* don't make buffer if not there */
4981105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
4982105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4983105197Ssam		sah->idents = NULL;
4984105197Ssam		sah->identd = NULL;
4985105197Ssam		return 0;
4986105197Ssam	}
4987105197Ssam
4988105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
4989105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4990105197Ssam		ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
4991105197Ssam		return EINVAL;
4992105197Ssam	}
4993105197Ssam
4994105197Ssam	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
4995105197Ssam	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
4996105197Ssam	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
4997105197Ssam	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
4998105197Ssam
4999105197Ssam	/* validity check */
5000105197Ssam	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5001105197Ssam		ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
5002105197Ssam		return EINVAL;
5003105197Ssam	}
5004105197Ssam
5005105197Ssam	switch (idsrc->sadb_ident_type) {
5006105197Ssam	case SADB_IDENTTYPE_PREFIX:
5007105197Ssam	case SADB_IDENTTYPE_FQDN:
5008105197Ssam	case SADB_IDENTTYPE_USERFQDN:
5009105197Ssam	default:
5010105197Ssam		/* XXX do nothing */
5011105197Ssam		sah->idents = NULL;
5012105197Ssam		sah->identd = NULL;
5013105197Ssam	 	return 0;
5014105197Ssam	}
5015105197Ssam
5016105197Ssam	/* make structure */
5017105197Ssam	KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
5018105197Ssam	if (sah->idents == NULL) {
5019105197Ssam		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5020105197Ssam		return ENOBUFS;
5021105197Ssam	}
5022105197Ssam	KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
5023105197Ssam	if (sah->identd == NULL) {
5024105197Ssam		KFREE(sah->idents);
5025105197Ssam		sah->idents = NULL;
5026105197Ssam		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5027105197Ssam		return ENOBUFS;
5028105197Ssam	}
5029105197Ssam	bcopy(idsrc, sah->idents, idsrclen);
5030105197Ssam	bcopy(iddst, sah->identd, iddstlen);
5031105197Ssam
5032105197Ssam	return 0;
5033105197Ssam}
5034105197Ssam
5035105197Ssam/*
5036105197Ssam * m will not be freed on return.
5037105197Ssam * it is caller's responsibility to free the result.
5038105197Ssam */
5039105197Ssamstatic struct mbuf *
5040105197Ssamkey_getmsgbuf_x1(m, mhp)
5041105197Ssam	struct mbuf *m;
5042105197Ssam	const struct sadb_msghdr *mhp;
5043105197Ssam{
5044105197Ssam	struct mbuf *n;
5045105197Ssam
5046105197Ssam	/* sanity check */
5047105197Ssam	if (m == NULL || mhp == NULL || mhp->msg == NULL)
5048105197Ssam		panic("key_getmsgbuf_x1: NULL pointer is passed.\n");
5049105197Ssam
5050105197Ssam	/* create new sadb_msg to reply. */
5051105197Ssam	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5052105197Ssam	    SADB_EXT_SA, SADB_X_EXT_SA2,
5053105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5054105197Ssam	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5055105197Ssam	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5056105197Ssam	if (!n)
5057105197Ssam		return NULL;
5058105197Ssam
5059105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5060105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5061105197Ssam		if (n == NULL)
5062105197Ssam			return NULL;
5063105197Ssam	}
5064105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5065105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_len =
5066105197Ssam	    PFKEY_UNIT64(n->m_pkthdr.len);
5067105197Ssam
5068105197Ssam	return n;
5069105197Ssam}
5070105197Ssam
5071105197Ssamstatic int key_delete_all __P((struct socket *, struct mbuf *,
5072105197Ssam	const struct sadb_msghdr *, u_int16_t));
5073105197Ssam
5074105197Ssam/*
5075105197Ssam * SADB_DELETE processing
5076105197Ssam * receive
5077105197Ssam *   <base, SA(*), address(SD)>
5078105197Ssam * from the ikmpd, and set SADB_SASTATE_DEAD,
5079105197Ssam * and send,
5080105197Ssam *   <base, SA(*), address(SD)>
5081105197Ssam * to the ikmpd.
5082105197Ssam *
5083105197Ssam * m will always be freed.
5084105197Ssam */
5085105197Ssamstatic int
5086105197Ssamkey_delete(so, m, mhp)
5087105197Ssam	struct socket *so;
5088105197Ssam	struct mbuf *m;
5089105197Ssam	const struct sadb_msghdr *mhp;
5090105197Ssam{
5091105197Ssam	struct sadb_sa *sa0;
5092105197Ssam	struct sadb_address *src0, *dst0;
5093105197Ssam	struct secasindex saidx;
5094105197Ssam	struct secashead *sah;
5095105197Ssam	struct secasvar *sav = NULL;
5096105197Ssam	u_int16_t proto;
5097105197Ssam
5098105197Ssam	/* sanity check */
5099105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5100105197Ssam		panic("key_delete: NULL pointer is passed.\n");
5101105197Ssam
5102105197Ssam	/* map satype to proto */
5103105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5104105197Ssam		ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
5105105197Ssam		return key_senderror(so, m, EINVAL);
5106105197Ssam	}
5107105197Ssam
5108105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5109105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5110105197Ssam		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5111105197Ssam		return key_senderror(so, m, EINVAL);
5112105197Ssam	}
5113105197Ssam
5114105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5115105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5116105197Ssam		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5117105197Ssam		return key_senderror(so, m, EINVAL);
5118105197Ssam	}
5119105197Ssam
5120105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL) {
5121105197Ssam		/*
5122105197Ssam		 * Caller wants us to delete all non-LARVAL SAs
5123105197Ssam		 * that match the src/dst.  This is used during
5124105197Ssam		 * IKE INITIAL-CONTACT.
5125105197Ssam		 */
5126105197Ssam		ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
5127105197Ssam		return key_delete_all(so, m, mhp, proto);
5128105197Ssam	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5129105197Ssam		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5130105197Ssam		return key_senderror(so, m, EINVAL);
5131105197Ssam	}
5132105197Ssam
5133105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5134105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5135105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5136105197Ssam
5137105197Ssam	/* XXX boundary check against sa_len */
5138105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5139105197Ssam
5140105197Ssam	/* get a SA header */
5141105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
5142105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5143105197Ssam			continue;
5144105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5145105197Ssam			continue;
5146105197Ssam
5147105197Ssam		/* get a SA with SPI. */
5148105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5149105197Ssam		if (sav)
5150105197Ssam			break;
5151105197Ssam	}
5152105197Ssam	if (sah == NULL) {
5153105197Ssam		ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
5154105197Ssam		return key_senderror(so, m, ENOENT);
5155105197Ssam	}
5156105197Ssam
5157105197Ssam	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5158105197Ssam	KEY_FREESAV(&sav);
5159105197Ssam
5160105197Ssam    {
5161105197Ssam	struct mbuf *n;
5162105197Ssam	struct sadb_msg *newmsg;
5163105197Ssam
5164105197Ssam	/* create new sadb_msg to reply. */
5165105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5166105197Ssam	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5167105197Ssam	if (!n)
5168105197Ssam		return key_senderror(so, m, ENOBUFS);
5169105197Ssam
5170105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5171105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5172105197Ssam		if (n == NULL)
5173105197Ssam			return key_senderror(so, m, ENOBUFS);
5174105197Ssam	}
5175105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5176105197Ssam	newmsg->sadb_msg_errno = 0;
5177105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5178105197Ssam
5179105197Ssam	m_freem(m);
5180105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5181105197Ssam    }
5182105197Ssam}
5183105197Ssam
5184105197Ssam/*
5185105197Ssam * delete all SAs for src/dst.  Called from key_delete().
5186105197Ssam */
5187105197Ssamstatic int
5188105197Ssamkey_delete_all(so, m, mhp, proto)
5189105197Ssam	struct socket *so;
5190105197Ssam	struct mbuf *m;
5191105197Ssam	const struct sadb_msghdr *mhp;
5192105197Ssam	u_int16_t proto;
5193105197Ssam{
5194105197Ssam	struct sadb_address *src0, *dst0;
5195105197Ssam	struct secasindex saidx;
5196105197Ssam	struct secashead *sah;
5197105197Ssam	struct secasvar *sav, *nextsav;
5198105197Ssam	u_int stateidx, state;
5199105197Ssam
5200105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5201105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5202105197Ssam
5203105197Ssam	/* XXX boundary check against sa_len */
5204105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5205105197Ssam
5206105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
5207105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5208105197Ssam			continue;
5209105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5210105197Ssam			continue;
5211105197Ssam
5212105197Ssam		/* Delete all non-LARVAL SAs. */
5213105197Ssam		for (stateidx = 0;
5214105197Ssam		     stateidx < _ARRAYLEN(saorder_state_alive);
5215105197Ssam		     stateidx++) {
5216105197Ssam			state = saorder_state_alive[stateidx];
5217105197Ssam			if (state == SADB_SASTATE_LARVAL)
5218105197Ssam				continue;
5219105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
5220105197Ssam			     sav != NULL; sav = nextsav) {
5221105197Ssam				nextsav = LIST_NEXT(sav, chain);
5222105197Ssam				/* sanity check */
5223105197Ssam				if (sav->state != state) {
5224105197Ssam					ipseclog((LOG_DEBUG, "key_delete_all: "
5225105197Ssam					       "invalid sav->state "
5226105197Ssam					       "(queue: %d SA: %d)\n",
5227105197Ssam					       state, sav->state));
5228105197Ssam					continue;
5229105197Ssam				}
5230105197Ssam
5231105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5232105197Ssam				KEY_FREESAV(&sav);
5233105197Ssam			}
5234105197Ssam		}
5235105197Ssam	}
5236105197Ssam    {
5237105197Ssam	struct mbuf *n;
5238105197Ssam	struct sadb_msg *newmsg;
5239105197Ssam
5240105197Ssam	/* create new sadb_msg to reply. */
5241105197Ssam	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5242105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5243105197Ssam	if (!n)
5244105197Ssam		return key_senderror(so, m, ENOBUFS);
5245105197Ssam
5246105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5247105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5248105197Ssam		if (n == NULL)
5249105197Ssam			return key_senderror(so, m, ENOBUFS);
5250105197Ssam	}
5251105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5252105197Ssam	newmsg->sadb_msg_errno = 0;
5253105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5254105197Ssam
5255105197Ssam	m_freem(m);
5256105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5257105197Ssam    }
5258105197Ssam}
5259105197Ssam
5260105197Ssam/*
5261105197Ssam * SADB_GET processing
5262105197Ssam * receive
5263105197Ssam *   <base, SA(*), address(SD)>
5264105197Ssam * from the ikmpd, and get a SP and a SA to respond,
5265105197Ssam * and send,
5266105197Ssam *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5267105197Ssam *       (identity(SD),) (sensitivity)>
5268105197Ssam * to the ikmpd.
5269105197Ssam *
5270105197Ssam * m will always be freed.
5271105197Ssam */
5272105197Ssamstatic int
5273105197Ssamkey_get(so, m, mhp)
5274105197Ssam	struct socket *so;
5275105197Ssam	struct mbuf *m;
5276105197Ssam	const struct sadb_msghdr *mhp;
5277105197Ssam{
5278105197Ssam	struct sadb_sa *sa0;
5279105197Ssam	struct sadb_address *src0, *dst0;
5280105197Ssam	struct secasindex saidx;
5281105197Ssam	struct secashead *sah;
5282105197Ssam	struct secasvar *sav = NULL;
5283105197Ssam	u_int16_t proto;
5284105197Ssam
5285105197Ssam	/* sanity check */
5286105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5287105197Ssam		panic("key_get: NULL pointer is passed.\n");
5288105197Ssam
5289105197Ssam	/* map satype to proto */
5290105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5291105197Ssam		ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
5292105197Ssam		return key_senderror(so, m, EINVAL);
5293105197Ssam	}
5294105197Ssam
5295105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5296105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5297105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5298105197Ssam		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5299105197Ssam		return key_senderror(so, m, EINVAL);
5300105197Ssam	}
5301105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5302105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5303105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5304105197Ssam		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5305105197Ssam		return key_senderror(so, m, EINVAL);
5306105197Ssam	}
5307105197Ssam
5308105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5309105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5310105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5311105197Ssam
5312105197Ssam	/* XXX boundary check against sa_len */
5313105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5314105197Ssam
5315105197Ssam	/* get a SA header */
5316105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
5317105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5318105197Ssam			continue;
5319105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5320105197Ssam			continue;
5321105197Ssam
5322105197Ssam		/* get a SA with SPI. */
5323105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5324105197Ssam		if (sav)
5325105197Ssam			break;
5326105197Ssam	}
5327105197Ssam	if (sah == NULL) {
5328105197Ssam		ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
5329105197Ssam		return key_senderror(so, m, ENOENT);
5330105197Ssam	}
5331105197Ssam
5332105197Ssam    {
5333105197Ssam	struct mbuf *n;
5334105197Ssam	u_int8_t satype;
5335105197Ssam
5336105197Ssam	/* map proto to satype */
5337105197Ssam	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5338105197Ssam		ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
5339105197Ssam		return key_senderror(so, m, EINVAL);
5340105197Ssam	}
5341105197Ssam
5342105197Ssam	/* create new sadb_msg to reply. */
5343105197Ssam	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5344105197Ssam	    mhp->msg->sadb_msg_pid);
5345105197Ssam	if (!n)
5346105197Ssam		return key_senderror(so, m, ENOBUFS);
5347105197Ssam
5348105197Ssam	m_freem(m);
5349105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5350105197Ssam    }
5351105197Ssam}
5352105197Ssam
5353105197Ssam/* XXX make it sysctl-configurable? */
5354105197Ssamstatic void
5355105197Ssamkey_getcomb_setlifetime(comb)
5356105197Ssam	struct sadb_comb *comb;
5357105197Ssam{
5358105197Ssam
5359105197Ssam	comb->sadb_comb_soft_allocations = 1;
5360105197Ssam	comb->sadb_comb_hard_allocations = 1;
5361105197Ssam	comb->sadb_comb_soft_bytes = 0;
5362105197Ssam	comb->sadb_comb_hard_bytes = 0;
5363105197Ssam	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5364105197Ssam	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5365105197Ssam	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5366105197Ssam	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5367105197Ssam}
5368105197Ssam
5369105197Ssam/*
5370105197Ssam * XXX reorder combinations by preference
5371105197Ssam * XXX no idea if the user wants ESP authentication or not
5372105197Ssam */
5373105197Ssamstatic struct mbuf *
5374105197Ssamkey_getcomb_esp()
5375105197Ssam{
5376105197Ssam	struct sadb_comb *comb;
5377105197Ssam	struct enc_xform *algo;
5378105197Ssam	struct mbuf *result = NULL, *m, *n;
5379105197Ssam	int encmin;
5380105197Ssam	int i, off, o;
5381105197Ssam	int totlen;
5382105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5383105197Ssam
5384105197Ssam	m = NULL;
5385105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
5386105197Ssam		algo = esp_algorithm_lookup(i);
5387105197Ssam		if (algo == NULL)
5388105197Ssam			continue;
5389105197Ssam
5390105197Ssam		/* discard algorithms with key size smaller than system min */
5391105197Ssam		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
5392105197Ssam			continue;
5393105197Ssam		if (_BITS(algo->minkey) < ipsec_esp_keymin)
5394105197Ssam			encmin = ipsec_esp_keymin;
5395105197Ssam		else
5396105197Ssam			encmin = _BITS(algo->minkey);
5397105197Ssam
5398105197Ssam		if (ipsec_esp_auth)
5399105197Ssam			m = key_getcomb_ah();
5400105197Ssam		else {
5401105197Ssam			KASSERT(l <= MLEN,
5402105197Ssam				("key_getcomb_esp: l=%u > MLEN=%lu",
5403105197Ssam				l, (u_long) MLEN));
5404111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5405105197Ssam			if (m) {
5406105197Ssam				M_ALIGN(m, l);
5407105197Ssam				m->m_len = l;
5408105197Ssam				m->m_next = NULL;
5409105197Ssam				bzero(mtod(m, caddr_t), m->m_len);
5410105197Ssam			}
5411105197Ssam		}
5412105197Ssam		if (!m)
5413105197Ssam			goto fail;
5414105197Ssam
5415105197Ssam		totlen = 0;
5416105197Ssam		for (n = m; n; n = n->m_next)
5417105197Ssam			totlen += n->m_len;
5418105197Ssam		KASSERT((totlen % l) == 0,
5419105197Ssam			("key_getcomb_esp: totlen=%u, l=%u", totlen, l));
5420105197Ssam
5421105197Ssam		for (off = 0; off < totlen; off += l) {
5422105197Ssam			n = m_pulldown(m, off, l, &o);
5423105197Ssam			if (!n) {
5424105197Ssam				/* m is already freed */
5425105197Ssam				goto fail;
5426105197Ssam			}
5427105197Ssam			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5428105197Ssam			bzero(comb, sizeof(*comb));
5429105197Ssam			key_getcomb_setlifetime(comb);
5430105197Ssam			comb->sadb_comb_encrypt = i;
5431105197Ssam			comb->sadb_comb_encrypt_minbits = encmin;
5432105197Ssam			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5433105197Ssam		}
5434105197Ssam
5435105197Ssam		if (!result)
5436105197Ssam			result = m;
5437105197Ssam		else
5438105197Ssam			m_cat(result, m);
5439105197Ssam	}
5440105197Ssam
5441105197Ssam	return result;
5442105197Ssam
5443105197Ssam fail:
5444105197Ssam	if (result)
5445105197Ssam		m_freem(result);
5446105197Ssam	return NULL;
5447105197Ssam}
5448105197Ssam
5449105197Ssamstatic void
5450105197Ssamkey_getsizes_ah(
5451105197Ssam	const struct auth_hash *ah,
5452105197Ssam	int alg,
5453105197Ssam	u_int16_t* min,
5454105197Ssam	u_int16_t* max)
5455105197Ssam{
5456105197Ssam	*min = *max = ah->keysize;
5457105197Ssam	if (ah->keysize == 0) {
5458105197Ssam		/*
5459105197Ssam		 * Transform takes arbitrary key size but algorithm
5460105197Ssam		 * key size is restricted.  Enforce this here.
5461105197Ssam		 */
5462105197Ssam		switch (alg) {
5463105197Ssam		case SADB_X_AALG_MD5:	*min = *max = 16; break;
5464105197Ssam		case SADB_X_AALG_SHA:	*min = *max = 20; break;
5465105197Ssam		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
5466105197Ssam		default:
5467105197Ssam			DPRINTF(("key_getsizes_ah: unknown AH algorithm %u\n",
5468105197Ssam				alg));
5469105197Ssam			break;
5470105197Ssam		}
5471105197Ssam	}
5472105197Ssam}
5473105197Ssam
5474105197Ssam/*
5475105197Ssam * XXX reorder combinations by preference
5476105197Ssam */
5477105197Ssamstatic struct mbuf *
5478105197Ssamkey_getcomb_ah()
5479105197Ssam{
5480105197Ssam	struct sadb_comb *comb;
5481105197Ssam	struct auth_hash *algo;
5482105197Ssam	struct mbuf *m;
5483105197Ssam	u_int16_t minkeysize, maxkeysize;
5484105197Ssam	int i;
5485105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5486105197Ssam
5487105197Ssam	m = NULL;
5488105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
5489105197Ssam#if 1
5490105197Ssam		/* we prefer HMAC algorithms, not old algorithms */
5491105197Ssam		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5492105197Ssam			continue;
5493105197Ssam#endif
5494105197Ssam		algo = ah_algorithm_lookup(i);
5495105197Ssam		if (!algo)
5496105197Ssam			continue;
5497105197Ssam		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5498105197Ssam		/* discard algorithms with key size smaller than system min */
5499105197Ssam		if (_BITS(minkeysize) < ipsec_ah_keymin)
5500105197Ssam			continue;
5501105197Ssam
5502105197Ssam		if (!m) {
5503105197Ssam			KASSERT(l <= MLEN,
5504105197Ssam				("key_getcomb_ah: l=%u > MLEN=%lu",
5505105197Ssam				l, (u_long) MLEN));
5506111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5507105197Ssam			if (m) {
5508105197Ssam				M_ALIGN(m, l);
5509105197Ssam				m->m_len = l;
5510105197Ssam				m->m_next = NULL;
5511105197Ssam			}
5512105197Ssam		} else
5513111119Simp			M_PREPEND(m, l, M_DONTWAIT);
5514105197Ssam		if (!m)
5515105197Ssam			return NULL;
5516105197Ssam
5517105197Ssam		comb = mtod(m, struct sadb_comb *);
5518105197Ssam		bzero(comb, sizeof(*comb));
5519105197Ssam		key_getcomb_setlifetime(comb);
5520105197Ssam		comb->sadb_comb_auth = i;
5521105197Ssam		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5522105197Ssam		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5523105197Ssam	}
5524105197Ssam
5525105197Ssam	return m;
5526105197Ssam}
5527105197Ssam
5528105197Ssam/*
5529105197Ssam * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5530105197Ssam * XXX reorder combinations by preference
5531105197Ssam */
5532105197Ssamstatic struct mbuf *
5533105197Ssamkey_getcomb_ipcomp()
5534105197Ssam{
5535105197Ssam	struct sadb_comb *comb;
5536105197Ssam	struct comp_algo *algo;
5537105197Ssam	struct mbuf *m;
5538105197Ssam	int i;
5539105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5540105197Ssam
5541105197Ssam	m = NULL;
5542105197Ssam	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5543105197Ssam		algo = ipcomp_algorithm_lookup(i);
5544105197Ssam		if (!algo)
5545105197Ssam			continue;
5546105197Ssam
5547105197Ssam		if (!m) {
5548105197Ssam			KASSERT(l <= MLEN,
5549105197Ssam				("key_getcomb_ipcomp: l=%u > MLEN=%lu",
5550105197Ssam				l, (u_long) MLEN));
5551111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5552105197Ssam			if (m) {
5553105197Ssam				M_ALIGN(m, l);
5554105197Ssam				m->m_len = l;
5555105197Ssam				m->m_next = NULL;
5556105197Ssam			}
5557105197Ssam		} else
5558111119Simp			M_PREPEND(m, l, M_DONTWAIT);
5559105197Ssam		if (!m)
5560105197Ssam			return NULL;
5561105197Ssam
5562105197Ssam		comb = mtod(m, struct sadb_comb *);
5563105197Ssam		bzero(comb, sizeof(*comb));
5564105197Ssam		key_getcomb_setlifetime(comb);
5565105197Ssam		comb->sadb_comb_encrypt = i;
5566105197Ssam		/* what should we set into sadb_comb_*_{min,max}bits? */
5567105197Ssam	}
5568105197Ssam
5569105197Ssam	return m;
5570105197Ssam}
5571105197Ssam
5572105197Ssam/*
5573105197Ssam * XXX no way to pass mode (transport/tunnel) to userland
5574105197Ssam * XXX replay checking?
5575105197Ssam * XXX sysctl interface to ipsec_{ah,esp}_keymin
5576105197Ssam */
5577105197Ssamstatic struct mbuf *
5578105197Ssamkey_getprop(saidx)
5579105197Ssam	const struct secasindex *saidx;
5580105197Ssam{
5581105197Ssam	struct sadb_prop *prop;
5582105197Ssam	struct mbuf *m, *n;
5583105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5584105197Ssam	int totlen;
5585105197Ssam
5586105197Ssam	switch (saidx->proto)  {
5587105197Ssam	case IPPROTO_ESP:
5588105197Ssam		m = key_getcomb_esp();
5589105197Ssam		break;
5590105197Ssam	case IPPROTO_AH:
5591105197Ssam		m = key_getcomb_ah();
5592105197Ssam		break;
5593105197Ssam	case IPPROTO_IPCOMP:
5594105197Ssam		m = key_getcomb_ipcomp();
5595105197Ssam		break;
5596105197Ssam	default:
5597105197Ssam		return NULL;
5598105197Ssam	}
5599105197Ssam
5600105197Ssam	if (!m)
5601105197Ssam		return NULL;
5602111119Simp	M_PREPEND(m, l, M_DONTWAIT);
5603105197Ssam	if (!m)
5604105197Ssam		return NULL;
5605105197Ssam
5606105197Ssam	totlen = 0;
5607105197Ssam	for (n = m; n; n = n->m_next)
5608105197Ssam		totlen += n->m_len;
5609105197Ssam
5610105197Ssam	prop = mtod(m, struct sadb_prop *);
5611105197Ssam	bzero(prop, sizeof(*prop));
5612105197Ssam	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5613105197Ssam	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5614105197Ssam	prop->sadb_prop_replay = 32;	/* XXX */
5615105197Ssam
5616105197Ssam	return m;
5617105197Ssam}
5618105197Ssam
5619105197Ssam/*
5620105197Ssam * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5621105197Ssam * send
5622105197Ssam *   <base, SA, address(SD), (address(P)), x_policy,
5623105197Ssam *       (identity(SD),) (sensitivity,) proposal>
5624105197Ssam * to KMD, and expect to receive
5625105197Ssam *   <base> with SADB_ACQUIRE if error occured,
5626105197Ssam * or
5627105197Ssam *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5628105197Ssam * from KMD by PF_KEY.
5629105197Ssam *
5630105197Ssam * XXX x_policy is outside of RFC2367 (KAME extension).
5631105197Ssam * XXX sensitivity is not supported.
5632105197Ssam * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5633105197Ssam * see comment for key_getcomb_ipcomp().
5634105197Ssam *
5635105197Ssam * OUT:
5636105197Ssam *    0     : succeed
5637105197Ssam *    others: error number
5638105197Ssam */
5639105197Ssamstatic int
5640105197Ssamkey_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5641105197Ssam{
5642105197Ssam	struct mbuf *result = NULL, *m;
5643105197Ssam#ifndef IPSEC_NONBLOCK_ACQUIRE
5644105197Ssam	struct secacq *newacq;
5645105197Ssam#endif
5646105197Ssam	u_int8_t satype;
5647105197Ssam	int error = -1;
5648105197Ssam	u_int32_t seq;
5649105197Ssam
5650105197Ssam	/* sanity check */
5651105197Ssam	KASSERT(saidx != NULL, ("key_acquire: null saidx"));
5652105197Ssam	satype = key_proto2satype(saidx->proto);
5653105197Ssam	KASSERT(satype != 0,
5654105197Ssam		("key_acquire: null satype, protocol %u", saidx->proto));
5655105197Ssam
5656105197Ssam#ifndef IPSEC_NONBLOCK_ACQUIRE
5657105197Ssam	/*
5658105197Ssam	 * We never do anything about acquirng SA.  There is anather
5659105197Ssam	 * solution that kernel blocks to send SADB_ACQUIRE message until
5660105197Ssam	 * getting something message from IKEd.  In later case, to be
5661105197Ssam	 * managed with ACQUIRING list.
5662105197Ssam	 */
5663108533Sschweikh	/* Get an entry to check whether sending message or not. */
5664105197Ssam	if ((newacq = key_getacq(saidx)) != NULL) {
5665105197Ssam		if (key_blockacq_count < newacq->count) {
5666105197Ssam			/* reset counter and do send message. */
5667105197Ssam			newacq->count = 0;
5668105197Ssam		} else {
5669105197Ssam			/* increment counter and do nothing. */
5670105197Ssam			newacq->count++;
5671105197Ssam			return 0;
5672105197Ssam		}
5673105197Ssam	} else {
5674105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
5675105197Ssam		if ((newacq = key_newacq(saidx)) == NULL)
5676105197Ssam			return ENOBUFS;
5677105197Ssam
5678105197Ssam		/* add to acqtree */
5679105197Ssam		LIST_INSERT_HEAD(&acqtree, newacq, chain);
5680105197Ssam	}
5681105197Ssam#endif
5682105197Ssam
5683105197Ssam
5684105197Ssam#ifndef IPSEC_NONBLOCK_ACQUIRE
5685105197Ssam	seq = newacq->seq;
5686105197Ssam#else
5687105197Ssam	seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
5688105197Ssam#endif
5689105197Ssam	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5690105197Ssam	if (!m) {
5691105197Ssam		error = ENOBUFS;
5692105197Ssam		goto fail;
5693105197Ssam	}
5694105197Ssam	result = m;
5695105197Ssam
5696105197Ssam	/* set sadb_address for saidx's. */
5697105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5698105197Ssam	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5699105197Ssam	if (!m) {
5700105197Ssam		error = ENOBUFS;
5701105197Ssam		goto fail;
5702105197Ssam	}
5703105197Ssam	m_cat(result, m);
5704105197Ssam
5705105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5706105197Ssam	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5707105197Ssam	if (!m) {
5708105197Ssam		error = ENOBUFS;
5709105197Ssam		goto fail;
5710105197Ssam	}
5711105197Ssam	m_cat(result, m);
5712105197Ssam
5713105197Ssam	/* XXX proxy address (optional) */
5714105197Ssam
5715105197Ssam	/* set sadb_x_policy */
5716105197Ssam	if (sp) {
5717105197Ssam		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5718105197Ssam		if (!m) {
5719105197Ssam			error = ENOBUFS;
5720105197Ssam			goto fail;
5721105197Ssam		}
5722105197Ssam		m_cat(result, m);
5723105197Ssam	}
5724105197Ssam
5725105197Ssam	/* XXX identity (optional) */
5726105197Ssam#if 0
5727105197Ssam	if (idexttype && fqdn) {
5728105197Ssam		/* create identity extension (FQDN) */
5729105197Ssam		struct sadb_ident *id;
5730105197Ssam		int fqdnlen;
5731105197Ssam
5732105197Ssam		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
5733105197Ssam		id = (struct sadb_ident *)p;
5734105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5735105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5736105197Ssam		id->sadb_ident_exttype = idexttype;
5737105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5738105197Ssam		bcopy(fqdn, id + 1, fqdnlen);
5739105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5740105197Ssam	}
5741105197Ssam
5742105197Ssam	if (idexttype) {
5743105197Ssam		/* create identity extension (USERFQDN) */
5744105197Ssam		struct sadb_ident *id;
5745105197Ssam		int userfqdnlen;
5746105197Ssam
5747105197Ssam		if (userfqdn) {
5748105197Ssam			/* +1 for terminating-NUL */
5749105197Ssam			userfqdnlen = strlen(userfqdn) + 1;
5750105197Ssam		} else
5751105197Ssam			userfqdnlen = 0;
5752105197Ssam		id = (struct sadb_ident *)p;
5753105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5754105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5755105197Ssam		id->sadb_ident_exttype = idexttype;
5756105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5757105197Ssam		/* XXX is it correct? */
5758105197Ssam		if (curproc && curproc->p_cred)
5759105197Ssam			id->sadb_ident_id = curproc->p_cred->p_ruid;
5760105197Ssam		if (userfqdn && userfqdnlen)
5761105197Ssam			bcopy(userfqdn, id + 1, userfqdnlen);
5762105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5763105197Ssam	}
5764105197Ssam#endif
5765105197Ssam
5766105197Ssam	/* XXX sensitivity (optional) */
5767105197Ssam
5768105197Ssam	/* create proposal/combination extension */
5769105197Ssam	m = key_getprop(saidx);
5770105197Ssam#if 0
5771105197Ssam	/*
5772105197Ssam	 * spec conformant: always attach proposal/combination extension,
5773105197Ssam	 * the problem is that we have no way to attach it for ipcomp,
5774105197Ssam	 * due to the way sadb_comb is declared in RFC2367.
5775105197Ssam	 */
5776105197Ssam	if (!m) {
5777105197Ssam		error = ENOBUFS;
5778105197Ssam		goto fail;
5779105197Ssam	}
5780105197Ssam	m_cat(result, m);
5781105197Ssam#else
5782105197Ssam	/*
5783105197Ssam	 * outside of spec; make proposal/combination extension optional.
5784105197Ssam	 */
5785105197Ssam	if (m)
5786105197Ssam		m_cat(result, m);
5787105197Ssam#endif
5788105197Ssam
5789105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
5790105197Ssam		error = EINVAL;
5791105197Ssam		goto fail;
5792105197Ssam	}
5793105197Ssam
5794105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
5795105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
5796105197Ssam		if (result == NULL) {
5797105197Ssam			error = ENOBUFS;
5798105197Ssam			goto fail;
5799105197Ssam		}
5800105197Ssam	}
5801105197Ssam
5802105197Ssam	result->m_pkthdr.len = 0;
5803105197Ssam	for (m = result; m; m = m->m_next)
5804105197Ssam		result->m_pkthdr.len += m->m_len;
5805105197Ssam
5806105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
5807105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
5808105197Ssam
5809105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5810105197Ssam
5811105197Ssam fail:
5812105197Ssam	if (result)
5813105197Ssam		m_freem(result);
5814105197Ssam	return error;
5815105197Ssam}
5816105197Ssam
5817105197Ssam#ifndef IPSEC_NONBLOCK_ACQUIRE
5818105197Ssamstatic struct secacq *
5819105197Ssamkey_newacq(const struct secasindex *saidx)
5820105197Ssam{
5821105197Ssam	struct secacq *newacq;
5822105197Ssam
5823105197Ssam	/* get new entry */
5824105197Ssam	KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
5825105197Ssam	if (newacq == NULL) {
5826105197Ssam		ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
5827105197Ssam		return NULL;
5828105197Ssam	}
5829105197Ssam	bzero(newacq, sizeof(*newacq));
5830105197Ssam
5831105197Ssam	/* copy secindex */
5832105197Ssam	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5833105197Ssam	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
5834105197Ssam	newacq->created = time_second;
5835105197Ssam	newacq->count = 0;
5836105197Ssam
5837105197Ssam	return newacq;
5838105197Ssam}
5839105197Ssam
5840105197Ssamstatic struct secacq *
5841105197Ssamkey_getacq(const struct secasindex *saidx)
5842105197Ssam{
5843105197Ssam	struct secacq *acq;
5844105197Ssam
5845105197Ssam	LIST_FOREACH(acq, &acqtree, chain) {
5846105197Ssam		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5847105197Ssam			return acq;
5848105197Ssam	}
5849105197Ssam
5850105197Ssam	return NULL;
5851105197Ssam}
5852105197Ssam
5853105197Ssamstatic struct secacq *
5854105197Ssamkey_getacqbyseq(seq)
5855105197Ssam	u_int32_t seq;
5856105197Ssam{
5857105197Ssam	struct secacq *acq;
5858105197Ssam
5859105197Ssam	LIST_FOREACH(acq, &acqtree, chain) {
5860105197Ssam		if (acq->seq == seq)
5861105197Ssam			return acq;
5862105197Ssam	}
5863105197Ssam
5864105197Ssam	return NULL;
5865105197Ssam}
5866105197Ssam#endif
5867105197Ssam
5868105197Ssamstatic struct secspacq *
5869105197Ssamkey_newspacq(spidx)
5870105197Ssam	struct secpolicyindex *spidx;
5871105197Ssam{
5872105197Ssam	struct secspacq *acq;
5873105197Ssam
5874105197Ssam	/* get new entry */
5875105197Ssam	KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
5876105197Ssam	if (acq == NULL) {
5877105197Ssam		ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
5878105197Ssam		return NULL;
5879105197Ssam	}
5880105197Ssam	bzero(acq, sizeof(*acq));
5881105197Ssam
5882105197Ssam	/* copy secindex */
5883105197Ssam	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5884105197Ssam	acq->created = time_second;
5885105197Ssam	acq->count = 0;
5886105197Ssam
5887105197Ssam	return acq;
5888105197Ssam}
5889105197Ssam
5890105197Ssamstatic struct secspacq *
5891105197Ssamkey_getspacq(spidx)
5892105197Ssam	struct secpolicyindex *spidx;
5893105197Ssam{
5894105197Ssam	struct secspacq *acq;
5895105197Ssam
5896105197Ssam	LIST_FOREACH(acq, &spacqtree, chain) {
5897105197Ssam		if (key_cmpspidx_exactly(spidx, &acq->spidx))
5898105197Ssam			return acq;
5899105197Ssam	}
5900105197Ssam
5901105197Ssam	return NULL;
5902105197Ssam}
5903105197Ssam
5904105197Ssam/*
5905105197Ssam * SADB_ACQUIRE processing,
5906105197Ssam * in first situation, is receiving
5907105197Ssam *   <base>
5908105197Ssam * from the ikmpd, and clear sequence of its secasvar entry.
5909105197Ssam *
5910105197Ssam * In second situation, is receiving
5911105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5912105197Ssam * from a user land process, and return
5913105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5914105197Ssam * to the socket.
5915105197Ssam *
5916105197Ssam * m will always be freed.
5917105197Ssam */
5918105197Ssamstatic int
5919105197Ssamkey_acquire2(so, m, mhp)
5920105197Ssam	struct socket *so;
5921105197Ssam	struct mbuf *m;
5922105197Ssam	const struct sadb_msghdr *mhp;
5923105197Ssam{
5924105197Ssam	const struct sadb_address *src0, *dst0;
5925105197Ssam	struct secasindex saidx;
5926105197Ssam	struct secashead *sah;
5927105197Ssam	u_int16_t proto;
5928105197Ssam	int error;
5929105197Ssam
5930105197Ssam	/* sanity check */
5931105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5932105197Ssam		panic("key_acquire2: NULL pointer is passed.\n");
5933105197Ssam
5934105197Ssam	/*
5935105197Ssam	 * Error message from KMd.
5936105197Ssam	 * We assume that if error was occured in IKEd, the length of PFKEY
5937105197Ssam	 * message is equal to the size of sadb_msg structure.
5938105197Ssam	 * We do not raise error even if error occured in this function.
5939105197Ssam	 */
5940105197Ssam	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
5941105197Ssam#ifndef IPSEC_NONBLOCK_ACQUIRE
5942105197Ssam		struct secacq *acq;
5943105197Ssam
5944105197Ssam		/* check sequence number */
5945105197Ssam		if (mhp->msg->sadb_msg_seq == 0) {
5946105197Ssam			ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
5947105197Ssam			m_freem(m);
5948105197Ssam			return 0;
5949105197Ssam		}
5950105197Ssam
5951105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
5952105197Ssam			/*
5953105197Ssam			 * the specified larval SA is already gone, or we got
5954105197Ssam			 * a bogus sequence number.  we can silently ignore it.
5955105197Ssam			 */
5956105197Ssam			m_freem(m);
5957105197Ssam			return 0;
5958105197Ssam		}
5959105197Ssam
5960105197Ssam		/* reset acq counter in order to deletion by timehander. */
5961105197Ssam		acq->created = time_second;
5962105197Ssam		acq->count = 0;
5963105197Ssam#endif
5964105197Ssam		m_freem(m);
5965105197Ssam		return 0;
5966105197Ssam	}
5967105197Ssam
5968105197Ssam	/*
5969105197Ssam	 * This message is from user land.
5970105197Ssam	 */
5971105197Ssam
5972105197Ssam	/* map satype to proto */
5973105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5974105197Ssam		ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
5975105197Ssam		return key_senderror(so, m, EINVAL);
5976105197Ssam	}
5977105197Ssam
5978105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5979105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5980105197Ssam	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
5981105197Ssam		/* error */
5982105197Ssam		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
5983105197Ssam		return key_senderror(so, m, EINVAL);
5984105197Ssam	}
5985105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5986105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
5987105197Ssam	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
5988105197Ssam		/* error */
5989105197Ssam		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
5990105197Ssam		return key_senderror(so, m, EINVAL);
5991105197Ssam	}
5992105197Ssam
5993105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5994105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5995105197Ssam
5996105197Ssam	/* XXX boundary check against sa_len */
5997105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5998105197Ssam
5999105197Ssam	/* get a SA index */
6000105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
6001105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
6002105197Ssam			continue;
6003105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6004105197Ssam			break;
6005105197Ssam	}
6006105197Ssam	if (sah != NULL) {
6007105197Ssam		ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
6008105197Ssam		return key_senderror(so, m, EEXIST);
6009105197Ssam	}
6010105197Ssam
6011105197Ssam	error = key_acquire(&saidx, NULL);
6012105197Ssam	if (error != 0) {
6013105197Ssam		ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
6014105197Ssam			"from key_acquire.\n", mhp->msg->sadb_msg_errno));
6015105197Ssam		return key_senderror(so, m, error);
6016105197Ssam	}
6017105197Ssam
6018105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6019105197Ssam}
6020105197Ssam
6021105197Ssam/*
6022105197Ssam * SADB_REGISTER processing.
6023105197Ssam * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6024105197Ssam * receive
6025105197Ssam *   <base>
6026105197Ssam * from the ikmpd, and register a socket to send PF_KEY messages,
6027105197Ssam * and send
6028105197Ssam *   <base, supported>
6029105197Ssam * to KMD by PF_KEY.
6030105197Ssam * If socket is detached, must free from regnode.
6031105197Ssam *
6032105197Ssam * m will always be freed.
6033105197Ssam */
6034105197Ssamstatic int
6035105197Ssamkey_register(so, m, mhp)
6036105197Ssam	struct socket *so;
6037105197Ssam	struct mbuf *m;
6038105197Ssam	const struct sadb_msghdr *mhp;
6039105197Ssam{
6040105197Ssam	struct secreg *reg, *newreg = 0;
6041105197Ssam
6042105197Ssam	/* sanity check */
6043105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6044105197Ssam		panic("key_register: NULL pointer is passed.\n");
6045105197Ssam
6046105197Ssam	/* check for invalid register message */
6047105197Ssam	if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
6048105197Ssam		return key_senderror(so, m, EINVAL);
6049105197Ssam
6050105197Ssam	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6051105197Ssam	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6052105197Ssam		goto setmsg;
6053105197Ssam
6054105197Ssam	/* check whether existing or not */
6055105197Ssam	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
6056105197Ssam		if (reg->so == so) {
6057105197Ssam			ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
6058105197Ssam			return key_senderror(so, m, EEXIST);
6059105197Ssam		}
6060105197Ssam	}
6061105197Ssam
6062105197Ssam	/* create regnode */
6063105197Ssam	KMALLOC(newreg, struct secreg *, sizeof(*newreg));
6064105197Ssam	if (newreg == NULL) {
6065105197Ssam		ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
6066105197Ssam		return key_senderror(so, m, ENOBUFS);
6067105197Ssam	}
6068105197Ssam	bzero((caddr_t)newreg, sizeof(*newreg));
6069105197Ssam
6070105197Ssam	newreg->so = so;
6071105197Ssam	((struct keycb *)sotorawcb(so))->kp_registered++;
6072105197Ssam
6073105197Ssam	/* add regnode to regtree. */
6074105197Ssam	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6075105197Ssam
6076105197Ssam  setmsg:
6077105197Ssam    {
6078105197Ssam	struct mbuf *n;
6079105197Ssam	struct sadb_msg *newmsg;
6080105197Ssam	struct sadb_supported *sup;
6081105197Ssam	u_int len, alen, elen;
6082105197Ssam	int off;
6083105197Ssam	int i;
6084105197Ssam	struct sadb_alg *alg;
6085105197Ssam
6086105197Ssam	/* create new sadb_msg to reply. */
6087105197Ssam	alen = 0;
6088105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6089105197Ssam		if (ah_algorithm_lookup(i))
6090105197Ssam			alen += sizeof(struct sadb_alg);
6091105197Ssam	}
6092105197Ssam	if (alen)
6093105197Ssam		alen += sizeof(struct sadb_supported);
6094105197Ssam	elen = 0;
6095105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6096105197Ssam		if (esp_algorithm_lookup(i))
6097105197Ssam			elen += sizeof(struct sadb_alg);
6098105197Ssam	}
6099105197Ssam	if (elen)
6100105197Ssam		elen += sizeof(struct sadb_supported);
6101105197Ssam
6102105197Ssam	len = sizeof(struct sadb_msg) + alen + elen;
6103105197Ssam
6104105197Ssam	if (len > MCLBYTES)
6105105197Ssam		return key_senderror(so, m, ENOBUFS);
6106105197Ssam
6107111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
6108105197Ssam	if (len > MHLEN) {
6109111119Simp		MCLGET(n, M_DONTWAIT);
6110105197Ssam		if ((n->m_flags & M_EXT) == 0) {
6111105197Ssam			m_freem(n);
6112105197Ssam			n = NULL;
6113105197Ssam		}
6114105197Ssam	}
6115105197Ssam	if (!n)
6116105197Ssam		return key_senderror(so, m, ENOBUFS);
6117105197Ssam
6118105197Ssam	n->m_pkthdr.len = n->m_len = len;
6119105197Ssam	n->m_next = NULL;
6120105197Ssam	off = 0;
6121105197Ssam
6122105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6123105197Ssam	newmsg = mtod(n, struct sadb_msg *);
6124105197Ssam	newmsg->sadb_msg_errno = 0;
6125105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6126105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6127105197Ssam
6128105197Ssam	/* for authentication algorithm */
6129105197Ssam	if (alen) {
6130105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6131105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6132105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6133105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6134105197Ssam
6135105197Ssam		for (i = 1; i <= SADB_AALG_MAX; i++) {
6136105197Ssam			struct auth_hash *aalgo;
6137105197Ssam			u_int16_t minkeysize, maxkeysize;
6138105197Ssam
6139105197Ssam			aalgo = ah_algorithm_lookup(i);
6140105197Ssam			if (!aalgo)
6141105197Ssam				continue;
6142105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6143105197Ssam			alg->sadb_alg_id = i;
6144105197Ssam			alg->sadb_alg_ivlen = 0;
6145105197Ssam			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6146105197Ssam			alg->sadb_alg_minbits = _BITS(minkeysize);
6147105197Ssam			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6148105197Ssam			off += PFKEY_ALIGN8(sizeof(*alg));
6149105197Ssam		}
6150105197Ssam	}
6151105197Ssam
6152105197Ssam	/* for encryption algorithm */
6153105197Ssam	if (elen) {
6154105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6155105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6156105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6157105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6158105197Ssam
6159105197Ssam		for (i = 1; i <= SADB_EALG_MAX; i++) {
6160105197Ssam			struct enc_xform *ealgo;
6161105197Ssam
6162105197Ssam			ealgo = esp_algorithm_lookup(i);
6163105197Ssam			if (!ealgo)
6164105197Ssam				continue;
6165105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6166105197Ssam			alg->sadb_alg_id = i;
6167105197Ssam			alg->sadb_alg_ivlen = ealgo->blocksize;
6168105197Ssam			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6169105197Ssam			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6170105197Ssam			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6171105197Ssam		}
6172105197Ssam	}
6173105197Ssam
6174105197Ssam#ifdef DIGAGNOSTIC
6175105197Ssam	if (off != len)
6176105197Ssam		panic("length assumption failed in key_register");
6177105197Ssam#endif
6178105197Ssam
6179105197Ssam	m_freem(m);
6180105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6181105197Ssam    }
6182105197Ssam}
6183105197Ssam
6184105197Ssam/*
6185105197Ssam * free secreg entry registered.
6186105197Ssam * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6187105197Ssam */
6188105197Ssamvoid
6189105197Ssamkey_freereg(so)
6190105197Ssam	struct socket *so;
6191105197Ssam{
6192105197Ssam	struct secreg *reg;
6193105197Ssam	int i;
6194105197Ssam
6195105197Ssam	/* sanity check */
6196105197Ssam	if (so == NULL)
6197105197Ssam		panic("key_freereg: NULL pointer is passed.\n");
6198105197Ssam
6199105197Ssam	/*
6200105197Ssam	 * check whether existing or not.
6201105197Ssam	 * check all type of SA, because there is a potential that
6202105197Ssam	 * one socket is registered to multiple type of SA.
6203105197Ssam	 */
6204105197Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6205105197Ssam		LIST_FOREACH(reg, &regtree[i], chain) {
6206105197Ssam			if (reg->so == so
6207105197Ssam			 && __LIST_CHAINED(reg)) {
6208105197Ssam				LIST_REMOVE(reg, chain);
6209105197Ssam				KFREE(reg);
6210105197Ssam				break;
6211105197Ssam			}
6212105197Ssam		}
6213105197Ssam	}
6214105197Ssam
6215105197Ssam	return;
6216105197Ssam}
6217105197Ssam
6218105197Ssam/*
6219105197Ssam * SADB_EXPIRE processing
6220105197Ssam * send
6221105197Ssam *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6222105197Ssam * to KMD by PF_KEY.
6223105197Ssam * NOTE: We send only soft lifetime extension.
6224105197Ssam *
6225105197Ssam * OUT:	0	: succeed
6226105197Ssam *	others	: error number
6227105197Ssam */
6228105197Ssamstatic int
6229105197Ssamkey_expire(sav)
6230105197Ssam	struct secasvar *sav;
6231105197Ssam{
6232105197Ssam	int s;
6233105197Ssam	int satype;
6234105197Ssam	struct mbuf *result = NULL, *m;
6235105197Ssam	int len;
6236105197Ssam	int error = -1;
6237105197Ssam	struct sadb_lifetime *lt;
6238105197Ssam
6239105197Ssam	/* XXX: Why do we lock ? */
6240105197Ssam	s = splnet();	/*called from softclock()*/
6241105197Ssam
6242105197Ssam	/* sanity check */
6243105197Ssam	if (sav == NULL)
6244105197Ssam		panic("key_expire: NULL pointer is passed.\n");
6245105197Ssam	if (sav->sah == NULL)
6246105197Ssam		panic("key_expire: Why was SA index in SA NULL.\n");
6247105197Ssam	if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
6248105197Ssam		panic("key_expire: invalid proto is passed.\n");
6249105197Ssam
6250105197Ssam	/* set msg header */
6251105197Ssam	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6252105197Ssam	if (!m) {
6253105197Ssam		error = ENOBUFS;
6254105197Ssam		goto fail;
6255105197Ssam	}
6256105197Ssam	result = m;
6257105197Ssam
6258105197Ssam	/* create SA extension */
6259105197Ssam	m = key_setsadbsa(sav);
6260105197Ssam	if (!m) {
6261105197Ssam		error = ENOBUFS;
6262105197Ssam		goto fail;
6263105197Ssam	}
6264105197Ssam	m_cat(result, m);
6265105197Ssam
6266105197Ssam	/* create SA extension */
6267105197Ssam	m = key_setsadbxsa2(sav->sah->saidx.mode,
6268105197Ssam			sav->replay ? sav->replay->count : 0,
6269105197Ssam			sav->sah->saidx.reqid);
6270105197Ssam	if (!m) {
6271105197Ssam		error = ENOBUFS;
6272105197Ssam		goto fail;
6273105197Ssam	}
6274105197Ssam	m_cat(result, m);
6275105197Ssam
6276105197Ssam	/* create lifetime extension (current and soft) */
6277105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6278105197Ssam	m = key_alloc_mbuf(len);
6279105197Ssam	if (!m || m->m_next) {	/*XXX*/
6280105197Ssam		if (m)
6281105197Ssam			m_freem(m);
6282105197Ssam		error = ENOBUFS;
6283105197Ssam		goto fail;
6284105197Ssam	}
6285105197Ssam	bzero(mtod(m, caddr_t), len);
6286105197Ssam	lt = mtod(m, struct sadb_lifetime *);
6287105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6288105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6289105197Ssam	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6290105197Ssam	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6291105197Ssam	lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
6292105197Ssam	lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
6293105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6294105197Ssam	bcopy(sav->lft_s, lt, sizeof(*lt));
6295105197Ssam	m_cat(result, m);
6296105197Ssam
6297105197Ssam	/* set sadb_address for source */
6298105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6299105197Ssam	    &sav->sah->saidx.src.sa,
6300105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6301105197Ssam	if (!m) {
6302105197Ssam		error = ENOBUFS;
6303105197Ssam		goto fail;
6304105197Ssam	}
6305105197Ssam	m_cat(result, m);
6306105197Ssam
6307105197Ssam	/* set sadb_address for destination */
6308105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6309105197Ssam	    &sav->sah->saidx.dst.sa,
6310105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6311105197Ssam	if (!m) {
6312105197Ssam		error = ENOBUFS;
6313105197Ssam		goto fail;
6314105197Ssam	}
6315105197Ssam	m_cat(result, m);
6316105197Ssam
6317105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
6318105197Ssam		error = EINVAL;
6319105197Ssam		goto fail;
6320105197Ssam	}
6321105197Ssam
6322105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
6323105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
6324105197Ssam		if (result == NULL) {
6325105197Ssam			error = ENOBUFS;
6326105197Ssam			goto fail;
6327105197Ssam		}
6328105197Ssam	}
6329105197Ssam
6330105197Ssam	result->m_pkthdr.len = 0;
6331105197Ssam	for (m = result; m; m = m->m_next)
6332105197Ssam		result->m_pkthdr.len += m->m_len;
6333105197Ssam
6334105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
6335105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
6336105197Ssam
6337105197Ssam	splx(s);
6338105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6339105197Ssam
6340105197Ssam fail:
6341105197Ssam	if (result)
6342105197Ssam		m_freem(result);
6343105197Ssam	splx(s);
6344105197Ssam	return error;
6345105197Ssam}
6346105197Ssam
6347105197Ssam/*
6348105197Ssam * SADB_FLUSH processing
6349105197Ssam * receive
6350105197Ssam *   <base>
6351105197Ssam * from the ikmpd, and free all entries in secastree.
6352105197Ssam * and send,
6353105197Ssam *   <base>
6354105197Ssam * to the ikmpd.
6355105197Ssam * NOTE: to do is only marking SADB_SASTATE_DEAD.
6356105197Ssam *
6357105197Ssam * m will always be freed.
6358105197Ssam */
6359105197Ssamstatic int
6360105197Ssamkey_flush(so, m, mhp)
6361105197Ssam	struct socket *so;
6362105197Ssam	struct mbuf *m;
6363105197Ssam	const struct sadb_msghdr *mhp;
6364105197Ssam{
6365105197Ssam	struct sadb_msg *newmsg;
6366105197Ssam	struct secashead *sah, *nextsah;
6367105197Ssam	struct secasvar *sav, *nextsav;
6368105197Ssam	u_int16_t proto;
6369105197Ssam	u_int8_t state;
6370105197Ssam	u_int stateidx;
6371105197Ssam
6372105197Ssam	/* sanity check */
6373105197Ssam	if (so == NULL || mhp == NULL || mhp->msg == NULL)
6374105197Ssam		panic("key_flush: NULL pointer is passed.\n");
6375105197Ssam
6376105197Ssam	/* map satype to proto */
6377105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6378105197Ssam		ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
6379105197Ssam		return key_senderror(so, m, EINVAL);
6380105197Ssam	}
6381105197Ssam
6382105197Ssam	/* no SATYPE specified, i.e. flushing all SA. */
6383105197Ssam	for (sah = LIST_FIRST(&sahtree);
6384105197Ssam	     sah != NULL;
6385105197Ssam	     sah = nextsah) {
6386105197Ssam		nextsah = LIST_NEXT(sah, chain);
6387105197Ssam
6388105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6389105197Ssam		 && proto != sah->saidx.proto)
6390105197Ssam			continue;
6391105197Ssam
6392105197Ssam		for (stateidx = 0;
6393105197Ssam		     stateidx < _ARRAYLEN(saorder_state_alive);
6394105197Ssam		     stateidx++) {
6395105197Ssam			state = saorder_state_any[stateidx];
6396105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
6397105197Ssam			     sav != NULL;
6398105197Ssam			     sav = nextsav) {
6399105197Ssam
6400105197Ssam				nextsav = LIST_NEXT(sav, chain);
6401105197Ssam
6402105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6403105197Ssam				KEY_FREESAV(&sav);
6404105197Ssam			}
6405105197Ssam		}
6406105197Ssam
6407105197Ssam		sah->state = SADB_SASTATE_DEAD;
6408105197Ssam	}
6409105197Ssam
6410105197Ssam	if (m->m_len < sizeof(struct sadb_msg) ||
6411105197Ssam	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6412105197Ssam		ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
6413105197Ssam		return key_senderror(so, m, ENOBUFS);
6414105197Ssam	}
6415105197Ssam
6416105197Ssam	if (m->m_next)
6417105197Ssam		m_freem(m->m_next);
6418105197Ssam	m->m_next = NULL;
6419105197Ssam	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6420105197Ssam	newmsg = mtod(m, struct sadb_msg *);
6421105197Ssam	newmsg->sadb_msg_errno = 0;
6422105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6423105197Ssam
6424105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6425105197Ssam}
6426105197Ssam
6427105197Ssam/*
6428105197Ssam * SADB_DUMP processing
6429105197Ssam * dump all entries including status of DEAD in SAD.
6430105197Ssam * receive
6431105197Ssam *   <base>
6432105197Ssam * from the ikmpd, and dump all secasvar leaves
6433105197Ssam * and send,
6434105197Ssam *   <base> .....
6435105197Ssam * to the ikmpd.
6436105197Ssam *
6437105197Ssam * m will always be freed.
6438105197Ssam */
6439105197Ssamstatic int
6440105197Ssamkey_dump(so, m, mhp)
6441105197Ssam	struct socket *so;
6442105197Ssam	struct mbuf *m;
6443105197Ssam	const struct sadb_msghdr *mhp;
6444105197Ssam{
6445105197Ssam	struct secashead *sah;
6446105197Ssam	struct secasvar *sav;
6447105197Ssam	u_int16_t proto;
6448105197Ssam	u_int stateidx;
6449105197Ssam	u_int8_t satype;
6450105197Ssam	u_int8_t state;
6451105197Ssam	int cnt;
6452105197Ssam	struct sadb_msg *newmsg;
6453105197Ssam	struct mbuf *n;
6454105197Ssam
6455105197Ssam	/* sanity check */
6456105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6457105197Ssam		panic("key_dump: NULL pointer is passed.\n");
6458105197Ssam
6459105197Ssam	/* map satype to proto */
6460105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6461105197Ssam		ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
6462105197Ssam		return key_senderror(so, m, EINVAL);
6463105197Ssam	}
6464105197Ssam
6465105197Ssam	/* count sav entries to be sent to the userland. */
6466105197Ssam	cnt = 0;
6467105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
6468105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6469105197Ssam		 && proto != sah->saidx.proto)
6470105197Ssam			continue;
6471105197Ssam
6472105197Ssam		for (stateidx = 0;
6473105197Ssam		     stateidx < _ARRAYLEN(saorder_state_any);
6474105197Ssam		     stateidx++) {
6475105197Ssam			state = saorder_state_any[stateidx];
6476105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6477105197Ssam				cnt++;
6478105197Ssam			}
6479105197Ssam		}
6480105197Ssam	}
6481105197Ssam
6482105197Ssam	if (cnt == 0)
6483105197Ssam		return key_senderror(so, m, ENOENT);
6484105197Ssam
6485105197Ssam	/* send this to the userland, one at a time. */
6486105197Ssam	newmsg = NULL;
6487105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
6488105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6489105197Ssam		 && proto != sah->saidx.proto)
6490105197Ssam			continue;
6491105197Ssam
6492105197Ssam		/* map proto to satype */
6493105197Ssam		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6494105197Ssam			ipseclog((LOG_DEBUG, "key_dump: there was invalid proto in SAD.\n"));
6495105197Ssam			return key_senderror(so, m, EINVAL);
6496105197Ssam		}
6497105197Ssam
6498105197Ssam		for (stateidx = 0;
6499105197Ssam		     stateidx < _ARRAYLEN(saorder_state_any);
6500105197Ssam		     stateidx++) {
6501105197Ssam			state = saorder_state_any[stateidx];
6502105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6503105197Ssam				n = key_setdumpsa(sav, SADB_DUMP, satype,
6504105197Ssam				    --cnt, mhp->msg->sadb_msg_pid);
6505105197Ssam				if (!n)
6506105197Ssam					return key_senderror(so, m, ENOBUFS);
6507105197Ssam
6508105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6509105197Ssam			}
6510105197Ssam		}
6511105197Ssam	}
6512105197Ssam
6513105197Ssam	m_freem(m);
6514105197Ssam	return 0;
6515105197Ssam}
6516105197Ssam
6517105197Ssam/*
6518105197Ssam * SADB_X_PROMISC processing
6519105197Ssam *
6520105197Ssam * m will always be freed.
6521105197Ssam */
6522105197Ssamstatic int
6523105197Ssamkey_promisc(so, m, mhp)
6524105197Ssam	struct socket *so;
6525105197Ssam	struct mbuf *m;
6526105197Ssam	const struct sadb_msghdr *mhp;
6527105197Ssam{
6528105197Ssam	int olen;
6529105197Ssam
6530105197Ssam	/* sanity check */
6531105197Ssam	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6532105197Ssam		panic("key_promisc: NULL pointer is passed.\n");
6533105197Ssam
6534105197Ssam	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6535105197Ssam
6536105197Ssam	if (olen < sizeof(struct sadb_msg)) {
6537105197Ssam#if 1
6538105197Ssam		return key_senderror(so, m, EINVAL);
6539105197Ssam#else
6540105197Ssam		m_freem(m);
6541105197Ssam		return 0;
6542105197Ssam#endif
6543105197Ssam	} else if (olen == sizeof(struct sadb_msg)) {
6544105197Ssam		/* enable/disable promisc mode */
6545105197Ssam		struct keycb *kp;
6546105197Ssam
6547105197Ssam		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6548105197Ssam			return key_senderror(so, m, EINVAL);
6549105197Ssam		mhp->msg->sadb_msg_errno = 0;
6550105197Ssam		switch (mhp->msg->sadb_msg_satype) {
6551105197Ssam		case 0:
6552105197Ssam		case 1:
6553105197Ssam			kp->kp_promisc = mhp->msg->sadb_msg_satype;
6554105197Ssam			break;
6555105197Ssam		default:
6556105197Ssam			return key_senderror(so, m, EINVAL);
6557105197Ssam		}
6558105197Ssam
6559105197Ssam		/* send the original message back to everyone */
6560105197Ssam		mhp->msg->sadb_msg_errno = 0;
6561105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6562105197Ssam	} else {
6563105197Ssam		/* send packet as is */
6564105197Ssam
6565105197Ssam		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6566105197Ssam
6567105197Ssam		/* TODO: if sadb_msg_seq is specified, send to specific pid */
6568105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6569105197Ssam	}
6570105197Ssam}
6571105197Ssam
6572105197Ssamstatic int (*key_typesw[]) __P((struct socket *, struct mbuf *,
6573105197Ssam		const struct sadb_msghdr *)) = {
6574105197Ssam	NULL,		/* SADB_RESERVED */
6575105197Ssam	key_getspi,	/* SADB_GETSPI */
6576105197Ssam	key_update,	/* SADB_UPDATE */
6577105197Ssam	key_add,	/* SADB_ADD */
6578105197Ssam	key_delete,	/* SADB_DELETE */
6579105197Ssam	key_get,	/* SADB_GET */
6580105197Ssam	key_acquire2,	/* SADB_ACQUIRE */
6581105197Ssam	key_register,	/* SADB_REGISTER */
6582105197Ssam	NULL,		/* SADB_EXPIRE */
6583105197Ssam	key_flush,	/* SADB_FLUSH */
6584105197Ssam	key_dump,	/* SADB_DUMP */
6585105197Ssam	key_promisc,	/* SADB_X_PROMISC */
6586105197Ssam	NULL,		/* SADB_X_PCHANGE */
6587105197Ssam	key_spdadd,	/* SADB_X_SPDUPDATE */
6588105197Ssam	key_spdadd,	/* SADB_X_SPDADD */
6589105197Ssam	key_spddelete,	/* SADB_X_SPDDELETE */
6590105197Ssam	key_spdget,	/* SADB_X_SPDGET */
6591105197Ssam	NULL,		/* SADB_X_SPDACQUIRE */
6592105197Ssam	key_spddump,	/* SADB_X_SPDDUMP */
6593105197Ssam	key_spdflush,	/* SADB_X_SPDFLUSH */
6594105197Ssam	key_spdadd,	/* SADB_X_SPDSETIDX */
6595105197Ssam	NULL,		/* SADB_X_SPDEXPIRE */
6596105197Ssam	key_spddelete2,	/* SADB_X_SPDDELETE2 */
6597105197Ssam};
6598105197Ssam
6599105197Ssam/*
6600105197Ssam * parse sadb_msg buffer to process PFKEYv2,
6601105197Ssam * and create a data to response if needed.
6602105197Ssam * I think to be dealed with mbuf directly.
6603105197Ssam * IN:
6604105197Ssam *     msgp  : pointer to pointer to a received buffer pulluped.
6605105197Ssam *             This is rewrited to response.
6606105197Ssam *     so    : pointer to socket.
6607105197Ssam * OUT:
6608105197Ssam *    length for buffer to send to user process.
6609105197Ssam */
6610105197Ssamint
6611105197Ssamkey_parse(m, so)
6612105197Ssam	struct mbuf *m;
6613105197Ssam	struct socket *so;
6614105197Ssam{
6615105197Ssam	struct sadb_msg *msg;
6616105197Ssam	struct sadb_msghdr mh;
6617105197Ssam	u_int orglen;
6618105197Ssam	int error;
6619105197Ssam	int target;
6620105197Ssam
6621105197Ssam	/* sanity check */
6622105197Ssam	if (m == NULL || so == NULL)
6623105197Ssam		panic("key_parse: NULL pointer is passed.\n");
6624105197Ssam
6625105197Ssam#if 0	/*kdebug_sadb assumes msg in linear buffer*/
6626105197Ssam	KEYDEBUG(KEYDEBUG_KEY_DUMP,
6627105197Ssam		ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
6628105197Ssam		kdebug_sadb(msg));
6629105197Ssam#endif
6630105197Ssam
6631105197Ssam	if (m->m_len < sizeof(struct sadb_msg)) {
6632105197Ssam		m = m_pullup(m, sizeof(struct sadb_msg));
6633105197Ssam		if (!m)
6634105197Ssam			return ENOBUFS;
6635105197Ssam	}
6636105197Ssam	msg = mtod(m, struct sadb_msg *);
6637105197Ssam	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6638105197Ssam	target = KEY_SENDUP_ONE;
6639105197Ssam
6640105197Ssam	if ((m->m_flags & M_PKTHDR) == 0 ||
6641105197Ssam	    m->m_pkthdr.len != m->m_pkthdr.len) {
6642105197Ssam		ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
6643105197Ssam		pfkeystat.out_invlen++;
6644105197Ssam		error = EINVAL;
6645105197Ssam		goto senderror;
6646105197Ssam	}
6647105197Ssam
6648105197Ssam	if (msg->sadb_msg_version != PF_KEY_V2) {
6649105197Ssam		ipseclog((LOG_DEBUG,
6650105197Ssam		    "key_parse: PF_KEY version %u is mismatched.\n",
6651105197Ssam		    msg->sadb_msg_version));
6652105197Ssam		pfkeystat.out_invver++;
6653105197Ssam		error = EINVAL;
6654105197Ssam		goto senderror;
6655105197Ssam	}
6656105197Ssam
6657105197Ssam	if (msg->sadb_msg_type > SADB_MAX) {
6658105197Ssam		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6659105197Ssam		    msg->sadb_msg_type));
6660105197Ssam		pfkeystat.out_invmsgtype++;
6661105197Ssam		error = EINVAL;
6662105197Ssam		goto senderror;
6663105197Ssam	}
6664105197Ssam
6665105197Ssam	/* for old-fashioned code - should be nuked */
6666105197Ssam	if (m->m_pkthdr.len > MCLBYTES) {
6667105197Ssam		m_freem(m);
6668105197Ssam		return ENOBUFS;
6669105197Ssam	}
6670105197Ssam	if (m->m_next) {
6671105197Ssam		struct mbuf *n;
6672105197Ssam
6673111119Simp		MGETHDR(n, M_DONTWAIT, MT_DATA);
6674105197Ssam		if (n && m->m_pkthdr.len > MHLEN) {
6675111119Simp			MCLGET(n, M_DONTWAIT);
6676105197Ssam			if ((n->m_flags & M_EXT) == 0) {
6677105197Ssam				m_free(n);
6678105197Ssam				n = NULL;
6679105197Ssam			}
6680105197Ssam		}
6681105197Ssam		if (!n) {
6682105197Ssam			m_freem(m);
6683105197Ssam			return ENOBUFS;
6684105197Ssam		}
6685105197Ssam		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6686105197Ssam		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6687105197Ssam		n->m_next = NULL;
6688105197Ssam		m_freem(m);
6689105197Ssam		m = n;
6690105197Ssam	}
6691105197Ssam
6692105197Ssam	/* align the mbuf chain so that extensions are in contiguous region. */
6693105197Ssam	error = key_align(m, &mh);
6694105197Ssam	if (error)
6695105197Ssam		return error;
6696105197Ssam
6697105197Ssam	if (m->m_next) {	/*XXX*/
6698105197Ssam		m_freem(m);
6699105197Ssam		return ENOBUFS;
6700105197Ssam	}
6701105197Ssam
6702105197Ssam	msg = mh.msg;
6703105197Ssam
6704105197Ssam	/* check SA type */
6705105197Ssam	switch (msg->sadb_msg_satype) {
6706105197Ssam	case SADB_SATYPE_UNSPEC:
6707105197Ssam		switch (msg->sadb_msg_type) {
6708105197Ssam		case SADB_GETSPI:
6709105197Ssam		case SADB_UPDATE:
6710105197Ssam		case SADB_ADD:
6711105197Ssam		case SADB_DELETE:
6712105197Ssam		case SADB_GET:
6713105197Ssam		case SADB_ACQUIRE:
6714105197Ssam		case SADB_EXPIRE:
6715105197Ssam			ipseclog((LOG_DEBUG, "key_parse: must specify satype "
6716105197Ssam			    "when msg type=%u.\n", msg->sadb_msg_type));
6717105197Ssam			pfkeystat.out_invsatype++;
6718105197Ssam			error = EINVAL;
6719105197Ssam			goto senderror;
6720105197Ssam		}
6721105197Ssam		break;
6722105197Ssam	case SADB_SATYPE_AH:
6723105197Ssam	case SADB_SATYPE_ESP:
6724105197Ssam	case SADB_X_SATYPE_IPCOMP:
6725105197Ssam		switch (msg->sadb_msg_type) {
6726105197Ssam		case SADB_X_SPDADD:
6727105197Ssam		case SADB_X_SPDDELETE:
6728105197Ssam		case SADB_X_SPDGET:
6729105197Ssam		case SADB_X_SPDDUMP:
6730105197Ssam		case SADB_X_SPDFLUSH:
6731105197Ssam		case SADB_X_SPDSETIDX:
6732105197Ssam		case SADB_X_SPDUPDATE:
6733105197Ssam		case SADB_X_SPDDELETE2:
6734105197Ssam			ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
6735105197Ssam			    msg->sadb_msg_type));
6736105197Ssam			pfkeystat.out_invsatype++;
6737105197Ssam			error = EINVAL;
6738105197Ssam			goto senderror;
6739105197Ssam		}
6740105197Ssam		break;
6741105197Ssam	case SADB_SATYPE_RSVP:
6742105197Ssam	case SADB_SATYPE_OSPFV2:
6743105197Ssam	case SADB_SATYPE_RIPV2:
6744105197Ssam	case SADB_SATYPE_MIP:
6745105197Ssam		ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
6746105197Ssam		    msg->sadb_msg_satype));
6747105197Ssam		pfkeystat.out_invsatype++;
6748105197Ssam		error = EOPNOTSUPP;
6749105197Ssam		goto senderror;
6750105197Ssam	case 1:	/* XXX: What does it do? */
6751105197Ssam		if (msg->sadb_msg_type == SADB_X_PROMISC)
6752105197Ssam			break;
6753105197Ssam		/*FALLTHROUGH*/
6754105197Ssam	default:
6755105197Ssam		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6756105197Ssam		    msg->sadb_msg_satype));
6757105197Ssam		pfkeystat.out_invsatype++;
6758105197Ssam		error = EINVAL;
6759105197Ssam		goto senderror;
6760105197Ssam	}
6761105197Ssam
6762105197Ssam	/* check field of upper layer protocol and address family */
6763105197Ssam	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6764105197Ssam	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6765105197Ssam		struct sadb_address *src0, *dst0;
6766105197Ssam		u_int plen;
6767105197Ssam
6768105197Ssam		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6769105197Ssam		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6770105197Ssam
6771105197Ssam		/* check upper layer protocol */
6772105197Ssam		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6773105197Ssam			ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
6774105197Ssam			pfkeystat.out_invaddr++;
6775105197Ssam			error = EINVAL;
6776105197Ssam			goto senderror;
6777105197Ssam		}
6778105197Ssam
6779105197Ssam		/* check family */
6780105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6781105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
6782105197Ssam			ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
6783105197Ssam			pfkeystat.out_invaddr++;
6784105197Ssam			error = EINVAL;
6785105197Ssam			goto senderror;
6786105197Ssam		}
6787105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6788105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
6789105197Ssam			ipseclog((LOG_DEBUG,
6790105197Ssam			    "key_parse: address struct size mismatched.\n"));
6791105197Ssam			pfkeystat.out_invaddr++;
6792105197Ssam			error = EINVAL;
6793105197Ssam			goto senderror;
6794105197Ssam		}
6795105197Ssam
6796105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6797105197Ssam		case AF_INET:
6798105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6799105197Ssam			    sizeof(struct sockaddr_in)) {
6800105197Ssam				pfkeystat.out_invaddr++;
6801105197Ssam				error = EINVAL;
6802105197Ssam				goto senderror;
6803105197Ssam			}
6804105197Ssam			break;
6805105197Ssam		case AF_INET6:
6806105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6807105197Ssam			    sizeof(struct sockaddr_in6)) {
6808105197Ssam				pfkeystat.out_invaddr++;
6809105197Ssam				error = EINVAL;
6810105197Ssam				goto senderror;
6811105197Ssam			}
6812105197Ssam			break;
6813105197Ssam		default:
6814105197Ssam			ipseclog((LOG_DEBUG,
6815105197Ssam			    "key_parse: unsupported address family.\n"));
6816105197Ssam			pfkeystat.out_invaddr++;
6817105197Ssam			error = EAFNOSUPPORT;
6818105197Ssam			goto senderror;
6819105197Ssam		}
6820105197Ssam
6821105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6822105197Ssam		case AF_INET:
6823105197Ssam			plen = sizeof(struct in_addr) << 3;
6824105197Ssam			break;
6825105197Ssam		case AF_INET6:
6826105197Ssam			plen = sizeof(struct in6_addr) << 3;
6827105197Ssam			break;
6828105197Ssam		default:
6829105197Ssam			plen = 0;	/*fool gcc*/
6830105197Ssam			break;
6831105197Ssam		}
6832105197Ssam
6833105197Ssam		/* check max prefix length */
6834105197Ssam		if (src0->sadb_address_prefixlen > plen ||
6835105197Ssam		    dst0->sadb_address_prefixlen > plen) {
6836105197Ssam			ipseclog((LOG_DEBUG,
6837105197Ssam			    "key_parse: illegal prefixlen.\n"));
6838105197Ssam			pfkeystat.out_invaddr++;
6839105197Ssam			error = EINVAL;
6840105197Ssam			goto senderror;
6841105197Ssam		}
6842105197Ssam
6843105197Ssam		/*
6844105197Ssam		 * prefixlen == 0 is valid because there can be a case when
6845105197Ssam		 * all addresses are matched.
6846105197Ssam		 */
6847105197Ssam	}
6848105197Ssam
6849105197Ssam	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
6850105197Ssam	    key_typesw[msg->sadb_msg_type] == NULL) {
6851105197Ssam		pfkeystat.out_invmsgtype++;
6852105197Ssam		error = EINVAL;
6853105197Ssam		goto senderror;
6854105197Ssam	}
6855105197Ssam
6856105197Ssam	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6857105197Ssam
6858105197Ssamsenderror:
6859105197Ssam	msg->sadb_msg_errno = error;
6860105197Ssam	return key_sendup_mbuf(so, m, target);
6861105197Ssam}
6862105197Ssam
6863105197Ssamstatic int
6864105197Ssamkey_senderror(so, m, code)
6865105197Ssam	struct socket *so;
6866105197Ssam	struct mbuf *m;
6867105197Ssam	int code;
6868105197Ssam{
6869105197Ssam	struct sadb_msg *msg;
6870105197Ssam
6871105197Ssam	if (m->m_len < sizeof(struct sadb_msg))
6872105197Ssam		panic("invalid mbuf passed to key_senderror");
6873105197Ssam
6874105197Ssam	msg = mtod(m, struct sadb_msg *);
6875105197Ssam	msg->sadb_msg_errno = code;
6876105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
6877105197Ssam}
6878105197Ssam
6879105197Ssam/*
6880105197Ssam * set the pointer to each header into message buffer.
6881105197Ssam * m will be freed on error.
6882105197Ssam * XXX larger-than-MCLBYTES extension?
6883105197Ssam */
6884105197Ssamstatic int
6885105197Ssamkey_align(m, mhp)
6886105197Ssam	struct mbuf *m;
6887105197Ssam	struct sadb_msghdr *mhp;
6888105197Ssam{
6889105197Ssam	struct mbuf *n;
6890105197Ssam	struct sadb_ext *ext;
6891105197Ssam	size_t off, end;
6892105197Ssam	int extlen;
6893105197Ssam	int toff;
6894105197Ssam
6895105197Ssam	/* sanity check */
6896105197Ssam	if (m == NULL || mhp == NULL)
6897105197Ssam		panic("key_align: NULL pointer is passed.\n");
6898105197Ssam	if (m->m_len < sizeof(struct sadb_msg))
6899105197Ssam		panic("invalid mbuf passed to key_align");
6900105197Ssam
6901105197Ssam	/* initialize */
6902105197Ssam	bzero(mhp, sizeof(*mhp));
6903105197Ssam
6904105197Ssam	mhp->msg = mtod(m, struct sadb_msg *);
6905105197Ssam	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
6906105197Ssam
6907105197Ssam	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6908105197Ssam	extlen = end;	/*just in case extlen is not updated*/
6909105197Ssam	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
6910105197Ssam		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
6911105197Ssam		if (!n) {
6912105197Ssam			/* m is already freed */
6913105197Ssam			return ENOBUFS;
6914105197Ssam		}
6915105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6916105197Ssam
6917105197Ssam		/* set pointer */
6918105197Ssam		switch (ext->sadb_ext_type) {
6919105197Ssam		case SADB_EXT_SA:
6920105197Ssam		case SADB_EXT_ADDRESS_SRC:
6921105197Ssam		case SADB_EXT_ADDRESS_DST:
6922105197Ssam		case SADB_EXT_ADDRESS_PROXY:
6923105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
6924105197Ssam		case SADB_EXT_LIFETIME_HARD:
6925105197Ssam		case SADB_EXT_LIFETIME_SOFT:
6926105197Ssam		case SADB_EXT_KEY_AUTH:
6927105197Ssam		case SADB_EXT_KEY_ENCRYPT:
6928105197Ssam		case SADB_EXT_IDENTITY_SRC:
6929105197Ssam		case SADB_EXT_IDENTITY_DST:
6930105197Ssam		case SADB_EXT_SENSITIVITY:
6931105197Ssam		case SADB_EXT_PROPOSAL:
6932105197Ssam		case SADB_EXT_SUPPORTED_AUTH:
6933105197Ssam		case SADB_EXT_SUPPORTED_ENCRYPT:
6934105197Ssam		case SADB_EXT_SPIRANGE:
6935105197Ssam		case SADB_X_EXT_POLICY:
6936105197Ssam		case SADB_X_EXT_SA2:
6937105197Ssam			/* duplicate check */
6938105197Ssam			/*
6939105197Ssam			 * XXX Are there duplication payloads of either
6940105197Ssam			 * KEY_AUTH or KEY_ENCRYPT ?
6941105197Ssam			 */
6942105197Ssam			if (mhp->ext[ext->sadb_ext_type] != NULL) {
6943105197Ssam				ipseclog((LOG_DEBUG,
6944105197Ssam				    "key_align: duplicate ext_type %u "
6945105197Ssam				    "is passed.\n", ext->sadb_ext_type));
6946105197Ssam				m_freem(m);
6947105197Ssam				pfkeystat.out_dupext++;
6948105197Ssam				return EINVAL;
6949105197Ssam			}
6950105197Ssam			break;
6951105197Ssam		default:
6952105197Ssam			ipseclog((LOG_DEBUG,
6953105197Ssam			    "key_align: invalid ext_type %u is passed.\n",
6954105197Ssam			    ext->sadb_ext_type));
6955105197Ssam			m_freem(m);
6956105197Ssam			pfkeystat.out_invexttype++;
6957105197Ssam			return EINVAL;
6958105197Ssam		}
6959105197Ssam
6960105197Ssam		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
6961105197Ssam
6962105197Ssam		if (key_validate_ext(ext, extlen)) {
6963105197Ssam			m_freem(m);
6964105197Ssam			pfkeystat.out_invlen++;
6965105197Ssam			return EINVAL;
6966105197Ssam		}
6967105197Ssam
6968105197Ssam		n = m_pulldown(m, off, extlen, &toff);
6969105197Ssam		if (!n) {
6970105197Ssam			/* m is already freed */
6971105197Ssam			return ENOBUFS;
6972105197Ssam		}
6973105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6974105197Ssam
6975105197Ssam		mhp->ext[ext->sadb_ext_type] = ext;
6976105197Ssam		mhp->extoff[ext->sadb_ext_type] = off;
6977105197Ssam		mhp->extlen[ext->sadb_ext_type] = extlen;
6978105197Ssam	}
6979105197Ssam
6980105197Ssam	if (off != end) {
6981105197Ssam		m_freem(m);
6982105197Ssam		pfkeystat.out_invlen++;
6983105197Ssam		return EINVAL;
6984105197Ssam	}
6985105197Ssam
6986105197Ssam	return 0;
6987105197Ssam}
6988105197Ssam
6989105197Ssamstatic int
6990105197Ssamkey_validate_ext(ext, len)
6991105197Ssam	const struct sadb_ext *ext;
6992105197Ssam	int len;
6993105197Ssam{
6994105197Ssam	const struct sockaddr *sa;
6995105197Ssam	enum { NONE, ADDR } checktype = NONE;
6996105197Ssam	int baselen = 0;
6997105197Ssam	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
6998105197Ssam
6999105197Ssam	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7000105197Ssam		return EINVAL;
7001105197Ssam
7002105197Ssam	/* if it does not match minimum/maximum length, bail */
7003105197Ssam	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7004105197Ssam	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7005105197Ssam		return EINVAL;
7006105197Ssam	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7007105197Ssam		return EINVAL;
7008105197Ssam	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7009105197Ssam		return EINVAL;
7010105197Ssam
7011105197Ssam	/* more checks based on sadb_ext_type XXX need more */
7012105197Ssam	switch (ext->sadb_ext_type) {
7013105197Ssam	case SADB_EXT_ADDRESS_SRC:
7014105197Ssam	case SADB_EXT_ADDRESS_DST:
7015105197Ssam	case SADB_EXT_ADDRESS_PROXY:
7016105197Ssam		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7017105197Ssam		checktype = ADDR;
7018105197Ssam		break;
7019105197Ssam	case SADB_EXT_IDENTITY_SRC:
7020105197Ssam	case SADB_EXT_IDENTITY_DST:
7021105197Ssam		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7022105197Ssam		    SADB_X_IDENTTYPE_ADDR) {
7023105197Ssam			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7024105197Ssam			checktype = ADDR;
7025105197Ssam		} else
7026105197Ssam			checktype = NONE;
7027105197Ssam		break;
7028105197Ssam	default:
7029105197Ssam		checktype = NONE;
7030105197Ssam		break;
7031105197Ssam	}
7032105197Ssam
7033105197Ssam	switch (checktype) {
7034105197Ssam	case NONE:
7035105197Ssam		break;
7036105197Ssam	case ADDR:
7037105197Ssam		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7038105197Ssam		if (len < baselen + sal)
7039105197Ssam			return EINVAL;
7040105197Ssam		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7041105197Ssam			return EINVAL;
7042105197Ssam		break;
7043105197Ssam	}
7044105197Ssam
7045105197Ssam	return 0;
7046105197Ssam}
7047105197Ssam
7048105197Ssamvoid
7049105197Ssamkey_init()
7050105197Ssam{
7051105197Ssam	int i;
7052105197Ssam
7053105197Ssam	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7054105197Ssam		LIST_INIT(&sptree[i]);
7055105197Ssam	}
7056105197Ssam
7057105197Ssam	LIST_INIT(&sahtree);
7058105197Ssam
7059105197Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7060105197Ssam		LIST_INIT(&regtree[i]);
7061105197Ssam	}
7062105197Ssam
7063105197Ssam#ifndef IPSEC_NONBLOCK_ACQUIRE
7064105197Ssam	LIST_INIT(&acqtree);
7065105197Ssam#endif
7066105197Ssam	LIST_INIT(&spacqtree);
7067105197Ssam
7068105197Ssam	/* system default */
7069105197Ssam	ip4_def_policy.policy = IPSEC_POLICY_NONE;
7070105197Ssam	ip4_def_policy.refcnt++;	/*never reclaim this*/
7071105197Ssam
7072105197Ssam#ifndef IPSEC_DEBUG2
7073105197Ssam	timeout((void *)key_timehandler, (void *)0, hz);
7074105197Ssam#endif /*IPSEC_DEBUG2*/
7075105197Ssam
7076105197Ssam	/* initialize key statistics */
7077105197Ssam	keystat.getspi_count = 1;
7078105197Ssam
7079105197Ssam	printf("IPsec: Initialized Security Association Processing.\n");
7080105197Ssam
7081105197Ssam	return;
7082105197Ssam}
7083105197Ssam
7084105197Ssam/*
7085105197Ssam * XXX: maybe This function is called after INBOUND IPsec processing.
7086105197Ssam *
7087105197Ssam * Special check for tunnel-mode packets.
7088105197Ssam * We must make some checks for consistency between inner and outer IP header.
7089105197Ssam *
7090105197Ssam * xxx more checks to be provided
7091105197Ssam */
7092105197Ssamint
7093105197Ssamkey_checktunnelsanity(sav, family, src, dst)
7094105197Ssam	struct secasvar *sav;
7095105197Ssam	u_int family;
7096105197Ssam	caddr_t src;
7097105197Ssam	caddr_t dst;
7098105197Ssam{
7099105197Ssam	/* sanity check */
7100105197Ssam	if (sav->sah == NULL)
7101105197Ssam		panic("sav->sah == NULL at key_checktunnelsanity");
7102105197Ssam
7103105197Ssam	/* XXX: check inner IP header */
7104105197Ssam
7105105197Ssam	return 1;
7106105197Ssam}
7107105197Ssam
7108105197Ssam#if 0
7109105197Ssam#define hostnamelen	strlen(hostname)
7110105197Ssam
7111105197Ssam/*
7112105197Ssam * Get FQDN for the host.
7113105197Ssam * If the administrator configured hostname (by hostname(1)) without
7114105197Ssam * domain name, returns nothing.
7115105197Ssam */
7116105197Ssamstatic const char *
7117105197Ssamkey_getfqdn()
7118105197Ssam{
7119105197Ssam	int i;
7120105197Ssam	int hasdot;
7121105197Ssam	static char fqdn[MAXHOSTNAMELEN + 1];
7122105197Ssam
7123105197Ssam	if (!hostnamelen)
7124105197Ssam		return NULL;
7125105197Ssam
7126105197Ssam	/* check if it comes with domain name. */
7127105197Ssam	hasdot = 0;
7128105197Ssam	for (i = 0; i < hostnamelen; i++) {
7129105197Ssam		if (hostname[i] == '.')
7130105197Ssam			hasdot++;
7131105197Ssam	}
7132105197Ssam	if (!hasdot)
7133105197Ssam		return NULL;
7134105197Ssam
7135105197Ssam	/* NOTE: hostname may not be NUL-terminated. */
7136105197Ssam	bzero(fqdn, sizeof(fqdn));
7137105197Ssam	bcopy(hostname, fqdn, hostnamelen);
7138105197Ssam	fqdn[hostnamelen] = '\0';
7139105197Ssam	return fqdn;
7140105197Ssam}
7141105197Ssam
7142105197Ssam/*
7143105197Ssam * get username@FQDN for the host/user.
7144105197Ssam */
7145105197Ssamstatic const char *
7146105197Ssamkey_getuserfqdn()
7147105197Ssam{
7148105197Ssam	const char *host;
7149105197Ssam	static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
7150105197Ssam	struct proc *p = curproc;
7151105197Ssam	char *q;
7152105197Ssam
7153105197Ssam	if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
7154105197Ssam		return NULL;
7155105197Ssam	if (!(host = key_getfqdn()))
7156105197Ssam		return NULL;
7157105197Ssam
7158105197Ssam	/* NOTE: s_login may not be-NUL terminated. */
7159105197Ssam	bzero(userfqdn, sizeof(userfqdn));
7160105197Ssam	bcopy(p->p_pgrp->pg_session->s_login, userfqdn, MAXLOGNAME);
7161105197Ssam	userfqdn[MAXLOGNAME] = '\0';	/* safeguard */
7162105197Ssam	q = userfqdn + strlen(userfqdn);
7163105197Ssam	*q++ = '@';
7164105197Ssam	bcopy(host, q, strlen(host));
7165105197Ssam	q += strlen(host);
7166105197Ssam	*q++ = '\0';
7167105197Ssam
7168105197Ssam	return userfqdn;
7169105197Ssam}
7170105197Ssam#endif
7171105197Ssam
7172105197Ssam/* record data transfer on SA, and update timestamps */
7173105197Ssamvoid
7174105197Ssamkey_sa_recordxfer(sav, m)
7175105197Ssam	struct secasvar *sav;
7176105197Ssam	struct mbuf *m;
7177105197Ssam{
7178105197Ssam	KASSERT(sav != NULL, ("key_sa_recordxfer: Null secasvar"));
7179105197Ssam	KASSERT(m != NULL, ("key_sa_recordxfer: Null mbuf"));
7180105197Ssam	if (!sav->lft_c)
7181105197Ssam		return;
7182105197Ssam
7183105197Ssam	/*
7184105197Ssam	 * XXX Currently, there is a difference of bytes size
7185105197Ssam	 * between inbound and outbound processing.
7186105197Ssam	 */
7187105197Ssam	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
7188105197Ssam	/* to check bytes lifetime is done in key_timehandler(). */
7189105197Ssam
7190105197Ssam	/*
7191105197Ssam	 * We use the number of packets as the unit of
7192105197Ssam	 * sadb_lifetime_allocations.  We increment the variable
7193105197Ssam	 * whenever {esp,ah}_{in,out}put is called.
7194105197Ssam	 */
7195105197Ssam	sav->lft_c->sadb_lifetime_allocations++;
7196105197Ssam	/* XXX check for expires? */
7197105197Ssam
7198105197Ssam	/*
7199105197Ssam	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
7200105197Ssam	 * in seconds.  HARD and SOFT lifetime are measured by the time
7201105197Ssam	 * difference (again in seconds) from sadb_lifetime_usetime.
7202105197Ssam	 *
7203105197Ssam	 *	usetime
7204105197Ssam	 *	v     expire   expire
7205105197Ssam	 * -----+-----+--------+---> t
7206105197Ssam	 *	<--------------> HARD
7207105197Ssam	 *	<-----> SOFT
7208105197Ssam	 */
7209105197Ssam	sav->lft_c->sadb_lifetime_usetime = time_second;
7210105197Ssam	/* XXX check for expires? */
7211105197Ssam
7212105197Ssam	return;
7213105197Ssam}
7214105197Ssam
7215105197Ssam/* dumb version */
7216105197Ssamvoid
7217105197Ssamkey_sa_routechange(dst)
7218105197Ssam	struct sockaddr *dst;
7219105197Ssam{
7220105197Ssam	struct secashead *sah;
7221105197Ssam	struct route *ro;
7222105197Ssam
7223105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
7224105197Ssam		ro = &sah->sa_route;
7225105197Ssam		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7226105197Ssam		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7227105197Ssam			RTFREE(ro->ro_rt);
7228105197Ssam			ro->ro_rt = (struct rtentry *)NULL;
7229105197Ssam		}
7230105197Ssam	}
7231105197Ssam
7232105197Ssam	return;
7233105197Ssam}
7234105197Ssam
7235105197Ssamstatic void
7236105197Ssamkey_sa_chgstate(sav, state)
7237105197Ssam	struct secasvar *sav;
7238105197Ssam	u_int8_t state;
7239105197Ssam{
7240105197Ssam	if (sav == NULL)
7241105197Ssam		panic("key_sa_chgstate called with sav == NULL");
7242105197Ssam
7243105197Ssam	if (sav->state == state)
7244105197Ssam		return;
7245105197Ssam
7246105197Ssam	if (__LIST_CHAINED(sav))
7247105197Ssam		LIST_REMOVE(sav, chain);
7248105197Ssam
7249105197Ssam	sav->state = state;
7250105197Ssam	LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7251105197Ssam}
7252105197Ssam
7253105197Ssamvoid
7254105197Ssamkey_sa_stir_iv(sav)
7255105197Ssam	struct secasvar *sav;
7256105197Ssam{
7257105197Ssam
7258105197Ssam	if (!sav->iv)
7259105197Ssam		panic("key_sa_stir_iv called with sav == NULL");
7260105197Ssam	key_randomfill(sav->iv, sav->ivlen);
7261105197Ssam}
7262105197Ssam
7263105197Ssam/* XXX too much? */
7264105197Ssamstatic struct mbuf *
7265105197Ssamkey_alloc_mbuf(l)
7266105197Ssam	int l;
7267105197Ssam{
7268105197Ssam	struct mbuf *m = NULL, *n;
7269105197Ssam	int len, t;
7270105197Ssam
7271105197Ssam	len = l;
7272105197Ssam	while (len > 0) {
7273111119Simp		MGET(n, M_DONTWAIT, MT_DATA);
7274105197Ssam		if (n && len > MLEN)
7275111119Simp			MCLGET(n, M_DONTWAIT);
7276105197Ssam		if (!n) {
7277105197Ssam			m_freem(m);
7278105197Ssam			return NULL;
7279105197Ssam		}
7280105197Ssam
7281105197Ssam		n->m_next = NULL;
7282105197Ssam		n->m_len = 0;
7283105197Ssam		n->m_len = M_TRAILINGSPACE(n);
7284105197Ssam		/* use the bottom of mbuf, hoping we can prepend afterwards */
7285105197Ssam		if (n->m_len > len) {
7286105197Ssam			t = (n->m_len - len) & ~(sizeof(long) - 1);
7287105197Ssam			n->m_data += t;
7288105197Ssam			n->m_len = len;
7289105197Ssam		}
7290105197Ssam
7291105197Ssam		len -= n->m_len;
7292105197Ssam
7293105197Ssam		if (m)
7294105197Ssam			m_cat(m, n);
7295105197Ssam		else
7296105197Ssam			m = n;
7297105197Ssam	}
7298105197Ssam
7299105197Ssam	return m;
7300105197Ssam}
7301