key.c revision 128856
1105197Ssam/*	$FreeBSD: head/sys/netipsec/key.c 128856 2004-05-03 03:29:21Z sam $	*/
2105197Ssam/*	$KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $	*/
3105197Ssam
4105197Ssam/*
5105197Ssam * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6105197Ssam * All rights reserved.
7105197Ssam *
8105197Ssam * Redistribution and use in source and binary forms, with or without
9105197Ssam * modification, are permitted provided that the following conditions
10105197Ssam * are met:
11105197Ssam * 1. Redistributions of source code must retain the above copyright
12105197Ssam *    notice, this list of conditions and the following disclaimer.
13105197Ssam * 2. Redistributions in binary form must reproduce the above copyright
14105197Ssam *    notice, this list of conditions and the following disclaimer in the
15105197Ssam *    documentation and/or other materials provided with the distribution.
16105197Ssam * 3. Neither the name of the project nor the names of its contributors
17105197Ssam *    may be used to endorse or promote products derived from this software
18105197Ssam *    without specific prior written permission.
19105197Ssam *
20105197Ssam * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21105197Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22105197Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23105197Ssam * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24105197Ssam * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25105197Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26105197Ssam * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27105197Ssam * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28105197Ssam * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29105197Ssam * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30105197Ssam * SUCH DAMAGE.
31105197Ssam */
32105197Ssam
33105197Ssam/*
34105197Ssam * This code is referd to RFC 2367
35105197Ssam */
36105197Ssam
37105197Ssam#include "opt_inet.h"
38105197Ssam#include "opt_inet6.h"
39105197Ssam#include "opt_ipsec.h"
40105197Ssam
41105197Ssam#include <sys/types.h>
42105197Ssam#include <sys/param.h>
43105197Ssam#include <sys/systm.h>
44105197Ssam#include <sys/kernel.h>
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 */
176128856Ssamstatic const u_int saorder_state_valid_prefer_old[] = {
177105197Ssam	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
178105197Ssam};
179128856Ssamstatic const u_int saorder_state_valid_prefer_new[] = {
180128856Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
181128856Ssam};
182105197Ssamstatic u_int saorder_state_alive[] = {
183105197Ssam	/* except DEAD */
184105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
185105197Ssam};
186105197Ssamstatic u_int saorder_state_any[] = {
187105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
188105197Ssam	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
189105197Ssam};
190105197Ssam
191105197Ssamstatic const int minsize[] = {
192105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
193105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
194105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
195105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
196105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
197105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
198105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
199105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
200105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
201105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
202105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
203105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
204105197Ssam	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
205105197Ssam	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
206105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
207105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
208105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
209105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
210105197Ssam	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
211105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
212105197Ssam};
213105197Ssamstatic const int maxsize[] = {
214105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
215105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
216105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
217105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
218105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
219105197Ssam	0,				/* SADB_EXT_ADDRESS_SRC */
220105197Ssam	0,				/* SADB_EXT_ADDRESS_DST */
221105197Ssam	0,				/* SADB_EXT_ADDRESS_PROXY */
222105197Ssam	0,				/* SADB_EXT_KEY_AUTH */
223105197Ssam	0,				/* SADB_EXT_KEY_ENCRYPT */
224105197Ssam	0,				/* SADB_EXT_IDENTITY_SRC */
225105197Ssam	0,				/* SADB_EXT_IDENTITY_DST */
226105197Ssam	0,				/* SADB_EXT_SENSITIVITY */
227105197Ssam	0,				/* SADB_EXT_PROPOSAL */
228105197Ssam	0,				/* SADB_EXT_SUPPORTED_AUTH */
229105197Ssam	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
230105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
231105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
232105197Ssam	0,				/* SADB_X_EXT_POLICY */
233105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
234105197Ssam};
235105197Ssam
236105197Ssamstatic int ipsec_esp_keymin = 256;
237105197Ssamstatic int ipsec_esp_auth = 0;
238105197Ssamstatic int ipsec_ah_keymin = 128;
239105197Ssam
240105197Ssam#ifdef SYSCTL_DECL
241105197SsamSYSCTL_DECL(_net_key);
242105197Ssam#endif
243105197Ssam
244105197SsamSYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,	CTLFLAG_RW, \
245105197Ssam	&key_debug_level,	0,	"");
246105197Ssam
247105197Ssam/* max count of trial for the decision of spi value */
248105197SsamSYSCTL_INT(_net_key, KEYCTL_SPI_TRY,		spi_trycnt,	CTLFLAG_RW, \
249105197Ssam	&key_spi_trycnt,	0,	"");
250105197Ssam
251105197Ssam/* minimum spi value to allocate automatically. */
252105197SsamSYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,	spi_minval,	CTLFLAG_RW, \
253105197Ssam	&key_spi_minval,	0,	"");
254105197Ssam
255105197Ssam/* maximun spi value to allocate automatically. */
256105197SsamSYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,	spi_maxval,	CTLFLAG_RW, \
257105197Ssam	&key_spi_maxval,	0,	"");
258105197Ssam
259105197Ssam/* interval to initialize randseed */
260105197SsamSYSCTL_INT(_net_key, KEYCTL_RANDOM_INT,	int_random,	CTLFLAG_RW, \
261105197Ssam	&key_int_random,	0,	"");
262105197Ssam
263105197Ssam/* lifetime for larval SA */
264105197SsamSYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,	larval_lifetime, CTLFLAG_RW, \
265105197Ssam	&key_larval_lifetime,	0,	"");
266105197Ssam
267105197Ssam/* counter for blocking to send SADB_ACQUIRE to IKEd */
268105197SsamSYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,	blockacq_count,	CTLFLAG_RW, \
269105197Ssam	&key_blockacq_count,	0,	"");
270105197Ssam
271105197Ssam/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
272105197SsamSYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,	blockacq_lifetime, CTLFLAG_RW, \
273105197Ssam	&key_blockacq_lifetime,	0,	"");
274105197Ssam
275105197Ssam/* ESP auth */
276105197SsamSYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth, CTLFLAG_RW, \
277105197Ssam	&ipsec_esp_auth,	0,	"");
278105197Ssam
279105197Ssam/* minimum ESP key length */
280105197SsamSYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN,	esp_keymin, CTLFLAG_RW, \
281105197Ssam	&ipsec_esp_keymin,	0,	"");
282105197Ssam
283105197Ssam/* minimum AH key length */
284105197SsamSYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin, CTLFLAG_RW, \
285105197Ssam	&ipsec_ah_keymin,	0,	"");
286105197Ssam
287105197Ssam/* perfered old SA rather than new SA */
288125876SguidoSYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,	preferred_oldsa, CTLFLAG_RW,\
289125876Sguido	&key_preferred_oldsa,	0,	"");
290105197Ssam
291105197Ssam#define __LIST_CHAINED(elm) \
292105197Ssam	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
293105197Ssam#define LIST_INSERT_TAIL(head, elm, type, field) \
294105197Ssamdo {\
295105197Ssam	struct type *curelm = LIST_FIRST(head); \
296105197Ssam	if (curelm == NULL) {\
297105197Ssam		LIST_INSERT_HEAD(head, elm, field); \
298105197Ssam	} else { \
299105197Ssam		while (LIST_NEXT(curelm, field)) \
300105197Ssam			curelm = LIST_NEXT(curelm, field);\
301105197Ssam		LIST_INSERT_AFTER(curelm, elm, field);\
302105197Ssam	}\
303105197Ssam} while (0)
304105197Ssam
305105197Ssam#define KEY_CHKSASTATE(head, sav, name) \
306105197Ssamdo { \
307105197Ssam	if ((head) != (sav)) {						\
308105197Ssam		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
309105197Ssam			(name), (head), (sav)));			\
310105197Ssam		continue;						\
311105197Ssam	}								\
312105197Ssam} while (0)
313105197Ssam
314105197Ssam#define KEY_CHKSPDIR(head, sp, name) \
315105197Ssamdo { \
316105197Ssam	if ((head) != (sp)) {						\
317105197Ssam		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
318105197Ssam			"anyway continue.\n",				\
319105197Ssam			(name), (head), (sp)));				\
320105197Ssam	}								\
321105197Ssam} while (0)
322105197Ssam
323119643SsamMALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
324119643SsamMALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
325119643SsamMALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
326119643SsamMALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
327119643SsamMALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
328119643SsamMALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
329119643SsamMALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
330105197Ssam
331105197Ssam/*
332105197Ssam * set parameters into secpolicyindex buffer.
333105197Ssam * Must allocate secpolicyindex buffer passed to this function.
334105197Ssam */
335105197Ssam#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
336105197Ssamdo { \
337105197Ssam	bzero((idx), sizeof(struct secpolicyindex));                         \
338105197Ssam	(idx)->dir = (_dir);                                                 \
339105197Ssam	(idx)->prefs = (ps);                                                 \
340105197Ssam	(idx)->prefd = (pd);                                                 \
341105197Ssam	(idx)->ul_proto = (ulp);                                             \
342105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
343105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
344105197Ssam} while (0)
345105197Ssam
346105197Ssam/*
347105197Ssam * set parameters into secasindex buffer.
348105197Ssam * Must allocate secasindex buffer before calling this function.
349105197Ssam */
350105197Ssam#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
351105197Ssamdo { \
352105197Ssam	bzero((idx), sizeof(struct secasindex));                             \
353105197Ssam	(idx)->proto = (p);                                                  \
354105197Ssam	(idx)->mode = (m);                                                   \
355105197Ssam	(idx)->reqid = (r);                                                  \
356105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
357105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
358105197Ssam} while (0)
359105197Ssam
360105197Ssam/* key statistics */
361105197Ssamstruct _keystat {
362105197Ssam	u_long getspi_count; /* the avarage of count to try to get new SPI */
363105197Ssam} keystat;
364105197Ssam
365105197Ssamstruct sadb_msghdr {
366105197Ssam	struct sadb_msg *msg;
367105197Ssam	struct sadb_ext *ext[SADB_EXT_MAX + 1];
368105197Ssam	int extoff[SADB_EXT_MAX + 1];
369105197Ssam	int extlen[SADB_EXT_MAX + 1];
370105197Ssam};
371105197Ssam
372105197Ssamstatic struct secasvar *key_allocsa_policy __P((const struct secasindex *));
373105197Ssamstatic void key_freesp_so __P((struct secpolicy **));
374105197Ssamstatic struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
375105197Ssamstatic void key_delsp __P((struct secpolicy *));
376105197Ssamstatic struct secpolicy *key_getsp __P((struct secpolicyindex *));
377119643Ssamstatic void _key_delsp(struct secpolicy *sp);
378105197Ssamstatic struct secpolicy *key_getspbyid __P((u_int32_t));
379105197Ssamstatic u_int32_t key_newreqid __P((void));
380105197Ssamstatic struct mbuf *key_gather_mbuf __P((struct mbuf *,
381105197Ssam	const struct sadb_msghdr *, int, int, ...));
382105197Ssamstatic int key_spdadd __P((struct socket *, struct mbuf *,
383105197Ssam	const struct sadb_msghdr *));
384105197Ssamstatic u_int32_t key_getnewspid __P((void));
385105197Ssamstatic int key_spddelete __P((struct socket *, struct mbuf *,
386105197Ssam	const struct sadb_msghdr *));
387105197Ssamstatic int key_spddelete2 __P((struct socket *, struct mbuf *,
388105197Ssam	const struct sadb_msghdr *));
389105197Ssamstatic int key_spdget __P((struct socket *, struct mbuf *,
390105197Ssam	const struct sadb_msghdr *));
391105197Ssamstatic int key_spdflush __P((struct socket *, struct mbuf *,
392105197Ssam	const struct sadb_msghdr *));
393105197Ssamstatic int key_spddump __P((struct socket *, struct mbuf *,
394105197Ssam	const struct sadb_msghdr *));
395105197Ssamstatic struct mbuf *key_setdumpsp __P((struct secpolicy *,
396105197Ssam	u_int8_t, u_int32_t, u_int32_t));
397105197Ssamstatic u_int key_getspreqmsglen __P((struct secpolicy *));
398105197Ssamstatic int key_spdexpire __P((struct secpolicy *));
399105197Ssamstatic struct secashead *key_newsah __P((struct secasindex *));
400105197Ssamstatic void key_delsah __P((struct secashead *));
401105197Ssamstatic struct secasvar *key_newsav __P((struct mbuf *,
402105197Ssam	const struct sadb_msghdr *, struct secashead *, int *,
403105197Ssam	const char*, int));
404105197Ssam#define	KEY_NEWSAV(m, sadb, sah, e)				\
405105197Ssam	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
406105197Ssamstatic void key_delsav __P((struct secasvar *));
407105197Ssamstatic struct secashead *key_getsah __P((struct secasindex *));
408105197Ssamstatic struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
409105197Ssamstatic struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
410105197Ssamstatic int key_setsaval __P((struct secasvar *, struct mbuf *,
411105197Ssam	const struct sadb_msghdr *));
412105197Ssamstatic int key_mature __P((struct secasvar *));
413105197Ssamstatic struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
414105197Ssam	u_int8_t, u_int32_t, u_int32_t));
415105197Ssamstatic struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
416105197Ssam	u_int32_t, pid_t, u_int16_t));
417105197Ssamstatic struct mbuf *key_setsadbsa __P((struct secasvar *));
418105197Ssamstatic struct mbuf *key_setsadbaddr __P((u_int16_t,
419105197Ssam	const struct sockaddr *, u_int8_t, u_int16_t));
420105197Ssamstatic struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
421105197Ssamstatic struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
422105197Ssam	u_int32_t));
423119643Ssamstatic void *key_dup(const void *, u_int, struct malloc_type *);
424105197Ssam#ifdef INET6
425105197Ssamstatic int key_ismyaddr6 __P((struct sockaddr_in6 *));
426105197Ssam#endif
427105197Ssam
428105197Ssam/* flags for key_cmpsaidx() */
429105197Ssam#define CMP_HEAD	1	/* protocol, addresses. */
430105197Ssam#define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
431105197Ssam#define CMP_REQID	3	/* additionally HEAD, reaid. */
432105197Ssam#define CMP_EXACTLY	4	/* all elements. */
433105197Ssamstatic int key_cmpsaidx
434105197Ssam	__P((const struct secasindex *, const struct secasindex *, int));
435105197Ssam
436105197Ssamstatic int key_cmpspidx_exactly
437105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
438105197Ssamstatic int key_cmpspidx_withmask
439105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
440105197Ssamstatic int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
441105197Ssamstatic int key_bbcmp __P((const void *, const void *, u_int));
442105197Ssamstatic u_int16_t key_satype2proto __P((u_int8_t));
443105197Ssamstatic u_int8_t key_proto2satype __P((u_int16_t));
444105197Ssam
445105197Ssamstatic int key_getspi __P((struct socket *, struct mbuf *,
446105197Ssam	const struct sadb_msghdr *));
447105197Ssamstatic u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
448105197Ssam					struct secasindex *));
449105197Ssamstatic int key_update __P((struct socket *, struct mbuf *,
450105197Ssam	const struct sadb_msghdr *));
451105197Ssam#ifdef IPSEC_DOSEQCHECK
452105197Ssamstatic struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
453105197Ssam#endif
454105197Ssamstatic int key_add __P((struct socket *, struct mbuf *,
455105197Ssam	const struct sadb_msghdr *));
456105197Ssamstatic int key_setident __P((struct secashead *, struct mbuf *,
457105197Ssam	const struct sadb_msghdr *));
458105197Ssamstatic struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
459105197Ssam	const struct sadb_msghdr *));
460105197Ssamstatic int key_delete __P((struct socket *, struct mbuf *,
461105197Ssam	const struct sadb_msghdr *));
462105197Ssamstatic int key_get __P((struct socket *, struct mbuf *,
463105197Ssam	const struct sadb_msghdr *));
464105197Ssam
465105197Ssamstatic void key_getcomb_setlifetime __P((struct sadb_comb *));
466105197Ssamstatic struct mbuf *key_getcomb_esp __P((void));
467105197Ssamstatic struct mbuf *key_getcomb_ah __P((void));
468105197Ssamstatic struct mbuf *key_getcomb_ipcomp __P((void));
469105197Ssamstatic struct mbuf *key_getprop __P((const struct secasindex *));
470105197Ssam
471105197Ssamstatic int key_acquire __P((const struct secasindex *, struct secpolicy *));
472105197Ssamstatic struct secacq *key_newacq __P((const struct secasindex *));
473105197Ssamstatic struct secacq *key_getacq __P((const struct secasindex *));
474105197Ssamstatic struct secacq *key_getacqbyseq __P((u_int32_t));
475105197Ssamstatic struct secspacq *key_newspacq __P((struct secpolicyindex *));
476105197Ssamstatic struct secspacq *key_getspacq __P((struct secpolicyindex *));
477105197Ssamstatic int key_acquire2 __P((struct socket *, struct mbuf *,
478105197Ssam	const struct sadb_msghdr *));
479105197Ssamstatic int key_register __P((struct socket *, struct mbuf *,
480105197Ssam	const struct sadb_msghdr *));
481105197Ssamstatic int key_expire __P((struct secasvar *));
482105197Ssamstatic int key_flush __P((struct socket *, struct mbuf *,
483105197Ssam	const struct sadb_msghdr *));
484105197Ssamstatic int key_dump __P((struct socket *, struct mbuf *,
485105197Ssam	const struct sadb_msghdr *));
486105197Ssamstatic int key_promisc __P((struct socket *, struct mbuf *,
487105197Ssam	const struct sadb_msghdr *));
488105197Ssamstatic int key_senderror __P((struct socket *, struct mbuf *, int));
489105197Ssamstatic int key_validate_ext __P((const struct sadb_ext *, int));
490105197Ssamstatic int key_align __P((struct mbuf *, struct sadb_msghdr *));
491105197Ssam#if 0
492105197Ssamstatic const char *key_getfqdn __P((void));
493105197Ssamstatic const char *key_getuserfqdn __P((void));
494105197Ssam#endif
495105197Ssamstatic void key_sa_chgstate __P((struct secasvar *, u_int8_t));
496105197Ssamstatic struct mbuf *key_alloc_mbuf __P((int));
497105197Ssam
498105197Ssam#define	SA_ADDREF(p) do {						\
499105197Ssam	(p)->refcnt++;							\
500120585Ssam	IPSEC_ASSERT((p)->refcnt != 0, ("SA refcnt overflow"));		\
501105197Ssam} while (0)
502105197Ssam#define	SA_DELREF(p) do {						\
503120585Ssam	IPSEC_ASSERT((p)->refcnt > 0, ("SA refcnt underflow"));		\
504105197Ssam	(p)->refcnt--;							\
505105197Ssam} while (0)
506105197Ssam
507105197Ssam#define	SP_ADDREF(p) do {						\
508105197Ssam	(p)->refcnt++;							\
509120585Ssam	IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));		\
510105197Ssam} while (0)
511105197Ssam#define	SP_DELREF(p) do {						\
512120585Ssam	IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));		\
513105197Ssam	(p)->refcnt--;							\
514105197Ssam} while (0)
515105197Ssam
516105197Ssam/*
517105197Ssam * Return 0 when there are known to be no SP's for the specified
518105197Ssam * direction.  Otherwise return 1.  This is used by IPsec code
519105197Ssam * to optimize performance.
520105197Ssam */
521105197Ssamint
522105197Ssamkey_havesp(u_int dir)
523105197Ssam{
524105197Ssam	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
525105197Ssam		LIST_FIRST(&sptree[dir]) != NULL : 1);
526105197Ssam}
527105197Ssam
528105197Ssam/* %%% IPsec policy management */
529105197Ssam/*
530105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
531105197Ssam * Must call key_freesp() later.
532105197Ssam * OUT:	NULL:	not found
533105197Ssam *	others:	found and return the pointer.
534105197Ssam */
535105197Ssamstruct secpolicy *
536105197Ssamkey_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
537105197Ssam{
538105197Ssam	struct secpolicy *sp;
539105197Ssam
540120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
541120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
542120585Ssam		("invalid direction %u", dir));
543105197Ssam
544105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
545120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
546105197Ssam
547105197Ssam	/* get a SP entry */
548105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
549105197Ssam		printf("*** objects\n");
550105197Ssam		kdebug_secpolicyindex(spidx));
551105197Ssam
552120585Ssam	SPTREE_LOCK();
553105197Ssam	LIST_FOREACH(sp, &sptree[dir], chain) {
554105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
555105197Ssam			printf("*** in SPD\n");
556105197Ssam			kdebug_secpolicyindex(&sp->spidx));
557105197Ssam
558105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
559105197Ssam			continue;
560105197Ssam		if (key_cmpspidx_withmask(&sp->spidx, spidx))
561105197Ssam			goto found;
562105197Ssam	}
563105197Ssam	sp = NULL;
564105197Ssamfound:
565105197Ssam	if (sp) {
566105197Ssam		/* sanity check */
567120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
568105197Ssam
569105197Ssam		/* found a SPD entry */
570105197Ssam		sp->lastused = time_second;
571105197Ssam		SP_ADDREF(sp);
572105197Ssam	}
573120585Ssam	SPTREE_UNLOCK();
574105197Ssam
575105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
576120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
577105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
578105197Ssam	return sp;
579105197Ssam}
580105197Ssam
581105197Ssam/*
582105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
583105197Ssam * Must call key_freesp() later.
584105197Ssam * OUT:	NULL:	not found
585105197Ssam *	others:	found and return the pointer.
586105197Ssam */
587105197Ssamstruct secpolicy *
588105197Ssamkey_allocsp2(u_int32_t spi,
589105197Ssam	     union sockaddr_union *dst,
590105197Ssam	     u_int8_t proto,
591105197Ssam	     u_int dir,
592105197Ssam	     const char* where, int tag)
593105197Ssam{
594105197Ssam	struct secpolicy *sp;
595105197Ssam
596120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst"));
597120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
598120585Ssam		("invalid direction %u", dir));
599105197Ssam
600105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
601120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
602105197Ssam
603105197Ssam	/* get a SP entry */
604105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
605105197Ssam		printf("*** objects\n");
606105197Ssam		printf("spi %u proto %u dir %u\n", spi, proto, dir);
607105197Ssam		kdebug_sockaddr(&dst->sa));
608105197Ssam
609120585Ssam	SPTREE_LOCK();
610105197Ssam	LIST_FOREACH(sp, &sptree[dir], chain) {
611105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
612105197Ssam			printf("*** in SPD\n");
613105197Ssam			kdebug_secpolicyindex(&sp->spidx));
614105197Ssam
615105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
616105197Ssam			continue;
617105197Ssam		/* compare simple values, then dst address */
618105197Ssam		if (sp->spidx.ul_proto != proto)
619105197Ssam			continue;
620105197Ssam		/* NB: spi's must exist and match */
621105197Ssam		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
622105197Ssam			continue;
623105197Ssam		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
624105197Ssam			goto found;
625105197Ssam	}
626105197Ssam	sp = NULL;
627105197Ssamfound:
628105197Ssam	if (sp) {
629105197Ssam		/* sanity check */
630120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
631105197Ssam
632105197Ssam		/* found a SPD entry */
633105197Ssam		sp->lastused = time_second;
634105197Ssam		SP_ADDREF(sp);
635105197Ssam	}
636120585Ssam	SPTREE_UNLOCK();
637105197Ssam
638105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
639120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
640105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
641105197Ssam	return sp;
642105197Ssam}
643105197Ssam
644105197Ssam/*
645105197Ssam * return a policy that matches this particular inbound packet.
646105197Ssam * XXX slow
647105197Ssam */
648105197Ssamstruct secpolicy *
649105197Ssamkey_gettunnel(const struct sockaddr *osrc,
650105197Ssam	      const struct sockaddr *odst,
651105197Ssam	      const struct sockaddr *isrc,
652105197Ssam	      const struct sockaddr *idst,
653105197Ssam	      const char* where, int tag)
654105197Ssam{
655105197Ssam	struct secpolicy *sp;
656105197Ssam	const int dir = IPSEC_DIR_INBOUND;
657105197Ssam	struct ipsecrequest *r1, *r2, *p;
658105197Ssam	struct secpolicyindex spidx;
659105197Ssam
660105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
661120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
662105197Ssam
663105197Ssam	if (isrc->sa_family != idst->sa_family) {
664120585Ssam		ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
665120585Ssam			__func__, isrc->sa_family, idst->sa_family));
666105197Ssam		sp = NULL;
667105197Ssam		goto done;
668105197Ssam	}
669105197Ssam
670120585Ssam	SPTREE_LOCK();
671105197Ssam	LIST_FOREACH(sp, &sptree[dir], chain) {
672105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
673105197Ssam			continue;
674105197Ssam
675105197Ssam		r1 = r2 = NULL;
676105197Ssam		for (p = sp->req; p; p = p->next) {
677105197Ssam			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
678105197Ssam				continue;
679105197Ssam
680105197Ssam			r1 = r2;
681105197Ssam			r2 = p;
682105197Ssam
683105197Ssam			if (!r1) {
684105197Ssam				/* here we look at address matches only */
685105197Ssam				spidx = sp->spidx;
686105197Ssam				if (isrc->sa_len > sizeof(spidx.src) ||
687105197Ssam				    idst->sa_len > sizeof(spidx.dst))
688105197Ssam					continue;
689105197Ssam				bcopy(isrc, &spidx.src, isrc->sa_len);
690105197Ssam				bcopy(idst, &spidx.dst, idst->sa_len);
691105197Ssam				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
692105197Ssam					continue;
693105197Ssam			} else {
694105197Ssam				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
695105197Ssam				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
696105197Ssam					continue;
697105197Ssam			}
698105197Ssam
699105197Ssam			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
700105197Ssam			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
701105197Ssam				continue;
702105197Ssam
703105197Ssam			goto found;
704105197Ssam		}
705105197Ssam	}
706105197Ssam	sp = NULL;
707105197Ssamfound:
708105197Ssam	if (sp) {
709105197Ssam		sp->lastused = time_second;
710105197Ssam		SP_ADDREF(sp);
711105197Ssam	}
712120585Ssam	SPTREE_UNLOCK();
713105197Ssamdone:
714105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
715120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
716105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
717105197Ssam	return sp;
718105197Ssam}
719105197Ssam
720105197Ssam/*
721105197Ssam * allocating an SA entry for an *OUTBOUND* packet.
722105197Ssam * checking each request entries in SP, and acquire an SA if need.
723105197Ssam * OUT:	0: there are valid requests.
724105197Ssam *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
725105197Ssam */
726105197Ssamint
727105197Ssamkey_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
728105197Ssam{
729105197Ssam	u_int level;
730105197Ssam	int error;
731105197Ssam
732120585Ssam	IPSEC_ASSERT(isr != NULL, ("null isr"));
733120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
734120585Ssam	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
735105197Ssam		saidx->mode == IPSEC_MODE_TUNNEL,
736120585Ssam		("unexpected policy %u", saidx->mode));
737105197Ssam
738105197Ssam	/*
739105197Ssam	 * XXX guard against protocol callbacks from the crypto
740105197Ssam	 * thread as they reference ipsecrequest.sav which we
741105197Ssam	 * temporarily null out below.  Need to rethink how we
742105197Ssam	 * handle bundled SA's in the callback thread.
743105197Ssam	 */
744120585Ssam	IPSECREQUEST_LOCK_ASSERT(isr);
745119643Ssam
746119643Ssam	/* get current level */
747119643Ssam	level = ipsec_get_reqlevel(isr);
748105197Ssam#if 0
749105197Ssam	/*
750105197Ssam	 * We do allocate new SA only if the state of SA in the holder is
751105197Ssam	 * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
752105197Ssam	 */
753105197Ssam	if (isr->sav != NULL) {
754105197Ssam		if (isr->sav->sah == NULL)
755120585Ssam			panic("%s: sah is null.\n", __func__);
756105197Ssam		if (isr->sav == (struct secasvar *)LIST_FIRST(
757105197Ssam			    &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
758105197Ssam			KEY_FREESAV(&isr->sav);
759105197Ssam			isr->sav = NULL;
760105197Ssam		}
761105197Ssam	}
762105197Ssam#else
763105197Ssam	/*
764105197Ssam	 * we free any SA stashed in the IPsec request because a different
765105197Ssam	 * SA may be involved each time this request is checked, either
766105197Ssam	 * because new SAs are being configured, or this request is
767105197Ssam	 * associated with an unconnected datagram socket, or this request
768105197Ssam	 * is associated with a system default policy.
769105197Ssam	 *
770105197Ssam	 * The operation may have negative impact to performance.  We may
771105197Ssam	 * want to check cached SA carefully, rather than picking new SA
772105197Ssam	 * every time.
773105197Ssam	 */
774105197Ssam	if (isr->sav != NULL) {
775105197Ssam		KEY_FREESAV(&isr->sav);
776105197Ssam		isr->sav = NULL;
777105197Ssam	}
778105197Ssam#endif
779105197Ssam
780105197Ssam	/*
781105197Ssam	 * new SA allocation if no SA found.
782105197Ssam	 * key_allocsa_policy should allocate the oldest SA available.
783105197Ssam	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
784105197Ssam	 */
785105197Ssam	if (isr->sav == NULL)
786105197Ssam		isr->sav = key_allocsa_policy(saidx);
787105197Ssam
788105197Ssam	/* When there is SA. */
789105197Ssam	if (isr->sav != NULL) {
790105197Ssam		if (isr->sav->state != SADB_SASTATE_MATURE &&
791105197Ssam		    isr->sav->state != SADB_SASTATE_DYING)
792105197Ssam			return EINVAL;
793105197Ssam		return 0;
794105197Ssam	}
795105197Ssam
796105197Ssam	/* there is no SA */
797105197Ssam	error = key_acquire(saidx, isr->sp);
798105197Ssam	if (error != 0) {
799105197Ssam		/* XXX What should I do ? */
800120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
801120585Ssam			__func__, error));
802105197Ssam		return error;
803105197Ssam	}
804105197Ssam
805105197Ssam	if (level != IPSEC_LEVEL_REQUIRE) {
806105197Ssam		/* XXX sigh, the interface to this routine is botched */
807120585Ssam		IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
808105197Ssam		return 0;
809105197Ssam	} else {
810105197Ssam		return ENOENT;
811105197Ssam	}
812105197Ssam}
813105197Ssam
814105197Ssam/*
815105197Ssam * allocating a SA for policy entry from SAD.
816105197Ssam * NOTE: searching SAD of aliving state.
817105197Ssam * OUT:	NULL:	not found.
818105197Ssam *	others:	found and return the pointer.
819105197Ssam */
820105197Ssamstatic struct secasvar *
821105197Ssamkey_allocsa_policy(const struct secasindex *saidx)
822105197Ssam{
823128856Ssam#define	N(a)	_ARRAYLEN(a)
824105197Ssam	struct secashead *sah;
825105197Ssam	struct secasvar *sav;
826128856Ssam	u_int stateidx, arraysize;
827128856Ssam	const u_int *state_valid;
828105197Ssam
829120585Ssam	SAHTREE_LOCK();
830105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
831105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
832105197Ssam			continue;
833119643Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
834128856Ssam			if (key_preferred_oldsa) {
835128856Ssam				state_valid = saorder_state_valid_prefer_old;
836128856Ssam				arraysize = N(saorder_state_valid_prefer_old);
837128856Ssam			} else {
838128856Ssam				state_valid = saorder_state_valid_prefer_new;
839128856Ssam				arraysize = N(saorder_state_valid_prefer_new);
840128856Ssam			}
841120585Ssam			SAHTREE_UNLOCK();
842105197Ssam			goto found;
843119643Ssam		}
844105197Ssam	}
845120585Ssam	SAHTREE_UNLOCK();
846105197Ssam
847105197Ssam	return NULL;
848105197Ssam
849105197Ssam    found:
850105197Ssam	/* search valid state */
851128856Ssam	for (stateidx = 0; stateidx < arraysize; stateidx++) {
852128856Ssam		sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
853105197Ssam		if (sav != NULL)
854105197Ssam			return sav;
855105197Ssam	}
856105197Ssam
857105197Ssam	return NULL;
858128856Ssam#undef N
859105197Ssam}
860105197Ssam
861105197Ssam/*
862105197Ssam * searching SAD with direction, protocol, mode and state.
863105197Ssam * called by key_allocsa_policy().
864105197Ssam * OUT:
865105197Ssam *	NULL	: not found
866105197Ssam *	others	: found, pointer to a SA.
867105197Ssam */
868105197Ssamstatic struct secasvar *
869105197Ssamkey_do_allocsa_policy(struct secashead *sah, u_int state)
870105197Ssam{
871105197Ssam	struct secasvar *sav, *nextsav, *candidate, *d;
872105197Ssam
873105197Ssam	/* initilize */
874105197Ssam	candidate = NULL;
875105197Ssam
876120585Ssam	SAHTREE_LOCK();
877105197Ssam	for (sav = LIST_FIRST(&sah->savtree[state]);
878105197Ssam	     sav != NULL;
879105197Ssam	     sav = nextsav) {
880105197Ssam
881105197Ssam		nextsav = LIST_NEXT(sav, chain);
882105197Ssam
883105197Ssam		/* sanity check */
884120585Ssam		KEY_CHKSASTATE(sav->state, state, __func__);
885105197Ssam
886105197Ssam		/* initialize */
887105197Ssam		if (candidate == NULL) {
888105197Ssam			candidate = sav;
889105197Ssam			continue;
890105197Ssam		}
891105197Ssam
892105197Ssam		/* Which SA is the better ? */
893105197Ssam
894120585Ssam		IPSEC_ASSERT(candidate->lft_c != NULL,
895120585Ssam			("null candidate lifetime"));
896120585Ssam		IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
897105197Ssam
898105197Ssam		/* What the best method is to compare ? */
899125876Sguido		if (key_preferred_oldsa) {
900105197Ssam			if (candidate->lft_c->sadb_lifetime_addtime >
901105197Ssam					sav->lft_c->sadb_lifetime_addtime) {
902105197Ssam				candidate = sav;
903105197Ssam			}
904105197Ssam			continue;
905105197Ssam			/*NOTREACHED*/
906105197Ssam		}
907105197Ssam
908125876Sguido		/* preferred new sa rather than old sa */
909105197Ssam		if (candidate->lft_c->sadb_lifetime_addtime <
910105197Ssam				sav->lft_c->sadb_lifetime_addtime) {
911105197Ssam			d = candidate;
912105197Ssam			candidate = sav;
913105197Ssam		} else
914105197Ssam			d = sav;
915105197Ssam
916105197Ssam		/*
917105197Ssam		 * prepared to delete the SA when there is more
918105197Ssam		 * suitable candidate and the lifetime of the SA is not
919105197Ssam		 * permanent.
920105197Ssam		 */
921105197Ssam		if (d->lft_c->sadb_lifetime_addtime != 0) {
922105197Ssam			struct mbuf *m, *result;
923125508Ssam			u_int8_t satype;
924105197Ssam
925105197Ssam			key_sa_chgstate(d, SADB_SASTATE_DEAD);
926105197Ssam
927120585Ssam			IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
928125508Ssam
929125508Ssam			satype = key_proto2satype(d->sah->saidx.proto);
930125508Ssam			if (satype == 0)
931125508Ssam				goto msgfail;
932125508Ssam
933105197Ssam			m = key_setsadbmsg(SADB_DELETE, 0,
934125508Ssam			    satype, 0, 0, d->refcnt - 1);
935105197Ssam			if (!m)
936105197Ssam				goto msgfail;
937105197Ssam			result = m;
938105197Ssam
939105197Ssam			/* set sadb_address for saidx's. */
940105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
941105197Ssam				&d->sah->saidx.src.sa,
942105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
943105197Ssam				IPSEC_ULPROTO_ANY);
944105197Ssam			if (!m)
945105197Ssam				goto msgfail;
946105197Ssam			m_cat(result, m);
947105197Ssam
948105197Ssam			/* set sadb_address for saidx's. */
949105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
950105197Ssam				&d->sah->saidx.src.sa,
951105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
952105197Ssam				IPSEC_ULPROTO_ANY);
953105197Ssam			if (!m)
954105197Ssam				goto msgfail;
955105197Ssam			m_cat(result, m);
956105197Ssam
957105197Ssam			/* create SA extension */
958105197Ssam			m = key_setsadbsa(d);
959105197Ssam			if (!m)
960105197Ssam				goto msgfail;
961105197Ssam			m_cat(result, m);
962105197Ssam
963105197Ssam			if (result->m_len < sizeof(struct sadb_msg)) {
964105197Ssam				result = m_pullup(result,
965105197Ssam						sizeof(struct sadb_msg));
966105197Ssam				if (result == NULL)
967105197Ssam					goto msgfail;
968105197Ssam			}
969105197Ssam
970105197Ssam			result->m_pkthdr.len = 0;
971105197Ssam			for (m = result; m; m = m->m_next)
972105197Ssam				result->m_pkthdr.len += m->m_len;
973105197Ssam			mtod(result, struct sadb_msg *)->sadb_msg_len =
974105197Ssam				PFKEY_UNIT64(result->m_pkthdr.len);
975105197Ssam
976105197Ssam			if (key_sendup_mbuf(NULL, result,
977105197Ssam					KEY_SENDUP_REGISTERED))
978105197Ssam				goto msgfail;
979105197Ssam		 msgfail:
980105197Ssam			KEY_FREESAV(&d);
981105197Ssam		}
982105197Ssam	}
983105197Ssam	if (candidate) {
984105197Ssam		SA_ADDREF(candidate);
985105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
986120585Ssam			printf("DP %s cause refcnt++:%d SA:%p\n",
987120585Ssam				__func__, candidate->refcnt, candidate));
988105197Ssam	}
989120585Ssam	SAHTREE_UNLOCK();
990119643Ssam
991105197Ssam	return candidate;
992105197Ssam}
993105197Ssam
994105197Ssam/*
995105197Ssam * allocating a usable SA entry for a *INBOUND* packet.
996105197Ssam * Must call key_freesav() later.
997105197Ssam * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
998105197Ssam *	NULL:		not found, or error occured.
999105197Ssam *
1000105197Ssam * In the comparison, no source address is used--for RFC2401 conformance.
1001105197Ssam * To quote, from section 4.1:
1002105197Ssam *	A security association is uniquely identified by a triple consisting
1003105197Ssam *	of a Security Parameter Index (SPI), an IP Destination Address, and a
1004105197Ssam *	security protocol (AH or ESP) identifier.
1005105197Ssam * Note that, however, we do need to keep source address in IPsec SA.
1006105197Ssam * IKE specification and PF_KEY specification do assume that we
1007105197Ssam * keep source address in IPsec SA.  We see a tricky situation here.
1008105197Ssam */
1009105197Ssamstruct secasvar *
1010105197Ssamkey_allocsa(
1011105197Ssam	union sockaddr_union *dst,
1012105197Ssam	u_int proto,
1013105197Ssam	u_int32_t spi,
1014105197Ssam	const char* where, int tag)
1015105197Ssam{
1016105197Ssam	struct secashead *sah;
1017105197Ssam	struct secasvar *sav;
1018128856Ssam	u_int stateidx, arraysize, state;
1019128856Ssam	const u_int *saorder_state_valid;
1020105197Ssam
1021120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst address"));
1022105197Ssam
1023105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1024120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
1025105197Ssam
1026105197Ssam	/*
1027105197Ssam	 * searching SAD.
1028105197Ssam	 * XXX: to be checked internal IP header somewhere.  Also when
1029105197Ssam	 * IPsec tunnel packet is received.  But ESP tunnel mode is
1030105197Ssam	 * encrypted so we can't check internal IP header.
1031105197Ssam	 */
1032120585Ssam	SAHTREE_LOCK();
1033128856Ssam	if (key_preferred_oldsa) {
1034128856Ssam		saorder_state_valid = saorder_state_valid_prefer_old;
1035128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1036128856Ssam	} else {
1037128856Ssam		saorder_state_valid = saorder_state_valid_prefer_new;
1038128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1039128856Ssam	}
1040105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
1041105197Ssam		/* search valid state */
1042128856Ssam		for (stateidx = 0; stateidx < arraysize; stateidx++) {
1043105197Ssam			state = saorder_state_valid[stateidx];
1044105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
1045105197Ssam				/* sanity check */
1046120585Ssam				KEY_CHKSASTATE(sav->state, state, __func__);
1047105197Ssam				/* do not return entries w/ unusable state */
1048105197Ssam				if (sav->state != SADB_SASTATE_MATURE &&
1049105197Ssam				    sav->state != SADB_SASTATE_DYING)
1050105197Ssam					continue;
1051105197Ssam				if (proto != sav->sah->saidx.proto)
1052105197Ssam					continue;
1053105197Ssam				if (spi != sav->spi)
1054105197Ssam					continue;
1055105197Ssam#if 0	/* don't check src */
1056105197Ssam				/* check src address */
1057105197Ssam				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, 0) != 0)
1058105197Ssam					continue;
1059105197Ssam#endif
1060105197Ssam				/* check dst address */
1061105197Ssam				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, 0) != 0)
1062105197Ssam					continue;
1063105197Ssam				SA_ADDREF(sav);
1064105197Ssam				goto done;
1065105197Ssam			}
1066105197Ssam		}
1067105197Ssam	}
1068105197Ssam	sav = NULL;
1069105197Ssamdone:
1070120585Ssam	SAHTREE_UNLOCK();
1071105197Ssam
1072105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1073120585Ssam		printf("DP %s return SA:%p; refcnt %u\n", __func__,
1074105197Ssam			sav, sav ? sav->refcnt : 0));
1075105197Ssam	return sav;
1076105197Ssam}
1077105197Ssam
1078105197Ssam/*
1079105197Ssam * Must be called after calling key_allocsp().
1080105197Ssam * For both the packet without socket and key_freeso().
1081105197Ssam */
1082105197Ssamvoid
1083105197Ssam_key_freesp(struct secpolicy **spp, const char* where, int tag)
1084105197Ssam{
1085105197Ssam	struct secpolicy *sp = *spp;
1086105197Ssam
1087120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1088105197Ssam
1089120585Ssam	SPTREE_LOCK();
1090105197Ssam	SP_DELREF(sp);
1091105197Ssam
1092105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1093120585Ssam		printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1094120585Ssam			__func__, sp, sp->id, where, tag, sp->refcnt));
1095105197Ssam
1096105197Ssam	if (sp->refcnt == 0) {
1097105197Ssam		*spp = NULL;
1098105197Ssam		key_delsp(sp);
1099105197Ssam	}
1100120585Ssam	SPTREE_UNLOCK();
1101105197Ssam}
1102105197Ssam
1103105197Ssam/*
1104105197Ssam * Must be called after calling key_allocsp().
1105105197Ssam * For the packet with socket.
1106105197Ssam */
1107105197Ssamvoid
1108105197Ssamkey_freeso(struct socket *so)
1109105197Ssam{
1110120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
1111105197Ssam
1112105197Ssam	switch (so->so_proto->pr_domain->dom_family) {
1113105197Ssam#ifdef INET
1114105197Ssam	case PF_INET:
1115105197Ssam	    {
1116105197Ssam		struct inpcb *pcb = sotoinpcb(so);
1117105197Ssam
1118105197Ssam		/* Does it have a PCB ? */
1119105197Ssam		if (pcb == NULL)
1120105197Ssam			return;
1121105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1122105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1123105197Ssam	    }
1124105197Ssam		break;
1125105197Ssam#endif
1126105197Ssam#ifdef INET6
1127105197Ssam	case PF_INET6:
1128105197Ssam	    {
1129105197Ssam#ifdef HAVE_NRL_INPCB
1130105197Ssam		struct inpcb *pcb  = sotoinpcb(so);
1131105197Ssam
1132105197Ssam		/* Does it have a PCB ? */
1133105197Ssam		if (pcb == NULL)
1134105197Ssam			return;
1135105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1136105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1137105197Ssam#else
1138105197Ssam		struct in6pcb *pcb  = sotoin6pcb(so);
1139105197Ssam
1140105197Ssam		/* Does it have a PCB ? */
1141105197Ssam		if (pcb == NULL)
1142105197Ssam			return;
1143105197Ssam		key_freesp_so(&pcb->in6p_sp->sp_in);
1144105197Ssam		key_freesp_so(&pcb->in6p_sp->sp_out);
1145105197Ssam#endif
1146105197Ssam	    }
1147105197Ssam		break;
1148105197Ssam#endif /* INET6 */
1149105197Ssam	default:
1150120585Ssam		ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1151120585Ssam		    __func__, so->so_proto->pr_domain->dom_family));
1152105197Ssam		return;
1153105197Ssam	}
1154105197Ssam}
1155105197Ssam
1156105197Ssamstatic void
1157105197Ssamkey_freesp_so(struct secpolicy **sp)
1158105197Ssam{
1159120585Ssam	IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1160105197Ssam
1161105197Ssam	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1162105197Ssam	    (*sp)->policy == IPSEC_POLICY_BYPASS)
1163105197Ssam		return;
1164105197Ssam
1165120585Ssam	IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1166120585Ssam		("invalid policy %u", (*sp)->policy));
1167105197Ssam	KEY_FREESP(sp);
1168105197Ssam}
1169105197Ssam
1170105197Ssam/*
1171105197Ssam * Must be called after calling key_allocsa().
1172105197Ssam * This function is called by key_freesp() to free some SA allocated
1173105197Ssam * for a policy.
1174105197Ssam */
1175105197Ssamvoid
1176105197Ssamkey_freesav(struct secasvar **psav, const char* where, int tag)
1177105197Ssam{
1178105197Ssam	struct secasvar *sav = *psav;
1179105197Ssam
1180120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
1181105197Ssam
1182120585Ssam	/* XXX unguarded? */
1183105197Ssam	SA_DELREF(sav);
1184105197Ssam
1185105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1186120585Ssam		printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1187120585Ssam			__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1188105197Ssam
1189105197Ssam	if (sav->refcnt == 0) {
1190105197Ssam		*psav = NULL;
1191105197Ssam		key_delsav(sav);
1192105197Ssam	}
1193105197Ssam}
1194105197Ssam
1195105197Ssam/* %%% SPD management */
1196105197Ssam/*
1197105197Ssam * free security policy entry.
1198105197Ssam */
1199105197Ssamstatic void
1200105197Ssamkey_delsp(struct secpolicy *sp)
1201105197Ssam{
1202119643Ssam	struct ipsecrequest *isr, *nextisr;
1203105197Ssam
1204120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1205120585Ssam	SPTREE_LOCK_ASSERT();
1206105197Ssam
1207105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
1208105197Ssam
1209120585Ssam	IPSEC_ASSERT(sp->refcnt == 0,
1210120585Ssam		("SP with references deleted (refcnt %u)", sp->refcnt));
1211105197Ssam
1212105197Ssam	/* remove from SP index */
1213105197Ssam	if (__LIST_CHAINED(sp))
1214105197Ssam		LIST_REMOVE(sp, chain);
1215105197Ssam
1216119643Ssam	for (isr = sp->req; isr != NULL; isr = nextisr) {
1217105197Ssam		if (isr->sav != NULL) {
1218105197Ssam			KEY_FREESAV(&isr->sav);
1219105197Ssam			isr->sav = NULL;
1220105197Ssam		}
1221105197Ssam
1222105197Ssam		nextisr = isr->next;
1223119643Ssam		ipsec_delisr(isr);
1224105197Ssam	}
1225119643Ssam	_key_delsp(sp);
1226105197Ssam}
1227105197Ssam
1228105197Ssam/*
1229105197Ssam * search SPD
1230105197Ssam * OUT:	NULL	: not found
1231105197Ssam *	others	: found, pointer to a SP.
1232105197Ssam */
1233105197Ssamstatic struct secpolicy *
1234105197Ssamkey_getsp(struct secpolicyindex *spidx)
1235105197Ssam{
1236105197Ssam	struct secpolicy *sp;
1237105197Ssam
1238120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1239105197Ssam
1240120585Ssam	SPTREE_LOCK();
1241105197Ssam	LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
1242105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1243105197Ssam			continue;
1244105197Ssam		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1245105197Ssam			SP_ADDREF(sp);
1246119643Ssam			break;
1247105197Ssam		}
1248105197Ssam	}
1249120585Ssam	SPTREE_UNLOCK();
1250105197Ssam
1251119643Ssam	return sp;
1252105197Ssam}
1253105197Ssam
1254105197Ssam/*
1255105197Ssam * get SP by index.
1256105197Ssam * OUT:	NULL	: not found
1257105197Ssam *	others	: found, pointer to a SP.
1258105197Ssam */
1259105197Ssamstatic struct secpolicy *
1260105197Ssamkey_getspbyid(u_int32_t id)
1261105197Ssam{
1262105197Ssam	struct secpolicy *sp;
1263105197Ssam
1264120585Ssam	SPTREE_LOCK();
1265105197Ssam	LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
1266105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1267105197Ssam			continue;
1268105197Ssam		if (sp->id == id) {
1269105197Ssam			SP_ADDREF(sp);
1270119643Ssam			goto done;
1271105197Ssam		}
1272105197Ssam	}
1273105197Ssam
1274105197Ssam	LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
1275105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1276105197Ssam			continue;
1277105197Ssam		if (sp->id == id) {
1278105197Ssam			SP_ADDREF(sp);
1279119643Ssam			goto done;
1280105197Ssam		}
1281105197Ssam	}
1282119643Ssamdone:
1283120585Ssam	SPTREE_UNLOCK();
1284105197Ssam
1285119643Ssam	return sp;
1286105197Ssam}
1287105197Ssam
1288105197Ssamstruct secpolicy *
1289105197Ssamkey_newsp(const char* where, int tag)
1290105197Ssam{
1291105197Ssam	struct secpolicy *newsp = NULL;
1292105197Ssam
1293105197Ssam	newsp = (struct secpolicy *)
1294119643Ssam		malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1295105197Ssam	if (newsp) {
1296120585Ssam		SECPOLICY_LOCK_INIT(newsp);
1297105197Ssam		newsp->refcnt = 1;
1298105197Ssam		newsp->req = NULL;
1299105197Ssam	}
1300105197Ssam
1301105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1302120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
1303105197Ssam			where, tag, newsp));
1304105197Ssam	return newsp;
1305105197Ssam}
1306105197Ssam
1307119643Ssamstatic void
1308119643Ssam_key_delsp(struct secpolicy *sp)
1309119643Ssam{
1310120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
1311119643Ssam	free(sp, M_IPSEC_SP);
1312119643Ssam}
1313119643Ssam
1314105197Ssam/*
1315105197Ssam * create secpolicy structure from sadb_x_policy structure.
1316105197Ssam * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1317105197Ssam * so must be set properly later.
1318105197Ssam */
1319105197Ssamstruct secpolicy *
1320105197Ssamkey_msg2sp(xpl0, len, error)
1321105197Ssam	struct sadb_x_policy *xpl0;
1322105197Ssam	size_t len;
1323105197Ssam	int *error;
1324105197Ssam{
1325105197Ssam	struct secpolicy *newsp;
1326105197Ssam
1327120585Ssam	IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1328127972Spjd	IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1329120585Ssam
1330105197Ssam	if (len != PFKEY_EXTLEN(xpl0)) {
1331120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1332105197Ssam		*error = EINVAL;
1333105197Ssam		return NULL;
1334105197Ssam	}
1335105197Ssam
1336105197Ssam	if ((newsp = KEY_NEWSP()) == NULL) {
1337105197Ssam		*error = ENOBUFS;
1338105197Ssam		return NULL;
1339105197Ssam	}
1340105197Ssam
1341105197Ssam	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1342105197Ssam	newsp->policy = xpl0->sadb_x_policy_type;
1343105197Ssam
1344105197Ssam	/* check policy */
1345105197Ssam	switch (xpl0->sadb_x_policy_type) {
1346105197Ssam	case IPSEC_POLICY_DISCARD:
1347105197Ssam	case IPSEC_POLICY_NONE:
1348105197Ssam	case IPSEC_POLICY_ENTRUST:
1349105197Ssam	case IPSEC_POLICY_BYPASS:
1350105197Ssam		newsp->req = NULL;
1351105197Ssam		break;
1352105197Ssam
1353105197Ssam	case IPSEC_POLICY_IPSEC:
1354105197Ssam	    {
1355105197Ssam		int tlen;
1356105197Ssam		struct sadb_x_ipsecrequest *xisr;
1357105197Ssam		struct ipsecrequest **p_isr = &newsp->req;
1358105197Ssam
1359105197Ssam		/* validity check */
1360105197Ssam		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1361120585Ssam			ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1362120585Ssam				__func__));
1363105197Ssam			KEY_FREESP(&newsp);
1364105197Ssam			*error = EINVAL;
1365105197Ssam			return NULL;
1366105197Ssam		}
1367105197Ssam
1368105197Ssam		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1369105197Ssam		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1370105197Ssam
1371105197Ssam		while (tlen > 0) {
1372105197Ssam			/* length check */
1373105197Ssam			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1374120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1375120585Ssam					"length.\n", __func__));
1376105197Ssam				KEY_FREESP(&newsp);
1377105197Ssam				*error = EINVAL;
1378105197Ssam				return NULL;
1379105197Ssam			}
1380105197Ssam
1381105197Ssam			/* allocate request buffer */
1382119643Ssam			/* NB: data structure is zero'd */
1383119643Ssam			*p_isr = ipsec_newisr();
1384105197Ssam			if ((*p_isr) == NULL) {
1385105197Ssam				ipseclog((LOG_DEBUG,
1386120585Ssam				    "%s: No more memory.\n", __func__));
1387105197Ssam				KEY_FREESP(&newsp);
1388105197Ssam				*error = ENOBUFS;
1389105197Ssam				return NULL;
1390105197Ssam			}
1391105197Ssam
1392105197Ssam			/* set values */
1393105197Ssam			switch (xisr->sadb_x_ipsecrequest_proto) {
1394105197Ssam			case IPPROTO_ESP:
1395105197Ssam			case IPPROTO_AH:
1396105197Ssam			case IPPROTO_IPCOMP:
1397105197Ssam				break;
1398105197Ssam			default:
1399105197Ssam				ipseclog((LOG_DEBUG,
1400120585Ssam				    "%s: invalid proto type=%u\n", __func__,
1401105197Ssam				    xisr->sadb_x_ipsecrequest_proto));
1402105197Ssam				KEY_FREESP(&newsp);
1403105197Ssam				*error = EPROTONOSUPPORT;
1404105197Ssam				return NULL;
1405105197Ssam			}
1406105197Ssam			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1407105197Ssam
1408105197Ssam			switch (xisr->sadb_x_ipsecrequest_mode) {
1409105197Ssam			case IPSEC_MODE_TRANSPORT:
1410105197Ssam			case IPSEC_MODE_TUNNEL:
1411105197Ssam				break;
1412105197Ssam			case IPSEC_MODE_ANY:
1413105197Ssam			default:
1414105197Ssam				ipseclog((LOG_DEBUG,
1415120585Ssam				    "%s: invalid mode=%u\n", __func__,
1416105197Ssam				    xisr->sadb_x_ipsecrequest_mode));
1417105197Ssam				KEY_FREESP(&newsp);
1418105197Ssam				*error = EINVAL;
1419105197Ssam				return NULL;
1420105197Ssam			}
1421105197Ssam			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1422105197Ssam
1423105197Ssam			switch (xisr->sadb_x_ipsecrequest_level) {
1424105197Ssam			case IPSEC_LEVEL_DEFAULT:
1425105197Ssam			case IPSEC_LEVEL_USE:
1426105197Ssam			case IPSEC_LEVEL_REQUIRE:
1427105197Ssam				break;
1428105197Ssam			case IPSEC_LEVEL_UNIQUE:
1429105197Ssam				/* validity check */
1430105197Ssam				/*
1431105197Ssam				 * If range violation of reqid, kernel will
1432105197Ssam				 * update it, don't refuse it.
1433105197Ssam				 */
1434105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid
1435105197Ssam						> IPSEC_MANUAL_REQID_MAX) {
1436105197Ssam					ipseclog((LOG_DEBUG,
1437120585Ssam					    "%s: reqid=%d range "
1438105197Ssam					    "violation, updated by kernel.\n",
1439120585Ssam					    __func__,
1440105197Ssam					    xisr->sadb_x_ipsecrequest_reqid));
1441105197Ssam					xisr->sadb_x_ipsecrequest_reqid = 0;
1442105197Ssam				}
1443105197Ssam
1444105197Ssam				/* allocate new reqid id if reqid is zero. */
1445105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1446105197Ssam					u_int32_t reqid;
1447105197Ssam					if ((reqid = key_newreqid()) == 0) {
1448105197Ssam						KEY_FREESP(&newsp);
1449105197Ssam						*error = ENOBUFS;
1450105197Ssam						return NULL;
1451105197Ssam					}
1452105197Ssam					(*p_isr)->saidx.reqid = reqid;
1453105197Ssam					xisr->sadb_x_ipsecrequest_reqid = reqid;
1454105197Ssam				} else {
1455105197Ssam				/* set it for manual keying. */
1456105197Ssam					(*p_isr)->saidx.reqid =
1457105197Ssam						xisr->sadb_x_ipsecrequest_reqid;
1458105197Ssam				}
1459105197Ssam				break;
1460105197Ssam
1461105197Ssam			default:
1462120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1463120585Ssam					__func__,
1464105197Ssam					xisr->sadb_x_ipsecrequest_level));
1465105197Ssam				KEY_FREESP(&newsp);
1466105197Ssam				*error = EINVAL;
1467105197Ssam				return NULL;
1468105197Ssam			}
1469105197Ssam			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1470105197Ssam
1471105197Ssam			/* set IP addresses if there */
1472105197Ssam			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1473105197Ssam				struct sockaddr *paddr;
1474105197Ssam
1475105197Ssam				paddr = (struct sockaddr *)(xisr + 1);
1476105197Ssam
1477105197Ssam				/* validity check */
1478105197Ssam				if (paddr->sa_len
1479105197Ssam				    > sizeof((*p_isr)->saidx.src)) {
1480120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1481120585Ssam						"request address length.\n",
1482120585Ssam						__func__));
1483105197Ssam					KEY_FREESP(&newsp);
1484105197Ssam					*error = EINVAL;
1485105197Ssam					return NULL;
1486105197Ssam				}
1487105197Ssam				bcopy(paddr, &(*p_isr)->saidx.src,
1488105197Ssam					paddr->sa_len);
1489105197Ssam
1490105197Ssam				paddr = (struct sockaddr *)((caddr_t)paddr
1491105197Ssam							+ paddr->sa_len);
1492105197Ssam
1493105197Ssam				/* validity check */
1494105197Ssam				if (paddr->sa_len
1495105197Ssam				    > sizeof((*p_isr)->saidx.dst)) {
1496120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1497120585Ssam						"request address length.\n",
1498120585Ssam						__func__));
1499105197Ssam					KEY_FREESP(&newsp);
1500105197Ssam					*error = EINVAL;
1501105197Ssam					return NULL;
1502105197Ssam				}
1503105197Ssam				bcopy(paddr, &(*p_isr)->saidx.dst,
1504105197Ssam					paddr->sa_len);
1505105197Ssam			}
1506105197Ssam
1507105197Ssam			(*p_isr)->sp = newsp;
1508105197Ssam
1509105197Ssam			/* initialization for the next. */
1510105197Ssam			p_isr = &(*p_isr)->next;
1511105197Ssam			tlen -= xisr->sadb_x_ipsecrequest_len;
1512105197Ssam
1513105197Ssam			/* validity check */
1514105197Ssam			if (tlen < 0) {
1515120585Ssam				ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1516120585Ssam					__func__));
1517105197Ssam				KEY_FREESP(&newsp);
1518105197Ssam				*error = EINVAL;
1519105197Ssam				return NULL;
1520105197Ssam			}
1521105197Ssam
1522105197Ssam			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1523105197Ssam			                 + xisr->sadb_x_ipsecrequest_len);
1524105197Ssam		}
1525105197Ssam	    }
1526105197Ssam		break;
1527105197Ssam	default:
1528120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1529105197Ssam		KEY_FREESP(&newsp);
1530105197Ssam		*error = EINVAL;
1531105197Ssam		return NULL;
1532105197Ssam	}
1533105197Ssam
1534105197Ssam	*error = 0;
1535105197Ssam	return newsp;
1536105197Ssam}
1537105197Ssam
1538105197Ssamstatic u_int32_t
1539105197Ssamkey_newreqid()
1540105197Ssam{
1541105197Ssam	static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1542105197Ssam
1543105197Ssam	auto_reqid = (auto_reqid == ~0
1544105197Ssam			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1545105197Ssam
1546105197Ssam	/* XXX should be unique check */
1547105197Ssam
1548105197Ssam	return auto_reqid;
1549105197Ssam}
1550105197Ssam
1551105197Ssam/*
1552105197Ssam * copy secpolicy struct to sadb_x_policy structure indicated.
1553105197Ssam */
1554105197Ssamstruct mbuf *
1555105197Ssamkey_sp2msg(sp)
1556105197Ssam	struct secpolicy *sp;
1557105197Ssam{
1558105197Ssam	struct sadb_x_policy *xpl;
1559105197Ssam	int tlen;
1560105197Ssam	caddr_t p;
1561105197Ssam	struct mbuf *m;
1562105197Ssam
1563120585Ssam	IPSEC_ASSERT(sp != NULL, ("null policy"));
1564105197Ssam
1565105197Ssam	tlen = key_getspreqmsglen(sp);
1566105197Ssam
1567105197Ssam	m = key_alloc_mbuf(tlen);
1568105197Ssam	if (!m || m->m_next) {	/*XXX*/
1569105197Ssam		if (m)
1570105197Ssam			m_freem(m);
1571105197Ssam		return NULL;
1572105197Ssam	}
1573105197Ssam
1574105197Ssam	m->m_len = tlen;
1575105197Ssam	m->m_next = NULL;
1576105197Ssam	xpl = mtod(m, struct sadb_x_policy *);
1577105197Ssam	bzero(xpl, tlen);
1578105197Ssam
1579105197Ssam	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1580105197Ssam	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1581105197Ssam	xpl->sadb_x_policy_type = sp->policy;
1582105197Ssam	xpl->sadb_x_policy_dir = sp->spidx.dir;
1583105197Ssam	xpl->sadb_x_policy_id = sp->id;
1584105197Ssam	p = (caddr_t)xpl + sizeof(*xpl);
1585105197Ssam
1586105197Ssam	/* if is the policy for ipsec ? */
1587105197Ssam	if (sp->policy == IPSEC_POLICY_IPSEC) {
1588105197Ssam		struct sadb_x_ipsecrequest *xisr;
1589105197Ssam		struct ipsecrequest *isr;
1590105197Ssam
1591105197Ssam		for (isr = sp->req; isr != NULL; isr = isr->next) {
1592105197Ssam
1593105197Ssam			xisr = (struct sadb_x_ipsecrequest *)p;
1594105197Ssam
1595105197Ssam			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1596105197Ssam			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1597105197Ssam			xisr->sadb_x_ipsecrequest_level = isr->level;
1598105197Ssam			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1599105197Ssam
1600105197Ssam			p += sizeof(*xisr);
1601105197Ssam			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1602105197Ssam			p += isr->saidx.src.sa.sa_len;
1603105197Ssam			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1604105197Ssam			p += isr->saidx.src.sa.sa_len;
1605105197Ssam
1606105197Ssam			xisr->sadb_x_ipsecrequest_len =
1607105197Ssam				PFKEY_ALIGN8(sizeof(*xisr)
1608105197Ssam					+ isr->saidx.src.sa.sa_len
1609105197Ssam					+ isr->saidx.dst.sa.sa_len);
1610105197Ssam		}
1611105197Ssam	}
1612105197Ssam
1613105197Ssam	return m;
1614105197Ssam}
1615105197Ssam
1616105197Ssam/* m will not be freed nor modified */
1617105197Ssamstatic struct mbuf *
1618105197Ssam#ifdef __STDC__
1619105197Ssamkey_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1620105197Ssam	int ndeep, int nitem, ...)
1621105197Ssam#else
1622105197Ssamkey_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1623105197Ssam	struct mbuf *m;
1624105197Ssam	const struct sadb_msghdr *mhp;
1625105197Ssam	int ndeep;
1626105197Ssam	int nitem;
1627105197Ssam	va_dcl
1628105197Ssam#endif
1629105197Ssam{
1630105197Ssam	va_list ap;
1631105197Ssam	int idx;
1632105197Ssam	int i;
1633105197Ssam	struct mbuf *result = NULL, *n;
1634105197Ssam	int len;
1635105197Ssam
1636120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1637120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1638105197Ssam
1639105197Ssam	va_start(ap, nitem);
1640105197Ssam	for (i = 0; i < nitem; i++) {
1641105197Ssam		idx = va_arg(ap, int);
1642105197Ssam		if (idx < 0 || idx > SADB_EXT_MAX)
1643105197Ssam			goto fail;
1644105197Ssam		/* don't attempt to pull empty extension */
1645105197Ssam		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1646105197Ssam			continue;
1647105197Ssam		if (idx != SADB_EXT_RESERVED  &&
1648105197Ssam		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1649105197Ssam			continue;
1650105197Ssam
1651105197Ssam		if (idx == SADB_EXT_RESERVED) {
1652105197Ssam			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1653120585Ssam
1654120585Ssam			IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1655120585Ssam
1656111119Simp			MGETHDR(n, M_DONTWAIT, MT_DATA);
1657105197Ssam			if (!n)
1658105197Ssam				goto fail;
1659105197Ssam			n->m_len = len;
1660105197Ssam			n->m_next = NULL;
1661105197Ssam			m_copydata(m, 0, sizeof(struct sadb_msg),
1662105197Ssam			    mtod(n, caddr_t));
1663105197Ssam		} else if (i < ndeep) {
1664105197Ssam			len = mhp->extlen[idx];
1665105197Ssam			n = key_alloc_mbuf(len);
1666105197Ssam			if (!n || n->m_next) {	/*XXX*/
1667105197Ssam				if (n)
1668105197Ssam					m_freem(n);
1669105197Ssam				goto fail;
1670105197Ssam			}
1671105197Ssam			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1672105197Ssam			    mtod(n, caddr_t));
1673105197Ssam		} else {
1674105197Ssam			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1675111119Simp			    M_DONTWAIT);
1676105197Ssam		}
1677105197Ssam		if (n == NULL)
1678105197Ssam			goto fail;
1679105197Ssam
1680105197Ssam		if (result)
1681105197Ssam			m_cat(result, n);
1682105197Ssam		else
1683105197Ssam			result = n;
1684105197Ssam	}
1685105197Ssam	va_end(ap);
1686105197Ssam
1687105197Ssam	if ((result->m_flags & M_PKTHDR) != 0) {
1688105197Ssam		result->m_pkthdr.len = 0;
1689105197Ssam		for (n = result; n; n = n->m_next)
1690105197Ssam			result->m_pkthdr.len += n->m_len;
1691105197Ssam	}
1692105197Ssam
1693105197Ssam	return result;
1694105197Ssam
1695105197Ssamfail:
1696105197Ssam	m_freem(result);
1697105197Ssam	return NULL;
1698105197Ssam}
1699105197Ssam
1700105197Ssam/*
1701105197Ssam * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1702108533Sschweikh * add an entry to SP database, when received
1703105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1704105197Ssam * from the user(?).
1705105197Ssam * Adding to SP database,
1706105197Ssam * and send
1707105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1708105197Ssam * to the socket which was send.
1709105197Ssam *
1710105197Ssam * SPDADD set a unique policy entry.
1711105197Ssam * SPDSETIDX like SPDADD without a part of policy requests.
1712105197Ssam * SPDUPDATE replace a unique policy entry.
1713105197Ssam *
1714105197Ssam * m will always be freed.
1715105197Ssam */
1716105197Ssamstatic int
1717105197Ssamkey_spdadd(so, m, mhp)
1718105197Ssam	struct socket *so;
1719105197Ssam	struct mbuf *m;
1720105197Ssam	const struct sadb_msghdr *mhp;
1721105197Ssam{
1722105197Ssam	struct sadb_address *src0, *dst0;
1723105197Ssam	struct sadb_x_policy *xpl0, *xpl;
1724105197Ssam	struct sadb_lifetime *lft = NULL;
1725105197Ssam	struct secpolicyindex spidx;
1726105197Ssam	struct secpolicy *newsp;
1727105197Ssam	int error;
1728105197Ssam
1729120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
1730120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1731120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1732120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1733105197Ssam
1734105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1735105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1736105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1737105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1738105197Ssam		return key_senderror(so, m, EINVAL);
1739105197Ssam	}
1740105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1741105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1742105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1743120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1744120585Ssam			__func__));
1745105197Ssam		return key_senderror(so, m, EINVAL);
1746105197Ssam	}
1747105197Ssam	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1748105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1749105197Ssam			< sizeof(struct sadb_lifetime)) {
1750120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1751120585Ssam				__func__));
1752105197Ssam			return key_senderror(so, m, EINVAL);
1753105197Ssam		}
1754105197Ssam		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1755105197Ssam	}
1756105197Ssam
1757105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1758105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1759105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1760105197Ssam
1761105197Ssam	/* make secindex */
1762105197Ssam	/* XXX boundary check against sa_len */
1763105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1764105197Ssam	                src0 + 1,
1765105197Ssam	                dst0 + 1,
1766105197Ssam	                src0->sadb_address_prefixlen,
1767105197Ssam	                dst0->sadb_address_prefixlen,
1768105197Ssam	                src0->sadb_address_proto,
1769105197Ssam	                &spidx);
1770105197Ssam
1771105197Ssam	/* checking the direciton. */
1772105197Ssam	switch (xpl0->sadb_x_policy_dir) {
1773105197Ssam	case IPSEC_DIR_INBOUND:
1774105197Ssam	case IPSEC_DIR_OUTBOUND:
1775105197Ssam		break;
1776105197Ssam	default:
1777120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1778105197Ssam		mhp->msg->sadb_msg_errno = EINVAL;
1779105197Ssam		return 0;
1780105197Ssam	}
1781105197Ssam
1782105197Ssam	/* check policy */
1783105197Ssam	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1784105197Ssam	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1785105197Ssam	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1786120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1787105197Ssam		return key_senderror(so, m, EINVAL);
1788105197Ssam	}
1789105197Ssam
1790105197Ssam	/* policy requests are mandatory when action is ipsec. */
1791105197Ssam        if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1792105197Ssam	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1793105197Ssam	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1794120585Ssam		ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1795120585Ssam			__func__));
1796105197Ssam		return key_senderror(so, m, EINVAL);
1797105197Ssam	}
1798105197Ssam
1799105197Ssam	/*
1800105197Ssam	 * checking there is SP already or not.
1801105197Ssam	 * SPDUPDATE doesn't depend on whether there is a SP or not.
1802105197Ssam	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1803105197Ssam	 * then error.
1804105197Ssam	 */
1805105197Ssam	newsp = key_getsp(&spidx);
1806105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1807105197Ssam		if (newsp) {
1808105197Ssam			newsp->state = IPSEC_SPSTATE_DEAD;
1809105197Ssam			KEY_FREESP(&newsp);
1810105197Ssam		}
1811105197Ssam	} else {
1812105197Ssam		if (newsp != NULL) {
1813105197Ssam			KEY_FREESP(&newsp);
1814120585Ssam			ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1815120585Ssam				__func__));
1816105197Ssam			return key_senderror(so, m, EEXIST);
1817105197Ssam		}
1818105197Ssam	}
1819105197Ssam
1820105197Ssam	/* allocation new SP entry */
1821105197Ssam	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1822105197Ssam		return key_senderror(so, m, error);
1823105197Ssam	}
1824105197Ssam
1825105197Ssam	if ((newsp->id = key_getnewspid()) == 0) {
1826119643Ssam		_key_delsp(newsp);
1827105197Ssam		return key_senderror(so, m, ENOBUFS);
1828105197Ssam	}
1829105197Ssam
1830105197Ssam	/* XXX boundary check against sa_len */
1831105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1832105197Ssam	                src0 + 1,
1833105197Ssam	                dst0 + 1,
1834105197Ssam	                src0->sadb_address_prefixlen,
1835105197Ssam	                dst0->sadb_address_prefixlen,
1836105197Ssam	                src0->sadb_address_proto,
1837105197Ssam	                &newsp->spidx);
1838105197Ssam
1839105197Ssam	/* sanity check on addr pair */
1840105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1841105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_family) {
1842119643Ssam		_key_delsp(newsp);
1843105197Ssam		return key_senderror(so, m, EINVAL);
1844105197Ssam	}
1845105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1846105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_len) {
1847119643Ssam		_key_delsp(newsp);
1848105197Ssam		return key_senderror(so, m, EINVAL);
1849105197Ssam	}
1850105197Ssam#if 1
1851105197Ssam	if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
1852105197Ssam		struct sockaddr *sa;
1853105197Ssam		sa = (struct sockaddr *)(src0 + 1);
1854105197Ssam		if (sa->sa_family != newsp->req->saidx.src.sa.sa_family) {
1855119643Ssam			_key_delsp(newsp);
1856105197Ssam			return key_senderror(so, m, EINVAL);
1857105197Ssam		}
1858105197Ssam	}
1859105197Ssam	if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
1860105197Ssam		struct sockaddr *sa;
1861105197Ssam		sa = (struct sockaddr *)(dst0 + 1);
1862105197Ssam		if (sa->sa_family != newsp->req->saidx.dst.sa.sa_family) {
1863119643Ssam			_key_delsp(newsp);
1864105197Ssam			return key_senderror(so, m, EINVAL);
1865105197Ssam		}
1866105197Ssam	}
1867105197Ssam#endif
1868105197Ssam
1869105197Ssam	newsp->created = time_second;
1870105197Ssam	newsp->lastused = newsp->created;
1871105197Ssam	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1872105197Ssam	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1873105197Ssam
1874105197Ssam	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1875105197Ssam	newsp->state = IPSEC_SPSTATE_ALIVE;
1876105197Ssam	LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1877105197Ssam
1878105197Ssam	/* delete the entry in spacqtree */
1879105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1880119643Ssam		struct secspacq *spacq = key_getspacq(&spidx);
1881119643Ssam		if (spacq != NULL) {
1882105197Ssam			/* reset counter in order to deletion by timehandler. */
1883105197Ssam			spacq->created = time_second;
1884105197Ssam			spacq->count = 0;
1885120585Ssam			SPACQ_UNLOCK();
1886105197Ssam		}
1887105197Ssam    	}
1888105197Ssam
1889105197Ssam    {
1890105197Ssam	struct mbuf *n, *mpolicy;
1891105197Ssam	struct sadb_msg *newmsg;
1892105197Ssam	int off;
1893105197Ssam
1894105197Ssam	/* create new sadb_msg to reply. */
1895105197Ssam	if (lft) {
1896105197Ssam		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1897105197Ssam		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1898105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1899105197Ssam	} else {
1900105197Ssam		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1901105197Ssam		    SADB_X_EXT_POLICY,
1902105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1903105197Ssam	}
1904105197Ssam	if (!n)
1905105197Ssam		return key_senderror(so, m, ENOBUFS);
1906105197Ssam
1907105197Ssam	if (n->m_len < sizeof(*newmsg)) {
1908105197Ssam		n = m_pullup(n, sizeof(*newmsg));
1909105197Ssam		if (!n)
1910105197Ssam			return key_senderror(so, m, ENOBUFS);
1911105197Ssam	}
1912105197Ssam	newmsg = mtod(n, struct sadb_msg *);
1913105197Ssam	newmsg->sadb_msg_errno = 0;
1914105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1915105197Ssam
1916105197Ssam	off = 0;
1917105197Ssam	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1918105197Ssam	    sizeof(*xpl), &off);
1919105197Ssam	if (mpolicy == NULL) {
1920105197Ssam		/* n is already freed */
1921105197Ssam		return key_senderror(so, m, ENOBUFS);
1922105197Ssam	}
1923105197Ssam	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1924105197Ssam	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1925105197Ssam		m_freem(n);
1926105197Ssam		return key_senderror(so, m, EINVAL);
1927105197Ssam	}
1928105197Ssam	xpl->sadb_x_policy_id = newsp->id;
1929105197Ssam
1930105197Ssam	m_freem(m);
1931105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1932105197Ssam    }
1933105197Ssam}
1934105197Ssam
1935105197Ssam/*
1936105197Ssam * get new policy id.
1937105197Ssam * OUT:
1938105197Ssam *	0:	failure.
1939105197Ssam *	others: success.
1940105197Ssam */
1941105197Ssamstatic u_int32_t
1942105197Ssamkey_getnewspid()
1943105197Ssam{
1944105197Ssam	u_int32_t newid = 0;
1945105197Ssam	int count = key_spi_trycnt;	/* XXX */
1946105197Ssam	struct secpolicy *sp;
1947105197Ssam
1948105197Ssam	/* when requesting to allocate spi ranged */
1949105197Ssam	while (count--) {
1950105197Ssam		newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
1951105197Ssam
1952105197Ssam		if ((sp = key_getspbyid(newid)) == NULL)
1953105197Ssam			break;
1954105197Ssam
1955105197Ssam		KEY_FREESP(&sp);
1956105197Ssam	}
1957105197Ssam
1958105197Ssam	if (count == 0 || newid == 0) {
1959120585Ssam		ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
1960120585Ssam			__func__));
1961105197Ssam		return 0;
1962105197Ssam	}
1963105197Ssam
1964105197Ssam	return newid;
1965105197Ssam}
1966105197Ssam
1967105197Ssam/*
1968105197Ssam * SADB_SPDDELETE processing
1969105197Ssam * receive
1970105197Ssam *   <base, address(SD), policy(*)>
1971105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
1972105197Ssam * and send,
1973105197Ssam *   <base, address(SD), policy(*)>
1974105197Ssam * to the ikmpd.
1975105197Ssam * policy(*) including direction of policy.
1976105197Ssam *
1977105197Ssam * m will always be freed.
1978105197Ssam */
1979105197Ssamstatic int
1980105197Ssamkey_spddelete(so, m, mhp)
1981105197Ssam	struct socket *so;
1982105197Ssam	struct mbuf *m;
1983105197Ssam	const struct sadb_msghdr *mhp;
1984105197Ssam{
1985105197Ssam	struct sadb_address *src0, *dst0;
1986105197Ssam	struct sadb_x_policy *xpl0;
1987105197Ssam	struct secpolicyindex spidx;
1988105197Ssam	struct secpolicy *sp;
1989105197Ssam
1990120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
1991120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1992120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1993120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1994105197Ssam
1995105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1996105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1997105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1998120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1999120585Ssam			__func__));
2000105197Ssam		return key_senderror(so, m, EINVAL);
2001105197Ssam	}
2002105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2003105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2004105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2005120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2006120585Ssam			__func__));
2007105197Ssam		return key_senderror(so, m, EINVAL);
2008105197Ssam	}
2009105197Ssam
2010105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2011105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2012105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2013105197Ssam
2014105197Ssam	/* make secindex */
2015105197Ssam	/* XXX boundary check against sa_len */
2016105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2017105197Ssam	                src0 + 1,
2018105197Ssam	                dst0 + 1,
2019105197Ssam	                src0->sadb_address_prefixlen,
2020105197Ssam	                dst0->sadb_address_prefixlen,
2021105197Ssam	                src0->sadb_address_proto,
2022105197Ssam	                &spidx);
2023105197Ssam
2024105197Ssam	/* checking the direciton. */
2025105197Ssam	switch (xpl0->sadb_x_policy_dir) {
2026105197Ssam	case IPSEC_DIR_INBOUND:
2027105197Ssam	case IPSEC_DIR_OUTBOUND:
2028105197Ssam		break;
2029105197Ssam	default:
2030120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2031105197Ssam		return key_senderror(so, m, EINVAL);
2032105197Ssam	}
2033105197Ssam
2034105197Ssam	/* Is there SP in SPD ? */
2035105197Ssam	if ((sp = key_getsp(&spidx)) == NULL) {
2036120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2037105197Ssam		return key_senderror(so, m, EINVAL);
2038105197Ssam	}
2039105197Ssam
2040105197Ssam	/* save policy id to buffer to be returned. */
2041105197Ssam	xpl0->sadb_x_policy_id = sp->id;
2042105197Ssam
2043105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2044120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
2045105197Ssam	KEY_FREESP(&sp);
2046105197Ssam
2047105197Ssam    {
2048105197Ssam	struct mbuf *n;
2049105197Ssam	struct sadb_msg *newmsg;
2050105197Ssam
2051105197Ssam	/* create new sadb_msg to reply. */
2052105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2053105197Ssam	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2054105197Ssam	if (!n)
2055105197Ssam		return key_senderror(so, m, ENOBUFS);
2056105197Ssam
2057105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2058105197Ssam	newmsg->sadb_msg_errno = 0;
2059105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2060105197Ssam
2061105197Ssam	m_freem(m);
2062105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2063105197Ssam    }
2064105197Ssam}
2065105197Ssam
2066105197Ssam/*
2067105197Ssam * SADB_SPDDELETE2 processing
2068105197Ssam * receive
2069105197Ssam *   <base, policy(*)>
2070105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2071105197Ssam * and send,
2072105197Ssam *   <base, policy(*)>
2073105197Ssam * to the ikmpd.
2074105197Ssam * policy(*) including direction of policy.
2075105197Ssam *
2076105197Ssam * m will always be freed.
2077105197Ssam */
2078105197Ssamstatic int
2079105197Ssamkey_spddelete2(so, m, mhp)
2080105197Ssam	struct socket *so;
2081105197Ssam	struct mbuf *m;
2082105197Ssam	const struct sadb_msghdr *mhp;
2083105197Ssam{
2084105197Ssam	u_int32_t id;
2085105197Ssam	struct secpolicy *sp;
2086105197Ssam
2087120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2088120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2089120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2090120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2091105197Ssam
2092105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2093105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2094120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2095105197Ssam		key_senderror(so, m, EINVAL);
2096105197Ssam		return 0;
2097105197Ssam	}
2098105197Ssam
2099105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2100105197Ssam
2101105197Ssam	/* Is there SP in SPD ? */
2102105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2103120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2104105197Ssam		key_senderror(so, m, EINVAL);
2105105197Ssam	}
2106105197Ssam
2107105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2108120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
2109105197Ssam	KEY_FREESP(&sp);
2110105197Ssam
2111105197Ssam    {
2112105197Ssam	struct mbuf *n, *nn;
2113105197Ssam	struct sadb_msg *newmsg;
2114105197Ssam	int off, len;
2115105197Ssam
2116105197Ssam	/* create new sadb_msg to reply. */
2117105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2118105197Ssam
2119105197Ssam	if (len > MCLBYTES)
2120105197Ssam		return key_senderror(so, m, ENOBUFS);
2121111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
2122105197Ssam	if (n && len > MHLEN) {
2123111119Simp		MCLGET(n, M_DONTWAIT);
2124105197Ssam		if ((n->m_flags & M_EXT) == 0) {
2125105197Ssam			m_freem(n);
2126105197Ssam			n = NULL;
2127105197Ssam		}
2128105197Ssam	}
2129105197Ssam	if (!n)
2130105197Ssam		return key_senderror(so, m, ENOBUFS);
2131105197Ssam
2132105197Ssam	n->m_len = len;
2133105197Ssam	n->m_next = NULL;
2134105197Ssam	off = 0;
2135105197Ssam
2136105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2137105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2138105197Ssam
2139120585Ssam	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2140120585Ssam		off, len));
2141105197Ssam
2142105197Ssam	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2143111119Simp	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2144105197Ssam	if (!n->m_next) {
2145105197Ssam		m_freem(n);
2146105197Ssam		return key_senderror(so, m, ENOBUFS);
2147105197Ssam	}
2148105197Ssam
2149105197Ssam	n->m_pkthdr.len = 0;
2150105197Ssam	for (nn = n; nn; nn = nn->m_next)
2151105197Ssam		n->m_pkthdr.len += nn->m_len;
2152105197Ssam
2153105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2154105197Ssam	newmsg->sadb_msg_errno = 0;
2155105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2156105197Ssam
2157105197Ssam	m_freem(m);
2158105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2159105197Ssam    }
2160105197Ssam}
2161105197Ssam
2162105197Ssam/*
2163105197Ssam * SADB_X_GET processing
2164105197Ssam * receive
2165105197Ssam *   <base, policy(*)>
2166105197Ssam * from the user(?),
2167105197Ssam * and send,
2168105197Ssam *   <base, address(SD), policy>
2169105197Ssam * to the ikmpd.
2170105197Ssam * policy(*) including direction of policy.
2171105197Ssam *
2172105197Ssam * m will always be freed.
2173105197Ssam */
2174105197Ssamstatic int
2175105197Ssamkey_spdget(so, m, mhp)
2176105197Ssam	struct socket *so;
2177105197Ssam	struct mbuf *m;
2178105197Ssam	const struct sadb_msghdr *mhp;
2179105197Ssam{
2180105197Ssam	u_int32_t id;
2181105197Ssam	struct secpolicy *sp;
2182105197Ssam	struct mbuf *n;
2183105197Ssam
2184120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2185120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2186120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2187120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2188105197Ssam
2189105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2190105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2191120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2192120585Ssam			__func__));
2193105197Ssam		return key_senderror(so, m, EINVAL);
2194105197Ssam	}
2195105197Ssam
2196105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2197105197Ssam
2198105197Ssam	/* Is there SP in SPD ? */
2199105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2200120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2201105197Ssam		return key_senderror(so, m, ENOENT);
2202105197Ssam	}
2203105197Ssam
2204105197Ssam	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2205105197Ssam	if (n != NULL) {
2206105197Ssam		m_freem(m);
2207105197Ssam		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2208105197Ssam	} else
2209105197Ssam		return key_senderror(so, m, ENOBUFS);
2210105197Ssam}
2211105197Ssam
2212105197Ssam/*
2213105197Ssam * SADB_X_SPDACQUIRE processing.
2214105197Ssam * Acquire policy and SA(s) for a *OUTBOUND* packet.
2215105197Ssam * send
2216105197Ssam *   <base, policy(*)>
2217105197Ssam * to KMD, and expect to receive
2218105197Ssam *   <base> with SADB_X_SPDACQUIRE if error occured,
2219105197Ssam * or
2220105197Ssam *   <base, policy>
2221105197Ssam * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2222105197Ssam * policy(*) is without policy requests.
2223105197Ssam *
2224105197Ssam *    0     : succeed
2225105197Ssam *    others: error number
2226105197Ssam */
2227105197Ssamint
2228105197Ssamkey_spdacquire(sp)
2229105197Ssam	struct secpolicy *sp;
2230105197Ssam{
2231105197Ssam	struct mbuf *result = NULL, *m;
2232105197Ssam	struct secspacq *newspacq;
2233105197Ssam	int error;
2234105197Ssam
2235120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2236120585Ssam	IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2237120585Ssam	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2238120585Ssam		("policy not IPSEC %u", sp->policy));
2239105197Ssam
2240108533Sschweikh	/* Get an entry to check whether sent message or not. */
2241119643Ssam	newspacq = key_getspacq(&sp->spidx);
2242119643Ssam	if (newspacq != NULL) {
2243105197Ssam		if (key_blockacq_count < newspacq->count) {
2244105197Ssam			/* reset counter and do send message. */
2245105197Ssam			newspacq->count = 0;
2246105197Ssam		} else {
2247105197Ssam			/* increment counter and do nothing. */
2248105197Ssam			newspacq->count++;
2249105197Ssam			return 0;
2250105197Ssam		}
2251120585Ssam		SPACQ_UNLOCK();
2252105197Ssam	} else {
2253105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
2254119643Ssam		newspacq = key_newspacq(&sp->spidx);
2255119643Ssam		if (newspacq == NULL)
2256105197Ssam			return ENOBUFS;
2257105197Ssam	}
2258105197Ssam
2259105197Ssam	/* create new sadb_msg to reply. */
2260105197Ssam	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2261105197Ssam	if (!m) {
2262105197Ssam		error = ENOBUFS;
2263105197Ssam		goto fail;
2264105197Ssam	}
2265105197Ssam	result = m;
2266105197Ssam
2267105197Ssam	result->m_pkthdr.len = 0;
2268105197Ssam	for (m = result; m; m = m->m_next)
2269105197Ssam		result->m_pkthdr.len += m->m_len;
2270105197Ssam
2271105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2272105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2273105197Ssam
2274105197Ssam	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2275105197Ssam
2276105197Ssamfail:
2277105197Ssam	if (result)
2278105197Ssam		m_freem(result);
2279105197Ssam	return error;
2280105197Ssam}
2281105197Ssam
2282105197Ssam/*
2283105197Ssam * SADB_SPDFLUSH processing
2284105197Ssam * receive
2285105197Ssam *   <base>
2286105197Ssam * from the user, and free all entries in secpctree.
2287105197Ssam * and send,
2288105197Ssam *   <base>
2289105197Ssam * to the user.
2290105197Ssam * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2291105197Ssam *
2292105197Ssam * m will always be freed.
2293105197Ssam */
2294105197Ssamstatic int
2295105197Ssamkey_spdflush(so, m, mhp)
2296105197Ssam	struct socket *so;
2297105197Ssam	struct mbuf *m;
2298105197Ssam	const struct sadb_msghdr *mhp;
2299105197Ssam{
2300105197Ssam	struct sadb_msg *newmsg;
2301105197Ssam	struct secpolicy *sp;
2302105197Ssam	u_int dir;
2303105197Ssam
2304120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2305120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2306120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2307120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2308105197Ssam
2309105197Ssam	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2310105197Ssam		return key_senderror(so, m, EINVAL);
2311105197Ssam
2312105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2313120585Ssam		SPTREE_LOCK();
2314120585Ssam		LIST_FOREACH(sp, &sptree[dir], chain)
2315105197Ssam			sp->state = IPSEC_SPSTATE_DEAD;
2316120585Ssam		SPTREE_UNLOCK();
2317105197Ssam	}
2318105197Ssam
2319105197Ssam	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2320120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2321105197Ssam		return key_senderror(so, m, ENOBUFS);
2322105197Ssam	}
2323105197Ssam
2324105197Ssam	if (m->m_next)
2325105197Ssam		m_freem(m->m_next);
2326105197Ssam	m->m_next = NULL;
2327105197Ssam	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2328105197Ssam	newmsg = mtod(m, struct sadb_msg *);
2329105197Ssam	newmsg->sadb_msg_errno = 0;
2330105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2331105197Ssam
2332105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2333105197Ssam}
2334105197Ssam
2335105197Ssam/*
2336105197Ssam * SADB_SPDDUMP processing
2337105197Ssam * receive
2338105197Ssam *   <base>
2339105197Ssam * from the user, and dump all SP leaves
2340105197Ssam * and send,
2341105197Ssam *   <base> .....
2342105197Ssam * to the ikmpd.
2343105197Ssam *
2344105197Ssam * m will always be freed.
2345105197Ssam */
2346105197Ssamstatic int
2347105197Ssamkey_spddump(so, m, mhp)
2348105197Ssam	struct socket *so;
2349105197Ssam	struct mbuf *m;
2350105197Ssam	const struct sadb_msghdr *mhp;
2351105197Ssam{
2352105197Ssam	struct secpolicy *sp;
2353105197Ssam	int cnt;
2354105197Ssam	u_int dir;
2355105197Ssam	struct mbuf *n;
2356105197Ssam
2357120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2358120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2359120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2360120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2361105197Ssam
2362105197Ssam	/* search SPD entry and get buffer size. */
2363105197Ssam	cnt = 0;
2364105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2365105197Ssam		LIST_FOREACH(sp, &sptree[dir], chain) {
2366105197Ssam			cnt++;
2367105197Ssam		}
2368105197Ssam	}
2369105197Ssam
2370105197Ssam	if (cnt == 0)
2371105197Ssam		return key_senderror(so, m, ENOENT);
2372105197Ssam
2373105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2374105197Ssam		LIST_FOREACH(sp, &sptree[dir], chain) {
2375105197Ssam			--cnt;
2376105197Ssam			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2377105197Ssam			    mhp->msg->sadb_msg_pid);
2378105197Ssam
2379105197Ssam			if (n)
2380105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2381105197Ssam		}
2382105197Ssam	}
2383105197Ssam
2384105197Ssam	m_freem(m);
2385105197Ssam	return 0;
2386105197Ssam}
2387105197Ssam
2388105197Ssamstatic struct mbuf *
2389105197Ssamkey_setdumpsp(sp, type, seq, pid)
2390105197Ssam	struct secpolicy *sp;
2391105197Ssam	u_int8_t type;
2392105197Ssam	u_int32_t seq, pid;
2393105197Ssam{
2394105197Ssam	struct mbuf *result = NULL, *m;
2395105197Ssam
2396105197Ssam	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2397105197Ssam	if (!m)
2398105197Ssam		goto fail;
2399105197Ssam	result = m;
2400105197Ssam
2401105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2402105197Ssam	    &sp->spidx.src.sa, sp->spidx.prefs,
2403105197Ssam	    sp->spidx.ul_proto);
2404105197Ssam	if (!m)
2405105197Ssam		goto fail;
2406105197Ssam	m_cat(result, m);
2407105197Ssam
2408105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2409105197Ssam	    &sp->spidx.dst.sa, sp->spidx.prefd,
2410105197Ssam	    sp->spidx.ul_proto);
2411105197Ssam	if (!m)
2412105197Ssam		goto fail;
2413105197Ssam	m_cat(result, m);
2414105197Ssam
2415105197Ssam	m = key_sp2msg(sp);
2416105197Ssam	if (!m)
2417105197Ssam		goto fail;
2418105197Ssam	m_cat(result, m);
2419105197Ssam
2420105197Ssam	if ((result->m_flags & M_PKTHDR) == 0)
2421105197Ssam		goto fail;
2422105197Ssam
2423105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2424105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2425105197Ssam		if (result == NULL)
2426105197Ssam			goto fail;
2427105197Ssam	}
2428105197Ssam
2429105197Ssam	result->m_pkthdr.len = 0;
2430105197Ssam	for (m = result; m; m = m->m_next)
2431105197Ssam		result->m_pkthdr.len += m->m_len;
2432105197Ssam
2433105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2434105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2435105197Ssam
2436105197Ssam	return result;
2437105197Ssam
2438105197Ssamfail:
2439105197Ssam	m_freem(result);
2440105197Ssam	return NULL;
2441105197Ssam}
2442105197Ssam
2443105197Ssam/*
2444105197Ssam * get PFKEY message length for security policy and request.
2445105197Ssam */
2446105197Ssamstatic u_int
2447105197Ssamkey_getspreqmsglen(sp)
2448105197Ssam	struct secpolicy *sp;
2449105197Ssam{
2450105197Ssam	u_int tlen;
2451105197Ssam
2452105197Ssam	tlen = sizeof(struct sadb_x_policy);
2453105197Ssam
2454105197Ssam	/* if is the policy for ipsec ? */
2455105197Ssam	if (sp->policy != IPSEC_POLICY_IPSEC)
2456105197Ssam		return tlen;
2457105197Ssam
2458105197Ssam	/* get length of ipsec requests */
2459105197Ssam    {
2460105197Ssam	struct ipsecrequest *isr;
2461105197Ssam	int len;
2462105197Ssam
2463105197Ssam	for (isr = sp->req; isr != NULL; isr = isr->next) {
2464105197Ssam		len = sizeof(struct sadb_x_ipsecrequest)
2465105197Ssam			+ isr->saidx.src.sa.sa_len
2466105197Ssam			+ isr->saidx.dst.sa.sa_len;
2467105197Ssam
2468105197Ssam		tlen += PFKEY_ALIGN8(len);
2469105197Ssam	}
2470105197Ssam    }
2471105197Ssam
2472105197Ssam	return tlen;
2473105197Ssam}
2474105197Ssam
2475105197Ssam/*
2476105197Ssam * SADB_SPDEXPIRE processing
2477105197Ssam * send
2478105197Ssam *   <base, address(SD), lifetime(CH), policy>
2479105197Ssam * to KMD by PF_KEY.
2480105197Ssam *
2481105197Ssam * OUT:	0	: succeed
2482105197Ssam *	others	: error number
2483105197Ssam */
2484105197Ssamstatic int
2485105197Ssamkey_spdexpire(sp)
2486105197Ssam	struct secpolicy *sp;
2487105197Ssam{
2488105197Ssam	struct mbuf *result = NULL, *m;
2489105197Ssam	int len;
2490105197Ssam	int error = -1;
2491105197Ssam	struct sadb_lifetime *lt;
2492105197Ssam
2493105197Ssam	/* XXX: Why do we lock ? */
2494105197Ssam
2495120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2496105197Ssam
2497105197Ssam	/* set msg header */
2498105197Ssam	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2499105197Ssam	if (!m) {
2500105197Ssam		error = ENOBUFS;
2501105197Ssam		goto fail;
2502105197Ssam	}
2503105197Ssam	result = m;
2504105197Ssam
2505105197Ssam	/* create lifetime extension (current and hard) */
2506105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2507105197Ssam	m = key_alloc_mbuf(len);
2508105197Ssam	if (!m || m->m_next) {	/*XXX*/
2509105197Ssam		if (m)
2510105197Ssam			m_freem(m);
2511105197Ssam		error = ENOBUFS;
2512105197Ssam		goto fail;
2513105197Ssam	}
2514105197Ssam	bzero(mtod(m, caddr_t), len);
2515105197Ssam	lt = mtod(m, struct sadb_lifetime *);
2516105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2517105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2518105197Ssam	lt->sadb_lifetime_allocations = 0;
2519105197Ssam	lt->sadb_lifetime_bytes = 0;
2520105197Ssam	lt->sadb_lifetime_addtime = sp->created;
2521105197Ssam	lt->sadb_lifetime_usetime = sp->lastused;
2522105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2523105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2524105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2525105197Ssam	lt->sadb_lifetime_allocations = 0;
2526105197Ssam	lt->sadb_lifetime_bytes = 0;
2527105197Ssam	lt->sadb_lifetime_addtime = sp->lifetime;
2528105197Ssam	lt->sadb_lifetime_usetime = sp->validtime;
2529105197Ssam	m_cat(result, m);
2530105197Ssam
2531105197Ssam	/* set sadb_address for source */
2532105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2533105197Ssam	    &sp->spidx.src.sa,
2534105197Ssam	    sp->spidx.prefs, sp->spidx.ul_proto);
2535105197Ssam	if (!m) {
2536105197Ssam		error = ENOBUFS;
2537105197Ssam		goto fail;
2538105197Ssam	}
2539105197Ssam	m_cat(result, m);
2540105197Ssam
2541105197Ssam	/* set sadb_address for destination */
2542105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2543105197Ssam	    &sp->spidx.dst.sa,
2544105197Ssam	    sp->spidx.prefd, sp->spidx.ul_proto);
2545105197Ssam	if (!m) {
2546105197Ssam		error = ENOBUFS;
2547105197Ssam		goto fail;
2548105197Ssam	}
2549105197Ssam	m_cat(result, m);
2550105197Ssam
2551105197Ssam	/* set secpolicy */
2552105197Ssam	m = key_sp2msg(sp);
2553105197Ssam	if (!m) {
2554105197Ssam		error = ENOBUFS;
2555105197Ssam		goto fail;
2556105197Ssam	}
2557105197Ssam	m_cat(result, m);
2558105197Ssam
2559105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
2560105197Ssam		error = EINVAL;
2561105197Ssam		goto fail;
2562105197Ssam	}
2563105197Ssam
2564105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2565105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2566105197Ssam		if (result == NULL) {
2567105197Ssam			error = ENOBUFS;
2568105197Ssam			goto fail;
2569105197Ssam		}
2570105197Ssam	}
2571105197Ssam
2572105197Ssam	result->m_pkthdr.len = 0;
2573105197Ssam	for (m = result; m; m = m->m_next)
2574105197Ssam		result->m_pkthdr.len += m->m_len;
2575105197Ssam
2576105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2577105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2578105197Ssam
2579105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2580105197Ssam
2581105197Ssam fail:
2582105197Ssam	if (result)
2583105197Ssam		m_freem(result);
2584105197Ssam	return error;
2585105197Ssam}
2586105197Ssam
2587105197Ssam/* %%% SAD management */
2588105197Ssam/*
2589105197Ssam * allocating a memory for new SA head, and copy from the values of mhp.
2590105197Ssam * OUT:	NULL	: failure due to the lack of memory.
2591105197Ssam *	others	: pointer to new SA head.
2592105197Ssam */
2593105197Ssamstatic struct secashead *
2594105197Ssamkey_newsah(saidx)
2595105197Ssam	struct secasindex *saidx;
2596105197Ssam{
2597105197Ssam	struct secashead *newsah;
2598105197Ssam
2599120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2600105197Ssam
2601119643Ssam	newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2602105197Ssam	if (newsah != NULL) {
2603105197Ssam		int i;
2604105197Ssam		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2605105197Ssam			LIST_INIT(&newsah->savtree[i]);
2606105197Ssam		newsah->saidx = *saidx;
2607105197Ssam
2608105197Ssam		/* add to saidxtree */
2609105197Ssam		newsah->state = SADB_SASTATE_MATURE;
2610119643Ssam
2611120585Ssam		SAHTREE_LOCK();
2612105197Ssam		LIST_INSERT_HEAD(&sahtree, newsah, chain);
2613120585Ssam		SAHTREE_UNLOCK();
2614105197Ssam	}
2615105197Ssam	return(newsah);
2616105197Ssam}
2617105197Ssam
2618105197Ssam/*
2619105197Ssam * delete SA index and all SA registerd.
2620105197Ssam */
2621105197Ssamstatic void
2622105197Ssamkey_delsah(sah)
2623105197Ssam	struct secashead *sah;
2624105197Ssam{
2625105197Ssam	struct secasvar *sav, *nextsav;
2626120585Ssam	u_int stateidx;
2627105197Ssam	int zombie = 0;
2628105197Ssam
2629120585Ssam	IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2630120585Ssam	SAHTREE_LOCK_ASSERT();
2631105197Ssam
2632105197Ssam	/* searching all SA registerd in the secindex. */
2633105197Ssam	for (stateidx = 0;
2634105197Ssam	     stateidx < _ARRAYLEN(saorder_state_any);
2635105197Ssam	     stateidx++) {
2636120585Ssam		u_int state = saorder_state_any[stateidx];
2637120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2638105197Ssam			if (sav->refcnt == 0) {
2639105197Ssam				/* sanity check */
2640120585Ssam				KEY_CHKSASTATE(state, sav->state, __func__);
2641105197Ssam				KEY_FREESAV(&sav);
2642105197Ssam			} else {
2643105197Ssam				/* give up to delete this sa */
2644105197Ssam				zombie++;
2645105197Ssam			}
2646105197Ssam		}
2647105197Ssam	}
2648120585Ssam	if (!zombie) {		/* delete only if there are savs */
2649120585Ssam		/* remove from tree of SA index */
2650120585Ssam		if (__LIST_CHAINED(sah))
2651120585Ssam			LIST_REMOVE(sah, chain);
2652120585Ssam		if (sah->sa_route.ro_rt) {
2653120585Ssam			RTFREE(sah->sa_route.ro_rt);
2654120585Ssam			sah->sa_route.ro_rt = (struct rtentry *)NULL;
2655120585Ssam		}
2656120585Ssam		free(sah, M_IPSEC_SAH);
2657105197Ssam	}
2658105197Ssam}
2659105197Ssam
2660105197Ssam/*
2661105197Ssam * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2662105197Ssam * and copy the values of mhp into new buffer.
2663105197Ssam * When SAD message type is GETSPI:
2664105197Ssam *	to set sequence number from acq_seq++,
2665105197Ssam *	to set zero to SPI.
2666105197Ssam *	not to call key_setsava().
2667105197Ssam * OUT:	NULL	: fail
2668105197Ssam *	others	: pointer to new secasvar.
2669105197Ssam *
2670105197Ssam * does not modify mbuf.  does not free mbuf on error.
2671105197Ssam */
2672105197Ssamstatic struct secasvar *
2673105197Ssamkey_newsav(m, mhp, sah, errp, where, tag)
2674105197Ssam	struct mbuf *m;
2675105197Ssam	const struct sadb_msghdr *mhp;
2676105197Ssam	struct secashead *sah;
2677105197Ssam	int *errp;
2678105197Ssam	const char* where;
2679105197Ssam	int tag;
2680105197Ssam{
2681105197Ssam	struct secasvar *newsav;
2682105197Ssam	const struct sadb_sa *xsa;
2683105197Ssam
2684120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2685120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2686120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2687120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
2688105197Ssam
2689119643Ssam	newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2690105197Ssam	if (newsav == NULL) {
2691120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2692105197Ssam		*errp = ENOBUFS;
2693105197Ssam		goto done;
2694105197Ssam	}
2695105197Ssam
2696105197Ssam	switch (mhp->msg->sadb_msg_type) {
2697105197Ssam	case SADB_GETSPI:
2698105197Ssam		newsav->spi = 0;
2699105197Ssam
2700105197Ssam#ifdef IPSEC_DOSEQCHECK
2701105197Ssam		/* sync sequence number */
2702105197Ssam		if (mhp->msg->sadb_msg_seq == 0)
2703105197Ssam			newsav->seq =
2704105197Ssam				(acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
2705105197Ssam		else
2706105197Ssam#endif
2707105197Ssam			newsav->seq = mhp->msg->sadb_msg_seq;
2708105197Ssam		break;
2709105197Ssam
2710105197Ssam	case SADB_ADD:
2711105197Ssam		/* sanity check */
2712105197Ssam		if (mhp->ext[SADB_EXT_SA] == NULL) {
2713119643Ssam			free(newsav, M_IPSEC_SA);
2714119643Ssam			newsav = NULL;
2715120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2716120585Ssam				__func__));
2717105197Ssam			*errp = EINVAL;
2718105197Ssam			goto done;
2719105197Ssam		}
2720105197Ssam		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2721105197Ssam		newsav->spi = xsa->sadb_sa_spi;
2722105197Ssam		newsav->seq = mhp->msg->sadb_msg_seq;
2723105197Ssam		break;
2724105197Ssam	default:
2725119643Ssam		free(newsav, M_IPSEC_SA);
2726119643Ssam		newsav = NULL;
2727105197Ssam		*errp = EINVAL;
2728105197Ssam		goto done;
2729105197Ssam	}
2730105197Ssam
2731119643Ssam
2732105197Ssam	/* copy sav values */
2733105197Ssam	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2734105197Ssam		*errp = key_setsaval(newsav, m, mhp);
2735105197Ssam		if (*errp) {
2736119643Ssam			free(newsav, M_IPSEC_SA);
2737119643Ssam			newsav = NULL;
2738105197Ssam			goto done;
2739105197Ssam		}
2740105197Ssam	}
2741105197Ssam
2742120585Ssam	SECASVAR_LOCK_INIT(newsav);
2743119643Ssam
2744105197Ssam	/* reset created */
2745105197Ssam	newsav->created = time_second;
2746105197Ssam	newsav->pid = mhp->msg->sadb_msg_pid;
2747105197Ssam
2748105197Ssam	/* add to satree */
2749105197Ssam	newsav->sah = sah;
2750105197Ssam	newsav->refcnt = 1;
2751105197Ssam	newsav->state = SADB_SASTATE_LARVAL;
2752119643Ssam
2753119643Ssam	/* XXX locking??? */
2754105197Ssam	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2755105197Ssam			secasvar, chain);
2756105197Ssamdone:
2757105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2758120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
2759105197Ssam			where, tag, newsav));
2760105197Ssam
2761105197Ssam	return newsav;
2762105197Ssam}
2763105197Ssam
2764105197Ssam/*
2765105197Ssam * free() SA variable entry.
2766105197Ssam */
2767105197Ssamstatic void
2768119643Ssamkey_cleansav(struct secasvar *sav)
2769105197Ssam{
2770117051Ssam	/*
2771117051Ssam	 * Cleanup xform state.  Note that zeroize'ing causes the
2772117051Ssam	 * keys to be cleared; otherwise we must do it ourself.
2773117051Ssam	 */
2774117051Ssam	if (sav->tdb_xform != NULL) {
2775117051Ssam		sav->tdb_xform->xf_zeroize(sav);
2776117051Ssam		sav->tdb_xform = NULL;
2777117051Ssam	} else {
2778120585Ssam		KASSERT(sav->iv == NULL, ("iv but no xform"));
2779117051Ssam		if (sav->key_auth != NULL)
2780117051Ssam			bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2781117051Ssam		if (sav->key_enc != NULL)
2782117051Ssam			bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
2783117051Ssam	}
2784105197Ssam	if (sav->key_auth != NULL) {
2785119643Ssam		free(sav->key_auth, M_IPSEC_MISC);
2786105197Ssam		sav->key_auth = NULL;
2787105197Ssam	}
2788105197Ssam	if (sav->key_enc != NULL) {
2789119643Ssam		free(sav->key_enc, M_IPSEC_MISC);
2790105197Ssam		sav->key_enc = NULL;
2791105197Ssam	}
2792105197Ssam	if (sav->sched) {
2793105197Ssam		bzero(sav->sched, sav->schedlen);
2794119643Ssam		free(sav->sched, M_IPSEC_MISC);
2795105197Ssam		sav->sched = NULL;
2796105197Ssam	}
2797105197Ssam	if (sav->replay != NULL) {
2798119643Ssam		free(sav->replay, M_IPSEC_MISC);
2799105197Ssam		sav->replay = NULL;
2800105197Ssam	}
2801105197Ssam	if (sav->lft_c != NULL) {
2802119643Ssam		free(sav->lft_c, M_IPSEC_MISC);
2803105197Ssam		sav->lft_c = NULL;
2804105197Ssam	}
2805105197Ssam	if (sav->lft_h != NULL) {
2806119643Ssam		free(sav->lft_h, M_IPSEC_MISC);
2807105197Ssam		sav->lft_h = NULL;
2808105197Ssam	}
2809105197Ssam	if (sav->lft_s != NULL) {
2810119643Ssam		free(sav->lft_s, M_IPSEC_MISC);
2811105197Ssam		sav->lft_s = NULL;
2812105197Ssam	}
2813119643Ssam}
2814105197Ssam
2815119643Ssam/*
2816119643Ssam * free() SA variable entry.
2817119643Ssam */
2818119643Ssamstatic void
2819119643Ssamkey_delsav(sav)
2820119643Ssam	struct secasvar *sav;
2821119643Ssam{
2822120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
2823120585Ssam	IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2824105197Ssam
2825119643Ssam	/* remove from SA header */
2826119643Ssam	if (__LIST_CHAINED(sav))
2827119643Ssam		LIST_REMOVE(sav, chain);
2828119643Ssam	key_cleansav(sav);
2829120585Ssam	SECASVAR_LOCK_DESTROY(sav);
2830119643Ssam	free(sav, M_IPSEC_SA);
2831105197Ssam}
2832105197Ssam
2833105197Ssam/*
2834105197Ssam * search SAD.
2835105197Ssam * OUT:
2836105197Ssam *	NULL	: not found
2837105197Ssam *	others	: found, pointer to a SA.
2838105197Ssam */
2839105197Ssamstatic struct secashead *
2840105197Ssamkey_getsah(saidx)
2841105197Ssam	struct secasindex *saidx;
2842105197Ssam{
2843105197Ssam	struct secashead *sah;
2844105197Ssam
2845120585Ssam	SAHTREE_LOCK();
2846105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
2847105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
2848105197Ssam			continue;
2849105197Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2850119643Ssam			break;
2851105197Ssam	}
2852120585Ssam	SAHTREE_UNLOCK();
2853105197Ssam
2854119643Ssam	return sah;
2855105197Ssam}
2856105197Ssam
2857105197Ssam/*
2858105197Ssam * check not to be duplicated SPI.
2859105197Ssam * NOTE: this function is too slow due to searching all SAD.
2860105197Ssam * OUT:
2861105197Ssam *	NULL	: not found
2862105197Ssam *	others	: found, pointer to a SA.
2863105197Ssam */
2864105197Ssamstatic struct secasvar *
2865105197Ssamkey_checkspidup(saidx, spi)
2866105197Ssam	struct secasindex *saidx;
2867105197Ssam	u_int32_t spi;
2868105197Ssam{
2869105197Ssam	struct secashead *sah;
2870105197Ssam	struct secasvar *sav;
2871105197Ssam
2872105197Ssam	/* check address family */
2873105197Ssam	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2874120585Ssam		ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2875120585Ssam			__func__));
2876105197Ssam		return NULL;
2877105197Ssam	}
2878105197Ssam
2879119643Ssam	sav = NULL;
2880105197Ssam	/* check all SAD */
2881120585Ssam	SAHTREE_LOCK();
2882105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
2883105197Ssam		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2884105197Ssam			continue;
2885105197Ssam		sav = key_getsavbyspi(sah, spi);
2886105197Ssam		if (sav != NULL)
2887119643Ssam			break;
2888105197Ssam	}
2889120585Ssam	SAHTREE_UNLOCK();
2890105197Ssam
2891119643Ssam	return sav;
2892105197Ssam}
2893105197Ssam
2894105197Ssam/*
2895105197Ssam * search SAD litmited alive SA, protocol, SPI.
2896105197Ssam * OUT:
2897105197Ssam *	NULL	: not found
2898105197Ssam *	others	: found, pointer to a SA.
2899105197Ssam */
2900105197Ssamstatic struct secasvar *
2901105197Ssamkey_getsavbyspi(sah, spi)
2902105197Ssam	struct secashead *sah;
2903105197Ssam	u_int32_t spi;
2904105197Ssam{
2905105197Ssam	struct secasvar *sav;
2906105197Ssam	u_int stateidx, state;
2907105197Ssam
2908119643Ssam	sav = NULL;
2909120585Ssam	SAHTREE_LOCK_ASSERT();
2910105197Ssam	/* search all status */
2911105197Ssam	for (stateidx = 0;
2912105197Ssam	     stateidx < _ARRAYLEN(saorder_state_alive);
2913105197Ssam	     stateidx++) {
2914105197Ssam
2915105197Ssam		state = saorder_state_alive[stateidx];
2916105197Ssam		LIST_FOREACH(sav, &sah->savtree[state], chain) {
2917105197Ssam
2918105197Ssam			/* sanity check */
2919105197Ssam			if (sav->state != state) {
2920120585Ssam				ipseclog((LOG_DEBUG, "%s: "
2921105197Ssam				    "invalid sav->state (queue: %d SA: %d)\n",
2922120585Ssam				    __func__, state, sav->state));
2923105197Ssam				continue;
2924105197Ssam			}
2925105197Ssam
2926105197Ssam			if (sav->spi == spi)
2927119643Ssam				break;
2928105197Ssam		}
2929105197Ssam	}
2930105197Ssam
2931119643Ssam	return sav;
2932105197Ssam}
2933105197Ssam
2934105197Ssam/*
2935105197Ssam * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
2936105197Ssam * You must update these if need.
2937105197Ssam * OUT:	0:	success.
2938105197Ssam *	!0:	failure.
2939105197Ssam *
2940105197Ssam * does not modify mbuf.  does not free mbuf on error.
2941105197Ssam */
2942105197Ssamstatic int
2943105197Ssamkey_setsaval(sav, m, mhp)
2944105197Ssam	struct secasvar *sav;
2945105197Ssam	struct mbuf *m;
2946105197Ssam	const struct sadb_msghdr *mhp;
2947105197Ssam{
2948105197Ssam	int error = 0;
2949105197Ssam
2950120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2951120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2952120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2953105197Ssam
2954105197Ssam	/* initialization */
2955105197Ssam	sav->replay = NULL;
2956105197Ssam	sav->key_auth = NULL;
2957105197Ssam	sav->key_enc = NULL;
2958105197Ssam	sav->sched = NULL;
2959105197Ssam	sav->schedlen = 0;
2960105197Ssam	sav->iv = NULL;
2961105197Ssam	sav->lft_c = NULL;
2962105197Ssam	sav->lft_h = NULL;
2963105197Ssam	sav->lft_s = NULL;
2964105197Ssam	sav->tdb_xform = NULL;		/* transform */
2965105197Ssam	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
2966105197Ssam	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
2967105197Ssam	sav->tdb_compalgxform = NULL;	/* compression algorithm */
2968105197Ssam
2969105197Ssam	/* SA */
2970105197Ssam	if (mhp->ext[SADB_EXT_SA] != NULL) {
2971105197Ssam		const struct sadb_sa *sa0;
2972105197Ssam
2973105197Ssam		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2974105197Ssam		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
2975105197Ssam			error = EINVAL;
2976105197Ssam			goto fail;
2977105197Ssam		}
2978105197Ssam
2979105197Ssam		sav->alg_auth = sa0->sadb_sa_auth;
2980105197Ssam		sav->alg_enc = sa0->sadb_sa_encrypt;
2981105197Ssam		sav->flags = sa0->sadb_sa_flags;
2982105197Ssam
2983105197Ssam		/* replay window */
2984105197Ssam		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
2985105197Ssam			sav->replay = (struct secreplay *)
2986119643Ssam				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
2987105197Ssam			if (sav->replay == NULL) {
2988120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
2989120585Ssam					__func__));
2990105197Ssam				error = ENOBUFS;
2991105197Ssam				goto fail;
2992105197Ssam			}
2993105197Ssam			if (sa0->sadb_sa_replay != 0)
2994105197Ssam				sav->replay->bitmap = (caddr_t)(sav->replay+1);
2995105197Ssam			sav->replay->wsize = sa0->sadb_sa_replay;
2996105197Ssam		}
2997105197Ssam	}
2998105197Ssam
2999105197Ssam	/* Authentication keys */
3000105197Ssam	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3001105197Ssam		const struct sadb_key *key0;
3002105197Ssam		int len;
3003105197Ssam
3004105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3005105197Ssam		len = mhp->extlen[SADB_EXT_KEY_AUTH];
3006105197Ssam
3007105197Ssam		error = 0;
3008105197Ssam		if (len < sizeof(*key0)) {
3009105197Ssam			error = EINVAL;
3010105197Ssam			goto fail;
3011105197Ssam		}
3012105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3013105197Ssam		case SADB_SATYPE_AH:
3014105197Ssam		case SADB_SATYPE_ESP:
3015125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3016105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3017105197Ssam			    sav->alg_auth != SADB_X_AALG_NULL)
3018105197Ssam				error = EINVAL;
3019105197Ssam			break;
3020105197Ssam		case SADB_X_SATYPE_IPCOMP:
3021105197Ssam		default:
3022105197Ssam			error = EINVAL;
3023105197Ssam			break;
3024105197Ssam		}
3025105197Ssam		if (error) {
3026120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3027120585Ssam				__func__));
3028105197Ssam			goto fail;
3029105197Ssam		}
3030105197Ssam
3031119643Ssam		sav->key_auth = key_dup(key0, len, M_IPSEC_MISC);
3032105197Ssam		if (sav->key_auth == NULL) {
3033120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3034105197Ssam			error = ENOBUFS;
3035105197Ssam			goto fail;
3036105197Ssam		}
3037105197Ssam	}
3038105197Ssam
3039105197Ssam	/* Encryption key */
3040105197Ssam	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3041105197Ssam		const struct sadb_key *key0;
3042105197Ssam		int len;
3043105197Ssam
3044105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3045105197Ssam		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3046105197Ssam
3047105197Ssam		error = 0;
3048105197Ssam		if (len < sizeof(*key0)) {
3049105197Ssam			error = EINVAL;
3050105197Ssam			goto fail;
3051105197Ssam		}
3052105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3053105197Ssam		case SADB_SATYPE_ESP:
3054105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3055105197Ssam			    sav->alg_enc != SADB_EALG_NULL) {
3056105197Ssam				error = EINVAL;
3057105197Ssam				break;
3058105197Ssam			}
3059119643Ssam			sav->key_enc = key_dup(key0, len, M_IPSEC_MISC);
3060105197Ssam			if (sav->key_enc == NULL) {
3061120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3062120585Ssam					__func__));
3063105197Ssam				error = ENOBUFS;
3064105197Ssam				goto fail;
3065105197Ssam			}
3066105197Ssam			break;
3067105197Ssam		case SADB_X_SATYPE_IPCOMP:
3068105197Ssam			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3069105197Ssam				error = EINVAL;
3070105197Ssam			sav->key_enc = NULL;	/*just in case*/
3071105197Ssam			break;
3072105197Ssam		case SADB_SATYPE_AH:
3073125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3074105197Ssam		default:
3075105197Ssam			error = EINVAL;
3076105197Ssam			break;
3077105197Ssam		}
3078105197Ssam		if (error) {
3079120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3080120585Ssam				__func__));
3081105197Ssam			goto fail;
3082105197Ssam		}
3083105197Ssam	}
3084105197Ssam
3085105197Ssam	/* set iv */
3086105197Ssam	sav->ivlen = 0;
3087105197Ssam
3088105197Ssam	switch (mhp->msg->sadb_msg_satype) {
3089105197Ssam	case SADB_SATYPE_AH:
3090105197Ssam		error = xform_init(sav, XF_AH);
3091105197Ssam		break;
3092105197Ssam	case SADB_SATYPE_ESP:
3093105197Ssam		error = xform_init(sav, XF_ESP);
3094105197Ssam		break;
3095105197Ssam	case SADB_X_SATYPE_IPCOMP:
3096105197Ssam		error = xform_init(sav, XF_IPCOMP);
3097105197Ssam		break;
3098125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
3099125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3100125680Sbms		break;
3101105197Ssam	}
3102105197Ssam	if (error) {
3103120585Ssam		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3104120585Ssam		        __func__, mhp->msg->sadb_msg_satype));
3105105197Ssam		goto fail;
3106105197Ssam	}
3107105197Ssam
3108105197Ssam	/* reset created */
3109105197Ssam	sav->created = time_second;
3110105197Ssam
3111105197Ssam	/* make lifetime for CURRENT */
3112119643Ssam	sav->lft_c = malloc(sizeof(struct sadb_lifetime), M_IPSEC_MISC, M_NOWAIT);
3113105197Ssam	if (sav->lft_c == NULL) {
3114120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3115105197Ssam		error = ENOBUFS;
3116105197Ssam		goto fail;
3117105197Ssam	}
3118105197Ssam
3119105197Ssam	sav->lft_c->sadb_lifetime_len =
3120105197Ssam	    PFKEY_UNIT64(sizeof(struct sadb_lifetime));
3121105197Ssam	sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
3122105197Ssam	sav->lft_c->sadb_lifetime_allocations = 0;
3123105197Ssam	sav->lft_c->sadb_lifetime_bytes = 0;
3124105197Ssam	sav->lft_c->sadb_lifetime_addtime = time_second;
3125105197Ssam	sav->lft_c->sadb_lifetime_usetime = 0;
3126105197Ssam
3127105197Ssam	/* lifetimes for HARD and SOFT */
3128105197Ssam    {
3129105197Ssam	const struct sadb_lifetime *lft0;
3130105197Ssam
3131105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3132105197Ssam	if (lft0 != NULL) {
3133105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3134105197Ssam			error = EINVAL;
3135105197Ssam			goto fail;
3136105197Ssam		}
3137119643Ssam		sav->lft_h = key_dup(lft0, sizeof(*lft0), M_IPSEC_MISC);
3138105197Ssam		if (sav->lft_h == NULL) {
3139120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3140105197Ssam			error = ENOBUFS;
3141105197Ssam			goto fail;
3142105197Ssam		}
3143105197Ssam		/* to be initialize ? */
3144105197Ssam	}
3145105197Ssam
3146105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3147105197Ssam	if (lft0 != NULL) {
3148105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3149105197Ssam			error = EINVAL;
3150105197Ssam			goto fail;
3151105197Ssam		}
3152119643Ssam		sav->lft_s = key_dup(lft0, sizeof(*lft0), M_IPSEC_MISC);
3153105197Ssam		if (sav->lft_s == NULL) {
3154120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3155105197Ssam			error = ENOBUFS;
3156105197Ssam			goto fail;
3157105197Ssam		}
3158105197Ssam		/* to be initialize ? */
3159105197Ssam	}
3160105197Ssam    }
3161105197Ssam
3162105197Ssam	return 0;
3163105197Ssam
3164105197Ssam fail:
3165105197Ssam	/* initialization */
3166119643Ssam	key_cleansav(sav);
3167105197Ssam
3168105197Ssam	return error;
3169105197Ssam}
3170105197Ssam
3171105197Ssam/*
3172105197Ssam * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3173105197Ssam * OUT:	0:	valid
3174105197Ssam *	other:	errno
3175105197Ssam */
3176105197Ssamstatic int
3177119643Ssamkey_mature(struct secasvar *sav)
3178105197Ssam{
3179105197Ssam	int error;
3180105197Ssam
3181105197Ssam	/* check SPI value */
3182105197Ssam	switch (sav->sah->saidx.proto) {
3183105197Ssam	case IPPROTO_ESP:
3184105197Ssam	case IPPROTO_AH:
3185105197Ssam		if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
3186120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3187120585Ssam			    __func__, (u_int32_t)ntohl(sav->spi)));
3188105197Ssam			return EINVAL;
3189105197Ssam		}
3190105197Ssam		break;
3191105197Ssam	}
3192105197Ssam
3193105197Ssam	/* check satype */
3194105197Ssam	switch (sav->sah->saidx.proto) {
3195105197Ssam	case IPPROTO_ESP:
3196105197Ssam		/* check flags */
3197105197Ssam		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3198105197Ssam		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3199120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3200120585Ssam				"given to old-esp.\n", __func__));
3201105197Ssam			return EINVAL;
3202105197Ssam		}
3203105197Ssam		error = xform_init(sav, XF_ESP);
3204105197Ssam		break;
3205105197Ssam	case IPPROTO_AH:
3206105197Ssam		/* check flags */
3207105197Ssam		if (sav->flags & SADB_X_EXT_DERIV) {
3208120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3209120585Ssam				"given to AH SA.\n", __func__));
3210105197Ssam			return EINVAL;
3211105197Ssam		}
3212105197Ssam		if (sav->alg_enc != SADB_EALG_NONE) {
3213120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3214120585Ssam				"mismated.\n", __func__));
3215105197Ssam			return(EINVAL);
3216105197Ssam		}
3217105197Ssam		error = xform_init(sav, XF_AH);
3218105197Ssam		break;
3219105197Ssam	case IPPROTO_IPCOMP:
3220105197Ssam		if (sav->alg_auth != SADB_AALG_NONE) {
3221120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3222120585Ssam				"mismated.\n", __func__));
3223105197Ssam			return(EINVAL);
3224105197Ssam		}
3225105197Ssam		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3226105197Ssam		 && ntohl(sav->spi) >= 0x10000) {
3227120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3228120585Ssam				__func__));
3229105197Ssam			return(EINVAL);
3230105197Ssam		}
3231105197Ssam		error = xform_init(sav, XF_IPCOMP);
3232105197Ssam		break;
3233125680Sbms	case IPPROTO_TCP:
3234125680Sbms		if (sav->alg_enc != SADB_EALG_NONE) {
3235125680Sbms			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3236125680Sbms				"mismated.\n", __func__));
3237125680Sbms			return(EINVAL);
3238125680Sbms		}
3239125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3240125680Sbms		break;
3241105197Ssam	default:
3242120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3243105197Ssam		error = EPROTONOSUPPORT;
3244105197Ssam		break;
3245105197Ssam	}
3246119643Ssam	if (error == 0) {
3247120585Ssam		SAHTREE_LOCK();
3248105197Ssam		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3249120585Ssam		SAHTREE_UNLOCK();
3250119643Ssam	}
3251105197Ssam	return (error);
3252105197Ssam}
3253105197Ssam
3254105197Ssam/*
3255105197Ssam * subroutine for SADB_GET and SADB_DUMP.
3256105197Ssam */
3257105197Ssamstatic struct mbuf *
3258105197Ssamkey_setdumpsa(sav, type, satype, seq, pid)
3259105197Ssam	struct secasvar *sav;
3260105197Ssam	u_int8_t type, satype;
3261105197Ssam	u_int32_t seq, pid;
3262105197Ssam{
3263105197Ssam	struct mbuf *result = NULL, *tres = NULL, *m;
3264105197Ssam	int l = 0;
3265105197Ssam	int i;
3266105197Ssam	void *p;
3267105197Ssam	int dumporder[] = {
3268105197Ssam		SADB_EXT_SA, SADB_X_EXT_SA2,
3269105197Ssam		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3270105197Ssam		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3271105197Ssam		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3272105197Ssam		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3273105197Ssam		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3274105197Ssam	};
3275105197Ssam
3276105197Ssam	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3277105197Ssam	if (m == NULL)
3278105197Ssam		goto fail;
3279105197Ssam	result = m;
3280105197Ssam
3281105197Ssam	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3282105197Ssam		m = NULL;
3283105197Ssam		p = NULL;
3284105197Ssam		switch (dumporder[i]) {
3285105197Ssam		case SADB_EXT_SA:
3286105197Ssam			m = key_setsadbsa(sav);
3287105197Ssam			if (!m)
3288105197Ssam				goto fail;
3289105197Ssam			break;
3290105197Ssam
3291105197Ssam		case SADB_X_EXT_SA2:
3292105197Ssam			m = key_setsadbxsa2(sav->sah->saidx.mode,
3293105197Ssam					sav->replay ? sav->replay->count : 0,
3294105197Ssam					sav->sah->saidx.reqid);
3295105197Ssam			if (!m)
3296105197Ssam				goto fail;
3297105197Ssam			break;
3298105197Ssam
3299105197Ssam		case SADB_EXT_ADDRESS_SRC:
3300105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3301105197Ssam			    &sav->sah->saidx.src.sa,
3302105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3303105197Ssam			if (!m)
3304105197Ssam				goto fail;
3305105197Ssam			break;
3306105197Ssam
3307105197Ssam		case SADB_EXT_ADDRESS_DST:
3308105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3309105197Ssam			    &sav->sah->saidx.dst.sa,
3310105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3311105197Ssam			if (!m)
3312105197Ssam				goto fail;
3313105197Ssam			break;
3314105197Ssam
3315105197Ssam		case SADB_EXT_KEY_AUTH:
3316105197Ssam			if (!sav->key_auth)
3317105197Ssam				continue;
3318105197Ssam			l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
3319105197Ssam			p = sav->key_auth;
3320105197Ssam			break;
3321105197Ssam
3322105197Ssam		case SADB_EXT_KEY_ENCRYPT:
3323105197Ssam			if (!sav->key_enc)
3324105197Ssam				continue;
3325105197Ssam			l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
3326105197Ssam			p = sav->key_enc;
3327105197Ssam			break;
3328105197Ssam
3329105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
3330105197Ssam			if (!sav->lft_c)
3331105197Ssam				continue;
3332105197Ssam			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
3333105197Ssam			p = sav->lft_c;
3334105197Ssam			break;
3335105197Ssam
3336105197Ssam		case SADB_EXT_LIFETIME_HARD:
3337105197Ssam			if (!sav->lft_h)
3338105197Ssam				continue;
3339105197Ssam			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
3340105197Ssam			p = sav->lft_h;
3341105197Ssam			break;
3342105197Ssam
3343105197Ssam		case SADB_EXT_LIFETIME_SOFT:
3344105197Ssam			if (!sav->lft_s)
3345105197Ssam				continue;
3346105197Ssam			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
3347105197Ssam			p = sav->lft_s;
3348105197Ssam			break;
3349105197Ssam
3350105197Ssam		case SADB_EXT_ADDRESS_PROXY:
3351105197Ssam		case SADB_EXT_IDENTITY_SRC:
3352105197Ssam		case SADB_EXT_IDENTITY_DST:
3353105197Ssam			/* XXX: should we brought from SPD ? */
3354105197Ssam		case SADB_EXT_SENSITIVITY:
3355105197Ssam		default:
3356105197Ssam			continue;
3357105197Ssam		}
3358105197Ssam
3359105197Ssam		if ((!m && !p) || (m && p))
3360105197Ssam			goto fail;
3361105197Ssam		if (p && tres) {
3362111119Simp			M_PREPEND(tres, l, M_DONTWAIT);
3363105197Ssam			if (!tres)
3364105197Ssam				goto fail;
3365105197Ssam			bcopy(p, mtod(tres, caddr_t), l);
3366105197Ssam			continue;
3367105197Ssam		}
3368105197Ssam		if (p) {
3369105197Ssam			m = key_alloc_mbuf(l);
3370105197Ssam			if (!m)
3371105197Ssam				goto fail;
3372105197Ssam			m_copyback(m, 0, l, p);
3373105197Ssam		}
3374105197Ssam
3375105197Ssam		if (tres)
3376105197Ssam			m_cat(m, tres);
3377105197Ssam		tres = m;
3378105197Ssam	}
3379105197Ssam
3380105197Ssam	m_cat(result, tres);
3381105197Ssam
3382105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
3383105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
3384105197Ssam		if (result == NULL)
3385105197Ssam			goto fail;
3386105197Ssam	}
3387105197Ssam
3388105197Ssam	result->m_pkthdr.len = 0;
3389105197Ssam	for (m = result; m; m = m->m_next)
3390105197Ssam		result->m_pkthdr.len += m->m_len;
3391105197Ssam
3392105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
3393105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
3394105197Ssam
3395105197Ssam	return result;
3396105197Ssam
3397105197Ssamfail:
3398105197Ssam	m_freem(result);
3399105197Ssam	m_freem(tres);
3400105197Ssam	return NULL;
3401105197Ssam}
3402105197Ssam
3403105197Ssam/*
3404105197Ssam * set data into sadb_msg.
3405105197Ssam */
3406105197Ssamstatic struct mbuf *
3407105197Ssamkey_setsadbmsg(type, tlen, satype, seq, pid, reserved)
3408105197Ssam	u_int8_t type, satype;
3409105197Ssam	u_int16_t tlen;
3410105197Ssam	u_int32_t seq;
3411105197Ssam	pid_t pid;
3412105197Ssam	u_int16_t reserved;
3413105197Ssam{
3414105197Ssam	struct mbuf *m;
3415105197Ssam	struct sadb_msg *p;
3416105197Ssam	int len;
3417105197Ssam
3418105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3419105197Ssam	if (len > MCLBYTES)
3420105197Ssam		return NULL;
3421111119Simp	MGETHDR(m, M_DONTWAIT, MT_DATA);
3422105197Ssam	if (m && len > MHLEN) {
3423111119Simp		MCLGET(m, M_DONTWAIT);
3424105197Ssam		if ((m->m_flags & M_EXT) == 0) {
3425105197Ssam			m_freem(m);
3426105197Ssam			m = NULL;
3427105197Ssam		}
3428105197Ssam	}
3429105197Ssam	if (!m)
3430105197Ssam		return NULL;
3431105197Ssam	m->m_pkthdr.len = m->m_len = len;
3432105197Ssam	m->m_next = NULL;
3433105197Ssam
3434105197Ssam	p = mtod(m, struct sadb_msg *);
3435105197Ssam
3436105197Ssam	bzero(p, len);
3437105197Ssam	p->sadb_msg_version = PF_KEY_V2;
3438105197Ssam	p->sadb_msg_type = type;
3439105197Ssam	p->sadb_msg_errno = 0;
3440105197Ssam	p->sadb_msg_satype = satype;
3441105197Ssam	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3442105197Ssam	p->sadb_msg_reserved = reserved;
3443105197Ssam	p->sadb_msg_seq = seq;
3444105197Ssam	p->sadb_msg_pid = (u_int32_t)pid;
3445105197Ssam
3446105197Ssam	return m;
3447105197Ssam}
3448105197Ssam
3449105197Ssam/*
3450105197Ssam * copy secasvar data into sadb_address.
3451105197Ssam */
3452105197Ssamstatic struct mbuf *
3453105197Ssamkey_setsadbsa(sav)
3454105197Ssam	struct secasvar *sav;
3455105197Ssam{
3456105197Ssam	struct mbuf *m;
3457105197Ssam	struct sadb_sa *p;
3458105197Ssam	int len;
3459105197Ssam
3460105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3461105197Ssam	m = key_alloc_mbuf(len);
3462105197Ssam	if (!m || m->m_next) {	/*XXX*/
3463105197Ssam		if (m)
3464105197Ssam			m_freem(m);
3465105197Ssam		return NULL;
3466105197Ssam	}
3467105197Ssam
3468105197Ssam	p = mtod(m, struct sadb_sa *);
3469105197Ssam
3470105197Ssam	bzero(p, len);
3471105197Ssam	p->sadb_sa_len = PFKEY_UNIT64(len);
3472105197Ssam	p->sadb_sa_exttype = SADB_EXT_SA;
3473105197Ssam	p->sadb_sa_spi = sav->spi;
3474105197Ssam	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3475105197Ssam	p->sadb_sa_state = sav->state;
3476105197Ssam	p->sadb_sa_auth = sav->alg_auth;
3477105197Ssam	p->sadb_sa_encrypt = sav->alg_enc;
3478105197Ssam	p->sadb_sa_flags = sav->flags;
3479105197Ssam
3480105197Ssam	return m;
3481105197Ssam}
3482105197Ssam
3483105197Ssam/*
3484105197Ssam * set data into sadb_address.
3485105197Ssam */
3486105197Ssamstatic struct mbuf *
3487105197Ssamkey_setsadbaddr(exttype, saddr, prefixlen, ul_proto)
3488105197Ssam	u_int16_t exttype;
3489105197Ssam	const struct sockaddr *saddr;
3490105197Ssam	u_int8_t prefixlen;
3491105197Ssam	u_int16_t ul_proto;
3492105197Ssam{
3493105197Ssam	struct mbuf *m;
3494105197Ssam	struct sadb_address *p;
3495105197Ssam	size_t len;
3496105197Ssam
3497105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3498105197Ssam	    PFKEY_ALIGN8(saddr->sa_len);
3499105197Ssam	m = key_alloc_mbuf(len);
3500105197Ssam	if (!m || m->m_next) {	/*XXX*/
3501105197Ssam		if (m)
3502105197Ssam			m_freem(m);
3503105197Ssam		return NULL;
3504105197Ssam	}
3505105197Ssam
3506105197Ssam	p = mtod(m, struct sadb_address *);
3507105197Ssam
3508105197Ssam	bzero(p, len);
3509105197Ssam	p->sadb_address_len = PFKEY_UNIT64(len);
3510105197Ssam	p->sadb_address_exttype = exttype;
3511105197Ssam	p->sadb_address_proto = ul_proto;
3512105197Ssam	if (prefixlen == FULLMASK) {
3513105197Ssam		switch (saddr->sa_family) {
3514105197Ssam		case AF_INET:
3515105197Ssam			prefixlen = sizeof(struct in_addr) << 3;
3516105197Ssam			break;
3517105197Ssam		case AF_INET6:
3518105197Ssam			prefixlen = sizeof(struct in6_addr) << 3;
3519105197Ssam			break;
3520105197Ssam		default:
3521105197Ssam			; /*XXX*/
3522105197Ssam		}
3523105197Ssam	}
3524105197Ssam	p->sadb_address_prefixlen = prefixlen;
3525105197Ssam	p->sadb_address_reserved = 0;
3526105197Ssam
3527105197Ssam	bcopy(saddr,
3528105197Ssam	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3529105197Ssam	    saddr->sa_len);
3530105197Ssam
3531105197Ssam	return m;
3532105197Ssam}
3533105197Ssam
3534105197Ssam/*
3535105197Ssam * set data into sadb_x_sa2.
3536105197Ssam */
3537105197Ssamstatic struct mbuf *
3538105197Ssamkey_setsadbxsa2(mode, seq, reqid)
3539105197Ssam	u_int8_t mode;
3540105197Ssam	u_int32_t seq, reqid;
3541105197Ssam{
3542105197Ssam	struct mbuf *m;
3543105197Ssam	struct sadb_x_sa2 *p;
3544105197Ssam	size_t len;
3545105197Ssam
3546105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3547105197Ssam	m = key_alloc_mbuf(len);
3548105197Ssam	if (!m || m->m_next) {	/*XXX*/
3549105197Ssam		if (m)
3550105197Ssam			m_freem(m);
3551105197Ssam		return NULL;
3552105197Ssam	}
3553105197Ssam
3554105197Ssam	p = mtod(m, struct sadb_x_sa2 *);
3555105197Ssam
3556105197Ssam	bzero(p, len);
3557105197Ssam	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3558105197Ssam	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3559105197Ssam	p->sadb_x_sa2_mode = mode;
3560105197Ssam	p->sadb_x_sa2_reserved1 = 0;
3561105197Ssam	p->sadb_x_sa2_reserved2 = 0;
3562105197Ssam	p->sadb_x_sa2_sequence = seq;
3563105197Ssam	p->sadb_x_sa2_reqid = reqid;
3564105197Ssam
3565105197Ssam	return m;
3566105197Ssam}
3567105197Ssam
3568105197Ssam/*
3569105197Ssam * set data into sadb_x_policy
3570105197Ssam */
3571105197Ssamstatic struct mbuf *
3572105197Ssamkey_setsadbxpolicy(type, dir, id)
3573105197Ssam	u_int16_t type;
3574105197Ssam	u_int8_t dir;
3575105197Ssam	u_int32_t id;
3576105197Ssam{
3577105197Ssam	struct mbuf *m;
3578105197Ssam	struct sadb_x_policy *p;
3579105197Ssam	size_t len;
3580105197Ssam
3581105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3582105197Ssam	m = key_alloc_mbuf(len);
3583105197Ssam	if (!m || m->m_next) {	/*XXX*/
3584105197Ssam		if (m)
3585105197Ssam			m_freem(m);
3586105197Ssam		return NULL;
3587105197Ssam	}
3588105197Ssam
3589105197Ssam	p = mtod(m, struct sadb_x_policy *);
3590105197Ssam
3591105197Ssam	bzero(p, len);
3592105197Ssam	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3593105197Ssam	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3594105197Ssam	p->sadb_x_policy_type = type;
3595105197Ssam	p->sadb_x_policy_dir = dir;
3596105197Ssam	p->sadb_x_policy_id = id;
3597105197Ssam
3598105197Ssam	return m;
3599105197Ssam}
3600105197Ssam
3601105197Ssam/* %%% utilities */
3602105197Ssam/*
3603105197Ssam * copy a buffer into the new buffer allocated.
3604105197Ssam */
3605105197Ssamstatic void *
3606119643Ssamkey_dup(const void *src, u_int len, struct malloc_type *type)
3607105197Ssam{
3608119643Ssam	void *copy;
3609105197Ssam
3610119643Ssam	copy = malloc(len, type, M_NOWAIT);
3611119643Ssam	if (copy == NULL) {
3612119643Ssam		/* XXX counter */
3613120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3614119643Ssam	} else
3615119643Ssam		bcopy(src, copy, len);
3616119643Ssam	return copy;
3617105197Ssam}
3618105197Ssam
3619105197Ssam/* compare my own address
3620105197Ssam * OUT:	1: true, i.e. my address.
3621105197Ssam *	0: false
3622105197Ssam */
3623105197Ssamint
3624105197Ssamkey_ismyaddr(sa)
3625105197Ssam	struct sockaddr *sa;
3626105197Ssam{
3627105197Ssam#ifdef INET
3628105197Ssam	struct sockaddr_in *sin;
3629105197Ssam	struct in_ifaddr *ia;
3630105197Ssam#endif
3631105197Ssam
3632120585Ssam	IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3633105197Ssam
3634105197Ssam	switch (sa->sa_family) {
3635105197Ssam#ifdef INET
3636105197Ssam	case AF_INET:
3637105197Ssam		sin = (struct sockaddr_in *)sa;
3638105197Ssam		for (ia = in_ifaddrhead.tqh_first; ia;
3639105197Ssam		     ia = ia->ia_link.tqe_next)
3640105197Ssam		{
3641105197Ssam			if (sin->sin_family == ia->ia_addr.sin_family &&
3642105197Ssam			    sin->sin_len == ia->ia_addr.sin_len &&
3643105197Ssam			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3644105197Ssam			{
3645105197Ssam				return 1;
3646105197Ssam			}
3647105197Ssam		}
3648105197Ssam		break;
3649105197Ssam#endif
3650105197Ssam#ifdef INET6
3651105197Ssam	case AF_INET6:
3652105197Ssam		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3653105197Ssam#endif
3654105197Ssam	}
3655105197Ssam
3656105197Ssam	return 0;
3657105197Ssam}
3658105197Ssam
3659105197Ssam#ifdef INET6
3660105197Ssam/*
3661105197Ssam * compare my own address for IPv6.
3662105197Ssam * 1: ours
3663105197Ssam * 0: other
3664105197Ssam * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3665105197Ssam */
3666105197Ssam#include <netinet6/in6_var.h>
3667105197Ssam
3668105197Ssamstatic int
3669105197Ssamkey_ismyaddr6(sin6)
3670105197Ssam	struct sockaddr_in6 *sin6;
3671105197Ssam{
3672105197Ssam	struct in6_ifaddr *ia;
3673105197Ssam	struct in6_multi *in6m;
3674105197Ssam
3675105197Ssam	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
3676105197Ssam		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3677105197Ssam		    (struct sockaddr *)&ia->ia_addr, 0) == 0)
3678105197Ssam			return 1;
3679105197Ssam
3680105197Ssam		/*
3681105197Ssam		 * XXX Multicast
3682105197Ssam		 * XXX why do we care about multlicast here while we don't care
3683105197Ssam		 * about IPv4 multicast??
3684105197Ssam		 * XXX scope
3685105197Ssam		 */
3686105197Ssam		in6m = NULL;
3687105197Ssam		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3688105197Ssam		if (in6m)
3689105197Ssam			return 1;
3690105197Ssam	}
3691105197Ssam
3692105197Ssam	/* loopback, just for safety */
3693105197Ssam	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3694105197Ssam		return 1;
3695105197Ssam
3696105197Ssam	return 0;
3697105197Ssam}
3698105197Ssam#endif /*INET6*/
3699105197Ssam
3700105197Ssam/*
3701105197Ssam * compare two secasindex structure.
3702105197Ssam * flag can specify to compare 2 saidxes.
3703105197Ssam * compare two secasindex structure without both mode and reqid.
3704105197Ssam * don't compare port.
3705105197Ssam * IN:
3706105197Ssam *      saidx0: source, it can be in SAD.
3707105197Ssam *      saidx1: object.
3708105197Ssam * OUT:
3709105197Ssam *      1 : equal
3710105197Ssam *      0 : not equal
3711105197Ssam */
3712105197Ssamstatic int
3713105197Ssamkey_cmpsaidx(
3714105197Ssam	const struct secasindex *saidx0,
3715105197Ssam	const struct secasindex *saidx1,
3716105197Ssam	int flag)
3717105197Ssam{
3718105197Ssam	/* sanity */
3719105197Ssam	if (saidx0 == NULL && saidx1 == NULL)
3720105197Ssam		return 1;
3721105197Ssam
3722105197Ssam	if (saidx0 == NULL || saidx1 == NULL)
3723105197Ssam		return 0;
3724105197Ssam
3725105197Ssam	if (saidx0->proto != saidx1->proto)
3726105197Ssam		return 0;
3727105197Ssam
3728105197Ssam	if (flag == CMP_EXACTLY) {
3729105197Ssam		if (saidx0->mode != saidx1->mode)
3730105197Ssam			return 0;
3731105197Ssam		if (saidx0->reqid != saidx1->reqid)
3732105197Ssam			return 0;
3733105197Ssam		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3734105197Ssam		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3735105197Ssam			return 0;
3736105197Ssam	} else {
3737105197Ssam
3738105197Ssam		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3739105197Ssam		if (flag == CMP_MODE_REQID
3740105197Ssam		  ||flag == CMP_REQID) {
3741105197Ssam			/*
3742105197Ssam			 * If reqid of SPD is non-zero, unique SA is required.
3743105197Ssam			 * The result must be of same reqid in this case.
3744105197Ssam			 */
3745105197Ssam			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3746105197Ssam				return 0;
3747105197Ssam		}
3748105197Ssam
3749105197Ssam		if (flag == CMP_MODE_REQID) {
3750105197Ssam			if (saidx0->mode != IPSEC_MODE_ANY
3751105197Ssam			 && saidx0->mode != saidx1->mode)
3752105197Ssam				return 0;
3753105197Ssam		}
3754105197Ssam
3755105197Ssam		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
3756105197Ssam			return 0;
3757105197Ssam		}
3758105197Ssam		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
3759105197Ssam			return 0;
3760105197Ssam		}
3761105197Ssam	}
3762105197Ssam
3763105197Ssam	return 1;
3764105197Ssam}
3765105197Ssam
3766105197Ssam/*
3767105197Ssam * compare two secindex structure exactly.
3768105197Ssam * IN:
3769105197Ssam *	spidx0: source, it is often in SPD.
3770105197Ssam *	spidx1: object, it is often from PFKEY message.
3771105197Ssam * OUT:
3772105197Ssam *	1 : equal
3773105197Ssam *	0 : not equal
3774105197Ssam */
3775105197Ssamstatic int
3776105197Ssamkey_cmpspidx_exactly(
3777105197Ssam	struct secpolicyindex *spidx0,
3778105197Ssam	struct secpolicyindex *spidx1)
3779105197Ssam{
3780105197Ssam	/* sanity */
3781105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
3782105197Ssam		return 1;
3783105197Ssam
3784105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
3785105197Ssam		return 0;
3786105197Ssam
3787105197Ssam	if (spidx0->prefs != spidx1->prefs
3788105197Ssam	 || spidx0->prefd != spidx1->prefd
3789105197Ssam	 || spidx0->ul_proto != spidx1->ul_proto)
3790105197Ssam		return 0;
3791105197Ssam
3792105197Ssam	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3793105197Ssam	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3794105197Ssam}
3795105197Ssam
3796105197Ssam/*
3797105197Ssam * compare two secindex structure with mask.
3798105197Ssam * IN:
3799105197Ssam *	spidx0: source, it is often in SPD.
3800105197Ssam *	spidx1: object, it is often from IP header.
3801105197Ssam * OUT:
3802105197Ssam *	1 : equal
3803105197Ssam *	0 : not equal
3804105197Ssam */
3805105197Ssamstatic int
3806105197Ssamkey_cmpspidx_withmask(
3807105197Ssam	struct secpolicyindex *spidx0,
3808105197Ssam	struct secpolicyindex *spidx1)
3809105197Ssam{
3810105197Ssam	/* sanity */
3811105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
3812105197Ssam		return 1;
3813105197Ssam
3814105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
3815105197Ssam		return 0;
3816105197Ssam
3817105197Ssam	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
3818105197Ssam	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
3819105197Ssam	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
3820105197Ssam	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
3821105197Ssam		return 0;
3822105197Ssam
3823105197Ssam	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3824105197Ssam	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3825105197Ssam	 && spidx0->ul_proto != spidx1->ul_proto)
3826105197Ssam		return 0;
3827105197Ssam
3828105197Ssam	switch (spidx0->src.sa.sa_family) {
3829105197Ssam	case AF_INET:
3830105197Ssam		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
3831105197Ssam		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
3832105197Ssam			return 0;
3833105197Ssam		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
3834105197Ssam		    &spidx1->src.sin.sin_addr, spidx0->prefs))
3835105197Ssam			return 0;
3836105197Ssam		break;
3837105197Ssam	case AF_INET6:
3838105197Ssam		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
3839105197Ssam		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
3840105197Ssam			return 0;
3841105197Ssam		/*
3842105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
3843105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
3844105197Ssam		 */
3845105197Ssam		if (spidx0->src.sin6.sin6_scope_id &&
3846105197Ssam		    spidx1->src.sin6.sin6_scope_id &&
3847105197Ssam		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
3848105197Ssam			return 0;
3849105197Ssam		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
3850105197Ssam		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
3851105197Ssam			return 0;
3852105197Ssam		break;
3853105197Ssam	default:
3854105197Ssam		/* XXX */
3855105197Ssam		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
3856105197Ssam			return 0;
3857105197Ssam		break;
3858105197Ssam	}
3859105197Ssam
3860105197Ssam	switch (spidx0->dst.sa.sa_family) {
3861105197Ssam	case AF_INET:
3862105197Ssam		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
3863105197Ssam		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
3864105197Ssam			return 0;
3865105197Ssam		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
3866105197Ssam		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
3867105197Ssam			return 0;
3868105197Ssam		break;
3869105197Ssam	case AF_INET6:
3870105197Ssam		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
3871105197Ssam		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
3872105197Ssam			return 0;
3873105197Ssam		/*
3874105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
3875105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
3876105197Ssam		 */
3877105197Ssam		if (spidx0->src.sin6.sin6_scope_id &&
3878105197Ssam		    spidx1->src.sin6.sin6_scope_id &&
3879105197Ssam		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
3880105197Ssam			return 0;
3881105197Ssam		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
3882105197Ssam		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
3883105197Ssam			return 0;
3884105197Ssam		break;
3885105197Ssam	default:
3886105197Ssam		/* XXX */
3887105197Ssam		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
3888105197Ssam			return 0;
3889105197Ssam		break;
3890105197Ssam	}
3891105197Ssam
3892105197Ssam	/* XXX Do we check other field ?  e.g. flowinfo */
3893105197Ssam
3894105197Ssam	return 1;
3895105197Ssam}
3896105197Ssam
3897105197Ssam/* returns 0 on match */
3898105197Ssamstatic int
3899105197Ssamkey_sockaddrcmp(
3900105197Ssam	const struct sockaddr *sa1,
3901105197Ssam	const struct sockaddr *sa2,
3902105197Ssam	int port)
3903105197Ssam{
3904105197Ssam#ifdef satosin
3905105197Ssam#undef satosin
3906105197Ssam#endif
3907105197Ssam#define satosin(s) ((const struct sockaddr_in *)s)
3908105197Ssam#ifdef satosin6
3909105197Ssam#undef satosin6
3910105197Ssam#endif
3911105197Ssam#define satosin6(s) ((const struct sockaddr_in6 *)s)
3912105197Ssam	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
3913105197Ssam		return 1;
3914105197Ssam
3915105197Ssam	switch (sa1->sa_family) {
3916105197Ssam	case AF_INET:
3917105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in))
3918105197Ssam			return 1;
3919105197Ssam		if (satosin(sa1)->sin_addr.s_addr !=
3920105197Ssam		    satosin(sa2)->sin_addr.s_addr) {
3921105197Ssam			return 1;
3922105197Ssam		}
3923105197Ssam		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
3924105197Ssam			return 1;
3925105197Ssam		break;
3926105197Ssam	case AF_INET6:
3927105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in6))
3928105197Ssam			return 1;	/*EINVAL*/
3929105197Ssam		if (satosin6(sa1)->sin6_scope_id !=
3930105197Ssam		    satosin6(sa2)->sin6_scope_id) {
3931105197Ssam			return 1;
3932105197Ssam		}
3933105197Ssam		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
3934105197Ssam		    &satosin6(sa2)->sin6_addr)) {
3935105197Ssam			return 1;
3936105197Ssam		}
3937105197Ssam		if (port &&
3938105197Ssam		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
3939105197Ssam			return 1;
3940105197Ssam		}
3941105197Ssam	default:
3942105197Ssam		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
3943105197Ssam			return 1;
3944105197Ssam		break;
3945105197Ssam	}
3946105197Ssam
3947105197Ssam	return 0;
3948105197Ssam#undef satosin
3949105197Ssam#undef satosin6
3950105197Ssam}
3951105197Ssam
3952105197Ssam/*
3953105197Ssam * compare two buffers with mask.
3954105197Ssam * IN:
3955105197Ssam *	addr1: source
3956105197Ssam *	addr2: object
3957105197Ssam *	bits:  Number of bits to compare
3958105197Ssam * OUT:
3959105197Ssam *	1 : equal
3960105197Ssam *	0 : not equal
3961105197Ssam */
3962105197Ssamstatic int
3963105197Ssamkey_bbcmp(const void *a1, const void *a2, u_int bits)
3964105197Ssam{
3965105197Ssam	const unsigned char *p1 = a1;
3966105197Ssam	const unsigned char *p2 = a2;
3967105197Ssam
3968105197Ssam	/* XXX: This could be considerably faster if we compare a word
3969105197Ssam	 * at a time, but it is complicated on LSB Endian machines */
3970105197Ssam
3971105197Ssam	/* Handle null pointers */
3972105197Ssam	if (p1 == NULL || p2 == NULL)
3973105197Ssam		return (p1 == p2);
3974105197Ssam
3975105197Ssam	while (bits >= 8) {
3976105197Ssam		if (*p1++ != *p2++)
3977105197Ssam			return 0;
3978105197Ssam		bits -= 8;
3979105197Ssam	}
3980105197Ssam
3981105197Ssam	if (bits > 0) {
3982105197Ssam		u_int8_t mask = ~((1<<(8-bits))-1);
3983105197Ssam		if ((*p1 & mask) != (*p2 & mask))
3984105197Ssam			return 0;
3985105197Ssam	}
3986105197Ssam	return 1;	/* Match! */
3987105197Ssam}
3988105197Ssam
3989119643Ssamstatic void
3990119643Ssamkey_flush_spd(time_t now)
3991105197Ssam{
3992120585Ssam	static u_int16_t sptree_scangen = 0;
3993120585Ssam	u_int16_t gen = sptree_scangen++;
3994120585Ssam	struct secpolicy *sp;
3995105197Ssam	u_int dir;
3996105197Ssam
3997105197Ssam	/* SPD */
3998105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
3999120585Ssamrestart:
4000120585Ssam		SPTREE_LOCK();
4001120585Ssam		LIST_FOREACH(sp, &sptree[dir], chain) {
4002120585Ssam			if (sp->scangen == gen)		/* previously handled */
4003120585Ssam				continue;
4004120585Ssam			sp->scangen = gen;
4005105197Ssam			if (sp->state == IPSEC_SPSTATE_DEAD) {
4006120585Ssam				/* NB: clean entries created by key_spdflush */
4007120585Ssam				SPTREE_UNLOCK();
4008105197Ssam				KEY_FREESP(&sp);
4009120585Ssam				goto restart;
4010105197Ssam			}
4011105197Ssam			if (sp->lifetime == 0 && sp->validtime == 0)
4012105197Ssam				continue;
4013105197Ssam			if ((sp->lifetime && now - sp->created > sp->lifetime)
4014105197Ssam			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4015105197Ssam				sp->state = IPSEC_SPSTATE_DEAD;
4016120585Ssam				SPTREE_UNLOCK();
4017105197Ssam				key_spdexpire(sp);
4018120585Ssam				KEY_FREESP(&sp);
4019120585Ssam				goto restart;
4020105197Ssam			}
4021105197Ssam		}
4022120585Ssam		SPTREE_UNLOCK();
4023105197Ssam	}
4024119643Ssam}
4025105197Ssam
4026119643Ssamstatic void
4027119643Ssamkey_flush_sad(time_t now)
4028119643Ssam{
4029105197Ssam	struct secashead *sah, *nextsah;
4030105197Ssam	struct secasvar *sav, *nextsav;
4031105197Ssam
4032119643Ssam	/* SAD */
4033120585Ssam	SAHTREE_LOCK();
4034120585Ssam	LIST_FOREACH_SAFE(sah, &sahtree, chain, nextsah) {
4035105197Ssam		/* if sah has been dead, then delete it and process next sah. */
4036105197Ssam		if (sah->state == SADB_SASTATE_DEAD) {
4037105197Ssam			key_delsah(sah);
4038105197Ssam			continue;
4039105197Ssam		}
4040105197Ssam
4041105197Ssam		/* if LARVAL entry doesn't become MATURE, delete it. */
4042120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4043120585Ssam			if (now - sav->created > key_larval_lifetime)
4044105197Ssam				KEY_FREESAV(&sav);
4045105197Ssam		}
4046105197Ssam
4047105197Ssam		/*
4048105197Ssam		 * check MATURE entry to start to send expire message
4049105197Ssam		 * whether or not.
4050105197Ssam		 */
4051120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4052105197Ssam			/* we don't need to check. */
4053105197Ssam			if (sav->lft_s == NULL)
4054105197Ssam				continue;
4055105197Ssam
4056105197Ssam			/* sanity check */
4057105197Ssam			if (sav->lft_c == NULL) {
4058120585Ssam				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4059120585Ssam					"time, why?\n", __func__));
4060105197Ssam				continue;
4061105197Ssam			}
4062105197Ssam
4063105197Ssam			/* check SOFT lifetime */
4064120585Ssam			if (sav->lft_s->sadb_lifetime_addtime != 0 &&
4065120585Ssam			    now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4066105197Ssam				/*
4067105197Ssam				 * check SA to be used whether or not.
4068105197Ssam				 * when SA hasn't been used, delete it.
4069105197Ssam				 */
4070105197Ssam				if (sav->lft_c->sadb_lifetime_usetime == 0) {
4071105197Ssam					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4072105197Ssam					KEY_FREESAV(&sav);
4073105197Ssam				} else {
4074105197Ssam					key_sa_chgstate(sav, SADB_SASTATE_DYING);
4075105197Ssam					/*
4076105197Ssam					 * XXX If we keep to send expire
4077105197Ssam					 * message in the status of
4078105197Ssam					 * DYING. Do remove below code.
4079105197Ssam					 */
4080105197Ssam					key_expire(sav);
4081105197Ssam				}
4082105197Ssam			}
4083105197Ssam			/* check SOFT lifetime by bytes */
4084105197Ssam			/*
4085105197Ssam			 * XXX I don't know the way to delete this SA
4086105197Ssam			 * when new SA is installed.  Caution when it's
4087105197Ssam			 * installed too big lifetime by time.
4088105197Ssam			 */
4089120585Ssam			else if (sav->lft_s->sadb_lifetime_bytes != 0 &&
4090120585Ssam			    sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4091105197Ssam
4092105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4093105197Ssam				/*
4094105197Ssam				 * XXX If we keep to send expire
4095105197Ssam				 * message in the status of
4096105197Ssam				 * DYING. Do remove below code.
4097105197Ssam				 */
4098105197Ssam				key_expire(sav);
4099105197Ssam			}
4100105197Ssam		}
4101105197Ssam
4102105197Ssam		/* check DYING entry to change status to DEAD. */
4103120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4104105197Ssam			/* we don't need to check. */
4105105197Ssam			if (sav->lft_h == NULL)
4106105197Ssam				continue;
4107105197Ssam
4108105197Ssam			/* sanity check */
4109105197Ssam			if (sav->lft_c == NULL) {
4110120585Ssam				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4111120585Ssam					"time, why?\n", __func__));
4112105197Ssam				continue;
4113105197Ssam			}
4114105197Ssam
4115120585Ssam			if (sav->lft_h->sadb_lifetime_addtime != 0 &&
4116120585Ssam			    now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
4117105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4118105197Ssam				KEY_FREESAV(&sav);
4119105197Ssam			}
4120105197Ssam#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4121105197Ssam			else if (sav->lft_s != NULL
4122105197Ssam			      && sav->lft_s->sadb_lifetime_addtime != 0
4123105197Ssam			      && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4124105197Ssam				/*
4125105197Ssam				 * XXX: should be checked to be
4126105197Ssam				 * installed the valid SA.
4127105197Ssam				 */
4128105197Ssam
4129105197Ssam				/*
4130105197Ssam				 * If there is no SA then sending
4131105197Ssam				 * expire message.
4132105197Ssam				 */
4133105197Ssam				key_expire(sav);
4134105197Ssam			}
4135105197Ssam#endif
4136105197Ssam			/* check HARD lifetime by bytes */
4137120585Ssam			else if (sav->lft_h->sadb_lifetime_bytes != 0 &&
4138120585Ssam			    sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4139105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4140105197Ssam				KEY_FREESAV(&sav);
4141105197Ssam			}
4142105197Ssam		}
4143105197Ssam
4144105197Ssam		/* delete entry in DEAD */
4145120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4146105197Ssam			/* sanity check */
4147105197Ssam			if (sav->state != SADB_SASTATE_DEAD) {
4148120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4149120585Ssam					"(queue: %d SA: %d): kill it anyway\n",
4150120585Ssam					__func__,
4151105197Ssam					SADB_SASTATE_DEAD, sav->state));
4152105197Ssam			}
4153105197Ssam			/*
4154105197Ssam			 * do not call key_freesav() here.
4155105197Ssam			 * sav should already be freed, and sav->refcnt
4156105197Ssam			 * shows other references to sav
4157105197Ssam			 * (such as from SPD).
4158105197Ssam			 */
4159105197Ssam		}
4160105197Ssam	}
4161120585Ssam	SAHTREE_UNLOCK();
4162119643Ssam}
4163105197Ssam
4164119643Ssamstatic void
4165119643Ssamkey_flush_acq(time_t now)
4166119643Ssam{
4167105197Ssam	struct secacq *acq, *nextacq;
4168105197Ssam
4169119643Ssam	/* ACQ tree */
4170120585Ssam	ACQ_LOCK();
4171119643Ssam	for (acq = LIST_FIRST(&acqtree); acq != NULL; acq = nextacq) {
4172105197Ssam		nextacq = LIST_NEXT(acq, chain);
4173105197Ssam		if (now - acq->created > key_blockacq_lifetime
4174105197Ssam		 && __LIST_CHAINED(acq)) {
4175105197Ssam			LIST_REMOVE(acq, chain);
4176119643Ssam			free(acq, M_IPSEC_SAQ);
4177105197Ssam		}
4178105197Ssam	}
4179120585Ssam	ACQ_UNLOCK();
4180119643Ssam}
4181105197Ssam
4182119643Ssamstatic void
4183119643Ssamkey_flush_spacq(time_t now)
4184119643Ssam{
4185105197Ssam	struct secspacq *acq, *nextacq;
4186105197Ssam
4187119643Ssam	/* SP ACQ tree */
4188120585Ssam	SPACQ_LOCK();
4189119643Ssam	for (acq = LIST_FIRST(&spacqtree); acq != NULL; acq = nextacq) {
4190105197Ssam		nextacq = LIST_NEXT(acq, chain);
4191105197Ssam		if (now - acq->created > key_blockacq_lifetime
4192105197Ssam		 && __LIST_CHAINED(acq)) {
4193105197Ssam			LIST_REMOVE(acq, chain);
4194119643Ssam			free(acq, M_IPSEC_SAQ);
4195105197Ssam		}
4196105197Ssam	}
4197120585Ssam	SPACQ_UNLOCK();
4198119643Ssam}
4199105197Ssam
4200119643Ssam/*
4201119643Ssam * time handler.
4202119643Ssam * scanning SPD and SAD to check status for each entries,
4203119643Ssam * and do to remove or to expire.
4204119643Ssam * XXX: year 2038 problem may remain.
4205119643Ssam */
4206119643Ssamvoid
4207119643Ssamkey_timehandler(void)
4208119643Ssam{
4209119643Ssam	time_t now = time_second;
4210105197Ssam
4211119643Ssam	key_flush_spd(now);
4212119643Ssam	key_flush_sad(now);
4213119643Ssam	key_flush_acq(now);
4214119643Ssam	key_flush_spacq(now);
4215119643Ssam
4216105197Ssam#ifndef IPSEC_DEBUG2
4217105197Ssam	/* do exchange to tick time !! */
4218105197Ssam	(void)timeout((void *)key_timehandler, (void *)0, hz);
4219105197Ssam#endif /* IPSEC_DEBUG2 */
4220105197Ssam}
4221105197Ssam
4222105197Ssamu_long
4223105197Ssamkey_random()
4224105197Ssam{
4225105197Ssam	u_long value;
4226105197Ssam
4227105197Ssam	key_randomfill(&value, sizeof(value));
4228105197Ssam	return value;
4229105197Ssam}
4230105197Ssam
4231105197Ssamvoid
4232105197Ssamkey_randomfill(p, l)
4233105197Ssam	void *p;
4234105197Ssam	size_t l;
4235105197Ssam{
4236105197Ssam	size_t n;
4237105197Ssam	u_long v;
4238105197Ssam	static int warn = 1;
4239105197Ssam
4240105197Ssam	n = 0;
4241105197Ssam	n = (size_t)read_random(p, (u_int)l);
4242105197Ssam	/* last resort */
4243105197Ssam	while (n < l) {
4244105197Ssam		v = random();
4245105197Ssam		bcopy(&v, (u_int8_t *)p + n,
4246105197Ssam		    l - n < sizeof(v) ? l - n : sizeof(v));
4247105197Ssam		n += sizeof(v);
4248105197Ssam
4249105197Ssam		if (warn) {
4250105197Ssam			printf("WARNING: pseudo-random number generator "
4251105197Ssam			    "used for IPsec processing\n");
4252105197Ssam			warn = 0;
4253105197Ssam		}
4254105197Ssam	}
4255105197Ssam}
4256105197Ssam
4257105197Ssam/*
4258105197Ssam * map SADB_SATYPE_* to IPPROTO_*.
4259105197Ssam * if satype == SADB_SATYPE then satype is mapped to ~0.
4260105197Ssam * OUT:
4261105197Ssam *	0: invalid satype.
4262105197Ssam */
4263105197Ssamstatic u_int16_t
4264105197Ssamkey_satype2proto(satype)
4265105197Ssam	u_int8_t satype;
4266105197Ssam{
4267105197Ssam	switch (satype) {
4268105197Ssam	case SADB_SATYPE_UNSPEC:
4269105197Ssam		return IPSEC_PROTO_ANY;
4270105197Ssam	case SADB_SATYPE_AH:
4271105197Ssam		return IPPROTO_AH;
4272105197Ssam	case SADB_SATYPE_ESP:
4273105197Ssam		return IPPROTO_ESP;
4274105197Ssam	case SADB_X_SATYPE_IPCOMP:
4275105197Ssam		return IPPROTO_IPCOMP;
4276125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
4277125680Sbms		return IPPROTO_TCP;
4278105197Ssam	default:
4279105197Ssam		return 0;
4280105197Ssam	}
4281105197Ssam	/* NOTREACHED */
4282105197Ssam}
4283105197Ssam
4284105197Ssam/*
4285105197Ssam * map IPPROTO_* to SADB_SATYPE_*
4286105197Ssam * OUT:
4287105197Ssam *	0: invalid protocol type.
4288105197Ssam */
4289105197Ssamstatic u_int8_t
4290105197Ssamkey_proto2satype(proto)
4291105197Ssam	u_int16_t proto;
4292105197Ssam{
4293105197Ssam	switch (proto) {
4294105197Ssam	case IPPROTO_AH:
4295105197Ssam		return SADB_SATYPE_AH;
4296105197Ssam	case IPPROTO_ESP:
4297105197Ssam		return SADB_SATYPE_ESP;
4298105197Ssam	case IPPROTO_IPCOMP:
4299105197Ssam		return SADB_X_SATYPE_IPCOMP;
4300125680Sbms	case IPPROTO_TCP:
4301125680Sbms		return SADB_X_SATYPE_TCPSIGNATURE;
4302105197Ssam	default:
4303105197Ssam		return 0;
4304105197Ssam	}
4305105197Ssam	/* NOTREACHED */
4306105197Ssam}
4307105197Ssam
4308105197Ssam/* %%% PF_KEY */
4309105197Ssam/*
4310105197Ssam * SADB_GETSPI processing is to receive
4311105197Ssam *	<base, (SA2), src address, dst address, (SPI range)>
4312105197Ssam * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4313105197Ssam * tree with the status of LARVAL, and send
4314105197Ssam *	<base, SA(*), address(SD)>
4315105197Ssam * to the IKMPd.
4316105197Ssam *
4317105197Ssam * IN:	mhp: pointer to the pointer to each header.
4318105197Ssam * OUT:	NULL if fail.
4319105197Ssam *	other if success, return pointer to the message to send.
4320105197Ssam */
4321105197Ssamstatic int
4322105197Ssamkey_getspi(so, m, mhp)
4323105197Ssam	struct socket *so;
4324105197Ssam	struct mbuf *m;
4325105197Ssam	const struct sadb_msghdr *mhp;
4326105197Ssam{
4327105197Ssam	struct sadb_address *src0, *dst0;
4328105197Ssam	struct secasindex saidx;
4329105197Ssam	struct secashead *newsah;
4330105197Ssam	struct secasvar *newsav;
4331105197Ssam	u_int8_t proto;
4332105197Ssam	u_int32_t spi;
4333105197Ssam	u_int8_t mode;
4334105197Ssam	u_int32_t reqid;
4335105197Ssam	int error;
4336105197Ssam
4337120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4338120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4339120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4340120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4341105197Ssam
4342105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4343105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4344120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4345120585Ssam			__func__));
4346105197Ssam		return key_senderror(so, m, EINVAL);
4347105197Ssam	}
4348105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4349105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4350120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4351120585Ssam			__func__));
4352105197Ssam		return key_senderror(so, m, EINVAL);
4353105197Ssam	}
4354105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4355105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4356105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4357105197Ssam	} else {
4358105197Ssam		mode = IPSEC_MODE_ANY;
4359105197Ssam		reqid = 0;
4360105197Ssam	}
4361105197Ssam
4362105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4363105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4364105197Ssam
4365105197Ssam	/* map satype to proto */
4366105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4367120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4368120585Ssam			__func__));
4369105197Ssam		return key_senderror(so, m, EINVAL);
4370105197Ssam	}
4371105197Ssam
4372105197Ssam	/* make sure if port number is zero. */
4373105197Ssam	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4374105197Ssam	case AF_INET:
4375105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4376105197Ssam		    sizeof(struct sockaddr_in))
4377105197Ssam			return key_senderror(so, m, EINVAL);
4378105197Ssam		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4379105197Ssam		break;
4380105197Ssam	case AF_INET6:
4381105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4382105197Ssam		    sizeof(struct sockaddr_in6))
4383105197Ssam			return key_senderror(so, m, EINVAL);
4384105197Ssam		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4385105197Ssam		break;
4386105197Ssam	default:
4387105197Ssam		; /*???*/
4388105197Ssam	}
4389105197Ssam	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4390105197Ssam	case AF_INET:
4391105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4392105197Ssam		    sizeof(struct sockaddr_in))
4393105197Ssam			return key_senderror(so, m, EINVAL);
4394105197Ssam		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4395105197Ssam		break;
4396105197Ssam	case AF_INET6:
4397105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4398105197Ssam		    sizeof(struct sockaddr_in6))
4399105197Ssam			return key_senderror(so, m, EINVAL);
4400105197Ssam		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4401105197Ssam		break;
4402105197Ssam	default:
4403105197Ssam		; /*???*/
4404105197Ssam	}
4405105197Ssam
4406105197Ssam	/* XXX boundary check against sa_len */
4407105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4408105197Ssam
4409105197Ssam	/* SPI allocation */
4410105197Ssam	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4411105197Ssam	                       &saidx);
4412105197Ssam	if (spi == 0)
4413105197Ssam		return key_senderror(so, m, EINVAL);
4414105197Ssam
4415105197Ssam	/* get a SA index */
4416105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4417105197Ssam		/* create a new SA index */
4418105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4419120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4420105197Ssam			return key_senderror(so, m, ENOBUFS);
4421105197Ssam		}
4422105197Ssam	}
4423105197Ssam
4424105197Ssam	/* get a new SA */
4425105197Ssam	/* XXX rewrite */
4426105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4427105197Ssam	if (newsav == NULL) {
4428105197Ssam		/* XXX don't free new SA index allocated in above. */
4429105197Ssam		return key_senderror(so, m, error);
4430105197Ssam	}
4431105197Ssam
4432105197Ssam	/* set spi */
4433105197Ssam	newsav->spi = htonl(spi);
4434105197Ssam
4435105197Ssam	/* delete the entry in acqtree */
4436105197Ssam	if (mhp->msg->sadb_msg_seq != 0) {
4437105197Ssam		struct secacq *acq;
4438105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4439105197Ssam			/* reset counter in order to deletion by timehandler. */
4440105197Ssam			acq->created = time_second;
4441105197Ssam			acq->count = 0;
4442105197Ssam		}
4443105197Ssam    	}
4444105197Ssam
4445105197Ssam    {
4446105197Ssam	struct mbuf *n, *nn;
4447105197Ssam	struct sadb_sa *m_sa;
4448105197Ssam	struct sadb_msg *newmsg;
4449105197Ssam	int off, len;
4450105197Ssam
4451105197Ssam	/* create new sadb_msg to reply. */
4452105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4453105197Ssam	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4454105197Ssam	if (len > MCLBYTES)
4455105197Ssam		return key_senderror(so, m, ENOBUFS);
4456105197Ssam
4457111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
4458105197Ssam	if (len > MHLEN) {
4459111119Simp		MCLGET(n, M_DONTWAIT);
4460105197Ssam		if ((n->m_flags & M_EXT) == 0) {
4461105197Ssam			m_freem(n);
4462105197Ssam			n = NULL;
4463105197Ssam		}
4464105197Ssam	}
4465105197Ssam	if (!n)
4466105197Ssam		return key_senderror(so, m, ENOBUFS);
4467105197Ssam
4468105197Ssam	n->m_len = len;
4469105197Ssam	n->m_next = NULL;
4470105197Ssam	off = 0;
4471105197Ssam
4472105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4473105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4474105197Ssam
4475105197Ssam	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4476105197Ssam	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4477105197Ssam	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4478105197Ssam	m_sa->sadb_sa_spi = htonl(spi);
4479105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4480105197Ssam
4481120585Ssam	IPSEC_ASSERT(off == len,
4482120585Ssam		("length inconsistency (off %u len %u)", off, len));
4483105197Ssam
4484105197Ssam	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4485105197Ssam	    SADB_EXT_ADDRESS_DST);
4486105197Ssam	if (!n->m_next) {
4487105197Ssam		m_freem(n);
4488105197Ssam		return key_senderror(so, m, ENOBUFS);
4489105197Ssam	}
4490105197Ssam
4491105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
4492105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
4493105197Ssam		if (n == NULL)
4494105197Ssam			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4495105197Ssam	}
4496105197Ssam
4497105197Ssam	n->m_pkthdr.len = 0;
4498105197Ssam	for (nn = n; nn; nn = nn->m_next)
4499105197Ssam		n->m_pkthdr.len += nn->m_len;
4500105197Ssam
4501105197Ssam	newmsg = mtod(n, struct sadb_msg *);
4502105197Ssam	newmsg->sadb_msg_seq = newsav->seq;
4503105197Ssam	newmsg->sadb_msg_errno = 0;
4504105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4505105197Ssam
4506105197Ssam	m_freem(m);
4507105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4508105197Ssam    }
4509105197Ssam}
4510105197Ssam
4511105197Ssam/*
4512105197Ssam * allocating new SPI
4513105197Ssam * called by key_getspi().
4514105197Ssam * OUT:
4515105197Ssam *	0:	failure.
4516105197Ssam *	others: success.
4517105197Ssam */
4518105197Ssamstatic u_int32_t
4519105197Ssamkey_do_getnewspi(spirange, saidx)
4520105197Ssam	struct sadb_spirange *spirange;
4521105197Ssam	struct secasindex *saidx;
4522105197Ssam{
4523105197Ssam	u_int32_t newspi;
4524105197Ssam	u_int32_t min, max;
4525105197Ssam	int count = key_spi_trycnt;
4526105197Ssam
4527105197Ssam	/* set spi range to allocate */
4528105197Ssam	if (spirange != NULL) {
4529105197Ssam		min = spirange->sadb_spirange_min;
4530105197Ssam		max = spirange->sadb_spirange_max;
4531105197Ssam	} else {
4532105197Ssam		min = key_spi_minval;
4533105197Ssam		max = key_spi_maxval;
4534105197Ssam	}
4535105197Ssam	/* IPCOMP needs 2-byte SPI */
4536105197Ssam	if (saidx->proto == IPPROTO_IPCOMP) {
4537105197Ssam		u_int32_t t;
4538105197Ssam		if (min >= 0x10000)
4539105197Ssam			min = 0xffff;
4540105197Ssam		if (max >= 0x10000)
4541105197Ssam			max = 0xffff;
4542105197Ssam		if (min > max) {
4543105197Ssam			t = min; min = max; max = t;
4544105197Ssam		}
4545105197Ssam	}
4546105197Ssam
4547105197Ssam	if (min == max) {
4548105197Ssam		if (key_checkspidup(saidx, min) != NULL) {
4549120585Ssam			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4550120585Ssam				__func__, min));
4551105197Ssam			return 0;
4552105197Ssam		}
4553105197Ssam
4554105197Ssam		count--; /* taking one cost. */
4555105197Ssam		newspi = min;
4556105197Ssam
4557105197Ssam	} else {
4558105197Ssam
4559105197Ssam		/* init SPI */
4560105197Ssam		newspi = 0;
4561105197Ssam
4562105197Ssam		/* when requesting to allocate spi ranged */
4563105197Ssam		while (count--) {
4564105197Ssam			/* generate pseudo-random SPI value ranged. */
4565105197Ssam			newspi = min + (key_random() % (max - min + 1));
4566105197Ssam
4567105197Ssam			if (key_checkspidup(saidx, newspi) == NULL)
4568105197Ssam				break;
4569105197Ssam		}
4570105197Ssam
4571105197Ssam		if (count == 0 || newspi == 0) {
4572120585Ssam			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4573120585Ssam				__func__));
4574105197Ssam			return 0;
4575105197Ssam		}
4576105197Ssam	}
4577105197Ssam
4578105197Ssam	/* statistics */
4579105197Ssam	keystat.getspi_count =
4580105197Ssam		(keystat.getspi_count + key_spi_trycnt - count) / 2;
4581105197Ssam
4582105197Ssam	return newspi;
4583105197Ssam}
4584105197Ssam
4585105197Ssam/*
4586105197Ssam * SADB_UPDATE processing
4587105197Ssam * receive
4588105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4589105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4590105197Ssam * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4591105197Ssam * and send
4592105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4593105197Ssam *       (identity(SD),) (sensitivity)>
4594105197Ssam * to the ikmpd.
4595105197Ssam *
4596105197Ssam * m will always be freed.
4597105197Ssam */
4598105197Ssamstatic int
4599105197Ssamkey_update(so, m, mhp)
4600105197Ssam	struct socket *so;
4601105197Ssam	struct mbuf *m;
4602105197Ssam	const struct sadb_msghdr *mhp;
4603105197Ssam{
4604105197Ssam	struct sadb_sa *sa0;
4605105197Ssam	struct sadb_address *src0, *dst0;
4606105197Ssam	struct secasindex saidx;
4607105197Ssam	struct secashead *sah;
4608105197Ssam	struct secasvar *sav;
4609105197Ssam	u_int16_t proto;
4610105197Ssam	u_int8_t mode;
4611105197Ssam	u_int32_t reqid;
4612105197Ssam	int error;
4613105197Ssam
4614120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4615120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4616120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4617120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4618105197Ssam
4619105197Ssam	/* map satype to proto */
4620105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4621120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4622120585Ssam			__func__));
4623105197Ssam		return key_senderror(so, m, EINVAL);
4624105197Ssam	}
4625105197Ssam
4626105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
4627105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4628105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4629105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4630105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4631105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4632105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4633105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4634105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4635105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4636105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4637120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4638120585Ssam			__func__));
4639105197Ssam		return key_senderror(so, m, EINVAL);
4640105197Ssam	}
4641105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4642105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4643105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4644120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4645120585Ssam			__func__));
4646105197Ssam		return key_senderror(so, m, EINVAL);
4647105197Ssam	}
4648105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4649105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4650105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4651105197Ssam	} else {
4652105197Ssam		mode = IPSEC_MODE_ANY;
4653105197Ssam		reqid = 0;
4654105197Ssam	}
4655105197Ssam	/* XXX boundary checking for other extensions */
4656105197Ssam
4657105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4658105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4659105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4660105197Ssam
4661105197Ssam	/* XXX boundary check against sa_len */
4662105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4663105197Ssam
4664105197Ssam	/* get a SA header */
4665105197Ssam	if ((sah = key_getsah(&saidx)) == NULL) {
4666120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
4667105197Ssam		return key_senderror(so, m, ENOENT);
4668105197Ssam	}
4669105197Ssam
4670105197Ssam	/* set spidx if there */
4671105197Ssam	/* XXX rewrite */
4672105197Ssam	error = key_setident(sah, m, mhp);
4673105197Ssam	if (error)
4674105197Ssam		return key_senderror(so, m, error);
4675105197Ssam
4676105197Ssam	/* find a SA with sequence number. */
4677105197Ssam#ifdef IPSEC_DOSEQCHECK
4678105197Ssam	if (mhp->msg->sadb_msg_seq != 0
4679105197Ssam	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4680120585Ssam		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
4681120585Ssam			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
4682105197Ssam		return key_senderror(so, m, ENOENT);
4683105197Ssam	}
4684105197Ssam#else
4685120585Ssam	SAHTREE_LOCK();
4686120585Ssam	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4687120585Ssam	SAHTREE_UNLOCK();
4688120585Ssam	if (sav == NULL) {
4689120585Ssam		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
4690120585Ssam			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4691105197Ssam		return key_senderror(so, m, EINVAL);
4692105197Ssam	}
4693105197Ssam#endif
4694105197Ssam
4695105197Ssam	/* validity check */
4696105197Ssam	if (sav->sah->saidx.proto != proto) {
4697120585Ssam		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
4698120585Ssam			"(DB=%u param=%u)\n", __func__,
4699120585Ssam			sav->sah->saidx.proto, proto));
4700105197Ssam		return key_senderror(so, m, EINVAL);
4701105197Ssam	}
4702105197Ssam#ifdef IPSEC_DOSEQCHECK
4703105197Ssam	if (sav->spi != sa0->sadb_sa_spi) {
4704120585Ssam		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
4705120585Ssam		    __func__,
4706105197Ssam		    (u_int32_t)ntohl(sav->spi),
4707105197Ssam		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4708105197Ssam		return key_senderror(so, m, EINVAL);
4709105197Ssam	}
4710105197Ssam#endif
4711105197Ssam	if (sav->pid != mhp->msg->sadb_msg_pid) {
4712120585Ssam		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
4713120585Ssam		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
4714105197Ssam		return key_senderror(so, m, EINVAL);
4715105197Ssam	}
4716105197Ssam
4717105197Ssam	/* copy sav values */
4718105197Ssam	error = key_setsaval(sav, m, mhp);
4719105197Ssam	if (error) {
4720105197Ssam		KEY_FREESAV(&sav);
4721105197Ssam		return key_senderror(so, m, error);
4722105197Ssam	}
4723105197Ssam
4724105197Ssam	/* check SA values to be mature. */
4725105197Ssam	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4726105197Ssam		KEY_FREESAV(&sav);
4727105197Ssam		return key_senderror(so, m, 0);
4728105197Ssam	}
4729105197Ssam
4730105197Ssam    {
4731105197Ssam	struct mbuf *n;
4732105197Ssam
4733105197Ssam	/* set msg buf from mhp */
4734105197Ssam	n = key_getmsgbuf_x1(m, mhp);
4735105197Ssam	if (n == NULL) {
4736120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4737105197Ssam		return key_senderror(so, m, ENOBUFS);
4738105197Ssam	}
4739105197Ssam
4740105197Ssam	m_freem(m);
4741105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4742105197Ssam    }
4743105197Ssam}
4744105197Ssam
4745105197Ssam/*
4746105197Ssam * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4747105197Ssam * only called by key_update().
4748105197Ssam * OUT:
4749105197Ssam *	NULL	: not found
4750105197Ssam *	others	: found, pointer to a SA.
4751105197Ssam */
4752105197Ssam#ifdef IPSEC_DOSEQCHECK
4753105197Ssamstatic struct secasvar *
4754105197Ssamkey_getsavbyseq(sah, seq)
4755105197Ssam	struct secashead *sah;
4756105197Ssam	u_int32_t seq;
4757105197Ssam{
4758105197Ssam	struct secasvar *sav;
4759105197Ssam	u_int state;
4760105197Ssam
4761105197Ssam	state = SADB_SASTATE_LARVAL;
4762105197Ssam
4763105197Ssam	/* search SAD with sequence number ? */
4764105197Ssam	LIST_FOREACH(sav, &sah->savtree[state], chain) {
4765105197Ssam
4766120585Ssam		KEY_CHKSASTATE(state, sav->state, __func__);
4767105197Ssam
4768105197Ssam		if (sav->seq == seq) {
4769105197Ssam			SA_ADDREF(sav);
4770105197Ssam			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4771120585Ssam				printf("DP %s cause refcnt++:%d SA:%p\n",
4772120585Ssam					__func__, sav->refcnt, sav));
4773105197Ssam			return sav;
4774105197Ssam		}
4775105197Ssam	}
4776105197Ssam
4777105197Ssam	return NULL;
4778105197Ssam}
4779105197Ssam#endif
4780105197Ssam
4781105197Ssam/*
4782105197Ssam * SADB_ADD processing
4783108533Sschweikh * add an entry to SA database, when received
4784105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4785105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4786105197Ssam * from the ikmpd,
4787105197Ssam * and send
4788105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4789105197Ssam *       (identity(SD),) (sensitivity)>
4790105197Ssam * to the ikmpd.
4791105197Ssam *
4792105197Ssam * IGNORE identity and sensitivity messages.
4793105197Ssam *
4794105197Ssam * m will always be freed.
4795105197Ssam */
4796105197Ssamstatic int
4797105197Ssamkey_add(so, m, mhp)
4798105197Ssam	struct socket *so;
4799105197Ssam	struct mbuf *m;
4800105197Ssam	const struct sadb_msghdr *mhp;
4801105197Ssam{
4802105197Ssam	struct sadb_sa *sa0;
4803105197Ssam	struct sadb_address *src0, *dst0;
4804105197Ssam	struct secasindex saidx;
4805105197Ssam	struct secashead *newsah;
4806105197Ssam	struct secasvar *newsav;
4807105197Ssam	u_int16_t proto;
4808105197Ssam	u_int8_t mode;
4809105197Ssam	u_int32_t reqid;
4810105197Ssam	int error;
4811105197Ssam
4812120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4813120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4814120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4815120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4816105197Ssam
4817105197Ssam	/* map satype to proto */
4818105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4819120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4820120585Ssam			__func__));
4821105197Ssam		return key_senderror(so, m, EINVAL);
4822105197Ssam	}
4823105197Ssam
4824105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
4825105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4826105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4827105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4828105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4829105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4830105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4831105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4832105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4833105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4834105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4835120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4836120585Ssam			__func__));
4837105197Ssam		return key_senderror(so, m, EINVAL);
4838105197Ssam	}
4839105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4840105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4841105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4842105197Ssam		/* XXX need more */
4843120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4844120585Ssam			__func__));
4845105197Ssam		return key_senderror(so, m, EINVAL);
4846105197Ssam	}
4847105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4848105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4849105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4850105197Ssam	} else {
4851105197Ssam		mode = IPSEC_MODE_ANY;
4852105197Ssam		reqid = 0;
4853105197Ssam	}
4854105197Ssam
4855105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4856105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4857105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4858105197Ssam
4859105197Ssam	/* XXX boundary check against sa_len */
4860105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4861105197Ssam
4862105197Ssam	/* get a SA header */
4863105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4864105197Ssam		/* create a new SA header */
4865105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4866120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4867105197Ssam			return key_senderror(so, m, ENOBUFS);
4868105197Ssam		}
4869105197Ssam	}
4870105197Ssam
4871105197Ssam	/* set spidx if there */
4872105197Ssam	/* XXX rewrite */
4873105197Ssam	error = key_setident(newsah, m, mhp);
4874105197Ssam	if (error) {
4875105197Ssam		return key_senderror(so, m, error);
4876105197Ssam	}
4877105197Ssam
4878105197Ssam	/* create new SA entry. */
4879105197Ssam	/* We can create new SA only if SPI is differenct. */
4880120585Ssam	SAHTREE_LOCK();
4881120585Ssam	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
4882120585Ssam	SAHTREE_UNLOCK();
4883120585Ssam	if (newsav != NULL) {
4884120585Ssam		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
4885105197Ssam		return key_senderror(so, m, EEXIST);
4886105197Ssam	}
4887105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4888105197Ssam	if (newsav == NULL) {
4889105197Ssam		return key_senderror(so, m, error);
4890105197Ssam	}
4891105197Ssam
4892105197Ssam	/* check SA values to be mature. */
4893105197Ssam	if ((error = key_mature(newsav)) != 0) {
4894105197Ssam		KEY_FREESAV(&newsav);
4895105197Ssam		return key_senderror(so, m, error);
4896105197Ssam	}
4897105197Ssam
4898105197Ssam	/*
4899105197Ssam	 * don't call key_freesav() here, as we would like to keep the SA
4900105197Ssam	 * in the database on success.
4901105197Ssam	 */
4902105197Ssam
4903105197Ssam    {
4904105197Ssam	struct mbuf *n;
4905105197Ssam
4906105197Ssam	/* set msg buf from mhp */
4907105197Ssam	n = key_getmsgbuf_x1(m, mhp);
4908105197Ssam	if (n == NULL) {
4909120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4910105197Ssam		return key_senderror(so, m, ENOBUFS);
4911105197Ssam	}
4912105197Ssam
4913105197Ssam	m_freem(m);
4914105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4915105197Ssam    }
4916105197Ssam}
4917105197Ssam
4918105197Ssam/* m is retained */
4919105197Ssamstatic int
4920105197Ssamkey_setident(sah, m, mhp)
4921105197Ssam	struct secashead *sah;
4922105197Ssam	struct mbuf *m;
4923105197Ssam	const struct sadb_msghdr *mhp;
4924105197Ssam{
4925105197Ssam	const struct sadb_ident *idsrc, *iddst;
4926105197Ssam	int idsrclen, iddstlen;
4927105197Ssam
4928120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
4929120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4930120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4931120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4932105197Ssam
4933105197Ssam	/* don't make buffer if not there */
4934105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
4935105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4936105197Ssam		sah->idents = NULL;
4937105197Ssam		sah->identd = NULL;
4938105197Ssam		return 0;
4939105197Ssam	}
4940105197Ssam
4941105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
4942105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4943120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
4944105197Ssam		return EINVAL;
4945105197Ssam	}
4946105197Ssam
4947105197Ssam	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
4948105197Ssam	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
4949105197Ssam	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
4950105197Ssam	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
4951105197Ssam
4952105197Ssam	/* validity check */
4953105197Ssam	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
4954120585Ssam		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
4955105197Ssam		return EINVAL;
4956105197Ssam	}
4957105197Ssam
4958105197Ssam	switch (idsrc->sadb_ident_type) {
4959105197Ssam	case SADB_IDENTTYPE_PREFIX:
4960105197Ssam	case SADB_IDENTTYPE_FQDN:
4961105197Ssam	case SADB_IDENTTYPE_USERFQDN:
4962105197Ssam	default:
4963105197Ssam		/* XXX do nothing */
4964105197Ssam		sah->idents = NULL;
4965105197Ssam		sah->identd = NULL;
4966105197Ssam	 	return 0;
4967105197Ssam	}
4968105197Ssam
4969105197Ssam	/* make structure */
4970119643Ssam	sah->idents = malloc(idsrclen, M_IPSEC_MISC, M_NOWAIT);
4971105197Ssam	if (sah->idents == NULL) {
4972120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4973105197Ssam		return ENOBUFS;
4974105197Ssam	}
4975119643Ssam	sah->identd = malloc(iddstlen, M_IPSEC_MISC, M_NOWAIT);
4976105197Ssam	if (sah->identd == NULL) {
4977119643Ssam		free(sah->idents, M_IPSEC_MISC);
4978105197Ssam		sah->idents = NULL;
4979120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4980105197Ssam		return ENOBUFS;
4981105197Ssam	}
4982105197Ssam	bcopy(idsrc, sah->idents, idsrclen);
4983105197Ssam	bcopy(iddst, sah->identd, iddstlen);
4984105197Ssam
4985105197Ssam	return 0;
4986105197Ssam}
4987105197Ssam
4988105197Ssam/*
4989105197Ssam * m will not be freed on return.
4990105197Ssam * it is caller's responsibility to free the result.
4991105197Ssam */
4992105197Ssamstatic struct mbuf *
4993105197Ssamkey_getmsgbuf_x1(m, mhp)
4994105197Ssam	struct mbuf *m;
4995105197Ssam	const struct sadb_msghdr *mhp;
4996105197Ssam{
4997105197Ssam	struct mbuf *n;
4998105197Ssam
4999120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5000120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5001120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5002105197Ssam
5003105197Ssam	/* create new sadb_msg to reply. */
5004105197Ssam	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5005105197Ssam	    SADB_EXT_SA, SADB_X_EXT_SA2,
5006105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5007105197Ssam	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5008105197Ssam	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5009105197Ssam	if (!n)
5010105197Ssam		return NULL;
5011105197Ssam
5012105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5013105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5014105197Ssam		if (n == NULL)
5015105197Ssam			return NULL;
5016105197Ssam	}
5017105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5018105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_len =
5019105197Ssam	    PFKEY_UNIT64(n->m_pkthdr.len);
5020105197Ssam
5021105197Ssam	return n;
5022105197Ssam}
5023105197Ssam
5024105197Ssamstatic int key_delete_all __P((struct socket *, struct mbuf *,
5025105197Ssam	const struct sadb_msghdr *, u_int16_t));
5026105197Ssam
5027105197Ssam/*
5028105197Ssam * SADB_DELETE processing
5029105197Ssam * receive
5030105197Ssam *   <base, SA(*), address(SD)>
5031105197Ssam * from the ikmpd, and set SADB_SASTATE_DEAD,
5032105197Ssam * and send,
5033105197Ssam *   <base, SA(*), address(SD)>
5034105197Ssam * to the ikmpd.
5035105197Ssam *
5036105197Ssam * m will always be freed.
5037105197Ssam */
5038105197Ssamstatic int
5039105197Ssamkey_delete(so, m, mhp)
5040105197Ssam	struct socket *so;
5041105197Ssam	struct mbuf *m;
5042105197Ssam	const struct sadb_msghdr *mhp;
5043105197Ssam{
5044105197Ssam	struct sadb_sa *sa0;
5045105197Ssam	struct sadb_address *src0, *dst0;
5046105197Ssam	struct secasindex saidx;
5047105197Ssam	struct secashead *sah;
5048105197Ssam	struct secasvar *sav = NULL;
5049105197Ssam	u_int16_t proto;
5050105197Ssam
5051120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5052120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5053120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5054120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5055105197Ssam
5056105197Ssam	/* map satype to proto */
5057105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5058120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5059120585Ssam			__func__));
5060105197Ssam		return key_senderror(so, m, EINVAL);
5061105197Ssam	}
5062105197Ssam
5063105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5064105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5065120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5066120585Ssam			__func__));
5067105197Ssam		return key_senderror(so, m, EINVAL);
5068105197Ssam	}
5069105197Ssam
5070105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5071105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5072120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5073120585Ssam			__func__));
5074105197Ssam		return key_senderror(so, m, EINVAL);
5075105197Ssam	}
5076105197Ssam
5077105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL) {
5078105197Ssam		/*
5079105197Ssam		 * Caller wants us to delete all non-LARVAL SAs
5080105197Ssam		 * that match the src/dst.  This is used during
5081105197Ssam		 * IKE INITIAL-CONTACT.
5082105197Ssam		 */
5083120585Ssam		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5084105197Ssam		return key_delete_all(so, m, mhp, proto);
5085105197Ssam	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5086120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5087120585Ssam			__func__));
5088105197Ssam		return key_senderror(so, m, EINVAL);
5089105197Ssam	}
5090105197Ssam
5091105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5092105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5093105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5094105197Ssam
5095105197Ssam	/* XXX boundary check against sa_len */
5096105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5097105197Ssam
5098105197Ssam	/* get a SA header */
5099120585Ssam	SAHTREE_LOCK();
5100105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
5101105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5102105197Ssam			continue;
5103105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5104105197Ssam			continue;
5105105197Ssam
5106105197Ssam		/* get a SA with SPI. */
5107105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5108105197Ssam		if (sav)
5109105197Ssam			break;
5110105197Ssam	}
5111105197Ssam	if (sah == NULL) {
5112120585Ssam		SAHTREE_UNLOCK();
5113120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5114105197Ssam		return key_senderror(so, m, ENOENT);
5115105197Ssam	}
5116105197Ssam
5117105197Ssam	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5118120585Ssam	SAHTREE_UNLOCK();
5119105197Ssam	KEY_FREESAV(&sav);
5120105197Ssam
5121105197Ssam    {
5122105197Ssam	struct mbuf *n;
5123105197Ssam	struct sadb_msg *newmsg;
5124105197Ssam
5125105197Ssam	/* create new sadb_msg to reply. */
5126105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5127105197Ssam	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5128105197Ssam	if (!n)
5129105197Ssam		return key_senderror(so, m, ENOBUFS);
5130105197Ssam
5131105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5132105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5133105197Ssam		if (n == NULL)
5134105197Ssam			return key_senderror(so, m, ENOBUFS);
5135105197Ssam	}
5136105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5137105197Ssam	newmsg->sadb_msg_errno = 0;
5138105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5139105197Ssam
5140105197Ssam	m_freem(m);
5141105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5142105197Ssam    }
5143105197Ssam}
5144105197Ssam
5145105197Ssam/*
5146105197Ssam * delete all SAs for src/dst.  Called from key_delete().
5147105197Ssam */
5148105197Ssamstatic int
5149105197Ssamkey_delete_all(so, m, mhp, proto)
5150105197Ssam	struct socket *so;
5151105197Ssam	struct mbuf *m;
5152105197Ssam	const struct sadb_msghdr *mhp;
5153105197Ssam	u_int16_t proto;
5154105197Ssam{
5155105197Ssam	struct sadb_address *src0, *dst0;
5156105197Ssam	struct secasindex saidx;
5157105197Ssam	struct secashead *sah;
5158105197Ssam	struct secasvar *sav, *nextsav;
5159105197Ssam	u_int stateidx, state;
5160105197Ssam
5161105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5162105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5163105197Ssam
5164105197Ssam	/* XXX boundary check against sa_len */
5165105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5166105197Ssam
5167120585Ssam	SAHTREE_LOCK();
5168105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
5169105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5170105197Ssam			continue;
5171105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5172105197Ssam			continue;
5173105197Ssam
5174105197Ssam		/* Delete all non-LARVAL SAs. */
5175105197Ssam		for (stateidx = 0;
5176105197Ssam		     stateidx < _ARRAYLEN(saorder_state_alive);
5177105197Ssam		     stateidx++) {
5178105197Ssam			state = saorder_state_alive[stateidx];
5179105197Ssam			if (state == SADB_SASTATE_LARVAL)
5180105197Ssam				continue;
5181105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
5182105197Ssam			     sav != NULL; sav = nextsav) {
5183105197Ssam				nextsav = LIST_NEXT(sav, chain);
5184105197Ssam				/* sanity check */
5185105197Ssam				if (sav->state != state) {
5186120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
5187120585Ssam						"sav->state (queue %d SA %d)\n",
5188120585Ssam						__func__, state, sav->state));
5189105197Ssam					continue;
5190105197Ssam				}
5191105197Ssam
5192105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5193105197Ssam				KEY_FREESAV(&sav);
5194105197Ssam			}
5195105197Ssam		}
5196105197Ssam	}
5197120585Ssam	SAHTREE_UNLOCK();
5198105197Ssam    {
5199105197Ssam	struct mbuf *n;
5200105197Ssam	struct sadb_msg *newmsg;
5201105197Ssam
5202105197Ssam	/* create new sadb_msg to reply. */
5203105197Ssam	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5204105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5205105197Ssam	if (!n)
5206105197Ssam		return key_senderror(so, m, ENOBUFS);
5207105197Ssam
5208105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5209105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5210105197Ssam		if (n == NULL)
5211105197Ssam			return key_senderror(so, m, ENOBUFS);
5212105197Ssam	}
5213105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5214105197Ssam	newmsg->sadb_msg_errno = 0;
5215105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5216105197Ssam
5217105197Ssam	m_freem(m);
5218105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5219105197Ssam    }
5220105197Ssam}
5221105197Ssam
5222105197Ssam/*
5223105197Ssam * SADB_GET processing
5224105197Ssam * receive
5225105197Ssam *   <base, SA(*), address(SD)>
5226105197Ssam * from the ikmpd, and get a SP and a SA to respond,
5227105197Ssam * and send,
5228105197Ssam *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5229105197Ssam *       (identity(SD),) (sensitivity)>
5230105197Ssam * to the ikmpd.
5231105197Ssam *
5232105197Ssam * m will always be freed.
5233105197Ssam */
5234105197Ssamstatic int
5235105197Ssamkey_get(so, m, mhp)
5236105197Ssam	struct socket *so;
5237105197Ssam	struct mbuf *m;
5238105197Ssam	const struct sadb_msghdr *mhp;
5239105197Ssam{
5240105197Ssam	struct sadb_sa *sa0;
5241105197Ssam	struct sadb_address *src0, *dst0;
5242105197Ssam	struct secasindex saidx;
5243105197Ssam	struct secashead *sah;
5244105197Ssam	struct secasvar *sav = NULL;
5245105197Ssam	u_int16_t proto;
5246105197Ssam
5247120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5248120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5249120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5250120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5251105197Ssam
5252105197Ssam	/* map satype to proto */
5253105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5254120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5255120585Ssam			__func__));
5256105197Ssam		return key_senderror(so, m, EINVAL);
5257105197Ssam	}
5258105197Ssam
5259105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5260105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5261105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5262120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5263120585Ssam			__func__));
5264105197Ssam		return key_senderror(so, m, EINVAL);
5265105197Ssam	}
5266105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5267105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5268105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5269120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5270120585Ssam			__func__));
5271105197Ssam		return key_senderror(so, m, EINVAL);
5272105197Ssam	}
5273105197Ssam
5274105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5275105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5276105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5277105197Ssam
5278105197Ssam	/* XXX boundary check against sa_len */
5279105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5280105197Ssam
5281105197Ssam	/* get a SA header */
5282120585Ssam	SAHTREE_LOCK();
5283105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
5284105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5285105197Ssam			continue;
5286105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5287105197Ssam			continue;
5288105197Ssam
5289105197Ssam		/* get a SA with SPI. */
5290105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5291105197Ssam		if (sav)
5292105197Ssam			break;
5293105197Ssam	}
5294120585Ssam	SAHTREE_UNLOCK();
5295105197Ssam	if (sah == NULL) {
5296120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5297105197Ssam		return key_senderror(so, m, ENOENT);
5298105197Ssam	}
5299105197Ssam
5300105197Ssam    {
5301105197Ssam	struct mbuf *n;
5302105197Ssam	u_int8_t satype;
5303105197Ssam
5304105197Ssam	/* map proto to satype */
5305105197Ssam	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5306120585Ssam		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5307120585Ssam			__func__));
5308105197Ssam		return key_senderror(so, m, EINVAL);
5309105197Ssam	}
5310105197Ssam
5311105197Ssam	/* create new sadb_msg to reply. */
5312105197Ssam	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5313105197Ssam	    mhp->msg->sadb_msg_pid);
5314105197Ssam	if (!n)
5315105197Ssam		return key_senderror(so, m, ENOBUFS);
5316105197Ssam
5317105197Ssam	m_freem(m);
5318105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5319105197Ssam    }
5320105197Ssam}
5321105197Ssam
5322105197Ssam/* XXX make it sysctl-configurable? */
5323105197Ssamstatic void
5324105197Ssamkey_getcomb_setlifetime(comb)
5325105197Ssam	struct sadb_comb *comb;
5326105197Ssam{
5327105197Ssam
5328105197Ssam	comb->sadb_comb_soft_allocations = 1;
5329105197Ssam	comb->sadb_comb_hard_allocations = 1;
5330105197Ssam	comb->sadb_comb_soft_bytes = 0;
5331105197Ssam	comb->sadb_comb_hard_bytes = 0;
5332105197Ssam	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5333105197Ssam	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5334105197Ssam	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5335105197Ssam	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5336105197Ssam}
5337105197Ssam
5338105197Ssam/*
5339105197Ssam * XXX reorder combinations by preference
5340105197Ssam * XXX no idea if the user wants ESP authentication or not
5341105197Ssam */
5342105197Ssamstatic struct mbuf *
5343105197Ssamkey_getcomb_esp()
5344105197Ssam{
5345105197Ssam	struct sadb_comb *comb;
5346105197Ssam	struct enc_xform *algo;
5347105197Ssam	struct mbuf *result = NULL, *m, *n;
5348105197Ssam	int encmin;
5349105197Ssam	int i, off, o;
5350105197Ssam	int totlen;
5351105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5352105197Ssam
5353105197Ssam	m = NULL;
5354105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
5355105197Ssam		algo = esp_algorithm_lookup(i);
5356105197Ssam		if (algo == NULL)
5357105197Ssam			continue;
5358105197Ssam
5359105197Ssam		/* discard algorithms with key size smaller than system min */
5360105197Ssam		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
5361105197Ssam			continue;
5362105197Ssam		if (_BITS(algo->minkey) < ipsec_esp_keymin)
5363105197Ssam			encmin = ipsec_esp_keymin;
5364105197Ssam		else
5365105197Ssam			encmin = _BITS(algo->minkey);
5366105197Ssam
5367105197Ssam		if (ipsec_esp_auth)
5368105197Ssam			m = key_getcomb_ah();
5369105197Ssam		else {
5370120585Ssam			IPSEC_ASSERT(l <= MLEN,
5371120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5372111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5373105197Ssam			if (m) {
5374105197Ssam				M_ALIGN(m, l);
5375105197Ssam				m->m_len = l;
5376105197Ssam				m->m_next = NULL;
5377105197Ssam				bzero(mtod(m, caddr_t), m->m_len);
5378105197Ssam			}
5379105197Ssam		}
5380105197Ssam		if (!m)
5381105197Ssam			goto fail;
5382105197Ssam
5383105197Ssam		totlen = 0;
5384105197Ssam		for (n = m; n; n = n->m_next)
5385105197Ssam			totlen += n->m_len;
5386120585Ssam		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
5387105197Ssam
5388105197Ssam		for (off = 0; off < totlen; off += l) {
5389105197Ssam			n = m_pulldown(m, off, l, &o);
5390105197Ssam			if (!n) {
5391105197Ssam				/* m is already freed */
5392105197Ssam				goto fail;
5393105197Ssam			}
5394105197Ssam			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5395105197Ssam			bzero(comb, sizeof(*comb));
5396105197Ssam			key_getcomb_setlifetime(comb);
5397105197Ssam			comb->sadb_comb_encrypt = i;
5398105197Ssam			comb->sadb_comb_encrypt_minbits = encmin;
5399105197Ssam			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5400105197Ssam		}
5401105197Ssam
5402105197Ssam		if (!result)
5403105197Ssam			result = m;
5404105197Ssam		else
5405105197Ssam			m_cat(result, m);
5406105197Ssam	}
5407105197Ssam
5408105197Ssam	return result;
5409105197Ssam
5410105197Ssam fail:
5411105197Ssam	if (result)
5412105197Ssam		m_freem(result);
5413105197Ssam	return NULL;
5414105197Ssam}
5415105197Ssam
5416105197Ssamstatic void
5417105197Ssamkey_getsizes_ah(
5418105197Ssam	const struct auth_hash *ah,
5419105197Ssam	int alg,
5420105197Ssam	u_int16_t* min,
5421105197Ssam	u_int16_t* max)
5422105197Ssam{
5423105197Ssam	*min = *max = ah->keysize;
5424105197Ssam	if (ah->keysize == 0) {
5425105197Ssam		/*
5426105197Ssam		 * Transform takes arbitrary key size but algorithm
5427105197Ssam		 * key size is restricted.  Enforce this here.
5428105197Ssam		 */
5429105197Ssam		switch (alg) {
5430105197Ssam		case SADB_X_AALG_MD5:	*min = *max = 16; break;
5431105197Ssam		case SADB_X_AALG_SHA:	*min = *max = 20; break;
5432105197Ssam		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
5433105197Ssam		default:
5434120585Ssam			DPRINTF(("%s: unknown AH algorithm %u\n",
5435120585Ssam				__func__, alg));
5436105197Ssam			break;
5437105197Ssam		}
5438105197Ssam	}
5439105197Ssam}
5440105197Ssam
5441105197Ssam/*
5442105197Ssam * XXX reorder combinations by preference
5443105197Ssam */
5444105197Ssamstatic struct mbuf *
5445105197Ssamkey_getcomb_ah()
5446105197Ssam{
5447105197Ssam	struct sadb_comb *comb;
5448105197Ssam	struct auth_hash *algo;
5449105197Ssam	struct mbuf *m;
5450105197Ssam	u_int16_t minkeysize, maxkeysize;
5451105197Ssam	int i;
5452105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5453105197Ssam
5454105197Ssam	m = NULL;
5455105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
5456105197Ssam#if 1
5457105197Ssam		/* we prefer HMAC algorithms, not old algorithms */
5458105197Ssam		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5459105197Ssam			continue;
5460105197Ssam#endif
5461105197Ssam		algo = ah_algorithm_lookup(i);
5462105197Ssam		if (!algo)
5463105197Ssam			continue;
5464105197Ssam		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5465105197Ssam		/* discard algorithms with key size smaller than system min */
5466105197Ssam		if (_BITS(minkeysize) < ipsec_ah_keymin)
5467105197Ssam			continue;
5468105197Ssam
5469105197Ssam		if (!m) {
5470120585Ssam			IPSEC_ASSERT(l <= MLEN,
5471120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5472111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5473105197Ssam			if (m) {
5474105197Ssam				M_ALIGN(m, l);
5475105197Ssam				m->m_len = l;
5476105197Ssam				m->m_next = NULL;
5477105197Ssam			}
5478105197Ssam		} else
5479111119Simp			M_PREPEND(m, l, M_DONTWAIT);
5480105197Ssam		if (!m)
5481105197Ssam			return NULL;
5482105197Ssam
5483105197Ssam		comb = mtod(m, struct sadb_comb *);
5484105197Ssam		bzero(comb, sizeof(*comb));
5485105197Ssam		key_getcomb_setlifetime(comb);
5486105197Ssam		comb->sadb_comb_auth = i;
5487105197Ssam		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5488105197Ssam		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5489105197Ssam	}
5490105197Ssam
5491105197Ssam	return m;
5492105197Ssam}
5493105197Ssam
5494105197Ssam/*
5495105197Ssam * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5496105197Ssam * XXX reorder combinations by preference
5497105197Ssam */
5498105197Ssamstatic struct mbuf *
5499105197Ssamkey_getcomb_ipcomp()
5500105197Ssam{
5501105197Ssam	struct sadb_comb *comb;
5502105197Ssam	struct comp_algo *algo;
5503105197Ssam	struct mbuf *m;
5504105197Ssam	int i;
5505105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5506105197Ssam
5507105197Ssam	m = NULL;
5508105197Ssam	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5509105197Ssam		algo = ipcomp_algorithm_lookup(i);
5510105197Ssam		if (!algo)
5511105197Ssam			continue;
5512105197Ssam
5513105197Ssam		if (!m) {
5514120585Ssam			IPSEC_ASSERT(l <= MLEN,
5515120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5516111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5517105197Ssam			if (m) {
5518105197Ssam				M_ALIGN(m, l);
5519105197Ssam				m->m_len = l;
5520105197Ssam				m->m_next = NULL;
5521105197Ssam			}
5522105197Ssam		} else
5523111119Simp			M_PREPEND(m, l, M_DONTWAIT);
5524105197Ssam		if (!m)
5525105197Ssam			return NULL;
5526105197Ssam
5527105197Ssam		comb = mtod(m, struct sadb_comb *);
5528105197Ssam		bzero(comb, sizeof(*comb));
5529105197Ssam		key_getcomb_setlifetime(comb);
5530105197Ssam		comb->sadb_comb_encrypt = i;
5531105197Ssam		/* what should we set into sadb_comb_*_{min,max}bits? */
5532105197Ssam	}
5533105197Ssam
5534105197Ssam	return m;
5535105197Ssam}
5536105197Ssam
5537105197Ssam/*
5538105197Ssam * XXX no way to pass mode (transport/tunnel) to userland
5539105197Ssam * XXX replay checking?
5540105197Ssam * XXX sysctl interface to ipsec_{ah,esp}_keymin
5541105197Ssam */
5542105197Ssamstatic struct mbuf *
5543105197Ssamkey_getprop(saidx)
5544105197Ssam	const struct secasindex *saidx;
5545105197Ssam{
5546105197Ssam	struct sadb_prop *prop;
5547105197Ssam	struct mbuf *m, *n;
5548105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5549105197Ssam	int totlen;
5550105197Ssam
5551105197Ssam	switch (saidx->proto)  {
5552105197Ssam	case IPPROTO_ESP:
5553105197Ssam		m = key_getcomb_esp();
5554105197Ssam		break;
5555105197Ssam	case IPPROTO_AH:
5556105197Ssam		m = key_getcomb_ah();
5557105197Ssam		break;
5558105197Ssam	case IPPROTO_IPCOMP:
5559105197Ssam		m = key_getcomb_ipcomp();
5560105197Ssam		break;
5561105197Ssam	default:
5562105197Ssam		return NULL;
5563105197Ssam	}
5564105197Ssam
5565105197Ssam	if (!m)
5566105197Ssam		return NULL;
5567111119Simp	M_PREPEND(m, l, M_DONTWAIT);
5568105197Ssam	if (!m)
5569105197Ssam		return NULL;
5570105197Ssam
5571105197Ssam	totlen = 0;
5572105197Ssam	for (n = m; n; n = n->m_next)
5573105197Ssam		totlen += n->m_len;
5574105197Ssam
5575105197Ssam	prop = mtod(m, struct sadb_prop *);
5576105197Ssam	bzero(prop, sizeof(*prop));
5577105197Ssam	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5578105197Ssam	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5579105197Ssam	prop->sadb_prop_replay = 32;	/* XXX */
5580105197Ssam
5581105197Ssam	return m;
5582105197Ssam}
5583105197Ssam
5584105197Ssam/*
5585105197Ssam * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5586105197Ssam * send
5587105197Ssam *   <base, SA, address(SD), (address(P)), x_policy,
5588105197Ssam *       (identity(SD),) (sensitivity,) proposal>
5589105197Ssam * to KMD, and expect to receive
5590105197Ssam *   <base> with SADB_ACQUIRE if error occured,
5591105197Ssam * or
5592105197Ssam *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5593105197Ssam * from KMD by PF_KEY.
5594105197Ssam *
5595105197Ssam * XXX x_policy is outside of RFC2367 (KAME extension).
5596105197Ssam * XXX sensitivity is not supported.
5597105197Ssam * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5598105197Ssam * see comment for key_getcomb_ipcomp().
5599105197Ssam *
5600105197Ssam * OUT:
5601105197Ssam *    0     : succeed
5602105197Ssam *    others: error number
5603105197Ssam */
5604105197Ssamstatic int
5605105197Ssamkey_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5606105197Ssam{
5607105197Ssam	struct mbuf *result = NULL, *m;
5608105197Ssam	struct secacq *newacq;
5609105197Ssam	u_int8_t satype;
5610105197Ssam	int error = -1;
5611105197Ssam	u_int32_t seq;
5612105197Ssam
5613120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
5614105197Ssam	satype = key_proto2satype(saidx->proto);
5615120585Ssam	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
5616105197Ssam
5617105197Ssam	/*
5618105197Ssam	 * We never do anything about acquirng SA.  There is anather
5619105197Ssam	 * solution that kernel blocks to send SADB_ACQUIRE message until
5620105197Ssam	 * getting something message from IKEd.  In later case, to be
5621105197Ssam	 * managed with ACQUIRING list.
5622105197Ssam	 */
5623108533Sschweikh	/* Get an entry to check whether sending message or not. */
5624105197Ssam	if ((newacq = key_getacq(saidx)) != NULL) {
5625105197Ssam		if (key_blockacq_count < newacq->count) {
5626105197Ssam			/* reset counter and do send message. */
5627105197Ssam			newacq->count = 0;
5628105197Ssam		} else {
5629105197Ssam			/* increment counter and do nothing. */
5630105197Ssam			newacq->count++;
5631105197Ssam			return 0;
5632105197Ssam		}
5633105197Ssam	} else {
5634105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
5635105197Ssam		if ((newacq = key_newacq(saidx)) == NULL)
5636105197Ssam			return ENOBUFS;
5637105197Ssam	}
5638105197Ssam
5639105197Ssam
5640105197Ssam	seq = newacq->seq;
5641105197Ssam	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5642105197Ssam	if (!m) {
5643105197Ssam		error = ENOBUFS;
5644105197Ssam		goto fail;
5645105197Ssam	}
5646105197Ssam	result = m;
5647105197Ssam
5648105197Ssam	/* set sadb_address for saidx's. */
5649105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5650105197Ssam	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5651105197Ssam	if (!m) {
5652105197Ssam		error = ENOBUFS;
5653105197Ssam		goto fail;
5654105197Ssam	}
5655105197Ssam	m_cat(result, m);
5656105197Ssam
5657105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5658105197Ssam	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5659105197Ssam	if (!m) {
5660105197Ssam		error = ENOBUFS;
5661105197Ssam		goto fail;
5662105197Ssam	}
5663105197Ssam	m_cat(result, m);
5664105197Ssam
5665105197Ssam	/* XXX proxy address (optional) */
5666105197Ssam
5667105197Ssam	/* set sadb_x_policy */
5668105197Ssam	if (sp) {
5669105197Ssam		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5670105197Ssam		if (!m) {
5671105197Ssam			error = ENOBUFS;
5672105197Ssam			goto fail;
5673105197Ssam		}
5674105197Ssam		m_cat(result, m);
5675105197Ssam	}
5676105197Ssam
5677105197Ssam	/* XXX identity (optional) */
5678105197Ssam#if 0
5679105197Ssam	if (idexttype && fqdn) {
5680105197Ssam		/* create identity extension (FQDN) */
5681105197Ssam		struct sadb_ident *id;
5682105197Ssam		int fqdnlen;
5683105197Ssam
5684105197Ssam		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
5685105197Ssam		id = (struct sadb_ident *)p;
5686105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5687105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5688105197Ssam		id->sadb_ident_exttype = idexttype;
5689105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5690105197Ssam		bcopy(fqdn, id + 1, fqdnlen);
5691105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5692105197Ssam	}
5693105197Ssam
5694105197Ssam	if (idexttype) {
5695105197Ssam		/* create identity extension (USERFQDN) */
5696105197Ssam		struct sadb_ident *id;
5697105197Ssam		int userfqdnlen;
5698105197Ssam
5699105197Ssam		if (userfqdn) {
5700105197Ssam			/* +1 for terminating-NUL */
5701105197Ssam			userfqdnlen = strlen(userfqdn) + 1;
5702105197Ssam		} else
5703105197Ssam			userfqdnlen = 0;
5704105197Ssam		id = (struct sadb_ident *)p;
5705105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5706105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5707105197Ssam		id->sadb_ident_exttype = idexttype;
5708105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5709105197Ssam		/* XXX is it correct? */
5710105197Ssam		if (curproc && curproc->p_cred)
5711105197Ssam			id->sadb_ident_id = curproc->p_cred->p_ruid;
5712105197Ssam		if (userfqdn && userfqdnlen)
5713105197Ssam			bcopy(userfqdn, id + 1, userfqdnlen);
5714105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5715105197Ssam	}
5716105197Ssam#endif
5717105197Ssam
5718105197Ssam	/* XXX sensitivity (optional) */
5719105197Ssam
5720105197Ssam	/* create proposal/combination extension */
5721105197Ssam	m = key_getprop(saidx);
5722105197Ssam#if 0
5723105197Ssam	/*
5724105197Ssam	 * spec conformant: always attach proposal/combination extension,
5725105197Ssam	 * the problem is that we have no way to attach it for ipcomp,
5726105197Ssam	 * due to the way sadb_comb is declared in RFC2367.
5727105197Ssam	 */
5728105197Ssam	if (!m) {
5729105197Ssam		error = ENOBUFS;
5730105197Ssam		goto fail;
5731105197Ssam	}
5732105197Ssam	m_cat(result, m);
5733105197Ssam#else
5734105197Ssam	/*
5735105197Ssam	 * outside of spec; make proposal/combination extension optional.
5736105197Ssam	 */
5737105197Ssam	if (m)
5738105197Ssam		m_cat(result, m);
5739105197Ssam#endif
5740105197Ssam
5741105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
5742105197Ssam		error = EINVAL;
5743105197Ssam		goto fail;
5744105197Ssam	}
5745105197Ssam
5746105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
5747105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
5748105197Ssam		if (result == NULL) {
5749105197Ssam			error = ENOBUFS;
5750105197Ssam			goto fail;
5751105197Ssam		}
5752105197Ssam	}
5753105197Ssam
5754105197Ssam	result->m_pkthdr.len = 0;
5755105197Ssam	for (m = result; m; m = m->m_next)
5756105197Ssam		result->m_pkthdr.len += m->m_len;
5757105197Ssam
5758105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
5759105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
5760105197Ssam
5761105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5762105197Ssam
5763105197Ssam fail:
5764105197Ssam	if (result)
5765105197Ssam		m_freem(result);
5766105197Ssam	return error;
5767105197Ssam}
5768105197Ssam
5769105197Ssamstatic struct secacq *
5770105197Ssamkey_newacq(const struct secasindex *saidx)
5771105197Ssam{
5772105197Ssam	struct secacq *newacq;
5773105197Ssam
5774105197Ssam	/* get new entry */
5775119643Ssam	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5776105197Ssam	if (newacq == NULL) {
5777120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5778105197Ssam		return NULL;
5779105197Ssam	}
5780105197Ssam
5781105197Ssam	/* copy secindex */
5782105197Ssam	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5783105197Ssam	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
5784105197Ssam	newacq->created = time_second;
5785105197Ssam	newacq->count = 0;
5786105197Ssam
5787119643Ssam	/* add to acqtree */
5788120585Ssam	ACQ_LOCK();
5789119643Ssam	LIST_INSERT_HEAD(&acqtree, newacq, chain);
5790120585Ssam	ACQ_UNLOCK();
5791119643Ssam
5792105197Ssam	return newacq;
5793105197Ssam}
5794105197Ssam
5795105197Ssamstatic struct secacq *
5796105197Ssamkey_getacq(const struct secasindex *saidx)
5797105197Ssam{
5798105197Ssam	struct secacq *acq;
5799105197Ssam
5800120585Ssam	ACQ_LOCK();
5801105197Ssam	LIST_FOREACH(acq, &acqtree, chain) {
5802105197Ssam		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5803119643Ssam			break;
5804105197Ssam	}
5805120585Ssam	ACQ_UNLOCK();
5806105197Ssam
5807119643Ssam	return acq;
5808105197Ssam}
5809105197Ssam
5810105197Ssamstatic struct secacq *
5811105197Ssamkey_getacqbyseq(seq)
5812105197Ssam	u_int32_t seq;
5813105197Ssam{
5814105197Ssam	struct secacq *acq;
5815105197Ssam
5816120585Ssam	ACQ_LOCK();
5817105197Ssam	LIST_FOREACH(acq, &acqtree, chain) {
5818105197Ssam		if (acq->seq == seq)
5819119643Ssam			break;
5820105197Ssam	}
5821120585Ssam	ACQ_UNLOCK();
5822105197Ssam
5823119643Ssam	return acq;
5824105197Ssam}
5825105197Ssam
5826105197Ssamstatic struct secspacq *
5827105197Ssamkey_newspacq(spidx)
5828105197Ssam	struct secpolicyindex *spidx;
5829105197Ssam{
5830105197Ssam	struct secspacq *acq;
5831105197Ssam
5832105197Ssam	/* get new entry */
5833119643Ssam	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5834105197Ssam	if (acq == NULL) {
5835120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5836105197Ssam		return NULL;
5837105197Ssam	}
5838105197Ssam
5839105197Ssam	/* copy secindex */
5840105197Ssam	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5841105197Ssam	acq->created = time_second;
5842105197Ssam	acq->count = 0;
5843105197Ssam
5844119643Ssam	/* add to spacqtree */
5845120585Ssam	SPACQ_LOCK();
5846119643Ssam	LIST_INSERT_HEAD(&spacqtree, acq, chain);
5847120585Ssam	SPACQ_UNLOCK();
5848119643Ssam
5849105197Ssam	return acq;
5850105197Ssam}
5851105197Ssam
5852105197Ssamstatic struct secspacq *
5853105197Ssamkey_getspacq(spidx)
5854105197Ssam	struct secpolicyindex *spidx;
5855105197Ssam{
5856105197Ssam	struct secspacq *acq;
5857105197Ssam
5858120585Ssam	SPACQ_LOCK();
5859105197Ssam	LIST_FOREACH(acq, &spacqtree, chain) {
5860119643Ssam		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
5861119643Ssam			/* NB: return holding spacq_lock */
5862105197Ssam			return acq;
5863119643Ssam		}
5864105197Ssam	}
5865120585Ssam	SPACQ_UNLOCK();
5866105197Ssam
5867105197Ssam	return NULL;
5868105197Ssam}
5869105197Ssam
5870105197Ssam/*
5871105197Ssam * SADB_ACQUIRE processing,
5872105197Ssam * in first situation, is receiving
5873105197Ssam *   <base>
5874105197Ssam * from the ikmpd, and clear sequence of its secasvar entry.
5875105197Ssam *
5876105197Ssam * In second situation, is receiving
5877105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5878105197Ssam * from a user land process, and return
5879105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5880105197Ssam * to the socket.
5881105197Ssam *
5882105197Ssam * m will always be freed.
5883105197Ssam */
5884105197Ssamstatic int
5885105197Ssamkey_acquire2(so, m, mhp)
5886105197Ssam	struct socket *so;
5887105197Ssam	struct mbuf *m;
5888105197Ssam	const struct sadb_msghdr *mhp;
5889105197Ssam{
5890105197Ssam	const struct sadb_address *src0, *dst0;
5891105197Ssam	struct secasindex saidx;
5892105197Ssam	struct secashead *sah;
5893105197Ssam	u_int16_t proto;
5894105197Ssam	int error;
5895105197Ssam
5896120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5897120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5898120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5899120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5900105197Ssam
5901105197Ssam	/*
5902105197Ssam	 * Error message from KMd.
5903105197Ssam	 * We assume that if error was occured in IKEd, the length of PFKEY
5904105197Ssam	 * message is equal to the size of sadb_msg structure.
5905105197Ssam	 * We do not raise error even if error occured in this function.
5906105197Ssam	 */
5907105197Ssam	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
5908105197Ssam		struct secacq *acq;
5909105197Ssam
5910105197Ssam		/* check sequence number */
5911105197Ssam		if (mhp->msg->sadb_msg_seq == 0) {
5912120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify sequence "
5913120585Ssam				"number.\n", __func__));
5914105197Ssam			m_freem(m);
5915105197Ssam			return 0;
5916105197Ssam		}
5917105197Ssam
5918105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
5919105197Ssam			/*
5920105197Ssam			 * the specified larval SA is already gone, or we got
5921105197Ssam			 * a bogus sequence number.  we can silently ignore it.
5922105197Ssam			 */
5923105197Ssam			m_freem(m);
5924105197Ssam			return 0;
5925105197Ssam		}
5926105197Ssam
5927105197Ssam		/* reset acq counter in order to deletion by timehander. */
5928105197Ssam		acq->created = time_second;
5929105197Ssam		acq->count = 0;
5930105197Ssam		m_freem(m);
5931105197Ssam		return 0;
5932105197Ssam	}
5933105197Ssam
5934105197Ssam	/*
5935105197Ssam	 * This message is from user land.
5936105197Ssam	 */
5937105197Ssam
5938105197Ssam	/* map satype to proto */
5939105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5940120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5941120585Ssam			__func__));
5942105197Ssam		return key_senderror(so, m, EINVAL);
5943105197Ssam	}
5944105197Ssam
5945105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5946105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5947105197Ssam	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
5948105197Ssam		/* error */
5949120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5950120585Ssam			__func__));
5951105197Ssam		return key_senderror(so, m, EINVAL);
5952105197Ssam	}
5953105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5954105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
5955105197Ssam	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
5956105197Ssam		/* error */
5957120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5958120585Ssam			__func__));
5959105197Ssam		return key_senderror(so, m, EINVAL);
5960105197Ssam	}
5961105197Ssam
5962105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5963105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5964105197Ssam
5965105197Ssam	/* XXX boundary check against sa_len */
5966105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5967105197Ssam
5968105197Ssam	/* get a SA index */
5969120585Ssam	SAHTREE_LOCK();
5970105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
5971105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5972105197Ssam			continue;
5973105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
5974105197Ssam			break;
5975105197Ssam	}
5976120585Ssam	SAHTREE_UNLOCK();
5977105197Ssam	if (sah != NULL) {
5978120585Ssam		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
5979105197Ssam		return key_senderror(so, m, EEXIST);
5980105197Ssam	}
5981105197Ssam
5982105197Ssam	error = key_acquire(&saidx, NULL);
5983105197Ssam	if (error != 0) {
5984120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
5985120585Ssam			__func__, mhp->msg->sadb_msg_errno));
5986105197Ssam		return key_senderror(so, m, error);
5987105197Ssam	}
5988105197Ssam
5989105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
5990105197Ssam}
5991105197Ssam
5992105197Ssam/*
5993105197Ssam * SADB_REGISTER processing.
5994105197Ssam * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
5995105197Ssam * receive
5996105197Ssam *   <base>
5997105197Ssam * from the ikmpd, and register a socket to send PF_KEY messages,
5998105197Ssam * and send
5999105197Ssam *   <base, supported>
6000105197Ssam * to KMD by PF_KEY.
6001105197Ssam * If socket is detached, must free from regnode.
6002105197Ssam *
6003105197Ssam * m will always be freed.
6004105197Ssam */
6005105197Ssamstatic int
6006105197Ssamkey_register(so, m, mhp)
6007105197Ssam	struct socket *so;
6008105197Ssam	struct mbuf *m;
6009105197Ssam	const struct sadb_msghdr *mhp;
6010105197Ssam{
6011105197Ssam	struct secreg *reg, *newreg = 0;
6012105197Ssam
6013120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6014120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6015120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6016120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6017105197Ssam
6018105197Ssam	/* check for invalid register message */
6019105197Ssam	if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
6020105197Ssam		return key_senderror(so, m, EINVAL);
6021105197Ssam
6022105197Ssam	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6023105197Ssam	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6024105197Ssam		goto setmsg;
6025105197Ssam
6026105197Ssam	/* check whether existing or not */
6027120585Ssam	REGTREE_LOCK();
6028105197Ssam	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
6029105197Ssam		if (reg->so == so) {
6030120585Ssam			REGTREE_UNLOCK();
6031120585Ssam			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6032120585Ssam				__func__));
6033105197Ssam			return key_senderror(so, m, EEXIST);
6034105197Ssam		}
6035105197Ssam	}
6036105197Ssam
6037105197Ssam	/* create regnode */
6038119643Ssam	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6039105197Ssam	if (newreg == NULL) {
6040120585Ssam		REGTREE_UNLOCK();
6041120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6042105197Ssam		return key_senderror(so, m, ENOBUFS);
6043105197Ssam	}
6044105197Ssam
6045105197Ssam	newreg->so = so;
6046105197Ssam	((struct keycb *)sotorawcb(so))->kp_registered++;
6047105197Ssam
6048105197Ssam	/* add regnode to regtree. */
6049105197Ssam	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6050120585Ssam	REGTREE_UNLOCK();
6051105197Ssam
6052105197Ssam  setmsg:
6053105197Ssam    {
6054105197Ssam	struct mbuf *n;
6055105197Ssam	struct sadb_msg *newmsg;
6056105197Ssam	struct sadb_supported *sup;
6057105197Ssam	u_int len, alen, elen;
6058105197Ssam	int off;
6059105197Ssam	int i;
6060105197Ssam	struct sadb_alg *alg;
6061105197Ssam
6062105197Ssam	/* create new sadb_msg to reply. */
6063105197Ssam	alen = 0;
6064105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6065105197Ssam		if (ah_algorithm_lookup(i))
6066105197Ssam			alen += sizeof(struct sadb_alg);
6067105197Ssam	}
6068105197Ssam	if (alen)
6069105197Ssam		alen += sizeof(struct sadb_supported);
6070105197Ssam	elen = 0;
6071105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6072105197Ssam		if (esp_algorithm_lookup(i))
6073105197Ssam			elen += sizeof(struct sadb_alg);
6074105197Ssam	}
6075105197Ssam	if (elen)
6076105197Ssam		elen += sizeof(struct sadb_supported);
6077105197Ssam
6078105197Ssam	len = sizeof(struct sadb_msg) + alen + elen;
6079105197Ssam
6080105197Ssam	if (len > MCLBYTES)
6081105197Ssam		return key_senderror(so, m, ENOBUFS);
6082105197Ssam
6083111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
6084105197Ssam	if (len > MHLEN) {
6085111119Simp		MCLGET(n, M_DONTWAIT);
6086105197Ssam		if ((n->m_flags & M_EXT) == 0) {
6087105197Ssam			m_freem(n);
6088105197Ssam			n = NULL;
6089105197Ssam		}
6090105197Ssam	}
6091105197Ssam	if (!n)
6092105197Ssam		return key_senderror(so, m, ENOBUFS);
6093105197Ssam
6094105197Ssam	n->m_pkthdr.len = n->m_len = len;
6095105197Ssam	n->m_next = NULL;
6096105197Ssam	off = 0;
6097105197Ssam
6098105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6099105197Ssam	newmsg = mtod(n, struct sadb_msg *);
6100105197Ssam	newmsg->sadb_msg_errno = 0;
6101105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6102105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6103105197Ssam
6104105197Ssam	/* for authentication algorithm */
6105105197Ssam	if (alen) {
6106105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6107105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6108105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6109105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6110105197Ssam
6111105197Ssam		for (i = 1; i <= SADB_AALG_MAX; i++) {
6112105197Ssam			struct auth_hash *aalgo;
6113105197Ssam			u_int16_t minkeysize, maxkeysize;
6114105197Ssam
6115105197Ssam			aalgo = ah_algorithm_lookup(i);
6116105197Ssam			if (!aalgo)
6117105197Ssam				continue;
6118105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6119105197Ssam			alg->sadb_alg_id = i;
6120105197Ssam			alg->sadb_alg_ivlen = 0;
6121105197Ssam			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6122105197Ssam			alg->sadb_alg_minbits = _BITS(minkeysize);
6123105197Ssam			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6124105197Ssam			off += PFKEY_ALIGN8(sizeof(*alg));
6125105197Ssam		}
6126105197Ssam	}
6127105197Ssam
6128105197Ssam	/* for encryption algorithm */
6129105197Ssam	if (elen) {
6130105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6131105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6132105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6133105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6134105197Ssam
6135105197Ssam		for (i = 1; i <= SADB_EALG_MAX; i++) {
6136105197Ssam			struct enc_xform *ealgo;
6137105197Ssam
6138105197Ssam			ealgo = esp_algorithm_lookup(i);
6139105197Ssam			if (!ealgo)
6140105197Ssam				continue;
6141105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6142105197Ssam			alg->sadb_alg_id = i;
6143105197Ssam			alg->sadb_alg_ivlen = ealgo->blocksize;
6144105197Ssam			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6145105197Ssam			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6146105197Ssam			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6147105197Ssam		}
6148105197Ssam	}
6149105197Ssam
6150120585Ssam	IPSEC_ASSERT(off == len,
6151120585Ssam		("length assumption failed (off %u len %u)", off, len));
6152105197Ssam
6153105197Ssam	m_freem(m);
6154105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6155105197Ssam    }
6156105197Ssam}
6157105197Ssam
6158105197Ssam/*
6159105197Ssam * free secreg entry registered.
6160105197Ssam * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6161105197Ssam */
6162105197Ssamvoid
6163119643Ssamkey_freereg(struct socket *so)
6164105197Ssam{
6165105197Ssam	struct secreg *reg;
6166105197Ssam	int i;
6167105197Ssam
6168120585Ssam	IPSEC_ASSERT(so != NULL, ("NULL so"));
6169105197Ssam
6170105197Ssam	/*
6171105197Ssam	 * check whether existing or not.
6172105197Ssam	 * check all type of SA, because there is a potential that
6173105197Ssam	 * one socket is registered to multiple type of SA.
6174105197Ssam	 */
6175120585Ssam	REGTREE_LOCK();
6176105197Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6177105197Ssam		LIST_FOREACH(reg, &regtree[i], chain) {
6178119643Ssam			if (reg->so == so && __LIST_CHAINED(reg)) {
6179105197Ssam				LIST_REMOVE(reg, chain);
6180119643Ssam				free(reg, M_IPSEC_SAR);
6181105197Ssam				break;
6182105197Ssam			}
6183105197Ssam		}
6184105197Ssam	}
6185120585Ssam	REGTREE_UNLOCK();
6186105197Ssam}
6187105197Ssam
6188105197Ssam/*
6189105197Ssam * SADB_EXPIRE processing
6190105197Ssam * send
6191105197Ssam *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6192105197Ssam * to KMD by PF_KEY.
6193105197Ssam * NOTE: We send only soft lifetime extension.
6194105197Ssam *
6195105197Ssam * OUT:	0	: succeed
6196105197Ssam *	others	: error number
6197105197Ssam */
6198105197Ssamstatic int
6199119643Ssamkey_expire(struct secasvar *sav)
6200105197Ssam{
6201105197Ssam	int s;
6202105197Ssam	int satype;
6203105197Ssam	struct mbuf *result = NULL, *m;
6204105197Ssam	int len;
6205105197Ssam	int error = -1;
6206105197Ssam	struct sadb_lifetime *lt;
6207105197Ssam
6208105197Ssam	/* XXX: Why do we lock ? */
6209105197Ssam	s = splnet();	/*called from softclock()*/
6210105197Ssam
6211120585Ssam	IPSEC_ASSERT (sav != NULL, ("null sav"));
6212120585Ssam	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6213105197Ssam
6214105197Ssam	/* set msg header */
6215120585Ssam	satype = key_proto2satype(sav->sah->saidx.proto);
6216120585Ssam	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6217105197Ssam	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6218105197Ssam	if (!m) {
6219105197Ssam		error = ENOBUFS;
6220105197Ssam		goto fail;
6221105197Ssam	}
6222105197Ssam	result = m;
6223105197Ssam
6224105197Ssam	/* create SA extension */
6225105197Ssam	m = key_setsadbsa(sav);
6226105197Ssam	if (!m) {
6227105197Ssam		error = ENOBUFS;
6228105197Ssam		goto fail;
6229105197Ssam	}
6230105197Ssam	m_cat(result, m);
6231105197Ssam
6232105197Ssam	/* create SA extension */
6233105197Ssam	m = key_setsadbxsa2(sav->sah->saidx.mode,
6234105197Ssam			sav->replay ? sav->replay->count : 0,
6235105197Ssam			sav->sah->saidx.reqid);
6236105197Ssam	if (!m) {
6237105197Ssam		error = ENOBUFS;
6238105197Ssam		goto fail;
6239105197Ssam	}
6240105197Ssam	m_cat(result, m);
6241105197Ssam
6242105197Ssam	/* create lifetime extension (current and soft) */
6243105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6244105197Ssam	m = key_alloc_mbuf(len);
6245105197Ssam	if (!m || m->m_next) {	/*XXX*/
6246105197Ssam		if (m)
6247105197Ssam			m_freem(m);
6248105197Ssam		error = ENOBUFS;
6249105197Ssam		goto fail;
6250105197Ssam	}
6251105197Ssam	bzero(mtod(m, caddr_t), len);
6252105197Ssam	lt = mtod(m, struct sadb_lifetime *);
6253105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6254105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6255105197Ssam	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6256105197Ssam	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6257105197Ssam	lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
6258105197Ssam	lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
6259105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6260105197Ssam	bcopy(sav->lft_s, lt, sizeof(*lt));
6261105197Ssam	m_cat(result, m);
6262105197Ssam
6263105197Ssam	/* set sadb_address for source */
6264105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6265105197Ssam	    &sav->sah->saidx.src.sa,
6266105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6267105197Ssam	if (!m) {
6268105197Ssam		error = ENOBUFS;
6269105197Ssam		goto fail;
6270105197Ssam	}
6271105197Ssam	m_cat(result, m);
6272105197Ssam
6273105197Ssam	/* set sadb_address for destination */
6274105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6275105197Ssam	    &sav->sah->saidx.dst.sa,
6276105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6277105197Ssam	if (!m) {
6278105197Ssam		error = ENOBUFS;
6279105197Ssam		goto fail;
6280105197Ssam	}
6281105197Ssam	m_cat(result, m);
6282105197Ssam
6283105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
6284105197Ssam		error = EINVAL;
6285105197Ssam		goto fail;
6286105197Ssam	}
6287105197Ssam
6288105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
6289105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
6290105197Ssam		if (result == NULL) {
6291105197Ssam			error = ENOBUFS;
6292105197Ssam			goto fail;
6293105197Ssam		}
6294105197Ssam	}
6295105197Ssam
6296105197Ssam	result->m_pkthdr.len = 0;
6297105197Ssam	for (m = result; m; m = m->m_next)
6298105197Ssam		result->m_pkthdr.len += m->m_len;
6299105197Ssam
6300105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
6301105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
6302105197Ssam
6303105197Ssam	splx(s);
6304105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6305105197Ssam
6306105197Ssam fail:
6307105197Ssam	if (result)
6308105197Ssam		m_freem(result);
6309105197Ssam	splx(s);
6310105197Ssam	return error;
6311105197Ssam}
6312105197Ssam
6313105197Ssam/*
6314105197Ssam * SADB_FLUSH processing
6315105197Ssam * receive
6316105197Ssam *   <base>
6317105197Ssam * from the ikmpd, and free all entries in secastree.
6318105197Ssam * and send,
6319105197Ssam *   <base>
6320105197Ssam * to the ikmpd.
6321105197Ssam * NOTE: to do is only marking SADB_SASTATE_DEAD.
6322105197Ssam *
6323105197Ssam * m will always be freed.
6324105197Ssam */
6325105197Ssamstatic int
6326105197Ssamkey_flush(so, m, mhp)
6327105197Ssam	struct socket *so;
6328105197Ssam	struct mbuf *m;
6329105197Ssam	const struct sadb_msghdr *mhp;
6330105197Ssam{
6331105197Ssam	struct sadb_msg *newmsg;
6332105197Ssam	struct secashead *sah, *nextsah;
6333105197Ssam	struct secasvar *sav, *nextsav;
6334105197Ssam	u_int16_t proto;
6335105197Ssam	u_int8_t state;
6336105197Ssam	u_int stateidx;
6337105197Ssam
6338120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6339120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6340120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6341105197Ssam
6342105197Ssam	/* map satype to proto */
6343105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6344120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6345120585Ssam			__func__));
6346105197Ssam		return key_senderror(so, m, EINVAL);
6347105197Ssam	}
6348105197Ssam
6349105197Ssam	/* no SATYPE specified, i.e. flushing all SA. */
6350120585Ssam	SAHTREE_LOCK();
6351105197Ssam	for (sah = LIST_FIRST(&sahtree);
6352105197Ssam	     sah != NULL;
6353105197Ssam	     sah = nextsah) {
6354105197Ssam		nextsah = LIST_NEXT(sah, chain);
6355105197Ssam
6356105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6357105197Ssam		 && proto != sah->saidx.proto)
6358105197Ssam			continue;
6359105197Ssam
6360105197Ssam		for (stateidx = 0;
6361105197Ssam		     stateidx < _ARRAYLEN(saorder_state_alive);
6362105197Ssam		     stateidx++) {
6363105197Ssam			state = saorder_state_any[stateidx];
6364105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
6365105197Ssam			     sav != NULL;
6366105197Ssam			     sav = nextsav) {
6367105197Ssam
6368105197Ssam				nextsav = LIST_NEXT(sav, chain);
6369105197Ssam
6370105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6371105197Ssam				KEY_FREESAV(&sav);
6372105197Ssam			}
6373105197Ssam		}
6374105197Ssam
6375105197Ssam		sah->state = SADB_SASTATE_DEAD;
6376105197Ssam	}
6377120585Ssam	SAHTREE_UNLOCK();
6378105197Ssam
6379105197Ssam	if (m->m_len < sizeof(struct sadb_msg) ||
6380105197Ssam	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6381120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6382105197Ssam		return key_senderror(so, m, ENOBUFS);
6383105197Ssam	}
6384105197Ssam
6385105197Ssam	if (m->m_next)
6386105197Ssam		m_freem(m->m_next);
6387105197Ssam	m->m_next = NULL;
6388105197Ssam	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6389105197Ssam	newmsg = mtod(m, struct sadb_msg *);
6390105197Ssam	newmsg->sadb_msg_errno = 0;
6391105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6392105197Ssam
6393105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6394105197Ssam}
6395105197Ssam
6396105197Ssam/*
6397105197Ssam * SADB_DUMP processing
6398105197Ssam * dump all entries including status of DEAD in SAD.
6399105197Ssam * receive
6400105197Ssam *   <base>
6401105197Ssam * from the ikmpd, and dump all secasvar leaves
6402105197Ssam * and send,
6403105197Ssam *   <base> .....
6404105197Ssam * to the ikmpd.
6405105197Ssam *
6406105197Ssam * m will always be freed.
6407105197Ssam */
6408105197Ssamstatic int
6409105197Ssamkey_dump(so, m, mhp)
6410105197Ssam	struct socket *so;
6411105197Ssam	struct mbuf *m;
6412105197Ssam	const struct sadb_msghdr *mhp;
6413105197Ssam{
6414105197Ssam	struct secashead *sah;
6415105197Ssam	struct secasvar *sav;
6416105197Ssam	u_int16_t proto;
6417105197Ssam	u_int stateidx;
6418105197Ssam	u_int8_t satype;
6419105197Ssam	u_int8_t state;
6420105197Ssam	int cnt;
6421105197Ssam	struct sadb_msg *newmsg;
6422105197Ssam	struct mbuf *n;
6423105197Ssam
6424120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6425120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6426120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6427120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6428105197Ssam
6429105197Ssam	/* map satype to proto */
6430105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6431120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6432120585Ssam			__func__));
6433105197Ssam		return key_senderror(so, m, EINVAL);
6434105197Ssam	}
6435105197Ssam
6436105197Ssam	/* count sav entries to be sent to the userland. */
6437105197Ssam	cnt = 0;
6438120585Ssam	SAHTREE_LOCK();
6439105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
6440105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6441105197Ssam		 && proto != sah->saidx.proto)
6442105197Ssam			continue;
6443105197Ssam
6444105197Ssam		for (stateidx = 0;
6445105197Ssam		     stateidx < _ARRAYLEN(saorder_state_any);
6446105197Ssam		     stateidx++) {
6447105197Ssam			state = saorder_state_any[stateidx];
6448105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6449105197Ssam				cnt++;
6450105197Ssam			}
6451105197Ssam		}
6452105197Ssam	}
6453105197Ssam
6454119643Ssam	if (cnt == 0) {
6455120585Ssam		SAHTREE_UNLOCK();
6456105197Ssam		return key_senderror(so, m, ENOENT);
6457119643Ssam	}
6458105197Ssam
6459105197Ssam	/* send this to the userland, one at a time. */
6460105197Ssam	newmsg = NULL;
6461105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
6462105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6463105197Ssam		 && proto != sah->saidx.proto)
6464105197Ssam			continue;
6465105197Ssam
6466105197Ssam		/* map proto to satype */
6467105197Ssam		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6468120585Ssam			SAHTREE_UNLOCK();
6469120585Ssam			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
6470120585Ssam				"SAD.\n", __func__));
6471105197Ssam			return key_senderror(so, m, EINVAL);
6472105197Ssam		}
6473105197Ssam
6474105197Ssam		for (stateidx = 0;
6475105197Ssam		     stateidx < _ARRAYLEN(saorder_state_any);
6476105197Ssam		     stateidx++) {
6477105197Ssam			state = saorder_state_any[stateidx];
6478105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6479105197Ssam				n = key_setdumpsa(sav, SADB_DUMP, satype,
6480105197Ssam				    --cnt, mhp->msg->sadb_msg_pid);
6481119643Ssam				if (!n) {
6482120585Ssam					SAHTREE_UNLOCK();
6483105197Ssam					return key_senderror(so, m, ENOBUFS);
6484119643Ssam				}
6485105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6486105197Ssam			}
6487105197Ssam		}
6488105197Ssam	}
6489120585Ssam	SAHTREE_UNLOCK();
6490105197Ssam
6491105197Ssam	m_freem(m);
6492105197Ssam	return 0;
6493105197Ssam}
6494105197Ssam
6495105197Ssam/*
6496105197Ssam * SADB_X_PROMISC processing
6497105197Ssam *
6498105197Ssam * m will always be freed.
6499105197Ssam */
6500105197Ssamstatic int
6501105197Ssamkey_promisc(so, m, mhp)
6502105197Ssam	struct socket *so;
6503105197Ssam	struct mbuf *m;
6504105197Ssam	const struct sadb_msghdr *mhp;
6505105197Ssam{
6506105197Ssam	int olen;
6507105197Ssam
6508120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6509120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6510120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6511120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6512105197Ssam
6513105197Ssam	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6514105197Ssam
6515105197Ssam	if (olen < sizeof(struct sadb_msg)) {
6516105197Ssam#if 1
6517105197Ssam		return key_senderror(so, m, EINVAL);
6518105197Ssam#else
6519105197Ssam		m_freem(m);
6520105197Ssam		return 0;
6521105197Ssam#endif
6522105197Ssam	} else if (olen == sizeof(struct sadb_msg)) {
6523105197Ssam		/* enable/disable promisc mode */
6524105197Ssam		struct keycb *kp;
6525105197Ssam
6526105197Ssam		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6527105197Ssam			return key_senderror(so, m, EINVAL);
6528105197Ssam		mhp->msg->sadb_msg_errno = 0;
6529105197Ssam		switch (mhp->msg->sadb_msg_satype) {
6530105197Ssam		case 0:
6531105197Ssam		case 1:
6532105197Ssam			kp->kp_promisc = mhp->msg->sadb_msg_satype;
6533105197Ssam			break;
6534105197Ssam		default:
6535105197Ssam			return key_senderror(so, m, EINVAL);
6536105197Ssam		}
6537105197Ssam
6538105197Ssam		/* send the original message back to everyone */
6539105197Ssam		mhp->msg->sadb_msg_errno = 0;
6540105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6541105197Ssam	} else {
6542105197Ssam		/* send packet as is */
6543105197Ssam
6544105197Ssam		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6545105197Ssam
6546105197Ssam		/* TODO: if sadb_msg_seq is specified, send to specific pid */
6547105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6548105197Ssam	}
6549105197Ssam}
6550105197Ssam
6551105197Ssamstatic int (*key_typesw[]) __P((struct socket *, struct mbuf *,
6552105197Ssam		const struct sadb_msghdr *)) = {
6553105197Ssam	NULL,		/* SADB_RESERVED */
6554105197Ssam	key_getspi,	/* SADB_GETSPI */
6555105197Ssam	key_update,	/* SADB_UPDATE */
6556105197Ssam	key_add,	/* SADB_ADD */
6557105197Ssam	key_delete,	/* SADB_DELETE */
6558105197Ssam	key_get,	/* SADB_GET */
6559105197Ssam	key_acquire2,	/* SADB_ACQUIRE */
6560105197Ssam	key_register,	/* SADB_REGISTER */
6561105197Ssam	NULL,		/* SADB_EXPIRE */
6562105197Ssam	key_flush,	/* SADB_FLUSH */
6563105197Ssam	key_dump,	/* SADB_DUMP */
6564105197Ssam	key_promisc,	/* SADB_X_PROMISC */
6565105197Ssam	NULL,		/* SADB_X_PCHANGE */
6566105197Ssam	key_spdadd,	/* SADB_X_SPDUPDATE */
6567105197Ssam	key_spdadd,	/* SADB_X_SPDADD */
6568105197Ssam	key_spddelete,	/* SADB_X_SPDDELETE */
6569105197Ssam	key_spdget,	/* SADB_X_SPDGET */
6570105197Ssam	NULL,		/* SADB_X_SPDACQUIRE */
6571105197Ssam	key_spddump,	/* SADB_X_SPDDUMP */
6572105197Ssam	key_spdflush,	/* SADB_X_SPDFLUSH */
6573105197Ssam	key_spdadd,	/* SADB_X_SPDSETIDX */
6574105197Ssam	NULL,		/* SADB_X_SPDEXPIRE */
6575105197Ssam	key_spddelete2,	/* SADB_X_SPDDELETE2 */
6576105197Ssam};
6577105197Ssam
6578105197Ssam/*
6579105197Ssam * parse sadb_msg buffer to process PFKEYv2,
6580105197Ssam * and create a data to response if needed.
6581105197Ssam * I think to be dealed with mbuf directly.
6582105197Ssam * IN:
6583105197Ssam *     msgp  : pointer to pointer to a received buffer pulluped.
6584105197Ssam *             This is rewrited to response.
6585105197Ssam *     so    : pointer to socket.
6586105197Ssam * OUT:
6587105197Ssam *    length for buffer to send to user process.
6588105197Ssam */
6589105197Ssamint
6590105197Ssamkey_parse(m, so)
6591105197Ssam	struct mbuf *m;
6592105197Ssam	struct socket *so;
6593105197Ssam{
6594105197Ssam	struct sadb_msg *msg;
6595105197Ssam	struct sadb_msghdr mh;
6596105197Ssam	u_int orglen;
6597105197Ssam	int error;
6598105197Ssam	int target;
6599105197Ssam
6600120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6601120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6602105197Ssam
6603105197Ssam#if 0	/*kdebug_sadb assumes msg in linear buffer*/
6604105197Ssam	KEYDEBUG(KEYDEBUG_KEY_DUMP,
6605120585Ssam		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
6606105197Ssam		kdebug_sadb(msg));
6607105197Ssam#endif
6608105197Ssam
6609105197Ssam	if (m->m_len < sizeof(struct sadb_msg)) {
6610105197Ssam		m = m_pullup(m, sizeof(struct sadb_msg));
6611105197Ssam		if (!m)
6612105197Ssam			return ENOBUFS;
6613105197Ssam	}
6614105197Ssam	msg = mtod(m, struct sadb_msg *);
6615105197Ssam	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6616105197Ssam	target = KEY_SENDUP_ONE;
6617105197Ssam
6618105197Ssam	if ((m->m_flags & M_PKTHDR) == 0 ||
6619105197Ssam	    m->m_pkthdr.len != m->m_pkthdr.len) {
6620120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
6621105197Ssam		pfkeystat.out_invlen++;
6622105197Ssam		error = EINVAL;
6623105197Ssam		goto senderror;
6624105197Ssam	}
6625105197Ssam
6626105197Ssam	if (msg->sadb_msg_version != PF_KEY_V2) {
6627120585Ssam		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
6628120585Ssam		    __func__, msg->sadb_msg_version));
6629105197Ssam		pfkeystat.out_invver++;
6630105197Ssam		error = EINVAL;
6631105197Ssam		goto senderror;
6632105197Ssam	}
6633105197Ssam
6634105197Ssam	if (msg->sadb_msg_type > SADB_MAX) {
6635120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6636120585Ssam		    __func__, msg->sadb_msg_type));
6637105197Ssam		pfkeystat.out_invmsgtype++;
6638105197Ssam		error = EINVAL;
6639105197Ssam		goto senderror;
6640105197Ssam	}
6641105197Ssam
6642105197Ssam	/* for old-fashioned code - should be nuked */
6643105197Ssam	if (m->m_pkthdr.len > MCLBYTES) {
6644105197Ssam		m_freem(m);
6645105197Ssam		return ENOBUFS;
6646105197Ssam	}
6647105197Ssam	if (m->m_next) {
6648105197Ssam		struct mbuf *n;
6649105197Ssam
6650111119Simp		MGETHDR(n, M_DONTWAIT, MT_DATA);
6651105197Ssam		if (n && m->m_pkthdr.len > MHLEN) {
6652111119Simp			MCLGET(n, M_DONTWAIT);
6653105197Ssam			if ((n->m_flags & M_EXT) == 0) {
6654105197Ssam				m_free(n);
6655105197Ssam				n = NULL;
6656105197Ssam			}
6657105197Ssam		}
6658105197Ssam		if (!n) {
6659105197Ssam			m_freem(m);
6660105197Ssam			return ENOBUFS;
6661105197Ssam		}
6662105197Ssam		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6663105197Ssam		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6664105197Ssam		n->m_next = NULL;
6665105197Ssam		m_freem(m);
6666105197Ssam		m = n;
6667105197Ssam	}
6668105197Ssam
6669105197Ssam	/* align the mbuf chain so that extensions are in contiguous region. */
6670105197Ssam	error = key_align(m, &mh);
6671105197Ssam	if (error)
6672105197Ssam		return error;
6673105197Ssam
6674105197Ssam	if (m->m_next) {	/*XXX*/
6675105197Ssam		m_freem(m);
6676105197Ssam		return ENOBUFS;
6677105197Ssam	}
6678105197Ssam
6679105197Ssam	msg = mh.msg;
6680105197Ssam
6681105197Ssam	/* check SA type */
6682105197Ssam	switch (msg->sadb_msg_satype) {
6683105197Ssam	case SADB_SATYPE_UNSPEC:
6684105197Ssam		switch (msg->sadb_msg_type) {
6685105197Ssam		case SADB_GETSPI:
6686105197Ssam		case SADB_UPDATE:
6687105197Ssam		case SADB_ADD:
6688105197Ssam		case SADB_DELETE:
6689105197Ssam		case SADB_GET:
6690105197Ssam		case SADB_ACQUIRE:
6691105197Ssam		case SADB_EXPIRE:
6692120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify satype "
6693120585Ssam			    "when msg type=%u.\n", __func__,
6694120585Ssam			    msg->sadb_msg_type));
6695105197Ssam			pfkeystat.out_invsatype++;
6696105197Ssam			error = EINVAL;
6697105197Ssam			goto senderror;
6698105197Ssam		}
6699105197Ssam		break;
6700105197Ssam	case SADB_SATYPE_AH:
6701105197Ssam	case SADB_SATYPE_ESP:
6702105197Ssam	case SADB_X_SATYPE_IPCOMP:
6703125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
6704105197Ssam		switch (msg->sadb_msg_type) {
6705105197Ssam		case SADB_X_SPDADD:
6706105197Ssam		case SADB_X_SPDDELETE:
6707105197Ssam		case SADB_X_SPDGET:
6708105197Ssam		case SADB_X_SPDDUMP:
6709105197Ssam		case SADB_X_SPDFLUSH:
6710105197Ssam		case SADB_X_SPDSETIDX:
6711105197Ssam		case SADB_X_SPDUPDATE:
6712105197Ssam		case SADB_X_SPDDELETE2:
6713120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
6714120585Ssam				__func__, msg->sadb_msg_type));
6715105197Ssam			pfkeystat.out_invsatype++;
6716105197Ssam			error = EINVAL;
6717105197Ssam			goto senderror;
6718105197Ssam		}
6719105197Ssam		break;
6720105197Ssam	case SADB_SATYPE_RSVP:
6721105197Ssam	case SADB_SATYPE_OSPFV2:
6722105197Ssam	case SADB_SATYPE_RIPV2:
6723105197Ssam	case SADB_SATYPE_MIP:
6724120585Ssam		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
6725120585Ssam			__func__, msg->sadb_msg_satype));
6726105197Ssam		pfkeystat.out_invsatype++;
6727105197Ssam		error = EOPNOTSUPP;
6728105197Ssam		goto senderror;
6729105197Ssam	case 1:	/* XXX: What does it do? */
6730105197Ssam		if (msg->sadb_msg_type == SADB_X_PROMISC)
6731105197Ssam			break;
6732105197Ssam		/*FALLTHROUGH*/
6733105197Ssam	default:
6734120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6735120585Ssam			__func__, msg->sadb_msg_satype));
6736105197Ssam		pfkeystat.out_invsatype++;
6737105197Ssam		error = EINVAL;
6738105197Ssam		goto senderror;
6739105197Ssam	}
6740105197Ssam
6741105197Ssam	/* check field of upper layer protocol and address family */
6742105197Ssam	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6743105197Ssam	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6744105197Ssam		struct sadb_address *src0, *dst0;
6745105197Ssam		u_int plen;
6746105197Ssam
6747105197Ssam		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6748105197Ssam		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6749105197Ssam
6750105197Ssam		/* check upper layer protocol */
6751105197Ssam		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6752120585Ssam			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
6753120585Ssam				"mismatched.\n", __func__));
6754105197Ssam			pfkeystat.out_invaddr++;
6755105197Ssam			error = EINVAL;
6756105197Ssam			goto senderror;
6757105197Ssam		}
6758105197Ssam
6759105197Ssam		/* check family */
6760105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6761105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
6762120585Ssam			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
6763120585Ssam				__func__));
6764105197Ssam			pfkeystat.out_invaddr++;
6765105197Ssam			error = EINVAL;
6766105197Ssam			goto senderror;
6767105197Ssam		}
6768105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6769105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
6770120585Ssam			ipseclog((LOG_DEBUG, "%s: address struct size "
6771120585Ssam				"mismatched.\n", __func__));
6772105197Ssam			pfkeystat.out_invaddr++;
6773105197Ssam			error = EINVAL;
6774105197Ssam			goto senderror;
6775105197Ssam		}
6776105197Ssam
6777105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6778105197Ssam		case AF_INET:
6779105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6780105197Ssam			    sizeof(struct sockaddr_in)) {
6781105197Ssam				pfkeystat.out_invaddr++;
6782105197Ssam				error = EINVAL;
6783105197Ssam				goto senderror;
6784105197Ssam			}
6785105197Ssam			break;
6786105197Ssam		case AF_INET6:
6787105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6788105197Ssam			    sizeof(struct sockaddr_in6)) {
6789105197Ssam				pfkeystat.out_invaddr++;
6790105197Ssam				error = EINVAL;
6791105197Ssam				goto senderror;
6792105197Ssam			}
6793105197Ssam			break;
6794105197Ssam		default:
6795120585Ssam			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
6796120585Ssam				__func__));
6797105197Ssam			pfkeystat.out_invaddr++;
6798105197Ssam			error = EAFNOSUPPORT;
6799105197Ssam			goto senderror;
6800105197Ssam		}
6801105197Ssam
6802105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6803105197Ssam		case AF_INET:
6804105197Ssam			plen = sizeof(struct in_addr) << 3;
6805105197Ssam			break;
6806105197Ssam		case AF_INET6:
6807105197Ssam			plen = sizeof(struct in6_addr) << 3;
6808105197Ssam			break;
6809105197Ssam		default:
6810105197Ssam			plen = 0;	/*fool gcc*/
6811105197Ssam			break;
6812105197Ssam		}
6813105197Ssam
6814105197Ssam		/* check max prefix length */
6815105197Ssam		if (src0->sadb_address_prefixlen > plen ||
6816105197Ssam		    dst0->sadb_address_prefixlen > plen) {
6817120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
6818120585Ssam				__func__));
6819105197Ssam			pfkeystat.out_invaddr++;
6820105197Ssam			error = EINVAL;
6821105197Ssam			goto senderror;
6822105197Ssam		}
6823105197Ssam
6824105197Ssam		/*
6825105197Ssam		 * prefixlen == 0 is valid because there can be a case when
6826105197Ssam		 * all addresses are matched.
6827105197Ssam		 */
6828105197Ssam	}
6829105197Ssam
6830105197Ssam	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
6831105197Ssam	    key_typesw[msg->sadb_msg_type] == NULL) {
6832105197Ssam		pfkeystat.out_invmsgtype++;
6833105197Ssam		error = EINVAL;
6834105197Ssam		goto senderror;
6835105197Ssam	}
6836105197Ssam
6837105197Ssam	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6838105197Ssam
6839105197Ssamsenderror:
6840105197Ssam	msg->sadb_msg_errno = error;
6841105197Ssam	return key_sendup_mbuf(so, m, target);
6842105197Ssam}
6843105197Ssam
6844105197Ssamstatic int
6845105197Ssamkey_senderror(so, m, code)
6846105197Ssam	struct socket *so;
6847105197Ssam	struct mbuf *m;
6848105197Ssam	int code;
6849105197Ssam{
6850105197Ssam	struct sadb_msg *msg;
6851105197Ssam
6852120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6853120585Ssam		("mbuf too small, len %u", m->m_len));
6854105197Ssam
6855105197Ssam	msg = mtod(m, struct sadb_msg *);
6856105197Ssam	msg->sadb_msg_errno = code;
6857105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
6858105197Ssam}
6859105197Ssam
6860105197Ssam/*
6861105197Ssam * set the pointer to each header into message buffer.
6862105197Ssam * m will be freed on error.
6863105197Ssam * XXX larger-than-MCLBYTES extension?
6864105197Ssam */
6865105197Ssamstatic int
6866105197Ssamkey_align(m, mhp)
6867105197Ssam	struct mbuf *m;
6868105197Ssam	struct sadb_msghdr *mhp;
6869105197Ssam{
6870105197Ssam	struct mbuf *n;
6871105197Ssam	struct sadb_ext *ext;
6872105197Ssam	size_t off, end;
6873105197Ssam	int extlen;
6874105197Ssam	int toff;
6875105197Ssam
6876120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6877120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6878120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6879120585Ssam		("mbuf too small, len %u", m->m_len));
6880105197Ssam
6881105197Ssam	/* initialize */
6882105197Ssam	bzero(mhp, sizeof(*mhp));
6883105197Ssam
6884105197Ssam	mhp->msg = mtod(m, struct sadb_msg *);
6885105197Ssam	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
6886105197Ssam
6887105197Ssam	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6888105197Ssam	extlen = end;	/*just in case extlen is not updated*/
6889105197Ssam	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
6890105197Ssam		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
6891105197Ssam		if (!n) {
6892105197Ssam			/* m is already freed */
6893105197Ssam			return ENOBUFS;
6894105197Ssam		}
6895105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6896105197Ssam
6897105197Ssam		/* set pointer */
6898105197Ssam		switch (ext->sadb_ext_type) {
6899105197Ssam		case SADB_EXT_SA:
6900105197Ssam		case SADB_EXT_ADDRESS_SRC:
6901105197Ssam		case SADB_EXT_ADDRESS_DST:
6902105197Ssam		case SADB_EXT_ADDRESS_PROXY:
6903105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
6904105197Ssam		case SADB_EXT_LIFETIME_HARD:
6905105197Ssam		case SADB_EXT_LIFETIME_SOFT:
6906105197Ssam		case SADB_EXT_KEY_AUTH:
6907105197Ssam		case SADB_EXT_KEY_ENCRYPT:
6908105197Ssam		case SADB_EXT_IDENTITY_SRC:
6909105197Ssam		case SADB_EXT_IDENTITY_DST:
6910105197Ssam		case SADB_EXT_SENSITIVITY:
6911105197Ssam		case SADB_EXT_PROPOSAL:
6912105197Ssam		case SADB_EXT_SUPPORTED_AUTH:
6913105197Ssam		case SADB_EXT_SUPPORTED_ENCRYPT:
6914105197Ssam		case SADB_EXT_SPIRANGE:
6915105197Ssam		case SADB_X_EXT_POLICY:
6916105197Ssam		case SADB_X_EXT_SA2:
6917105197Ssam			/* duplicate check */
6918105197Ssam			/*
6919105197Ssam			 * XXX Are there duplication payloads of either
6920105197Ssam			 * KEY_AUTH or KEY_ENCRYPT ?
6921105197Ssam			 */
6922105197Ssam			if (mhp->ext[ext->sadb_ext_type] != NULL) {
6923120585Ssam				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
6924120585Ssam					"%u\n", __func__, ext->sadb_ext_type));
6925105197Ssam				m_freem(m);
6926105197Ssam				pfkeystat.out_dupext++;
6927105197Ssam				return EINVAL;
6928105197Ssam			}
6929105197Ssam			break;
6930105197Ssam		default:
6931120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
6932120585Ssam				__func__, ext->sadb_ext_type));
6933105197Ssam			m_freem(m);
6934105197Ssam			pfkeystat.out_invexttype++;
6935105197Ssam			return EINVAL;
6936105197Ssam		}
6937105197Ssam
6938105197Ssam		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
6939105197Ssam
6940105197Ssam		if (key_validate_ext(ext, extlen)) {
6941105197Ssam			m_freem(m);
6942105197Ssam			pfkeystat.out_invlen++;
6943105197Ssam			return EINVAL;
6944105197Ssam		}
6945105197Ssam
6946105197Ssam		n = m_pulldown(m, off, extlen, &toff);
6947105197Ssam		if (!n) {
6948105197Ssam			/* m is already freed */
6949105197Ssam			return ENOBUFS;
6950105197Ssam		}
6951105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6952105197Ssam
6953105197Ssam		mhp->ext[ext->sadb_ext_type] = ext;
6954105197Ssam		mhp->extoff[ext->sadb_ext_type] = off;
6955105197Ssam		mhp->extlen[ext->sadb_ext_type] = extlen;
6956105197Ssam	}
6957105197Ssam
6958105197Ssam	if (off != end) {
6959105197Ssam		m_freem(m);
6960105197Ssam		pfkeystat.out_invlen++;
6961105197Ssam		return EINVAL;
6962105197Ssam	}
6963105197Ssam
6964105197Ssam	return 0;
6965105197Ssam}
6966105197Ssam
6967105197Ssamstatic int
6968105197Ssamkey_validate_ext(ext, len)
6969105197Ssam	const struct sadb_ext *ext;
6970105197Ssam	int len;
6971105197Ssam{
6972105197Ssam	const struct sockaddr *sa;
6973105197Ssam	enum { NONE, ADDR } checktype = NONE;
6974105197Ssam	int baselen = 0;
6975105197Ssam	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
6976105197Ssam
6977105197Ssam	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
6978105197Ssam		return EINVAL;
6979105197Ssam
6980105197Ssam	/* if it does not match minimum/maximum length, bail */
6981105197Ssam	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
6982105197Ssam	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
6983105197Ssam		return EINVAL;
6984105197Ssam	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
6985105197Ssam		return EINVAL;
6986105197Ssam	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
6987105197Ssam		return EINVAL;
6988105197Ssam
6989105197Ssam	/* more checks based on sadb_ext_type XXX need more */
6990105197Ssam	switch (ext->sadb_ext_type) {
6991105197Ssam	case SADB_EXT_ADDRESS_SRC:
6992105197Ssam	case SADB_EXT_ADDRESS_DST:
6993105197Ssam	case SADB_EXT_ADDRESS_PROXY:
6994105197Ssam		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
6995105197Ssam		checktype = ADDR;
6996105197Ssam		break;
6997105197Ssam	case SADB_EXT_IDENTITY_SRC:
6998105197Ssam	case SADB_EXT_IDENTITY_DST:
6999105197Ssam		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7000105197Ssam		    SADB_X_IDENTTYPE_ADDR) {
7001105197Ssam			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7002105197Ssam			checktype = ADDR;
7003105197Ssam		} else
7004105197Ssam			checktype = NONE;
7005105197Ssam		break;
7006105197Ssam	default:
7007105197Ssam		checktype = NONE;
7008105197Ssam		break;
7009105197Ssam	}
7010105197Ssam
7011105197Ssam	switch (checktype) {
7012105197Ssam	case NONE:
7013105197Ssam		break;
7014105197Ssam	case ADDR:
7015105197Ssam		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7016105197Ssam		if (len < baselen + sal)
7017105197Ssam			return EINVAL;
7018105197Ssam		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7019105197Ssam			return EINVAL;
7020105197Ssam		break;
7021105197Ssam	}
7022105197Ssam
7023105197Ssam	return 0;
7024105197Ssam}
7025105197Ssam
7026105197Ssamvoid
7027105197Ssamkey_init()
7028105197Ssam{
7029105197Ssam	int i;
7030105197Ssam
7031120585Ssam	SPTREE_LOCK_INIT();
7032120585Ssam	REGTREE_LOCK_INIT();
7033120585Ssam	SAHTREE_LOCK_INIT();
7034120585Ssam	ACQ_LOCK_INIT();
7035120585Ssam	SPACQ_LOCK_INIT();
7036119643Ssam
7037119643Ssam	for (i = 0; i < IPSEC_DIR_MAX; i++)
7038105197Ssam		LIST_INIT(&sptree[i]);
7039105197Ssam
7040105197Ssam	LIST_INIT(&sahtree);
7041105197Ssam
7042119643Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7043105197Ssam		LIST_INIT(&regtree[i]);
7044105197Ssam
7045105197Ssam	LIST_INIT(&acqtree);
7046105197Ssam	LIST_INIT(&spacqtree);
7047105197Ssam
7048105197Ssam	/* system default */
7049105197Ssam	ip4_def_policy.policy = IPSEC_POLICY_NONE;
7050105197Ssam	ip4_def_policy.refcnt++;	/*never reclaim this*/
7051105197Ssam
7052105197Ssam#ifndef IPSEC_DEBUG2
7053105197Ssam	timeout((void *)key_timehandler, (void *)0, hz);
7054105197Ssam#endif /*IPSEC_DEBUG2*/
7055105197Ssam
7056105197Ssam	/* initialize key statistics */
7057105197Ssam	keystat.getspi_count = 1;
7058105197Ssam
7059120585Ssam	printf("Fast IPsec: Initialized Security Association Processing.\n");
7060105197Ssam
7061105197Ssam	return;
7062105197Ssam}
7063105197Ssam
7064105197Ssam/*
7065105197Ssam * XXX: maybe This function is called after INBOUND IPsec processing.
7066105197Ssam *
7067105197Ssam * Special check for tunnel-mode packets.
7068105197Ssam * We must make some checks for consistency between inner and outer IP header.
7069105197Ssam *
7070105197Ssam * xxx more checks to be provided
7071105197Ssam */
7072105197Ssamint
7073105197Ssamkey_checktunnelsanity(sav, family, src, dst)
7074105197Ssam	struct secasvar *sav;
7075105197Ssam	u_int family;
7076105197Ssam	caddr_t src;
7077105197Ssam	caddr_t dst;
7078105197Ssam{
7079120585Ssam	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7080105197Ssam
7081105197Ssam	/* XXX: check inner IP header */
7082105197Ssam
7083105197Ssam	return 1;
7084105197Ssam}
7085105197Ssam
7086105197Ssam/* record data transfer on SA, and update timestamps */
7087105197Ssamvoid
7088105197Ssamkey_sa_recordxfer(sav, m)
7089105197Ssam	struct secasvar *sav;
7090105197Ssam	struct mbuf *m;
7091105197Ssam{
7092120585Ssam	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7093120585Ssam	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7094105197Ssam	if (!sav->lft_c)
7095105197Ssam		return;
7096105197Ssam
7097105197Ssam	/*
7098105197Ssam	 * XXX Currently, there is a difference of bytes size
7099105197Ssam	 * between inbound and outbound processing.
7100105197Ssam	 */
7101105197Ssam	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
7102105197Ssam	/* to check bytes lifetime is done in key_timehandler(). */
7103105197Ssam
7104105197Ssam	/*
7105105197Ssam	 * We use the number of packets as the unit of
7106105197Ssam	 * sadb_lifetime_allocations.  We increment the variable
7107105197Ssam	 * whenever {esp,ah}_{in,out}put is called.
7108105197Ssam	 */
7109105197Ssam	sav->lft_c->sadb_lifetime_allocations++;
7110105197Ssam	/* XXX check for expires? */
7111105197Ssam
7112105197Ssam	/*
7113105197Ssam	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
7114105197Ssam	 * in seconds.  HARD and SOFT lifetime are measured by the time
7115105197Ssam	 * difference (again in seconds) from sadb_lifetime_usetime.
7116105197Ssam	 *
7117105197Ssam	 *	usetime
7118105197Ssam	 *	v     expire   expire
7119105197Ssam	 * -----+-----+--------+---> t
7120105197Ssam	 *	<--------------> HARD
7121105197Ssam	 *	<-----> SOFT
7122105197Ssam	 */
7123105197Ssam	sav->lft_c->sadb_lifetime_usetime = time_second;
7124105197Ssam	/* XXX check for expires? */
7125105197Ssam
7126105197Ssam	return;
7127105197Ssam}
7128105197Ssam
7129105197Ssam/* dumb version */
7130105197Ssamvoid
7131105197Ssamkey_sa_routechange(dst)
7132105197Ssam	struct sockaddr *dst;
7133105197Ssam{
7134105197Ssam	struct secashead *sah;
7135105197Ssam	struct route *ro;
7136105197Ssam
7137120585Ssam	SAHTREE_LOCK();
7138105197Ssam	LIST_FOREACH(sah, &sahtree, chain) {
7139105197Ssam		ro = &sah->sa_route;
7140105197Ssam		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7141105197Ssam		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7142105197Ssam			RTFREE(ro->ro_rt);
7143105197Ssam			ro->ro_rt = (struct rtentry *)NULL;
7144105197Ssam		}
7145105197Ssam	}
7146120585Ssam	SAHTREE_UNLOCK();
7147105197Ssam}
7148105197Ssam
7149105197Ssamstatic void
7150105197Ssamkey_sa_chgstate(sav, state)
7151105197Ssam	struct secasvar *sav;
7152105197Ssam	u_int8_t state;
7153105197Ssam{
7154120585Ssam	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7155120585Ssam	SAHTREE_LOCK_ASSERT();
7156105197Ssam
7157119643Ssam	if (sav->state != state) {
7158119643Ssam		if (__LIST_CHAINED(sav))
7159119643Ssam			LIST_REMOVE(sav, chain);
7160119643Ssam		sav->state = state;
7161119643Ssam		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7162119643Ssam	}
7163105197Ssam}
7164105197Ssam
7165105197Ssamvoid
7166105197Ssamkey_sa_stir_iv(sav)
7167105197Ssam	struct secasvar *sav;
7168105197Ssam{
7169105197Ssam
7170120585Ssam	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7171105197Ssam	key_randomfill(sav->iv, sav->ivlen);
7172105197Ssam}
7173105197Ssam
7174105197Ssam/* XXX too much? */
7175105197Ssamstatic struct mbuf *
7176105197Ssamkey_alloc_mbuf(l)
7177105197Ssam	int l;
7178105197Ssam{
7179105197Ssam	struct mbuf *m = NULL, *n;
7180105197Ssam	int len, t;
7181105197Ssam
7182105197Ssam	len = l;
7183105197Ssam	while (len > 0) {
7184111119Simp		MGET(n, M_DONTWAIT, MT_DATA);
7185105197Ssam		if (n && len > MLEN)
7186111119Simp			MCLGET(n, M_DONTWAIT);
7187105197Ssam		if (!n) {
7188105197Ssam			m_freem(m);
7189105197Ssam			return NULL;
7190105197Ssam		}
7191105197Ssam
7192105197Ssam		n->m_next = NULL;
7193105197Ssam		n->m_len = 0;
7194105197Ssam		n->m_len = M_TRAILINGSPACE(n);
7195105197Ssam		/* use the bottom of mbuf, hoping we can prepend afterwards */
7196105197Ssam		if (n->m_len > len) {
7197105197Ssam			t = (n->m_len - len) & ~(sizeof(long) - 1);
7198105197Ssam			n->m_data += t;
7199105197Ssam			n->m_len = len;
7200105197Ssam		}
7201105197Ssam
7202105197Ssam		len -= n->m_len;
7203105197Ssam
7204105197Ssam		if (m)
7205105197Ssam			m_cat(m, n);
7206105197Ssam		else
7207105197Ssam			m = n;
7208105197Ssam	}
7209105197Ssam
7210105197Ssam	return m;
7211105197Ssam}
7212