key.c revision 125876
1105197Ssam/*	$FreeBSD: head/sys/netipsec/key.c 125876 2004-02-16 17:09:53Z guido $	*/
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>
45119643Ssam#include <sys/lock.h>
46119643Ssam#include <sys/mutex.h>
47105197Ssam#include <sys/mbuf.h>
48105197Ssam#include <sys/domain.h>
49105197Ssam#include <sys/protosw.h>
50105197Ssam#include <sys/malloc.h>
51105197Ssam#include <sys/socket.h>
52105197Ssam#include <sys/socketvar.h>
53105197Ssam#include <sys/sysctl.h>
54105197Ssam#include <sys/errno.h>
55105197Ssam#include <sys/proc.h>
56105197Ssam#include <sys/queue.h>
57105197Ssam#include <sys/syslog.h>
58105197Ssam
59105197Ssam#include <net/if.h>
60105197Ssam#include <net/route.h>
61105197Ssam#include <net/raw_cb.h>
62105197Ssam
63105197Ssam#include <netinet/in.h>
64105197Ssam#include <netinet/in_systm.h>
65105197Ssam#include <netinet/ip.h>
66105197Ssam#include <netinet/in_var.h>
67105197Ssam
68105197Ssam#ifdef INET6
69105197Ssam#include <netinet/ip6.h>
70105197Ssam#include <netinet6/in6_var.h>
71105197Ssam#include <netinet6/ip6_var.h>
72105197Ssam#endif /* INET6 */
73105197Ssam
74105197Ssam#ifdef INET
75105197Ssam#include <netinet/in_pcb.h>
76105197Ssam#endif
77105197Ssam#ifdef INET6
78105197Ssam#include <netinet6/in6_pcb.h>
79105197Ssam#endif /* INET6 */
80105197Ssam
81105197Ssam#include <net/pfkeyv2.h>
82105197Ssam#include <netipsec/keydb.h>
83105197Ssam#include <netipsec/key.h>
84105197Ssam#include <netipsec/keysock.h>
85105197Ssam#include <netipsec/key_debug.h>
86105197Ssam
87105197Ssam#include <netipsec/ipsec.h>
88105197Ssam#ifdef INET6
89105197Ssam#include <netipsec/ipsec6.h>
90105197Ssam#endif
91105197Ssam
92105197Ssam#include <netipsec/xform.h>
93105197Ssam
94105197Ssam#include <machine/stdarg.h>
95105197Ssam
96105197Ssam/* randomness */
97105197Ssam#include <sys/random.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.*/
122125876Sguidostatic int key_preferred_oldsa = 1;	/* preferred old sa rather than new sa.*/
123105197Ssam
124105197Ssamstatic u_int32_t acq_seq = 0;
125105197Ssam
126105197Ssamstatic LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];	/* SPD */
127119643Ssamstatic struct mtx sptree_lock;
128120585Ssam#define	SPTREE_LOCK_INIT() \
129120585Ssam	mtx_init(&sptree_lock, "sptree", \
130120585Ssam		"fast ipsec security policy database", MTX_DEF)
131120585Ssam#define	SPTREE_LOCK_DESTROY()	mtx_destroy(&sptree_lock)
132120585Ssam#define	SPTREE_LOCK()		mtx_lock(&sptree_lock)
133120585Ssam#define	SPTREE_UNLOCK()	mtx_unlock(&sptree_lock)
134120585Ssam#define	SPTREE_LOCK_ASSERT()	mtx_assert(&sptree_lock, MA_OWNED)
135120585Ssam
136105197Ssamstatic LIST_HEAD(_sahtree, secashead) sahtree;			/* SAD */
137119643Ssamstatic struct mtx sahtree_lock;
138120585Ssam#define	SAHTREE_LOCK_INIT() \
139120585Ssam	mtx_init(&sahtree_lock, "sahtree", \
140120585Ssam		"fast ipsec security association database", MTX_DEF)
141120585Ssam#define	SAHTREE_LOCK_DESTROY()	mtx_destroy(&sahtree_lock)
142120585Ssam#define	SAHTREE_LOCK()		mtx_lock(&sahtree_lock)
143120585Ssam#define	SAHTREE_UNLOCK()	mtx_unlock(&sahtree_lock)
144120585Ssam#define	SAHTREE_LOCK_ASSERT()	mtx_assert(&sahtree_lock, MA_OWNED)
145120585Ssam
146119643Ssam							/* registed list */
147105197Ssamstatic LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
148119643Ssamstatic struct mtx regtree_lock;
149120585Ssam#define	REGTREE_LOCK_INIT() \
150120585Ssam	mtx_init(&regtree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
151120585Ssam#define	REGTREE_LOCK_DESTROY()	mtx_destroy(&regtree_lock)
152120585Ssam#define	REGTREE_LOCK()		mtx_lock(&regtree_lock)
153120585Ssam#define	REGTREE_UNLOCK()	mtx_unlock(&regtree_lock)
154120585Ssam#define	REGTREE_LOCK_ASSERT()	mtx_assert(&regtree_lock, MA_OWNED)
155120585Ssam
156105197Ssamstatic LIST_HEAD(_acqtree, secacq) acqtree;		/* acquiring list */
157119643Ssamstatic struct mtx acq_lock;
158120585Ssam#define	ACQ_LOCK_INIT() \
159120585Ssam	mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
160120585Ssam#define	ACQ_LOCK_DESTROY()	mtx_destroy(&acq_lock)
161120585Ssam#define	ACQ_LOCK()		mtx_lock(&acq_lock)
162120585Ssam#define	ACQ_UNLOCK()		mtx_unlock(&acq_lock)
163120585Ssam#define	ACQ_LOCK_ASSERT()	mtx_assert(&acq_lock, MA_OWNED)
164120585Ssam
165105197Ssamstatic LIST_HEAD(_spacqtree, secspacq) spacqtree;	/* SP acquiring list */
166119643Ssamstatic struct mtx spacq_lock;
167120585Ssam#define	SPACQ_LOCK_INIT() \
168120585Ssam	mtx_init(&spacq_lock, "spacqtree", \
169120585Ssam		"fast ipsec security policy acquire list", MTX_DEF)
170120585Ssam#define	SPACQ_LOCK_DESTROY()	mtx_destroy(&spacq_lock)
171120585Ssam#define	SPACQ_LOCK()		mtx_lock(&spacq_lock)
172120585Ssam#define	SPACQ_UNLOCK()		mtx_unlock(&spacq_lock)
173120585Ssam#define	SPACQ_LOCK_ASSERT()	mtx_assert(&spacq_lock, MA_OWNED)
174105197Ssam
175105197Ssam/* search order for SAs */
176105197Ssamstatic u_int saorder_state_valid[] = {
177105197Ssam	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
178105197Ssam	/*
179108533Sschweikh	 * This order is important because we must select the oldest SA
180105197Ssam	 * for outbound processing.  For inbound, This is not important.
181105197Ssam	 */
182105197Ssam};
183105197Ssamstatic u_int saorder_state_alive[] = {
184105197Ssam	/* except DEAD */
185105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
186105197Ssam};
187105197Ssamstatic u_int saorder_state_any[] = {
188105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
189105197Ssam	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
190105197Ssam};
191105197Ssam
192105197Ssamstatic const int minsize[] = {
193105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
194105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
195105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
196105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
197105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
198105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
199105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
200105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
201105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
202105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
203105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
204105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
205105197Ssam	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
206105197Ssam	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
207105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
208105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
209105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
210105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
211105197Ssam	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
212105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
213105197Ssam};
214105197Ssamstatic const int maxsize[] = {
215105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
216105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
217105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
218105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
219105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
220105197Ssam	0,				/* SADB_EXT_ADDRESS_SRC */
221105197Ssam	0,				/* SADB_EXT_ADDRESS_DST */
222105197Ssam	0,				/* SADB_EXT_ADDRESS_PROXY */
223105197Ssam	0,				/* SADB_EXT_KEY_AUTH */
224105197Ssam	0,				/* SADB_EXT_KEY_ENCRYPT */
225105197Ssam	0,				/* SADB_EXT_IDENTITY_SRC */
226105197Ssam	0,				/* SADB_EXT_IDENTITY_DST */
227105197Ssam	0,				/* SADB_EXT_SENSITIVITY */
228105197Ssam	0,				/* SADB_EXT_PROPOSAL */
229105197Ssam	0,				/* SADB_EXT_SUPPORTED_AUTH */
230105197Ssam	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
231105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
232105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
233105197Ssam	0,				/* SADB_X_EXT_POLICY */
234105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
235105197Ssam};
236105197Ssam
237105197Ssamstatic int ipsec_esp_keymin = 256;
238105197Ssamstatic int ipsec_esp_auth = 0;
239105197Ssamstatic int ipsec_ah_keymin = 128;
240105197Ssam
241105197Ssam#ifdef SYSCTL_DECL
242105197SsamSYSCTL_DECL(_net_key);
243105197Ssam#endif
244105197Ssam
245105197SsamSYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,	CTLFLAG_RW, \
246105197Ssam	&key_debug_level,	0,	"");
247105197Ssam
248105197Ssam/* max count of trial for the decision of spi value */
249105197SsamSYSCTL_INT(_net_key, KEYCTL_SPI_TRY,		spi_trycnt,	CTLFLAG_RW, \
250105197Ssam	&key_spi_trycnt,	0,	"");
251105197Ssam
252105197Ssam/* minimum spi value to allocate automatically. */
253105197SsamSYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,	spi_minval,	CTLFLAG_RW, \
254105197Ssam	&key_spi_minval,	0,	"");
255105197Ssam
256105197Ssam/* maximun spi value to allocate automatically. */
257105197SsamSYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,	spi_maxval,	CTLFLAG_RW, \
258105197Ssam	&key_spi_maxval,	0,	"");
259105197Ssam
260105197Ssam/* interval to initialize randseed */
261105197SsamSYSCTL_INT(_net_key, KEYCTL_RANDOM_INT,	int_random,	CTLFLAG_RW, \
262105197Ssam	&key_int_random,	0,	"");
263105197Ssam
264105197Ssam/* lifetime for larval SA */
265105197SsamSYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,	larval_lifetime, CTLFLAG_RW, \
266105197Ssam	&key_larval_lifetime,	0,	"");
267105197Ssam
268105197Ssam/* counter for blocking to send SADB_ACQUIRE to IKEd */
269105197SsamSYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,	blockacq_count,	CTLFLAG_RW, \
270105197Ssam	&key_blockacq_count,	0,	"");
271105197Ssam
272105197Ssam/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
273105197SsamSYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,	blockacq_lifetime, CTLFLAG_RW, \
274105197Ssam	&key_blockacq_lifetime,	0,	"");
275105197Ssam
276105197Ssam/* ESP auth */
277105197SsamSYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth, CTLFLAG_RW, \
278105197Ssam	&ipsec_esp_auth,	0,	"");
279105197Ssam
280105197Ssam/* minimum ESP key length */
281105197SsamSYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN,	esp_keymin, CTLFLAG_RW, \
282105197Ssam	&ipsec_esp_keymin,	0,	"");
283105197Ssam
284105197Ssam/* minimum AH key length */
285105197SsamSYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin, CTLFLAG_RW, \
286105197Ssam	&ipsec_ah_keymin,	0,	"");
287105197Ssam
288105197Ssam/* perfered old SA rather than new SA */
289125876SguidoSYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,	preferred_oldsa, CTLFLAG_RW,\
290125876Sguido	&key_preferred_oldsa,	0,	"");
291105197Ssam
292105197Ssam#define __LIST_CHAINED(elm) \
293105197Ssam	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
294105197Ssam#define LIST_INSERT_TAIL(head, elm, type, field) \
295105197Ssamdo {\
296105197Ssam	struct type *curelm = LIST_FIRST(head); \
297105197Ssam	if (curelm == NULL) {\
298105197Ssam		LIST_INSERT_HEAD(head, elm, field); \
299105197Ssam	} else { \
300105197Ssam		while (LIST_NEXT(curelm, field)) \
301105197Ssam			curelm = LIST_NEXT(curelm, field);\
302105197Ssam		LIST_INSERT_AFTER(curelm, elm, field);\
303105197Ssam	}\
304105197Ssam} while (0)
305105197Ssam
306105197Ssam#define KEY_CHKSASTATE(head, sav, name) \
307105197Ssamdo { \
308105197Ssam	if ((head) != (sav)) {						\
309105197Ssam		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
310105197Ssam			(name), (head), (sav)));			\
311105197Ssam		continue;						\
312105197Ssam	}								\
313105197Ssam} while (0)
314105197Ssam
315105197Ssam#define KEY_CHKSPDIR(head, sp, name) \
316105197Ssamdo { \
317105197Ssam	if ((head) != (sp)) {						\
318105197Ssam		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
319105197Ssam			"anyway continue.\n",				\
320105197Ssam			(name), (head), (sp)));				\
321105197Ssam	}								\
322105197Ssam} while (0)
323105197Ssam
324119643SsamMALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
325119643SsamMALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
326119643SsamMALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
327119643SsamMALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
328119643SsamMALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
329119643SsamMALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
330119643SsamMALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
331105197Ssam
332105197Ssam/*
333105197Ssam * set parameters into secpolicyindex buffer.
334105197Ssam * Must allocate secpolicyindex buffer passed to this function.
335105197Ssam */
336105197Ssam#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
337105197Ssamdo { \
338105197Ssam	bzero((idx), sizeof(struct secpolicyindex));                         \
339105197Ssam	(idx)->dir = (_dir);                                                 \
340105197Ssam	(idx)->prefs = (ps);                                                 \
341105197Ssam	(idx)->prefd = (pd);                                                 \
342105197Ssam	(idx)->ul_proto = (ulp);                                             \
343105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
344105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
345105197Ssam} while (0)
346105197Ssam
347105197Ssam/*
348105197Ssam * set parameters into secasindex buffer.
349105197Ssam * Must allocate secasindex buffer before calling this function.
350105197Ssam */
351105197Ssam#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
352105197Ssamdo { \
353105197Ssam	bzero((idx), sizeof(struct secasindex));                             \
354105197Ssam	(idx)->proto = (p);                                                  \
355105197Ssam	(idx)->mode = (m);                                                   \
356105197Ssam	(idx)->reqid = (r);                                                  \
357105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
358105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
359105197Ssam} while (0)
360105197Ssam
361105197Ssam/* key statistics */
362105197Ssamstruct _keystat {
363105197Ssam	u_long getspi_count; /* the avarage of count to try to get new SPI */
364105197Ssam} keystat;
365105197Ssam
366105197Ssamstruct sadb_msghdr {
367105197Ssam	struct sadb_msg *msg;
368105197Ssam	struct sadb_ext *ext[SADB_EXT_MAX + 1];
369105197Ssam	int extoff[SADB_EXT_MAX + 1];
370105197Ssam	int extlen[SADB_EXT_MAX + 1];
371105197Ssam};
372105197Ssam
373105197Ssamstatic struct secasvar *key_allocsa_policy __P((const struct secasindex *));
374105197Ssamstatic void key_freesp_so __P((struct secpolicy **));
375105197Ssamstatic struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
376105197Ssamstatic void key_delsp __P((struct secpolicy *));
377105197Ssamstatic struct secpolicy *key_getsp __P((struct secpolicyindex *));
378119643Ssamstatic void _key_delsp(struct secpolicy *sp);
379105197Ssamstatic struct secpolicy *key_getspbyid __P((u_int32_t));
380105197Ssamstatic u_int32_t key_newreqid __P((void));
381105197Ssamstatic struct mbuf *key_gather_mbuf __P((struct mbuf *,
382105197Ssam	const struct sadb_msghdr *, int, int, ...));
383105197Ssamstatic int key_spdadd __P((struct socket *, struct mbuf *,
384105197Ssam	const struct sadb_msghdr *));
385105197Ssamstatic u_int32_t key_getnewspid __P((void));
386105197Ssamstatic int key_spddelete __P((struct socket *, struct mbuf *,
387105197Ssam	const struct sadb_msghdr *));
388105197Ssamstatic int key_spddelete2 __P((struct socket *, struct mbuf *,
389105197Ssam	const struct sadb_msghdr *));
390105197Ssamstatic int key_spdget __P((struct socket *, struct mbuf *,
391105197Ssam	const struct sadb_msghdr *));
392105197Ssamstatic int key_spdflush __P((struct socket *, struct mbuf *,
393105197Ssam	const struct sadb_msghdr *));
394105197Ssamstatic int key_spddump __P((struct socket *, struct mbuf *,
395105197Ssam	const struct sadb_msghdr *));
396105197Ssamstatic struct mbuf *key_setdumpsp __P((struct secpolicy *,
397105197Ssam	u_int8_t, u_int32_t, u_int32_t));
398105197Ssamstatic u_int key_getspreqmsglen __P((struct secpolicy *));
399105197Ssamstatic int key_spdexpire __P((struct secpolicy *));
400105197Ssamstatic struct secashead *key_newsah __P((struct secasindex *));
401105197Ssamstatic void key_delsah __P((struct secashead *));
402105197Ssamstatic struct secasvar *key_newsav __P((struct mbuf *,
403105197Ssam	const struct sadb_msghdr *, struct secashead *, int *,
404105197Ssam	const char*, int));
405105197Ssam#define	KEY_NEWSAV(m, sadb, sah, e)				\
406105197Ssam	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
407105197Ssamstatic void key_delsav __P((struct secasvar *));
408105197Ssamstatic struct secashead *key_getsah __P((struct secasindex *));
409105197Ssamstatic struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
410105197Ssamstatic struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
411105197Ssamstatic int key_setsaval __P((struct secasvar *, struct mbuf *,
412105197Ssam	const struct sadb_msghdr *));
413105197Ssamstatic int key_mature __P((struct secasvar *));
414105197Ssamstatic struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
415105197Ssam	u_int8_t, u_int32_t, u_int32_t));
416105197Ssamstatic struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
417105197Ssam	u_int32_t, pid_t, u_int16_t));
418105197Ssamstatic struct mbuf *key_setsadbsa __P((struct secasvar *));
419105197Ssamstatic struct mbuf *key_setsadbaddr __P((u_int16_t,
420105197Ssam	const struct sockaddr *, u_int8_t, u_int16_t));
421105197Ssamstatic struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
422105197Ssamstatic struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
423105197Ssam	u_int32_t));
424119643Ssamstatic void *key_dup(const void *, u_int, struct malloc_type *);
425105197Ssam#ifdef INET6
426105197Ssamstatic int key_ismyaddr6 __P((struct sockaddr_in6 *));
427105197Ssam#endif
428105197Ssam
429105197Ssam/* flags for key_cmpsaidx() */
430105197Ssam#define CMP_HEAD	1	/* protocol, addresses. */
431105197Ssam#define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
432105197Ssam#define CMP_REQID	3	/* additionally HEAD, reaid. */
433105197Ssam#define CMP_EXACTLY	4	/* all elements. */
434105197Ssamstatic int key_cmpsaidx
435105197Ssam	__P((const struct secasindex *, const struct secasindex *, int));
436105197Ssam
437105197Ssamstatic int key_cmpspidx_exactly
438105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
439105197Ssamstatic int key_cmpspidx_withmask
440105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
441105197Ssamstatic int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
442105197Ssamstatic int key_bbcmp __P((const void *, const void *, u_int));
443105197Ssamstatic u_int16_t key_satype2proto __P((u_int8_t));
444105197Ssamstatic u_int8_t key_proto2satype __P((u_int16_t));
445105197Ssam
446105197Ssamstatic int key_getspi __P((struct socket *, struct mbuf *,
447105197Ssam	const struct sadb_msghdr *));
448105197Ssamstatic u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
449105197Ssam					struct secasindex *));
450105197Ssamstatic int key_update __P((struct socket *, struct mbuf *,
451105197Ssam	const struct sadb_msghdr *));
452105197Ssam#ifdef IPSEC_DOSEQCHECK
453105197Ssamstatic struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
454105197Ssam#endif
455105197Ssamstatic int key_add __P((struct socket *, struct mbuf *,
456105197Ssam	const struct sadb_msghdr *));
457105197Ssamstatic int key_setident __P((struct secashead *, struct mbuf *,
458105197Ssam	const struct sadb_msghdr *));
459105197Ssamstatic struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
460105197Ssam	const struct sadb_msghdr *));
461105197Ssamstatic int key_delete __P((struct socket *, struct mbuf *,
462105197Ssam	const struct sadb_msghdr *));
463105197Ssamstatic int key_get __P((struct socket *, struct mbuf *,
464105197Ssam	const struct sadb_msghdr *));
465105197Ssam
466105197Ssamstatic void key_getcomb_setlifetime __P((struct sadb_comb *));
467105197Ssamstatic struct mbuf *key_getcomb_esp __P((void));
468105197Ssamstatic struct mbuf *key_getcomb_ah __P((void));
469105197Ssamstatic struct mbuf *key_getcomb_ipcomp __P((void));
470105197Ssamstatic struct mbuf *key_getprop __P((const struct secasindex *));
471105197Ssam
472105197Ssamstatic int key_acquire __P((const struct secasindex *, struct secpolicy *));
473105197Ssamstatic struct secacq *key_newacq __P((const struct secasindex *));
474105197Ssamstatic struct secacq *key_getacq __P((const struct secasindex *));
475105197Ssamstatic struct secacq *key_getacqbyseq __P((u_int32_t));
476105197Ssamstatic struct secspacq *key_newspacq __P((struct secpolicyindex *));
477105197Ssamstatic struct secspacq *key_getspacq __P((struct secpolicyindex *));
478105197Ssamstatic int key_acquire2 __P((struct socket *, struct mbuf *,
479105197Ssam	const struct sadb_msghdr *));
480105197Ssamstatic int key_register __P((struct socket *, struct mbuf *,
481105197Ssam	const struct sadb_msghdr *));
482105197Ssamstatic int key_expire __P((struct secasvar *));
483105197Ssamstatic int key_flush __P((struct socket *, struct mbuf *,
484105197Ssam	const struct sadb_msghdr *));
485105197Ssamstatic int key_dump __P((struct socket *, struct mbuf *,
486105197Ssam	const struct sadb_msghdr *));
487105197Ssamstatic int key_promisc __P((struct socket *, struct mbuf *,
488105197Ssam	const struct sadb_msghdr *));
489105197Ssamstatic int key_senderror __P((struct socket *, struct mbuf *, int));
490105197Ssamstatic int key_validate_ext __P((const struct sadb_ext *, int));
491105197Ssamstatic int key_align __P((struct mbuf *, struct sadb_msghdr *));
492105197Ssam#if 0
493105197Ssamstatic const char *key_getfqdn __P((void));
494105197Ssamstatic const char *key_getuserfqdn __P((void));
495105197Ssam#endif
496105197Ssamstatic void key_sa_chgstate __P((struct secasvar *, u_int8_t));
497105197Ssamstatic struct mbuf *key_alloc_mbuf __P((int));
498105197Ssam
499105197Ssam#define	SA_ADDREF(p) do {						\
500105197Ssam	(p)->refcnt++;							\
501120585Ssam	IPSEC_ASSERT((p)->refcnt != 0, ("SA refcnt overflow"));		\
502105197Ssam} while (0)
503105197Ssam#define	SA_DELREF(p) do {						\
504120585Ssam	IPSEC_ASSERT((p)->refcnt > 0, ("SA refcnt underflow"));		\
505105197Ssam	(p)->refcnt--;							\
506105197Ssam} while (0)
507105197Ssam
508105197Ssam#define	SP_ADDREF(p) do {						\
509105197Ssam	(p)->refcnt++;							\
510120585Ssam	IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));		\
511105197Ssam} while (0)
512105197Ssam#define	SP_DELREF(p) do {						\
513120585Ssam	IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));		\
514105197Ssam	(p)->refcnt--;							\
515105197Ssam} while (0)
516105197Ssam
517105197Ssam/*
518105197Ssam * Return 0 when there are known to be no SP's for the specified
519105197Ssam * direction.  Otherwise return 1.  This is used by IPsec code
520105197Ssam * to optimize performance.
521105197Ssam */
522105197Ssamint
523105197Ssamkey_havesp(u_int dir)
524105197Ssam{
525105197Ssam	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
526105197Ssam		LIST_FIRST(&sptree[dir]) != NULL : 1);
527105197Ssam}
528105197Ssam
529105197Ssam/* %%% IPsec policy management */
530105197Ssam/*
531105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
532105197Ssam * Must call key_freesp() later.
533105197Ssam * OUT:	NULL:	not found
534105197Ssam *	others:	found and return the pointer.
535105197Ssam */
536105197Ssamstruct secpolicy *
537105197Ssamkey_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
538105197Ssam{
539105197Ssam	struct secpolicy *sp;
540105197Ssam
541120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
542120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
543120585Ssam		("invalid direction %u", dir));
544105197Ssam
545105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
546120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
547105197Ssam
548105197Ssam	/* get a SP entry */
549105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
550105197Ssam		printf("*** objects\n");
551105197Ssam		kdebug_secpolicyindex(spidx));
552105197Ssam
553120585Ssam	SPTREE_LOCK();
554105197Ssam	LIST_FOREACH(sp, &sptree[dir], chain) {
555105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
556105197Ssam			printf("*** in SPD\n");
557105197Ssam			kdebug_secpolicyindex(&sp->spidx));
558105197Ssam
559105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
560105197Ssam			continue;
561105197Ssam		if (key_cmpspidx_withmask(&sp->spidx, spidx))
562105197Ssam			goto found;
563105197Ssam	}
564105197Ssam	sp = NULL;
565105197Ssamfound:
566105197Ssam	if (sp) {
567105197Ssam		/* sanity check */
568120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
569105197Ssam
570105197Ssam		/* found a SPD entry */
571105197Ssam		sp->lastused = time_second;
572105197Ssam		SP_ADDREF(sp);
573105197Ssam	}
574120585Ssam	SPTREE_UNLOCK();
575105197Ssam
576105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
577120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
578105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
579105197Ssam	return sp;
580105197Ssam}
581105197Ssam
582105197Ssam/*
583105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
584105197Ssam * Must call key_freesp() later.
585105197Ssam * OUT:	NULL:	not found
586105197Ssam *	others:	found and return the pointer.
587105197Ssam */
588105197Ssamstruct secpolicy *
589105197Ssamkey_allocsp2(u_int32_t spi,
590105197Ssam	     union sockaddr_union *dst,
591105197Ssam	     u_int8_t proto,
592105197Ssam	     u_int dir,
593105197Ssam	     const char* where, int tag)
594105197Ssam{
595105197Ssam	struct secpolicy *sp;
596105197Ssam
597120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst"));
598120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
599120585Ssam		("invalid direction %u", dir));
600105197Ssam
601105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
602120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
603105197Ssam
604105197Ssam	/* get a SP entry */
605105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
606105197Ssam		printf("*** objects\n");
607105197Ssam		printf("spi %u proto %u dir %u\n", spi, proto, dir);
608105197Ssam		kdebug_sockaddr(&dst->sa));
609105197Ssam
610120585Ssam	SPTREE_LOCK();
611105197Ssam	LIST_FOREACH(sp, &sptree[dir], chain) {
612105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
613105197Ssam			printf("*** in SPD\n");
614105197Ssam			kdebug_secpolicyindex(&sp->spidx));
615105197Ssam
616105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
617105197Ssam			continue;
618105197Ssam		/* compare simple values, then dst address */
619105197Ssam		if (sp->spidx.ul_proto != proto)
620105197Ssam			continue;
621105197Ssam		/* NB: spi's must exist and match */
622105197Ssam		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
623105197Ssam			continue;
624105197Ssam		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
625105197Ssam			goto found;
626105197Ssam	}
627105197Ssam	sp = NULL;
628105197Ssamfound:
629105197Ssam	if (sp) {
630105197Ssam		/* sanity check */
631120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
632105197Ssam
633105197Ssam		/* found a SPD entry */
634105197Ssam		sp->lastused = time_second;
635105197Ssam		SP_ADDREF(sp);
636105197Ssam	}
637120585Ssam	SPTREE_UNLOCK();
638105197Ssam
639105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
640120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
641105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
642105197Ssam	return sp;
643105197Ssam}
644105197Ssam
645105197Ssam/*
646105197Ssam * return a policy that matches this particular inbound packet.
647105197Ssam * XXX slow
648105197Ssam */
649105197Ssamstruct secpolicy *
650105197Ssamkey_gettunnel(const struct sockaddr *osrc,
651105197Ssam	      const struct sockaddr *odst,
652105197Ssam	      const struct sockaddr *isrc,
653105197Ssam	      const struct sockaddr *idst,
654105197Ssam	      const char* where, int tag)
655105197Ssam{
656105197Ssam	struct secpolicy *sp;
657105197Ssam	const int dir = IPSEC_DIR_INBOUND;
658105197Ssam	struct ipsecrequest *r1, *r2, *p;
659105197Ssam	struct secpolicyindex spidx;
660105197Ssam
661105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
662120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
663105197Ssam
664105197Ssam	if (isrc->sa_family != idst->sa_family) {
665120585Ssam		ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
666120585Ssam			__func__, isrc->sa_family, idst->sa_family));
667105197Ssam		sp = NULL;
668105197Ssam		goto done;
669105197Ssam	}
670105197Ssam
671120585Ssam	SPTREE_LOCK();
672105197Ssam	LIST_FOREACH(sp, &sptree[dir], chain) {
673105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
674105197Ssam			continue;
675105197Ssam
676105197Ssam		r1 = r2 = NULL;
677105197Ssam		for (p = sp->req; p; p = p->next) {
678105197Ssam			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
679105197Ssam				continue;
680105197Ssam
681105197Ssam			r1 = r2;
682105197Ssam			r2 = p;
683105197Ssam
684105197Ssam			if (!r1) {
685105197Ssam				/* here we look at address matches only */
686105197Ssam				spidx = sp->spidx;
687105197Ssam				if (isrc->sa_len > sizeof(spidx.src) ||
688105197Ssam				    idst->sa_len > sizeof(spidx.dst))
689105197Ssam					continue;
690105197Ssam				bcopy(isrc, &spidx.src, isrc->sa_len);
691105197Ssam				bcopy(idst, &spidx.dst, idst->sa_len);
692105197Ssam				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
693105197Ssam					continue;
694105197Ssam			} else {
695105197Ssam				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
696105197Ssam				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
697105197Ssam					continue;
698105197Ssam			}
699105197Ssam
700105197Ssam			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
701105197Ssam			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
702105197Ssam				continue;
703105197Ssam
704105197Ssam			goto found;
705105197Ssam		}
706105197Ssam	}
707105197Ssam	sp = NULL;
708105197Ssamfound:
709105197Ssam	if (sp) {
710105197Ssam		sp->lastused = time_second;
711105197Ssam		SP_ADDREF(sp);
712105197Ssam	}
713120585Ssam	SPTREE_UNLOCK();
714105197Ssamdone:
715105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
716120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
717105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
718105197Ssam	return sp;
719105197Ssam}
720105197Ssam
721105197Ssam/*
722105197Ssam * allocating an SA entry for an *OUTBOUND* packet.
723105197Ssam * checking each request entries in SP, and acquire an SA if need.
724105197Ssam * OUT:	0: there are valid requests.
725105197Ssam *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
726105197Ssam */
727105197Ssamint
728105197Ssamkey_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
729105197Ssam{
730105197Ssam	u_int level;
731105197Ssam	int error;
732105197Ssam
733120585Ssam	IPSEC_ASSERT(isr != NULL, ("null isr"));
734120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
735120585Ssam	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
736105197Ssam		saidx->mode == IPSEC_MODE_TUNNEL,
737120585Ssam		("unexpected policy %u", saidx->mode));
738105197Ssam
739105197Ssam	/*
740105197Ssam	 * XXX guard against protocol callbacks from the crypto
741105197Ssam	 * thread as they reference ipsecrequest.sav which we
742105197Ssam	 * temporarily null out below.  Need to rethink how we
743105197Ssam	 * handle bundled SA's in the callback thread.
744105197Ssam	 */
745120585Ssam	IPSECREQUEST_LOCK_ASSERT(isr);
746119643Ssam
747119643Ssam	/* get current level */
748119643Ssam	level = ipsec_get_reqlevel(isr);
749105197Ssam#if 0
750105197Ssam	/*
751105197Ssam	 * We do allocate new SA only if the state of SA in the holder is
752105197Ssam	 * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
753105197Ssam	 */
754105197Ssam	if (isr->sav != NULL) {
755105197Ssam		if (isr->sav->sah == NULL)
756120585Ssam			panic("%s: sah is null.\n", __func__);
757105197Ssam		if (isr->sav == (struct secasvar *)LIST_FIRST(
758105197Ssam			    &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
759105197Ssam			KEY_FREESAV(&isr->sav);
760105197Ssam			isr->sav = NULL;
761105197Ssam		}
762105197Ssam	}
763105197Ssam#else
764105197Ssam	/*
765105197Ssam	 * we free any SA stashed in the IPsec request because a different
766105197Ssam	 * SA may be involved each time this request is checked, either
767105197Ssam	 * because new SAs are being configured, or this request is
768105197Ssam	 * associated with an unconnected datagram socket, or this request
769105197Ssam	 * is associated with a system default policy.
770105197Ssam	 *
771105197Ssam	 * The operation may have negative impact to performance.  We may
772105197Ssam	 * want to check cached SA carefully, rather than picking new SA
773105197Ssam	 * every time.
774105197Ssam	 */
775105197Ssam	if (isr->sav != NULL) {
776105197Ssam		KEY_FREESAV(&isr->sav);
777105197Ssam		isr->sav = NULL;
778105197Ssam	}
779105197Ssam#endif
780105197Ssam
781105197Ssam	/*
782105197Ssam	 * new SA allocation if no SA found.
783105197Ssam	 * key_allocsa_policy should allocate the oldest SA available.
784105197Ssam	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
785105197Ssam	 */
786105197Ssam	if (isr->sav == NULL)
787105197Ssam		isr->sav = key_allocsa_policy(saidx);
788105197Ssam
789105197Ssam	/* When there is SA. */
790105197Ssam	if (isr->sav != NULL) {
791105197Ssam		if (isr->sav->state != SADB_SASTATE_MATURE &&
792105197Ssam		    isr->sav->state != SADB_SASTATE_DYING)
793105197Ssam			return EINVAL;
794105197Ssam		return 0;
795105197Ssam	}
796105197Ssam
797105197Ssam	/* there is no SA */
798105197Ssam	error = key_acquire(saidx, isr->sp);
799105197Ssam	if (error != 0) {
800105197Ssam		/* XXX What should I do ? */
801120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
802120585Ssam			__func__, error));
803105197Ssam		return error;
804105197Ssam	}
805105197Ssam
806105197Ssam	if (level != IPSEC_LEVEL_REQUIRE) {
807105197Ssam		/* XXX sigh, the interface to this routine is botched */
808120585Ssam		IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
809105197Ssam		return 0;
810105197Ssam	} else {
811105197Ssam		return ENOENT;
812105197Ssam	}
813105197Ssam}
814105197Ssam
815105197Ssam/*
816105197Ssam * allocating a SA for policy entry from SAD.
817105197Ssam * NOTE: searching SAD of aliving state.
818105197Ssam * OUT:	NULL:	not found.
819105197Ssam *	others:	found and return the pointer.
820105197Ssam */
821105197Ssamstatic struct secasvar *
822105197Ssamkey_allocsa_policy(const struct secasindex *saidx)
823105197Ssam{
824105197Ssam	struct secashead *sah;
825105197Ssam	struct secasvar *sav;
826105197Ssam	u_int stateidx, state;
827105197Ssam
828120585Ssam	SAHTREE_LOCK();
829105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
830105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
831105197Ssam			continue;
832119643Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
833120585Ssam			SAHTREE_UNLOCK();
834105197Ssam			goto found;
835119643Ssam		}
836105197Ssam	}
837120585Ssam	SAHTREE_UNLOCK();
838105197Ssam
839105197Ssam	return NULL;
840105197Ssam
841105197Ssam    found:
842105197Ssam
843105197Ssam	/* search valid state */
844105197Ssam	for (stateidx = 0;
845105197Ssam	     stateidx < _ARRAYLEN(saorder_state_valid);
846105197Ssam	     stateidx++) {
847105197Ssam
848105197Ssam		state = saorder_state_valid[stateidx];
849105197Ssam
850105197Ssam		sav = key_do_allocsa_policy(sah, state);
851105197Ssam		if (sav != NULL)
852105197Ssam			return sav;
853105197Ssam	}
854105197Ssam
855105197Ssam	return NULL;
856105197Ssam}
857105197Ssam
858105197Ssam/*
859105197Ssam * searching SAD with direction, protocol, mode and state.
860105197Ssam * called by key_allocsa_policy().
861105197Ssam * OUT:
862105197Ssam *	NULL	: not found
863105197Ssam *	others	: found, pointer to a SA.
864105197Ssam */
865105197Ssamstatic struct secasvar *
866105197Ssamkey_do_allocsa_policy(struct secashead *sah, u_int state)
867105197Ssam{
868105197Ssam	struct secasvar *sav, *nextsav, *candidate, *d;
869105197Ssam
870105197Ssam	/* initilize */
871105197Ssam	candidate = NULL;
872105197Ssam
873120585Ssam	SAHTREE_LOCK();
874105197Ssam	for (sav = LIST_FIRST(&sah->savtree[state]);
875105197Ssam	     sav != NULL;
876105197Ssam	     sav = nextsav) {
877105197Ssam
878105197Ssam		nextsav = LIST_NEXT(sav, chain);
879105197Ssam
880105197Ssam		/* sanity check */
881120585Ssam		KEY_CHKSASTATE(sav->state, state, __func__);
882105197Ssam
883105197Ssam		/* initialize */
884105197Ssam		if (candidate == NULL) {
885105197Ssam			candidate = sav;
886105197Ssam			continue;
887105197Ssam		}
888105197Ssam
889105197Ssam		/* Which SA is the better ? */
890105197Ssam
891120585Ssam		IPSEC_ASSERT(candidate->lft_c != NULL,
892120585Ssam			("null candidate lifetime"));
893120585Ssam		IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
894105197Ssam
895105197Ssam		/* What the best method is to compare ? */
896125876Sguido		if (key_preferred_oldsa) {
897105197Ssam			if (candidate->lft_c->sadb_lifetime_addtime >
898105197Ssam					sav->lft_c->sadb_lifetime_addtime) {
899105197Ssam				candidate = sav;
900105197Ssam			}
901105197Ssam			continue;
902105197Ssam			/*NOTREACHED*/
903105197Ssam		}
904105197Ssam
905125876Sguido		/* preferred new sa rather than old sa */
906105197Ssam		if (candidate->lft_c->sadb_lifetime_addtime <
907105197Ssam				sav->lft_c->sadb_lifetime_addtime) {
908105197Ssam			d = candidate;
909105197Ssam			candidate = sav;
910105197Ssam		} else
911105197Ssam			d = sav;
912105197Ssam
913105197Ssam		/*
914105197Ssam		 * prepared to delete the SA when there is more
915105197Ssam		 * suitable candidate and the lifetime of the SA is not
916105197Ssam		 * permanent.
917105197Ssam		 */
918105197Ssam		if (d->lft_c->sadb_lifetime_addtime != 0) {
919105197Ssam			struct mbuf *m, *result;
920125508Ssam			u_int8_t satype;
921105197Ssam
922105197Ssam			key_sa_chgstate(d, SADB_SASTATE_DEAD);
923105197Ssam
924120585Ssam			IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
925125508Ssam
926125508Ssam			satype = key_proto2satype(d->sah->saidx.proto);
927125508Ssam			if (satype == 0)
928125508Ssam				goto msgfail;
929125508Ssam
930105197Ssam			m = key_setsadbmsg(SADB_DELETE, 0,
931125508Ssam			    satype, 0, 0, d->refcnt - 1);
932105197Ssam			if (!m)
933105197Ssam				goto msgfail;
934105197Ssam			result = m;
935105197Ssam
936105197Ssam			/* set sadb_address for saidx's. */
937105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
938105197Ssam				&d->sah->saidx.src.sa,
939105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
940105197Ssam				IPSEC_ULPROTO_ANY);
941105197Ssam			if (!m)
942105197Ssam				goto msgfail;
943105197Ssam			m_cat(result, m);
944105197Ssam
945105197Ssam			/* set sadb_address for saidx's. */
946105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
947105197Ssam				&d->sah->saidx.src.sa,
948105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
949105197Ssam				IPSEC_ULPROTO_ANY);
950105197Ssam			if (!m)
951105197Ssam				goto msgfail;
952105197Ssam			m_cat(result, m);
953105197Ssam
954105197Ssam			/* create SA extension */
955105197Ssam			m = key_setsadbsa(d);
956105197Ssam			if (!m)
957105197Ssam				goto msgfail;
958105197Ssam			m_cat(result, m);
959105197Ssam
960105197Ssam			if (result->m_len < sizeof(struct sadb_msg)) {
961105197Ssam				result = m_pullup(result,
962105197Ssam						sizeof(struct sadb_msg));
963105197Ssam				if (result == NULL)
964105197Ssam					goto msgfail;
965105197Ssam			}
966105197Ssam
967105197Ssam			result->m_pkthdr.len = 0;
968105197Ssam			for (m = result; m; m = m->m_next)
969105197Ssam				result->m_pkthdr.len += m->m_len;
970105197Ssam			mtod(result, struct sadb_msg *)->sadb_msg_len =
971105197Ssam				PFKEY_UNIT64(result->m_pkthdr.len);
972105197Ssam
973105197Ssam			if (key_sendup_mbuf(NULL, result,
974105197Ssam					KEY_SENDUP_REGISTERED))
975105197Ssam				goto msgfail;
976105197Ssam		 msgfail:
977105197Ssam			KEY_FREESAV(&d);
978105197Ssam		}
979105197Ssam	}
980105197Ssam	if (candidate) {
981105197Ssam		SA_ADDREF(candidate);
982105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
983120585Ssam			printf("DP %s cause refcnt++:%d SA:%p\n",
984120585Ssam				__func__, candidate->refcnt, candidate));
985105197Ssam	}
986120585Ssam	SAHTREE_UNLOCK();
987119643Ssam
988105197Ssam	return candidate;
989105197Ssam}
990105197Ssam
991105197Ssam/*
992105197Ssam * allocating a usable SA entry for a *INBOUND* packet.
993105197Ssam * Must call key_freesav() later.
994105197Ssam * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
995105197Ssam *	NULL:		not found, or error occured.
996105197Ssam *
997105197Ssam * In the comparison, no source address is used--for RFC2401 conformance.
998105197Ssam * To quote, from section 4.1:
999105197Ssam *	A security association is uniquely identified by a triple consisting
1000105197Ssam *	of a Security Parameter Index (SPI), an IP Destination Address, and a
1001105197Ssam *	security protocol (AH or ESP) identifier.
1002105197Ssam * Note that, however, we do need to keep source address in IPsec SA.
1003105197Ssam * IKE specification and PF_KEY specification do assume that we
1004105197Ssam * keep source address in IPsec SA.  We see a tricky situation here.
1005105197Ssam */
1006105197Ssamstruct secasvar *
1007105197Ssamkey_allocsa(
1008105197Ssam	union sockaddr_union *dst,
1009105197Ssam	u_int proto,
1010105197Ssam	u_int32_t spi,
1011105197Ssam	const char* where, int tag)
1012105197Ssam{
1013105197Ssam	struct secashead *sah;
1014105197Ssam	struct secasvar *sav;
1015105197Ssam	u_int stateidx, state;
1016105197Ssam
1017120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst address"));
1018105197Ssam
1019105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1020120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
1021105197Ssam
1022105197Ssam	/*
1023105197Ssam	 * searching SAD.
1024105197Ssam	 * XXX: to be checked internal IP header somewhere.  Also when
1025105197Ssam	 * IPsec tunnel packet is received.  But ESP tunnel mode is
1026105197Ssam	 * encrypted so we can't check internal IP header.
1027105197Ssam	 */
1028120585Ssam	SAHTREE_LOCK();
1029105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
1030105197Ssam		/* search valid state */
1031105197Ssam		for (stateidx = 0;
1032105197Ssam		     stateidx < _ARRAYLEN(saorder_state_valid);
1033105197Ssam		     stateidx++) {
1034105197Ssam			state = saorder_state_valid[stateidx];
1035105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
1036105197Ssam				/* sanity check */
1037120585Ssam				KEY_CHKSASTATE(sav->state, state, __func__);
1038105197Ssam				/* do not return entries w/ unusable state */
1039105197Ssam				if (sav->state != SADB_SASTATE_MATURE &&
1040105197Ssam				    sav->state != SADB_SASTATE_DYING)
1041105197Ssam					continue;
1042105197Ssam				if (proto != sav->sah->saidx.proto)
1043105197Ssam					continue;
1044105197Ssam				if (spi != sav->spi)
1045105197Ssam					continue;
1046105197Ssam#if 0	/* don't check src */
1047105197Ssam				/* check src address */
1048105197Ssam				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, 0) != 0)
1049105197Ssam					continue;
1050105197Ssam#endif
1051105197Ssam				/* check dst address */
1052105197Ssam				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, 0) != 0)
1053105197Ssam					continue;
1054105197Ssam				SA_ADDREF(sav);
1055105197Ssam				goto done;
1056105197Ssam			}
1057105197Ssam		}
1058105197Ssam	}
1059105197Ssam	sav = NULL;
1060105197Ssamdone:
1061120585Ssam	SAHTREE_UNLOCK();
1062105197Ssam
1063105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1064120585Ssam		printf("DP %s return SA:%p; refcnt %u\n", __func__,
1065105197Ssam			sav, sav ? sav->refcnt : 0));
1066105197Ssam	return sav;
1067105197Ssam}
1068105197Ssam
1069105197Ssam/*
1070105197Ssam * Must be called after calling key_allocsp().
1071105197Ssam * For both the packet without socket and key_freeso().
1072105197Ssam */
1073105197Ssamvoid
1074105197Ssam_key_freesp(struct secpolicy **spp, const char* where, int tag)
1075105197Ssam{
1076105197Ssam	struct secpolicy *sp = *spp;
1077105197Ssam
1078120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1079105197Ssam
1080120585Ssam	SPTREE_LOCK();
1081105197Ssam	SP_DELREF(sp);
1082105197Ssam
1083105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1084120585Ssam		printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1085120585Ssam			__func__, sp, sp->id, where, tag, sp->refcnt));
1086105197Ssam
1087105197Ssam	if (sp->refcnt == 0) {
1088105197Ssam		*spp = NULL;
1089105197Ssam		key_delsp(sp);
1090105197Ssam	}
1091120585Ssam	SPTREE_UNLOCK();
1092105197Ssam}
1093105197Ssam
1094105197Ssam/*
1095105197Ssam * Must be called after calling key_allocsp().
1096105197Ssam * For the packet with socket.
1097105197Ssam */
1098105197Ssamvoid
1099105197Ssamkey_freeso(struct socket *so)
1100105197Ssam{
1101120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
1102105197Ssam
1103105197Ssam	switch (so->so_proto->pr_domain->dom_family) {
1104105197Ssam#ifdef INET
1105105197Ssam	case PF_INET:
1106105197Ssam	    {
1107105197Ssam		struct inpcb *pcb = sotoinpcb(so);
1108105197Ssam
1109105197Ssam		/* Does it have a PCB ? */
1110105197Ssam		if (pcb == NULL)
1111105197Ssam			return;
1112105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1113105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1114105197Ssam	    }
1115105197Ssam		break;
1116105197Ssam#endif
1117105197Ssam#ifdef INET6
1118105197Ssam	case PF_INET6:
1119105197Ssam	    {
1120105197Ssam#ifdef HAVE_NRL_INPCB
1121105197Ssam		struct inpcb *pcb  = sotoinpcb(so);
1122105197Ssam
1123105197Ssam		/* Does it have a PCB ? */
1124105197Ssam		if (pcb == NULL)
1125105197Ssam			return;
1126105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1127105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1128105197Ssam#else
1129105197Ssam		struct in6pcb *pcb  = sotoin6pcb(so);
1130105197Ssam
1131105197Ssam		/* Does it have a PCB ? */
1132105197Ssam		if (pcb == NULL)
1133105197Ssam			return;
1134105197Ssam		key_freesp_so(&pcb->in6p_sp->sp_in);
1135105197Ssam		key_freesp_so(&pcb->in6p_sp->sp_out);
1136105197Ssam#endif
1137105197Ssam	    }
1138105197Ssam		break;
1139105197Ssam#endif /* INET6 */
1140105197Ssam	default:
1141120585Ssam		ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1142120585Ssam		    __func__, so->so_proto->pr_domain->dom_family));
1143105197Ssam		return;
1144105197Ssam	}
1145105197Ssam}
1146105197Ssam
1147105197Ssamstatic void
1148105197Ssamkey_freesp_so(struct secpolicy **sp)
1149105197Ssam{
1150120585Ssam	IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1151105197Ssam
1152105197Ssam	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1153105197Ssam	    (*sp)->policy == IPSEC_POLICY_BYPASS)
1154105197Ssam		return;
1155105197Ssam
1156120585Ssam	IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1157120585Ssam		("invalid policy %u", (*sp)->policy));
1158105197Ssam	KEY_FREESP(sp);
1159105197Ssam}
1160105197Ssam
1161105197Ssam/*
1162105197Ssam * Must be called after calling key_allocsa().
1163105197Ssam * This function is called by key_freesp() to free some SA allocated
1164105197Ssam * for a policy.
1165105197Ssam */
1166105197Ssamvoid
1167105197Ssamkey_freesav(struct secasvar **psav, const char* where, int tag)
1168105197Ssam{
1169105197Ssam	struct secasvar *sav = *psav;
1170105197Ssam
1171120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
1172105197Ssam
1173120585Ssam	/* XXX unguarded? */
1174105197Ssam	SA_DELREF(sav);
1175105197Ssam
1176105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1177120585Ssam		printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1178120585Ssam			__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1179105197Ssam
1180105197Ssam	if (sav->refcnt == 0) {
1181105197Ssam		*psav = NULL;
1182105197Ssam		key_delsav(sav);
1183105197Ssam	}
1184105197Ssam}
1185105197Ssam
1186105197Ssam/* %%% SPD management */
1187105197Ssam/*
1188105197Ssam * free security policy entry.
1189105197Ssam */
1190105197Ssamstatic void
1191105197Ssamkey_delsp(struct secpolicy *sp)
1192105197Ssam{
1193119643Ssam	struct ipsecrequest *isr, *nextisr;
1194105197Ssam
1195120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1196120585Ssam	SPTREE_LOCK_ASSERT();
1197105197Ssam
1198105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
1199105197Ssam
1200120585Ssam	IPSEC_ASSERT(sp->refcnt == 0,
1201120585Ssam		("SP with references deleted (refcnt %u)", sp->refcnt));
1202105197Ssam
1203105197Ssam	/* remove from SP index */
1204105197Ssam	if (__LIST_CHAINED(sp))
1205105197Ssam		LIST_REMOVE(sp, chain);
1206105197Ssam
1207119643Ssam	for (isr = sp->req; isr != NULL; isr = nextisr) {
1208105197Ssam		if (isr->sav != NULL) {
1209105197Ssam			KEY_FREESAV(&isr->sav);
1210105197Ssam			isr->sav = NULL;
1211105197Ssam		}
1212105197Ssam
1213105197Ssam		nextisr = isr->next;
1214119643Ssam		ipsec_delisr(isr);
1215105197Ssam	}
1216119643Ssam	_key_delsp(sp);
1217105197Ssam}
1218105197Ssam
1219105197Ssam/*
1220105197Ssam * search SPD
1221105197Ssam * OUT:	NULL	: not found
1222105197Ssam *	others	: found, pointer to a SP.
1223105197Ssam */
1224105197Ssamstatic struct secpolicy *
1225105197Ssamkey_getsp(struct secpolicyindex *spidx)
1226105197Ssam{
1227105197Ssam	struct secpolicy *sp;
1228105197Ssam
1229120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1230105197Ssam
1231120585Ssam	SPTREE_LOCK();
1232105197Ssam	LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
1233105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1234105197Ssam			continue;
1235105197Ssam		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1236105197Ssam			SP_ADDREF(sp);
1237119643Ssam			break;
1238105197Ssam		}
1239105197Ssam	}
1240120585Ssam	SPTREE_UNLOCK();
1241105197Ssam
1242119643Ssam	return sp;
1243105197Ssam}
1244105197Ssam
1245105197Ssam/*
1246105197Ssam * get SP by index.
1247105197Ssam * OUT:	NULL	: not found
1248105197Ssam *	others	: found, pointer to a SP.
1249105197Ssam */
1250105197Ssamstatic struct secpolicy *
1251105197Ssamkey_getspbyid(u_int32_t id)
1252105197Ssam{
1253105197Ssam	struct secpolicy *sp;
1254105197Ssam
1255120585Ssam	SPTREE_LOCK();
1256105197Ssam	LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
1257105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1258105197Ssam			continue;
1259105197Ssam		if (sp->id == id) {
1260105197Ssam			SP_ADDREF(sp);
1261119643Ssam			goto done;
1262105197Ssam		}
1263105197Ssam	}
1264105197Ssam
1265105197Ssam	LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
1266105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1267105197Ssam			continue;
1268105197Ssam		if (sp->id == id) {
1269105197Ssam			SP_ADDREF(sp);
1270119643Ssam			goto done;
1271105197Ssam		}
1272105197Ssam	}
1273119643Ssamdone:
1274120585Ssam	SPTREE_UNLOCK();
1275105197Ssam
1276119643Ssam	return sp;
1277105197Ssam}
1278105197Ssam
1279105197Ssamstruct secpolicy *
1280105197Ssamkey_newsp(const char* where, int tag)
1281105197Ssam{
1282105197Ssam	struct secpolicy *newsp = NULL;
1283105197Ssam
1284105197Ssam	newsp = (struct secpolicy *)
1285119643Ssam		malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1286105197Ssam	if (newsp) {
1287120585Ssam		SECPOLICY_LOCK_INIT(newsp);
1288105197Ssam		newsp->refcnt = 1;
1289105197Ssam		newsp->req = NULL;
1290105197Ssam	}
1291105197Ssam
1292105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1293120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
1294105197Ssam			where, tag, newsp));
1295105197Ssam	return newsp;
1296105197Ssam}
1297105197Ssam
1298119643Ssamstatic void
1299119643Ssam_key_delsp(struct secpolicy *sp)
1300119643Ssam{
1301120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
1302119643Ssam	free(sp, M_IPSEC_SP);
1303119643Ssam}
1304119643Ssam
1305105197Ssam/*
1306105197Ssam * create secpolicy structure from sadb_x_policy structure.
1307105197Ssam * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1308105197Ssam * so must be set properly later.
1309105197Ssam */
1310105197Ssamstruct secpolicy *
1311105197Ssamkey_msg2sp(xpl0, len, error)
1312105197Ssam	struct sadb_x_policy *xpl0;
1313105197Ssam	size_t len;
1314105197Ssam	int *error;
1315105197Ssam{
1316105197Ssam	struct secpolicy *newsp;
1317105197Ssam
1318120585Ssam	IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1319120585Ssam	IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %u", len));
1320120585Ssam
1321105197Ssam	if (len != PFKEY_EXTLEN(xpl0)) {
1322120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1323105197Ssam		*error = EINVAL;
1324105197Ssam		return NULL;
1325105197Ssam	}
1326105197Ssam
1327105197Ssam	if ((newsp = KEY_NEWSP()) == NULL) {
1328105197Ssam		*error = ENOBUFS;
1329105197Ssam		return NULL;
1330105197Ssam	}
1331105197Ssam
1332105197Ssam	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1333105197Ssam	newsp->policy = xpl0->sadb_x_policy_type;
1334105197Ssam
1335105197Ssam	/* check policy */
1336105197Ssam	switch (xpl0->sadb_x_policy_type) {
1337105197Ssam	case IPSEC_POLICY_DISCARD:
1338105197Ssam	case IPSEC_POLICY_NONE:
1339105197Ssam	case IPSEC_POLICY_ENTRUST:
1340105197Ssam	case IPSEC_POLICY_BYPASS:
1341105197Ssam		newsp->req = NULL;
1342105197Ssam		break;
1343105197Ssam
1344105197Ssam	case IPSEC_POLICY_IPSEC:
1345105197Ssam	    {
1346105197Ssam		int tlen;
1347105197Ssam		struct sadb_x_ipsecrequest *xisr;
1348105197Ssam		struct ipsecrequest **p_isr = &newsp->req;
1349105197Ssam
1350105197Ssam		/* validity check */
1351105197Ssam		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1352120585Ssam			ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1353120585Ssam				__func__));
1354105197Ssam			KEY_FREESP(&newsp);
1355105197Ssam			*error = EINVAL;
1356105197Ssam			return NULL;
1357105197Ssam		}
1358105197Ssam
1359105197Ssam		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1360105197Ssam		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1361105197Ssam
1362105197Ssam		while (tlen > 0) {
1363105197Ssam			/* length check */
1364105197Ssam			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1365120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1366120585Ssam					"length.\n", __func__));
1367105197Ssam				KEY_FREESP(&newsp);
1368105197Ssam				*error = EINVAL;
1369105197Ssam				return NULL;
1370105197Ssam			}
1371105197Ssam
1372105197Ssam			/* allocate request buffer */
1373119643Ssam			/* NB: data structure is zero'd */
1374119643Ssam			*p_isr = ipsec_newisr();
1375105197Ssam			if ((*p_isr) == NULL) {
1376105197Ssam				ipseclog((LOG_DEBUG,
1377120585Ssam				    "%s: No more memory.\n", __func__));
1378105197Ssam				KEY_FREESP(&newsp);
1379105197Ssam				*error = ENOBUFS;
1380105197Ssam				return NULL;
1381105197Ssam			}
1382105197Ssam
1383105197Ssam			/* set values */
1384105197Ssam			switch (xisr->sadb_x_ipsecrequest_proto) {
1385105197Ssam			case IPPROTO_ESP:
1386105197Ssam			case IPPROTO_AH:
1387105197Ssam			case IPPROTO_IPCOMP:
1388105197Ssam				break;
1389105197Ssam			default:
1390105197Ssam				ipseclog((LOG_DEBUG,
1391120585Ssam				    "%s: invalid proto type=%u\n", __func__,
1392105197Ssam				    xisr->sadb_x_ipsecrequest_proto));
1393105197Ssam				KEY_FREESP(&newsp);
1394105197Ssam				*error = EPROTONOSUPPORT;
1395105197Ssam				return NULL;
1396105197Ssam			}
1397105197Ssam			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1398105197Ssam
1399105197Ssam			switch (xisr->sadb_x_ipsecrequest_mode) {
1400105197Ssam			case IPSEC_MODE_TRANSPORT:
1401105197Ssam			case IPSEC_MODE_TUNNEL:
1402105197Ssam				break;
1403105197Ssam			case IPSEC_MODE_ANY:
1404105197Ssam			default:
1405105197Ssam				ipseclog((LOG_DEBUG,
1406120585Ssam				    "%s: invalid mode=%u\n", __func__,
1407105197Ssam				    xisr->sadb_x_ipsecrequest_mode));
1408105197Ssam				KEY_FREESP(&newsp);
1409105197Ssam				*error = EINVAL;
1410105197Ssam				return NULL;
1411105197Ssam			}
1412105197Ssam			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1413105197Ssam
1414105197Ssam			switch (xisr->sadb_x_ipsecrequest_level) {
1415105197Ssam			case IPSEC_LEVEL_DEFAULT:
1416105197Ssam			case IPSEC_LEVEL_USE:
1417105197Ssam			case IPSEC_LEVEL_REQUIRE:
1418105197Ssam				break;
1419105197Ssam			case IPSEC_LEVEL_UNIQUE:
1420105197Ssam				/* validity check */
1421105197Ssam				/*
1422105197Ssam				 * If range violation of reqid, kernel will
1423105197Ssam				 * update it, don't refuse it.
1424105197Ssam				 */
1425105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid
1426105197Ssam						> IPSEC_MANUAL_REQID_MAX) {
1427105197Ssam					ipseclog((LOG_DEBUG,
1428120585Ssam					    "%s: reqid=%d range "
1429105197Ssam					    "violation, updated by kernel.\n",
1430120585Ssam					    __func__,
1431105197Ssam					    xisr->sadb_x_ipsecrequest_reqid));
1432105197Ssam					xisr->sadb_x_ipsecrequest_reqid = 0;
1433105197Ssam				}
1434105197Ssam
1435105197Ssam				/* allocate new reqid id if reqid is zero. */
1436105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1437105197Ssam					u_int32_t reqid;
1438105197Ssam					if ((reqid = key_newreqid()) == 0) {
1439105197Ssam						KEY_FREESP(&newsp);
1440105197Ssam						*error = ENOBUFS;
1441105197Ssam						return NULL;
1442105197Ssam					}
1443105197Ssam					(*p_isr)->saidx.reqid = reqid;
1444105197Ssam					xisr->sadb_x_ipsecrequest_reqid = reqid;
1445105197Ssam				} else {
1446105197Ssam				/* set it for manual keying. */
1447105197Ssam					(*p_isr)->saidx.reqid =
1448105197Ssam						xisr->sadb_x_ipsecrequest_reqid;
1449105197Ssam				}
1450105197Ssam				break;
1451105197Ssam
1452105197Ssam			default:
1453120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1454120585Ssam					__func__,
1455105197Ssam					xisr->sadb_x_ipsecrequest_level));
1456105197Ssam				KEY_FREESP(&newsp);
1457105197Ssam				*error = EINVAL;
1458105197Ssam				return NULL;
1459105197Ssam			}
1460105197Ssam			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1461105197Ssam
1462105197Ssam			/* set IP addresses if there */
1463105197Ssam			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1464105197Ssam				struct sockaddr *paddr;
1465105197Ssam
1466105197Ssam				paddr = (struct sockaddr *)(xisr + 1);
1467105197Ssam
1468105197Ssam				/* validity check */
1469105197Ssam				if (paddr->sa_len
1470105197Ssam				    > sizeof((*p_isr)->saidx.src)) {
1471120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1472120585Ssam						"request address length.\n",
1473120585Ssam						__func__));
1474105197Ssam					KEY_FREESP(&newsp);
1475105197Ssam					*error = EINVAL;
1476105197Ssam					return NULL;
1477105197Ssam				}
1478105197Ssam				bcopy(paddr, &(*p_isr)->saidx.src,
1479105197Ssam					paddr->sa_len);
1480105197Ssam
1481105197Ssam				paddr = (struct sockaddr *)((caddr_t)paddr
1482105197Ssam							+ paddr->sa_len);
1483105197Ssam
1484105197Ssam				/* validity check */
1485105197Ssam				if (paddr->sa_len
1486105197Ssam				    > sizeof((*p_isr)->saidx.dst)) {
1487120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1488120585Ssam						"request address length.\n",
1489120585Ssam						__func__));
1490105197Ssam					KEY_FREESP(&newsp);
1491105197Ssam					*error = EINVAL;
1492105197Ssam					return NULL;
1493105197Ssam				}
1494105197Ssam				bcopy(paddr, &(*p_isr)->saidx.dst,
1495105197Ssam					paddr->sa_len);
1496105197Ssam			}
1497105197Ssam
1498105197Ssam			(*p_isr)->sp = newsp;
1499105197Ssam
1500105197Ssam			/* initialization for the next. */
1501105197Ssam			p_isr = &(*p_isr)->next;
1502105197Ssam			tlen -= xisr->sadb_x_ipsecrequest_len;
1503105197Ssam
1504105197Ssam			/* validity check */
1505105197Ssam			if (tlen < 0) {
1506120585Ssam				ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1507120585Ssam					__func__));
1508105197Ssam				KEY_FREESP(&newsp);
1509105197Ssam				*error = EINVAL;
1510105197Ssam				return NULL;
1511105197Ssam			}
1512105197Ssam
1513105197Ssam			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1514105197Ssam			                 + xisr->sadb_x_ipsecrequest_len);
1515105197Ssam		}
1516105197Ssam	    }
1517105197Ssam		break;
1518105197Ssam	default:
1519120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1520105197Ssam		KEY_FREESP(&newsp);
1521105197Ssam		*error = EINVAL;
1522105197Ssam		return NULL;
1523105197Ssam	}
1524105197Ssam
1525105197Ssam	*error = 0;
1526105197Ssam	return newsp;
1527105197Ssam}
1528105197Ssam
1529105197Ssamstatic u_int32_t
1530105197Ssamkey_newreqid()
1531105197Ssam{
1532105197Ssam	static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1533105197Ssam
1534105197Ssam	auto_reqid = (auto_reqid == ~0
1535105197Ssam			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1536105197Ssam
1537105197Ssam	/* XXX should be unique check */
1538105197Ssam
1539105197Ssam	return auto_reqid;
1540105197Ssam}
1541105197Ssam
1542105197Ssam/*
1543105197Ssam * copy secpolicy struct to sadb_x_policy structure indicated.
1544105197Ssam */
1545105197Ssamstruct mbuf *
1546105197Ssamkey_sp2msg(sp)
1547105197Ssam	struct secpolicy *sp;
1548105197Ssam{
1549105197Ssam	struct sadb_x_policy *xpl;
1550105197Ssam	int tlen;
1551105197Ssam	caddr_t p;
1552105197Ssam	struct mbuf *m;
1553105197Ssam
1554120585Ssam	IPSEC_ASSERT(sp != NULL, ("null policy"));
1555105197Ssam
1556105197Ssam	tlen = key_getspreqmsglen(sp);
1557105197Ssam
1558105197Ssam	m = key_alloc_mbuf(tlen);
1559105197Ssam	if (!m || m->m_next) {	/*XXX*/
1560105197Ssam		if (m)
1561105197Ssam			m_freem(m);
1562105197Ssam		return NULL;
1563105197Ssam	}
1564105197Ssam
1565105197Ssam	m->m_len = tlen;
1566105197Ssam	m->m_next = NULL;
1567105197Ssam	xpl = mtod(m, struct sadb_x_policy *);
1568105197Ssam	bzero(xpl, tlen);
1569105197Ssam
1570105197Ssam	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1571105197Ssam	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1572105197Ssam	xpl->sadb_x_policy_type = sp->policy;
1573105197Ssam	xpl->sadb_x_policy_dir = sp->spidx.dir;
1574105197Ssam	xpl->sadb_x_policy_id = sp->id;
1575105197Ssam	p = (caddr_t)xpl + sizeof(*xpl);
1576105197Ssam
1577105197Ssam	/* if is the policy for ipsec ? */
1578105197Ssam	if (sp->policy == IPSEC_POLICY_IPSEC) {
1579105197Ssam		struct sadb_x_ipsecrequest *xisr;
1580105197Ssam		struct ipsecrequest *isr;
1581105197Ssam
1582105197Ssam		for (isr = sp->req; isr != NULL; isr = isr->next) {
1583105197Ssam
1584105197Ssam			xisr = (struct sadb_x_ipsecrequest *)p;
1585105197Ssam
1586105197Ssam			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1587105197Ssam			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1588105197Ssam			xisr->sadb_x_ipsecrequest_level = isr->level;
1589105197Ssam			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1590105197Ssam
1591105197Ssam			p += sizeof(*xisr);
1592105197Ssam			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1593105197Ssam			p += isr->saidx.src.sa.sa_len;
1594105197Ssam			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1595105197Ssam			p += isr->saidx.src.sa.sa_len;
1596105197Ssam
1597105197Ssam			xisr->sadb_x_ipsecrequest_len =
1598105197Ssam				PFKEY_ALIGN8(sizeof(*xisr)
1599105197Ssam					+ isr->saidx.src.sa.sa_len
1600105197Ssam					+ isr->saidx.dst.sa.sa_len);
1601105197Ssam		}
1602105197Ssam	}
1603105197Ssam
1604105197Ssam	return m;
1605105197Ssam}
1606105197Ssam
1607105197Ssam/* m will not be freed nor modified */
1608105197Ssamstatic struct mbuf *
1609105197Ssam#ifdef __STDC__
1610105197Ssamkey_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1611105197Ssam	int ndeep, int nitem, ...)
1612105197Ssam#else
1613105197Ssamkey_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1614105197Ssam	struct mbuf *m;
1615105197Ssam	const struct sadb_msghdr *mhp;
1616105197Ssam	int ndeep;
1617105197Ssam	int nitem;
1618105197Ssam	va_dcl
1619105197Ssam#endif
1620105197Ssam{
1621105197Ssam	va_list ap;
1622105197Ssam	int idx;
1623105197Ssam	int i;
1624105197Ssam	struct mbuf *result = NULL, *n;
1625105197Ssam	int len;
1626105197Ssam
1627120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1628120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1629105197Ssam
1630105197Ssam	va_start(ap, nitem);
1631105197Ssam	for (i = 0; i < nitem; i++) {
1632105197Ssam		idx = va_arg(ap, int);
1633105197Ssam		if (idx < 0 || idx > SADB_EXT_MAX)
1634105197Ssam			goto fail;
1635105197Ssam		/* don't attempt to pull empty extension */
1636105197Ssam		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1637105197Ssam			continue;
1638105197Ssam		if (idx != SADB_EXT_RESERVED  &&
1639105197Ssam		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1640105197Ssam			continue;
1641105197Ssam
1642105197Ssam		if (idx == SADB_EXT_RESERVED) {
1643105197Ssam			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1644120585Ssam
1645120585Ssam			IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1646120585Ssam
1647111119Simp			MGETHDR(n, M_DONTWAIT, MT_DATA);
1648105197Ssam			if (!n)
1649105197Ssam				goto fail;
1650105197Ssam			n->m_len = len;
1651105197Ssam			n->m_next = NULL;
1652105197Ssam			m_copydata(m, 0, sizeof(struct sadb_msg),
1653105197Ssam			    mtod(n, caddr_t));
1654105197Ssam		} else if (i < ndeep) {
1655105197Ssam			len = mhp->extlen[idx];
1656105197Ssam			n = key_alloc_mbuf(len);
1657105197Ssam			if (!n || n->m_next) {	/*XXX*/
1658105197Ssam				if (n)
1659105197Ssam					m_freem(n);
1660105197Ssam				goto fail;
1661105197Ssam			}
1662105197Ssam			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1663105197Ssam			    mtod(n, caddr_t));
1664105197Ssam		} else {
1665105197Ssam			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1666111119Simp			    M_DONTWAIT);
1667105197Ssam		}
1668105197Ssam		if (n == NULL)
1669105197Ssam			goto fail;
1670105197Ssam
1671105197Ssam		if (result)
1672105197Ssam			m_cat(result, n);
1673105197Ssam		else
1674105197Ssam			result = n;
1675105197Ssam	}
1676105197Ssam	va_end(ap);
1677105197Ssam
1678105197Ssam	if ((result->m_flags & M_PKTHDR) != 0) {
1679105197Ssam		result->m_pkthdr.len = 0;
1680105197Ssam		for (n = result; n; n = n->m_next)
1681105197Ssam			result->m_pkthdr.len += n->m_len;
1682105197Ssam	}
1683105197Ssam
1684105197Ssam	return result;
1685105197Ssam
1686105197Ssamfail:
1687105197Ssam	m_freem(result);
1688105197Ssam	return NULL;
1689105197Ssam}
1690105197Ssam
1691105197Ssam/*
1692105197Ssam * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1693108533Sschweikh * add an entry to SP database, when received
1694105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1695105197Ssam * from the user(?).
1696105197Ssam * Adding to SP database,
1697105197Ssam * and send
1698105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1699105197Ssam * to the socket which was send.
1700105197Ssam *
1701105197Ssam * SPDADD set a unique policy entry.
1702105197Ssam * SPDSETIDX like SPDADD without a part of policy requests.
1703105197Ssam * SPDUPDATE replace a unique policy entry.
1704105197Ssam *
1705105197Ssam * m will always be freed.
1706105197Ssam */
1707105197Ssamstatic int
1708105197Ssamkey_spdadd(so, m, mhp)
1709105197Ssam	struct socket *so;
1710105197Ssam	struct mbuf *m;
1711105197Ssam	const struct sadb_msghdr *mhp;
1712105197Ssam{
1713105197Ssam	struct sadb_address *src0, *dst0;
1714105197Ssam	struct sadb_x_policy *xpl0, *xpl;
1715105197Ssam	struct sadb_lifetime *lft = NULL;
1716105197Ssam	struct secpolicyindex spidx;
1717105197Ssam	struct secpolicy *newsp;
1718105197Ssam	int error;
1719105197Ssam
1720120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
1721120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1722120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1723120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1724105197Ssam
1725105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1726105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1727105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1728105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1729105197Ssam		return key_senderror(so, m, EINVAL);
1730105197Ssam	}
1731105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1732105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1733105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1734120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1735120585Ssam			__func__));
1736105197Ssam		return key_senderror(so, m, EINVAL);
1737105197Ssam	}
1738105197Ssam	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1739105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1740105197Ssam			< sizeof(struct sadb_lifetime)) {
1741120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1742120585Ssam				__func__));
1743105197Ssam			return key_senderror(so, m, EINVAL);
1744105197Ssam		}
1745105197Ssam		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1746105197Ssam	}
1747105197Ssam
1748105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1749105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1750105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1751105197Ssam
1752105197Ssam	/* make secindex */
1753105197Ssam	/* XXX boundary check against sa_len */
1754105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1755105197Ssam	                src0 + 1,
1756105197Ssam	                dst0 + 1,
1757105197Ssam	                src0->sadb_address_prefixlen,
1758105197Ssam	                dst0->sadb_address_prefixlen,
1759105197Ssam	                src0->sadb_address_proto,
1760105197Ssam	                &spidx);
1761105197Ssam
1762105197Ssam	/* checking the direciton. */
1763105197Ssam	switch (xpl0->sadb_x_policy_dir) {
1764105197Ssam	case IPSEC_DIR_INBOUND:
1765105197Ssam	case IPSEC_DIR_OUTBOUND:
1766105197Ssam		break;
1767105197Ssam	default:
1768120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1769105197Ssam		mhp->msg->sadb_msg_errno = EINVAL;
1770105197Ssam		return 0;
1771105197Ssam	}
1772105197Ssam
1773105197Ssam	/* check policy */
1774105197Ssam	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1775105197Ssam	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1776105197Ssam	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1777120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1778105197Ssam		return key_senderror(so, m, EINVAL);
1779105197Ssam	}
1780105197Ssam
1781105197Ssam	/* policy requests are mandatory when action is ipsec. */
1782105197Ssam        if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1783105197Ssam	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1784105197Ssam	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1785120585Ssam		ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1786120585Ssam			__func__));
1787105197Ssam		return key_senderror(so, m, EINVAL);
1788105197Ssam	}
1789105197Ssam
1790105197Ssam	/*
1791105197Ssam	 * checking there is SP already or not.
1792105197Ssam	 * SPDUPDATE doesn't depend on whether there is a SP or not.
1793105197Ssam	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1794105197Ssam	 * then error.
1795105197Ssam	 */
1796105197Ssam	newsp = key_getsp(&spidx);
1797105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1798105197Ssam		if (newsp) {
1799105197Ssam			newsp->state = IPSEC_SPSTATE_DEAD;
1800105197Ssam			KEY_FREESP(&newsp);
1801105197Ssam		}
1802105197Ssam	} else {
1803105197Ssam		if (newsp != NULL) {
1804105197Ssam			KEY_FREESP(&newsp);
1805120585Ssam			ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1806120585Ssam				__func__));
1807105197Ssam			return key_senderror(so, m, EEXIST);
1808105197Ssam		}
1809105197Ssam	}
1810105197Ssam
1811105197Ssam	/* allocation new SP entry */
1812105197Ssam	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1813105197Ssam		return key_senderror(so, m, error);
1814105197Ssam	}
1815105197Ssam
1816105197Ssam	if ((newsp->id = key_getnewspid()) == 0) {
1817119643Ssam		_key_delsp(newsp);
1818105197Ssam		return key_senderror(so, m, ENOBUFS);
1819105197Ssam	}
1820105197Ssam
1821105197Ssam	/* XXX boundary check against sa_len */
1822105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1823105197Ssam	                src0 + 1,
1824105197Ssam	                dst0 + 1,
1825105197Ssam	                src0->sadb_address_prefixlen,
1826105197Ssam	                dst0->sadb_address_prefixlen,
1827105197Ssam	                src0->sadb_address_proto,
1828105197Ssam	                &newsp->spidx);
1829105197Ssam
1830105197Ssam	/* sanity check on addr pair */
1831105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1832105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_family) {
1833119643Ssam		_key_delsp(newsp);
1834105197Ssam		return key_senderror(so, m, EINVAL);
1835105197Ssam	}
1836105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1837105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_len) {
1838119643Ssam		_key_delsp(newsp);
1839105197Ssam		return key_senderror(so, m, EINVAL);
1840105197Ssam	}
1841105197Ssam#if 1
1842105197Ssam	if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
1843105197Ssam		struct sockaddr *sa;
1844105197Ssam		sa = (struct sockaddr *)(src0 + 1);
1845105197Ssam		if (sa->sa_family != newsp->req->saidx.src.sa.sa_family) {
1846119643Ssam			_key_delsp(newsp);
1847105197Ssam			return key_senderror(so, m, EINVAL);
1848105197Ssam		}
1849105197Ssam	}
1850105197Ssam	if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
1851105197Ssam		struct sockaddr *sa;
1852105197Ssam		sa = (struct sockaddr *)(dst0 + 1);
1853105197Ssam		if (sa->sa_family != newsp->req->saidx.dst.sa.sa_family) {
1854119643Ssam			_key_delsp(newsp);
1855105197Ssam			return key_senderror(so, m, EINVAL);
1856105197Ssam		}
1857105197Ssam	}
1858105197Ssam#endif
1859105197Ssam
1860105197Ssam	newsp->created = time_second;
1861105197Ssam	newsp->lastused = newsp->created;
1862105197Ssam	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1863105197Ssam	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1864105197Ssam
1865105197Ssam	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1866105197Ssam	newsp->state = IPSEC_SPSTATE_ALIVE;
1867105197Ssam	LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1868105197Ssam
1869105197Ssam	/* delete the entry in spacqtree */
1870105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1871119643Ssam		struct secspacq *spacq = key_getspacq(&spidx);
1872119643Ssam		if (spacq != NULL) {
1873105197Ssam			/* reset counter in order to deletion by timehandler. */
1874105197Ssam			spacq->created = time_second;
1875105197Ssam			spacq->count = 0;
1876120585Ssam			SPACQ_UNLOCK();
1877105197Ssam		}
1878105197Ssam    	}
1879105197Ssam
1880105197Ssam    {
1881105197Ssam	struct mbuf *n, *mpolicy;
1882105197Ssam	struct sadb_msg *newmsg;
1883105197Ssam	int off;
1884105197Ssam
1885105197Ssam	/* create new sadb_msg to reply. */
1886105197Ssam	if (lft) {
1887105197Ssam		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1888105197Ssam		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1889105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1890105197Ssam	} else {
1891105197Ssam		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1892105197Ssam		    SADB_X_EXT_POLICY,
1893105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1894105197Ssam	}
1895105197Ssam	if (!n)
1896105197Ssam		return key_senderror(so, m, ENOBUFS);
1897105197Ssam
1898105197Ssam	if (n->m_len < sizeof(*newmsg)) {
1899105197Ssam		n = m_pullup(n, sizeof(*newmsg));
1900105197Ssam		if (!n)
1901105197Ssam			return key_senderror(so, m, ENOBUFS);
1902105197Ssam	}
1903105197Ssam	newmsg = mtod(n, struct sadb_msg *);
1904105197Ssam	newmsg->sadb_msg_errno = 0;
1905105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1906105197Ssam
1907105197Ssam	off = 0;
1908105197Ssam	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1909105197Ssam	    sizeof(*xpl), &off);
1910105197Ssam	if (mpolicy == NULL) {
1911105197Ssam		/* n is already freed */
1912105197Ssam		return key_senderror(so, m, ENOBUFS);
1913105197Ssam	}
1914105197Ssam	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1915105197Ssam	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1916105197Ssam		m_freem(n);
1917105197Ssam		return key_senderror(so, m, EINVAL);
1918105197Ssam	}
1919105197Ssam	xpl->sadb_x_policy_id = newsp->id;
1920105197Ssam
1921105197Ssam	m_freem(m);
1922105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1923105197Ssam    }
1924105197Ssam}
1925105197Ssam
1926105197Ssam/*
1927105197Ssam * get new policy id.
1928105197Ssam * OUT:
1929105197Ssam *	0:	failure.
1930105197Ssam *	others: success.
1931105197Ssam */
1932105197Ssamstatic u_int32_t
1933105197Ssamkey_getnewspid()
1934105197Ssam{
1935105197Ssam	u_int32_t newid = 0;
1936105197Ssam	int count = key_spi_trycnt;	/* XXX */
1937105197Ssam	struct secpolicy *sp;
1938105197Ssam
1939105197Ssam	/* when requesting to allocate spi ranged */
1940105197Ssam	while (count--) {
1941105197Ssam		newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
1942105197Ssam
1943105197Ssam		if ((sp = key_getspbyid(newid)) == NULL)
1944105197Ssam			break;
1945105197Ssam
1946105197Ssam		KEY_FREESP(&sp);
1947105197Ssam	}
1948105197Ssam
1949105197Ssam	if (count == 0 || newid == 0) {
1950120585Ssam		ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
1951120585Ssam			__func__));
1952105197Ssam		return 0;
1953105197Ssam	}
1954105197Ssam
1955105197Ssam	return newid;
1956105197Ssam}
1957105197Ssam
1958105197Ssam/*
1959105197Ssam * SADB_SPDDELETE processing
1960105197Ssam * receive
1961105197Ssam *   <base, address(SD), policy(*)>
1962105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
1963105197Ssam * and send,
1964105197Ssam *   <base, address(SD), policy(*)>
1965105197Ssam * to the ikmpd.
1966105197Ssam * policy(*) including direction of policy.
1967105197Ssam *
1968105197Ssam * m will always be freed.
1969105197Ssam */
1970105197Ssamstatic int
1971105197Ssamkey_spddelete(so, m, mhp)
1972105197Ssam	struct socket *so;
1973105197Ssam	struct mbuf *m;
1974105197Ssam	const struct sadb_msghdr *mhp;
1975105197Ssam{
1976105197Ssam	struct sadb_address *src0, *dst0;
1977105197Ssam	struct sadb_x_policy *xpl0;
1978105197Ssam	struct secpolicyindex spidx;
1979105197Ssam	struct secpolicy *sp;
1980105197Ssam
1981120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
1982120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1983120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1984120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1985105197Ssam
1986105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1987105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1988105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1989120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1990120585Ssam			__func__));
1991105197Ssam		return key_senderror(so, m, EINVAL);
1992105197Ssam	}
1993105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1994105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1995105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1996120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1997120585Ssam			__func__));
1998105197Ssam		return key_senderror(so, m, EINVAL);
1999105197Ssam	}
2000105197Ssam
2001105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2002105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2003105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2004105197Ssam
2005105197Ssam	/* make secindex */
2006105197Ssam	/* XXX boundary check against sa_len */
2007105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2008105197Ssam	                src0 + 1,
2009105197Ssam	                dst0 + 1,
2010105197Ssam	                src0->sadb_address_prefixlen,
2011105197Ssam	                dst0->sadb_address_prefixlen,
2012105197Ssam	                src0->sadb_address_proto,
2013105197Ssam	                &spidx);
2014105197Ssam
2015105197Ssam	/* checking the direciton. */
2016105197Ssam	switch (xpl0->sadb_x_policy_dir) {
2017105197Ssam	case IPSEC_DIR_INBOUND:
2018105197Ssam	case IPSEC_DIR_OUTBOUND:
2019105197Ssam		break;
2020105197Ssam	default:
2021120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2022105197Ssam		return key_senderror(so, m, EINVAL);
2023105197Ssam	}
2024105197Ssam
2025105197Ssam	/* Is there SP in SPD ? */
2026105197Ssam	if ((sp = key_getsp(&spidx)) == NULL) {
2027120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2028105197Ssam		return key_senderror(so, m, EINVAL);
2029105197Ssam	}
2030105197Ssam
2031105197Ssam	/* save policy id to buffer to be returned. */
2032105197Ssam	xpl0->sadb_x_policy_id = sp->id;
2033105197Ssam
2034105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2035120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
2036105197Ssam	KEY_FREESP(&sp);
2037105197Ssam
2038105197Ssam    {
2039105197Ssam	struct mbuf *n;
2040105197Ssam	struct sadb_msg *newmsg;
2041105197Ssam
2042105197Ssam	/* create new sadb_msg to reply. */
2043105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2044105197Ssam	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2045105197Ssam	if (!n)
2046105197Ssam		return key_senderror(so, m, ENOBUFS);
2047105197Ssam
2048105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2049105197Ssam	newmsg->sadb_msg_errno = 0;
2050105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2051105197Ssam
2052105197Ssam	m_freem(m);
2053105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2054105197Ssam    }
2055105197Ssam}
2056105197Ssam
2057105197Ssam/*
2058105197Ssam * SADB_SPDDELETE2 processing
2059105197Ssam * receive
2060105197Ssam *   <base, policy(*)>
2061105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2062105197Ssam * and send,
2063105197Ssam *   <base, policy(*)>
2064105197Ssam * to the ikmpd.
2065105197Ssam * policy(*) including direction of policy.
2066105197Ssam *
2067105197Ssam * m will always be freed.
2068105197Ssam */
2069105197Ssamstatic int
2070105197Ssamkey_spddelete2(so, m, mhp)
2071105197Ssam	struct socket *so;
2072105197Ssam	struct mbuf *m;
2073105197Ssam	const struct sadb_msghdr *mhp;
2074105197Ssam{
2075105197Ssam	u_int32_t id;
2076105197Ssam	struct secpolicy *sp;
2077105197Ssam
2078120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2079120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2080120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2081120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2082105197Ssam
2083105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2084105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2085120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2086105197Ssam		key_senderror(so, m, EINVAL);
2087105197Ssam		return 0;
2088105197Ssam	}
2089105197Ssam
2090105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2091105197Ssam
2092105197Ssam	/* Is there SP in SPD ? */
2093105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2094120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2095105197Ssam		key_senderror(so, m, EINVAL);
2096105197Ssam	}
2097105197Ssam
2098105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2099120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
2100105197Ssam	KEY_FREESP(&sp);
2101105197Ssam
2102105197Ssam    {
2103105197Ssam	struct mbuf *n, *nn;
2104105197Ssam	struct sadb_msg *newmsg;
2105105197Ssam	int off, len;
2106105197Ssam
2107105197Ssam	/* create new sadb_msg to reply. */
2108105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2109105197Ssam
2110105197Ssam	if (len > MCLBYTES)
2111105197Ssam		return key_senderror(so, m, ENOBUFS);
2112111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
2113105197Ssam	if (n && len > MHLEN) {
2114111119Simp		MCLGET(n, M_DONTWAIT);
2115105197Ssam		if ((n->m_flags & M_EXT) == 0) {
2116105197Ssam			m_freem(n);
2117105197Ssam			n = NULL;
2118105197Ssam		}
2119105197Ssam	}
2120105197Ssam	if (!n)
2121105197Ssam		return key_senderror(so, m, ENOBUFS);
2122105197Ssam
2123105197Ssam	n->m_len = len;
2124105197Ssam	n->m_next = NULL;
2125105197Ssam	off = 0;
2126105197Ssam
2127105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2128105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2129105197Ssam
2130120585Ssam	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2131120585Ssam		off, len));
2132105197Ssam
2133105197Ssam	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2134111119Simp	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2135105197Ssam	if (!n->m_next) {
2136105197Ssam		m_freem(n);
2137105197Ssam		return key_senderror(so, m, ENOBUFS);
2138105197Ssam	}
2139105197Ssam
2140105197Ssam	n->m_pkthdr.len = 0;
2141105197Ssam	for (nn = n; nn; nn = nn->m_next)
2142105197Ssam		n->m_pkthdr.len += nn->m_len;
2143105197Ssam
2144105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2145105197Ssam	newmsg->sadb_msg_errno = 0;
2146105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2147105197Ssam
2148105197Ssam	m_freem(m);
2149105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2150105197Ssam    }
2151105197Ssam}
2152105197Ssam
2153105197Ssam/*
2154105197Ssam * SADB_X_GET processing
2155105197Ssam * receive
2156105197Ssam *   <base, policy(*)>
2157105197Ssam * from the user(?),
2158105197Ssam * and send,
2159105197Ssam *   <base, address(SD), policy>
2160105197Ssam * to the ikmpd.
2161105197Ssam * policy(*) including direction of policy.
2162105197Ssam *
2163105197Ssam * m will always be freed.
2164105197Ssam */
2165105197Ssamstatic int
2166105197Ssamkey_spdget(so, m, mhp)
2167105197Ssam	struct socket *so;
2168105197Ssam	struct mbuf *m;
2169105197Ssam	const struct sadb_msghdr *mhp;
2170105197Ssam{
2171105197Ssam	u_int32_t id;
2172105197Ssam	struct secpolicy *sp;
2173105197Ssam	struct mbuf *n;
2174105197Ssam
2175120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2176120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2177120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2178120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2179105197Ssam
2180105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2181105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2182120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2183120585Ssam			__func__));
2184105197Ssam		return key_senderror(so, m, EINVAL);
2185105197Ssam	}
2186105197Ssam
2187105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2188105197Ssam
2189105197Ssam	/* Is there SP in SPD ? */
2190105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2191120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2192105197Ssam		return key_senderror(so, m, ENOENT);
2193105197Ssam	}
2194105197Ssam
2195105197Ssam	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2196105197Ssam	if (n != NULL) {
2197105197Ssam		m_freem(m);
2198105197Ssam		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2199105197Ssam	} else
2200105197Ssam		return key_senderror(so, m, ENOBUFS);
2201105197Ssam}
2202105197Ssam
2203105197Ssam/*
2204105197Ssam * SADB_X_SPDACQUIRE processing.
2205105197Ssam * Acquire policy and SA(s) for a *OUTBOUND* packet.
2206105197Ssam * send
2207105197Ssam *   <base, policy(*)>
2208105197Ssam * to KMD, and expect to receive
2209105197Ssam *   <base> with SADB_X_SPDACQUIRE if error occured,
2210105197Ssam * or
2211105197Ssam *   <base, policy>
2212105197Ssam * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2213105197Ssam * policy(*) is without policy requests.
2214105197Ssam *
2215105197Ssam *    0     : succeed
2216105197Ssam *    others: error number
2217105197Ssam */
2218105197Ssamint
2219105197Ssamkey_spdacquire(sp)
2220105197Ssam	struct secpolicy *sp;
2221105197Ssam{
2222105197Ssam	struct mbuf *result = NULL, *m;
2223105197Ssam	struct secspacq *newspacq;
2224105197Ssam	int error;
2225105197Ssam
2226120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2227120585Ssam	IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2228120585Ssam	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2229120585Ssam		("policy not IPSEC %u", sp->policy));
2230105197Ssam
2231108533Sschweikh	/* Get an entry to check whether sent message or not. */
2232119643Ssam	newspacq = key_getspacq(&sp->spidx);
2233119643Ssam	if (newspacq != NULL) {
2234105197Ssam		if (key_blockacq_count < newspacq->count) {
2235105197Ssam			/* reset counter and do send message. */
2236105197Ssam			newspacq->count = 0;
2237105197Ssam		} else {
2238105197Ssam			/* increment counter and do nothing. */
2239105197Ssam			newspacq->count++;
2240105197Ssam			return 0;
2241105197Ssam		}
2242120585Ssam		SPACQ_UNLOCK();
2243105197Ssam	} else {
2244105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
2245119643Ssam		newspacq = key_newspacq(&sp->spidx);
2246119643Ssam		if (newspacq == NULL)
2247105197Ssam			return ENOBUFS;
2248105197Ssam	}
2249105197Ssam
2250105197Ssam	/* create new sadb_msg to reply. */
2251105197Ssam	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2252105197Ssam	if (!m) {
2253105197Ssam		error = ENOBUFS;
2254105197Ssam		goto fail;
2255105197Ssam	}
2256105197Ssam	result = m;
2257105197Ssam
2258105197Ssam	result->m_pkthdr.len = 0;
2259105197Ssam	for (m = result; m; m = m->m_next)
2260105197Ssam		result->m_pkthdr.len += m->m_len;
2261105197Ssam
2262105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2263105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2264105197Ssam
2265105197Ssam	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2266105197Ssam
2267105197Ssamfail:
2268105197Ssam	if (result)
2269105197Ssam		m_freem(result);
2270105197Ssam	return error;
2271105197Ssam}
2272105197Ssam
2273105197Ssam/*
2274105197Ssam * SADB_SPDFLUSH processing
2275105197Ssam * receive
2276105197Ssam *   <base>
2277105197Ssam * from the user, and free all entries in secpctree.
2278105197Ssam * and send,
2279105197Ssam *   <base>
2280105197Ssam * to the user.
2281105197Ssam * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2282105197Ssam *
2283105197Ssam * m will always be freed.
2284105197Ssam */
2285105197Ssamstatic int
2286105197Ssamkey_spdflush(so, m, mhp)
2287105197Ssam	struct socket *so;
2288105197Ssam	struct mbuf *m;
2289105197Ssam	const struct sadb_msghdr *mhp;
2290105197Ssam{
2291105197Ssam	struct sadb_msg *newmsg;
2292105197Ssam	struct secpolicy *sp;
2293105197Ssam	u_int dir;
2294105197Ssam
2295120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2296120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2297120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2298120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2299105197Ssam
2300105197Ssam	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2301105197Ssam		return key_senderror(so, m, EINVAL);
2302105197Ssam
2303105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2304120585Ssam		SPTREE_LOCK();
2305120585Ssam		LIST_FOREACH(sp, &sptree[dir], chain)
2306105197Ssam			sp->state = IPSEC_SPSTATE_DEAD;
2307120585Ssam		SPTREE_UNLOCK();
2308105197Ssam	}
2309105197Ssam
2310105197Ssam	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2311120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2312105197Ssam		return key_senderror(so, m, ENOBUFS);
2313105197Ssam	}
2314105197Ssam
2315105197Ssam	if (m->m_next)
2316105197Ssam		m_freem(m->m_next);
2317105197Ssam	m->m_next = NULL;
2318105197Ssam	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2319105197Ssam	newmsg = mtod(m, struct sadb_msg *);
2320105197Ssam	newmsg->sadb_msg_errno = 0;
2321105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2322105197Ssam
2323105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2324105197Ssam}
2325105197Ssam
2326105197Ssam/*
2327105197Ssam * SADB_SPDDUMP processing
2328105197Ssam * receive
2329105197Ssam *   <base>
2330105197Ssam * from the user, and dump all SP leaves
2331105197Ssam * and send,
2332105197Ssam *   <base> .....
2333105197Ssam * to the ikmpd.
2334105197Ssam *
2335105197Ssam * m will always be freed.
2336105197Ssam */
2337105197Ssamstatic int
2338105197Ssamkey_spddump(so, m, mhp)
2339105197Ssam	struct socket *so;
2340105197Ssam	struct mbuf *m;
2341105197Ssam	const struct sadb_msghdr *mhp;
2342105197Ssam{
2343105197Ssam	struct secpolicy *sp;
2344105197Ssam	int cnt;
2345105197Ssam	u_int dir;
2346105197Ssam	struct mbuf *n;
2347105197Ssam
2348120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2349120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2350120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2351120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2352105197Ssam
2353105197Ssam	/* search SPD entry and get buffer size. */
2354105197Ssam	cnt = 0;
2355105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2356105197Ssam		LIST_FOREACH(sp, &sptree[dir], chain) {
2357105197Ssam			cnt++;
2358105197Ssam		}
2359105197Ssam	}
2360105197Ssam
2361105197Ssam	if (cnt == 0)
2362105197Ssam		return key_senderror(so, m, ENOENT);
2363105197Ssam
2364105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2365105197Ssam		LIST_FOREACH(sp, &sptree[dir], chain) {
2366105197Ssam			--cnt;
2367105197Ssam			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2368105197Ssam			    mhp->msg->sadb_msg_pid);
2369105197Ssam
2370105197Ssam			if (n)
2371105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2372105197Ssam		}
2373105197Ssam	}
2374105197Ssam
2375105197Ssam	m_freem(m);
2376105197Ssam	return 0;
2377105197Ssam}
2378105197Ssam
2379105197Ssamstatic struct mbuf *
2380105197Ssamkey_setdumpsp(sp, type, seq, pid)
2381105197Ssam	struct secpolicy *sp;
2382105197Ssam	u_int8_t type;
2383105197Ssam	u_int32_t seq, pid;
2384105197Ssam{
2385105197Ssam	struct mbuf *result = NULL, *m;
2386105197Ssam
2387105197Ssam	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2388105197Ssam	if (!m)
2389105197Ssam		goto fail;
2390105197Ssam	result = m;
2391105197Ssam
2392105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2393105197Ssam	    &sp->spidx.src.sa, sp->spidx.prefs,
2394105197Ssam	    sp->spidx.ul_proto);
2395105197Ssam	if (!m)
2396105197Ssam		goto fail;
2397105197Ssam	m_cat(result, m);
2398105197Ssam
2399105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2400105197Ssam	    &sp->spidx.dst.sa, sp->spidx.prefd,
2401105197Ssam	    sp->spidx.ul_proto);
2402105197Ssam	if (!m)
2403105197Ssam		goto fail;
2404105197Ssam	m_cat(result, m);
2405105197Ssam
2406105197Ssam	m = key_sp2msg(sp);
2407105197Ssam	if (!m)
2408105197Ssam		goto fail;
2409105197Ssam	m_cat(result, m);
2410105197Ssam
2411105197Ssam	if ((result->m_flags & M_PKTHDR) == 0)
2412105197Ssam		goto fail;
2413105197Ssam
2414105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2415105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2416105197Ssam		if (result == NULL)
2417105197Ssam			goto fail;
2418105197Ssam	}
2419105197Ssam
2420105197Ssam	result->m_pkthdr.len = 0;
2421105197Ssam	for (m = result; m; m = m->m_next)
2422105197Ssam		result->m_pkthdr.len += m->m_len;
2423105197Ssam
2424105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2425105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2426105197Ssam
2427105197Ssam	return result;
2428105197Ssam
2429105197Ssamfail:
2430105197Ssam	m_freem(result);
2431105197Ssam	return NULL;
2432105197Ssam}
2433105197Ssam
2434105197Ssam/*
2435105197Ssam * get PFKEY message length for security policy and request.
2436105197Ssam */
2437105197Ssamstatic u_int
2438105197Ssamkey_getspreqmsglen(sp)
2439105197Ssam	struct secpolicy *sp;
2440105197Ssam{
2441105197Ssam	u_int tlen;
2442105197Ssam
2443105197Ssam	tlen = sizeof(struct sadb_x_policy);
2444105197Ssam
2445105197Ssam	/* if is the policy for ipsec ? */
2446105197Ssam	if (sp->policy != IPSEC_POLICY_IPSEC)
2447105197Ssam		return tlen;
2448105197Ssam
2449105197Ssam	/* get length of ipsec requests */
2450105197Ssam    {
2451105197Ssam	struct ipsecrequest *isr;
2452105197Ssam	int len;
2453105197Ssam
2454105197Ssam	for (isr = sp->req; isr != NULL; isr = isr->next) {
2455105197Ssam		len = sizeof(struct sadb_x_ipsecrequest)
2456105197Ssam			+ isr->saidx.src.sa.sa_len
2457105197Ssam			+ isr->saidx.dst.sa.sa_len;
2458105197Ssam
2459105197Ssam		tlen += PFKEY_ALIGN8(len);
2460105197Ssam	}
2461105197Ssam    }
2462105197Ssam
2463105197Ssam	return tlen;
2464105197Ssam}
2465105197Ssam
2466105197Ssam/*
2467105197Ssam * SADB_SPDEXPIRE processing
2468105197Ssam * send
2469105197Ssam *   <base, address(SD), lifetime(CH), policy>
2470105197Ssam * to KMD by PF_KEY.
2471105197Ssam *
2472105197Ssam * OUT:	0	: succeed
2473105197Ssam *	others	: error number
2474105197Ssam */
2475105197Ssamstatic int
2476105197Ssamkey_spdexpire(sp)
2477105197Ssam	struct secpolicy *sp;
2478105197Ssam{
2479105197Ssam	struct mbuf *result = NULL, *m;
2480105197Ssam	int len;
2481105197Ssam	int error = -1;
2482105197Ssam	struct sadb_lifetime *lt;
2483105197Ssam
2484105197Ssam	/* XXX: Why do we lock ? */
2485105197Ssam
2486120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2487105197Ssam
2488105197Ssam	/* set msg header */
2489105197Ssam	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2490105197Ssam	if (!m) {
2491105197Ssam		error = ENOBUFS;
2492105197Ssam		goto fail;
2493105197Ssam	}
2494105197Ssam	result = m;
2495105197Ssam
2496105197Ssam	/* create lifetime extension (current and hard) */
2497105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2498105197Ssam	m = key_alloc_mbuf(len);
2499105197Ssam	if (!m || m->m_next) {	/*XXX*/
2500105197Ssam		if (m)
2501105197Ssam			m_freem(m);
2502105197Ssam		error = ENOBUFS;
2503105197Ssam		goto fail;
2504105197Ssam	}
2505105197Ssam	bzero(mtod(m, caddr_t), len);
2506105197Ssam	lt = mtod(m, struct sadb_lifetime *);
2507105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2508105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2509105197Ssam	lt->sadb_lifetime_allocations = 0;
2510105197Ssam	lt->sadb_lifetime_bytes = 0;
2511105197Ssam	lt->sadb_lifetime_addtime = sp->created;
2512105197Ssam	lt->sadb_lifetime_usetime = sp->lastused;
2513105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2514105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2515105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2516105197Ssam	lt->sadb_lifetime_allocations = 0;
2517105197Ssam	lt->sadb_lifetime_bytes = 0;
2518105197Ssam	lt->sadb_lifetime_addtime = sp->lifetime;
2519105197Ssam	lt->sadb_lifetime_usetime = sp->validtime;
2520105197Ssam	m_cat(result, m);
2521105197Ssam
2522105197Ssam	/* set sadb_address for source */
2523105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2524105197Ssam	    &sp->spidx.src.sa,
2525105197Ssam	    sp->spidx.prefs, sp->spidx.ul_proto);
2526105197Ssam	if (!m) {
2527105197Ssam		error = ENOBUFS;
2528105197Ssam		goto fail;
2529105197Ssam	}
2530105197Ssam	m_cat(result, m);
2531105197Ssam
2532105197Ssam	/* set sadb_address for destination */
2533105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2534105197Ssam	    &sp->spidx.dst.sa,
2535105197Ssam	    sp->spidx.prefd, sp->spidx.ul_proto);
2536105197Ssam	if (!m) {
2537105197Ssam		error = ENOBUFS;
2538105197Ssam		goto fail;
2539105197Ssam	}
2540105197Ssam	m_cat(result, m);
2541105197Ssam
2542105197Ssam	/* set secpolicy */
2543105197Ssam	m = key_sp2msg(sp);
2544105197Ssam	if (!m) {
2545105197Ssam		error = ENOBUFS;
2546105197Ssam		goto fail;
2547105197Ssam	}
2548105197Ssam	m_cat(result, m);
2549105197Ssam
2550105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
2551105197Ssam		error = EINVAL;
2552105197Ssam		goto fail;
2553105197Ssam	}
2554105197Ssam
2555105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2556105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2557105197Ssam		if (result == NULL) {
2558105197Ssam			error = ENOBUFS;
2559105197Ssam			goto fail;
2560105197Ssam		}
2561105197Ssam	}
2562105197Ssam
2563105197Ssam	result->m_pkthdr.len = 0;
2564105197Ssam	for (m = result; m; m = m->m_next)
2565105197Ssam		result->m_pkthdr.len += m->m_len;
2566105197Ssam
2567105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2568105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2569105197Ssam
2570105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2571105197Ssam
2572105197Ssam fail:
2573105197Ssam	if (result)
2574105197Ssam		m_freem(result);
2575105197Ssam	return error;
2576105197Ssam}
2577105197Ssam
2578105197Ssam/* %%% SAD management */
2579105197Ssam/*
2580105197Ssam * allocating a memory for new SA head, and copy from the values of mhp.
2581105197Ssam * OUT:	NULL	: failure due to the lack of memory.
2582105197Ssam *	others	: pointer to new SA head.
2583105197Ssam */
2584105197Ssamstatic struct secashead *
2585105197Ssamkey_newsah(saidx)
2586105197Ssam	struct secasindex *saidx;
2587105197Ssam{
2588105197Ssam	struct secashead *newsah;
2589105197Ssam
2590120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2591105197Ssam
2592119643Ssam	newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2593105197Ssam	if (newsah != NULL) {
2594105197Ssam		int i;
2595105197Ssam		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2596105197Ssam			LIST_INIT(&newsah->savtree[i]);
2597105197Ssam		newsah->saidx = *saidx;
2598105197Ssam
2599105197Ssam		/* add to saidxtree */
2600105197Ssam		newsah->state = SADB_SASTATE_MATURE;
2601119643Ssam
2602120585Ssam		SAHTREE_LOCK();
2603105197Ssam		LIST_INSERT_HEAD(&sahtree, newsah, chain);
2604120585Ssam		SAHTREE_UNLOCK();
2605105197Ssam	}
2606105197Ssam	return(newsah);
2607105197Ssam}
2608105197Ssam
2609105197Ssam/*
2610105197Ssam * delete SA index and all SA registerd.
2611105197Ssam */
2612105197Ssamstatic void
2613105197Ssamkey_delsah(sah)
2614105197Ssam	struct secashead *sah;
2615105197Ssam{
2616105197Ssam	struct secasvar *sav, *nextsav;
2617120585Ssam	u_int stateidx;
2618105197Ssam	int zombie = 0;
2619105197Ssam
2620120585Ssam	IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2621120585Ssam	SAHTREE_LOCK_ASSERT();
2622105197Ssam
2623105197Ssam	/* searching all SA registerd in the secindex. */
2624105197Ssam	for (stateidx = 0;
2625105197Ssam	     stateidx < _ARRAYLEN(saorder_state_any);
2626105197Ssam	     stateidx++) {
2627120585Ssam		u_int state = saorder_state_any[stateidx];
2628120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2629105197Ssam			if (sav->refcnt == 0) {
2630105197Ssam				/* sanity check */
2631120585Ssam				KEY_CHKSASTATE(state, sav->state, __func__);
2632105197Ssam				KEY_FREESAV(&sav);
2633105197Ssam			} else {
2634105197Ssam				/* give up to delete this sa */
2635105197Ssam				zombie++;
2636105197Ssam			}
2637105197Ssam		}
2638105197Ssam	}
2639120585Ssam	if (!zombie) {		/* delete only if there are savs */
2640120585Ssam		/* remove from tree of SA index */
2641120585Ssam		if (__LIST_CHAINED(sah))
2642120585Ssam			LIST_REMOVE(sah, chain);
2643120585Ssam		if (sah->sa_route.ro_rt) {
2644120585Ssam			RTFREE(sah->sa_route.ro_rt);
2645120585Ssam			sah->sa_route.ro_rt = (struct rtentry *)NULL;
2646120585Ssam		}
2647120585Ssam		free(sah, M_IPSEC_SAH);
2648105197Ssam	}
2649105197Ssam}
2650105197Ssam
2651105197Ssam/*
2652105197Ssam * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2653105197Ssam * and copy the values of mhp into new buffer.
2654105197Ssam * When SAD message type is GETSPI:
2655105197Ssam *	to set sequence number from acq_seq++,
2656105197Ssam *	to set zero to SPI.
2657105197Ssam *	not to call key_setsava().
2658105197Ssam * OUT:	NULL	: fail
2659105197Ssam *	others	: pointer to new secasvar.
2660105197Ssam *
2661105197Ssam * does not modify mbuf.  does not free mbuf on error.
2662105197Ssam */
2663105197Ssamstatic struct secasvar *
2664105197Ssamkey_newsav(m, mhp, sah, errp, where, tag)
2665105197Ssam	struct mbuf *m;
2666105197Ssam	const struct sadb_msghdr *mhp;
2667105197Ssam	struct secashead *sah;
2668105197Ssam	int *errp;
2669105197Ssam	const char* where;
2670105197Ssam	int tag;
2671105197Ssam{
2672105197Ssam	struct secasvar *newsav;
2673105197Ssam	const struct sadb_sa *xsa;
2674105197Ssam
2675120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2676120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2677120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2678120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
2679105197Ssam
2680119643Ssam	newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2681105197Ssam	if (newsav == NULL) {
2682120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2683105197Ssam		*errp = ENOBUFS;
2684105197Ssam		goto done;
2685105197Ssam	}
2686105197Ssam
2687105197Ssam	switch (mhp->msg->sadb_msg_type) {
2688105197Ssam	case SADB_GETSPI:
2689105197Ssam		newsav->spi = 0;
2690105197Ssam
2691105197Ssam#ifdef IPSEC_DOSEQCHECK
2692105197Ssam		/* sync sequence number */
2693105197Ssam		if (mhp->msg->sadb_msg_seq == 0)
2694105197Ssam			newsav->seq =
2695105197Ssam				(acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
2696105197Ssam		else
2697105197Ssam#endif
2698105197Ssam			newsav->seq = mhp->msg->sadb_msg_seq;
2699105197Ssam		break;
2700105197Ssam
2701105197Ssam	case SADB_ADD:
2702105197Ssam		/* sanity check */
2703105197Ssam		if (mhp->ext[SADB_EXT_SA] == NULL) {
2704119643Ssam			free(newsav, M_IPSEC_SA);
2705119643Ssam			newsav = NULL;
2706120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2707120585Ssam				__func__));
2708105197Ssam			*errp = EINVAL;
2709105197Ssam			goto done;
2710105197Ssam		}
2711105197Ssam		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2712105197Ssam		newsav->spi = xsa->sadb_sa_spi;
2713105197Ssam		newsav->seq = mhp->msg->sadb_msg_seq;
2714105197Ssam		break;
2715105197Ssam	default:
2716119643Ssam		free(newsav, M_IPSEC_SA);
2717119643Ssam		newsav = NULL;
2718105197Ssam		*errp = EINVAL;
2719105197Ssam		goto done;
2720105197Ssam	}
2721105197Ssam
2722119643Ssam
2723105197Ssam	/* copy sav values */
2724105197Ssam	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2725105197Ssam		*errp = key_setsaval(newsav, m, mhp);
2726105197Ssam		if (*errp) {
2727119643Ssam			free(newsav, M_IPSEC_SA);
2728119643Ssam			newsav = NULL;
2729105197Ssam			goto done;
2730105197Ssam		}
2731105197Ssam	}
2732105197Ssam
2733120585Ssam	SECASVAR_LOCK_INIT(newsav);
2734119643Ssam
2735105197Ssam	/* reset created */
2736105197Ssam	newsav->created = time_second;
2737105197Ssam	newsav->pid = mhp->msg->sadb_msg_pid;
2738105197Ssam
2739105197Ssam	/* add to satree */
2740105197Ssam	newsav->sah = sah;
2741105197Ssam	newsav->refcnt = 1;
2742105197Ssam	newsav->state = SADB_SASTATE_LARVAL;
2743119643Ssam
2744119643Ssam	/* XXX locking??? */
2745105197Ssam	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2746105197Ssam			secasvar, chain);
2747105197Ssamdone:
2748105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2749120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
2750105197Ssam			where, tag, newsav));
2751105197Ssam
2752105197Ssam	return newsav;
2753105197Ssam}
2754105197Ssam
2755105197Ssam/*
2756105197Ssam * free() SA variable entry.
2757105197Ssam */
2758105197Ssamstatic void
2759119643Ssamkey_cleansav(struct secasvar *sav)
2760105197Ssam{
2761117051Ssam	/*
2762117051Ssam	 * Cleanup xform state.  Note that zeroize'ing causes the
2763117051Ssam	 * keys to be cleared; otherwise we must do it ourself.
2764117051Ssam	 */
2765117051Ssam	if (sav->tdb_xform != NULL) {
2766117051Ssam		sav->tdb_xform->xf_zeroize(sav);
2767117051Ssam		sav->tdb_xform = NULL;
2768117051Ssam	} else {
2769120585Ssam		KASSERT(sav->iv == NULL, ("iv but no xform"));
2770117051Ssam		if (sav->key_auth != NULL)
2771117051Ssam			bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2772117051Ssam		if (sav->key_enc != NULL)
2773117051Ssam			bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
2774117051Ssam	}
2775105197Ssam	if (sav->key_auth != NULL) {
2776119643Ssam		free(sav->key_auth, M_IPSEC_MISC);
2777105197Ssam		sav->key_auth = NULL;
2778105197Ssam	}
2779105197Ssam	if (sav->key_enc != NULL) {
2780119643Ssam		free(sav->key_enc, M_IPSEC_MISC);
2781105197Ssam		sav->key_enc = NULL;
2782105197Ssam	}
2783105197Ssam	if (sav->sched) {
2784105197Ssam		bzero(sav->sched, sav->schedlen);
2785119643Ssam		free(sav->sched, M_IPSEC_MISC);
2786105197Ssam		sav->sched = NULL;
2787105197Ssam	}
2788105197Ssam	if (sav->replay != NULL) {
2789119643Ssam		free(sav->replay, M_IPSEC_MISC);
2790105197Ssam		sav->replay = NULL;
2791105197Ssam	}
2792105197Ssam	if (sav->lft_c != NULL) {
2793119643Ssam		free(sav->lft_c, M_IPSEC_MISC);
2794105197Ssam		sav->lft_c = NULL;
2795105197Ssam	}
2796105197Ssam	if (sav->lft_h != NULL) {
2797119643Ssam		free(sav->lft_h, M_IPSEC_MISC);
2798105197Ssam		sav->lft_h = NULL;
2799105197Ssam	}
2800105197Ssam	if (sav->lft_s != NULL) {
2801119643Ssam		free(sav->lft_s, M_IPSEC_MISC);
2802105197Ssam		sav->lft_s = NULL;
2803105197Ssam	}
2804119643Ssam}
2805105197Ssam
2806119643Ssam/*
2807119643Ssam * free() SA variable entry.
2808119643Ssam */
2809119643Ssamstatic void
2810119643Ssamkey_delsav(sav)
2811119643Ssam	struct secasvar *sav;
2812119643Ssam{
2813120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
2814120585Ssam	IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2815105197Ssam
2816119643Ssam	/* remove from SA header */
2817119643Ssam	if (__LIST_CHAINED(sav))
2818119643Ssam		LIST_REMOVE(sav, chain);
2819119643Ssam	key_cleansav(sav);
2820120585Ssam	SECASVAR_LOCK_DESTROY(sav);
2821119643Ssam	free(sav, M_IPSEC_SA);
2822105197Ssam}
2823105197Ssam
2824105197Ssam/*
2825105197Ssam * search SAD.
2826105197Ssam * OUT:
2827105197Ssam *	NULL	: not found
2828105197Ssam *	others	: found, pointer to a SA.
2829105197Ssam */
2830105197Ssamstatic struct secashead *
2831105197Ssamkey_getsah(saidx)
2832105197Ssam	struct secasindex *saidx;
2833105197Ssam{
2834105197Ssam	struct secashead *sah;
2835105197Ssam
2836120585Ssam	SAHTREE_LOCK();
2837105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
2838105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
2839105197Ssam			continue;
2840105197Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2841119643Ssam			break;
2842105197Ssam	}
2843120585Ssam	SAHTREE_UNLOCK();
2844105197Ssam
2845119643Ssam	return sah;
2846105197Ssam}
2847105197Ssam
2848105197Ssam/*
2849105197Ssam * check not to be duplicated SPI.
2850105197Ssam * NOTE: this function is too slow due to searching all SAD.
2851105197Ssam * OUT:
2852105197Ssam *	NULL	: not found
2853105197Ssam *	others	: found, pointer to a SA.
2854105197Ssam */
2855105197Ssamstatic struct secasvar *
2856105197Ssamkey_checkspidup(saidx, spi)
2857105197Ssam	struct secasindex *saidx;
2858105197Ssam	u_int32_t spi;
2859105197Ssam{
2860105197Ssam	struct secashead *sah;
2861105197Ssam	struct secasvar *sav;
2862105197Ssam
2863105197Ssam	/* check address family */
2864105197Ssam	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2865120585Ssam		ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2866120585Ssam			__func__));
2867105197Ssam		return NULL;
2868105197Ssam	}
2869105197Ssam
2870119643Ssam	sav = NULL;
2871105197Ssam	/* check all SAD */
2872120585Ssam	SAHTREE_LOCK();
2873105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
2874105197Ssam		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2875105197Ssam			continue;
2876105197Ssam		sav = key_getsavbyspi(sah, spi);
2877105197Ssam		if (sav != NULL)
2878119643Ssam			break;
2879105197Ssam	}
2880120585Ssam	SAHTREE_UNLOCK();
2881105197Ssam
2882119643Ssam	return sav;
2883105197Ssam}
2884105197Ssam
2885105197Ssam/*
2886105197Ssam * search SAD litmited alive SA, protocol, SPI.
2887105197Ssam * OUT:
2888105197Ssam *	NULL	: not found
2889105197Ssam *	others	: found, pointer to a SA.
2890105197Ssam */
2891105197Ssamstatic struct secasvar *
2892105197Ssamkey_getsavbyspi(sah, spi)
2893105197Ssam	struct secashead *sah;
2894105197Ssam	u_int32_t spi;
2895105197Ssam{
2896105197Ssam	struct secasvar *sav;
2897105197Ssam	u_int stateidx, state;
2898105197Ssam
2899119643Ssam	sav = NULL;
2900120585Ssam	SAHTREE_LOCK_ASSERT();
2901105197Ssam	/* search all status */
2902105197Ssam	for (stateidx = 0;
2903105197Ssam	     stateidx < _ARRAYLEN(saorder_state_alive);
2904105197Ssam	     stateidx++) {
2905105197Ssam
2906105197Ssam		state = saorder_state_alive[stateidx];
2907105197Ssam		LIST_FOREACH(sav, &sah->savtree[state], chain) {
2908105197Ssam
2909105197Ssam			/* sanity check */
2910105197Ssam			if (sav->state != state) {
2911120585Ssam				ipseclog((LOG_DEBUG, "%s: "
2912105197Ssam				    "invalid sav->state (queue: %d SA: %d)\n",
2913120585Ssam				    __func__, state, sav->state));
2914105197Ssam				continue;
2915105197Ssam			}
2916105197Ssam
2917105197Ssam			if (sav->spi == spi)
2918119643Ssam				break;
2919105197Ssam		}
2920105197Ssam	}
2921105197Ssam
2922119643Ssam	return sav;
2923105197Ssam}
2924105197Ssam
2925105197Ssam/*
2926105197Ssam * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
2927105197Ssam * You must update these if need.
2928105197Ssam * OUT:	0:	success.
2929105197Ssam *	!0:	failure.
2930105197Ssam *
2931105197Ssam * does not modify mbuf.  does not free mbuf on error.
2932105197Ssam */
2933105197Ssamstatic int
2934105197Ssamkey_setsaval(sav, m, mhp)
2935105197Ssam	struct secasvar *sav;
2936105197Ssam	struct mbuf *m;
2937105197Ssam	const struct sadb_msghdr *mhp;
2938105197Ssam{
2939105197Ssam	int error = 0;
2940105197Ssam
2941120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2942120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2943120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2944105197Ssam
2945105197Ssam	/* initialization */
2946105197Ssam	sav->replay = NULL;
2947105197Ssam	sav->key_auth = NULL;
2948105197Ssam	sav->key_enc = NULL;
2949105197Ssam	sav->sched = NULL;
2950105197Ssam	sav->schedlen = 0;
2951105197Ssam	sav->iv = NULL;
2952105197Ssam	sav->lft_c = NULL;
2953105197Ssam	sav->lft_h = NULL;
2954105197Ssam	sav->lft_s = NULL;
2955105197Ssam	sav->tdb_xform = NULL;		/* transform */
2956105197Ssam	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
2957105197Ssam	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
2958105197Ssam	sav->tdb_compalgxform = NULL;	/* compression algorithm */
2959105197Ssam
2960105197Ssam	/* SA */
2961105197Ssam	if (mhp->ext[SADB_EXT_SA] != NULL) {
2962105197Ssam		const struct sadb_sa *sa0;
2963105197Ssam
2964105197Ssam		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2965105197Ssam		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
2966105197Ssam			error = EINVAL;
2967105197Ssam			goto fail;
2968105197Ssam		}
2969105197Ssam
2970105197Ssam		sav->alg_auth = sa0->sadb_sa_auth;
2971105197Ssam		sav->alg_enc = sa0->sadb_sa_encrypt;
2972105197Ssam		sav->flags = sa0->sadb_sa_flags;
2973105197Ssam
2974105197Ssam		/* replay window */
2975105197Ssam		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
2976105197Ssam			sav->replay = (struct secreplay *)
2977119643Ssam				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
2978105197Ssam			if (sav->replay == NULL) {
2979120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
2980120585Ssam					__func__));
2981105197Ssam				error = ENOBUFS;
2982105197Ssam				goto fail;
2983105197Ssam			}
2984105197Ssam			if (sa0->sadb_sa_replay != 0)
2985105197Ssam				sav->replay->bitmap = (caddr_t)(sav->replay+1);
2986105197Ssam			sav->replay->wsize = sa0->sadb_sa_replay;
2987105197Ssam		}
2988105197Ssam	}
2989105197Ssam
2990105197Ssam	/* Authentication keys */
2991105197Ssam	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
2992105197Ssam		const struct sadb_key *key0;
2993105197Ssam		int len;
2994105197Ssam
2995105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
2996105197Ssam		len = mhp->extlen[SADB_EXT_KEY_AUTH];
2997105197Ssam
2998105197Ssam		error = 0;
2999105197Ssam		if (len < sizeof(*key0)) {
3000105197Ssam			error = EINVAL;
3001105197Ssam			goto fail;
3002105197Ssam		}
3003105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3004105197Ssam		case SADB_SATYPE_AH:
3005105197Ssam		case SADB_SATYPE_ESP:
3006125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3007105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3008105197Ssam			    sav->alg_auth != SADB_X_AALG_NULL)
3009105197Ssam				error = EINVAL;
3010105197Ssam			break;
3011105197Ssam		case SADB_X_SATYPE_IPCOMP:
3012105197Ssam		default:
3013105197Ssam			error = EINVAL;
3014105197Ssam			break;
3015105197Ssam		}
3016105197Ssam		if (error) {
3017120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3018120585Ssam				__func__));
3019105197Ssam			goto fail;
3020105197Ssam		}
3021105197Ssam
3022119643Ssam		sav->key_auth = key_dup(key0, len, M_IPSEC_MISC);
3023105197Ssam		if (sav->key_auth == NULL) {
3024120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3025105197Ssam			error = ENOBUFS;
3026105197Ssam			goto fail;
3027105197Ssam		}
3028105197Ssam	}
3029105197Ssam
3030105197Ssam	/* Encryption key */
3031105197Ssam	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3032105197Ssam		const struct sadb_key *key0;
3033105197Ssam		int len;
3034105197Ssam
3035105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3036105197Ssam		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3037105197Ssam
3038105197Ssam		error = 0;
3039105197Ssam		if (len < sizeof(*key0)) {
3040105197Ssam			error = EINVAL;
3041105197Ssam			goto fail;
3042105197Ssam		}
3043105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3044105197Ssam		case SADB_SATYPE_ESP:
3045105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3046105197Ssam			    sav->alg_enc != SADB_EALG_NULL) {
3047105197Ssam				error = EINVAL;
3048105197Ssam				break;
3049105197Ssam			}
3050119643Ssam			sav->key_enc = key_dup(key0, len, M_IPSEC_MISC);
3051105197Ssam			if (sav->key_enc == NULL) {
3052120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3053120585Ssam					__func__));
3054105197Ssam				error = ENOBUFS;
3055105197Ssam				goto fail;
3056105197Ssam			}
3057105197Ssam			break;
3058105197Ssam		case SADB_X_SATYPE_IPCOMP:
3059105197Ssam			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3060105197Ssam				error = EINVAL;
3061105197Ssam			sav->key_enc = NULL;	/*just in case*/
3062105197Ssam			break;
3063105197Ssam		case SADB_SATYPE_AH:
3064125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3065105197Ssam		default:
3066105197Ssam			error = EINVAL;
3067105197Ssam			break;
3068105197Ssam		}
3069105197Ssam		if (error) {
3070120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3071120585Ssam				__func__));
3072105197Ssam			goto fail;
3073105197Ssam		}
3074105197Ssam	}
3075105197Ssam
3076105197Ssam	/* set iv */
3077105197Ssam	sav->ivlen = 0;
3078105197Ssam
3079105197Ssam	switch (mhp->msg->sadb_msg_satype) {
3080105197Ssam	case SADB_SATYPE_AH:
3081105197Ssam		error = xform_init(sav, XF_AH);
3082105197Ssam		break;
3083105197Ssam	case SADB_SATYPE_ESP:
3084105197Ssam		error = xform_init(sav, XF_ESP);
3085105197Ssam		break;
3086105197Ssam	case SADB_X_SATYPE_IPCOMP:
3087105197Ssam		error = xform_init(sav, XF_IPCOMP);
3088105197Ssam		break;
3089125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
3090125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3091125680Sbms		break;
3092105197Ssam	}
3093105197Ssam	if (error) {
3094120585Ssam		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3095120585Ssam		        __func__, mhp->msg->sadb_msg_satype));
3096105197Ssam		goto fail;
3097105197Ssam	}
3098105197Ssam
3099105197Ssam	/* reset created */
3100105197Ssam	sav->created = time_second;
3101105197Ssam
3102105197Ssam	/* make lifetime for CURRENT */
3103119643Ssam	sav->lft_c = malloc(sizeof(struct sadb_lifetime), M_IPSEC_MISC, M_NOWAIT);
3104105197Ssam	if (sav->lft_c == NULL) {
3105120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3106105197Ssam		error = ENOBUFS;
3107105197Ssam		goto fail;
3108105197Ssam	}
3109105197Ssam
3110105197Ssam	sav->lft_c->sadb_lifetime_len =
3111105197Ssam	    PFKEY_UNIT64(sizeof(struct sadb_lifetime));
3112105197Ssam	sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
3113105197Ssam	sav->lft_c->sadb_lifetime_allocations = 0;
3114105197Ssam	sav->lft_c->sadb_lifetime_bytes = 0;
3115105197Ssam	sav->lft_c->sadb_lifetime_addtime = time_second;
3116105197Ssam	sav->lft_c->sadb_lifetime_usetime = 0;
3117105197Ssam
3118105197Ssam	/* lifetimes for HARD and SOFT */
3119105197Ssam    {
3120105197Ssam	const struct sadb_lifetime *lft0;
3121105197Ssam
3122105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3123105197Ssam	if (lft0 != NULL) {
3124105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3125105197Ssam			error = EINVAL;
3126105197Ssam			goto fail;
3127105197Ssam		}
3128119643Ssam		sav->lft_h = key_dup(lft0, sizeof(*lft0), M_IPSEC_MISC);
3129105197Ssam		if (sav->lft_h == NULL) {
3130120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3131105197Ssam			error = ENOBUFS;
3132105197Ssam			goto fail;
3133105197Ssam		}
3134105197Ssam		/* to be initialize ? */
3135105197Ssam	}
3136105197Ssam
3137105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3138105197Ssam	if (lft0 != NULL) {
3139105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3140105197Ssam			error = EINVAL;
3141105197Ssam			goto fail;
3142105197Ssam		}
3143119643Ssam		sav->lft_s = key_dup(lft0, sizeof(*lft0), M_IPSEC_MISC);
3144105197Ssam		if (sav->lft_s == NULL) {
3145120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3146105197Ssam			error = ENOBUFS;
3147105197Ssam			goto fail;
3148105197Ssam		}
3149105197Ssam		/* to be initialize ? */
3150105197Ssam	}
3151105197Ssam    }
3152105197Ssam
3153105197Ssam	return 0;
3154105197Ssam
3155105197Ssam fail:
3156105197Ssam	/* initialization */
3157119643Ssam	key_cleansav(sav);
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
3168119643Ssamkey_mature(struct secasvar *sav)
3169105197Ssam{
3170105197Ssam	int error;
3171105197Ssam
3172105197Ssam	/* check SPI value */
3173105197Ssam	switch (sav->sah->saidx.proto) {
3174105197Ssam	case IPPROTO_ESP:
3175105197Ssam	case IPPROTO_AH:
3176105197Ssam		if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
3177120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3178120585Ssam			    __func__, (u_int32_t)ntohl(sav->spi)));
3179105197Ssam			return EINVAL;
3180105197Ssam		}
3181105197Ssam		break;
3182105197Ssam	}
3183105197Ssam
3184105197Ssam	/* check satype */
3185105197Ssam	switch (sav->sah->saidx.proto) {
3186105197Ssam	case IPPROTO_ESP:
3187105197Ssam		/* check flags */
3188105197Ssam		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3189105197Ssam		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3190120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3191120585Ssam				"given to old-esp.\n", __func__));
3192105197Ssam			return EINVAL;
3193105197Ssam		}
3194105197Ssam		error = xform_init(sav, XF_ESP);
3195105197Ssam		break;
3196105197Ssam	case IPPROTO_AH:
3197105197Ssam		/* check flags */
3198105197Ssam		if (sav->flags & SADB_X_EXT_DERIV) {
3199120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3200120585Ssam				"given to AH SA.\n", __func__));
3201105197Ssam			return EINVAL;
3202105197Ssam		}
3203105197Ssam		if (sav->alg_enc != SADB_EALG_NONE) {
3204120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3205120585Ssam				"mismated.\n", __func__));
3206105197Ssam			return(EINVAL);
3207105197Ssam		}
3208105197Ssam		error = xform_init(sav, XF_AH);
3209105197Ssam		break;
3210105197Ssam	case IPPROTO_IPCOMP:
3211105197Ssam		if (sav->alg_auth != SADB_AALG_NONE) {
3212120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3213120585Ssam				"mismated.\n", __func__));
3214105197Ssam			return(EINVAL);
3215105197Ssam		}
3216105197Ssam		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3217105197Ssam		 && ntohl(sav->spi) >= 0x10000) {
3218120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3219120585Ssam				__func__));
3220105197Ssam			return(EINVAL);
3221105197Ssam		}
3222105197Ssam		error = xform_init(sav, XF_IPCOMP);
3223105197Ssam		break;
3224125680Sbms	case IPPROTO_TCP:
3225125680Sbms		if (sav->alg_enc != SADB_EALG_NONE) {
3226125680Sbms			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3227125680Sbms				"mismated.\n", __func__));
3228125680Sbms			return(EINVAL);
3229125680Sbms		}
3230125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3231125680Sbms		break;
3232105197Ssam	default:
3233120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3234105197Ssam		error = EPROTONOSUPPORT;
3235105197Ssam		break;
3236105197Ssam	}
3237119643Ssam	if (error == 0) {
3238120585Ssam		SAHTREE_LOCK();
3239105197Ssam		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3240120585Ssam		SAHTREE_UNLOCK();
3241119643Ssam	}
3242105197Ssam	return (error);
3243105197Ssam}
3244105197Ssam
3245105197Ssam/*
3246105197Ssam * subroutine for SADB_GET and SADB_DUMP.
3247105197Ssam */
3248105197Ssamstatic struct mbuf *
3249105197Ssamkey_setdumpsa(sav, type, satype, seq, pid)
3250105197Ssam	struct secasvar *sav;
3251105197Ssam	u_int8_t type, satype;
3252105197Ssam	u_int32_t seq, pid;
3253105197Ssam{
3254105197Ssam	struct mbuf *result = NULL, *tres = NULL, *m;
3255105197Ssam	int l = 0;
3256105197Ssam	int i;
3257105197Ssam	void *p;
3258105197Ssam	int dumporder[] = {
3259105197Ssam		SADB_EXT_SA, SADB_X_EXT_SA2,
3260105197Ssam		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3261105197Ssam		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3262105197Ssam		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3263105197Ssam		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3264105197Ssam		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3265105197Ssam	};
3266105197Ssam
3267105197Ssam	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3268105197Ssam	if (m == NULL)
3269105197Ssam		goto fail;
3270105197Ssam	result = m;
3271105197Ssam
3272105197Ssam	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3273105197Ssam		m = NULL;
3274105197Ssam		p = NULL;
3275105197Ssam		switch (dumporder[i]) {
3276105197Ssam		case SADB_EXT_SA:
3277105197Ssam			m = key_setsadbsa(sav);
3278105197Ssam			if (!m)
3279105197Ssam				goto fail;
3280105197Ssam			break;
3281105197Ssam
3282105197Ssam		case SADB_X_EXT_SA2:
3283105197Ssam			m = key_setsadbxsa2(sav->sah->saidx.mode,
3284105197Ssam					sav->replay ? sav->replay->count : 0,
3285105197Ssam					sav->sah->saidx.reqid);
3286105197Ssam			if (!m)
3287105197Ssam				goto fail;
3288105197Ssam			break;
3289105197Ssam
3290105197Ssam		case SADB_EXT_ADDRESS_SRC:
3291105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3292105197Ssam			    &sav->sah->saidx.src.sa,
3293105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3294105197Ssam			if (!m)
3295105197Ssam				goto fail;
3296105197Ssam			break;
3297105197Ssam
3298105197Ssam		case SADB_EXT_ADDRESS_DST:
3299105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3300105197Ssam			    &sav->sah->saidx.dst.sa,
3301105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3302105197Ssam			if (!m)
3303105197Ssam				goto fail;
3304105197Ssam			break;
3305105197Ssam
3306105197Ssam		case SADB_EXT_KEY_AUTH:
3307105197Ssam			if (!sav->key_auth)
3308105197Ssam				continue;
3309105197Ssam			l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
3310105197Ssam			p = sav->key_auth;
3311105197Ssam			break;
3312105197Ssam
3313105197Ssam		case SADB_EXT_KEY_ENCRYPT:
3314105197Ssam			if (!sav->key_enc)
3315105197Ssam				continue;
3316105197Ssam			l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
3317105197Ssam			p = sav->key_enc;
3318105197Ssam			break;
3319105197Ssam
3320105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
3321105197Ssam			if (!sav->lft_c)
3322105197Ssam				continue;
3323105197Ssam			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
3324105197Ssam			p = sav->lft_c;
3325105197Ssam			break;
3326105197Ssam
3327105197Ssam		case SADB_EXT_LIFETIME_HARD:
3328105197Ssam			if (!sav->lft_h)
3329105197Ssam				continue;
3330105197Ssam			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
3331105197Ssam			p = sav->lft_h;
3332105197Ssam			break;
3333105197Ssam
3334105197Ssam		case SADB_EXT_LIFETIME_SOFT:
3335105197Ssam			if (!sav->lft_s)
3336105197Ssam				continue;
3337105197Ssam			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
3338105197Ssam			p = sav->lft_s;
3339105197Ssam			break;
3340105197Ssam
3341105197Ssam		case SADB_EXT_ADDRESS_PROXY:
3342105197Ssam		case SADB_EXT_IDENTITY_SRC:
3343105197Ssam		case SADB_EXT_IDENTITY_DST:
3344105197Ssam			/* XXX: should we brought from SPD ? */
3345105197Ssam		case SADB_EXT_SENSITIVITY:
3346105197Ssam		default:
3347105197Ssam			continue;
3348105197Ssam		}
3349105197Ssam
3350105197Ssam		if ((!m && !p) || (m && p))
3351105197Ssam			goto fail;
3352105197Ssam		if (p && tres) {
3353111119Simp			M_PREPEND(tres, l, M_DONTWAIT);
3354105197Ssam			if (!tres)
3355105197Ssam				goto fail;
3356105197Ssam			bcopy(p, mtod(tres, caddr_t), l);
3357105197Ssam			continue;
3358105197Ssam		}
3359105197Ssam		if (p) {
3360105197Ssam			m = key_alloc_mbuf(l);
3361105197Ssam			if (!m)
3362105197Ssam				goto fail;
3363105197Ssam			m_copyback(m, 0, l, p);
3364105197Ssam		}
3365105197Ssam
3366105197Ssam		if (tres)
3367105197Ssam			m_cat(m, tres);
3368105197Ssam		tres = m;
3369105197Ssam	}
3370105197Ssam
3371105197Ssam	m_cat(result, tres);
3372105197Ssam
3373105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
3374105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
3375105197Ssam		if (result == NULL)
3376105197Ssam			goto fail;
3377105197Ssam	}
3378105197Ssam
3379105197Ssam	result->m_pkthdr.len = 0;
3380105197Ssam	for (m = result; m; m = m->m_next)
3381105197Ssam		result->m_pkthdr.len += m->m_len;
3382105197Ssam
3383105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
3384105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
3385105197Ssam
3386105197Ssam	return result;
3387105197Ssam
3388105197Ssamfail:
3389105197Ssam	m_freem(result);
3390105197Ssam	m_freem(tres);
3391105197Ssam	return NULL;
3392105197Ssam}
3393105197Ssam
3394105197Ssam/*
3395105197Ssam * set data into sadb_msg.
3396105197Ssam */
3397105197Ssamstatic struct mbuf *
3398105197Ssamkey_setsadbmsg(type, tlen, satype, seq, pid, reserved)
3399105197Ssam	u_int8_t type, satype;
3400105197Ssam	u_int16_t tlen;
3401105197Ssam	u_int32_t seq;
3402105197Ssam	pid_t pid;
3403105197Ssam	u_int16_t reserved;
3404105197Ssam{
3405105197Ssam	struct mbuf *m;
3406105197Ssam	struct sadb_msg *p;
3407105197Ssam	int len;
3408105197Ssam
3409105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3410105197Ssam	if (len > MCLBYTES)
3411105197Ssam		return NULL;
3412111119Simp	MGETHDR(m, M_DONTWAIT, MT_DATA);
3413105197Ssam	if (m && len > MHLEN) {
3414111119Simp		MCLGET(m, M_DONTWAIT);
3415105197Ssam		if ((m->m_flags & M_EXT) == 0) {
3416105197Ssam			m_freem(m);
3417105197Ssam			m = NULL;
3418105197Ssam		}
3419105197Ssam	}
3420105197Ssam	if (!m)
3421105197Ssam		return NULL;
3422105197Ssam	m->m_pkthdr.len = m->m_len = len;
3423105197Ssam	m->m_next = NULL;
3424105197Ssam
3425105197Ssam	p = mtod(m, struct sadb_msg *);
3426105197Ssam
3427105197Ssam	bzero(p, len);
3428105197Ssam	p->sadb_msg_version = PF_KEY_V2;
3429105197Ssam	p->sadb_msg_type = type;
3430105197Ssam	p->sadb_msg_errno = 0;
3431105197Ssam	p->sadb_msg_satype = satype;
3432105197Ssam	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3433105197Ssam	p->sadb_msg_reserved = reserved;
3434105197Ssam	p->sadb_msg_seq = seq;
3435105197Ssam	p->sadb_msg_pid = (u_int32_t)pid;
3436105197Ssam
3437105197Ssam	return m;
3438105197Ssam}
3439105197Ssam
3440105197Ssam/*
3441105197Ssam * copy secasvar data into sadb_address.
3442105197Ssam */
3443105197Ssamstatic struct mbuf *
3444105197Ssamkey_setsadbsa(sav)
3445105197Ssam	struct secasvar *sav;
3446105197Ssam{
3447105197Ssam	struct mbuf *m;
3448105197Ssam	struct sadb_sa *p;
3449105197Ssam	int len;
3450105197Ssam
3451105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3452105197Ssam	m = key_alloc_mbuf(len);
3453105197Ssam	if (!m || m->m_next) {	/*XXX*/
3454105197Ssam		if (m)
3455105197Ssam			m_freem(m);
3456105197Ssam		return NULL;
3457105197Ssam	}
3458105197Ssam
3459105197Ssam	p = mtod(m, struct sadb_sa *);
3460105197Ssam
3461105197Ssam	bzero(p, len);
3462105197Ssam	p->sadb_sa_len = PFKEY_UNIT64(len);
3463105197Ssam	p->sadb_sa_exttype = SADB_EXT_SA;
3464105197Ssam	p->sadb_sa_spi = sav->spi;
3465105197Ssam	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3466105197Ssam	p->sadb_sa_state = sav->state;
3467105197Ssam	p->sadb_sa_auth = sav->alg_auth;
3468105197Ssam	p->sadb_sa_encrypt = sav->alg_enc;
3469105197Ssam	p->sadb_sa_flags = sav->flags;
3470105197Ssam
3471105197Ssam	return m;
3472105197Ssam}
3473105197Ssam
3474105197Ssam/*
3475105197Ssam * set data into sadb_address.
3476105197Ssam */
3477105197Ssamstatic struct mbuf *
3478105197Ssamkey_setsadbaddr(exttype, saddr, prefixlen, ul_proto)
3479105197Ssam	u_int16_t exttype;
3480105197Ssam	const struct sockaddr *saddr;
3481105197Ssam	u_int8_t prefixlen;
3482105197Ssam	u_int16_t ul_proto;
3483105197Ssam{
3484105197Ssam	struct mbuf *m;
3485105197Ssam	struct sadb_address *p;
3486105197Ssam	size_t len;
3487105197Ssam
3488105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3489105197Ssam	    PFKEY_ALIGN8(saddr->sa_len);
3490105197Ssam	m = key_alloc_mbuf(len);
3491105197Ssam	if (!m || m->m_next) {	/*XXX*/
3492105197Ssam		if (m)
3493105197Ssam			m_freem(m);
3494105197Ssam		return NULL;
3495105197Ssam	}
3496105197Ssam
3497105197Ssam	p = mtod(m, struct sadb_address *);
3498105197Ssam
3499105197Ssam	bzero(p, len);
3500105197Ssam	p->sadb_address_len = PFKEY_UNIT64(len);
3501105197Ssam	p->sadb_address_exttype = exttype;
3502105197Ssam	p->sadb_address_proto = ul_proto;
3503105197Ssam	if (prefixlen == FULLMASK) {
3504105197Ssam		switch (saddr->sa_family) {
3505105197Ssam		case AF_INET:
3506105197Ssam			prefixlen = sizeof(struct in_addr) << 3;
3507105197Ssam			break;
3508105197Ssam		case AF_INET6:
3509105197Ssam			prefixlen = sizeof(struct in6_addr) << 3;
3510105197Ssam			break;
3511105197Ssam		default:
3512105197Ssam			; /*XXX*/
3513105197Ssam		}
3514105197Ssam	}
3515105197Ssam	p->sadb_address_prefixlen = prefixlen;
3516105197Ssam	p->sadb_address_reserved = 0;
3517105197Ssam
3518105197Ssam	bcopy(saddr,
3519105197Ssam	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3520105197Ssam	    saddr->sa_len);
3521105197Ssam
3522105197Ssam	return m;
3523105197Ssam}
3524105197Ssam
3525105197Ssam/*
3526105197Ssam * set data into sadb_x_sa2.
3527105197Ssam */
3528105197Ssamstatic struct mbuf *
3529105197Ssamkey_setsadbxsa2(mode, seq, reqid)
3530105197Ssam	u_int8_t mode;
3531105197Ssam	u_int32_t seq, reqid;
3532105197Ssam{
3533105197Ssam	struct mbuf *m;
3534105197Ssam	struct sadb_x_sa2 *p;
3535105197Ssam	size_t len;
3536105197Ssam
3537105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3538105197Ssam	m = key_alloc_mbuf(len);
3539105197Ssam	if (!m || m->m_next) {	/*XXX*/
3540105197Ssam		if (m)
3541105197Ssam			m_freem(m);
3542105197Ssam		return NULL;
3543105197Ssam	}
3544105197Ssam
3545105197Ssam	p = mtod(m, struct sadb_x_sa2 *);
3546105197Ssam
3547105197Ssam	bzero(p, len);
3548105197Ssam	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3549105197Ssam	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3550105197Ssam	p->sadb_x_sa2_mode = mode;
3551105197Ssam	p->sadb_x_sa2_reserved1 = 0;
3552105197Ssam	p->sadb_x_sa2_reserved2 = 0;
3553105197Ssam	p->sadb_x_sa2_sequence = seq;
3554105197Ssam	p->sadb_x_sa2_reqid = reqid;
3555105197Ssam
3556105197Ssam	return m;
3557105197Ssam}
3558105197Ssam
3559105197Ssam/*
3560105197Ssam * set data into sadb_x_policy
3561105197Ssam */
3562105197Ssamstatic struct mbuf *
3563105197Ssamkey_setsadbxpolicy(type, dir, id)
3564105197Ssam	u_int16_t type;
3565105197Ssam	u_int8_t dir;
3566105197Ssam	u_int32_t id;
3567105197Ssam{
3568105197Ssam	struct mbuf *m;
3569105197Ssam	struct sadb_x_policy *p;
3570105197Ssam	size_t len;
3571105197Ssam
3572105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3573105197Ssam	m = key_alloc_mbuf(len);
3574105197Ssam	if (!m || m->m_next) {	/*XXX*/
3575105197Ssam		if (m)
3576105197Ssam			m_freem(m);
3577105197Ssam		return NULL;
3578105197Ssam	}
3579105197Ssam
3580105197Ssam	p = mtod(m, struct sadb_x_policy *);
3581105197Ssam
3582105197Ssam	bzero(p, len);
3583105197Ssam	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3584105197Ssam	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3585105197Ssam	p->sadb_x_policy_type = type;
3586105197Ssam	p->sadb_x_policy_dir = dir;
3587105197Ssam	p->sadb_x_policy_id = id;
3588105197Ssam
3589105197Ssam	return m;
3590105197Ssam}
3591105197Ssam
3592105197Ssam/* %%% utilities */
3593105197Ssam/*
3594105197Ssam * copy a buffer into the new buffer allocated.
3595105197Ssam */
3596105197Ssamstatic void *
3597119643Ssamkey_dup(const void *src, u_int len, struct malloc_type *type)
3598105197Ssam{
3599119643Ssam	void *copy;
3600105197Ssam
3601119643Ssam	copy = malloc(len, type, M_NOWAIT);
3602119643Ssam	if (copy == NULL) {
3603119643Ssam		/* XXX counter */
3604120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3605119643Ssam	} else
3606119643Ssam		bcopy(src, copy, len);
3607119643Ssam	return copy;
3608105197Ssam}
3609105197Ssam
3610105197Ssam/* compare my own address
3611105197Ssam * OUT:	1: true, i.e. my address.
3612105197Ssam *	0: false
3613105197Ssam */
3614105197Ssamint
3615105197Ssamkey_ismyaddr(sa)
3616105197Ssam	struct sockaddr *sa;
3617105197Ssam{
3618105197Ssam#ifdef INET
3619105197Ssam	struct sockaddr_in *sin;
3620105197Ssam	struct in_ifaddr *ia;
3621105197Ssam#endif
3622105197Ssam
3623120585Ssam	IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3624105197Ssam
3625105197Ssam	switch (sa->sa_family) {
3626105197Ssam#ifdef INET
3627105197Ssam	case AF_INET:
3628105197Ssam		sin = (struct sockaddr_in *)sa;
3629105197Ssam		for (ia = in_ifaddrhead.tqh_first; ia;
3630105197Ssam		     ia = ia->ia_link.tqe_next)
3631105197Ssam		{
3632105197Ssam			if (sin->sin_family == ia->ia_addr.sin_family &&
3633105197Ssam			    sin->sin_len == ia->ia_addr.sin_len &&
3634105197Ssam			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3635105197Ssam			{
3636105197Ssam				return 1;
3637105197Ssam			}
3638105197Ssam		}
3639105197Ssam		break;
3640105197Ssam#endif
3641105197Ssam#ifdef INET6
3642105197Ssam	case AF_INET6:
3643105197Ssam		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3644105197Ssam#endif
3645105197Ssam	}
3646105197Ssam
3647105197Ssam	return 0;
3648105197Ssam}
3649105197Ssam
3650105197Ssam#ifdef INET6
3651105197Ssam/*
3652105197Ssam * compare my own address for IPv6.
3653105197Ssam * 1: ours
3654105197Ssam * 0: other
3655105197Ssam * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3656105197Ssam */
3657105197Ssam#include <netinet6/in6_var.h>
3658105197Ssam
3659105197Ssamstatic int
3660105197Ssamkey_ismyaddr6(sin6)
3661105197Ssam	struct sockaddr_in6 *sin6;
3662105197Ssam{
3663105197Ssam	struct in6_ifaddr *ia;
3664105197Ssam	struct in6_multi *in6m;
3665105197Ssam
3666105197Ssam	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
3667105197Ssam		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3668105197Ssam		    (struct sockaddr *)&ia->ia_addr, 0) == 0)
3669105197Ssam			return 1;
3670105197Ssam
3671105197Ssam		/*
3672105197Ssam		 * XXX Multicast
3673105197Ssam		 * XXX why do we care about multlicast here while we don't care
3674105197Ssam		 * about IPv4 multicast??
3675105197Ssam		 * XXX scope
3676105197Ssam		 */
3677105197Ssam		in6m = NULL;
3678105197Ssam		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3679105197Ssam		if (in6m)
3680105197Ssam			return 1;
3681105197Ssam	}
3682105197Ssam
3683105197Ssam	/* loopback, just for safety */
3684105197Ssam	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3685105197Ssam		return 1;
3686105197Ssam
3687105197Ssam	return 0;
3688105197Ssam}
3689105197Ssam#endif /*INET6*/
3690105197Ssam
3691105197Ssam/*
3692105197Ssam * compare two secasindex structure.
3693105197Ssam * flag can specify to compare 2 saidxes.
3694105197Ssam * compare two secasindex structure without both mode and reqid.
3695105197Ssam * don't compare port.
3696105197Ssam * IN:
3697105197Ssam *      saidx0: source, it can be in SAD.
3698105197Ssam *      saidx1: object.
3699105197Ssam * OUT:
3700105197Ssam *      1 : equal
3701105197Ssam *      0 : not equal
3702105197Ssam */
3703105197Ssamstatic int
3704105197Ssamkey_cmpsaidx(
3705105197Ssam	const struct secasindex *saidx0,
3706105197Ssam	const struct secasindex *saidx1,
3707105197Ssam	int flag)
3708105197Ssam{
3709105197Ssam	/* sanity */
3710105197Ssam	if (saidx0 == NULL && saidx1 == NULL)
3711105197Ssam		return 1;
3712105197Ssam
3713105197Ssam	if (saidx0 == NULL || saidx1 == NULL)
3714105197Ssam		return 0;
3715105197Ssam
3716105197Ssam	if (saidx0->proto != saidx1->proto)
3717105197Ssam		return 0;
3718105197Ssam
3719105197Ssam	if (flag == CMP_EXACTLY) {
3720105197Ssam		if (saidx0->mode != saidx1->mode)
3721105197Ssam			return 0;
3722105197Ssam		if (saidx0->reqid != saidx1->reqid)
3723105197Ssam			return 0;
3724105197Ssam		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3725105197Ssam		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3726105197Ssam			return 0;
3727105197Ssam	} else {
3728105197Ssam
3729105197Ssam		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3730105197Ssam		if (flag == CMP_MODE_REQID
3731105197Ssam		  ||flag == CMP_REQID) {
3732105197Ssam			/*
3733105197Ssam			 * If reqid of SPD is non-zero, unique SA is required.
3734105197Ssam			 * The result must be of same reqid in this case.
3735105197Ssam			 */
3736105197Ssam			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3737105197Ssam				return 0;
3738105197Ssam		}
3739105197Ssam
3740105197Ssam		if (flag == CMP_MODE_REQID) {
3741105197Ssam			if (saidx0->mode != IPSEC_MODE_ANY
3742105197Ssam			 && saidx0->mode != saidx1->mode)
3743105197Ssam				return 0;
3744105197Ssam		}
3745105197Ssam
3746105197Ssam		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
3747105197Ssam			return 0;
3748105197Ssam		}
3749105197Ssam		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
3750105197Ssam			return 0;
3751105197Ssam		}
3752105197Ssam	}
3753105197Ssam
3754105197Ssam	return 1;
3755105197Ssam}
3756105197Ssam
3757105197Ssam/*
3758105197Ssam * compare two secindex structure exactly.
3759105197Ssam * IN:
3760105197Ssam *	spidx0: source, it is often in SPD.
3761105197Ssam *	spidx1: object, it is often from PFKEY message.
3762105197Ssam * OUT:
3763105197Ssam *	1 : equal
3764105197Ssam *	0 : not equal
3765105197Ssam */
3766105197Ssamstatic int
3767105197Ssamkey_cmpspidx_exactly(
3768105197Ssam	struct secpolicyindex *spidx0,
3769105197Ssam	struct secpolicyindex *spidx1)
3770105197Ssam{
3771105197Ssam	/* sanity */
3772105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
3773105197Ssam		return 1;
3774105197Ssam
3775105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
3776105197Ssam		return 0;
3777105197Ssam
3778105197Ssam	if (spidx0->prefs != spidx1->prefs
3779105197Ssam	 || spidx0->prefd != spidx1->prefd
3780105197Ssam	 || spidx0->ul_proto != spidx1->ul_proto)
3781105197Ssam		return 0;
3782105197Ssam
3783105197Ssam	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3784105197Ssam	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3785105197Ssam}
3786105197Ssam
3787105197Ssam/*
3788105197Ssam * compare two secindex structure with mask.
3789105197Ssam * IN:
3790105197Ssam *	spidx0: source, it is often in SPD.
3791105197Ssam *	spidx1: object, it is often from IP header.
3792105197Ssam * OUT:
3793105197Ssam *	1 : equal
3794105197Ssam *	0 : not equal
3795105197Ssam */
3796105197Ssamstatic int
3797105197Ssamkey_cmpspidx_withmask(
3798105197Ssam	struct secpolicyindex *spidx0,
3799105197Ssam	struct secpolicyindex *spidx1)
3800105197Ssam{
3801105197Ssam	/* sanity */
3802105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
3803105197Ssam		return 1;
3804105197Ssam
3805105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
3806105197Ssam		return 0;
3807105197Ssam
3808105197Ssam	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
3809105197Ssam	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
3810105197Ssam	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
3811105197Ssam	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
3812105197Ssam		return 0;
3813105197Ssam
3814105197Ssam	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3815105197Ssam	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3816105197Ssam	 && spidx0->ul_proto != spidx1->ul_proto)
3817105197Ssam		return 0;
3818105197Ssam
3819105197Ssam	switch (spidx0->src.sa.sa_family) {
3820105197Ssam	case AF_INET:
3821105197Ssam		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
3822105197Ssam		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
3823105197Ssam			return 0;
3824105197Ssam		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
3825105197Ssam		    &spidx1->src.sin.sin_addr, spidx0->prefs))
3826105197Ssam			return 0;
3827105197Ssam		break;
3828105197Ssam	case AF_INET6:
3829105197Ssam		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
3830105197Ssam		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
3831105197Ssam			return 0;
3832105197Ssam		/*
3833105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
3834105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
3835105197Ssam		 */
3836105197Ssam		if (spidx0->src.sin6.sin6_scope_id &&
3837105197Ssam		    spidx1->src.sin6.sin6_scope_id &&
3838105197Ssam		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
3839105197Ssam			return 0;
3840105197Ssam		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
3841105197Ssam		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
3842105197Ssam			return 0;
3843105197Ssam		break;
3844105197Ssam	default:
3845105197Ssam		/* XXX */
3846105197Ssam		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
3847105197Ssam			return 0;
3848105197Ssam		break;
3849105197Ssam	}
3850105197Ssam
3851105197Ssam	switch (spidx0->dst.sa.sa_family) {
3852105197Ssam	case AF_INET:
3853105197Ssam		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
3854105197Ssam		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
3855105197Ssam			return 0;
3856105197Ssam		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
3857105197Ssam		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
3858105197Ssam			return 0;
3859105197Ssam		break;
3860105197Ssam	case AF_INET6:
3861105197Ssam		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
3862105197Ssam		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
3863105197Ssam			return 0;
3864105197Ssam		/*
3865105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
3866105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
3867105197Ssam		 */
3868105197Ssam		if (spidx0->src.sin6.sin6_scope_id &&
3869105197Ssam		    spidx1->src.sin6.sin6_scope_id &&
3870105197Ssam		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
3871105197Ssam			return 0;
3872105197Ssam		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
3873105197Ssam		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
3874105197Ssam			return 0;
3875105197Ssam		break;
3876105197Ssam	default:
3877105197Ssam		/* XXX */
3878105197Ssam		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
3879105197Ssam			return 0;
3880105197Ssam		break;
3881105197Ssam	}
3882105197Ssam
3883105197Ssam	/* XXX Do we check other field ?  e.g. flowinfo */
3884105197Ssam
3885105197Ssam	return 1;
3886105197Ssam}
3887105197Ssam
3888105197Ssam/* returns 0 on match */
3889105197Ssamstatic int
3890105197Ssamkey_sockaddrcmp(
3891105197Ssam	const struct sockaddr *sa1,
3892105197Ssam	const struct sockaddr *sa2,
3893105197Ssam	int port)
3894105197Ssam{
3895105197Ssam#ifdef satosin
3896105197Ssam#undef satosin
3897105197Ssam#endif
3898105197Ssam#define satosin(s) ((const struct sockaddr_in *)s)
3899105197Ssam#ifdef satosin6
3900105197Ssam#undef satosin6
3901105197Ssam#endif
3902105197Ssam#define satosin6(s) ((const struct sockaddr_in6 *)s)
3903105197Ssam	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
3904105197Ssam		return 1;
3905105197Ssam
3906105197Ssam	switch (sa1->sa_family) {
3907105197Ssam	case AF_INET:
3908105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in))
3909105197Ssam			return 1;
3910105197Ssam		if (satosin(sa1)->sin_addr.s_addr !=
3911105197Ssam		    satosin(sa2)->sin_addr.s_addr) {
3912105197Ssam			return 1;
3913105197Ssam		}
3914105197Ssam		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
3915105197Ssam			return 1;
3916105197Ssam		break;
3917105197Ssam	case AF_INET6:
3918105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in6))
3919105197Ssam			return 1;	/*EINVAL*/
3920105197Ssam		if (satosin6(sa1)->sin6_scope_id !=
3921105197Ssam		    satosin6(sa2)->sin6_scope_id) {
3922105197Ssam			return 1;
3923105197Ssam		}
3924105197Ssam		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
3925105197Ssam		    &satosin6(sa2)->sin6_addr)) {
3926105197Ssam			return 1;
3927105197Ssam		}
3928105197Ssam		if (port &&
3929105197Ssam		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
3930105197Ssam			return 1;
3931105197Ssam		}
3932105197Ssam	default:
3933105197Ssam		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
3934105197Ssam			return 1;
3935105197Ssam		break;
3936105197Ssam	}
3937105197Ssam
3938105197Ssam	return 0;
3939105197Ssam#undef satosin
3940105197Ssam#undef satosin6
3941105197Ssam}
3942105197Ssam
3943105197Ssam/*
3944105197Ssam * compare two buffers with mask.
3945105197Ssam * IN:
3946105197Ssam *	addr1: source
3947105197Ssam *	addr2: object
3948105197Ssam *	bits:  Number of bits to compare
3949105197Ssam * OUT:
3950105197Ssam *	1 : equal
3951105197Ssam *	0 : not equal
3952105197Ssam */
3953105197Ssamstatic int
3954105197Ssamkey_bbcmp(const void *a1, const void *a2, u_int bits)
3955105197Ssam{
3956105197Ssam	const unsigned char *p1 = a1;
3957105197Ssam	const unsigned char *p2 = a2;
3958105197Ssam
3959105197Ssam	/* XXX: This could be considerably faster if we compare a word
3960105197Ssam	 * at a time, but it is complicated on LSB Endian machines */
3961105197Ssam
3962105197Ssam	/* Handle null pointers */
3963105197Ssam	if (p1 == NULL || p2 == NULL)
3964105197Ssam		return (p1 == p2);
3965105197Ssam
3966105197Ssam	while (bits >= 8) {
3967105197Ssam		if (*p1++ != *p2++)
3968105197Ssam			return 0;
3969105197Ssam		bits -= 8;
3970105197Ssam	}
3971105197Ssam
3972105197Ssam	if (bits > 0) {
3973105197Ssam		u_int8_t mask = ~((1<<(8-bits))-1);
3974105197Ssam		if ((*p1 & mask) != (*p2 & mask))
3975105197Ssam			return 0;
3976105197Ssam	}
3977105197Ssam	return 1;	/* Match! */
3978105197Ssam}
3979105197Ssam
3980119643Ssamstatic void
3981119643Ssamkey_flush_spd(time_t now)
3982105197Ssam{
3983120585Ssam	static u_int16_t sptree_scangen = 0;
3984120585Ssam	u_int16_t gen = sptree_scangen++;
3985120585Ssam	struct secpolicy *sp;
3986105197Ssam	u_int dir;
3987105197Ssam
3988105197Ssam	/* SPD */
3989105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
3990120585Ssamrestart:
3991120585Ssam		SPTREE_LOCK();
3992120585Ssam		LIST_FOREACH(sp, &sptree[dir], chain) {
3993120585Ssam			if (sp->scangen == gen)		/* previously handled */
3994120585Ssam				continue;
3995120585Ssam			sp->scangen = gen;
3996105197Ssam			if (sp->state == IPSEC_SPSTATE_DEAD) {
3997120585Ssam				/* NB: clean entries created by key_spdflush */
3998120585Ssam				SPTREE_UNLOCK();
3999105197Ssam				KEY_FREESP(&sp);
4000120585Ssam				goto restart;
4001105197Ssam			}
4002105197Ssam			if (sp->lifetime == 0 && sp->validtime == 0)
4003105197Ssam				continue;
4004105197Ssam			if ((sp->lifetime && now - sp->created > sp->lifetime)
4005105197Ssam			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4006105197Ssam				sp->state = IPSEC_SPSTATE_DEAD;
4007120585Ssam				SPTREE_UNLOCK();
4008105197Ssam				key_spdexpire(sp);
4009120585Ssam				KEY_FREESP(&sp);
4010120585Ssam				goto restart;
4011105197Ssam			}
4012105197Ssam		}
4013120585Ssam		SPTREE_UNLOCK();
4014105197Ssam	}
4015119643Ssam}
4016105197Ssam
4017119643Ssamstatic void
4018119643Ssamkey_flush_sad(time_t now)
4019119643Ssam{
4020105197Ssam	struct secashead *sah, *nextsah;
4021105197Ssam	struct secasvar *sav, *nextsav;
4022105197Ssam
4023119643Ssam	/* SAD */
4024120585Ssam	SAHTREE_LOCK();
4025120585Ssam	LIST_FOREACH_SAFE(sah, &sahtree, chain, nextsah) {
4026105197Ssam		/* if sah has been dead, then delete it and process next sah. */
4027105197Ssam		if (sah->state == SADB_SASTATE_DEAD) {
4028105197Ssam			key_delsah(sah);
4029105197Ssam			continue;
4030105197Ssam		}
4031105197Ssam
4032105197Ssam		/* if LARVAL entry doesn't become MATURE, delete it. */
4033120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4034120585Ssam			if (now - sav->created > key_larval_lifetime)
4035105197Ssam				KEY_FREESAV(&sav);
4036105197Ssam		}
4037105197Ssam
4038105197Ssam		/*
4039105197Ssam		 * check MATURE entry to start to send expire message
4040105197Ssam		 * whether or not.
4041105197Ssam		 */
4042120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4043105197Ssam			/* we don't need to check. */
4044105197Ssam			if (sav->lft_s == NULL)
4045105197Ssam				continue;
4046105197Ssam
4047105197Ssam			/* sanity check */
4048105197Ssam			if (sav->lft_c == NULL) {
4049120585Ssam				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4050120585Ssam					"time, why?\n", __func__));
4051105197Ssam				continue;
4052105197Ssam			}
4053105197Ssam
4054105197Ssam			/* check SOFT lifetime */
4055120585Ssam			if (sav->lft_s->sadb_lifetime_addtime != 0 &&
4056120585Ssam			    now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4057105197Ssam				/*
4058105197Ssam				 * check SA to be used whether or not.
4059105197Ssam				 * when SA hasn't been used, delete it.
4060105197Ssam				 */
4061105197Ssam				if (sav->lft_c->sadb_lifetime_usetime == 0) {
4062105197Ssam					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4063105197Ssam					KEY_FREESAV(&sav);
4064105197Ssam				} else {
4065105197Ssam					key_sa_chgstate(sav, SADB_SASTATE_DYING);
4066105197Ssam					/*
4067105197Ssam					 * XXX If we keep to send expire
4068105197Ssam					 * message in the status of
4069105197Ssam					 * DYING. Do remove below code.
4070105197Ssam					 */
4071105197Ssam					key_expire(sav);
4072105197Ssam				}
4073105197Ssam			}
4074105197Ssam			/* check SOFT lifetime by bytes */
4075105197Ssam			/*
4076105197Ssam			 * XXX I don't know the way to delete this SA
4077105197Ssam			 * when new SA is installed.  Caution when it's
4078105197Ssam			 * installed too big lifetime by time.
4079105197Ssam			 */
4080120585Ssam			else if (sav->lft_s->sadb_lifetime_bytes != 0 &&
4081120585Ssam			    sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4082105197Ssam
4083105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4084105197Ssam				/*
4085105197Ssam				 * XXX If we keep to send expire
4086105197Ssam				 * message in the status of
4087105197Ssam				 * DYING. Do remove below code.
4088105197Ssam				 */
4089105197Ssam				key_expire(sav);
4090105197Ssam			}
4091105197Ssam		}
4092105197Ssam
4093105197Ssam		/* check DYING entry to change status to DEAD. */
4094120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4095105197Ssam			/* we don't need to check. */
4096105197Ssam			if (sav->lft_h == NULL)
4097105197Ssam				continue;
4098105197Ssam
4099105197Ssam			/* sanity check */
4100105197Ssam			if (sav->lft_c == NULL) {
4101120585Ssam				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4102120585Ssam					"time, why?\n", __func__));
4103105197Ssam				continue;
4104105197Ssam			}
4105105197Ssam
4106120585Ssam			if (sav->lft_h->sadb_lifetime_addtime != 0 &&
4107120585Ssam			    now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
4108105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4109105197Ssam				KEY_FREESAV(&sav);
4110105197Ssam			}
4111105197Ssam#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4112105197Ssam			else if (sav->lft_s != NULL
4113105197Ssam			      && sav->lft_s->sadb_lifetime_addtime != 0
4114105197Ssam			      && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4115105197Ssam				/*
4116105197Ssam				 * XXX: should be checked to be
4117105197Ssam				 * installed the valid SA.
4118105197Ssam				 */
4119105197Ssam
4120105197Ssam				/*
4121105197Ssam				 * If there is no SA then sending
4122105197Ssam				 * expire message.
4123105197Ssam				 */
4124105197Ssam				key_expire(sav);
4125105197Ssam			}
4126105197Ssam#endif
4127105197Ssam			/* check HARD lifetime by bytes */
4128120585Ssam			else if (sav->lft_h->sadb_lifetime_bytes != 0 &&
4129120585Ssam			    sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4130105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4131105197Ssam				KEY_FREESAV(&sav);
4132105197Ssam			}
4133105197Ssam		}
4134105197Ssam
4135105197Ssam		/* delete entry in DEAD */
4136120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4137105197Ssam			/* sanity check */
4138105197Ssam			if (sav->state != SADB_SASTATE_DEAD) {
4139120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4140120585Ssam					"(queue: %d SA: %d): kill it anyway\n",
4141120585Ssam					__func__,
4142105197Ssam					SADB_SASTATE_DEAD, sav->state));
4143105197Ssam			}
4144105197Ssam			/*
4145105197Ssam			 * do not call key_freesav() here.
4146105197Ssam			 * sav should already be freed, and sav->refcnt
4147105197Ssam			 * shows other references to sav
4148105197Ssam			 * (such as from SPD).
4149105197Ssam			 */
4150105197Ssam		}
4151105197Ssam	}
4152120585Ssam	SAHTREE_UNLOCK();
4153119643Ssam}
4154105197Ssam
4155119643Ssamstatic void
4156119643Ssamkey_flush_acq(time_t now)
4157119643Ssam{
4158105197Ssam	struct secacq *acq, *nextacq;
4159105197Ssam
4160119643Ssam	/* ACQ tree */
4161120585Ssam	ACQ_LOCK();
4162119643Ssam	for (acq = LIST_FIRST(&acqtree); acq != NULL; acq = nextacq) {
4163105197Ssam		nextacq = LIST_NEXT(acq, chain);
4164105197Ssam		if (now - acq->created > key_blockacq_lifetime
4165105197Ssam		 && __LIST_CHAINED(acq)) {
4166105197Ssam			LIST_REMOVE(acq, chain);
4167119643Ssam			free(acq, M_IPSEC_SAQ);
4168105197Ssam		}
4169105197Ssam	}
4170120585Ssam	ACQ_UNLOCK();
4171119643Ssam}
4172105197Ssam
4173119643Ssamstatic void
4174119643Ssamkey_flush_spacq(time_t now)
4175119643Ssam{
4176105197Ssam	struct secspacq *acq, *nextacq;
4177105197Ssam
4178119643Ssam	/* SP ACQ tree */
4179120585Ssam	SPACQ_LOCK();
4180119643Ssam	for (acq = LIST_FIRST(&spacqtree); acq != NULL; acq = nextacq) {
4181105197Ssam		nextacq = LIST_NEXT(acq, chain);
4182105197Ssam		if (now - acq->created > key_blockacq_lifetime
4183105197Ssam		 && __LIST_CHAINED(acq)) {
4184105197Ssam			LIST_REMOVE(acq, chain);
4185119643Ssam			free(acq, M_IPSEC_SAQ);
4186105197Ssam		}
4187105197Ssam	}
4188120585Ssam	SPACQ_UNLOCK();
4189119643Ssam}
4190105197Ssam
4191119643Ssam/*
4192119643Ssam * time handler.
4193119643Ssam * scanning SPD and SAD to check status for each entries,
4194119643Ssam * and do to remove or to expire.
4195119643Ssam * XXX: year 2038 problem may remain.
4196119643Ssam */
4197119643Ssamvoid
4198119643Ssamkey_timehandler(void)
4199119643Ssam{
4200119643Ssam	time_t now = time_second;
4201105197Ssam
4202119643Ssam	key_flush_spd(now);
4203119643Ssam	key_flush_sad(now);
4204119643Ssam	key_flush_acq(now);
4205119643Ssam	key_flush_spacq(now);
4206119643Ssam
4207105197Ssam#ifndef IPSEC_DEBUG2
4208105197Ssam	/* do exchange to tick time !! */
4209105197Ssam	(void)timeout((void *)key_timehandler, (void *)0, hz);
4210105197Ssam#endif /* IPSEC_DEBUG2 */
4211105197Ssam}
4212105197Ssam
4213105197Ssamu_long
4214105197Ssamkey_random()
4215105197Ssam{
4216105197Ssam	u_long value;
4217105197Ssam
4218105197Ssam	key_randomfill(&value, sizeof(value));
4219105197Ssam	return value;
4220105197Ssam}
4221105197Ssam
4222105197Ssamvoid
4223105197Ssamkey_randomfill(p, l)
4224105197Ssam	void *p;
4225105197Ssam	size_t l;
4226105197Ssam{
4227105197Ssam	size_t n;
4228105197Ssam	u_long v;
4229105197Ssam	static int warn = 1;
4230105197Ssam
4231105197Ssam	n = 0;
4232105197Ssam	n = (size_t)read_random(p, (u_int)l);
4233105197Ssam	/* last resort */
4234105197Ssam	while (n < l) {
4235105197Ssam		v = random();
4236105197Ssam		bcopy(&v, (u_int8_t *)p + n,
4237105197Ssam		    l - n < sizeof(v) ? l - n : sizeof(v));
4238105197Ssam		n += sizeof(v);
4239105197Ssam
4240105197Ssam		if (warn) {
4241105197Ssam			printf("WARNING: pseudo-random number generator "
4242105197Ssam			    "used for IPsec processing\n");
4243105197Ssam			warn = 0;
4244105197Ssam		}
4245105197Ssam	}
4246105197Ssam}
4247105197Ssam
4248105197Ssam/*
4249105197Ssam * map SADB_SATYPE_* to IPPROTO_*.
4250105197Ssam * if satype == SADB_SATYPE then satype is mapped to ~0.
4251105197Ssam * OUT:
4252105197Ssam *	0: invalid satype.
4253105197Ssam */
4254105197Ssamstatic u_int16_t
4255105197Ssamkey_satype2proto(satype)
4256105197Ssam	u_int8_t satype;
4257105197Ssam{
4258105197Ssam	switch (satype) {
4259105197Ssam	case SADB_SATYPE_UNSPEC:
4260105197Ssam		return IPSEC_PROTO_ANY;
4261105197Ssam	case SADB_SATYPE_AH:
4262105197Ssam		return IPPROTO_AH;
4263105197Ssam	case SADB_SATYPE_ESP:
4264105197Ssam		return IPPROTO_ESP;
4265105197Ssam	case SADB_X_SATYPE_IPCOMP:
4266105197Ssam		return IPPROTO_IPCOMP;
4267125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
4268125680Sbms		return IPPROTO_TCP;
4269105197Ssam	default:
4270105197Ssam		return 0;
4271105197Ssam	}
4272105197Ssam	/* NOTREACHED */
4273105197Ssam}
4274105197Ssam
4275105197Ssam/*
4276105197Ssam * map IPPROTO_* to SADB_SATYPE_*
4277105197Ssam * OUT:
4278105197Ssam *	0: invalid protocol type.
4279105197Ssam */
4280105197Ssamstatic u_int8_t
4281105197Ssamkey_proto2satype(proto)
4282105197Ssam	u_int16_t proto;
4283105197Ssam{
4284105197Ssam	switch (proto) {
4285105197Ssam	case IPPROTO_AH:
4286105197Ssam		return SADB_SATYPE_AH;
4287105197Ssam	case IPPROTO_ESP:
4288105197Ssam		return SADB_SATYPE_ESP;
4289105197Ssam	case IPPROTO_IPCOMP:
4290105197Ssam		return SADB_X_SATYPE_IPCOMP;
4291125680Sbms	case IPPROTO_TCP:
4292125680Sbms		return SADB_X_SATYPE_TCPSIGNATURE;
4293105197Ssam	default:
4294105197Ssam		return 0;
4295105197Ssam	}
4296105197Ssam	/* NOTREACHED */
4297105197Ssam}
4298105197Ssam
4299105197Ssam/* %%% PF_KEY */
4300105197Ssam/*
4301105197Ssam * SADB_GETSPI processing is to receive
4302105197Ssam *	<base, (SA2), src address, dst address, (SPI range)>
4303105197Ssam * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4304105197Ssam * tree with the status of LARVAL, and send
4305105197Ssam *	<base, SA(*), address(SD)>
4306105197Ssam * to the IKMPd.
4307105197Ssam *
4308105197Ssam * IN:	mhp: pointer to the pointer to each header.
4309105197Ssam * OUT:	NULL if fail.
4310105197Ssam *	other if success, return pointer to the message to send.
4311105197Ssam */
4312105197Ssamstatic int
4313105197Ssamkey_getspi(so, m, mhp)
4314105197Ssam	struct socket *so;
4315105197Ssam	struct mbuf *m;
4316105197Ssam	const struct sadb_msghdr *mhp;
4317105197Ssam{
4318105197Ssam	struct sadb_address *src0, *dst0;
4319105197Ssam	struct secasindex saidx;
4320105197Ssam	struct secashead *newsah;
4321105197Ssam	struct secasvar *newsav;
4322105197Ssam	u_int8_t proto;
4323105197Ssam	u_int32_t spi;
4324105197Ssam	u_int8_t mode;
4325105197Ssam	u_int32_t reqid;
4326105197Ssam	int error;
4327105197Ssam
4328120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4329120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4330120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4331120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4332105197Ssam
4333105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4334105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4335120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4336120585Ssam			__func__));
4337105197Ssam		return key_senderror(so, m, EINVAL);
4338105197Ssam	}
4339105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4340105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4341120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4342120585Ssam			__func__));
4343105197Ssam		return key_senderror(so, m, EINVAL);
4344105197Ssam	}
4345105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4346105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4347105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4348105197Ssam	} else {
4349105197Ssam		mode = IPSEC_MODE_ANY;
4350105197Ssam		reqid = 0;
4351105197Ssam	}
4352105197Ssam
4353105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4354105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4355105197Ssam
4356105197Ssam	/* map satype to proto */
4357105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4358120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4359120585Ssam			__func__));
4360105197Ssam		return key_senderror(so, m, EINVAL);
4361105197Ssam	}
4362105197Ssam
4363105197Ssam	/* make sure if port number is zero. */
4364105197Ssam	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4365105197Ssam	case AF_INET:
4366105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4367105197Ssam		    sizeof(struct sockaddr_in))
4368105197Ssam			return key_senderror(so, m, EINVAL);
4369105197Ssam		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4370105197Ssam		break;
4371105197Ssam	case AF_INET6:
4372105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4373105197Ssam		    sizeof(struct sockaddr_in6))
4374105197Ssam			return key_senderror(so, m, EINVAL);
4375105197Ssam		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4376105197Ssam		break;
4377105197Ssam	default:
4378105197Ssam		; /*???*/
4379105197Ssam	}
4380105197Ssam	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4381105197Ssam	case AF_INET:
4382105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4383105197Ssam		    sizeof(struct sockaddr_in))
4384105197Ssam			return key_senderror(so, m, EINVAL);
4385105197Ssam		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4386105197Ssam		break;
4387105197Ssam	case AF_INET6:
4388105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4389105197Ssam		    sizeof(struct sockaddr_in6))
4390105197Ssam			return key_senderror(so, m, EINVAL);
4391105197Ssam		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4392105197Ssam		break;
4393105197Ssam	default:
4394105197Ssam		; /*???*/
4395105197Ssam	}
4396105197Ssam
4397105197Ssam	/* XXX boundary check against sa_len */
4398105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4399105197Ssam
4400105197Ssam	/* SPI allocation */
4401105197Ssam	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4402105197Ssam	                       &saidx);
4403105197Ssam	if (spi == 0)
4404105197Ssam		return key_senderror(so, m, EINVAL);
4405105197Ssam
4406105197Ssam	/* get a SA index */
4407105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4408105197Ssam		/* create a new SA index */
4409105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4410120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4411105197Ssam			return key_senderror(so, m, ENOBUFS);
4412105197Ssam		}
4413105197Ssam	}
4414105197Ssam
4415105197Ssam	/* get a new SA */
4416105197Ssam	/* XXX rewrite */
4417105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4418105197Ssam	if (newsav == NULL) {
4419105197Ssam		/* XXX don't free new SA index allocated in above. */
4420105197Ssam		return key_senderror(so, m, error);
4421105197Ssam	}
4422105197Ssam
4423105197Ssam	/* set spi */
4424105197Ssam	newsav->spi = htonl(spi);
4425105197Ssam
4426105197Ssam	/* delete the entry in acqtree */
4427105197Ssam	if (mhp->msg->sadb_msg_seq != 0) {
4428105197Ssam		struct secacq *acq;
4429105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4430105197Ssam			/* reset counter in order to deletion by timehandler. */
4431105197Ssam			acq->created = time_second;
4432105197Ssam			acq->count = 0;
4433105197Ssam		}
4434105197Ssam    	}
4435105197Ssam
4436105197Ssam    {
4437105197Ssam	struct mbuf *n, *nn;
4438105197Ssam	struct sadb_sa *m_sa;
4439105197Ssam	struct sadb_msg *newmsg;
4440105197Ssam	int off, len;
4441105197Ssam
4442105197Ssam	/* create new sadb_msg to reply. */
4443105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4444105197Ssam	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4445105197Ssam	if (len > MCLBYTES)
4446105197Ssam		return key_senderror(so, m, ENOBUFS);
4447105197Ssam
4448111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
4449105197Ssam	if (len > MHLEN) {
4450111119Simp		MCLGET(n, M_DONTWAIT);
4451105197Ssam		if ((n->m_flags & M_EXT) == 0) {
4452105197Ssam			m_freem(n);
4453105197Ssam			n = NULL;
4454105197Ssam		}
4455105197Ssam	}
4456105197Ssam	if (!n)
4457105197Ssam		return key_senderror(so, m, ENOBUFS);
4458105197Ssam
4459105197Ssam	n->m_len = len;
4460105197Ssam	n->m_next = NULL;
4461105197Ssam	off = 0;
4462105197Ssam
4463105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4464105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4465105197Ssam
4466105197Ssam	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4467105197Ssam	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4468105197Ssam	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4469105197Ssam	m_sa->sadb_sa_spi = htonl(spi);
4470105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4471105197Ssam
4472120585Ssam	IPSEC_ASSERT(off == len,
4473120585Ssam		("length inconsistency (off %u len %u)", off, len));
4474105197Ssam
4475105197Ssam	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4476105197Ssam	    SADB_EXT_ADDRESS_DST);
4477105197Ssam	if (!n->m_next) {
4478105197Ssam		m_freem(n);
4479105197Ssam		return key_senderror(so, m, ENOBUFS);
4480105197Ssam	}
4481105197Ssam
4482105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
4483105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
4484105197Ssam		if (n == NULL)
4485105197Ssam			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4486105197Ssam	}
4487105197Ssam
4488105197Ssam	n->m_pkthdr.len = 0;
4489105197Ssam	for (nn = n; nn; nn = nn->m_next)
4490105197Ssam		n->m_pkthdr.len += nn->m_len;
4491105197Ssam
4492105197Ssam	newmsg = mtod(n, struct sadb_msg *);
4493105197Ssam	newmsg->sadb_msg_seq = newsav->seq;
4494105197Ssam	newmsg->sadb_msg_errno = 0;
4495105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4496105197Ssam
4497105197Ssam	m_freem(m);
4498105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4499105197Ssam    }
4500105197Ssam}
4501105197Ssam
4502105197Ssam/*
4503105197Ssam * allocating new SPI
4504105197Ssam * called by key_getspi().
4505105197Ssam * OUT:
4506105197Ssam *	0:	failure.
4507105197Ssam *	others: success.
4508105197Ssam */
4509105197Ssamstatic u_int32_t
4510105197Ssamkey_do_getnewspi(spirange, saidx)
4511105197Ssam	struct sadb_spirange *spirange;
4512105197Ssam	struct secasindex *saidx;
4513105197Ssam{
4514105197Ssam	u_int32_t newspi;
4515105197Ssam	u_int32_t min, max;
4516105197Ssam	int count = key_spi_trycnt;
4517105197Ssam
4518105197Ssam	/* set spi range to allocate */
4519105197Ssam	if (spirange != NULL) {
4520105197Ssam		min = spirange->sadb_spirange_min;
4521105197Ssam		max = spirange->sadb_spirange_max;
4522105197Ssam	} else {
4523105197Ssam		min = key_spi_minval;
4524105197Ssam		max = key_spi_maxval;
4525105197Ssam	}
4526105197Ssam	/* IPCOMP needs 2-byte SPI */
4527105197Ssam	if (saidx->proto == IPPROTO_IPCOMP) {
4528105197Ssam		u_int32_t t;
4529105197Ssam		if (min >= 0x10000)
4530105197Ssam			min = 0xffff;
4531105197Ssam		if (max >= 0x10000)
4532105197Ssam			max = 0xffff;
4533105197Ssam		if (min > max) {
4534105197Ssam			t = min; min = max; max = t;
4535105197Ssam		}
4536105197Ssam	}
4537105197Ssam
4538105197Ssam	if (min == max) {
4539105197Ssam		if (key_checkspidup(saidx, min) != NULL) {
4540120585Ssam			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4541120585Ssam				__func__, min));
4542105197Ssam			return 0;
4543105197Ssam		}
4544105197Ssam
4545105197Ssam		count--; /* taking one cost. */
4546105197Ssam		newspi = min;
4547105197Ssam
4548105197Ssam	} else {
4549105197Ssam
4550105197Ssam		/* init SPI */
4551105197Ssam		newspi = 0;
4552105197Ssam
4553105197Ssam		/* when requesting to allocate spi ranged */
4554105197Ssam		while (count--) {
4555105197Ssam			/* generate pseudo-random SPI value ranged. */
4556105197Ssam			newspi = min + (key_random() % (max - min + 1));
4557105197Ssam
4558105197Ssam			if (key_checkspidup(saidx, newspi) == NULL)
4559105197Ssam				break;
4560105197Ssam		}
4561105197Ssam
4562105197Ssam		if (count == 0 || newspi == 0) {
4563120585Ssam			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4564120585Ssam				__func__));
4565105197Ssam			return 0;
4566105197Ssam		}
4567105197Ssam	}
4568105197Ssam
4569105197Ssam	/* statistics */
4570105197Ssam	keystat.getspi_count =
4571105197Ssam		(keystat.getspi_count + key_spi_trycnt - count) / 2;
4572105197Ssam
4573105197Ssam	return newspi;
4574105197Ssam}
4575105197Ssam
4576105197Ssam/*
4577105197Ssam * SADB_UPDATE processing
4578105197Ssam * receive
4579105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4580105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4581105197Ssam * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4582105197Ssam * and send
4583105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4584105197Ssam *       (identity(SD),) (sensitivity)>
4585105197Ssam * to the ikmpd.
4586105197Ssam *
4587105197Ssam * m will always be freed.
4588105197Ssam */
4589105197Ssamstatic int
4590105197Ssamkey_update(so, m, mhp)
4591105197Ssam	struct socket *so;
4592105197Ssam	struct mbuf *m;
4593105197Ssam	const struct sadb_msghdr *mhp;
4594105197Ssam{
4595105197Ssam	struct sadb_sa *sa0;
4596105197Ssam	struct sadb_address *src0, *dst0;
4597105197Ssam	struct secasindex saidx;
4598105197Ssam	struct secashead *sah;
4599105197Ssam	struct secasvar *sav;
4600105197Ssam	u_int16_t proto;
4601105197Ssam	u_int8_t mode;
4602105197Ssam	u_int32_t reqid;
4603105197Ssam	int error;
4604105197Ssam
4605120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4606120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4607120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4608120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4609105197Ssam
4610105197Ssam	/* map satype to proto */
4611105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4612120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4613120585Ssam			__func__));
4614105197Ssam		return key_senderror(so, m, EINVAL);
4615105197Ssam	}
4616105197Ssam
4617105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
4618105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4619105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4620105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4621105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4622105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4623105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4624105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4625105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4626105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4627105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4628120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4629120585Ssam			__func__));
4630105197Ssam		return key_senderror(so, m, EINVAL);
4631105197Ssam	}
4632105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4633105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4634105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4635120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4636120585Ssam			__func__));
4637105197Ssam		return key_senderror(so, m, EINVAL);
4638105197Ssam	}
4639105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4640105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4641105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4642105197Ssam	} else {
4643105197Ssam		mode = IPSEC_MODE_ANY;
4644105197Ssam		reqid = 0;
4645105197Ssam	}
4646105197Ssam	/* XXX boundary checking for other extensions */
4647105197Ssam
4648105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4649105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4650105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4651105197Ssam
4652105197Ssam	/* XXX boundary check against sa_len */
4653105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4654105197Ssam
4655105197Ssam	/* get a SA header */
4656105197Ssam	if ((sah = key_getsah(&saidx)) == NULL) {
4657120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
4658105197Ssam		return key_senderror(so, m, ENOENT);
4659105197Ssam	}
4660105197Ssam
4661105197Ssam	/* set spidx if there */
4662105197Ssam	/* XXX rewrite */
4663105197Ssam	error = key_setident(sah, m, mhp);
4664105197Ssam	if (error)
4665105197Ssam		return key_senderror(so, m, error);
4666105197Ssam
4667105197Ssam	/* find a SA with sequence number. */
4668105197Ssam#ifdef IPSEC_DOSEQCHECK
4669105197Ssam	if (mhp->msg->sadb_msg_seq != 0
4670105197Ssam	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4671120585Ssam		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
4672120585Ssam			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
4673105197Ssam		return key_senderror(so, m, ENOENT);
4674105197Ssam	}
4675105197Ssam#else
4676120585Ssam	SAHTREE_LOCK();
4677120585Ssam	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4678120585Ssam	SAHTREE_UNLOCK();
4679120585Ssam	if (sav == NULL) {
4680120585Ssam		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
4681120585Ssam			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4682105197Ssam		return key_senderror(so, m, EINVAL);
4683105197Ssam	}
4684105197Ssam#endif
4685105197Ssam
4686105197Ssam	/* validity check */
4687105197Ssam	if (sav->sah->saidx.proto != proto) {
4688120585Ssam		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
4689120585Ssam			"(DB=%u param=%u)\n", __func__,
4690120585Ssam			sav->sah->saidx.proto, proto));
4691105197Ssam		return key_senderror(so, m, EINVAL);
4692105197Ssam	}
4693105197Ssam#ifdef IPSEC_DOSEQCHECK
4694105197Ssam	if (sav->spi != sa0->sadb_sa_spi) {
4695120585Ssam		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
4696120585Ssam		    __func__,
4697105197Ssam		    (u_int32_t)ntohl(sav->spi),
4698105197Ssam		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4699105197Ssam		return key_senderror(so, m, EINVAL);
4700105197Ssam	}
4701105197Ssam#endif
4702105197Ssam	if (sav->pid != mhp->msg->sadb_msg_pid) {
4703120585Ssam		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
4704120585Ssam		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
4705105197Ssam		return key_senderror(so, m, EINVAL);
4706105197Ssam	}
4707105197Ssam
4708105197Ssam	/* copy sav values */
4709105197Ssam	error = key_setsaval(sav, m, mhp);
4710105197Ssam	if (error) {
4711105197Ssam		KEY_FREESAV(&sav);
4712105197Ssam		return key_senderror(so, m, error);
4713105197Ssam	}
4714105197Ssam
4715105197Ssam	/* check SA values to be mature. */
4716105197Ssam	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4717105197Ssam		KEY_FREESAV(&sav);
4718105197Ssam		return key_senderror(so, m, 0);
4719105197Ssam	}
4720105197Ssam
4721105197Ssam    {
4722105197Ssam	struct mbuf *n;
4723105197Ssam
4724105197Ssam	/* set msg buf from mhp */
4725105197Ssam	n = key_getmsgbuf_x1(m, mhp);
4726105197Ssam	if (n == NULL) {
4727120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4728105197Ssam		return key_senderror(so, m, ENOBUFS);
4729105197Ssam	}
4730105197Ssam
4731105197Ssam	m_freem(m);
4732105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4733105197Ssam    }
4734105197Ssam}
4735105197Ssam
4736105197Ssam/*
4737105197Ssam * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4738105197Ssam * only called by key_update().
4739105197Ssam * OUT:
4740105197Ssam *	NULL	: not found
4741105197Ssam *	others	: found, pointer to a SA.
4742105197Ssam */
4743105197Ssam#ifdef IPSEC_DOSEQCHECK
4744105197Ssamstatic struct secasvar *
4745105197Ssamkey_getsavbyseq(sah, seq)
4746105197Ssam	struct secashead *sah;
4747105197Ssam	u_int32_t seq;
4748105197Ssam{
4749105197Ssam	struct secasvar *sav;
4750105197Ssam	u_int state;
4751105197Ssam
4752105197Ssam	state = SADB_SASTATE_LARVAL;
4753105197Ssam
4754105197Ssam	/* search SAD with sequence number ? */
4755105197Ssam	LIST_FOREACH(sav, &sah->savtree[state], chain) {
4756105197Ssam
4757120585Ssam		KEY_CHKSASTATE(state, sav->state, __func__);
4758105197Ssam
4759105197Ssam		if (sav->seq == seq) {
4760105197Ssam			SA_ADDREF(sav);
4761105197Ssam			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4762120585Ssam				printf("DP %s cause refcnt++:%d SA:%p\n",
4763120585Ssam					__func__, sav->refcnt, sav));
4764105197Ssam			return sav;
4765105197Ssam		}
4766105197Ssam	}
4767105197Ssam
4768105197Ssam	return NULL;
4769105197Ssam}
4770105197Ssam#endif
4771105197Ssam
4772105197Ssam/*
4773105197Ssam * SADB_ADD processing
4774108533Sschweikh * add an entry to SA database, when received
4775105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4776105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4777105197Ssam * from the ikmpd,
4778105197Ssam * and send
4779105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4780105197Ssam *       (identity(SD),) (sensitivity)>
4781105197Ssam * to the ikmpd.
4782105197Ssam *
4783105197Ssam * IGNORE identity and sensitivity messages.
4784105197Ssam *
4785105197Ssam * m will always be freed.
4786105197Ssam */
4787105197Ssamstatic int
4788105197Ssamkey_add(so, m, mhp)
4789105197Ssam	struct socket *so;
4790105197Ssam	struct mbuf *m;
4791105197Ssam	const struct sadb_msghdr *mhp;
4792105197Ssam{
4793105197Ssam	struct sadb_sa *sa0;
4794105197Ssam	struct sadb_address *src0, *dst0;
4795105197Ssam	struct secasindex saidx;
4796105197Ssam	struct secashead *newsah;
4797105197Ssam	struct secasvar *newsav;
4798105197Ssam	u_int16_t proto;
4799105197Ssam	u_int8_t mode;
4800105197Ssam	u_int32_t reqid;
4801105197Ssam	int error;
4802105197Ssam
4803120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4804120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4805120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4806120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4807105197Ssam
4808105197Ssam	/* map satype to proto */
4809105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4810120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4811120585Ssam			__func__));
4812105197Ssam		return key_senderror(so, m, EINVAL);
4813105197Ssam	}
4814105197Ssam
4815105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
4816105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4817105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4818105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4819105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4820105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4821105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4822105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4823105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4824105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4825105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4826120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4827120585Ssam			__func__));
4828105197Ssam		return key_senderror(so, m, EINVAL);
4829105197Ssam	}
4830105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4831105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4832105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4833105197Ssam		/* XXX need more */
4834120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4835120585Ssam			__func__));
4836105197Ssam		return key_senderror(so, m, EINVAL);
4837105197Ssam	}
4838105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4839105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4840105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4841105197Ssam	} else {
4842105197Ssam		mode = IPSEC_MODE_ANY;
4843105197Ssam		reqid = 0;
4844105197Ssam	}
4845105197Ssam
4846105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4847105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4848105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4849105197Ssam
4850105197Ssam	/* XXX boundary check against sa_len */
4851105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4852105197Ssam
4853105197Ssam	/* get a SA header */
4854105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4855105197Ssam		/* create a new SA header */
4856105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4857120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4858105197Ssam			return key_senderror(so, m, ENOBUFS);
4859105197Ssam		}
4860105197Ssam	}
4861105197Ssam
4862105197Ssam	/* set spidx if there */
4863105197Ssam	/* XXX rewrite */
4864105197Ssam	error = key_setident(newsah, m, mhp);
4865105197Ssam	if (error) {
4866105197Ssam		return key_senderror(so, m, error);
4867105197Ssam	}
4868105197Ssam
4869105197Ssam	/* create new SA entry. */
4870105197Ssam	/* We can create new SA only if SPI is differenct. */
4871120585Ssam	SAHTREE_LOCK();
4872120585Ssam	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
4873120585Ssam	SAHTREE_UNLOCK();
4874120585Ssam	if (newsav != NULL) {
4875120585Ssam		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
4876105197Ssam		return key_senderror(so, m, EEXIST);
4877105197Ssam	}
4878105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4879105197Ssam	if (newsav == NULL) {
4880105197Ssam		return key_senderror(so, m, error);
4881105197Ssam	}
4882105197Ssam
4883105197Ssam	/* check SA values to be mature. */
4884105197Ssam	if ((error = key_mature(newsav)) != 0) {
4885105197Ssam		KEY_FREESAV(&newsav);
4886105197Ssam		return key_senderror(so, m, error);
4887105197Ssam	}
4888105197Ssam
4889105197Ssam	/*
4890105197Ssam	 * don't call key_freesav() here, as we would like to keep the SA
4891105197Ssam	 * in the database on success.
4892105197Ssam	 */
4893105197Ssam
4894105197Ssam    {
4895105197Ssam	struct mbuf *n;
4896105197Ssam
4897105197Ssam	/* set msg buf from mhp */
4898105197Ssam	n = key_getmsgbuf_x1(m, mhp);
4899105197Ssam	if (n == NULL) {
4900120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4901105197Ssam		return key_senderror(so, m, ENOBUFS);
4902105197Ssam	}
4903105197Ssam
4904105197Ssam	m_freem(m);
4905105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4906105197Ssam    }
4907105197Ssam}
4908105197Ssam
4909105197Ssam/* m is retained */
4910105197Ssamstatic int
4911105197Ssamkey_setident(sah, m, mhp)
4912105197Ssam	struct secashead *sah;
4913105197Ssam	struct mbuf *m;
4914105197Ssam	const struct sadb_msghdr *mhp;
4915105197Ssam{
4916105197Ssam	const struct sadb_ident *idsrc, *iddst;
4917105197Ssam	int idsrclen, iddstlen;
4918105197Ssam
4919120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
4920120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4921120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4922120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4923105197Ssam
4924105197Ssam	/* don't make buffer if not there */
4925105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
4926105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4927105197Ssam		sah->idents = NULL;
4928105197Ssam		sah->identd = NULL;
4929105197Ssam		return 0;
4930105197Ssam	}
4931105197Ssam
4932105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
4933105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4934120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
4935105197Ssam		return EINVAL;
4936105197Ssam	}
4937105197Ssam
4938105197Ssam	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
4939105197Ssam	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
4940105197Ssam	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
4941105197Ssam	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
4942105197Ssam
4943105197Ssam	/* validity check */
4944105197Ssam	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
4945120585Ssam		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
4946105197Ssam		return EINVAL;
4947105197Ssam	}
4948105197Ssam
4949105197Ssam	switch (idsrc->sadb_ident_type) {
4950105197Ssam	case SADB_IDENTTYPE_PREFIX:
4951105197Ssam	case SADB_IDENTTYPE_FQDN:
4952105197Ssam	case SADB_IDENTTYPE_USERFQDN:
4953105197Ssam	default:
4954105197Ssam		/* XXX do nothing */
4955105197Ssam		sah->idents = NULL;
4956105197Ssam		sah->identd = NULL;
4957105197Ssam	 	return 0;
4958105197Ssam	}
4959105197Ssam
4960105197Ssam	/* make structure */
4961119643Ssam	sah->idents = malloc(idsrclen, M_IPSEC_MISC, M_NOWAIT);
4962105197Ssam	if (sah->idents == NULL) {
4963120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4964105197Ssam		return ENOBUFS;
4965105197Ssam	}
4966119643Ssam	sah->identd = malloc(iddstlen, M_IPSEC_MISC, M_NOWAIT);
4967105197Ssam	if (sah->identd == NULL) {
4968119643Ssam		free(sah->idents, M_IPSEC_MISC);
4969105197Ssam		sah->idents = NULL;
4970120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4971105197Ssam		return ENOBUFS;
4972105197Ssam	}
4973105197Ssam	bcopy(idsrc, sah->idents, idsrclen);
4974105197Ssam	bcopy(iddst, sah->identd, iddstlen);
4975105197Ssam
4976105197Ssam	return 0;
4977105197Ssam}
4978105197Ssam
4979105197Ssam/*
4980105197Ssam * m will not be freed on return.
4981105197Ssam * it is caller's responsibility to free the result.
4982105197Ssam */
4983105197Ssamstatic struct mbuf *
4984105197Ssamkey_getmsgbuf_x1(m, mhp)
4985105197Ssam	struct mbuf *m;
4986105197Ssam	const struct sadb_msghdr *mhp;
4987105197Ssam{
4988105197Ssam	struct mbuf *n;
4989105197Ssam
4990120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4991120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4992120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4993105197Ssam
4994105197Ssam	/* create new sadb_msg to reply. */
4995105197Ssam	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
4996105197Ssam	    SADB_EXT_SA, SADB_X_EXT_SA2,
4997105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
4998105197Ssam	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
4999105197Ssam	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5000105197Ssam	if (!n)
5001105197Ssam		return NULL;
5002105197Ssam
5003105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5004105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5005105197Ssam		if (n == NULL)
5006105197Ssam			return NULL;
5007105197Ssam	}
5008105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5009105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_len =
5010105197Ssam	    PFKEY_UNIT64(n->m_pkthdr.len);
5011105197Ssam
5012105197Ssam	return n;
5013105197Ssam}
5014105197Ssam
5015105197Ssamstatic int key_delete_all __P((struct socket *, struct mbuf *,
5016105197Ssam	const struct sadb_msghdr *, u_int16_t));
5017105197Ssam
5018105197Ssam/*
5019105197Ssam * SADB_DELETE processing
5020105197Ssam * receive
5021105197Ssam *   <base, SA(*), address(SD)>
5022105197Ssam * from the ikmpd, and set SADB_SASTATE_DEAD,
5023105197Ssam * and send,
5024105197Ssam *   <base, SA(*), address(SD)>
5025105197Ssam * to the ikmpd.
5026105197Ssam *
5027105197Ssam * m will always be freed.
5028105197Ssam */
5029105197Ssamstatic int
5030105197Ssamkey_delete(so, m, mhp)
5031105197Ssam	struct socket *so;
5032105197Ssam	struct mbuf *m;
5033105197Ssam	const struct sadb_msghdr *mhp;
5034105197Ssam{
5035105197Ssam	struct sadb_sa *sa0;
5036105197Ssam	struct sadb_address *src0, *dst0;
5037105197Ssam	struct secasindex saidx;
5038105197Ssam	struct secashead *sah;
5039105197Ssam	struct secasvar *sav = NULL;
5040105197Ssam	u_int16_t proto;
5041105197Ssam
5042120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5043120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5044120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5045120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5046105197Ssam
5047105197Ssam	/* map satype to proto */
5048105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5049120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5050120585Ssam			__func__));
5051105197Ssam		return key_senderror(so, m, EINVAL);
5052105197Ssam	}
5053105197Ssam
5054105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5055105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5056120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5057120585Ssam			__func__));
5058105197Ssam		return key_senderror(so, m, EINVAL);
5059105197Ssam	}
5060105197Ssam
5061105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5062105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5063120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5064120585Ssam			__func__));
5065105197Ssam		return key_senderror(so, m, EINVAL);
5066105197Ssam	}
5067105197Ssam
5068105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL) {
5069105197Ssam		/*
5070105197Ssam		 * Caller wants us to delete all non-LARVAL SAs
5071105197Ssam		 * that match the src/dst.  This is used during
5072105197Ssam		 * IKE INITIAL-CONTACT.
5073105197Ssam		 */
5074120585Ssam		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5075105197Ssam		return key_delete_all(so, m, mhp, proto);
5076105197Ssam	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5077120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5078120585Ssam			__func__));
5079105197Ssam		return key_senderror(so, m, EINVAL);
5080105197Ssam	}
5081105197Ssam
5082105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5083105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5084105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5085105197Ssam
5086105197Ssam	/* XXX boundary check against sa_len */
5087105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5088105197Ssam
5089105197Ssam	/* get a SA header */
5090120585Ssam	SAHTREE_LOCK();
5091105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
5092105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5093105197Ssam			continue;
5094105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5095105197Ssam			continue;
5096105197Ssam
5097105197Ssam		/* get a SA with SPI. */
5098105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5099105197Ssam		if (sav)
5100105197Ssam			break;
5101105197Ssam	}
5102105197Ssam	if (sah == NULL) {
5103120585Ssam		SAHTREE_UNLOCK();
5104120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5105105197Ssam		return key_senderror(so, m, ENOENT);
5106105197Ssam	}
5107105197Ssam
5108105197Ssam	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5109120585Ssam	SAHTREE_UNLOCK();
5110105197Ssam	KEY_FREESAV(&sav);
5111105197Ssam
5112105197Ssam    {
5113105197Ssam	struct mbuf *n;
5114105197Ssam	struct sadb_msg *newmsg;
5115105197Ssam
5116105197Ssam	/* create new sadb_msg to reply. */
5117105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5118105197Ssam	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5119105197Ssam	if (!n)
5120105197Ssam		return key_senderror(so, m, ENOBUFS);
5121105197Ssam
5122105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5123105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5124105197Ssam		if (n == NULL)
5125105197Ssam			return key_senderror(so, m, ENOBUFS);
5126105197Ssam	}
5127105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5128105197Ssam	newmsg->sadb_msg_errno = 0;
5129105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5130105197Ssam
5131105197Ssam	m_freem(m);
5132105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5133105197Ssam    }
5134105197Ssam}
5135105197Ssam
5136105197Ssam/*
5137105197Ssam * delete all SAs for src/dst.  Called from key_delete().
5138105197Ssam */
5139105197Ssamstatic int
5140105197Ssamkey_delete_all(so, m, mhp, proto)
5141105197Ssam	struct socket *so;
5142105197Ssam	struct mbuf *m;
5143105197Ssam	const struct sadb_msghdr *mhp;
5144105197Ssam	u_int16_t proto;
5145105197Ssam{
5146105197Ssam	struct sadb_address *src0, *dst0;
5147105197Ssam	struct secasindex saidx;
5148105197Ssam	struct secashead *sah;
5149105197Ssam	struct secasvar *sav, *nextsav;
5150105197Ssam	u_int stateidx, state;
5151105197Ssam
5152105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5153105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5154105197Ssam
5155105197Ssam	/* XXX boundary check against sa_len */
5156105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5157105197Ssam
5158120585Ssam	SAHTREE_LOCK();
5159105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
5160105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5161105197Ssam			continue;
5162105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5163105197Ssam			continue;
5164105197Ssam
5165105197Ssam		/* Delete all non-LARVAL SAs. */
5166105197Ssam		for (stateidx = 0;
5167105197Ssam		     stateidx < _ARRAYLEN(saorder_state_alive);
5168105197Ssam		     stateidx++) {
5169105197Ssam			state = saorder_state_alive[stateidx];
5170105197Ssam			if (state == SADB_SASTATE_LARVAL)
5171105197Ssam				continue;
5172105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
5173105197Ssam			     sav != NULL; sav = nextsav) {
5174105197Ssam				nextsav = LIST_NEXT(sav, chain);
5175105197Ssam				/* sanity check */
5176105197Ssam				if (sav->state != state) {
5177120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
5178120585Ssam						"sav->state (queue %d SA %d)\n",
5179120585Ssam						__func__, state, sav->state));
5180105197Ssam					continue;
5181105197Ssam				}
5182105197Ssam
5183105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5184105197Ssam				KEY_FREESAV(&sav);
5185105197Ssam			}
5186105197Ssam		}
5187105197Ssam	}
5188120585Ssam	SAHTREE_UNLOCK();
5189105197Ssam    {
5190105197Ssam	struct mbuf *n;
5191105197Ssam	struct sadb_msg *newmsg;
5192105197Ssam
5193105197Ssam	/* create new sadb_msg to reply. */
5194105197Ssam	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5195105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5196105197Ssam	if (!n)
5197105197Ssam		return key_senderror(so, m, ENOBUFS);
5198105197Ssam
5199105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5200105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5201105197Ssam		if (n == NULL)
5202105197Ssam			return key_senderror(so, m, ENOBUFS);
5203105197Ssam	}
5204105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5205105197Ssam	newmsg->sadb_msg_errno = 0;
5206105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5207105197Ssam
5208105197Ssam	m_freem(m);
5209105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5210105197Ssam    }
5211105197Ssam}
5212105197Ssam
5213105197Ssam/*
5214105197Ssam * SADB_GET processing
5215105197Ssam * receive
5216105197Ssam *   <base, SA(*), address(SD)>
5217105197Ssam * from the ikmpd, and get a SP and a SA to respond,
5218105197Ssam * and send,
5219105197Ssam *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5220105197Ssam *       (identity(SD),) (sensitivity)>
5221105197Ssam * to the ikmpd.
5222105197Ssam *
5223105197Ssam * m will always be freed.
5224105197Ssam */
5225105197Ssamstatic int
5226105197Ssamkey_get(so, m, mhp)
5227105197Ssam	struct socket *so;
5228105197Ssam	struct mbuf *m;
5229105197Ssam	const struct sadb_msghdr *mhp;
5230105197Ssam{
5231105197Ssam	struct sadb_sa *sa0;
5232105197Ssam	struct sadb_address *src0, *dst0;
5233105197Ssam	struct secasindex saidx;
5234105197Ssam	struct secashead *sah;
5235105197Ssam	struct secasvar *sav = NULL;
5236105197Ssam	u_int16_t proto;
5237105197Ssam
5238120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5239120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5240120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5241120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5242105197Ssam
5243105197Ssam	/* map satype to proto */
5244105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5245120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5246120585Ssam			__func__));
5247105197Ssam		return key_senderror(so, m, EINVAL);
5248105197Ssam	}
5249105197Ssam
5250105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5251105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5252105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5253120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5254120585Ssam			__func__));
5255105197Ssam		return key_senderror(so, m, EINVAL);
5256105197Ssam	}
5257105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5258105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5259105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5260120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5261120585Ssam			__func__));
5262105197Ssam		return key_senderror(so, m, EINVAL);
5263105197Ssam	}
5264105197Ssam
5265105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5266105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5267105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5268105197Ssam
5269105197Ssam	/* XXX boundary check against sa_len */
5270105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5271105197Ssam
5272105197Ssam	/* get a SA header */
5273120585Ssam	SAHTREE_LOCK();
5274105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
5275105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5276105197Ssam			continue;
5277105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5278105197Ssam			continue;
5279105197Ssam
5280105197Ssam		/* get a SA with SPI. */
5281105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5282105197Ssam		if (sav)
5283105197Ssam			break;
5284105197Ssam	}
5285120585Ssam	SAHTREE_UNLOCK();
5286105197Ssam	if (sah == NULL) {
5287120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5288105197Ssam		return key_senderror(so, m, ENOENT);
5289105197Ssam	}
5290105197Ssam
5291105197Ssam    {
5292105197Ssam	struct mbuf *n;
5293105197Ssam	u_int8_t satype;
5294105197Ssam
5295105197Ssam	/* map proto to satype */
5296105197Ssam	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5297120585Ssam		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5298120585Ssam			__func__));
5299105197Ssam		return key_senderror(so, m, EINVAL);
5300105197Ssam	}
5301105197Ssam
5302105197Ssam	/* create new sadb_msg to reply. */
5303105197Ssam	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5304105197Ssam	    mhp->msg->sadb_msg_pid);
5305105197Ssam	if (!n)
5306105197Ssam		return key_senderror(so, m, ENOBUFS);
5307105197Ssam
5308105197Ssam	m_freem(m);
5309105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5310105197Ssam    }
5311105197Ssam}
5312105197Ssam
5313105197Ssam/* XXX make it sysctl-configurable? */
5314105197Ssamstatic void
5315105197Ssamkey_getcomb_setlifetime(comb)
5316105197Ssam	struct sadb_comb *comb;
5317105197Ssam{
5318105197Ssam
5319105197Ssam	comb->sadb_comb_soft_allocations = 1;
5320105197Ssam	comb->sadb_comb_hard_allocations = 1;
5321105197Ssam	comb->sadb_comb_soft_bytes = 0;
5322105197Ssam	comb->sadb_comb_hard_bytes = 0;
5323105197Ssam	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5324105197Ssam	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5325105197Ssam	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5326105197Ssam	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5327105197Ssam}
5328105197Ssam
5329105197Ssam/*
5330105197Ssam * XXX reorder combinations by preference
5331105197Ssam * XXX no idea if the user wants ESP authentication or not
5332105197Ssam */
5333105197Ssamstatic struct mbuf *
5334105197Ssamkey_getcomb_esp()
5335105197Ssam{
5336105197Ssam	struct sadb_comb *comb;
5337105197Ssam	struct enc_xform *algo;
5338105197Ssam	struct mbuf *result = NULL, *m, *n;
5339105197Ssam	int encmin;
5340105197Ssam	int i, off, o;
5341105197Ssam	int totlen;
5342105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5343105197Ssam
5344105197Ssam	m = NULL;
5345105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
5346105197Ssam		algo = esp_algorithm_lookup(i);
5347105197Ssam		if (algo == NULL)
5348105197Ssam			continue;
5349105197Ssam
5350105197Ssam		/* discard algorithms with key size smaller than system min */
5351105197Ssam		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
5352105197Ssam			continue;
5353105197Ssam		if (_BITS(algo->minkey) < ipsec_esp_keymin)
5354105197Ssam			encmin = ipsec_esp_keymin;
5355105197Ssam		else
5356105197Ssam			encmin = _BITS(algo->minkey);
5357105197Ssam
5358105197Ssam		if (ipsec_esp_auth)
5359105197Ssam			m = key_getcomb_ah();
5360105197Ssam		else {
5361120585Ssam			IPSEC_ASSERT(l <= MLEN,
5362120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5363111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5364105197Ssam			if (m) {
5365105197Ssam				M_ALIGN(m, l);
5366105197Ssam				m->m_len = l;
5367105197Ssam				m->m_next = NULL;
5368105197Ssam				bzero(mtod(m, caddr_t), m->m_len);
5369105197Ssam			}
5370105197Ssam		}
5371105197Ssam		if (!m)
5372105197Ssam			goto fail;
5373105197Ssam
5374105197Ssam		totlen = 0;
5375105197Ssam		for (n = m; n; n = n->m_next)
5376105197Ssam			totlen += n->m_len;
5377120585Ssam		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
5378105197Ssam
5379105197Ssam		for (off = 0; off < totlen; off += l) {
5380105197Ssam			n = m_pulldown(m, off, l, &o);
5381105197Ssam			if (!n) {
5382105197Ssam				/* m is already freed */
5383105197Ssam				goto fail;
5384105197Ssam			}
5385105197Ssam			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5386105197Ssam			bzero(comb, sizeof(*comb));
5387105197Ssam			key_getcomb_setlifetime(comb);
5388105197Ssam			comb->sadb_comb_encrypt = i;
5389105197Ssam			comb->sadb_comb_encrypt_minbits = encmin;
5390105197Ssam			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5391105197Ssam		}
5392105197Ssam
5393105197Ssam		if (!result)
5394105197Ssam			result = m;
5395105197Ssam		else
5396105197Ssam			m_cat(result, m);
5397105197Ssam	}
5398105197Ssam
5399105197Ssam	return result;
5400105197Ssam
5401105197Ssam fail:
5402105197Ssam	if (result)
5403105197Ssam		m_freem(result);
5404105197Ssam	return NULL;
5405105197Ssam}
5406105197Ssam
5407105197Ssamstatic void
5408105197Ssamkey_getsizes_ah(
5409105197Ssam	const struct auth_hash *ah,
5410105197Ssam	int alg,
5411105197Ssam	u_int16_t* min,
5412105197Ssam	u_int16_t* max)
5413105197Ssam{
5414105197Ssam	*min = *max = ah->keysize;
5415105197Ssam	if (ah->keysize == 0) {
5416105197Ssam		/*
5417105197Ssam		 * Transform takes arbitrary key size but algorithm
5418105197Ssam		 * key size is restricted.  Enforce this here.
5419105197Ssam		 */
5420105197Ssam		switch (alg) {
5421105197Ssam		case SADB_X_AALG_MD5:	*min = *max = 16; break;
5422105197Ssam		case SADB_X_AALG_SHA:	*min = *max = 20; break;
5423105197Ssam		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
5424105197Ssam		default:
5425120585Ssam			DPRINTF(("%s: unknown AH algorithm %u\n",
5426120585Ssam				__func__, alg));
5427105197Ssam			break;
5428105197Ssam		}
5429105197Ssam	}
5430105197Ssam}
5431105197Ssam
5432105197Ssam/*
5433105197Ssam * XXX reorder combinations by preference
5434105197Ssam */
5435105197Ssamstatic struct mbuf *
5436105197Ssamkey_getcomb_ah()
5437105197Ssam{
5438105197Ssam	struct sadb_comb *comb;
5439105197Ssam	struct auth_hash *algo;
5440105197Ssam	struct mbuf *m;
5441105197Ssam	u_int16_t minkeysize, maxkeysize;
5442105197Ssam	int i;
5443105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5444105197Ssam
5445105197Ssam	m = NULL;
5446105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
5447105197Ssam#if 1
5448105197Ssam		/* we prefer HMAC algorithms, not old algorithms */
5449105197Ssam		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5450105197Ssam			continue;
5451105197Ssam#endif
5452105197Ssam		algo = ah_algorithm_lookup(i);
5453105197Ssam		if (!algo)
5454105197Ssam			continue;
5455105197Ssam		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5456105197Ssam		/* discard algorithms with key size smaller than system min */
5457105197Ssam		if (_BITS(minkeysize) < ipsec_ah_keymin)
5458105197Ssam			continue;
5459105197Ssam
5460105197Ssam		if (!m) {
5461120585Ssam			IPSEC_ASSERT(l <= MLEN,
5462120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5463111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5464105197Ssam			if (m) {
5465105197Ssam				M_ALIGN(m, l);
5466105197Ssam				m->m_len = l;
5467105197Ssam				m->m_next = NULL;
5468105197Ssam			}
5469105197Ssam		} else
5470111119Simp			M_PREPEND(m, l, M_DONTWAIT);
5471105197Ssam		if (!m)
5472105197Ssam			return NULL;
5473105197Ssam
5474105197Ssam		comb = mtod(m, struct sadb_comb *);
5475105197Ssam		bzero(comb, sizeof(*comb));
5476105197Ssam		key_getcomb_setlifetime(comb);
5477105197Ssam		comb->sadb_comb_auth = i;
5478105197Ssam		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5479105197Ssam		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5480105197Ssam	}
5481105197Ssam
5482105197Ssam	return m;
5483105197Ssam}
5484105197Ssam
5485105197Ssam/*
5486105197Ssam * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5487105197Ssam * XXX reorder combinations by preference
5488105197Ssam */
5489105197Ssamstatic struct mbuf *
5490105197Ssamkey_getcomb_ipcomp()
5491105197Ssam{
5492105197Ssam	struct sadb_comb *comb;
5493105197Ssam	struct comp_algo *algo;
5494105197Ssam	struct mbuf *m;
5495105197Ssam	int i;
5496105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5497105197Ssam
5498105197Ssam	m = NULL;
5499105197Ssam	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5500105197Ssam		algo = ipcomp_algorithm_lookup(i);
5501105197Ssam		if (!algo)
5502105197Ssam			continue;
5503105197Ssam
5504105197Ssam		if (!m) {
5505120585Ssam			IPSEC_ASSERT(l <= MLEN,
5506120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5507111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5508105197Ssam			if (m) {
5509105197Ssam				M_ALIGN(m, l);
5510105197Ssam				m->m_len = l;
5511105197Ssam				m->m_next = NULL;
5512105197Ssam			}
5513105197Ssam		} else
5514111119Simp			M_PREPEND(m, l, M_DONTWAIT);
5515105197Ssam		if (!m)
5516105197Ssam			return NULL;
5517105197Ssam
5518105197Ssam		comb = mtod(m, struct sadb_comb *);
5519105197Ssam		bzero(comb, sizeof(*comb));
5520105197Ssam		key_getcomb_setlifetime(comb);
5521105197Ssam		comb->sadb_comb_encrypt = i;
5522105197Ssam		/* what should we set into sadb_comb_*_{min,max}bits? */
5523105197Ssam	}
5524105197Ssam
5525105197Ssam	return m;
5526105197Ssam}
5527105197Ssam
5528105197Ssam/*
5529105197Ssam * XXX no way to pass mode (transport/tunnel) to userland
5530105197Ssam * XXX replay checking?
5531105197Ssam * XXX sysctl interface to ipsec_{ah,esp}_keymin
5532105197Ssam */
5533105197Ssamstatic struct mbuf *
5534105197Ssamkey_getprop(saidx)
5535105197Ssam	const struct secasindex *saidx;
5536105197Ssam{
5537105197Ssam	struct sadb_prop *prop;
5538105197Ssam	struct mbuf *m, *n;
5539105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5540105197Ssam	int totlen;
5541105197Ssam
5542105197Ssam	switch (saidx->proto)  {
5543105197Ssam	case IPPROTO_ESP:
5544105197Ssam		m = key_getcomb_esp();
5545105197Ssam		break;
5546105197Ssam	case IPPROTO_AH:
5547105197Ssam		m = key_getcomb_ah();
5548105197Ssam		break;
5549105197Ssam	case IPPROTO_IPCOMP:
5550105197Ssam		m = key_getcomb_ipcomp();
5551105197Ssam		break;
5552105197Ssam	default:
5553105197Ssam		return NULL;
5554105197Ssam	}
5555105197Ssam
5556105197Ssam	if (!m)
5557105197Ssam		return NULL;
5558111119Simp	M_PREPEND(m, l, M_DONTWAIT);
5559105197Ssam	if (!m)
5560105197Ssam		return NULL;
5561105197Ssam
5562105197Ssam	totlen = 0;
5563105197Ssam	for (n = m; n; n = n->m_next)
5564105197Ssam		totlen += n->m_len;
5565105197Ssam
5566105197Ssam	prop = mtod(m, struct sadb_prop *);
5567105197Ssam	bzero(prop, sizeof(*prop));
5568105197Ssam	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5569105197Ssam	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5570105197Ssam	prop->sadb_prop_replay = 32;	/* XXX */
5571105197Ssam
5572105197Ssam	return m;
5573105197Ssam}
5574105197Ssam
5575105197Ssam/*
5576105197Ssam * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5577105197Ssam * send
5578105197Ssam *   <base, SA, address(SD), (address(P)), x_policy,
5579105197Ssam *       (identity(SD),) (sensitivity,) proposal>
5580105197Ssam * to KMD, and expect to receive
5581105197Ssam *   <base> with SADB_ACQUIRE if error occured,
5582105197Ssam * or
5583105197Ssam *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5584105197Ssam * from KMD by PF_KEY.
5585105197Ssam *
5586105197Ssam * XXX x_policy is outside of RFC2367 (KAME extension).
5587105197Ssam * XXX sensitivity is not supported.
5588105197Ssam * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5589105197Ssam * see comment for key_getcomb_ipcomp().
5590105197Ssam *
5591105197Ssam * OUT:
5592105197Ssam *    0     : succeed
5593105197Ssam *    others: error number
5594105197Ssam */
5595105197Ssamstatic int
5596105197Ssamkey_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5597105197Ssam{
5598105197Ssam	struct mbuf *result = NULL, *m;
5599105197Ssam	struct secacq *newacq;
5600105197Ssam	u_int8_t satype;
5601105197Ssam	int error = -1;
5602105197Ssam	u_int32_t seq;
5603105197Ssam
5604120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
5605105197Ssam	satype = key_proto2satype(saidx->proto);
5606120585Ssam	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
5607105197Ssam
5608105197Ssam	/*
5609105197Ssam	 * We never do anything about acquirng SA.  There is anather
5610105197Ssam	 * solution that kernel blocks to send SADB_ACQUIRE message until
5611105197Ssam	 * getting something message from IKEd.  In later case, to be
5612105197Ssam	 * managed with ACQUIRING list.
5613105197Ssam	 */
5614108533Sschweikh	/* Get an entry to check whether sending message or not. */
5615105197Ssam	if ((newacq = key_getacq(saidx)) != NULL) {
5616105197Ssam		if (key_blockacq_count < newacq->count) {
5617105197Ssam			/* reset counter and do send message. */
5618105197Ssam			newacq->count = 0;
5619105197Ssam		} else {
5620105197Ssam			/* increment counter and do nothing. */
5621105197Ssam			newacq->count++;
5622105197Ssam			return 0;
5623105197Ssam		}
5624105197Ssam	} else {
5625105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
5626105197Ssam		if ((newacq = key_newacq(saidx)) == NULL)
5627105197Ssam			return ENOBUFS;
5628105197Ssam	}
5629105197Ssam
5630105197Ssam
5631105197Ssam	seq = newacq->seq;
5632105197Ssam	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5633105197Ssam	if (!m) {
5634105197Ssam		error = ENOBUFS;
5635105197Ssam		goto fail;
5636105197Ssam	}
5637105197Ssam	result = m;
5638105197Ssam
5639105197Ssam	/* set sadb_address for saidx's. */
5640105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5641105197Ssam	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5642105197Ssam	if (!m) {
5643105197Ssam		error = ENOBUFS;
5644105197Ssam		goto fail;
5645105197Ssam	}
5646105197Ssam	m_cat(result, m);
5647105197Ssam
5648105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5649105197Ssam	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5650105197Ssam	if (!m) {
5651105197Ssam		error = ENOBUFS;
5652105197Ssam		goto fail;
5653105197Ssam	}
5654105197Ssam	m_cat(result, m);
5655105197Ssam
5656105197Ssam	/* XXX proxy address (optional) */
5657105197Ssam
5658105197Ssam	/* set sadb_x_policy */
5659105197Ssam	if (sp) {
5660105197Ssam		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5661105197Ssam		if (!m) {
5662105197Ssam			error = ENOBUFS;
5663105197Ssam			goto fail;
5664105197Ssam		}
5665105197Ssam		m_cat(result, m);
5666105197Ssam	}
5667105197Ssam
5668105197Ssam	/* XXX identity (optional) */
5669105197Ssam#if 0
5670105197Ssam	if (idexttype && fqdn) {
5671105197Ssam		/* create identity extension (FQDN) */
5672105197Ssam		struct sadb_ident *id;
5673105197Ssam		int fqdnlen;
5674105197Ssam
5675105197Ssam		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
5676105197Ssam		id = (struct sadb_ident *)p;
5677105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5678105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5679105197Ssam		id->sadb_ident_exttype = idexttype;
5680105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5681105197Ssam		bcopy(fqdn, id + 1, fqdnlen);
5682105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5683105197Ssam	}
5684105197Ssam
5685105197Ssam	if (idexttype) {
5686105197Ssam		/* create identity extension (USERFQDN) */
5687105197Ssam		struct sadb_ident *id;
5688105197Ssam		int userfqdnlen;
5689105197Ssam
5690105197Ssam		if (userfqdn) {
5691105197Ssam			/* +1 for terminating-NUL */
5692105197Ssam			userfqdnlen = strlen(userfqdn) + 1;
5693105197Ssam		} else
5694105197Ssam			userfqdnlen = 0;
5695105197Ssam		id = (struct sadb_ident *)p;
5696105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5697105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5698105197Ssam		id->sadb_ident_exttype = idexttype;
5699105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5700105197Ssam		/* XXX is it correct? */
5701105197Ssam		if (curproc && curproc->p_cred)
5702105197Ssam			id->sadb_ident_id = curproc->p_cred->p_ruid;
5703105197Ssam		if (userfqdn && userfqdnlen)
5704105197Ssam			bcopy(userfqdn, id + 1, userfqdnlen);
5705105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5706105197Ssam	}
5707105197Ssam#endif
5708105197Ssam
5709105197Ssam	/* XXX sensitivity (optional) */
5710105197Ssam
5711105197Ssam	/* create proposal/combination extension */
5712105197Ssam	m = key_getprop(saidx);
5713105197Ssam#if 0
5714105197Ssam	/*
5715105197Ssam	 * spec conformant: always attach proposal/combination extension,
5716105197Ssam	 * the problem is that we have no way to attach it for ipcomp,
5717105197Ssam	 * due to the way sadb_comb is declared in RFC2367.
5718105197Ssam	 */
5719105197Ssam	if (!m) {
5720105197Ssam		error = ENOBUFS;
5721105197Ssam		goto fail;
5722105197Ssam	}
5723105197Ssam	m_cat(result, m);
5724105197Ssam#else
5725105197Ssam	/*
5726105197Ssam	 * outside of spec; make proposal/combination extension optional.
5727105197Ssam	 */
5728105197Ssam	if (m)
5729105197Ssam		m_cat(result, m);
5730105197Ssam#endif
5731105197Ssam
5732105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
5733105197Ssam		error = EINVAL;
5734105197Ssam		goto fail;
5735105197Ssam	}
5736105197Ssam
5737105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
5738105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
5739105197Ssam		if (result == NULL) {
5740105197Ssam			error = ENOBUFS;
5741105197Ssam			goto fail;
5742105197Ssam		}
5743105197Ssam	}
5744105197Ssam
5745105197Ssam	result->m_pkthdr.len = 0;
5746105197Ssam	for (m = result; m; m = m->m_next)
5747105197Ssam		result->m_pkthdr.len += m->m_len;
5748105197Ssam
5749105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
5750105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
5751105197Ssam
5752105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5753105197Ssam
5754105197Ssam fail:
5755105197Ssam	if (result)
5756105197Ssam		m_freem(result);
5757105197Ssam	return error;
5758105197Ssam}
5759105197Ssam
5760105197Ssamstatic struct secacq *
5761105197Ssamkey_newacq(const struct secasindex *saidx)
5762105197Ssam{
5763105197Ssam	struct secacq *newacq;
5764105197Ssam
5765105197Ssam	/* get new entry */
5766119643Ssam	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5767105197Ssam	if (newacq == NULL) {
5768120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5769105197Ssam		return NULL;
5770105197Ssam	}
5771105197Ssam
5772105197Ssam	/* copy secindex */
5773105197Ssam	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5774105197Ssam	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
5775105197Ssam	newacq->created = time_second;
5776105197Ssam	newacq->count = 0;
5777105197Ssam
5778119643Ssam	/* add to acqtree */
5779120585Ssam	ACQ_LOCK();
5780119643Ssam	LIST_INSERT_HEAD(&acqtree, newacq, chain);
5781120585Ssam	ACQ_UNLOCK();
5782119643Ssam
5783105197Ssam	return newacq;
5784105197Ssam}
5785105197Ssam
5786105197Ssamstatic struct secacq *
5787105197Ssamkey_getacq(const struct secasindex *saidx)
5788105197Ssam{
5789105197Ssam	struct secacq *acq;
5790105197Ssam
5791120585Ssam	ACQ_LOCK();
5792105197Ssam	LIST_FOREACH(acq, &acqtree, chain) {
5793105197Ssam		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5794119643Ssam			break;
5795105197Ssam	}
5796120585Ssam	ACQ_UNLOCK();
5797105197Ssam
5798119643Ssam	return acq;
5799105197Ssam}
5800105197Ssam
5801105197Ssamstatic struct secacq *
5802105197Ssamkey_getacqbyseq(seq)
5803105197Ssam	u_int32_t seq;
5804105197Ssam{
5805105197Ssam	struct secacq *acq;
5806105197Ssam
5807120585Ssam	ACQ_LOCK();
5808105197Ssam	LIST_FOREACH(acq, &acqtree, chain) {
5809105197Ssam		if (acq->seq == seq)
5810119643Ssam			break;
5811105197Ssam	}
5812120585Ssam	ACQ_UNLOCK();
5813105197Ssam
5814119643Ssam	return acq;
5815105197Ssam}
5816105197Ssam
5817105197Ssamstatic struct secspacq *
5818105197Ssamkey_newspacq(spidx)
5819105197Ssam	struct secpolicyindex *spidx;
5820105197Ssam{
5821105197Ssam	struct secspacq *acq;
5822105197Ssam
5823105197Ssam	/* get new entry */
5824119643Ssam	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5825105197Ssam	if (acq == NULL) {
5826120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5827105197Ssam		return NULL;
5828105197Ssam	}
5829105197Ssam
5830105197Ssam	/* copy secindex */
5831105197Ssam	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5832105197Ssam	acq->created = time_second;
5833105197Ssam	acq->count = 0;
5834105197Ssam
5835119643Ssam	/* add to spacqtree */
5836120585Ssam	SPACQ_LOCK();
5837119643Ssam	LIST_INSERT_HEAD(&spacqtree, acq, chain);
5838120585Ssam	SPACQ_UNLOCK();
5839119643Ssam
5840105197Ssam	return acq;
5841105197Ssam}
5842105197Ssam
5843105197Ssamstatic struct secspacq *
5844105197Ssamkey_getspacq(spidx)
5845105197Ssam	struct secpolicyindex *spidx;
5846105197Ssam{
5847105197Ssam	struct secspacq *acq;
5848105197Ssam
5849120585Ssam	SPACQ_LOCK();
5850105197Ssam	LIST_FOREACH(acq, &spacqtree, chain) {
5851119643Ssam		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
5852119643Ssam			/* NB: return holding spacq_lock */
5853105197Ssam			return acq;
5854119643Ssam		}
5855105197Ssam	}
5856120585Ssam	SPACQ_UNLOCK();
5857105197Ssam
5858105197Ssam	return NULL;
5859105197Ssam}
5860105197Ssam
5861105197Ssam/*
5862105197Ssam * SADB_ACQUIRE processing,
5863105197Ssam * in first situation, is receiving
5864105197Ssam *   <base>
5865105197Ssam * from the ikmpd, and clear sequence of its secasvar entry.
5866105197Ssam *
5867105197Ssam * In second situation, is receiving
5868105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5869105197Ssam * from a user land process, and return
5870105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5871105197Ssam * to the socket.
5872105197Ssam *
5873105197Ssam * m will always be freed.
5874105197Ssam */
5875105197Ssamstatic int
5876105197Ssamkey_acquire2(so, m, mhp)
5877105197Ssam	struct socket *so;
5878105197Ssam	struct mbuf *m;
5879105197Ssam	const struct sadb_msghdr *mhp;
5880105197Ssam{
5881105197Ssam	const struct sadb_address *src0, *dst0;
5882105197Ssam	struct secasindex saidx;
5883105197Ssam	struct secashead *sah;
5884105197Ssam	u_int16_t proto;
5885105197Ssam	int error;
5886105197Ssam
5887120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5888120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5889120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5890120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5891105197Ssam
5892105197Ssam	/*
5893105197Ssam	 * Error message from KMd.
5894105197Ssam	 * We assume that if error was occured in IKEd, the length of PFKEY
5895105197Ssam	 * message is equal to the size of sadb_msg structure.
5896105197Ssam	 * We do not raise error even if error occured in this function.
5897105197Ssam	 */
5898105197Ssam	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
5899105197Ssam		struct secacq *acq;
5900105197Ssam
5901105197Ssam		/* check sequence number */
5902105197Ssam		if (mhp->msg->sadb_msg_seq == 0) {
5903120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify sequence "
5904120585Ssam				"number.\n", __func__));
5905105197Ssam			m_freem(m);
5906105197Ssam			return 0;
5907105197Ssam		}
5908105197Ssam
5909105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
5910105197Ssam			/*
5911105197Ssam			 * the specified larval SA is already gone, or we got
5912105197Ssam			 * a bogus sequence number.  we can silently ignore it.
5913105197Ssam			 */
5914105197Ssam			m_freem(m);
5915105197Ssam			return 0;
5916105197Ssam		}
5917105197Ssam
5918105197Ssam		/* reset acq counter in order to deletion by timehander. */
5919105197Ssam		acq->created = time_second;
5920105197Ssam		acq->count = 0;
5921105197Ssam		m_freem(m);
5922105197Ssam		return 0;
5923105197Ssam	}
5924105197Ssam
5925105197Ssam	/*
5926105197Ssam	 * This message is from user land.
5927105197Ssam	 */
5928105197Ssam
5929105197Ssam	/* map satype to proto */
5930105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5931120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5932120585Ssam			__func__));
5933105197Ssam		return key_senderror(so, m, EINVAL);
5934105197Ssam	}
5935105197Ssam
5936105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5937105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5938105197Ssam	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
5939105197Ssam		/* error */
5940120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5941120585Ssam			__func__));
5942105197Ssam		return key_senderror(so, m, EINVAL);
5943105197Ssam	}
5944105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5945105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
5946105197Ssam	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
5947105197Ssam		/* error */
5948120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5949120585Ssam			__func__));
5950105197Ssam		return key_senderror(so, m, EINVAL);
5951105197Ssam	}
5952105197Ssam
5953105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5954105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5955105197Ssam
5956105197Ssam	/* XXX boundary check against sa_len */
5957105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5958105197Ssam
5959105197Ssam	/* get a SA index */
5960120585Ssam	SAHTREE_LOCK();
5961105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
5962105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5963105197Ssam			continue;
5964105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
5965105197Ssam			break;
5966105197Ssam	}
5967120585Ssam	SAHTREE_UNLOCK();
5968105197Ssam	if (sah != NULL) {
5969120585Ssam		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
5970105197Ssam		return key_senderror(so, m, EEXIST);
5971105197Ssam	}
5972105197Ssam
5973105197Ssam	error = key_acquire(&saidx, NULL);
5974105197Ssam	if (error != 0) {
5975120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
5976120585Ssam			__func__, mhp->msg->sadb_msg_errno));
5977105197Ssam		return key_senderror(so, m, error);
5978105197Ssam	}
5979105197Ssam
5980105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
5981105197Ssam}
5982105197Ssam
5983105197Ssam/*
5984105197Ssam * SADB_REGISTER processing.
5985105197Ssam * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
5986105197Ssam * receive
5987105197Ssam *   <base>
5988105197Ssam * from the ikmpd, and register a socket to send PF_KEY messages,
5989105197Ssam * and send
5990105197Ssam *   <base, supported>
5991105197Ssam * to KMD by PF_KEY.
5992105197Ssam * If socket is detached, must free from regnode.
5993105197Ssam *
5994105197Ssam * m will always be freed.
5995105197Ssam */
5996105197Ssamstatic int
5997105197Ssamkey_register(so, m, mhp)
5998105197Ssam	struct socket *so;
5999105197Ssam	struct mbuf *m;
6000105197Ssam	const struct sadb_msghdr *mhp;
6001105197Ssam{
6002105197Ssam	struct secreg *reg, *newreg = 0;
6003105197Ssam
6004120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6005120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6006120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6007120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6008105197Ssam
6009105197Ssam	/* check for invalid register message */
6010105197Ssam	if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
6011105197Ssam		return key_senderror(so, m, EINVAL);
6012105197Ssam
6013105197Ssam	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6014105197Ssam	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6015105197Ssam		goto setmsg;
6016105197Ssam
6017105197Ssam	/* check whether existing or not */
6018120585Ssam	REGTREE_LOCK();
6019105197Ssam	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
6020105197Ssam		if (reg->so == so) {
6021120585Ssam			REGTREE_UNLOCK();
6022120585Ssam			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6023120585Ssam				__func__));
6024105197Ssam			return key_senderror(so, m, EEXIST);
6025105197Ssam		}
6026105197Ssam	}
6027105197Ssam
6028105197Ssam	/* create regnode */
6029119643Ssam	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6030105197Ssam	if (newreg == NULL) {
6031120585Ssam		REGTREE_UNLOCK();
6032120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6033105197Ssam		return key_senderror(so, m, ENOBUFS);
6034105197Ssam	}
6035105197Ssam
6036105197Ssam	newreg->so = so;
6037105197Ssam	((struct keycb *)sotorawcb(so))->kp_registered++;
6038105197Ssam
6039105197Ssam	/* add regnode to regtree. */
6040105197Ssam	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6041120585Ssam	REGTREE_UNLOCK();
6042105197Ssam
6043105197Ssam  setmsg:
6044105197Ssam    {
6045105197Ssam	struct mbuf *n;
6046105197Ssam	struct sadb_msg *newmsg;
6047105197Ssam	struct sadb_supported *sup;
6048105197Ssam	u_int len, alen, elen;
6049105197Ssam	int off;
6050105197Ssam	int i;
6051105197Ssam	struct sadb_alg *alg;
6052105197Ssam
6053105197Ssam	/* create new sadb_msg to reply. */
6054105197Ssam	alen = 0;
6055105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6056105197Ssam		if (ah_algorithm_lookup(i))
6057105197Ssam			alen += sizeof(struct sadb_alg);
6058105197Ssam	}
6059105197Ssam	if (alen)
6060105197Ssam		alen += sizeof(struct sadb_supported);
6061105197Ssam	elen = 0;
6062105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6063105197Ssam		if (esp_algorithm_lookup(i))
6064105197Ssam			elen += sizeof(struct sadb_alg);
6065105197Ssam	}
6066105197Ssam	if (elen)
6067105197Ssam		elen += sizeof(struct sadb_supported);
6068105197Ssam
6069105197Ssam	len = sizeof(struct sadb_msg) + alen + elen;
6070105197Ssam
6071105197Ssam	if (len > MCLBYTES)
6072105197Ssam		return key_senderror(so, m, ENOBUFS);
6073105197Ssam
6074111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
6075105197Ssam	if (len > MHLEN) {
6076111119Simp		MCLGET(n, M_DONTWAIT);
6077105197Ssam		if ((n->m_flags & M_EXT) == 0) {
6078105197Ssam			m_freem(n);
6079105197Ssam			n = NULL;
6080105197Ssam		}
6081105197Ssam	}
6082105197Ssam	if (!n)
6083105197Ssam		return key_senderror(so, m, ENOBUFS);
6084105197Ssam
6085105197Ssam	n->m_pkthdr.len = n->m_len = len;
6086105197Ssam	n->m_next = NULL;
6087105197Ssam	off = 0;
6088105197Ssam
6089105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6090105197Ssam	newmsg = mtod(n, struct sadb_msg *);
6091105197Ssam	newmsg->sadb_msg_errno = 0;
6092105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6093105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6094105197Ssam
6095105197Ssam	/* for authentication algorithm */
6096105197Ssam	if (alen) {
6097105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6098105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6099105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6100105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6101105197Ssam
6102105197Ssam		for (i = 1; i <= SADB_AALG_MAX; i++) {
6103105197Ssam			struct auth_hash *aalgo;
6104105197Ssam			u_int16_t minkeysize, maxkeysize;
6105105197Ssam
6106105197Ssam			aalgo = ah_algorithm_lookup(i);
6107105197Ssam			if (!aalgo)
6108105197Ssam				continue;
6109105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6110105197Ssam			alg->sadb_alg_id = i;
6111105197Ssam			alg->sadb_alg_ivlen = 0;
6112105197Ssam			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6113105197Ssam			alg->sadb_alg_minbits = _BITS(minkeysize);
6114105197Ssam			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6115105197Ssam			off += PFKEY_ALIGN8(sizeof(*alg));
6116105197Ssam		}
6117105197Ssam	}
6118105197Ssam
6119105197Ssam	/* for encryption algorithm */
6120105197Ssam	if (elen) {
6121105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6122105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6123105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6124105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6125105197Ssam
6126105197Ssam		for (i = 1; i <= SADB_EALG_MAX; i++) {
6127105197Ssam			struct enc_xform *ealgo;
6128105197Ssam
6129105197Ssam			ealgo = esp_algorithm_lookup(i);
6130105197Ssam			if (!ealgo)
6131105197Ssam				continue;
6132105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6133105197Ssam			alg->sadb_alg_id = i;
6134105197Ssam			alg->sadb_alg_ivlen = ealgo->blocksize;
6135105197Ssam			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6136105197Ssam			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6137105197Ssam			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6138105197Ssam		}
6139105197Ssam	}
6140105197Ssam
6141120585Ssam	IPSEC_ASSERT(off == len,
6142120585Ssam		("length assumption failed (off %u len %u)", off, len));
6143105197Ssam
6144105197Ssam	m_freem(m);
6145105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6146105197Ssam    }
6147105197Ssam}
6148105197Ssam
6149105197Ssam/*
6150105197Ssam * free secreg entry registered.
6151105197Ssam * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6152105197Ssam */
6153105197Ssamvoid
6154119643Ssamkey_freereg(struct socket *so)
6155105197Ssam{
6156105197Ssam	struct secreg *reg;
6157105197Ssam	int i;
6158105197Ssam
6159120585Ssam	IPSEC_ASSERT(so != NULL, ("NULL so"));
6160105197Ssam
6161105197Ssam	/*
6162105197Ssam	 * check whether existing or not.
6163105197Ssam	 * check all type of SA, because there is a potential that
6164105197Ssam	 * one socket is registered to multiple type of SA.
6165105197Ssam	 */
6166120585Ssam	REGTREE_LOCK();
6167105197Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6168105197Ssam		LIST_FOREACH(reg, &regtree[i], chain) {
6169119643Ssam			if (reg->so == so && __LIST_CHAINED(reg)) {
6170105197Ssam				LIST_REMOVE(reg, chain);
6171119643Ssam				free(reg, M_IPSEC_SAR);
6172105197Ssam				break;
6173105197Ssam			}
6174105197Ssam		}
6175105197Ssam	}
6176120585Ssam	REGTREE_UNLOCK();
6177105197Ssam}
6178105197Ssam
6179105197Ssam/*
6180105197Ssam * SADB_EXPIRE processing
6181105197Ssam * send
6182105197Ssam *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6183105197Ssam * to KMD by PF_KEY.
6184105197Ssam * NOTE: We send only soft lifetime extension.
6185105197Ssam *
6186105197Ssam * OUT:	0	: succeed
6187105197Ssam *	others	: error number
6188105197Ssam */
6189105197Ssamstatic int
6190119643Ssamkey_expire(struct secasvar *sav)
6191105197Ssam{
6192105197Ssam	int s;
6193105197Ssam	int satype;
6194105197Ssam	struct mbuf *result = NULL, *m;
6195105197Ssam	int len;
6196105197Ssam	int error = -1;
6197105197Ssam	struct sadb_lifetime *lt;
6198105197Ssam
6199105197Ssam	/* XXX: Why do we lock ? */
6200105197Ssam	s = splnet();	/*called from softclock()*/
6201105197Ssam
6202120585Ssam	IPSEC_ASSERT (sav != NULL, ("null sav"));
6203120585Ssam	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6204105197Ssam
6205105197Ssam	/* set msg header */
6206120585Ssam	satype = key_proto2satype(sav->sah->saidx.proto);
6207120585Ssam	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6208105197Ssam	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6209105197Ssam	if (!m) {
6210105197Ssam		error = ENOBUFS;
6211105197Ssam		goto fail;
6212105197Ssam	}
6213105197Ssam	result = m;
6214105197Ssam
6215105197Ssam	/* create SA extension */
6216105197Ssam	m = key_setsadbsa(sav);
6217105197Ssam	if (!m) {
6218105197Ssam		error = ENOBUFS;
6219105197Ssam		goto fail;
6220105197Ssam	}
6221105197Ssam	m_cat(result, m);
6222105197Ssam
6223105197Ssam	/* create SA extension */
6224105197Ssam	m = key_setsadbxsa2(sav->sah->saidx.mode,
6225105197Ssam			sav->replay ? sav->replay->count : 0,
6226105197Ssam			sav->sah->saidx.reqid);
6227105197Ssam	if (!m) {
6228105197Ssam		error = ENOBUFS;
6229105197Ssam		goto fail;
6230105197Ssam	}
6231105197Ssam	m_cat(result, m);
6232105197Ssam
6233105197Ssam	/* create lifetime extension (current and soft) */
6234105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6235105197Ssam	m = key_alloc_mbuf(len);
6236105197Ssam	if (!m || m->m_next) {	/*XXX*/
6237105197Ssam		if (m)
6238105197Ssam			m_freem(m);
6239105197Ssam		error = ENOBUFS;
6240105197Ssam		goto fail;
6241105197Ssam	}
6242105197Ssam	bzero(mtod(m, caddr_t), len);
6243105197Ssam	lt = mtod(m, struct sadb_lifetime *);
6244105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6245105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6246105197Ssam	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6247105197Ssam	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6248105197Ssam	lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
6249105197Ssam	lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
6250105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6251105197Ssam	bcopy(sav->lft_s, lt, sizeof(*lt));
6252105197Ssam	m_cat(result, m);
6253105197Ssam
6254105197Ssam	/* set sadb_address for source */
6255105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6256105197Ssam	    &sav->sah->saidx.src.sa,
6257105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6258105197Ssam	if (!m) {
6259105197Ssam		error = ENOBUFS;
6260105197Ssam		goto fail;
6261105197Ssam	}
6262105197Ssam	m_cat(result, m);
6263105197Ssam
6264105197Ssam	/* set sadb_address for destination */
6265105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6266105197Ssam	    &sav->sah->saidx.dst.sa,
6267105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6268105197Ssam	if (!m) {
6269105197Ssam		error = ENOBUFS;
6270105197Ssam		goto fail;
6271105197Ssam	}
6272105197Ssam	m_cat(result, m);
6273105197Ssam
6274105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
6275105197Ssam		error = EINVAL;
6276105197Ssam		goto fail;
6277105197Ssam	}
6278105197Ssam
6279105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
6280105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
6281105197Ssam		if (result == NULL) {
6282105197Ssam			error = ENOBUFS;
6283105197Ssam			goto fail;
6284105197Ssam		}
6285105197Ssam	}
6286105197Ssam
6287105197Ssam	result->m_pkthdr.len = 0;
6288105197Ssam	for (m = result; m; m = m->m_next)
6289105197Ssam		result->m_pkthdr.len += m->m_len;
6290105197Ssam
6291105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
6292105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
6293105197Ssam
6294105197Ssam	splx(s);
6295105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6296105197Ssam
6297105197Ssam fail:
6298105197Ssam	if (result)
6299105197Ssam		m_freem(result);
6300105197Ssam	splx(s);
6301105197Ssam	return error;
6302105197Ssam}
6303105197Ssam
6304105197Ssam/*
6305105197Ssam * SADB_FLUSH processing
6306105197Ssam * receive
6307105197Ssam *   <base>
6308105197Ssam * from the ikmpd, and free all entries in secastree.
6309105197Ssam * and send,
6310105197Ssam *   <base>
6311105197Ssam * to the ikmpd.
6312105197Ssam * NOTE: to do is only marking SADB_SASTATE_DEAD.
6313105197Ssam *
6314105197Ssam * m will always be freed.
6315105197Ssam */
6316105197Ssamstatic int
6317105197Ssamkey_flush(so, m, mhp)
6318105197Ssam	struct socket *so;
6319105197Ssam	struct mbuf *m;
6320105197Ssam	const struct sadb_msghdr *mhp;
6321105197Ssam{
6322105197Ssam	struct sadb_msg *newmsg;
6323105197Ssam	struct secashead *sah, *nextsah;
6324105197Ssam	struct secasvar *sav, *nextsav;
6325105197Ssam	u_int16_t proto;
6326105197Ssam	u_int8_t state;
6327105197Ssam	u_int stateidx;
6328105197Ssam
6329120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6330120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6331120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6332105197Ssam
6333105197Ssam	/* map satype to proto */
6334105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6335120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6336120585Ssam			__func__));
6337105197Ssam		return key_senderror(so, m, EINVAL);
6338105197Ssam	}
6339105197Ssam
6340105197Ssam	/* no SATYPE specified, i.e. flushing all SA. */
6341120585Ssam	SAHTREE_LOCK();
6342105197Ssam	for (sah = LIST_FIRST(&sahtree);
6343105197Ssam	     sah != NULL;
6344105197Ssam	     sah = nextsah) {
6345105197Ssam		nextsah = LIST_NEXT(sah, chain);
6346105197Ssam
6347105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6348105197Ssam		 && proto != sah->saidx.proto)
6349105197Ssam			continue;
6350105197Ssam
6351105197Ssam		for (stateidx = 0;
6352105197Ssam		     stateidx < _ARRAYLEN(saorder_state_alive);
6353105197Ssam		     stateidx++) {
6354105197Ssam			state = saorder_state_any[stateidx];
6355105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
6356105197Ssam			     sav != NULL;
6357105197Ssam			     sav = nextsav) {
6358105197Ssam
6359105197Ssam				nextsav = LIST_NEXT(sav, chain);
6360105197Ssam
6361105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6362105197Ssam				KEY_FREESAV(&sav);
6363105197Ssam			}
6364105197Ssam		}
6365105197Ssam
6366105197Ssam		sah->state = SADB_SASTATE_DEAD;
6367105197Ssam	}
6368120585Ssam	SAHTREE_UNLOCK();
6369105197Ssam
6370105197Ssam	if (m->m_len < sizeof(struct sadb_msg) ||
6371105197Ssam	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6372120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6373105197Ssam		return key_senderror(so, m, ENOBUFS);
6374105197Ssam	}
6375105197Ssam
6376105197Ssam	if (m->m_next)
6377105197Ssam		m_freem(m->m_next);
6378105197Ssam	m->m_next = NULL;
6379105197Ssam	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6380105197Ssam	newmsg = mtod(m, struct sadb_msg *);
6381105197Ssam	newmsg->sadb_msg_errno = 0;
6382105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6383105197Ssam
6384105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6385105197Ssam}
6386105197Ssam
6387105197Ssam/*
6388105197Ssam * SADB_DUMP processing
6389105197Ssam * dump all entries including status of DEAD in SAD.
6390105197Ssam * receive
6391105197Ssam *   <base>
6392105197Ssam * from the ikmpd, and dump all secasvar leaves
6393105197Ssam * and send,
6394105197Ssam *   <base> .....
6395105197Ssam * to the ikmpd.
6396105197Ssam *
6397105197Ssam * m will always be freed.
6398105197Ssam */
6399105197Ssamstatic int
6400105197Ssamkey_dump(so, m, mhp)
6401105197Ssam	struct socket *so;
6402105197Ssam	struct mbuf *m;
6403105197Ssam	const struct sadb_msghdr *mhp;
6404105197Ssam{
6405105197Ssam	struct secashead *sah;
6406105197Ssam	struct secasvar *sav;
6407105197Ssam	u_int16_t proto;
6408105197Ssam	u_int stateidx;
6409105197Ssam	u_int8_t satype;
6410105197Ssam	u_int8_t state;
6411105197Ssam	int cnt;
6412105197Ssam	struct sadb_msg *newmsg;
6413105197Ssam	struct mbuf *n;
6414105197Ssam
6415120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6416120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6417120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6418120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6419105197Ssam
6420105197Ssam	/* map satype to proto */
6421105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6422120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6423120585Ssam			__func__));
6424105197Ssam		return key_senderror(so, m, EINVAL);
6425105197Ssam	}
6426105197Ssam
6427105197Ssam	/* count sav entries to be sent to the userland. */
6428105197Ssam	cnt = 0;
6429120585Ssam	SAHTREE_LOCK();
6430105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
6431105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6432105197Ssam		 && proto != sah->saidx.proto)
6433105197Ssam			continue;
6434105197Ssam
6435105197Ssam		for (stateidx = 0;
6436105197Ssam		     stateidx < _ARRAYLEN(saorder_state_any);
6437105197Ssam		     stateidx++) {
6438105197Ssam			state = saorder_state_any[stateidx];
6439105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6440105197Ssam				cnt++;
6441105197Ssam			}
6442105197Ssam		}
6443105197Ssam	}
6444105197Ssam
6445119643Ssam	if (cnt == 0) {
6446120585Ssam		SAHTREE_UNLOCK();
6447105197Ssam		return key_senderror(so, m, ENOENT);
6448119643Ssam	}
6449105197Ssam
6450105197Ssam	/* send this to the userland, one at a time. */
6451105197Ssam	newmsg = NULL;
6452105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
6453105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6454105197Ssam		 && proto != sah->saidx.proto)
6455105197Ssam			continue;
6456105197Ssam
6457105197Ssam		/* map proto to satype */
6458105197Ssam		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6459120585Ssam			SAHTREE_UNLOCK();
6460120585Ssam			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
6461120585Ssam				"SAD.\n", __func__));
6462105197Ssam			return key_senderror(so, m, EINVAL);
6463105197Ssam		}
6464105197Ssam
6465105197Ssam		for (stateidx = 0;
6466105197Ssam		     stateidx < _ARRAYLEN(saorder_state_any);
6467105197Ssam		     stateidx++) {
6468105197Ssam			state = saorder_state_any[stateidx];
6469105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6470105197Ssam				n = key_setdumpsa(sav, SADB_DUMP, satype,
6471105197Ssam				    --cnt, mhp->msg->sadb_msg_pid);
6472119643Ssam				if (!n) {
6473120585Ssam					SAHTREE_UNLOCK();
6474105197Ssam					return key_senderror(so, m, ENOBUFS);
6475119643Ssam				}
6476105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6477105197Ssam			}
6478105197Ssam		}
6479105197Ssam	}
6480120585Ssam	SAHTREE_UNLOCK();
6481105197Ssam
6482105197Ssam	m_freem(m);
6483105197Ssam	return 0;
6484105197Ssam}
6485105197Ssam
6486105197Ssam/*
6487105197Ssam * SADB_X_PROMISC processing
6488105197Ssam *
6489105197Ssam * m will always be freed.
6490105197Ssam */
6491105197Ssamstatic int
6492105197Ssamkey_promisc(so, m, mhp)
6493105197Ssam	struct socket *so;
6494105197Ssam	struct mbuf *m;
6495105197Ssam	const struct sadb_msghdr *mhp;
6496105197Ssam{
6497105197Ssam	int olen;
6498105197Ssam
6499120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6500120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6501120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6502120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6503105197Ssam
6504105197Ssam	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6505105197Ssam
6506105197Ssam	if (olen < sizeof(struct sadb_msg)) {
6507105197Ssam#if 1
6508105197Ssam		return key_senderror(so, m, EINVAL);
6509105197Ssam#else
6510105197Ssam		m_freem(m);
6511105197Ssam		return 0;
6512105197Ssam#endif
6513105197Ssam	} else if (olen == sizeof(struct sadb_msg)) {
6514105197Ssam		/* enable/disable promisc mode */
6515105197Ssam		struct keycb *kp;
6516105197Ssam
6517105197Ssam		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6518105197Ssam			return key_senderror(so, m, EINVAL);
6519105197Ssam		mhp->msg->sadb_msg_errno = 0;
6520105197Ssam		switch (mhp->msg->sadb_msg_satype) {
6521105197Ssam		case 0:
6522105197Ssam		case 1:
6523105197Ssam			kp->kp_promisc = mhp->msg->sadb_msg_satype;
6524105197Ssam			break;
6525105197Ssam		default:
6526105197Ssam			return key_senderror(so, m, EINVAL);
6527105197Ssam		}
6528105197Ssam
6529105197Ssam		/* send the original message back to everyone */
6530105197Ssam		mhp->msg->sadb_msg_errno = 0;
6531105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6532105197Ssam	} else {
6533105197Ssam		/* send packet as is */
6534105197Ssam
6535105197Ssam		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6536105197Ssam
6537105197Ssam		/* TODO: if sadb_msg_seq is specified, send to specific pid */
6538105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6539105197Ssam	}
6540105197Ssam}
6541105197Ssam
6542105197Ssamstatic int (*key_typesw[]) __P((struct socket *, struct mbuf *,
6543105197Ssam		const struct sadb_msghdr *)) = {
6544105197Ssam	NULL,		/* SADB_RESERVED */
6545105197Ssam	key_getspi,	/* SADB_GETSPI */
6546105197Ssam	key_update,	/* SADB_UPDATE */
6547105197Ssam	key_add,	/* SADB_ADD */
6548105197Ssam	key_delete,	/* SADB_DELETE */
6549105197Ssam	key_get,	/* SADB_GET */
6550105197Ssam	key_acquire2,	/* SADB_ACQUIRE */
6551105197Ssam	key_register,	/* SADB_REGISTER */
6552105197Ssam	NULL,		/* SADB_EXPIRE */
6553105197Ssam	key_flush,	/* SADB_FLUSH */
6554105197Ssam	key_dump,	/* SADB_DUMP */
6555105197Ssam	key_promisc,	/* SADB_X_PROMISC */
6556105197Ssam	NULL,		/* SADB_X_PCHANGE */
6557105197Ssam	key_spdadd,	/* SADB_X_SPDUPDATE */
6558105197Ssam	key_spdadd,	/* SADB_X_SPDADD */
6559105197Ssam	key_spddelete,	/* SADB_X_SPDDELETE */
6560105197Ssam	key_spdget,	/* SADB_X_SPDGET */
6561105197Ssam	NULL,		/* SADB_X_SPDACQUIRE */
6562105197Ssam	key_spddump,	/* SADB_X_SPDDUMP */
6563105197Ssam	key_spdflush,	/* SADB_X_SPDFLUSH */
6564105197Ssam	key_spdadd,	/* SADB_X_SPDSETIDX */
6565105197Ssam	NULL,		/* SADB_X_SPDEXPIRE */
6566105197Ssam	key_spddelete2,	/* SADB_X_SPDDELETE2 */
6567105197Ssam};
6568105197Ssam
6569105197Ssam/*
6570105197Ssam * parse sadb_msg buffer to process PFKEYv2,
6571105197Ssam * and create a data to response if needed.
6572105197Ssam * I think to be dealed with mbuf directly.
6573105197Ssam * IN:
6574105197Ssam *     msgp  : pointer to pointer to a received buffer pulluped.
6575105197Ssam *             This is rewrited to response.
6576105197Ssam *     so    : pointer to socket.
6577105197Ssam * OUT:
6578105197Ssam *    length for buffer to send to user process.
6579105197Ssam */
6580105197Ssamint
6581105197Ssamkey_parse(m, so)
6582105197Ssam	struct mbuf *m;
6583105197Ssam	struct socket *so;
6584105197Ssam{
6585105197Ssam	struct sadb_msg *msg;
6586105197Ssam	struct sadb_msghdr mh;
6587105197Ssam	u_int orglen;
6588105197Ssam	int error;
6589105197Ssam	int target;
6590105197Ssam
6591120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6592120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6593105197Ssam
6594105197Ssam#if 0	/*kdebug_sadb assumes msg in linear buffer*/
6595105197Ssam	KEYDEBUG(KEYDEBUG_KEY_DUMP,
6596120585Ssam		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
6597105197Ssam		kdebug_sadb(msg));
6598105197Ssam#endif
6599105197Ssam
6600105197Ssam	if (m->m_len < sizeof(struct sadb_msg)) {
6601105197Ssam		m = m_pullup(m, sizeof(struct sadb_msg));
6602105197Ssam		if (!m)
6603105197Ssam			return ENOBUFS;
6604105197Ssam	}
6605105197Ssam	msg = mtod(m, struct sadb_msg *);
6606105197Ssam	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6607105197Ssam	target = KEY_SENDUP_ONE;
6608105197Ssam
6609105197Ssam	if ((m->m_flags & M_PKTHDR) == 0 ||
6610105197Ssam	    m->m_pkthdr.len != m->m_pkthdr.len) {
6611120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
6612105197Ssam		pfkeystat.out_invlen++;
6613105197Ssam		error = EINVAL;
6614105197Ssam		goto senderror;
6615105197Ssam	}
6616105197Ssam
6617105197Ssam	if (msg->sadb_msg_version != PF_KEY_V2) {
6618120585Ssam		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
6619120585Ssam		    __func__, msg->sadb_msg_version));
6620105197Ssam		pfkeystat.out_invver++;
6621105197Ssam		error = EINVAL;
6622105197Ssam		goto senderror;
6623105197Ssam	}
6624105197Ssam
6625105197Ssam	if (msg->sadb_msg_type > SADB_MAX) {
6626120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6627120585Ssam		    __func__, msg->sadb_msg_type));
6628105197Ssam		pfkeystat.out_invmsgtype++;
6629105197Ssam		error = EINVAL;
6630105197Ssam		goto senderror;
6631105197Ssam	}
6632105197Ssam
6633105197Ssam	/* for old-fashioned code - should be nuked */
6634105197Ssam	if (m->m_pkthdr.len > MCLBYTES) {
6635105197Ssam		m_freem(m);
6636105197Ssam		return ENOBUFS;
6637105197Ssam	}
6638105197Ssam	if (m->m_next) {
6639105197Ssam		struct mbuf *n;
6640105197Ssam
6641111119Simp		MGETHDR(n, M_DONTWAIT, MT_DATA);
6642105197Ssam		if (n && m->m_pkthdr.len > MHLEN) {
6643111119Simp			MCLGET(n, M_DONTWAIT);
6644105197Ssam			if ((n->m_flags & M_EXT) == 0) {
6645105197Ssam				m_free(n);
6646105197Ssam				n = NULL;
6647105197Ssam			}
6648105197Ssam		}
6649105197Ssam		if (!n) {
6650105197Ssam			m_freem(m);
6651105197Ssam			return ENOBUFS;
6652105197Ssam		}
6653105197Ssam		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6654105197Ssam		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6655105197Ssam		n->m_next = NULL;
6656105197Ssam		m_freem(m);
6657105197Ssam		m = n;
6658105197Ssam	}
6659105197Ssam
6660105197Ssam	/* align the mbuf chain so that extensions are in contiguous region. */
6661105197Ssam	error = key_align(m, &mh);
6662105197Ssam	if (error)
6663105197Ssam		return error;
6664105197Ssam
6665105197Ssam	if (m->m_next) {	/*XXX*/
6666105197Ssam		m_freem(m);
6667105197Ssam		return ENOBUFS;
6668105197Ssam	}
6669105197Ssam
6670105197Ssam	msg = mh.msg;
6671105197Ssam
6672105197Ssam	/* check SA type */
6673105197Ssam	switch (msg->sadb_msg_satype) {
6674105197Ssam	case SADB_SATYPE_UNSPEC:
6675105197Ssam		switch (msg->sadb_msg_type) {
6676105197Ssam		case SADB_GETSPI:
6677105197Ssam		case SADB_UPDATE:
6678105197Ssam		case SADB_ADD:
6679105197Ssam		case SADB_DELETE:
6680105197Ssam		case SADB_GET:
6681105197Ssam		case SADB_ACQUIRE:
6682105197Ssam		case SADB_EXPIRE:
6683120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify satype "
6684120585Ssam			    "when msg type=%u.\n", __func__,
6685120585Ssam			    msg->sadb_msg_type));
6686105197Ssam			pfkeystat.out_invsatype++;
6687105197Ssam			error = EINVAL;
6688105197Ssam			goto senderror;
6689105197Ssam		}
6690105197Ssam		break;
6691105197Ssam	case SADB_SATYPE_AH:
6692105197Ssam	case SADB_SATYPE_ESP:
6693105197Ssam	case SADB_X_SATYPE_IPCOMP:
6694125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
6695105197Ssam		switch (msg->sadb_msg_type) {
6696105197Ssam		case SADB_X_SPDADD:
6697105197Ssam		case SADB_X_SPDDELETE:
6698105197Ssam		case SADB_X_SPDGET:
6699105197Ssam		case SADB_X_SPDDUMP:
6700105197Ssam		case SADB_X_SPDFLUSH:
6701105197Ssam		case SADB_X_SPDSETIDX:
6702105197Ssam		case SADB_X_SPDUPDATE:
6703105197Ssam		case SADB_X_SPDDELETE2:
6704120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
6705120585Ssam				__func__, msg->sadb_msg_type));
6706105197Ssam			pfkeystat.out_invsatype++;
6707105197Ssam			error = EINVAL;
6708105197Ssam			goto senderror;
6709105197Ssam		}
6710105197Ssam		break;
6711105197Ssam	case SADB_SATYPE_RSVP:
6712105197Ssam	case SADB_SATYPE_OSPFV2:
6713105197Ssam	case SADB_SATYPE_RIPV2:
6714105197Ssam	case SADB_SATYPE_MIP:
6715120585Ssam		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
6716120585Ssam			__func__, msg->sadb_msg_satype));
6717105197Ssam		pfkeystat.out_invsatype++;
6718105197Ssam		error = EOPNOTSUPP;
6719105197Ssam		goto senderror;
6720105197Ssam	case 1:	/* XXX: What does it do? */
6721105197Ssam		if (msg->sadb_msg_type == SADB_X_PROMISC)
6722105197Ssam			break;
6723105197Ssam		/*FALLTHROUGH*/
6724105197Ssam	default:
6725120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6726120585Ssam			__func__, msg->sadb_msg_satype));
6727105197Ssam		pfkeystat.out_invsatype++;
6728105197Ssam		error = EINVAL;
6729105197Ssam		goto senderror;
6730105197Ssam	}
6731105197Ssam
6732105197Ssam	/* check field of upper layer protocol and address family */
6733105197Ssam	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6734105197Ssam	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6735105197Ssam		struct sadb_address *src0, *dst0;
6736105197Ssam		u_int plen;
6737105197Ssam
6738105197Ssam		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6739105197Ssam		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6740105197Ssam
6741105197Ssam		/* check upper layer protocol */
6742105197Ssam		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6743120585Ssam			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
6744120585Ssam				"mismatched.\n", __func__));
6745105197Ssam			pfkeystat.out_invaddr++;
6746105197Ssam			error = EINVAL;
6747105197Ssam			goto senderror;
6748105197Ssam		}
6749105197Ssam
6750105197Ssam		/* check family */
6751105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6752105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
6753120585Ssam			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
6754120585Ssam				__func__));
6755105197Ssam			pfkeystat.out_invaddr++;
6756105197Ssam			error = EINVAL;
6757105197Ssam			goto senderror;
6758105197Ssam		}
6759105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6760105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
6761120585Ssam			ipseclog((LOG_DEBUG, "%s: address struct size "
6762120585Ssam				"mismatched.\n", __func__));
6763105197Ssam			pfkeystat.out_invaddr++;
6764105197Ssam			error = EINVAL;
6765105197Ssam			goto senderror;
6766105197Ssam		}
6767105197Ssam
6768105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6769105197Ssam		case AF_INET:
6770105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6771105197Ssam			    sizeof(struct sockaddr_in)) {
6772105197Ssam				pfkeystat.out_invaddr++;
6773105197Ssam				error = EINVAL;
6774105197Ssam				goto senderror;
6775105197Ssam			}
6776105197Ssam			break;
6777105197Ssam		case AF_INET6:
6778105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6779105197Ssam			    sizeof(struct sockaddr_in6)) {
6780105197Ssam				pfkeystat.out_invaddr++;
6781105197Ssam				error = EINVAL;
6782105197Ssam				goto senderror;
6783105197Ssam			}
6784105197Ssam			break;
6785105197Ssam		default:
6786120585Ssam			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
6787120585Ssam				__func__));
6788105197Ssam			pfkeystat.out_invaddr++;
6789105197Ssam			error = EAFNOSUPPORT;
6790105197Ssam			goto senderror;
6791105197Ssam		}
6792105197Ssam
6793105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6794105197Ssam		case AF_INET:
6795105197Ssam			plen = sizeof(struct in_addr) << 3;
6796105197Ssam			break;
6797105197Ssam		case AF_INET6:
6798105197Ssam			plen = sizeof(struct in6_addr) << 3;
6799105197Ssam			break;
6800105197Ssam		default:
6801105197Ssam			plen = 0;	/*fool gcc*/
6802105197Ssam			break;
6803105197Ssam		}
6804105197Ssam
6805105197Ssam		/* check max prefix length */
6806105197Ssam		if (src0->sadb_address_prefixlen > plen ||
6807105197Ssam		    dst0->sadb_address_prefixlen > plen) {
6808120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
6809120585Ssam				__func__));
6810105197Ssam			pfkeystat.out_invaddr++;
6811105197Ssam			error = EINVAL;
6812105197Ssam			goto senderror;
6813105197Ssam		}
6814105197Ssam
6815105197Ssam		/*
6816105197Ssam		 * prefixlen == 0 is valid because there can be a case when
6817105197Ssam		 * all addresses are matched.
6818105197Ssam		 */
6819105197Ssam	}
6820105197Ssam
6821105197Ssam	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
6822105197Ssam	    key_typesw[msg->sadb_msg_type] == NULL) {
6823105197Ssam		pfkeystat.out_invmsgtype++;
6824105197Ssam		error = EINVAL;
6825105197Ssam		goto senderror;
6826105197Ssam	}
6827105197Ssam
6828105197Ssam	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6829105197Ssam
6830105197Ssamsenderror:
6831105197Ssam	msg->sadb_msg_errno = error;
6832105197Ssam	return key_sendup_mbuf(so, m, target);
6833105197Ssam}
6834105197Ssam
6835105197Ssamstatic int
6836105197Ssamkey_senderror(so, m, code)
6837105197Ssam	struct socket *so;
6838105197Ssam	struct mbuf *m;
6839105197Ssam	int code;
6840105197Ssam{
6841105197Ssam	struct sadb_msg *msg;
6842105197Ssam
6843120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6844120585Ssam		("mbuf too small, len %u", m->m_len));
6845105197Ssam
6846105197Ssam	msg = mtod(m, struct sadb_msg *);
6847105197Ssam	msg->sadb_msg_errno = code;
6848105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
6849105197Ssam}
6850105197Ssam
6851105197Ssam/*
6852105197Ssam * set the pointer to each header into message buffer.
6853105197Ssam * m will be freed on error.
6854105197Ssam * XXX larger-than-MCLBYTES extension?
6855105197Ssam */
6856105197Ssamstatic int
6857105197Ssamkey_align(m, mhp)
6858105197Ssam	struct mbuf *m;
6859105197Ssam	struct sadb_msghdr *mhp;
6860105197Ssam{
6861105197Ssam	struct mbuf *n;
6862105197Ssam	struct sadb_ext *ext;
6863105197Ssam	size_t off, end;
6864105197Ssam	int extlen;
6865105197Ssam	int toff;
6866105197Ssam
6867120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6868120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6869120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6870120585Ssam		("mbuf too small, len %u", m->m_len));
6871105197Ssam
6872105197Ssam	/* initialize */
6873105197Ssam	bzero(mhp, sizeof(*mhp));
6874105197Ssam
6875105197Ssam	mhp->msg = mtod(m, struct sadb_msg *);
6876105197Ssam	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
6877105197Ssam
6878105197Ssam	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6879105197Ssam	extlen = end;	/*just in case extlen is not updated*/
6880105197Ssam	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
6881105197Ssam		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
6882105197Ssam		if (!n) {
6883105197Ssam			/* m is already freed */
6884105197Ssam			return ENOBUFS;
6885105197Ssam		}
6886105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6887105197Ssam
6888105197Ssam		/* set pointer */
6889105197Ssam		switch (ext->sadb_ext_type) {
6890105197Ssam		case SADB_EXT_SA:
6891105197Ssam		case SADB_EXT_ADDRESS_SRC:
6892105197Ssam		case SADB_EXT_ADDRESS_DST:
6893105197Ssam		case SADB_EXT_ADDRESS_PROXY:
6894105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
6895105197Ssam		case SADB_EXT_LIFETIME_HARD:
6896105197Ssam		case SADB_EXT_LIFETIME_SOFT:
6897105197Ssam		case SADB_EXT_KEY_AUTH:
6898105197Ssam		case SADB_EXT_KEY_ENCRYPT:
6899105197Ssam		case SADB_EXT_IDENTITY_SRC:
6900105197Ssam		case SADB_EXT_IDENTITY_DST:
6901105197Ssam		case SADB_EXT_SENSITIVITY:
6902105197Ssam		case SADB_EXT_PROPOSAL:
6903105197Ssam		case SADB_EXT_SUPPORTED_AUTH:
6904105197Ssam		case SADB_EXT_SUPPORTED_ENCRYPT:
6905105197Ssam		case SADB_EXT_SPIRANGE:
6906105197Ssam		case SADB_X_EXT_POLICY:
6907105197Ssam		case SADB_X_EXT_SA2:
6908105197Ssam			/* duplicate check */
6909105197Ssam			/*
6910105197Ssam			 * XXX Are there duplication payloads of either
6911105197Ssam			 * KEY_AUTH or KEY_ENCRYPT ?
6912105197Ssam			 */
6913105197Ssam			if (mhp->ext[ext->sadb_ext_type] != NULL) {
6914120585Ssam				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
6915120585Ssam					"%u\n", __func__, ext->sadb_ext_type));
6916105197Ssam				m_freem(m);
6917105197Ssam				pfkeystat.out_dupext++;
6918105197Ssam				return EINVAL;
6919105197Ssam			}
6920105197Ssam			break;
6921105197Ssam		default:
6922120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
6923120585Ssam				__func__, ext->sadb_ext_type));
6924105197Ssam			m_freem(m);
6925105197Ssam			pfkeystat.out_invexttype++;
6926105197Ssam			return EINVAL;
6927105197Ssam		}
6928105197Ssam
6929105197Ssam		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
6930105197Ssam
6931105197Ssam		if (key_validate_ext(ext, extlen)) {
6932105197Ssam			m_freem(m);
6933105197Ssam			pfkeystat.out_invlen++;
6934105197Ssam			return EINVAL;
6935105197Ssam		}
6936105197Ssam
6937105197Ssam		n = m_pulldown(m, off, extlen, &toff);
6938105197Ssam		if (!n) {
6939105197Ssam			/* m is already freed */
6940105197Ssam			return ENOBUFS;
6941105197Ssam		}
6942105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6943105197Ssam
6944105197Ssam		mhp->ext[ext->sadb_ext_type] = ext;
6945105197Ssam		mhp->extoff[ext->sadb_ext_type] = off;
6946105197Ssam		mhp->extlen[ext->sadb_ext_type] = extlen;
6947105197Ssam	}
6948105197Ssam
6949105197Ssam	if (off != end) {
6950105197Ssam		m_freem(m);
6951105197Ssam		pfkeystat.out_invlen++;
6952105197Ssam		return EINVAL;
6953105197Ssam	}
6954105197Ssam
6955105197Ssam	return 0;
6956105197Ssam}
6957105197Ssam
6958105197Ssamstatic int
6959105197Ssamkey_validate_ext(ext, len)
6960105197Ssam	const struct sadb_ext *ext;
6961105197Ssam	int len;
6962105197Ssam{
6963105197Ssam	const struct sockaddr *sa;
6964105197Ssam	enum { NONE, ADDR } checktype = NONE;
6965105197Ssam	int baselen = 0;
6966105197Ssam	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
6967105197Ssam
6968105197Ssam	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
6969105197Ssam		return EINVAL;
6970105197Ssam
6971105197Ssam	/* if it does not match minimum/maximum length, bail */
6972105197Ssam	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
6973105197Ssam	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
6974105197Ssam		return EINVAL;
6975105197Ssam	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
6976105197Ssam		return EINVAL;
6977105197Ssam	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
6978105197Ssam		return EINVAL;
6979105197Ssam
6980105197Ssam	/* more checks based on sadb_ext_type XXX need more */
6981105197Ssam	switch (ext->sadb_ext_type) {
6982105197Ssam	case SADB_EXT_ADDRESS_SRC:
6983105197Ssam	case SADB_EXT_ADDRESS_DST:
6984105197Ssam	case SADB_EXT_ADDRESS_PROXY:
6985105197Ssam		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
6986105197Ssam		checktype = ADDR;
6987105197Ssam		break;
6988105197Ssam	case SADB_EXT_IDENTITY_SRC:
6989105197Ssam	case SADB_EXT_IDENTITY_DST:
6990105197Ssam		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
6991105197Ssam		    SADB_X_IDENTTYPE_ADDR) {
6992105197Ssam			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
6993105197Ssam			checktype = ADDR;
6994105197Ssam		} else
6995105197Ssam			checktype = NONE;
6996105197Ssam		break;
6997105197Ssam	default:
6998105197Ssam		checktype = NONE;
6999105197Ssam		break;
7000105197Ssam	}
7001105197Ssam
7002105197Ssam	switch (checktype) {
7003105197Ssam	case NONE:
7004105197Ssam		break;
7005105197Ssam	case ADDR:
7006105197Ssam		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7007105197Ssam		if (len < baselen + sal)
7008105197Ssam			return EINVAL;
7009105197Ssam		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7010105197Ssam			return EINVAL;
7011105197Ssam		break;
7012105197Ssam	}
7013105197Ssam
7014105197Ssam	return 0;
7015105197Ssam}
7016105197Ssam
7017105197Ssamvoid
7018105197Ssamkey_init()
7019105197Ssam{
7020105197Ssam	int i;
7021105197Ssam
7022120585Ssam	SPTREE_LOCK_INIT();
7023120585Ssam	REGTREE_LOCK_INIT();
7024120585Ssam	SAHTREE_LOCK_INIT();
7025120585Ssam	ACQ_LOCK_INIT();
7026120585Ssam	SPACQ_LOCK_INIT();
7027119643Ssam
7028119643Ssam	for (i = 0; i < IPSEC_DIR_MAX; i++)
7029105197Ssam		LIST_INIT(&sptree[i]);
7030105197Ssam
7031105197Ssam	LIST_INIT(&sahtree);
7032105197Ssam
7033119643Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7034105197Ssam		LIST_INIT(&regtree[i]);
7035105197Ssam
7036105197Ssam	LIST_INIT(&acqtree);
7037105197Ssam	LIST_INIT(&spacqtree);
7038105197Ssam
7039105197Ssam	/* system default */
7040105197Ssam	ip4_def_policy.policy = IPSEC_POLICY_NONE;
7041105197Ssam	ip4_def_policy.refcnt++;	/*never reclaim this*/
7042105197Ssam
7043105197Ssam#ifndef IPSEC_DEBUG2
7044105197Ssam	timeout((void *)key_timehandler, (void *)0, hz);
7045105197Ssam#endif /*IPSEC_DEBUG2*/
7046105197Ssam
7047105197Ssam	/* initialize key statistics */
7048105197Ssam	keystat.getspi_count = 1;
7049105197Ssam
7050120585Ssam	printf("Fast IPsec: Initialized Security Association Processing.\n");
7051105197Ssam
7052105197Ssam	return;
7053105197Ssam}
7054105197Ssam
7055105197Ssam/*
7056105197Ssam * XXX: maybe This function is called after INBOUND IPsec processing.
7057105197Ssam *
7058105197Ssam * Special check for tunnel-mode packets.
7059105197Ssam * We must make some checks for consistency between inner and outer IP header.
7060105197Ssam *
7061105197Ssam * xxx more checks to be provided
7062105197Ssam */
7063105197Ssamint
7064105197Ssamkey_checktunnelsanity(sav, family, src, dst)
7065105197Ssam	struct secasvar *sav;
7066105197Ssam	u_int family;
7067105197Ssam	caddr_t src;
7068105197Ssam	caddr_t dst;
7069105197Ssam{
7070120585Ssam	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7071105197Ssam
7072105197Ssam	/* XXX: check inner IP header */
7073105197Ssam
7074105197Ssam	return 1;
7075105197Ssam}
7076105197Ssam
7077105197Ssam/* record data transfer on SA, and update timestamps */
7078105197Ssamvoid
7079105197Ssamkey_sa_recordxfer(sav, m)
7080105197Ssam	struct secasvar *sav;
7081105197Ssam	struct mbuf *m;
7082105197Ssam{
7083120585Ssam	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7084120585Ssam	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7085105197Ssam	if (!sav->lft_c)
7086105197Ssam		return;
7087105197Ssam
7088105197Ssam	/*
7089105197Ssam	 * XXX Currently, there is a difference of bytes size
7090105197Ssam	 * between inbound and outbound processing.
7091105197Ssam	 */
7092105197Ssam	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
7093105197Ssam	/* to check bytes lifetime is done in key_timehandler(). */
7094105197Ssam
7095105197Ssam	/*
7096105197Ssam	 * We use the number of packets as the unit of
7097105197Ssam	 * sadb_lifetime_allocations.  We increment the variable
7098105197Ssam	 * whenever {esp,ah}_{in,out}put is called.
7099105197Ssam	 */
7100105197Ssam	sav->lft_c->sadb_lifetime_allocations++;
7101105197Ssam	/* XXX check for expires? */
7102105197Ssam
7103105197Ssam	/*
7104105197Ssam	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
7105105197Ssam	 * in seconds.  HARD and SOFT lifetime are measured by the time
7106105197Ssam	 * difference (again in seconds) from sadb_lifetime_usetime.
7107105197Ssam	 *
7108105197Ssam	 *	usetime
7109105197Ssam	 *	v     expire   expire
7110105197Ssam	 * -----+-----+--------+---> t
7111105197Ssam	 *	<--------------> HARD
7112105197Ssam	 *	<-----> SOFT
7113105197Ssam	 */
7114105197Ssam	sav->lft_c->sadb_lifetime_usetime = time_second;
7115105197Ssam	/* XXX check for expires? */
7116105197Ssam
7117105197Ssam	return;
7118105197Ssam}
7119105197Ssam
7120105197Ssam/* dumb version */
7121105197Ssamvoid
7122105197Ssamkey_sa_routechange(dst)
7123105197Ssam	struct sockaddr *dst;
7124105197Ssam{
7125105197Ssam	struct secashead *sah;
7126105197Ssam	struct route *ro;
7127105197Ssam
7128120585Ssam	SAHTREE_LOCK();
7129105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
7130105197Ssam		ro = &sah->sa_route;
7131105197Ssam		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7132105197Ssam		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7133105197Ssam			RTFREE(ro->ro_rt);
7134105197Ssam			ro->ro_rt = (struct rtentry *)NULL;
7135105197Ssam		}
7136105197Ssam	}
7137120585Ssam	SAHTREE_UNLOCK();
7138105197Ssam}
7139105197Ssam
7140105197Ssamstatic void
7141105197Ssamkey_sa_chgstate(sav, state)
7142105197Ssam	struct secasvar *sav;
7143105197Ssam	u_int8_t state;
7144105197Ssam{
7145120585Ssam	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7146120585Ssam	SAHTREE_LOCK_ASSERT();
7147105197Ssam
7148119643Ssam	if (sav->state != state) {
7149119643Ssam		if (__LIST_CHAINED(sav))
7150119643Ssam			LIST_REMOVE(sav, chain);
7151119643Ssam		sav->state = state;
7152119643Ssam		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7153119643Ssam	}
7154105197Ssam}
7155105197Ssam
7156105197Ssamvoid
7157105197Ssamkey_sa_stir_iv(sav)
7158105197Ssam	struct secasvar *sav;
7159105197Ssam{
7160105197Ssam
7161120585Ssam	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7162105197Ssam	key_randomfill(sav->iv, sav->ivlen);
7163105197Ssam}
7164105197Ssam
7165105197Ssam/* XXX too much? */
7166105197Ssamstatic struct mbuf *
7167105197Ssamkey_alloc_mbuf(l)
7168105197Ssam	int l;
7169105197Ssam{
7170105197Ssam	struct mbuf *m = NULL, *n;
7171105197Ssam	int len, t;
7172105197Ssam
7173105197Ssam	len = l;
7174105197Ssam	while (len > 0) {
7175111119Simp		MGET(n, M_DONTWAIT, MT_DATA);
7176105197Ssam		if (n && len > MLEN)
7177111119Simp			MCLGET(n, M_DONTWAIT);
7178105197Ssam		if (!n) {
7179105197Ssam			m_freem(m);
7180105197Ssam			return NULL;
7181105197Ssam		}
7182105197Ssam
7183105197Ssam		n->m_next = NULL;
7184105197Ssam		n->m_len = 0;
7185105197Ssam		n->m_len = M_TRAILINGSPACE(n);
7186105197Ssam		/* use the bottom of mbuf, hoping we can prepend afterwards */
7187105197Ssam		if (n->m_len > len) {
7188105197Ssam			t = (n->m_len - len) & ~(sizeof(long) - 1);
7189105197Ssam			n->m_data += t;
7190105197Ssam			n->m_len = len;
7191105197Ssam		}
7192105197Ssam
7193105197Ssam		len -= n->m_len;
7194105197Ssam
7195105197Ssam		if (m)
7196105197Ssam			m_cat(m, n);
7197105197Ssam		else
7198105197Ssam			m = n;
7199105197Ssam	}
7200105197Ssam
7201105197Ssam	return m;
7202105197Ssam}
7203