key.c revision 185348
1105197Ssam/*	$FreeBSD: head/sys/netipsec/key.c 185348 2008-11-26 22:32:07Z 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>
78105197Ssam#endif
79105197Ssam#ifdef INET6
80105197Ssam#include <netinet6/in6_pcb.h>
81105197Ssam#endif /* INET6 */
82105197Ssam
83105197Ssam#include <net/pfkeyv2.h>
84105197Ssam#include <netipsec/keydb.h>
85105197Ssam#include <netipsec/key.h>
86105197Ssam#include <netipsec/keysock.h>
87105197Ssam#include <netipsec/key_debug.h>
88105197Ssam
89105197Ssam#include <netipsec/ipsec.h>
90105197Ssam#ifdef INET6
91105197Ssam#include <netipsec/ipsec6.h>
92105197Ssam#endif
93105197Ssam
94105197Ssam#include <netipsec/xform.h>
95105197Ssam
96105197Ssam#include <machine/stdarg.h>
97105197Ssam
98105197Ssam/* randomness */
99105197Ssam#include <sys/random.h>
100181803Sbz#include <sys/vimage.h>
101105197Ssam
102105197Ssam#define FULLMASK	0xff
103105197Ssam#define	_BITS(bytes)	((bytes) << 3)
104105197Ssam
105105197Ssam/*
106105197Ssam * Note on SA reference counting:
107105197Ssam * - SAs that are not in DEAD state will have (total external reference + 1)
108105197Ssam *   following value in reference count field.  they cannot be freed and are
109105197Ssam *   referenced from SA header.
110105197Ssam * - SAs that are in DEAD state will have (total external reference)
111105197Ssam *   in reference count field.  they are ready to be freed.  reference from
112105197Ssam *   SA header will be removed in key_delsav(), when the reference count
113105197Ssam *   field hits 0 (= no external reference other than from SA header.
114105197Ssam */
115105197Ssam
116185088Szec#ifdef VIMAGE_GLOBALS
117185088Szecu_int32_t key_debug_level;
118185088Szecstatic u_int key_spi_trycnt;
119185088Szecstatic u_int32_t key_spi_minval;
120185088Szecstatic u_int32_t key_spi_maxval;
121185088Szecstatic u_int32_t policy_id;
122185088Szecstatic u_int key_int_random;
123185088Szecstatic u_int key_larval_lifetime;
124185088Szecstatic int key_blockacq_count;
125185088Szecstatic int key_blockacq_lifetime;
126185088Szecstatic int key_preferred_oldsa;
127105197Ssam
128185088Szecstatic u_int32_t acq_seq;
129105197Ssam
130185088Szecstatic int ipsec_esp_keymin;
131185088Szecstatic int ipsec_esp_auth;
132185088Szecstatic int ipsec_ah_keymin;
133185088Szec
134105197Ssamstatic LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];	/* SPD */
135185088Szecstatic LIST_HEAD(_sahtree, secashead) sahtree;			/* SAD */
136185088Szecstatic LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
137185088Szecstatic LIST_HEAD(_acqtree, secacq) acqtree;		/* acquiring list */
138185088Szecstatic LIST_HEAD(_spacqtree, secspacq) spacqtree;	/* SP acquiring list */
139185088Szec#endif /* VIMAGE_GLOBALS */
140185088Szec
141119643Ssamstatic struct mtx sptree_lock;
142120585Ssam#define	SPTREE_LOCK_INIT() \
143120585Ssam	mtx_init(&sptree_lock, "sptree", \
144120585Ssam		"fast ipsec security policy database", MTX_DEF)
145120585Ssam#define	SPTREE_LOCK_DESTROY()	mtx_destroy(&sptree_lock)
146120585Ssam#define	SPTREE_LOCK()		mtx_lock(&sptree_lock)
147120585Ssam#define	SPTREE_UNLOCK()	mtx_unlock(&sptree_lock)
148120585Ssam#define	SPTREE_LOCK_ASSERT()	mtx_assert(&sptree_lock, MA_OWNED)
149120585Ssam
150119643Ssamstatic struct mtx sahtree_lock;
151120585Ssam#define	SAHTREE_LOCK_INIT() \
152120585Ssam	mtx_init(&sahtree_lock, "sahtree", \
153120585Ssam		"fast ipsec security association database", MTX_DEF)
154120585Ssam#define	SAHTREE_LOCK_DESTROY()	mtx_destroy(&sahtree_lock)
155120585Ssam#define	SAHTREE_LOCK()		mtx_lock(&sahtree_lock)
156120585Ssam#define	SAHTREE_UNLOCK()	mtx_unlock(&sahtree_lock)
157120585Ssam#define	SAHTREE_LOCK_ASSERT()	mtx_assert(&sahtree_lock, MA_OWNED)
158120585Ssam
159119643Ssam							/* registed list */
160119643Ssamstatic struct mtx regtree_lock;
161120585Ssam#define	REGTREE_LOCK_INIT() \
162120585Ssam	mtx_init(&regtree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
163120585Ssam#define	REGTREE_LOCK_DESTROY()	mtx_destroy(&regtree_lock)
164120585Ssam#define	REGTREE_LOCK()		mtx_lock(&regtree_lock)
165120585Ssam#define	REGTREE_UNLOCK()	mtx_unlock(&regtree_lock)
166120585Ssam#define	REGTREE_LOCK_ASSERT()	mtx_assert(&regtree_lock, MA_OWNED)
167120585Ssam
168119643Ssamstatic struct mtx acq_lock;
169120585Ssam#define	ACQ_LOCK_INIT() \
170120585Ssam	mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
171120585Ssam#define	ACQ_LOCK_DESTROY()	mtx_destroy(&acq_lock)
172120585Ssam#define	ACQ_LOCK()		mtx_lock(&acq_lock)
173120585Ssam#define	ACQ_UNLOCK()		mtx_unlock(&acq_lock)
174120585Ssam#define	ACQ_LOCK_ASSERT()	mtx_assert(&acq_lock, MA_OWNED)
175120585Ssam
176119643Ssamstatic struct mtx spacq_lock;
177120585Ssam#define	SPACQ_LOCK_INIT() \
178120585Ssam	mtx_init(&spacq_lock, "spacqtree", \
179120585Ssam		"fast ipsec security policy acquire list", MTX_DEF)
180120585Ssam#define	SPACQ_LOCK_DESTROY()	mtx_destroy(&spacq_lock)
181120585Ssam#define	SPACQ_LOCK()		mtx_lock(&spacq_lock)
182120585Ssam#define	SPACQ_UNLOCK()		mtx_unlock(&spacq_lock)
183120585Ssam#define	SPACQ_LOCK_ASSERT()	mtx_assert(&spacq_lock, MA_OWNED)
184105197Ssam
185105197Ssam/* search order for SAs */
186128856Ssamstatic const u_int saorder_state_valid_prefer_old[] = {
187105197Ssam	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
188105197Ssam};
189128856Ssamstatic const u_int saorder_state_valid_prefer_new[] = {
190128856Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
191128856Ssam};
192185348Szecstatic const u_int saorder_state_alive[] = {
193105197Ssam	/* except DEAD */
194105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
195105197Ssam};
196185348Szecstatic const u_int saorder_state_any[] = {
197105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
198105197Ssam	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
199105197Ssam};
200105197Ssam
201105197Ssamstatic const int minsize[] = {
202105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
203105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
204105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
205105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
206105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
207105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
208105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
209105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
210105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
211105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
212105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
213105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
214105197Ssam	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
215105197Ssam	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
216105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
217105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
218105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
219105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
220105197Ssam	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
221105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
222105197Ssam};
223105197Ssamstatic const int maxsize[] = {
224105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
225105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
226105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
227105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
228105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
229105197Ssam	0,				/* SADB_EXT_ADDRESS_SRC */
230105197Ssam	0,				/* SADB_EXT_ADDRESS_DST */
231105197Ssam	0,				/* SADB_EXT_ADDRESS_PROXY */
232105197Ssam	0,				/* SADB_EXT_KEY_AUTH */
233105197Ssam	0,				/* SADB_EXT_KEY_ENCRYPT */
234105197Ssam	0,				/* SADB_EXT_IDENTITY_SRC */
235105197Ssam	0,				/* SADB_EXT_IDENTITY_DST */
236105197Ssam	0,				/* SADB_EXT_SENSITIVITY */
237105197Ssam	0,				/* SADB_EXT_PROPOSAL */
238105197Ssam	0,				/* SADB_EXT_SUPPORTED_AUTH */
239105197Ssam	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
240105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
241105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
242105197Ssam	0,				/* SADB_X_EXT_POLICY */
243105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
244105197Ssam};
245105197Ssam
246105197Ssam#ifdef SYSCTL_DECL
247105197SsamSYSCTL_DECL(_net_key);
248105197Ssam#endif
249105197Ssam
250183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec,_net_key, KEYCTL_DEBUG_LEVEL,	debug,
251183550Szec	CTLFLAG_RW, key_debug_level,	0,	"");
252105197Ssam
253105197Ssam/* max count of trial for the decision of spi value */
254183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec,_net_key, KEYCTL_SPI_TRY, spi_trycnt,
255183550Szec	CTLFLAG_RW, key_spi_trycnt,	0,	"");
256105197Ssam
257105197Ssam/* minimum spi value to allocate automatically. */
258183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_SPI_MIN_VALUE,
259183550Szec	spi_minval,	CTLFLAG_RW, key_spi_minval,	0,	"");
260105197Ssam
261105197Ssam/* maximun spi value to allocate automatically. */
262183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_SPI_MAX_VALUE,
263183550Szec	spi_maxval,	CTLFLAG_RW, key_spi_maxval,	0,	"");
264105197Ssam
265105197Ssam/* interval to initialize randseed */
266183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_RANDOM_INT,
267183550Szec	int_random,	CTLFLAG_RW, key_int_random,	0,	"");
268105197Ssam
269105197Ssam/* lifetime for larval SA */
270183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_LARVAL_LIFETIME,
271183550Szec	larval_lifetime, CTLFLAG_RW, key_larval_lifetime,	0,	"");
272105197Ssam
273105197Ssam/* counter for blocking to send SADB_ACQUIRE to IKEd */
274183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_BLOCKACQ_COUNT,
275183550Szec	blockacq_count,	CTLFLAG_RW, key_blockacq_count,	0,	"");
276105197Ssam
277105197Ssam/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
278183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_BLOCKACQ_LIFETIME,
279183550Szec	blockacq_lifetime, CTLFLAG_RW, key_blockacq_lifetime,	0, "");
280105197Ssam
281105197Ssam/* ESP auth */
282183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_ESP_AUTH,	esp_auth,
283183550Szec	CTLFLAG_RW, ipsec_esp_auth,	0,	"");
284105197Ssam
285105197Ssam/* minimum ESP key length */
286183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_ESP_KEYMIN,
287183550Szec	esp_keymin, CTLFLAG_RW, ipsec_esp_keymin,	0,	"");
288105197Ssam
289105197Ssam/* minimum AH key length */
290183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_AH_KEYMIN,	ah_keymin,
291183550Szec	CTLFLAG_RW, ipsec_ah_keymin,	0,	"");
292105197Ssam
293105197Ssam/* perfered old SA rather than new SA */
294183550SzecSYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_PREFERED_OLDSA,
295183550Szec	preferred_oldsa, CTLFLAG_RW, key_preferred_oldsa,	0,	"");
296105197Ssam
297105197Ssam#define __LIST_CHAINED(elm) \
298105197Ssam	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
299105197Ssam#define LIST_INSERT_TAIL(head, elm, type, field) \
300105197Ssamdo {\
301105197Ssam	struct type *curelm = LIST_FIRST(head); \
302105197Ssam	if (curelm == NULL) {\
303105197Ssam		LIST_INSERT_HEAD(head, elm, field); \
304105197Ssam	} else { \
305105197Ssam		while (LIST_NEXT(curelm, field)) \
306105197Ssam			curelm = LIST_NEXT(curelm, field);\
307105197Ssam		LIST_INSERT_AFTER(curelm, elm, field);\
308105197Ssam	}\
309105197Ssam} while (0)
310105197Ssam
311105197Ssam#define KEY_CHKSASTATE(head, sav, name) \
312105197Ssamdo { \
313105197Ssam	if ((head) != (sav)) {						\
314105197Ssam		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
315105197Ssam			(name), (head), (sav)));			\
316105197Ssam		continue;						\
317105197Ssam	}								\
318105197Ssam} while (0)
319105197Ssam
320105197Ssam#define KEY_CHKSPDIR(head, sp, name) \
321105197Ssamdo { \
322105197Ssam	if ((head) != (sp)) {						\
323105197Ssam		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
324105197Ssam			"anyway continue.\n",				\
325105197Ssam			(name), (head), (sp)));				\
326105197Ssam	}								\
327105197Ssam} while (0)
328105197Ssam
329119643SsamMALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
330119643SsamMALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
331119643SsamMALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
332119643SsamMALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
333119643SsamMALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
334119643SsamMALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
335119643SsamMALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
336105197Ssam
337105197Ssam/*
338105197Ssam * set parameters into secpolicyindex buffer.
339105197Ssam * Must allocate secpolicyindex buffer passed to this function.
340105197Ssam */
341105197Ssam#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
342105197Ssamdo { \
343105197Ssam	bzero((idx), sizeof(struct secpolicyindex));                         \
344105197Ssam	(idx)->dir = (_dir);                                                 \
345105197Ssam	(idx)->prefs = (ps);                                                 \
346105197Ssam	(idx)->prefd = (pd);                                                 \
347105197Ssam	(idx)->ul_proto = (ulp);                                             \
348105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
349105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
350105197Ssam} while (0)
351105197Ssam
352105197Ssam/*
353105197Ssam * set parameters into secasindex buffer.
354105197Ssam * Must allocate secasindex buffer before calling this function.
355105197Ssam */
356105197Ssam#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
357105197Ssamdo { \
358105197Ssam	bzero((idx), sizeof(struct secasindex));                             \
359105197Ssam	(idx)->proto = (p);                                                  \
360105197Ssam	(idx)->mode = (m);                                                   \
361105197Ssam	(idx)->reqid = (r);                                                  \
362105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
363105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
364105197Ssam} while (0)
365105197Ssam
366105197Ssam/* key statistics */
367105197Ssamstruct _keystat {
368105197Ssam	u_long getspi_count; /* the avarage of count to try to get new SPI */
369105197Ssam} keystat;
370105197Ssam
371105197Ssamstruct sadb_msghdr {
372105197Ssam	struct sadb_msg *msg;
373105197Ssam	struct sadb_ext *ext[SADB_EXT_MAX + 1];
374105197Ssam	int extoff[SADB_EXT_MAX + 1];
375105197Ssam	int extlen[SADB_EXT_MAX + 1];
376105197Ssam};
377105197Ssam
378105197Ssamstatic struct secasvar *key_allocsa_policy __P((const struct secasindex *));
379105197Ssamstatic void key_freesp_so __P((struct secpolicy **));
380105197Ssamstatic struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
381105197Ssamstatic void key_delsp __P((struct secpolicy *));
382105197Ssamstatic struct secpolicy *key_getsp __P((struct secpolicyindex *));
383119643Ssamstatic void _key_delsp(struct secpolicy *sp);
384105197Ssamstatic struct secpolicy *key_getspbyid __P((u_int32_t));
385105197Ssamstatic u_int32_t key_newreqid __P((void));
386105197Ssamstatic struct mbuf *key_gather_mbuf __P((struct mbuf *,
387105197Ssam	const struct sadb_msghdr *, int, int, ...));
388105197Ssamstatic int key_spdadd __P((struct socket *, struct mbuf *,
389105197Ssam	const struct sadb_msghdr *));
390105197Ssamstatic u_int32_t key_getnewspid __P((void));
391105197Ssamstatic int key_spddelete __P((struct socket *, struct mbuf *,
392105197Ssam	const struct sadb_msghdr *));
393105197Ssamstatic int key_spddelete2 __P((struct socket *, struct mbuf *,
394105197Ssam	const struct sadb_msghdr *));
395105197Ssamstatic int key_spdget __P((struct socket *, struct mbuf *,
396105197Ssam	const struct sadb_msghdr *));
397105197Ssamstatic int key_spdflush __P((struct socket *, struct mbuf *,
398105197Ssam	const struct sadb_msghdr *));
399105197Ssamstatic int key_spddump __P((struct socket *, struct mbuf *,
400105197Ssam	const struct sadb_msghdr *));
401105197Ssamstatic struct mbuf *key_setdumpsp __P((struct secpolicy *,
402105197Ssam	u_int8_t, u_int32_t, u_int32_t));
403105197Ssamstatic u_int key_getspreqmsglen __P((struct secpolicy *));
404105197Ssamstatic int key_spdexpire __P((struct secpolicy *));
405105197Ssamstatic struct secashead *key_newsah __P((struct secasindex *));
406105197Ssamstatic void key_delsah __P((struct secashead *));
407105197Ssamstatic struct secasvar *key_newsav __P((struct mbuf *,
408105197Ssam	const struct sadb_msghdr *, struct secashead *, int *,
409105197Ssam	const char*, int));
410105197Ssam#define	KEY_NEWSAV(m, sadb, sah, e)				\
411105197Ssam	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
412105197Ssamstatic void key_delsav __P((struct secasvar *));
413105197Ssamstatic struct secashead *key_getsah __P((struct secasindex *));
414105197Ssamstatic struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
415105197Ssamstatic struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
416105197Ssamstatic int key_setsaval __P((struct secasvar *, struct mbuf *,
417105197Ssam	const struct sadb_msghdr *));
418105197Ssamstatic int key_mature __P((struct secasvar *));
419105197Ssamstatic struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
420105197Ssam	u_int8_t, u_int32_t, u_int32_t));
421105197Ssamstatic struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
422105197Ssam	u_int32_t, pid_t, u_int16_t));
423105197Ssamstatic struct mbuf *key_setsadbsa __P((struct secasvar *));
424105197Ssamstatic struct mbuf *key_setsadbaddr __P((u_int16_t,
425105197Ssam	const struct sockaddr *, u_int8_t, u_int16_t));
426105197Ssamstatic struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
427105197Ssamstatic struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
428105197Ssam	u_int32_t));
429157123Sgnnstatic struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
430157123Sgnn				     struct malloc_type *);
431157123Sgnnstatic struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
432157123Sgnn					    struct malloc_type *type);
433105197Ssam#ifdef INET6
434105197Ssamstatic int key_ismyaddr6 __P((struct sockaddr_in6 *));
435105197Ssam#endif
436105197Ssam
437105197Ssam/* flags for key_cmpsaidx() */
438105197Ssam#define CMP_HEAD	1	/* protocol, addresses. */
439105197Ssam#define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
440105197Ssam#define CMP_REQID	3	/* additionally HEAD, reaid. */
441105197Ssam#define CMP_EXACTLY	4	/* all elements. */
442105197Ssamstatic int key_cmpsaidx
443105197Ssam	__P((const struct secasindex *, const struct secasindex *, int));
444105197Ssam
445105197Ssamstatic int key_cmpspidx_exactly
446105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
447105197Ssamstatic int key_cmpspidx_withmask
448105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
449105197Ssamstatic int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
450105197Ssamstatic int key_bbcmp __P((const void *, const void *, u_int));
451105197Ssamstatic u_int16_t key_satype2proto __P((u_int8_t));
452105197Ssamstatic u_int8_t key_proto2satype __P((u_int16_t));
453105197Ssam
454105197Ssamstatic int key_getspi __P((struct socket *, struct mbuf *,
455105197Ssam	const struct sadb_msghdr *));
456105197Ssamstatic u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
457105197Ssam					struct secasindex *));
458105197Ssamstatic int key_update __P((struct socket *, struct mbuf *,
459105197Ssam	const struct sadb_msghdr *));
460105197Ssam#ifdef IPSEC_DOSEQCHECK
461105197Ssamstatic struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
462105197Ssam#endif
463105197Ssamstatic int key_add __P((struct socket *, struct mbuf *,
464105197Ssam	const struct sadb_msghdr *));
465105197Ssamstatic int key_setident __P((struct secashead *, struct mbuf *,
466105197Ssam	const struct sadb_msghdr *));
467105197Ssamstatic struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
468105197Ssam	const struct sadb_msghdr *));
469105197Ssamstatic int key_delete __P((struct socket *, struct mbuf *,
470105197Ssam	const struct sadb_msghdr *));
471105197Ssamstatic int key_get __P((struct socket *, struct mbuf *,
472105197Ssam	const struct sadb_msghdr *));
473105197Ssam
474105197Ssamstatic void key_getcomb_setlifetime __P((struct sadb_comb *));
475105197Ssamstatic struct mbuf *key_getcomb_esp __P((void));
476105197Ssamstatic struct mbuf *key_getcomb_ah __P((void));
477105197Ssamstatic struct mbuf *key_getcomb_ipcomp __P((void));
478105197Ssamstatic struct mbuf *key_getprop __P((const struct secasindex *));
479105197Ssam
480105197Ssamstatic int key_acquire __P((const struct secasindex *, struct secpolicy *));
481105197Ssamstatic struct secacq *key_newacq __P((const struct secasindex *));
482105197Ssamstatic struct secacq *key_getacq __P((const struct secasindex *));
483105197Ssamstatic struct secacq *key_getacqbyseq __P((u_int32_t));
484105197Ssamstatic struct secspacq *key_newspacq __P((struct secpolicyindex *));
485105197Ssamstatic struct secspacq *key_getspacq __P((struct secpolicyindex *));
486105197Ssamstatic int key_acquire2 __P((struct socket *, struct mbuf *,
487105197Ssam	const struct sadb_msghdr *));
488105197Ssamstatic int key_register __P((struct socket *, struct mbuf *,
489105197Ssam	const struct sadb_msghdr *));
490105197Ssamstatic int key_expire __P((struct secasvar *));
491105197Ssamstatic int key_flush __P((struct socket *, struct mbuf *,
492105197Ssam	const struct sadb_msghdr *));
493105197Ssamstatic int key_dump __P((struct socket *, struct mbuf *,
494105197Ssam	const struct sadb_msghdr *));
495105197Ssamstatic int key_promisc __P((struct socket *, struct mbuf *,
496105197Ssam	const struct sadb_msghdr *));
497105197Ssamstatic int key_senderror __P((struct socket *, struct mbuf *, int));
498105197Ssamstatic int key_validate_ext __P((const struct sadb_ext *, int));
499105197Ssamstatic int key_align __P((struct mbuf *, struct sadb_msghdr *));
500157123Sgnnstatic struct mbuf *key_setlifetime(struct seclifetime *src,
501157123Sgnn				     u_int16_t exttype);
502157123Sgnnstatic struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
503157123Sgnn
504105197Ssam#if 0
505105197Ssamstatic const char *key_getfqdn __P((void));
506105197Ssamstatic const char *key_getuserfqdn __P((void));
507105197Ssam#endif
508105197Ssamstatic void key_sa_chgstate __P((struct secasvar *, u_int8_t));
509105197Ssamstatic struct mbuf *key_alloc_mbuf __P((int));
510105197Ssam
511158767Spjdstatic __inline void
512158767Spjdsa_initref(struct secasvar *sav)
513158767Spjd{
514105197Ssam
515158767Spjd	refcount_init(&sav->refcnt, 1);
516158767Spjd}
517158767Spjdstatic __inline void
518158767Spjdsa_addref(struct secasvar *sav)
519158767Spjd{
520158767Spjd
521158767Spjd	refcount_acquire(&sav->refcnt);
522158767Spjd	IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
523158767Spjd}
524158767Spjdstatic __inline int
525158767Spjdsa_delref(struct secasvar *sav)
526158767Spjd{
527158767Spjd
528158767Spjd	IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
529158767Spjd	return (refcount_release(&sav->refcnt));
530158767Spjd}
531158767Spjd
532105197Ssam#define	SP_ADDREF(p) do {						\
533105197Ssam	(p)->refcnt++;							\
534120585Ssam	IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));		\
535105197Ssam} while (0)
536105197Ssam#define	SP_DELREF(p) do {						\
537120585Ssam	IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));		\
538105197Ssam	(p)->refcnt--;							\
539105197Ssam} while (0)
540135947Ssam
541105197Ssam
542105197Ssam/*
543135947Ssam * Update the refcnt while holding the SPTREE lock.
544135947Ssam */
545135947Ssamvoid
546135947Ssamkey_addref(struct secpolicy *sp)
547135947Ssam{
548135947Ssam	SPTREE_LOCK();
549135947Ssam	SP_ADDREF(sp);
550135947Ssam	SPTREE_UNLOCK();
551135947Ssam}
552135947Ssam
553135947Ssam/*
554105197Ssam * Return 0 when there are known to be no SP's for the specified
555105197Ssam * direction.  Otherwise return 1.  This is used by IPsec code
556105197Ssam * to optimize performance.
557105197Ssam */
558105197Ssamint
559105197Ssamkey_havesp(u_int dir)
560105197Ssam{
561183550Szec	INIT_VNET_IPSEC(curvnet);
562183550Szec
563105197Ssam	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
564181803Sbz		LIST_FIRST(&V_sptree[dir]) != NULL : 1);
565105197Ssam}
566105197Ssam
567105197Ssam/* %%% IPsec policy management */
568105197Ssam/*
569105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
570105197Ssam * Must call key_freesp() later.
571105197Ssam * OUT:	NULL:	not found
572105197Ssam *	others:	found and return the pointer.
573105197Ssam */
574105197Ssamstruct secpolicy *
575105197Ssamkey_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
576105197Ssam{
577183550Szec	INIT_VNET_IPSEC(curvnet);
578105197Ssam	struct secpolicy *sp;
579105197Ssam
580120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
581120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
582120585Ssam		("invalid direction %u", dir));
583105197Ssam
584105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
585120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
586105197Ssam
587105197Ssam	/* get a SP entry */
588105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
589105197Ssam		printf("*** objects\n");
590105197Ssam		kdebug_secpolicyindex(spidx));
591105197Ssam
592120585Ssam	SPTREE_LOCK();
593181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
594105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
595105197Ssam			printf("*** in SPD\n");
596105197Ssam			kdebug_secpolicyindex(&sp->spidx));
597105197Ssam
598105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
599105197Ssam			continue;
600105197Ssam		if (key_cmpspidx_withmask(&sp->spidx, spidx))
601105197Ssam			goto found;
602105197Ssam	}
603105197Ssam	sp = NULL;
604105197Ssamfound:
605105197Ssam	if (sp) {
606105197Ssam		/* sanity check */
607120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
608105197Ssam
609105197Ssam		/* found a SPD entry */
610105197Ssam		sp->lastused = time_second;
611105197Ssam		SP_ADDREF(sp);
612105197Ssam	}
613120585Ssam	SPTREE_UNLOCK();
614105197Ssam
615105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
616120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
617105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
618105197Ssam	return sp;
619105197Ssam}
620105197Ssam
621105197Ssam/*
622105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
623105197Ssam * Must call key_freesp() later.
624105197Ssam * OUT:	NULL:	not found
625105197Ssam *	others:	found and return the pointer.
626105197Ssam */
627105197Ssamstruct secpolicy *
628105197Ssamkey_allocsp2(u_int32_t spi,
629105197Ssam	     union sockaddr_union *dst,
630105197Ssam	     u_int8_t proto,
631105197Ssam	     u_int dir,
632105197Ssam	     const char* where, int tag)
633105197Ssam{
634183550Szec	INIT_VNET_IPSEC(curvnet);
635105197Ssam	struct secpolicy *sp;
636105197Ssam
637120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst"));
638120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
639120585Ssam		("invalid direction %u", dir));
640105197Ssam
641105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
642120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
643105197Ssam
644105197Ssam	/* get a SP entry */
645105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
646105197Ssam		printf("*** objects\n");
647105197Ssam		printf("spi %u proto %u dir %u\n", spi, proto, dir);
648105197Ssam		kdebug_sockaddr(&dst->sa));
649105197Ssam
650120585Ssam	SPTREE_LOCK();
651181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
652105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
653105197Ssam			printf("*** in SPD\n");
654105197Ssam			kdebug_secpolicyindex(&sp->spidx));
655105197Ssam
656105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
657105197Ssam			continue;
658105197Ssam		/* compare simple values, then dst address */
659105197Ssam		if (sp->spidx.ul_proto != proto)
660105197Ssam			continue;
661105197Ssam		/* NB: spi's must exist and match */
662105197Ssam		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
663105197Ssam			continue;
664105197Ssam		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
665105197Ssam			goto found;
666105197Ssam	}
667105197Ssam	sp = NULL;
668105197Ssamfound:
669105197Ssam	if (sp) {
670105197Ssam		/* sanity check */
671120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
672105197Ssam
673105197Ssam		/* found a SPD entry */
674105197Ssam		sp->lastused = time_second;
675105197Ssam		SP_ADDREF(sp);
676105197Ssam	}
677120585Ssam	SPTREE_UNLOCK();
678105197Ssam
679105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
680120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
681105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
682105197Ssam	return sp;
683105197Ssam}
684105197Ssam
685105197Ssam/*
686105197Ssam * return a policy that matches this particular inbound packet.
687105197Ssam * XXX slow
688105197Ssam */
689105197Ssamstruct secpolicy *
690105197Ssamkey_gettunnel(const struct sockaddr *osrc,
691105197Ssam	      const struct sockaddr *odst,
692105197Ssam	      const struct sockaddr *isrc,
693105197Ssam	      const struct sockaddr *idst,
694105197Ssam	      const char* where, int tag)
695105197Ssam{
696183550Szec	INIT_VNET_IPSEC(curvnet);
697105197Ssam	struct secpolicy *sp;
698105197Ssam	const int dir = IPSEC_DIR_INBOUND;
699105197Ssam	struct ipsecrequest *r1, *r2, *p;
700105197Ssam	struct secpolicyindex spidx;
701105197Ssam
702105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
703120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
704105197Ssam
705105197Ssam	if (isrc->sa_family != idst->sa_family) {
706120585Ssam		ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
707120585Ssam			__func__, isrc->sa_family, idst->sa_family));
708105197Ssam		sp = NULL;
709105197Ssam		goto done;
710105197Ssam	}
711105197Ssam
712120585Ssam	SPTREE_LOCK();
713181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
714105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
715105197Ssam			continue;
716105197Ssam
717105197Ssam		r1 = r2 = NULL;
718105197Ssam		for (p = sp->req; p; p = p->next) {
719105197Ssam			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
720105197Ssam				continue;
721105197Ssam
722105197Ssam			r1 = r2;
723105197Ssam			r2 = p;
724105197Ssam
725105197Ssam			if (!r1) {
726105197Ssam				/* here we look at address matches only */
727105197Ssam				spidx = sp->spidx;
728105197Ssam				if (isrc->sa_len > sizeof(spidx.src) ||
729105197Ssam				    idst->sa_len > sizeof(spidx.dst))
730105197Ssam					continue;
731105197Ssam				bcopy(isrc, &spidx.src, isrc->sa_len);
732105197Ssam				bcopy(idst, &spidx.dst, idst->sa_len);
733105197Ssam				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
734105197Ssam					continue;
735105197Ssam			} else {
736105197Ssam				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
737105197Ssam				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
738105197Ssam					continue;
739105197Ssam			}
740105197Ssam
741105197Ssam			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
742105197Ssam			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
743105197Ssam				continue;
744105197Ssam
745105197Ssam			goto found;
746105197Ssam		}
747105197Ssam	}
748105197Ssam	sp = NULL;
749105197Ssamfound:
750105197Ssam	if (sp) {
751105197Ssam		sp->lastused = time_second;
752105197Ssam		SP_ADDREF(sp);
753105197Ssam	}
754120585Ssam	SPTREE_UNLOCK();
755105197Ssamdone:
756105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
757120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
758105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
759105197Ssam	return sp;
760105197Ssam}
761105197Ssam
762105197Ssam/*
763105197Ssam * allocating an SA entry for an *OUTBOUND* packet.
764105197Ssam * checking each request entries in SP, and acquire an SA if need.
765105197Ssam * OUT:	0: there are valid requests.
766105197Ssam *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
767105197Ssam */
768105197Ssamint
769105197Ssamkey_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
770105197Ssam{
771183550Szec	INIT_VNET_IPSEC(curvnet);
772105197Ssam	u_int level;
773105197Ssam	int error;
774105197Ssam
775120585Ssam	IPSEC_ASSERT(isr != NULL, ("null isr"));
776120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
777120585Ssam	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
778105197Ssam		saidx->mode == IPSEC_MODE_TUNNEL,
779120585Ssam		("unexpected policy %u", saidx->mode));
780105197Ssam
781105197Ssam	/*
782105197Ssam	 * XXX guard against protocol callbacks from the crypto
783105197Ssam	 * thread as they reference ipsecrequest.sav which we
784105197Ssam	 * temporarily null out below.  Need to rethink how we
785105197Ssam	 * handle bundled SA's in the callback thread.
786105197Ssam	 */
787120585Ssam	IPSECREQUEST_LOCK_ASSERT(isr);
788119643Ssam
789119643Ssam	/* get current level */
790119643Ssam	level = ipsec_get_reqlevel(isr);
791105197Ssam#if 0
792105197Ssam	/*
793105197Ssam	 * We do allocate new SA only if the state of SA in the holder is
794105197Ssam	 * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
795105197Ssam	 */
796105197Ssam	if (isr->sav != NULL) {
797105197Ssam		if (isr->sav->sah == NULL)
798120585Ssam			panic("%s: sah is null.\n", __func__);
799105197Ssam		if (isr->sav == (struct secasvar *)LIST_FIRST(
800105197Ssam			    &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
801105197Ssam			KEY_FREESAV(&isr->sav);
802105197Ssam			isr->sav = NULL;
803105197Ssam		}
804105197Ssam	}
805105197Ssam#else
806105197Ssam	/*
807105197Ssam	 * we free any SA stashed in the IPsec request because a different
808105197Ssam	 * SA may be involved each time this request is checked, either
809105197Ssam	 * because new SAs are being configured, or this request is
810105197Ssam	 * associated with an unconnected datagram socket, or this request
811105197Ssam	 * is associated with a system default policy.
812105197Ssam	 *
813105197Ssam	 * The operation may have negative impact to performance.  We may
814105197Ssam	 * want to check cached SA carefully, rather than picking new SA
815105197Ssam	 * every time.
816105197Ssam	 */
817105197Ssam	if (isr->sav != NULL) {
818105197Ssam		KEY_FREESAV(&isr->sav);
819105197Ssam		isr->sav = NULL;
820105197Ssam	}
821105197Ssam#endif
822105197Ssam
823105197Ssam	/*
824105197Ssam	 * new SA allocation if no SA found.
825105197Ssam	 * key_allocsa_policy should allocate the oldest SA available.
826105197Ssam	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
827105197Ssam	 */
828105197Ssam	if (isr->sav == NULL)
829105197Ssam		isr->sav = key_allocsa_policy(saidx);
830105197Ssam
831105197Ssam	/* When there is SA. */
832105197Ssam	if (isr->sav != NULL) {
833105197Ssam		if (isr->sav->state != SADB_SASTATE_MATURE &&
834105197Ssam		    isr->sav->state != SADB_SASTATE_DYING)
835105197Ssam			return EINVAL;
836105197Ssam		return 0;
837105197Ssam	}
838105197Ssam
839105197Ssam	/* there is no SA */
840105197Ssam	error = key_acquire(saidx, isr->sp);
841105197Ssam	if (error != 0) {
842105197Ssam		/* XXX What should I do ? */
843120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
844120585Ssam			__func__, error));
845105197Ssam		return error;
846105197Ssam	}
847105197Ssam
848105197Ssam	if (level != IPSEC_LEVEL_REQUIRE) {
849105197Ssam		/* XXX sigh, the interface to this routine is botched */
850120585Ssam		IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
851105197Ssam		return 0;
852105197Ssam	} else {
853105197Ssam		return ENOENT;
854105197Ssam	}
855105197Ssam}
856105197Ssam
857105197Ssam/*
858105197Ssam * allocating a SA for policy entry from SAD.
859105197Ssam * NOTE: searching SAD of aliving state.
860105197Ssam * OUT:	NULL:	not found.
861105197Ssam *	others:	found and return the pointer.
862105197Ssam */
863105197Ssamstatic struct secasvar *
864105197Ssamkey_allocsa_policy(const struct secasindex *saidx)
865105197Ssam{
866128856Ssam#define	N(a)	_ARRAYLEN(a)
867183550Szec	INIT_VNET_IPSEC(curvnet);
868105197Ssam	struct secashead *sah;
869105197Ssam	struct secasvar *sav;
870128856Ssam	u_int stateidx, arraysize;
871128856Ssam	const u_int *state_valid;
872105197Ssam
873120585Ssam	SAHTREE_LOCK();
874181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
875105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
876105197Ssam			continue;
877119643Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
878181803Sbz			if (V_key_preferred_oldsa) {
879128856Ssam				state_valid = saorder_state_valid_prefer_old;
880128856Ssam				arraysize = N(saorder_state_valid_prefer_old);
881128856Ssam			} else {
882128856Ssam				state_valid = saorder_state_valid_prefer_new;
883128856Ssam				arraysize = N(saorder_state_valid_prefer_new);
884128856Ssam			}
885120585Ssam			SAHTREE_UNLOCK();
886105197Ssam			goto found;
887119643Ssam		}
888105197Ssam	}
889120585Ssam	SAHTREE_UNLOCK();
890105197Ssam
891105197Ssam	return NULL;
892105197Ssam
893105197Ssam    found:
894105197Ssam	/* search valid state */
895128856Ssam	for (stateidx = 0; stateidx < arraysize; stateidx++) {
896128856Ssam		sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
897105197Ssam		if (sav != NULL)
898105197Ssam			return sav;
899105197Ssam	}
900105197Ssam
901105197Ssam	return NULL;
902128856Ssam#undef N
903105197Ssam}
904105197Ssam
905105197Ssam/*
906105197Ssam * searching SAD with direction, protocol, mode and state.
907105197Ssam * called by key_allocsa_policy().
908105197Ssam * OUT:
909105197Ssam *	NULL	: not found
910105197Ssam *	others	: found, pointer to a SA.
911105197Ssam */
912105197Ssamstatic struct secasvar *
913105197Ssamkey_do_allocsa_policy(struct secashead *sah, u_int state)
914105197Ssam{
915183550Szec	INIT_VNET_IPSEC(curvnet);
916105197Ssam	struct secasvar *sav, *nextsav, *candidate, *d;
917105197Ssam
918105197Ssam	/* initilize */
919105197Ssam	candidate = NULL;
920105197Ssam
921120585Ssam	SAHTREE_LOCK();
922105197Ssam	for (sav = LIST_FIRST(&sah->savtree[state]);
923105197Ssam	     sav != NULL;
924105197Ssam	     sav = nextsav) {
925105197Ssam
926105197Ssam		nextsav = LIST_NEXT(sav, chain);
927105197Ssam
928105197Ssam		/* sanity check */
929120585Ssam		KEY_CHKSASTATE(sav->state, state, __func__);
930105197Ssam
931105197Ssam		/* initialize */
932105197Ssam		if (candidate == NULL) {
933105197Ssam			candidate = sav;
934105197Ssam			continue;
935105197Ssam		}
936105197Ssam
937105197Ssam		/* Which SA is the better ? */
938105197Ssam
939120585Ssam		IPSEC_ASSERT(candidate->lft_c != NULL,
940120585Ssam			("null candidate lifetime"));
941120585Ssam		IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
942105197Ssam
943105197Ssam		/* What the best method is to compare ? */
944181803Sbz		if (V_key_preferred_oldsa) {
945157123Sgnn			if (candidate->lft_c->addtime >
946157123Sgnn					sav->lft_c->addtime) {
947105197Ssam				candidate = sav;
948105197Ssam			}
949105197Ssam			continue;
950105197Ssam			/*NOTREACHED*/
951105197Ssam		}
952105197Ssam
953125876Sguido		/* preferred new sa rather than old sa */
954157123Sgnn		if (candidate->lft_c->addtime <
955157123Sgnn				sav->lft_c->addtime) {
956105197Ssam			d = candidate;
957105197Ssam			candidate = sav;
958105197Ssam		} else
959105197Ssam			d = sav;
960105197Ssam
961105197Ssam		/*
962105197Ssam		 * prepared to delete the SA when there is more
963105197Ssam		 * suitable candidate and the lifetime of the SA is not
964105197Ssam		 * permanent.
965105197Ssam		 */
966177553Sbz		if (d->lft_h->addtime != 0) {
967105197Ssam			struct mbuf *m, *result;
968125508Ssam			u_int8_t satype;
969105197Ssam
970105197Ssam			key_sa_chgstate(d, SADB_SASTATE_DEAD);
971105197Ssam
972120585Ssam			IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
973125508Ssam
974125508Ssam			satype = key_proto2satype(d->sah->saidx.proto);
975125508Ssam			if (satype == 0)
976125508Ssam				goto msgfail;
977125508Ssam
978105197Ssam			m = key_setsadbmsg(SADB_DELETE, 0,
979125508Ssam			    satype, 0, 0, d->refcnt - 1);
980105197Ssam			if (!m)
981105197Ssam				goto msgfail;
982105197Ssam			result = m;
983105197Ssam
984105197Ssam			/* set sadb_address for saidx's. */
985105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
986105197Ssam				&d->sah->saidx.src.sa,
987105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
988105197Ssam				IPSEC_ULPROTO_ANY);
989105197Ssam			if (!m)
990105197Ssam				goto msgfail;
991105197Ssam			m_cat(result, m);
992105197Ssam
993105197Ssam			/* set sadb_address for saidx's. */
994105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
995128860Ssam				&d->sah->saidx.dst.sa,
996128860Ssam				d->sah->saidx.dst.sa.sa_len << 3,
997105197Ssam				IPSEC_ULPROTO_ANY);
998105197Ssam			if (!m)
999105197Ssam				goto msgfail;
1000105197Ssam			m_cat(result, m);
1001105197Ssam
1002105197Ssam			/* create SA extension */
1003105197Ssam			m = key_setsadbsa(d);
1004105197Ssam			if (!m)
1005105197Ssam				goto msgfail;
1006105197Ssam			m_cat(result, m);
1007105197Ssam
1008105197Ssam			if (result->m_len < sizeof(struct sadb_msg)) {
1009105197Ssam				result = m_pullup(result,
1010105197Ssam						sizeof(struct sadb_msg));
1011105197Ssam				if (result == NULL)
1012105197Ssam					goto msgfail;
1013105197Ssam			}
1014105197Ssam
1015105197Ssam			result->m_pkthdr.len = 0;
1016105197Ssam			for (m = result; m; m = m->m_next)
1017105197Ssam				result->m_pkthdr.len += m->m_len;
1018105197Ssam			mtod(result, struct sadb_msg *)->sadb_msg_len =
1019105197Ssam				PFKEY_UNIT64(result->m_pkthdr.len);
1020105197Ssam
1021105197Ssam			if (key_sendup_mbuf(NULL, result,
1022105197Ssam					KEY_SENDUP_REGISTERED))
1023105197Ssam				goto msgfail;
1024105197Ssam		 msgfail:
1025105197Ssam			KEY_FREESAV(&d);
1026105197Ssam		}
1027105197Ssam	}
1028105197Ssam	if (candidate) {
1029158767Spjd		sa_addref(candidate);
1030105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1031120585Ssam			printf("DP %s cause refcnt++:%d SA:%p\n",
1032120585Ssam				__func__, candidate->refcnt, candidate));
1033105197Ssam	}
1034120585Ssam	SAHTREE_UNLOCK();
1035119643Ssam
1036105197Ssam	return candidate;
1037105197Ssam}
1038105197Ssam
1039105197Ssam/*
1040105197Ssam * allocating a usable SA entry for a *INBOUND* packet.
1041105197Ssam * Must call key_freesav() later.
1042105197Ssam * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
1043105197Ssam *	NULL:		not found, or error occured.
1044105197Ssam *
1045105197Ssam * In the comparison, no source address is used--for RFC2401 conformance.
1046105197Ssam * To quote, from section 4.1:
1047105197Ssam *	A security association is uniquely identified by a triple consisting
1048105197Ssam *	of a Security Parameter Index (SPI), an IP Destination Address, and a
1049105197Ssam *	security protocol (AH or ESP) identifier.
1050105197Ssam * Note that, however, we do need to keep source address in IPsec SA.
1051105197Ssam * IKE specification and PF_KEY specification do assume that we
1052105197Ssam * keep source address in IPsec SA.  We see a tricky situation here.
1053105197Ssam */
1054105197Ssamstruct secasvar *
1055105197Ssamkey_allocsa(
1056105197Ssam	union sockaddr_union *dst,
1057105197Ssam	u_int proto,
1058105197Ssam	u_int32_t spi,
1059105197Ssam	const char* where, int tag)
1060105197Ssam{
1061183550Szec	INIT_VNET_IPSEC(curvnet);
1062105197Ssam	struct secashead *sah;
1063105197Ssam	struct secasvar *sav;
1064128856Ssam	u_int stateidx, arraysize, state;
1065128856Ssam	const u_int *saorder_state_valid;
1066105197Ssam
1067120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst address"));
1068105197Ssam
1069105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1070120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
1071105197Ssam
1072105197Ssam	/*
1073105197Ssam	 * searching SAD.
1074105197Ssam	 * XXX: to be checked internal IP header somewhere.  Also when
1075105197Ssam	 * IPsec tunnel packet is received.  But ESP tunnel mode is
1076105197Ssam	 * encrypted so we can't check internal IP header.
1077105197Ssam	 */
1078120585Ssam	SAHTREE_LOCK();
1079181803Sbz	if (V_key_preferred_oldsa) {
1080128856Ssam		saorder_state_valid = saorder_state_valid_prefer_old;
1081128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1082128856Ssam	} else {
1083128856Ssam		saorder_state_valid = saorder_state_valid_prefer_new;
1084128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1085128856Ssam	}
1086181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
1087105197Ssam		/* search valid state */
1088128856Ssam		for (stateidx = 0; stateidx < arraysize; stateidx++) {
1089105197Ssam			state = saorder_state_valid[stateidx];
1090105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
1091105197Ssam				/* sanity check */
1092120585Ssam				KEY_CHKSASTATE(sav->state, state, __func__);
1093105197Ssam				/* do not return entries w/ unusable state */
1094105197Ssam				if (sav->state != SADB_SASTATE_MATURE &&
1095105197Ssam				    sav->state != SADB_SASTATE_DYING)
1096105197Ssam					continue;
1097105197Ssam				if (proto != sav->sah->saidx.proto)
1098105197Ssam					continue;
1099105197Ssam				if (spi != sav->spi)
1100105197Ssam					continue;
1101105197Ssam#if 0	/* don't check src */
1102105197Ssam				/* check src address */
1103105197Ssam				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, 0) != 0)
1104105197Ssam					continue;
1105105197Ssam#endif
1106105197Ssam				/* check dst address */
1107105197Ssam				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, 0) != 0)
1108105197Ssam					continue;
1109158767Spjd				sa_addref(sav);
1110105197Ssam				goto done;
1111105197Ssam			}
1112105197Ssam		}
1113105197Ssam	}
1114105197Ssam	sav = NULL;
1115105197Ssamdone:
1116120585Ssam	SAHTREE_UNLOCK();
1117105197Ssam
1118105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1119120585Ssam		printf("DP %s return SA:%p; refcnt %u\n", __func__,
1120105197Ssam			sav, sav ? sav->refcnt : 0));
1121105197Ssam	return sav;
1122105197Ssam}
1123105197Ssam
1124105197Ssam/*
1125105197Ssam * Must be called after calling key_allocsp().
1126105197Ssam * For both the packet without socket and key_freeso().
1127105197Ssam */
1128105197Ssamvoid
1129105197Ssam_key_freesp(struct secpolicy **spp, const char* where, int tag)
1130105197Ssam{
1131183550Szec	INIT_VNET_IPSEC(curvnet);
1132105197Ssam	struct secpolicy *sp = *spp;
1133105197Ssam
1134120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1135105197Ssam
1136120585Ssam	SPTREE_LOCK();
1137105197Ssam	SP_DELREF(sp);
1138105197Ssam
1139105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1140120585Ssam		printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1141120585Ssam			__func__, sp, sp->id, where, tag, sp->refcnt));
1142105197Ssam
1143105197Ssam	if (sp->refcnt == 0) {
1144105197Ssam		*spp = NULL;
1145105197Ssam		key_delsp(sp);
1146105197Ssam	}
1147120585Ssam	SPTREE_UNLOCK();
1148105197Ssam}
1149105197Ssam
1150105197Ssam/*
1151105197Ssam * Must be called after calling key_allocsp().
1152105197Ssam * For the packet with socket.
1153105197Ssam */
1154105197Ssamvoid
1155105197Ssamkey_freeso(struct socket *so)
1156105197Ssam{
1157183550Szec	INIT_VNET_IPSEC(curvnet);
1158120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
1159105197Ssam
1160105197Ssam	switch (so->so_proto->pr_domain->dom_family) {
1161105197Ssam#ifdef INET
1162105197Ssam	case PF_INET:
1163105197Ssam	    {
1164105197Ssam		struct inpcb *pcb = sotoinpcb(so);
1165105197Ssam
1166105197Ssam		/* Does it have a PCB ? */
1167105197Ssam		if (pcb == NULL)
1168105197Ssam			return;
1169105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1170105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1171105197Ssam	    }
1172105197Ssam		break;
1173105197Ssam#endif
1174105197Ssam#ifdef INET6
1175105197Ssam	case PF_INET6:
1176105197Ssam	    {
1177105197Ssam#ifdef HAVE_NRL_INPCB
1178105197Ssam		struct inpcb *pcb  = sotoinpcb(so);
1179105197Ssam
1180105197Ssam		/* Does it have a PCB ? */
1181105197Ssam		if (pcb == NULL)
1182105197Ssam			return;
1183105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1184105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1185105197Ssam#else
1186105197Ssam		struct in6pcb *pcb  = sotoin6pcb(so);
1187105197Ssam
1188105197Ssam		/* Does it have a PCB ? */
1189105197Ssam		if (pcb == NULL)
1190105197Ssam			return;
1191105197Ssam		key_freesp_so(&pcb->in6p_sp->sp_in);
1192105197Ssam		key_freesp_so(&pcb->in6p_sp->sp_out);
1193105197Ssam#endif
1194105197Ssam	    }
1195105197Ssam		break;
1196105197Ssam#endif /* INET6 */
1197105197Ssam	default:
1198120585Ssam		ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1199120585Ssam		    __func__, so->so_proto->pr_domain->dom_family));
1200105197Ssam		return;
1201105197Ssam	}
1202105197Ssam}
1203105197Ssam
1204105197Ssamstatic void
1205105197Ssamkey_freesp_so(struct secpolicy **sp)
1206105197Ssam{
1207120585Ssam	IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1208105197Ssam
1209105197Ssam	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1210105197Ssam	    (*sp)->policy == IPSEC_POLICY_BYPASS)
1211105197Ssam		return;
1212105197Ssam
1213120585Ssam	IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1214120585Ssam		("invalid policy %u", (*sp)->policy));
1215105197Ssam	KEY_FREESP(sp);
1216105197Ssam}
1217105197Ssam
1218105197Ssam/*
1219105197Ssam * Must be called after calling key_allocsa().
1220105197Ssam * This function is called by key_freesp() to free some SA allocated
1221105197Ssam * for a policy.
1222105197Ssam */
1223105197Ssamvoid
1224105197Ssamkey_freesav(struct secasvar **psav, const char* where, int tag)
1225105197Ssam{
1226183550Szec	INIT_VNET_IPSEC(curvnet);
1227105197Ssam	struct secasvar *sav = *psav;
1228105197Ssam
1229120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
1230105197Ssam
1231158767Spjd	if (sa_delref(sav)) {
1232158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1233158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1234158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1235105197Ssam		*psav = NULL;
1236105197Ssam		key_delsav(sav);
1237158767Spjd	} else {
1238158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1239158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1240158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1241105197Ssam	}
1242105197Ssam}
1243105197Ssam
1244105197Ssam/* %%% SPD management */
1245105197Ssam/*
1246105197Ssam * free security policy entry.
1247105197Ssam */
1248105197Ssamstatic void
1249105197Ssamkey_delsp(struct secpolicy *sp)
1250105197Ssam{
1251119643Ssam	struct ipsecrequest *isr, *nextisr;
1252105197Ssam
1253120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1254120585Ssam	SPTREE_LOCK_ASSERT();
1255105197Ssam
1256105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
1257105197Ssam
1258120585Ssam	IPSEC_ASSERT(sp->refcnt == 0,
1259120585Ssam		("SP with references deleted (refcnt %u)", sp->refcnt));
1260105197Ssam
1261105197Ssam	/* remove from SP index */
1262105197Ssam	if (__LIST_CHAINED(sp))
1263105197Ssam		LIST_REMOVE(sp, chain);
1264105197Ssam
1265119643Ssam	for (isr = sp->req; isr != NULL; isr = nextisr) {
1266105197Ssam		if (isr->sav != NULL) {
1267105197Ssam			KEY_FREESAV(&isr->sav);
1268105197Ssam			isr->sav = NULL;
1269105197Ssam		}
1270105197Ssam
1271105197Ssam		nextisr = isr->next;
1272119643Ssam		ipsec_delisr(isr);
1273105197Ssam	}
1274119643Ssam	_key_delsp(sp);
1275105197Ssam}
1276105197Ssam
1277105197Ssam/*
1278105197Ssam * search SPD
1279105197Ssam * OUT:	NULL	: not found
1280105197Ssam *	others	: found, pointer to a SP.
1281105197Ssam */
1282105197Ssamstatic struct secpolicy *
1283105197Ssamkey_getsp(struct secpolicyindex *spidx)
1284105197Ssam{
1285183550Szec	INIT_VNET_IPSEC(curvnet);
1286105197Ssam	struct secpolicy *sp;
1287105197Ssam
1288120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1289105197Ssam
1290120585Ssam	SPTREE_LOCK();
1291181803Sbz	LIST_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1292105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1293105197Ssam			continue;
1294105197Ssam		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1295105197Ssam			SP_ADDREF(sp);
1296119643Ssam			break;
1297105197Ssam		}
1298105197Ssam	}
1299120585Ssam	SPTREE_UNLOCK();
1300105197Ssam
1301119643Ssam	return sp;
1302105197Ssam}
1303105197Ssam
1304105197Ssam/*
1305105197Ssam * get SP by index.
1306105197Ssam * OUT:	NULL	: not found
1307105197Ssam *	others	: found, pointer to a SP.
1308105197Ssam */
1309105197Ssamstatic struct secpolicy *
1310105197Ssamkey_getspbyid(u_int32_t id)
1311105197Ssam{
1312183550Szec	INIT_VNET_IPSEC(curvnet);
1313105197Ssam	struct secpolicy *sp;
1314105197Ssam
1315120585Ssam	SPTREE_LOCK();
1316181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
1317105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1318105197Ssam			continue;
1319105197Ssam		if (sp->id == id) {
1320105197Ssam			SP_ADDREF(sp);
1321119643Ssam			goto done;
1322105197Ssam		}
1323105197Ssam	}
1324105197Ssam
1325181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
1326105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1327105197Ssam			continue;
1328105197Ssam		if (sp->id == id) {
1329105197Ssam			SP_ADDREF(sp);
1330119643Ssam			goto done;
1331105197Ssam		}
1332105197Ssam	}
1333119643Ssamdone:
1334120585Ssam	SPTREE_UNLOCK();
1335105197Ssam
1336119643Ssam	return sp;
1337105197Ssam}
1338105197Ssam
1339105197Ssamstruct secpolicy *
1340105197Ssamkey_newsp(const char* where, int tag)
1341105197Ssam{
1342183550Szec	INIT_VNET_IPSEC(curvnet);
1343105197Ssam	struct secpolicy *newsp = NULL;
1344105197Ssam
1345105197Ssam	newsp = (struct secpolicy *)
1346119643Ssam		malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1347105197Ssam	if (newsp) {
1348120585Ssam		SECPOLICY_LOCK_INIT(newsp);
1349105197Ssam		newsp->refcnt = 1;
1350105197Ssam		newsp->req = NULL;
1351105197Ssam	}
1352105197Ssam
1353105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1354120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
1355105197Ssam			where, tag, newsp));
1356105197Ssam	return newsp;
1357105197Ssam}
1358105197Ssam
1359119643Ssamstatic void
1360119643Ssam_key_delsp(struct secpolicy *sp)
1361119643Ssam{
1362120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
1363119643Ssam	free(sp, M_IPSEC_SP);
1364119643Ssam}
1365119643Ssam
1366105197Ssam/*
1367105197Ssam * create secpolicy structure from sadb_x_policy structure.
1368105197Ssam * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1369105197Ssam * so must be set properly later.
1370105197Ssam */
1371105197Ssamstruct secpolicy *
1372105197Ssamkey_msg2sp(xpl0, len, error)
1373105197Ssam	struct sadb_x_policy *xpl0;
1374105197Ssam	size_t len;
1375105197Ssam	int *error;
1376105197Ssam{
1377183550Szec	INIT_VNET_IPSEC(curvnet);
1378105197Ssam	struct secpolicy *newsp;
1379105197Ssam
1380120585Ssam	IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1381127972Spjd	IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1382120585Ssam
1383105197Ssam	if (len != PFKEY_EXTLEN(xpl0)) {
1384120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1385105197Ssam		*error = EINVAL;
1386105197Ssam		return NULL;
1387105197Ssam	}
1388105197Ssam
1389105197Ssam	if ((newsp = KEY_NEWSP()) == NULL) {
1390105197Ssam		*error = ENOBUFS;
1391105197Ssam		return NULL;
1392105197Ssam	}
1393105197Ssam
1394105197Ssam	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1395105197Ssam	newsp->policy = xpl0->sadb_x_policy_type;
1396105197Ssam
1397105197Ssam	/* check policy */
1398105197Ssam	switch (xpl0->sadb_x_policy_type) {
1399105197Ssam	case IPSEC_POLICY_DISCARD:
1400105197Ssam	case IPSEC_POLICY_NONE:
1401105197Ssam	case IPSEC_POLICY_ENTRUST:
1402105197Ssam	case IPSEC_POLICY_BYPASS:
1403105197Ssam		newsp->req = NULL;
1404105197Ssam		break;
1405105197Ssam
1406105197Ssam	case IPSEC_POLICY_IPSEC:
1407105197Ssam	    {
1408105197Ssam		int tlen;
1409105197Ssam		struct sadb_x_ipsecrequest *xisr;
1410105197Ssam		struct ipsecrequest **p_isr = &newsp->req;
1411105197Ssam
1412105197Ssam		/* validity check */
1413105197Ssam		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1414120585Ssam			ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1415120585Ssam				__func__));
1416105197Ssam			KEY_FREESP(&newsp);
1417105197Ssam			*error = EINVAL;
1418105197Ssam			return NULL;
1419105197Ssam		}
1420105197Ssam
1421105197Ssam		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1422105197Ssam		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1423105197Ssam
1424105197Ssam		while (tlen > 0) {
1425105197Ssam			/* length check */
1426105197Ssam			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1427120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1428120585Ssam					"length.\n", __func__));
1429105197Ssam				KEY_FREESP(&newsp);
1430105197Ssam				*error = EINVAL;
1431105197Ssam				return NULL;
1432105197Ssam			}
1433105197Ssam
1434105197Ssam			/* allocate request buffer */
1435119643Ssam			/* NB: data structure is zero'd */
1436119643Ssam			*p_isr = ipsec_newisr();
1437105197Ssam			if ((*p_isr) == NULL) {
1438105197Ssam				ipseclog((LOG_DEBUG,
1439120585Ssam				    "%s: No more memory.\n", __func__));
1440105197Ssam				KEY_FREESP(&newsp);
1441105197Ssam				*error = ENOBUFS;
1442105197Ssam				return NULL;
1443105197Ssam			}
1444105197Ssam
1445105197Ssam			/* set values */
1446105197Ssam			switch (xisr->sadb_x_ipsecrequest_proto) {
1447105197Ssam			case IPPROTO_ESP:
1448105197Ssam			case IPPROTO_AH:
1449105197Ssam			case IPPROTO_IPCOMP:
1450105197Ssam				break;
1451105197Ssam			default:
1452105197Ssam				ipseclog((LOG_DEBUG,
1453120585Ssam				    "%s: invalid proto type=%u\n", __func__,
1454105197Ssam				    xisr->sadb_x_ipsecrequest_proto));
1455105197Ssam				KEY_FREESP(&newsp);
1456105197Ssam				*error = EPROTONOSUPPORT;
1457105197Ssam				return NULL;
1458105197Ssam			}
1459105197Ssam			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1460105197Ssam
1461105197Ssam			switch (xisr->sadb_x_ipsecrequest_mode) {
1462105197Ssam			case IPSEC_MODE_TRANSPORT:
1463105197Ssam			case IPSEC_MODE_TUNNEL:
1464105197Ssam				break;
1465105197Ssam			case IPSEC_MODE_ANY:
1466105197Ssam			default:
1467105197Ssam				ipseclog((LOG_DEBUG,
1468120585Ssam				    "%s: invalid mode=%u\n", __func__,
1469105197Ssam				    xisr->sadb_x_ipsecrequest_mode));
1470105197Ssam				KEY_FREESP(&newsp);
1471105197Ssam				*error = EINVAL;
1472105197Ssam				return NULL;
1473105197Ssam			}
1474105197Ssam			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1475105197Ssam
1476105197Ssam			switch (xisr->sadb_x_ipsecrequest_level) {
1477105197Ssam			case IPSEC_LEVEL_DEFAULT:
1478105197Ssam			case IPSEC_LEVEL_USE:
1479105197Ssam			case IPSEC_LEVEL_REQUIRE:
1480105197Ssam				break;
1481105197Ssam			case IPSEC_LEVEL_UNIQUE:
1482105197Ssam				/* validity check */
1483105197Ssam				/*
1484105197Ssam				 * If range violation of reqid, kernel will
1485105197Ssam				 * update it, don't refuse it.
1486105197Ssam				 */
1487105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid
1488105197Ssam						> IPSEC_MANUAL_REQID_MAX) {
1489105197Ssam					ipseclog((LOG_DEBUG,
1490120585Ssam					    "%s: reqid=%d range "
1491105197Ssam					    "violation, updated by kernel.\n",
1492120585Ssam					    __func__,
1493105197Ssam					    xisr->sadb_x_ipsecrequest_reqid));
1494105197Ssam					xisr->sadb_x_ipsecrequest_reqid = 0;
1495105197Ssam				}
1496105197Ssam
1497105197Ssam				/* allocate new reqid id if reqid is zero. */
1498105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1499105197Ssam					u_int32_t reqid;
1500105197Ssam					if ((reqid = key_newreqid()) == 0) {
1501105197Ssam						KEY_FREESP(&newsp);
1502105197Ssam						*error = ENOBUFS;
1503105197Ssam						return NULL;
1504105197Ssam					}
1505105197Ssam					(*p_isr)->saidx.reqid = reqid;
1506105197Ssam					xisr->sadb_x_ipsecrequest_reqid = reqid;
1507105197Ssam				} else {
1508105197Ssam				/* set it for manual keying. */
1509105197Ssam					(*p_isr)->saidx.reqid =
1510105197Ssam						xisr->sadb_x_ipsecrequest_reqid;
1511105197Ssam				}
1512105197Ssam				break;
1513105197Ssam
1514105197Ssam			default:
1515120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1516120585Ssam					__func__,
1517105197Ssam					xisr->sadb_x_ipsecrequest_level));
1518105197Ssam				KEY_FREESP(&newsp);
1519105197Ssam				*error = EINVAL;
1520105197Ssam				return NULL;
1521105197Ssam			}
1522105197Ssam			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1523105197Ssam
1524105197Ssam			/* set IP addresses if there */
1525105197Ssam			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1526105197Ssam				struct sockaddr *paddr;
1527105197Ssam
1528105197Ssam				paddr = (struct sockaddr *)(xisr + 1);
1529105197Ssam
1530105197Ssam				/* validity check */
1531105197Ssam				if (paddr->sa_len
1532105197Ssam				    > sizeof((*p_isr)->saidx.src)) {
1533120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1534120585Ssam						"request address length.\n",
1535120585Ssam						__func__));
1536105197Ssam					KEY_FREESP(&newsp);
1537105197Ssam					*error = EINVAL;
1538105197Ssam					return NULL;
1539105197Ssam				}
1540105197Ssam				bcopy(paddr, &(*p_isr)->saidx.src,
1541105197Ssam					paddr->sa_len);
1542105197Ssam
1543105197Ssam				paddr = (struct sockaddr *)((caddr_t)paddr
1544105197Ssam							+ paddr->sa_len);
1545105197Ssam
1546105197Ssam				/* validity check */
1547105197Ssam				if (paddr->sa_len
1548105197Ssam				    > sizeof((*p_isr)->saidx.dst)) {
1549120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1550120585Ssam						"request address length.\n",
1551120585Ssam						__func__));
1552105197Ssam					KEY_FREESP(&newsp);
1553105197Ssam					*error = EINVAL;
1554105197Ssam					return NULL;
1555105197Ssam				}
1556105197Ssam				bcopy(paddr, &(*p_isr)->saidx.dst,
1557105197Ssam					paddr->sa_len);
1558105197Ssam			}
1559105197Ssam
1560105197Ssam			(*p_isr)->sp = newsp;
1561105197Ssam
1562105197Ssam			/* initialization for the next. */
1563105197Ssam			p_isr = &(*p_isr)->next;
1564105197Ssam			tlen -= xisr->sadb_x_ipsecrequest_len;
1565105197Ssam
1566105197Ssam			/* validity check */
1567105197Ssam			if (tlen < 0) {
1568120585Ssam				ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1569120585Ssam					__func__));
1570105197Ssam				KEY_FREESP(&newsp);
1571105197Ssam				*error = EINVAL;
1572105197Ssam				return NULL;
1573105197Ssam			}
1574105197Ssam
1575105197Ssam			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1576105197Ssam			                 + xisr->sadb_x_ipsecrequest_len);
1577105197Ssam		}
1578105197Ssam	    }
1579105197Ssam		break;
1580105197Ssam	default:
1581120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1582105197Ssam		KEY_FREESP(&newsp);
1583105197Ssam		*error = EINVAL;
1584105197Ssam		return NULL;
1585105197Ssam	}
1586105197Ssam
1587105197Ssam	*error = 0;
1588105197Ssam	return newsp;
1589105197Ssam}
1590105197Ssam
1591105197Ssamstatic u_int32_t
1592105197Ssamkey_newreqid()
1593105197Ssam{
1594105197Ssam	static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1595105197Ssam
1596105197Ssam	auto_reqid = (auto_reqid == ~0
1597105197Ssam			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1598105197Ssam
1599105197Ssam	/* XXX should be unique check */
1600105197Ssam
1601105197Ssam	return auto_reqid;
1602105197Ssam}
1603105197Ssam
1604105197Ssam/*
1605105197Ssam * copy secpolicy struct to sadb_x_policy structure indicated.
1606105197Ssam */
1607105197Ssamstruct mbuf *
1608105197Ssamkey_sp2msg(sp)
1609105197Ssam	struct secpolicy *sp;
1610105197Ssam{
1611105197Ssam	struct sadb_x_policy *xpl;
1612105197Ssam	int tlen;
1613105197Ssam	caddr_t p;
1614105197Ssam	struct mbuf *m;
1615105197Ssam
1616120585Ssam	IPSEC_ASSERT(sp != NULL, ("null policy"));
1617105197Ssam
1618105197Ssam	tlen = key_getspreqmsglen(sp);
1619105197Ssam
1620105197Ssam	m = key_alloc_mbuf(tlen);
1621105197Ssam	if (!m || m->m_next) {	/*XXX*/
1622105197Ssam		if (m)
1623105197Ssam			m_freem(m);
1624105197Ssam		return NULL;
1625105197Ssam	}
1626105197Ssam
1627105197Ssam	m->m_len = tlen;
1628105197Ssam	m->m_next = NULL;
1629105197Ssam	xpl = mtod(m, struct sadb_x_policy *);
1630105197Ssam	bzero(xpl, tlen);
1631105197Ssam
1632105197Ssam	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1633105197Ssam	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1634105197Ssam	xpl->sadb_x_policy_type = sp->policy;
1635105197Ssam	xpl->sadb_x_policy_dir = sp->spidx.dir;
1636105197Ssam	xpl->sadb_x_policy_id = sp->id;
1637105197Ssam	p = (caddr_t)xpl + sizeof(*xpl);
1638105197Ssam
1639105197Ssam	/* if is the policy for ipsec ? */
1640105197Ssam	if (sp->policy == IPSEC_POLICY_IPSEC) {
1641105197Ssam		struct sadb_x_ipsecrequest *xisr;
1642105197Ssam		struct ipsecrequest *isr;
1643105197Ssam
1644105197Ssam		for (isr = sp->req; isr != NULL; isr = isr->next) {
1645105197Ssam
1646105197Ssam			xisr = (struct sadb_x_ipsecrequest *)p;
1647105197Ssam
1648105197Ssam			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1649105197Ssam			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1650105197Ssam			xisr->sadb_x_ipsecrequest_level = isr->level;
1651105197Ssam			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1652105197Ssam
1653105197Ssam			p += sizeof(*xisr);
1654105197Ssam			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1655105197Ssam			p += isr->saidx.src.sa.sa_len;
1656105197Ssam			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1657105197Ssam			p += isr->saidx.src.sa.sa_len;
1658105197Ssam
1659105197Ssam			xisr->sadb_x_ipsecrequest_len =
1660105197Ssam				PFKEY_ALIGN8(sizeof(*xisr)
1661105197Ssam					+ isr->saidx.src.sa.sa_len
1662105197Ssam					+ isr->saidx.dst.sa.sa_len);
1663105197Ssam		}
1664105197Ssam	}
1665105197Ssam
1666105197Ssam	return m;
1667105197Ssam}
1668105197Ssam
1669105197Ssam/* m will not be freed nor modified */
1670105197Ssamstatic struct mbuf *
1671105197Ssam#ifdef __STDC__
1672105197Ssamkey_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1673105197Ssam	int ndeep, int nitem, ...)
1674105197Ssam#else
1675105197Ssamkey_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1676105197Ssam	struct mbuf *m;
1677105197Ssam	const struct sadb_msghdr *mhp;
1678105197Ssam	int ndeep;
1679105197Ssam	int nitem;
1680105197Ssam	va_dcl
1681105197Ssam#endif
1682105197Ssam{
1683105197Ssam	va_list ap;
1684105197Ssam	int idx;
1685105197Ssam	int i;
1686105197Ssam	struct mbuf *result = NULL, *n;
1687105197Ssam	int len;
1688105197Ssam
1689120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1690120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1691105197Ssam
1692105197Ssam	va_start(ap, nitem);
1693105197Ssam	for (i = 0; i < nitem; i++) {
1694105197Ssam		idx = va_arg(ap, int);
1695105197Ssam		if (idx < 0 || idx > SADB_EXT_MAX)
1696105197Ssam			goto fail;
1697105197Ssam		/* don't attempt to pull empty extension */
1698105197Ssam		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1699105197Ssam			continue;
1700105197Ssam		if (idx != SADB_EXT_RESERVED  &&
1701105197Ssam		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1702105197Ssam			continue;
1703105197Ssam
1704105197Ssam		if (idx == SADB_EXT_RESERVED) {
1705105197Ssam			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1706120585Ssam
1707120585Ssam			IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1708120585Ssam
1709111119Simp			MGETHDR(n, M_DONTWAIT, MT_DATA);
1710105197Ssam			if (!n)
1711105197Ssam				goto fail;
1712105197Ssam			n->m_len = len;
1713105197Ssam			n->m_next = NULL;
1714105197Ssam			m_copydata(m, 0, sizeof(struct sadb_msg),
1715105197Ssam			    mtod(n, caddr_t));
1716105197Ssam		} else if (i < ndeep) {
1717105197Ssam			len = mhp->extlen[idx];
1718105197Ssam			n = key_alloc_mbuf(len);
1719105197Ssam			if (!n || n->m_next) {	/*XXX*/
1720105197Ssam				if (n)
1721105197Ssam					m_freem(n);
1722105197Ssam				goto fail;
1723105197Ssam			}
1724105197Ssam			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1725105197Ssam			    mtod(n, caddr_t));
1726105197Ssam		} else {
1727105197Ssam			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1728111119Simp			    M_DONTWAIT);
1729105197Ssam		}
1730105197Ssam		if (n == NULL)
1731105197Ssam			goto fail;
1732105197Ssam
1733105197Ssam		if (result)
1734105197Ssam			m_cat(result, n);
1735105197Ssam		else
1736105197Ssam			result = n;
1737105197Ssam	}
1738105197Ssam	va_end(ap);
1739105197Ssam
1740105197Ssam	if ((result->m_flags & M_PKTHDR) != 0) {
1741105197Ssam		result->m_pkthdr.len = 0;
1742105197Ssam		for (n = result; n; n = n->m_next)
1743105197Ssam			result->m_pkthdr.len += n->m_len;
1744105197Ssam	}
1745105197Ssam
1746105197Ssam	return result;
1747105197Ssam
1748105197Ssamfail:
1749105197Ssam	m_freem(result);
1750105197Ssam	return NULL;
1751105197Ssam}
1752105197Ssam
1753105197Ssam/*
1754105197Ssam * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1755108533Sschweikh * add an entry to SP database, when received
1756105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1757105197Ssam * from the user(?).
1758105197Ssam * Adding to SP database,
1759105197Ssam * and send
1760105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1761105197Ssam * to the socket which was send.
1762105197Ssam *
1763105197Ssam * SPDADD set a unique policy entry.
1764105197Ssam * SPDSETIDX like SPDADD without a part of policy requests.
1765105197Ssam * SPDUPDATE replace a unique policy entry.
1766105197Ssam *
1767105197Ssam * m will always be freed.
1768105197Ssam */
1769105197Ssamstatic int
1770105197Ssamkey_spdadd(so, m, mhp)
1771105197Ssam	struct socket *so;
1772105197Ssam	struct mbuf *m;
1773105197Ssam	const struct sadb_msghdr *mhp;
1774105197Ssam{
1775183550Szec	INIT_VNET_IPSEC(curvnet);
1776105197Ssam	struct sadb_address *src0, *dst0;
1777105197Ssam	struct sadb_x_policy *xpl0, *xpl;
1778105197Ssam	struct sadb_lifetime *lft = NULL;
1779105197Ssam	struct secpolicyindex spidx;
1780105197Ssam	struct secpolicy *newsp;
1781105197Ssam	int error;
1782105197Ssam
1783120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
1784120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1785120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1786120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1787105197Ssam
1788105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1789105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1790105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1791105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1792105197Ssam		return key_senderror(so, m, EINVAL);
1793105197Ssam	}
1794105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1795105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1796105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1797120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1798120585Ssam			__func__));
1799105197Ssam		return key_senderror(so, m, EINVAL);
1800105197Ssam	}
1801105197Ssam	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1802105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1803105197Ssam			< sizeof(struct sadb_lifetime)) {
1804120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1805120585Ssam				__func__));
1806105197Ssam			return key_senderror(so, m, EINVAL);
1807105197Ssam		}
1808105197Ssam		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1809105197Ssam	}
1810105197Ssam
1811105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1812105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1813105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1814105197Ssam
1815105197Ssam	/* make secindex */
1816105197Ssam	/* XXX boundary check against sa_len */
1817105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1818105197Ssam	                src0 + 1,
1819105197Ssam	                dst0 + 1,
1820105197Ssam	                src0->sadb_address_prefixlen,
1821105197Ssam	                dst0->sadb_address_prefixlen,
1822105197Ssam	                src0->sadb_address_proto,
1823105197Ssam	                &spidx);
1824105197Ssam
1825105197Ssam	/* checking the direciton. */
1826105197Ssam	switch (xpl0->sadb_x_policy_dir) {
1827105197Ssam	case IPSEC_DIR_INBOUND:
1828105197Ssam	case IPSEC_DIR_OUTBOUND:
1829105197Ssam		break;
1830105197Ssam	default:
1831120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1832105197Ssam		mhp->msg->sadb_msg_errno = EINVAL;
1833105197Ssam		return 0;
1834105197Ssam	}
1835105197Ssam
1836105197Ssam	/* check policy */
1837105197Ssam	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1838105197Ssam	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1839105197Ssam	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1840120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1841105197Ssam		return key_senderror(so, m, EINVAL);
1842105197Ssam	}
1843105197Ssam
1844105197Ssam	/* policy requests are mandatory when action is ipsec. */
1845105197Ssam        if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1846105197Ssam	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1847105197Ssam	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1848120585Ssam		ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1849120585Ssam			__func__));
1850105197Ssam		return key_senderror(so, m, EINVAL);
1851105197Ssam	}
1852105197Ssam
1853105197Ssam	/*
1854105197Ssam	 * checking there is SP already or not.
1855105197Ssam	 * SPDUPDATE doesn't depend on whether there is a SP or not.
1856105197Ssam	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1857105197Ssam	 * then error.
1858105197Ssam	 */
1859105197Ssam	newsp = key_getsp(&spidx);
1860105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1861105197Ssam		if (newsp) {
1862105197Ssam			newsp->state = IPSEC_SPSTATE_DEAD;
1863105197Ssam			KEY_FREESP(&newsp);
1864105197Ssam		}
1865105197Ssam	} else {
1866105197Ssam		if (newsp != NULL) {
1867105197Ssam			KEY_FREESP(&newsp);
1868120585Ssam			ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1869120585Ssam				__func__));
1870105197Ssam			return key_senderror(so, m, EEXIST);
1871105197Ssam		}
1872105197Ssam	}
1873105197Ssam
1874105197Ssam	/* allocation new SP entry */
1875105197Ssam	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1876105197Ssam		return key_senderror(so, m, error);
1877105197Ssam	}
1878105197Ssam
1879105197Ssam	if ((newsp->id = key_getnewspid()) == 0) {
1880119643Ssam		_key_delsp(newsp);
1881105197Ssam		return key_senderror(so, m, ENOBUFS);
1882105197Ssam	}
1883105197Ssam
1884105197Ssam	/* XXX boundary check against sa_len */
1885105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1886105197Ssam	                src0 + 1,
1887105197Ssam	                dst0 + 1,
1888105197Ssam	                src0->sadb_address_prefixlen,
1889105197Ssam	                dst0->sadb_address_prefixlen,
1890105197Ssam	                src0->sadb_address_proto,
1891105197Ssam	                &newsp->spidx);
1892105197Ssam
1893105197Ssam	/* sanity check on addr pair */
1894105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1895105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_family) {
1896119643Ssam		_key_delsp(newsp);
1897105197Ssam		return key_senderror(so, m, EINVAL);
1898105197Ssam	}
1899105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1900105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_len) {
1901119643Ssam		_key_delsp(newsp);
1902105197Ssam		return key_senderror(so, m, EINVAL);
1903105197Ssam	}
1904105197Ssam#if 1
1905105197Ssam	if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
1906105197Ssam		struct sockaddr *sa;
1907105197Ssam		sa = (struct sockaddr *)(src0 + 1);
1908105197Ssam		if (sa->sa_family != newsp->req->saidx.src.sa.sa_family) {
1909119643Ssam			_key_delsp(newsp);
1910105197Ssam			return key_senderror(so, m, EINVAL);
1911105197Ssam		}
1912105197Ssam	}
1913105197Ssam	if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
1914105197Ssam		struct sockaddr *sa;
1915105197Ssam		sa = (struct sockaddr *)(dst0 + 1);
1916105197Ssam		if (sa->sa_family != newsp->req->saidx.dst.sa.sa_family) {
1917119643Ssam			_key_delsp(newsp);
1918105197Ssam			return key_senderror(so, m, EINVAL);
1919105197Ssam		}
1920105197Ssam	}
1921105197Ssam#endif
1922105197Ssam
1923105197Ssam	newsp->created = time_second;
1924105197Ssam	newsp->lastused = newsp->created;
1925105197Ssam	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1926105197Ssam	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1927105197Ssam
1928105197Ssam	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1929105197Ssam	newsp->state = IPSEC_SPSTATE_ALIVE;
1930181803Sbz	LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1931105197Ssam
1932105197Ssam	/* delete the entry in spacqtree */
1933105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1934119643Ssam		struct secspacq *spacq = key_getspacq(&spidx);
1935119643Ssam		if (spacq != NULL) {
1936105197Ssam			/* reset counter in order to deletion by timehandler. */
1937105197Ssam			spacq->created = time_second;
1938105197Ssam			spacq->count = 0;
1939120585Ssam			SPACQ_UNLOCK();
1940105197Ssam		}
1941105197Ssam    	}
1942105197Ssam
1943105197Ssam    {
1944105197Ssam	struct mbuf *n, *mpolicy;
1945105197Ssam	struct sadb_msg *newmsg;
1946105197Ssam	int off;
1947105197Ssam
1948105197Ssam	/* create new sadb_msg to reply. */
1949105197Ssam	if (lft) {
1950105197Ssam		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1951105197Ssam		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1952105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1953105197Ssam	} else {
1954105197Ssam		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1955105197Ssam		    SADB_X_EXT_POLICY,
1956105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1957105197Ssam	}
1958105197Ssam	if (!n)
1959105197Ssam		return key_senderror(so, m, ENOBUFS);
1960105197Ssam
1961105197Ssam	if (n->m_len < sizeof(*newmsg)) {
1962105197Ssam		n = m_pullup(n, sizeof(*newmsg));
1963105197Ssam		if (!n)
1964105197Ssam			return key_senderror(so, m, ENOBUFS);
1965105197Ssam	}
1966105197Ssam	newmsg = mtod(n, struct sadb_msg *);
1967105197Ssam	newmsg->sadb_msg_errno = 0;
1968105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1969105197Ssam
1970105197Ssam	off = 0;
1971105197Ssam	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1972105197Ssam	    sizeof(*xpl), &off);
1973105197Ssam	if (mpolicy == NULL) {
1974105197Ssam		/* n is already freed */
1975105197Ssam		return key_senderror(so, m, ENOBUFS);
1976105197Ssam	}
1977105197Ssam	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1978105197Ssam	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1979105197Ssam		m_freem(n);
1980105197Ssam		return key_senderror(so, m, EINVAL);
1981105197Ssam	}
1982105197Ssam	xpl->sadb_x_policy_id = newsp->id;
1983105197Ssam
1984105197Ssam	m_freem(m);
1985105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1986105197Ssam    }
1987105197Ssam}
1988105197Ssam
1989105197Ssam/*
1990105197Ssam * get new policy id.
1991105197Ssam * OUT:
1992105197Ssam *	0:	failure.
1993105197Ssam *	others: success.
1994105197Ssam */
1995105197Ssamstatic u_int32_t
1996105197Ssamkey_getnewspid()
1997105197Ssam{
1998183550Szec	INIT_VNET_IPSEC(curvnet);
1999105197Ssam	u_int32_t newid = 0;
2000181803Sbz	int count = V_key_spi_trycnt;	/* XXX */
2001105197Ssam	struct secpolicy *sp;
2002105197Ssam
2003105197Ssam	/* when requesting to allocate spi ranged */
2004105197Ssam	while (count--) {
2005181803Sbz		newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
2006105197Ssam
2007105197Ssam		if ((sp = key_getspbyid(newid)) == NULL)
2008105197Ssam			break;
2009105197Ssam
2010105197Ssam		KEY_FREESP(&sp);
2011105197Ssam	}
2012105197Ssam
2013105197Ssam	if (count == 0 || newid == 0) {
2014120585Ssam		ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2015120585Ssam			__func__));
2016105197Ssam		return 0;
2017105197Ssam	}
2018105197Ssam
2019105197Ssam	return newid;
2020105197Ssam}
2021105197Ssam
2022105197Ssam/*
2023105197Ssam * SADB_SPDDELETE processing
2024105197Ssam * receive
2025105197Ssam *   <base, address(SD), policy(*)>
2026105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2027105197Ssam * and send,
2028105197Ssam *   <base, address(SD), policy(*)>
2029105197Ssam * to the ikmpd.
2030105197Ssam * policy(*) including direction of policy.
2031105197Ssam *
2032105197Ssam * m will always be freed.
2033105197Ssam */
2034105197Ssamstatic int
2035105197Ssamkey_spddelete(so, m, mhp)
2036105197Ssam	struct socket *so;
2037105197Ssam	struct mbuf *m;
2038105197Ssam	const struct sadb_msghdr *mhp;
2039105197Ssam{
2040183550Szec	INIT_VNET_IPSEC(curvnet);
2041105197Ssam	struct sadb_address *src0, *dst0;
2042105197Ssam	struct sadb_x_policy *xpl0;
2043105197Ssam	struct secpolicyindex spidx;
2044105197Ssam	struct secpolicy *sp;
2045105197Ssam
2046120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
2047120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2048120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2049120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2050105197Ssam
2051105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2052105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2053105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2054120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2055120585Ssam			__func__));
2056105197Ssam		return key_senderror(so, m, EINVAL);
2057105197Ssam	}
2058105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2059105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2060105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2061120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2062120585Ssam			__func__));
2063105197Ssam		return key_senderror(so, m, EINVAL);
2064105197Ssam	}
2065105197Ssam
2066105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2067105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2068105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2069105197Ssam
2070105197Ssam	/* make secindex */
2071105197Ssam	/* XXX boundary check against sa_len */
2072105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2073105197Ssam	                src0 + 1,
2074105197Ssam	                dst0 + 1,
2075105197Ssam	                src0->sadb_address_prefixlen,
2076105197Ssam	                dst0->sadb_address_prefixlen,
2077105197Ssam	                src0->sadb_address_proto,
2078105197Ssam	                &spidx);
2079105197Ssam
2080105197Ssam	/* checking the direciton. */
2081105197Ssam	switch (xpl0->sadb_x_policy_dir) {
2082105197Ssam	case IPSEC_DIR_INBOUND:
2083105197Ssam	case IPSEC_DIR_OUTBOUND:
2084105197Ssam		break;
2085105197Ssam	default:
2086120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2087105197Ssam		return key_senderror(so, m, EINVAL);
2088105197Ssam	}
2089105197Ssam
2090105197Ssam	/* Is there SP in SPD ? */
2091105197Ssam	if ((sp = key_getsp(&spidx)) == NULL) {
2092120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2093105197Ssam		return key_senderror(so, m, EINVAL);
2094105197Ssam	}
2095105197Ssam
2096105197Ssam	/* save policy id to buffer to be returned. */
2097105197Ssam	xpl0->sadb_x_policy_id = sp->id;
2098105197Ssam
2099105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2100105197Ssam	KEY_FREESP(&sp);
2101105197Ssam
2102105197Ssam    {
2103105197Ssam	struct mbuf *n;
2104105197Ssam	struct sadb_msg *newmsg;
2105105197Ssam
2106105197Ssam	/* create new sadb_msg to reply. */
2107105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2108105197Ssam	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2109105197Ssam	if (!n)
2110105197Ssam		return key_senderror(so, m, ENOBUFS);
2111105197Ssam
2112105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2113105197Ssam	newmsg->sadb_msg_errno = 0;
2114105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2115105197Ssam
2116105197Ssam	m_freem(m);
2117105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2118105197Ssam    }
2119105197Ssam}
2120105197Ssam
2121105197Ssam/*
2122105197Ssam * SADB_SPDDELETE2 processing
2123105197Ssam * receive
2124105197Ssam *   <base, policy(*)>
2125105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2126105197Ssam * and send,
2127105197Ssam *   <base, policy(*)>
2128105197Ssam * to the ikmpd.
2129105197Ssam * policy(*) including direction of policy.
2130105197Ssam *
2131105197Ssam * m will always be freed.
2132105197Ssam */
2133105197Ssamstatic int
2134105197Ssamkey_spddelete2(so, m, mhp)
2135105197Ssam	struct socket *so;
2136105197Ssam	struct mbuf *m;
2137105197Ssam	const struct sadb_msghdr *mhp;
2138105197Ssam{
2139183550Szec	INIT_VNET_IPSEC(curvnet);
2140105197Ssam	u_int32_t id;
2141105197Ssam	struct secpolicy *sp;
2142105197Ssam
2143120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2144120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2145120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2146120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2147105197Ssam
2148105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2149105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2150120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2151170803Sbz		return key_senderror(so, m, EINVAL);
2152105197Ssam	}
2153105197Ssam
2154105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2155105197Ssam
2156105197Ssam	/* Is there SP in SPD ? */
2157105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2158120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2159170803Sbz		return key_senderror(so, m, EINVAL);
2160105197Ssam	}
2161105197Ssam
2162105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2163105197Ssam	KEY_FREESP(&sp);
2164105197Ssam
2165105197Ssam    {
2166105197Ssam	struct mbuf *n, *nn;
2167105197Ssam	struct sadb_msg *newmsg;
2168105197Ssam	int off, len;
2169105197Ssam
2170105197Ssam	/* create new sadb_msg to reply. */
2171105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2172105197Ssam
2173111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
2174105197Ssam	if (n && len > MHLEN) {
2175111119Simp		MCLGET(n, M_DONTWAIT);
2176105197Ssam		if ((n->m_flags & M_EXT) == 0) {
2177105197Ssam			m_freem(n);
2178105197Ssam			n = NULL;
2179105197Ssam		}
2180105197Ssam	}
2181105197Ssam	if (!n)
2182105197Ssam		return key_senderror(so, m, ENOBUFS);
2183105197Ssam
2184105197Ssam	n->m_len = len;
2185105197Ssam	n->m_next = NULL;
2186105197Ssam	off = 0;
2187105197Ssam
2188105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2189105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2190105197Ssam
2191120585Ssam	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2192120585Ssam		off, len));
2193105197Ssam
2194105197Ssam	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2195111119Simp	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2196105197Ssam	if (!n->m_next) {
2197105197Ssam		m_freem(n);
2198105197Ssam		return key_senderror(so, m, ENOBUFS);
2199105197Ssam	}
2200105197Ssam
2201105197Ssam	n->m_pkthdr.len = 0;
2202105197Ssam	for (nn = n; nn; nn = nn->m_next)
2203105197Ssam		n->m_pkthdr.len += nn->m_len;
2204105197Ssam
2205105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2206105197Ssam	newmsg->sadb_msg_errno = 0;
2207105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2208105197Ssam
2209105197Ssam	m_freem(m);
2210105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2211105197Ssam    }
2212105197Ssam}
2213105197Ssam
2214105197Ssam/*
2215105197Ssam * SADB_X_GET processing
2216105197Ssam * receive
2217105197Ssam *   <base, policy(*)>
2218105197Ssam * from the user(?),
2219105197Ssam * and send,
2220105197Ssam *   <base, address(SD), policy>
2221105197Ssam * to the ikmpd.
2222105197Ssam * policy(*) including direction of policy.
2223105197Ssam *
2224105197Ssam * m will always be freed.
2225105197Ssam */
2226105197Ssamstatic int
2227105197Ssamkey_spdget(so, m, mhp)
2228105197Ssam	struct socket *so;
2229105197Ssam	struct mbuf *m;
2230105197Ssam	const struct sadb_msghdr *mhp;
2231105197Ssam{
2232183550Szec	INIT_VNET_IPSEC(curvnet);
2233105197Ssam	u_int32_t id;
2234105197Ssam	struct secpolicy *sp;
2235105197Ssam	struct mbuf *n;
2236105197Ssam
2237120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2238120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2239120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2240120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2241105197Ssam
2242105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2243105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2244120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2245120585Ssam			__func__));
2246105197Ssam		return key_senderror(so, m, EINVAL);
2247105197Ssam	}
2248105197Ssam
2249105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2250105197Ssam
2251105197Ssam	/* Is there SP in SPD ? */
2252105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2253120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2254105197Ssam		return key_senderror(so, m, ENOENT);
2255105197Ssam	}
2256105197Ssam
2257105197Ssam	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2258105197Ssam	if (n != NULL) {
2259105197Ssam		m_freem(m);
2260105197Ssam		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2261105197Ssam	} else
2262105197Ssam		return key_senderror(so, m, ENOBUFS);
2263105197Ssam}
2264105197Ssam
2265105197Ssam/*
2266105197Ssam * SADB_X_SPDACQUIRE processing.
2267105197Ssam * Acquire policy and SA(s) for a *OUTBOUND* packet.
2268105197Ssam * send
2269105197Ssam *   <base, policy(*)>
2270105197Ssam * to KMD, and expect to receive
2271105197Ssam *   <base> with SADB_X_SPDACQUIRE if error occured,
2272105197Ssam * or
2273105197Ssam *   <base, policy>
2274105197Ssam * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2275105197Ssam * policy(*) is without policy requests.
2276105197Ssam *
2277105197Ssam *    0     : succeed
2278105197Ssam *    others: error number
2279105197Ssam */
2280105197Ssamint
2281105197Ssamkey_spdacquire(sp)
2282105197Ssam	struct secpolicy *sp;
2283105197Ssam{
2284183550Szec	INIT_VNET_IPSEC(curvnet);
2285105197Ssam	struct mbuf *result = NULL, *m;
2286105197Ssam	struct secspacq *newspacq;
2287105197Ssam
2288120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2289120585Ssam	IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2290120585Ssam	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2291120585Ssam		("policy not IPSEC %u", sp->policy));
2292105197Ssam
2293108533Sschweikh	/* Get an entry to check whether sent message or not. */
2294119643Ssam	newspacq = key_getspacq(&sp->spidx);
2295119643Ssam	if (newspacq != NULL) {
2296181803Sbz		if (V_key_blockacq_count < newspacq->count) {
2297105197Ssam			/* reset counter and do send message. */
2298105197Ssam			newspacq->count = 0;
2299105197Ssam		} else {
2300105197Ssam			/* increment counter and do nothing. */
2301105197Ssam			newspacq->count++;
2302105197Ssam			return 0;
2303105197Ssam		}
2304120585Ssam		SPACQ_UNLOCK();
2305105197Ssam	} else {
2306105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
2307119643Ssam		newspacq = key_newspacq(&sp->spidx);
2308119643Ssam		if (newspacq == NULL)
2309105197Ssam			return ENOBUFS;
2310105197Ssam	}
2311105197Ssam
2312105197Ssam	/* create new sadb_msg to reply. */
2313105197Ssam	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2314170805Sbz	if (!m)
2315170805Sbz		return ENOBUFS;
2316170805Sbz
2317105197Ssam	result = m;
2318105197Ssam
2319105197Ssam	result->m_pkthdr.len = 0;
2320105197Ssam	for (m = result; m; m = m->m_next)
2321105197Ssam		result->m_pkthdr.len += m->m_len;
2322105197Ssam
2323105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2324105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2325105197Ssam
2326105197Ssam	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2327105197Ssam}
2328105197Ssam
2329105197Ssam/*
2330105197Ssam * SADB_SPDFLUSH processing
2331105197Ssam * receive
2332105197Ssam *   <base>
2333105197Ssam * from the user, and free all entries in secpctree.
2334105197Ssam * and send,
2335105197Ssam *   <base>
2336105197Ssam * to the user.
2337105197Ssam * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2338105197Ssam *
2339105197Ssam * m will always be freed.
2340105197Ssam */
2341105197Ssamstatic int
2342105197Ssamkey_spdflush(so, m, mhp)
2343105197Ssam	struct socket *so;
2344105197Ssam	struct mbuf *m;
2345105197Ssam	const struct sadb_msghdr *mhp;
2346105197Ssam{
2347183550Szec	INIT_VNET_IPSEC(curvnet);
2348105197Ssam	struct sadb_msg *newmsg;
2349105197Ssam	struct secpolicy *sp;
2350105197Ssam	u_int dir;
2351105197Ssam
2352120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2353120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2354120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2355120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2356105197Ssam
2357105197Ssam	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2358105197Ssam		return key_senderror(so, m, EINVAL);
2359105197Ssam
2360105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2361120585Ssam		SPTREE_LOCK();
2362181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain)
2363105197Ssam			sp->state = IPSEC_SPSTATE_DEAD;
2364120585Ssam		SPTREE_UNLOCK();
2365105197Ssam	}
2366105197Ssam
2367105197Ssam	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2368120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2369105197Ssam		return key_senderror(so, m, ENOBUFS);
2370105197Ssam	}
2371105197Ssam
2372105197Ssam	if (m->m_next)
2373105197Ssam		m_freem(m->m_next);
2374105197Ssam	m->m_next = NULL;
2375105197Ssam	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2376105197Ssam	newmsg = mtod(m, struct sadb_msg *);
2377105197Ssam	newmsg->sadb_msg_errno = 0;
2378105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2379105197Ssam
2380105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2381105197Ssam}
2382105197Ssam
2383105197Ssam/*
2384105197Ssam * SADB_SPDDUMP processing
2385105197Ssam * receive
2386105197Ssam *   <base>
2387105197Ssam * from the user, and dump all SP leaves
2388105197Ssam * and send,
2389105197Ssam *   <base> .....
2390105197Ssam * to the ikmpd.
2391105197Ssam *
2392105197Ssam * m will always be freed.
2393105197Ssam */
2394105197Ssamstatic int
2395105197Ssamkey_spddump(so, m, mhp)
2396105197Ssam	struct socket *so;
2397105197Ssam	struct mbuf *m;
2398105197Ssam	const struct sadb_msghdr *mhp;
2399105197Ssam{
2400183550Szec	INIT_VNET_IPSEC(curvnet);
2401105197Ssam	struct secpolicy *sp;
2402105197Ssam	int cnt;
2403105197Ssam	u_int dir;
2404105197Ssam	struct mbuf *n;
2405105197Ssam
2406120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2407120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2408120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2409120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2410105197Ssam
2411105197Ssam	/* search SPD entry and get buffer size. */
2412105197Ssam	cnt = 0;
2413105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2414181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2415105197Ssam			cnt++;
2416105197Ssam		}
2417105197Ssam	}
2418105197Ssam
2419105197Ssam	if (cnt == 0)
2420105197Ssam		return key_senderror(so, m, ENOENT);
2421105197Ssam
2422105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2423181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2424105197Ssam			--cnt;
2425105197Ssam			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2426105197Ssam			    mhp->msg->sadb_msg_pid);
2427105197Ssam
2428105197Ssam			if (n)
2429105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2430105197Ssam		}
2431105197Ssam	}
2432105197Ssam
2433105197Ssam	m_freem(m);
2434105197Ssam	return 0;
2435105197Ssam}
2436105197Ssam
2437105197Ssamstatic struct mbuf *
2438105197Ssamkey_setdumpsp(sp, type, seq, pid)
2439105197Ssam	struct secpolicy *sp;
2440105197Ssam	u_int8_t type;
2441105197Ssam	u_int32_t seq, pid;
2442105197Ssam{
2443105197Ssam	struct mbuf *result = NULL, *m;
2444181330Svanhu	struct seclifetime lt;
2445105197Ssam
2446105197Ssam	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2447105197Ssam	if (!m)
2448105197Ssam		goto fail;
2449105197Ssam	result = m;
2450105197Ssam
2451105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2452105197Ssam	    &sp->spidx.src.sa, sp->spidx.prefs,
2453105197Ssam	    sp->spidx.ul_proto);
2454105197Ssam	if (!m)
2455105197Ssam		goto fail;
2456105197Ssam	m_cat(result, m);
2457105197Ssam
2458105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2459105197Ssam	    &sp->spidx.dst.sa, sp->spidx.prefd,
2460105197Ssam	    sp->spidx.ul_proto);
2461105197Ssam	if (!m)
2462105197Ssam		goto fail;
2463105197Ssam	m_cat(result, m);
2464105197Ssam
2465105197Ssam	m = key_sp2msg(sp);
2466105197Ssam	if (!m)
2467105197Ssam		goto fail;
2468105197Ssam	m_cat(result, m);
2469105197Ssam
2470181330Svanhu	if(sp->lifetime){
2471181330Svanhu		lt.addtime=sp->created;
2472181330Svanhu		lt.usetime= sp->lastused;
2473181330Svanhu		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_CURRENT);
2474181330Svanhu		if (!m)
2475181330Svanhu			goto fail;
2476181330Svanhu		m_cat(result, m);
2477181330Svanhu
2478181330Svanhu		lt.addtime=sp->lifetime;
2479181330Svanhu		lt.usetime= sp->validtime;
2480181330Svanhu		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_HARD);
2481181330Svanhu		if (!m)
2482181330Svanhu			goto fail;
2483181330Svanhu		m_cat(result, m);
2484181330Svanhu	}
2485181330Svanhu
2486105197Ssam	if ((result->m_flags & M_PKTHDR) == 0)
2487105197Ssam		goto fail;
2488105197Ssam
2489105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2490105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2491105197Ssam		if (result == NULL)
2492105197Ssam			goto fail;
2493105197Ssam	}
2494105197Ssam
2495105197Ssam	result->m_pkthdr.len = 0;
2496105197Ssam	for (m = result; m; m = m->m_next)
2497105197Ssam		result->m_pkthdr.len += m->m_len;
2498105197Ssam
2499105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2500105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2501105197Ssam
2502105197Ssam	return result;
2503105197Ssam
2504105197Ssamfail:
2505105197Ssam	m_freem(result);
2506105197Ssam	return NULL;
2507105197Ssam}
2508105197Ssam
2509105197Ssam/*
2510105197Ssam * get PFKEY message length for security policy and request.
2511105197Ssam */
2512105197Ssamstatic u_int
2513105197Ssamkey_getspreqmsglen(sp)
2514105197Ssam	struct secpolicy *sp;
2515105197Ssam{
2516105197Ssam	u_int tlen;
2517105197Ssam
2518105197Ssam	tlen = sizeof(struct sadb_x_policy);
2519105197Ssam
2520105197Ssam	/* if is the policy for ipsec ? */
2521105197Ssam	if (sp->policy != IPSEC_POLICY_IPSEC)
2522105197Ssam		return tlen;
2523105197Ssam
2524105197Ssam	/* get length of ipsec requests */
2525105197Ssam    {
2526105197Ssam	struct ipsecrequest *isr;
2527105197Ssam	int len;
2528105197Ssam
2529105197Ssam	for (isr = sp->req; isr != NULL; isr = isr->next) {
2530105197Ssam		len = sizeof(struct sadb_x_ipsecrequest)
2531105197Ssam			+ isr->saidx.src.sa.sa_len
2532105197Ssam			+ isr->saidx.dst.sa.sa_len;
2533105197Ssam
2534105197Ssam		tlen += PFKEY_ALIGN8(len);
2535105197Ssam	}
2536105197Ssam    }
2537105197Ssam
2538105197Ssam	return tlen;
2539105197Ssam}
2540105197Ssam
2541105197Ssam/*
2542105197Ssam * SADB_SPDEXPIRE processing
2543105197Ssam * send
2544105197Ssam *   <base, address(SD), lifetime(CH), policy>
2545105197Ssam * to KMD by PF_KEY.
2546105197Ssam *
2547105197Ssam * OUT:	0	: succeed
2548105197Ssam *	others	: error number
2549105197Ssam */
2550105197Ssamstatic int
2551105197Ssamkey_spdexpire(sp)
2552105197Ssam	struct secpolicy *sp;
2553105197Ssam{
2554105197Ssam	struct mbuf *result = NULL, *m;
2555105197Ssam	int len;
2556105197Ssam	int error = -1;
2557105197Ssam	struct sadb_lifetime *lt;
2558105197Ssam
2559105197Ssam	/* XXX: Why do we lock ? */
2560105197Ssam
2561120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2562105197Ssam
2563105197Ssam	/* set msg header */
2564105197Ssam	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2565105197Ssam	if (!m) {
2566105197Ssam		error = ENOBUFS;
2567105197Ssam		goto fail;
2568105197Ssam	}
2569105197Ssam	result = m;
2570105197Ssam
2571105197Ssam	/* create lifetime extension (current and hard) */
2572105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2573105197Ssam	m = key_alloc_mbuf(len);
2574105197Ssam	if (!m || m->m_next) {	/*XXX*/
2575105197Ssam		if (m)
2576105197Ssam			m_freem(m);
2577105197Ssam		error = ENOBUFS;
2578105197Ssam		goto fail;
2579105197Ssam	}
2580105197Ssam	bzero(mtod(m, caddr_t), len);
2581105197Ssam	lt = mtod(m, struct sadb_lifetime *);
2582105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2583105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2584105197Ssam	lt->sadb_lifetime_allocations = 0;
2585105197Ssam	lt->sadb_lifetime_bytes = 0;
2586105197Ssam	lt->sadb_lifetime_addtime = sp->created;
2587105197Ssam	lt->sadb_lifetime_usetime = sp->lastused;
2588105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2589105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2590105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2591105197Ssam	lt->sadb_lifetime_allocations = 0;
2592105197Ssam	lt->sadb_lifetime_bytes = 0;
2593105197Ssam	lt->sadb_lifetime_addtime = sp->lifetime;
2594105197Ssam	lt->sadb_lifetime_usetime = sp->validtime;
2595105197Ssam	m_cat(result, m);
2596105197Ssam
2597105197Ssam	/* set sadb_address for source */
2598105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2599105197Ssam	    &sp->spidx.src.sa,
2600105197Ssam	    sp->spidx.prefs, sp->spidx.ul_proto);
2601105197Ssam	if (!m) {
2602105197Ssam		error = ENOBUFS;
2603105197Ssam		goto fail;
2604105197Ssam	}
2605105197Ssam	m_cat(result, m);
2606105197Ssam
2607105197Ssam	/* set sadb_address for destination */
2608105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2609105197Ssam	    &sp->spidx.dst.sa,
2610105197Ssam	    sp->spidx.prefd, sp->spidx.ul_proto);
2611105197Ssam	if (!m) {
2612105197Ssam		error = ENOBUFS;
2613105197Ssam		goto fail;
2614105197Ssam	}
2615105197Ssam	m_cat(result, m);
2616105197Ssam
2617105197Ssam	/* set secpolicy */
2618105197Ssam	m = key_sp2msg(sp);
2619105197Ssam	if (!m) {
2620105197Ssam		error = ENOBUFS;
2621105197Ssam		goto fail;
2622105197Ssam	}
2623105197Ssam	m_cat(result, m);
2624105197Ssam
2625105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
2626105197Ssam		error = EINVAL;
2627105197Ssam		goto fail;
2628105197Ssam	}
2629105197Ssam
2630105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2631105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2632105197Ssam		if (result == NULL) {
2633105197Ssam			error = ENOBUFS;
2634105197Ssam			goto fail;
2635105197Ssam		}
2636105197Ssam	}
2637105197Ssam
2638105197Ssam	result->m_pkthdr.len = 0;
2639105197Ssam	for (m = result; m; m = m->m_next)
2640105197Ssam		result->m_pkthdr.len += m->m_len;
2641105197Ssam
2642105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2643105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2644105197Ssam
2645105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2646105197Ssam
2647105197Ssam fail:
2648105197Ssam	if (result)
2649105197Ssam		m_freem(result);
2650105197Ssam	return error;
2651105197Ssam}
2652105197Ssam
2653105197Ssam/* %%% SAD management */
2654105197Ssam/*
2655105197Ssam * allocating a memory for new SA head, and copy from the values of mhp.
2656105197Ssam * OUT:	NULL	: failure due to the lack of memory.
2657105197Ssam *	others	: pointer to new SA head.
2658105197Ssam */
2659105197Ssamstatic struct secashead *
2660105197Ssamkey_newsah(saidx)
2661105197Ssam	struct secasindex *saidx;
2662105197Ssam{
2663183550Szec	INIT_VNET_IPSEC(curvnet);
2664105197Ssam	struct secashead *newsah;
2665105197Ssam
2666120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2667105197Ssam
2668119643Ssam	newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2669105197Ssam	if (newsah != NULL) {
2670105197Ssam		int i;
2671105197Ssam		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2672105197Ssam			LIST_INIT(&newsah->savtree[i]);
2673105197Ssam		newsah->saidx = *saidx;
2674105197Ssam
2675105197Ssam		/* add to saidxtree */
2676105197Ssam		newsah->state = SADB_SASTATE_MATURE;
2677119643Ssam
2678120585Ssam		SAHTREE_LOCK();
2679181803Sbz		LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2680120585Ssam		SAHTREE_UNLOCK();
2681105197Ssam	}
2682105197Ssam	return(newsah);
2683105197Ssam}
2684105197Ssam
2685105197Ssam/*
2686105197Ssam * delete SA index and all SA registerd.
2687105197Ssam */
2688105197Ssamstatic void
2689105197Ssamkey_delsah(sah)
2690105197Ssam	struct secashead *sah;
2691105197Ssam{
2692183550Szec	INIT_VNET_IPSEC(curvnet);
2693105197Ssam	struct secasvar *sav, *nextsav;
2694120585Ssam	u_int stateidx;
2695105197Ssam	int zombie = 0;
2696105197Ssam
2697120585Ssam	IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2698120585Ssam	SAHTREE_LOCK_ASSERT();
2699105197Ssam
2700105197Ssam	/* searching all SA registerd in the secindex. */
2701105197Ssam	for (stateidx = 0;
2702185348Szec	     stateidx < _ARRAYLEN(saorder_state_any);
2703105197Ssam	     stateidx++) {
2704185348Szec		u_int state = saorder_state_any[stateidx];
2705120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2706105197Ssam			if (sav->refcnt == 0) {
2707105197Ssam				/* sanity check */
2708120585Ssam				KEY_CHKSASTATE(state, sav->state, __func__);
2709105197Ssam				KEY_FREESAV(&sav);
2710105197Ssam			} else {
2711105197Ssam				/* give up to delete this sa */
2712105197Ssam				zombie++;
2713105197Ssam			}
2714105197Ssam		}
2715105197Ssam	}
2716120585Ssam	if (!zombie) {		/* delete only if there are savs */
2717120585Ssam		/* remove from tree of SA index */
2718120585Ssam		if (__LIST_CHAINED(sah))
2719120585Ssam			LIST_REMOVE(sah, chain);
2720120585Ssam		if (sah->sa_route.ro_rt) {
2721120585Ssam			RTFREE(sah->sa_route.ro_rt);
2722120585Ssam			sah->sa_route.ro_rt = (struct rtentry *)NULL;
2723120585Ssam		}
2724120585Ssam		free(sah, M_IPSEC_SAH);
2725105197Ssam	}
2726105197Ssam}
2727105197Ssam
2728105197Ssam/*
2729105197Ssam * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2730105197Ssam * and copy the values of mhp into new buffer.
2731105197Ssam * When SAD message type is GETSPI:
2732105197Ssam *	to set sequence number from acq_seq++,
2733105197Ssam *	to set zero to SPI.
2734105197Ssam *	not to call key_setsava().
2735105197Ssam * OUT:	NULL	: fail
2736105197Ssam *	others	: pointer to new secasvar.
2737105197Ssam *
2738105197Ssam * does not modify mbuf.  does not free mbuf on error.
2739105197Ssam */
2740105197Ssamstatic struct secasvar *
2741105197Ssamkey_newsav(m, mhp, sah, errp, where, tag)
2742105197Ssam	struct mbuf *m;
2743105197Ssam	const struct sadb_msghdr *mhp;
2744105197Ssam	struct secashead *sah;
2745105197Ssam	int *errp;
2746105197Ssam	const char* where;
2747105197Ssam	int tag;
2748105197Ssam{
2749183550Szec	INIT_VNET_IPSEC(curvnet);
2750105197Ssam	struct secasvar *newsav;
2751105197Ssam	const struct sadb_sa *xsa;
2752105197Ssam
2753120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2754120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2755120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2756120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
2757105197Ssam
2758119643Ssam	newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2759105197Ssam	if (newsav == NULL) {
2760120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2761105197Ssam		*errp = ENOBUFS;
2762105197Ssam		goto done;
2763105197Ssam	}
2764105197Ssam
2765105197Ssam	switch (mhp->msg->sadb_msg_type) {
2766105197Ssam	case SADB_GETSPI:
2767105197Ssam		newsav->spi = 0;
2768105197Ssam
2769105197Ssam#ifdef IPSEC_DOSEQCHECK
2770105197Ssam		/* sync sequence number */
2771105197Ssam		if (mhp->msg->sadb_msg_seq == 0)
2772105197Ssam			newsav->seq =
2773181803Sbz				(V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2774105197Ssam		else
2775105197Ssam#endif
2776105197Ssam			newsav->seq = mhp->msg->sadb_msg_seq;
2777105197Ssam		break;
2778105197Ssam
2779105197Ssam	case SADB_ADD:
2780105197Ssam		/* sanity check */
2781105197Ssam		if (mhp->ext[SADB_EXT_SA] == NULL) {
2782119643Ssam			free(newsav, M_IPSEC_SA);
2783119643Ssam			newsav = NULL;
2784120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2785120585Ssam				__func__));
2786105197Ssam			*errp = EINVAL;
2787105197Ssam			goto done;
2788105197Ssam		}
2789105197Ssam		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2790105197Ssam		newsav->spi = xsa->sadb_sa_spi;
2791105197Ssam		newsav->seq = mhp->msg->sadb_msg_seq;
2792105197Ssam		break;
2793105197Ssam	default:
2794119643Ssam		free(newsav, M_IPSEC_SA);
2795119643Ssam		newsav = NULL;
2796105197Ssam		*errp = EINVAL;
2797105197Ssam		goto done;
2798105197Ssam	}
2799105197Ssam
2800119643Ssam
2801105197Ssam	/* copy sav values */
2802105197Ssam	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2803105197Ssam		*errp = key_setsaval(newsav, m, mhp);
2804105197Ssam		if (*errp) {
2805119643Ssam			free(newsav, M_IPSEC_SA);
2806119643Ssam			newsav = NULL;
2807105197Ssam			goto done;
2808105197Ssam		}
2809105197Ssam	}
2810105197Ssam
2811120585Ssam	SECASVAR_LOCK_INIT(newsav);
2812119643Ssam
2813105197Ssam	/* reset created */
2814105197Ssam	newsav->created = time_second;
2815105197Ssam	newsav->pid = mhp->msg->sadb_msg_pid;
2816105197Ssam
2817105197Ssam	/* add to satree */
2818105197Ssam	newsav->sah = sah;
2819158767Spjd	sa_initref(newsav);
2820105197Ssam	newsav->state = SADB_SASTATE_LARVAL;
2821119643Ssam
2822119643Ssam	/* XXX locking??? */
2823105197Ssam	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2824105197Ssam			secasvar, chain);
2825105197Ssamdone:
2826105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2827120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
2828105197Ssam			where, tag, newsav));
2829105197Ssam
2830105197Ssam	return newsav;
2831105197Ssam}
2832105197Ssam
2833105197Ssam/*
2834105197Ssam * free() SA variable entry.
2835105197Ssam */
2836105197Ssamstatic void
2837119643Ssamkey_cleansav(struct secasvar *sav)
2838105197Ssam{
2839117051Ssam	/*
2840117051Ssam	 * Cleanup xform state.  Note that zeroize'ing causes the
2841117051Ssam	 * keys to be cleared; otherwise we must do it ourself.
2842117051Ssam	 */
2843117051Ssam	if (sav->tdb_xform != NULL) {
2844117051Ssam		sav->tdb_xform->xf_zeroize(sav);
2845117051Ssam		sav->tdb_xform = NULL;
2846117051Ssam	} else {
2847120585Ssam		KASSERT(sav->iv == NULL, ("iv but no xform"));
2848117051Ssam		if (sav->key_auth != NULL)
2849157123Sgnn			bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2850117051Ssam		if (sav->key_enc != NULL)
2851157123Sgnn			bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2852117051Ssam	}
2853105197Ssam	if (sav->key_auth != NULL) {
2854157123Sgnn		if (sav->key_auth->key_data != NULL)
2855157123Sgnn			free(sav->key_auth->key_data, M_IPSEC_MISC);
2856119643Ssam		free(sav->key_auth, M_IPSEC_MISC);
2857105197Ssam		sav->key_auth = NULL;
2858105197Ssam	}
2859105197Ssam	if (sav->key_enc != NULL) {
2860157123Sgnn		if (sav->key_enc->key_data != NULL)
2861157123Sgnn			free(sav->key_enc->key_data, M_IPSEC_MISC);
2862119643Ssam		free(sav->key_enc, M_IPSEC_MISC);
2863105197Ssam		sav->key_enc = NULL;
2864105197Ssam	}
2865105197Ssam	if (sav->sched) {
2866105197Ssam		bzero(sav->sched, sav->schedlen);
2867119643Ssam		free(sav->sched, M_IPSEC_MISC);
2868105197Ssam		sav->sched = NULL;
2869105197Ssam	}
2870105197Ssam	if (sav->replay != NULL) {
2871119643Ssam		free(sav->replay, M_IPSEC_MISC);
2872105197Ssam		sav->replay = NULL;
2873105197Ssam	}
2874105197Ssam	if (sav->lft_c != NULL) {
2875119643Ssam		free(sav->lft_c, M_IPSEC_MISC);
2876105197Ssam		sav->lft_c = NULL;
2877105197Ssam	}
2878105197Ssam	if (sav->lft_h != NULL) {
2879119643Ssam		free(sav->lft_h, M_IPSEC_MISC);
2880105197Ssam		sav->lft_h = NULL;
2881105197Ssam	}
2882105197Ssam	if (sav->lft_s != NULL) {
2883119643Ssam		free(sav->lft_s, M_IPSEC_MISC);
2884105197Ssam		sav->lft_s = NULL;
2885105197Ssam	}
2886119643Ssam}
2887105197Ssam
2888119643Ssam/*
2889119643Ssam * free() SA variable entry.
2890119643Ssam */
2891119643Ssamstatic void
2892119643Ssamkey_delsav(sav)
2893119643Ssam	struct secasvar *sav;
2894119643Ssam{
2895120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
2896120585Ssam	IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2897105197Ssam
2898119643Ssam	/* remove from SA header */
2899119643Ssam	if (__LIST_CHAINED(sav))
2900119643Ssam		LIST_REMOVE(sav, chain);
2901119643Ssam	key_cleansav(sav);
2902120585Ssam	SECASVAR_LOCK_DESTROY(sav);
2903119643Ssam	free(sav, M_IPSEC_SA);
2904105197Ssam}
2905105197Ssam
2906105197Ssam/*
2907105197Ssam * search SAD.
2908105197Ssam * OUT:
2909105197Ssam *	NULL	: not found
2910105197Ssam *	others	: found, pointer to a SA.
2911105197Ssam */
2912105197Ssamstatic struct secashead *
2913105197Ssamkey_getsah(saidx)
2914105197Ssam	struct secasindex *saidx;
2915105197Ssam{
2916183550Szec	INIT_VNET_IPSEC(curvnet);
2917105197Ssam	struct secashead *sah;
2918105197Ssam
2919120585Ssam	SAHTREE_LOCK();
2920181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
2921105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
2922105197Ssam			continue;
2923105197Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2924119643Ssam			break;
2925105197Ssam	}
2926120585Ssam	SAHTREE_UNLOCK();
2927105197Ssam
2928119643Ssam	return sah;
2929105197Ssam}
2930105197Ssam
2931105197Ssam/*
2932105197Ssam * check not to be duplicated SPI.
2933105197Ssam * NOTE: this function is too slow due to searching all SAD.
2934105197Ssam * OUT:
2935105197Ssam *	NULL	: not found
2936105197Ssam *	others	: found, pointer to a SA.
2937105197Ssam */
2938105197Ssamstatic struct secasvar *
2939105197Ssamkey_checkspidup(saidx, spi)
2940105197Ssam	struct secasindex *saidx;
2941105197Ssam	u_int32_t spi;
2942105197Ssam{
2943183550Szec	INIT_VNET_IPSEC(curvnet);
2944105197Ssam	struct secashead *sah;
2945105197Ssam	struct secasvar *sav;
2946105197Ssam
2947105197Ssam	/* check address family */
2948105197Ssam	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2949120585Ssam		ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2950120585Ssam			__func__));
2951105197Ssam		return NULL;
2952105197Ssam	}
2953105197Ssam
2954119643Ssam	sav = NULL;
2955105197Ssam	/* check all SAD */
2956120585Ssam	SAHTREE_LOCK();
2957181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
2958105197Ssam		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2959105197Ssam			continue;
2960105197Ssam		sav = key_getsavbyspi(sah, spi);
2961105197Ssam		if (sav != NULL)
2962119643Ssam			break;
2963105197Ssam	}
2964120585Ssam	SAHTREE_UNLOCK();
2965105197Ssam
2966119643Ssam	return sav;
2967105197Ssam}
2968105197Ssam
2969105197Ssam/*
2970105197Ssam * search SAD litmited alive SA, protocol, SPI.
2971105197Ssam * OUT:
2972105197Ssam *	NULL	: not found
2973105197Ssam *	others	: found, pointer to a SA.
2974105197Ssam */
2975105197Ssamstatic struct secasvar *
2976105197Ssamkey_getsavbyspi(sah, spi)
2977105197Ssam	struct secashead *sah;
2978105197Ssam	u_int32_t spi;
2979105197Ssam{
2980183550Szec	INIT_VNET_IPSEC(curvnet);
2981105197Ssam	struct secasvar *sav;
2982105197Ssam	u_int stateidx, state;
2983105197Ssam
2984119643Ssam	sav = NULL;
2985120585Ssam	SAHTREE_LOCK_ASSERT();
2986105197Ssam	/* search all status */
2987105197Ssam	for (stateidx = 0;
2988185348Szec	     stateidx < _ARRAYLEN(saorder_state_alive);
2989105197Ssam	     stateidx++) {
2990105197Ssam
2991185348Szec		state = saorder_state_alive[stateidx];
2992105197Ssam		LIST_FOREACH(sav, &sah->savtree[state], chain) {
2993105197Ssam
2994105197Ssam			/* sanity check */
2995105197Ssam			if (sav->state != state) {
2996120585Ssam				ipseclog((LOG_DEBUG, "%s: "
2997105197Ssam				    "invalid sav->state (queue: %d SA: %d)\n",
2998120585Ssam				    __func__, state, sav->state));
2999105197Ssam				continue;
3000105197Ssam			}
3001105197Ssam
3002105197Ssam			if (sav->spi == spi)
3003128859Ssam				return sav;
3004105197Ssam		}
3005105197Ssam	}
3006105197Ssam
3007128859Ssam	return NULL;
3008105197Ssam}
3009105197Ssam
3010105197Ssam/*
3011105197Ssam * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3012105197Ssam * You must update these if need.
3013105197Ssam * OUT:	0:	success.
3014105197Ssam *	!0:	failure.
3015105197Ssam *
3016105197Ssam * does not modify mbuf.  does not free mbuf on error.
3017105197Ssam */
3018105197Ssamstatic int
3019105197Ssamkey_setsaval(sav, m, mhp)
3020105197Ssam	struct secasvar *sav;
3021105197Ssam	struct mbuf *m;
3022105197Ssam	const struct sadb_msghdr *mhp;
3023105197Ssam{
3024183550Szec	INIT_VNET_IPSEC(curvnet);
3025105197Ssam	int error = 0;
3026105197Ssam
3027120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
3028120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3029120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3030105197Ssam
3031105197Ssam	/* initialization */
3032105197Ssam	sav->replay = NULL;
3033105197Ssam	sav->key_auth = NULL;
3034105197Ssam	sav->key_enc = NULL;
3035105197Ssam	sav->sched = NULL;
3036105197Ssam	sav->schedlen = 0;
3037105197Ssam	sav->iv = NULL;
3038105197Ssam	sav->lft_c = NULL;
3039105197Ssam	sav->lft_h = NULL;
3040105197Ssam	sav->lft_s = NULL;
3041105197Ssam	sav->tdb_xform = NULL;		/* transform */
3042105197Ssam	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
3043105197Ssam	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
3044105197Ssam	sav->tdb_compalgxform = NULL;	/* compression algorithm */
3045105197Ssam
3046105197Ssam	/* SA */
3047105197Ssam	if (mhp->ext[SADB_EXT_SA] != NULL) {
3048105197Ssam		const struct sadb_sa *sa0;
3049105197Ssam
3050105197Ssam		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3051105197Ssam		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3052105197Ssam			error = EINVAL;
3053105197Ssam			goto fail;
3054105197Ssam		}
3055105197Ssam
3056105197Ssam		sav->alg_auth = sa0->sadb_sa_auth;
3057105197Ssam		sav->alg_enc = sa0->sadb_sa_encrypt;
3058105197Ssam		sav->flags = sa0->sadb_sa_flags;
3059105197Ssam
3060105197Ssam		/* replay window */
3061105197Ssam		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3062105197Ssam			sav->replay = (struct secreplay *)
3063119643Ssam				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3064105197Ssam			if (sav->replay == NULL) {
3065120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3066120585Ssam					__func__));
3067105197Ssam				error = ENOBUFS;
3068105197Ssam				goto fail;
3069105197Ssam			}
3070105197Ssam			if (sa0->sadb_sa_replay != 0)
3071105197Ssam				sav->replay->bitmap = (caddr_t)(sav->replay+1);
3072105197Ssam			sav->replay->wsize = sa0->sadb_sa_replay;
3073105197Ssam		}
3074105197Ssam	}
3075105197Ssam
3076105197Ssam	/* Authentication keys */
3077105197Ssam	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3078105197Ssam		const struct sadb_key *key0;
3079105197Ssam		int len;
3080105197Ssam
3081105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3082105197Ssam		len = mhp->extlen[SADB_EXT_KEY_AUTH];
3083105197Ssam
3084105197Ssam		error = 0;
3085105197Ssam		if (len < sizeof(*key0)) {
3086105197Ssam			error = EINVAL;
3087105197Ssam			goto fail;
3088105197Ssam		}
3089105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3090105197Ssam		case SADB_SATYPE_AH:
3091105197Ssam		case SADB_SATYPE_ESP:
3092125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3093105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3094105197Ssam			    sav->alg_auth != SADB_X_AALG_NULL)
3095105197Ssam				error = EINVAL;
3096105197Ssam			break;
3097105197Ssam		case SADB_X_SATYPE_IPCOMP:
3098105197Ssam		default:
3099105197Ssam			error = EINVAL;
3100105197Ssam			break;
3101105197Ssam		}
3102105197Ssam		if (error) {
3103120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3104120585Ssam				__func__));
3105105197Ssam			goto fail;
3106105197Ssam		}
3107105197Ssam
3108157123Sgnn		sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3109157123Sgnn								M_IPSEC_MISC);
3110157123Sgnn		if (sav->key_auth == NULL ) {
3111157123Sgnn			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3112157123Sgnn				  __func__));
3113105197Ssam			error = ENOBUFS;
3114105197Ssam			goto fail;
3115105197Ssam		}
3116105197Ssam	}
3117105197Ssam
3118105197Ssam	/* Encryption key */
3119105197Ssam	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3120105197Ssam		const struct sadb_key *key0;
3121105197Ssam		int len;
3122105197Ssam
3123105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3124105197Ssam		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3125105197Ssam
3126105197Ssam		error = 0;
3127105197Ssam		if (len < sizeof(*key0)) {
3128105197Ssam			error = EINVAL;
3129105197Ssam			goto fail;
3130105197Ssam		}
3131105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3132105197Ssam		case SADB_SATYPE_ESP:
3133105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3134105197Ssam			    sav->alg_enc != SADB_EALG_NULL) {
3135105197Ssam				error = EINVAL;
3136105197Ssam				break;
3137105197Ssam			}
3138157123Sgnn			sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3139157123Sgnn								       len,
3140157123Sgnn								       M_IPSEC_MISC);
3141105197Ssam			if (sav->key_enc == NULL) {
3142120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3143120585Ssam					__func__));
3144105197Ssam				error = ENOBUFS;
3145105197Ssam				goto fail;
3146105197Ssam			}
3147105197Ssam			break;
3148105197Ssam		case SADB_X_SATYPE_IPCOMP:
3149105197Ssam			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3150105197Ssam				error = EINVAL;
3151105197Ssam			sav->key_enc = NULL;	/*just in case*/
3152105197Ssam			break;
3153105197Ssam		case SADB_SATYPE_AH:
3154125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3155105197Ssam		default:
3156105197Ssam			error = EINVAL;
3157105197Ssam			break;
3158105197Ssam		}
3159105197Ssam		if (error) {
3160120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3161120585Ssam				__func__));
3162105197Ssam			goto fail;
3163105197Ssam		}
3164105197Ssam	}
3165105197Ssam
3166105197Ssam	/* set iv */
3167105197Ssam	sav->ivlen = 0;
3168105197Ssam
3169105197Ssam	switch (mhp->msg->sadb_msg_satype) {
3170105197Ssam	case SADB_SATYPE_AH:
3171105197Ssam		error = xform_init(sav, XF_AH);
3172105197Ssam		break;
3173105197Ssam	case SADB_SATYPE_ESP:
3174105197Ssam		error = xform_init(sav, XF_ESP);
3175105197Ssam		break;
3176105197Ssam	case SADB_X_SATYPE_IPCOMP:
3177105197Ssam		error = xform_init(sav, XF_IPCOMP);
3178105197Ssam		break;
3179125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
3180125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3181125680Sbms		break;
3182105197Ssam	}
3183105197Ssam	if (error) {
3184120585Ssam		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3185120585Ssam		        __func__, mhp->msg->sadb_msg_satype));
3186105197Ssam		goto fail;
3187105197Ssam	}
3188105197Ssam
3189105197Ssam	/* reset created */
3190105197Ssam	sav->created = time_second;
3191105197Ssam
3192105197Ssam	/* make lifetime for CURRENT */
3193176743Sbz	sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3194105197Ssam	if (sav->lft_c == NULL) {
3195120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3196105197Ssam		error = ENOBUFS;
3197105197Ssam		goto fail;
3198105197Ssam	}
3199105197Ssam
3200157123Sgnn	sav->lft_c->allocations = 0;
3201157123Sgnn	sav->lft_c->bytes = 0;
3202157123Sgnn	sav->lft_c->addtime = time_second;
3203157123Sgnn	sav->lft_c->usetime = 0;
3204105197Ssam
3205105197Ssam	/* lifetimes for HARD and SOFT */
3206105197Ssam    {
3207105197Ssam	const struct sadb_lifetime *lft0;
3208105197Ssam
3209105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3210105197Ssam	if (lft0 != NULL) {
3211105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3212105197Ssam			error = EINVAL;
3213105197Ssam			goto fail;
3214105197Ssam		}
3215157123Sgnn		sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3216105197Ssam		if (sav->lft_h == NULL) {
3217120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3218105197Ssam			error = ENOBUFS;
3219105197Ssam			goto fail;
3220105197Ssam		}
3221105197Ssam		/* to be initialize ? */
3222105197Ssam	}
3223105197Ssam
3224105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3225105197Ssam	if (lft0 != NULL) {
3226105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3227105197Ssam			error = EINVAL;
3228105197Ssam			goto fail;
3229105197Ssam		}
3230157123Sgnn		sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3231105197Ssam		if (sav->lft_s == NULL) {
3232120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3233105197Ssam			error = ENOBUFS;
3234105197Ssam			goto fail;
3235105197Ssam		}
3236105197Ssam		/* to be initialize ? */
3237105197Ssam	}
3238105197Ssam    }
3239105197Ssam
3240105197Ssam	return 0;
3241105197Ssam
3242105197Ssam fail:
3243105197Ssam	/* initialization */
3244119643Ssam	key_cleansav(sav);
3245105197Ssam
3246105197Ssam	return error;
3247105197Ssam}
3248105197Ssam
3249105197Ssam/*
3250105197Ssam * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3251105197Ssam * OUT:	0:	valid
3252105197Ssam *	other:	errno
3253105197Ssam */
3254105197Ssamstatic int
3255119643Ssamkey_mature(struct secasvar *sav)
3256105197Ssam{
3257183550Szec	INIT_VNET_IPSEC(curvnet);
3258105197Ssam	int error;
3259105197Ssam
3260105197Ssam	/* check SPI value */
3261105197Ssam	switch (sav->sah->saidx.proto) {
3262105197Ssam	case IPPROTO_ESP:
3263105197Ssam	case IPPROTO_AH:
3264170823Sbz		/*
3265170823Sbz		 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3266170823Sbz		 * 1-255 reserved by IANA for future use,
3267170823Sbz		 * 0 for implementation specific, local use.
3268170823Sbz		 */
3269170823Sbz		if (ntohl(sav->spi) <= 255) {
3270120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3271120585Ssam			    __func__, (u_int32_t)ntohl(sav->spi)));
3272105197Ssam			return EINVAL;
3273105197Ssam		}
3274105197Ssam		break;
3275105197Ssam	}
3276105197Ssam
3277105197Ssam	/* check satype */
3278105197Ssam	switch (sav->sah->saidx.proto) {
3279105197Ssam	case IPPROTO_ESP:
3280105197Ssam		/* check flags */
3281105197Ssam		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3282105197Ssam		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3283120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3284120585Ssam				"given to old-esp.\n", __func__));
3285105197Ssam			return EINVAL;
3286105197Ssam		}
3287105197Ssam		error = xform_init(sav, XF_ESP);
3288105197Ssam		break;
3289105197Ssam	case IPPROTO_AH:
3290105197Ssam		/* check flags */
3291105197Ssam		if (sav->flags & SADB_X_EXT_DERIV) {
3292120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3293120585Ssam				"given to AH SA.\n", __func__));
3294105197Ssam			return EINVAL;
3295105197Ssam		}
3296105197Ssam		if (sav->alg_enc != SADB_EALG_NONE) {
3297120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3298120585Ssam				"mismated.\n", __func__));
3299105197Ssam			return(EINVAL);
3300105197Ssam		}
3301105197Ssam		error = xform_init(sav, XF_AH);
3302105197Ssam		break;
3303105197Ssam	case IPPROTO_IPCOMP:
3304105197Ssam		if (sav->alg_auth != SADB_AALG_NONE) {
3305120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3306120585Ssam				"mismated.\n", __func__));
3307105197Ssam			return(EINVAL);
3308105197Ssam		}
3309105197Ssam		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3310105197Ssam		 && ntohl(sav->spi) >= 0x10000) {
3311120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3312120585Ssam				__func__));
3313105197Ssam			return(EINVAL);
3314105197Ssam		}
3315105197Ssam		error = xform_init(sav, XF_IPCOMP);
3316105197Ssam		break;
3317125680Sbms	case IPPROTO_TCP:
3318125680Sbms		if (sav->alg_enc != SADB_EALG_NONE) {
3319125680Sbms			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3320125680Sbms				"mismated.\n", __func__));
3321125680Sbms			return(EINVAL);
3322125680Sbms		}
3323125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3324125680Sbms		break;
3325105197Ssam	default:
3326120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3327105197Ssam		error = EPROTONOSUPPORT;
3328105197Ssam		break;
3329105197Ssam	}
3330119643Ssam	if (error == 0) {
3331120585Ssam		SAHTREE_LOCK();
3332105197Ssam		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3333120585Ssam		SAHTREE_UNLOCK();
3334119643Ssam	}
3335105197Ssam	return (error);
3336105197Ssam}
3337105197Ssam
3338105197Ssam/*
3339105197Ssam * subroutine for SADB_GET and SADB_DUMP.
3340105197Ssam */
3341105197Ssamstatic struct mbuf *
3342105197Ssamkey_setdumpsa(sav, type, satype, seq, pid)
3343105197Ssam	struct secasvar *sav;
3344105197Ssam	u_int8_t type, satype;
3345105197Ssam	u_int32_t seq, pid;
3346105197Ssam{
3347105197Ssam	struct mbuf *result = NULL, *tres = NULL, *m;
3348105197Ssam	int i;
3349105197Ssam	int dumporder[] = {
3350105197Ssam		SADB_EXT_SA, SADB_X_EXT_SA2,
3351105197Ssam		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3352105197Ssam		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3353105197Ssam		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3354105197Ssam		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3355105197Ssam		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3356105197Ssam	};
3357105197Ssam
3358105197Ssam	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3359105197Ssam	if (m == NULL)
3360105197Ssam		goto fail;
3361105197Ssam	result = m;
3362105197Ssam
3363105197Ssam	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3364105197Ssam		m = NULL;
3365105197Ssam		switch (dumporder[i]) {
3366105197Ssam		case SADB_EXT_SA:
3367105197Ssam			m = key_setsadbsa(sav);
3368105197Ssam			if (!m)
3369105197Ssam				goto fail;
3370105197Ssam			break;
3371105197Ssam
3372105197Ssam		case SADB_X_EXT_SA2:
3373105197Ssam			m = key_setsadbxsa2(sav->sah->saidx.mode,
3374105197Ssam					sav->replay ? sav->replay->count : 0,
3375105197Ssam					sav->sah->saidx.reqid);
3376105197Ssam			if (!m)
3377105197Ssam				goto fail;
3378105197Ssam			break;
3379105197Ssam
3380105197Ssam		case SADB_EXT_ADDRESS_SRC:
3381105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3382105197Ssam			    &sav->sah->saidx.src.sa,
3383105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3384105197Ssam			if (!m)
3385105197Ssam				goto fail;
3386105197Ssam			break;
3387105197Ssam
3388105197Ssam		case SADB_EXT_ADDRESS_DST:
3389105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3390105197Ssam			    &sav->sah->saidx.dst.sa,
3391105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3392105197Ssam			if (!m)
3393105197Ssam				goto fail;
3394105197Ssam			break;
3395105197Ssam
3396105197Ssam		case SADB_EXT_KEY_AUTH:
3397105197Ssam			if (!sav->key_auth)
3398105197Ssam				continue;
3399157123Sgnn			m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3400157123Sgnn			if (!m)
3401157123Sgnn				goto fail;
3402105197Ssam			break;
3403105197Ssam
3404105197Ssam		case SADB_EXT_KEY_ENCRYPT:
3405105197Ssam			if (!sav->key_enc)
3406105197Ssam				continue;
3407157123Sgnn			m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3408157123Sgnn			if (!m)
3409157123Sgnn				goto fail;
3410105197Ssam			break;
3411105197Ssam
3412105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
3413105197Ssam			if (!sav->lft_c)
3414105197Ssam				continue;
3415157123Sgnn			m = key_setlifetime(sav->lft_c,
3416157123Sgnn					    SADB_EXT_LIFETIME_CURRENT);
3417157123Sgnn			if (!m)
3418157123Sgnn				goto fail;
3419105197Ssam			break;
3420105197Ssam
3421105197Ssam		case SADB_EXT_LIFETIME_HARD:
3422105197Ssam			if (!sav->lft_h)
3423105197Ssam				continue;
3424157123Sgnn			m = key_setlifetime(sav->lft_h,
3425157123Sgnn					    SADB_EXT_LIFETIME_HARD);
3426157123Sgnn			if (!m)
3427157123Sgnn				goto fail;
3428105197Ssam			break;
3429105197Ssam
3430105197Ssam		case SADB_EXT_LIFETIME_SOFT:
3431105197Ssam			if (!sav->lft_s)
3432105197Ssam				continue;
3433177554Sbz			m = key_setlifetime(sav->lft_s,
3434157123Sgnn					    SADB_EXT_LIFETIME_SOFT);
3435157123Sgnn
3436157123Sgnn			if (!m)
3437157123Sgnn				goto fail;
3438105197Ssam			break;
3439105197Ssam
3440105197Ssam		case SADB_EXT_ADDRESS_PROXY:
3441105197Ssam		case SADB_EXT_IDENTITY_SRC:
3442105197Ssam		case SADB_EXT_IDENTITY_DST:
3443105197Ssam			/* XXX: should we brought from SPD ? */
3444105197Ssam		case SADB_EXT_SENSITIVITY:
3445105197Ssam		default:
3446105197Ssam			continue;
3447105197Ssam		}
3448105197Ssam
3449157123Sgnn		if (!m)
3450105197Ssam			goto fail;
3451105197Ssam		if (tres)
3452105197Ssam			m_cat(m, tres);
3453105197Ssam		tres = m;
3454157123Sgnn
3455105197Ssam	}
3456105197Ssam
3457105197Ssam	m_cat(result, tres);
3458105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
3459105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
3460105197Ssam		if (result == NULL)
3461105197Ssam			goto fail;
3462105197Ssam	}
3463105197Ssam
3464105197Ssam	result->m_pkthdr.len = 0;
3465105197Ssam	for (m = result; m; m = m->m_next)
3466105197Ssam		result->m_pkthdr.len += m->m_len;
3467105197Ssam
3468105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
3469105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
3470105197Ssam
3471105197Ssam	return result;
3472105197Ssam
3473105197Ssamfail:
3474105197Ssam	m_freem(result);
3475105197Ssam	m_freem(tres);
3476105197Ssam	return NULL;
3477105197Ssam}
3478105197Ssam
3479105197Ssam/*
3480105197Ssam * set data into sadb_msg.
3481105197Ssam */
3482105197Ssamstatic struct mbuf *
3483105197Ssamkey_setsadbmsg(type, tlen, satype, seq, pid, reserved)
3484105197Ssam	u_int8_t type, satype;
3485105197Ssam	u_int16_t tlen;
3486105197Ssam	u_int32_t seq;
3487105197Ssam	pid_t pid;
3488105197Ssam	u_int16_t reserved;
3489105197Ssam{
3490105197Ssam	struct mbuf *m;
3491105197Ssam	struct sadb_msg *p;
3492105197Ssam	int len;
3493105197Ssam
3494105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3495105197Ssam	if (len > MCLBYTES)
3496105197Ssam		return NULL;
3497111119Simp	MGETHDR(m, M_DONTWAIT, MT_DATA);
3498105197Ssam	if (m && len > MHLEN) {
3499111119Simp		MCLGET(m, M_DONTWAIT);
3500105197Ssam		if ((m->m_flags & M_EXT) == 0) {
3501105197Ssam			m_freem(m);
3502105197Ssam			m = NULL;
3503105197Ssam		}
3504105197Ssam	}
3505105197Ssam	if (!m)
3506105197Ssam		return NULL;
3507105197Ssam	m->m_pkthdr.len = m->m_len = len;
3508105197Ssam	m->m_next = NULL;
3509105197Ssam
3510105197Ssam	p = mtod(m, struct sadb_msg *);
3511105197Ssam
3512105197Ssam	bzero(p, len);
3513105197Ssam	p->sadb_msg_version = PF_KEY_V2;
3514105197Ssam	p->sadb_msg_type = type;
3515105197Ssam	p->sadb_msg_errno = 0;
3516105197Ssam	p->sadb_msg_satype = satype;
3517105197Ssam	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3518105197Ssam	p->sadb_msg_reserved = reserved;
3519105197Ssam	p->sadb_msg_seq = seq;
3520105197Ssam	p->sadb_msg_pid = (u_int32_t)pid;
3521105197Ssam
3522105197Ssam	return m;
3523105197Ssam}
3524105197Ssam
3525105197Ssam/*
3526105197Ssam * copy secasvar data into sadb_address.
3527105197Ssam */
3528105197Ssamstatic struct mbuf *
3529105197Ssamkey_setsadbsa(sav)
3530105197Ssam	struct secasvar *sav;
3531105197Ssam{
3532105197Ssam	struct mbuf *m;
3533105197Ssam	struct sadb_sa *p;
3534105197Ssam	int len;
3535105197Ssam
3536105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3537105197Ssam	m = key_alloc_mbuf(len);
3538105197Ssam	if (!m || m->m_next) {	/*XXX*/
3539105197Ssam		if (m)
3540105197Ssam			m_freem(m);
3541105197Ssam		return NULL;
3542105197Ssam	}
3543105197Ssam
3544105197Ssam	p = mtod(m, struct sadb_sa *);
3545105197Ssam
3546105197Ssam	bzero(p, len);
3547105197Ssam	p->sadb_sa_len = PFKEY_UNIT64(len);
3548105197Ssam	p->sadb_sa_exttype = SADB_EXT_SA;
3549105197Ssam	p->sadb_sa_spi = sav->spi;
3550105197Ssam	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3551105197Ssam	p->sadb_sa_state = sav->state;
3552105197Ssam	p->sadb_sa_auth = sav->alg_auth;
3553105197Ssam	p->sadb_sa_encrypt = sav->alg_enc;
3554105197Ssam	p->sadb_sa_flags = sav->flags;
3555105197Ssam
3556105197Ssam	return m;
3557105197Ssam}
3558105197Ssam
3559105197Ssam/*
3560105197Ssam * set data into sadb_address.
3561105197Ssam */
3562105197Ssamstatic struct mbuf *
3563105197Ssamkey_setsadbaddr(exttype, saddr, prefixlen, ul_proto)
3564105197Ssam	u_int16_t exttype;
3565105197Ssam	const struct sockaddr *saddr;
3566105197Ssam	u_int8_t prefixlen;
3567105197Ssam	u_int16_t ul_proto;
3568105197Ssam{
3569105197Ssam	struct mbuf *m;
3570105197Ssam	struct sadb_address *p;
3571105197Ssam	size_t len;
3572105197Ssam
3573105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3574105197Ssam	    PFKEY_ALIGN8(saddr->sa_len);
3575105197Ssam	m = key_alloc_mbuf(len);
3576105197Ssam	if (!m || m->m_next) {	/*XXX*/
3577105197Ssam		if (m)
3578105197Ssam			m_freem(m);
3579105197Ssam		return NULL;
3580105197Ssam	}
3581105197Ssam
3582105197Ssam	p = mtod(m, struct sadb_address *);
3583105197Ssam
3584105197Ssam	bzero(p, len);
3585105197Ssam	p->sadb_address_len = PFKEY_UNIT64(len);
3586105197Ssam	p->sadb_address_exttype = exttype;
3587105197Ssam	p->sadb_address_proto = ul_proto;
3588105197Ssam	if (prefixlen == FULLMASK) {
3589105197Ssam		switch (saddr->sa_family) {
3590105197Ssam		case AF_INET:
3591105197Ssam			prefixlen = sizeof(struct in_addr) << 3;
3592105197Ssam			break;
3593105197Ssam		case AF_INET6:
3594105197Ssam			prefixlen = sizeof(struct in6_addr) << 3;
3595105197Ssam			break;
3596105197Ssam		default:
3597105197Ssam			; /*XXX*/
3598105197Ssam		}
3599105197Ssam	}
3600105197Ssam	p->sadb_address_prefixlen = prefixlen;
3601105197Ssam	p->sadb_address_reserved = 0;
3602105197Ssam
3603105197Ssam	bcopy(saddr,
3604105197Ssam	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3605105197Ssam	    saddr->sa_len);
3606105197Ssam
3607105197Ssam	return m;
3608105197Ssam}
3609105197Ssam
3610105197Ssam/*
3611105197Ssam * set data into sadb_x_sa2.
3612105197Ssam */
3613105197Ssamstatic struct mbuf *
3614105197Ssamkey_setsadbxsa2(mode, seq, reqid)
3615105197Ssam	u_int8_t mode;
3616105197Ssam	u_int32_t seq, reqid;
3617105197Ssam{
3618105197Ssam	struct mbuf *m;
3619105197Ssam	struct sadb_x_sa2 *p;
3620105197Ssam	size_t len;
3621105197Ssam
3622105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3623105197Ssam	m = key_alloc_mbuf(len);
3624105197Ssam	if (!m || m->m_next) {	/*XXX*/
3625105197Ssam		if (m)
3626105197Ssam			m_freem(m);
3627105197Ssam		return NULL;
3628105197Ssam	}
3629105197Ssam
3630105197Ssam	p = mtod(m, struct sadb_x_sa2 *);
3631105197Ssam
3632105197Ssam	bzero(p, len);
3633105197Ssam	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3634105197Ssam	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3635105197Ssam	p->sadb_x_sa2_mode = mode;
3636105197Ssam	p->sadb_x_sa2_reserved1 = 0;
3637105197Ssam	p->sadb_x_sa2_reserved2 = 0;
3638105197Ssam	p->sadb_x_sa2_sequence = seq;
3639105197Ssam	p->sadb_x_sa2_reqid = reqid;
3640105197Ssam
3641105197Ssam	return m;
3642105197Ssam}
3643105197Ssam
3644105197Ssam/*
3645105197Ssam * set data into sadb_x_policy
3646105197Ssam */
3647105197Ssamstatic struct mbuf *
3648105197Ssamkey_setsadbxpolicy(type, dir, id)
3649105197Ssam	u_int16_t type;
3650105197Ssam	u_int8_t dir;
3651105197Ssam	u_int32_t id;
3652105197Ssam{
3653105197Ssam	struct mbuf *m;
3654105197Ssam	struct sadb_x_policy *p;
3655105197Ssam	size_t len;
3656105197Ssam
3657105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3658105197Ssam	m = key_alloc_mbuf(len);
3659105197Ssam	if (!m || m->m_next) {	/*XXX*/
3660105197Ssam		if (m)
3661105197Ssam			m_freem(m);
3662105197Ssam		return NULL;
3663105197Ssam	}
3664105197Ssam
3665105197Ssam	p = mtod(m, struct sadb_x_policy *);
3666105197Ssam
3667105197Ssam	bzero(p, len);
3668105197Ssam	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3669105197Ssam	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3670105197Ssam	p->sadb_x_policy_type = type;
3671105197Ssam	p->sadb_x_policy_dir = dir;
3672105197Ssam	p->sadb_x_policy_id = id;
3673105197Ssam
3674105197Ssam	return m;
3675105197Ssam}
3676105197Ssam
3677105197Ssam/* %%% utilities */
3678157123Sgnn/* Take a key message (sadb_key) from the socket and turn it into one
3679157123Sgnn * of the kernel's key structures (seckey).
3680157123Sgnn *
3681157123Sgnn * IN: pointer to the src
3682157123Sgnn * OUT: NULL no more memory
3683105197Ssam */
3684157123Sgnnstruct seckey *
3685157123Sgnnkey_dup_keymsg(const struct sadb_key *src, u_int len,
3686157123Sgnn	       struct malloc_type *type)
3687105197Ssam{
3688183550Szec	INIT_VNET_IPSEC(curvnet);
3689157123Sgnn	struct seckey *dst;
3690157123Sgnn	dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3691157123Sgnn	if (dst != NULL) {
3692157123Sgnn		dst->bits = src->sadb_key_bits;
3693157123Sgnn		dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3694157123Sgnn		if (dst->key_data != NULL) {
3695157123Sgnn			bcopy((const char *)src + sizeof(struct sadb_key),
3696157123Sgnn			      dst->key_data, len);
3697157123Sgnn		} else {
3698157123Sgnn			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3699157123Sgnn				  __func__));
3700157123Sgnn			free(dst, type);
3701157123Sgnn			dst = NULL;
3702157123Sgnn		}
3703157123Sgnn	} else {
3704157123Sgnn		ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3705157123Sgnn			  __func__));
3706105197Ssam
3707157123Sgnn	}
3708157123Sgnn	return dst;
3709157123Sgnn}
3710157123Sgnn
3711157123Sgnn/* Take a lifetime message (sadb_lifetime) passed in on a socket and
3712157123Sgnn * turn it into one of the kernel's lifetime structures (seclifetime).
3713157123Sgnn *
3714157123Sgnn * IN: pointer to the destination, source and malloc type
3715157123Sgnn * OUT: NULL, no more memory
3716157123Sgnn */
3717157123Sgnn
3718157123Sgnnstatic struct seclifetime *
3719157123Sgnnkey_dup_lifemsg(const struct sadb_lifetime *src,
3720157123Sgnn		 struct malloc_type *type)
3721157123Sgnn{
3722183550Szec	INIT_VNET_IPSEC(curvnet);
3723157123Sgnn	struct seclifetime *dst = NULL;
3724157123Sgnn
3725157123Sgnn	dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3726157123Sgnn					   type, M_NOWAIT);
3727157123Sgnn	if (dst == NULL) {
3728119643Ssam		/* XXX counter */
3729120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3730157123Sgnn	} else {
3731157123Sgnn		dst->allocations = src->sadb_lifetime_allocations;
3732157123Sgnn		dst->bytes = src->sadb_lifetime_bytes;
3733157123Sgnn		dst->addtime = src->sadb_lifetime_addtime;
3734157123Sgnn		dst->usetime = src->sadb_lifetime_usetime;
3735157123Sgnn	}
3736157123Sgnn	return dst;
3737105197Ssam}
3738105197Ssam
3739105197Ssam/* compare my own address
3740105197Ssam * OUT:	1: true, i.e. my address.
3741105197Ssam *	0: false
3742105197Ssam */
3743105197Ssamint
3744105197Ssamkey_ismyaddr(sa)
3745105197Ssam	struct sockaddr *sa;
3746105197Ssam{
3747105197Ssam#ifdef INET
3748183550Szec	INIT_VNET_INET(curvnet);
3749105197Ssam	struct sockaddr_in *sin;
3750105197Ssam	struct in_ifaddr *ia;
3751105197Ssam#endif
3752105197Ssam
3753120585Ssam	IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3754105197Ssam
3755105197Ssam	switch (sa->sa_family) {
3756105197Ssam#ifdef INET
3757105197Ssam	case AF_INET:
3758105197Ssam		sin = (struct sockaddr_in *)sa;
3759181803Sbz		for (ia = V_in_ifaddrhead.tqh_first; ia;
3760105197Ssam		     ia = ia->ia_link.tqe_next)
3761105197Ssam		{
3762105197Ssam			if (sin->sin_family == ia->ia_addr.sin_family &&
3763105197Ssam			    sin->sin_len == ia->ia_addr.sin_len &&
3764105197Ssam			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3765105197Ssam			{
3766105197Ssam				return 1;
3767105197Ssam			}
3768105197Ssam		}
3769105197Ssam		break;
3770105197Ssam#endif
3771105197Ssam#ifdef INET6
3772105197Ssam	case AF_INET6:
3773105197Ssam		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3774105197Ssam#endif
3775105197Ssam	}
3776105197Ssam
3777105197Ssam	return 0;
3778105197Ssam}
3779105197Ssam
3780105197Ssam#ifdef INET6
3781105197Ssam/*
3782105197Ssam * compare my own address for IPv6.
3783105197Ssam * 1: ours
3784105197Ssam * 0: other
3785105197Ssam * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3786105197Ssam */
3787105197Ssam#include <netinet6/in6_var.h>
3788105197Ssam
3789105197Ssamstatic int
3790105197Ssamkey_ismyaddr6(sin6)
3791105197Ssam	struct sockaddr_in6 *sin6;
3792105197Ssam{
3793183550Szec	INIT_VNET_INET6(curvnet);
3794105197Ssam	struct in6_ifaddr *ia;
3795105197Ssam	struct in6_multi *in6m;
3796105197Ssam
3797181803Sbz	for (ia = V_in6_ifaddr; ia; ia = ia->ia_next) {
3798105197Ssam		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3799105197Ssam		    (struct sockaddr *)&ia->ia_addr, 0) == 0)
3800105197Ssam			return 1;
3801105197Ssam
3802105197Ssam		/*
3803105197Ssam		 * XXX Multicast
3804105197Ssam		 * XXX why do we care about multlicast here while we don't care
3805105197Ssam		 * about IPv4 multicast??
3806105197Ssam		 * XXX scope
3807105197Ssam		 */
3808105197Ssam		in6m = NULL;
3809105197Ssam		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3810105197Ssam		if (in6m)
3811105197Ssam			return 1;
3812105197Ssam	}
3813105197Ssam
3814105197Ssam	/* loopback, just for safety */
3815105197Ssam	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3816105197Ssam		return 1;
3817105197Ssam
3818105197Ssam	return 0;
3819105197Ssam}
3820105197Ssam#endif /*INET6*/
3821105197Ssam
3822105197Ssam/*
3823105197Ssam * compare two secasindex structure.
3824105197Ssam * flag can specify to compare 2 saidxes.
3825105197Ssam * compare two secasindex structure without both mode and reqid.
3826105197Ssam * don't compare port.
3827105197Ssam * IN:
3828105197Ssam *      saidx0: source, it can be in SAD.
3829105197Ssam *      saidx1: object.
3830105197Ssam * OUT:
3831105197Ssam *      1 : equal
3832105197Ssam *      0 : not equal
3833105197Ssam */
3834105197Ssamstatic int
3835105197Ssamkey_cmpsaidx(
3836105197Ssam	const struct secasindex *saidx0,
3837105197Ssam	const struct secasindex *saidx1,
3838105197Ssam	int flag)
3839105197Ssam{
3840105197Ssam	/* sanity */
3841105197Ssam	if (saidx0 == NULL && saidx1 == NULL)
3842105197Ssam		return 1;
3843105197Ssam
3844105197Ssam	if (saidx0 == NULL || saidx1 == NULL)
3845105197Ssam		return 0;
3846105197Ssam
3847105197Ssam	if (saidx0->proto != saidx1->proto)
3848105197Ssam		return 0;
3849105197Ssam
3850105197Ssam	if (flag == CMP_EXACTLY) {
3851105197Ssam		if (saidx0->mode != saidx1->mode)
3852105197Ssam			return 0;
3853105197Ssam		if (saidx0->reqid != saidx1->reqid)
3854105197Ssam			return 0;
3855105197Ssam		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3856105197Ssam		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3857105197Ssam			return 0;
3858105197Ssam	} else {
3859105197Ssam
3860105197Ssam		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3861105197Ssam		if (flag == CMP_MODE_REQID
3862105197Ssam		  ||flag == CMP_REQID) {
3863105197Ssam			/*
3864105197Ssam			 * If reqid of SPD is non-zero, unique SA is required.
3865105197Ssam			 * The result must be of same reqid in this case.
3866105197Ssam			 */
3867105197Ssam			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3868105197Ssam				return 0;
3869105197Ssam		}
3870105197Ssam
3871105197Ssam		if (flag == CMP_MODE_REQID) {
3872105197Ssam			if (saidx0->mode != IPSEC_MODE_ANY
3873105197Ssam			 && saidx0->mode != saidx1->mode)
3874105197Ssam				return 0;
3875105197Ssam		}
3876105197Ssam
3877105197Ssam		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
3878105197Ssam			return 0;
3879105197Ssam		}
3880105197Ssam		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
3881105197Ssam			return 0;
3882105197Ssam		}
3883105197Ssam	}
3884105197Ssam
3885105197Ssam	return 1;
3886105197Ssam}
3887105197Ssam
3888105197Ssam/*
3889105197Ssam * compare two secindex structure exactly.
3890105197Ssam * IN:
3891105197Ssam *	spidx0: source, it is often in SPD.
3892105197Ssam *	spidx1: object, it is often from PFKEY message.
3893105197Ssam * OUT:
3894105197Ssam *	1 : equal
3895105197Ssam *	0 : not equal
3896105197Ssam */
3897105197Ssamstatic int
3898105197Ssamkey_cmpspidx_exactly(
3899105197Ssam	struct secpolicyindex *spidx0,
3900105197Ssam	struct secpolicyindex *spidx1)
3901105197Ssam{
3902105197Ssam	/* sanity */
3903105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
3904105197Ssam		return 1;
3905105197Ssam
3906105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
3907105197Ssam		return 0;
3908105197Ssam
3909105197Ssam	if (spidx0->prefs != spidx1->prefs
3910105197Ssam	 || spidx0->prefd != spidx1->prefd
3911105197Ssam	 || spidx0->ul_proto != spidx1->ul_proto)
3912105197Ssam		return 0;
3913105197Ssam
3914105197Ssam	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3915105197Ssam	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3916105197Ssam}
3917105197Ssam
3918105197Ssam/*
3919105197Ssam * compare two secindex structure with mask.
3920105197Ssam * IN:
3921105197Ssam *	spidx0: source, it is often in SPD.
3922105197Ssam *	spidx1: object, it is often from IP header.
3923105197Ssam * OUT:
3924105197Ssam *	1 : equal
3925105197Ssam *	0 : not equal
3926105197Ssam */
3927105197Ssamstatic int
3928105197Ssamkey_cmpspidx_withmask(
3929105197Ssam	struct secpolicyindex *spidx0,
3930105197Ssam	struct secpolicyindex *spidx1)
3931105197Ssam{
3932105197Ssam	/* sanity */
3933105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
3934105197Ssam		return 1;
3935105197Ssam
3936105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
3937105197Ssam		return 0;
3938105197Ssam
3939105197Ssam	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
3940105197Ssam	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
3941105197Ssam	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
3942105197Ssam	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
3943105197Ssam		return 0;
3944105197Ssam
3945105197Ssam	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3946105197Ssam	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3947105197Ssam	 && spidx0->ul_proto != spidx1->ul_proto)
3948105197Ssam		return 0;
3949105197Ssam
3950105197Ssam	switch (spidx0->src.sa.sa_family) {
3951105197Ssam	case AF_INET:
3952105197Ssam		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
3953105197Ssam		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
3954105197Ssam			return 0;
3955105197Ssam		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
3956105197Ssam		    &spidx1->src.sin.sin_addr, spidx0->prefs))
3957105197Ssam			return 0;
3958105197Ssam		break;
3959105197Ssam	case AF_INET6:
3960105197Ssam		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
3961105197Ssam		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
3962105197Ssam			return 0;
3963105197Ssam		/*
3964105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
3965105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
3966105197Ssam		 */
3967105197Ssam		if (spidx0->src.sin6.sin6_scope_id &&
3968105197Ssam		    spidx1->src.sin6.sin6_scope_id &&
3969105197Ssam		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
3970105197Ssam			return 0;
3971105197Ssam		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
3972105197Ssam		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
3973105197Ssam			return 0;
3974105197Ssam		break;
3975105197Ssam	default:
3976105197Ssam		/* XXX */
3977105197Ssam		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
3978105197Ssam			return 0;
3979105197Ssam		break;
3980105197Ssam	}
3981105197Ssam
3982105197Ssam	switch (spidx0->dst.sa.sa_family) {
3983105197Ssam	case AF_INET:
3984105197Ssam		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
3985105197Ssam		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
3986105197Ssam			return 0;
3987105197Ssam		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
3988105197Ssam		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
3989105197Ssam			return 0;
3990105197Ssam		break;
3991105197Ssam	case AF_INET6:
3992105197Ssam		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
3993105197Ssam		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
3994105197Ssam			return 0;
3995105197Ssam		/*
3996105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
3997105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
3998105197Ssam		 */
3999130928Sbms		if (spidx0->dst.sin6.sin6_scope_id &&
4000130928Sbms		    spidx1->dst.sin6.sin6_scope_id &&
4001105197Ssam		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4002105197Ssam			return 0;
4003105197Ssam		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4004105197Ssam		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4005105197Ssam			return 0;
4006105197Ssam		break;
4007105197Ssam	default:
4008105197Ssam		/* XXX */
4009105197Ssam		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4010105197Ssam			return 0;
4011105197Ssam		break;
4012105197Ssam	}
4013105197Ssam
4014105197Ssam	/* XXX Do we check other field ?  e.g. flowinfo */
4015105197Ssam
4016105197Ssam	return 1;
4017105197Ssam}
4018105197Ssam
4019105197Ssam/* returns 0 on match */
4020105197Ssamstatic int
4021105197Ssamkey_sockaddrcmp(
4022105197Ssam	const struct sockaddr *sa1,
4023105197Ssam	const struct sockaddr *sa2,
4024105197Ssam	int port)
4025105197Ssam{
4026105197Ssam#ifdef satosin
4027105197Ssam#undef satosin
4028105197Ssam#endif
4029105197Ssam#define satosin(s) ((const struct sockaddr_in *)s)
4030105197Ssam#ifdef satosin6
4031105197Ssam#undef satosin6
4032105197Ssam#endif
4033105197Ssam#define satosin6(s) ((const struct sockaddr_in6 *)s)
4034105197Ssam	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4035105197Ssam		return 1;
4036105197Ssam
4037105197Ssam	switch (sa1->sa_family) {
4038105197Ssam	case AF_INET:
4039105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in))
4040105197Ssam			return 1;
4041105197Ssam		if (satosin(sa1)->sin_addr.s_addr !=
4042105197Ssam		    satosin(sa2)->sin_addr.s_addr) {
4043105197Ssam			return 1;
4044105197Ssam		}
4045105197Ssam		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4046105197Ssam			return 1;
4047105197Ssam		break;
4048105197Ssam	case AF_INET6:
4049105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4050105197Ssam			return 1;	/*EINVAL*/
4051105197Ssam		if (satosin6(sa1)->sin6_scope_id !=
4052105197Ssam		    satosin6(sa2)->sin6_scope_id) {
4053105197Ssam			return 1;
4054105197Ssam		}
4055105197Ssam		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4056105197Ssam		    &satosin6(sa2)->sin6_addr)) {
4057105197Ssam			return 1;
4058105197Ssam		}
4059105197Ssam		if (port &&
4060105197Ssam		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4061105197Ssam			return 1;
4062105197Ssam		}
4063170120Sbz		break;
4064105197Ssam	default:
4065105197Ssam		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4066105197Ssam			return 1;
4067105197Ssam		break;
4068105197Ssam	}
4069105197Ssam
4070105197Ssam	return 0;
4071105197Ssam#undef satosin
4072105197Ssam#undef satosin6
4073105197Ssam}
4074105197Ssam
4075105197Ssam/*
4076105197Ssam * compare two buffers with mask.
4077105197Ssam * IN:
4078105197Ssam *	addr1: source
4079105197Ssam *	addr2: object
4080105197Ssam *	bits:  Number of bits to compare
4081105197Ssam * OUT:
4082105197Ssam *	1 : equal
4083105197Ssam *	0 : not equal
4084105197Ssam */
4085105197Ssamstatic int
4086105197Ssamkey_bbcmp(const void *a1, const void *a2, u_int bits)
4087105197Ssam{
4088105197Ssam	const unsigned char *p1 = a1;
4089105197Ssam	const unsigned char *p2 = a2;
4090105197Ssam
4091105197Ssam	/* XXX: This could be considerably faster if we compare a word
4092105197Ssam	 * at a time, but it is complicated on LSB Endian machines */
4093105197Ssam
4094105197Ssam	/* Handle null pointers */
4095105197Ssam	if (p1 == NULL || p2 == NULL)
4096105197Ssam		return (p1 == p2);
4097105197Ssam
4098105197Ssam	while (bits >= 8) {
4099105197Ssam		if (*p1++ != *p2++)
4100105197Ssam			return 0;
4101105197Ssam		bits -= 8;
4102105197Ssam	}
4103105197Ssam
4104105197Ssam	if (bits > 0) {
4105105197Ssam		u_int8_t mask = ~((1<<(8-bits))-1);
4106105197Ssam		if ((*p1 & mask) != (*p2 & mask))
4107105197Ssam			return 0;
4108105197Ssam	}
4109105197Ssam	return 1;	/* Match! */
4110105197Ssam}
4111105197Ssam
4112119643Ssamstatic void
4113119643Ssamkey_flush_spd(time_t now)
4114105197Ssam{
4115183550Szec	INIT_VNET_IPSEC(curvnet);
4116120585Ssam	static u_int16_t sptree_scangen = 0;
4117120585Ssam	u_int16_t gen = sptree_scangen++;
4118120585Ssam	struct secpolicy *sp;
4119105197Ssam	u_int dir;
4120105197Ssam
4121105197Ssam	/* SPD */
4122105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4123120585Ssamrestart:
4124120585Ssam		SPTREE_LOCK();
4125181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
4126120585Ssam			if (sp->scangen == gen)		/* previously handled */
4127120585Ssam				continue;
4128120585Ssam			sp->scangen = gen;
4129105197Ssam			if (sp->state == IPSEC_SPSTATE_DEAD) {
4130120585Ssam				/* NB: clean entries created by key_spdflush */
4131120585Ssam				SPTREE_UNLOCK();
4132105197Ssam				KEY_FREESP(&sp);
4133120585Ssam				goto restart;
4134105197Ssam			}
4135105197Ssam			if (sp->lifetime == 0 && sp->validtime == 0)
4136105197Ssam				continue;
4137105197Ssam			if ((sp->lifetime && now - sp->created > sp->lifetime)
4138105197Ssam			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4139105197Ssam				sp->state = IPSEC_SPSTATE_DEAD;
4140120585Ssam				SPTREE_UNLOCK();
4141105197Ssam				key_spdexpire(sp);
4142120585Ssam				KEY_FREESP(&sp);
4143120585Ssam				goto restart;
4144105197Ssam			}
4145105197Ssam		}
4146120585Ssam		SPTREE_UNLOCK();
4147105197Ssam	}
4148119643Ssam}
4149105197Ssam
4150119643Ssamstatic void
4151119643Ssamkey_flush_sad(time_t now)
4152119643Ssam{
4153183550Szec	INIT_VNET_IPSEC(curvnet);
4154105197Ssam	struct secashead *sah, *nextsah;
4155105197Ssam	struct secasvar *sav, *nextsav;
4156105197Ssam
4157119643Ssam	/* SAD */
4158120585Ssam	SAHTREE_LOCK();
4159181803Sbz	LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4160105197Ssam		/* if sah has been dead, then delete it and process next sah. */
4161105197Ssam		if (sah->state == SADB_SASTATE_DEAD) {
4162105197Ssam			key_delsah(sah);
4163105197Ssam			continue;
4164105197Ssam		}
4165105197Ssam
4166105197Ssam		/* if LARVAL entry doesn't become MATURE, delete it. */
4167120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4168181803Sbz			if (now - sav->created > V_key_larval_lifetime)
4169105197Ssam				KEY_FREESAV(&sav);
4170105197Ssam		}
4171105197Ssam
4172105197Ssam		/*
4173105197Ssam		 * check MATURE entry to start to send expire message
4174105197Ssam		 * whether or not.
4175105197Ssam		 */
4176120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4177105197Ssam			/* we don't need to check. */
4178105197Ssam			if (sav->lft_s == NULL)
4179105197Ssam				continue;
4180105197Ssam
4181105197Ssam			/* sanity check */
4182105197Ssam			if (sav->lft_c == NULL) {
4183120585Ssam				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4184120585Ssam					"time, why?\n", __func__));
4185105197Ssam				continue;
4186105197Ssam			}
4187105197Ssam
4188105197Ssam			/* check SOFT lifetime */
4189157123Sgnn			if (sav->lft_s->addtime != 0 &&
4190157123Sgnn			    now - sav->created > sav->lft_s->addtime) {
4191105197Ssam				/*
4192105197Ssam				 * check SA to be used whether or not.
4193105197Ssam				 * when SA hasn't been used, delete it.
4194105197Ssam				 */
4195157123Sgnn				if (sav->lft_c->usetime == 0) {
4196105197Ssam					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4197105197Ssam					KEY_FREESAV(&sav);
4198105197Ssam				} else {
4199105197Ssam					key_sa_chgstate(sav, SADB_SASTATE_DYING);
4200105197Ssam					/*
4201105197Ssam					 * XXX If we keep to send expire
4202105197Ssam					 * message in the status of
4203105197Ssam					 * DYING. Do remove below code.
4204105197Ssam					 */
4205105197Ssam					key_expire(sav);
4206105197Ssam				}
4207105197Ssam			}
4208105197Ssam			/* check SOFT lifetime by bytes */
4209105197Ssam			/*
4210105197Ssam			 * XXX I don't know the way to delete this SA
4211105197Ssam			 * when new SA is installed.  Caution when it's
4212105197Ssam			 * installed too big lifetime by time.
4213105197Ssam			 */
4214157123Sgnn			else if (sav->lft_s->bytes != 0 &&
4215157123Sgnn			    sav->lft_s->bytes < sav->lft_c->bytes) {
4216105197Ssam
4217105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4218105197Ssam				/*
4219105197Ssam				 * XXX If we keep to send expire
4220105197Ssam				 * message in the status of
4221105197Ssam				 * DYING. Do remove below code.
4222105197Ssam				 */
4223105197Ssam				key_expire(sav);
4224105197Ssam			}
4225105197Ssam		}
4226105197Ssam
4227105197Ssam		/* check DYING entry to change status to DEAD. */
4228120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4229105197Ssam			/* we don't need to check. */
4230105197Ssam			if (sav->lft_h == NULL)
4231105197Ssam				continue;
4232105197Ssam
4233105197Ssam			/* sanity check */
4234105197Ssam			if (sav->lft_c == NULL) {
4235120585Ssam				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4236120585Ssam					"time, why?\n", __func__));
4237105197Ssam				continue;
4238105197Ssam			}
4239105197Ssam
4240157123Sgnn			if (sav->lft_h->addtime != 0 &&
4241157123Sgnn			    now - sav->created > sav->lft_h->addtime) {
4242105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4243105197Ssam				KEY_FREESAV(&sav);
4244105197Ssam			}
4245105197Ssam#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4246105197Ssam			else if (sav->lft_s != NULL
4247157123Sgnn			      && sav->lft_s->addtime != 0
4248157123Sgnn			      && now - sav->created > sav->lft_s->addtime) {
4249105197Ssam				/*
4250105197Ssam				 * XXX: should be checked to be
4251105197Ssam				 * installed the valid SA.
4252105197Ssam				 */
4253105197Ssam
4254105197Ssam				/*
4255105197Ssam				 * If there is no SA then sending
4256105197Ssam				 * expire message.
4257105197Ssam				 */
4258105197Ssam				key_expire(sav);
4259105197Ssam			}
4260105197Ssam#endif
4261105197Ssam			/* check HARD lifetime by bytes */
4262157123Sgnn			else if (sav->lft_h->bytes != 0 &&
4263157123Sgnn			    sav->lft_h->bytes < sav->lft_c->bytes) {
4264105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4265105197Ssam				KEY_FREESAV(&sav);
4266105197Ssam			}
4267105197Ssam		}
4268105197Ssam
4269105197Ssam		/* delete entry in DEAD */
4270120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4271105197Ssam			/* sanity check */
4272105197Ssam			if (sav->state != SADB_SASTATE_DEAD) {
4273120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4274120585Ssam					"(queue: %d SA: %d): kill it anyway\n",
4275120585Ssam					__func__,
4276105197Ssam					SADB_SASTATE_DEAD, sav->state));
4277105197Ssam			}
4278105197Ssam			/*
4279105197Ssam			 * do not call key_freesav() here.
4280105197Ssam			 * sav should already be freed, and sav->refcnt
4281105197Ssam			 * shows other references to sav
4282105197Ssam			 * (such as from SPD).
4283105197Ssam			 */
4284105197Ssam		}
4285105197Ssam	}
4286120585Ssam	SAHTREE_UNLOCK();
4287119643Ssam}
4288105197Ssam
4289119643Ssamstatic void
4290119643Ssamkey_flush_acq(time_t now)
4291119643Ssam{
4292183550Szec	INIT_VNET_IPSEC(curvnet);
4293105197Ssam	struct secacq *acq, *nextacq;
4294105197Ssam
4295119643Ssam	/* ACQ tree */
4296120585Ssam	ACQ_LOCK();
4297181803Sbz	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4298105197Ssam		nextacq = LIST_NEXT(acq, chain);
4299181803Sbz		if (now - acq->created > V_key_blockacq_lifetime
4300105197Ssam		 && __LIST_CHAINED(acq)) {
4301105197Ssam			LIST_REMOVE(acq, chain);
4302119643Ssam			free(acq, M_IPSEC_SAQ);
4303105197Ssam		}
4304105197Ssam	}
4305120585Ssam	ACQ_UNLOCK();
4306119643Ssam}
4307105197Ssam
4308119643Ssamstatic void
4309119643Ssamkey_flush_spacq(time_t now)
4310119643Ssam{
4311183550Szec	INIT_VNET_IPSEC(curvnet);
4312105197Ssam	struct secspacq *acq, *nextacq;
4313105197Ssam
4314119643Ssam	/* SP ACQ tree */
4315120585Ssam	SPACQ_LOCK();
4316181803Sbz	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4317105197Ssam		nextacq = LIST_NEXT(acq, chain);
4318181803Sbz		if (now - acq->created > V_key_blockacq_lifetime
4319105197Ssam		 && __LIST_CHAINED(acq)) {
4320105197Ssam			LIST_REMOVE(acq, chain);
4321119643Ssam			free(acq, M_IPSEC_SAQ);
4322105197Ssam		}
4323105197Ssam	}
4324120585Ssam	SPACQ_UNLOCK();
4325119643Ssam}
4326105197Ssam
4327119643Ssam/*
4328119643Ssam * time handler.
4329119643Ssam * scanning SPD and SAD to check status for each entries,
4330119643Ssam * and do to remove or to expire.
4331119643Ssam * XXX: year 2038 problem may remain.
4332119643Ssam */
4333119643Ssamvoid
4334119643Ssamkey_timehandler(void)
4335119643Ssam{
4336183550Szec	VNET_ITERATOR_DECL(vnet_iter);
4337119643Ssam	time_t now = time_second;
4338105197Ssam
4339185348Szec	VNET_LIST_RLOCK();
4340183550Szec	VNET_FOREACH(vnet_iter) {
4341183550Szec		CURVNET_SET(vnet_iter);
4342183550Szec		key_flush_spd(now);
4343183550Szec		key_flush_sad(now);
4344183550Szec		key_flush_acq(now);
4345183550Szec		key_flush_spacq(now);
4346183550Szec		CURVNET_RESTORE();
4347183550Szec	}
4348185348Szec	VNET_LIST_RUNLOCK();
4349119643Ssam
4350105197Ssam#ifndef IPSEC_DEBUG2
4351105197Ssam	/* do exchange to tick time !! */
4352105197Ssam	(void)timeout((void *)key_timehandler, (void *)0, hz);
4353105197Ssam#endif /* IPSEC_DEBUG2 */
4354105197Ssam}
4355105197Ssam
4356105197Ssamu_long
4357105197Ssamkey_random()
4358105197Ssam{
4359105197Ssam	u_long value;
4360105197Ssam
4361105197Ssam	key_randomfill(&value, sizeof(value));
4362105197Ssam	return value;
4363105197Ssam}
4364105197Ssam
4365105197Ssamvoid
4366105197Ssamkey_randomfill(p, l)
4367105197Ssam	void *p;
4368105197Ssam	size_t l;
4369105197Ssam{
4370105197Ssam	size_t n;
4371105197Ssam	u_long v;
4372105197Ssam	static int warn = 1;
4373105197Ssam
4374105197Ssam	n = 0;
4375105197Ssam	n = (size_t)read_random(p, (u_int)l);
4376105197Ssam	/* last resort */
4377105197Ssam	while (n < l) {
4378105197Ssam		v = random();
4379105197Ssam		bcopy(&v, (u_int8_t *)p + n,
4380105197Ssam		    l - n < sizeof(v) ? l - n : sizeof(v));
4381105197Ssam		n += sizeof(v);
4382105197Ssam
4383105197Ssam		if (warn) {
4384105197Ssam			printf("WARNING: pseudo-random number generator "
4385105197Ssam			    "used for IPsec processing\n");
4386105197Ssam			warn = 0;
4387105197Ssam		}
4388105197Ssam	}
4389105197Ssam}
4390105197Ssam
4391105197Ssam/*
4392105197Ssam * map SADB_SATYPE_* to IPPROTO_*.
4393105197Ssam * if satype == SADB_SATYPE then satype is mapped to ~0.
4394105197Ssam * OUT:
4395105197Ssam *	0: invalid satype.
4396105197Ssam */
4397105197Ssamstatic u_int16_t
4398105197Ssamkey_satype2proto(satype)
4399105197Ssam	u_int8_t satype;
4400105197Ssam{
4401105197Ssam	switch (satype) {
4402105197Ssam	case SADB_SATYPE_UNSPEC:
4403105197Ssam		return IPSEC_PROTO_ANY;
4404105197Ssam	case SADB_SATYPE_AH:
4405105197Ssam		return IPPROTO_AH;
4406105197Ssam	case SADB_SATYPE_ESP:
4407105197Ssam		return IPPROTO_ESP;
4408105197Ssam	case SADB_X_SATYPE_IPCOMP:
4409105197Ssam		return IPPROTO_IPCOMP;
4410125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
4411125680Sbms		return IPPROTO_TCP;
4412105197Ssam	default:
4413105197Ssam		return 0;
4414105197Ssam	}
4415105197Ssam	/* NOTREACHED */
4416105197Ssam}
4417105197Ssam
4418105197Ssam/*
4419105197Ssam * map IPPROTO_* to SADB_SATYPE_*
4420105197Ssam * OUT:
4421105197Ssam *	0: invalid protocol type.
4422105197Ssam */
4423105197Ssamstatic u_int8_t
4424105197Ssamkey_proto2satype(proto)
4425105197Ssam	u_int16_t proto;
4426105197Ssam{
4427105197Ssam	switch (proto) {
4428105197Ssam	case IPPROTO_AH:
4429105197Ssam		return SADB_SATYPE_AH;
4430105197Ssam	case IPPROTO_ESP:
4431105197Ssam		return SADB_SATYPE_ESP;
4432105197Ssam	case IPPROTO_IPCOMP:
4433105197Ssam		return SADB_X_SATYPE_IPCOMP;
4434125680Sbms	case IPPROTO_TCP:
4435125680Sbms		return SADB_X_SATYPE_TCPSIGNATURE;
4436105197Ssam	default:
4437105197Ssam		return 0;
4438105197Ssam	}
4439105197Ssam	/* NOTREACHED */
4440105197Ssam}
4441105197Ssam
4442105197Ssam/* %%% PF_KEY */
4443105197Ssam/*
4444105197Ssam * SADB_GETSPI processing is to receive
4445105197Ssam *	<base, (SA2), src address, dst address, (SPI range)>
4446105197Ssam * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4447105197Ssam * tree with the status of LARVAL, and send
4448105197Ssam *	<base, SA(*), address(SD)>
4449105197Ssam * to the IKMPd.
4450105197Ssam *
4451105197Ssam * IN:	mhp: pointer to the pointer to each header.
4452105197Ssam * OUT:	NULL if fail.
4453105197Ssam *	other if success, return pointer to the message to send.
4454105197Ssam */
4455105197Ssamstatic int
4456105197Ssamkey_getspi(so, m, mhp)
4457105197Ssam	struct socket *so;
4458105197Ssam	struct mbuf *m;
4459105197Ssam	const struct sadb_msghdr *mhp;
4460105197Ssam{
4461183550Szec	INIT_VNET_IPSEC(curvnet);
4462105197Ssam	struct sadb_address *src0, *dst0;
4463105197Ssam	struct secasindex saidx;
4464105197Ssam	struct secashead *newsah;
4465105197Ssam	struct secasvar *newsav;
4466105197Ssam	u_int8_t proto;
4467105197Ssam	u_int32_t spi;
4468105197Ssam	u_int8_t mode;
4469105197Ssam	u_int32_t reqid;
4470105197Ssam	int error;
4471105197Ssam
4472120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4473120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4474120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4475120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4476105197Ssam
4477105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4478105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4479120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4480120585Ssam			__func__));
4481105197Ssam		return key_senderror(so, m, EINVAL);
4482105197Ssam	}
4483105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4484105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4485120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4486120585Ssam			__func__));
4487105197Ssam		return key_senderror(so, m, EINVAL);
4488105197Ssam	}
4489105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4490105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4491105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4492105197Ssam	} else {
4493105197Ssam		mode = IPSEC_MODE_ANY;
4494105197Ssam		reqid = 0;
4495105197Ssam	}
4496105197Ssam
4497105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4498105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4499105197Ssam
4500105197Ssam	/* map satype to proto */
4501105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4502120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4503120585Ssam			__func__));
4504105197Ssam		return key_senderror(so, m, EINVAL);
4505105197Ssam	}
4506105197Ssam
4507105197Ssam	/* make sure if port number is zero. */
4508105197Ssam	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4509105197Ssam	case AF_INET:
4510105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4511105197Ssam		    sizeof(struct sockaddr_in))
4512105197Ssam			return key_senderror(so, m, EINVAL);
4513105197Ssam		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4514105197Ssam		break;
4515105197Ssam	case AF_INET6:
4516105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4517105197Ssam		    sizeof(struct sockaddr_in6))
4518105197Ssam			return key_senderror(so, m, EINVAL);
4519105197Ssam		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4520105197Ssam		break;
4521105197Ssam	default:
4522105197Ssam		; /*???*/
4523105197Ssam	}
4524105197Ssam	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4525105197Ssam	case AF_INET:
4526105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4527105197Ssam		    sizeof(struct sockaddr_in))
4528105197Ssam			return key_senderror(so, m, EINVAL);
4529105197Ssam		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4530105197Ssam		break;
4531105197Ssam	case AF_INET6:
4532105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4533105197Ssam		    sizeof(struct sockaddr_in6))
4534105197Ssam			return key_senderror(so, m, EINVAL);
4535105197Ssam		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4536105197Ssam		break;
4537105197Ssam	default:
4538105197Ssam		; /*???*/
4539105197Ssam	}
4540105197Ssam
4541105197Ssam	/* XXX boundary check against sa_len */
4542105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4543105197Ssam
4544105197Ssam	/* SPI allocation */
4545105197Ssam	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4546105197Ssam	                       &saidx);
4547105197Ssam	if (spi == 0)
4548105197Ssam		return key_senderror(so, m, EINVAL);
4549105197Ssam
4550105197Ssam	/* get a SA index */
4551105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4552105197Ssam		/* create a new SA index */
4553105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4554120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4555105197Ssam			return key_senderror(so, m, ENOBUFS);
4556105197Ssam		}
4557105197Ssam	}
4558105197Ssam
4559105197Ssam	/* get a new SA */
4560105197Ssam	/* XXX rewrite */
4561105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4562105197Ssam	if (newsav == NULL) {
4563105197Ssam		/* XXX don't free new SA index allocated in above. */
4564105197Ssam		return key_senderror(so, m, error);
4565105197Ssam	}
4566105197Ssam
4567105197Ssam	/* set spi */
4568105197Ssam	newsav->spi = htonl(spi);
4569105197Ssam
4570105197Ssam	/* delete the entry in acqtree */
4571105197Ssam	if (mhp->msg->sadb_msg_seq != 0) {
4572105197Ssam		struct secacq *acq;
4573105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4574105197Ssam			/* reset counter in order to deletion by timehandler. */
4575105197Ssam			acq->created = time_second;
4576105197Ssam			acq->count = 0;
4577105197Ssam		}
4578105197Ssam    	}
4579105197Ssam
4580105197Ssam    {
4581105197Ssam	struct mbuf *n, *nn;
4582105197Ssam	struct sadb_sa *m_sa;
4583105197Ssam	struct sadb_msg *newmsg;
4584105197Ssam	int off, len;
4585105197Ssam
4586105197Ssam	/* create new sadb_msg to reply. */
4587105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4588105197Ssam	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4589105197Ssam
4590111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
4591105197Ssam	if (len > MHLEN) {
4592111119Simp		MCLGET(n, M_DONTWAIT);
4593105197Ssam		if ((n->m_flags & M_EXT) == 0) {
4594105197Ssam			m_freem(n);
4595105197Ssam			n = NULL;
4596105197Ssam		}
4597105197Ssam	}
4598105197Ssam	if (!n)
4599105197Ssam		return key_senderror(so, m, ENOBUFS);
4600105197Ssam
4601105197Ssam	n->m_len = len;
4602105197Ssam	n->m_next = NULL;
4603105197Ssam	off = 0;
4604105197Ssam
4605105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4606105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4607105197Ssam
4608105197Ssam	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4609105197Ssam	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4610105197Ssam	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4611105197Ssam	m_sa->sadb_sa_spi = htonl(spi);
4612105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4613105197Ssam
4614120585Ssam	IPSEC_ASSERT(off == len,
4615120585Ssam		("length inconsistency (off %u len %u)", off, len));
4616105197Ssam
4617105197Ssam	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4618105197Ssam	    SADB_EXT_ADDRESS_DST);
4619105197Ssam	if (!n->m_next) {
4620105197Ssam		m_freem(n);
4621105197Ssam		return key_senderror(so, m, ENOBUFS);
4622105197Ssam	}
4623105197Ssam
4624105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
4625105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
4626105197Ssam		if (n == NULL)
4627105197Ssam			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4628105197Ssam	}
4629105197Ssam
4630105197Ssam	n->m_pkthdr.len = 0;
4631105197Ssam	for (nn = n; nn; nn = nn->m_next)
4632105197Ssam		n->m_pkthdr.len += nn->m_len;
4633105197Ssam
4634105197Ssam	newmsg = mtod(n, struct sadb_msg *);
4635105197Ssam	newmsg->sadb_msg_seq = newsav->seq;
4636105197Ssam	newmsg->sadb_msg_errno = 0;
4637105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4638105197Ssam
4639105197Ssam	m_freem(m);
4640105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4641105197Ssam    }
4642105197Ssam}
4643105197Ssam
4644105197Ssam/*
4645105197Ssam * allocating new SPI
4646105197Ssam * called by key_getspi().
4647105197Ssam * OUT:
4648105197Ssam *	0:	failure.
4649105197Ssam *	others: success.
4650105197Ssam */
4651105197Ssamstatic u_int32_t
4652105197Ssamkey_do_getnewspi(spirange, saidx)
4653105197Ssam	struct sadb_spirange *spirange;
4654105197Ssam	struct secasindex *saidx;
4655105197Ssam{
4656183550Szec	INIT_VNET_IPSEC(curvnet);
4657105197Ssam	u_int32_t newspi;
4658105197Ssam	u_int32_t min, max;
4659181803Sbz	int count = V_key_spi_trycnt;
4660105197Ssam
4661105197Ssam	/* set spi range to allocate */
4662105197Ssam	if (spirange != NULL) {
4663105197Ssam		min = spirange->sadb_spirange_min;
4664105197Ssam		max = spirange->sadb_spirange_max;
4665105197Ssam	} else {
4666181803Sbz		min = V_key_spi_minval;
4667181803Sbz		max = V_key_spi_maxval;
4668105197Ssam	}
4669105197Ssam	/* IPCOMP needs 2-byte SPI */
4670105197Ssam	if (saidx->proto == IPPROTO_IPCOMP) {
4671105197Ssam		u_int32_t t;
4672105197Ssam		if (min >= 0x10000)
4673105197Ssam			min = 0xffff;
4674105197Ssam		if (max >= 0x10000)
4675105197Ssam			max = 0xffff;
4676105197Ssam		if (min > max) {
4677105197Ssam			t = min; min = max; max = t;
4678105197Ssam		}
4679105197Ssam	}
4680105197Ssam
4681105197Ssam	if (min == max) {
4682105197Ssam		if (key_checkspidup(saidx, min) != NULL) {
4683120585Ssam			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4684120585Ssam				__func__, min));
4685105197Ssam			return 0;
4686105197Ssam		}
4687105197Ssam
4688105197Ssam		count--; /* taking one cost. */
4689105197Ssam		newspi = min;
4690105197Ssam
4691105197Ssam	} else {
4692105197Ssam
4693105197Ssam		/* init SPI */
4694105197Ssam		newspi = 0;
4695105197Ssam
4696105197Ssam		/* when requesting to allocate spi ranged */
4697105197Ssam		while (count--) {
4698105197Ssam			/* generate pseudo-random SPI value ranged. */
4699105197Ssam			newspi = min + (key_random() % (max - min + 1));
4700105197Ssam
4701105197Ssam			if (key_checkspidup(saidx, newspi) == NULL)
4702105197Ssam				break;
4703105197Ssam		}
4704105197Ssam
4705105197Ssam		if (count == 0 || newspi == 0) {
4706120585Ssam			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4707120585Ssam				__func__));
4708105197Ssam			return 0;
4709105197Ssam		}
4710105197Ssam	}
4711105197Ssam
4712105197Ssam	/* statistics */
4713105197Ssam	keystat.getspi_count =
4714181803Sbz		(keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4715105197Ssam
4716105197Ssam	return newspi;
4717105197Ssam}
4718105197Ssam
4719105197Ssam/*
4720105197Ssam * SADB_UPDATE processing
4721105197Ssam * receive
4722105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4723105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4724105197Ssam * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4725105197Ssam * and send
4726105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4727105197Ssam *       (identity(SD),) (sensitivity)>
4728105197Ssam * to the ikmpd.
4729105197Ssam *
4730105197Ssam * m will always be freed.
4731105197Ssam */
4732105197Ssamstatic int
4733105197Ssamkey_update(so, m, mhp)
4734105197Ssam	struct socket *so;
4735105197Ssam	struct mbuf *m;
4736105197Ssam	const struct sadb_msghdr *mhp;
4737105197Ssam{
4738183550Szec	INIT_VNET_IPSEC(curvnet);
4739105197Ssam	struct sadb_sa *sa0;
4740105197Ssam	struct sadb_address *src0, *dst0;
4741105197Ssam	struct secasindex saidx;
4742105197Ssam	struct secashead *sah;
4743105197Ssam	struct secasvar *sav;
4744105197Ssam	u_int16_t proto;
4745105197Ssam	u_int8_t mode;
4746105197Ssam	u_int32_t reqid;
4747105197Ssam	int error;
4748105197Ssam
4749120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4750120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4751120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4752120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4753105197Ssam
4754105197Ssam	/* map satype to proto */
4755105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4756120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4757120585Ssam			__func__));
4758105197Ssam		return key_senderror(so, m, EINVAL);
4759105197Ssam	}
4760105197Ssam
4761105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
4762105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4763105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4764105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4765105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4766105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4767105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4768105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4769105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4770105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4771105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4772120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4773120585Ssam			__func__));
4774105197Ssam		return key_senderror(so, m, EINVAL);
4775105197Ssam	}
4776105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4777105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4778105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4779120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4780120585Ssam			__func__));
4781105197Ssam		return key_senderror(so, m, EINVAL);
4782105197Ssam	}
4783105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4784105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4785105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4786105197Ssam	} else {
4787105197Ssam		mode = IPSEC_MODE_ANY;
4788105197Ssam		reqid = 0;
4789105197Ssam	}
4790105197Ssam	/* XXX boundary checking for other extensions */
4791105197Ssam
4792105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4793105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4794105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4795105197Ssam
4796105197Ssam	/* XXX boundary check against sa_len */
4797105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4798105197Ssam
4799105197Ssam	/* get a SA header */
4800105197Ssam	if ((sah = key_getsah(&saidx)) == NULL) {
4801120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
4802105197Ssam		return key_senderror(so, m, ENOENT);
4803105197Ssam	}
4804105197Ssam
4805105197Ssam	/* set spidx if there */
4806105197Ssam	/* XXX rewrite */
4807105197Ssam	error = key_setident(sah, m, mhp);
4808105197Ssam	if (error)
4809105197Ssam		return key_senderror(so, m, error);
4810105197Ssam
4811105197Ssam	/* find a SA with sequence number. */
4812105197Ssam#ifdef IPSEC_DOSEQCHECK
4813105197Ssam	if (mhp->msg->sadb_msg_seq != 0
4814105197Ssam	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4815120585Ssam		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
4816120585Ssam			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
4817105197Ssam		return key_senderror(so, m, ENOENT);
4818105197Ssam	}
4819105197Ssam#else
4820120585Ssam	SAHTREE_LOCK();
4821120585Ssam	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4822120585Ssam	SAHTREE_UNLOCK();
4823120585Ssam	if (sav == NULL) {
4824120585Ssam		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
4825120585Ssam			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4826105197Ssam		return key_senderror(so, m, EINVAL);
4827105197Ssam	}
4828105197Ssam#endif
4829105197Ssam
4830105197Ssam	/* validity check */
4831105197Ssam	if (sav->sah->saidx.proto != proto) {
4832120585Ssam		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
4833120585Ssam			"(DB=%u param=%u)\n", __func__,
4834120585Ssam			sav->sah->saidx.proto, proto));
4835105197Ssam		return key_senderror(so, m, EINVAL);
4836105197Ssam	}
4837105197Ssam#ifdef IPSEC_DOSEQCHECK
4838105197Ssam	if (sav->spi != sa0->sadb_sa_spi) {
4839120585Ssam		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
4840120585Ssam		    __func__,
4841105197Ssam		    (u_int32_t)ntohl(sav->spi),
4842105197Ssam		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4843105197Ssam		return key_senderror(so, m, EINVAL);
4844105197Ssam	}
4845105197Ssam#endif
4846105197Ssam	if (sav->pid != mhp->msg->sadb_msg_pid) {
4847120585Ssam		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
4848120585Ssam		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
4849105197Ssam		return key_senderror(so, m, EINVAL);
4850105197Ssam	}
4851105197Ssam
4852105197Ssam	/* copy sav values */
4853105197Ssam	error = key_setsaval(sav, m, mhp);
4854105197Ssam	if (error) {
4855105197Ssam		KEY_FREESAV(&sav);
4856105197Ssam		return key_senderror(so, m, error);
4857105197Ssam	}
4858105197Ssam
4859105197Ssam	/* check SA values to be mature. */
4860105197Ssam	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4861105197Ssam		KEY_FREESAV(&sav);
4862105197Ssam		return key_senderror(so, m, 0);
4863105197Ssam	}
4864105197Ssam
4865105197Ssam    {
4866105197Ssam	struct mbuf *n;
4867105197Ssam
4868105197Ssam	/* set msg buf from mhp */
4869105197Ssam	n = key_getmsgbuf_x1(m, mhp);
4870105197Ssam	if (n == NULL) {
4871120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4872105197Ssam		return key_senderror(so, m, ENOBUFS);
4873105197Ssam	}
4874105197Ssam
4875105197Ssam	m_freem(m);
4876105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4877105197Ssam    }
4878105197Ssam}
4879105197Ssam
4880105197Ssam/*
4881105197Ssam * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4882105197Ssam * only called by key_update().
4883105197Ssam * OUT:
4884105197Ssam *	NULL	: not found
4885105197Ssam *	others	: found, pointer to a SA.
4886105197Ssam */
4887105197Ssam#ifdef IPSEC_DOSEQCHECK
4888105197Ssamstatic struct secasvar *
4889105197Ssamkey_getsavbyseq(sah, seq)
4890105197Ssam	struct secashead *sah;
4891105197Ssam	u_int32_t seq;
4892105197Ssam{
4893105197Ssam	struct secasvar *sav;
4894105197Ssam	u_int state;
4895105197Ssam
4896105197Ssam	state = SADB_SASTATE_LARVAL;
4897105197Ssam
4898105197Ssam	/* search SAD with sequence number ? */
4899105197Ssam	LIST_FOREACH(sav, &sah->savtree[state], chain) {
4900105197Ssam
4901120585Ssam		KEY_CHKSASTATE(state, sav->state, __func__);
4902105197Ssam
4903105197Ssam		if (sav->seq == seq) {
4904158767Spjd			sa_addref(sav);
4905105197Ssam			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4906120585Ssam				printf("DP %s cause refcnt++:%d SA:%p\n",
4907120585Ssam					__func__, sav->refcnt, sav));
4908105197Ssam			return sav;
4909105197Ssam		}
4910105197Ssam	}
4911105197Ssam
4912105197Ssam	return NULL;
4913105197Ssam}
4914105197Ssam#endif
4915105197Ssam
4916105197Ssam/*
4917105197Ssam * SADB_ADD processing
4918108533Sschweikh * add an entry to SA database, when received
4919105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4920105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4921105197Ssam * from the ikmpd,
4922105197Ssam * and send
4923105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4924105197Ssam *       (identity(SD),) (sensitivity)>
4925105197Ssam * to the ikmpd.
4926105197Ssam *
4927105197Ssam * IGNORE identity and sensitivity messages.
4928105197Ssam *
4929105197Ssam * m will always be freed.
4930105197Ssam */
4931105197Ssamstatic int
4932105197Ssamkey_add(so, m, mhp)
4933105197Ssam	struct socket *so;
4934105197Ssam	struct mbuf *m;
4935105197Ssam	const struct sadb_msghdr *mhp;
4936105197Ssam{
4937183550Szec	INIT_VNET_IPSEC(curvnet);
4938105197Ssam	struct sadb_sa *sa0;
4939105197Ssam	struct sadb_address *src0, *dst0;
4940105197Ssam	struct secasindex saidx;
4941105197Ssam	struct secashead *newsah;
4942105197Ssam	struct secasvar *newsav;
4943105197Ssam	u_int16_t proto;
4944105197Ssam	u_int8_t mode;
4945105197Ssam	u_int32_t reqid;
4946105197Ssam	int error;
4947105197Ssam
4948120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4949120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4950120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4951120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4952105197Ssam
4953105197Ssam	/* map satype to proto */
4954105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4955120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4956120585Ssam			__func__));
4957105197Ssam		return key_senderror(so, m, EINVAL);
4958105197Ssam	}
4959105197Ssam
4960105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
4961105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4962105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4963105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4964105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4965105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4966105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4967105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4968105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4969105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4970105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4971120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4972120585Ssam			__func__));
4973105197Ssam		return key_senderror(so, m, EINVAL);
4974105197Ssam	}
4975105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4976105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4977105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4978105197Ssam		/* XXX need more */
4979120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4980120585Ssam			__func__));
4981105197Ssam		return key_senderror(so, m, EINVAL);
4982105197Ssam	}
4983105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4984105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4985105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4986105197Ssam	} else {
4987105197Ssam		mode = IPSEC_MODE_ANY;
4988105197Ssam		reqid = 0;
4989105197Ssam	}
4990105197Ssam
4991105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4992105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4993105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4994105197Ssam
4995105197Ssam	/* XXX boundary check against sa_len */
4996105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4997105197Ssam
4998105197Ssam	/* get a SA header */
4999105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
5000105197Ssam		/* create a new SA header */
5001105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
5002120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5003105197Ssam			return key_senderror(so, m, ENOBUFS);
5004105197Ssam		}
5005105197Ssam	}
5006105197Ssam
5007105197Ssam	/* set spidx if there */
5008105197Ssam	/* XXX rewrite */
5009105197Ssam	error = key_setident(newsah, m, mhp);
5010105197Ssam	if (error) {
5011105197Ssam		return key_senderror(so, m, error);
5012105197Ssam	}
5013105197Ssam
5014105197Ssam	/* create new SA entry. */
5015105197Ssam	/* We can create new SA only if SPI is differenct. */
5016120585Ssam	SAHTREE_LOCK();
5017120585Ssam	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5018120585Ssam	SAHTREE_UNLOCK();
5019120585Ssam	if (newsav != NULL) {
5020120585Ssam		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5021105197Ssam		return key_senderror(so, m, EEXIST);
5022105197Ssam	}
5023105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5024105197Ssam	if (newsav == NULL) {
5025105197Ssam		return key_senderror(so, m, error);
5026105197Ssam	}
5027105197Ssam
5028105197Ssam	/* check SA values to be mature. */
5029105197Ssam	if ((error = key_mature(newsav)) != 0) {
5030105197Ssam		KEY_FREESAV(&newsav);
5031105197Ssam		return key_senderror(so, m, error);
5032105197Ssam	}
5033105197Ssam
5034105197Ssam	/*
5035105197Ssam	 * don't call key_freesav() here, as we would like to keep the SA
5036105197Ssam	 * in the database on success.
5037105197Ssam	 */
5038105197Ssam
5039105197Ssam    {
5040105197Ssam	struct mbuf *n;
5041105197Ssam
5042105197Ssam	/* set msg buf from mhp */
5043105197Ssam	n = key_getmsgbuf_x1(m, mhp);
5044105197Ssam	if (n == NULL) {
5045120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5046105197Ssam		return key_senderror(so, m, ENOBUFS);
5047105197Ssam	}
5048105197Ssam
5049105197Ssam	m_freem(m);
5050105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5051105197Ssam    }
5052105197Ssam}
5053105197Ssam
5054105197Ssam/* m is retained */
5055105197Ssamstatic int
5056105197Ssamkey_setident(sah, m, mhp)
5057105197Ssam	struct secashead *sah;
5058105197Ssam	struct mbuf *m;
5059105197Ssam	const struct sadb_msghdr *mhp;
5060105197Ssam{
5061183550Szec	INIT_VNET_IPSEC(curvnet);
5062105197Ssam	const struct sadb_ident *idsrc, *iddst;
5063105197Ssam	int idsrclen, iddstlen;
5064105197Ssam
5065120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5066120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5067120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5068120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5069105197Ssam
5070105197Ssam	/* don't make buffer if not there */
5071105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5072105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5073105197Ssam		sah->idents = NULL;
5074105197Ssam		sah->identd = NULL;
5075105197Ssam		return 0;
5076105197Ssam	}
5077105197Ssam
5078105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5079105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5080120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5081105197Ssam		return EINVAL;
5082105197Ssam	}
5083105197Ssam
5084105197Ssam	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5085105197Ssam	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5086105197Ssam	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5087105197Ssam	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5088105197Ssam
5089105197Ssam	/* validity check */
5090105197Ssam	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5091120585Ssam		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5092105197Ssam		return EINVAL;
5093105197Ssam	}
5094105197Ssam
5095105197Ssam	switch (idsrc->sadb_ident_type) {
5096105197Ssam	case SADB_IDENTTYPE_PREFIX:
5097105197Ssam	case SADB_IDENTTYPE_FQDN:
5098105197Ssam	case SADB_IDENTTYPE_USERFQDN:
5099105197Ssam	default:
5100105197Ssam		/* XXX do nothing */
5101105197Ssam		sah->idents = NULL;
5102105197Ssam		sah->identd = NULL;
5103105197Ssam	 	return 0;
5104105197Ssam	}
5105105197Ssam
5106105197Ssam	/* make structure */
5107157123Sgnn	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5108105197Ssam	if (sah->idents == NULL) {
5109120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5110105197Ssam		return ENOBUFS;
5111105197Ssam	}
5112157123Sgnn	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5113105197Ssam	if (sah->identd == NULL) {
5114119643Ssam		free(sah->idents, M_IPSEC_MISC);
5115105197Ssam		sah->idents = NULL;
5116120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5117105197Ssam		return ENOBUFS;
5118105197Ssam	}
5119157123Sgnn	sah->idents->type = idsrc->sadb_ident_type;
5120157123Sgnn	sah->idents->id = idsrc->sadb_ident_id;
5121105197Ssam
5122157123Sgnn	sah->identd->type = iddst->sadb_ident_type;
5123157123Sgnn	sah->identd->id = iddst->sadb_ident_id;
5124157123Sgnn
5125105197Ssam	return 0;
5126105197Ssam}
5127105197Ssam
5128105197Ssam/*
5129105197Ssam * m will not be freed on return.
5130105197Ssam * it is caller's responsibility to free the result.
5131105197Ssam */
5132105197Ssamstatic struct mbuf *
5133105197Ssamkey_getmsgbuf_x1(m, mhp)
5134105197Ssam	struct mbuf *m;
5135105197Ssam	const struct sadb_msghdr *mhp;
5136105197Ssam{
5137105197Ssam	struct mbuf *n;
5138105197Ssam
5139120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5140120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5141120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5142105197Ssam
5143105197Ssam	/* create new sadb_msg to reply. */
5144105197Ssam	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5145105197Ssam	    SADB_EXT_SA, SADB_X_EXT_SA2,
5146105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5147105197Ssam	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5148105197Ssam	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5149105197Ssam	if (!n)
5150105197Ssam		return NULL;
5151105197Ssam
5152105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5153105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5154105197Ssam		if (n == NULL)
5155105197Ssam			return NULL;
5156105197Ssam	}
5157105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5158105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_len =
5159105197Ssam	    PFKEY_UNIT64(n->m_pkthdr.len);
5160105197Ssam
5161105197Ssam	return n;
5162105197Ssam}
5163105197Ssam
5164105197Ssamstatic int key_delete_all __P((struct socket *, struct mbuf *,
5165105197Ssam	const struct sadb_msghdr *, u_int16_t));
5166105197Ssam
5167105197Ssam/*
5168105197Ssam * SADB_DELETE processing
5169105197Ssam * receive
5170105197Ssam *   <base, SA(*), address(SD)>
5171105197Ssam * from the ikmpd, and set SADB_SASTATE_DEAD,
5172105197Ssam * and send,
5173105197Ssam *   <base, SA(*), address(SD)>
5174105197Ssam * to the ikmpd.
5175105197Ssam *
5176105197Ssam * m will always be freed.
5177105197Ssam */
5178105197Ssamstatic int
5179105197Ssamkey_delete(so, m, mhp)
5180105197Ssam	struct socket *so;
5181105197Ssam	struct mbuf *m;
5182105197Ssam	const struct sadb_msghdr *mhp;
5183105197Ssam{
5184183550Szec	INIT_VNET_IPSEC(curvnet);
5185105197Ssam	struct sadb_sa *sa0;
5186105197Ssam	struct sadb_address *src0, *dst0;
5187105197Ssam	struct secasindex saidx;
5188105197Ssam	struct secashead *sah;
5189105197Ssam	struct secasvar *sav = NULL;
5190105197Ssam	u_int16_t proto;
5191105197Ssam
5192120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5193120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5194120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5195120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5196105197Ssam
5197105197Ssam	/* map satype to proto */
5198105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5199120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5200120585Ssam			__func__));
5201105197Ssam		return key_senderror(so, m, EINVAL);
5202105197Ssam	}
5203105197Ssam
5204105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5205105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5206120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5207120585Ssam			__func__));
5208105197Ssam		return key_senderror(so, m, EINVAL);
5209105197Ssam	}
5210105197Ssam
5211105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5212105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5213120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5214120585Ssam			__func__));
5215105197Ssam		return key_senderror(so, m, EINVAL);
5216105197Ssam	}
5217105197Ssam
5218105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL) {
5219105197Ssam		/*
5220105197Ssam		 * Caller wants us to delete all non-LARVAL SAs
5221105197Ssam		 * that match the src/dst.  This is used during
5222105197Ssam		 * IKE INITIAL-CONTACT.
5223105197Ssam		 */
5224120585Ssam		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5225105197Ssam		return key_delete_all(so, m, mhp, proto);
5226105197Ssam	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5227120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5228120585Ssam			__func__));
5229105197Ssam		return key_senderror(so, m, EINVAL);
5230105197Ssam	}
5231105197Ssam
5232105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5233105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5234105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5235105197Ssam
5236105197Ssam	/* XXX boundary check against sa_len */
5237105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5238105197Ssam
5239105197Ssam	/* get a SA header */
5240120585Ssam	SAHTREE_LOCK();
5241181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5242105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5243105197Ssam			continue;
5244105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5245105197Ssam			continue;
5246105197Ssam
5247105197Ssam		/* get a SA with SPI. */
5248105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5249105197Ssam		if (sav)
5250105197Ssam			break;
5251105197Ssam	}
5252105197Ssam	if (sah == NULL) {
5253120585Ssam		SAHTREE_UNLOCK();
5254120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5255105197Ssam		return key_senderror(so, m, ENOENT);
5256105197Ssam	}
5257105197Ssam
5258105197Ssam	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5259120585Ssam	SAHTREE_UNLOCK();
5260105197Ssam	KEY_FREESAV(&sav);
5261105197Ssam
5262105197Ssam    {
5263105197Ssam	struct mbuf *n;
5264105197Ssam	struct sadb_msg *newmsg;
5265105197Ssam
5266105197Ssam	/* create new sadb_msg to reply. */
5267105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5268105197Ssam	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5269105197Ssam	if (!n)
5270105197Ssam		return key_senderror(so, m, ENOBUFS);
5271105197Ssam
5272105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5273105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5274105197Ssam		if (n == NULL)
5275105197Ssam			return key_senderror(so, m, ENOBUFS);
5276105197Ssam	}
5277105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5278105197Ssam	newmsg->sadb_msg_errno = 0;
5279105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5280105197Ssam
5281105197Ssam	m_freem(m);
5282105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5283105197Ssam    }
5284105197Ssam}
5285105197Ssam
5286105197Ssam/*
5287105197Ssam * delete all SAs for src/dst.  Called from key_delete().
5288105197Ssam */
5289105197Ssamstatic int
5290105197Ssamkey_delete_all(so, m, mhp, proto)
5291105197Ssam	struct socket *so;
5292105197Ssam	struct mbuf *m;
5293105197Ssam	const struct sadb_msghdr *mhp;
5294105197Ssam	u_int16_t proto;
5295105197Ssam{
5296183550Szec	INIT_VNET_IPSEC(curvnet);
5297105197Ssam	struct sadb_address *src0, *dst0;
5298105197Ssam	struct secasindex saidx;
5299105197Ssam	struct secashead *sah;
5300105197Ssam	struct secasvar *sav, *nextsav;
5301105197Ssam	u_int stateidx, state;
5302105197Ssam
5303105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5304105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5305105197Ssam
5306105197Ssam	/* XXX boundary check against sa_len */
5307105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5308105197Ssam
5309120585Ssam	SAHTREE_LOCK();
5310181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5311105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5312105197Ssam			continue;
5313105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5314105197Ssam			continue;
5315105197Ssam
5316105197Ssam		/* Delete all non-LARVAL SAs. */
5317105197Ssam		for (stateidx = 0;
5318185348Szec		     stateidx < _ARRAYLEN(saorder_state_alive);
5319105197Ssam		     stateidx++) {
5320185348Szec			state = saorder_state_alive[stateidx];
5321105197Ssam			if (state == SADB_SASTATE_LARVAL)
5322105197Ssam				continue;
5323105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
5324105197Ssam			     sav != NULL; sav = nextsav) {
5325105197Ssam				nextsav = LIST_NEXT(sav, chain);
5326105197Ssam				/* sanity check */
5327105197Ssam				if (sav->state != state) {
5328120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
5329120585Ssam						"sav->state (queue %d SA %d)\n",
5330120585Ssam						__func__, state, sav->state));
5331105197Ssam					continue;
5332105197Ssam				}
5333105197Ssam
5334105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5335105197Ssam				KEY_FREESAV(&sav);
5336105197Ssam			}
5337105197Ssam		}
5338105197Ssam	}
5339120585Ssam	SAHTREE_UNLOCK();
5340105197Ssam    {
5341105197Ssam	struct mbuf *n;
5342105197Ssam	struct sadb_msg *newmsg;
5343105197Ssam
5344105197Ssam	/* create new sadb_msg to reply. */
5345105197Ssam	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5346105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5347105197Ssam	if (!n)
5348105197Ssam		return key_senderror(so, m, ENOBUFS);
5349105197Ssam
5350105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5351105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5352105197Ssam		if (n == NULL)
5353105197Ssam			return key_senderror(so, m, ENOBUFS);
5354105197Ssam	}
5355105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5356105197Ssam	newmsg->sadb_msg_errno = 0;
5357105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5358105197Ssam
5359105197Ssam	m_freem(m);
5360105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5361105197Ssam    }
5362105197Ssam}
5363105197Ssam
5364105197Ssam/*
5365105197Ssam * SADB_GET processing
5366105197Ssam * receive
5367105197Ssam *   <base, SA(*), address(SD)>
5368105197Ssam * from the ikmpd, and get a SP and a SA to respond,
5369105197Ssam * and send,
5370105197Ssam *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5371105197Ssam *       (identity(SD),) (sensitivity)>
5372105197Ssam * to the ikmpd.
5373105197Ssam *
5374105197Ssam * m will always be freed.
5375105197Ssam */
5376105197Ssamstatic int
5377105197Ssamkey_get(so, m, mhp)
5378105197Ssam	struct socket *so;
5379105197Ssam	struct mbuf *m;
5380105197Ssam	const struct sadb_msghdr *mhp;
5381105197Ssam{
5382183550Szec	INIT_VNET_IPSEC(curvnet);
5383105197Ssam	struct sadb_sa *sa0;
5384105197Ssam	struct sadb_address *src0, *dst0;
5385105197Ssam	struct secasindex saidx;
5386105197Ssam	struct secashead *sah;
5387105197Ssam	struct secasvar *sav = NULL;
5388105197Ssam	u_int16_t proto;
5389105197Ssam
5390120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5391120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5392120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5393120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5394105197Ssam
5395105197Ssam	/* map satype to proto */
5396105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5397120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5398120585Ssam			__func__));
5399105197Ssam		return key_senderror(so, m, EINVAL);
5400105197Ssam	}
5401105197Ssam
5402105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5403105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5404105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5405120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5406120585Ssam			__func__));
5407105197Ssam		return key_senderror(so, m, EINVAL);
5408105197Ssam	}
5409105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5410105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5411105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5412120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5413120585Ssam			__func__));
5414105197Ssam		return key_senderror(so, m, EINVAL);
5415105197Ssam	}
5416105197Ssam
5417105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5418105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5419105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5420105197Ssam
5421105197Ssam	/* XXX boundary check against sa_len */
5422105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5423105197Ssam
5424105197Ssam	/* get a SA header */
5425120585Ssam	SAHTREE_LOCK();
5426181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5427105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5428105197Ssam			continue;
5429105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5430105197Ssam			continue;
5431105197Ssam
5432105197Ssam		/* get a SA with SPI. */
5433105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5434105197Ssam		if (sav)
5435105197Ssam			break;
5436105197Ssam	}
5437120585Ssam	SAHTREE_UNLOCK();
5438105197Ssam	if (sah == NULL) {
5439120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5440105197Ssam		return key_senderror(so, m, ENOENT);
5441105197Ssam	}
5442105197Ssam
5443105197Ssam    {
5444105197Ssam	struct mbuf *n;
5445105197Ssam	u_int8_t satype;
5446105197Ssam
5447105197Ssam	/* map proto to satype */
5448105197Ssam	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5449120585Ssam		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5450120585Ssam			__func__));
5451105197Ssam		return key_senderror(so, m, EINVAL);
5452105197Ssam	}
5453105197Ssam
5454105197Ssam	/* create new sadb_msg to reply. */
5455105197Ssam	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5456105197Ssam	    mhp->msg->sadb_msg_pid);
5457105197Ssam	if (!n)
5458105197Ssam		return key_senderror(so, m, ENOBUFS);
5459105197Ssam
5460105197Ssam	m_freem(m);
5461105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5462105197Ssam    }
5463105197Ssam}
5464105197Ssam
5465105197Ssam/* XXX make it sysctl-configurable? */
5466105197Ssamstatic void
5467105197Ssamkey_getcomb_setlifetime(comb)
5468105197Ssam	struct sadb_comb *comb;
5469105197Ssam{
5470105197Ssam
5471105197Ssam	comb->sadb_comb_soft_allocations = 1;
5472105197Ssam	comb->sadb_comb_hard_allocations = 1;
5473105197Ssam	comb->sadb_comb_soft_bytes = 0;
5474105197Ssam	comb->sadb_comb_hard_bytes = 0;
5475105197Ssam	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5476105197Ssam	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5477105197Ssam	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5478105197Ssam	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5479105197Ssam}
5480105197Ssam
5481105197Ssam/*
5482105197Ssam * XXX reorder combinations by preference
5483105197Ssam * XXX no idea if the user wants ESP authentication or not
5484105197Ssam */
5485105197Ssamstatic struct mbuf *
5486105197Ssamkey_getcomb_esp()
5487105197Ssam{
5488183550Szec	INIT_VNET_IPSEC(curvnet);
5489105197Ssam	struct sadb_comb *comb;
5490105197Ssam	struct enc_xform *algo;
5491105197Ssam	struct mbuf *result = NULL, *m, *n;
5492105197Ssam	int encmin;
5493105197Ssam	int i, off, o;
5494105197Ssam	int totlen;
5495105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5496105197Ssam
5497105197Ssam	m = NULL;
5498105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
5499105197Ssam		algo = esp_algorithm_lookup(i);
5500105197Ssam		if (algo == NULL)
5501105197Ssam			continue;
5502105197Ssam
5503105197Ssam		/* discard algorithms with key size smaller than system min */
5504181803Sbz		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
5505105197Ssam			continue;
5506181803Sbz		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
5507181803Sbz			encmin = V_ipsec_esp_keymin;
5508105197Ssam		else
5509105197Ssam			encmin = _BITS(algo->minkey);
5510105197Ssam
5511181803Sbz		if (V_ipsec_esp_auth)
5512105197Ssam			m = key_getcomb_ah();
5513105197Ssam		else {
5514120585Ssam			IPSEC_ASSERT(l <= MLEN,
5515120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5516111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5517105197Ssam			if (m) {
5518105197Ssam				M_ALIGN(m, l);
5519105197Ssam				m->m_len = l;
5520105197Ssam				m->m_next = NULL;
5521105197Ssam				bzero(mtod(m, caddr_t), m->m_len);
5522105197Ssam			}
5523105197Ssam		}
5524105197Ssam		if (!m)
5525105197Ssam			goto fail;
5526105197Ssam
5527105197Ssam		totlen = 0;
5528105197Ssam		for (n = m; n; n = n->m_next)
5529105197Ssam			totlen += n->m_len;
5530120585Ssam		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
5531105197Ssam
5532105197Ssam		for (off = 0; off < totlen; off += l) {
5533105197Ssam			n = m_pulldown(m, off, l, &o);
5534105197Ssam			if (!n) {
5535105197Ssam				/* m is already freed */
5536105197Ssam				goto fail;
5537105197Ssam			}
5538105197Ssam			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5539105197Ssam			bzero(comb, sizeof(*comb));
5540105197Ssam			key_getcomb_setlifetime(comb);
5541105197Ssam			comb->sadb_comb_encrypt = i;
5542105197Ssam			comb->sadb_comb_encrypt_minbits = encmin;
5543105197Ssam			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5544105197Ssam		}
5545105197Ssam
5546105197Ssam		if (!result)
5547105197Ssam			result = m;
5548105197Ssam		else
5549105197Ssam			m_cat(result, m);
5550105197Ssam	}
5551105197Ssam
5552105197Ssam	return result;
5553105197Ssam
5554105197Ssam fail:
5555105197Ssam	if (result)
5556105197Ssam		m_freem(result);
5557105197Ssam	return NULL;
5558105197Ssam}
5559105197Ssam
5560105197Ssamstatic void
5561105197Ssamkey_getsizes_ah(
5562105197Ssam	const struct auth_hash *ah,
5563105197Ssam	int alg,
5564105197Ssam	u_int16_t* min,
5565105197Ssam	u_int16_t* max)
5566105197Ssam{
5567183550Szec	INIT_VNET_IPSEC(curvnet);
5568183550Szec
5569105197Ssam	*min = *max = ah->keysize;
5570105197Ssam	if (ah->keysize == 0) {
5571105197Ssam		/*
5572105197Ssam		 * Transform takes arbitrary key size but algorithm
5573105197Ssam		 * key size is restricted.  Enforce this here.
5574105197Ssam		 */
5575105197Ssam		switch (alg) {
5576105197Ssam		case SADB_X_AALG_MD5:	*min = *max = 16; break;
5577105197Ssam		case SADB_X_AALG_SHA:	*min = *max = 20; break;
5578105197Ssam		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
5579105197Ssam		default:
5580120585Ssam			DPRINTF(("%s: unknown AH algorithm %u\n",
5581120585Ssam				__func__, alg));
5582105197Ssam			break;
5583105197Ssam		}
5584105197Ssam	}
5585105197Ssam}
5586105197Ssam
5587105197Ssam/*
5588105197Ssam * XXX reorder combinations by preference
5589105197Ssam */
5590105197Ssamstatic struct mbuf *
5591105197Ssamkey_getcomb_ah()
5592105197Ssam{
5593183550Szec	INIT_VNET_IPSEC(curvnet);
5594105197Ssam	struct sadb_comb *comb;
5595105197Ssam	struct auth_hash *algo;
5596105197Ssam	struct mbuf *m;
5597105197Ssam	u_int16_t minkeysize, maxkeysize;
5598105197Ssam	int i;
5599105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5600105197Ssam
5601105197Ssam	m = NULL;
5602105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
5603105197Ssam#if 1
5604105197Ssam		/* we prefer HMAC algorithms, not old algorithms */
5605105197Ssam		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5606105197Ssam			continue;
5607105197Ssam#endif
5608105197Ssam		algo = ah_algorithm_lookup(i);
5609105197Ssam		if (!algo)
5610105197Ssam			continue;
5611105197Ssam		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5612105197Ssam		/* discard algorithms with key size smaller than system min */
5613181803Sbz		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
5614105197Ssam			continue;
5615105197Ssam
5616105197Ssam		if (!m) {
5617120585Ssam			IPSEC_ASSERT(l <= MLEN,
5618120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5619111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5620105197Ssam			if (m) {
5621105197Ssam				M_ALIGN(m, l);
5622105197Ssam				m->m_len = l;
5623105197Ssam				m->m_next = NULL;
5624105197Ssam			}
5625105197Ssam		} else
5626111119Simp			M_PREPEND(m, l, M_DONTWAIT);
5627105197Ssam		if (!m)
5628105197Ssam			return NULL;
5629105197Ssam
5630105197Ssam		comb = mtod(m, struct sadb_comb *);
5631105197Ssam		bzero(comb, sizeof(*comb));
5632105197Ssam		key_getcomb_setlifetime(comb);
5633105197Ssam		comb->sadb_comb_auth = i;
5634105197Ssam		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5635105197Ssam		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5636105197Ssam	}
5637105197Ssam
5638105197Ssam	return m;
5639105197Ssam}
5640105197Ssam
5641105197Ssam/*
5642105197Ssam * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5643105197Ssam * XXX reorder combinations by preference
5644105197Ssam */
5645105197Ssamstatic struct mbuf *
5646105197Ssamkey_getcomb_ipcomp()
5647105197Ssam{
5648105197Ssam	struct sadb_comb *comb;
5649105197Ssam	struct comp_algo *algo;
5650105197Ssam	struct mbuf *m;
5651105197Ssam	int i;
5652105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5653105197Ssam
5654105197Ssam	m = NULL;
5655105197Ssam	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5656105197Ssam		algo = ipcomp_algorithm_lookup(i);
5657105197Ssam		if (!algo)
5658105197Ssam			continue;
5659105197Ssam
5660105197Ssam		if (!m) {
5661120585Ssam			IPSEC_ASSERT(l <= MLEN,
5662120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
5663111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
5664105197Ssam			if (m) {
5665105197Ssam				M_ALIGN(m, l);
5666105197Ssam				m->m_len = l;
5667105197Ssam				m->m_next = NULL;
5668105197Ssam			}
5669105197Ssam		} else
5670111119Simp			M_PREPEND(m, l, M_DONTWAIT);
5671105197Ssam		if (!m)
5672105197Ssam			return NULL;
5673105197Ssam
5674105197Ssam		comb = mtod(m, struct sadb_comb *);
5675105197Ssam		bzero(comb, sizeof(*comb));
5676105197Ssam		key_getcomb_setlifetime(comb);
5677105197Ssam		comb->sadb_comb_encrypt = i;
5678105197Ssam		/* what should we set into sadb_comb_*_{min,max}bits? */
5679105197Ssam	}
5680105197Ssam
5681105197Ssam	return m;
5682105197Ssam}
5683105197Ssam
5684105197Ssam/*
5685105197Ssam * XXX no way to pass mode (transport/tunnel) to userland
5686105197Ssam * XXX replay checking?
5687105197Ssam * XXX sysctl interface to ipsec_{ah,esp}_keymin
5688105197Ssam */
5689105197Ssamstatic struct mbuf *
5690105197Ssamkey_getprop(saidx)
5691105197Ssam	const struct secasindex *saidx;
5692105197Ssam{
5693105197Ssam	struct sadb_prop *prop;
5694105197Ssam	struct mbuf *m, *n;
5695105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5696105197Ssam	int totlen;
5697105197Ssam
5698105197Ssam	switch (saidx->proto)  {
5699105197Ssam	case IPPROTO_ESP:
5700105197Ssam		m = key_getcomb_esp();
5701105197Ssam		break;
5702105197Ssam	case IPPROTO_AH:
5703105197Ssam		m = key_getcomb_ah();
5704105197Ssam		break;
5705105197Ssam	case IPPROTO_IPCOMP:
5706105197Ssam		m = key_getcomb_ipcomp();
5707105197Ssam		break;
5708105197Ssam	default:
5709105197Ssam		return NULL;
5710105197Ssam	}
5711105197Ssam
5712105197Ssam	if (!m)
5713105197Ssam		return NULL;
5714111119Simp	M_PREPEND(m, l, M_DONTWAIT);
5715105197Ssam	if (!m)
5716105197Ssam		return NULL;
5717105197Ssam
5718105197Ssam	totlen = 0;
5719105197Ssam	for (n = m; n; n = n->m_next)
5720105197Ssam		totlen += n->m_len;
5721105197Ssam
5722105197Ssam	prop = mtod(m, struct sadb_prop *);
5723105197Ssam	bzero(prop, sizeof(*prop));
5724105197Ssam	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5725105197Ssam	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5726105197Ssam	prop->sadb_prop_replay = 32;	/* XXX */
5727105197Ssam
5728105197Ssam	return m;
5729105197Ssam}
5730105197Ssam
5731105197Ssam/*
5732105197Ssam * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5733105197Ssam * send
5734105197Ssam *   <base, SA, address(SD), (address(P)), x_policy,
5735105197Ssam *       (identity(SD),) (sensitivity,) proposal>
5736105197Ssam * to KMD, and expect to receive
5737105197Ssam *   <base> with SADB_ACQUIRE if error occured,
5738105197Ssam * or
5739105197Ssam *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5740105197Ssam * from KMD by PF_KEY.
5741105197Ssam *
5742105197Ssam * XXX x_policy is outside of RFC2367 (KAME extension).
5743105197Ssam * XXX sensitivity is not supported.
5744105197Ssam * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5745105197Ssam * see comment for key_getcomb_ipcomp().
5746105197Ssam *
5747105197Ssam * OUT:
5748105197Ssam *    0     : succeed
5749105197Ssam *    others: error number
5750105197Ssam */
5751105197Ssamstatic int
5752105197Ssamkey_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5753105197Ssam{
5754183550Szec	INIT_VNET_IPSEC(curvnet);
5755105197Ssam	struct mbuf *result = NULL, *m;
5756105197Ssam	struct secacq *newacq;
5757105197Ssam	u_int8_t satype;
5758105197Ssam	int error = -1;
5759105197Ssam	u_int32_t seq;
5760105197Ssam
5761120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
5762105197Ssam	satype = key_proto2satype(saidx->proto);
5763120585Ssam	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
5764105197Ssam
5765105197Ssam	/*
5766105197Ssam	 * We never do anything about acquirng SA.  There is anather
5767105197Ssam	 * solution that kernel blocks to send SADB_ACQUIRE message until
5768105197Ssam	 * getting something message from IKEd.  In later case, to be
5769105197Ssam	 * managed with ACQUIRING list.
5770105197Ssam	 */
5771108533Sschweikh	/* Get an entry to check whether sending message or not. */
5772105197Ssam	if ((newacq = key_getacq(saidx)) != NULL) {
5773181803Sbz		if (V_key_blockacq_count < newacq->count) {
5774105197Ssam			/* reset counter and do send message. */
5775105197Ssam			newacq->count = 0;
5776105197Ssam		} else {
5777105197Ssam			/* increment counter and do nothing. */
5778105197Ssam			newacq->count++;
5779105197Ssam			return 0;
5780105197Ssam		}
5781105197Ssam	} else {
5782105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
5783105197Ssam		if ((newacq = key_newacq(saidx)) == NULL)
5784105197Ssam			return ENOBUFS;
5785105197Ssam	}
5786105197Ssam
5787105197Ssam
5788105197Ssam	seq = newacq->seq;
5789105197Ssam	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5790105197Ssam	if (!m) {
5791105197Ssam		error = ENOBUFS;
5792105197Ssam		goto fail;
5793105197Ssam	}
5794105197Ssam	result = m;
5795105197Ssam
5796105197Ssam	/* set sadb_address for saidx's. */
5797105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5798105197Ssam	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5799105197Ssam	if (!m) {
5800105197Ssam		error = ENOBUFS;
5801105197Ssam		goto fail;
5802105197Ssam	}
5803105197Ssam	m_cat(result, m);
5804105197Ssam
5805105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5806105197Ssam	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5807105197Ssam	if (!m) {
5808105197Ssam		error = ENOBUFS;
5809105197Ssam		goto fail;
5810105197Ssam	}
5811105197Ssam	m_cat(result, m);
5812105197Ssam
5813105197Ssam	/* XXX proxy address (optional) */
5814105197Ssam
5815105197Ssam	/* set sadb_x_policy */
5816105197Ssam	if (sp) {
5817105197Ssam		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5818105197Ssam		if (!m) {
5819105197Ssam			error = ENOBUFS;
5820105197Ssam			goto fail;
5821105197Ssam		}
5822105197Ssam		m_cat(result, m);
5823105197Ssam	}
5824105197Ssam
5825105197Ssam	/* XXX identity (optional) */
5826105197Ssam#if 0
5827105197Ssam	if (idexttype && fqdn) {
5828105197Ssam		/* create identity extension (FQDN) */
5829105197Ssam		struct sadb_ident *id;
5830105197Ssam		int fqdnlen;
5831105197Ssam
5832105197Ssam		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
5833105197Ssam		id = (struct sadb_ident *)p;
5834105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5835105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5836105197Ssam		id->sadb_ident_exttype = idexttype;
5837105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5838105197Ssam		bcopy(fqdn, id + 1, fqdnlen);
5839105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5840105197Ssam	}
5841105197Ssam
5842105197Ssam	if (idexttype) {
5843105197Ssam		/* create identity extension (USERFQDN) */
5844105197Ssam		struct sadb_ident *id;
5845105197Ssam		int userfqdnlen;
5846105197Ssam
5847105197Ssam		if (userfqdn) {
5848105197Ssam			/* +1 for terminating-NUL */
5849105197Ssam			userfqdnlen = strlen(userfqdn) + 1;
5850105197Ssam		} else
5851105197Ssam			userfqdnlen = 0;
5852105197Ssam		id = (struct sadb_ident *)p;
5853105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5854105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5855105197Ssam		id->sadb_ident_exttype = idexttype;
5856105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5857105197Ssam		/* XXX is it correct? */
5858105197Ssam		if (curproc && curproc->p_cred)
5859105197Ssam			id->sadb_ident_id = curproc->p_cred->p_ruid;
5860105197Ssam		if (userfqdn && userfqdnlen)
5861105197Ssam			bcopy(userfqdn, id + 1, userfqdnlen);
5862105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5863105197Ssam	}
5864105197Ssam#endif
5865105197Ssam
5866105197Ssam	/* XXX sensitivity (optional) */
5867105197Ssam
5868105197Ssam	/* create proposal/combination extension */
5869105197Ssam	m = key_getprop(saidx);
5870105197Ssam#if 0
5871105197Ssam	/*
5872105197Ssam	 * spec conformant: always attach proposal/combination extension,
5873105197Ssam	 * the problem is that we have no way to attach it for ipcomp,
5874105197Ssam	 * due to the way sadb_comb is declared in RFC2367.
5875105197Ssam	 */
5876105197Ssam	if (!m) {
5877105197Ssam		error = ENOBUFS;
5878105197Ssam		goto fail;
5879105197Ssam	}
5880105197Ssam	m_cat(result, m);
5881105197Ssam#else
5882105197Ssam	/*
5883105197Ssam	 * outside of spec; make proposal/combination extension optional.
5884105197Ssam	 */
5885105197Ssam	if (m)
5886105197Ssam		m_cat(result, m);
5887105197Ssam#endif
5888105197Ssam
5889105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
5890105197Ssam		error = EINVAL;
5891105197Ssam		goto fail;
5892105197Ssam	}
5893105197Ssam
5894105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
5895105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
5896105197Ssam		if (result == NULL) {
5897105197Ssam			error = ENOBUFS;
5898105197Ssam			goto fail;
5899105197Ssam		}
5900105197Ssam	}
5901105197Ssam
5902105197Ssam	result->m_pkthdr.len = 0;
5903105197Ssam	for (m = result; m; m = m->m_next)
5904105197Ssam		result->m_pkthdr.len += m->m_len;
5905105197Ssam
5906105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
5907105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
5908105197Ssam
5909105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5910105197Ssam
5911105197Ssam fail:
5912105197Ssam	if (result)
5913105197Ssam		m_freem(result);
5914105197Ssam	return error;
5915105197Ssam}
5916105197Ssam
5917105197Ssamstatic struct secacq *
5918105197Ssamkey_newacq(const struct secasindex *saidx)
5919105197Ssam{
5920183550Szec	INIT_VNET_IPSEC(curvnet);
5921105197Ssam	struct secacq *newacq;
5922105197Ssam
5923105197Ssam	/* get new entry */
5924119643Ssam	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5925105197Ssam	if (newacq == NULL) {
5926120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5927105197Ssam		return NULL;
5928105197Ssam	}
5929105197Ssam
5930105197Ssam	/* copy secindex */
5931105197Ssam	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5932181803Sbz	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
5933105197Ssam	newacq->created = time_second;
5934105197Ssam	newacq->count = 0;
5935105197Ssam
5936119643Ssam	/* add to acqtree */
5937120585Ssam	ACQ_LOCK();
5938181803Sbz	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
5939120585Ssam	ACQ_UNLOCK();
5940119643Ssam
5941105197Ssam	return newacq;
5942105197Ssam}
5943105197Ssam
5944105197Ssamstatic struct secacq *
5945105197Ssamkey_getacq(const struct secasindex *saidx)
5946105197Ssam{
5947183550Szec	INIT_VNET_IPSEC(curvnet);
5948105197Ssam	struct secacq *acq;
5949105197Ssam
5950120585Ssam	ACQ_LOCK();
5951181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
5952105197Ssam		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5953119643Ssam			break;
5954105197Ssam	}
5955120585Ssam	ACQ_UNLOCK();
5956105197Ssam
5957119643Ssam	return acq;
5958105197Ssam}
5959105197Ssam
5960105197Ssamstatic struct secacq *
5961105197Ssamkey_getacqbyseq(seq)
5962105197Ssam	u_int32_t seq;
5963105197Ssam{
5964183550Szec	INIT_VNET_IPSEC(curvnet);
5965105197Ssam	struct secacq *acq;
5966105197Ssam
5967120585Ssam	ACQ_LOCK();
5968181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
5969105197Ssam		if (acq->seq == seq)
5970119643Ssam			break;
5971105197Ssam	}
5972120585Ssam	ACQ_UNLOCK();
5973105197Ssam
5974119643Ssam	return acq;
5975105197Ssam}
5976105197Ssam
5977105197Ssamstatic struct secspacq *
5978105197Ssamkey_newspacq(spidx)
5979105197Ssam	struct secpolicyindex *spidx;
5980105197Ssam{
5981183550Szec	INIT_VNET_IPSEC(curvnet);
5982105197Ssam	struct secspacq *acq;
5983105197Ssam
5984105197Ssam	/* get new entry */
5985119643Ssam	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5986105197Ssam	if (acq == NULL) {
5987120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5988105197Ssam		return NULL;
5989105197Ssam	}
5990105197Ssam
5991105197Ssam	/* copy secindex */
5992105197Ssam	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5993105197Ssam	acq->created = time_second;
5994105197Ssam	acq->count = 0;
5995105197Ssam
5996119643Ssam	/* add to spacqtree */
5997120585Ssam	SPACQ_LOCK();
5998181803Sbz	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
5999120585Ssam	SPACQ_UNLOCK();
6000119643Ssam
6001105197Ssam	return acq;
6002105197Ssam}
6003105197Ssam
6004105197Ssamstatic struct secspacq *
6005105197Ssamkey_getspacq(spidx)
6006105197Ssam	struct secpolicyindex *spidx;
6007105197Ssam{
6008183550Szec	INIT_VNET_IPSEC(curvnet);
6009105197Ssam	struct secspacq *acq;
6010105197Ssam
6011120585Ssam	SPACQ_LOCK();
6012181803Sbz	LIST_FOREACH(acq, &V_spacqtree, chain) {
6013119643Ssam		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6014119643Ssam			/* NB: return holding spacq_lock */
6015105197Ssam			return acq;
6016119643Ssam		}
6017105197Ssam	}
6018120585Ssam	SPACQ_UNLOCK();
6019105197Ssam
6020105197Ssam	return NULL;
6021105197Ssam}
6022105197Ssam
6023105197Ssam/*
6024105197Ssam * SADB_ACQUIRE processing,
6025105197Ssam * in first situation, is receiving
6026105197Ssam *   <base>
6027105197Ssam * from the ikmpd, and clear sequence of its secasvar entry.
6028105197Ssam *
6029105197Ssam * In second situation, is receiving
6030105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6031105197Ssam * from a user land process, and return
6032105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6033105197Ssam * to the socket.
6034105197Ssam *
6035105197Ssam * m will always be freed.
6036105197Ssam */
6037105197Ssamstatic int
6038105197Ssamkey_acquire2(so, m, mhp)
6039105197Ssam	struct socket *so;
6040105197Ssam	struct mbuf *m;
6041105197Ssam	const struct sadb_msghdr *mhp;
6042105197Ssam{
6043183550Szec	INIT_VNET_IPSEC(curvnet);
6044105197Ssam	const struct sadb_address *src0, *dst0;
6045105197Ssam	struct secasindex saidx;
6046105197Ssam	struct secashead *sah;
6047105197Ssam	u_int16_t proto;
6048105197Ssam	int error;
6049105197Ssam
6050120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6051120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6052120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6053120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6054105197Ssam
6055105197Ssam	/*
6056105197Ssam	 * Error message from KMd.
6057105197Ssam	 * We assume that if error was occured in IKEd, the length of PFKEY
6058105197Ssam	 * message is equal to the size of sadb_msg structure.
6059105197Ssam	 * We do not raise error even if error occured in this function.
6060105197Ssam	 */
6061105197Ssam	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6062105197Ssam		struct secacq *acq;
6063105197Ssam
6064105197Ssam		/* check sequence number */
6065105197Ssam		if (mhp->msg->sadb_msg_seq == 0) {
6066120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6067120585Ssam				"number.\n", __func__));
6068105197Ssam			m_freem(m);
6069105197Ssam			return 0;
6070105197Ssam		}
6071105197Ssam
6072105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6073105197Ssam			/*
6074105197Ssam			 * the specified larval SA is already gone, or we got
6075105197Ssam			 * a bogus sequence number.  we can silently ignore it.
6076105197Ssam			 */
6077105197Ssam			m_freem(m);
6078105197Ssam			return 0;
6079105197Ssam		}
6080105197Ssam
6081105197Ssam		/* reset acq counter in order to deletion by timehander. */
6082105197Ssam		acq->created = time_second;
6083105197Ssam		acq->count = 0;
6084105197Ssam		m_freem(m);
6085105197Ssam		return 0;
6086105197Ssam	}
6087105197Ssam
6088105197Ssam	/*
6089105197Ssam	 * This message is from user land.
6090105197Ssam	 */
6091105197Ssam
6092105197Ssam	/* map satype to proto */
6093105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6094120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6095120585Ssam			__func__));
6096105197Ssam		return key_senderror(so, m, EINVAL);
6097105197Ssam	}
6098105197Ssam
6099105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6100105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6101105197Ssam	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6102105197Ssam		/* error */
6103120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6104120585Ssam			__func__));
6105105197Ssam		return key_senderror(so, m, EINVAL);
6106105197Ssam	}
6107105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6108105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6109105197Ssam	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6110105197Ssam		/* error */
6111120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6112120585Ssam			__func__));
6113105197Ssam		return key_senderror(so, m, EINVAL);
6114105197Ssam	}
6115105197Ssam
6116105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6117105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6118105197Ssam
6119105197Ssam	/* XXX boundary check against sa_len */
6120105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6121105197Ssam
6122105197Ssam	/* get a SA index */
6123120585Ssam	SAHTREE_LOCK();
6124181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
6125105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
6126105197Ssam			continue;
6127105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6128105197Ssam			break;
6129105197Ssam	}
6130120585Ssam	SAHTREE_UNLOCK();
6131105197Ssam	if (sah != NULL) {
6132120585Ssam		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6133105197Ssam		return key_senderror(so, m, EEXIST);
6134105197Ssam	}
6135105197Ssam
6136105197Ssam	error = key_acquire(&saidx, NULL);
6137105197Ssam	if (error != 0) {
6138120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6139120585Ssam			__func__, mhp->msg->sadb_msg_errno));
6140105197Ssam		return key_senderror(so, m, error);
6141105197Ssam	}
6142105197Ssam
6143105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6144105197Ssam}
6145105197Ssam
6146105197Ssam/*
6147105197Ssam * SADB_REGISTER processing.
6148105197Ssam * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6149105197Ssam * receive
6150105197Ssam *   <base>
6151105197Ssam * from the ikmpd, and register a socket to send PF_KEY messages,
6152105197Ssam * and send
6153105197Ssam *   <base, supported>
6154105197Ssam * to KMD by PF_KEY.
6155105197Ssam * If socket is detached, must free from regnode.
6156105197Ssam *
6157105197Ssam * m will always be freed.
6158105197Ssam */
6159105197Ssamstatic int
6160105197Ssamkey_register(so, m, mhp)
6161105197Ssam	struct socket *so;
6162105197Ssam	struct mbuf *m;
6163105197Ssam	const struct sadb_msghdr *mhp;
6164105197Ssam{
6165183550Szec	INIT_VNET_IPSEC(curvnet);
6166105197Ssam	struct secreg *reg, *newreg = 0;
6167105197Ssam
6168120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6169120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6170120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6171120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6172105197Ssam
6173105197Ssam	/* check for invalid register message */
6174181803Sbz	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6175105197Ssam		return key_senderror(so, m, EINVAL);
6176105197Ssam
6177105197Ssam	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6178105197Ssam	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6179105197Ssam		goto setmsg;
6180105197Ssam
6181105197Ssam	/* check whether existing or not */
6182120585Ssam	REGTREE_LOCK();
6183181803Sbz	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6184105197Ssam		if (reg->so == so) {
6185120585Ssam			REGTREE_UNLOCK();
6186120585Ssam			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6187120585Ssam				__func__));
6188105197Ssam			return key_senderror(so, m, EEXIST);
6189105197Ssam		}
6190105197Ssam	}
6191105197Ssam
6192105197Ssam	/* create regnode */
6193119643Ssam	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6194105197Ssam	if (newreg == NULL) {
6195120585Ssam		REGTREE_UNLOCK();
6196120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6197105197Ssam		return key_senderror(so, m, ENOBUFS);
6198105197Ssam	}
6199105197Ssam
6200105197Ssam	newreg->so = so;
6201105197Ssam	((struct keycb *)sotorawcb(so))->kp_registered++;
6202105197Ssam
6203105197Ssam	/* add regnode to regtree. */
6204181803Sbz	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6205120585Ssam	REGTREE_UNLOCK();
6206105197Ssam
6207105197Ssam  setmsg:
6208105197Ssam    {
6209105197Ssam	struct mbuf *n;
6210105197Ssam	struct sadb_msg *newmsg;
6211105197Ssam	struct sadb_supported *sup;
6212105197Ssam	u_int len, alen, elen;
6213105197Ssam	int off;
6214105197Ssam	int i;
6215105197Ssam	struct sadb_alg *alg;
6216105197Ssam
6217105197Ssam	/* create new sadb_msg to reply. */
6218105197Ssam	alen = 0;
6219105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6220105197Ssam		if (ah_algorithm_lookup(i))
6221105197Ssam			alen += sizeof(struct sadb_alg);
6222105197Ssam	}
6223105197Ssam	if (alen)
6224105197Ssam		alen += sizeof(struct sadb_supported);
6225105197Ssam	elen = 0;
6226105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6227105197Ssam		if (esp_algorithm_lookup(i))
6228105197Ssam			elen += sizeof(struct sadb_alg);
6229105197Ssam	}
6230105197Ssam	if (elen)
6231105197Ssam		elen += sizeof(struct sadb_supported);
6232105197Ssam
6233105197Ssam	len = sizeof(struct sadb_msg) + alen + elen;
6234105197Ssam
6235105197Ssam	if (len > MCLBYTES)
6236105197Ssam		return key_senderror(so, m, ENOBUFS);
6237105197Ssam
6238111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
6239105197Ssam	if (len > MHLEN) {
6240111119Simp		MCLGET(n, M_DONTWAIT);
6241105197Ssam		if ((n->m_flags & M_EXT) == 0) {
6242105197Ssam			m_freem(n);
6243105197Ssam			n = NULL;
6244105197Ssam		}
6245105197Ssam	}
6246105197Ssam	if (!n)
6247105197Ssam		return key_senderror(so, m, ENOBUFS);
6248105197Ssam
6249105197Ssam	n->m_pkthdr.len = n->m_len = len;
6250105197Ssam	n->m_next = NULL;
6251105197Ssam	off = 0;
6252105197Ssam
6253105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6254105197Ssam	newmsg = mtod(n, struct sadb_msg *);
6255105197Ssam	newmsg->sadb_msg_errno = 0;
6256105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6257105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6258105197Ssam
6259105197Ssam	/* for authentication algorithm */
6260105197Ssam	if (alen) {
6261105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6262105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6263105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6264105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6265105197Ssam
6266105197Ssam		for (i = 1; i <= SADB_AALG_MAX; i++) {
6267105197Ssam			struct auth_hash *aalgo;
6268105197Ssam			u_int16_t minkeysize, maxkeysize;
6269105197Ssam
6270105197Ssam			aalgo = ah_algorithm_lookup(i);
6271105197Ssam			if (!aalgo)
6272105197Ssam				continue;
6273105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6274105197Ssam			alg->sadb_alg_id = i;
6275105197Ssam			alg->sadb_alg_ivlen = 0;
6276105197Ssam			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6277105197Ssam			alg->sadb_alg_minbits = _BITS(minkeysize);
6278105197Ssam			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6279105197Ssam			off += PFKEY_ALIGN8(sizeof(*alg));
6280105197Ssam		}
6281105197Ssam	}
6282105197Ssam
6283105197Ssam	/* for encryption algorithm */
6284105197Ssam	if (elen) {
6285105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6286105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6287105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6288105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6289105197Ssam
6290105197Ssam		for (i = 1; i <= SADB_EALG_MAX; i++) {
6291105197Ssam			struct enc_xform *ealgo;
6292105197Ssam
6293105197Ssam			ealgo = esp_algorithm_lookup(i);
6294105197Ssam			if (!ealgo)
6295105197Ssam				continue;
6296105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6297105197Ssam			alg->sadb_alg_id = i;
6298105197Ssam			alg->sadb_alg_ivlen = ealgo->blocksize;
6299105197Ssam			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6300105197Ssam			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6301105197Ssam			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6302105197Ssam		}
6303105197Ssam	}
6304105197Ssam
6305120585Ssam	IPSEC_ASSERT(off == len,
6306120585Ssam		("length assumption failed (off %u len %u)", off, len));
6307105197Ssam
6308105197Ssam	m_freem(m);
6309105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6310105197Ssam    }
6311105197Ssam}
6312105197Ssam
6313105197Ssam/*
6314105197Ssam * free secreg entry registered.
6315105197Ssam * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6316105197Ssam */
6317105197Ssamvoid
6318119643Ssamkey_freereg(struct socket *so)
6319105197Ssam{
6320183550Szec	INIT_VNET_IPSEC(curvnet);
6321105197Ssam	struct secreg *reg;
6322105197Ssam	int i;
6323105197Ssam
6324120585Ssam	IPSEC_ASSERT(so != NULL, ("NULL so"));
6325105197Ssam
6326105197Ssam	/*
6327105197Ssam	 * check whether existing or not.
6328105197Ssam	 * check all type of SA, because there is a potential that
6329105197Ssam	 * one socket is registered to multiple type of SA.
6330105197Ssam	 */
6331120585Ssam	REGTREE_LOCK();
6332105197Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6333181803Sbz		LIST_FOREACH(reg, &V_regtree[i], chain) {
6334119643Ssam			if (reg->so == so && __LIST_CHAINED(reg)) {
6335105197Ssam				LIST_REMOVE(reg, chain);
6336119643Ssam				free(reg, M_IPSEC_SAR);
6337105197Ssam				break;
6338105197Ssam			}
6339105197Ssam		}
6340105197Ssam	}
6341120585Ssam	REGTREE_UNLOCK();
6342105197Ssam}
6343105197Ssam
6344105197Ssam/*
6345105197Ssam * SADB_EXPIRE processing
6346105197Ssam * send
6347105197Ssam *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6348105197Ssam * to KMD by PF_KEY.
6349105197Ssam * NOTE: We send only soft lifetime extension.
6350105197Ssam *
6351105197Ssam * OUT:	0	: succeed
6352105197Ssam *	others	: error number
6353105197Ssam */
6354105197Ssamstatic int
6355119643Ssamkey_expire(struct secasvar *sav)
6356105197Ssam{
6357105197Ssam	int s;
6358105197Ssam	int satype;
6359105197Ssam	struct mbuf *result = NULL, *m;
6360105197Ssam	int len;
6361105197Ssam	int error = -1;
6362105197Ssam	struct sadb_lifetime *lt;
6363105197Ssam
6364105197Ssam	/* XXX: Why do we lock ? */
6365105197Ssam	s = splnet();	/*called from softclock()*/
6366105197Ssam
6367120585Ssam	IPSEC_ASSERT (sav != NULL, ("null sav"));
6368120585Ssam	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6369105197Ssam
6370105197Ssam	/* set msg header */
6371120585Ssam	satype = key_proto2satype(sav->sah->saidx.proto);
6372120585Ssam	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6373105197Ssam	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6374105197Ssam	if (!m) {
6375105197Ssam		error = ENOBUFS;
6376105197Ssam		goto fail;
6377105197Ssam	}
6378105197Ssam	result = m;
6379105197Ssam
6380105197Ssam	/* create SA extension */
6381105197Ssam	m = key_setsadbsa(sav);
6382105197Ssam	if (!m) {
6383105197Ssam		error = ENOBUFS;
6384105197Ssam		goto fail;
6385105197Ssam	}
6386105197Ssam	m_cat(result, m);
6387105197Ssam
6388105197Ssam	/* create SA extension */
6389105197Ssam	m = key_setsadbxsa2(sav->sah->saidx.mode,
6390105197Ssam			sav->replay ? sav->replay->count : 0,
6391105197Ssam			sav->sah->saidx.reqid);
6392105197Ssam	if (!m) {
6393105197Ssam		error = ENOBUFS;
6394105197Ssam		goto fail;
6395105197Ssam	}
6396105197Ssam	m_cat(result, m);
6397105197Ssam
6398105197Ssam	/* create lifetime extension (current and soft) */
6399105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6400105197Ssam	m = key_alloc_mbuf(len);
6401105197Ssam	if (!m || m->m_next) {	/*XXX*/
6402105197Ssam		if (m)
6403105197Ssam			m_freem(m);
6404105197Ssam		error = ENOBUFS;
6405105197Ssam		goto fail;
6406105197Ssam	}
6407105197Ssam	bzero(mtod(m, caddr_t), len);
6408105197Ssam	lt = mtod(m, struct sadb_lifetime *);
6409105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6410105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6411157123Sgnn	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6412157123Sgnn	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6413157123Sgnn	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6414157123Sgnn	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6415105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6416176743Sbz	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6417176743Sbz	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6418176743Sbz	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6419176743Sbz	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6420176743Sbz	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6421176743Sbz	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6422105197Ssam	m_cat(result, m);
6423105197Ssam
6424105197Ssam	/* set sadb_address for source */
6425105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6426105197Ssam	    &sav->sah->saidx.src.sa,
6427105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6428105197Ssam	if (!m) {
6429105197Ssam		error = ENOBUFS;
6430105197Ssam		goto fail;
6431105197Ssam	}
6432105197Ssam	m_cat(result, m);
6433105197Ssam
6434105197Ssam	/* set sadb_address for destination */
6435105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6436105197Ssam	    &sav->sah->saidx.dst.sa,
6437105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6438105197Ssam	if (!m) {
6439105197Ssam		error = ENOBUFS;
6440105197Ssam		goto fail;
6441105197Ssam	}
6442105197Ssam	m_cat(result, m);
6443105197Ssam
6444105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
6445105197Ssam		error = EINVAL;
6446105197Ssam		goto fail;
6447105197Ssam	}
6448105197Ssam
6449105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
6450105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
6451105197Ssam		if (result == NULL) {
6452105197Ssam			error = ENOBUFS;
6453105197Ssam			goto fail;
6454105197Ssam		}
6455105197Ssam	}
6456105197Ssam
6457105197Ssam	result->m_pkthdr.len = 0;
6458105197Ssam	for (m = result; m; m = m->m_next)
6459105197Ssam		result->m_pkthdr.len += m->m_len;
6460105197Ssam
6461105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
6462105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
6463105197Ssam
6464105197Ssam	splx(s);
6465105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6466105197Ssam
6467105197Ssam fail:
6468105197Ssam	if (result)
6469105197Ssam		m_freem(result);
6470105197Ssam	splx(s);
6471105197Ssam	return error;
6472105197Ssam}
6473105197Ssam
6474105197Ssam/*
6475105197Ssam * SADB_FLUSH processing
6476105197Ssam * receive
6477105197Ssam *   <base>
6478105197Ssam * from the ikmpd, and free all entries in secastree.
6479105197Ssam * and send,
6480105197Ssam *   <base>
6481105197Ssam * to the ikmpd.
6482105197Ssam * NOTE: to do is only marking SADB_SASTATE_DEAD.
6483105197Ssam *
6484105197Ssam * m will always be freed.
6485105197Ssam */
6486105197Ssamstatic int
6487105197Ssamkey_flush(so, m, mhp)
6488105197Ssam	struct socket *so;
6489105197Ssam	struct mbuf *m;
6490105197Ssam	const struct sadb_msghdr *mhp;
6491105197Ssam{
6492183550Szec	INIT_VNET_IPSEC(curvnet);
6493105197Ssam	struct sadb_msg *newmsg;
6494105197Ssam	struct secashead *sah, *nextsah;
6495105197Ssam	struct secasvar *sav, *nextsav;
6496105197Ssam	u_int16_t proto;
6497105197Ssam	u_int8_t state;
6498105197Ssam	u_int stateidx;
6499105197Ssam
6500120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6501120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6502120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6503105197Ssam
6504105197Ssam	/* map satype to proto */
6505105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6506120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6507120585Ssam			__func__));
6508105197Ssam		return key_senderror(so, m, EINVAL);
6509105197Ssam	}
6510105197Ssam
6511105197Ssam	/* no SATYPE specified, i.e. flushing all SA. */
6512120585Ssam	SAHTREE_LOCK();
6513181803Sbz	for (sah = LIST_FIRST(&V_sahtree);
6514105197Ssam	     sah != NULL;
6515105197Ssam	     sah = nextsah) {
6516105197Ssam		nextsah = LIST_NEXT(sah, chain);
6517105197Ssam
6518105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6519105197Ssam		 && proto != sah->saidx.proto)
6520105197Ssam			continue;
6521105197Ssam
6522105197Ssam		for (stateidx = 0;
6523185348Szec		     stateidx < _ARRAYLEN(saorder_state_alive);
6524105197Ssam		     stateidx++) {
6525185348Szec			state = saorder_state_any[stateidx];
6526105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
6527105197Ssam			     sav != NULL;
6528105197Ssam			     sav = nextsav) {
6529105197Ssam
6530105197Ssam				nextsav = LIST_NEXT(sav, chain);
6531105197Ssam
6532105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6533105197Ssam				KEY_FREESAV(&sav);
6534105197Ssam			}
6535105197Ssam		}
6536105197Ssam
6537105197Ssam		sah->state = SADB_SASTATE_DEAD;
6538105197Ssam	}
6539120585Ssam	SAHTREE_UNLOCK();
6540105197Ssam
6541105197Ssam	if (m->m_len < sizeof(struct sadb_msg) ||
6542105197Ssam	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6543120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6544105197Ssam		return key_senderror(so, m, ENOBUFS);
6545105197Ssam	}
6546105197Ssam
6547105197Ssam	if (m->m_next)
6548105197Ssam		m_freem(m->m_next);
6549105197Ssam	m->m_next = NULL;
6550105197Ssam	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6551105197Ssam	newmsg = mtod(m, struct sadb_msg *);
6552105197Ssam	newmsg->sadb_msg_errno = 0;
6553105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6554105197Ssam
6555105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6556105197Ssam}
6557105197Ssam
6558105197Ssam/*
6559105197Ssam * SADB_DUMP processing
6560105197Ssam * dump all entries including status of DEAD in SAD.
6561105197Ssam * receive
6562105197Ssam *   <base>
6563105197Ssam * from the ikmpd, and dump all secasvar leaves
6564105197Ssam * and send,
6565105197Ssam *   <base> .....
6566105197Ssam * to the ikmpd.
6567105197Ssam *
6568105197Ssam * m will always be freed.
6569105197Ssam */
6570105197Ssamstatic int
6571105197Ssamkey_dump(so, m, mhp)
6572105197Ssam	struct socket *so;
6573105197Ssam	struct mbuf *m;
6574105197Ssam	const struct sadb_msghdr *mhp;
6575105197Ssam{
6576183550Szec	INIT_VNET_IPSEC(curvnet);
6577105197Ssam	struct secashead *sah;
6578105197Ssam	struct secasvar *sav;
6579105197Ssam	u_int16_t proto;
6580105197Ssam	u_int stateidx;
6581105197Ssam	u_int8_t satype;
6582105197Ssam	u_int8_t state;
6583105197Ssam	int cnt;
6584105197Ssam	struct sadb_msg *newmsg;
6585105197Ssam	struct mbuf *n;
6586105197Ssam
6587120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6588120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6589120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6590120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6591105197Ssam
6592105197Ssam	/* map satype to proto */
6593105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6594120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6595120585Ssam			__func__));
6596105197Ssam		return key_senderror(so, m, EINVAL);
6597105197Ssam	}
6598105197Ssam
6599105197Ssam	/* count sav entries to be sent to the userland. */
6600105197Ssam	cnt = 0;
6601120585Ssam	SAHTREE_LOCK();
6602181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
6603105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6604105197Ssam		 && proto != sah->saidx.proto)
6605105197Ssam			continue;
6606105197Ssam
6607105197Ssam		for (stateidx = 0;
6608185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
6609105197Ssam		     stateidx++) {
6610185348Szec			state = saorder_state_any[stateidx];
6611105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6612105197Ssam				cnt++;
6613105197Ssam			}
6614105197Ssam		}
6615105197Ssam	}
6616105197Ssam
6617119643Ssam	if (cnt == 0) {
6618120585Ssam		SAHTREE_UNLOCK();
6619105197Ssam		return key_senderror(so, m, ENOENT);
6620119643Ssam	}
6621105197Ssam
6622105197Ssam	/* send this to the userland, one at a time. */
6623105197Ssam	newmsg = NULL;
6624181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
6625105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6626105197Ssam		 && proto != sah->saidx.proto)
6627105197Ssam			continue;
6628105197Ssam
6629105197Ssam		/* map proto to satype */
6630105197Ssam		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6631120585Ssam			SAHTREE_UNLOCK();
6632120585Ssam			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
6633120585Ssam				"SAD.\n", __func__));
6634105197Ssam			return key_senderror(so, m, EINVAL);
6635105197Ssam		}
6636105197Ssam
6637105197Ssam		for (stateidx = 0;
6638185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
6639105197Ssam		     stateidx++) {
6640185348Szec			state = saorder_state_any[stateidx];
6641105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6642105197Ssam				n = key_setdumpsa(sav, SADB_DUMP, satype,
6643105197Ssam				    --cnt, mhp->msg->sadb_msg_pid);
6644119643Ssam				if (!n) {
6645120585Ssam					SAHTREE_UNLOCK();
6646105197Ssam					return key_senderror(so, m, ENOBUFS);
6647119643Ssam				}
6648105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6649105197Ssam			}
6650105197Ssam		}
6651105197Ssam	}
6652120585Ssam	SAHTREE_UNLOCK();
6653105197Ssam
6654105197Ssam	m_freem(m);
6655105197Ssam	return 0;
6656105197Ssam}
6657105197Ssam
6658105197Ssam/*
6659105197Ssam * SADB_X_PROMISC processing
6660105197Ssam *
6661105197Ssam * m will always be freed.
6662105197Ssam */
6663105197Ssamstatic int
6664105197Ssamkey_promisc(so, m, mhp)
6665105197Ssam	struct socket *so;
6666105197Ssam	struct mbuf *m;
6667105197Ssam	const struct sadb_msghdr *mhp;
6668105197Ssam{
6669105197Ssam	int olen;
6670105197Ssam
6671120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6672120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6673120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6674120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6675105197Ssam
6676105197Ssam	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6677105197Ssam
6678105197Ssam	if (olen < sizeof(struct sadb_msg)) {
6679105197Ssam#if 1
6680105197Ssam		return key_senderror(so, m, EINVAL);
6681105197Ssam#else
6682105197Ssam		m_freem(m);
6683105197Ssam		return 0;
6684105197Ssam#endif
6685105197Ssam	} else if (olen == sizeof(struct sadb_msg)) {
6686105197Ssam		/* enable/disable promisc mode */
6687105197Ssam		struct keycb *kp;
6688105197Ssam
6689105197Ssam		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6690105197Ssam			return key_senderror(so, m, EINVAL);
6691105197Ssam		mhp->msg->sadb_msg_errno = 0;
6692105197Ssam		switch (mhp->msg->sadb_msg_satype) {
6693105197Ssam		case 0:
6694105197Ssam		case 1:
6695105197Ssam			kp->kp_promisc = mhp->msg->sadb_msg_satype;
6696105197Ssam			break;
6697105197Ssam		default:
6698105197Ssam			return key_senderror(so, m, EINVAL);
6699105197Ssam		}
6700105197Ssam
6701105197Ssam		/* send the original message back to everyone */
6702105197Ssam		mhp->msg->sadb_msg_errno = 0;
6703105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6704105197Ssam	} else {
6705105197Ssam		/* send packet as is */
6706105197Ssam
6707105197Ssam		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6708105197Ssam
6709105197Ssam		/* TODO: if sadb_msg_seq is specified, send to specific pid */
6710105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6711105197Ssam	}
6712105197Ssam}
6713105197Ssam
6714105197Ssamstatic int (*key_typesw[]) __P((struct socket *, struct mbuf *,
6715105197Ssam		const struct sadb_msghdr *)) = {
6716105197Ssam	NULL,		/* SADB_RESERVED */
6717105197Ssam	key_getspi,	/* SADB_GETSPI */
6718105197Ssam	key_update,	/* SADB_UPDATE */
6719105197Ssam	key_add,	/* SADB_ADD */
6720105197Ssam	key_delete,	/* SADB_DELETE */
6721105197Ssam	key_get,	/* SADB_GET */
6722105197Ssam	key_acquire2,	/* SADB_ACQUIRE */
6723105197Ssam	key_register,	/* SADB_REGISTER */
6724105197Ssam	NULL,		/* SADB_EXPIRE */
6725105197Ssam	key_flush,	/* SADB_FLUSH */
6726105197Ssam	key_dump,	/* SADB_DUMP */
6727105197Ssam	key_promisc,	/* SADB_X_PROMISC */
6728105197Ssam	NULL,		/* SADB_X_PCHANGE */
6729105197Ssam	key_spdadd,	/* SADB_X_SPDUPDATE */
6730105197Ssam	key_spdadd,	/* SADB_X_SPDADD */
6731105197Ssam	key_spddelete,	/* SADB_X_SPDDELETE */
6732105197Ssam	key_spdget,	/* SADB_X_SPDGET */
6733105197Ssam	NULL,		/* SADB_X_SPDACQUIRE */
6734105197Ssam	key_spddump,	/* SADB_X_SPDDUMP */
6735105197Ssam	key_spdflush,	/* SADB_X_SPDFLUSH */
6736105197Ssam	key_spdadd,	/* SADB_X_SPDSETIDX */
6737105197Ssam	NULL,		/* SADB_X_SPDEXPIRE */
6738105197Ssam	key_spddelete2,	/* SADB_X_SPDDELETE2 */
6739105197Ssam};
6740105197Ssam
6741105197Ssam/*
6742105197Ssam * parse sadb_msg buffer to process PFKEYv2,
6743105197Ssam * and create a data to response if needed.
6744105197Ssam * I think to be dealed with mbuf directly.
6745105197Ssam * IN:
6746105197Ssam *     msgp  : pointer to pointer to a received buffer pulluped.
6747105197Ssam *             This is rewrited to response.
6748105197Ssam *     so    : pointer to socket.
6749105197Ssam * OUT:
6750105197Ssam *    length for buffer to send to user process.
6751105197Ssam */
6752105197Ssamint
6753105197Ssamkey_parse(m, so)
6754105197Ssam	struct mbuf *m;
6755105197Ssam	struct socket *so;
6756105197Ssam{
6757183550Szec	INIT_VNET_IPSEC(curvnet);
6758105197Ssam	struct sadb_msg *msg;
6759105197Ssam	struct sadb_msghdr mh;
6760105197Ssam	u_int orglen;
6761105197Ssam	int error;
6762105197Ssam	int target;
6763105197Ssam
6764120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6765120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6766105197Ssam
6767105197Ssam#if 0	/*kdebug_sadb assumes msg in linear buffer*/
6768105197Ssam	KEYDEBUG(KEYDEBUG_KEY_DUMP,
6769120585Ssam		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
6770105197Ssam		kdebug_sadb(msg));
6771105197Ssam#endif
6772105197Ssam
6773105197Ssam	if (m->m_len < sizeof(struct sadb_msg)) {
6774105197Ssam		m = m_pullup(m, sizeof(struct sadb_msg));
6775105197Ssam		if (!m)
6776105197Ssam			return ENOBUFS;
6777105197Ssam	}
6778105197Ssam	msg = mtod(m, struct sadb_msg *);
6779105197Ssam	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6780105197Ssam	target = KEY_SENDUP_ONE;
6781105197Ssam
6782105197Ssam	if ((m->m_flags & M_PKTHDR) == 0 ||
6783105197Ssam	    m->m_pkthdr.len != m->m_pkthdr.len) {
6784120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
6785181803Sbz		V_pfkeystat.out_invlen++;
6786105197Ssam		error = EINVAL;
6787105197Ssam		goto senderror;
6788105197Ssam	}
6789105197Ssam
6790105197Ssam	if (msg->sadb_msg_version != PF_KEY_V2) {
6791120585Ssam		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
6792120585Ssam		    __func__, msg->sadb_msg_version));
6793181803Sbz		V_pfkeystat.out_invver++;
6794105197Ssam		error = EINVAL;
6795105197Ssam		goto senderror;
6796105197Ssam	}
6797105197Ssam
6798105197Ssam	if (msg->sadb_msg_type > SADB_MAX) {
6799120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6800120585Ssam		    __func__, msg->sadb_msg_type));
6801181803Sbz		V_pfkeystat.out_invmsgtype++;
6802105197Ssam		error = EINVAL;
6803105197Ssam		goto senderror;
6804105197Ssam	}
6805105197Ssam
6806105197Ssam	/* for old-fashioned code - should be nuked */
6807105197Ssam	if (m->m_pkthdr.len > MCLBYTES) {
6808105197Ssam		m_freem(m);
6809105197Ssam		return ENOBUFS;
6810105197Ssam	}
6811105197Ssam	if (m->m_next) {
6812105197Ssam		struct mbuf *n;
6813105197Ssam
6814111119Simp		MGETHDR(n, M_DONTWAIT, MT_DATA);
6815105197Ssam		if (n && m->m_pkthdr.len > MHLEN) {
6816111119Simp			MCLGET(n, M_DONTWAIT);
6817105197Ssam			if ((n->m_flags & M_EXT) == 0) {
6818105197Ssam				m_free(n);
6819105197Ssam				n = NULL;
6820105197Ssam			}
6821105197Ssam		}
6822105197Ssam		if (!n) {
6823105197Ssam			m_freem(m);
6824105197Ssam			return ENOBUFS;
6825105197Ssam		}
6826105197Ssam		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6827105197Ssam		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6828105197Ssam		n->m_next = NULL;
6829105197Ssam		m_freem(m);
6830105197Ssam		m = n;
6831105197Ssam	}
6832105197Ssam
6833105197Ssam	/* align the mbuf chain so that extensions are in contiguous region. */
6834105197Ssam	error = key_align(m, &mh);
6835105197Ssam	if (error)
6836105197Ssam		return error;
6837105197Ssam
6838105197Ssam	msg = mh.msg;
6839105197Ssam
6840105197Ssam	/* check SA type */
6841105197Ssam	switch (msg->sadb_msg_satype) {
6842105197Ssam	case SADB_SATYPE_UNSPEC:
6843105197Ssam		switch (msg->sadb_msg_type) {
6844105197Ssam		case SADB_GETSPI:
6845105197Ssam		case SADB_UPDATE:
6846105197Ssam		case SADB_ADD:
6847105197Ssam		case SADB_DELETE:
6848105197Ssam		case SADB_GET:
6849105197Ssam		case SADB_ACQUIRE:
6850105197Ssam		case SADB_EXPIRE:
6851120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify satype "
6852120585Ssam			    "when msg type=%u.\n", __func__,
6853120585Ssam			    msg->sadb_msg_type));
6854181803Sbz			V_pfkeystat.out_invsatype++;
6855105197Ssam			error = EINVAL;
6856105197Ssam			goto senderror;
6857105197Ssam		}
6858105197Ssam		break;
6859105197Ssam	case SADB_SATYPE_AH:
6860105197Ssam	case SADB_SATYPE_ESP:
6861105197Ssam	case SADB_X_SATYPE_IPCOMP:
6862125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
6863105197Ssam		switch (msg->sadb_msg_type) {
6864105197Ssam		case SADB_X_SPDADD:
6865105197Ssam		case SADB_X_SPDDELETE:
6866105197Ssam		case SADB_X_SPDGET:
6867105197Ssam		case SADB_X_SPDDUMP:
6868105197Ssam		case SADB_X_SPDFLUSH:
6869105197Ssam		case SADB_X_SPDSETIDX:
6870105197Ssam		case SADB_X_SPDUPDATE:
6871105197Ssam		case SADB_X_SPDDELETE2:
6872120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
6873120585Ssam				__func__, msg->sadb_msg_type));
6874181803Sbz			V_pfkeystat.out_invsatype++;
6875105197Ssam			error = EINVAL;
6876105197Ssam			goto senderror;
6877105197Ssam		}
6878105197Ssam		break;
6879105197Ssam	case SADB_SATYPE_RSVP:
6880105197Ssam	case SADB_SATYPE_OSPFV2:
6881105197Ssam	case SADB_SATYPE_RIPV2:
6882105197Ssam	case SADB_SATYPE_MIP:
6883120585Ssam		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
6884120585Ssam			__func__, msg->sadb_msg_satype));
6885181803Sbz		V_pfkeystat.out_invsatype++;
6886105197Ssam		error = EOPNOTSUPP;
6887105197Ssam		goto senderror;
6888105197Ssam	case 1:	/* XXX: What does it do? */
6889105197Ssam		if (msg->sadb_msg_type == SADB_X_PROMISC)
6890105197Ssam			break;
6891105197Ssam		/*FALLTHROUGH*/
6892105197Ssam	default:
6893120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6894120585Ssam			__func__, msg->sadb_msg_satype));
6895181803Sbz		V_pfkeystat.out_invsatype++;
6896105197Ssam		error = EINVAL;
6897105197Ssam		goto senderror;
6898105197Ssam	}
6899105197Ssam
6900105197Ssam	/* check field of upper layer protocol and address family */
6901105197Ssam	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6902105197Ssam	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6903105197Ssam		struct sadb_address *src0, *dst0;
6904105197Ssam		u_int plen;
6905105197Ssam
6906105197Ssam		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6907105197Ssam		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6908105197Ssam
6909105197Ssam		/* check upper layer protocol */
6910105197Ssam		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6911120585Ssam			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
6912120585Ssam				"mismatched.\n", __func__));
6913181803Sbz			V_pfkeystat.out_invaddr++;
6914105197Ssam			error = EINVAL;
6915105197Ssam			goto senderror;
6916105197Ssam		}
6917105197Ssam
6918105197Ssam		/* check family */
6919105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6920105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
6921120585Ssam			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
6922120585Ssam				__func__));
6923181803Sbz			V_pfkeystat.out_invaddr++;
6924105197Ssam			error = EINVAL;
6925105197Ssam			goto senderror;
6926105197Ssam		}
6927105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6928105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
6929120585Ssam			ipseclog((LOG_DEBUG, "%s: address struct size "
6930120585Ssam				"mismatched.\n", __func__));
6931181803Sbz			V_pfkeystat.out_invaddr++;
6932105197Ssam			error = EINVAL;
6933105197Ssam			goto senderror;
6934105197Ssam		}
6935105197Ssam
6936105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6937105197Ssam		case AF_INET:
6938105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6939105197Ssam			    sizeof(struct sockaddr_in)) {
6940181803Sbz				V_pfkeystat.out_invaddr++;
6941105197Ssam				error = EINVAL;
6942105197Ssam				goto senderror;
6943105197Ssam			}
6944105197Ssam			break;
6945105197Ssam		case AF_INET6:
6946105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6947105197Ssam			    sizeof(struct sockaddr_in6)) {
6948181803Sbz				V_pfkeystat.out_invaddr++;
6949105197Ssam				error = EINVAL;
6950105197Ssam				goto senderror;
6951105197Ssam			}
6952105197Ssam			break;
6953105197Ssam		default:
6954120585Ssam			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
6955120585Ssam				__func__));
6956181803Sbz			V_pfkeystat.out_invaddr++;
6957105197Ssam			error = EAFNOSUPPORT;
6958105197Ssam			goto senderror;
6959105197Ssam		}
6960105197Ssam
6961105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6962105197Ssam		case AF_INET:
6963105197Ssam			plen = sizeof(struct in_addr) << 3;
6964105197Ssam			break;
6965105197Ssam		case AF_INET6:
6966105197Ssam			plen = sizeof(struct in6_addr) << 3;
6967105197Ssam			break;
6968105197Ssam		default:
6969105197Ssam			plen = 0;	/*fool gcc*/
6970105197Ssam			break;
6971105197Ssam		}
6972105197Ssam
6973105197Ssam		/* check max prefix length */
6974105197Ssam		if (src0->sadb_address_prefixlen > plen ||
6975105197Ssam		    dst0->sadb_address_prefixlen > plen) {
6976120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
6977120585Ssam				__func__));
6978181803Sbz			V_pfkeystat.out_invaddr++;
6979105197Ssam			error = EINVAL;
6980105197Ssam			goto senderror;
6981105197Ssam		}
6982105197Ssam
6983105197Ssam		/*
6984105197Ssam		 * prefixlen == 0 is valid because there can be a case when
6985105197Ssam		 * all addresses are matched.
6986105197Ssam		 */
6987105197Ssam	}
6988105197Ssam
6989105197Ssam	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
6990105197Ssam	    key_typesw[msg->sadb_msg_type] == NULL) {
6991181803Sbz		V_pfkeystat.out_invmsgtype++;
6992105197Ssam		error = EINVAL;
6993105197Ssam		goto senderror;
6994105197Ssam	}
6995105197Ssam
6996105197Ssam	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6997105197Ssam
6998105197Ssamsenderror:
6999105197Ssam	msg->sadb_msg_errno = error;
7000105197Ssam	return key_sendup_mbuf(so, m, target);
7001105197Ssam}
7002105197Ssam
7003105197Ssamstatic int
7004105197Ssamkey_senderror(so, m, code)
7005105197Ssam	struct socket *so;
7006105197Ssam	struct mbuf *m;
7007105197Ssam	int code;
7008105197Ssam{
7009105197Ssam	struct sadb_msg *msg;
7010105197Ssam
7011120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7012120585Ssam		("mbuf too small, len %u", m->m_len));
7013105197Ssam
7014105197Ssam	msg = mtod(m, struct sadb_msg *);
7015105197Ssam	msg->sadb_msg_errno = code;
7016105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7017105197Ssam}
7018105197Ssam
7019105197Ssam/*
7020105197Ssam * set the pointer to each header into message buffer.
7021105197Ssam * m will be freed on error.
7022105197Ssam * XXX larger-than-MCLBYTES extension?
7023105197Ssam */
7024105197Ssamstatic int
7025105197Ssamkey_align(m, mhp)
7026105197Ssam	struct mbuf *m;
7027105197Ssam	struct sadb_msghdr *mhp;
7028105197Ssam{
7029183550Szec	INIT_VNET_IPSEC(curvnet);
7030105197Ssam	struct mbuf *n;
7031105197Ssam	struct sadb_ext *ext;
7032105197Ssam	size_t off, end;
7033105197Ssam	int extlen;
7034105197Ssam	int toff;
7035105197Ssam
7036120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7037120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7038120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7039120585Ssam		("mbuf too small, len %u", m->m_len));
7040105197Ssam
7041105197Ssam	/* initialize */
7042105197Ssam	bzero(mhp, sizeof(*mhp));
7043105197Ssam
7044105197Ssam	mhp->msg = mtod(m, struct sadb_msg *);
7045105197Ssam	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7046105197Ssam
7047105197Ssam	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7048105197Ssam	extlen = end;	/*just in case extlen is not updated*/
7049105197Ssam	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7050105197Ssam		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7051105197Ssam		if (!n) {
7052105197Ssam			/* m is already freed */
7053105197Ssam			return ENOBUFS;
7054105197Ssam		}
7055105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7056105197Ssam
7057105197Ssam		/* set pointer */
7058105197Ssam		switch (ext->sadb_ext_type) {
7059105197Ssam		case SADB_EXT_SA:
7060105197Ssam		case SADB_EXT_ADDRESS_SRC:
7061105197Ssam		case SADB_EXT_ADDRESS_DST:
7062105197Ssam		case SADB_EXT_ADDRESS_PROXY:
7063105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
7064105197Ssam		case SADB_EXT_LIFETIME_HARD:
7065105197Ssam		case SADB_EXT_LIFETIME_SOFT:
7066105197Ssam		case SADB_EXT_KEY_AUTH:
7067105197Ssam		case SADB_EXT_KEY_ENCRYPT:
7068105197Ssam		case SADB_EXT_IDENTITY_SRC:
7069105197Ssam		case SADB_EXT_IDENTITY_DST:
7070105197Ssam		case SADB_EXT_SENSITIVITY:
7071105197Ssam		case SADB_EXT_PROPOSAL:
7072105197Ssam		case SADB_EXT_SUPPORTED_AUTH:
7073105197Ssam		case SADB_EXT_SUPPORTED_ENCRYPT:
7074105197Ssam		case SADB_EXT_SPIRANGE:
7075105197Ssam		case SADB_X_EXT_POLICY:
7076105197Ssam		case SADB_X_EXT_SA2:
7077105197Ssam			/* duplicate check */
7078105197Ssam			/*
7079105197Ssam			 * XXX Are there duplication payloads of either
7080105197Ssam			 * KEY_AUTH or KEY_ENCRYPT ?
7081105197Ssam			 */
7082105197Ssam			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7083120585Ssam				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7084120585Ssam					"%u\n", __func__, ext->sadb_ext_type));
7085105197Ssam				m_freem(m);
7086181803Sbz				V_pfkeystat.out_dupext++;
7087105197Ssam				return EINVAL;
7088105197Ssam			}
7089105197Ssam			break;
7090105197Ssam		default:
7091120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7092120585Ssam				__func__, ext->sadb_ext_type));
7093105197Ssam			m_freem(m);
7094181803Sbz			V_pfkeystat.out_invexttype++;
7095105197Ssam			return EINVAL;
7096105197Ssam		}
7097105197Ssam
7098105197Ssam		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7099105197Ssam
7100105197Ssam		if (key_validate_ext(ext, extlen)) {
7101105197Ssam			m_freem(m);
7102181803Sbz			V_pfkeystat.out_invlen++;
7103105197Ssam			return EINVAL;
7104105197Ssam		}
7105105197Ssam
7106105197Ssam		n = m_pulldown(m, off, extlen, &toff);
7107105197Ssam		if (!n) {
7108105197Ssam			/* m is already freed */
7109105197Ssam			return ENOBUFS;
7110105197Ssam		}
7111105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7112105197Ssam
7113105197Ssam		mhp->ext[ext->sadb_ext_type] = ext;
7114105197Ssam		mhp->extoff[ext->sadb_ext_type] = off;
7115105197Ssam		mhp->extlen[ext->sadb_ext_type] = extlen;
7116105197Ssam	}
7117105197Ssam
7118105197Ssam	if (off != end) {
7119105197Ssam		m_freem(m);
7120181803Sbz		V_pfkeystat.out_invlen++;
7121105197Ssam		return EINVAL;
7122105197Ssam	}
7123105197Ssam
7124105197Ssam	return 0;
7125105197Ssam}
7126105197Ssam
7127105197Ssamstatic int
7128105197Ssamkey_validate_ext(ext, len)
7129105197Ssam	const struct sadb_ext *ext;
7130105197Ssam	int len;
7131105197Ssam{
7132105197Ssam	const struct sockaddr *sa;
7133105197Ssam	enum { NONE, ADDR } checktype = NONE;
7134105197Ssam	int baselen = 0;
7135105197Ssam	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7136105197Ssam
7137105197Ssam	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7138105197Ssam		return EINVAL;
7139105197Ssam
7140105197Ssam	/* if it does not match minimum/maximum length, bail */
7141105197Ssam	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7142105197Ssam	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7143105197Ssam		return EINVAL;
7144105197Ssam	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7145105197Ssam		return EINVAL;
7146105197Ssam	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7147105197Ssam		return EINVAL;
7148105197Ssam
7149105197Ssam	/* more checks based on sadb_ext_type XXX need more */
7150105197Ssam	switch (ext->sadb_ext_type) {
7151105197Ssam	case SADB_EXT_ADDRESS_SRC:
7152105197Ssam	case SADB_EXT_ADDRESS_DST:
7153105197Ssam	case SADB_EXT_ADDRESS_PROXY:
7154105197Ssam		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7155105197Ssam		checktype = ADDR;
7156105197Ssam		break;
7157105197Ssam	case SADB_EXT_IDENTITY_SRC:
7158105197Ssam	case SADB_EXT_IDENTITY_DST:
7159105197Ssam		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7160105197Ssam		    SADB_X_IDENTTYPE_ADDR) {
7161105197Ssam			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7162105197Ssam			checktype = ADDR;
7163105197Ssam		} else
7164105197Ssam			checktype = NONE;
7165105197Ssam		break;
7166105197Ssam	default:
7167105197Ssam		checktype = NONE;
7168105197Ssam		break;
7169105197Ssam	}
7170105197Ssam
7171105197Ssam	switch (checktype) {
7172105197Ssam	case NONE:
7173105197Ssam		break;
7174105197Ssam	case ADDR:
7175105197Ssam		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7176105197Ssam		if (len < baselen + sal)
7177105197Ssam			return EINVAL;
7178105197Ssam		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7179105197Ssam			return EINVAL;
7180105197Ssam		break;
7181105197Ssam	}
7182105197Ssam
7183105197Ssam	return 0;
7184105197Ssam}
7185105197Ssam
7186105197Ssamvoid
7187180086Sjuliankey_init(void)
7188105197Ssam{
7189183550Szec	INIT_VNET_IPSEC(curvnet);
7190105197Ssam	int i;
7191105197Ssam
7192185088Szec	V_key_debug_level = 0;
7193185088Szec	V_key_spi_trycnt = 1000;
7194185088Szec	V_key_spi_minval = 0x100;
7195185088Szec	V_key_spi_maxval = 0x0fffffff;	/* XXX */
7196185088Szec	V_policy_id = 0;
7197185088Szec	V_key_int_random = 60;		/*interval to initialize randseed,1(m)*/
7198185088Szec	V_key_larval_lifetime = 30;	/* interval to expire acquiring, 30(s)*/
7199185088Szec	V_key_blockacq_count = 10;	/* counter for blocking SADB_ACQUIRE.*/
7200185088Szec	V_key_blockacq_lifetime = 20;	/* lifetime for blocking SADB_ACQUIRE.*/
7201185088Szec	V_key_preferred_oldsa = 1;	/* preferred old sa rather than new sa*/
7202185088Szec
7203185088Szec	V_acq_seq = 0;
7204185088Szec
7205185088Szec	V_ipsec_esp_keymin = 256;
7206185088Szec	V_ipsec_esp_auth = 0;
7207185088Szec	V_ipsec_ah_keymin = 128;
7208185088Szec
7209120585Ssam	SPTREE_LOCK_INIT();
7210120585Ssam	REGTREE_LOCK_INIT();
7211120585Ssam	SAHTREE_LOCK_INIT();
7212120585Ssam	ACQ_LOCK_INIT();
7213120585Ssam	SPACQ_LOCK_INIT();
7214119643Ssam
7215119643Ssam	for (i = 0; i < IPSEC_DIR_MAX; i++)
7216181803Sbz		LIST_INIT(&V_sptree[i]);
7217105197Ssam
7218181803Sbz	LIST_INIT(&V_sahtree);
7219105197Ssam
7220119643Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7221181803Sbz		LIST_INIT(&V_regtree[i]);
7222105197Ssam
7223181803Sbz	LIST_INIT(&V_acqtree);
7224181803Sbz	LIST_INIT(&V_spacqtree);
7225105197Ssam
7226105197Ssam	/* system default */
7227181803Sbz	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7228181803Sbz	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7229105197Ssam
7230105197Ssam#ifndef IPSEC_DEBUG2
7231105197Ssam	timeout((void *)key_timehandler, (void *)0, hz);
7232105197Ssam#endif /*IPSEC_DEBUG2*/
7233105197Ssam
7234105197Ssam	/* initialize key statistics */
7235105197Ssam	keystat.getspi_count = 1;
7236105197Ssam
7237177173Sbz	printf("IPsec: Initialized Security Association Processing.\n");
7238105197Ssam
7239105197Ssam	return;
7240105197Ssam}
7241105197Ssam
7242105197Ssam/*
7243105197Ssam * XXX: maybe This function is called after INBOUND IPsec processing.
7244105197Ssam *
7245105197Ssam * Special check for tunnel-mode packets.
7246105197Ssam * We must make some checks for consistency between inner and outer IP header.
7247105197Ssam *
7248105197Ssam * xxx more checks to be provided
7249105197Ssam */
7250105197Ssamint
7251105197Ssamkey_checktunnelsanity(sav, family, src, dst)
7252105197Ssam	struct secasvar *sav;
7253105197Ssam	u_int family;
7254105197Ssam	caddr_t src;
7255105197Ssam	caddr_t dst;
7256105197Ssam{
7257120585Ssam	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7258105197Ssam
7259105197Ssam	/* XXX: check inner IP header */
7260105197Ssam
7261105197Ssam	return 1;
7262105197Ssam}
7263105197Ssam
7264105197Ssam/* record data transfer on SA, and update timestamps */
7265105197Ssamvoid
7266105197Ssamkey_sa_recordxfer(sav, m)
7267105197Ssam	struct secasvar *sav;
7268105197Ssam	struct mbuf *m;
7269105197Ssam{
7270120585Ssam	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7271120585Ssam	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7272105197Ssam	if (!sav->lft_c)
7273105197Ssam		return;
7274105197Ssam
7275105197Ssam	/*
7276105197Ssam	 * XXX Currently, there is a difference of bytes size
7277105197Ssam	 * between inbound and outbound processing.
7278105197Ssam	 */
7279157123Sgnn	sav->lft_c->bytes += m->m_pkthdr.len;
7280105197Ssam	/* to check bytes lifetime is done in key_timehandler(). */
7281105197Ssam
7282105197Ssam	/*
7283105197Ssam	 * We use the number of packets as the unit of
7284157123Sgnn	 * allocations.  We increment the variable
7285105197Ssam	 * whenever {esp,ah}_{in,out}put is called.
7286105197Ssam	 */
7287157123Sgnn	sav->lft_c->allocations++;
7288105197Ssam	/* XXX check for expires? */
7289105197Ssam
7290105197Ssam	/*
7291157123Sgnn	 * NOTE: We record CURRENT usetime by using wall clock,
7292105197Ssam	 * in seconds.  HARD and SOFT lifetime are measured by the time
7293157123Sgnn	 * difference (again in seconds) from usetime.
7294105197Ssam	 *
7295105197Ssam	 *	usetime
7296105197Ssam	 *	v     expire   expire
7297105197Ssam	 * -----+-----+--------+---> t
7298105197Ssam	 *	<--------------> HARD
7299105197Ssam	 *	<-----> SOFT
7300105197Ssam	 */
7301157123Sgnn	sav->lft_c->usetime = time_second;
7302105197Ssam	/* XXX check for expires? */
7303105197Ssam
7304105197Ssam	return;
7305105197Ssam}
7306105197Ssam
7307105197Ssam/* dumb version */
7308105197Ssamvoid
7309105197Ssamkey_sa_routechange(dst)
7310105197Ssam	struct sockaddr *dst;
7311105197Ssam{
7312183550Szec	INIT_VNET_IPSEC(curvnet);
7313105197Ssam	struct secashead *sah;
7314105197Ssam	struct route *ro;
7315105197Ssam
7316120585Ssam	SAHTREE_LOCK();
7317181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7318105197Ssam		ro = &sah->sa_route;
7319105197Ssam		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7320105197Ssam		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7321105197Ssam			RTFREE(ro->ro_rt);
7322105197Ssam			ro->ro_rt = (struct rtentry *)NULL;
7323105197Ssam		}
7324105197Ssam	}
7325120585Ssam	SAHTREE_UNLOCK();
7326105197Ssam}
7327105197Ssam
7328105197Ssamstatic void
7329105197Ssamkey_sa_chgstate(sav, state)
7330105197Ssam	struct secasvar *sav;
7331105197Ssam	u_int8_t state;
7332105197Ssam{
7333120585Ssam	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7334120585Ssam	SAHTREE_LOCK_ASSERT();
7335105197Ssam
7336119643Ssam	if (sav->state != state) {
7337119643Ssam		if (__LIST_CHAINED(sav))
7338119643Ssam			LIST_REMOVE(sav, chain);
7339119643Ssam		sav->state = state;
7340119643Ssam		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7341119643Ssam	}
7342105197Ssam}
7343105197Ssam
7344105197Ssamvoid
7345105197Ssamkey_sa_stir_iv(sav)
7346105197Ssam	struct secasvar *sav;
7347105197Ssam{
7348105197Ssam
7349120585Ssam	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7350105197Ssam	key_randomfill(sav->iv, sav->ivlen);
7351105197Ssam}
7352105197Ssam
7353105197Ssam/* XXX too much? */
7354105197Ssamstatic struct mbuf *
7355105197Ssamkey_alloc_mbuf(l)
7356105197Ssam	int l;
7357105197Ssam{
7358105197Ssam	struct mbuf *m = NULL, *n;
7359105197Ssam	int len, t;
7360105197Ssam
7361105197Ssam	len = l;
7362105197Ssam	while (len > 0) {
7363111119Simp		MGET(n, M_DONTWAIT, MT_DATA);
7364105197Ssam		if (n && len > MLEN)
7365111119Simp			MCLGET(n, M_DONTWAIT);
7366105197Ssam		if (!n) {
7367105197Ssam			m_freem(m);
7368105197Ssam			return NULL;
7369105197Ssam		}
7370105197Ssam
7371105197Ssam		n->m_next = NULL;
7372105197Ssam		n->m_len = 0;
7373105197Ssam		n->m_len = M_TRAILINGSPACE(n);
7374105197Ssam		/* use the bottom of mbuf, hoping we can prepend afterwards */
7375105197Ssam		if (n->m_len > len) {
7376105197Ssam			t = (n->m_len - len) & ~(sizeof(long) - 1);
7377105197Ssam			n->m_data += t;
7378105197Ssam			n->m_len = len;
7379105197Ssam		}
7380105197Ssam
7381105197Ssam		len -= n->m_len;
7382105197Ssam
7383105197Ssam		if (m)
7384105197Ssam			m_cat(m, n);
7385105197Ssam		else
7386105197Ssam			m = n;
7387105197Ssam	}
7388105197Ssam
7389105197Ssam	return m;
7390105197Ssam}
7391157123Sgnn
7392157123Sgnn/*
7393157123Sgnn * Take one of the kernel's security keys and convert it into a PF_KEY
7394157123Sgnn * structure within an mbuf, suitable for sending up to a waiting
7395157123Sgnn * application in user land.
7396157123Sgnn *
7397157123Sgnn * IN:
7398157123Sgnn *    src: A pointer to a kernel security key.
7399157123Sgnn *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
7400157123Sgnn * OUT:
7401157123Sgnn *    a valid mbuf or NULL indicating an error
7402157123Sgnn *
7403157123Sgnn */
7404157123Sgnn
7405157123Sgnnstatic struct mbuf *
7406157123Sgnnkey_setkey(struct seckey *src, u_int16_t exttype)
7407157123Sgnn{
7408157123Sgnn	struct mbuf *m;
7409157123Sgnn	struct sadb_key *p;
7410170799Sbz	int len;
7411157123Sgnn
7412157123Sgnn	if (src == NULL)
7413157123Sgnn		return NULL;
7414157123Sgnn
7415170799Sbz	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
7416157123Sgnn	m = key_alloc_mbuf(len);
7417157123Sgnn	if (m == NULL)
7418157123Sgnn		return NULL;
7419157123Sgnn	p = mtod(m, struct sadb_key *);
7420157123Sgnn	bzero(p, len);
7421157123Sgnn	p->sadb_key_len = PFKEY_UNIT64(len);
7422157123Sgnn	p->sadb_key_exttype = exttype;
7423157123Sgnn	p->sadb_key_bits = src->bits;
7424157123Sgnn	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
7425157123Sgnn
7426157123Sgnn	return m;
7427157123Sgnn}
7428157123Sgnn
7429157123Sgnn/*
7430157123Sgnn * Take one of the kernel's lifetime data structures and convert it
7431157123Sgnn * into a PF_KEY structure within an mbuf, suitable for sending up to
7432157123Sgnn * a waiting application in user land.
7433157123Sgnn *
7434157123Sgnn * IN:
7435157123Sgnn *    src: A pointer to a kernel lifetime structure.
7436157123Sgnn *    exttype: Which type of lifetime this is. Refer to the PF_KEY
7437157123Sgnn *             data structures for more information.
7438157123Sgnn * OUT:
7439157123Sgnn *    a valid mbuf or NULL indicating an error
7440157123Sgnn *
7441157123Sgnn */
7442157123Sgnn
7443157123Sgnnstatic struct mbuf *
7444157123Sgnnkey_setlifetime(struct seclifetime *src, u_int16_t exttype)
7445157123Sgnn{
7446157123Sgnn	struct mbuf *m = NULL;
7447157123Sgnn	struct sadb_lifetime *p;
7448157123Sgnn	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
7449157123Sgnn
7450157123Sgnn	if (src == NULL)
7451157123Sgnn		return NULL;
7452157123Sgnn
7453157123Sgnn	m = key_alloc_mbuf(len);
7454157123Sgnn	if (m == NULL)
7455157123Sgnn		return m;
7456157123Sgnn	p = mtod(m, struct sadb_lifetime *);
7457157123Sgnn
7458157123Sgnn	bzero(p, len);
7459157123Sgnn	p->sadb_lifetime_len = PFKEY_UNIT64(len);
7460157123Sgnn	p->sadb_lifetime_exttype = exttype;
7461157123Sgnn	p->sadb_lifetime_allocations = src->allocations;
7462157123Sgnn	p->sadb_lifetime_bytes = src->bytes;
7463157123Sgnn	p->sadb_lifetime_addtime = src->addtime;
7464157123Sgnn	p->sadb_lifetime_usetime = src->usetime;
7465157123Sgnn
7466157123Sgnn	return m;
7467157123Sgnn
7468157123Sgnn}
7469