key.c revision 193731
1105197Ssam/*	$FreeBSD: head/sys/netipsec/key.c 193731 2009-06-08 17:15:40Z zec $	*/
2105197Ssam/*	$KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $	*/
3105197Ssam
4139823Simp/*-
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>
57158767Spjd#include <sys/refcount.h>
58105197Ssam#include <sys/syslog.h>
59183550Szec#include <sys/vimage.h>
60105197Ssam
61105197Ssam#include <net/if.h>
62105197Ssam#include <net/route.h>
63105197Ssam#include <net/raw_cb.h>
64105197Ssam
65105197Ssam#include <netinet/in.h>
66105197Ssam#include <netinet/in_systm.h>
67105197Ssam#include <netinet/ip.h>
68105197Ssam#include <netinet/in_var.h>
69105197Ssam
70105197Ssam#ifdef INET6
71105197Ssam#include <netinet/ip6.h>
72105197Ssam#include <netinet6/in6_var.h>
73105197Ssam#include <netinet6/ip6_var.h>
74105197Ssam#endif /* INET6 */
75105197Ssam
76105197Ssam#ifdef INET
77105197Ssam#include <netinet/in_pcb.h>
78185571Sbz#include <netinet/vinet.h>
79105197Ssam#endif
80105197Ssam#ifdef INET6
81105197Ssam#include <netinet6/in6_pcb.h>
82185571Sbz#include <netinet6/vinet6.h>
83105197Ssam#endif /* INET6 */
84105197Ssam
85105197Ssam#include <net/pfkeyv2.h>
86105197Ssam#include <netipsec/keydb.h>
87105197Ssam#include <netipsec/key.h>
88105197Ssam#include <netipsec/keysock.h>
89105197Ssam#include <netipsec/key_debug.h>
90105197Ssam
91105197Ssam#include <netipsec/ipsec.h>
92105197Ssam#ifdef INET6
93105197Ssam#include <netipsec/ipsec6.h>
94105197Ssam#endif
95105197Ssam
96105197Ssam#include <netipsec/xform.h>
97105197Ssam
98105197Ssam#include <machine/stdarg.h>
99105197Ssam
100105197Ssam/* randomness */
101105197Ssam#include <sys/random.h>
102181803Sbz#include <sys/vimage.h>
103105197Ssam
104105197Ssam#define FULLMASK	0xff
105105197Ssam#define	_BITS(bytes)	((bytes) << 3)
106105197Ssam
107105197Ssam/*
108105197Ssam * Note on SA reference counting:
109105197Ssam * - SAs that are not in DEAD state will have (total external reference + 1)
110105197Ssam *   following value in reference count field.  they cannot be freed and are
111105197Ssam *   referenced from SA header.
112105197Ssam * - SAs that are in DEAD state will have (total external reference)
113105197Ssam *   in reference count field.  they are ready to be freed.  reference from
114105197Ssam *   SA header will be removed in key_delsav(), when the reference count
115105197Ssam *   field hits 0 (= no external reference other than from SA header.
116105197Ssam */
117105197Ssam
118185088Szec#ifdef VIMAGE_GLOBALS
119185088Szecu_int32_t key_debug_level;
120185088Szecstatic u_int key_spi_trycnt;
121185088Szecstatic u_int32_t key_spi_minval;
122185088Szecstatic u_int32_t key_spi_maxval;
123185088Szecstatic u_int32_t policy_id;
124185088Szecstatic u_int key_int_random;
125185088Szecstatic u_int key_larval_lifetime;
126185088Szecstatic int key_blockacq_count;
127185088Szecstatic int key_blockacq_lifetime;
128185088Szecstatic int key_preferred_oldsa;
129105197Ssam
130185088Szecstatic u_int32_t acq_seq;
131105197Ssam
132185088Szecstatic int ipsec_esp_keymin;
133185088Szecstatic int ipsec_esp_auth;
134185088Szecstatic int ipsec_ah_keymin;
135185088Szec
136105197Ssamstatic LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];	/* SPD */
137185088Szecstatic LIST_HEAD(_sahtree, secashead) sahtree;			/* SAD */
138185088Szecstatic LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
139185088Szecstatic LIST_HEAD(_acqtree, secacq) acqtree;		/* acquiring list */
140185088Szecstatic LIST_HEAD(_spacqtree, secspacq) spacqtree;	/* SP acquiring list */
141185088Szec#endif /* VIMAGE_GLOBALS */
142185088Szec
143119643Ssamstatic struct mtx sptree_lock;
144120585Ssam#define	SPTREE_LOCK_INIT() \
145120585Ssam	mtx_init(&sptree_lock, "sptree", \
146120585Ssam		"fast ipsec security policy database", MTX_DEF)
147120585Ssam#define	SPTREE_LOCK_DESTROY()	mtx_destroy(&sptree_lock)
148120585Ssam#define	SPTREE_LOCK()		mtx_lock(&sptree_lock)
149120585Ssam#define	SPTREE_UNLOCK()	mtx_unlock(&sptree_lock)
150120585Ssam#define	SPTREE_LOCK_ASSERT()	mtx_assert(&sptree_lock, MA_OWNED)
151120585Ssam
152119643Ssamstatic struct mtx sahtree_lock;
153120585Ssam#define	SAHTREE_LOCK_INIT() \
154120585Ssam	mtx_init(&sahtree_lock, "sahtree", \
155120585Ssam		"fast ipsec security association database", MTX_DEF)
156120585Ssam#define	SAHTREE_LOCK_DESTROY()	mtx_destroy(&sahtree_lock)
157120585Ssam#define	SAHTREE_LOCK()		mtx_lock(&sahtree_lock)
158120585Ssam#define	SAHTREE_UNLOCK()	mtx_unlock(&sahtree_lock)
159120585Ssam#define	SAHTREE_LOCK_ASSERT()	mtx_assert(&sahtree_lock, MA_OWNED)
160120585Ssam
161119643Ssam							/* registed list */
162119643Ssamstatic struct mtx regtree_lock;
163120585Ssam#define	REGTREE_LOCK_INIT() \
164120585Ssam	mtx_init(&regtree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
165120585Ssam#define	REGTREE_LOCK_DESTROY()	mtx_destroy(&regtree_lock)
166120585Ssam#define	REGTREE_LOCK()		mtx_lock(&regtree_lock)
167120585Ssam#define	REGTREE_UNLOCK()	mtx_unlock(&regtree_lock)
168120585Ssam#define	REGTREE_LOCK_ASSERT()	mtx_assert(&regtree_lock, MA_OWNED)
169120585Ssam
170119643Ssamstatic struct mtx acq_lock;
171120585Ssam#define	ACQ_LOCK_INIT() \
172120585Ssam	mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
173120585Ssam#define	ACQ_LOCK_DESTROY()	mtx_destroy(&acq_lock)
174120585Ssam#define	ACQ_LOCK()		mtx_lock(&acq_lock)
175120585Ssam#define	ACQ_UNLOCK()		mtx_unlock(&acq_lock)
176120585Ssam#define	ACQ_LOCK_ASSERT()	mtx_assert(&acq_lock, MA_OWNED)
177120585Ssam
178119643Ssamstatic struct mtx spacq_lock;
179120585Ssam#define	SPACQ_LOCK_INIT() \
180120585Ssam	mtx_init(&spacq_lock, "spacqtree", \
181120585Ssam		"fast ipsec security policy acquire list", MTX_DEF)
182120585Ssam#define	SPACQ_LOCK_DESTROY()	mtx_destroy(&spacq_lock)
183120585Ssam#define	SPACQ_LOCK()		mtx_lock(&spacq_lock)
184120585Ssam#define	SPACQ_UNLOCK()		mtx_unlock(&spacq_lock)
185120585Ssam#define	SPACQ_LOCK_ASSERT()	mtx_assert(&spacq_lock, MA_OWNED)
186105197Ssam
187105197Ssam/* search order for SAs */
188128856Ssamstatic const u_int saorder_state_valid_prefer_old[] = {
189105197Ssam	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
190105197Ssam};
191128856Ssamstatic const u_int saorder_state_valid_prefer_new[] = {
192128856Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
193128856Ssam};
194185348Szecstatic const u_int saorder_state_alive[] = {
195105197Ssam	/* except DEAD */
196105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
197105197Ssam};
198185348Szecstatic const u_int saorder_state_any[] = {
199105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
200105197Ssam	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
201105197Ssam};
202105197Ssam
203105197Ssamstatic const int minsize[] = {
204105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
205105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
206105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
207105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
208105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
209105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
210105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
211105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
212105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
213105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
214105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
215105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
216105197Ssam	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
217105197Ssam	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
218105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
219105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
220105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
221105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
222105197Ssam	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
223105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
224105197Ssam};
225105197Ssamstatic const int maxsize[] = {
226105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
227105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
228105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
229105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
230105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
231105197Ssam	0,				/* SADB_EXT_ADDRESS_SRC */
232105197Ssam	0,				/* SADB_EXT_ADDRESS_DST */
233105197Ssam	0,				/* SADB_EXT_ADDRESS_PROXY */
234105197Ssam	0,				/* SADB_EXT_KEY_AUTH */
235105197Ssam	0,				/* SADB_EXT_KEY_ENCRYPT */
236105197Ssam	0,				/* SADB_EXT_IDENTITY_SRC */
237105197Ssam	0,				/* SADB_EXT_IDENTITY_DST */
238105197Ssam	0,				/* SADB_EXT_SENSITIVITY */
239105197Ssam	0,				/* SADB_EXT_PROPOSAL */
240105197Ssam	0,				/* SADB_EXT_SUPPORTED_AUTH */
241105197Ssam	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
242105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
243105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
244105197Ssam	0,				/* SADB_X_EXT_POLICY */
245105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
246105197Ssam};
247105197Ssam
248105197Ssam#ifdef SYSCTL_DECL
249105197SsamSYSCTL_DECL(_net_key);
250105197Ssam#endif
251105197Ssam
252183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec,_net_key, KEYCTL_DEBUG_LEVEL,	debug,
253183550Szec	CTLFLAG_RW, key_debug_level,	0,	"");
254105197Ssam
255105197Ssam/* max count of trial for the decision of spi value */
256183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec,_net_key, KEYCTL_SPI_TRY, spi_trycnt,
257183550Szec	CTLFLAG_RW, key_spi_trycnt,	0,	"");
258105197Ssam
259105197Ssam/* minimum spi value to allocate automatically. */
260183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_SPI_MIN_VALUE,
261183550Szec	spi_minval,	CTLFLAG_RW, key_spi_minval,	0,	"");
262105197Ssam
263105197Ssam/* maximun spi value to allocate automatically. */
264183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_SPI_MAX_VALUE,
265183550Szec	spi_maxval,	CTLFLAG_RW, key_spi_maxval,	0,	"");
266105197Ssam
267105197Ssam/* interval to initialize randseed */
268183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_RANDOM_INT,
269183550Szec	int_random,	CTLFLAG_RW, key_int_random,	0,	"");
270105197Ssam
271105197Ssam/* lifetime for larval SA */
272183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_LARVAL_LIFETIME,
273183550Szec	larval_lifetime, CTLFLAG_RW, key_larval_lifetime,	0,	"");
274105197Ssam
275105197Ssam/* counter for blocking to send SADB_ACQUIRE to IKEd */
276183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_BLOCKACQ_COUNT,
277183550Szec	blockacq_count,	CTLFLAG_RW, key_blockacq_count,	0,	"");
278105197Ssam
279105197Ssam/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
280183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_BLOCKACQ_LIFETIME,
281183550Szec	blockacq_lifetime, CTLFLAG_RW, key_blockacq_lifetime,	0, "");
282105197Ssam
283105197Ssam/* ESP auth */
284183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_ESP_AUTH,	esp_auth,
285183550Szec	CTLFLAG_RW, ipsec_esp_auth,	0,	"");
286105197Ssam
287105197Ssam/* minimum ESP key length */
288183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_ESP_KEYMIN,
289183550Szec	esp_keymin, CTLFLAG_RW, ipsec_esp_keymin,	0,	"");
290105197Ssam
291105197Ssam/* minimum AH key length */
292183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_AH_KEYMIN,	ah_keymin,
293183550Szec	CTLFLAG_RW, ipsec_ah_keymin,	0,	"");
294105197Ssam
295105197Ssam/* perfered old SA rather than new SA */
296183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_PREFERED_OLDSA,
297183550Szec	preferred_oldsa, CTLFLAG_RW, key_preferred_oldsa,	0,	"");
298105197Ssam
299105197Ssam#define __LIST_CHAINED(elm) \
300105197Ssam	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
301105197Ssam#define LIST_INSERT_TAIL(head, elm, type, field) \
302105197Ssamdo {\
303105197Ssam	struct type *curelm = LIST_FIRST(head); \
304105197Ssam	if (curelm == NULL) {\
305105197Ssam		LIST_INSERT_HEAD(head, elm, field); \
306105197Ssam	} else { \
307105197Ssam		while (LIST_NEXT(curelm, field)) \
308105197Ssam			curelm = LIST_NEXT(curelm, field);\
309105197Ssam		LIST_INSERT_AFTER(curelm, elm, field);\
310105197Ssam	}\
311105197Ssam} while (0)
312105197Ssam
313105197Ssam#define KEY_CHKSASTATE(head, sav, name) \
314105197Ssamdo { \
315105197Ssam	if ((head) != (sav)) {						\
316105197Ssam		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
317105197Ssam			(name), (head), (sav)));			\
318105197Ssam		continue;						\
319105197Ssam	}								\
320105197Ssam} while (0)
321105197Ssam
322105197Ssam#define KEY_CHKSPDIR(head, sp, name) \
323105197Ssamdo { \
324105197Ssam	if ((head) != (sp)) {						\
325105197Ssam		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
326105197Ssam			"anyway continue.\n",				\
327105197Ssam			(name), (head), (sp)));				\
328105197Ssam	}								\
329105197Ssam} while (0)
330105197Ssam
331119643SsamMALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
332119643SsamMALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
333119643SsamMALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
334119643SsamMALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
335119643SsamMALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
336119643SsamMALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
337119643SsamMALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
338105197Ssam
339105197Ssam/*
340105197Ssam * set parameters into secpolicyindex buffer.
341105197Ssam * Must allocate secpolicyindex buffer passed to this function.
342105197Ssam */
343105197Ssam#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
344105197Ssamdo { \
345105197Ssam	bzero((idx), sizeof(struct secpolicyindex));                         \
346105197Ssam	(idx)->dir = (_dir);                                                 \
347105197Ssam	(idx)->prefs = (ps);                                                 \
348105197Ssam	(idx)->prefd = (pd);                                                 \
349105197Ssam	(idx)->ul_proto = (ulp);                                             \
350105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
351105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
352105197Ssam} while (0)
353105197Ssam
354105197Ssam/*
355105197Ssam * set parameters into secasindex buffer.
356105197Ssam * Must allocate secasindex buffer before calling this function.
357105197Ssam */
358105197Ssam#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
359105197Ssamdo { \
360105197Ssam	bzero((idx), sizeof(struct secasindex));                             \
361105197Ssam	(idx)->proto = (p);                                                  \
362105197Ssam	(idx)->mode = (m);                                                   \
363105197Ssam	(idx)->reqid = (r);                                                  \
364105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
365105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
366105197Ssam} while (0)
367105197Ssam
368105197Ssam/* key statistics */
369105197Ssamstruct _keystat {
370105197Ssam	u_long getspi_count; /* the avarage of count to try to get new SPI */
371105197Ssam} keystat;
372105197Ssam
373105197Ssamstruct sadb_msghdr {
374105197Ssam	struct sadb_msg *msg;
375105197Ssam	struct sadb_ext *ext[SADB_EXT_MAX + 1];
376105197Ssam	int extoff[SADB_EXT_MAX + 1];
377105197Ssam	int extlen[SADB_EXT_MAX + 1];
378105197Ssam};
379105197Ssam
380105197Ssamstatic struct secasvar *key_allocsa_policy __P((const struct secasindex *));
381105197Ssamstatic void key_freesp_so __P((struct secpolicy **));
382105197Ssamstatic struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
383105197Ssamstatic void key_delsp __P((struct secpolicy *));
384105197Ssamstatic struct secpolicy *key_getsp __P((struct secpolicyindex *));
385119643Ssamstatic void _key_delsp(struct secpolicy *sp);
386105197Ssamstatic struct secpolicy *key_getspbyid __P((u_int32_t));
387105197Ssamstatic u_int32_t key_newreqid __P((void));
388105197Ssamstatic struct mbuf *key_gather_mbuf __P((struct mbuf *,
389105197Ssam	const struct sadb_msghdr *, int, int, ...));
390105197Ssamstatic int key_spdadd __P((struct socket *, struct mbuf *,
391105197Ssam	const struct sadb_msghdr *));
392105197Ssamstatic u_int32_t key_getnewspid __P((void));
393105197Ssamstatic int key_spddelete __P((struct socket *, struct mbuf *,
394105197Ssam	const struct sadb_msghdr *));
395105197Ssamstatic int key_spddelete2 __P((struct socket *, struct mbuf *,
396105197Ssam	const struct sadb_msghdr *));
397105197Ssamstatic int key_spdget __P((struct socket *, struct mbuf *,
398105197Ssam	const struct sadb_msghdr *));
399105197Ssamstatic int key_spdflush __P((struct socket *, struct mbuf *,
400105197Ssam	const struct sadb_msghdr *));
401105197Ssamstatic int key_spddump __P((struct socket *, struct mbuf *,
402105197Ssam	const struct sadb_msghdr *));
403105197Ssamstatic struct mbuf *key_setdumpsp __P((struct secpolicy *,
404105197Ssam	u_int8_t, u_int32_t, u_int32_t));
405105197Ssamstatic u_int key_getspreqmsglen __P((struct secpolicy *));
406105197Ssamstatic int key_spdexpire __P((struct secpolicy *));
407105197Ssamstatic struct secashead *key_newsah __P((struct secasindex *));
408105197Ssamstatic void key_delsah __P((struct secashead *));
409105197Ssamstatic struct secasvar *key_newsav __P((struct mbuf *,
410105197Ssam	const struct sadb_msghdr *, struct secashead *, int *,
411105197Ssam	const char*, int));
412105197Ssam#define	KEY_NEWSAV(m, sadb, sah, e)				\
413105197Ssam	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
414105197Ssamstatic void key_delsav __P((struct secasvar *));
415105197Ssamstatic struct secashead *key_getsah __P((struct secasindex *));
416105197Ssamstatic struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
417105197Ssamstatic struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
418105197Ssamstatic int key_setsaval __P((struct secasvar *, struct mbuf *,
419105197Ssam	const struct sadb_msghdr *));
420105197Ssamstatic int key_mature __P((struct secasvar *));
421105197Ssamstatic struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
422105197Ssam	u_int8_t, u_int32_t, u_int32_t));
423105197Ssamstatic struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
424105197Ssam	u_int32_t, pid_t, u_int16_t));
425105197Ssamstatic struct mbuf *key_setsadbsa __P((struct secasvar *));
426105197Ssamstatic struct mbuf *key_setsadbaddr __P((u_int16_t,
427105197Ssam	const struct sockaddr *, u_int8_t, u_int16_t));
428105197Ssamstatic struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
429105197Ssamstatic struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
430105197Ssam	u_int32_t));
431157123Sgnnstatic struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
432157123Sgnn				     struct malloc_type *);
433157123Sgnnstatic struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
434157123Sgnn					    struct malloc_type *type);
435105197Ssam#ifdef INET6
436105197Ssamstatic int key_ismyaddr6 __P((struct sockaddr_in6 *));
437105197Ssam#endif
438105197Ssam
439105197Ssam/* flags for key_cmpsaidx() */
440105197Ssam#define CMP_HEAD	1	/* protocol, addresses. */
441105197Ssam#define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
442105197Ssam#define CMP_REQID	3	/* additionally HEAD, reaid. */
443105197Ssam#define CMP_EXACTLY	4	/* all elements. */
444105197Ssamstatic int key_cmpsaidx
445105197Ssam	__P((const struct secasindex *, const struct secasindex *, int));
446105197Ssam
447105197Ssamstatic int key_cmpspidx_exactly
448105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
449105197Ssamstatic int key_cmpspidx_withmask
450105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
451105197Ssamstatic int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
452105197Ssamstatic int key_bbcmp __P((const void *, const void *, u_int));
453105197Ssamstatic u_int16_t key_satype2proto __P((u_int8_t));
454105197Ssamstatic u_int8_t key_proto2satype __P((u_int16_t));
455105197Ssam
456105197Ssamstatic int key_getspi __P((struct socket *, struct mbuf *,
457105197Ssam	const struct sadb_msghdr *));
458105197Ssamstatic u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
459105197Ssam					struct secasindex *));
460105197Ssamstatic int key_update __P((struct socket *, struct mbuf *,
461105197Ssam	const struct sadb_msghdr *));
462105197Ssam#ifdef IPSEC_DOSEQCHECK
463105197Ssamstatic struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
464105197Ssam#endif
465105197Ssamstatic int key_add __P((struct socket *, struct mbuf *,
466105197Ssam	const struct sadb_msghdr *));
467105197Ssamstatic int key_setident __P((struct secashead *, struct mbuf *,
468105197Ssam	const struct sadb_msghdr *));
469105197Ssamstatic struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
470105197Ssam	const struct sadb_msghdr *));
471105197Ssamstatic int key_delete __P((struct socket *, struct mbuf *,
472105197Ssam	const struct sadb_msghdr *));
473105197Ssamstatic int key_get __P((struct socket *, struct mbuf *,
474105197Ssam	const struct sadb_msghdr *));
475105197Ssam
476105197Ssamstatic void key_getcomb_setlifetime __P((struct sadb_comb *));
477105197Ssamstatic struct mbuf *key_getcomb_esp __P((void));
478105197Ssamstatic struct mbuf *key_getcomb_ah __P((void));
479105197Ssamstatic struct mbuf *key_getcomb_ipcomp __P((void));
480105197Ssamstatic struct mbuf *key_getprop __P((const struct secasindex *));
481105197Ssam
482105197Ssamstatic int key_acquire __P((const struct secasindex *, struct secpolicy *));
483105197Ssamstatic struct secacq *key_newacq __P((const struct secasindex *));
484105197Ssamstatic struct secacq *key_getacq __P((const struct secasindex *));
485105197Ssamstatic struct secacq *key_getacqbyseq __P((u_int32_t));
486105197Ssamstatic struct secspacq *key_newspacq __P((struct secpolicyindex *));
487105197Ssamstatic struct secspacq *key_getspacq __P((struct secpolicyindex *));
488105197Ssamstatic int key_acquire2 __P((struct socket *, struct mbuf *,
489105197Ssam	const struct sadb_msghdr *));
490105197Ssamstatic int key_register __P((struct socket *, struct mbuf *,
491105197Ssam	const struct sadb_msghdr *));
492105197Ssamstatic int key_expire __P((struct secasvar *));
493105197Ssamstatic int key_flush __P((struct socket *, struct mbuf *,
494105197Ssam	const struct sadb_msghdr *));
495105197Ssamstatic int key_dump __P((struct socket *, struct mbuf *,
496105197Ssam	const struct sadb_msghdr *));
497105197Ssamstatic int key_promisc __P((struct socket *, struct mbuf *,
498105197Ssam	const struct sadb_msghdr *));
499105197Ssamstatic int key_senderror __P((struct socket *, struct mbuf *, int));
500105197Ssamstatic int key_validate_ext __P((const struct sadb_ext *, int));
501105197Ssamstatic int key_align __P((struct mbuf *, struct sadb_msghdr *));
502157123Sgnnstatic struct mbuf *key_setlifetime(struct seclifetime *src,
503157123Sgnn				     u_int16_t exttype);
504157123Sgnnstatic struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
505157123Sgnn
506105197Ssam#if 0
507105197Ssamstatic const char *key_getfqdn __P((void));
508105197Ssamstatic const char *key_getuserfqdn __P((void));
509105197Ssam#endif
510105197Ssamstatic void key_sa_chgstate __P((struct secasvar *, u_int8_t));
511105197Ssamstatic struct mbuf *key_alloc_mbuf __P((int));
512105197Ssam
513158767Spjdstatic __inline void
514158767Spjdsa_initref(struct secasvar *sav)
515158767Spjd{
516105197Ssam
517158767Spjd	refcount_init(&sav->refcnt, 1);
518158767Spjd}
519158767Spjdstatic __inline void
520158767Spjdsa_addref(struct secasvar *sav)
521158767Spjd{
522158767Spjd
523158767Spjd	refcount_acquire(&sav->refcnt);
524158767Spjd	IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
525158767Spjd}
526158767Spjdstatic __inline int
527158767Spjdsa_delref(struct secasvar *sav)
528158767Spjd{
529158767Spjd
530158767Spjd	IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
531158767Spjd	return (refcount_release(&sav->refcnt));
532158767Spjd}
533158767Spjd
534105197Ssam#define	SP_ADDREF(p) do {						\
535105197Ssam	(p)->refcnt++;							\
536120585Ssam	IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));		\
537105197Ssam} while (0)
538105197Ssam#define	SP_DELREF(p) do {						\
539120585Ssam	IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));		\
540105197Ssam	(p)->refcnt--;							\
541105197Ssam} while (0)
542135947Ssam
543105197Ssam
544105197Ssam/*
545135947Ssam * Update the refcnt while holding the SPTREE lock.
546135947Ssam */
547135947Ssamvoid
548135947Ssamkey_addref(struct secpolicy *sp)
549135947Ssam{
550135947Ssam	SPTREE_LOCK();
551135947Ssam	SP_ADDREF(sp);
552135947Ssam	SPTREE_UNLOCK();
553135947Ssam}
554135947Ssam
555135947Ssam/*
556105197Ssam * Return 0 when there are known to be no SP's for the specified
557105197Ssam * direction.  Otherwise return 1.  This is used by IPsec code
558105197Ssam * to optimize performance.
559105197Ssam */
560105197Ssamint
561105197Ssamkey_havesp(u_int dir)
562105197Ssam{
563183550Szec	INIT_VNET_IPSEC(curvnet);
564183550Szec
565105197Ssam	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
566181803Sbz		LIST_FIRST(&V_sptree[dir]) != NULL : 1);
567105197Ssam}
568105197Ssam
569105197Ssam/* %%% IPsec policy management */
570105197Ssam/*
571105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
572105197Ssam * Must call key_freesp() later.
573105197Ssam * OUT:	NULL:	not found
574105197Ssam *	others:	found and return the pointer.
575105197Ssam */
576105197Ssamstruct secpolicy *
577105197Ssamkey_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
578105197Ssam{
579183550Szec	INIT_VNET_IPSEC(curvnet);
580105197Ssam	struct secpolicy *sp;
581105197Ssam
582120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
583120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
584120585Ssam		("invalid direction %u", dir));
585105197Ssam
586105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
587120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
588105197Ssam
589105197Ssam	/* get a SP entry */
590105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
591105197Ssam		printf("*** objects\n");
592105197Ssam		kdebug_secpolicyindex(spidx));
593105197Ssam
594120585Ssam	SPTREE_LOCK();
595181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
596105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
597105197Ssam			printf("*** in SPD\n");
598105197Ssam			kdebug_secpolicyindex(&sp->spidx));
599105197Ssam
600105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
601105197Ssam			continue;
602105197Ssam		if (key_cmpspidx_withmask(&sp->spidx, spidx))
603105197Ssam			goto found;
604105197Ssam	}
605105197Ssam	sp = NULL;
606105197Ssamfound:
607105197Ssam	if (sp) {
608105197Ssam		/* sanity check */
609120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
610105197Ssam
611105197Ssam		/* found a SPD entry */
612105197Ssam		sp->lastused = time_second;
613105197Ssam		SP_ADDREF(sp);
614105197Ssam	}
615120585Ssam	SPTREE_UNLOCK();
616105197Ssam
617105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
618120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
619105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
620105197Ssam	return sp;
621105197Ssam}
622105197Ssam
623105197Ssam/*
624105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
625105197Ssam * Must call key_freesp() later.
626105197Ssam * OUT:	NULL:	not found
627105197Ssam *	others:	found and return the pointer.
628105197Ssam */
629105197Ssamstruct secpolicy *
630105197Ssamkey_allocsp2(u_int32_t spi,
631105197Ssam	     union sockaddr_union *dst,
632105197Ssam	     u_int8_t proto,
633105197Ssam	     u_int dir,
634105197Ssam	     const char* where, int tag)
635105197Ssam{
636183550Szec	INIT_VNET_IPSEC(curvnet);
637105197Ssam	struct secpolicy *sp;
638105197Ssam
639120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst"));
640120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
641120585Ssam		("invalid direction %u", dir));
642105197Ssam
643105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
644120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
645105197Ssam
646105197Ssam	/* get a SP entry */
647105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
648105197Ssam		printf("*** objects\n");
649105197Ssam		printf("spi %u proto %u dir %u\n", spi, proto, dir);
650105197Ssam		kdebug_sockaddr(&dst->sa));
651105197Ssam
652120585Ssam	SPTREE_LOCK();
653181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
654105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
655105197Ssam			printf("*** in SPD\n");
656105197Ssam			kdebug_secpolicyindex(&sp->spidx));
657105197Ssam
658105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
659105197Ssam			continue;
660105197Ssam		/* compare simple values, then dst address */
661105197Ssam		if (sp->spidx.ul_proto != proto)
662105197Ssam			continue;
663105197Ssam		/* NB: spi's must exist and match */
664105197Ssam		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
665105197Ssam			continue;
666105197Ssam		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
667105197Ssam			goto found;
668105197Ssam	}
669105197Ssam	sp = NULL;
670105197Ssamfound:
671105197Ssam	if (sp) {
672105197Ssam		/* sanity check */
673120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
674105197Ssam
675105197Ssam		/* found a SPD entry */
676105197Ssam		sp->lastused = time_second;
677105197Ssam		SP_ADDREF(sp);
678105197Ssam	}
679120585Ssam	SPTREE_UNLOCK();
680105197Ssam
681105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
682120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
683105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
684105197Ssam	return sp;
685105197Ssam}
686105197Ssam
687191599Sbz#if 0
688105197Ssam/*
689105197Ssam * return a policy that matches this particular inbound packet.
690105197Ssam * XXX slow
691105197Ssam */
692105197Ssamstruct secpolicy *
693105197Ssamkey_gettunnel(const struct sockaddr *osrc,
694105197Ssam	      const struct sockaddr *odst,
695105197Ssam	      const struct sockaddr *isrc,
696105197Ssam	      const struct sockaddr *idst,
697105197Ssam	      const char* where, int tag)
698105197Ssam{
699183550Szec	INIT_VNET_IPSEC(curvnet);
700105197Ssam	struct secpolicy *sp;
701105197Ssam	const int dir = IPSEC_DIR_INBOUND;
702105197Ssam	struct ipsecrequest *r1, *r2, *p;
703105197Ssam	struct secpolicyindex spidx;
704105197Ssam
705105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
706120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
707105197Ssam
708105197Ssam	if (isrc->sa_family != idst->sa_family) {
709120585Ssam		ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
710120585Ssam			__func__, isrc->sa_family, idst->sa_family));
711105197Ssam		sp = NULL;
712105197Ssam		goto done;
713105197Ssam	}
714105197Ssam
715120585Ssam	SPTREE_LOCK();
716181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
717105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
718105197Ssam			continue;
719105197Ssam
720105197Ssam		r1 = r2 = NULL;
721105197Ssam		for (p = sp->req; p; p = p->next) {
722105197Ssam			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
723105197Ssam				continue;
724105197Ssam
725105197Ssam			r1 = r2;
726105197Ssam			r2 = p;
727105197Ssam
728105197Ssam			if (!r1) {
729105197Ssam				/* here we look at address matches only */
730105197Ssam				spidx = sp->spidx;
731105197Ssam				if (isrc->sa_len > sizeof(spidx.src) ||
732105197Ssam				    idst->sa_len > sizeof(spidx.dst))
733105197Ssam					continue;
734105197Ssam				bcopy(isrc, &spidx.src, isrc->sa_len);
735105197Ssam				bcopy(idst, &spidx.dst, idst->sa_len);
736105197Ssam				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
737105197Ssam					continue;
738105197Ssam			} else {
739105197Ssam				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
740105197Ssam				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
741105197Ssam					continue;
742105197Ssam			}
743105197Ssam
744105197Ssam			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
745105197Ssam			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
746105197Ssam				continue;
747105197Ssam
748105197Ssam			goto found;
749105197Ssam		}
750105197Ssam	}
751105197Ssam	sp = NULL;
752105197Ssamfound:
753105197Ssam	if (sp) {
754105197Ssam		sp->lastused = time_second;
755105197Ssam		SP_ADDREF(sp);
756105197Ssam	}
757120585Ssam	SPTREE_UNLOCK();
758105197Ssamdone:
759105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
760120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
761105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
762105197Ssam	return sp;
763105197Ssam}
764191599Sbz#endif
765105197Ssam
766105197Ssam/*
767105197Ssam * allocating an SA entry for an *OUTBOUND* packet.
768105197Ssam * checking each request entries in SP, and acquire an SA if need.
769105197Ssam * OUT:	0: there are valid requests.
770105197Ssam *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
771105197Ssam */
772105197Ssamint
773105197Ssamkey_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
774105197Ssam{
775183550Szec	INIT_VNET_IPSEC(curvnet);
776105197Ssam	u_int level;
777105197Ssam	int error;
778105197Ssam
779120585Ssam	IPSEC_ASSERT(isr != NULL, ("null isr"));
780120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
781120585Ssam	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
782105197Ssam		saidx->mode == IPSEC_MODE_TUNNEL,
783120585Ssam		("unexpected policy %u", saidx->mode));
784105197Ssam
785105197Ssam	/*
786105197Ssam	 * XXX guard against protocol callbacks from the crypto
787105197Ssam	 * thread as they reference ipsecrequest.sav which we
788105197Ssam	 * temporarily null out below.  Need to rethink how we
789105197Ssam	 * handle bundled SA's in the callback thread.
790105197Ssam	 */
791120585Ssam	IPSECREQUEST_LOCK_ASSERT(isr);
792119643Ssam
793119643Ssam	/* get current level */
794119643Ssam	level = ipsec_get_reqlevel(isr);
795105197Ssam#if 0
796105197Ssam	/*
797105197Ssam	 * We do allocate new SA only if the state of SA in the holder is
798105197Ssam	 * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
799105197Ssam	 */
800105197Ssam	if (isr->sav != NULL) {
801105197Ssam		if (isr->sav->sah == NULL)
802120585Ssam			panic("%s: sah is null.\n", __func__);
803105197Ssam		if (isr->sav == (struct secasvar *)LIST_FIRST(
804105197Ssam			    &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
805105197Ssam			KEY_FREESAV(&isr->sav);
806105197Ssam			isr->sav = NULL;
807105197Ssam		}
808105197Ssam	}
809105197Ssam#else
810105197Ssam	/*
811105197Ssam	 * we free any SA stashed in the IPsec request because a different
812105197Ssam	 * SA may be involved each time this request is checked, either
813105197Ssam	 * because new SAs are being configured, or this request is
814105197Ssam	 * associated with an unconnected datagram socket, or this request
815105197Ssam	 * is associated with a system default policy.
816105197Ssam	 *
817105197Ssam	 * The operation may have negative impact to performance.  We may
818105197Ssam	 * want to check cached SA carefully, rather than picking new SA
819105197Ssam	 * every time.
820105197Ssam	 */
821105197Ssam	if (isr->sav != NULL) {
822105197Ssam		KEY_FREESAV(&isr->sav);
823105197Ssam		isr->sav = NULL;
824105197Ssam	}
825105197Ssam#endif
826105197Ssam
827105197Ssam	/*
828105197Ssam	 * new SA allocation if no SA found.
829105197Ssam	 * key_allocsa_policy should allocate the oldest SA available.
830105197Ssam	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
831105197Ssam	 */
832105197Ssam	if (isr->sav == NULL)
833105197Ssam		isr->sav = key_allocsa_policy(saidx);
834105197Ssam
835105197Ssam	/* When there is SA. */
836105197Ssam	if (isr->sav != NULL) {
837105197Ssam		if (isr->sav->state != SADB_SASTATE_MATURE &&
838105197Ssam		    isr->sav->state != SADB_SASTATE_DYING)
839105197Ssam			return EINVAL;
840105197Ssam		return 0;
841105197Ssam	}
842105197Ssam
843105197Ssam	/* there is no SA */
844105197Ssam	error = key_acquire(saidx, isr->sp);
845105197Ssam	if (error != 0) {
846105197Ssam		/* XXX What should I do ? */
847120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
848120585Ssam			__func__, error));
849105197Ssam		return error;
850105197Ssam	}
851105197Ssam
852105197Ssam	if (level != IPSEC_LEVEL_REQUIRE) {
853105197Ssam		/* XXX sigh, the interface to this routine is botched */
854120585Ssam		IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
855105197Ssam		return 0;
856105197Ssam	} else {
857105197Ssam		return ENOENT;
858105197Ssam	}
859105197Ssam}
860105197Ssam
861105197Ssam/*
862105197Ssam * allocating a SA for policy entry from SAD.
863105197Ssam * NOTE: searching SAD of aliving state.
864105197Ssam * OUT:	NULL:	not found.
865105197Ssam *	others:	found and return the pointer.
866105197Ssam */
867105197Ssamstatic struct secasvar *
868105197Ssamkey_allocsa_policy(const struct secasindex *saidx)
869105197Ssam{
870128856Ssam#define	N(a)	_ARRAYLEN(a)
871183550Szec	INIT_VNET_IPSEC(curvnet);
872105197Ssam	struct secashead *sah;
873105197Ssam	struct secasvar *sav;
874128856Ssam	u_int stateidx, arraysize;
875128856Ssam	const u_int *state_valid;
876105197Ssam
877120585Ssam	SAHTREE_LOCK();
878181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
879105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
880105197Ssam			continue;
881119643Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
882181803Sbz			if (V_key_preferred_oldsa) {
883128856Ssam				state_valid = saorder_state_valid_prefer_old;
884128856Ssam				arraysize = N(saorder_state_valid_prefer_old);
885128856Ssam			} else {
886128856Ssam				state_valid = saorder_state_valid_prefer_new;
887128856Ssam				arraysize = N(saorder_state_valid_prefer_new);
888128856Ssam			}
889120585Ssam			SAHTREE_UNLOCK();
890105197Ssam			goto found;
891119643Ssam		}
892105197Ssam	}
893120585Ssam	SAHTREE_UNLOCK();
894105197Ssam
895105197Ssam	return NULL;
896105197Ssam
897105197Ssam    found:
898105197Ssam	/* search valid state */
899128856Ssam	for (stateidx = 0; stateidx < arraysize; stateidx++) {
900128856Ssam		sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
901105197Ssam		if (sav != NULL)
902105197Ssam			return sav;
903105197Ssam	}
904105197Ssam
905105197Ssam	return NULL;
906128856Ssam#undef N
907105197Ssam}
908105197Ssam
909105197Ssam/*
910105197Ssam * searching SAD with direction, protocol, mode and state.
911105197Ssam * called by key_allocsa_policy().
912105197Ssam * OUT:
913105197Ssam *	NULL	: not found
914105197Ssam *	others	: found, pointer to a SA.
915105197Ssam */
916105197Ssamstatic struct secasvar *
917105197Ssamkey_do_allocsa_policy(struct secashead *sah, u_int state)
918105197Ssam{
919183550Szec	INIT_VNET_IPSEC(curvnet);
920105197Ssam	struct secasvar *sav, *nextsav, *candidate, *d;
921105197Ssam
922105197Ssam	/* initilize */
923105197Ssam	candidate = NULL;
924105197Ssam
925120585Ssam	SAHTREE_LOCK();
926105197Ssam	for (sav = LIST_FIRST(&sah->savtree[state]);
927105197Ssam	     sav != NULL;
928105197Ssam	     sav = nextsav) {
929105197Ssam
930105197Ssam		nextsav = LIST_NEXT(sav, chain);
931105197Ssam
932105197Ssam		/* sanity check */
933120585Ssam		KEY_CHKSASTATE(sav->state, state, __func__);
934105197Ssam
935105197Ssam		/* initialize */
936105197Ssam		if (candidate == NULL) {
937105197Ssam			candidate = sav;
938105197Ssam			continue;
939105197Ssam		}
940105197Ssam
941105197Ssam		/* Which SA is the better ? */
942105197Ssam
943120585Ssam		IPSEC_ASSERT(candidate->lft_c != NULL,
944120585Ssam			("null candidate lifetime"));
945120585Ssam		IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
946105197Ssam
947105197Ssam		/* What the best method is to compare ? */
948181803Sbz		if (V_key_preferred_oldsa) {
949157123Sgnn			if (candidate->lft_c->addtime >
950157123Sgnn					sav->lft_c->addtime) {
951105197Ssam				candidate = sav;
952105197Ssam			}
953105197Ssam			continue;
954105197Ssam			/*NOTREACHED*/
955105197Ssam		}
956105197Ssam
957125876Sguido		/* preferred new sa rather than old sa */
958157123Sgnn		if (candidate->lft_c->addtime <
959157123Sgnn				sav->lft_c->addtime) {
960105197Ssam			d = candidate;
961105197Ssam			candidate = sav;
962105197Ssam		} else
963105197Ssam			d = sav;
964105197Ssam
965105197Ssam		/*
966105197Ssam		 * prepared to delete the SA when there is more
967105197Ssam		 * suitable candidate and the lifetime of the SA is not
968105197Ssam		 * permanent.
969105197Ssam		 */
970177553Sbz		if (d->lft_h->addtime != 0) {
971105197Ssam			struct mbuf *m, *result;
972125508Ssam			u_int8_t satype;
973105197Ssam
974105197Ssam			key_sa_chgstate(d, SADB_SASTATE_DEAD);
975105197Ssam
976120585Ssam			IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
977125508Ssam
978125508Ssam			satype = key_proto2satype(d->sah->saidx.proto);
979125508Ssam			if (satype == 0)
980125508Ssam				goto msgfail;
981125508Ssam
982105197Ssam			m = key_setsadbmsg(SADB_DELETE, 0,
983125508Ssam			    satype, 0, 0, d->refcnt - 1);
984105197Ssam			if (!m)
985105197Ssam				goto msgfail;
986105197Ssam			result = m;
987105197Ssam
988105197Ssam			/* set sadb_address for saidx's. */
989105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
990105197Ssam				&d->sah->saidx.src.sa,
991105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
992105197Ssam				IPSEC_ULPROTO_ANY);
993105197Ssam			if (!m)
994105197Ssam				goto msgfail;
995105197Ssam			m_cat(result, m);
996105197Ssam
997105197Ssam			/* set sadb_address for saidx's. */
998105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
999128860Ssam				&d->sah->saidx.dst.sa,
1000128860Ssam				d->sah->saidx.dst.sa.sa_len << 3,
1001105197Ssam				IPSEC_ULPROTO_ANY);
1002105197Ssam			if (!m)
1003105197Ssam				goto msgfail;
1004105197Ssam			m_cat(result, m);
1005105197Ssam
1006105197Ssam			/* create SA extension */
1007105197Ssam			m = key_setsadbsa(d);
1008105197Ssam			if (!m)
1009105197Ssam				goto msgfail;
1010105197Ssam			m_cat(result, m);
1011105197Ssam
1012105197Ssam			if (result->m_len < sizeof(struct sadb_msg)) {
1013105197Ssam				result = m_pullup(result,
1014105197Ssam						sizeof(struct sadb_msg));
1015105197Ssam				if (result == NULL)
1016105197Ssam					goto msgfail;
1017105197Ssam			}
1018105197Ssam
1019105197Ssam			result->m_pkthdr.len = 0;
1020105197Ssam			for (m = result; m; m = m->m_next)
1021105197Ssam				result->m_pkthdr.len += m->m_len;
1022105197Ssam			mtod(result, struct sadb_msg *)->sadb_msg_len =
1023105197Ssam				PFKEY_UNIT64(result->m_pkthdr.len);
1024105197Ssam
1025105197Ssam			if (key_sendup_mbuf(NULL, result,
1026105197Ssam					KEY_SENDUP_REGISTERED))
1027105197Ssam				goto msgfail;
1028105197Ssam		 msgfail:
1029105197Ssam			KEY_FREESAV(&d);
1030105197Ssam		}
1031105197Ssam	}
1032105197Ssam	if (candidate) {
1033158767Spjd		sa_addref(candidate);
1034105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1035120585Ssam			printf("DP %s cause refcnt++:%d SA:%p\n",
1036120585Ssam				__func__, candidate->refcnt, candidate));
1037105197Ssam	}
1038120585Ssam	SAHTREE_UNLOCK();
1039119643Ssam
1040105197Ssam	return candidate;
1041105197Ssam}
1042105197Ssam
1043105197Ssam/*
1044105197Ssam * allocating a usable SA entry for a *INBOUND* packet.
1045105197Ssam * Must call key_freesav() later.
1046105197Ssam * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
1047105197Ssam *	NULL:		not found, or error occured.
1048105197Ssam *
1049105197Ssam * In the comparison, no source address is used--for RFC2401 conformance.
1050105197Ssam * To quote, from section 4.1:
1051105197Ssam *	A security association is uniquely identified by a triple consisting
1052105197Ssam *	of a Security Parameter Index (SPI), an IP Destination Address, and a
1053105197Ssam *	security protocol (AH or ESP) identifier.
1054105197Ssam * Note that, however, we do need to keep source address in IPsec SA.
1055105197Ssam * IKE specification and PF_KEY specification do assume that we
1056105197Ssam * keep source address in IPsec SA.  We see a tricky situation here.
1057105197Ssam */
1058105197Ssamstruct secasvar *
1059105197Ssamkey_allocsa(
1060105197Ssam	union sockaddr_union *dst,
1061105197Ssam	u_int proto,
1062105197Ssam	u_int32_t spi,
1063105197Ssam	const char* where, int tag)
1064105197Ssam{
1065183550Szec	INIT_VNET_IPSEC(curvnet);
1066105197Ssam	struct secashead *sah;
1067105197Ssam	struct secasvar *sav;
1068128856Ssam	u_int stateidx, arraysize, state;
1069128856Ssam	const u_int *saorder_state_valid;
1070105197Ssam
1071120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst address"));
1072105197Ssam
1073105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1074120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
1075105197Ssam
1076105197Ssam	/*
1077105197Ssam	 * searching SAD.
1078105197Ssam	 * XXX: to be checked internal IP header somewhere.  Also when
1079105197Ssam	 * IPsec tunnel packet is received.  But ESP tunnel mode is
1080105197Ssam	 * encrypted so we can't check internal IP header.
1081105197Ssam	 */
1082120585Ssam	SAHTREE_LOCK();
1083181803Sbz	if (V_key_preferred_oldsa) {
1084128856Ssam		saorder_state_valid = saorder_state_valid_prefer_old;
1085128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1086128856Ssam	} else {
1087128856Ssam		saorder_state_valid = saorder_state_valid_prefer_new;
1088128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1089128856Ssam	}
1090181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
1091105197Ssam		/* search valid state */
1092128856Ssam		for (stateidx = 0; stateidx < arraysize; stateidx++) {
1093105197Ssam			state = saorder_state_valid[stateidx];
1094105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
1095105197Ssam				/* sanity check */
1096120585Ssam				KEY_CHKSASTATE(sav->state, state, __func__);
1097105197Ssam				/* do not return entries w/ unusable state */
1098105197Ssam				if (sav->state != SADB_SASTATE_MATURE &&
1099105197Ssam				    sav->state != SADB_SASTATE_DYING)
1100105197Ssam					continue;
1101105197Ssam				if (proto != sav->sah->saidx.proto)
1102105197Ssam					continue;
1103105197Ssam				if (spi != sav->spi)
1104105197Ssam					continue;
1105105197Ssam#if 0	/* don't check src */
1106105197Ssam				/* check src address */
1107105197Ssam				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, 0) != 0)
1108105197Ssam					continue;
1109105197Ssam#endif
1110105197Ssam				/* check dst address */
1111105197Ssam				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, 0) != 0)
1112105197Ssam					continue;
1113158767Spjd				sa_addref(sav);
1114105197Ssam				goto done;
1115105197Ssam			}
1116105197Ssam		}
1117105197Ssam	}
1118105197Ssam	sav = NULL;
1119105197Ssamdone:
1120120585Ssam	SAHTREE_UNLOCK();
1121105197Ssam
1122105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1123120585Ssam		printf("DP %s return SA:%p; refcnt %u\n", __func__,
1124105197Ssam			sav, sav ? sav->refcnt : 0));
1125105197Ssam	return sav;
1126105197Ssam}
1127105197Ssam
1128105197Ssam/*
1129105197Ssam * Must be called after calling key_allocsp().
1130105197Ssam * For both the packet without socket and key_freeso().
1131105197Ssam */
1132105197Ssamvoid
1133105197Ssam_key_freesp(struct secpolicy **spp, const char* where, int tag)
1134105197Ssam{
1135183550Szec	INIT_VNET_IPSEC(curvnet);
1136105197Ssam	struct secpolicy *sp = *spp;
1137105197Ssam
1138120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1139105197Ssam
1140120585Ssam	SPTREE_LOCK();
1141105197Ssam	SP_DELREF(sp);
1142105197Ssam
1143105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1144120585Ssam		printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1145120585Ssam			__func__, sp, sp->id, where, tag, sp->refcnt));
1146105197Ssam
1147105197Ssam	if (sp->refcnt == 0) {
1148105197Ssam		*spp = NULL;
1149105197Ssam		key_delsp(sp);
1150105197Ssam	}
1151120585Ssam	SPTREE_UNLOCK();
1152105197Ssam}
1153105197Ssam
1154105197Ssam/*
1155105197Ssam * Must be called after calling key_allocsp().
1156105197Ssam * For the packet with socket.
1157105197Ssam */
1158105197Ssamvoid
1159105197Ssamkey_freeso(struct socket *so)
1160105197Ssam{
1161183550Szec	INIT_VNET_IPSEC(curvnet);
1162120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
1163105197Ssam
1164105197Ssam	switch (so->so_proto->pr_domain->dom_family) {
1165186141Sbz#if defined(INET) || defined(INET6)
1166105197Ssam#ifdef INET
1167105197Ssam	case PF_INET:
1168105197Ssam#endif
1169105197Ssam#ifdef INET6
1170105197Ssam	case PF_INET6:
1171186141Sbz#endif
1172105197Ssam	    {
1173186141Sbz		struct inpcb *pcb = sotoinpcb(so);
1174105197Ssam
1175105197Ssam		/* Does it have a PCB ? */
1176105197Ssam		if (pcb == NULL)
1177105197Ssam			return;
1178105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1179105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1180105197Ssam	    }
1181105197Ssam		break;
1182186141Sbz#endif /* INET || INET6 */
1183105197Ssam	default:
1184120585Ssam		ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1185120585Ssam		    __func__, so->so_proto->pr_domain->dom_family));
1186105197Ssam		return;
1187105197Ssam	}
1188105197Ssam}
1189105197Ssam
1190105197Ssamstatic void
1191105197Ssamkey_freesp_so(struct secpolicy **sp)
1192105197Ssam{
1193120585Ssam	IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1194105197Ssam
1195105197Ssam	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1196105197Ssam	    (*sp)->policy == IPSEC_POLICY_BYPASS)
1197105197Ssam		return;
1198105197Ssam
1199120585Ssam	IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1200120585Ssam		("invalid policy %u", (*sp)->policy));
1201105197Ssam	KEY_FREESP(sp);
1202105197Ssam}
1203105197Ssam
1204105197Ssam/*
1205105197Ssam * Must be called after calling key_allocsa().
1206105197Ssam * This function is called by key_freesp() to free some SA allocated
1207105197Ssam * for a policy.
1208105197Ssam */
1209105197Ssamvoid
1210105197Ssamkey_freesav(struct secasvar **psav, const char* where, int tag)
1211105197Ssam{
1212183550Szec	INIT_VNET_IPSEC(curvnet);
1213105197Ssam	struct secasvar *sav = *psav;
1214105197Ssam
1215120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
1216105197Ssam
1217158767Spjd	if (sa_delref(sav)) {
1218158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1219158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1220158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1221105197Ssam		*psav = NULL;
1222105197Ssam		key_delsav(sav);
1223158767Spjd	} else {
1224158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1225158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1226158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1227105197Ssam	}
1228105197Ssam}
1229105197Ssam
1230105197Ssam/* %%% SPD management */
1231105197Ssam/*
1232105197Ssam * free security policy entry.
1233105197Ssam */
1234105197Ssamstatic void
1235105197Ssamkey_delsp(struct secpolicy *sp)
1236105197Ssam{
1237119643Ssam	struct ipsecrequest *isr, *nextisr;
1238105197Ssam
1239120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1240120585Ssam	SPTREE_LOCK_ASSERT();
1241105197Ssam
1242105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
1243105197Ssam
1244120585Ssam	IPSEC_ASSERT(sp->refcnt == 0,
1245120585Ssam		("SP with references deleted (refcnt %u)", sp->refcnt));
1246105197Ssam
1247105197Ssam	/* remove from SP index */
1248105197Ssam	if (__LIST_CHAINED(sp))
1249105197Ssam		LIST_REMOVE(sp, chain);
1250105197Ssam
1251119643Ssam	for (isr = sp->req; isr != NULL; isr = nextisr) {
1252105197Ssam		if (isr->sav != NULL) {
1253105197Ssam			KEY_FREESAV(&isr->sav);
1254105197Ssam			isr->sav = NULL;
1255105197Ssam		}
1256105197Ssam
1257105197Ssam		nextisr = isr->next;
1258119643Ssam		ipsec_delisr(isr);
1259105197Ssam	}
1260119643Ssam	_key_delsp(sp);
1261105197Ssam}
1262105197Ssam
1263105197Ssam/*
1264105197Ssam * search SPD
1265105197Ssam * OUT:	NULL	: not found
1266105197Ssam *	others	: found, pointer to a SP.
1267105197Ssam */
1268105197Ssamstatic struct secpolicy *
1269105197Ssamkey_getsp(struct secpolicyindex *spidx)
1270105197Ssam{
1271183550Szec	INIT_VNET_IPSEC(curvnet);
1272105197Ssam	struct secpolicy *sp;
1273105197Ssam
1274120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1275105197Ssam
1276120585Ssam	SPTREE_LOCK();
1277181803Sbz	LIST_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1278105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1279105197Ssam			continue;
1280105197Ssam		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1281105197Ssam			SP_ADDREF(sp);
1282119643Ssam			break;
1283105197Ssam		}
1284105197Ssam	}
1285120585Ssam	SPTREE_UNLOCK();
1286105197Ssam
1287119643Ssam	return sp;
1288105197Ssam}
1289105197Ssam
1290105197Ssam/*
1291105197Ssam * get SP by index.
1292105197Ssam * OUT:	NULL	: not found
1293105197Ssam *	others	: found, pointer to a SP.
1294105197Ssam */
1295105197Ssamstatic struct secpolicy *
1296105197Ssamkey_getspbyid(u_int32_t id)
1297105197Ssam{
1298183550Szec	INIT_VNET_IPSEC(curvnet);
1299105197Ssam	struct secpolicy *sp;
1300105197Ssam
1301120585Ssam	SPTREE_LOCK();
1302181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
1303105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1304105197Ssam			continue;
1305105197Ssam		if (sp->id == id) {
1306105197Ssam			SP_ADDREF(sp);
1307119643Ssam			goto done;
1308105197Ssam		}
1309105197Ssam	}
1310105197Ssam
1311181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
1312105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1313105197Ssam			continue;
1314105197Ssam		if (sp->id == id) {
1315105197Ssam			SP_ADDREF(sp);
1316119643Ssam			goto done;
1317105197Ssam		}
1318105197Ssam	}
1319119643Ssamdone:
1320120585Ssam	SPTREE_UNLOCK();
1321105197Ssam
1322119643Ssam	return sp;
1323105197Ssam}
1324105197Ssam
1325105197Ssamstruct secpolicy *
1326105197Ssamkey_newsp(const char* where, int tag)
1327105197Ssam{
1328183550Szec	INIT_VNET_IPSEC(curvnet);
1329105197Ssam	struct secpolicy *newsp = NULL;
1330105197Ssam
1331105197Ssam	newsp = (struct secpolicy *)
1332119643Ssam		malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1333105197Ssam	if (newsp) {
1334120585Ssam		SECPOLICY_LOCK_INIT(newsp);
1335105197Ssam		newsp->refcnt = 1;
1336105197Ssam		newsp->req = NULL;
1337105197Ssam	}
1338105197Ssam
1339105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1340120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
1341105197Ssam			where, tag, newsp));
1342105197Ssam	return newsp;
1343105197Ssam}
1344105197Ssam
1345119643Ssamstatic void
1346119643Ssam_key_delsp(struct secpolicy *sp)
1347119643Ssam{
1348120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
1349119643Ssam	free(sp, M_IPSEC_SP);
1350119643Ssam}
1351119643Ssam
1352105197Ssam/*
1353105197Ssam * create secpolicy structure from sadb_x_policy structure.
1354105197Ssam * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1355105197Ssam * so must be set properly later.
1356105197Ssam */
1357105197Ssamstruct secpolicy *
1358105197Ssamkey_msg2sp(xpl0, len, error)
1359105197Ssam	struct sadb_x_policy *xpl0;
1360105197Ssam	size_t len;
1361105197Ssam	int *error;
1362105197Ssam{
1363183550Szec	INIT_VNET_IPSEC(curvnet);
1364105197Ssam	struct secpolicy *newsp;
1365105197Ssam
1366120585Ssam	IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1367127972Spjd	IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1368120585Ssam
1369105197Ssam	if (len != PFKEY_EXTLEN(xpl0)) {
1370120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1371105197Ssam		*error = EINVAL;
1372105197Ssam		return NULL;
1373105197Ssam	}
1374105197Ssam
1375105197Ssam	if ((newsp = KEY_NEWSP()) == NULL) {
1376105197Ssam		*error = ENOBUFS;
1377105197Ssam		return NULL;
1378105197Ssam	}
1379105197Ssam
1380105197Ssam	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1381105197Ssam	newsp->policy = xpl0->sadb_x_policy_type;
1382105197Ssam
1383105197Ssam	/* check policy */
1384105197Ssam	switch (xpl0->sadb_x_policy_type) {
1385105197Ssam	case IPSEC_POLICY_DISCARD:
1386105197Ssam	case IPSEC_POLICY_NONE:
1387105197Ssam	case IPSEC_POLICY_ENTRUST:
1388105197Ssam	case IPSEC_POLICY_BYPASS:
1389105197Ssam		newsp->req = NULL;
1390105197Ssam		break;
1391105197Ssam
1392105197Ssam	case IPSEC_POLICY_IPSEC:
1393105197Ssam	    {
1394105197Ssam		int tlen;
1395105197Ssam		struct sadb_x_ipsecrequest *xisr;
1396105197Ssam		struct ipsecrequest **p_isr = &newsp->req;
1397105197Ssam
1398105197Ssam		/* validity check */
1399105197Ssam		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1400120585Ssam			ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1401120585Ssam				__func__));
1402105197Ssam			KEY_FREESP(&newsp);
1403105197Ssam			*error = EINVAL;
1404105197Ssam			return NULL;
1405105197Ssam		}
1406105197Ssam
1407105197Ssam		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1408105197Ssam		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1409105197Ssam
1410105197Ssam		while (tlen > 0) {
1411105197Ssam			/* length check */
1412105197Ssam			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1413120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1414120585Ssam					"length.\n", __func__));
1415105197Ssam				KEY_FREESP(&newsp);
1416105197Ssam				*error = EINVAL;
1417105197Ssam				return NULL;
1418105197Ssam			}
1419105197Ssam
1420105197Ssam			/* allocate request buffer */
1421119643Ssam			/* NB: data structure is zero'd */
1422119643Ssam			*p_isr = ipsec_newisr();
1423105197Ssam			if ((*p_isr) == NULL) {
1424105197Ssam				ipseclog((LOG_DEBUG,
1425120585Ssam				    "%s: No more memory.\n", __func__));
1426105197Ssam				KEY_FREESP(&newsp);
1427105197Ssam				*error = ENOBUFS;
1428105197Ssam				return NULL;
1429105197Ssam			}
1430105197Ssam
1431105197Ssam			/* set values */
1432105197Ssam			switch (xisr->sadb_x_ipsecrequest_proto) {
1433105197Ssam			case IPPROTO_ESP:
1434105197Ssam			case IPPROTO_AH:
1435105197Ssam			case IPPROTO_IPCOMP:
1436105197Ssam				break;
1437105197Ssam			default:
1438105197Ssam				ipseclog((LOG_DEBUG,
1439120585Ssam				    "%s: invalid proto type=%u\n", __func__,
1440105197Ssam				    xisr->sadb_x_ipsecrequest_proto));
1441105197Ssam				KEY_FREESP(&newsp);
1442105197Ssam				*error = EPROTONOSUPPORT;
1443105197Ssam				return NULL;
1444105197Ssam			}
1445105197Ssam			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1446105197Ssam
1447105197Ssam			switch (xisr->sadb_x_ipsecrequest_mode) {
1448105197Ssam			case IPSEC_MODE_TRANSPORT:
1449105197Ssam			case IPSEC_MODE_TUNNEL:
1450105197Ssam				break;
1451105197Ssam			case IPSEC_MODE_ANY:
1452105197Ssam			default:
1453105197Ssam				ipseclog((LOG_DEBUG,
1454120585Ssam				    "%s: invalid mode=%u\n", __func__,
1455105197Ssam				    xisr->sadb_x_ipsecrequest_mode));
1456105197Ssam				KEY_FREESP(&newsp);
1457105197Ssam				*error = EINVAL;
1458105197Ssam				return NULL;
1459105197Ssam			}
1460105197Ssam			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1461105197Ssam
1462105197Ssam			switch (xisr->sadb_x_ipsecrequest_level) {
1463105197Ssam			case IPSEC_LEVEL_DEFAULT:
1464105197Ssam			case IPSEC_LEVEL_USE:
1465105197Ssam			case IPSEC_LEVEL_REQUIRE:
1466105197Ssam				break;
1467105197Ssam			case IPSEC_LEVEL_UNIQUE:
1468105197Ssam				/* validity check */
1469105197Ssam				/*
1470105197Ssam				 * If range violation of reqid, kernel will
1471105197Ssam				 * update it, don't refuse it.
1472105197Ssam				 */
1473105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid
1474105197Ssam						> IPSEC_MANUAL_REQID_MAX) {
1475105197Ssam					ipseclog((LOG_DEBUG,
1476120585Ssam					    "%s: reqid=%d range "
1477105197Ssam					    "violation, updated by kernel.\n",
1478120585Ssam					    __func__,
1479105197Ssam					    xisr->sadb_x_ipsecrequest_reqid));
1480105197Ssam					xisr->sadb_x_ipsecrequest_reqid = 0;
1481105197Ssam				}
1482105197Ssam
1483105197Ssam				/* allocate new reqid id if reqid is zero. */
1484105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1485105197Ssam					u_int32_t reqid;
1486105197Ssam					if ((reqid = key_newreqid()) == 0) {
1487105197Ssam						KEY_FREESP(&newsp);
1488105197Ssam						*error = ENOBUFS;
1489105197Ssam						return NULL;
1490105197Ssam					}
1491105197Ssam					(*p_isr)->saidx.reqid = reqid;
1492105197Ssam					xisr->sadb_x_ipsecrequest_reqid = reqid;
1493105197Ssam				} else {
1494105197Ssam				/* set it for manual keying. */
1495105197Ssam					(*p_isr)->saidx.reqid =
1496105197Ssam						xisr->sadb_x_ipsecrequest_reqid;
1497105197Ssam				}
1498105197Ssam				break;
1499105197Ssam
1500105197Ssam			default:
1501120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1502120585Ssam					__func__,
1503105197Ssam					xisr->sadb_x_ipsecrequest_level));
1504105197Ssam				KEY_FREESP(&newsp);
1505105197Ssam				*error = EINVAL;
1506105197Ssam				return NULL;
1507105197Ssam			}
1508105197Ssam			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1509105197Ssam
1510105197Ssam			/* set IP addresses if there */
1511105197Ssam			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1512105197Ssam				struct sockaddr *paddr;
1513105197Ssam
1514105197Ssam				paddr = (struct sockaddr *)(xisr + 1);
1515105197Ssam
1516105197Ssam				/* validity check */
1517105197Ssam				if (paddr->sa_len
1518105197Ssam				    > sizeof((*p_isr)->saidx.src)) {
1519120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1520120585Ssam						"request address length.\n",
1521120585Ssam						__func__));
1522105197Ssam					KEY_FREESP(&newsp);
1523105197Ssam					*error = EINVAL;
1524105197Ssam					return NULL;
1525105197Ssam				}
1526105197Ssam				bcopy(paddr, &(*p_isr)->saidx.src,
1527105197Ssam					paddr->sa_len);
1528105197Ssam
1529105197Ssam				paddr = (struct sockaddr *)((caddr_t)paddr
1530105197Ssam							+ paddr->sa_len);
1531105197Ssam
1532105197Ssam				/* validity check */
1533105197Ssam				if (paddr->sa_len
1534105197Ssam				    > sizeof((*p_isr)->saidx.dst)) {
1535120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1536120585Ssam						"request address length.\n",
1537120585Ssam						__func__));
1538105197Ssam					KEY_FREESP(&newsp);
1539105197Ssam					*error = EINVAL;
1540105197Ssam					return NULL;
1541105197Ssam				}
1542105197Ssam				bcopy(paddr, &(*p_isr)->saidx.dst,
1543105197Ssam					paddr->sa_len);
1544105197Ssam			}
1545105197Ssam
1546105197Ssam			(*p_isr)->sp = newsp;
1547105197Ssam
1548105197Ssam			/* initialization for the next. */
1549105197Ssam			p_isr = &(*p_isr)->next;
1550105197Ssam			tlen -= xisr->sadb_x_ipsecrequest_len;
1551105197Ssam
1552105197Ssam			/* validity check */
1553105197Ssam			if (tlen < 0) {
1554120585Ssam				ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1555120585Ssam					__func__));
1556105197Ssam				KEY_FREESP(&newsp);
1557105197Ssam				*error = EINVAL;
1558105197Ssam				return NULL;
1559105197Ssam			}
1560105197Ssam
1561105197Ssam			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1562105197Ssam			                 + xisr->sadb_x_ipsecrequest_len);
1563105197Ssam		}
1564105197Ssam	    }
1565105197Ssam		break;
1566105197Ssam	default:
1567120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1568105197Ssam		KEY_FREESP(&newsp);
1569105197Ssam		*error = EINVAL;
1570105197Ssam		return NULL;
1571105197Ssam	}
1572105197Ssam
1573105197Ssam	*error = 0;
1574105197Ssam	return newsp;
1575105197Ssam}
1576105197Ssam
1577105197Ssamstatic u_int32_t
1578105197Ssamkey_newreqid()
1579105197Ssam{
1580105197Ssam	static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1581105197Ssam
1582105197Ssam	auto_reqid = (auto_reqid == ~0
1583105197Ssam			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1584105197Ssam
1585105197Ssam	/* XXX should be unique check */
1586105197Ssam
1587105197Ssam	return auto_reqid;
1588105197Ssam}
1589105197Ssam
1590105197Ssam/*
1591105197Ssam * copy secpolicy struct to sadb_x_policy structure indicated.
1592105197Ssam */
1593105197Ssamstruct mbuf *
1594105197Ssamkey_sp2msg(sp)
1595105197Ssam	struct secpolicy *sp;
1596105197Ssam{
1597105197Ssam	struct sadb_x_policy *xpl;
1598105197Ssam	int tlen;
1599105197Ssam	caddr_t p;
1600105197Ssam	struct mbuf *m;
1601105197Ssam
1602120585Ssam	IPSEC_ASSERT(sp != NULL, ("null policy"));
1603105197Ssam
1604105197Ssam	tlen = key_getspreqmsglen(sp);
1605105197Ssam
1606105197Ssam	m = key_alloc_mbuf(tlen);
1607105197Ssam	if (!m || m->m_next) {	/*XXX*/
1608105197Ssam		if (m)
1609105197Ssam			m_freem(m);
1610105197Ssam		return NULL;
1611105197Ssam	}
1612105197Ssam
1613105197Ssam	m->m_len = tlen;
1614105197Ssam	m->m_next = NULL;
1615105197Ssam	xpl = mtod(m, struct sadb_x_policy *);
1616105197Ssam	bzero(xpl, tlen);
1617105197Ssam
1618105197Ssam	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1619105197Ssam	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1620105197Ssam	xpl->sadb_x_policy_type = sp->policy;
1621105197Ssam	xpl->sadb_x_policy_dir = sp->spidx.dir;
1622105197Ssam	xpl->sadb_x_policy_id = sp->id;
1623105197Ssam	p = (caddr_t)xpl + sizeof(*xpl);
1624105197Ssam
1625105197Ssam	/* if is the policy for ipsec ? */
1626105197Ssam	if (sp->policy == IPSEC_POLICY_IPSEC) {
1627105197Ssam		struct sadb_x_ipsecrequest *xisr;
1628105197Ssam		struct ipsecrequest *isr;
1629105197Ssam
1630105197Ssam		for (isr = sp->req; isr != NULL; isr = isr->next) {
1631105197Ssam
1632105197Ssam			xisr = (struct sadb_x_ipsecrequest *)p;
1633105197Ssam
1634105197Ssam			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1635105197Ssam			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1636105197Ssam			xisr->sadb_x_ipsecrequest_level = isr->level;
1637105197Ssam			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1638105197Ssam
1639105197Ssam			p += sizeof(*xisr);
1640105197Ssam			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1641105197Ssam			p += isr->saidx.src.sa.sa_len;
1642105197Ssam			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1643105197Ssam			p += isr->saidx.src.sa.sa_len;
1644105197Ssam
1645105197Ssam			xisr->sadb_x_ipsecrequest_len =
1646105197Ssam				PFKEY_ALIGN8(sizeof(*xisr)
1647105197Ssam					+ isr->saidx.src.sa.sa_len
1648105197Ssam					+ isr->saidx.dst.sa.sa_len);
1649105197Ssam		}
1650105197Ssam	}
1651105197Ssam
1652105197Ssam	return m;
1653105197Ssam}
1654105197Ssam
1655105197Ssam/* m will not be freed nor modified */
1656105197Ssamstatic struct mbuf *
1657105197Ssam#ifdef __STDC__
1658105197Ssamkey_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1659105197Ssam	int ndeep, int nitem, ...)
1660105197Ssam#else
1661105197Ssamkey_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1662105197Ssam	struct mbuf *m;
1663105197Ssam	const struct sadb_msghdr *mhp;
1664105197Ssam	int ndeep;
1665105197Ssam	int nitem;
1666105197Ssam	va_dcl
1667105197Ssam#endif
1668105197Ssam{
1669105197Ssam	va_list ap;
1670105197Ssam	int idx;
1671105197Ssam	int i;
1672105197Ssam	struct mbuf *result = NULL, *n;
1673105197Ssam	int len;
1674105197Ssam
1675120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1676120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1677105197Ssam
1678105197Ssam	va_start(ap, nitem);
1679105197Ssam	for (i = 0; i < nitem; i++) {
1680105197Ssam		idx = va_arg(ap, int);
1681105197Ssam		if (idx < 0 || idx > SADB_EXT_MAX)
1682105197Ssam			goto fail;
1683105197Ssam		/* don't attempt to pull empty extension */
1684105197Ssam		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1685105197Ssam			continue;
1686105197Ssam		if (idx != SADB_EXT_RESERVED  &&
1687105197Ssam		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1688105197Ssam			continue;
1689105197Ssam
1690105197Ssam		if (idx == SADB_EXT_RESERVED) {
1691105197Ssam			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1692120585Ssam
1693120585Ssam			IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1694120585Ssam
1695111119Simp			MGETHDR(n, M_DONTWAIT, MT_DATA);
1696105197Ssam			if (!n)
1697105197Ssam				goto fail;
1698105197Ssam			n->m_len = len;
1699105197Ssam			n->m_next = NULL;
1700105197Ssam			m_copydata(m, 0, sizeof(struct sadb_msg),
1701105197Ssam			    mtod(n, caddr_t));
1702105197Ssam		} else if (i < ndeep) {
1703105197Ssam			len = mhp->extlen[idx];
1704105197Ssam			n = key_alloc_mbuf(len);
1705105197Ssam			if (!n || n->m_next) {	/*XXX*/
1706105197Ssam				if (n)
1707105197Ssam					m_freem(n);
1708105197Ssam				goto fail;
1709105197Ssam			}
1710105197Ssam			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1711105197Ssam			    mtod(n, caddr_t));
1712105197Ssam		} else {
1713105197Ssam			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1714111119Simp			    M_DONTWAIT);
1715105197Ssam		}
1716105197Ssam		if (n == NULL)
1717105197Ssam			goto fail;
1718105197Ssam
1719105197Ssam		if (result)
1720105197Ssam			m_cat(result, n);
1721105197Ssam		else
1722105197Ssam			result = n;
1723105197Ssam	}
1724105197Ssam	va_end(ap);
1725105197Ssam
1726105197Ssam	if ((result->m_flags & M_PKTHDR) != 0) {
1727105197Ssam		result->m_pkthdr.len = 0;
1728105197Ssam		for (n = result; n; n = n->m_next)
1729105197Ssam			result->m_pkthdr.len += n->m_len;
1730105197Ssam	}
1731105197Ssam
1732105197Ssam	return result;
1733105197Ssam
1734105197Ssamfail:
1735105197Ssam	m_freem(result);
1736105197Ssam	return NULL;
1737105197Ssam}
1738105197Ssam
1739105197Ssam/*
1740105197Ssam * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1741108533Sschweikh * add an entry to SP database, when received
1742105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1743105197Ssam * from the user(?).
1744105197Ssam * Adding to SP database,
1745105197Ssam * and send
1746105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1747105197Ssam * to the socket which was send.
1748105197Ssam *
1749105197Ssam * SPDADD set a unique policy entry.
1750105197Ssam * SPDSETIDX like SPDADD without a part of policy requests.
1751105197Ssam * SPDUPDATE replace a unique policy entry.
1752105197Ssam *
1753105197Ssam * m will always be freed.
1754105197Ssam */
1755105197Ssamstatic int
1756105197Ssamkey_spdadd(so, m, mhp)
1757105197Ssam	struct socket *so;
1758105197Ssam	struct mbuf *m;
1759105197Ssam	const struct sadb_msghdr *mhp;
1760105197Ssam{
1761183550Szec	INIT_VNET_IPSEC(curvnet);
1762105197Ssam	struct sadb_address *src0, *dst0;
1763105197Ssam	struct sadb_x_policy *xpl0, *xpl;
1764105197Ssam	struct sadb_lifetime *lft = NULL;
1765105197Ssam	struct secpolicyindex spidx;
1766105197Ssam	struct secpolicy *newsp;
1767105197Ssam	int error;
1768105197Ssam
1769120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
1770120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1771120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1772120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1773105197Ssam
1774105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1775105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1776105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1777105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1778105197Ssam		return key_senderror(so, m, EINVAL);
1779105197Ssam	}
1780105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1781105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1782105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1783120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1784120585Ssam			__func__));
1785105197Ssam		return key_senderror(so, m, EINVAL);
1786105197Ssam	}
1787105197Ssam	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1788105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1789105197Ssam			< sizeof(struct sadb_lifetime)) {
1790120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1791120585Ssam				__func__));
1792105197Ssam			return key_senderror(so, m, EINVAL);
1793105197Ssam		}
1794105197Ssam		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1795105197Ssam	}
1796105197Ssam
1797105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1798105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1799105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1800105197Ssam
1801105197Ssam	/* make secindex */
1802105197Ssam	/* XXX boundary check against sa_len */
1803105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1804105197Ssam	                src0 + 1,
1805105197Ssam	                dst0 + 1,
1806105197Ssam	                src0->sadb_address_prefixlen,
1807105197Ssam	                dst0->sadb_address_prefixlen,
1808105197Ssam	                src0->sadb_address_proto,
1809105197Ssam	                &spidx);
1810105197Ssam
1811105197Ssam	/* checking the direciton. */
1812105197Ssam	switch (xpl0->sadb_x_policy_dir) {
1813105197Ssam	case IPSEC_DIR_INBOUND:
1814105197Ssam	case IPSEC_DIR_OUTBOUND:
1815105197Ssam		break;
1816105197Ssam	default:
1817120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1818105197Ssam		mhp->msg->sadb_msg_errno = EINVAL;
1819105197Ssam		return 0;
1820105197Ssam	}
1821105197Ssam
1822105197Ssam	/* check policy */
1823105197Ssam	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1824105197Ssam	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1825105197Ssam	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1826120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1827105197Ssam		return key_senderror(so, m, EINVAL);
1828105197Ssam	}
1829105197Ssam
1830105197Ssam	/* policy requests are mandatory when action is ipsec. */
1831105197Ssam        if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1832105197Ssam	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1833105197Ssam	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1834120585Ssam		ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1835120585Ssam			__func__));
1836105197Ssam		return key_senderror(so, m, EINVAL);
1837105197Ssam	}
1838105197Ssam
1839105197Ssam	/*
1840105197Ssam	 * checking there is SP already or not.
1841105197Ssam	 * SPDUPDATE doesn't depend on whether there is a SP or not.
1842105197Ssam	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1843105197Ssam	 * then error.
1844105197Ssam	 */
1845105197Ssam	newsp = key_getsp(&spidx);
1846105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1847105197Ssam		if (newsp) {
1848105197Ssam			newsp->state = IPSEC_SPSTATE_DEAD;
1849105197Ssam			KEY_FREESP(&newsp);
1850105197Ssam		}
1851105197Ssam	} else {
1852105197Ssam		if (newsp != NULL) {
1853105197Ssam			KEY_FREESP(&newsp);
1854120585Ssam			ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1855120585Ssam				__func__));
1856105197Ssam			return key_senderror(so, m, EEXIST);
1857105197Ssam		}
1858105197Ssam	}
1859105197Ssam
1860105197Ssam	/* allocation new SP entry */
1861105197Ssam	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1862105197Ssam		return key_senderror(so, m, error);
1863105197Ssam	}
1864105197Ssam
1865105197Ssam	if ((newsp->id = key_getnewspid()) == 0) {
1866119643Ssam		_key_delsp(newsp);
1867105197Ssam		return key_senderror(so, m, ENOBUFS);
1868105197Ssam	}
1869105197Ssam
1870105197Ssam	/* XXX boundary check against sa_len */
1871105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1872105197Ssam	                src0 + 1,
1873105197Ssam	                dst0 + 1,
1874105197Ssam	                src0->sadb_address_prefixlen,
1875105197Ssam	                dst0->sadb_address_prefixlen,
1876105197Ssam	                src0->sadb_address_proto,
1877105197Ssam	                &newsp->spidx);
1878105197Ssam
1879105197Ssam	/* sanity check on addr pair */
1880105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1881105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_family) {
1882119643Ssam		_key_delsp(newsp);
1883105197Ssam		return key_senderror(so, m, EINVAL);
1884105197Ssam	}
1885105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1886105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_len) {
1887119643Ssam		_key_delsp(newsp);
1888105197Ssam		return key_senderror(so, m, EINVAL);
1889105197Ssam	}
1890105197Ssam#if 1
1891105197Ssam	if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
1892105197Ssam		struct sockaddr *sa;
1893105197Ssam		sa = (struct sockaddr *)(src0 + 1);
1894105197Ssam		if (sa->sa_family != newsp->req->saidx.src.sa.sa_family) {
1895119643Ssam			_key_delsp(newsp);
1896105197Ssam			return key_senderror(so, m, EINVAL);
1897105197Ssam		}
1898105197Ssam	}
1899105197Ssam	if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
1900105197Ssam		struct sockaddr *sa;
1901105197Ssam		sa = (struct sockaddr *)(dst0 + 1);
1902105197Ssam		if (sa->sa_family != newsp->req->saidx.dst.sa.sa_family) {
1903119643Ssam			_key_delsp(newsp);
1904105197Ssam			return key_senderror(so, m, EINVAL);
1905105197Ssam		}
1906105197Ssam	}
1907105197Ssam#endif
1908105197Ssam
1909105197Ssam	newsp->created = time_second;
1910105197Ssam	newsp->lastused = newsp->created;
1911105197Ssam	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1912105197Ssam	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1913105197Ssam
1914105197Ssam	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1915105197Ssam	newsp->state = IPSEC_SPSTATE_ALIVE;
1916181803Sbz	LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1917105197Ssam
1918105197Ssam	/* delete the entry in spacqtree */
1919105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1920119643Ssam		struct secspacq *spacq = key_getspacq(&spidx);
1921119643Ssam		if (spacq != NULL) {
1922105197Ssam			/* reset counter in order to deletion by timehandler. */
1923105197Ssam			spacq->created = time_second;
1924105197Ssam			spacq->count = 0;
1925120585Ssam			SPACQ_UNLOCK();
1926105197Ssam		}
1927105197Ssam    	}
1928105197Ssam
1929105197Ssam    {
1930105197Ssam	struct mbuf *n, *mpolicy;
1931105197Ssam	struct sadb_msg *newmsg;
1932105197Ssam	int off;
1933105197Ssam
1934105197Ssam	/* create new sadb_msg to reply. */
1935105197Ssam	if (lft) {
1936105197Ssam		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1937105197Ssam		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1938105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1939105197Ssam	} else {
1940105197Ssam		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1941105197Ssam		    SADB_X_EXT_POLICY,
1942105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1943105197Ssam	}
1944105197Ssam	if (!n)
1945105197Ssam		return key_senderror(so, m, ENOBUFS);
1946105197Ssam
1947105197Ssam	if (n->m_len < sizeof(*newmsg)) {
1948105197Ssam		n = m_pullup(n, sizeof(*newmsg));
1949105197Ssam		if (!n)
1950105197Ssam			return key_senderror(so, m, ENOBUFS);
1951105197Ssam	}
1952105197Ssam	newmsg = mtod(n, struct sadb_msg *);
1953105197Ssam	newmsg->sadb_msg_errno = 0;
1954105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1955105197Ssam
1956105197Ssam	off = 0;
1957105197Ssam	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1958105197Ssam	    sizeof(*xpl), &off);
1959105197Ssam	if (mpolicy == NULL) {
1960105197Ssam		/* n is already freed */
1961105197Ssam		return key_senderror(so, m, ENOBUFS);
1962105197Ssam	}
1963105197Ssam	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1964105197Ssam	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1965105197Ssam		m_freem(n);
1966105197Ssam		return key_senderror(so, m, EINVAL);
1967105197Ssam	}
1968105197Ssam	xpl->sadb_x_policy_id = newsp->id;
1969105197Ssam
1970105197Ssam	m_freem(m);
1971105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1972105197Ssam    }
1973105197Ssam}
1974105197Ssam
1975105197Ssam/*
1976105197Ssam * get new policy id.
1977105197Ssam * OUT:
1978105197Ssam *	0:	failure.
1979105197Ssam *	others: success.
1980105197Ssam */
1981105197Ssamstatic u_int32_t
1982105197Ssamkey_getnewspid()
1983105197Ssam{
1984183550Szec	INIT_VNET_IPSEC(curvnet);
1985105197Ssam	u_int32_t newid = 0;
1986181803Sbz	int count = V_key_spi_trycnt;	/* XXX */
1987105197Ssam	struct secpolicy *sp;
1988105197Ssam
1989105197Ssam	/* when requesting to allocate spi ranged */
1990105197Ssam	while (count--) {
1991181803Sbz		newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
1992105197Ssam
1993105197Ssam		if ((sp = key_getspbyid(newid)) == NULL)
1994105197Ssam			break;
1995105197Ssam
1996105197Ssam		KEY_FREESP(&sp);
1997105197Ssam	}
1998105197Ssam
1999105197Ssam	if (count == 0 || newid == 0) {
2000120585Ssam		ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2001120585Ssam			__func__));
2002105197Ssam		return 0;
2003105197Ssam	}
2004105197Ssam
2005105197Ssam	return newid;
2006105197Ssam}
2007105197Ssam
2008105197Ssam/*
2009105197Ssam * SADB_SPDDELETE processing
2010105197Ssam * receive
2011105197Ssam *   <base, address(SD), policy(*)>
2012105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2013105197Ssam * and send,
2014105197Ssam *   <base, address(SD), policy(*)>
2015105197Ssam * to the ikmpd.
2016105197Ssam * policy(*) including direction of policy.
2017105197Ssam *
2018105197Ssam * m will always be freed.
2019105197Ssam */
2020105197Ssamstatic int
2021105197Ssamkey_spddelete(so, m, mhp)
2022105197Ssam	struct socket *so;
2023105197Ssam	struct mbuf *m;
2024105197Ssam	const struct sadb_msghdr *mhp;
2025105197Ssam{
2026183550Szec	INIT_VNET_IPSEC(curvnet);
2027105197Ssam	struct sadb_address *src0, *dst0;
2028105197Ssam	struct sadb_x_policy *xpl0;
2029105197Ssam	struct secpolicyindex spidx;
2030105197Ssam	struct secpolicy *sp;
2031105197Ssam
2032120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
2033120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2034120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2035120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2036105197Ssam
2037105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2038105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2039105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2040120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2041120585Ssam			__func__));
2042105197Ssam		return key_senderror(so, m, EINVAL);
2043105197Ssam	}
2044105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2045105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2046105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2047120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2048120585Ssam			__func__));
2049105197Ssam		return key_senderror(so, m, EINVAL);
2050105197Ssam	}
2051105197Ssam
2052105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2053105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2054105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2055105197Ssam
2056105197Ssam	/* make secindex */
2057105197Ssam	/* XXX boundary check against sa_len */
2058105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2059105197Ssam	                src0 + 1,
2060105197Ssam	                dst0 + 1,
2061105197Ssam	                src0->sadb_address_prefixlen,
2062105197Ssam	                dst0->sadb_address_prefixlen,
2063105197Ssam	                src0->sadb_address_proto,
2064105197Ssam	                &spidx);
2065105197Ssam
2066105197Ssam	/* checking the direciton. */
2067105197Ssam	switch (xpl0->sadb_x_policy_dir) {
2068105197Ssam	case IPSEC_DIR_INBOUND:
2069105197Ssam	case IPSEC_DIR_OUTBOUND:
2070105197Ssam		break;
2071105197Ssam	default:
2072120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2073105197Ssam		return key_senderror(so, m, EINVAL);
2074105197Ssam	}
2075105197Ssam
2076105197Ssam	/* Is there SP in SPD ? */
2077105197Ssam	if ((sp = key_getsp(&spidx)) == NULL) {
2078120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2079105197Ssam		return key_senderror(so, m, EINVAL);
2080105197Ssam	}
2081105197Ssam
2082105197Ssam	/* save policy id to buffer to be returned. */
2083105197Ssam	xpl0->sadb_x_policy_id = sp->id;
2084105197Ssam
2085105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2086105197Ssam	KEY_FREESP(&sp);
2087105197Ssam
2088105197Ssam    {
2089105197Ssam	struct mbuf *n;
2090105197Ssam	struct sadb_msg *newmsg;
2091105197Ssam
2092105197Ssam	/* create new sadb_msg to reply. */
2093105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2094105197Ssam	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2095105197Ssam	if (!n)
2096105197Ssam		return key_senderror(so, m, ENOBUFS);
2097105197Ssam
2098105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2099105197Ssam	newmsg->sadb_msg_errno = 0;
2100105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2101105197Ssam
2102105197Ssam	m_freem(m);
2103105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2104105197Ssam    }
2105105197Ssam}
2106105197Ssam
2107105197Ssam/*
2108105197Ssam * SADB_SPDDELETE2 processing
2109105197Ssam * receive
2110105197Ssam *   <base, policy(*)>
2111105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2112105197Ssam * and send,
2113105197Ssam *   <base, policy(*)>
2114105197Ssam * to the ikmpd.
2115105197Ssam * policy(*) including direction of policy.
2116105197Ssam *
2117105197Ssam * m will always be freed.
2118105197Ssam */
2119105197Ssamstatic int
2120105197Ssamkey_spddelete2(so, m, mhp)
2121105197Ssam	struct socket *so;
2122105197Ssam	struct mbuf *m;
2123105197Ssam	const struct sadb_msghdr *mhp;
2124105197Ssam{
2125183550Szec	INIT_VNET_IPSEC(curvnet);
2126105197Ssam	u_int32_t id;
2127105197Ssam	struct secpolicy *sp;
2128105197Ssam
2129120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2130120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2131120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2132120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2133105197Ssam
2134105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2135105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2136120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2137170803Sbz		return key_senderror(so, m, EINVAL);
2138105197Ssam	}
2139105197Ssam
2140105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2141105197Ssam
2142105197Ssam	/* Is there SP in SPD ? */
2143105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2144120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2145170803Sbz		return key_senderror(so, m, EINVAL);
2146105197Ssam	}
2147105197Ssam
2148105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2149105197Ssam	KEY_FREESP(&sp);
2150105197Ssam
2151105197Ssam    {
2152105197Ssam	struct mbuf *n, *nn;
2153105197Ssam	struct sadb_msg *newmsg;
2154105197Ssam	int off, len;
2155105197Ssam
2156105197Ssam	/* create new sadb_msg to reply. */
2157105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2158105197Ssam
2159111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
2160105197Ssam	if (n && len > MHLEN) {
2161111119Simp		MCLGET(n, M_DONTWAIT);
2162105197Ssam		if ((n->m_flags & M_EXT) == 0) {
2163105197Ssam			m_freem(n);
2164105197Ssam			n = NULL;
2165105197Ssam		}
2166105197Ssam	}
2167105197Ssam	if (!n)
2168105197Ssam		return key_senderror(so, m, ENOBUFS);
2169105197Ssam
2170105197Ssam	n->m_len = len;
2171105197Ssam	n->m_next = NULL;
2172105197Ssam	off = 0;
2173105197Ssam
2174105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2175105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2176105197Ssam
2177120585Ssam	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2178120585Ssam		off, len));
2179105197Ssam
2180105197Ssam	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2181111119Simp	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2182105197Ssam	if (!n->m_next) {
2183105197Ssam		m_freem(n);
2184105197Ssam		return key_senderror(so, m, ENOBUFS);
2185105197Ssam	}
2186105197Ssam
2187105197Ssam	n->m_pkthdr.len = 0;
2188105197Ssam	for (nn = n; nn; nn = nn->m_next)
2189105197Ssam		n->m_pkthdr.len += nn->m_len;
2190105197Ssam
2191105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2192105197Ssam	newmsg->sadb_msg_errno = 0;
2193105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2194105197Ssam
2195105197Ssam	m_freem(m);
2196105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2197105197Ssam    }
2198105197Ssam}
2199105197Ssam
2200105197Ssam/*
2201105197Ssam * SADB_X_GET processing
2202105197Ssam * receive
2203105197Ssam *   <base, policy(*)>
2204105197Ssam * from the user(?),
2205105197Ssam * and send,
2206105197Ssam *   <base, address(SD), policy>
2207105197Ssam * to the ikmpd.
2208105197Ssam * policy(*) including direction of policy.
2209105197Ssam *
2210105197Ssam * m will always be freed.
2211105197Ssam */
2212105197Ssamstatic int
2213105197Ssamkey_spdget(so, m, mhp)
2214105197Ssam	struct socket *so;
2215105197Ssam	struct mbuf *m;
2216105197Ssam	const struct sadb_msghdr *mhp;
2217105197Ssam{
2218183550Szec	INIT_VNET_IPSEC(curvnet);
2219105197Ssam	u_int32_t id;
2220105197Ssam	struct secpolicy *sp;
2221105197Ssam	struct mbuf *n;
2222105197Ssam
2223120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2224120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2225120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2226120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2227105197Ssam
2228105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2229105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2230120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2231120585Ssam			__func__));
2232105197Ssam		return key_senderror(so, m, EINVAL);
2233105197Ssam	}
2234105197Ssam
2235105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2236105197Ssam
2237105197Ssam	/* Is there SP in SPD ? */
2238105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2239120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2240105197Ssam		return key_senderror(so, m, ENOENT);
2241105197Ssam	}
2242105197Ssam
2243105197Ssam	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2244105197Ssam	if (n != NULL) {
2245105197Ssam		m_freem(m);
2246105197Ssam		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2247105197Ssam	} else
2248105197Ssam		return key_senderror(so, m, ENOBUFS);
2249105197Ssam}
2250105197Ssam
2251105197Ssam/*
2252105197Ssam * SADB_X_SPDACQUIRE processing.
2253105197Ssam * Acquire policy and SA(s) for a *OUTBOUND* packet.
2254105197Ssam * send
2255105197Ssam *   <base, policy(*)>
2256105197Ssam * to KMD, and expect to receive
2257105197Ssam *   <base> with SADB_X_SPDACQUIRE if error occured,
2258105197Ssam * or
2259105197Ssam *   <base, policy>
2260105197Ssam * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2261105197Ssam * policy(*) is without policy requests.
2262105197Ssam *
2263105197Ssam *    0     : succeed
2264105197Ssam *    others: error number
2265105197Ssam */
2266105197Ssamint
2267105197Ssamkey_spdacquire(sp)
2268105197Ssam	struct secpolicy *sp;
2269105197Ssam{
2270183550Szec	INIT_VNET_IPSEC(curvnet);
2271105197Ssam	struct mbuf *result = NULL, *m;
2272105197Ssam	struct secspacq *newspacq;
2273105197Ssam
2274120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2275120585Ssam	IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2276120585Ssam	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2277120585Ssam		("policy not IPSEC %u", sp->policy));
2278105197Ssam
2279108533Sschweikh	/* Get an entry to check whether sent message or not. */
2280119643Ssam	newspacq = key_getspacq(&sp->spidx);
2281119643Ssam	if (newspacq != NULL) {
2282181803Sbz		if (V_key_blockacq_count < newspacq->count) {
2283105197Ssam			/* reset counter and do send message. */
2284105197Ssam			newspacq->count = 0;
2285105197Ssam		} else {
2286105197Ssam			/* increment counter and do nothing. */
2287105197Ssam			newspacq->count++;
2288105197Ssam			return 0;
2289105197Ssam		}
2290120585Ssam		SPACQ_UNLOCK();
2291105197Ssam	} else {
2292105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
2293119643Ssam		newspacq = key_newspacq(&sp->spidx);
2294119643Ssam		if (newspacq == NULL)
2295105197Ssam			return ENOBUFS;
2296105197Ssam	}
2297105197Ssam
2298105197Ssam	/* create new sadb_msg to reply. */
2299105197Ssam	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2300170805Sbz	if (!m)
2301170805Sbz		return ENOBUFS;
2302170805Sbz
2303105197Ssam	result = m;
2304105197Ssam
2305105197Ssam	result->m_pkthdr.len = 0;
2306105197Ssam	for (m = result; m; m = m->m_next)
2307105197Ssam		result->m_pkthdr.len += m->m_len;
2308105197Ssam
2309105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2310105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2311105197Ssam
2312105197Ssam	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2313105197Ssam}
2314105197Ssam
2315105197Ssam/*
2316105197Ssam * SADB_SPDFLUSH processing
2317105197Ssam * receive
2318105197Ssam *   <base>
2319105197Ssam * from the user, and free all entries in secpctree.
2320105197Ssam * and send,
2321105197Ssam *   <base>
2322105197Ssam * to the user.
2323105197Ssam * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2324105197Ssam *
2325105197Ssam * m will always be freed.
2326105197Ssam */
2327105197Ssamstatic int
2328105197Ssamkey_spdflush(so, m, mhp)
2329105197Ssam	struct socket *so;
2330105197Ssam	struct mbuf *m;
2331105197Ssam	const struct sadb_msghdr *mhp;
2332105197Ssam{
2333183550Szec	INIT_VNET_IPSEC(curvnet);
2334105197Ssam	struct sadb_msg *newmsg;
2335105197Ssam	struct secpolicy *sp;
2336105197Ssam	u_int dir;
2337105197Ssam
2338120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2339120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2340120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2341120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2342105197Ssam
2343105197Ssam	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2344105197Ssam		return key_senderror(so, m, EINVAL);
2345105197Ssam
2346105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2347120585Ssam		SPTREE_LOCK();
2348181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain)
2349105197Ssam			sp->state = IPSEC_SPSTATE_DEAD;
2350120585Ssam		SPTREE_UNLOCK();
2351105197Ssam	}
2352105197Ssam
2353105197Ssam	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2354120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2355105197Ssam		return key_senderror(so, m, ENOBUFS);
2356105197Ssam	}
2357105197Ssam
2358105197Ssam	if (m->m_next)
2359105197Ssam		m_freem(m->m_next);
2360105197Ssam	m->m_next = NULL;
2361105197Ssam	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2362105197Ssam	newmsg = mtod(m, struct sadb_msg *);
2363105197Ssam	newmsg->sadb_msg_errno = 0;
2364105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2365105197Ssam
2366105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2367105197Ssam}
2368105197Ssam
2369105197Ssam/*
2370105197Ssam * SADB_SPDDUMP processing
2371105197Ssam * receive
2372105197Ssam *   <base>
2373105197Ssam * from the user, and dump all SP leaves
2374105197Ssam * and send,
2375105197Ssam *   <base> .....
2376105197Ssam * to the ikmpd.
2377105197Ssam *
2378105197Ssam * m will always be freed.
2379105197Ssam */
2380105197Ssamstatic int
2381105197Ssamkey_spddump(so, m, mhp)
2382105197Ssam	struct socket *so;
2383105197Ssam	struct mbuf *m;
2384105197Ssam	const struct sadb_msghdr *mhp;
2385105197Ssam{
2386183550Szec	INIT_VNET_IPSEC(curvnet);
2387105197Ssam	struct secpolicy *sp;
2388105197Ssam	int cnt;
2389105197Ssam	u_int dir;
2390105197Ssam	struct mbuf *n;
2391105197Ssam
2392120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2393120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2394120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2395120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2396105197Ssam
2397105197Ssam	/* search SPD entry and get buffer size. */
2398105197Ssam	cnt = 0;
2399192882Svanhu	SPTREE_LOCK();
2400105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2401181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2402105197Ssam			cnt++;
2403105197Ssam		}
2404105197Ssam	}
2405105197Ssam
2406192882Svanhu	if (cnt == 0) {
2407192882Svanhu		SPTREE_UNLOCK();
2408105197Ssam		return key_senderror(so, m, ENOENT);
2409192882Svanhu	}
2410105197Ssam
2411105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2412181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2413105197Ssam			--cnt;
2414105197Ssam			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2415105197Ssam			    mhp->msg->sadb_msg_pid);
2416105197Ssam
2417105197Ssam			if (n)
2418105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2419105197Ssam		}
2420105197Ssam	}
2421105197Ssam
2422192882Svanhu	SPTREE_UNLOCK();
2423105197Ssam	m_freem(m);
2424105197Ssam	return 0;
2425105197Ssam}
2426105197Ssam
2427105197Ssamstatic struct mbuf *
2428189004Srdivackykey_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid)
2429105197Ssam{
2430105197Ssam	struct mbuf *result = NULL, *m;
2431181330Svanhu	struct seclifetime lt;
2432105197Ssam
2433105197Ssam	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2434105197Ssam	if (!m)
2435105197Ssam		goto fail;
2436105197Ssam	result = m;
2437105197Ssam
2438105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2439105197Ssam	    &sp->spidx.src.sa, sp->spidx.prefs,
2440105197Ssam	    sp->spidx.ul_proto);
2441105197Ssam	if (!m)
2442105197Ssam		goto fail;
2443105197Ssam	m_cat(result, m);
2444105197Ssam
2445105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2446105197Ssam	    &sp->spidx.dst.sa, sp->spidx.prefd,
2447105197Ssam	    sp->spidx.ul_proto);
2448105197Ssam	if (!m)
2449105197Ssam		goto fail;
2450105197Ssam	m_cat(result, m);
2451105197Ssam
2452105197Ssam	m = key_sp2msg(sp);
2453105197Ssam	if (!m)
2454105197Ssam		goto fail;
2455105197Ssam	m_cat(result, m);
2456105197Ssam
2457181330Svanhu	if(sp->lifetime){
2458181330Svanhu		lt.addtime=sp->created;
2459181330Svanhu		lt.usetime= sp->lastused;
2460181330Svanhu		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_CURRENT);
2461181330Svanhu		if (!m)
2462181330Svanhu			goto fail;
2463181330Svanhu		m_cat(result, m);
2464181330Svanhu
2465181330Svanhu		lt.addtime=sp->lifetime;
2466181330Svanhu		lt.usetime= sp->validtime;
2467181330Svanhu		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_HARD);
2468181330Svanhu		if (!m)
2469181330Svanhu			goto fail;
2470181330Svanhu		m_cat(result, m);
2471181330Svanhu	}
2472181330Svanhu
2473105197Ssam	if ((result->m_flags & M_PKTHDR) == 0)
2474105197Ssam		goto fail;
2475105197Ssam
2476105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2477105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2478105197Ssam		if (result == NULL)
2479105197Ssam			goto fail;
2480105197Ssam	}
2481105197Ssam
2482105197Ssam	result->m_pkthdr.len = 0;
2483105197Ssam	for (m = result; m; m = m->m_next)
2484105197Ssam		result->m_pkthdr.len += m->m_len;
2485105197Ssam
2486105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2487105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2488105197Ssam
2489105197Ssam	return result;
2490105197Ssam
2491105197Ssamfail:
2492105197Ssam	m_freem(result);
2493105197Ssam	return NULL;
2494105197Ssam}
2495105197Ssam
2496105197Ssam/*
2497105197Ssam * get PFKEY message length for security policy and request.
2498105197Ssam */
2499105197Ssamstatic u_int
2500105197Ssamkey_getspreqmsglen(sp)
2501105197Ssam	struct secpolicy *sp;
2502105197Ssam{
2503105197Ssam	u_int tlen;
2504105197Ssam
2505105197Ssam	tlen = sizeof(struct sadb_x_policy);
2506105197Ssam
2507105197Ssam	/* if is the policy for ipsec ? */
2508105197Ssam	if (sp->policy != IPSEC_POLICY_IPSEC)
2509105197Ssam		return tlen;
2510105197Ssam
2511105197Ssam	/* get length of ipsec requests */
2512105197Ssam    {
2513105197Ssam	struct ipsecrequest *isr;
2514105197Ssam	int len;
2515105197Ssam
2516105197Ssam	for (isr = sp->req; isr != NULL; isr = isr->next) {
2517105197Ssam		len = sizeof(struct sadb_x_ipsecrequest)
2518105197Ssam			+ isr->saidx.src.sa.sa_len
2519105197Ssam			+ isr->saidx.dst.sa.sa_len;
2520105197Ssam
2521105197Ssam		tlen += PFKEY_ALIGN8(len);
2522105197Ssam	}
2523105197Ssam    }
2524105197Ssam
2525105197Ssam	return tlen;
2526105197Ssam}
2527105197Ssam
2528105197Ssam/*
2529105197Ssam * SADB_SPDEXPIRE processing
2530105197Ssam * send
2531105197Ssam *   <base, address(SD), lifetime(CH), policy>
2532105197Ssam * to KMD by PF_KEY.
2533105197Ssam *
2534105197Ssam * OUT:	0	: succeed
2535105197Ssam *	others	: error number
2536105197Ssam */
2537105197Ssamstatic int
2538105197Ssamkey_spdexpire(sp)
2539105197Ssam	struct secpolicy *sp;
2540105197Ssam{
2541105197Ssam	struct mbuf *result = NULL, *m;
2542105197Ssam	int len;
2543105197Ssam	int error = -1;
2544105197Ssam	struct sadb_lifetime *lt;
2545105197Ssam
2546105197Ssam	/* XXX: Why do we lock ? */
2547105197Ssam
2548120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2549105197Ssam
2550105197Ssam	/* set msg header */
2551105197Ssam	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2552105197Ssam	if (!m) {
2553105197Ssam		error = ENOBUFS;
2554105197Ssam		goto fail;
2555105197Ssam	}
2556105197Ssam	result = m;
2557105197Ssam
2558105197Ssam	/* create lifetime extension (current and hard) */
2559105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2560105197Ssam	m = key_alloc_mbuf(len);
2561105197Ssam	if (!m || m->m_next) {	/*XXX*/
2562105197Ssam		if (m)
2563105197Ssam			m_freem(m);
2564105197Ssam		error = ENOBUFS;
2565105197Ssam		goto fail;
2566105197Ssam	}
2567105197Ssam	bzero(mtod(m, caddr_t), len);
2568105197Ssam	lt = mtod(m, struct sadb_lifetime *);
2569105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2570105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2571105197Ssam	lt->sadb_lifetime_allocations = 0;
2572105197Ssam	lt->sadb_lifetime_bytes = 0;
2573105197Ssam	lt->sadb_lifetime_addtime = sp->created;
2574105197Ssam	lt->sadb_lifetime_usetime = sp->lastused;
2575105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2576105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2577105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2578105197Ssam	lt->sadb_lifetime_allocations = 0;
2579105197Ssam	lt->sadb_lifetime_bytes = 0;
2580105197Ssam	lt->sadb_lifetime_addtime = sp->lifetime;
2581105197Ssam	lt->sadb_lifetime_usetime = sp->validtime;
2582105197Ssam	m_cat(result, m);
2583105197Ssam
2584105197Ssam	/* set sadb_address for source */
2585105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2586105197Ssam	    &sp->spidx.src.sa,
2587105197Ssam	    sp->spidx.prefs, sp->spidx.ul_proto);
2588105197Ssam	if (!m) {
2589105197Ssam		error = ENOBUFS;
2590105197Ssam		goto fail;
2591105197Ssam	}
2592105197Ssam	m_cat(result, m);
2593105197Ssam
2594105197Ssam	/* set sadb_address for destination */
2595105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2596105197Ssam	    &sp->spidx.dst.sa,
2597105197Ssam	    sp->spidx.prefd, sp->spidx.ul_proto);
2598105197Ssam	if (!m) {
2599105197Ssam		error = ENOBUFS;
2600105197Ssam		goto fail;
2601105197Ssam	}
2602105197Ssam	m_cat(result, m);
2603105197Ssam
2604105197Ssam	/* set secpolicy */
2605105197Ssam	m = key_sp2msg(sp);
2606105197Ssam	if (!m) {
2607105197Ssam		error = ENOBUFS;
2608105197Ssam		goto fail;
2609105197Ssam	}
2610105197Ssam	m_cat(result, m);
2611105197Ssam
2612105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
2613105197Ssam		error = EINVAL;
2614105197Ssam		goto fail;
2615105197Ssam	}
2616105197Ssam
2617105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2618105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2619105197Ssam		if (result == NULL) {
2620105197Ssam			error = ENOBUFS;
2621105197Ssam			goto fail;
2622105197Ssam		}
2623105197Ssam	}
2624105197Ssam
2625105197Ssam	result->m_pkthdr.len = 0;
2626105197Ssam	for (m = result; m; m = m->m_next)
2627105197Ssam		result->m_pkthdr.len += m->m_len;
2628105197Ssam
2629105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2630105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2631105197Ssam
2632105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2633105197Ssam
2634105197Ssam fail:
2635105197Ssam	if (result)
2636105197Ssam		m_freem(result);
2637105197Ssam	return error;
2638105197Ssam}
2639105197Ssam
2640105197Ssam/* %%% SAD management */
2641105197Ssam/*
2642105197Ssam * allocating a memory for new SA head, and copy from the values of mhp.
2643105197Ssam * OUT:	NULL	: failure due to the lack of memory.
2644105197Ssam *	others	: pointer to new SA head.
2645105197Ssam */
2646105197Ssamstatic struct secashead *
2647105197Ssamkey_newsah(saidx)
2648105197Ssam	struct secasindex *saidx;
2649105197Ssam{
2650183550Szec	INIT_VNET_IPSEC(curvnet);
2651105197Ssam	struct secashead *newsah;
2652105197Ssam
2653120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2654105197Ssam
2655119643Ssam	newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2656105197Ssam	if (newsah != NULL) {
2657105197Ssam		int i;
2658105197Ssam		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2659105197Ssam			LIST_INIT(&newsah->savtree[i]);
2660105197Ssam		newsah->saidx = *saidx;
2661105197Ssam
2662105197Ssam		/* add to saidxtree */
2663105197Ssam		newsah->state = SADB_SASTATE_MATURE;
2664119643Ssam
2665120585Ssam		SAHTREE_LOCK();
2666181803Sbz		LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2667120585Ssam		SAHTREE_UNLOCK();
2668105197Ssam	}
2669105197Ssam	return(newsah);
2670105197Ssam}
2671105197Ssam
2672105197Ssam/*
2673105197Ssam * delete SA index and all SA registerd.
2674105197Ssam */
2675105197Ssamstatic void
2676105197Ssamkey_delsah(sah)
2677105197Ssam	struct secashead *sah;
2678105197Ssam{
2679183550Szec	INIT_VNET_IPSEC(curvnet);
2680105197Ssam	struct secasvar *sav, *nextsav;
2681120585Ssam	u_int stateidx;
2682105197Ssam	int zombie = 0;
2683105197Ssam
2684120585Ssam	IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2685120585Ssam	SAHTREE_LOCK_ASSERT();
2686105197Ssam
2687105197Ssam	/* searching all SA registerd in the secindex. */
2688105197Ssam	for (stateidx = 0;
2689185348Szec	     stateidx < _ARRAYLEN(saorder_state_any);
2690105197Ssam	     stateidx++) {
2691185348Szec		u_int state = saorder_state_any[stateidx];
2692120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2693105197Ssam			if (sav->refcnt == 0) {
2694105197Ssam				/* sanity check */
2695120585Ssam				KEY_CHKSASTATE(state, sav->state, __func__);
2696190071Svanhu				/*
2697190071Svanhu				 * do NOT call KEY_FREESAV here:
2698190071Svanhu				 * it will only delete the sav if refcnt == 1,
2699189962Svanhu				 * where we already know that refcnt == 0
2700189962Svanhu				 */
2701189962Svanhu				key_delsav(sav);
2702105197Ssam			} else {
2703105197Ssam				/* give up to delete this sa */
2704105197Ssam				zombie++;
2705105197Ssam			}
2706105197Ssam		}
2707105197Ssam	}
2708120585Ssam	if (!zombie) {		/* delete only if there are savs */
2709120585Ssam		/* remove from tree of SA index */
2710120585Ssam		if (__LIST_CHAINED(sah))
2711120585Ssam			LIST_REMOVE(sah, chain);
2712120585Ssam		if (sah->sa_route.ro_rt) {
2713120585Ssam			RTFREE(sah->sa_route.ro_rt);
2714120585Ssam			sah->sa_route.ro_rt = (struct rtentry *)NULL;
2715120585Ssam		}
2716120585Ssam		free(sah, M_IPSEC_SAH);
2717105197Ssam	}
2718105197Ssam}
2719105197Ssam
2720105197Ssam/*
2721105197Ssam * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2722105197Ssam * and copy the values of mhp into new buffer.
2723105197Ssam * When SAD message type is GETSPI:
2724105197Ssam *	to set sequence number from acq_seq++,
2725105197Ssam *	to set zero to SPI.
2726105197Ssam *	not to call key_setsava().
2727105197Ssam * OUT:	NULL	: fail
2728105197Ssam *	others	: pointer to new secasvar.
2729105197Ssam *
2730105197Ssam * does not modify mbuf.  does not free mbuf on error.
2731105197Ssam */
2732105197Ssamstatic struct secasvar *
2733105197Ssamkey_newsav(m, mhp, sah, errp, where, tag)
2734105197Ssam	struct mbuf *m;
2735105197Ssam	const struct sadb_msghdr *mhp;
2736105197Ssam	struct secashead *sah;
2737105197Ssam	int *errp;
2738105197Ssam	const char* where;
2739105197Ssam	int tag;
2740105197Ssam{
2741183550Szec	INIT_VNET_IPSEC(curvnet);
2742105197Ssam	struct secasvar *newsav;
2743105197Ssam	const struct sadb_sa *xsa;
2744105197Ssam
2745120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2746120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2747120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2748120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
2749105197Ssam
2750119643Ssam	newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2751105197Ssam	if (newsav == NULL) {
2752120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2753105197Ssam		*errp = ENOBUFS;
2754105197Ssam		goto done;
2755105197Ssam	}
2756105197Ssam
2757105197Ssam	switch (mhp->msg->sadb_msg_type) {
2758105197Ssam	case SADB_GETSPI:
2759105197Ssam		newsav->spi = 0;
2760105197Ssam
2761105197Ssam#ifdef IPSEC_DOSEQCHECK
2762105197Ssam		/* sync sequence number */
2763105197Ssam		if (mhp->msg->sadb_msg_seq == 0)
2764105197Ssam			newsav->seq =
2765181803Sbz				(V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2766105197Ssam		else
2767105197Ssam#endif
2768105197Ssam			newsav->seq = mhp->msg->sadb_msg_seq;
2769105197Ssam		break;
2770105197Ssam
2771105197Ssam	case SADB_ADD:
2772105197Ssam		/* sanity check */
2773105197Ssam		if (mhp->ext[SADB_EXT_SA] == NULL) {
2774119643Ssam			free(newsav, M_IPSEC_SA);
2775119643Ssam			newsav = NULL;
2776120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2777120585Ssam				__func__));
2778105197Ssam			*errp = EINVAL;
2779105197Ssam			goto done;
2780105197Ssam		}
2781105197Ssam		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2782105197Ssam		newsav->spi = xsa->sadb_sa_spi;
2783105197Ssam		newsav->seq = mhp->msg->sadb_msg_seq;
2784105197Ssam		break;
2785105197Ssam	default:
2786119643Ssam		free(newsav, M_IPSEC_SA);
2787119643Ssam		newsav = NULL;
2788105197Ssam		*errp = EINVAL;
2789105197Ssam		goto done;
2790105197Ssam	}
2791105197Ssam
2792119643Ssam
2793105197Ssam	/* copy sav values */
2794105197Ssam	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2795105197Ssam		*errp = key_setsaval(newsav, m, mhp);
2796105197Ssam		if (*errp) {
2797119643Ssam			free(newsav, M_IPSEC_SA);
2798119643Ssam			newsav = NULL;
2799105197Ssam			goto done;
2800105197Ssam		}
2801105197Ssam	}
2802105197Ssam
2803120585Ssam	SECASVAR_LOCK_INIT(newsav);
2804119643Ssam
2805105197Ssam	/* reset created */
2806105197Ssam	newsav->created = time_second;
2807105197Ssam	newsav->pid = mhp->msg->sadb_msg_pid;
2808105197Ssam
2809105197Ssam	/* add to satree */
2810105197Ssam	newsav->sah = sah;
2811158767Spjd	sa_initref(newsav);
2812105197Ssam	newsav->state = SADB_SASTATE_LARVAL;
2813119643Ssam
2814119643Ssam	/* XXX locking??? */
2815105197Ssam	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2816105197Ssam			secasvar, chain);
2817105197Ssamdone:
2818105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2819120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
2820105197Ssam			where, tag, newsav));
2821105197Ssam
2822105197Ssam	return newsav;
2823105197Ssam}
2824105197Ssam
2825105197Ssam/*
2826105197Ssam * free() SA variable entry.
2827105197Ssam */
2828105197Ssamstatic void
2829119643Ssamkey_cleansav(struct secasvar *sav)
2830105197Ssam{
2831117051Ssam	/*
2832117051Ssam	 * Cleanup xform state.  Note that zeroize'ing causes the
2833117051Ssam	 * keys to be cleared; otherwise we must do it ourself.
2834117051Ssam	 */
2835117051Ssam	if (sav->tdb_xform != NULL) {
2836117051Ssam		sav->tdb_xform->xf_zeroize(sav);
2837117051Ssam		sav->tdb_xform = NULL;
2838117051Ssam	} else {
2839120585Ssam		KASSERT(sav->iv == NULL, ("iv but no xform"));
2840117051Ssam		if (sav->key_auth != NULL)
2841157123Sgnn			bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2842117051Ssam		if (sav->key_enc != NULL)
2843157123Sgnn			bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2844117051Ssam	}
2845105197Ssam	if (sav->key_auth != NULL) {
2846157123Sgnn		if (sav->key_auth->key_data != NULL)
2847157123Sgnn			free(sav->key_auth->key_data, M_IPSEC_MISC);
2848119643Ssam		free(sav->key_auth, M_IPSEC_MISC);
2849105197Ssam		sav->key_auth = NULL;
2850105197Ssam	}
2851105197Ssam	if (sav->key_enc != NULL) {
2852157123Sgnn		if (sav->key_enc->key_data != NULL)
2853157123Sgnn			free(sav->key_enc->key_data, M_IPSEC_MISC);
2854119643Ssam		free(sav->key_enc, M_IPSEC_MISC);
2855105197Ssam		sav->key_enc = NULL;
2856105197Ssam	}
2857105197Ssam	if (sav->sched) {
2858105197Ssam		bzero(sav->sched, sav->schedlen);
2859119643Ssam		free(sav->sched, M_IPSEC_MISC);
2860105197Ssam		sav->sched = NULL;
2861105197Ssam	}
2862105197Ssam	if (sav->replay != NULL) {
2863119643Ssam		free(sav->replay, M_IPSEC_MISC);
2864105197Ssam		sav->replay = NULL;
2865105197Ssam	}
2866105197Ssam	if (sav->lft_c != NULL) {
2867119643Ssam		free(sav->lft_c, M_IPSEC_MISC);
2868105197Ssam		sav->lft_c = NULL;
2869105197Ssam	}
2870105197Ssam	if (sav->lft_h != NULL) {
2871119643Ssam		free(sav->lft_h, M_IPSEC_MISC);
2872105197Ssam		sav->lft_h = NULL;
2873105197Ssam	}
2874105197Ssam	if (sav->lft_s != NULL) {
2875119643Ssam		free(sav->lft_s, M_IPSEC_MISC);
2876105197Ssam		sav->lft_s = NULL;
2877105197Ssam	}
2878119643Ssam}
2879105197Ssam
2880119643Ssam/*
2881119643Ssam * free() SA variable entry.
2882119643Ssam */
2883119643Ssamstatic void
2884119643Ssamkey_delsav(sav)
2885119643Ssam	struct secasvar *sav;
2886119643Ssam{
2887120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
2888120585Ssam	IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2889105197Ssam
2890119643Ssam	/* remove from SA header */
2891119643Ssam	if (__LIST_CHAINED(sav))
2892119643Ssam		LIST_REMOVE(sav, chain);
2893119643Ssam	key_cleansav(sav);
2894120585Ssam	SECASVAR_LOCK_DESTROY(sav);
2895119643Ssam	free(sav, M_IPSEC_SA);
2896105197Ssam}
2897105197Ssam
2898105197Ssam/*
2899105197Ssam * search SAD.
2900105197Ssam * OUT:
2901105197Ssam *	NULL	: not found
2902105197Ssam *	others	: found, pointer to a SA.
2903105197Ssam */
2904105197Ssamstatic struct secashead *
2905105197Ssamkey_getsah(saidx)
2906105197Ssam	struct secasindex *saidx;
2907105197Ssam{
2908183550Szec	INIT_VNET_IPSEC(curvnet);
2909105197Ssam	struct secashead *sah;
2910105197Ssam
2911120585Ssam	SAHTREE_LOCK();
2912181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
2913105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
2914105197Ssam			continue;
2915105197Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2916119643Ssam			break;
2917105197Ssam	}
2918120585Ssam	SAHTREE_UNLOCK();
2919105197Ssam
2920119643Ssam	return sah;
2921105197Ssam}
2922105197Ssam
2923105197Ssam/*
2924105197Ssam * check not to be duplicated SPI.
2925105197Ssam * NOTE: this function is too slow due to searching all SAD.
2926105197Ssam * OUT:
2927105197Ssam *	NULL	: not found
2928105197Ssam *	others	: found, pointer to a SA.
2929105197Ssam */
2930105197Ssamstatic struct secasvar *
2931105197Ssamkey_checkspidup(saidx, spi)
2932105197Ssam	struct secasindex *saidx;
2933105197Ssam	u_int32_t spi;
2934105197Ssam{
2935183550Szec	INIT_VNET_IPSEC(curvnet);
2936105197Ssam	struct secashead *sah;
2937105197Ssam	struct secasvar *sav;
2938105197Ssam
2939105197Ssam	/* check address family */
2940105197Ssam	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2941120585Ssam		ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2942120585Ssam			__func__));
2943105197Ssam		return NULL;
2944105197Ssam	}
2945105197Ssam
2946119643Ssam	sav = NULL;
2947105197Ssam	/* check all SAD */
2948120585Ssam	SAHTREE_LOCK();
2949181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
2950105197Ssam		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2951105197Ssam			continue;
2952105197Ssam		sav = key_getsavbyspi(sah, spi);
2953105197Ssam		if (sav != NULL)
2954119643Ssam			break;
2955105197Ssam	}
2956120585Ssam	SAHTREE_UNLOCK();
2957105197Ssam
2958119643Ssam	return sav;
2959105197Ssam}
2960105197Ssam
2961105197Ssam/*
2962105197Ssam * search SAD litmited alive SA, protocol, SPI.
2963105197Ssam * OUT:
2964105197Ssam *	NULL	: not found
2965105197Ssam *	others	: found, pointer to a SA.
2966105197Ssam */
2967105197Ssamstatic struct secasvar *
2968105197Ssamkey_getsavbyspi(sah, spi)
2969105197Ssam	struct secashead *sah;
2970105197Ssam	u_int32_t spi;
2971105197Ssam{
2972183550Szec	INIT_VNET_IPSEC(curvnet);
2973105197Ssam	struct secasvar *sav;
2974105197Ssam	u_int stateidx, state;
2975105197Ssam
2976119643Ssam	sav = NULL;
2977120585Ssam	SAHTREE_LOCK_ASSERT();
2978105197Ssam	/* search all status */
2979105197Ssam	for (stateidx = 0;
2980185348Szec	     stateidx < _ARRAYLEN(saorder_state_alive);
2981105197Ssam	     stateidx++) {
2982105197Ssam
2983185348Szec		state = saorder_state_alive[stateidx];
2984105197Ssam		LIST_FOREACH(sav, &sah->savtree[state], chain) {
2985105197Ssam
2986105197Ssam			/* sanity check */
2987105197Ssam			if (sav->state != state) {
2988120585Ssam				ipseclog((LOG_DEBUG, "%s: "
2989105197Ssam				    "invalid sav->state (queue: %d SA: %d)\n",
2990120585Ssam				    __func__, state, sav->state));
2991105197Ssam				continue;
2992105197Ssam			}
2993105197Ssam
2994105197Ssam			if (sav->spi == spi)
2995128859Ssam				return sav;
2996105197Ssam		}
2997105197Ssam	}
2998105197Ssam
2999128859Ssam	return NULL;
3000105197Ssam}
3001105197Ssam
3002105197Ssam/*
3003105197Ssam * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3004105197Ssam * You must update these if need.
3005105197Ssam * OUT:	0:	success.
3006105197Ssam *	!0:	failure.
3007105197Ssam *
3008105197Ssam * does not modify mbuf.  does not free mbuf on error.
3009105197Ssam */
3010105197Ssamstatic int
3011105197Ssamkey_setsaval(sav, m, mhp)
3012105197Ssam	struct secasvar *sav;
3013105197Ssam	struct mbuf *m;
3014105197Ssam	const struct sadb_msghdr *mhp;
3015105197Ssam{
3016183550Szec	INIT_VNET_IPSEC(curvnet);
3017105197Ssam	int error = 0;
3018105197Ssam
3019120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
3020120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3021120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3022105197Ssam
3023105197Ssam	/* initialization */
3024105197Ssam	sav->replay = NULL;
3025105197Ssam	sav->key_auth = NULL;
3026105197Ssam	sav->key_enc = NULL;
3027105197Ssam	sav->sched = NULL;
3028105197Ssam	sav->schedlen = 0;
3029105197Ssam	sav->iv = NULL;
3030105197Ssam	sav->lft_c = NULL;
3031105197Ssam	sav->lft_h = NULL;
3032105197Ssam	sav->lft_s = NULL;
3033105197Ssam	sav->tdb_xform = NULL;		/* transform */
3034105197Ssam	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
3035105197Ssam	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
3036105197Ssam	sav->tdb_compalgxform = NULL;	/* compression algorithm */
3037105197Ssam
3038105197Ssam	/* SA */
3039105197Ssam	if (mhp->ext[SADB_EXT_SA] != NULL) {
3040105197Ssam		const struct sadb_sa *sa0;
3041105197Ssam
3042105197Ssam		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3043105197Ssam		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3044105197Ssam			error = EINVAL;
3045105197Ssam			goto fail;
3046105197Ssam		}
3047105197Ssam
3048105197Ssam		sav->alg_auth = sa0->sadb_sa_auth;
3049105197Ssam		sav->alg_enc = sa0->sadb_sa_encrypt;
3050105197Ssam		sav->flags = sa0->sadb_sa_flags;
3051105197Ssam
3052105197Ssam		/* replay window */
3053105197Ssam		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3054105197Ssam			sav->replay = (struct secreplay *)
3055119643Ssam				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3056105197Ssam			if (sav->replay == NULL) {
3057120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3058120585Ssam					__func__));
3059105197Ssam				error = ENOBUFS;
3060105197Ssam				goto fail;
3061105197Ssam			}
3062105197Ssam			if (sa0->sadb_sa_replay != 0)
3063105197Ssam				sav->replay->bitmap = (caddr_t)(sav->replay+1);
3064105197Ssam			sav->replay->wsize = sa0->sadb_sa_replay;
3065105197Ssam		}
3066105197Ssam	}
3067105197Ssam
3068105197Ssam	/* Authentication keys */
3069105197Ssam	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3070105197Ssam		const struct sadb_key *key0;
3071105197Ssam		int len;
3072105197Ssam
3073105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3074105197Ssam		len = mhp->extlen[SADB_EXT_KEY_AUTH];
3075105197Ssam
3076105197Ssam		error = 0;
3077105197Ssam		if (len < sizeof(*key0)) {
3078105197Ssam			error = EINVAL;
3079105197Ssam			goto fail;
3080105197Ssam		}
3081105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3082105197Ssam		case SADB_SATYPE_AH:
3083105197Ssam		case SADB_SATYPE_ESP:
3084125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3085105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3086105197Ssam			    sav->alg_auth != SADB_X_AALG_NULL)
3087105197Ssam				error = EINVAL;
3088105197Ssam			break;
3089105197Ssam		case SADB_X_SATYPE_IPCOMP:
3090105197Ssam		default:
3091105197Ssam			error = EINVAL;
3092105197Ssam			break;
3093105197Ssam		}
3094105197Ssam		if (error) {
3095120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3096120585Ssam				__func__));
3097105197Ssam			goto fail;
3098105197Ssam		}
3099105197Ssam
3100157123Sgnn		sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3101157123Sgnn								M_IPSEC_MISC);
3102157123Sgnn		if (sav->key_auth == NULL ) {
3103157123Sgnn			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3104157123Sgnn				  __func__));
3105105197Ssam			error = ENOBUFS;
3106105197Ssam			goto fail;
3107105197Ssam		}
3108105197Ssam	}
3109105197Ssam
3110105197Ssam	/* Encryption key */
3111105197Ssam	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3112105197Ssam		const struct sadb_key *key0;
3113105197Ssam		int len;
3114105197Ssam
3115105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3116105197Ssam		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3117105197Ssam
3118105197Ssam		error = 0;
3119105197Ssam		if (len < sizeof(*key0)) {
3120105197Ssam			error = EINVAL;
3121105197Ssam			goto fail;
3122105197Ssam		}
3123105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3124105197Ssam		case SADB_SATYPE_ESP:
3125105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3126105197Ssam			    sav->alg_enc != SADB_EALG_NULL) {
3127105197Ssam				error = EINVAL;
3128105197Ssam				break;
3129105197Ssam			}
3130157123Sgnn			sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3131157123Sgnn								       len,
3132157123Sgnn								       M_IPSEC_MISC);
3133105197Ssam			if (sav->key_enc == NULL) {
3134120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3135120585Ssam					__func__));
3136105197Ssam				error = ENOBUFS;
3137105197Ssam				goto fail;
3138105197Ssam			}
3139105197Ssam			break;
3140105197Ssam		case SADB_X_SATYPE_IPCOMP:
3141105197Ssam			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3142105197Ssam				error = EINVAL;
3143105197Ssam			sav->key_enc = NULL;	/*just in case*/
3144105197Ssam			break;
3145105197Ssam		case SADB_SATYPE_AH:
3146125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3147105197Ssam		default:
3148105197Ssam			error = EINVAL;
3149105197Ssam			break;
3150105197Ssam		}
3151105197Ssam		if (error) {
3152120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3153120585Ssam				__func__));
3154105197Ssam			goto fail;
3155105197Ssam		}
3156105197Ssam	}
3157105197Ssam
3158105197Ssam	/* set iv */
3159105197Ssam	sav->ivlen = 0;
3160105197Ssam
3161105197Ssam	switch (mhp->msg->sadb_msg_satype) {
3162105197Ssam	case SADB_SATYPE_AH:
3163105197Ssam		error = xform_init(sav, XF_AH);
3164105197Ssam		break;
3165105197Ssam	case SADB_SATYPE_ESP:
3166105197Ssam		error = xform_init(sav, XF_ESP);
3167105197Ssam		break;
3168105197Ssam	case SADB_X_SATYPE_IPCOMP:
3169105197Ssam		error = xform_init(sav, XF_IPCOMP);
3170105197Ssam		break;
3171125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
3172125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3173125680Sbms		break;
3174105197Ssam	}
3175105197Ssam	if (error) {
3176120585Ssam		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3177120585Ssam		        __func__, mhp->msg->sadb_msg_satype));
3178105197Ssam		goto fail;
3179105197Ssam	}
3180105197Ssam
3181105197Ssam	/* reset created */
3182105197Ssam	sav->created = time_second;
3183105197Ssam
3184105197Ssam	/* make lifetime for CURRENT */
3185176743Sbz	sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3186105197Ssam	if (sav->lft_c == NULL) {
3187120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3188105197Ssam		error = ENOBUFS;
3189105197Ssam		goto fail;
3190105197Ssam	}
3191105197Ssam
3192157123Sgnn	sav->lft_c->allocations = 0;
3193157123Sgnn	sav->lft_c->bytes = 0;
3194157123Sgnn	sav->lft_c->addtime = time_second;
3195157123Sgnn	sav->lft_c->usetime = 0;
3196105197Ssam
3197105197Ssam	/* lifetimes for HARD and SOFT */
3198105197Ssam    {
3199105197Ssam	const struct sadb_lifetime *lft0;
3200105197Ssam
3201105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3202105197Ssam	if (lft0 != NULL) {
3203105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3204105197Ssam			error = EINVAL;
3205105197Ssam			goto fail;
3206105197Ssam		}
3207157123Sgnn		sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3208105197Ssam		if (sav->lft_h == NULL) {
3209120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3210105197Ssam			error = ENOBUFS;
3211105197Ssam			goto fail;
3212105197Ssam		}
3213105197Ssam		/* to be initialize ? */
3214105197Ssam	}
3215105197Ssam
3216105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3217105197Ssam	if (lft0 != NULL) {
3218105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3219105197Ssam			error = EINVAL;
3220105197Ssam			goto fail;
3221105197Ssam		}
3222157123Sgnn		sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3223105197Ssam		if (sav->lft_s == NULL) {
3224120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3225105197Ssam			error = ENOBUFS;
3226105197Ssam			goto fail;
3227105197Ssam		}
3228105197Ssam		/* to be initialize ? */
3229105197Ssam	}
3230105197Ssam    }
3231105197Ssam
3232105197Ssam	return 0;
3233105197Ssam
3234105197Ssam fail:
3235105197Ssam	/* initialization */
3236119643Ssam	key_cleansav(sav);
3237105197Ssam
3238105197Ssam	return error;
3239105197Ssam}
3240105197Ssam
3241105197Ssam/*
3242105197Ssam * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3243105197Ssam * OUT:	0:	valid
3244105197Ssam *	other:	errno
3245105197Ssam */
3246105197Ssamstatic int
3247119643Ssamkey_mature(struct secasvar *sav)
3248105197Ssam{
3249183550Szec	INIT_VNET_IPSEC(curvnet);
3250105197Ssam	int error;
3251105197Ssam
3252105197Ssam	/* check SPI value */
3253105197Ssam	switch (sav->sah->saidx.proto) {
3254105197Ssam	case IPPROTO_ESP:
3255105197Ssam	case IPPROTO_AH:
3256170823Sbz		/*
3257170823Sbz		 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3258170823Sbz		 * 1-255 reserved by IANA for future use,
3259170823Sbz		 * 0 for implementation specific, local use.
3260170823Sbz		 */
3261170823Sbz		if (ntohl(sav->spi) <= 255) {
3262120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3263120585Ssam			    __func__, (u_int32_t)ntohl(sav->spi)));
3264105197Ssam			return EINVAL;
3265105197Ssam		}
3266105197Ssam		break;
3267105197Ssam	}
3268105197Ssam
3269105197Ssam	/* check satype */
3270105197Ssam	switch (sav->sah->saidx.proto) {
3271105197Ssam	case IPPROTO_ESP:
3272105197Ssam		/* check flags */
3273105197Ssam		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3274105197Ssam		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3275120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3276120585Ssam				"given to old-esp.\n", __func__));
3277105197Ssam			return EINVAL;
3278105197Ssam		}
3279105197Ssam		error = xform_init(sav, XF_ESP);
3280105197Ssam		break;
3281105197Ssam	case IPPROTO_AH:
3282105197Ssam		/* check flags */
3283105197Ssam		if (sav->flags & SADB_X_EXT_DERIV) {
3284120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3285120585Ssam				"given to AH SA.\n", __func__));
3286105197Ssam			return EINVAL;
3287105197Ssam		}
3288105197Ssam		if (sav->alg_enc != SADB_EALG_NONE) {
3289120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3290120585Ssam				"mismated.\n", __func__));
3291105197Ssam			return(EINVAL);
3292105197Ssam		}
3293105197Ssam		error = xform_init(sav, XF_AH);
3294105197Ssam		break;
3295105197Ssam	case IPPROTO_IPCOMP:
3296105197Ssam		if (sav->alg_auth != SADB_AALG_NONE) {
3297120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3298120585Ssam				"mismated.\n", __func__));
3299105197Ssam			return(EINVAL);
3300105197Ssam		}
3301105197Ssam		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3302105197Ssam		 && ntohl(sav->spi) >= 0x10000) {
3303120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3304120585Ssam				__func__));
3305105197Ssam			return(EINVAL);
3306105197Ssam		}
3307105197Ssam		error = xform_init(sav, XF_IPCOMP);
3308105197Ssam		break;
3309125680Sbms	case IPPROTO_TCP:
3310125680Sbms		if (sav->alg_enc != SADB_EALG_NONE) {
3311125680Sbms			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3312125680Sbms				"mismated.\n", __func__));
3313125680Sbms			return(EINVAL);
3314125680Sbms		}
3315125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3316125680Sbms		break;
3317105197Ssam	default:
3318120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3319105197Ssam		error = EPROTONOSUPPORT;
3320105197Ssam		break;
3321105197Ssam	}
3322119643Ssam	if (error == 0) {
3323120585Ssam		SAHTREE_LOCK();
3324105197Ssam		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3325120585Ssam		SAHTREE_UNLOCK();
3326119643Ssam	}
3327105197Ssam	return (error);
3328105197Ssam}
3329105197Ssam
3330105197Ssam/*
3331105197Ssam * subroutine for SADB_GET and SADB_DUMP.
3332105197Ssam */
3333105197Ssamstatic struct mbuf *
3334189004Srdivackykey_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3335189004Srdivacky    u_int32_t seq, u_int32_t pid)
3336105197Ssam{
3337105197Ssam	struct mbuf *result = NULL, *tres = NULL, *m;
3338105197Ssam	int i;
3339105197Ssam	int dumporder[] = {
3340105197Ssam		SADB_EXT_SA, SADB_X_EXT_SA2,
3341105197Ssam		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3342105197Ssam		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3343105197Ssam		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3344105197Ssam		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3345105197Ssam		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3346105197Ssam	};
3347105197Ssam
3348105197Ssam	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3349105197Ssam	if (m == NULL)
3350105197Ssam		goto fail;
3351105197Ssam	result = m;
3352105197Ssam
3353105197Ssam	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3354105197Ssam		m = NULL;
3355105197Ssam		switch (dumporder[i]) {
3356105197Ssam		case SADB_EXT_SA:
3357105197Ssam			m = key_setsadbsa(sav);
3358105197Ssam			if (!m)
3359105197Ssam				goto fail;
3360105197Ssam			break;
3361105197Ssam
3362105197Ssam		case SADB_X_EXT_SA2:
3363105197Ssam			m = key_setsadbxsa2(sav->sah->saidx.mode,
3364105197Ssam					sav->replay ? sav->replay->count : 0,
3365105197Ssam					sav->sah->saidx.reqid);
3366105197Ssam			if (!m)
3367105197Ssam				goto fail;
3368105197Ssam			break;
3369105197Ssam
3370105197Ssam		case SADB_EXT_ADDRESS_SRC:
3371105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3372105197Ssam			    &sav->sah->saidx.src.sa,
3373105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3374105197Ssam			if (!m)
3375105197Ssam				goto fail;
3376105197Ssam			break;
3377105197Ssam
3378105197Ssam		case SADB_EXT_ADDRESS_DST:
3379105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3380105197Ssam			    &sav->sah->saidx.dst.sa,
3381105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3382105197Ssam			if (!m)
3383105197Ssam				goto fail;
3384105197Ssam			break;
3385105197Ssam
3386105197Ssam		case SADB_EXT_KEY_AUTH:
3387105197Ssam			if (!sav->key_auth)
3388105197Ssam				continue;
3389157123Sgnn			m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3390157123Sgnn			if (!m)
3391157123Sgnn				goto fail;
3392105197Ssam			break;
3393105197Ssam
3394105197Ssam		case SADB_EXT_KEY_ENCRYPT:
3395105197Ssam			if (!sav->key_enc)
3396105197Ssam				continue;
3397157123Sgnn			m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3398157123Sgnn			if (!m)
3399157123Sgnn				goto fail;
3400105197Ssam			break;
3401105197Ssam
3402105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
3403105197Ssam			if (!sav->lft_c)
3404105197Ssam				continue;
3405157123Sgnn			m = key_setlifetime(sav->lft_c,
3406157123Sgnn					    SADB_EXT_LIFETIME_CURRENT);
3407157123Sgnn			if (!m)
3408157123Sgnn				goto fail;
3409105197Ssam			break;
3410105197Ssam
3411105197Ssam		case SADB_EXT_LIFETIME_HARD:
3412105197Ssam			if (!sav->lft_h)
3413105197Ssam				continue;
3414157123Sgnn			m = key_setlifetime(sav->lft_h,
3415157123Sgnn					    SADB_EXT_LIFETIME_HARD);
3416157123Sgnn			if (!m)
3417157123Sgnn				goto fail;
3418105197Ssam			break;
3419105197Ssam
3420105197Ssam		case SADB_EXT_LIFETIME_SOFT:
3421105197Ssam			if (!sav->lft_s)
3422105197Ssam				continue;
3423177554Sbz			m = key_setlifetime(sav->lft_s,
3424157123Sgnn					    SADB_EXT_LIFETIME_SOFT);
3425157123Sgnn
3426157123Sgnn			if (!m)
3427157123Sgnn				goto fail;
3428105197Ssam			break;
3429105197Ssam
3430105197Ssam		case SADB_EXT_ADDRESS_PROXY:
3431105197Ssam		case SADB_EXT_IDENTITY_SRC:
3432105197Ssam		case SADB_EXT_IDENTITY_DST:
3433105197Ssam			/* XXX: should we brought from SPD ? */
3434105197Ssam		case SADB_EXT_SENSITIVITY:
3435105197Ssam		default:
3436105197Ssam			continue;
3437105197Ssam		}
3438105197Ssam
3439157123Sgnn		if (!m)
3440105197Ssam			goto fail;
3441105197Ssam		if (tres)
3442105197Ssam			m_cat(m, tres);
3443105197Ssam		tres = m;
3444157123Sgnn
3445105197Ssam	}
3446105197Ssam
3447105197Ssam	m_cat(result, tres);
3448105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
3449105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
3450105197Ssam		if (result == NULL)
3451105197Ssam			goto fail;
3452105197Ssam	}
3453105197Ssam
3454105197Ssam	result->m_pkthdr.len = 0;
3455105197Ssam	for (m = result; m; m = m->m_next)
3456105197Ssam		result->m_pkthdr.len += m->m_len;
3457105197Ssam
3458105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
3459105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
3460105197Ssam
3461105197Ssam	return result;
3462105197Ssam
3463105197Ssamfail:
3464105197Ssam	m_freem(result);
3465105197Ssam	m_freem(tres);
3466105197Ssam	return NULL;
3467105197Ssam}
3468105197Ssam
3469105197Ssam/*
3470105197Ssam * set data into sadb_msg.
3471105197Ssam */
3472105197Ssamstatic struct mbuf *
3473189004Srdivackykey_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3474189004Srdivacky    pid_t pid, u_int16_t reserved)
3475105197Ssam{
3476105197Ssam	struct mbuf *m;
3477105197Ssam	struct sadb_msg *p;
3478105197Ssam	int len;
3479105197Ssam
3480105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3481105197Ssam	if (len > MCLBYTES)
3482105197Ssam		return NULL;
3483111119Simp	MGETHDR(m, M_DONTWAIT, MT_DATA);
3484105197Ssam	if (m && len > MHLEN) {
3485111119Simp		MCLGET(m, M_DONTWAIT);
3486105197Ssam		if ((m->m_flags & M_EXT) == 0) {
3487105197Ssam			m_freem(m);
3488105197Ssam			m = NULL;
3489105197Ssam		}
3490105197Ssam	}
3491105197Ssam	if (!m)
3492105197Ssam		return NULL;
3493105197Ssam	m->m_pkthdr.len = m->m_len = len;
3494105197Ssam	m->m_next = NULL;
3495105197Ssam
3496105197Ssam	p = mtod(m, struct sadb_msg *);
3497105197Ssam
3498105197Ssam	bzero(p, len);
3499105197Ssam	p->sadb_msg_version = PF_KEY_V2;
3500105197Ssam	p->sadb_msg_type = type;
3501105197Ssam	p->sadb_msg_errno = 0;
3502105197Ssam	p->sadb_msg_satype = satype;
3503105197Ssam	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3504105197Ssam	p->sadb_msg_reserved = reserved;
3505105197Ssam	p->sadb_msg_seq = seq;
3506105197Ssam	p->sadb_msg_pid = (u_int32_t)pid;
3507105197Ssam
3508105197Ssam	return m;
3509105197Ssam}
3510105197Ssam
3511105197Ssam/*
3512105197Ssam * copy secasvar data into sadb_address.
3513105197Ssam */
3514105197Ssamstatic struct mbuf *
3515105197Ssamkey_setsadbsa(sav)
3516105197Ssam	struct secasvar *sav;
3517105197Ssam{
3518105197Ssam	struct mbuf *m;
3519105197Ssam	struct sadb_sa *p;
3520105197Ssam	int len;
3521105197Ssam
3522105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3523105197Ssam	m = key_alloc_mbuf(len);
3524105197Ssam	if (!m || m->m_next) {	/*XXX*/
3525105197Ssam		if (m)
3526105197Ssam			m_freem(m);
3527105197Ssam		return NULL;
3528105197Ssam	}
3529105197Ssam
3530105197Ssam	p = mtod(m, struct sadb_sa *);
3531105197Ssam
3532105197Ssam	bzero(p, len);
3533105197Ssam	p->sadb_sa_len = PFKEY_UNIT64(len);
3534105197Ssam	p->sadb_sa_exttype = SADB_EXT_SA;
3535105197Ssam	p->sadb_sa_spi = sav->spi;
3536105197Ssam	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3537105197Ssam	p->sadb_sa_state = sav->state;
3538105197Ssam	p->sadb_sa_auth = sav->alg_auth;
3539105197Ssam	p->sadb_sa_encrypt = sav->alg_enc;
3540105197Ssam	p->sadb_sa_flags = sav->flags;
3541105197Ssam
3542105197Ssam	return m;
3543105197Ssam}
3544105197Ssam
3545105197Ssam/*
3546105197Ssam * set data into sadb_address.
3547105197Ssam */
3548105197Ssamstatic struct mbuf *
3549189004Srdivackykey_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto)
3550105197Ssam{
3551105197Ssam	struct mbuf *m;
3552105197Ssam	struct sadb_address *p;
3553105197Ssam	size_t len;
3554105197Ssam
3555105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3556105197Ssam	    PFKEY_ALIGN8(saddr->sa_len);
3557105197Ssam	m = key_alloc_mbuf(len);
3558105197Ssam	if (!m || m->m_next) {	/*XXX*/
3559105197Ssam		if (m)
3560105197Ssam			m_freem(m);
3561105197Ssam		return NULL;
3562105197Ssam	}
3563105197Ssam
3564105197Ssam	p = mtod(m, struct sadb_address *);
3565105197Ssam
3566105197Ssam	bzero(p, len);
3567105197Ssam	p->sadb_address_len = PFKEY_UNIT64(len);
3568105197Ssam	p->sadb_address_exttype = exttype;
3569105197Ssam	p->sadb_address_proto = ul_proto;
3570105197Ssam	if (prefixlen == FULLMASK) {
3571105197Ssam		switch (saddr->sa_family) {
3572105197Ssam		case AF_INET:
3573105197Ssam			prefixlen = sizeof(struct in_addr) << 3;
3574105197Ssam			break;
3575105197Ssam		case AF_INET6:
3576105197Ssam			prefixlen = sizeof(struct in6_addr) << 3;
3577105197Ssam			break;
3578105197Ssam		default:
3579105197Ssam			; /*XXX*/
3580105197Ssam		}
3581105197Ssam	}
3582105197Ssam	p->sadb_address_prefixlen = prefixlen;
3583105197Ssam	p->sadb_address_reserved = 0;
3584105197Ssam
3585105197Ssam	bcopy(saddr,
3586105197Ssam	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3587105197Ssam	    saddr->sa_len);
3588105197Ssam
3589105197Ssam	return m;
3590105197Ssam}
3591105197Ssam
3592105197Ssam/*
3593105197Ssam * set data into sadb_x_sa2.
3594105197Ssam */
3595105197Ssamstatic struct mbuf *
3596189004Srdivackykey_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3597105197Ssam{
3598105197Ssam	struct mbuf *m;
3599105197Ssam	struct sadb_x_sa2 *p;
3600105197Ssam	size_t len;
3601105197Ssam
3602105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3603105197Ssam	m = key_alloc_mbuf(len);
3604105197Ssam	if (!m || m->m_next) {	/*XXX*/
3605105197Ssam		if (m)
3606105197Ssam			m_freem(m);
3607105197Ssam		return NULL;
3608105197Ssam	}
3609105197Ssam
3610105197Ssam	p = mtod(m, struct sadb_x_sa2 *);
3611105197Ssam
3612105197Ssam	bzero(p, len);
3613105197Ssam	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3614105197Ssam	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3615105197Ssam	p->sadb_x_sa2_mode = mode;
3616105197Ssam	p->sadb_x_sa2_reserved1 = 0;
3617105197Ssam	p->sadb_x_sa2_reserved2 = 0;
3618105197Ssam	p->sadb_x_sa2_sequence = seq;
3619105197Ssam	p->sadb_x_sa2_reqid = reqid;
3620105197Ssam
3621105197Ssam	return m;
3622105197Ssam}
3623105197Ssam
3624105197Ssam/*
3625105197Ssam * set data into sadb_x_policy
3626105197Ssam */
3627105197Ssamstatic struct mbuf *
3628189004Srdivackykey_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3629105197Ssam{
3630105197Ssam	struct mbuf *m;
3631105197Ssam	struct sadb_x_policy *p;
3632105197Ssam	size_t len;
3633105197Ssam
3634105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3635105197Ssam	m = key_alloc_mbuf(len);
3636105197Ssam	if (!m || m->m_next) {	/*XXX*/
3637105197Ssam		if (m)
3638105197Ssam			m_freem(m);
3639105197Ssam		return NULL;
3640105197Ssam	}
3641105197Ssam
3642105197Ssam	p = mtod(m, struct sadb_x_policy *);
3643105197Ssam
3644105197Ssam	bzero(p, len);
3645105197Ssam	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3646105197Ssam	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3647105197Ssam	p->sadb_x_policy_type = type;
3648105197Ssam	p->sadb_x_policy_dir = dir;
3649105197Ssam	p->sadb_x_policy_id = id;
3650105197Ssam
3651105197Ssam	return m;
3652105197Ssam}
3653105197Ssam
3654105197Ssam/* %%% utilities */
3655157123Sgnn/* Take a key message (sadb_key) from the socket and turn it into one
3656157123Sgnn * of the kernel's key structures (seckey).
3657157123Sgnn *
3658157123Sgnn * IN: pointer to the src
3659157123Sgnn * OUT: NULL no more memory
3660105197Ssam */
3661157123Sgnnstruct seckey *
3662157123Sgnnkey_dup_keymsg(const struct sadb_key *src, u_int len,
3663157123Sgnn	       struct malloc_type *type)
3664105197Ssam{
3665183550Szec	INIT_VNET_IPSEC(curvnet);
3666157123Sgnn	struct seckey *dst;
3667157123Sgnn	dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3668157123Sgnn	if (dst != NULL) {
3669157123Sgnn		dst->bits = src->sadb_key_bits;
3670157123Sgnn		dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3671157123Sgnn		if (dst->key_data != NULL) {
3672157123Sgnn			bcopy((const char *)src + sizeof(struct sadb_key),
3673157123Sgnn			      dst->key_data, len);
3674157123Sgnn		} else {
3675157123Sgnn			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3676157123Sgnn				  __func__));
3677157123Sgnn			free(dst, type);
3678157123Sgnn			dst = NULL;
3679157123Sgnn		}
3680157123Sgnn	} else {
3681157123Sgnn		ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3682157123Sgnn			  __func__));
3683105197Ssam
3684157123Sgnn	}
3685157123Sgnn	return dst;
3686157123Sgnn}
3687157123Sgnn
3688157123Sgnn/* Take a lifetime message (sadb_lifetime) passed in on a socket and
3689157123Sgnn * turn it into one of the kernel's lifetime structures (seclifetime).
3690157123Sgnn *
3691157123Sgnn * IN: pointer to the destination, source and malloc type
3692157123Sgnn * OUT: NULL, no more memory
3693157123Sgnn */
3694157123Sgnn
3695157123Sgnnstatic struct seclifetime *
3696157123Sgnnkey_dup_lifemsg(const struct sadb_lifetime *src,
3697157123Sgnn		 struct malloc_type *type)
3698157123Sgnn{
3699183550Szec	INIT_VNET_IPSEC(curvnet);
3700157123Sgnn	struct seclifetime *dst = NULL;
3701157123Sgnn
3702157123Sgnn	dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3703157123Sgnn					   type, M_NOWAIT);
3704157123Sgnn	if (dst == NULL) {
3705119643Ssam		/* XXX counter */
3706120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3707157123Sgnn	} else {
3708157123Sgnn		dst->allocations = src->sadb_lifetime_allocations;
3709157123Sgnn		dst->bytes = src->sadb_lifetime_bytes;
3710157123Sgnn		dst->addtime = src->sadb_lifetime_addtime;
3711157123Sgnn		dst->usetime = src->sadb_lifetime_usetime;
3712157123Sgnn	}
3713157123Sgnn	return dst;
3714105197Ssam}
3715105197Ssam
3716105197Ssam/* compare my own address
3717105197Ssam * OUT:	1: true, i.e. my address.
3718105197Ssam *	0: false
3719105197Ssam */
3720105197Ssamint
3721105197Ssamkey_ismyaddr(sa)
3722105197Ssam	struct sockaddr *sa;
3723105197Ssam{
3724105197Ssam#ifdef INET
3725183550Szec	INIT_VNET_INET(curvnet);
3726105197Ssam	struct sockaddr_in *sin;
3727105197Ssam	struct in_ifaddr *ia;
3728105197Ssam#endif
3729105197Ssam
3730120585Ssam	IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3731105197Ssam
3732105197Ssam	switch (sa->sa_family) {
3733105197Ssam#ifdef INET
3734105197Ssam	case AF_INET:
3735105197Ssam		sin = (struct sockaddr_in *)sa;
3736181803Sbz		for (ia = V_in_ifaddrhead.tqh_first; ia;
3737105197Ssam		     ia = ia->ia_link.tqe_next)
3738105197Ssam		{
3739105197Ssam			if (sin->sin_family == ia->ia_addr.sin_family &&
3740105197Ssam			    sin->sin_len == ia->ia_addr.sin_len &&
3741105197Ssam			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3742105197Ssam			{
3743105197Ssam				return 1;
3744105197Ssam			}
3745105197Ssam		}
3746105197Ssam		break;
3747105197Ssam#endif
3748105197Ssam#ifdef INET6
3749105197Ssam	case AF_INET6:
3750105197Ssam		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3751105197Ssam#endif
3752105197Ssam	}
3753105197Ssam
3754105197Ssam	return 0;
3755105197Ssam}
3756105197Ssam
3757105197Ssam#ifdef INET6
3758105197Ssam/*
3759105197Ssam * compare my own address for IPv6.
3760105197Ssam * 1: ours
3761105197Ssam * 0: other
3762105197Ssam * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3763105197Ssam */
3764105197Ssam#include <netinet6/in6_var.h>
3765105197Ssam
3766105197Ssamstatic int
3767105197Ssamkey_ismyaddr6(sin6)
3768105197Ssam	struct sockaddr_in6 *sin6;
3769105197Ssam{
3770183550Szec	INIT_VNET_INET6(curvnet);
3771105197Ssam	struct in6_ifaddr *ia;
3772191663Sbms#if 0
3773105197Ssam	struct in6_multi *in6m;
3774191663Sbms#endif
3775105197Ssam
3776181803Sbz	for (ia = V_in6_ifaddr; ia; ia = ia->ia_next) {
3777105197Ssam		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3778105197Ssam		    (struct sockaddr *)&ia->ia_addr, 0) == 0)
3779105197Ssam			return 1;
3780105197Ssam
3781191663Sbms#if 0
3782105197Ssam		/*
3783105197Ssam		 * XXX Multicast
3784105197Ssam		 * XXX why do we care about multlicast here while we don't care
3785105197Ssam		 * about IPv4 multicast??
3786105197Ssam		 * XXX scope
3787105197Ssam		 */
3788105197Ssam		in6m = NULL;
3789105197Ssam		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3790105197Ssam		if (in6m)
3791105197Ssam			return 1;
3792191663Sbms#endif
3793105197Ssam	}
3794105197Ssam
3795105197Ssam	/* loopback, just for safety */
3796105197Ssam	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3797105197Ssam		return 1;
3798105197Ssam
3799105197Ssam	return 0;
3800105197Ssam}
3801105197Ssam#endif /*INET6*/
3802105197Ssam
3803105197Ssam/*
3804105197Ssam * compare two secasindex structure.
3805105197Ssam * flag can specify to compare 2 saidxes.
3806105197Ssam * compare two secasindex structure without both mode and reqid.
3807105197Ssam * don't compare port.
3808105197Ssam * IN:
3809105197Ssam *      saidx0: source, it can be in SAD.
3810105197Ssam *      saidx1: object.
3811105197Ssam * OUT:
3812105197Ssam *      1 : equal
3813105197Ssam *      0 : not equal
3814105197Ssam */
3815105197Ssamstatic int
3816105197Ssamkey_cmpsaidx(
3817105197Ssam	const struct secasindex *saidx0,
3818105197Ssam	const struct secasindex *saidx1,
3819105197Ssam	int flag)
3820105197Ssam{
3821105197Ssam	/* sanity */
3822105197Ssam	if (saidx0 == NULL && saidx1 == NULL)
3823105197Ssam		return 1;
3824105197Ssam
3825105197Ssam	if (saidx0 == NULL || saidx1 == NULL)
3826105197Ssam		return 0;
3827105197Ssam
3828105197Ssam	if (saidx0->proto != saidx1->proto)
3829105197Ssam		return 0;
3830105197Ssam
3831105197Ssam	if (flag == CMP_EXACTLY) {
3832105197Ssam		if (saidx0->mode != saidx1->mode)
3833105197Ssam			return 0;
3834105197Ssam		if (saidx0->reqid != saidx1->reqid)
3835105197Ssam			return 0;
3836105197Ssam		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3837105197Ssam		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3838105197Ssam			return 0;
3839105197Ssam	} else {
3840105197Ssam
3841105197Ssam		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3842105197Ssam		if (flag == CMP_MODE_REQID
3843105197Ssam		  ||flag == CMP_REQID) {
3844105197Ssam			/*
3845105197Ssam			 * If reqid of SPD is non-zero, unique SA is required.
3846105197Ssam			 * The result must be of same reqid in this case.
3847105197Ssam			 */
3848105197Ssam			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3849105197Ssam				return 0;
3850105197Ssam		}
3851105197Ssam
3852105197Ssam		if (flag == CMP_MODE_REQID) {
3853105197Ssam			if (saidx0->mode != IPSEC_MODE_ANY
3854105197Ssam			 && saidx0->mode != saidx1->mode)
3855105197Ssam				return 0;
3856105197Ssam		}
3857105197Ssam
3858105197Ssam		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
3859105197Ssam			return 0;
3860105197Ssam		}
3861105197Ssam		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
3862105197Ssam			return 0;
3863105197Ssam		}
3864105197Ssam	}
3865105197Ssam
3866105197Ssam	return 1;
3867105197Ssam}
3868105197Ssam
3869105197Ssam/*
3870105197Ssam * compare two secindex structure exactly.
3871105197Ssam * IN:
3872105197Ssam *	spidx0: source, it is often in SPD.
3873105197Ssam *	spidx1: object, it is often from PFKEY message.
3874105197Ssam * OUT:
3875105197Ssam *	1 : equal
3876105197Ssam *	0 : not equal
3877105197Ssam */
3878105197Ssamstatic int
3879105197Ssamkey_cmpspidx_exactly(
3880105197Ssam	struct secpolicyindex *spidx0,
3881105197Ssam	struct secpolicyindex *spidx1)
3882105197Ssam{
3883105197Ssam	/* sanity */
3884105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
3885105197Ssam		return 1;
3886105197Ssam
3887105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
3888105197Ssam		return 0;
3889105197Ssam
3890105197Ssam	if (spidx0->prefs != spidx1->prefs
3891105197Ssam	 || spidx0->prefd != spidx1->prefd
3892105197Ssam	 || spidx0->ul_proto != spidx1->ul_proto)
3893105197Ssam		return 0;
3894105197Ssam
3895105197Ssam	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3896105197Ssam	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3897105197Ssam}
3898105197Ssam
3899105197Ssam/*
3900105197Ssam * compare two secindex structure with mask.
3901105197Ssam * IN:
3902105197Ssam *	spidx0: source, it is often in SPD.
3903105197Ssam *	spidx1: object, it is often from IP header.
3904105197Ssam * OUT:
3905105197Ssam *	1 : equal
3906105197Ssam *	0 : not equal
3907105197Ssam */
3908105197Ssamstatic int
3909105197Ssamkey_cmpspidx_withmask(
3910105197Ssam	struct secpolicyindex *spidx0,
3911105197Ssam	struct secpolicyindex *spidx1)
3912105197Ssam{
3913105197Ssam	/* sanity */
3914105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
3915105197Ssam		return 1;
3916105197Ssam
3917105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
3918105197Ssam		return 0;
3919105197Ssam
3920105197Ssam	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
3921105197Ssam	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
3922105197Ssam	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
3923105197Ssam	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
3924105197Ssam		return 0;
3925105197Ssam
3926105197Ssam	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3927105197Ssam	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3928105197Ssam	 && spidx0->ul_proto != spidx1->ul_proto)
3929105197Ssam		return 0;
3930105197Ssam
3931105197Ssam	switch (spidx0->src.sa.sa_family) {
3932105197Ssam	case AF_INET:
3933105197Ssam		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
3934105197Ssam		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
3935105197Ssam			return 0;
3936105197Ssam		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
3937105197Ssam		    &spidx1->src.sin.sin_addr, spidx0->prefs))
3938105197Ssam			return 0;
3939105197Ssam		break;
3940105197Ssam	case AF_INET6:
3941105197Ssam		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
3942105197Ssam		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
3943105197Ssam			return 0;
3944105197Ssam		/*
3945105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
3946105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
3947105197Ssam		 */
3948105197Ssam		if (spidx0->src.sin6.sin6_scope_id &&
3949105197Ssam		    spidx1->src.sin6.sin6_scope_id &&
3950105197Ssam		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
3951105197Ssam			return 0;
3952105197Ssam		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
3953105197Ssam		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
3954105197Ssam			return 0;
3955105197Ssam		break;
3956105197Ssam	default:
3957105197Ssam		/* XXX */
3958105197Ssam		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
3959105197Ssam			return 0;
3960105197Ssam		break;
3961105197Ssam	}
3962105197Ssam
3963105197Ssam	switch (spidx0->dst.sa.sa_family) {
3964105197Ssam	case AF_INET:
3965105197Ssam		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
3966105197Ssam		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
3967105197Ssam			return 0;
3968105197Ssam		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
3969105197Ssam		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
3970105197Ssam			return 0;
3971105197Ssam		break;
3972105197Ssam	case AF_INET6:
3973105197Ssam		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
3974105197Ssam		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
3975105197Ssam			return 0;
3976105197Ssam		/*
3977105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
3978105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
3979105197Ssam		 */
3980130928Sbms		if (spidx0->dst.sin6.sin6_scope_id &&
3981130928Sbms		    spidx1->dst.sin6.sin6_scope_id &&
3982105197Ssam		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
3983105197Ssam			return 0;
3984105197Ssam		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
3985105197Ssam		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
3986105197Ssam			return 0;
3987105197Ssam		break;
3988105197Ssam	default:
3989105197Ssam		/* XXX */
3990105197Ssam		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
3991105197Ssam			return 0;
3992105197Ssam		break;
3993105197Ssam	}
3994105197Ssam
3995105197Ssam	/* XXX Do we check other field ?  e.g. flowinfo */
3996105197Ssam
3997105197Ssam	return 1;
3998105197Ssam}
3999105197Ssam
4000105197Ssam/* returns 0 on match */
4001105197Ssamstatic int
4002105197Ssamkey_sockaddrcmp(
4003105197Ssam	const struct sockaddr *sa1,
4004105197Ssam	const struct sockaddr *sa2,
4005105197Ssam	int port)
4006105197Ssam{
4007105197Ssam#ifdef satosin
4008105197Ssam#undef satosin
4009105197Ssam#endif
4010105197Ssam#define satosin(s) ((const struct sockaddr_in *)s)
4011105197Ssam#ifdef satosin6
4012105197Ssam#undef satosin6
4013105197Ssam#endif
4014105197Ssam#define satosin6(s) ((const struct sockaddr_in6 *)s)
4015105197Ssam	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4016105197Ssam		return 1;
4017105197Ssam
4018105197Ssam	switch (sa1->sa_family) {
4019105197Ssam	case AF_INET:
4020105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in))
4021105197Ssam			return 1;
4022105197Ssam		if (satosin(sa1)->sin_addr.s_addr !=
4023105197Ssam		    satosin(sa2)->sin_addr.s_addr) {
4024105197Ssam			return 1;
4025105197Ssam		}
4026105197Ssam		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4027105197Ssam			return 1;
4028105197Ssam		break;
4029105197Ssam	case AF_INET6:
4030105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4031105197Ssam			return 1;	/*EINVAL*/
4032105197Ssam		if (satosin6(sa1)->sin6_scope_id !=
4033105197Ssam		    satosin6(sa2)->sin6_scope_id) {
4034105197Ssam			return 1;
4035105197Ssam		}
4036105197Ssam		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4037105197Ssam		    &satosin6(sa2)->sin6_addr)) {
4038105197Ssam			return 1;
4039105197Ssam		}
4040105197Ssam		if (port &&
4041105197Ssam		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4042105197Ssam			return 1;
4043105197Ssam		}
4044170120Sbz		break;
4045105197Ssam	default:
4046105197Ssam		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4047105197Ssam			return 1;
4048105197Ssam		break;
4049105197Ssam	}
4050105197Ssam
4051105197Ssam	return 0;
4052105197Ssam#undef satosin
4053105197Ssam#undef satosin6
4054105197Ssam}
4055105197Ssam
4056105197Ssam/*
4057105197Ssam * compare two buffers with mask.
4058105197Ssam * IN:
4059105197Ssam *	addr1: source
4060105197Ssam *	addr2: object
4061105197Ssam *	bits:  Number of bits to compare
4062105197Ssam * OUT:
4063105197Ssam *	1 : equal
4064105197Ssam *	0 : not equal
4065105197Ssam */
4066105197Ssamstatic int
4067105197Ssamkey_bbcmp(const void *a1, const void *a2, u_int bits)
4068105197Ssam{
4069105197Ssam	const unsigned char *p1 = a1;
4070105197Ssam	const unsigned char *p2 = a2;
4071105197Ssam
4072105197Ssam	/* XXX: This could be considerably faster if we compare a word
4073105197Ssam	 * at a time, but it is complicated on LSB Endian machines */
4074105197Ssam
4075105197Ssam	/* Handle null pointers */
4076105197Ssam	if (p1 == NULL || p2 == NULL)
4077105197Ssam		return (p1 == p2);
4078105197Ssam
4079105197Ssam	while (bits >= 8) {
4080105197Ssam		if (*p1++ != *p2++)
4081105197Ssam			return 0;
4082105197Ssam		bits -= 8;
4083105197Ssam	}
4084105197Ssam
4085105197Ssam	if (bits > 0) {
4086105197Ssam		u_int8_t mask = ~((1<<(8-bits))-1);
4087105197Ssam		if ((*p1 & mask) != (*p2 & mask))
4088105197Ssam			return 0;
4089105197Ssam	}
4090105197Ssam	return 1;	/* Match! */
4091105197Ssam}
4092105197Ssam
4093119643Ssamstatic void
4094119643Ssamkey_flush_spd(time_t now)
4095105197Ssam{
4096183550Szec	INIT_VNET_IPSEC(curvnet);
4097120585Ssam	static u_int16_t sptree_scangen = 0;
4098120585Ssam	u_int16_t gen = sptree_scangen++;
4099120585Ssam	struct secpolicy *sp;
4100105197Ssam	u_int dir;
4101105197Ssam
4102105197Ssam	/* SPD */
4103105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4104120585Ssamrestart:
4105120585Ssam		SPTREE_LOCK();
4106181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
4107120585Ssam			if (sp->scangen == gen)		/* previously handled */
4108120585Ssam				continue;
4109120585Ssam			sp->scangen = gen;
4110192880Svanhu			if (sp->state == IPSEC_SPSTATE_DEAD &&
4111192880Svanhu			    sp->refcnt == 1) {
4112192880Svanhu				/*
4113192880Svanhu				 * Ensure that we only decrease refcnt once,
4114192880Svanhu				 * when we're the last consumer.
4115192880Svanhu				 * Directly call SP_DELREF/key_delsp instead
4116192880Svanhu				 * of KEY_FREESP to avoid unlocking/relocking
4117192880Svanhu				 * SPTREE_LOCK before key_delsp: may refcnt
4118192880Svanhu				 * be increased again during that time ?
4119192880Svanhu				 * NB: also clean entries created by
4120192880Svanhu				 * key_spdflush
4121192880Svanhu				 */
4122192880Svanhu				SP_DELREF(sp);
4123192880Svanhu				key_delsp(sp);
4124120585Ssam				SPTREE_UNLOCK();
4125120585Ssam				goto restart;
4126105197Ssam			}
4127105197Ssam			if (sp->lifetime == 0 && sp->validtime == 0)
4128105197Ssam				continue;
4129105197Ssam			if ((sp->lifetime && now - sp->created > sp->lifetime)
4130105197Ssam			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4131105197Ssam				sp->state = IPSEC_SPSTATE_DEAD;
4132120585Ssam				SPTREE_UNLOCK();
4133105197Ssam				key_spdexpire(sp);
4134120585Ssam				goto restart;
4135105197Ssam			}
4136105197Ssam		}
4137120585Ssam		SPTREE_UNLOCK();
4138105197Ssam	}
4139119643Ssam}
4140105197Ssam
4141119643Ssamstatic void
4142119643Ssamkey_flush_sad(time_t now)
4143119643Ssam{
4144183550Szec	INIT_VNET_IPSEC(curvnet);
4145105197Ssam	struct secashead *sah, *nextsah;
4146105197Ssam	struct secasvar *sav, *nextsav;
4147105197Ssam
4148119643Ssam	/* SAD */
4149120585Ssam	SAHTREE_LOCK();
4150181803Sbz	LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4151105197Ssam		/* if sah has been dead, then delete it and process next sah. */
4152105197Ssam		if (sah->state == SADB_SASTATE_DEAD) {
4153105197Ssam			key_delsah(sah);
4154105197Ssam			continue;
4155105197Ssam		}
4156105197Ssam
4157105197Ssam		/* if LARVAL entry doesn't become MATURE, delete it. */
4158120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4159190071Svanhu			/* Need to also check refcnt for a larval SA ??? */
4160181803Sbz			if (now - sav->created > V_key_larval_lifetime)
4161105197Ssam				KEY_FREESAV(&sav);
4162105197Ssam		}
4163105197Ssam
4164105197Ssam		/*
4165105197Ssam		 * check MATURE entry to start to send expire message
4166105197Ssam		 * whether or not.
4167105197Ssam		 */
4168120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4169105197Ssam			/* we don't need to check. */
4170105197Ssam			if (sav->lft_s == NULL)
4171105197Ssam				continue;
4172105197Ssam
4173105197Ssam			/* sanity check */
4174105197Ssam			if (sav->lft_c == NULL) {
4175120585Ssam				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4176120585Ssam					"time, why?\n", __func__));
4177105197Ssam				continue;
4178105197Ssam			}
4179105197Ssam
4180105197Ssam			/* check SOFT lifetime */
4181157123Sgnn			if (sav->lft_s->addtime != 0 &&
4182157123Sgnn			    now - sav->created > sav->lft_s->addtime) {
4183189406Svanhu				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4184190075Svanhu				/*
4185190323Svanhu				 * Actually, only send expire message if
4186190323Svanhu				 * SA has been used, as it was done before,
4187190323Svanhu				 * but should we always send such message,
4188190323Svanhu				 * and let IKE daemon decide if it should be
4189190323Svanhu				 * renegotiated or not ?
4190190323Svanhu				 * XXX expire message will actually NOT be
4191190323Svanhu				 * sent if SA is only used after soft
4192190323Svanhu				 * lifetime has been reached, see below
4193190323Svanhu				 * (DYING state)
4194105197Ssam				 */
4195189406Svanhu				if (sav->lft_c->usetime != 0)
4196105197Ssam					key_expire(sav);
4197105197Ssam			}
4198105197Ssam			/* check SOFT lifetime by bytes */
4199105197Ssam			/*
4200105197Ssam			 * XXX I don't know the way to delete this SA
4201105197Ssam			 * when new SA is installed.  Caution when it's
4202105197Ssam			 * installed too big lifetime by time.
4203105197Ssam			 */
4204157123Sgnn			else if (sav->lft_s->bytes != 0 &&
4205157123Sgnn			    sav->lft_s->bytes < sav->lft_c->bytes) {
4206105197Ssam
4207105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4208105197Ssam				/*
4209105197Ssam				 * XXX If we keep to send expire
4210105197Ssam				 * message in the status of
4211105197Ssam				 * DYING. Do remove below code.
4212105197Ssam				 */
4213105197Ssam				key_expire(sav);
4214105197Ssam			}
4215105197Ssam		}
4216105197Ssam
4217105197Ssam		/* check DYING entry to change status to DEAD. */
4218120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4219105197Ssam			/* we don't need to check. */
4220105197Ssam			if (sav->lft_h == NULL)
4221105197Ssam				continue;
4222105197Ssam
4223105197Ssam			/* sanity check */
4224105197Ssam			if (sav->lft_c == NULL) {
4225120585Ssam				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4226120585Ssam					"time, why?\n", __func__));
4227105197Ssam				continue;
4228105197Ssam			}
4229105197Ssam
4230157123Sgnn			if (sav->lft_h->addtime != 0 &&
4231157123Sgnn			    now - sav->created > sav->lft_h->addtime) {
4232105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4233105197Ssam				KEY_FREESAV(&sav);
4234105197Ssam			}
4235105197Ssam#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4236105197Ssam			else if (sav->lft_s != NULL
4237157123Sgnn			      && sav->lft_s->addtime != 0
4238157123Sgnn			      && now - sav->created > sav->lft_s->addtime) {
4239105197Ssam				/*
4240105197Ssam				 * XXX: should be checked to be
4241105197Ssam				 * installed the valid SA.
4242105197Ssam				 */
4243105197Ssam
4244105197Ssam				/*
4245105197Ssam				 * If there is no SA then sending
4246105197Ssam				 * expire message.
4247105197Ssam				 */
4248105197Ssam				key_expire(sav);
4249105197Ssam			}
4250105197Ssam#endif
4251105197Ssam			/* check HARD lifetime by bytes */
4252157123Sgnn			else if (sav->lft_h->bytes != 0 &&
4253157123Sgnn			    sav->lft_h->bytes < sav->lft_c->bytes) {
4254105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4255105197Ssam				KEY_FREESAV(&sav);
4256105197Ssam			}
4257105197Ssam		}
4258105197Ssam
4259105197Ssam		/* delete entry in DEAD */
4260120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4261105197Ssam			/* sanity check */
4262105197Ssam			if (sav->state != SADB_SASTATE_DEAD) {
4263120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4264120585Ssam					"(queue: %d SA: %d): kill it anyway\n",
4265120585Ssam					__func__,
4266105197Ssam					SADB_SASTATE_DEAD, sav->state));
4267105197Ssam			}
4268105197Ssam			/*
4269105197Ssam			 * do not call key_freesav() here.
4270105197Ssam			 * sav should already be freed, and sav->refcnt
4271105197Ssam			 * shows other references to sav
4272105197Ssam			 * (such as from SPD).
4273105197Ssam			 */
4274105197Ssam		}
4275105197Ssam	}
4276120585Ssam	SAHTREE_UNLOCK();
4277119643Ssam}
4278105197Ssam
4279119643Ssamstatic void
4280119643Ssamkey_flush_acq(time_t now)
4281119643Ssam{
4282183550Szec	INIT_VNET_IPSEC(curvnet);
4283105197Ssam	struct secacq *acq, *nextacq;
4284105197Ssam
4285119643Ssam	/* ACQ tree */
4286120585Ssam	ACQ_LOCK();
4287181803Sbz	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4288105197Ssam		nextacq = LIST_NEXT(acq, chain);
4289181803Sbz		if (now - acq->created > V_key_blockacq_lifetime
4290105197Ssam		 && __LIST_CHAINED(acq)) {
4291105197Ssam			LIST_REMOVE(acq, chain);
4292119643Ssam			free(acq, M_IPSEC_SAQ);
4293105197Ssam		}
4294105197Ssam	}
4295120585Ssam	ACQ_UNLOCK();
4296119643Ssam}
4297105197Ssam
4298119643Ssamstatic void
4299119643Ssamkey_flush_spacq(time_t now)
4300119643Ssam{
4301183550Szec	INIT_VNET_IPSEC(curvnet);
4302105197Ssam	struct secspacq *acq, *nextacq;
4303105197Ssam
4304119643Ssam	/* SP ACQ tree */
4305120585Ssam	SPACQ_LOCK();
4306181803Sbz	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4307105197Ssam		nextacq = LIST_NEXT(acq, chain);
4308181803Sbz		if (now - acq->created > V_key_blockacq_lifetime
4309105197Ssam		 && __LIST_CHAINED(acq)) {
4310105197Ssam			LIST_REMOVE(acq, chain);
4311119643Ssam			free(acq, M_IPSEC_SAQ);
4312105197Ssam		}
4313105197Ssam	}
4314120585Ssam	SPACQ_UNLOCK();
4315119643Ssam}
4316105197Ssam
4317119643Ssam/*
4318119643Ssam * time handler.
4319119643Ssam * scanning SPD and SAD to check status for each entries,
4320119643Ssam * and do to remove or to expire.
4321119643Ssam * XXX: year 2038 problem may remain.
4322119643Ssam */
4323119643Ssamvoid
4324119643Ssamkey_timehandler(void)
4325119643Ssam{
4326183550Szec	VNET_ITERATOR_DECL(vnet_iter);
4327119643Ssam	time_t now = time_second;
4328105197Ssam
4329185348Szec	VNET_LIST_RLOCK();
4330183550Szec	VNET_FOREACH(vnet_iter) {
4331183550Szec		CURVNET_SET(vnet_iter);
4332183550Szec		key_flush_spd(now);
4333183550Szec		key_flush_sad(now);
4334183550Szec		key_flush_acq(now);
4335183550Szec		key_flush_spacq(now);
4336183550Szec		CURVNET_RESTORE();
4337183550Szec	}
4338185348Szec	VNET_LIST_RUNLOCK();
4339119643Ssam
4340105197Ssam#ifndef IPSEC_DEBUG2
4341105197Ssam	/* do exchange to tick time !! */
4342105197Ssam	(void)timeout((void *)key_timehandler, (void *)0, hz);
4343105197Ssam#endif /* IPSEC_DEBUG2 */
4344105197Ssam}
4345105197Ssam
4346105197Ssamu_long
4347105197Ssamkey_random()
4348105197Ssam{
4349105197Ssam	u_long value;
4350105197Ssam
4351105197Ssam	key_randomfill(&value, sizeof(value));
4352105197Ssam	return value;
4353105197Ssam}
4354105197Ssam
4355105197Ssamvoid
4356105197Ssamkey_randomfill(p, l)
4357105197Ssam	void *p;
4358105197Ssam	size_t l;
4359105197Ssam{
4360105197Ssam	size_t n;
4361105197Ssam	u_long v;
4362105197Ssam	static int warn = 1;
4363105197Ssam
4364105197Ssam	n = 0;
4365105197Ssam	n = (size_t)read_random(p, (u_int)l);
4366105197Ssam	/* last resort */
4367105197Ssam	while (n < l) {
4368105197Ssam		v = random();
4369105197Ssam		bcopy(&v, (u_int8_t *)p + n,
4370105197Ssam		    l - n < sizeof(v) ? l - n : sizeof(v));
4371105197Ssam		n += sizeof(v);
4372105197Ssam
4373105197Ssam		if (warn) {
4374105197Ssam			printf("WARNING: pseudo-random number generator "
4375105197Ssam			    "used for IPsec processing\n");
4376105197Ssam			warn = 0;
4377105197Ssam		}
4378105197Ssam	}
4379105197Ssam}
4380105197Ssam
4381105197Ssam/*
4382105197Ssam * map SADB_SATYPE_* to IPPROTO_*.
4383105197Ssam * if satype == SADB_SATYPE then satype is mapped to ~0.
4384105197Ssam * OUT:
4385105197Ssam *	0: invalid satype.
4386105197Ssam */
4387105197Ssamstatic u_int16_t
4388189004Srdivackykey_satype2proto(u_int8_t satype)
4389105197Ssam{
4390105197Ssam	switch (satype) {
4391105197Ssam	case SADB_SATYPE_UNSPEC:
4392105197Ssam		return IPSEC_PROTO_ANY;
4393105197Ssam	case SADB_SATYPE_AH:
4394105197Ssam		return IPPROTO_AH;
4395105197Ssam	case SADB_SATYPE_ESP:
4396105197Ssam		return IPPROTO_ESP;
4397105197Ssam	case SADB_X_SATYPE_IPCOMP:
4398105197Ssam		return IPPROTO_IPCOMP;
4399125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
4400125680Sbms		return IPPROTO_TCP;
4401105197Ssam	default:
4402105197Ssam		return 0;
4403105197Ssam	}
4404105197Ssam	/* NOTREACHED */
4405105197Ssam}
4406105197Ssam
4407105197Ssam/*
4408105197Ssam * map IPPROTO_* to SADB_SATYPE_*
4409105197Ssam * OUT:
4410105197Ssam *	0: invalid protocol type.
4411105197Ssam */
4412105197Ssamstatic u_int8_t
4413189004Srdivackykey_proto2satype(u_int16_t proto)
4414105197Ssam{
4415105197Ssam	switch (proto) {
4416105197Ssam	case IPPROTO_AH:
4417105197Ssam		return SADB_SATYPE_AH;
4418105197Ssam	case IPPROTO_ESP:
4419105197Ssam		return SADB_SATYPE_ESP;
4420105197Ssam	case IPPROTO_IPCOMP:
4421105197Ssam		return SADB_X_SATYPE_IPCOMP;
4422125680Sbms	case IPPROTO_TCP:
4423125680Sbms		return SADB_X_SATYPE_TCPSIGNATURE;
4424105197Ssam	default:
4425105197Ssam		return 0;
4426105197Ssam	}
4427105197Ssam	/* NOTREACHED */
4428105197Ssam}
4429105197Ssam
4430105197Ssam/* %%% PF_KEY */
4431105197Ssam/*
4432105197Ssam * SADB_GETSPI processing is to receive
4433105197Ssam *	<base, (SA2), src address, dst address, (SPI range)>
4434105197Ssam * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4435105197Ssam * tree with the status of LARVAL, and send
4436105197Ssam *	<base, SA(*), address(SD)>
4437105197Ssam * to the IKMPd.
4438105197Ssam *
4439105197Ssam * IN:	mhp: pointer to the pointer to each header.
4440105197Ssam * OUT:	NULL if fail.
4441105197Ssam *	other if success, return pointer to the message to send.
4442105197Ssam */
4443105197Ssamstatic int
4444105197Ssamkey_getspi(so, m, mhp)
4445105197Ssam	struct socket *so;
4446105197Ssam	struct mbuf *m;
4447105197Ssam	const struct sadb_msghdr *mhp;
4448105197Ssam{
4449183550Szec	INIT_VNET_IPSEC(curvnet);
4450105197Ssam	struct sadb_address *src0, *dst0;
4451105197Ssam	struct secasindex saidx;
4452105197Ssam	struct secashead *newsah;
4453105197Ssam	struct secasvar *newsav;
4454105197Ssam	u_int8_t proto;
4455105197Ssam	u_int32_t spi;
4456105197Ssam	u_int8_t mode;
4457105197Ssam	u_int32_t reqid;
4458105197Ssam	int error;
4459105197Ssam
4460120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4461120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4462120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4463120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4464105197Ssam
4465105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4466105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4467120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4468120585Ssam			__func__));
4469105197Ssam		return key_senderror(so, m, EINVAL);
4470105197Ssam	}
4471105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4472105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4473120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4474120585Ssam			__func__));
4475105197Ssam		return key_senderror(so, m, EINVAL);
4476105197Ssam	}
4477105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4478105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4479105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4480105197Ssam	} else {
4481105197Ssam		mode = IPSEC_MODE_ANY;
4482105197Ssam		reqid = 0;
4483105197Ssam	}
4484105197Ssam
4485105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4486105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4487105197Ssam
4488105197Ssam	/* map satype to proto */
4489105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4490120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4491120585Ssam			__func__));
4492105197Ssam		return key_senderror(so, m, EINVAL);
4493105197Ssam	}
4494105197Ssam
4495105197Ssam	/* make sure if port number is zero. */
4496105197Ssam	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4497105197Ssam	case AF_INET:
4498105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4499105197Ssam		    sizeof(struct sockaddr_in))
4500105197Ssam			return key_senderror(so, m, EINVAL);
4501105197Ssam		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4502105197Ssam		break;
4503105197Ssam	case AF_INET6:
4504105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4505105197Ssam		    sizeof(struct sockaddr_in6))
4506105197Ssam			return key_senderror(so, m, EINVAL);
4507105197Ssam		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4508105197Ssam		break;
4509105197Ssam	default:
4510105197Ssam		; /*???*/
4511105197Ssam	}
4512105197Ssam	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4513105197Ssam	case AF_INET:
4514105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4515105197Ssam		    sizeof(struct sockaddr_in))
4516105197Ssam			return key_senderror(so, m, EINVAL);
4517105197Ssam		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4518105197Ssam		break;
4519105197Ssam	case AF_INET6:
4520105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4521105197Ssam		    sizeof(struct sockaddr_in6))
4522105197Ssam			return key_senderror(so, m, EINVAL);
4523105197Ssam		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4524105197Ssam		break;
4525105197Ssam	default:
4526105197Ssam		; /*???*/
4527105197Ssam	}
4528105197Ssam
4529105197Ssam	/* XXX boundary check against sa_len */
4530105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4531105197Ssam
4532105197Ssam	/* SPI allocation */
4533105197Ssam	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4534105197Ssam	                       &saidx);
4535105197Ssam	if (spi == 0)
4536105197Ssam		return key_senderror(so, m, EINVAL);
4537105197Ssam
4538105197Ssam	/* get a SA index */
4539105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4540105197Ssam		/* create a new SA index */
4541105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4542120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4543105197Ssam			return key_senderror(so, m, ENOBUFS);
4544105197Ssam		}
4545105197Ssam	}
4546105197Ssam
4547105197Ssam	/* get a new SA */
4548105197Ssam	/* XXX rewrite */
4549105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4550105197Ssam	if (newsav == NULL) {
4551105197Ssam		/* XXX don't free new SA index allocated in above. */
4552105197Ssam		return key_senderror(so, m, error);
4553105197Ssam	}
4554105197Ssam
4555105197Ssam	/* set spi */
4556105197Ssam	newsav->spi = htonl(spi);
4557105197Ssam
4558105197Ssam	/* delete the entry in acqtree */
4559105197Ssam	if (mhp->msg->sadb_msg_seq != 0) {
4560105197Ssam		struct secacq *acq;
4561105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4562105197Ssam			/* reset counter in order to deletion by timehandler. */
4563105197Ssam			acq->created = time_second;
4564105197Ssam			acq->count = 0;
4565105197Ssam		}
4566105197Ssam    	}
4567105197Ssam
4568105197Ssam    {
4569105197Ssam	struct mbuf *n, *nn;
4570105197Ssam	struct sadb_sa *m_sa;
4571105197Ssam	struct sadb_msg *newmsg;
4572105197Ssam	int off, len;
4573105197Ssam
4574105197Ssam	/* create new sadb_msg to reply. */
4575105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4576105197Ssam	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4577105197Ssam
4578111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
4579105197Ssam	if (len > MHLEN) {
4580111119Simp		MCLGET(n, M_DONTWAIT);
4581105197Ssam		if ((n->m_flags & M_EXT) == 0) {
4582105197Ssam			m_freem(n);
4583105197Ssam			n = NULL;
4584105197Ssam		}
4585105197Ssam	}
4586105197Ssam	if (!n)
4587105197Ssam		return key_senderror(so, m, ENOBUFS);
4588105197Ssam
4589105197Ssam	n->m_len = len;
4590105197Ssam	n->m_next = NULL;
4591105197Ssam	off = 0;
4592105197Ssam
4593105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4594105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4595105197Ssam
4596105197Ssam	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4597105197Ssam	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4598105197Ssam	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4599105197Ssam	m_sa->sadb_sa_spi = htonl(spi);
4600105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4601105197Ssam
4602120585Ssam	IPSEC_ASSERT(off == len,
4603120585Ssam		("length inconsistency (off %u len %u)", off, len));
4604105197Ssam
4605105197Ssam	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4606105197Ssam	    SADB_EXT_ADDRESS_DST);
4607105197Ssam	if (!n->m_next) {
4608105197Ssam		m_freem(n);
4609105197Ssam		return key_senderror(so, m, ENOBUFS);
4610105197Ssam	}
4611105197Ssam
4612105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
4613105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
4614105197Ssam		if (n == NULL)
4615105197Ssam			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4616105197Ssam	}
4617105197Ssam
4618105197Ssam	n->m_pkthdr.len = 0;
4619105197Ssam	for (nn = n; nn; nn = nn->m_next)
4620105197Ssam		n->m_pkthdr.len += nn->m_len;
4621105197Ssam
4622105197Ssam	newmsg = mtod(n, struct sadb_msg *);
4623105197Ssam	newmsg->sadb_msg_seq = newsav->seq;
4624105197Ssam	newmsg->sadb_msg_errno = 0;
4625105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4626105197Ssam
4627105197Ssam	m_freem(m);
4628105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4629105197Ssam    }
4630105197Ssam}
4631105197Ssam
4632105197Ssam/*
4633105197Ssam * allocating new SPI
4634105197Ssam * called by key_getspi().
4635105197Ssam * OUT:
4636105197Ssam *	0:	failure.
4637105197Ssam *	others: success.
4638105197Ssam */
4639105197Ssamstatic u_int32_t
4640105197Ssamkey_do_getnewspi(spirange, saidx)
4641105197Ssam	struct sadb_spirange *spirange;
4642105197Ssam	struct secasindex *saidx;
4643105197Ssam{
4644183550Szec	INIT_VNET_IPSEC(curvnet);
4645105197Ssam	u_int32_t newspi;
4646105197Ssam	u_int32_t min, max;
4647181803Sbz	int count = V_key_spi_trycnt;
4648105197Ssam
4649105197Ssam	/* set spi range to allocate */
4650105197Ssam	if (spirange != NULL) {
4651105197Ssam		min = spirange->sadb_spirange_min;
4652105197Ssam		max = spirange->sadb_spirange_max;
4653105197Ssam	} else {
4654181803Sbz		min = V_key_spi_minval;
4655181803Sbz		max = V_key_spi_maxval;
4656105197Ssam	}
4657105197Ssam	/* IPCOMP needs 2-byte SPI */
4658105197Ssam	if (saidx->proto == IPPROTO_IPCOMP) {
4659105197Ssam		u_int32_t t;
4660105197Ssam		if (min >= 0x10000)
4661105197Ssam			min = 0xffff;
4662105197Ssam		if (max >= 0x10000)
4663105197Ssam			max = 0xffff;
4664105197Ssam		if (min > max) {
4665105197Ssam			t = min; min = max; max = t;
4666105197Ssam		}
4667105197Ssam	}
4668105197Ssam
4669105197Ssam	if (min == max) {
4670105197Ssam		if (key_checkspidup(saidx, min) != NULL) {
4671120585Ssam			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4672120585Ssam				__func__, min));
4673105197Ssam			return 0;
4674105197Ssam		}
4675105197Ssam
4676105197Ssam		count--; /* taking one cost. */
4677105197Ssam		newspi = min;
4678105197Ssam
4679105197Ssam	} else {
4680105197Ssam
4681105197Ssam		/* init SPI */
4682105197Ssam		newspi = 0;
4683105197Ssam
4684105197Ssam		/* when requesting to allocate spi ranged */
4685105197Ssam		while (count--) {
4686105197Ssam			/* generate pseudo-random SPI value ranged. */
4687105197Ssam			newspi = min + (key_random() % (max - min + 1));
4688105197Ssam
4689105197Ssam			if (key_checkspidup(saidx, newspi) == NULL)
4690105197Ssam				break;
4691105197Ssam		}
4692105197Ssam
4693105197Ssam		if (count == 0 || newspi == 0) {
4694120585Ssam			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4695120585Ssam				__func__));
4696105197Ssam			return 0;
4697105197Ssam		}
4698105197Ssam	}
4699105197Ssam
4700105197Ssam	/* statistics */
4701105197Ssam	keystat.getspi_count =
4702181803Sbz		(keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4703105197Ssam
4704105197Ssam	return newspi;
4705105197Ssam}
4706105197Ssam
4707105197Ssam/*
4708105197Ssam * SADB_UPDATE processing
4709105197Ssam * receive
4710105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4711105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4712105197Ssam * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4713105197Ssam * and send
4714105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4715105197Ssam *       (identity(SD),) (sensitivity)>
4716105197Ssam * to the ikmpd.
4717105197Ssam *
4718105197Ssam * m will always be freed.
4719105197Ssam */
4720105197Ssamstatic int
4721105197Ssamkey_update(so, m, mhp)
4722105197Ssam	struct socket *so;
4723105197Ssam	struct mbuf *m;
4724105197Ssam	const struct sadb_msghdr *mhp;
4725105197Ssam{
4726183550Szec	INIT_VNET_IPSEC(curvnet);
4727105197Ssam	struct sadb_sa *sa0;
4728105197Ssam	struct sadb_address *src0, *dst0;
4729105197Ssam	struct secasindex saidx;
4730105197Ssam	struct secashead *sah;
4731105197Ssam	struct secasvar *sav;
4732105197Ssam	u_int16_t proto;
4733105197Ssam	u_int8_t mode;
4734105197Ssam	u_int32_t reqid;
4735105197Ssam	int error;
4736105197Ssam
4737120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4738120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4739120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4740120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4741105197Ssam
4742105197Ssam	/* map satype to proto */
4743105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4744120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4745120585Ssam			__func__));
4746105197Ssam		return key_senderror(so, m, EINVAL);
4747105197Ssam	}
4748105197Ssam
4749105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
4750105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4751105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4752105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4753105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4754105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4755105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4756105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4757105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4758105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4759105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4760120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4761120585Ssam			__func__));
4762105197Ssam		return key_senderror(so, m, EINVAL);
4763105197Ssam	}
4764105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4765105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4766105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4767120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4768120585Ssam			__func__));
4769105197Ssam		return key_senderror(so, m, EINVAL);
4770105197Ssam	}
4771105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4772105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4773105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4774105197Ssam	} else {
4775105197Ssam		mode = IPSEC_MODE_ANY;
4776105197Ssam		reqid = 0;
4777105197Ssam	}
4778105197Ssam	/* XXX boundary checking for other extensions */
4779105197Ssam
4780105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4781105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4782105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4783105197Ssam
4784105197Ssam	/* XXX boundary check against sa_len */
4785105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4786105197Ssam
4787105197Ssam	/* get a SA header */
4788105197Ssam	if ((sah = key_getsah(&saidx)) == NULL) {
4789120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
4790105197Ssam		return key_senderror(so, m, ENOENT);
4791105197Ssam	}
4792105197Ssam
4793105197Ssam	/* set spidx if there */
4794105197Ssam	/* XXX rewrite */
4795105197Ssam	error = key_setident(sah, m, mhp);
4796105197Ssam	if (error)
4797105197Ssam		return key_senderror(so, m, error);
4798105197Ssam
4799105197Ssam	/* find a SA with sequence number. */
4800105197Ssam#ifdef IPSEC_DOSEQCHECK
4801105197Ssam	if (mhp->msg->sadb_msg_seq != 0
4802105197Ssam	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4803120585Ssam		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
4804120585Ssam			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
4805105197Ssam		return key_senderror(so, m, ENOENT);
4806105197Ssam	}
4807105197Ssam#else
4808120585Ssam	SAHTREE_LOCK();
4809120585Ssam	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4810120585Ssam	SAHTREE_UNLOCK();
4811120585Ssam	if (sav == NULL) {
4812120585Ssam		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
4813120585Ssam			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4814105197Ssam		return key_senderror(so, m, EINVAL);
4815105197Ssam	}
4816105197Ssam#endif
4817105197Ssam
4818105197Ssam	/* validity check */
4819105197Ssam	if (sav->sah->saidx.proto != proto) {
4820120585Ssam		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
4821120585Ssam			"(DB=%u param=%u)\n", __func__,
4822120585Ssam			sav->sah->saidx.proto, proto));
4823105197Ssam		return key_senderror(so, m, EINVAL);
4824105197Ssam	}
4825105197Ssam#ifdef IPSEC_DOSEQCHECK
4826105197Ssam	if (sav->spi != sa0->sadb_sa_spi) {
4827120585Ssam		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
4828120585Ssam		    __func__,
4829105197Ssam		    (u_int32_t)ntohl(sav->spi),
4830105197Ssam		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4831105197Ssam		return key_senderror(so, m, EINVAL);
4832105197Ssam	}
4833105197Ssam#endif
4834105197Ssam	if (sav->pid != mhp->msg->sadb_msg_pid) {
4835120585Ssam		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
4836120585Ssam		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
4837105197Ssam		return key_senderror(so, m, EINVAL);
4838105197Ssam	}
4839105197Ssam
4840105197Ssam	/* copy sav values */
4841105197Ssam	error = key_setsaval(sav, m, mhp);
4842105197Ssam	if (error) {
4843105197Ssam		KEY_FREESAV(&sav);
4844105197Ssam		return key_senderror(so, m, error);
4845105197Ssam	}
4846105197Ssam
4847105197Ssam	/* check SA values to be mature. */
4848105197Ssam	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4849105197Ssam		KEY_FREESAV(&sav);
4850105197Ssam		return key_senderror(so, m, 0);
4851105197Ssam	}
4852105197Ssam
4853105197Ssam    {
4854105197Ssam	struct mbuf *n;
4855105197Ssam
4856105197Ssam	/* set msg buf from mhp */
4857105197Ssam	n = key_getmsgbuf_x1(m, mhp);
4858105197Ssam	if (n == NULL) {
4859120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4860105197Ssam		return key_senderror(so, m, ENOBUFS);
4861105197Ssam	}
4862105197Ssam
4863105197Ssam	m_freem(m);
4864105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4865105197Ssam    }
4866105197Ssam}
4867105197Ssam
4868105197Ssam/*
4869105197Ssam * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4870105197Ssam * only called by key_update().
4871105197Ssam * OUT:
4872105197Ssam *	NULL	: not found
4873105197Ssam *	others	: found, pointer to a SA.
4874105197Ssam */
4875105197Ssam#ifdef IPSEC_DOSEQCHECK
4876105197Ssamstatic struct secasvar *
4877105197Ssamkey_getsavbyseq(sah, seq)
4878105197Ssam	struct secashead *sah;
4879105197Ssam	u_int32_t seq;
4880105197Ssam{
4881105197Ssam	struct secasvar *sav;
4882105197Ssam	u_int state;
4883105197Ssam
4884105197Ssam	state = SADB_SASTATE_LARVAL;
4885105197Ssam
4886105197Ssam	/* search SAD with sequence number ? */
4887105197Ssam	LIST_FOREACH(sav, &sah->savtree[state], chain) {
4888105197Ssam
4889120585Ssam		KEY_CHKSASTATE(state, sav->state, __func__);
4890105197Ssam
4891105197Ssam		if (sav->seq == seq) {
4892158767Spjd			sa_addref(sav);
4893105197Ssam			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4894120585Ssam				printf("DP %s cause refcnt++:%d SA:%p\n",
4895120585Ssam					__func__, sav->refcnt, sav));
4896105197Ssam			return sav;
4897105197Ssam		}
4898105197Ssam	}
4899105197Ssam
4900105197Ssam	return NULL;
4901105197Ssam}
4902105197Ssam#endif
4903105197Ssam
4904105197Ssam/*
4905105197Ssam * SADB_ADD processing
4906108533Sschweikh * add an entry to SA database, when received
4907105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4908105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4909105197Ssam * from the ikmpd,
4910105197Ssam * and send
4911105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4912105197Ssam *       (identity(SD),) (sensitivity)>
4913105197Ssam * to the ikmpd.
4914105197Ssam *
4915105197Ssam * IGNORE identity and sensitivity messages.
4916105197Ssam *
4917105197Ssam * m will always be freed.
4918105197Ssam */
4919105197Ssamstatic int
4920105197Ssamkey_add(so, m, mhp)
4921105197Ssam	struct socket *so;
4922105197Ssam	struct mbuf *m;
4923105197Ssam	const struct sadb_msghdr *mhp;
4924105197Ssam{
4925183550Szec	INIT_VNET_IPSEC(curvnet);
4926105197Ssam	struct sadb_sa *sa0;
4927105197Ssam	struct sadb_address *src0, *dst0;
4928105197Ssam	struct secasindex saidx;
4929105197Ssam	struct secashead *newsah;
4930105197Ssam	struct secasvar *newsav;
4931105197Ssam	u_int16_t proto;
4932105197Ssam	u_int8_t mode;
4933105197Ssam	u_int32_t reqid;
4934105197Ssam	int error;
4935105197Ssam
4936120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4937120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4938120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4939120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4940105197Ssam
4941105197Ssam	/* map satype to proto */
4942105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4943120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4944120585Ssam			__func__));
4945105197Ssam		return key_senderror(so, m, EINVAL);
4946105197Ssam	}
4947105197Ssam
4948105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
4949105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4950105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4951105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4952105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4953105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4954105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4955105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4956105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4957105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4958105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4959120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4960120585Ssam			__func__));
4961105197Ssam		return key_senderror(so, m, EINVAL);
4962105197Ssam	}
4963105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4964105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4965105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4966105197Ssam		/* XXX need more */
4967120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4968120585Ssam			__func__));
4969105197Ssam		return key_senderror(so, m, EINVAL);
4970105197Ssam	}
4971105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4972105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4973105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4974105197Ssam	} else {
4975105197Ssam		mode = IPSEC_MODE_ANY;
4976105197Ssam		reqid = 0;
4977105197Ssam	}
4978105197Ssam
4979105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4980105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4981105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4982105197Ssam
4983105197Ssam	/* XXX boundary check against sa_len */
4984105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4985105197Ssam
4986105197Ssam	/* get a SA header */
4987105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4988105197Ssam		/* create a new SA header */
4989105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4990120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4991105197Ssam			return key_senderror(so, m, ENOBUFS);
4992105197Ssam		}
4993105197Ssam	}
4994105197Ssam
4995105197Ssam	/* set spidx if there */
4996105197Ssam	/* XXX rewrite */
4997105197Ssam	error = key_setident(newsah, m, mhp);
4998105197Ssam	if (error) {
4999105197Ssam		return key_senderror(so, m, error);
5000105197Ssam	}
5001105197Ssam
5002105197Ssam	/* create new SA entry. */
5003105197Ssam	/* We can create new SA only if SPI is differenct. */
5004120585Ssam	SAHTREE_LOCK();
5005120585Ssam	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5006120585Ssam	SAHTREE_UNLOCK();
5007120585Ssam	if (newsav != NULL) {
5008120585Ssam		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5009105197Ssam		return key_senderror(so, m, EEXIST);
5010105197Ssam	}
5011105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5012105197Ssam	if (newsav == NULL) {
5013105197Ssam		return key_senderror(so, m, error);
5014105197Ssam	}
5015105197Ssam
5016105197Ssam	/* check SA values to be mature. */
5017105197Ssam	if ((error = key_mature(newsav)) != 0) {
5018105197Ssam		KEY_FREESAV(&newsav);
5019105197Ssam		return key_senderror(so, m, error);
5020105197Ssam	}
5021105197Ssam
5022105197Ssam	/*
5023105197Ssam	 * don't call key_freesav() here, as we would like to keep the SA
5024105197Ssam	 * in the database on success.
5025105197Ssam	 */
5026105197Ssam
5027105197Ssam    {
5028105197Ssam	struct mbuf *n;
5029105197Ssam
5030105197Ssam	/* set msg buf from mhp */
5031105197Ssam	n = key_getmsgbuf_x1(m, mhp);
5032105197Ssam	if (n == NULL) {
5033120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5034105197Ssam		return key_senderror(so, m, ENOBUFS);
5035105197Ssam	}
5036105197Ssam
5037105197Ssam	m_freem(m);
5038105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5039105197Ssam    }
5040105197Ssam}
5041105197Ssam
5042105197Ssam/* m is retained */
5043105197Ssamstatic int
5044105197Ssamkey_setident(sah, m, mhp)
5045105197Ssam	struct secashead *sah;
5046105197Ssam	struct mbuf *m;
5047105197Ssam	const struct sadb_msghdr *mhp;
5048105197Ssam{
5049183550Szec	INIT_VNET_IPSEC(curvnet);
5050105197Ssam	const struct sadb_ident *idsrc, *iddst;
5051105197Ssam	int idsrclen, iddstlen;
5052105197Ssam
5053120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5054120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5055120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5056120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5057105197Ssam
5058105197Ssam	/* don't make buffer if not there */
5059105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5060105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5061105197Ssam		sah->idents = NULL;
5062105197Ssam		sah->identd = NULL;
5063105197Ssam		return 0;
5064105197Ssam	}
5065105197Ssam
5066105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5067105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5068120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5069105197Ssam		return EINVAL;
5070105197Ssam	}
5071105197Ssam
5072105197Ssam	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5073105197Ssam	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5074105197Ssam	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5075105197Ssam	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5076105197Ssam
5077105197Ssam	/* validity check */
5078105197Ssam	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5079120585Ssam		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5080105197Ssam		return EINVAL;
5081105197Ssam	}
5082105197Ssam
5083105197Ssam	switch (idsrc->sadb_ident_type) {
5084105197Ssam	case SADB_IDENTTYPE_PREFIX:
5085105197Ssam	case SADB_IDENTTYPE_FQDN:
5086105197Ssam	case SADB_IDENTTYPE_USERFQDN:
5087105197Ssam	default:
5088105197Ssam		/* XXX do nothing */
5089105197Ssam		sah->idents = NULL;
5090105197Ssam		sah->identd = NULL;
5091105197Ssam	 	return 0;
5092105197Ssam	}
5093105197Ssam
5094105197Ssam	/* make structure */
5095157123Sgnn	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5096105197Ssam	if (sah->idents == NULL) {
5097120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5098105197Ssam		return ENOBUFS;
5099105197Ssam	}
5100157123Sgnn	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5101105197Ssam	if (sah->identd == NULL) {
5102119643Ssam		free(sah->idents, M_IPSEC_MISC);
5103105197Ssam		sah->idents = NULL;
5104120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5105105197Ssam		return ENOBUFS;
5106105197Ssam	}
5107157123Sgnn	sah->idents->type = idsrc->sadb_ident_type;
5108157123Sgnn	sah->idents->id = idsrc->sadb_ident_id;
5109105197Ssam
5110157123Sgnn	sah->identd->type = iddst->sadb_ident_type;
5111157123Sgnn	sah->identd->id = iddst->sadb_ident_id;
5112157123Sgnn
5113105197Ssam	return 0;
5114105197Ssam}
5115105197Ssam
5116105197Ssam/*
5117105197Ssam * m will not be freed on return.
5118105197Ssam * it is caller's responsibility to free the result.
5119105197Ssam */
5120105197Ssamstatic struct mbuf *
5121105197Ssamkey_getmsgbuf_x1(m, mhp)
5122105197Ssam	struct mbuf *m;
5123105197Ssam	const struct sadb_msghdr *mhp;
5124105197Ssam{
5125105197Ssam	struct mbuf *n;
5126105197Ssam
5127120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5128120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5129120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5130105197Ssam
5131105197Ssam	/* create new sadb_msg to reply. */
5132105197Ssam	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5133105197Ssam	    SADB_EXT_SA, SADB_X_EXT_SA2,
5134105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5135105197Ssam	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5136105197Ssam	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5137105197Ssam	if (!n)
5138105197Ssam		return NULL;
5139105197Ssam
5140105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5141105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5142105197Ssam		if (n == NULL)
5143105197Ssam			return NULL;
5144105197Ssam	}
5145105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5146105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_len =
5147105197Ssam	    PFKEY_UNIT64(n->m_pkthdr.len);
5148105197Ssam
5149105197Ssam	return n;
5150105197Ssam}
5151105197Ssam
5152105197Ssamstatic int key_delete_all __P((struct socket *, struct mbuf *,
5153105197Ssam	const struct sadb_msghdr *, u_int16_t));
5154105197Ssam
5155105197Ssam/*
5156105197Ssam * SADB_DELETE processing
5157105197Ssam * receive
5158105197Ssam *   <base, SA(*), address(SD)>
5159105197Ssam * from the ikmpd, and set SADB_SASTATE_DEAD,
5160105197Ssam * and send,
5161105197Ssam *   <base, SA(*), address(SD)>
5162105197Ssam * to the ikmpd.
5163105197Ssam *
5164105197Ssam * m will always be freed.
5165105197Ssam */
5166105197Ssamstatic int
5167105197Ssamkey_delete(so, m, mhp)
5168105197Ssam	struct socket *so;
5169105197Ssam	struct mbuf *m;
5170105197Ssam	const struct sadb_msghdr *mhp;
5171105197Ssam{
5172183550Szec	INIT_VNET_IPSEC(curvnet);
5173105197Ssam	struct sadb_sa *sa0;
5174105197Ssam	struct sadb_address *src0, *dst0;
5175105197Ssam	struct secasindex saidx;
5176105197Ssam	struct secashead *sah;
5177105197Ssam	struct secasvar *sav = NULL;
5178105197Ssam	u_int16_t proto;
5179105197Ssam
5180120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5181120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5182120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5183120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5184105197Ssam
5185105197Ssam	/* map satype to proto */
5186105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5187120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5188120585Ssam			__func__));
5189105197Ssam		return key_senderror(so, m, EINVAL);
5190105197Ssam	}
5191105197Ssam
5192105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5193105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5194120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5195120585Ssam			__func__));
5196105197Ssam		return key_senderror(so, m, EINVAL);
5197105197Ssam	}
5198105197Ssam
5199105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5200105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5201120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5202120585Ssam			__func__));
5203105197Ssam		return key_senderror(so, m, EINVAL);
5204105197Ssam	}
5205105197Ssam
5206105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL) {
5207105197Ssam		/*
5208105197Ssam		 * Caller wants us to delete all non-LARVAL SAs
5209105197Ssam		 * that match the src/dst.  This is used during
5210105197Ssam		 * IKE INITIAL-CONTACT.
5211105197Ssam		 */
5212120585Ssam		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5213105197Ssam		return key_delete_all(so, m, mhp, proto);
5214105197Ssam	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5215120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5216120585Ssam			__func__));
5217105197Ssam		return key_senderror(so, m, EINVAL);
5218105197Ssam	}
5219105197Ssam
5220105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5221105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5222105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5223105197Ssam
5224105197Ssam	/* XXX boundary check against sa_len */
5225105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5226105197Ssam
5227105197Ssam	/* get a SA header */
5228120585Ssam	SAHTREE_LOCK();
5229181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5230105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5231105197Ssam			continue;
5232105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5233105197Ssam			continue;
5234105197Ssam
5235105197Ssam		/* get a SA with SPI. */
5236105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5237105197Ssam		if (sav)
5238105197Ssam			break;
5239105197Ssam	}
5240105197Ssam	if (sah == NULL) {
5241120585Ssam		SAHTREE_UNLOCK();
5242120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5243105197Ssam		return key_senderror(so, m, ENOENT);
5244105197Ssam	}
5245105197Ssam
5246105197Ssam	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5247120585Ssam	SAHTREE_UNLOCK();
5248105197Ssam	KEY_FREESAV(&sav);
5249105197Ssam
5250105197Ssam    {
5251105197Ssam	struct mbuf *n;
5252105197Ssam	struct sadb_msg *newmsg;
5253105197Ssam
5254105197Ssam	/* create new sadb_msg to reply. */
5255105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5256105197Ssam	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5257105197Ssam	if (!n)
5258105197Ssam		return key_senderror(so, m, ENOBUFS);
5259105197Ssam
5260105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5261105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5262105197Ssam		if (n == NULL)
5263105197Ssam			return key_senderror(so, m, ENOBUFS);
5264105197Ssam	}
5265105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5266105197Ssam	newmsg->sadb_msg_errno = 0;
5267105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5268105197Ssam
5269105197Ssam	m_freem(m);
5270105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5271105197Ssam    }
5272105197Ssam}
5273105197Ssam
5274105197Ssam/*
5275105197Ssam * delete all SAs for src/dst.  Called from key_delete().
5276105197Ssam */
5277105197Ssamstatic int
5278189004Srdivackykey_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5279189004Srdivacky    u_int16_t proto)
5280105197Ssam{
5281183550Szec	INIT_VNET_IPSEC(curvnet);
5282105197Ssam	struct sadb_address *src0, *dst0;
5283105197Ssam	struct secasindex saidx;
5284105197Ssam	struct secashead *sah;
5285105197Ssam	struct secasvar *sav, *nextsav;
5286105197Ssam	u_int stateidx, state;
5287105197Ssam
5288105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5289105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5290105197Ssam
5291105197Ssam	/* XXX boundary check against sa_len */
5292105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5293105197Ssam
5294120585Ssam	SAHTREE_LOCK();
5295181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5296105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5297105197Ssam			continue;
5298105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5299105197Ssam			continue;
5300105197Ssam
5301105197Ssam		/* Delete all non-LARVAL SAs. */
5302105197Ssam		for (stateidx = 0;
5303185348Szec		     stateidx < _ARRAYLEN(saorder_state_alive);
5304105197Ssam		     stateidx++) {
5305185348Szec			state = saorder_state_alive[stateidx];
5306105197Ssam			if (state == SADB_SASTATE_LARVAL)
5307105197Ssam				continue;
5308105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
5309105197Ssam			     sav != NULL; sav = nextsav) {
5310105197Ssam				nextsav = LIST_NEXT(sav, chain);
5311105197Ssam				/* sanity check */
5312105197Ssam				if (sav->state != state) {
5313120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
5314120585Ssam						"sav->state (queue %d SA %d)\n",
5315120585Ssam						__func__, state, sav->state));
5316105197Ssam					continue;
5317105197Ssam				}
5318105197Ssam
5319105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5320105197Ssam				KEY_FREESAV(&sav);
5321105197Ssam			}
5322105197Ssam		}
5323105197Ssam	}
5324120585Ssam	SAHTREE_UNLOCK();
5325105197Ssam    {
5326105197Ssam	struct mbuf *n;
5327105197Ssam	struct sadb_msg *newmsg;
5328105197Ssam
5329105197Ssam	/* create new sadb_msg to reply. */
5330105197Ssam	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5331105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5332105197Ssam	if (!n)
5333105197Ssam		return key_senderror(so, m, ENOBUFS);
5334105197Ssam
5335105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5336105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5337105197Ssam		if (n == NULL)
5338105197Ssam			return key_senderror(so, m, ENOBUFS);
5339105197Ssam	}
5340105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5341105197Ssam	newmsg->sadb_msg_errno = 0;
5342105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5343105197Ssam
5344105197Ssam	m_freem(m);
5345105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5346105197Ssam    }
5347105197Ssam}
5348105197Ssam
5349105197Ssam/*
5350105197Ssam * SADB_GET processing
5351105197Ssam * receive
5352105197Ssam *   <base, SA(*), address(SD)>
5353105197Ssam * from the ikmpd, and get a SP and a SA to respond,
5354105197Ssam * and send,
5355105197Ssam *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5356105197Ssam *       (identity(SD),) (sensitivity)>
5357105197Ssam * to the ikmpd.
5358105197Ssam *
5359105197Ssam * m will always be freed.
5360105197Ssam */
5361105197Ssamstatic int
5362105197Ssamkey_get(so, m, mhp)
5363105197Ssam	struct socket *so;
5364105197Ssam	struct mbuf *m;
5365105197Ssam	const struct sadb_msghdr *mhp;
5366105197Ssam{
5367183550Szec	INIT_VNET_IPSEC(curvnet);
5368105197Ssam	struct sadb_sa *sa0;
5369105197Ssam	struct sadb_address *src0, *dst0;
5370105197Ssam	struct secasindex saidx;
5371105197Ssam	struct secashead *sah;
5372105197Ssam	struct secasvar *sav = NULL;
5373105197Ssam	u_int16_t proto;
5374105197Ssam
5375120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5376120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5377120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5378120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5379105197Ssam
5380105197Ssam	/* map satype to proto */
5381105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5382120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5383120585Ssam			__func__));
5384105197Ssam		return key_senderror(so, m, EINVAL);
5385105197Ssam	}
5386105197Ssam
5387105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5388105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5389105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5390120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5391120585Ssam			__func__));
5392105197Ssam		return key_senderror(so, m, EINVAL);
5393105197Ssam	}
5394105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5395105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5396105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5397120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5398120585Ssam			__func__));
5399105197Ssam		return key_senderror(so, m, EINVAL);
5400105197Ssam	}
5401105197Ssam
5402105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5403105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5404105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5405105197Ssam
5406105197Ssam	/* XXX boundary check against sa_len */
5407105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5408105197Ssam
5409105197Ssam	/* get a SA header */
5410120585Ssam	SAHTREE_LOCK();
5411181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5412105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5413105197Ssam			continue;
5414105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5415105197Ssam			continue;
5416105197Ssam
5417105197Ssam		/* get a SA with SPI. */
5418105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5419105197Ssam		if (sav)
5420105197Ssam			break;
5421105197Ssam	}
5422120585Ssam	SAHTREE_UNLOCK();
5423105197Ssam	if (sah == NULL) {
5424120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5425105197Ssam		return key_senderror(so, m, ENOENT);
5426105197Ssam	}
5427105197Ssam
5428105197Ssam    {
5429105197Ssam	struct mbuf *n;
5430105197Ssam	u_int8_t satype;
5431105197Ssam
5432105197Ssam	/* map proto to satype */
5433105197Ssam	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5434120585Ssam		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5435120585Ssam			__func__));
5436105197Ssam		return key_senderror(so, m, EINVAL);
5437105197Ssam	}
5438105197Ssam
5439105197Ssam	/* create new sadb_msg to reply. */
5440105197Ssam	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5441105197Ssam	    mhp->msg->sadb_msg_pid);
5442105197Ssam	if (!n)
5443105197Ssam		return key_senderror(so, m, ENOBUFS);
5444105197Ssam
5445105197Ssam	m_freem(m);
5446105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5447105197Ssam    }
5448105197Ssam}
5449105197Ssam
5450105197Ssam/* XXX make it sysctl-configurable? */
5451105197Ssamstatic void
5452105197Ssamkey_getcomb_setlifetime(comb)
5453105197Ssam	struct sadb_comb *comb;
5454105197Ssam{
5455105197Ssam
5456105197Ssam	comb->sadb_comb_soft_allocations = 1;
5457105197Ssam	comb->sadb_comb_hard_allocations = 1;
5458105197Ssam	comb->sadb_comb_soft_bytes = 0;
5459105197Ssam	comb->sadb_comb_hard_bytes = 0;
5460105197Ssam	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5461105197Ssam	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5462105197Ssam	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5463105197Ssam	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5464105197Ssam}
5465105197Ssam
5466105197Ssam/*
5467105197Ssam * XXX reorder combinations by preference
5468105197Ssam * XXX no idea if the user wants ESP authentication or not
5469105197Ssam */
5470105197Ssamstatic struct mbuf *
5471105197Ssamkey_getcomb_esp()
5472105197Ssam{
5473183550Szec	INIT_VNET_IPSEC(curvnet);
5474105197Ssam	struct sadb_comb *comb;
5475105197Ssam	struct enc_xform *algo;
5476105197Ssam	struct mbuf *result = NULL, *m, *n;
5477105197Ssam	int encmin;
5478105197Ssam	int i, off, o;
5479105197Ssam	int totlen;
5480105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5481105197Ssam
5482105197Ssam	m = NULL;
5483105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
5484105197Ssam		algo = esp_algorithm_lookup(i);
5485105197Ssam		if (algo == NULL)
5486105197Ssam			continue;
5487105197Ssam
5488105197Ssam		/* discard algorithms with key size smaller than system min */
5489181803Sbz		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
5490105197Ssam			continue;
5491181803Sbz		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
5492181803Sbz			encmin = V_ipsec_esp_keymin;
5493105197Ssam		else
5494105197Ssam			encmin = _BITS(algo->minkey);
5495105197Ssam
5496181803Sbz		if (V_ipsec_esp_auth)
5497105197Ssam			m = key_getcomb_ah();
5498105197Ssam		else {
5499120585Ssam			IPSEC_ASSERT(l <= MLEN,
5500120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5501111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5502105197Ssam			if (m) {
5503105197Ssam				M_ALIGN(m, l);
5504105197Ssam				m->m_len = l;
5505105197Ssam				m->m_next = NULL;
5506105197Ssam				bzero(mtod(m, caddr_t), m->m_len);
5507105197Ssam			}
5508105197Ssam		}
5509105197Ssam		if (!m)
5510105197Ssam			goto fail;
5511105197Ssam
5512105197Ssam		totlen = 0;
5513105197Ssam		for (n = m; n; n = n->m_next)
5514105197Ssam			totlen += n->m_len;
5515120585Ssam		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
5516105197Ssam
5517105197Ssam		for (off = 0; off < totlen; off += l) {
5518105197Ssam			n = m_pulldown(m, off, l, &o);
5519105197Ssam			if (!n) {
5520105197Ssam				/* m is already freed */
5521105197Ssam				goto fail;
5522105197Ssam			}
5523105197Ssam			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5524105197Ssam			bzero(comb, sizeof(*comb));
5525105197Ssam			key_getcomb_setlifetime(comb);
5526105197Ssam			comb->sadb_comb_encrypt = i;
5527105197Ssam			comb->sadb_comb_encrypt_minbits = encmin;
5528105197Ssam			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5529105197Ssam		}
5530105197Ssam
5531105197Ssam		if (!result)
5532105197Ssam			result = m;
5533105197Ssam		else
5534105197Ssam			m_cat(result, m);
5535105197Ssam	}
5536105197Ssam
5537105197Ssam	return result;
5538105197Ssam
5539105197Ssam fail:
5540105197Ssam	if (result)
5541105197Ssam		m_freem(result);
5542105197Ssam	return NULL;
5543105197Ssam}
5544105197Ssam
5545105197Ssamstatic void
5546105197Ssamkey_getsizes_ah(
5547105197Ssam	const struct auth_hash *ah,
5548105197Ssam	int alg,
5549105197Ssam	u_int16_t* min,
5550105197Ssam	u_int16_t* max)
5551105197Ssam{
5552183550Szec	INIT_VNET_IPSEC(curvnet);
5553183550Szec
5554105197Ssam	*min = *max = ah->keysize;
5555105197Ssam	if (ah->keysize == 0) {
5556105197Ssam		/*
5557105197Ssam		 * Transform takes arbitrary key size but algorithm
5558105197Ssam		 * key size is restricted.  Enforce this here.
5559105197Ssam		 */
5560105197Ssam		switch (alg) {
5561105197Ssam		case SADB_X_AALG_MD5:	*min = *max = 16; break;
5562105197Ssam		case SADB_X_AALG_SHA:	*min = *max = 20; break;
5563105197Ssam		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
5564105197Ssam		default:
5565120585Ssam			DPRINTF(("%s: unknown AH algorithm %u\n",
5566120585Ssam				__func__, alg));
5567105197Ssam			break;
5568105197Ssam		}
5569105197Ssam	}
5570105197Ssam}
5571105197Ssam
5572105197Ssam/*
5573105197Ssam * XXX reorder combinations by preference
5574105197Ssam */
5575105197Ssamstatic struct mbuf *
5576105197Ssamkey_getcomb_ah()
5577105197Ssam{
5578183550Szec	INIT_VNET_IPSEC(curvnet);
5579105197Ssam	struct sadb_comb *comb;
5580105197Ssam	struct auth_hash *algo;
5581105197Ssam	struct mbuf *m;
5582105197Ssam	u_int16_t minkeysize, maxkeysize;
5583105197Ssam	int i;
5584105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5585105197Ssam
5586105197Ssam	m = NULL;
5587105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
5588105197Ssam#if 1
5589105197Ssam		/* we prefer HMAC algorithms, not old algorithms */
5590105197Ssam		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5591105197Ssam			continue;
5592105197Ssam#endif
5593105197Ssam		algo = ah_algorithm_lookup(i);
5594105197Ssam		if (!algo)
5595105197Ssam			continue;
5596105197Ssam		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5597105197Ssam		/* discard algorithms with key size smaller than system min */
5598181803Sbz		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
5599105197Ssam			continue;
5600105197Ssam
5601105197Ssam		if (!m) {
5602120585Ssam			IPSEC_ASSERT(l <= MLEN,
5603120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5604111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5605105197Ssam			if (m) {
5606105197Ssam				M_ALIGN(m, l);
5607105197Ssam				m->m_len = l;
5608105197Ssam				m->m_next = NULL;
5609105197Ssam			}
5610105197Ssam		} else
5611111119Simp			M_PREPEND(m, l, M_DONTWAIT);
5612105197Ssam		if (!m)
5613105197Ssam			return NULL;
5614105197Ssam
5615105197Ssam		comb = mtod(m, struct sadb_comb *);
5616105197Ssam		bzero(comb, sizeof(*comb));
5617105197Ssam		key_getcomb_setlifetime(comb);
5618105197Ssam		comb->sadb_comb_auth = i;
5619105197Ssam		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5620105197Ssam		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5621105197Ssam	}
5622105197Ssam
5623105197Ssam	return m;
5624105197Ssam}
5625105197Ssam
5626105197Ssam/*
5627105197Ssam * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5628105197Ssam * XXX reorder combinations by preference
5629105197Ssam */
5630105197Ssamstatic struct mbuf *
5631105197Ssamkey_getcomb_ipcomp()
5632105197Ssam{
5633105197Ssam	struct sadb_comb *comb;
5634105197Ssam	struct comp_algo *algo;
5635105197Ssam	struct mbuf *m;
5636105197Ssam	int i;
5637105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5638105197Ssam
5639105197Ssam	m = NULL;
5640105197Ssam	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5641105197Ssam		algo = ipcomp_algorithm_lookup(i);
5642105197Ssam		if (!algo)
5643105197Ssam			continue;
5644105197Ssam
5645105197Ssam		if (!m) {
5646120585Ssam			IPSEC_ASSERT(l <= MLEN,
5647120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5648111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5649105197Ssam			if (m) {
5650105197Ssam				M_ALIGN(m, l);
5651105197Ssam				m->m_len = l;
5652105197Ssam				m->m_next = NULL;
5653105197Ssam			}
5654105197Ssam		} else
5655111119Simp			M_PREPEND(m, l, M_DONTWAIT);
5656105197Ssam		if (!m)
5657105197Ssam			return NULL;
5658105197Ssam
5659105197Ssam		comb = mtod(m, struct sadb_comb *);
5660105197Ssam		bzero(comb, sizeof(*comb));
5661105197Ssam		key_getcomb_setlifetime(comb);
5662105197Ssam		comb->sadb_comb_encrypt = i;
5663105197Ssam		/* what should we set into sadb_comb_*_{min,max}bits? */
5664105197Ssam	}
5665105197Ssam
5666105197Ssam	return m;
5667105197Ssam}
5668105197Ssam
5669105197Ssam/*
5670105197Ssam * XXX no way to pass mode (transport/tunnel) to userland
5671105197Ssam * XXX replay checking?
5672105197Ssam * XXX sysctl interface to ipsec_{ah,esp}_keymin
5673105197Ssam */
5674105197Ssamstatic struct mbuf *
5675105197Ssamkey_getprop(saidx)
5676105197Ssam	const struct secasindex *saidx;
5677105197Ssam{
5678105197Ssam	struct sadb_prop *prop;
5679105197Ssam	struct mbuf *m, *n;
5680105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5681105197Ssam	int totlen;
5682105197Ssam
5683105197Ssam	switch (saidx->proto)  {
5684105197Ssam	case IPPROTO_ESP:
5685105197Ssam		m = key_getcomb_esp();
5686105197Ssam		break;
5687105197Ssam	case IPPROTO_AH:
5688105197Ssam		m = key_getcomb_ah();
5689105197Ssam		break;
5690105197Ssam	case IPPROTO_IPCOMP:
5691105197Ssam		m = key_getcomb_ipcomp();
5692105197Ssam		break;
5693105197Ssam	default:
5694105197Ssam		return NULL;
5695105197Ssam	}
5696105197Ssam
5697105197Ssam	if (!m)
5698105197Ssam		return NULL;
5699111119Simp	M_PREPEND(m, l, M_DONTWAIT);
5700105197Ssam	if (!m)
5701105197Ssam		return NULL;
5702105197Ssam
5703105197Ssam	totlen = 0;
5704105197Ssam	for (n = m; n; n = n->m_next)
5705105197Ssam		totlen += n->m_len;
5706105197Ssam
5707105197Ssam	prop = mtod(m, struct sadb_prop *);
5708105197Ssam	bzero(prop, sizeof(*prop));
5709105197Ssam	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5710105197Ssam	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5711105197Ssam	prop->sadb_prop_replay = 32;	/* XXX */
5712105197Ssam
5713105197Ssam	return m;
5714105197Ssam}
5715105197Ssam
5716105197Ssam/*
5717105197Ssam * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5718105197Ssam * send
5719105197Ssam *   <base, SA, address(SD), (address(P)), x_policy,
5720105197Ssam *       (identity(SD),) (sensitivity,) proposal>
5721105197Ssam * to KMD, and expect to receive
5722105197Ssam *   <base> with SADB_ACQUIRE if error occured,
5723105197Ssam * or
5724105197Ssam *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5725105197Ssam * from KMD by PF_KEY.
5726105197Ssam *
5727105197Ssam * XXX x_policy is outside of RFC2367 (KAME extension).
5728105197Ssam * XXX sensitivity is not supported.
5729105197Ssam * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5730105197Ssam * see comment for key_getcomb_ipcomp().
5731105197Ssam *
5732105197Ssam * OUT:
5733105197Ssam *    0     : succeed
5734105197Ssam *    others: error number
5735105197Ssam */
5736105197Ssamstatic int
5737105197Ssamkey_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5738105197Ssam{
5739183550Szec	INIT_VNET_IPSEC(curvnet);
5740105197Ssam	struct mbuf *result = NULL, *m;
5741105197Ssam	struct secacq *newacq;
5742105197Ssam	u_int8_t satype;
5743105197Ssam	int error = -1;
5744105197Ssam	u_int32_t seq;
5745105197Ssam
5746120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
5747105197Ssam	satype = key_proto2satype(saidx->proto);
5748120585Ssam	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
5749105197Ssam
5750105197Ssam	/*
5751105197Ssam	 * We never do anything about acquirng SA.  There is anather
5752105197Ssam	 * solution that kernel blocks to send SADB_ACQUIRE message until
5753105197Ssam	 * getting something message from IKEd.  In later case, to be
5754105197Ssam	 * managed with ACQUIRING list.
5755105197Ssam	 */
5756108533Sschweikh	/* Get an entry to check whether sending message or not. */
5757105197Ssam	if ((newacq = key_getacq(saidx)) != NULL) {
5758181803Sbz		if (V_key_blockacq_count < newacq->count) {
5759105197Ssam			/* reset counter and do send message. */
5760105197Ssam			newacq->count = 0;
5761105197Ssam		} else {
5762105197Ssam			/* increment counter and do nothing. */
5763105197Ssam			newacq->count++;
5764105197Ssam			return 0;
5765105197Ssam		}
5766105197Ssam	} else {
5767105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
5768105197Ssam		if ((newacq = key_newacq(saidx)) == NULL)
5769105197Ssam			return ENOBUFS;
5770105197Ssam	}
5771105197Ssam
5772105197Ssam
5773105197Ssam	seq = newacq->seq;
5774105197Ssam	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5775105197Ssam	if (!m) {
5776105197Ssam		error = ENOBUFS;
5777105197Ssam		goto fail;
5778105197Ssam	}
5779105197Ssam	result = m;
5780105197Ssam
5781105197Ssam	/* set sadb_address for saidx's. */
5782105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5783105197Ssam	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5784105197Ssam	if (!m) {
5785105197Ssam		error = ENOBUFS;
5786105197Ssam		goto fail;
5787105197Ssam	}
5788105197Ssam	m_cat(result, m);
5789105197Ssam
5790105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5791105197Ssam	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5792105197Ssam	if (!m) {
5793105197Ssam		error = ENOBUFS;
5794105197Ssam		goto fail;
5795105197Ssam	}
5796105197Ssam	m_cat(result, m);
5797105197Ssam
5798105197Ssam	/* XXX proxy address (optional) */
5799105197Ssam
5800105197Ssam	/* set sadb_x_policy */
5801105197Ssam	if (sp) {
5802105197Ssam		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5803105197Ssam		if (!m) {
5804105197Ssam			error = ENOBUFS;
5805105197Ssam			goto fail;
5806105197Ssam		}
5807105197Ssam		m_cat(result, m);
5808105197Ssam	}
5809105197Ssam
5810105197Ssam	/* XXX identity (optional) */
5811105197Ssam#if 0
5812105197Ssam	if (idexttype && fqdn) {
5813105197Ssam		/* create identity extension (FQDN) */
5814105197Ssam		struct sadb_ident *id;
5815105197Ssam		int fqdnlen;
5816105197Ssam
5817105197Ssam		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
5818105197Ssam		id = (struct sadb_ident *)p;
5819105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5820105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5821105197Ssam		id->sadb_ident_exttype = idexttype;
5822105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5823105197Ssam		bcopy(fqdn, id + 1, fqdnlen);
5824105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5825105197Ssam	}
5826105197Ssam
5827105197Ssam	if (idexttype) {
5828105197Ssam		/* create identity extension (USERFQDN) */
5829105197Ssam		struct sadb_ident *id;
5830105197Ssam		int userfqdnlen;
5831105197Ssam
5832105197Ssam		if (userfqdn) {
5833105197Ssam			/* +1 for terminating-NUL */
5834105197Ssam			userfqdnlen = strlen(userfqdn) + 1;
5835105197Ssam		} else
5836105197Ssam			userfqdnlen = 0;
5837105197Ssam		id = (struct sadb_ident *)p;
5838105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5839105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5840105197Ssam		id->sadb_ident_exttype = idexttype;
5841105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5842105197Ssam		/* XXX is it correct? */
5843105197Ssam		if (curproc && curproc->p_cred)
5844105197Ssam			id->sadb_ident_id = curproc->p_cred->p_ruid;
5845105197Ssam		if (userfqdn && userfqdnlen)
5846105197Ssam			bcopy(userfqdn, id + 1, userfqdnlen);
5847105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5848105197Ssam	}
5849105197Ssam#endif
5850105197Ssam
5851105197Ssam	/* XXX sensitivity (optional) */
5852105197Ssam
5853105197Ssam	/* create proposal/combination extension */
5854105197Ssam	m = key_getprop(saidx);
5855105197Ssam#if 0
5856105197Ssam	/*
5857105197Ssam	 * spec conformant: always attach proposal/combination extension,
5858105197Ssam	 * the problem is that we have no way to attach it for ipcomp,
5859105197Ssam	 * due to the way sadb_comb is declared in RFC2367.
5860105197Ssam	 */
5861105197Ssam	if (!m) {
5862105197Ssam		error = ENOBUFS;
5863105197Ssam		goto fail;
5864105197Ssam	}
5865105197Ssam	m_cat(result, m);
5866105197Ssam#else
5867105197Ssam	/*
5868105197Ssam	 * outside of spec; make proposal/combination extension optional.
5869105197Ssam	 */
5870105197Ssam	if (m)
5871105197Ssam		m_cat(result, m);
5872105197Ssam#endif
5873105197Ssam
5874105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
5875105197Ssam		error = EINVAL;
5876105197Ssam		goto fail;
5877105197Ssam	}
5878105197Ssam
5879105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
5880105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
5881105197Ssam		if (result == NULL) {
5882105197Ssam			error = ENOBUFS;
5883105197Ssam			goto fail;
5884105197Ssam		}
5885105197Ssam	}
5886105197Ssam
5887105197Ssam	result->m_pkthdr.len = 0;
5888105197Ssam	for (m = result; m; m = m->m_next)
5889105197Ssam		result->m_pkthdr.len += m->m_len;
5890105197Ssam
5891105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
5892105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
5893105197Ssam
5894105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5895105197Ssam
5896105197Ssam fail:
5897105197Ssam	if (result)
5898105197Ssam		m_freem(result);
5899105197Ssam	return error;
5900105197Ssam}
5901105197Ssam
5902105197Ssamstatic struct secacq *
5903105197Ssamkey_newacq(const struct secasindex *saidx)
5904105197Ssam{
5905183550Szec	INIT_VNET_IPSEC(curvnet);
5906105197Ssam	struct secacq *newacq;
5907105197Ssam
5908105197Ssam	/* get new entry */
5909119643Ssam	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5910105197Ssam	if (newacq == NULL) {
5911120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5912105197Ssam		return NULL;
5913105197Ssam	}
5914105197Ssam
5915105197Ssam	/* copy secindex */
5916105197Ssam	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5917181803Sbz	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
5918105197Ssam	newacq->created = time_second;
5919105197Ssam	newacq->count = 0;
5920105197Ssam
5921119643Ssam	/* add to acqtree */
5922120585Ssam	ACQ_LOCK();
5923181803Sbz	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
5924120585Ssam	ACQ_UNLOCK();
5925119643Ssam
5926105197Ssam	return newacq;
5927105197Ssam}
5928105197Ssam
5929105197Ssamstatic struct secacq *
5930105197Ssamkey_getacq(const struct secasindex *saidx)
5931105197Ssam{
5932183550Szec	INIT_VNET_IPSEC(curvnet);
5933105197Ssam	struct secacq *acq;
5934105197Ssam
5935120585Ssam	ACQ_LOCK();
5936181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
5937105197Ssam		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5938119643Ssam			break;
5939105197Ssam	}
5940120585Ssam	ACQ_UNLOCK();
5941105197Ssam
5942119643Ssam	return acq;
5943105197Ssam}
5944105197Ssam
5945105197Ssamstatic struct secacq *
5946105197Ssamkey_getacqbyseq(seq)
5947105197Ssam	u_int32_t seq;
5948105197Ssam{
5949183550Szec	INIT_VNET_IPSEC(curvnet);
5950105197Ssam	struct secacq *acq;
5951105197Ssam
5952120585Ssam	ACQ_LOCK();
5953181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
5954105197Ssam		if (acq->seq == seq)
5955119643Ssam			break;
5956105197Ssam	}
5957120585Ssam	ACQ_UNLOCK();
5958105197Ssam
5959119643Ssam	return acq;
5960105197Ssam}
5961105197Ssam
5962105197Ssamstatic struct secspacq *
5963105197Ssamkey_newspacq(spidx)
5964105197Ssam	struct secpolicyindex *spidx;
5965105197Ssam{
5966183550Szec	INIT_VNET_IPSEC(curvnet);
5967105197Ssam	struct secspacq *acq;
5968105197Ssam
5969105197Ssam	/* get new entry */
5970119643Ssam	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5971105197Ssam	if (acq == NULL) {
5972120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5973105197Ssam		return NULL;
5974105197Ssam	}
5975105197Ssam
5976105197Ssam	/* copy secindex */
5977105197Ssam	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5978105197Ssam	acq->created = time_second;
5979105197Ssam	acq->count = 0;
5980105197Ssam
5981119643Ssam	/* add to spacqtree */
5982120585Ssam	SPACQ_LOCK();
5983181803Sbz	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
5984120585Ssam	SPACQ_UNLOCK();
5985119643Ssam
5986105197Ssam	return acq;
5987105197Ssam}
5988105197Ssam
5989105197Ssamstatic struct secspacq *
5990105197Ssamkey_getspacq(spidx)
5991105197Ssam	struct secpolicyindex *spidx;
5992105197Ssam{
5993183550Szec	INIT_VNET_IPSEC(curvnet);
5994105197Ssam	struct secspacq *acq;
5995105197Ssam
5996120585Ssam	SPACQ_LOCK();
5997181803Sbz	LIST_FOREACH(acq, &V_spacqtree, chain) {
5998119643Ssam		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
5999119643Ssam			/* NB: return holding spacq_lock */
6000105197Ssam			return acq;
6001119643Ssam		}
6002105197Ssam	}
6003120585Ssam	SPACQ_UNLOCK();
6004105197Ssam
6005105197Ssam	return NULL;
6006105197Ssam}
6007105197Ssam
6008105197Ssam/*
6009105197Ssam * SADB_ACQUIRE processing,
6010105197Ssam * in first situation, is receiving
6011105197Ssam *   <base>
6012105197Ssam * from the ikmpd, and clear sequence of its secasvar entry.
6013105197Ssam *
6014105197Ssam * In second situation, is receiving
6015105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6016105197Ssam * from a user land process, and return
6017105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6018105197Ssam * to the socket.
6019105197Ssam *
6020105197Ssam * m will always be freed.
6021105197Ssam */
6022105197Ssamstatic int
6023105197Ssamkey_acquire2(so, m, mhp)
6024105197Ssam	struct socket *so;
6025105197Ssam	struct mbuf *m;
6026105197Ssam	const struct sadb_msghdr *mhp;
6027105197Ssam{
6028183550Szec	INIT_VNET_IPSEC(curvnet);
6029105197Ssam	const struct sadb_address *src0, *dst0;
6030105197Ssam	struct secasindex saidx;
6031105197Ssam	struct secashead *sah;
6032105197Ssam	u_int16_t proto;
6033105197Ssam	int error;
6034105197Ssam
6035120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6036120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6037120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6038120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6039105197Ssam
6040105197Ssam	/*
6041105197Ssam	 * Error message from KMd.
6042105197Ssam	 * We assume that if error was occured in IKEd, the length of PFKEY
6043105197Ssam	 * message is equal to the size of sadb_msg structure.
6044105197Ssam	 * We do not raise error even if error occured in this function.
6045105197Ssam	 */
6046105197Ssam	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6047105197Ssam		struct secacq *acq;
6048105197Ssam
6049105197Ssam		/* check sequence number */
6050105197Ssam		if (mhp->msg->sadb_msg_seq == 0) {
6051120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6052120585Ssam				"number.\n", __func__));
6053105197Ssam			m_freem(m);
6054105197Ssam			return 0;
6055105197Ssam		}
6056105197Ssam
6057105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6058105197Ssam			/*
6059105197Ssam			 * the specified larval SA is already gone, or we got
6060105197Ssam			 * a bogus sequence number.  we can silently ignore it.
6061105197Ssam			 */
6062105197Ssam			m_freem(m);
6063105197Ssam			return 0;
6064105197Ssam		}
6065105197Ssam
6066105197Ssam		/* reset acq counter in order to deletion by timehander. */
6067105197Ssam		acq->created = time_second;
6068105197Ssam		acq->count = 0;
6069105197Ssam		m_freem(m);
6070105197Ssam		return 0;
6071105197Ssam	}
6072105197Ssam
6073105197Ssam	/*
6074105197Ssam	 * This message is from user land.
6075105197Ssam	 */
6076105197Ssam
6077105197Ssam	/* map satype to proto */
6078105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6079120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6080120585Ssam			__func__));
6081105197Ssam		return key_senderror(so, m, EINVAL);
6082105197Ssam	}
6083105197Ssam
6084105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6085105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6086105197Ssam	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6087105197Ssam		/* error */
6088120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6089120585Ssam			__func__));
6090105197Ssam		return key_senderror(so, m, EINVAL);
6091105197Ssam	}
6092105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6093105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6094105197Ssam	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6095105197Ssam		/* error */
6096120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6097120585Ssam			__func__));
6098105197Ssam		return key_senderror(so, m, EINVAL);
6099105197Ssam	}
6100105197Ssam
6101105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6102105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6103105197Ssam
6104105197Ssam	/* XXX boundary check against sa_len */
6105105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6106105197Ssam
6107105197Ssam	/* get a SA index */
6108120585Ssam	SAHTREE_LOCK();
6109181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
6110105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
6111105197Ssam			continue;
6112105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6113105197Ssam			break;
6114105197Ssam	}
6115120585Ssam	SAHTREE_UNLOCK();
6116105197Ssam	if (sah != NULL) {
6117120585Ssam		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6118105197Ssam		return key_senderror(so, m, EEXIST);
6119105197Ssam	}
6120105197Ssam
6121105197Ssam	error = key_acquire(&saidx, NULL);
6122105197Ssam	if (error != 0) {
6123120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6124120585Ssam			__func__, mhp->msg->sadb_msg_errno));
6125105197Ssam		return key_senderror(so, m, error);
6126105197Ssam	}
6127105197Ssam
6128105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6129105197Ssam}
6130105197Ssam
6131105197Ssam/*
6132105197Ssam * SADB_REGISTER processing.
6133105197Ssam * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6134105197Ssam * receive
6135105197Ssam *   <base>
6136105197Ssam * from the ikmpd, and register a socket to send PF_KEY messages,
6137105197Ssam * and send
6138105197Ssam *   <base, supported>
6139105197Ssam * to KMD by PF_KEY.
6140105197Ssam * If socket is detached, must free from regnode.
6141105197Ssam *
6142105197Ssam * m will always be freed.
6143105197Ssam */
6144105197Ssamstatic int
6145105197Ssamkey_register(so, m, mhp)
6146105197Ssam	struct socket *so;
6147105197Ssam	struct mbuf *m;
6148105197Ssam	const struct sadb_msghdr *mhp;
6149105197Ssam{
6150183550Szec	INIT_VNET_IPSEC(curvnet);
6151105197Ssam	struct secreg *reg, *newreg = 0;
6152105197Ssam
6153120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6154120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6155120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6156120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6157105197Ssam
6158105197Ssam	/* check for invalid register message */
6159181803Sbz	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6160105197Ssam		return key_senderror(so, m, EINVAL);
6161105197Ssam
6162105197Ssam	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6163105197Ssam	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6164105197Ssam		goto setmsg;
6165105197Ssam
6166105197Ssam	/* check whether existing or not */
6167120585Ssam	REGTREE_LOCK();
6168181803Sbz	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6169105197Ssam		if (reg->so == so) {
6170120585Ssam			REGTREE_UNLOCK();
6171120585Ssam			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6172120585Ssam				__func__));
6173105197Ssam			return key_senderror(so, m, EEXIST);
6174105197Ssam		}
6175105197Ssam	}
6176105197Ssam
6177105197Ssam	/* create regnode */
6178119643Ssam	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6179105197Ssam	if (newreg == NULL) {
6180120585Ssam		REGTREE_UNLOCK();
6181120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6182105197Ssam		return key_senderror(so, m, ENOBUFS);
6183105197Ssam	}
6184105197Ssam
6185105197Ssam	newreg->so = so;
6186105197Ssam	((struct keycb *)sotorawcb(so))->kp_registered++;
6187105197Ssam
6188105197Ssam	/* add regnode to regtree. */
6189181803Sbz	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6190120585Ssam	REGTREE_UNLOCK();
6191105197Ssam
6192105197Ssam  setmsg:
6193105197Ssam    {
6194105197Ssam	struct mbuf *n;
6195105197Ssam	struct sadb_msg *newmsg;
6196105197Ssam	struct sadb_supported *sup;
6197105197Ssam	u_int len, alen, elen;
6198105197Ssam	int off;
6199105197Ssam	int i;
6200105197Ssam	struct sadb_alg *alg;
6201105197Ssam
6202105197Ssam	/* create new sadb_msg to reply. */
6203105197Ssam	alen = 0;
6204105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6205105197Ssam		if (ah_algorithm_lookup(i))
6206105197Ssam			alen += sizeof(struct sadb_alg);
6207105197Ssam	}
6208105197Ssam	if (alen)
6209105197Ssam		alen += sizeof(struct sadb_supported);
6210105197Ssam	elen = 0;
6211105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6212105197Ssam		if (esp_algorithm_lookup(i))
6213105197Ssam			elen += sizeof(struct sadb_alg);
6214105197Ssam	}
6215105197Ssam	if (elen)
6216105197Ssam		elen += sizeof(struct sadb_supported);
6217105197Ssam
6218105197Ssam	len = sizeof(struct sadb_msg) + alen + elen;
6219105197Ssam
6220105197Ssam	if (len > MCLBYTES)
6221105197Ssam		return key_senderror(so, m, ENOBUFS);
6222105197Ssam
6223111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
6224105197Ssam	if (len > MHLEN) {
6225111119Simp		MCLGET(n, M_DONTWAIT);
6226105197Ssam		if ((n->m_flags & M_EXT) == 0) {
6227105197Ssam			m_freem(n);
6228105197Ssam			n = NULL;
6229105197Ssam		}
6230105197Ssam	}
6231105197Ssam	if (!n)
6232105197Ssam		return key_senderror(so, m, ENOBUFS);
6233105197Ssam
6234105197Ssam	n->m_pkthdr.len = n->m_len = len;
6235105197Ssam	n->m_next = NULL;
6236105197Ssam	off = 0;
6237105197Ssam
6238105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6239105197Ssam	newmsg = mtod(n, struct sadb_msg *);
6240105197Ssam	newmsg->sadb_msg_errno = 0;
6241105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6242105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6243105197Ssam
6244105197Ssam	/* for authentication algorithm */
6245105197Ssam	if (alen) {
6246105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6247105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6248105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6249105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6250105197Ssam
6251105197Ssam		for (i = 1; i <= SADB_AALG_MAX; i++) {
6252105197Ssam			struct auth_hash *aalgo;
6253105197Ssam			u_int16_t minkeysize, maxkeysize;
6254105197Ssam
6255105197Ssam			aalgo = ah_algorithm_lookup(i);
6256105197Ssam			if (!aalgo)
6257105197Ssam				continue;
6258105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6259105197Ssam			alg->sadb_alg_id = i;
6260105197Ssam			alg->sadb_alg_ivlen = 0;
6261105197Ssam			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6262105197Ssam			alg->sadb_alg_minbits = _BITS(minkeysize);
6263105197Ssam			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6264105197Ssam			off += PFKEY_ALIGN8(sizeof(*alg));
6265105197Ssam		}
6266105197Ssam	}
6267105197Ssam
6268105197Ssam	/* for encryption algorithm */
6269105197Ssam	if (elen) {
6270105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6271105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6272105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6273105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6274105197Ssam
6275105197Ssam		for (i = 1; i <= SADB_EALG_MAX; i++) {
6276105197Ssam			struct enc_xform *ealgo;
6277105197Ssam
6278105197Ssam			ealgo = esp_algorithm_lookup(i);
6279105197Ssam			if (!ealgo)
6280105197Ssam				continue;
6281105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6282105197Ssam			alg->sadb_alg_id = i;
6283105197Ssam			alg->sadb_alg_ivlen = ealgo->blocksize;
6284105197Ssam			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6285105197Ssam			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6286105197Ssam			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6287105197Ssam		}
6288105197Ssam	}
6289105197Ssam
6290120585Ssam	IPSEC_ASSERT(off == len,
6291120585Ssam		("length assumption failed (off %u len %u)", off, len));
6292105197Ssam
6293105197Ssam	m_freem(m);
6294105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6295105197Ssam    }
6296105197Ssam}
6297105197Ssam
6298105197Ssam/*
6299105197Ssam * free secreg entry registered.
6300105197Ssam * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6301105197Ssam */
6302105197Ssamvoid
6303119643Ssamkey_freereg(struct socket *so)
6304105197Ssam{
6305183550Szec	INIT_VNET_IPSEC(curvnet);
6306105197Ssam	struct secreg *reg;
6307105197Ssam	int i;
6308105197Ssam
6309120585Ssam	IPSEC_ASSERT(so != NULL, ("NULL so"));
6310105197Ssam
6311105197Ssam	/*
6312105197Ssam	 * check whether existing or not.
6313105197Ssam	 * check all type of SA, because there is a potential that
6314105197Ssam	 * one socket is registered to multiple type of SA.
6315105197Ssam	 */
6316120585Ssam	REGTREE_LOCK();
6317105197Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6318181803Sbz		LIST_FOREACH(reg, &V_regtree[i], chain) {
6319119643Ssam			if (reg->so == so && __LIST_CHAINED(reg)) {
6320105197Ssam				LIST_REMOVE(reg, chain);
6321119643Ssam				free(reg, M_IPSEC_SAR);
6322105197Ssam				break;
6323105197Ssam			}
6324105197Ssam		}
6325105197Ssam	}
6326120585Ssam	REGTREE_UNLOCK();
6327105197Ssam}
6328105197Ssam
6329105197Ssam/*
6330105197Ssam * SADB_EXPIRE processing
6331105197Ssam * send
6332105197Ssam *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6333105197Ssam * to KMD by PF_KEY.
6334105197Ssam * NOTE: We send only soft lifetime extension.
6335105197Ssam *
6336105197Ssam * OUT:	0	: succeed
6337105197Ssam *	others	: error number
6338105197Ssam */
6339105197Ssamstatic int
6340119643Ssamkey_expire(struct secasvar *sav)
6341105197Ssam{
6342105197Ssam	int s;
6343105197Ssam	int satype;
6344105197Ssam	struct mbuf *result = NULL, *m;
6345105197Ssam	int len;
6346105197Ssam	int error = -1;
6347105197Ssam	struct sadb_lifetime *lt;
6348105197Ssam
6349105197Ssam	/* XXX: Why do we lock ? */
6350105197Ssam	s = splnet();	/*called from softclock()*/
6351105197Ssam
6352120585Ssam	IPSEC_ASSERT (sav != NULL, ("null sav"));
6353120585Ssam	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6354105197Ssam
6355105197Ssam	/* set msg header */
6356120585Ssam	satype = key_proto2satype(sav->sah->saidx.proto);
6357120585Ssam	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6358105197Ssam	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6359105197Ssam	if (!m) {
6360105197Ssam		error = ENOBUFS;
6361105197Ssam		goto fail;
6362105197Ssam	}
6363105197Ssam	result = m;
6364105197Ssam
6365105197Ssam	/* create SA extension */
6366105197Ssam	m = key_setsadbsa(sav);
6367105197Ssam	if (!m) {
6368105197Ssam		error = ENOBUFS;
6369105197Ssam		goto fail;
6370105197Ssam	}
6371105197Ssam	m_cat(result, m);
6372105197Ssam
6373105197Ssam	/* create SA extension */
6374105197Ssam	m = key_setsadbxsa2(sav->sah->saidx.mode,
6375105197Ssam			sav->replay ? sav->replay->count : 0,
6376105197Ssam			sav->sah->saidx.reqid);
6377105197Ssam	if (!m) {
6378105197Ssam		error = ENOBUFS;
6379105197Ssam		goto fail;
6380105197Ssam	}
6381105197Ssam	m_cat(result, m);
6382105197Ssam
6383105197Ssam	/* create lifetime extension (current and soft) */
6384105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6385105197Ssam	m = key_alloc_mbuf(len);
6386105197Ssam	if (!m || m->m_next) {	/*XXX*/
6387105197Ssam		if (m)
6388105197Ssam			m_freem(m);
6389105197Ssam		error = ENOBUFS;
6390105197Ssam		goto fail;
6391105197Ssam	}
6392105197Ssam	bzero(mtod(m, caddr_t), len);
6393105197Ssam	lt = mtod(m, struct sadb_lifetime *);
6394105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6395105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6396157123Sgnn	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6397157123Sgnn	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6398157123Sgnn	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6399157123Sgnn	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6400105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6401176743Sbz	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6402176743Sbz	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6403176743Sbz	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6404176743Sbz	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6405176743Sbz	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6406176743Sbz	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6407105197Ssam	m_cat(result, m);
6408105197Ssam
6409105197Ssam	/* set sadb_address for source */
6410105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6411105197Ssam	    &sav->sah->saidx.src.sa,
6412105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6413105197Ssam	if (!m) {
6414105197Ssam		error = ENOBUFS;
6415105197Ssam		goto fail;
6416105197Ssam	}
6417105197Ssam	m_cat(result, m);
6418105197Ssam
6419105197Ssam	/* set sadb_address for destination */
6420105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6421105197Ssam	    &sav->sah->saidx.dst.sa,
6422105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6423105197Ssam	if (!m) {
6424105197Ssam		error = ENOBUFS;
6425105197Ssam		goto fail;
6426105197Ssam	}
6427105197Ssam	m_cat(result, m);
6428105197Ssam
6429105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
6430105197Ssam		error = EINVAL;
6431105197Ssam		goto fail;
6432105197Ssam	}
6433105197Ssam
6434105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
6435105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
6436105197Ssam		if (result == NULL) {
6437105197Ssam			error = ENOBUFS;
6438105197Ssam			goto fail;
6439105197Ssam		}
6440105197Ssam	}
6441105197Ssam
6442105197Ssam	result->m_pkthdr.len = 0;
6443105197Ssam	for (m = result; m; m = m->m_next)
6444105197Ssam		result->m_pkthdr.len += m->m_len;
6445105197Ssam
6446105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
6447105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
6448105197Ssam
6449105197Ssam	splx(s);
6450105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6451105197Ssam
6452105197Ssam fail:
6453105197Ssam	if (result)
6454105197Ssam		m_freem(result);
6455105197Ssam	splx(s);
6456105197Ssam	return error;
6457105197Ssam}
6458105197Ssam
6459105197Ssam/*
6460105197Ssam * SADB_FLUSH processing
6461105197Ssam * receive
6462105197Ssam *   <base>
6463105197Ssam * from the ikmpd, and free all entries in secastree.
6464105197Ssam * and send,
6465105197Ssam *   <base>
6466105197Ssam * to the ikmpd.
6467105197Ssam * NOTE: to do is only marking SADB_SASTATE_DEAD.
6468105197Ssam *
6469105197Ssam * m will always be freed.
6470105197Ssam */
6471105197Ssamstatic int
6472105197Ssamkey_flush(so, m, mhp)
6473105197Ssam	struct socket *so;
6474105197Ssam	struct mbuf *m;
6475105197Ssam	const struct sadb_msghdr *mhp;
6476105197Ssam{
6477183550Szec	INIT_VNET_IPSEC(curvnet);
6478105197Ssam	struct sadb_msg *newmsg;
6479105197Ssam	struct secashead *sah, *nextsah;
6480105197Ssam	struct secasvar *sav, *nextsav;
6481105197Ssam	u_int16_t proto;
6482105197Ssam	u_int8_t state;
6483105197Ssam	u_int stateidx;
6484105197Ssam
6485120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6486120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6487120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6488105197Ssam
6489105197Ssam	/* map satype to proto */
6490105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6491120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6492120585Ssam			__func__));
6493105197Ssam		return key_senderror(so, m, EINVAL);
6494105197Ssam	}
6495105197Ssam
6496105197Ssam	/* no SATYPE specified, i.e. flushing all SA. */
6497120585Ssam	SAHTREE_LOCK();
6498181803Sbz	for (sah = LIST_FIRST(&V_sahtree);
6499105197Ssam	     sah != NULL;
6500105197Ssam	     sah = nextsah) {
6501105197Ssam		nextsah = LIST_NEXT(sah, chain);
6502105197Ssam
6503105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6504105197Ssam		 && proto != sah->saidx.proto)
6505105197Ssam			continue;
6506105197Ssam
6507105197Ssam		for (stateidx = 0;
6508185348Szec		     stateidx < _ARRAYLEN(saorder_state_alive);
6509105197Ssam		     stateidx++) {
6510185348Szec			state = saorder_state_any[stateidx];
6511105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
6512105197Ssam			     sav != NULL;
6513105197Ssam			     sav = nextsav) {
6514105197Ssam
6515105197Ssam				nextsav = LIST_NEXT(sav, chain);
6516105197Ssam
6517105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6518105197Ssam				KEY_FREESAV(&sav);
6519105197Ssam			}
6520105197Ssam		}
6521105197Ssam
6522105197Ssam		sah->state = SADB_SASTATE_DEAD;
6523105197Ssam	}
6524120585Ssam	SAHTREE_UNLOCK();
6525105197Ssam
6526105197Ssam	if (m->m_len < sizeof(struct sadb_msg) ||
6527105197Ssam	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6528120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6529105197Ssam		return key_senderror(so, m, ENOBUFS);
6530105197Ssam	}
6531105197Ssam
6532105197Ssam	if (m->m_next)
6533105197Ssam		m_freem(m->m_next);
6534105197Ssam	m->m_next = NULL;
6535105197Ssam	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6536105197Ssam	newmsg = mtod(m, struct sadb_msg *);
6537105197Ssam	newmsg->sadb_msg_errno = 0;
6538105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6539105197Ssam
6540105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6541105197Ssam}
6542105197Ssam
6543105197Ssam/*
6544105197Ssam * SADB_DUMP processing
6545105197Ssam * dump all entries including status of DEAD in SAD.
6546105197Ssam * receive
6547105197Ssam *   <base>
6548105197Ssam * from the ikmpd, and dump all secasvar leaves
6549105197Ssam * and send,
6550105197Ssam *   <base> .....
6551105197Ssam * to the ikmpd.
6552105197Ssam *
6553105197Ssam * m will always be freed.
6554105197Ssam */
6555105197Ssamstatic int
6556105197Ssamkey_dump(so, m, mhp)
6557105197Ssam	struct socket *so;
6558105197Ssam	struct mbuf *m;
6559105197Ssam	const struct sadb_msghdr *mhp;
6560105197Ssam{
6561183550Szec	INIT_VNET_IPSEC(curvnet);
6562105197Ssam	struct secashead *sah;
6563105197Ssam	struct secasvar *sav;
6564105197Ssam	u_int16_t proto;
6565105197Ssam	u_int stateidx;
6566105197Ssam	u_int8_t satype;
6567105197Ssam	u_int8_t state;
6568105197Ssam	int cnt;
6569105197Ssam	struct sadb_msg *newmsg;
6570105197Ssam	struct mbuf *n;
6571105197Ssam
6572120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6573120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6574120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6575120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6576105197Ssam
6577105197Ssam	/* map satype to proto */
6578105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6579120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6580120585Ssam			__func__));
6581105197Ssam		return key_senderror(so, m, EINVAL);
6582105197Ssam	}
6583105197Ssam
6584105197Ssam	/* count sav entries to be sent to the userland. */
6585105197Ssam	cnt = 0;
6586120585Ssam	SAHTREE_LOCK();
6587181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
6588105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6589105197Ssam		 && proto != sah->saidx.proto)
6590105197Ssam			continue;
6591105197Ssam
6592105197Ssam		for (stateidx = 0;
6593185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
6594105197Ssam		     stateidx++) {
6595185348Szec			state = saorder_state_any[stateidx];
6596105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6597105197Ssam				cnt++;
6598105197Ssam			}
6599105197Ssam		}
6600105197Ssam	}
6601105197Ssam
6602119643Ssam	if (cnt == 0) {
6603120585Ssam		SAHTREE_UNLOCK();
6604105197Ssam		return key_senderror(so, m, ENOENT);
6605119643Ssam	}
6606105197Ssam
6607105197Ssam	/* send this to the userland, one at a time. */
6608105197Ssam	newmsg = NULL;
6609181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
6610105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6611105197Ssam		 && proto != sah->saidx.proto)
6612105197Ssam			continue;
6613105197Ssam
6614105197Ssam		/* map proto to satype */
6615105197Ssam		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6616120585Ssam			SAHTREE_UNLOCK();
6617120585Ssam			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
6618120585Ssam				"SAD.\n", __func__));
6619105197Ssam			return key_senderror(so, m, EINVAL);
6620105197Ssam		}
6621105197Ssam
6622105197Ssam		for (stateidx = 0;
6623185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
6624105197Ssam		     stateidx++) {
6625185348Szec			state = saorder_state_any[stateidx];
6626105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6627105197Ssam				n = key_setdumpsa(sav, SADB_DUMP, satype,
6628105197Ssam				    --cnt, mhp->msg->sadb_msg_pid);
6629119643Ssam				if (!n) {
6630120585Ssam					SAHTREE_UNLOCK();
6631105197Ssam					return key_senderror(so, m, ENOBUFS);
6632119643Ssam				}
6633105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6634105197Ssam			}
6635105197Ssam		}
6636105197Ssam	}
6637120585Ssam	SAHTREE_UNLOCK();
6638105197Ssam
6639105197Ssam	m_freem(m);
6640105197Ssam	return 0;
6641105197Ssam}
6642105197Ssam
6643105197Ssam/*
6644105197Ssam * SADB_X_PROMISC processing
6645105197Ssam *
6646105197Ssam * m will always be freed.
6647105197Ssam */
6648105197Ssamstatic int
6649105197Ssamkey_promisc(so, m, mhp)
6650105197Ssam	struct socket *so;
6651105197Ssam	struct mbuf *m;
6652105197Ssam	const struct sadb_msghdr *mhp;
6653105197Ssam{
6654105197Ssam	int olen;
6655105197Ssam
6656120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6657120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6658120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6659120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6660105197Ssam
6661105197Ssam	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6662105197Ssam
6663105197Ssam	if (olen < sizeof(struct sadb_msg)) {
6664105197Ssam#if 1
6665105197Ssam		return key_senderror(so, m, EINVAL);
6666105197Ssam#else
6667105197Ssam		m_freem(m);
6668105197Ssam		return 0;
6669105197Ssam#endif
6670105197Ssam	} else if (olen == sizeof(struct sadb_msg)) {
6671105197Ssam		/* enable/disable promisc mode */
6672105197Ssam		struct keycb *kp;
6673105197Ssam
6674105197Ssam		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6675105197Ssam			return key_senderror(so, m, EINVAL);
6676105197Ssam		mhp->msg->sadb_msg_errno = 0;
6677105197Ssam		switch (mhp->msg->sadb_msg_satype) {
6678105197Ssam		case 0:
6679105197Ssam		case 1:
6680105197Ssam			kp->kp_promisc = mhp->msg->sadb_msg_satype;
6681105197Ssam			break;
6682105197Ssam		default:
6683105197Ssam			return key_senderror(so, m, EINVAL);
6684105197Ssam		}
6685105197Ssam
6686105197Ssam		/* send the original message back to everyone */
6687105197Ssam		mhp->msg->sadb_msg_errno = 0;
6688105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6689105197Ssam	} else {
6690105197Ssam		/* send packet as is */
6691105197Ssam
6692105197Ssam		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6693105197Ssam
6694105197Ssam		/* TODO: if sadb_msg_seq is specified, send to specific pid */
6695105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6696105197Ssam	}
6697105197Ssam}
6698105197Ssam
6699105197Ssamstatic int (*key_typesw[]) __P((struct socket *, struct mbuf *,
6700105197Ssam		const struct sadb_msghdr *)) = {
6701105197Ssam	NULL,		/* SADB_RESERVED */
6702105197Ssam	key_getspi,	/* SADB_GETSPI */
6703105197Ssam	key_update,	/* SADB_UPDATE */
6704105197Ssam	key_add,	/* SADB_ADD */
6705105197Ssam	key_delete,	/* SADB_DELETE */
6706105197Ssam	key_get,	/* SADB_GET */
6707105197Ssam	key_acquire2,	/* SADB_ACQUIRE */
6708105197Ssam	key_register,	/* SADB_REGISTER */
6709105197Ssam	NULL,		/* SADB_EXPIRE */
6710105197Ssam	key_flush,	/* SADB_FLUSH */
6711105197Ssam	key_dump,	/* SADB_DUMP */
6712105197Ssam	key_promisc,	/* SADB_X_PROMISC */
6713105197Ssam	NULL,		/* SADB_X_PCHANGE */
6714105197Ssam	key_spdadd,	/* SADB_X_SPDUPDATE */
6715105197Ssam	key_spdadd,	/* SADB_X_SPDADD */
6716105197Ssam	key_spddelete,	/* SADB_X_SPDDELETE */
6717105197Ssam	key_spdget,	/* SADB_X_SPDGET */
6718105197Ssam	NULL,		/* SADB_X_SPDACQUIRE */
6719105197Ssam	key_spddump,	/* SADB_X_SPDDUMP */
6720105197Ssam	key_spdflush,	/* SADB_X_SPDFLUSH */
6721105197Ssam	key_spdadd,	/* SADB_X_SPDSETIDX */
6722105197Ssam	NULL,		/* SADB_X_SPDEXPIRE */
6723105197Ssam	key_spddelete2,	/* SADB_X_SPDDELETE2 */
6724105197Ssam};
6725105197Ssam
6726105197Ssam/*
6727105197Ssam * parse sadb_msg buffer to process PFKEYv2,
6728105197Ssam * and create a data to response if needed.
6729105197Ssam * I think to be dealed with mbuf directly.
6730105197Ssam * IN:
6731105197Ssam *     msgp  : pointer to pointer to a received buffer pulluped.
6732105197Ssam *             This is rewrited to response.
6733105197Ssam *     so    : pointer to socket.
6734105197Ssam * OUT:
6735105197Ssam *    length for buffer to send to user process.
6736105197Ssam */
6737105197Ssamint
6738105197Ssamkey_parse(m, so)
6739105197Ssam	struct mbuf *m;
6740105197Ssam	struct socket *so;
6741105197Ssam{
6742183550Szec	INIT_VNET_IPSEC(curvnet);
6743105197Ssam	struct sadb_msg *msg;
6744105197Ssam	struct sadb_msghdr mh;
6745105197Ssam	u_int orglen;
6746105197Ssam	int error;
6747105197Ssam	int target;
6748105197Ssam
6749120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6750120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6751105197Ssam
6752105197Ssam#if 0	/*kdebug_sadb assumes msg in linear buffer*/
6753105197Ssam	KEYDEBUG(KEYDEBUG_KEY_DUMP,
6754120585Ssam		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
6755105197Ssam		kdebug_sadb(msg));
6756105197Ssam#endif
6757105197Ssam
6758105197Ssam	if (m->m_len < sizeof(struct sadb_msg)) {
6759105197Ssam		m = m_pullup(m, sizeof(struct sadb_msg));
6760105197Ssam		if (!m)
6761105197Ssam			return ENOBUFS;
6762105197Ssam	}
6763105197Ssam	msg = mtod(m, struct sadb_msg *);
6764105197Ssam	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6765105197Ssam	target = KEY_SENDUP_ONE;
6766105197Ssam
6767105197Ssam	if ((m->m_flags & M_PKTHDR) == 0 ||
6768105197Ssam	    m->m_pkthdr.len != m->m_pkthdr.len) {
6769120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
6770181803Sbz		V_pfkeystat.out_invlen++;
6771105197Ssam		error = EINVAL;
6772105197Ssam		goto senderror;
6773105197Ssam	}
6774105197Ssam
6775105197Ssam	if (msg->sadb_msg_version != PF_KEY_V2) {
6776120585Ssam		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
6777120585Ssam		    __func__, msg->sadb_msg_version));
6778181803Sbz		V_pfkeystat.out_invver++;
6779105197Ssam		error = EINVAL;
6780105197Ssam		goto senderror;
6781105197Ssam	}
6782105197Ssam
6783105197Ssam	if (msg->sadb_msg_type > SADB_MAX) {
6784120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6785120585Ssam		    __func__, msg->sadb_msg_type));
6786181803Sbz		V_pfkeystat.out_invmsgtype++;
6787105197Ssam		error = EINVAL;
6788105197Ssam		goto senderror;
6789105197Ssam	}
6790105197Ssam
6791105197Ssam	/* for old-fashioned code - should be nuked */
6792105197Ssam	if (m->m_pkthdr.len > MCLBYTES) {
6793105197Ssam		m_freem(m);
6794105197Ssam		return ENOBUFS;
6795105197Ssam	}
6796105197Ssam	if (m->m_next) {
6797105197Ssam		struct mbuf *n;
6798105197Ssam
6799111119Simp		MGETHDR(n, M_DONTWAIT, MT_DATA);
6800105197Ssam		if (n && m->m_pkthdr.len > MHLEN) {
6801111119Simp			MCLGET(n, M_DONTWAIT);
6802105197Ssam			if ((n->m_flags & M_EXT) == 0) {
6803105197Ssam				m_free(n);
6804105197Ssam				n = NULL;
6805105197Ssam			}
6806105197Ssam		}
6807105197Ssam		if (!n) {
6808105197Ssam			m_freem(m);
6809105197Ssam			return ENOBUFS;
6810105197Ssam		}
6811105197Ssam		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6812105197Ssam		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6813105197Ssam		n->m_next = NULL;
6814105197Ssam		m_freem(m);
6815105197Ssam		m = n;
6816105197Ssam	}
6817105197Ssam
6818105197Ssam	/* align the mbuf chain so that extensions are in contiguous region. */
6819105197Ssam	error = key_align(m, &mh);
6820105197Ssam	if (error)
6821105197Ssam		return error;
6822105197Ssam
6823105197Ssam	msg = mh.msg;
6824105197Ssam
6825105197Ssam	/* check SA type */
6826105197Ssam	switch (msg->sadb_msg_satype) {
6827105197Ssam	case SADB_SATYPE_UNSPEC:
6828105197Ssam		switch (msg->sadb_msg_type) {
6829105197Ssam		case SADB_GETSPI:
6830105197Ssam		case SADB_UPDATE:
6831105197Ssam		case SADB_ADD:
6832105197Ssam		case SADB_DELETE:
6833105197Ssam		case SADB_GET:
6834105197Ssam		case SADB_ACQUIRE:
6835105197Ssam		case SADB_EXPIRE:
6836120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify satype "
6837120585Ssam			    "when msg type=%u.\n", __func__,
6838120585Ssam			    msg->sadb_msg_type));
6839181803Sbz			V_pfkeystat.out_invsatype++;
6840105197Ssam			error = EINVAL;
6841105197Ssam			goto senderror;
6842105197Ssam		}
6843105197Ssam		break;
6844105197Ssam	case SADB_SATYPE_AH:
6845105197Ssam	case SADB_SATYPE_ESP:
6846105197Ssam	case SADB_X_SATYPE_IPCOMP:
6847125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
6848105197Ssam		switch (msg->sadb_msg_type) {
6849105197Ssam		case SADB_X_SPDADD:
6850105197Ssam		case SADB_X_SPDDELETE:
6851105197Ssam		case SADB_X_SPDGET:
6852105197Ssam		case SADB_X_SPDDUMP:
6853105197Ssam		case SADB_X_SPDFLUSH:
6854105197Ssam		case SADB_X_SPDSETIDX:
6855105197Ssam		case SADB_X_SPDUPDATE:
6856105197Ssam		case SADB_X_SPDDELETE2:
6857120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
6858120585Ssam				__func__, msg->sadb_msg_type));
6859181803Sbz			V_pfkeystat.out_invsatype++;
6860105197Ssam			error = EINVAL;
6861105197Ssam			goto senderror;
6862105197Ssam		}
6863105197Ssam		break;
6864105197Ssam	case SADB_SATYPE_RSVP:
6865105197Ssam	case SADB_SATYPE_OSPFV2:
6866105197Ssam	case SADB_SATYPE_RIPV2:
6867105197Ssam	case SADB_SATYPE_MIP:
6868120585Ssam		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
6869120585Ssam			__func__, msg->sadb_msg_satype));
6870181803Sbz		V_pfkeystat.out_invsatype++;
6871105197Ssam		error = EOPNOTSUPP;
6872105197Ssam		goto senderror;
6873105197Ssam	case 1:	/* XXX: What does it do? */
6874105197Ssam		if (msg->sadb_msg_type == SADB_X_PROMISC)
6875105197Ssam			break;
6876105197Ssam		/*FALLTHROUGH*/
6877105197Ssam	default:
6878120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6879120585Ssam			__func__, msg->sadb_msg_satype));
6880181803Sbz		V_pfkeystat.out_invsatype++;
6881105197Ssam		error = EINVAL;
6882105197Ssam		goto senderror;
6883105197Ssam	}
6884105197Ssam
6885105197Ssam	/* check field of upper layer protocol and address family */
6886105197Ssam	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6887105197Ssam	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6888105197Ssam		struct sadb_address *src0, *dst0;
6889105197Ssam		u_int plen;
6890105197Ssam
6891105197Ssam		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6892105197Ssam		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6893105197Ssam
6894105197Ssam		/* check upper layer protocol */
6895105197Ssam		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6896120585Ssam			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
6897120585Ssam				"mismatched.\n", __func__));
6898181803Sbz			V_pfkeystat.out_invaddr++;
6899105197Ssam			error = EINVAL;
6900105197Ssam			goto senderror;
6901105197Ssam		}
6902105197Ssam
6903105197Ssam		/* check family */
6904105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6905105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
6906120585Ssam			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
6907120585Ssam				__func__));
6908181803Sbz			V_pfkeystat.out_invaddr++;
6909105197Ssam			error = EINVAL;
6910105197Ssam			goto senderror;
6911105197Ssam		}
6912105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6913105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
6914120585Ssam			ipseclog((LOG_DEBUG, "%s: address struct size "
6915120585Ssam				"mismatched.\n", __func__));
6916181803Sbz			V_pfkeystat.out_invaddr++;
6917105197Ssam			error = EINVAL;
6918105197Ssam			goto senderror;
6919105197Ssam		}
6920105197Ssam
6921105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6922105197Ssam		case AF_INET:
6923105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6924105197Ssam			    sizeof(struct sockaddr_in)) {
6925181803Sbz				V_pfkeystat.out_invaddr++;
6926105197Ssam				error = EINVAL;
6927105197Ssam				goto senderror;
6928105197Ssam			}
6929105197Ssam			break;
6930105197Ssam		case AF_INET6:
6931105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6932105197Ssam			    sizeof(struct sockaddr_in6)) {
6933181803Sbz				V_pfkeystat.out_invaddr++;
6934105197Ssam				error = EINVAL;
6935105197Ssam				goto senderror;
6936105197Ssam			}
6937105197Ssam			break;
6938105197Ssam		default:
6939120585Ssam			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
6940120585Ssam				__func__));
6941181803Sbz			V_pfkeystat.out_invaddr++;
6942105197Ssam			error = EAFNOSUPPORT;
6943105197Ssam			goto senderror;
6944105197Ssam		}
6945105197Ssam
6946105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6947105197Ssam		case AF_INET:
6948105197Ssam			plen = sizeof(struct in_addr) << 3;
6949105197Ssam			break;
6950105197Ssam		case AF_INET6:
6951105197Ssam			plen = sizeof(struct in6_addr) << 3;
6952105197Ssam			break;
6953105197Ssam		default:
6954105197Ssam			plen = 0;	/*fool gcc*/
6955105197Ssam			break;
6956105197Ssam		}
6957105197Ssam
6958105197Ssam		/* check max prefix length */
6959105197Ssam		if (src0->sadb_address_prefixlen > plen ||
6960105197Ssam		    dst0->sadb_address_prefixlen > plen) {
6961120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
6962120585Ssam				__func__));
6963181803Sbz			V_pfkeystat.out_invaddr++;
6964105197Ssam			error = EINVAL;
6965105197Ssam			goto senderror;
6966105197Ssam		}
6967105197Ssam
6968105197Ssam		/*
6969105197Ssam		 * prefixlen == 0 is valid because there can be a case when
6970105197Ssam		 * all addresses are matched.
6971105197Ssam		 */
6972105197Ssam	}
6973105197Ssam
6974105197Ssam	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
6975105197Ssam	    key_typesw[msg->sadb_msg_type] == NULL) {
6976181803Sbz		V_pfkeystat.out_invmsgtype++;
6977105197Ssam		error = EINVAL;
6978105197Ssam		goto senderror;
6979105197Ssam	}
6980105197Ssam
6981105197Ssam	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6982105197Ssam
6983105197Ssamsenderror:
6984105197Ssam	msg->sadb_msg_errno = error;
6985105197Ssam	return key_sendup_mbuf(so, m, target);
6986105197Ssam}
6987105197Ssam
6988105197Ssamstatic int
6989105197Ssamkey_senderror(so, m, code)
6990105197Ssam	struct socket *so;
6991105197Ssam	struct mbuf *m;
6992105197Ssam	int code;
6993105197Ssam{
6994105197Ssam	struct sadb_msg *msg;
6995105197Ssam
6996120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6997120585Ssam		("mbuf too small, len %u", m->m_len));
6998105197Ssam
6999105197Ssam	msg = mtod(m, struct sadb_msg *);
7000105197Ssam	msg->sadb_msg_errno = code;
7001105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7002105197Ssam}
7003105197Ssam
7004105197Ssam/*
7005105197Ssam * set the pointer to each header into message buffer.
7006105197Ssam * m will be freed on error.
7007105197Ssam * XXX larger-than-MCLBYTES extension?
7008105197Ssam */
7009105197Ssamstatic int
7010105197Ssamkey_align(m, mhp)
7011105197Ssam	struct mbuf *m;
7012105197Ssam	struct sadb_msghdr *mhp;
7013105197Ssam{
7014183550Szec	INIT_VNET_IPSEC(curvnet);
7015105197Ssam	struct mbuf *n;
7016105197Ssam	struct sadb_ext *ext;
7017105197Ssam	size_t off, end;
7018105197Ssam	int extlen;
7019105197Ssam	int toff;
7020105197Ssam
7021120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7022120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7023120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7024120585Ssam		("mbuf too small, len %u", m->m_len));
7025105197Ssam
7026105197Ssam	/* initialize */
7027105197Ssam	bzero(mhp, sizeof(*mhp));
7028105197Ssam
7029105197Ssam	mhp->msg = mtod(m, struct sadb_msg *);
7030105197Ssam	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7031105197Ssam
7032105197Ssam	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7033105197Ssam	extlen = end;	/*just in case extlen is not updated*/
7034105197Ssam	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7035105197Ssam		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7036105197Ssam		if (!n) {
7037105197Ssam			/* m is already freed */
7038105197Ssam			return ENOBUFS;
7039105197Ssam		}
7040105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7041105197Ssam
7042105197Ssam		/* set pointer */
7043105197Ssam		switch (ext->sadb_ext_type) {
7044105197Ssam		case SADB_EXT_SA:
7045105197Ssam		case SADB_EXT_ADDRESS_SRC:
7046105197Ssam		case SADB_EXT_ADDRESS_DST:
7047105197Ssam		case SADB_EXT_ADDRESS_PROXY:
7048105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
7049105197Ssam		case SADB_EXT_LIFETIME_HARD:
7050105197Ssam		case SADB_EXT_LIFETIME_SOFT:
7051105197Ssam		case SADB_EXT_KEY_AUTH:
7052105197Ssam		case SADB_EXT_KEY_ENCRYPT:
7053105197Ssam		case SADB_EXT_IDENTITY_SRC:
7054105197Ssam		case SADB_EXT_IDENTITY_DST:
7055105197Ssam		case SADB_EXT_SENSITIVITY:
7056105197Ssam		case SADB_EXT_PROPOSAL:
7057105197Ssam		case SADB_EXT_SUPPORTED_AUTH:
7058105197Ssam		case SADB_EXT_SUPPORTED_ENCRYPT:
7059105197Ssam		case SADB_EXT_SPIRANGE:
7060105197Ssam		case SADB_X_EXT_POLICY:
7061105197Ssam		case SADB_X_EXT_SA2:
7062105197Ssam			/* duplicate check */
7063105197Ssam			/*
7064105197Ssam			 * XXX Are there duplication payloads of either
7065105197Ssam			 * KEY_AUTH or KEY_ENCRYPT ?
7066105197Ssam			 */
7067105197Ssam			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7068120585Ssam				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7069120585Ssam					"%u\n", __func__, ext->sadb_ext_type));
7070105197Ssam				m_freem(m);
7071181803Sbz				V_pfkeystat.out_dupext++;
7072105197Ssam				return EINVAL;
7073105197Ssam			}
7074105197Ssam			break;
7075105197Ssam		default:
7076120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7077120585Ssam				__func__, ext->sadb_ext_type));
7078105197Ssam			m_freem(m);
7079181803Sbz			V_pfkeystat.out_invexttype++;
7080105197Ssam			return EINVAL;
7081105197Ssam		}
7082105197Ssam
7083105197Ssam		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7084105197Ssam
7085105197Ssam		if (key_validate_ext(ext, extlen)) {
7086105197Ssam			m_freem(m);
7087181803Sbz			V_pfkeystat.out_invlen++;
7088105197Ssam			return EINVAL;
7089105197Ssam		}
7090105197Ssam
7091105197Ssam		n = m_pulldown(m, off, extlen, &toff);
7092105197Ssam		if (!n) {
7093105197Ssam			/* m is already freed */
7094105197Ssam			return ENOBUFS;
7095105197Ssam		}
7096105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7097105197Ssam
7098105197Ssam		mhp->ext[ext->sadb_ext_type] = ext;
7099105197Ssam		mhp->extoff[ext->sadb_ext_type] = off;
7100105197Ssam		mhp->extlen[ext->sadb_ext_type] = extlen;
7101105197Ssam	}
7102105197Ssam
7103105197Ssam	if (off != end) {
7104105197Ssam		m_freem(m);
7105181803Sbz		V_pfkeystat.out_invlen++;
7106105197Ssam		return EINVAL;
7107105197Ssam	}
7108105197Ssam
7109105197Ssam	return 0;
7110105197Ssam}
7111105197Ssam
7112105197Ssamstatic int
7113105197Ssamkey_validate_ext(ext, len)
7114105197Ssam	const struct sadb_ext *ext;
7115105197Ssam	int len;
7116105197Ssam{
7117105197Ssam	const struct sockaddr *sa;
7118105197Ssam	enum { NONE, ADDR } checktype = NONE;
7119105197Ssam	int baselen = 0;
7120105197Ssam	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7121105197Ssam
7122105197Ssam	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7123105197Ssam		return EINVAL;
7124105197Ssam
7125105197Ssam	/* if it does not match minimum/maximum length, bail */
7126105197Ssam	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7127105197Ssam	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7128105197Ssam		return EINVAL;
7129105197Ssam	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7130105197Ssam		return EINVAL;
7131105197Ssam	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7132105197Ssam		return EINVAL;
7133105197Ssam
7134105197Ssam	/* more checks based on sadb_ext_type XXX need more */
7135105197Ssam	switch (ext->sadb_ext_type) {
7136105197Ssam	case SADB_EXT_ADDRESS_SRC:
7137105197Ssam	case SADB_EXT_ADDRESS_DST:
7138105197Ssam	case SADB_EXT_ADDRESS_PROXY:
7139105197Ssam		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7140105197Ssam		checktype = ADDR;
7141105197Ssam		break;
7142105197Ssam	case SADB_EXT_IDENTITY_SRC:
7143105197Ssam	case SADB_EXT_IDENTITY_DST:
7144105197Ssam		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7145105197Ssam		    SADB_X_IDENTTYPE_ADDR) {
7146105197Ssam			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7147105197Ssam			checktype = ADDR;
7148105197Ssam		} else
7149105197Ssam			checktype = NONE;
7150105197Ssam		break;
7151105197Ssam	default:
7152105197Ssam		checktype = NONE;
7153105197Ssam		break;
7154105197Ssam	}
7155105197Ssam
7156105197Ssam	switch (checktype) {
7157105197Ssam	case NONE:
7158105197Ssam		break;
7159105197Ssam	case ADDR:
7160105197Ssam		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7161105197Ssam		if (len < baselen + sal)
7162105197Ssam			return EINVAL;
7163105197Ssam		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7164105197Ssam			return EINVAL;
7165105197Ssam		break;
7166105197Ssam	}
7167105197Ssam
7168105197Ssam	return 0;
7169105197Ssam}
7170105197Ssam
7171105197Ssamvoid
7172180086Sjuliankey_init(void)
7173105197Ssam{
7174183550Szec	INIT_VNET_IPSEC(curvnet);
7175105197Ssam	int i;
7176105197Ssam
7177185088Szec	V_key_debug_level = 0;
7178185088Szec	V_key_spi_trycnt = 1000;
7179185088Szec	V_key_spi_minval = 0x100;
7180185088Szec	V_key_spi_maxval = 0x0fffffff;	/* XXX */
7181185088Szec	V_policy_id = 0;
7182185088Szec	V_key_int_random = 60;		/*interval to initialize randseed,1(m)*/
7183185088Szec	V_key_larval_lifetime = 30;	/* interval to expire acquiring, 30(s)*/
7184185088Szec	V_key_blockacq_count = 10;	/* counter for blocking SADB_ACQUIRE.*/
7185185088Szec	V_key_blockacq_lifetime = 20;	/* lifetime for blocking SADB_ACQUIRE.*/
7186185088Szec	V_key_preferred_oldsa = 1;	/* preferred old sa rather than new sa*/
7187185088Szec
7188185088Szec	V_acq_seq = 0;
7189185088Szec
7190185088Szec	V_ipsec_esp_keymin = 256;
7191185088Szec	V_ipsec_esp_auth = 0;
7192185088Szec	V_ipsec_ah_keymin = 128;
7193185088Szec
7194119643Ssam	for (i = 0; i < IPSEC_DIR_MAX; i++)
7195181803Sbz		LIST_INIT(&V_sptree[i]);
7196105197Ssam
7197181803Sbz	LIST_INIT(&V_sahtree);
7198105197Ssam
7199119643Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7200181803Sbz		LIST_INIT(&V_regtree[i]);
7201105197Ssam
7202181803Sbz	LIST_INIT(&V_acqtree);
7203181803Sbz	LIST_INIT(&V_spacqtree);
7204105197Ssam
7205105197Ssam	/* system default */
7206181803Sbz	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7207181803Sbz	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7208105197Ssam
7209190787Szec	if (!IS_DEFAULT_VNET(curvnet))
7210190787Szec		return;
7211190787Szec
7212190787Szec	SPTREE_LOCK_INIT();
7213190787Szec	REGTREE_LOCK_INIT();
7214190787Szec	SAHTREE_LOCK_INIT();
7215190787Szec	ACQ_LOCK_INIT();
7216190787Szec	SPACQ_LOCK_INIT();
7217190787Szec
7218105197Ssam#ifndef IPSEC_DEBUG2
7219105197Ssam	timeout((void *)key_timehandler, (void *)0, hz);
7220105197Ssam#endif /*IPSEC_DEBUG2*/
7221105197Ssam
7222105197Ssam	/* initialize key statistics */
7223105197Ssam	keystat.getspi_count = 1;
7224105197Ssam
7225177173Sbz	printf("IPsec: Initialized Security Association Processing.\n");
7226193731Szec}
7227105197Ssam
7228193731Szec#ifdef VIMAGE
7229193731Szecvoid
7230193731Szeckey_destroy(void)
7231193731Szec{
7232193731Szec	INIT_VNET_IPSEC(curvnet);
7233193731Szec	struct secpolicy *sp, *nextsp;
7234193731Szec	struct secspacq *acq, *nextacq;
7235193731Szec	struct secashead *sah, *nextsah;
7236193731Szec	struct secreg *reg;
7237193731Szec	int i;
7238193731Szec
7239193731Szec	SPTREE_LOCK();
7240193731Szec	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7241193731Szec		for (sp = LIST_FIRST(&V_sptree[i]);
7242193731Szec		    sp != NULL; sp = nextsp) {
7243193731Szec			nextsp = LIST_NEXT(sp, chain);
7244193731Szec			if (__LIST_CHAINED(sp)) {
7245193731Szec				LIST_REMOVE(sp, chain);
7246193731Szec				free(sp, M_IPSEC_SP);
7247193731Szec			}
7248193731Szec		}
7249193731Szec	}
7250193731Szec	SPTREE_UNLOCK();
7251193731Szec
7252193731Szec	SAHTREE_LOCK();
7253193731Szec	for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7254193731Szec		nextsah = LIST_NEXT(sah, chain);
7255193731Szec		if (__LIST_CHAINED(sah)) {
7256193731Szec			LIST_REMOVE(sah, chain);
7257193731Szec			free(sah, M_IPSEC_SAH);
7258193731Szec		}
7259193731Szec	}
7260193731Szec	SAHTREE_UNLOCK();
7261193731Szec
7262193731Szec	REGTREE_LOCK();
7263193731Szec	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7264193731Szec		LIST_FOREACH(reg, &V_regtree[i], chain) {
7265193731Szec			if (__LIST_CHAINED(reg)) {
7266193731Szec				LIST_REMOVE(reg, chain);
7267193731Szec				free(reg, M_IPSEC_SAR);
7268193731Szec				break;
7269193731Szec			}
7270193731Szec		}
7271193731Szec	}
7272193731Szec	REGTREE_UNLOCK();
7273193731Szec
7274193731Szec	ACQ_LOCK();
7275193731Szec	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
7276193731Szec		nextacq = LIST_NEXT(acq, chain);
7277193731Szec		if (__LIST_CHAINED(acq)) {
7278193731Szec			LIST_REMOVE(acq, chain);
7279193731Szec			free(acq, M_IPSEC_SAQ);
7280193731Szec		}
7281193731Szec	}
7282193731Szec	ACQ_UNLOCK();
7283193731Szec
7284193731Szec	SPACQ_LOCK();
7285193731Szec	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
7286193731Szec		nextacq = LIST_NEXT(acq, chain);
7287193731Szec		if (__LIST_CHAINED(acq)) {
7288193731Szec			LIST_REMOVE(acq, chain);
7289193731Szec			free(acq, M_IPSEC_SAQ);
7290193731Szec		}
7291193731Szec	}
7292193731Szec	SPACQ_UNLOCK();
7293105197Ssam}
7294193731Szec#endif
7295105197Ssam
7296105197Ssam/*
7297105197Ssam * XXX: maybe This function is called after INBOUND IPsec processing.
7298105197Ssam *
7299105197Ssam * Special check for tunnel-mode packets.
7300105197Ssam * We must make some checks for consistency between inner and outer IP header.
7301105197Ssam *
7302105197Ssam * xxx more checks to be provided
7303105197Ssam */
7304105197Ssamint
7305105197Ssamkey_checktunnelsanity(sav, family, src, dst)
7306105197Ssam	struct secasvar *sav;
7307105197Ssam	u_int family;
7308105197Ssam	caddr_t src;
7309105197Ssam	caddr_t dst;
7310105197Ssam{
7311120585Ssam	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7312105197Ssam
7313105197Ssam	/* XXX: check inner IP header */
7314105197Ssam
7315105197Ssam	return 1;
7316105197Ssam}
7317105197Ssam
7318105197Ssam/* record data transfer on SA, and update timestamps */
7319105197Ssamvoid
7320105197Ssamkey_sa_recordxfer(sav, m)
7321105197Ssam	struct secasvar *sav;
7322105197Ssam	struct mbuf *m;
7323105197Ssam{
7324120585Ssam	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7325120585Ssam	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7326105197Ssam	if (!sav->lft_c)
7327105197Ssam		return;
7328105197Ssam
7329105197Ssam	/*
7330105197Ssam	 * XXX Currently, there is a difference of bytes size
7331105197Ssam	 * between inbound and outbound processing.
7332105197Ssam	 */
7333157123Sgnn	sav->lft_c->bytes += m->m_pkthdr.len;
7334105197Ssam	/* to check bytes lifetime is done in key_timehandler(). */
7335105197Ssam
7336105197Ssam	/*
7337105197Ssam	 * We use the number of packets as the unit of
7338157123Sgnn	 * allocations.  We increment the variable
7339105197Ssam	 * whenever {esp,ah}_{in,out}put is called.
7340105197Ssam	 */
7341157123Sgnn	sav->lft_c->allocations++;
7342105197Ssam	/* XXX check for expires? */
7343105197Ssam
7344105197Ssam	/*
7345157123Sgnn	 * NOTE: We record CURRENT usetime by using wall clock,
7346105197Ssam	 * in seconds.  HARD and SOFT lifetime are measured by the time
7347157123Sgnn	 * difference (again in seconds) from usetime.
7348105197Ssam	 *
7349105197Ssam	 *	usetime
7350105197Ssam	 *	v     expire   expire
7351105197Ssam	 * -----+-----+--------+---> t
7352105197Ssam	 *	<--------------> HARD
7353105197Ssam	 *	<-----> SOFT
7354105197Ssam	 */
7355157123Sgnn	sav->lft_c->usetime = time_second;
7356105197Ssam	/* XXX check for expires? */
7357105197Ssam
7358105197Ssam	return;
7359105197Ssam}
7360105197Ssam
7361105197Ssam/* dumb version */
7362105197Ssamvoid
7363105197Ssamkey_sa_routechange(dst)
7364105197Ssam	struct sockaddr *dst;
7365105197Ssam{
7366183550Szec	INIT_VNET_IPSEC(curvnet);
7367105197Ssam	struct secashead *sah;
7368105197Ssam	struct route *ro;
7369105197Ssam
7370120585Ssam	SAHTREE_LOCK();
7371181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7372105197Ssam		ro = &sah->sa_route;
7373105197Ssam		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7374105197Ssam		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7375105197Ssam			RTFREE(ro->ro_rt);
7376105197Ssam			ro->ro_rt = (struct rtentry *)NULL;
7377105197Ssam		}
7378105197Ssam	}
7379120585Ssam	SAHTREE_UNLOCK();
7380105197Ssam}
7381105197Ssam
7382105197Ssamstatic void
7383189004Srdivackykey_sa_chgstate(struct secasvar *sav, u_int8_t state)
7384105197Ssam{
7385120585Ssam	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7386120585Ssam	SAHTREE_LOCK_ASSERT();
7387105197Ssam
7388119643Ssam	if (sav->state != state) {
7389119643Ssam		if (__LIST_CHAINED(sav))
7390119643Ssam			LIST_REMOVE(sav, chain);
7391119643Ssam		sav->state = state;
7392119643Ssam		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7393119643Ssam	}
7394105197Ssam}
7395105197Ssam
7396105197Ssamvoid
7397105197Ssamkey_sa_stir_iv(sav)
7398105197Ssam	struct secasvar *sav;
7399105197Ssam{
7400105197Ssam
7401120585Ssam	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7402105197Ssam	key_randomfill(sav->iv, sav->ivlen);
7403105197Ssam}
7404105197Ssam
7405105197Ssam/* XXX too much? */
7406105197Ssamstatic struct mbuf *
7407105197Ssamkey_alloc_mbuf(l)
7408105197Ssam	int l;
7409105197Ssam{
7410105197Ssam	struct mbuf *m = NULL, *n;
7411105197Ssam	int len, t;
7412105197Ssam
7413105197Ssam	len = l;
7414105197Ssam	while (len > 0) {
7415111119Simp		MGET(n, M_DONTWAIT, MT_DATA);
7416105197Ssam		if (n && len > MLEN)
7417111119Simp			MCLGET(n, M_DONTWAIT);
7418105197Ssam		if (!n) {
7419105197Ssam			m_freem(m);
7420105197Ssam			return NULL;
7421105197Ssam		}
7422105197Ssam
7423105197Ssam		n->m_next = NULL;
7424105197Ssam		n->m_len = 0;
7425105197Ssam		n->m_len = M_TRAILINGSPACE(n);
7426105197Ssam		/* use the bottom of mbuf, hoping we can prepend afterwards */
7427105197Ssam		if (n->m_len > len) {
7428105197Ssam			t = (n->m_len - len) & ~(sizeof(long) - 1);
7429105197Ssam			n->m_data += t;
7430105197Ssam			n->m_len = len;
7431105197Ssam		}
7432105197Ssam
7433105197Ssam		len -= n->m_len;
7434105197Ssam
7435105197Ssam		if (m)
7436105197Ssam			m_cat(m, n);
7437105197Ssam		else
7438105197Ssam			m = n;
7439105197Ssam	}
7440105197Ssam
7441105197Ssam	return m;
7442105197Ssam}
7443157123Sgnn
7444157123Sgnn/*
7445157123Sgnn * Take one of the kernel's security keys and convert it into a PF_KEY
7446157123Sgnn * structure within an mbuf, suitable for sending up to a waiting
7447157123Sgnn * application in user land.
7448157123Sgnn *
7449157123Sgnn * IN:
7450157123Sgnn *    src: A pointer to a kernel security key.
7451157123Sgnn *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
7452157123Sgnn * OUT:
7453157123Sgnn *    a valid mbuf or NULL indicating an error
7454157123Sgnn *
7455157123Sgnn */
7456157123Sgnn
7457157123Sgnnstatic struct mbuf *
7458157123Sgnnkey_setkey(struct seckey *src, u_int16_t exttype)
7459157123Sgnn{
7460157123Sgnn	struct mbuf *m;
7461157123Sgnn	struct sadb_key *p;
7462170799Sbz	int len;
7463157123Sgnn
7464157123Sgnn	if (src == NULL)
7465157123Sgnn		return NULL;
7466157123Sgnn
7467170799Sbz	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
7468157123Sgnn	m = key_alloc_mbuf(len);
7469157123Sgnn	if (m == NULL)
7470157123Sgnn		return NULL;
7471157123Sgnn	p = mtod(m, struct sadb_key *);
7472157123Sgnn	bzero(p, len);
7473157123Sgnn	p->sadb_key_len = PFKEY_UNIT64(len);
7474157123Sgnn	p->sadb_key_exttype = exttype;
7475157123Sgnn	p->sadb_key_bits = src->bits;
7476157123Sgnn	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
7477157123Sgnn
7478157123Sgnn	return m;
7479157123Sgnn}
7480157123Sgnn
7481157123Sgnn/*
7482157123Sgnn * Take one of the kernel's lifetime data structures and convert it
7483157123Sgnn * into a PF_KEY structure within an mbuf, suitable for sending up to
7484157123Sgnn * a waiting application in user land.
7485157123Sgnn *
7486157123Sgnn * IN:
7487157123Sgnn *    src: A pointer to a kernel lifetime structure.
7488157123Sgnn *    exttype: Which type of lifetime this is. Refer to the PF_KEY
7489157123Sgnn *             data structures for more information.
7490157123Sgnn * OUT:
7491157123Sgnn *    a valid mbuf or NULL indicating an error
7492157123Sgnn *
7493157123Sgnn */
7494157123Sgnn
7495157123Sgnnstatic struct mbuf *
7496157123Sgnnkey_setlifetime(struct seclifetime *src, u_int16_t exttype)
7497157123Sgnn{
7498157123Sgnn	struct mbuf *m = NULL;
7499157123Sgnn	struct sadb_lifetime *p;
7500157123Sgnn	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
7501157123Sgnn
7502157123Sgnn	if (src == NULL)
7503157123Sgnn		return NULL;
7504157123Sgnn
7505157123Sgnn	m = key_alloc_mbuf(len);
7506157123Sgnn	if (m == NULL)
7507157123Sgnn		return m;
7508157123Sgnn	p = mtod(m, struct sadb_lifetime *);
7509157123Sgnn
7510157123Sgnn	bzero(p, len);
7511157123Sgnn	p->sadb_lifetime_len = PFKEY_UNIT64(len);
7512157123Sgnn	p->sadb_lifetime_exttype = exttype;
7513157123Sgnn	p->sadb_lifetime_allocations = src->allocations;
7514157123Sgnn	p->sadb_lifetime_bytes = src->bytes;
7515157123Sgnn	p->sadb_lifetime_addtime = src->addtime;
7516157123Sgnn	p->sadb_lifetime_usetime = src->usetime;
7517157123Sgnn
7518157123Sgnn	return m;
7519157123Sgnn
7520157123Sgnn}
7521