key.c revision 207651
1105197Ssam/*	$FreeBSD: head/sys/netipsec/key.c 207651 2010-05-05 08:55:26Z vanhu $	*/
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>
59105197Ssam
60105197Ssam#include <net/if.h>
61105197Ssam#include <net/route.h>
62105197Ssam#include <net/raw_cb.h>
63195699Srwatson#include <net/vnet.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>
100105197Ssam
101105197Ssam#define FULLMASK	0xff
102105197Ssam#define	_BITS(bytes)	((bytes) << 3)
103105197Ssam
104105197Ssam/*
105105197Ssam * Note on SA reference counting:
106105197Ssam * - SAs that are not in DEAD state will have (total external reference + 1)
107105197Ssam *   following value in reference count field.  they cannot be freed and are
108105197Ssam *   referenced from SA header.
109105197Ssam * - SAs that are in DEAD state will have (total external reference)
110105197Ssam *   in reference count field.  they are ready to be freed.  reference from
111105197Ssam *   SA header will be removed in key_delsav(), when the reference count
112105197Ssam *   field hits 0 (= no external reference other than from SA header.
113105197Ssam */
114105197Ssam
115195699SrwatsonVNET_DEFINE(u_int32_t, key_debug_level) = 0;
116195699Srwatsonstatic VNET_DEFINE(u_int, key_spi_trycnt) = 1000;
117195699Srwatsonstatic VNET_DEFINE(u_int32_t, key_spi_minval) = 0x100;
118195699Srwatsonstatic VNET_DEFINE(u_int32_t, key_spi_maxval) = 0x0fffffff;	/* XXX */
119195699Srwatsonstatic VNET_DEFINE(u_int32_t, policy_id) = 0;
120195699Srwatson/*interval to initialize randseed,1(m)*/
121195699Srwatsonstatic VNET_DEFINE(u_int, key_int_random) = 60;
122195699Srwatson/* interval to expire acquiring, 30(s)*/
123195699Srwatsonstatic VNET_DEFINE(u_int, key_larval_lifetime) = 30;
124195699Srwatson/* counter for blocking SADB_ACQUIRE.*/
125195699Srwatsonstatic VNET_DEFINE(int, key_blockacq_count) = 10;
126195699Srwatson/* lifetime for blocking SADB_ACQUIRE.*/
127195699Srwatsonstatic VNET_DEFINE(int, key_blockacq_lifetime) = 20;
128195699Srwatson/* preferred old sa rather than new sa.*/
129195699Srwatsonstatic VNET_DEFINE(int, key_preferred_oldsa) = 1;
130207369Sbz#define	V_key_spi_trycnt	VNET(key_spi_trycnt)
131207369Sbz#define	V_key_spi_minval	VNET(key_spi_minval)
132207369Sbz#define	V_key_spi_maxval	VNET(key_spi_maxval)
133207369Sbz#define	V_policy_id		VNET(policy_id)
134207369Sbz#define	V_key_int_random	VNET(key_int_random)
135207369Sbz#define	V_key_larval_lifetime	VNET(key_larval_lifetime)
136207369Sbz#define	V_key_blockacq_count	VNET(key_blockacq_count)
137207369Sbz#define	V_key_blockacq_lifetime	VNET(key_blockacq_lifetime)
138195727Srwatson#define	V_key_preferred_oldsa	VNET(key_preferred_oldsa)
139105197Ssam
140195699Srwatsonstatic VNET_DEFINE(u_int32_t, acq_seq) = 0;
141195727Srwatson#define	V_acq_seq		VNET(acq_seq)
142105197Ssam
143195699Srwatson								/* SPD */
144195699Srwatsonstatic VNET_DEFINE(LIST_HEAD(_sptree, secpolicy), sptree[IPSEC_DIR_MAX]);
145195727Srwatson#define	V_sptree		VNET(sptree)
146119643Ssamstatic struct mtx sptree_lock;
147120585Ssam#define	SPTREE_LOCK_INIT() \
148120585Ssam	mtx_init(&sptree_lock, "sptree", \
149120585Ssam		"fast ipsec security policy database", MTX_DEF)
150120585Ssam#define	SPTREE_LOCK_DESTROY()	mtx_destroy(&sptree_lock)
151120585Ssam#define	SPTREE_LOCK()		mtx_lock(&sptree_lock)
152120585Ssam#define	SPTREE_UNLOCK()	mtx_unlock(&sptree_lock)
153120585Ssam#define	SPTREE_LOCK_ASSERT()	mtx_assert(&sptree_lock, MA_OWNED)
154120585Ssam
155195699Srwatsonstatic VNET_DEFINE(LIST_HEAD(_sahtree, secashead), sahtree);	/* SAD */
156195727Srwatson#define	V_sahtree		VNET(sahtree)
157119643Ssamstatic struct mtx sahtree_lock;
158120585Ssam#define	SAHTREE_LOCK_INIT() \
159120585Ssam	mtx_init(&sahtree_lock, "sahtree", \
160120585Ssam		"fast ipsec security association database", MTX_DEF)
161120585Ssam#define	SAHTREE_LOCK_DESTROY()	mtx_destroy(&sahtree_lock)
162120585Ssam#define	SAHTREE_LOCK()		mtx_lock(&sahtree_lock)
163120585Ssam#define	SAHTREE_UNLOCK()	mtx_unlock(&sahtree_lock)
164120585Ssam#define	SAHTREE_LOCK_ASSERT()	mtx_assert(&sahtree_lock, MA_OWNED)
165120585Ssam
166119643Ssam							/* registed list */
167195699Srwatsonstatic VNET_DEFINE(LIST_HEAD(_regtree, secreg), regtree[SADB_SATYPE_MAX + 1]);
168195727Srwatson#define	V_regtree		VNET(regtree)
169119643Ssamstatic struct mtx regtree_lock;
170120585Ssam#define	REGTREE_LOCK_INIT() \
171120585Ssam	mtx_init(&regtree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
172120585Ssam#define	REGTREE_LOCK_DESTROY()	mtx_destroy(&regtree_lock)
173120585Ssam#define	REGTREE_LOCK()		mtx_lock(&regtree_lock)
174120585Ssam#define	REGTREE_UNLOCK()	mtx_unlock(&regtree_lock)
175120585Ssam#define	REGTREE_LOCK_ASSERT()	mtx_assert(&regtree_lock, MA_OWNED)
176120585Ssam
177195699Srwatsonstatic VNET_DEFINE(LIST_HEAD(_acqtree, secacq), acqtree); /* acquiring list */
178195727Srwatson#define	V_acqtree		VNET(acqtree)
179119643Ssamstatic struct mtx acq_lock;
180120585Ssam#define	ACQ_LOCK_INIT() \
181120585Ssam	mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
182120585Ssam#define	ACQ_LOCK_DESTROY()	mtx_destroy(&acq_lock)
183120585Ssam#define	ACQ_LOCK()		mtx_lock(&acq_lock)
184120585Ssam#define	ACQ_UNLOCK()		mtx_unlock(&acq_lock)
185120585Ssam#define	ACQ_LOCK_ASSERT()	mtx_assert(&acq_lock, MA_OWNED)
186120585Ssam
187195699Srwatson							/* SP acquiring list */
188195699Srwatsonstatic VNET_DEFINE(LIST_HEAD(_spacqtree, secspacq), spacqtree);
189195727Srwatson#define	V_spacqtree		VNET(spacqtree)
190119643Ssamstatic struct mtx spacq_lock;
191120585Ssam#define	SPACQ_LOCK_INIT() \
192120585Ssam	mtx_init(&spacq_lock, "spacqtree", \
193120585Ssam		"fast ipsec security policy acquire list", MTX_DEF)
194120585Ssam#define	SPACQ_LOCK_DESTROY()	mtx_destroy(&spacq_lock)
195120585Ssam#define	SPACQ_LOCK()		mtx_lock(&spacq_lock)
196120585Ssam#define	SPACQ_UNLOCK()		mtx_unlock(&spacq_lock)
197120585Ssam#define	SPACQ_LOCK_ASSERT()	mtx_assert(&spacq_lock, MA_OWNED)
198105197Ssam
199105197Ssam/* search order for SAs */
200128856Ssamstatic const u_int saorder_state_valid_prefer_old[] = {
201105197Ssam	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
202105197Ssam};
203128856Ssamstatic const u_int saorder_state_valid_prefer_new[] = {
204128856Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
205128856Ssam};
206185348Szecstatic const u_int saorder_state_alive[] = {
207105197Ssam	/* except DEAD */
208105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
209105197Ssam};
210185348Szecstatic const u_int saorder_state_any[] = {
211105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
212105197Ssam	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
213105197Ssam};
214105197Ssam
215105197Ssamstatic const int minsize[] = {
216105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
217105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
218105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
219105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
220105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
221105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
222105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
223105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
224105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
225105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
226105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
227105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
228105197Ssam	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
229105197Ssam	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
230105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
231105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
232105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
233105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
234105197Ssam	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
235105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
236194062Svanhu	sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
237194062Svanhu	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
238194062Svanhu	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
239194062Svanhu	sizeof(struct sadb_address),	/* SADB_X_EXT_NAT_T_OAI */
240194062Svanhu	sizeof(struct sadb_address),	/* SADB_X_EXT_NAT_T_OAR */
241194062Svanhu	sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
242105197Ssam};
243105197Ssamstatic const int maxsize[] = {
244105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
245105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
246105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
247105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
248105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
249105197Ssam	0,				/* SADB_EXT_ADDRESS_SRC */
250105197Ssam	0,				/* SADB_EXT_ADDRESS_DST */
251105197Ssam	0,				/* SADB_EXT_ADDRESS_PROXY */
252105197Ssam	0,				/* SADB_EXT_KEY_AUTH */
253105197Ssam	0,				/* SADB_EXT_KEY_ENCRYPT */
254105197Ssam	0,				/* SADB_EXT_IDENTITY_SRC */
255105197Ssam	0,				/* SADB_EXT_IDENTITY_DST */
256105197Ssam	0,				/* SADB_EXT_SENSITIVITY */
257105197Ssam	0,				/* SADB_EXT_PROPOSAL */
258105197Ssam	0,				/* SADB_EXT_SUPPORTED_AUTH */
259105197Ssam	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
260105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
261105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
262105197Ssam	0,				/* SADB_X_EXT_POLICY */
263105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
264194062Svanhu	sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
265194062Svanhu	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
266194062Svanhu	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
267194062Svanhu	0,				/* SADB_X_EXT_NAT_T_OAI */
268194062Svanhu	0,				/* SADB_X_EXT_NAT_T_OAR */
269194062Svanhu	sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
270105197Ssam};
271105197Ssam
272195699Srwatsonstatic VNET_DEFINE(int, ipsec_esp_keymin) = 256;
273207369Sbzstatic VNET_DEFINE(int, ipsec_esp_auth) = 0;
274207369Sbzstatic VNET_DEFINE(int, ipsec_ah_keymin) = 128;
275207369Sbz
276195727Srwatson#define	V_ipsec_esp_keymin	VNET(ipsec_esp_keymin)
277195727Srwatson#define	V_ipsec_esp_auth	VNET(ipsec_esp_auth)
278195727Srwatson#define	V_ipsec_ah_keymin	VNET(ipsec_ah_keymin)
279195699Srwatson
280105197Ssam#ifdef SYSCTL_DECL
281105197SsamSYSCTL_DECL(_net_key);
282105197Ssam#endif
283105197Ssam
284195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,
285195699Srwatson	CTLFLAG_RW, &VNET_NAME(key_debug_level),	0,	"");
286105197Ssam
287105197Ssam/* max count of trial for the decision of spi value */
288195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
289195699Srwatson	CTLFLAG_RW, &VNET_NAME(key_spi_trycnt),	0,	"");
290105197Ssam
291105197Ssam/* minimum spi value to allocate automatically. */
292195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MIN_VALUE,
293195699Srwatson	spi_minval,	CTLFLAG_RW, &VNET_NAME(key_spi_minval),	0,	"");
294105197Ssam
295105197Ssam/* maximun spi value to allocate automatically. */
296195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MAX_VALUE,
297195699Srwatson	spi_maxval,	CTLFLAG_RW, &VNET_NAME(key_spi_maxval),	0,	"");
298105197Ssam
299105197Ssam/* interval to initialize randseed */
300195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_RANDOM_INT,
301195699Srwatson	int_random,	CTLFLAG_RW, &VNET_NAME(key_int_random),	0,	"");
302105197Ssam
303105197Ssam/* lifetime for larval SA */
304195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_LARVAL_LIFETIME,
305195699Srwatson	larval_lifetime, CTLFLAG_RW, &VNET_NAME(key_larval_lifetime),	0, "");
306105197Ssam
307105197Ssam/* counter for blocking to send SADB_ACQUIRE to IKEd */
308195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,
309195699Srwatson	blockacq_count,	CTLFLAG_RW, &VNET_NAME(key_blockacq_count),	0, "");
310105197Ssam
311105197Ssam/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
312195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,
313195699Srwatson	blockacq_lifetime, CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
314105197Ssam
315105197Ssam/* ESP auth */
316195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth,
317195699Srwatson	CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth),	0,	"");
318105197Ssam
319105197Ssam/* minimum ESP key length */
320195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_ESP_KEYMIN,
321195699Srwatson	esp_keymin, CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin),	0,	"");
322105197Ssam
323105197Ssam/* minimum AH key length */
324195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin,
325195699Srwatson	CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin),	0,	"");
326105197Ssam
327105197Ssam/* perfered old SA rather than new SA */
328195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_PREFERED_OLDSA,
329195699Srwatson	preferred_oldsa, CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa),	0, "");
330105197Ssam
331105197Ssam#define __LIST_CHAINED(elm) \
332105197Ssam	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
333105197Ssam#define LIST_INSERT_TAIL(head, elm, type, field) \
334105197Ssamdo {\
335105197Ssam	struct type *curelm = LIST_FIRST(head); \
336105197Ssam	if (curelm == NULL) {\
337105197Ssam		LIST_INSERT_HEAD(head, elm, field); \
338105197Ssam	} else { \
339105197Ssam		while (LIST_NEXT(curelm, field)) \
340105197Ssam			curelm = LIST_NEXT(curelm, field);\
341105197Ssam		LIST_INSERT_AFTER(curelm, elm, field);\
342105197Ssam	}\
343105197Ssam} while (0)
344105197Ssam
345105197Ssam#define KEY_CHKSASTATE(head, sav, name) \
346105197Ssamdo { \
347105197Ssam	if ((head) != (sav)) {						\
348105197Ssam		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
349105197Ssam			(name), (head), (sav)));			\
350105197Ssam		continue;						\
351105197Ssam	}								\
352105197Ssam} while (0)
353105197Ssam
354105197Ssam#define KEY_CHKSPDIR(head, sp, name) \
355105197Ssamdo { \
356105197Ssam	if ((head) != (sp)) {						\
357105197Ssam		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
358105197Ssam			"anyway continue.\n",				\
359105197Ssam			(name), (head), (sp)));				\
360105197Ssam	}								\
361105197Ssam} while (0)
362105197Ssam
363119643SsamMALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
364119643SsamMALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
365119643SsamMALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
366119643SsamMALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
367119643SsamMALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
368119643SsamMALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
369119643SsamMALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
370105197Ssam
371105197Ssam/*
372105197Ssam * set parameters into secpolicyindex buffer.
373105197Ssam * Must allocate secpolicyindex buffer passed to this function.
374105197Ssam */
375105197Ssam#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
376105197Ssamdo { \
377105197Ssam	bzero((idx), sizeof(struct secpolicyindex));                         \
378105197Ssam	(idx)->dir = (_dir);                                                 \
379105197Ssam	(idx)->prefs = (ps);                                                 \
380105197Ssam	(idx)->prefd = (pd);                                                 \
381105197Ssam	(idx)->ul_proto = (ulp);                                             \
382105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
383105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
384105197Ssam} while (0)
385105197Ssam
386105197Ssam/*
387105197Ssam * set parameters into secasindex buffer.
388105197Ssam * Must allocate secasindex buffer before calling this function.
389105197Ssam */
390105197Ssam#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
391105197Ssamdo { \
392105197Ssam	bzero((idx), sizeof(struct secasindex));                             \
393105197Ssam	(idx)->proto = (p);                                                  \
394105197Ssam	(idx)->mode = (m);                                                   \
395105197Ssam	(idx)->reqid = (r);                                                  \
396105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
397105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
398105197Ssam} while (0)
399105197Ssam
400105197Ssam/* key statistics */
401105197Ssamstruct _keystat {
402105197Ssam	u_long getspi_count; /* the avarage of count to try to get new SPI */
403105197Ssam} keystat;
404105197Ssam
405105197Ssamstruct sadb_msghdr {
406105197Ssam	struct sadb_msg *msg;
407105197Ssam	struct sadb_ext *ext[SADB_EXT_MAX + 1];
408105197Ssam	int extoff[SADB_EXT_MAX + 1];
409105197Ssam	int extlen[SADB_EXT_MAX + 1];
410105197Ssam};
411105197Ssam
412105197Ssamstatic struct secasvar *key_allocsa_policy __P((const struct secasindex *));
413105197Ssamstatic void key_freesp_so __P((struct secpolicy **));
414105197Ssamstatic struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
415105197Ssamstatic void key_delsp __P((struct secpolicy *));
416105197Ssamstatic struct secpolicy *key_getsp __P((struct secpolicyindex *));
417119643Ssamstatic void _key_delsp(struct secpolicy *sp);
418105197Ssamstatic struct secpolicy *key_getspbyid __P((u_int32_t));
419105197Ssamstatic u_int32_t key_newreqid __P((void));
420105197Ssamstatic struct mbuf *key_gather_mbuf __P((struct mbuf *,
421105197Ssam	const struct sadb_msghdr *, int, int, ...));
422105197Ssamstatic int key_spdadd __P((struct socket *, struct mbuf *,
423105197Ssam	const struct sadb_msghdr *));
424105197Ssamstatic u_int32_t key_getnewspid __P((void));
425105197Ssamstatic int key_spddelete __P((struct socket *, struct mbuf *,
426105197Ssam	const struct sadb_msghdr *));
427105197Ssamstatic int key_spddelete2 __P((struct socket *, struct mbuf *,
428105197Ssam	const struct sadb_msghdr *));
429105197Ssamstatic int key_spdget __P((struct socket *, struct mbuf *,
430105197Ssam	const struct sadb_msghdr *));
431105197Ssamstatic int key_spdflush __P((struct socket *, struct mbuf *,
432105197Ssam	const struct sadb_msghdr *));
433105197Ssamstatic int key_spddump __P((struct socket *, struct mbuf *,
434105197Ssam	const struct sadb_msghdr *));
435105197Ssamstatic struct mbuf *key_setdumpsp __P((struct secpolicy *,
436105197Ssam	u_int8_t, u_int32_t, u_int32_t));
437105197Ssamstatic u_int key_getspreqmsglen __P((struct secpolicy *));
438105197Ssamstatic int key_spdexpire __P((struct secpolicy *));
439105197Ssamstatic struct secashead *key_newsah __P((struct secasindex *));
440105197Ssamstatic void key_delsah __P((struct secashead *));
441105197Ssamstatic struct secasvar *key_newsav __P((struct mbuf *,
442105197Ssam	const struct sadb_msghdr *, struct secashead *, int *,
443105197Ssam	const char*, int));
444105197Ssam#define	KEY_NEWSAV(m, sadb, sah, e)				\
445105197Ssam	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
446105197Ssamstatic void key_delsav __P((struct secasvar *));
447105197Ssamstatic struct secashead *key_getsah __P((struct secasindex *));
448105197Ssamstatic struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
449105197Ssamstatic struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
450105197Ssamstatic int key_setsaval __P((struct secasvar *, struct mbuf *,
451105197Ssam	const struct sadb_msghdr *));
452105197Ssamstatic int key_mature __P((struct secasvar *));
453105197Ssamstatic struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
454105197Ssam	u_int8_t, u_int32_t, u_int32_t));
455105197Ssamstatic struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
456105197Ssam	u_int32_t, pid_t, u_int16_t));
457105197Ssamstatic struct mbuf *key_setsadbsa __P((struct secasvar *));
458105197Ssamstatic struct mbuf *key_setsadbaddr __P((u_int16_t,
459105197Ssam	const struct sockaddr *, u_int8_t, u_int16_t));
460194062Svanhu#ifdef IPSEC_NAT_T
461194062Svanhustatic struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
462194062Svanhustatic struct mbuf *key_setsadbxtype(u_int16_t);
463194062Svanhu#endif
464194062Svanhustatic void key_porttosaddr(struct sockaddr *, u_int16_t);
465194062Svanhu#define	KEY_PORTTOSADDR(saddr, port)				\
466194062Svanhu	key_porttosaddr((struct sockaddr *)(saddr), (port))
467105197Ssamstatic struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
468105197Ssamstatic struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
469105197Ssam	u_int32_t));
470157123Sgnnstatic struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
471157123Sgnn				     struct malloc_type *);
472157123Sgnnstatic struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
473157123Sgnn					    struct malloc_type *type);
474105197Ssam#ifdef INET6
475105197Ssamstatic int key_ismyaddr6 __P((struct sockaddr_in6 *));
476105197Ssam#endif
477105197Ssam
478105197Ssam/* flags for key_cmpsaidx() */
479105197Ssam#define CMP_HEAD	1	/* protocol, addresses. */
480105197Ssam#define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
481105197Ssam#define CMP_REQID	3	/* additionally HEAD, reaid. */
482105197Ssam#define CMP_EXACTLY	4	/* all elements. */
483105197Ssamstatic int key_cmpsaidx
484105197Ssam	__P((const struct secasindex *, const struct secasindex *, int));
485105197Ssam
486105197Ssamstatic int key_cmpspidx_exactly
487105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
488105197Ssamstatic int key_cmpspidx_withmask
489105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
490105197Ssamstatic int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
491105197Ssamstatic int key_bbcmp __P((const void *, const void *, u_int));
492105197Ssamstatic u_int16_t key_satype2proto __P((u_int8_t));
493105197Ssamstatic u_int8_t key_proto2satype __P((u_int16_t));
494105197Ssam
495105197Ssamstatic int key_getspi __P((struct socket *, struct mbuf *,
496105197Ssam	const struct sadb_msghdr *));
497105197Ssamstatic u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
498105197Ssam					struct secasindex *));
499105197Ssamstatic int key_update __P((struct socket *, struct mbuf *,
500105197Ssam	const struct sadb_msghdr *));
501105197Ssam#ifdef IPSEC_DOSEQCHECK
502105197Ssamstatic struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
503105197Ssam#endif
504105197Ssamstatic int key_add __P((struct socket *, struct mbuf *,
505105197Ssam	const struct sadb_msghdr *));
506105197Ssamstatic int key_setident __P((struct secashead *, struct mbuf *,
507105197Ssam	const struct sadb_msghdr *));
508105197Ssamstatic struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
509105197Ssam	const struct sadb_msghdr *));
510105197Ssamstatic int key_delete __P((struct socket *, struct mbuf *,
511105197Ssam	const struct sadb_msghdr *));
512105197Ssamstatic int key_get __P((struct socket *, struct mbuf *,
513105197Ssam	const struct sadb_msghdr *));
514105197Ssam
515105197Ssamstatic void key_getcomb_setlifetime __P((struct sadb_comb *));
516105197Ssamstatic struct mbuf *key_getcomb_esp __P((void));
517105197Ssamstatic struct mbuf *key_getcomb_ah __P((void));
518105197Ssamstatic struct mbuf *key_getcomb_ipcomp __P((void));
519105197Ssamstatic struct mbuf *key_getprop __P((const struct secasindex *));
520105197Ssam
521105197Ssamstatic int key_acquire __P((const struct secasindex *, struct secpolicy *));
522105197Ssamstatic struct secacq *key_newacq __P((const struct secasindex *));
523105197Ssamstatic struct secacq *key_getacq __P((const struct secasindex *));
524105197Ssamstatic struct secacq *key_getacqbyseq __P((u_int32_t));
525105197Ssamstatic struct secspacq *key_newspacq __P((struct secpolicyindex *));
526105197Ssamstatic struct secspacq *key_getspacq __P((struct secpolicyindex *));
527105197Ssamstatic int key_acquire2 __P((struct socket *, struct mbuf *,
528105197Ssam	const struct sadb_msghdr *));
529105197Ssamstatic int key_register __P((struct socket *, struct mbuf *,
530105197Ssam	const struct sadb_msghdr *));
531105197Ssamstatic int key_expire __P((struct secasvar *));
532105197Ssamstatic int key_flush __P((struct socket *, struct mbuf *,
533105197Ssam	const struct sadb_msghdr *));
534105197Ssamstatic int key_dump __P((struct socket *, struct mbuf *,
535105197Ssam	const struct sadb_msghdr *));
536105197Ssamstatic int key_promisc __P((struct socket *, struct mbuf *,
537105197Ssam	const struct sadb_msghdr *));
538105197Ssamstatic int key_senderror __P((struct socket *, struct mbuf *, int));
539105197Ssamstatic int key_validate_ext __P((const struct sadb_ext *, int));
540105197Ssamstatic int key_align __P((struct mbuf *, struct sadb_msghdr *));
541157123Sgnnstatic struct mbuf *key_setlifetime(struct seclifetime *src,
542157123Sgnn				     u_int16_t exttype);
543157123Sgnnstatic struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
544157123Sgnn
545105197Ssam#if 0
546105197Ssamstatic const char *key_getfqdn __P((void));
547105197Ssamstatic const char *key_getuserfqdn __P((void));
548105197Ssam#endif
549105197Ssamstatic void key_sa_chgstate __P((struct secasvar *, u_int8_t));
550105197Ssamstatic struct mbuf *key_alloc_mbuf __P((int));
551105197Ssam
552158767Spjdstatic __inline void
553158767Spjdsa_initref(struct secasvar *sav)
554158767Spjd{
555105197Ssam
556158767Spjd	refcount_init(&sav->refcnt, 1);
557158767Spjd}
558158767Spjdstatic __inline void
559158767Spjdsa_addref(struct secasvar *sav)
560158767Spjd{
561158767Spjd
562158767Spjd	refcount_acquire(&sav->refcnt);
563158767Spjd	IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
564158767Spjd}
565158767Spjdstatic __inline int
566158767Spjdsa_delref(struct secasvar *sav)
567158767Spjd{
568158767Spjd
569158767Spjd	IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
570158767Spjd	return (refcount_release(&sav->refcnt));
571158767Spjd}
572158767Spjd
573105197Ssam#define	SP_ADDREF(p) do {						\
574105197Ssam	(p)->refcnt++;							\
575120585Ssam	IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));		\
576105197Ssam} while (0)
577105197Ssam#define	SP_DELREF(p) do {						\
578120585Ssam	IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));		\
579105197Ssam	(p)->refcnt--;							\
580105197Ssam} while (0)
581135947Ssam
582105197Ssam
583105197Ssam/*
584135947Ssam * Update the refcnt while holding the SPTREE lock.
585135947Ssam */
586135947Ssamvoid
587135947Ssamkey_addref(struct secpolicy *sp)
588135947Ssam{
589135947Ssam	SPTREE_LOCK();
590135947Ssam	SP_ADDREF(sp);
591135947Ssam	SPTREE_UNLOCK();
592135947Ssam}
593135947Ssam
594135947Ssam/*
595105197Ssam * Return 0 when there are known to be no SP's for the specified
596105197Ssam * direction.  Otherwise return 1.  This is used by IPsec code
597105197Ssam * to optimize performance.
598105197Ssam */
599105197Ssamint
600105197Ssamkey_havesp(u_int dir)
601105197Ssam{
602183550Szec
603105197Ssam	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
604181803Sbz		LIST_FIRST(&V_sptree[dir]) != NULL : 1);
605105197Ssam}
606105197Ssam
607105197Ssam/* %%% IPsec policy management */
608105197Ssam/*
609105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
610105197Ssam * Must call key_freesp() later.
611105197Ssam * OUT:	NULL:	not found
612105197Ssam *	others:	found and return the pointer.
613105197Ssam */
614105197Ssamstruct secpolicy *
615105197Ssamkey_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
616105197Ssam{
617105197Ssam	struct secpolicy *sp;
618105197Ssam
619120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
620120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
621120585Ssam		("invalid direction %u", dir));
622105197Ssam
623105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
624120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
625105197Ssam
626105197Ssam	/* get a SP entry */
627105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
628105197Ssam		printf("*** objects\n");
629105197Ssam		kdebug_secpolicyindex(spidx));
630105197Ssam
631120585Ssam	SPTREE_LOCK();
632181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
633105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
634105197Ssam			printf("*** in SPD\n");
635105197Ssam			kdebug_secpolicyindex(&sp->spidx));
636105197Ssam
637105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
638105197Ssam			continue;
639105197Ssam		if (key_cmpspidx_withmask(&sp->spidx, spidx))
640105197Ssam			goto found;
641105197Ssam	}
642105197Ssam	sp = NULL;
643105197Ssamfound:
644105197Ssam	if (sp) {
645105197Ssam		/* sanity check */
646120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
647105197Ssam
648105197Ssam		/* found a SPD entry */
649105197Ssam		sp->lastused = time_second;
650105197Ssam		SP_ADDREF(sp);
651105197Ssam	}
652120585Ssam	SPTREE_UNLOCK();
653105197Ssam
654105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
655120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
656105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
657105197Ssam	return sp;
658105197Ssam}
659105197Ssam
660105197Ssam/*
661105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
662105197Ssam * Must call key_freesp() later.
663105197Ssam * OUT:	NULL:	not found
664105197Ssam *	others:	found and return the pointer.
665105197Ssam */
666105197Ssamstruct secpolicy *
667105197Ssamkey_allocsp2(u_int32_t spi,
668105197Ssam	     union sockaddr_union *dst,
669105197Ssam	     u_int8_t proto,
670105197Ssam	     u_int dir,
671105197Ssam	     const char* where, int tag)
672105197Ssam{
673105197Ssam	struct secpolicy *sp;
674105197Ssam
675120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst"));
676120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
677120585Ssam		("invalid direction %u", dir));
678105197Ssam
679105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
680120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
681105197Ssam
682105197Ssam	/* get a SP entry */
683105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
684105197Ssam		printf("*** objects\n");
685105197Ssam		printf("spi %u proto %u dir %u\n", spi, proto, dir);
686105197Ssam		kdebug_sockaddr(&dst->sa));
687105197Ssam
688120585Ssam	SPTREE_LOCK();
689181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
690105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
691105197Ssam			printf("*** in SPD\n");
692105197Ssam			kdebug_secpolicyindex(&sp->spidx));
693105197Ssam
694105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
695105197Ssam			continue;
696105197Ssam		/* compare simple values, then dst address */
697105197Ssam		if (sp->spidx.ul_proto != proto)
698105197Ssam			continue;
699105197Ssam		/* NB: spi's must exist and match */
700105197Ssam		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
701105197Ssam			continue;
702105197Ssam		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
703105197Ssam			goto found;
704105197Ssam	}
705105197Ssam	sp = NULL;
706105197Ssamfound:
707105197Ssam	if (sp) {
708105197Ssam		/* sanity check */
709120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
710105197Ssam
711105197Ssam		/* found a SPD entry */
712105197Ssam		sp->lastused = time_second;
713105197Ssam		SP_ADDREF(sp);
714105197Ssam	}
715120585Ssam	SPTREE_UNLOCK();
716105197Ssam
717105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
718120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
719105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
720105197Ssam	return sp;
721105197Ssam}
722105197Ssam
723191599Sbz#if 0
724105197Ssam/*
725105197Ssam * return a policy that matches this particular inbound packet.
726105197Ssam * XXX slow
727105197Ssam */
728105197Ssamstruct secpolicy *
729105197Ssamkey_gettunnel(const struct sockaddr *osrc,
730105197Ssam	      const struct sockaddr *odst,
731105197Ssam	      const struct sockaddr *isrc,
732105197Ssam	      const struct sockaddr *idst,
733105197Ssam	      const char* where, int tag)
734105197Ssam{
735105197Ssam	struct secpolicy *sp;
736105197Ssam	const int dir = IPSEC_DIR_INBOUND;
737105197Ssam	struct ipsecrequest *r1, *r2, *p;
738105197Ssam	struct secpolicyindex spidx;
739105197Ssam
740105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
741120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
742105197Ssam
743105197Ssam	if (isrc->sa_family != idst->sa_family) {
744120585Ssam		ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
745120585Ssam			__func__, isrc->sa_family, idst->sa_family));
746105197Ssam		sp = NULL;
747105197Ssam		goto done;
748105197Ssam	}
749105197Ssam
750120585Ssam	SPTREE_LOCK();
751181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
752105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
753105197Ssam			continue;
754105197Ssam
755105197Ssam		r1 = r2 = NULL;
756105197Ssam		for (p = sp->req; p; p = p->next) {
757105197Ssam			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
758105197Ssam				continue;
759105197Ssam
760105197Ssam			r1 = r2;
761105197Ssam			r2 = p;
762105197Ssam
763105197Ssam			if (!r1) {
764105197Ssam				/* here we look at address matches only */
765105197Ssam				spidx = sp->spidx;
766105197Ssam				if (isrc->sa_len > sizeof(spidx.src) ||
767105197Ssam				    idst->sa_len > sizeof(spidx.dst))
768105197Ssam					continue;
769105197Ssam				bcopy(isrc, &spidx.src, isrc->sa_len);
770105197Ssam				bcopy(idst, &spidx.dst, idst->sa_len);
771105197Ssam				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
772105197Ssam					continue;
773105197Ssam			} else {
774105197Ssam				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
775105197Ssam				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
776105197Ssam					continue;
777105197Ssam			}
778105197Ssam
779105197Ssam			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
780105197Ssam			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
781105197Ssam				continue;
782105197Ssam
783105197Ssam			goto found;
784105197Ssam		}
785105197Ssam	}
786105197Ssam	sp = NULL;
787105197Ssamfound:
788105197Ssam	if (sp) {
789105197Ssam		sp->lastused = time_second;
790105197Ssam		SP_ADDREF(sp);
791105197Ssam	}
792120585Ssam	SPTREE_UNLOCK();
793105197Ssamdone:
794105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
795120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
796105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
797105197Ssam	return sp;
798105197Ssam}
799191599Sbz#endif
800105197Ssam
801105197Ssam/*
802105197Ssam * allocating an SA entry for an *OUTBOUND* packet.
803105197Ssam * checking each request entries in SP, and acquire an SA if need.
804105197Ssam * OUT:	0: there are valid requests.
805105197Ssam *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
806105197Ssam */
807105197Ssamint
808105197Ssamkey_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
809105197Ssam{
810105197Ssam	u_int level;
811105197Ssam	int error;
812105197Ssam
813120585Ssam	IPSEC_ASSERT(isr != NULL, ("null isr"));
814120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
815120585Ssam	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
816105197Ssam		saidx->mode == IPSEC_MODE_TUNNEL,
817120585Ssam		("unexpected policy %u", saidx->mode));
818105197Ssam
819105197Ssam	/*
820105197Ssam	 * XXX guard against protocol callbacks from the crypto
821105197Ssam	 * thread as they reference ipsecrequest.sav which we
822105197Ssam	 * temporarily null out below.  Need to rethink how we
823105197Ssam	 * handle bundled SA's in the callback thread.
824105197Ssam	 */
825120585Ssam	IPSECREQUEST_LOCK_ASSERT(isr);
826119643Ssam
827119643Ssam	/* get current level */
828119643Ssam	level = ipsec_get_reqlevel(isr);
829105197Ssam#if 0
830105197Ssam	/*
831105197Ssam	 * We do allocate new SA only if the state of SA in the holder is
832105197Ssam	 * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
833105197Ssam	 */
834105197Ssam	if (isr->sav != NULL) {
835105197Ssam		if (isr->sav->sah == NULL)
836120585Ssam			panic("%s: sah is null.\n", __func__);
837105197Ssam		if (isr->sav == (struct secasvar *)LIST_FIRST(
838105197Ssam			    &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
839105197Ssam			KEY_FREESAV(&isr->sav);
840105197Ssam			isr->sav = NULL;
841105197Ssam		}
842105197Ssam	}
843105197Ssam#else
844105197Ssam	/*
845105197Ssam	 * we free any SA stashed in the IPsec request because a different
846105197Ssam	 * SA may be involved each time this request is checked, either
847105197Ssam	 * because new SAs are being configured, or this request is
848105197Ssam	 * associated with an unconnected datagram socket, or this request
849105197Ssam	 * is associated with a system default policy.
850105197Ssam	 *
851105197Ssam	 * The operation may have negative impact to performance.  We may
852105197Ssam	 * want to check cached SA carefully, rather than picking new SA
853105197Ssam	 * every time.
854105197Ssam	 */
855105197Ssam	if (isr->sav != NULL) {
856105197Ssam		KEY_FREESAV(&isr->sav);
857105197Ssam		isr->sav = NULL;
858105197Ssam	}
859105197Ssam#endif
860105197Ssam
861105197Ssam	/*
862105197Ssam	 * new SA allocation if no SA found.
863105197Ssam	 * key_allocsa_policy should allocate the oldest SA available.
864105197Ssam	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
865105197Ssam	 */
866105197Ssam	if (isr->sav == NULL)
867105197Ssam		isr->sav = key_allocsa_policy(saidx);
868105197Ssam
869105197Ssam	/* When there is SA. */
870105197Ssam	if (isr->sav != NULL) {
871105197Ssam		if (isr->sav->state != SADB_SASTATE_MATURE &&
872105197Ssam		    isr->sav->state != SADB_SASTATE_DYING)
873105197Ssam			return EINVAL;
874105197Ssam		return 0;
875105197Ssam	}
876105197Ssam
877105197Ssam	/* there is no SA */
878105197Ssam	error = key_acquire(saidx, isr->sp);
879105197Ssam	if (error != 0) {
880105197Ssam		/* XXX What should I do ? */
881120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
882120585Ssam			__func__, error));
883105197Ssam		return error;
884105197Ssam	}
885105197Ssam
886105197Ssam	if (level != IPSEC_LEVEL_REQUIRE) {
887105197Ssam		/* XXX sigh, the interface to this routine is botched */
888120585Ssam		IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
889105197Ssam		return 0;
890105197Ssam	} else {
891105197Ssam		return ENOENT;
892105197Ssam	}
893105197Ssam}
894105197Ssam
895105197Ssam/*
896105197Ssam * allocating a SA for policy entry from SAD.
897105197Ssam * NOTE: searching SAD of aliving state.
898105197Ssam * OUT:	NULL:	not found.
899105197Ssam *	others:	found and return the pointer.
900105197Ssam */
901105197Ssamstatic struct secasvar *
902105197Ssamkey_allocsa_policy(const struct secasindex *saidx)
903105197Ssam{
904128856Ssam#define	N(a)	_ARRAYLEN(a)
905105197Ssam	struct secashead *sah;
906105197Ssam	struct secasvar *sav;
907128856Ssam	u_int stateidx, arraysize;
908128856Ssam	const u_int *state_valid;
909105197Ssam
910196902Spjd	state_valid = NULL;	/* silence gcc */
911196902Spjd	arraysize = 0;		/* silence gcc */
912196896Spjd
913120585Ssam	SAHTREE_LOCK();
914181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
915105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
916105197Ssam			continue;
917119643Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
918181803Sbz			if (V_key_preferred_oldsa) {
919128856Ssam				state_valid = saorder_state_valid_prefer_old;
920128856Ssam				arraysize = N(saorder_state_valid_prefer_old);
921128856Ssam			} else {
922128856Ssam				state_valid = saorder_state_valid_prefer_new;
923128856Ssam				arraysize = N(saorder_state_valid_prefer_new);
924128856Ssam			}
925196883Spjd			break;
926119643Ssam		}
927105197Ssam	}
928120585Ssam	SAHTREE_UNLOCK();
929196883Spjd	if (sah == NULL)
930196883Spjd		return NULL;
931105197Ssam
932105197Ssam	/* search valid state */
933128856Ssam	for (stateidx = 0; stateidx < arraysize; stateidx++) {
934128856Ssam		sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
935105197Ssam		if (sav != NULL)
936105197Ssam			return sav;
937105197Ssam	}
938105197Ssam
939105197Ssam	return NULL;
940128856Ssam#undef N
941105197Ssam}
942105197Ssam
943105197Ssam/*
944105197Ssam * searching SAD with direction, protocol, mode and state.
945105197Ssam * called by key_allocsa_policy().
946105197Ssam * OUT:
947105197Ssam *	NULL	: not found
948105197Ssam *	others	: found, pointer to a SA.
949105197Ssam */
950105197Ssamstatic struct secasvar *
951105197Ssamkey_do_allocsa_policy(struct secashead *sah, u_int state)
952105197Ssam{
953105197Ssam	struct secasvar *sav, *nextsav, *candidate, *d;
954105197Ssam
955105197Ssam	/* initilize */
956105197Ssam	candidate = NULL;
957105197Ssam
958120585Ssam	SAHTREE_LOCK();
959105197Ssam	for (sav = LIST_FIRST(&sah->savtree[state]);
960105197Ssam	     sav != NULL;
961105197Ssam	     sav = nextsav) {
962105197Ssam
963105197Ssam		nextsav = LIST_NEXT(sav, chain);
964105197Ssam
965105197Ssam		/* sanity check */
966120585Ssam		KEY_CHKSASTATE(sav->state, state, __func__);
967105197Ssam
968105197Ssam		/* initialize */
969105197Ssam		if (candidate == NULL) {
970105197Ssam			candidate = sav;
971105197Ssam			continue;
972105197Ssam		}
973105197Ssam
974105197Ssam		/* Which SA is the better ? */
975105197Ssam
976120585Ssam		IPSEC_ASSERT(candidate->lft_c != NULL,
977120585Ssam			("null candidate lifetime"));
978120585Ssam		IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
979105197Ssam
980105197Ssam		/* What the best method is to compare ? */
981181803Sbz		if (V_key_preferred_oldsa) {
982157123Sgnn			if (candidate->lft_c->addtime >
983157123Sgnn					sav->lft_c->addtime) {
984105197Ssam				candidate = sav;
985105197Ssam			}
986105197Ssam			continue;
987105197Ssam			/*NOTREACHED*/
988105197Ssam		}
989105197Ssam
990125876Sguido		/* preferred new sa rather than old sa */
991157123Sgnn		if (candidate->lft_c->addtime <
992157123Sgnn				sav->lft_c->addtime) {
993105197Ssam			d = candidate;
994105197Ssam			candidate = sav;
995105197Ssam		} else
996105197Ssam			d = sav;
997105197Ssam
998105197Ssam		/*
999105197Ssam		 * prepared to delete the SA when there is more
1000105197Ssam		 * suitable candidate and the lifetime of the SA is not
1001105197Ssam		 * permanent.
1002105197Ssam		 */
1003177553Sbz		if (d->lft_h->addtime != 0) {
1004105197Ssam			struct mbuf *m, *result;
1005125508Ssam			u_int8_t satype;
1006105197Ssam
1007105197Ssam			key_sa_chgstate(d, SADB_SASTATE_DEAD);
1008105197Ssam
1009120585Ssam			IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
1010125508Ssam
1011125508Ssam			satype = key_proto2satype(d->sah->saidx.proto);
1012125508Ssam			if (satype == 0)
1013125508Ssam				goto msgfail;
1014125508Ssam
1015105197Ssam			m = key_setsadbmsg(SADB_DELETE, 0,
1016125508Ssam			    satype, 0, 0, d->refcnt - 1);
1017105197Ssam			if (!m)
1018105197Ssam				goto msgfail;
1019105197Ssam			result = m;
1020105197Ssam
1021105197Ssam			/* set sadb_address for saidx's. */
1022105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
1023105197Ssam				&d->sah->saidx.src.sa,
1024105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
1025105197Ssam				IPSEC_ULPROTO_ANY);
1026105197Ssam			if (!m)
1027105197Ssam				goto msgfail;
1028105197Ssam			m_cat(result, m);
1029105197Ssam
1030105197Ssam			/* set sadb_address for saidx's. */
1031105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
1032128860Ssam				&d->sah->saidx.dst.sa,
1033128860Ssam				d->sah->saidx.dst.sa.sa_len << 3,
1034105197Ssam				IPSEC_ULPROTO_ANY);
1035105197Ssam			if (!m)
1036105197Ssam				goto msgfail;
1037105197Ssam			m_cat(result, m);
1038105197Ssam
1039105197Ssam			/* create SA extension */
1040105197Ssam			m = key_setsadbsa(d);
1041105197Ssam			if (!m)
1042105197Ssam				goto msgfail;
1043105197Ssam			m_cat(result, m);
1044105197Ssam
1045105197Ssam			if (result->m_len < sizeof(struct sadb_msg)) {
1046105197Ssam				result = m_pullup(result,
1047105197Ssam						sizeof(struct sadb_msg));
1048105197Ssam				if (result == NULL)
1049105197Ssam					goto msgfail;
1050105197Ssam			}
1051105197Ssam
1052105197Ssam			result->m_pkthdr.len = 0;
1053105197Ssam			for (m = result; m; m = m->m_next)
1054105197Ssam				result->m_pkthdr.len += m->m_len;
1055105197Ssam			mtod(result, struct sadb_msg *)->sadb_msg_len =
1056105197Ssam				PFKEY_UNIT64(result->m_pkthdr.len);
1057105197Ssam
1058105197Ssam			if (key_sendup_mbuf(NULL, result,
1059105197Ssam					KEY_SENDUP_REGISTERED))
1060105197Ssam				goto msgfail;
1061105197Ssam		 msgfail:
1062105197Ssam			KEY_FREESAV(&d);
1063105197Ssam		}
1064105197Ssam	}
1065105197Ssam	if (candidate) {
1066158767Spjd		sa_addref(candidate);
1067105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1068120585Ssam			printf("DP %s cause refcnt++:%d SA:%p\n",
1069120585Ssam				__func__, candidate->refcnt, candidate));
1070105197Ssam	}
1071120585Ssam	SAHTREE_UNLOCK();
1072119643Ssam
1073105197Ssam	return candidate;
1074105197Ssam}
1075105197Ssam
1076105197Ssam/*
1077105197Ssam * allocating a usable SA entry for a *INBOUND* packet.
1078105197Ssam * Must call key_freesav() later.
1079105197Ssam * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
1080105197Ssam *	NULL:		not found, or error occured.
1081105197Ssam *
1082105197Ssam * In the comparison, no source address is used--for RFC2401 conformance.
1083105197Ssam * To quote, from section 4.1:
1084105197Ssam *	A security association is uniquely identified by a triple consisting
1085105197Ssam *	of a Security Parameter Index (SPI), an IP Destination Address, and a
1086105197Ssam *	security protocol (AH or ESP) identifier.
1087105197Ssam * Note that, however, we do need to keep source address in IPsec SA.
1088105197Ssam * IKE specification and PF_KEY specification do assume that we
1089105197Ssam * keep source address in IPsec SA.  We see a tricky situation here.
1090105197Ssam */
1091105197Ssamstruct secasvar *
1092105197Ssamkey_allocsa(
1093105197Ssam	union sockaddr_union *dst,
1094105197Ssam	u_int proto,
1095105197Ssam	u_int32_t spi,
1096105197Ssam	const char* where, int tag)
1097105197Ssam{
1098105197Ssam	struct secashead *sah;
1099105197Ssam	struct secasvar *sav;
1100128856Ssam	u_int stateidx, arraysize, state;
1101128856Ssam	const u_int *saorder_state_valid;
1102194062Svanhu	int chkport;
1103105197Ssam
1104120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst address"));
1105105197Ssam
1106105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1107120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
1108105197Ssam
1109194062Svanhu#ifdef IPSEC_NAT_T
1110194062Svanhu        chkport = (dst->sa.sa_family == AF_INET &&
1111194062Svanhu	    dst->sa.sa_len == sizeof(struct sockaddr_in) &&
1112194062Svanhu	    dst->sin.sin_port != 0);
1113194062Svanhu#else
1114194062Svanhu	chkport = 0;
1115194062Svanhu#endif
1116194062Svanhu
1117105197Ssam	/*
1118105197Ssam	 * searching SAD.
1119105197Ssam	 * XXX: to be checked internal IP header somewhere.  Also when
1120105197Ssam	 * IPsec tunnel packet is received.  But ESP tunnel mode is
1121105197Ssam	 * encrypted so we can't check internal IP header.
1122105197Ssam	 */
1123120585Ssam	SAHTREE_LOCK();
1124181803Sbz	if (V_key_preferred_oldsa) {
1125128856Ssam		saorder_state_valid = saorder_state_valid_prefer_old;
1126128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1127128856Ssam	} else {
1128128856Ssam		saorder_state_valid = saorder_state_valid_prefer_new;
1129128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1130128856Ssam	}
1131181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
1132105197Ssam		/* search valid state */
1133128856Ssam		for (stateidx = 0; stateidx < arraysize; stateidx++) {
1134105197Ssam			state = saorder_state_valid[stateidx];
1135105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
1136105197Ssam				/* sanity check */
1137120585Ssam				KEY_CHKSASTATE(sav->state, state, __func__);
1138105197Ssam				/* do not return entries w/ unusable state */
1139105197Ssam				if (sav->state != SADB_SASTATE_MATURE &&
1140105197Ssam				    sav->state != SADB_SASTATE_DYING)
1141105197Ssam					continue;
1142105197Ssam				if (proto != sav->sah->saidx.proto)
1143105197Ssam					continue;
1144105197Ssam				if (spi != sav->spi)
1145105197Ssam					continue;
1146105197Ssam#if 0	/* don't check src */
1147105197Ssam				/* check src address */
1148194062Svanhu				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, chkport) != 0)
1149105197Ssam					continue;
1150105197Ssam#endif
1151105197Ssam				/* check dst address */
1152194062Svanhu				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, chkport) != 0)
1153105197Ssam					continue;
1154158767Spjd				sa_addref(sav);
1155105197Ssam				goto done;
1156105197Ssam			}
1157105197Ssam		}
1158105197Ssam	}
1159105197Ssam	sav = NULL;
1160105197Ssamdone:
1161120585Ssam	SAHTREE_UNLOCK();
1162105197Ssam
1163105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1164120585Ssam		printf("DP %s return SA:%p; refcnt %u\n", __func__,
1165105197Ssam			sav, sav ? sav->refcnt : 0));
1166105197Ssam	return sav;
1167105197Ssam}
1168105197Ssam
1169105197Ssam/*
1170105197Ssam * Must be called after calling key_allocsp().
1171105197Ssam * For both the packet without socket and key_freeso().
1172105197Ssam */
1173105197Ssamvoid
1174105197Ssam_key_freesp(struct secpolicy **spp, const char* where, int tag)
1175105197Ssam{
1176105197Ssam	struct secpolicy *sp = *spp;
1177105197Ssam
1178120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1179105197Ssam
1180120585Ssam	SPTREE_LOCK();
1181105197Ssam	SP_DELREF(sp);
1182105197Ssam
1183105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1184120585Ssam		printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1185120585Ssam			__func__, sp, sp->id, where, tag, sp->refcnt));
1186105197Ssam
1187105197Ssam	if (sp->refcnt == 0) {
1188105197Ssam		*spp = NULL;
1189105197Ssam		key_delsp(sp);
1190105197Ssam	}
1191120585Ssam	SPTREE_UNLOCK();
1192105197Ssam}
1193105197Ssam
1194105197Ssam/*
1195105197Ssam * Must be called after calling key_allocsp().
1196105197Ssam * For the packet with socket.
1197105197Ssam */
1198105197Ssamvoid
1199105197Ssamkey_freeso(struct socket *so)
1200105197Ssam{
1201120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
1202105197Ssam
1203105197Ssam	switch (so->so_proto->pr_domain->dom_family) {
1204186141Sbz#if defined(INET) || defined(INET6)
1205105197Ssam#ifdef INET
1206105197Ssam	case PF_INET:
1207105197Ssam#endif
1208105197Ssam#ifdef INET6
1209105197Ssam	case PF_INET6:
1210186141Sbz#endif
1211105197Ssam	    {
1212186141Sbz		struct inpcb *pcb = sotoinpcb(so);
1213105197Ssam
1214105197Ssam		/* Does it have a PCB ? */
1215105197Ssam		if (pcb == NULL)
1216105197Ssam			return;
1217105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1218105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1219105197Ssam	    }
1220105197Ssam		break;
1221186141Sbz#endif /* INET || INET6 */
1222105197Ssam	default:
1223120585Ssam		ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1224120585Ssam		    __func__, so->so_proto->pr_domain->dom_family));
1225105197Ssam		return;
1226105197Ssam	}
1227105197Ssam}
1228105197Ssam
1229105197Ssamstatic void
1230105197Ssamkey_freesp_so(struct secpolicy **sp)
1231105197Ssam{
1232120585Ssam	IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1233105197Ssam
1234105197Ssam	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1235105197Ssam	    (*sp)->policy == IPSEC_POLICY_BYPASS)
1236105197Ssam		return;
1237105197Ssam
1238120585Ssam	IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1239120585Ssam		("invalid policy %u", (*sp)->policy));
1240105197Ssam	KEY_FREESP(sp);
1241105197Ssam}
1242105197Ssam
1243105197Ssam/*
1244105197Ssam * Must be called after calling key_allocsa().
1245105197Ssam * This function is called by key_freesp() to free some SA allocated
1246105197Ssam * for a policy.
1247105197Ssam */
1248105197Ssamvoid
1249105197Ssamkey_freesav(struct secasvar **psav, const char* where, int tag)
1250105197Ssam{
1251105197Ssam	struct secasvar *sav = *psav;
1252105197Ssam
1253120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
1254105197Ssam
1255158767Spjd	if (sa_delref(sav)) {
1256158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1257158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1258158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1259105197Ssam		*psav = NULL;
1260105197Ssam		key_delsav(sav);
1261158767Spjd	} else {
1262158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1263158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1264158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1265105197Ssam	}
1266105197Ssam}
1267105197Ssam
1268105197Ssam/* %%% SPD management */
1269105197Ssam/*
1270105197Ssam * free security policy entry.
1271105197Ssam */
1272105197Ssamstatic void
1273105197Ssamkey_delsp(struct secpolicy *sp)
1274105197Ssam{
1275119643Ssam	struct ipsecrequest *isr, *nextisr;
1276105197Ssam
1277120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1278120585Ssam	SPTREE_LOCK_ASSERT();
1279105197Ssam
1280105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
1281105197Ssam
1282120585Ssam	IPSEC_ASSERT(sp->refcnt == 0,
1283120585Ssam		("SP with references deleted (refcnt %u)", sp->refcnt));
1284105197Ssam
1285105197Ssam	/* remove from SP index */
1286105197Ssam	if (__LIST_CHAINED(sp))
1287105197Ssam		LIST_REMOVE(sp, chain);
1288105197Ssam
1289119643Ssam	for (isr = sp->req; isr != NULL; isr = nextisr) {
1290105197Ssam		if (isr->sav != NULL) {
1291105197Ssam			KEY_FREESAV(&isr->sav);
1292105197Ssam			isr->sav = NULL;
1293105197Ssam		}
1294105197Ssam
1295105197Ssam		nextisr = isr->next;
1296119643Ssam		ipsec_delisr(isr);
1297105197Ssam	}
1298119643Ssam	_key_delsp(sp);
1299105197Ssam}
1300105197Ssam
1301105197Ssam/*
1302105197Ssam * search SPD
1303105197Ssam * OUT:	NULL	: not found
1304105197Ssam *	others	: found, pointer to a SP.
1305105197Ssam */
1306105197Ssamstatic struct secpolicy *
1307105197Ssamkey_getsp(struct secpolicyindex *spidx)
1308105197Ssam{
1309105197Ssam	struct secpolicy *sp;
1310105197Ssam
1311120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1312105197Ssam
1313120585Ssam	SPTREE_LOCK();
1314181803Sbz	LIST_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1315105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1316105197Ssam			continue;
1317105197Ssam		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1318105197Ssam			SP_ADDREF(sp);
1319119643Ssam			break;
1320105197Ssam		}
1321105197Ssam	}
1322120585Ssam	SPTREE_UNLOCK();
1323105197Ssam
1324119643Ssam	return sp;
1325105197Ssam}
1326105197Ssam
1327105197Ssam/*
1328105197Ssam * get SP by index.
1329105197Ssam * OUT:	NULL	: not found
1330105197Ssam *	others	: found, pointer to a SP.
1331105197Ssam */
1332105197Ssamstatic struct secpolicy *
1333105197Ssamkey_getspbyid(u_int32_t id)
1334105197Ssam{
1335105197Ssam	struct secpolicy *sp;
1336105197Ssam
1337120585Ssam	SPTREE_LOCK();
1338181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
1339105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1340105197Ssam			continue;
1341105197Ssam		if (sp->id == id) {
1342105197Ssam			SP_ADDREF(sp);
1343119643Ssam			goto done;
1344105197Ssam		}
1345105197Ssam	}
1346105197Ssam
1347181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
1348105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1349105197Ssam			continue;
1350105197Ssam		if (sp->id == id) {
1351105197Ssam			SP_ADDREF(sp);
1352119643Ssam			goto done;
1353105197Ssam		}
1354105197Ssam	}
1355119643Ssamdone:
1356120585Ssam	SPTREE_UNLOCK();
1357105197Ssam
1358119643Ssam	return sp;
1359105197Ssam}
1360105197Ssam
1361105197Ssamstruct secpolicy *
1362105197Ssamkey_newsp(const char* where, int tag)
1363105197Ssam{
1364105197Ssam	struct secpolicy *newsp = NULL;
1365105197Ssam
1366105197Ssam	newsp = (struct secpolicy *)
1367119643Ssam		malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1368105197Ssam	if (newsp) {
1369120585Ssam		SECPOLICY_LOCK_INIT(newsp);
1370105197Ssam		newsp->refcnt = 1;
1371105197Ssam		newsp->req = NULL;
1372105197Ssam	}
1373105197Ssam
1374105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1375120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
1376105197Ssam			where, tag, newsp));
1377105197Ssam	return newsp;
1378105197Ssam}
1379105197Ssam
1380119643Ssamstatic void
1381119643Ssam_key_delsp(struct secpolicy *sp)
1382119643Ssam{
1383120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
1384119643Ssam	free(sp, M_IPSEC_SP);
1385119643Ssam}
1386119643Ssam
1387105197Ssam/*
1388105197Ssam * create secpolicy structure from sadb_x_policy structure.
1389105197Ssam * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1390105197Ssam * so must be set properly later.
1391105197Ssam */
1392105197Ssamstruct secpolicy *
1393105197Ssamkey_msg2sp(xpl0, len, error)
1394105197Ssam	struct sadb_x_policy *xpl0;
1395105197Ssam	size_t len;
1396105197Ssam	int *error;
1397105197Ssam{
1398105197Ssam	struct secpolicy *newsp;
1399105197Ssam
1400120585Ssam	IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1401127972Spjd	IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1402120585Ssam
1403105197Ssam	if (len != PFKEY_EXTLEN(xpl0)) {
1404120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1405105197Ssam		*error = EINVAL;
1406105197Ssam		return NULL;
1407105197Ssam	}
1408105197Ssam
1409105197Ssam	if ((newsp = KEY_NEWSP()) == NULL) {
1410105197Ssam		*error = ENOBUFS;
1411105197Ssam		return NULL;
1412105197Ssam	}
1413105197Ssam
1414105197Ssam	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1415105197Ssam	newsp->policy = xpl0->sadb_x_policy_type;
1416105197Ssam
1417105197Ssam	/* check policy */
1418105197Ssam	switch (xpl0->sadb_x_policy_type) {
1419105197Ssam	case IPSEC_POLICY_DISCARD:
1420105197Ssam	case IPSEC_POLICY_NONE:
1421105197Ssam	case IPSEC_POLICY_ENTRUST:
1422105197Ssam	case IPSEC_POLICY_BYPASS:
1423105197Ssam		newsp->req = NULL;
1424105197Ssam		break;
1425105197Ssam
1426105197Ssam	case IPSEC_POLICY_IPSEC:
1427105197Ssam	    {
1428105197Ssam		int tlen;
1429105197Ssam		struct sadb_x_ipsecrequest *xisr;
1430105197Ssam		struct ipsecrequest **p_isr = &newsp->req;
1431105197Ssam
1432105197Ssam		/* validity check */
1433105197Ssam		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1434120585Ssam			ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1435120585Ssam				__func__));
1436105197Ssam			KEY_FREESP(&newsp);
1437105197Ssam			*error = EINVAL;
1438105197Ssam			return NULL;
1439105197Ssam		}
1440105197Ssam
1441105197Ssam		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1442105197Ssam		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1443105197Ssam
1444105197Ssam		while (tlen > 0) {
1445105197Ssam			/* length check */
1446105197Ssam			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1447120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1448120585Ssam					"length.\n", __func__));
1449105197Ssam				KEY_FREESP(&newsp);
1450105197Ssam				*error = EINVAL;
1451105197Ssam				return NULL;
1452105197Ssam			}
1453105197Ssam
1454105197Ssam			/* allocate request buffer */
1455119643Ssam			/* NB: data structure is zero'd */
1456119643Ssam			*p_isr = ipsec_newisr();
1457105197Ssam			if ((*p_isr) == NULL) {
1458105197Ssam				ipseclog((LOG_DEBUG,
1459120585Ssam				    "%s: No more memory.\n", __func__));
1460105197Ssam				KEY_FREESP(&newsp);
1461105197Ssam				*error = ENOBUFS;
1462105197Ssam				return NULL;
1463105197Ssam			}
1464105197Ssam
1465105197Ssam			/* set values */
1466105197Ssam			switch (xisr->sadb_x_ipsecrequest_proto) {
1467105197Ssam			case IPPROTO_ESP:
1468105197Ssam			case IPPROTO_AH:
1469105197Ssam			case IPPROTO_IPCOMP:
1470105197Ssam				break;
1471105197Ssam			default:
1472105197Ssam				ipseclog((LOG_DEBUG,
1473120585Ssam				    "%s: invalid proto type=%u\n", __func__,
1474105197Ssam				    xisr->sadb_x_ipsecrequest_proto));
1475105197Ssam				KEY_FREESP(&newsp);
1476105197Ssam				*error = EPROTONOSUPPORT;
1477105197Ssam				return NULL;
1478105197Ssam			}
1479105197Ssam			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1480105197Ssam
1481105197Ssam			switch (xisr->sadb_x_ipsecrequest_mode) {
1482105197Ssam			case IPSEC_MODE_TRANSPORT:
1483105197Ssam			case IPSEC_MODE_TUNNEL:
1484105197Ssam				break;
1485105197Ssam			case IPSEC_MODE_ANY:
1486105197Ssam			default:
1487105197Ssam				ipseclog((LOG_DEBUG,
1488120585Ssam				    "%s: invalid mode=%u\n", __func__,
1489105197Ssam				    xisr->sadb_x_ipsecrequest_mode));
1490105197Ssam				KEY_FREESP(&newsp);
1491105197Ssam				*error = EINVAL;
1492105197Ssam				return NULL;
1493105197Ssam			}
1494105197Ssam			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1495105197Ssam
1496105197Ssam			switch (xisr->sadb_x_ipsecrequest_level) {
1497105197Ssam			case IPSEC_LEVEL_DEFAULT:
1498105197Ssam			case IPSEC_LEVEL_USE:
1499105197Ssam			case IPSEC_LEVEL_REQUIRE:
1500105197Ssam				break;
1501105197Ssam			case IPSEC_LEVEL_UNIQUE:
1502105197Ssam				/* validity check */
1503105197Ssam				/*
1504105197Ssam				 * If range violation of reqid, kernel will
1505105197Ssam				 * update it, don't refuse it.
1506105197Ssam				 */
1507105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid
1508105197Ssam						> IPSEC_MANUAL_REQID_MAX) {
1509105197Ssam					ipseclog((LOG_DEBUG,
1510120585Ssam					    "%s: reqid=%d range "
1511105197Ssam					    "violation, updated by kernel.\n",
1512120585Ssam					    __func__,
1513105197Ssam					    xisr->sadb_x_ipsecrequest_reqid));
1514105197Ssam					xisr->sadb_x_ipsecrequest_reqid = 0;
1515105197Ssam				}
1516105197Ssam
1517105197Ssam				/* allocate new reqid id if reqid is zero. */
1518105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1519105197Ssam					u_int32_t reqid;
1520105197Ssam					if ((reqid = key_newreqid()) == 0) {
1521105197Ssam						KEY_FREESP(&newsp);
1522105197Ssam						*error = ENOBUFS;
1523105197Ssam						return NULL;
1524105197Ssam					}
1525105197Ssam					(*p_isr)->saidx.reqid = reqid;
1526105197Ssam					xisr->sadb_x_ipsecrequest_reqid = reqid;
1527105197Ssam				} else {
1528105197Ssam				/* set it for manual keying. */
1529105197Ssam					(*p_isr)->saidx.reqid =
1530105197Ssam						xisr->sadb_x_ipsecrequest_reqid;
1531105197Ssam				}
1532105197Ssam				break;
1533105197Ssam
1534105197Ssam			default:
1535120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1536120585Ssam					__func__,
1537105197Ssam					xisr->sadb_x_ipsecrequest_level));
1538105197Ssam				KEY_FREESP(&newsp);
1539105197Ssam				*error = EINVAL;
1540105197Ssam				return NULL;
1541105197Ssam			}
1542105197Ssam			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1543105197Ssam
1544105197Ssam			/* set IP addresses if there */
1545105197Ssam			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1546105197Ssam				struct sockaddr *paddr;
1547105197Ssam
1548105197Ssam				paddr = (struct sockaddr *)(xisr + 1);
1549105197Ssam
1550105197Ssam				/* validity check */
1551105197Ssam				if (paddr->sa_len
1552105197Ssam				    > sizeof((*p_isr)->saidx.src)) {
1553120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1554120585Ssam						"request address length.\n",
1555120585Ssam						__func__));
1556105197Ssam					KEY_FREESP(&newsp);
1557105197Ssam					*error = EINVAL;
1558105197Ssam					return NULL;
1559105197Ssam				}
1560105197Ssam				bcopy(paddr, &(*p_isr)->saidx.src,
1561105197Ssam					paddr->sa_len);
1562105197Ssam
1563105197Ssam				paddr = (struct sockaddr *)((caddr_t)paddr
1564105197Ssam							+ paddr->sa_len);
1565105197Ssam
1566105197Ssam				/* validity check */
1567105197Ssam				if (paddr->sa_len
1568105197Ssam				    > sizeof((*p_isr)->saidx.dst)) {
1569120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1570120585Ssam						"request address length.\n",
1571120585Ssam						__func__));
1572105197Ssam					KEY_FREESP(&newsp);
1573105197Ssam					*error = EINVAL;
1574105197Ssam					return NULL;
1575105197Ssam				}
1576105197Ssam				bcopy(paddr, &(*p_isr)->saidx.dst,
1577105197Ssam					paddr->sa_len);
1578105197Ssam			}
1579105197Ssam
1580105197Ssam			(*p_isr)->sp = newsp;
1581105197Ssam
1582105197Ssam			/* initialization for the next. */
1583105197Ssam			p_isr = &(*p_isr)->next;
1584105197Ssam			tlen -= xisr->sadb_x_ipsecrequest_len;
1585105197Ssam
1586105197Ssam			/* validity check */
1587105197Ssam			if (tlen < 0) {
1588120585Ssam				ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1589120585Ssam					__func__));
1590105197Ssam				KEY_FREESP(&newsp);
1591105197Ssam				*error = EINVAL;
1592105197Ssam				return NULL;
1593105197Ssam			}
1594105197Ssam
1595105197Ssam			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1596105197Ssam			                 + xisr->sadb_x_ipsecrequest_len);
1597105197Ssam		}
1598105197Ssam	    }
1599105197Ssam		break;
1600105197Ssam	default:
1601120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1602105197Ssam		KEY_FREESP(&newsp);
1603105197Ssam		*error = EINVAL;
1604105197Ssam		return NULL;
1605105197Ssam	}
1606105197Ssam
1607105197Ssam	*error = 0;
1608105197Ssam	return newsp;
1609105197Ssam}
1610105197Ssam
1611105197Ssamstatic u_int32_t
1612105197Ssamkey_newreqid()
1613105197Ssam{
1614105197Ssam	static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1615105197Ssam
1616105197Ssam	auto_reqid = (auto_reqid == ~0
1617105197Ssam			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1618105197Ssam
1619105197Ssam	/* XXX should be unique check */
1620105197Ssam
1621105197Ssam	return auto_reqid;
1622105197Ssam}
1623105197Ssam
1624105197Ssam/*
1625105197Ssam * copy secpolicy struct to sadb_x_policy structure indicated.
1626105197Ssam */
1627105197Ssamstruct mbuf *
1628105197Ssamkey_sp2msg(sp)
1629105197Ssam	struct secpolicy *sp;
1630105197Ssam{
1631105197Ssam	struct sadb_x_policy *xpl;
1632105197Ssam	int tlen;
1633105197Ssam	caddr_t p;
1634105197Ssam	struct mbuf *m;
1635105197Ssam
1636120585Ssam	IPSEC_ASSERT(sp != NULL, ("null policy"));
1637105197Ssam
1638105197Ssam	tlen = key_getspreqmsglen(sp);
1639105197Ssam
1640105197Ssam	m = key_alloc_mbuf(tlen);
1641105197Ssam	if (!m || m->m_next) {	/*XXX*/
1642105197Ssam		if (m)
1643105197Ssam			m_freem(m);
1644105197Ssam		return NULL;
1645105197Ssam	}
1646105197Ssam
1647105197Ssam	m->m_len = tlen;
1648105197Ssam	m->m_next = NULL;
1649105197Ssam	xpl = mtod(m, struct sadb_x_policy *);
1650105197Ssam	bzero(xpl, tlen);
1651105197Ssam
1652105197Ssam	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1653105197Ssam	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1654105197Ssam	xpl->sadb_x_policy_type = sp->policy;
1655105197Ssam	xpl->sadb_x_policy_dir = sp->spidx.dir;
1656105197Ssam	xpl->sadb_x_policy_id = sp->id;
1657105197Ssam	p = (caddr_t)xpl + sizeof(*xpl);
1658105197Ssam
1659105197Ssam	/* if is the policy for ipsec ? */
1660105197Ssam	if (sp->policy == IPSEC_POLICY_IPSEC) {
1661105197Ssam		struct sadb_x_ipsecrequest *xisr;
1662105197Ssam		struct ipsecrequest *isr;
1663105197Ssam
1664105197Ssam		for (isr = sp->req; isr != NULL; isr = isr->next) {
1665105197Ssam
1666105197Ssam			xisr = (struct sadb_x_ipsecrequest *)p;
1667105197Ssam
1668105197Ssam			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1669105197Ssam			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1670105197Ssam			xisr->sadb_x_ipsecrequest_level = isr->level;
1671105197Ssam			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1672105197Ssam
1673105197Ssam			p += sizeof(*xisr);
1674105197Ssam			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1675105197Ssam			p += isr->saidx.src.sa.sa_len;
1676105197Ssam			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1677105197Ssam			p += isr->saidx.src.sa.sa_len;
1678105197Ssam
1679105197Ssam			xisr->sadb_x_ipsecrequest_len =
1680105197Ssam				PFKEY_ALIGN8(sizeof(*xisr)
1681105197Ssam					+ isr->saidx.src.sa.sa_len
1682105197Ssam					+ isr->saidx.dst.sa.sa_len);
1683105197Ssam		}
1684105197Ssam	}
1685105197Ssam
1686105197Ssam	return m;
1687105197Ssam}
1688105197Ssam
1689105197Ssam/* m will not be freed nor modified */
1690105197Ssamstatic struct mbuf *
1691105197Ssam#ifdef __STDC__
1692105197Ssamkey_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1693105197Ssam	int ndeep, int nitem, ...)
1694105197Ssam#else
1695105197Ssamkey_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1696105197Ssam	struct mbuf *m;
1697105197Ssam	const struct sadb_msghdr *mhp;
1698105197Ssam	int ndeep;
1699105197Ssam	int nitem;
1700105197Ssam	va_dcl
1701105197Ssam#endif
1702105197Ssam{
1703105197Ssam	va_list ap;
1704105197Ssam	int idx;
1705105197Ssam	int i;
1706105197Ssam	struct mbuf *result = NULL, *n;
1707105197Ssam	int len;
1708105197Ssam
1709120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1710120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1711105197Ssam
1712105197Ssam	va_start(ap, nitem);
1713105197Ssam	for (i = 0; i < nitem; i++) {
1714105197Ssam		idx = va_arg(ap, int);
1715105197Ssam		if (idx < 0 || idx > SADB_EXT_MAX)
1716105197Ssam			goto fail;
1717105197Ssam		/* don't attempt to pull empty extension */
1718105197Ssam		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1719105197Ssam			continue;
1720105197Ssam		if (idx != SADB_EXT_RESERVED  &&
1721105197Ssam		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1722105197Ssam			continue;
1723105197Ssam
1724105197Ssam		if (idx == SADB_EXT_RESERVED) {
1725105197Ssam			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1726120585Ssam
1727120585Ssam			IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1728120585Ssam
1729111119Simp			MGETHDR(n, M_DONTWAIT, MT_DATA);
1730105197Ssam			if (!n)
1731105197Ssam				goto fail;
1732105197Ssam			n->m_len = len;
1733105197Ssam			n->m_next = NULL;
1734105197Ssam			m_copydata(m, 0, sizeof(struct sadb_msg),
1735105197Ssam			    mtod(n, caddr_t));
1736105197Ssam		} else if (i < ndeep) {
1737105197Ssam			len = mhp->extlen[idx];
1738105197Ssam			n = key_alloc_mbuf(len);
1739105197Ssam			if (!n || n->m_next) {	/*XXX*/
1740105197Ssam				if (n)
1741105197Ssam					m_freem(n);
1742105197Ssam				goto fail;
1743105197Ssam			}
1744105197Ssam			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1745105197Ssam			    mtod(n, caddr_t));
1746105197Ssam		} else {
1747105197Ssam			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1748111119Simp			    M_DONTWAIT);
1749105197Ssam		}
1750105197Ssam		if (n == NULL)
1751105197Ssam			goto fail;
1752105197Ssam
1753105197Ssam		if (result)
1754105197Ssam			m_cat(result, n);
1755105197Ssam		else
1756105197Ssam			result = n;
1757105197Ssam	}
1758105197Ssam	va_end(ap);
1759105197Ssam
1760105197Ssam	if ((result->m_flags & M_PKTHDR) != 0) {
1761105197Ssam		result->m_pkthdr.len = 0;
1762105197Ssam		for (n = result; n; n = n->m_next)
1763105197Ssam			result->m_pkthdr.len += n->m_len;
1764105197Ssam	}
1765105197Ssam
1766105197Ssam	return result;
1767105197Ssam
1768105197Ssamfail:
1769105197Ssam	m_freem(result);
1770105197Ssam	return NULL;
1771105197Ssam}
1772105197Ssam
1773105197Ssam/*
1774105197Ssam * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1775108533Sschweikh * add an entry to SP database, when received
1776105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1777105197Ssam * from the user(?).
1778105197Ssam * Adding to SP database,
1779105197Ssam * and send
1780105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1781105197Ssam * to the socket which was send.
1782105197Ssam *
1783105197Ssam * SPDADD set a unique policy entry.
1784105197Ssam * SPDSETIDX like SPDADD without a part of policy requests.
1785105197Ssam * SPDUPDATE replace a unique policy entry.
1786105197Ssam *
1787105197Ssam * m will always be freed.
1788105197Ssam */
1789105197Ssamstatic int
1790105197Ssamkey_spdadd(so, m, mhp)
1791105197Ssam	struct socket *so;
1792105197Ssam	struct mbuf *m;
1793105197Ssam	const struct sadb_msghdr *mhp;
1794105197Ssam{
1795105197Ssam	struct sadb_address *src0, *dst0;
1796105197Ssam	struct sadb_x_policy *xpl0, *xpl;
1797105197Ssam	struct sadb_lifetime *lft = NULL;
1798105197Ssam	struct secpolicyindex spidx;
1799105197Ssam	struct secpolicy *newsp;
1800105197Ssam	int error;
1801105197Ssam
1802120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
1803120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1804120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1805120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1806105197Ssam
1807105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1808105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1809105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1810105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1811105197Ssam		return key_senderror(so, m, EINVAL);
1812105197Ssam	}
1813105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1814105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1815105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1816120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1817120585Ssam			__func__));
1818105197Ssam		return key_senderror(so, m, EINVAL);
1819105197Ssam	}
1820105197Ssam	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1821105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1822105197Ssam			< sizeof(struct sadb_lifetime)) {
1823120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1824120585Ssam				__func__));
1825105197Ssam			return key_senderror(so, m, EINVAL);
1826105197Ssam		}
1827105197Ssam		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1828105197Ssam	}
1829105197Ssam
1830105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1831105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1832105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1833105197Ssam
1834194062Svanhu	/*
1835194062Svanhu	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
1836194062Svanhu	 * we are processing traffic endpoints.
1837194062Svanhu	 */
1838194062Svanhu
1839105197Ssam	/* make secindex */
1840105197Ssam	/* XXX boundary check against sa_len */
1841105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1842105197Ssam	                src0 + 1,
1843105197Ssam	                dst0 + 1,
1844105197Ssam	                src0->sadb_address_prefixlen,
1845105197Ssam	                dst0->sadb_address_prefixlen,
1846105197Ssam	                src0->sadb_address_proto,
1847105197Ssam	                &spidx);
1848105197Ssam
1849105197Ssam	/* checking the direciton. */
1850105197Ssam	switch (xpl0->sadb_x_policy_dir) {
1851105197Ssam	case IPSEC_DIR_INBOUND:
1852105197Ssam	case IPSEC_DIR_OUTBOUND:
1853105197Ssam		break;
1854105197Ssam	default:
1855120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1856105197Ssam		mhp->msg->sadb_msg_errno = EINVAL;
1857105197Ssam		return 0;
1858105197Ssam	}
1859105197Ssam
1860105197Ssam	/* check policy */
1861105197Ssam	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1862105197Ssam	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1863105197Ssam	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1864120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1865105197Ssam		return key_senderror(so, m, EINVAL);
1866105197Ssam	}
1867105197Ssam
1868105197Ssam	/* policy requests are mandatory when action is ipsec. */
1869105197Ssam        if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1870105197Ssam	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1871105197Ssam	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1872120585Ssam		ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1873120585Ssam			__func__));
1874105197Ssam		return key_senderror(so, m, EINVAL);
1875105197Ssam	}
1876105197Ssam
1877105197Ssam	/*
1878105197Ssam	 * checking there is SP already or not.
1879105197Ssam	 * SPDUPDATE doesn't depend on whether there is a SP or not.
1880105197Ssam	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1881105197Ssam	 * then error.
1882105197Ssam	 */
1883105197Ssam	newsp = key_getsp(&spidx);
1884105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1885105197Ssam		if (newsp) {
1886206659Svanhu			SPTREE_LOCK();
1887105197Ssam			newsp->state = IPSEC_SPSTATE_DEAD;
1888206659Svanhu			SPTREE_UNLOCK();
1889105197Ssam			KEY_FREESP(&newsp);
1890105197Ssam		}
1891105197Ssam	} else {
1892105197Ssam		if (newsp != NULL) {
1893105197Ssam			KEY_FREESP(&newsp);
1894120585Ssam			ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1895120585Ssam				__func__));
1896105197Ssam			return key_senderror(so, m, EEXIST);
1897105197Ssam		}
1898105197Ssam	}
1899105197Ssam
1900105197Ssam	/* allocation new SP entry */
1901105197Ssam	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1902105197Ssam		return key_senderror(so, m, error);
1903105197Ssam	}
1904105197Ssam
1905105197Ssam	if ((newsp->id = key_getnewspid()) == 0) {
1906119643Ssam		_key_delsp(newsp);
1907105197Ssam		return key_senderror(so, m, ENOBUFS);
1908105197Ssam	}
1909105197Ssam
1910105197Ssam	/* XXX boundary check against sa_len */
1911105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1912105197Ssam	                src0 + 1,
1913105197Ssam	                dst0 + 1,
1914105197Ssam	                src0->sadb_address_prefixlen,
1915105197Ssam	                dst0->sadb_address_prefixlen,
1916105197Ssam	                src0->sadb_address_proto,
1917105197Ssam	                &newsp->spidx);
1918105197Ssam
1919105197Ssam	/* sanity check on addr pair */
1920105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1921105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_family) {
1922119643Ssam		_key_delsp(newsp);
1923105197Ssam		return key_senderror(so, m, EINVAL);
1924105197Ssam	}
1925105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1926105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_len) {
1927119643Ssam		_key_delsp(newsp);
1928105197Ssam		return key_senderror(so, m, EINVAL);
1929105197Ssam	}
1930105197Ssam#if 1
1931197250Svanhu	if (newsp->req && newsp->req->saidx.src.sa.sa_family && newsp->req->saidx.dst.sa.sa_family) {
1932197250Svanhu		if (newsp->req->saidx.src.sa.sa_family != newsp->req->saidx.dst.sa.sa_family) {
1933119643Ssam			_key_delsp(newsp);
1934105197Ssam			return key_senderror(so, m, EINVAL);
1935105197Ssam		}
1936105197Ssam	}
1937105197Ssam#endif
1938105197Ssam
1939105197Ssam	newsp->created = time_second;
1940105197Ssam	newsp->lastused = newsp->created;
1941105197Ssam	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1942105197Ssam	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1943105197Ssam
1944105197Ssam	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1945105197Ssam	newsp->state = IPSEC_SPSTATE_ALIVE;
1946181803Sbz	LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1947105197Ssam
1948105197Ssam	/* delete the entry in spacqtree */
1949105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1950119643Ssam		struct secspacq *spacq = key_getspacq(&spidx);
1951119643Ssam		if (spacq != NULL) {
1952105197Ssam			/* reset counter in order to deletion by timehandler. */
1953105197Ssam			spacq->created = time_second;
1954105197Ssam			spacq->count = 0;
1955120585Ssam			SPACQ_UNLOCK();
1956105197Ssam		}
1957105197Ssam    	}
1958105197Ssam
1959105197Ssam    {
1960105197Ssam	struct mbuf *n, *mpolicy;
1961105197Ssam	struct sadb_msg *newmsg;
1962105197Ssam	int off;
1963105197Ssam
1964194062Svanhu	/*
1965194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
1966194062Svanhu	 * we are sending traffic endpoints.
1967194062Svanhu	 */
1968194062Svanhu
1969105197Ssam	/* create new sadb_msg to reply. */
1970105197Ssam	if (lft) {
1971105197Ssam		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1972105197Ssam		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1973105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1974105197Ssam	} else {
1975105197Ssam		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1976105197Ssam		    SADB_X_EXT_POLICY,
1977105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1978105197Ssam	}
1979105197Ssam	if (!n)
1980105197Ssam		return key_senderror(so, m, ENOBUFS);
1981105197Ssam
1982105197Ssam	if (n->m_len < sizeof(*newmsg)) {
1983105197Ssam		n = m_pullup(n, sizeof(*newmsg));
1984105197Ssam		if (!n)
1985105197Ssam			return key_senderror(so, m, ENOBUFS);
1986105197Ssam	}
1987105197Ssam	newmsg = mtod(n, struct sadb_msg *);
1988105197Ssam	newmsg->sadb_msg_errno = 0;
1989105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1990105197Ssam
1991105197Ssam	off = 0;
1992105197Ssam	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1993105197Ssam	    sizeof(*xpl), &off);
1994105197Ssam	if (mpolicy == NULL) {
1995105197Ssam		/* n is already freed */
1996105197Ssam		return key_senderror(so, m, ENOBUFS);
1997105197Ssam	}
1998105197Ssam	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1999105197Ssam	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
2000105197Ssam		m_freem(n);
2001105197Ssam		return key_senderror(so, m, EINVAL);
2002105197Ssam	}
2003105197Ssam	xpl->sadb_x_policy_id = newsp->id;
2004105197Ssam
2005105197Ssam	m_freem(m);
2006105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2007105197Ssam    }
2008105197Ssam}
2009105197Ssam
2010105197Ssam/*
2011105197Ssam * get new policy id.
2012105197Ssam * OUT:
2013105197Ssam *	0:	failure.
2014105197Ssam *	others: success.
2015105197Ssam */
2016105197Ssamstatic u_int32_t
2017105197Ssamkey_getnewspid()
2018105197Ssam{
2019105197Ssam	u_int32_t newid = 0;
2020181803Sbz	int count = V_key_spi_trycnt;	/* XXX */
2021105197Ssam	struct secpolicy *sp;
2022105197Ssam
2023105197Ssam	/* when requesting to allocate spi ranged */
2024105197Ssam	while (count--) {
2025181803Sbz		newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
2026105197Ssam
2027105197Ssam		if ((sp = key_getspbyid(newid)) == NULL)
2028105197Ssam			break;
2029105197Ssam
2030105197Ssam		KEY_FREESP(&sp);
2031105197Ssam	}
2032105197Ssam
2033105197Ssam	if (count == 0 || newid == 0) {
2034120585Ssam		ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2035120585Ssam			__func__));
2036105197Ssam		return 0;
2037105197Ssam	}
2038105197Ssam
2039105197Ssam	return newid;
2040105197Ssam}
2041105197Ssam
2042105197Ssam/*
2043105197Ssam * SADB_SPDDELETE processing
2044105197Ssam * receive
2045105197Ssam *   <base, address(SD), policy(*)>
2046105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2047105197Ssam * and send,
2048105197Ssam *   <base, address(SD), policy(*)>
2049105197Ssam * to the ikmpd.
2050105197Ssam * policy(*) including direction of policy.
2051105197Ssam *
2052105197Ssam * m will always be freed.
2053105197Ssam */
2054105197Ssamstatic int
2055105197Ssamkey_spddelete(so, m, mhp)
2056105197Ssam	struct socket *so;
2057105197Ssam	struct mbuf *m;
2058105197Ssam	const struct sadb_msghdr *mhp;
2059105197Ssam{
2060105197Ssam	struct sadb_address *src0, *dst0;
2061105197Ssam	struct sadb_x_policy *xpl0;
2062105197Ssam	struct secpolicyindex spidx;
2063105197Ssam	struct secpolicy *sp;
2064105197Ssam
2065120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
2066120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2067120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2068120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2069105197Ssam
2070105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2071105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2072105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2073120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2074120585Ssam			__func__));
2075105197Ssam		return key_senderror(so, m, EINVAL);
2076105197Ssam	}
2077105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2078105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2079105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2080120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2081120585Ssam			__func__));
2082105197Ssam		return key_senderror(so, m, EINVAL);
2083105197Ssam	}
2084105197Ssam
2085105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2086105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2087105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2088105197Ssam
2089194062Svanhu	/*
2090194062Svanhu	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
2091194062Svanhu	 * we are processing traffic endpoints.
2092194062Svanhu	 */
2093194062Svanhu
2094105197Ssam	/* make secindex */
2095105197Ssam	/* XXX boundary check against sa_len */
2096105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2097105197Ssam	                src0 + 1,
2098105197Ssam	                dst0 + 1,
2099105197Ssam	                src0->sadb_address_prefixlen,
2100105197Ssam	                dst0->sadb_address_prefixlen,
2101105197Ssam	                src0->sadb_address_proto,
2102105197Ssam	                &spidx);
2103105197Ssam
2104105197Ssam	/* checking the direciton. */
2105105197Ssam	switch (xpl0->sadb_x_policy_dir) {
2106105197Ssam	case IPSEC_DIR_INBOUND:
2107105197Ssam	case IPSEC_DIR_OUTBOUND:
2108105197Ssam		break;
2109105197Ssam	default:
2110120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2111105197Ssam		return key_senderror(so, m, EINVAL);
2112105197Ssam	}
2113105197Ssam
2114105197Ssam	/* Is there SP in SPD ? */
2115105197Ssam	if ((sp = key_getsp(&spidx)) == NULL) {
2116120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2117105197Ssam		return key_senderror(so, m, EINVAL);
2118105197Ssam	}
2119105197Ssam
2120105197Ssam	/* save policy id to buffer to be returned. */
2121105197Ssam	xpl0->sadb_x_policy_id = sp->id;
2122105197Ssam
2123206659Svanhu	SPTREE_LOCK();
2124105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2125206659Svanhu	SPTREE_UNLOCK();
2126105197Ssam	KEY_FREESP(&sp);
2127105197Ssam
2128105197Ssam    {
2129105197Ssam	struct mbuf *n;
2130105197Ssam	struct sadb_msg *newmsg;
2131105197Ssam
2132194062Svanhu	/*
2133194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2134194062Svanhu	 * we are sending traffic endpoints.
2135194062Svanhu	 */
2136194062Svanhu
2137105197Ssam	/* create new sadb_msg to reply. */
2138105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2139105197Ssam	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2140105197Ssam	if (!n)
2141105197Ssam		return key_senderror(so, m, ENOBUFS);
2142105197Ssam
2143105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2144105197Ssam	newmsg->sadb_msg_errno = 0;
2145105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2146105197Ssam
2147105197Ssam	m_freem(m);
2148105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2149105197Ssam    }
2150105197Ssam}
2151105197Ssam
2152105197Ssam/*
2153105197Ssam * SADB_SPDDELETE2 processing
2154105197Ssam * receive
2155105197Ssam *   <base, policy(*)>
2156105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2157105197Ssam * and send,
2158105197Ssam *   <base, policy(*)>
2159105197Ssam * to the ikmpd.
2160105197Ssam * policy(*) including direction of policy.
2161105197Ssam *
2162105197Ssam * m will always be freed.
2163105197Ssam */
2164105197Ssamstatic int
2165105197Ssamkey_spddelete2(so, m, mhp)
2166105197Ssam	struct socket *so;
2167105197Ssam	struct mbuf *m;
2168105197Ssam	const struct sadb_msghdr *mhp;
2169105197Ssam{
2170105197Ssam	u_int32_t id;
2171105197Ssam	struct secpolicy *sp;
2172105197Ssam
2173120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2174120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2175120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2176120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2177105197Ssam
2178105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2179105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2180120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2181170803Sbz		return key_senderror(so, m, EINVAL);
2182105197Ssam	}
2183105197Ssam
2184105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2185105197Ssam
2186105197Ssam	/* Is there SP in SPD ? */
2187105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2188120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2189170803Sbz		return key_senderror(so, m, EINVAL);
2190105197Ssam	}
2191105197Ssam
2192206659Svanhu	SPTREE_LOCK();
2193105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2194206659Svanhu	SPTREE_UNLOCK();
2195105197Ssam	KEY_FREESP(&sp);
2196105197Ssam
2197105197Ssam    {
2198105197Ssam	struct mbuf *n, *nn;
2199105197Ssam	struct sadb_msg *newmsg;
2200105197Ssam	int off, len;
2201105197Ssam
2202105197Ssam	/* create new sadb_msg to reply. */
2203105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2204105197Ssam
2205111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
2206105197Ssam	if (n && len > MHLEN) {
2207111119Simp		MCLGET(n, M_DONTWAIT);
2208105197Ssam		if ((n->m_flags & M_EXT) == 0) {
2209105197Ssam			m_freem(n);
2210105197Ssam			n = NULL;
2211105197Ssam		}
2212105197Ssam	}
2213105197Ssam	if (!n)
2214105197Ssam		return key_senderror(so, m, ENOBUFS);
2215105197Ssam
2216105197Ssam	n->m_len = len;
2217105197Ssam	n->m_next = NULL;
2218105197Ssam	off = 0;
2219105197Ssam
2220105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2221105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2222105197Ssam
2223120585Ssam	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2224120585Ssam		off, len));
2225105197Ssam
2226105197Ssam	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2227111119Simp	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2228105197Ssam	if (!n->m_next) {
2229105197Ssam		m_freem(n);
2230105197Ssam		return key_senderror(so, m, ENOBUFS);
2231105197Ssam	}
2232105197Ssam
2233105197Ssam	n->m_pkthdr.len = 0;
2234105197Ssam	for (nn = n; nn; nn = nn->m_next)
2235105197Ssam		n->m_pkthdr.len += nn->m_len;
2236105197Ssam
2237105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2238105197Ssam	newmsg->sadb_msg_errno = 0;
2239105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2240105197Ssam
2241105197Ssam	m_freem(m);
2242105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2243105197Ssam    }
2244105197Ssam}
2245105197Ssam
2246105197Ssam/*
2247105197Ssam * SADB_X_GET processing
2248105197Ssam * receive
2249105197Ssam *   <base, policy(*)>
2250105197Ssam * from the user(?),
2251105197Ssam * and send,
2252105197Ssam *   <base, address(SD), policy>
2253105197Ssam * to the ikmpd.
2254105197Ssam * policy(*) including direction of policy.
2255105197Ssam *
2256105197Ssam * m will always be freed.
2257105197Ssam */
2258105197Ssamstatic int
2259105197Ssamkey_spdget(so, m, mhp)
2260105197Ssam	struct socket *so;
2261105197Ssam	struct mbuf *m;
2262105197Ssam	const struct sadb_msghdr *mhp;
2263105197Ssam{
2264105197Ssam	u_int32_t id;
2265105197Ssam	struct secpolicy *sp;
2266105197Ssam	struct mbuf *n;
2267105197Ssam
2268120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2269120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2270120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2271120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2272105197Ssam
2273105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2274105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2275120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2276120585Ssam			__func__));
2277105197Ssam		return key_senderror(so, m, EINVAL);
2278105197Ssam	}
2279105197Ssam
2280105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2281105197Ssam
2282105197Ssam	/* Is there SP in SPD ? */
2283105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2284120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2285105197Ssam		return key_senderror(so, m, ENOENT);
2286105197Ssam	}
2287105197Ssam
2288105197Ssam	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2289105197Ssam	if (n != NULL) {
2290105197Ssam		m_freem(m);
2291105197Ssam		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2292105197Ssam	} else
2293105197Ssam		return key_senderror(so, m, ENOBUFS);
2294105197Ssam}
2295105197Ssam
2296105197Ssam/*
2297105197Ssam * SADB_X_SPDACQUIRE processing.
2298105197Ssam * Acquire policy and SA(s) for a *OUTBOUND* packet.
2299105197Ssam * send
2300105197Ssam *   <base, policy(*)>
2301105197Ssam * to KMD, and expect to receive
2302105197Ssam *   <base> with SADB_X_SPDACQUIRE if error occured,
2303105197Ssam * or
2304105197Ssam *   <base, policy>
2305105197Ssam * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2306105197Ssam * policy(*) is without policy requests.
2307105197Ssam *
2308105197Ssam *    0     : succeed
2309105197Ssam *    others: error number
2310105197Ssam */
2311105197Ssamint
2312105197Ssamkey_spdacquire(sp)
2313105197Ssam	struct secpolicy *sp;
2314105197Ssam{
2315105197Ssam	struct mbuf *result = NULL, *m;
2316105197Ssam	struct secspacq *newspacq;
2317105197Ssam
2318120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2319120585Ssam	IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2320120585Ssam	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2321120585Ssam		("policy not IPSEC %u", sp->policy));
2322105197Ssam
2323108533Sschweikh	/* Get an entry to check whether sent message or not. */
2324119643Ssam	newspacq = key_getspacq(&sp->spidx);
2325119643Ssam	if (newspacq != NULL) {
2326181803Sbz		if (V_key_blockacq_count < newspacq->count) {
2327105197Ssam			/* reset counter and do send message. */
2328105197Ssam			newspacq->count = 0;
2329105197Ssam		} else {
2330105197Ssam			/* increment counter and do nothing. */
2331105197Ssam			newspacq->count++;
2332105197Ssam			return 0;
2333105197Ssam		}
2334120585Ssam		SPACQ_UNLOCK();
2335105197Ssam	} else {
2336105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
2337119643Ssam		newspacq = key_newspacq(&sp->spidx);
2338119643Ssam		if (newspacq == NULL)
2339105197Ssam			return ENOBUFS;
2340105197Ssam	}
2341105197Ssam
2342105197Ssam	/* create new sadb_msg to reply. */
2343105197Ssam	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2344170805Sbz	if (!m)
2345170805Sbz		return ENOBUFS;
2346170805Sbz
2347105197Ssam	result = m;
2348105197Ssam
2349105197Ssam	result->m_pkthdr.len = 0;
2350105197Ssam	for (m = result; m; m = m->m_next)
2351105197Ssam		result->m_pkthdr.len += m->m_len;
2352105197Ssam
2353105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2354105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2355105197Ssam
2356105197Ssam	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2357105197Ssam}
2358105197Ssam
2359105197Ssam/*
2360105197Ssam * SADB_SPDFLUSH processing
2361105197Ssam * receive
2362105197Ssam *   <base>
2363105197Ssam * from the user, and free all entries in secpctree.
2364105197Ssam * and send,
2365105197Ssam *   <base>
2366105197Ssam * to the user.
2367105197Ssam * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2368105197Ssam *
2369105197Ssam * m will always be freed.
2370105197Ssam */
2371105197Ssamstatic int
2372105197Ssamkey_spdflush(so, m, mhp)
2373105197Ssam	struct socket *so;
2374105197Ssam	struct mbuf *m;
2375105197Ssam	const struct sadb_msghdr *mhp;
2376105197Ssam{
2377105197Ssam	struct sadb_msg *newmsg;
2378105197Ssam	struct secpolicy *sp;
2379105197Ssam	u_int dir;
2380105197Ssam
2381120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2382120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2383120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2384120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2385105197Ssam
2386105197Ssam	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2387105197Ssam		return key_senderror(so, m, EINVAL);
2388105197Ssam
2389105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2390120585Ssam		SPTREE_LOCK();
2391181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain)
2392105197Ssam			sp->state = IPSEC_SPSTATE_DEAD;
2393120585Ssam		SPTREE_UNLOCK();
2394105197Ssam	}
2395105197Ssam
2396105197Ssam	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2397120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2398105197Ssam		return key_senderror(so, m, ENOBUFS);
2399105197Ssam	}
2400105197Ssam
2401105197Ssam	if (m->m_next)
2402105197Ssam		m_freem(m->m_next);
2403105197Ssam	m->m_next = NULL;
2404105197Ssam	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2405105197Ssam	newmsg = mtod(m, struct sadb_msg *);
2406105197Ssam	newmsg->sadb_msg_errno = 0;
2407105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2408105197Ssam
2409105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2410105197Ssam}
2411105197Ssam
2412105197Ssam/*
2413105197Ssam * SADB_SPDDUMP processing
2414105197Ssam * receive
2415105197Ssam *   <base>
2416105197Ssam * from the user, and dump all SP leaves
2417105197Ssam * and send,
2418105197Ssam *   <base> .....
2419105197Ssam * to the ikmpd.
2420105197Ssam *
2421105197Ssam * m will always be freed.
2422105197Ssam */
2423105197Ssamstatic int
2424105197Ssamkey_spddump(so, m, mhp)
2425105197Ssam	struct socket *so;
2426105197Ssam	struct mbuf *m;
2427105197Ssam	const struct sadb_msghdr *mhp;
2428105197Ssam{
2429105197Ssam	struct secpolicy *sp;
2430105197Ssam	int cnt;
2431105197Ssam	u_int dir;
2432105197Ssam	struct mbuf *n;
2433105197Ssam
2434120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2435120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2436120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2437120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2438105197Ssam
2439105197Ssam	/* search SPD entry and get buffer size. */
2440105197Ssam	cnt = 0;
2441192882Svanhu	SPTREE_LOCK();
2442105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2443181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2444105197Ssam			cnt++;
2445105197Ssam		}
2446105197Ssam	}
2447105197Ssam
2448192882Svanhu	if (cnt == 0) {
2449192882Svanhu		SPTREE_UNLOCK();
2450105197Ssam		return key_senderror(so, m, ENOENT);
2451192882Svanhu	}
2452105197Ssam
2453105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2454181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2455105197Ssam			--cnt;
2456105197Ssam			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2457105197Ssam			    mhp->msg->sadb_msg_pid);
2458105197Ssam
2459105197Ssam			if (n)
2460105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2461105197Ssam		}
2462105197Ssam	}
2463105197Ssam
2464192882Svanhu	SPTREE_UNLOCK();
2465105197Ssam	m_freem(m);
2466105197Ssam	return 0;
2467105197Ssam}
2468105197Ssam
2469105197Ssamstatic struct mbuf *
2470189004Srdivackykey_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid)
2471105197Ssam{
2472105197Ssam	struct mbuf *result = NULL, *m;
2473181330Svanhu	struct seclifetime lt;
2474105197Ssam
2475105197Ssam	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2476105197Ssam	if (!m)
2477105197Ssam		goto fail;
2478105197Ssam	result = m;
2479105197Ssam
2480194062Svanhu	/*
2481194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2482194062Svanhu	 * we are sending traffic endpoints.
2483194062Svanhu	 */
2484105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2485105197Ssam	    &sp->spidx.src.sa, sp->spidx.prefs,
2486105197Ssam	    sp->spidx.ul_proto);
2487105197Ssam	if (!m)
2488105197Ssam		goto fail;
2489105197Ssam	m_cat(result, m);
2490105197Ssam
2491105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2492105197Ssam	    &sp->spidx.dst.sa, sp->spidx.prefd,
2493105197Ssam	    sp->spidx.ul_proto);
2494105197Ssam	if (!m)
2495105197Ssam		goto fail;
2496105197Ssam	m_cat(result, m);
2497105197Ssam
2498105197Ssam	m = key_sp2msg(sp);
2499105197Ssam	if (!m)
2500105197Ssam		goto fail;
2501105197Ssam	m_cat(result, m);
2502105197Ssam
2503181330Svanhu	if(sp->lifetime){
2504181330Svanhu		lt.addtime=sp->created;
2505181330Svanhu		lt.usetime= sp->lastused;
2506181330Svanhu		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_CURRENT);
2507181330Svanhu		if (!m)
2508181330Svanhu			goto fail;
2509181330Svanhu		m_cat(result, m);
2510181330Svanhu
2511181330Svanhu		lt.addtime=sp->lifetime;
2512181330Svanhu		lt.usetime= sp->validtime;
2513181330Svanhu		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_HARD);
2514181330Svanhu		if (!m)
2515181330Svanhu			goto fail;
2516181330Svanhu		m_cat(result, m);
2517181330Svanhu	}
2518181330Svanhu
2519105197Ssam	if ((result->m_flags & M_PKTHDR) == 0)
2520105197Ssam		goto fail;
2521105197Ssam
2522105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2523105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2524105197Ssam		if (result == NULL)
2525105197Ssam			goto fail;
2526105197Ssam	}
2527105197Ssam
2528105197Ssam	result->m_pkthdr.len = 0;
2529105197Ssam	for (m = result; m; m = m->m_next)
2530105197Ssam		result->m_pkthdr.len += m->m_len;
2531105197Ssam
2532105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2533105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2534105197Ssam
2535105197Ssam	return result;
2536105197Ssam
2537105197Ssamfail:
2538105197Ssam	m_freem(result);
2539105197Ssam	return NULL;
2540105197Ssam}
2541105197Ssam
2542105197Ssam/*
2543105197Ssam * get PFKEY message length for security policy and request.
2544105197Ssam */
2545105197Ssamstatic u_int
2546105197Ssamkey_getspreqmsglen(sp)
2547105197Ssam	struct secpolicy *sp;
2548105197Ssam{
2549105197Ssam	u_int tlen;
2550105197Ssam
2551105197Ssam	tlen = sizeof(struct sadb_x_policy);
2552105197Ssam
2553105197Ssam	/* if is the policy for ipsec ? */
2554105197Ssam	if (sp->policy != IPSEC_POLICY_IPSEC)
2555105197Ssam		return tlen;
2556105197Ssam
2557105197Ssam	/* get length of ipsec requests */
2558105197Ssam    {
2559105197Ssam	struct ipsecrequest *isr;
2560105197Ssam	int len;
2561105197Ssam
2562105197Ssam	for (isr = sp->req; isr != NULL; isr = isr->next) {
2563105197Ssam		len = sizeof(struct sadb_x_ipsecrequest)
2564105197Ssam			+ isr->saidx.src.sa.sa_len
2565105197Ssam			+ isr->saidx.dst.sa.sa_len;
2566105197Ssam
2567105197Ssam		tlen += PFKEY_ALIGN8(len);
2568105197Ssam	}
2569105197Ssam    }
2570105197Ssam
2571105197Ssam	return tlen;
2572105197Ssam}
2573105197Ssam
2574105197Ssam/*
2575105197Ssam * SADB_SPDEXPIRE processing
2576105197Ssam * send
2577105197Ssam *   <base, address(SD), lifetime(CH), policy>
2578105197Ssam * to KMD by PF_KEY.
2579105197Ssam *
2580105197Ssam * OUT:	0	: succeed
2581105197Ssam *	others	: error number
2582105197Ssam */
2583105197Ssamstatic int
2584105197Ssamkey_spdexpire(sp)
2585105197Ssam	struct secpolicy *sp;
2586105197Ssam{
2587105197Ssam	struct mbuf *result = NULL, *m;
2588105197Ssam	int len;
2589105197Ssam	int error = -1;
2590105197Ssam	struct sadb_lifetime *lt;
2591105197Ssam
2592105197Ssam	/* XXX: Why do we lock ? */
2593105197Ssam
2594120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2595105197Ssam
2596105197Ssam	/* set msg header */
2597105197Ssam	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2598105197Ssam	if (!m) {
2599105197Ssam		error = ENOBUFS;
2600105197Ssam		goto fail;
2601105197Ssam	}
2602105197Ssam	result = m;
2603105197Ssam
2604105197Ssam	/* create lifetime extension (current and hard) */
2605105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2606105197Ssam	m = key_alloc_mbuf(len);
2607105197Ssam	if (!m || m->m_next) {	/*XXX*/
2608105197Ssam		if (m)
2609105197Ssam			m_freem(m);
2610105197Ssam		error = ENOBUFS;
2611105197Ssam		goto fail;
2612105197Ssam	}
2613105197Ssam	bzero(mtod(m, caddr_t), len);
2614105197Ssam	lt = mtod(m, struct sadb_lifetime *);
2615105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2616105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2617105197Ssam	lt->sadb_lifetime_allocations = 0;
2618105197Ssam	lt->sadb_lifetime_bytes = 0;
2619105197Ssam	lt->sadb_lifetime_addtime = sp->created;
2620105197Ssam	lt->sadb_lifetime_usetime = sp->lastused;
2621105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2622105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2623105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2624105197Ssam	lt->sadb_lifetime_allocations = 0;
2625105197Ssam	lt->sadb_lifetime_bytes = 0;
2626105197Ssam	lt->sadb_lifetime_addtime = sp->lifetime;
2627105197Ssam	lt->sadb_lifetime_usetime = sp->validtime;
2628105197Ssam	m_cat(result, m);
2629105197Ssam
2630194062Svanhu	/*
2631194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2632194062Svanhu	 * we are sending traffic endpoints.
2633194062Svanhu	 */
2634194062Svanhu
2635105197Ssam	/* set sadb_address for source */
2636105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2637105197Ssam	    &sp->spidx.src.sa,
2638105197Ssam	    sp->spidx.prefs, sp->spidx.ul_proto);
2639105197Ssam	if (!m) {
2640105197Ssam		error = ENOBUFS;
2641105197Ssam		goto fail;
2642105197Ssam	}
2643105197Ssam	m_cat(result, m);
2644105197Ssam
2645105197Ssam	/* set sadb_address for destination */
2646105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2647105197Ssam	    &sp->spidx.dst.sa,
2648105197Ssam	    sp->spidx.prefd, sp->spidx.ul_proto);
2649105197Ssam	if (!m) {
2650105197Ssam		error = ENOBUFS;
2651105197Ssam		goto fail;
2652105197Ssam	}
2653105197Ssam	m_cat(result, m);
2654105197Ssam
2655105197Ssam	/* set secpolicy */
2656105197Ssam	m = key_sp2msg(sp);
2657105197Ssam	if (!m) {
2658105197Ssam		error = ENOBUFS;
2659105197Ssam		goto fail;
2660105197Ssam	}
2661105197Ssam	m_cat(result, m);
2662105197Ssam
2663105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
2664105197Ssam		error = EINVAL;
2665105197Ssam		goto fail;
2666105197Ssam	}
2667105197Ssam
2668105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2669105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2670105197Ssam		if (result == NULL) {
2671105197Ssam			error = ENOBUFS;
2672105197Ssam			goto fail;
2673105197Ssam		}
2674105197Ssam	}
2675105197Ssam
2676105197Ssam	result->m_pkthdr.len = 0;
2677105197Ssam	for (m = result; m; m = m->m_next)
2678105197Ssam		result->m_pkthdr.len += m->m_len;
2679105197Ssam
2680105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2681105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2682105197Ssam
2683105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2684105197Ssam
2685105197Ssam fail:
2686105197Ssam	if (result)
2687105197Ssam		m_freem(result);
2688105197Ssam	return error;
2689105197Ssam}
2690105197Ssam
2691105197Ssam/* %%% SAD management */
2692105197Ssam/*
2693105197Ssam * allocating a memory for new SA head, and copy from the values of mhp.
2694105197Ssam * OUT:	NULL	: failure due to the lack of memory.
2695105197Ssam *	others	: pointer to new SA head.
2696105197Ssam */
2697105197Ssamstatic struct secashead *
2698105197Ssamkey_newsah(saidx)
2699105197Ssam	struct secasindex *saidx;
2700105197Ssam{
2701105197Ssam	struct secashead *newsah;
2702105197Ssam
2703120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2704105197Ssam
2705119643Ssam	newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2706105197Ssam	if (newsah != NULL) {
2707105197Ssam		int i;
2708105197Ssam		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2709105197Ssam			LIST_INIT(&newsah->savtree[i]);
2710105197Ssam		newsah->saidx = *saidx;
2711105197Ssam
2712105197Ssam		/* add to saidxtree */
2713105197Ssam		newsah->state = SADB_SASTATE_MATURE;
2714119643Ssam
2715120585Ssam		SAHTREE_LOCK();
2716181803Sbz		LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2717120585Ssam		SAHTREE_UNLOCK();
2718105197Ssam	}
2719105197Ssam	return(newsah);
2720105197Ssam}
2721105197Ssam
2722105197Ssam/*
2723105197Ssam * delete SA index and all SA registerd.
2724105197Ssam */
2725105197Ssamstatic void
2726105197Ssamkey_delsah(sah)
2727105197Ssam	struct secashead *sah;
2728105197Ssam{
2729105197Ssam	struct secasvar *sav, *nextsav;
2730120585Ssam	u_int stateidx;
2731105197Ssam	int zombie = 0;
2732105197Ssam
2733120585Ssam	IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2734120585Ssam	SAHTREE_LOCK_ASSERT();
2735105197Ssam
2736105197Ssam	/* searching all SA registerd in the secindex. */
2737105197Ssam	for (stateidx = 0;
2738185348Szec	     stateidx < _ARRAYLEN(saorder_state_any);
2739105197Ssam	     stateidx++) {
2740185348Szec		u_int state = saorder_state_any[stateidx];
2741120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2742105197Ssam			if (sav->refcnt == 0) {
2743105197Ssam				/* sanity check */
2744120585Ssam				KEY_CHKSASTATE(state, sav->state, __func__);
2745190071Svanhu				/*
2746190071Svanhu				 * do NOT call KEY_FREESAV here:
2747190071Svanhu				 * it will only delete the sav if refcnt == 1,
2748189962Svanhu				 * where we already know that refcnt == 0
2749189962Svanhu				 */
2750189962Svanhu				key_delsav(sav);
2751105197Ssam			} else {
2752105197Ssam				/* give up to delete this sa */
2753105197Ssam				zombie++;
2754105197Ssam			}
2755105197Ssam		}
2756105197Ssam	}
2757120585Ssam	if (!zombie) {		/* delete only if there are savs */
2758120585Ssam		/* remove from tree of SA index */
2759120585Ssam		if (__LIST_CHAINED(sah))
2760120585Ssam			LIST_REMOVE(sah, chain);
2761120585Ssam		if (sah->sa_route.ro_rt) {
2762120585Ssam			RTFREE(sah->sa_route.ro_rt);
2763120585Ssam			sah->sa_route.ro_rt = (struct rtentry *)NULL;
2764120585Ssam		}
2765120585Ssam		free(sah, M_IPSEC_SAH);
2766105197Ssam	}
2767105197Ssam}
2768105197Ssam
2769105197Ssam/*
2770105197Ssam * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2771105197Ssam * and copy the values of mhp into new buffer.
2772105197Ssam * When SAD message type is GETSPI:
2773105197Ssam *	to set sequence number from acq_seq++,
2774105197Ssam *	to set zero to SPI.
2775105197Ssam *	not to call key_setsava().
2776105197Ssam * OUT:	NULL	: fail
2777105197Ssam *	others	: pointer to new secasvar.
2778105197Ssam *
2779105197Ssam * does not modify mbuf.  does not free mbuf on error.
2780105197Ssam */
2781105197Ssamstatic struct secasvar *
2782105197Ssamkey_newsav(m, mhp, sah, errp, where, tag)
2783105197Ssam	struct mbuf *m;
2784105197Ssam	const struct sadb_msghdr *mhp;
2785105197Ssam	struct secashead *sah;
2786105197Ssam	int *errp;
2787105197Ssam	const char* where;
2788105197Ssam	int tag;
2789105197Ssam{
2790105197Ssam	struct secasvar *newsav;
2791105197Ssam	const struct sadb_sa *xsa;
2792105197Ssam
2793120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2794120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2795120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2796120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
2797105197Ssam
2798119643Ssam	newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2799105197Ssam	if (newsav == NULL) {
2800120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2801105197Ssam		*errp = ENOBUFS;
2802105197Ssam		goto done;
2803105197Ssam	}
2804105197Ssam
2805105197Ssam	switch (mhp->msg->sadb_msg_type) {
2806105197Ssam	case SADB_GETSPI:
2807105197Ssam		newsav->spi = 0;
2808105197Ssam
2809105197Ssam#ifdef IPSEC_DOSEQCHECK
2810105197Ssam		/* sync sequence number */
2811105197Ssam		if (mhp->msg->sadb_msg_seq == 0)
2812105197Ssam			newsav->seq =
2813181803Sbz				(V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2814105197Ssam		else
2815105197Ssam#endif
2816105197Ssam			newsav->seq = mhp->msg->sadb_msg_seq;
2817105197Ssam		break;
2818105197Ssam
2819105197Ssam	case SADB_ADD:
2820105197Ssam		/* sanity check */
2821105197Ssam		if (mhp->ext[SADB_EXT_SA] == NULL) {
2822119643Ssam			free(newsav, M_IPSEC_SA);
2823119643Ssam			newsav = NULL;
2824120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2825120585Ssam				__func__));
2826105197Ssam			*errp = EINVAL;
2827105197Ssam			goto done;
2828105197Ssam		}
2829105197Ssam		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2830105197Ssam		newsav->spi = xsa->sadb_sa_spi;
2831105197Ssam		newsav->seq = mhp->msg->sadb_msg_seq;
2832105197Ssam		break;
2833105197Ssam	default:
2834119643Ssam		free(newsav, M_IPSEC_SA);
2835119643Ssam		newsav = NULL;
2836105197Ssam		*errp = EINVAL;
2837105197Ssam		goto done;
2838105197Ssam	}
2839105197Ssam
2840119643Ssam
2841105197Ssam	/* copy sav values */
2842105197Ssam	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2843105197Ssam		*errp = key_setsaval(newsav, m, mhp);
2844105197Ssam		if (*errp) {
2845119643Ssam			free(newsav, M_IPSEC_SA);
2846119643Ssam			newsav = NULL;
2847105197Ssam			goto done;
2848105197Ssam		}
2849105197Ssam	}
2850105197Ssam
2851120585Ssam	SECASVAR_LOCK_INIT(newsav);
2852119643Ssam
2853105197Ssam	/* reset created */
2854105197Ssam	newsav->created = time_second;
2855105197Ssam	newsav->pid = mhp->msg->sadb_msg_pid;
2856105197Ssam
2857105197Ssam	/* add to satree */
2858105197Ssam	newsav->sah = sah;
2859158767Spjd	sa_initref(newsav);
2860105197Ssam	newsav->state = SADB_SASTATE_LARVAL;
2861119643Ssam
2862199398Svanhu	SAHTREE_LOCK();
2863105197Ssam	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2864105197Ssam			secasvar, chain);
2865199398Svanhu	SAHTREE_UNLOCK();
2866105197Ssamdone:
2867105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2868120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
2869105197Ssam			where, tag, newsav));
2870105197Ssam
2871105197Ssam	return newsav;
2872105197Ssam}
2873105197Ssam
2874105197Ssam/*
2875105197Ssam * free() SA variable entry.
2876105197Ssam */
2877105197Ssamstatic void
2878119643Ssamkey_cleansav(struct secasvar *sav)
2879105197Ssam{
2880117051Ssam	/*
2881117051Ssam	 * Cleanup xform state.  Note that zeroize'ing causes the
2882117051Ssam	 * keys to be cleared; otherwise we must do it ourself.
2883117051Ssam	 */
2884117051Ssam	if (sav->tdb_xform != NULL) {
2885117051Ssam		sav->tdb_xform->xf_zeroize(sav);
2886117051Ssam		sav->tdb_xform = NULL;
2887117051Ssam	} else {
2888120585Ssam		KASSERT(sav->iv == NULL, ("iv but no xform"));
2889117051Ssam		if (sav->key_auth != NULL)
2890157123Sgnn			bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2891117051Ssam		if (sav->key_enc != NULL)
2892157123Sgnn			bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2893117051Ssam	}
2894105197Ssam	if (sav->key_auth != NULL) {
2895157123Sgnn		if (sav->key_auth->key_data != NULL)
2896157123Sgnn			free(sav->key_auth->key_data, M_IPSEC_MISC);
2897119643Ssam		free(sav->key_auth, M_IPSEC_MISC);
2898105197Ssam		sav->key_auth = NULL;
2899105197Ssam	}
2900105197Ssam	if (sav->key_enc != NULL) {
2901157123Sgnn		if (sav->key_enc->key_data != NULL)
2902157123Sgnn			free(sav->key_enc->key_data, M_IPSEC_MISC);
2903119643Ssam		free(sav->key_enc, M_IPSEC_MISC);
2904105197Ssam		sav->key_enc = NULL;
2905105197Ssam	}
2906105197Ssam	if (sav->sched) {
2907105197Ssam		bzero(sav->sched, sav->schedlen);
2908119643Ssam		free(sav->sched, M_IPSEC_MISC);
2909105197Ssam		sav->sched = NULL;
2910105197Ssam	}
2911105197Ssam	if (sav->replay != NULL) {
2912119643Ssam		free(sav->replay, M_IPSEC_MISC);
2913105197Ssam		sav->replay = NULL;
2914105197Ssam	}
2915105197Ssam	if (sav->lft_c != NULL) {
2916119643Ssam		free(sav->lft_c, M_IPSEC_MISC);
2917105197Ssam		sav->lft_c = NULL;
2918105197Ssam	}
2919105197Ssam	if (sav->lft_h != NULL) {
2920119643Ssam		free(sav->lft_h, M_IPSEC_MISC);
2921105197Ssam		sav->lft_h = NULL;
2922105197Ssam	}
2923105197Ssam	if (sav->lft_s != NULL) {
2924119643Ssam		free(sav->lft_s, M_IPSEC_MISC);
2925105197Ssam		sav->lft_s = NULL;
2926105197Ssam	}
2927119643Ssam}
2928105197Ssam
2929119643Ssam/*
2930119643Ssam * free() SA variable entry.
2931119643Ssam */
2932119643Ssamstatic void
2933119643Ssamkey_delsav(sav)
2934119643Ssam	struct secasvar *sav;
2935119643Ssam{
2936120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
2937120585Ssam	IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2938105197Ssam
2939119643Ssam	/* remove from SA header */
2940119643Ssam	if (__LIST_CHAINED(sav))
2941119643Ssam		LIST_REMOVE(sav, chain);
2942119643Ssam	key_cleansav(sav);
2943120585Ssam	SECASVAR_LOCK_DESTROY(sav);
2944119643Ssam	free(sav, M_IPSEC_SA);
2945105197Ssam}
2946105197Ssam
2947105197Ssam/*
2948105197Ssam * search SAD.
2949105197Ssam * OUT:
2950105197Ssam *	NULL	: not found
2951105197Ssam *	others	: found, pointer to a SA.
2952105197Ssam */
2953105197Ssamstatic struct secashead *
2954105197Ssamkey_getsah(saidx)
2955105197Ssam	struct secasindex *saidx;
2956105197Ssam{
2957105197Ssam	struct secashead *sah;
2958105197Ssam
2959120585Ssam	SAHTREE_LOCK();
2960181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
2961105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
2962105197Ssam			continue;
2963105197Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2964119643Ssam			break;
2965105197Ssam	}
2966120585Ssam	SAHTREE_UNLOCK();
2967105197Ssam
2968119643Ssam	return sah;
2969105197Ssam}
2970105197Ssam
2971105197Ssam/*
2972105197Ssam * check not to be duplicated SPI.
2973105197Ssam * NOTE: this function is too slow due to searching all SAD.
2974105197Ssam * OUT:
2975105197Ssam *	NULL	: not found
2976105197Ssam *	others	: found, pointer to a SA.
2977105197Ssam */
2978105197Ssamstatic struct secasvar *
2979105197Ssamkey_checkspidup(saidx, spi)
2980105197Ssam	struct secasindex *saidx;
2981105197Ssam	u_int32_t spi;
2982105197Ssam{
2983105197Ssam	struct secashead *sah;
2984105197Ssam	struct secasvar *sav;
2985105197Ssam
2986105197Ssam	/* check address family */
2987105197Ssam	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2988120585Ssam		ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2989120585Ssam			__func__));
2990105197Ssam		return NULL;
2991105197Ssam	}
2992105197Ssam
2993119643Ssam	sav = NULL;
2994105197Ssam	/* check all SAD */
2995120585Ssam	SAHTREE_LOCK();
2996181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
2997105197Ssam		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2998105197Ssam			continue;
2999105197Ssam		sav = key_getsavbyspi(sah, spi);
3000105197Ssam		if (sav != NULL)
3001119643Ssam			break;
3002105197Ssam	}
3003120585Ssam	SAHTREE_UNLOCK();
3004105197Ssam
3005119643Ssam	return sav;
3006105197Ssam}
3007105197Ssam
3008105197Ssam/*
3009105197Ssam * search SAD litmited alive SA, protocol, SPI.
3010105197Ssam * OUT:
3011105197Ssam *	NULL	: not found
3012105197Ssam *	others	: found, pointer to a SA.
3013105197Ssam */
3014105197Ssamstatic struct secasvar *
3015105197Ssamkey_getsavbyspi(sah, spi)
3016105197Ssam	struct secashead *sah;
3017105197Ssam	u_int32_t spi;
3018105197Ssam{
3019105197Ssam	struct secasvar *sav;
3020105197Ssam	u_int stateidx, state;
3021105197Ssam
3022119643Ssam	sav = NULL;
3023120585Ssam	SAHTREE_LOCK_ASSERT();
3024105197Ssam	/* search all status */
3025105197Ssam	for (stateidx = 0;
3026185348Szec	     stateidx < _ARRAYLEN(saorder_state_alive);
3027105197Ssam	     stateidx++) {
3028105197Ssam
3029185348Szec		state = saorder_state_alive[stateidx];
3030105197Ssam		LIST_FOREACH(sav, &sah->savtree[state], chain) {
3031105197Ssam
3032105197Ssam			/* sanity check */
3033105197Ssam			if (sav->state != state) {
3034120585Ssam				ipseclog((LOG_DEBUG, "%s: "
3035105197Ssam				    "invalid sav->state (queue: %d SA: %d)\n",
3036120585Ssam				    __func__, state, sav->state));
3037105197Ssam				continue;
3038105197Ssam			}
3039105197Ssam
3040105197Ssam			if (sav->spi == spi)
3041128859Ssam				return sav;
3042105197Ssam		}
3043105197Ssam	}
3044105197Ssam
3045128859Ssam	return NULL;
3046105197Ssam}
3047105197Ssam
3048105197Ssam/*
3049105197Ssam * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3050105197Ssam * You must update these if need.
3051105197Ssam * OUT:	0:	success.
3052105197Ssam *	!0:	failure.
3053105197Ssam *
3054105197Ssam * does not modify mbuf.  does not free mbuf on error.
3055105197Ssam */
3056105197Ssamstatic int
3057105197Ssamkey_setsaval(sav, m, mhp)
3058105197Ssam	struct secasvar *sav;
3059105197Ssam	struct mbuf *m;
3060105197Ssam	const struct sadb_msghdr *mhp;
3061105197Ssam{
3062105197Ssam	int error = 0;
3063105197Ssam
3064120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
3065120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3066120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3067105197Ssam
3068105197Ssam	/* initialization */
3069105197Ssam	sav->replay = NULL;
3070105197Ssam	sav->key_auth = NULL;
3071105197Ssam	sav->key_enc = NULL;
3072105197Ssam	sav->sched = NULL;
3073105197Ssam	sav->schedlen = 0;
3074105197Ssam	sav->iv = NULL;
3075105197Ssam	sav->lft_c = NULL;
3076105197Ssam	sav->lft_h = NULL;
3077105197Ssam	sav->lft_s = NULL;
3078105197Ssam	sav->tdb_xform = NULL;		/* transform */
3079105197Ssam	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
3080105197Ssam	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
3081105197Ssam	sav->tdb_compalgxform = NULL;	/* compression algorithm */
3082194062Svanhu	/*  Initialize even if NAT-T not compiled in: */
3083194062Svanhu	sav->natt_type = 0;
3084194062Svanhu	sav->natt_esp_frag_len = 0;
3085105197Ssam
3086105197Ssam	/* SA */
3087105197Ssam	if (mhp->ext[SADB_EXT_SA] != NULL) {
3088105197Ssam		const struct sadb_sa *sa0;
3089105197Ssam
3090105197Ssam		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3091105197Ssam		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3092105197Ssam			error = EINVAL;
3093105197Ssam			goto fail;
3094105197Ssam		}
3095105197Ssam
3096105197Ssam		sav->alg_auth = sa0->sadb_sa_auth;
3097105197Ssam		sav->alg_enc = sa0->sadb_sa_encrypt;
3098105197Ssam		sav->flags = sa0->sadb_sa_flags;
3099105197Ssam
3100105197Ssam		/* replay window */
3101105197Ssam		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3102105197Ssam			sav->replay = (struct secreplay *)
3103119643Ssam				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3104105197Ssam			if (sav->replay == NULL) {
3105120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3106120585Ssam					__func__));
3107105197Ssam				error = ENOBUFS;
3108105197Ssam				goto fail;
3109105197Ssam			}
3110105197Ssam			if (sa0->sadb_sa_replay != 0)
3111105197Ssam				sav->replay->bitmap = (caddr_t)(sav->replay+1);
3112105197Ssam			sav->replay->wsize = sa0->sadb_sa_replay;
3113105197Ssam		}
3114105197Ssam	}
3115105197Ssam
3116105197Ssam	/* Authentication keys */
3117105197Ssam	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3118105197Ssam		const struct sadb_key *key0;
3119105197Ssam		int len;
3120105197Ssam
3121105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3122105197Ssam		len = mhp->extlen[SADB_EXT_KEY_AUTH];
3123105197Ssam
3124105197Ssam		error = 0;
3125105197Ssam		if (len < sizeof(*key0)) {
3126105197Ssam			error = EINVAL;
3127105197Ssam			goto fail;
3128105197Ssam		}
3129105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3130105197Ssam		case SADB_SATYPE_AH:
3131105197Ssam		case SADB_SATYPE_ESP:
3132125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3133105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3134105197Ssam			    sav->alg_auth != SADB_X_AALG_NULL)
3135105197Ssam				error = EINVAL;
3136105197Ssam			break;
3137105197Ssam		case SADB_X_SATYPE_IPCOMP:
3138105197Ssam		default:
3139105197Ssam			error = EINVAL;
3140105197Ssam			break;
3141105197Ssam		}
3142105197Ssam		if (error) {
3143120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3144120585Ssam				__func__));
3145105197Ssam			goto fail;
3146105197Ssam		}
3147105197Ssam
3148157123Sgnn		sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3149157123Sgnn								M_IPSEC_MISC);
3150157123Sgnn		if (sav->key_auth == NULL ) {
3151157123Sgnn			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3152157123Sgnn				  __func__));
3153105197Ssam			error = ENOBUFS;
3154105197Ssam			goto fail;
3155105197Ssam		}
3156105197Ssam	}
3157105197Ssam
3158105197Ssam	/* Encryption key */
3159105197Ssam	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3160105197Ssam		const struct sadb_key *key0;
3161105197Ssam		int len;
3162105197Ssam
3163105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3164105197Ssam		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3165105197Ssam
3166105197Ssam		error = 0;
3167105197Ssam		if (len < sizeof(*key0)) {
3168105197Ssam			error = EINVAL;
3169105197Ssam			goto fail;
3170105197Ssam		}
3171105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3172105197Ssam		case SADB_SATYPE_ESP:
3173105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3174105197Ssam			    sav->alg_enc != SADB_EALG_NULL) {
3175105197Ssam				error = EINVAL;
3176105197Ssam				break;
3177105197Ssam			}
3178157123Sgnn			sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3179157123Sgnn								       len,
3180157123Sgnn								       M_IPSEC_MISC);
3181105197Ssam			if (sav->key_enc == NULL) {
3182120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3183120585Ssam					__func__));
3184105197Ssam				error = ENOBUFS;
3185105197Ssam				goto fail;
3186105197Ssam			}
3187105197Ssam			break;
3188105197Ssam		case SADB_X_SATYPE_IPCOMP:
3189105197Ssam			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3190105197Ssam				error = EINVAL;
3191105197Ssam			sav->key_enc = NULL;	/*just in case*/
3192105197Ssam			break;
3193105197Ssam		case SADB_SATYPE_AH:
3194125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3195105197Ssam		default:
3196105197Ssam			error = EINVAL;
3197105197Ssam			break;
3198105197Ssam		}
3199105197Ssam		if (error) {
3200120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3201120585Ssam				__func__));
3202105197Ssam			goto fail;
3203105197Ssam		}
3204105197Ssam	}
3205105197Ssam
3206105197Ssam	/* set iv */
3207105197Ssam	sav->ivlen = 0;
3208105197Ssam
3209105197Ssam	switch (mhp->msg->sadb_msg_satype) {
3210105197Ssam	case SADB_SATYPE_AH:
3211105197Ssam		error = xform_init(sav, XF_AH);
3212105197Ssam		break;
3213105197Ssam	case SADB_SATYPE_ESP:
3214105197Ssam		error = xform_init(sav, XF_ESP);
3215105197Ssam		break;
3216105197Ssam	case SADB_X_SATYPE_IPCOMP:
3217105197Ssam		error = xform_init(sav, XF_IPCOMP);
3218105197Ssam		break;
3219125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
3220125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3221125680Sbms		break;
3222105197Ssam	}
3223105197Ssam	if (error) {
3224120585Ssam		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3225120585Ssam		        __func__, mhp->msg->sadb_msg_satype));
3226105197Ssam		goto fail;
3227105197Ssam	}
3228105197Ssam
3229105197Ssam	/* reset created */
3230105197Ssam	sav->created = time_second;
3231105197Ssam
3232105197Ssam	/* make lifetime for CURRENT */
3233176743Sbz	sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3234105197Ssam	if (sav->lft_c == NULL) {
3235120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3236105197Ssam		error = ENOBUFS;
3237105197Ssam		goto fail;
3238105197Ssam	}
3239105197Ssam
3240157123Sgnn	sav->lft_c->allocations = 0;
3241157123Sgnn	sav->lft_c->bytes = 0;
3242157123Sgnn	sav->lft_c->addtime = time_second;
3243157123Sgnn	sav->lft_c->usetime = 0;
3244105197Ssam
3245105197Ssam	/* lifetimes for HARD and SOFT */
3246105197Ssam    {
3247105197Ssam	const struct sadb_lifetime *lft0;
3248105197Ssam
3249105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3250105197Ssam	if (lft0 != NULL) {
3251105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3252105197Ssam			error = EINVAL;
3253105197Ssam			goto fail;
3254105197Ssam		}
3255157123Sgnn		sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3256105197Ssam		if (sav->lft_h == NULL) {
3257120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3258105197Ssam			error = ENOBUFS;
3259105197Ssam			goto fail;
3260105197Ssam		}
3261105197Ssam		/* to be initialize ? */
3262105197Ssam	}
3263105197Ssam
3264105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3265105197Ssam	if (lft0 != NULL) {
3266105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3267105197Ssam			error = EINVAL;
3268105197Ssam			goto fail;
3269105197Ssam		}
3270157123Sgnn		sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3271105197Ssam		if (sav->lft_s == NULL) {
3272120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3273105197Ssam			error = ENOBUFS;
3274105197Ssam			goto fail;
3275105197Ssam		}
3276105197Ssam		/* to be initialize ? */
3277105197Ssam	}
3278105197Ssam    }
3279105197Ssam
3280105197Ssam	return 0;
3281105197Ssam
3282105197Ssam fail:
3283105197Ssam	/* initialization */
3284119643Ssam	key_cleansav(sav);
3285105197Ssam
3286105197Ssam	return error;
3287105197Ssam}
3288105197Ssam
3289105197Ssam/*
3290105197Ssam * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3291105197Ssam * OUT:	0:	valid
3292105197Ssam *	other:	errno
3293105197Ssam */
3294105197Ssamstatic int
3295119643Ssamkey_mature(struct secasvar *sav)
3296105197Ssam{
3297105197Ssam	int error;
3298105197Ssam
3299105197Ssam	/* check SPI value */
3300105197Ssam	switch (sav->sah->saidx.proto) {
3301105197Ssam	case IPPROTO_ESP:
3302105197Ssam	case IPPROTO_AH:
3303170823Sbz		/*
3304170823Sbz		 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3305170823Sbz		 * 1-255 reserved by IANA for future use,
3306170823Sbz		 * 0 for implementation specific, local use.
3307170823Sbz		 */
3308170823Sbz		if (ntohl(sav->spi) <= 255) {
3309120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3310120585Ssam			    __func__, (u_int32_t)ntohl(sav->spi)));
3311105197Ssam			return EINVAL;
3312105197Ssam		}
3313105197Ssam		break;
3314105197Ssam	}
3315105197Ssam
3316105197Ssam	/* check satype */
3317105197Ssam	switch (sav->sah->saidx.proto) {
3318105197Ssam	case IPPROTO_ESP:
3319105197Ssam		/* check flags */
3320105197Ssam		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3321105197Ssam		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3322120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3323120585Ssam				"given to old-esp.\n", __func__));
3324105197Ssam			return EINVAL;
3325105197Ssam		}
3326105197Ssam		error = xform_init(sav, XF_ESP);
3327105197Ssam		break;
3328105197Ssam	case IPPROTO_AH:
3329105197Ssam		/* check flags */
3330105197Ssam		if (sav->flags & SADB_X_EXT_DERIV) {
3331120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3332120585Ssam				"given to AH SA.\n", __func__));
3333105197Ssam			return EINVAL;
3334105197Ssam		}
3335105197Ssam		if (sav->alg_enc != SADB_EALG_NONE) {
3336120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3337120585Ssam				"mismated.\n", __func__));
3338105197Ssam			return(EINVAL);
3339105197Ssam		}
3340105197Ssam		error = xform_init(sav, XF_AH);
3341105197Ssam		break;
3342105197Ssam	case IPPROTO_IPCOMP:
3343105197Ssam		if (sav->alg_auth != SADB_AALG_NONE) {
3344120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3345120585Ssam				"mismated.\n", __func__));
3346105197Ssam			return(EINVAL);
3347105197Ssam		}
3348105197Ssam		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3349105197Ssam		 && ntohl(sav->spi) >= 0x10000) {
3350120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3351120585Ssam				__func__));
3352105197Ssam			return(EINVAL);
3353105197Ssam		}
3354105197Ssam		error = xform_init(sav, XF_IPCOMP);
3355105197Ssam		break;
3356125680Sbms	case IPPROTO_TCP:
3357125680Sbms		if (sav->alg_enc != SADB_EALG_NONE) {
3358125680Sbms			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3359125680Sbms				"mismated.\n", __func__));
3360125680Sbms			return(EINVAL);
3361125680Sbms		}
3362125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3363125680Sbms		break;
3364105197Ssam	default:
3365120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3366105197Ssam		error = EPROTONOSUPPORT;
3367105197Ssam		break;
3368105197Ssam	}
3369119643Ssam	if (error == 0) {
3370120585Ssam		SAHTREE_LOCK();
3371105197Ssam		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3372120585Ssam		SAHTREE_UNLOCK();
3373119643Ssam	}
3374105197Ssam	return (error);
3375105197Ssam}
3376105197Ssam
3377105197Ssam/*
3378105197Ssam * subroutine for SADB_GET and SADB_DUMP.
3379105197Ssam */
3380105197Ssamstatic struct mbuf *
3381189004Srdivackykey_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3382189004Srdivacky    u_int32_t seq, u_int32_t pid)
3383105197Ssam{
3384105197Ssam	struct mbuf *result = NULL, *tres = NULL, *m;
3385105197Ssam	int i;
3386105197Ssam	int dumporder[] = {
3387105197Ssam		SADB_EXT_SA, SADB_X_EXT_SA2,
3388105197Ssam		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3389105197Ssam		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3390105197Ssam		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3391105197Ssam		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3392105197Ssam		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3393194062Svanhu#ifdef IPSEC_NAT_T
3394194062Svanhu		SADB_X_EXT_NAT_T_TYPE,
3395194062Svanhu		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3396194062Svanhu		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3397194062Svanhu		SADB_X_EXT_NAT_T_FRAG,
3398194062Svanhu#endif
3399105197Ssam	};
3400105197Ssam
3401105197Ssam	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3402105197Ssam	if (m == NULL)
3403105197Ssam		goto fail;
3404105197Ssam	result = m;
3405105197Ssam
3406105197Ssam	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3407105197Ssam		m = NULL;
3408105197Ssam		switch (dumporder[i]) {
3409105197Ssam		case SADB_EXT_SA:
3410105197Ssam			m = key_setsadbsa(sav);
3411105197Ssam			if (!m)
3412105197Ssam				goto fail;
3413105197Ssam			break;
3414105197Ssam
3415105197Ssam		case SADB_X_EXT_SA2:
3416105197Ssam			m = key_setsadbxsa2(sav->sah->saidx.mode,
3417105197Ssam					sav->replay ? sav->replay->count : 0,
3418105197Ssam					sav->sah->saidx.reqid);
3419105197Ssam			if (!m)
3420105197Ssam				goto fail;
3421105197Ssam			break;
3422105197Ssam
3423105197Ssam		case SADB_EXT_ADDRESS_SRC:
3424105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3425105197Ssam			    &sav->sah->saidx.src.sa,
3426105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3427105197Ssam			if (!m)
3428105197Ssam				goto fail;
3429105197Ssam			break;
3430105197Ssam
3431105197Ssam		case SADB_EXT_ADDRESS_DST:
3432105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3433105197Ssam			    &sav->sah->saidx.dst.sa,
3434105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3435105197Ssam			if (!m)
3436105197Ssam				goto fail;
3437105197Ssam			break;
3438105197Ssam
3439105197Ssam		case SADB_EXT_KEY_AUTH:
3440105197Ssam			if (!sav->key_auth)
3441105197Ssam				continue;
3442157123Sgnn			m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3443157123Sgnn			if (!m)
3444157123Sgnn				goto fail;
3445105197Ssam			break;
3446105197Ssam
3447105197Ssam		case SADB_EXT_KEY_ENCRYPT:
3448105197Ssam			if (!sav->key_enc)
3449105197Ssam				continue;
3450157123Sgnn			m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3451157123Sgnn			if (!m)
3452157123Sgnn				goto fail;
3453105197Ssam			break;
3454105197Ssam
3455105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
3456105197Ssam			if (!sav->lft_c)
3457105197Ssam				continue;
3458157123Sgnn			m = key_setlifetime(sav->lft_c,
3459157123Sgnn					    SADB_EXT_LIFETIME_CURRENT);
3460157123Sgnn			if (!m)
3461157123Sgnn				goto fail;
3462105197Ssam			break;
3463105197Ssam
3464105197Ssam		case SADB_EXT_LIFETIME_HARD:
3465105197Ssam			if (!sav->lft_h)
3466105197Ssam				continue;
3467157123Sgnn			m = key_setlifetime(sav->lft_h,
3468157123Sgnn					    SADB_EXT_LIFETIME_HARD);
3469157123Sgnn			if (!m)
3470157123Sgnn				goto fail;
3471105197Ssam			break;
3472105197Ssam
3473105197Ssam		case SADB_EXT_LIFETIME_SOFT:
3474105197Ssam			if (!sav->lft_s)
3475105197Ssam				continue;
3476177554Sbz			m = key_setlifetime(sav->lft_s,
3477157123Sgnn					    SADB_EXT_LIFETIME_SOFT);
3478157123Sgnn
3479157123Sgnn			if (!m)
3480157123Sgnn				goto fail;
3481105197Ssam			break;
3482105197Ssam
3483194062Svanhu#ifdef IPSEC_NAT_T
3484194062Svanhu		case SADB_X_EXT_NAT_T_TYPE:
3485194062Svanhu			m = key_setsadbxtype(sav->natt_type);
3486194062Svanhu			if (!m)
3487194062Svanhu				goto fail;
3488194062Svanhu			break;
3489194062Svanhu
3490194062Svanhu		case SADB_X_EXT_NAT_T_DPORT:
3491194062Svanhu			m = key_setsadbxport(
3492194062Svanhu			    KEY_PORTFROMSADDR(&sav->sah->saidx.dst),
3493194062Svanhu			    SADB_X_EXT_NAT_T_DPORT);
3494194062Svanhu			if (!m)
3495194062Svanhu				goto fail;
3496194062Svanhu			break;
3497194062Svanhu
3498194062Svanhu		case SADB_X_EXT_NAT_T_SPORT:
3499194062Svanhu			m = key_setsadbxport(
3500194062Svanhu			    KEY_PORTFROMSADDR(&sav->sah->saidx.src),
3501194062Svanhu			    SADB_X_EXT_NAT_T_SPORT);
3502194062Svanhu			if (!m)
3503194062Svanhu				goto fail;
3504194062Svanhu			break;
3505194062Svanhu
3506194062Svanhu		case SADB_X_EXT_NAT_T_OAI:
3507194062Svanhu		case SADB_X_EXT_NAT_T_OAR:
3508194062Svanhu		case SADB_X_EXT_NAT_T_FRAG:
3509194062Svanhu			/* We do not (yet) support those. */
3510194062Svanhu			continue;
3511194062Svanhu#endif
3512194062Svanhu
3513105197Ssam		case SADB_EXT_ADDRESS_PROXY:
3514105197Ssam		case SADB_EXT_IDENTITY_SRC:
3515105197Ssam		case SADB_EXT_IDENTITY_DST:
3516105197Ssam			/* XXX: should we brought from SPD ? */
3517105197Ssam		case SADB_EXT_SENSITIVITY:
3518105197Ssam		default:
3519105197Ssam			continue;
3520105197Ssam		}
3521105197Ssam
3522157123Sgnn		if (!m)
3523105197Ssam			goto fail;
3524105197Ssam		if (tres)
3525105197Ssam			m_cat(m, tres);
3526105197Ssam		tres = m;
3527157123Sgnn
3528105197Ssam	}
3529105197Ssam
3530105197Ssam	m_cat(result, tres);
3531105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
3532105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
3533105197Ssam		if (result == NULL)
3534105197Ssam			goto fail;
3535105197Ssam	}
3536105197Ssam
3537105197Ssam	result->m_pkthdr.len = 0;
3538105197Ssam	for (m = result; m; m = m->m_next)
3539105197Ssam		result->m_pkthdr.len += m->m_len;
3540105197Ssam
3541105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
3542105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
3543105197Ssam
3544105197Ssam	return result;
3545105197Ssam
3546105197Ssamfail:
3547105197Ssam	m_freem(result);
3548105197Ssam	m_freem(tres);
3549105197Ssam	return NULL;
3550105197Ssam}
3551105197Ssam
3552105197Ssam/*
3553105197Ssam * set data into sadb_msg.
3554105197Ssam */
3555105197Ssamstatic struct mbuf *
3556189004Srdivackykey_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3557189004Srdivacky    pid_t pid, u_int16_t reserved)
3558105197Ssam{
3559105197Ssam	struct mbuf *m;
3560105197Ssam	struct sadb_msg *p;
3561105197Ssam	int len;
3562105197Ssam
3563105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3564105197Ssam	if (len > MCLBYTES)
3565105197Ssam		return NULL;
3566111119Simp	MGETHDR(m, M_DONTWAIT, MT_DATA);
3567105197Ssam	if (m && len > MHLEN) {
3568111119Simp		MCLGET(m, M_DONTWAIT);
3569105197Ssam		if ((m->m_flags & M_EXT) == 0) {
3570105197Ssam			m_freem(m);
3571105197Ssam			m = NULL;
3572105197Ssam		}
3573105197Ssam	}
3574105197Ssam	if (!m)
3575105197Ssam		return NULL;
3576105197Ssam	m->m_pkthdr.len = m->m_len = len;
3577105197Ssam	m->m_next = NULL;
3578105197Ssam
3579105197Ssam	p = mtod(m, struct sadb_msg *);
3580105197Ssam
3581105197Ssam	bzero(p, len);
3582105197Ssam	p->sadb_msg_version = PF_KEY_V2;
3583105197Ssam	p->sadb_msg_type = type;
3584105197Ssam	p->sadb_msg_errno = 0;
3585105197Ssam	p->sadb_msg_satype = satype;
3586105197Ssam	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3587105197Ssam	p->sadb_msg_reserved = reserved;
3588105197Ssam	p->sadb_msg_seq = seq;
3589105197Ssam	p->sadb_msg_pid = (u_int32_t)pid;
3590105197Ssam
3591105197Ssam	return m;
3592105197Ssam}
3593105197Ssam
3594105197Ssam/*
3595105197Ssam * copy secasvar data into sadb_address.
3596105197Ssam */
3597105197Ssamstatic struct mbuf *
3598105197Ssamkey_setsadbsa(sav)
3599105197Ssam	struct secasvar *sav;
3600105197Ssam{
3601105197Ssam	struct mbuf *m;
3602105197Ssam	struct sadb_sa *p;
3603105197Ssam	int len;
3604105197Ssam
3605105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3606105197Ssam	m = key_alloc_mbuf(len);
3607105197Ssam	if (!m || m->m_next) {	/*XXX*/
3608105197Ssam		if (m)
3609105197Ssam			m_freem(m);
3610105197Ssam		return NULL;
3611105197Ssam	}
3612105197Ssam
3613105197Ssam	p = mtod(m, struct sadb_sa *);
3614105197Ssam
3615105197Ssam	bzero(p, len);
3616105197Ssam	p->sadb_sa_len = PFKEY_UNIT64(len);
3617105197Ssam	p->sadb_sa_exttype = SADB_EXT_SA;
3618105197Ssam	p->sadb_sa_spi = sav->spi;
3619105197Ssam	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3620105197Ssam	p->sadb_sa_state = sav->state;
3621105197Ssam	p->sadb_sa_auth = sav->alg_auth;
3622105197Ssam	p->sadb_sa_encrypt = sav->alg_enc;
3623105197Ssam	p->sadb_sa_flags = sav->flags;
3624105197Ssam
3625105197Ssam	return m;
3626105197Ssam}
3627105197Ssam
3628105197Ssam/*
3629105197Ssam * set data into sadb_address.
3630105197Ssam */
3631105197Ssamstatic struct mbuf *
3632189004Srdivackykey_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto)
3633105197Ssam{
3634105197Ssam	struct mbuf *m;
3635105197Ssam	struct sadb_address *p;
3636105197Ssam	size_t len;
3637105197Ssam
3638105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3639105197Ssam	    PFKEY_ALIGN8(saddr->sa_len);
3640105197Ssam	m = key_alloc_mbuf(len);
3641105197Ssam	if (!m || m->m_next) {	/*XXX*/
3642105197Ssam		if (m)
3643105197Ssam			m_freem(m);
3644105197Ssam		return NULL;
3645105197Ssam	}
3646105197Ssam
3647105197Ssam	p = mtod(m, struct sadb_address *);
3648105197Ssam
3649105197Ssam	bzero(p, len);
3650105197Ssam	p->sadb_address_len = PFKEY_UNIT64(len);
3651105197Ssam	p->sadb_address_exttype = exttype;
3652105197Ssam	p->sadb_address_proto = ul_proto;
3653105197Ssam	if (prefixlen == FULLMASK) {
3654105197Ssam		switch (saddr->sa_family) {
3655105197Ssam		case AF_INET:
3656105197Ssam			prefixlen = sizeof(struct in_addr) << 3;
3657105197Ssam			break;
3658105197Ssam		case AF_INET6:
3659105197Ssam			prefixlen = sizeof(struct in6_addr) << 3;
3660105197Ssam			break;
3661105197Ssam		default:
3662105197Ssam			; /*XXX*/
3663105197Ssam		}
3664105197Ssam	}
3665105197Ssam	p->sadb_address_prefixlen = prefixlen;
3666105197Ssam	p->sadb_address_reserved = 0;
3667105197Ssam
3668105197Ssam	bcopy(saddr,
3669105197Ssam	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3670105197Ssam	    saddr->sa_len);
3671105197Ssam
3672105197Ssam	return m;
3673105197Ssam}
3674105197Ssam
3675105197Ssam/*
3676105197Ssam * set data into sadb_x_sa2.
3677105197Ssam */
3678105197Ssamstatic struct mbuf *
3679189004Srdivackykey_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3680105197Ssam{
3681105197Ssam	struct mbuf *m;
3682105197Ssam	struct sadb_x_sa2 *p;
3683105197Ssam	size_t len;
3684105197Ssam
3685105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3686105197Ssam	m = key_alloc_mbuf(len);
3687105197Ssam	if (!m || m->m_next) {	/*XXX*/
3688105197Ssam		if (m)
3689105197Ssam			m_freem(m);
3690105197Ssam		return NULL;
3691105197Ssam	}
3692105197Ssam
3693105197Ssam	p = mtod(m, struct sadb_x_sa2 *);
3694105197Ssam
3695105197Ssam	bzero(p, len);
3696105197Ssam	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3697105197Ssam	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3698105197Ssam	p->sadb_x_sa2_mode = mode;
3699105197Ssam	p->sadb_x_sa2_reserved1 = 0;
3700105197Ssam	p->sadb_x_sa2_reserved2 = 0;
3701105197Ssam	p->sadb_x_sa2_sequence = seq;
3702105197Ssam	p->sadb_x_sa2_reqid = reqid;
3703105197Ssam
3704105197Ssam	return m;
3705105197Ssam}
3706105197Ssam
3707194062Svanhu#ifdef IPSEC_NAT_T
3708105197Ssam/*
3709194062Svanhu * Set a type in sadb_x_nat_t_type.
3710194062Svanhu */
3711194062Svanhustatic struct mbuf *
3712194062Svanhukey_setsadbxtype(u_int16_t type)
3713194062Svanhu{
3714194062Svanhu	struct mbuf *m;
3715194062Svanhu	size_t len;
3716194062Svanhu	struct sadb_x_nat_t_type *p;
3717194062Svanhu
3718194062Svanhu	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3719194062Svanhu
3720194062Svanhu	m = key_alloc_mbuf(len);
3721194062Svanhu	if (!m || m->m_next) {	/*XXX*/
3722194062Svanhu		if (m)
3723194062Svanhu			m_freem(m);
3724194062Svanhu		return (NULL);
3725194062Svanhu	}
3726194062Svanhu
3727194062Svanhu	p = mtod(m, struct sadb_x_nat_t_type *);
3728194062Svanhu
3729194062Svanhu	bzero(p, len);
3730194062Svanhu	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3731194062Svanhu	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3732194062Svanhu	p->sadb_x_nat_t_type_type = type;
3733194062Svanhu
3734194062Svanhu	return (m);
3735194062Svanhu}
3736194062Svanhu/*
3737194062Svanhu * Set a port in sadb_x_nat_t_port.
3738194062Svanhu * In contrast to default RFC 2367 behaviour, port is in network byte order.
3739194062Svanhu */
3740194062Svanhustatic struct mbuf *
3741194062Svanhukey_setsadbxport(u_int16_t port, u_int16_t type)
3742194062Svanhu{
3743194062Svanhu	struct mbuf *m;
3744194062Svanhu	size_t len;
3745194062Svanhu	struct sadb_x_nat_t_port *p;
3746194062Svanhu
3747194062Svanhu	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3748194062Svanhu
3749194062Svanhu	m = key_alloc_mbuf(len);
3750194062Svanhu	if (!m || m->m_next) {	/*XXX*/
3751194062Svanhu		if (m)
3752194062Svanhu			m_freem(m);
3753194062Svanhu		return (NULL);
3754194062Svanhu	}
3755194062Svanhu
3756194062Svanhu	p = mtod(m, struct sadb_x_nat_t_port *);
3757194062Svanhu
3758194062Svanhu	bzero(p, len);
3759194062Svanhu	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3760194062Svanhu	p->sadb_x_nat_t_port_exttype = type;
3761194062Svanhu	p->sadb_x_nat_t_port_port = port;
3762194062Svanhu
3763194062Svanhu	return (m);
3764194062Svanhu}
3765194062Svanhu
3766194062Svanhu/*
3767194062Svanhu * Get port from sockaddr. Port is in network byte order.
3768194062Svanhu */
3769194062Svanhuu_int16_t
3770194062Svanhukey_portfromsaddr(struct sockaddr *sa)
3771194062Svanhu{
3772194062Svanhu
3773194062Svanhu	switch (sa->sa_family) {
3774194062Svanhu#ifdef INET
3775194062Svanhu	case AF_INET:
3776194062Svanhu		return ((struct sockaddr_in *)sa)->sin_port;
3777194062Svanhu#endif
3778194062Svanhu#ifdef INET6
3779194062Svanhu	case AF_INET6:
3780194062Svanhu		return ((struct sockaddr_in6 *)sa)->sin6_port;
3781194062Svanhu#endif
3782194062Svanhu	}
3783194062Svanhu	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
3784194062Svanhu		printf("DP %s unexpected address family %d\n",
3785194062Svanhu			__func__, sa->sa_family));
3786194062Svanhu	return (0);
3787194062Svanhu}
3788194062Svanhu#endif /* IPSEC_NAT_T */
3789194062Svanhu
3790194062Svanhu/*
3791194062Svanhu * Set port in struct sockaddr. Port is in network byte order.
3792194062Svanhu */
3793194062Svanhustatic void
3794194062Svanhukey_porttosaddr(struct sockaddr *sa, u_int16_t port)
3795194062Svanhu{
3796194062Svanhu
3797194062Svanhu	switch (sa->sa_family) {
3798194062Svanhu#ifdef INET
3799194062Svanhu	case AF_INET:
3800194062Svanhu		((struct sockaddr_in *)sa)->sin_port = port;
3801194062Svanhu		break;
3802194062Svanhu#endif
3803194062Svanhu#ifdef INET6
3804194062Svanhu	case AF_INET6:
3805194062Svanhu		((struct sockaddr_in6 *)sa)->sin6_port = port;
3806194062Svanhu		break;
3807194062Svanhu#endif
3808194062Svanhu	default:
3809194062Svanhu		ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
3810194062Svanhu			__func__, sa->sa_family));
3811194062Svanhu		break;
3812194062Svanhu	}
3813194062Svanhu}
3814194062Svanhu
3815194062Svanhu/*
3816105197Ssam * set data into sadb_x_policy
3817105197Ssam */
3818105197Ssamstatic struct mbuf *
3819189004Srdivackykey_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3820105197Ssam{
3821105197Ssam	struct mbuf *m;
3822105197Ssam	struct sadb_x_policy *p;
3823105197Ssam	size_t len;
3824105197Ssam
3825105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3826105197Ssam	m = key_alloc_mbuf(len);
3827105197Ssam	if (!m || m->m_next) {	/*XXX*/
3828105197Ssam		if (m)
3829105197Ssam			m_freem(m);
3830105197Ssam		return NULL;
3831105197Ssam	}
3832105197Ssam
3833105197Ssam	p = mtod(m, struct sadb_x_policy *);
3834105197Ssam
3835105197Ssam	bzero(p, len);
3836105197Ssam	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3837105197Ssam	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3838105197Ssam	p->sadb_x_policy_type = type;
3839105197Ssam	p->sadb_x_policy_dir = dir;
3840105197Ssam	p->sadb_x_policy_id = id;
3841105197Ssam
3842105197Ssam	return m;
3843105197Ssam}
3844105197Ssam
3845105197Ssam/* %%% utilities */
3846157123Sgnn/* Take a key message (sadb_key) from the socket and turn it into one
3847157123Sgnn * of the kernel's key structures (seckey).
3848157123Sgnn *
3849157123Sgnn * IN: pointer to the src
3850157123Sgnn * OUT: NULL no more memory
3851105197Ssam */
3852157123Sgnnstruct seckey *
3853157123Sgnnkey_dup_keymsg(const struct sadb_key *src, u_int len,
3854157123Sgnn	       struct malloc_type *type)
3855105197Ssam{
3856157123Sgnn	struct seckey *dst;
3857157123Sgnn	dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3858157123Sgnn	if (dst != NULL) {
3859157123Sgnn		dst->bits = src->sadb_key_bits;
3860157123Sgnn		dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3861157123Sgnn		if (dst->key_data != NULL) {
3862157123Sgnn			bcopy((const char *)src + sizeof(struct sadb_key),
3863157123Sgnn			      dst->key_data, len);
3864157123Sgnn		} else {
3865157123Sgnn			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3866157123Sgnn				  __func__));
3867157123Sgnn			free(dst, type);
3868157123Sgnn			dst = NULL;
3869157123Sgnn		}
3870157123Sgnn	} else {
3871157123Sgnn		ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3872157123Sgnn			  __func__));
3873105197Ssam
3874157123Sgnn	}
3875157123Sgnn	return dst;
3876157123Sgnn}
3877157123Sgnn
3878157123Sgnn/* Take a lifetime message (sadb_lifetime) passed in on a socket and
3879157123Sgnn * turn it into one of the kernel's lifetime structures (seclifetime).
3880157123Sgnn *
3881157123Sgnn * IN: pointer to the destination, source and malloc type
3882157123Sgnn * OUT: NULL, no more memory
3883157123Sgnn */
3884157123Sgnn
3885157123Sgnnstatic struct seclifetime *
3886157123Sgnnkey_dup_lifemsg(const struct sadb_lifetime *src,
3887157123Sgnn		 struct malloc_type *type)
3888157123Sgnn{
3889157123Sgnn	struct seclifetime *dst = NULL;
3890157123Sgnn
3891157123Sgnn	dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3892157123Sgnn					   type, M_NOWAIT);
3893157123Sgnn	if (dst == NULL) {
3894119643Ssam		/* XXX counter */
3895120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3896157123Sgnn	} else {
3897157123Sgnn		dst->allocations = src->sadb_lifetime_allocations;
3898157123Sgnn		dst->bytes = src->sadb_lifetime_bytes;
3899157123Sgnn		dst->addtime = src->sadb_lifetime_addtime;
3900157123Sgnn		dst->usetime = src->sadb_lifetime_usetime;
3901157123Sgnn	}
3902157123Sgnn	return dst;
3903105197Ssam}
3904105197Ssam
3905105197Ssam/* compare my own address
3906105197Ssam * OUT:	1: true, i.e. my address.
3907105197Ssam *	0: false
3908105197Ssam */
3909105197Ssamint
3910105197Ssamkey_ismyaddr(sa)
3911105197Ssam	struct sockaddr *sa;
3912105197Ssam{
3913105197Ssam#ifdef INET
3914105197Ssam	struct sockaddr_in *sin;
3915105197Ssam	struct in_ifaddr *ia;
3916105197Ssam#endif
3917105197Ssam
3918120585Ssam	IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3919105197Ssam
3920105197Ssam	switch (sa->sa_family) {
3921105197Ssam#ifdef INET
3922105197Ssam	case AF_INET:
3923105197Ssam		sin = (struct sockaddr_in *)sa;
3924194951Srwatson		IN_IFADDR_RLOCK();
3925181803Sbz		for (ia = V_in_ifaddrhead.tqh_first; ia;
3926105197Ssam		     ia = ia->ia_link.tqe_next)
3927105197Ssam		{
3928105197Ssam			if (sin->sin_family == ia->ia_addr.sin_family &&
3929105197Ssam			    sin->sin_len == ia->ia_addr.sin_len &&
3930105197Ssam			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3931105197Ssam			{
3932194951Srwatson				IN_IFADDR_RUNLOCK();
3933105197Ssam				return 1;
3934105197Ssam			}
3935105197Ssam		}
3936194951Srwatson		IN_IFADDR_RUNLOCK();
3937105197Ssam		break;
3938105197Ssam#endif
3939105197Ssam#ifdef INET6
3940105197Ssam	case AF_INET6:
3941105197Ssam		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3942105197Ssam#endif
3943105197Ssam	}
3944105197Ssam
3945105197Ssam	return 0;
3946105197Ssam}
3947105197Ssam
3948105197Ssam#ifdef INET6
3949105197Ssam/*
3950105197Ssam * compare my own address for IPv6.
3951105197Ssam * 1: ours
3952105197Ssam * 0: other
3953105197Ssam * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3954105197Ssam */
3955105197Ssam#include <netinet6/in6_var.h>
3956105197Ssam
3957105197Ssamstatic int
3958105197Ssamkey_ismyaddr6(sin6)
3959105197Ssam	struct sockaddr_in6 *sin6;
3960105197Ssam{
3961105197Ssam	struct in6_ifaddr *ia;
3962191663Sbms#if 0
3963105197Ssam	struct in6_multi *in6m;
3964191663Sbms#endif
3965105197Ssam
3966194971Srwatson	IN6_IFADDR_RLOCK();
3967194907Srwatson	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
3968105197Ssam		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3969194971Srwatson		    (struct sockaddr *)&ia->ia_addr, 0) == 0) {
3970194971Srwatson			IN6_IFADDR_RUNLOCK();
3971105197Ssam			return 1;
3972194971Srwatson		}
3973105197Ssam
3974191663Sbms#if 0
3975105197Ssam		/*
3976105197Ssam		 * XXX Multicast
3977105197Ssam		 * XXX why do we care about multlicast here while we don't care
3978105197Ssam		 * about IPv4 multicast??
3979105197Ssam		 * XXX scope
3980105197Ssam		 */
3981105197Ssam		in6m = NULL;
3982105197Ssam		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3983194971Srwatson		if (in6m) {
3984194971Srwatson			IN6_IFADDR_RUNLOCK();
3985105197Ssam			return 1;
3986194971Srwatson		}
3987191663Sbms#endif
3988105197Ssam	}
3989194971Srwatson	IN6_IFADDR_RUNLOCK();
3990105197Ssam
3991105197Ssam	/* loopback, just for safety */
3992105197Ssam	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3993105197Ssam		return 1;
3994105197Ssam
3995105197Ssam	return 0;
3996105197Ssam}
3997105197Ssam#endif /*INET6*/
3998105197Ssam
3999105197Ssam/*
4000105197Ssam * compare two secasindex structure.
4001105197Ssam * flag can specify to compare 2 saidxes.
4002105197Ssam * compare two secasindex structure without both mode and reqid.
4003105197Ssam * don't compare port.
4004105197Ssam * IN:
4005105197Ssam *      saidx0: source, it can be in SAD.
4006105197Ssam *      saidx1: object.
4007105197Ssam * OUT:
4008105197Ssam *      1 : equal
4009105197Ssam *      0 : not equal
4010105197Ssam */
4011105197Ssamstatic int
4012105197Ssamkey_cmpsaidx(
4013105197Ssam	const struct secasindex *saidx0,
4014105197Ssam	const struct secasindex *saidx1,
4015105197Ssam	int flag)
4016105197Ssam{
4017194062Svanhu	int chkport = 0;
4018194062Svanhu
4019105197Ssam	/* sanity */
4020105197Ssam	if (saidx0 == NULL && saidx1 == NULL)
4021105197Ssam		return 1;
4022105197Ssam
4023105197Ssam	if (saidx0 == NULL || saidx1 == NULL)
4024105197Ssam		return 0;
4025105197Ssam
4026105197Ssam	if (saidx0->proto != saidx1->proto)
4027105197Ssam		return 0;
4028105197Ssam
4029105197Ssam	if (flag == CMP_EXACTLY) {
4030105197Ssam		if (saidx0->mode != saidx1->mode)
4031105197Ssam			return 0;
4032105197Ssam		if (saidx0->reqid != saidx1->reqid)
4033105197Ssam			return 0;
4034105197Ssam		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4035105197Ssam		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4036105197Ssam			return 0;
4037105197Ssam	} else {
4038105197Ssam
4039105197Ssam		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4040105197Ssam		if (flag == CMP_MODE_REQID
4041105197Ssam		  ||flag == CMP_REQID) {
4042105197Ssam			/*
4043105197Ssam			 * If reqid of SPD is non-zero, unique SA is required.
4044105197Ssam			 * The result must be of same reqid in this case.
4045105197Ssam			 */
4046105197Ssam			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4047105197Ssam				return 0;
4048105197Ssam		}
4049105197Ssam
4050105197Ssam		if (flag == CMP_MODE_REQID) {
4051105197Ssam			if (saidx0->mode != IPSEC_MODE_ANY
4052105197Ssam			 && saidx0->mode != saidx1->mode)
4053105197Ssam				return 0;
4054105197Ssam		}
4055105197Ssam
4056194062Svanhu#ifdef IPSEC_NAT_T
4057194062Svanhu		/*
4058194062Svanhu		 * If NAT-T is enabled, check ports for tunnel mode.
4059194062Svanhu		 * Do not check ports if they are set to zero in the SPD.
4060194062Svanhu		 * Also do not do it for transport mode, as there is no
4061194062Svanhu		 * port information available in the SP.
4062194062Svanhu		 */
4063194062Svanhu		if (saidx1->mode == IPSEC_MODE_TUNNEL &&
4064194062Svanhu		    saidx1->src.sa.sa_family == AF_INET &&
4065194062Svanhu		    saidx1->dst.sa.sa_family == AF_INET &&
4066194062Svanhu		    ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
4067194062Svanhu		    ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
4068194062Svanhu			chkport = 1;
4069194062Svanhu#endif /* IPSEC_NAT_T */
4070194062Svanhu
4071194062Svanhu		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
4072105197Ssam			return 0;
4073105197Ssam		}
4074194062Svanhu		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
4075105197Ssam			return 0;
4076105197Ssam		}
4077105197Ssam	}
4078105197Ssam
4079105197Ssam	return 1;
4080105197Ssam}
4081105197Ssam
4082105197Ssam/*
4083105197Ssam * compare two secindex structure exactly.
4084105197Ssam * IN:
4085105197Ssam *	spidx0: source, it is often in SPD.
4086105197Ssam *	spidx1: object, it is often from PFKEY message.
4087105197Ssam * OUT:
4088105197Ssam *	1 : equal
4089105197Ssam *	0 : not equal
4090105197Ssam */
4091105197Ssamstatic int
4092105197Ssamkey_cmpspidx_exactly(
4093105197Ssam	struct secpolicyindex *spidx0,
4094105197Ssam	struct secpolicyindex *spidx1)
4095105197Ssam{
4096105197Ssam	/* sanity */
4097105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
4098105197Ssam		return 1;
4099105197Ssam
4100105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
4101105197Ssam		return 0;
4102105197Ssam
4103105197Ssam	if (spidx0->prefs != spidx1->prefs
4104105197Ssam	 || spidx0->prefd != spidx1->prefd
4105105197Ssam	 || spidx0->ul_proto != spidx1->ul_proto)
4106105197Ssam		return 0;
4107105197Ssam
4108105197Ssam	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4109105197Ssam	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4110105197Ssam}
4111105197Ssam
4112105197Ssam/*
4113105197Ssam * compare two secindex structure with mask.
4114105197Ssam * IN:
4115105197Ssam *	spidx0: source, it is often in SPD.
4116105197Ssam *	spidx1: object, it is often from IP header.
4117105197Ssam * OUT:
4118105197Ssam *	1 : equal
4119105197Ssam *	0 : not equal
4120105197Ssam */
4121105197Ssamstatic int
4122105197Ssamkey_cmpspidx_withmask(
4123105197Ssam	struct secpolicyindex *spidx0,
4124105197Ssam	struct secpolicyindex *spidx1)
4125105197Ssam{
4126105197Ssam	/* sanity */
4127105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
4128105197Ssam		return 1;
4129105197Ssam
4130105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
4131105197Ssam		return 0;
4132105197Ssam
4133105197Ssam	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4134105197Ssam	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4135105197Ssam	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4136105197Ssam	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4137105197Ssam		return 0;
4138105197Ssam
4139105197Ssam	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4140105197Ssam	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4141105197Ssam	 && spidx0->ul_proto != spidx1->ul_proto)
4142105197Ssam		return 0;
4143105197Ssam
4144105197Ssam	switch (spidx0->src.sa.sa_family) {
4145105197Ssam	case AF_INET:
4146105197Ssam		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4147105197Ssam		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4148105197Ssam			return 0;
4149105197Ssam		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4150105197Ssam		    &spidx1->src.sin.sin_addr, spidx0->prefs))
4151105197Ssam			return 0;
4152105197Ssam		break;
4153105197Ssam	case AF_INET6:
4154105197Ssam		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4155105197Ssam		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4156105197Ssam			return 0;
4157105197Ssam		/*
4158105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
4159105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
4160105197Ssam		 */
4161105197Ssam		if (spidx0->src.sin6.sin6_scope_id &&
4162105197Ssam		    spidx1->src.sin6.sin6_scope_id &&
4163105197Ssam		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4164105197Ssam			return 0;
4165105197Ssam		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4166105197Ssam		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4167105197Ssam			return 0;
4168105197Ssam		break;
4169105197Ssam	default:
4170105197Ssam		/* XXX */
4171105197Ssam		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4172105197Ssam			return 0;
4173105197Ssam		break;
4174105197Ssam	}
4175105197Ssam
4176105197Ssam	switch (spidx0->dst.sa.sa_family) {
4177105197Ssam	case AF_INET:
4178105197Ssam		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4179105197Ssam		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4180105197Ssam			return 0;
4181105197Ssam		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4182105197Ssam		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
4183105197Ssam			return 0;
4184105197Ssam		break;
4185105197Ssam	case AF_INET6:
4186105197Ssam		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4187105197Ssam		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4188105197Ssam			return 0;
4189105197Ssam		/*
4190105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
4191105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
4192105197Ssam		 */
4193130928Sbms		if (spidx0->dst.sin6.sin6_scope_id &&
4194130928Sbms		    spidx1->dst.sin6.sin6_scope_id &&
4195105197Ssam		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4196105197Ssam			return 0;
4197105197Ssam		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4198105197Ssam		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4199105197Ssam			return 0;
4200105197Ssam		break;
4201105197Ssam	default:
4202105197Ssam		/* XXX */
4203105197Ssam		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4204105197Ssam			return 0;
4205105197Ssam		break;
4206105197Ssam	}
4207105197Ssam
4208105197Ssam	/* XXX Do we check other field ?  e.g. flowinfo */
4209105197Ssam
4210105197Ssam	return 1;
4211105197Ssam}
4212105197Ssam
4213105197Ssam/* returns 0 on match */
4214105197Ssamstatic int
4215105197Ssamkey_sockaddrcmp(
4216105197Ssam	const struct sockaddr *sa1,
4217105197Ssam	const struct sockaddr *sa2,
4218105197Ssam	int port)
4219105197Ssam{
4220105197Ssam#ifdef satosin
4221105197Ssam#undef satosin
4222105197Ssam#endif
4223105197Ssam#define satosin(s) ((const struct sockaddr_in *)s)
4224105197Ssam#ifdef satosin6
4225105197Ssam#undef satosin6
4226105197Ssam#endif
4227105197Ssam#define satosin6(s) ((const struct sockaddr_in6 *)s)
4228105197Ssam	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4229105197Ssam		return 1;
4230105197Ssam
4231105197Ssam	switch (sa1->sa_family) {
4232105197Ssam	case AF_INET:
4233105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in))
4234105197Ssam			return 1;
4235105197Ssam		if (satosin(sa1)->sin_addr.s_addr !=
4236105197Ssam		    satosin(sa2)->sin_addr.s_addr) {
4237105197Ssam			return 1;
4238105197Ssam		}
4239105197Ssam		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4240105197Ssam			return 1;
4241105197Ssam		break;
4242105197Ssam	case AF_INET6:
4243105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4244105197Ssam			return 1;	/*EINVAL*/
4245105197Ssam		if (satosin6(sa1)->sin6_scope_id !=
4246105197Ssam		    satosin6(sa2)->sin6_scope_id) {
4247105197Ssam			return 1;
4248105197Ssam		}
4249105197Ssam		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4250105197Ssam		    &satosin6(sa2)->sin6_addr)) {
4251105197Ssam			return 1;
4252105197Ssam		}
4253105197Ssam		if (port &&
4254105197Ssam		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4255105197Ssam			return 1;
4256105197Ssam		}
4257170120Sbz		break;
4258105197Ssam	default:
4259105197Ssam		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4260105197Ssam			return 1;
4261105197Ssam		break;
4262105197Ssam	}
4263105197Ssam
4264105197Ssam	return 0;
4265105197Ssam#undef satosin
4266105197Ssam#undef satosin6
4267105197Ssam}
4268105197Ssam
4269105197Ssam/*
4270105197Ssam * compare two buffers with mask.
4271105197Ssam * IN:
4272105197Ssam *	addr1: source
4273105197Ssam *	addr2: object
4274105197Ssam *	bits:  Number of bits to compare
4275105197Ssam * OUT:
4276105197Ssam *	1 : equal
4277105197Ssam *	0 : not equal
4278105197Ssam */
4279105197Ssamstatic int
4280105197Ssamkey_bbcmp(const void *a1, const void *a2, u_int bits)
4281105197Ssam{
4282105197Ssam	const unsigned char *p1 = a1;
4283105197Ssam	const unsigned char *p2 = a2;
4284105197Ssam
4285105197Ssam	/* XXX: This could be considerably faster if we compare a word
4286105197Ssam	 * at a time, but it is complicated on LSB Endian machines */
4287105197Ssam
4288105197Ssam	/* Handle null pointers */
4289105197Ssam	if (p1 == NULL || p2 == NULL)
4290105197Ssam		return (p1 == p2);
4291105197Ssam
4292105197Ssam	while (bits >= 8) {
4293105197Ssam		if (*p1++ != *p2++)
4294105197Ssam			return 0;
4295105197Ssam		bits -= 8;
4296105197Ssam	}
4297105197Ssam
4298105197Ssam	if (bits > 0) {
4299105197Ssam		u_int8_t mask = ~((1<<(8-bits))-1);
4300105197Ssam		if ((*p1 & mask) != (*p2 & mask))
4301105197Ssam			return 0;
4302105197Ssam	}
4303105197Ssam	return 1;	/* Match! */
4304105197Ssam}
4305105197Ssam
4306119643Ssamstatic void
4307119643Ssamkey_flush_spd(time_t now)
4308105197Ssam{
4309120585Ssam	static u_int16_t sptree_scangen = 0;
4310120585Ssam	u_int16_t gen = sptree_scangen++;
4311120585Ssam	struct secpolicy *sp;
4312105197Ssam	u_int dir;
4313105197Ssam
4314105197Ssam	/* SPD */
4315105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4316120585Ssamrestart:
4317120585Ssam		SPTREE_LOCK();
4318181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
4319120585Ssam			if (sp->scangen == gen)		/* previously handled */
4320120585Ssam				continue;
4321120585Ssam			sp->scangen = gen;
4322192880Svanhu			if (sp->state == IPSEC_SPSTATE_DEAD &&
4323192880Svanhu			    sp->refcnt == 1) {
4324192880Svanhu				/*
4325192880Svanhu				 * Ensure that we only decrease refcnt once,
4326192880Svanhu				 * when we're the last consumer.
4327192880Svanhu				 * Directly call SP_DELREF/key_delsp instead
4328192880Svanhu				 * of KEY_FREESP to avoid unlocking/relocking
4329192880Svanhu				 * SPTREE_LOCK before key_delsp: may refcnt
4330192880Svanhu				 * be increased again during that time ?
4331192880Svanhu				 * NB: also clean entries created by
4332192880Svanhu				 * key_spdflush
4333192880Svanhu				 */
4334192880Svanhu				SP_DELREF(sp);
4335192880Svanhu				key_delsp(sp);
4336120585Ssam				SPTREE_UNLOCK();
4337120585Ssam				goto restart;
4338105197Ssam			}
4339105197Ssam			if (sp->lifetime == 0 && sp->validtime == 0)
4340105197Ssam				continue;
4341105197Ssam			if ((sp->lifetime && now - sp->created > sp->lifetime)
4342105197Ssam			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4343105197Ssam				sp->state = IPSEC_SPSTATE_DEAD;
4344120585Ssam				SPTREE_UNLOCK();
4345105197Ssam				key_spdexpire(sp);
4346120585Ssam				goto restart;
4347105197Ssam			}
4348105197Ssam		}
4349120585Ssam		SPTREE_UNLOCK();
4350105197Ssam	}
4351119643Ssam}
4352105197Ssam
4353119643Ssamstatic void
4354119643Ssamkey_flush_sad(time_t now)
4355119643Ssam{
4356105197Ssam	struct secashead *sah, *nextsah;
4357105197Ssam	struct secasvar *sav, *nextsav;
4358105197Ssam
4359119643Ssam	/* SAD */
4360120585Ssam	SAHTREE_LOCK();
4361181803Sbz	LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4362105197Ssam		/* if sah has been dead, then delete it and process next sah. */
4363105197Ssam		if (sah->state == SADB_SASTATE_DEAD) {
4364105197Ssam			key_delsah(sah);
4365105197Ssam			continue;
4366105197Ssam		}
4367105197Ssam
4368105197Ssam		/* if LARVAL entry doesn't become MATURE, delete it. */
4369120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4370190071Svanhu			/* Need to also check refcnt for a larval SA ??? */
4371181803Sbz			if (now - sav->created > V_key_larval_lifetime)
4372105197Ssam				KEY_FREESAV(&sav);
4373105197Ssam		}
4374105197Ssam
4375105197Ssam		/*
4376105197Ssam		 * check MATURE entry to start to send expire message
4377105197Ssam		 * whether or not.
4378105197Ssam		 */
4379120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4380105197Ssam			/* we don't need to check. */
4381105197Ssam			if (sav->lft_s == NULL)
4382105197Ssam				continue;
4383105197Ssam
4384105197Ssam			/* sanity check */
4385105197Ssam			if (sav->lft_c == NULL) {
4386120585Ssam				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4387120585Ssam					"time, why?\n", __func__));
4388105197Ssam				continue;
4389105197Ssam			}
4390105197Ssam
4391105197Ssam			/* check SOFT lifetime */
4392157123Sgnn			if (sav->lft_s->addtime != 0 &&
4393157123Sgnn			    now - sav->created > sav->lft_s->addtime) {
4394189406Svanhu				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4395190075Svanhu				/*
4396190323Svanhu				 * Actually, only send expire message if
4397190323Svanhu				 * SA has been used, as it was done before,
4398190323Svanhu				 * but should we always send such message,
4399190323Svanhu				 * and let IKE daemon decide if it should be
4400190323Svanhu				 * renegotiated or not ?
4401190323Svanhu				 * XXX expire message will actually NOT be
4402190323Svanhu				 * sent if SA is only used after soft
4403190323Svanhu				 * lifetime has been reached, see below
4404190323Svanhu				 * (DYING state)
4405105197Ssam				 */
4406189406Svanhu				if (sav->lft_c->usetime != 0)
4407105197Ssam					key_expire(sav);
4408105197Ssam			}
4409105197Ssam			/* check SOFT lifetime by bytes */
4410105197Ssam			/*
4411105197Ssam			 * XXX I don't know the way to delete this SA
4412105197Ssam			 * when new SA is installed.  Caution when it's
4413105197Ssam			 * installed too big lifetime by time.
4414105197Ssam			 */
4415157123Sgnn			else if (sav->lft_s->bytes != 0 &&
4416157123Sgnn			    sav->lft_s->bytes < sav->lft_c->bytes) {
4417105197Ssam
4418105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4419105197Ssam				/*
4420105197Ssam				 * XXX If we keep to send expire
4421105197Ssam				 * message in the status of
4422105197Ssam				 * DYING. Do remove below code.
4423105197Ssam				 */
4424105197Ssam				key_expire(sav);
4425105197Ssam			}
4426105197Ssam		}
4427105197Ssam
4428105197Ssam		/* check DYING entry to change status to DEAD. */
4429120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4430105197Ssam			/* we don't need to check. */
4431105197Ssam			if (sav->lft_h == NULL)
4432105197Ssam				continue;
4433105197Ssam
4434105197Ssam			/* sanity check */
4435105197Ssam			if (sav->lft_c == NULL) {
4436120585Ssam				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4437120585Ssam					"time, why?\n", __func__));
4438105197Ssam				continue;
4439105197Ssam			}
4440105197Ssam
4441157123Sgnn			if (sav->lft_h->addtime != 0 &&
4442157123Sgnn			    now - sav->created > sav->lft_h->addtime) {
4443105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4444105197Ssam				KEY_FREESAV(&sav);
4445105197Ssam			}
4446105197Ssam#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4447105197Ssam			else if (sav->lft_s != NULL
4448157123Sgnn			      && sav->lft_s->addtime != 0
4449157123Sgnn			      && now - sav->created > sav->lft_s->addtime) {
4450105197Ssam				/*
4451105197Ssam				 * XXX: should be checked to be
4452105197Ssam				 * installed the valid SA.
4453105197Ssam				 */
4454105197Ssam
4455105197Ssam				/*
4456105197Ssam				 * If there is no SA then sending
4457105197Ssam				 * expire message.
4458105197Ssam				 */
4459105197Ssam				key_expire(sav);
4460105197Ssam			}
4461105197Ssam#endif
4462105197Ssam			/* check HARD lifetime by bytes */
4463157123Sgnn			else if (sav->lft_h->bytes != 0 &&
4464157123Sgnn			    sav->lft_h->bytes < sav->lft_c->bytes) {
4465105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4466105197Ssam				KEY_FREESAV(&sav);
4467105197Ssam			}
4468105197Ssam		}
4469105197Ssam
4470105197Ssam		/* delete entry in DEAD */
4471120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4472105197Ssam			/* sanity check */
4473105197Ssam			if (sav->state != SADB_SASTATE_DEAD) {
4474120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4475120585Ssam					"(queue: %d SA: %d): kill it anyway\n",
4476120585Ssam					__func__,
4477105197Ssam					SADB_SASTATE_DEAD, sav->state));
4478105197Ssam			}
4479105197Ssam			/*
4480105197Ssam			 * do not call key_freesav() here.
4481105197Ssam			 * sav should already be freed, and sav->refcnt
4482105197Ssam			 * shows other references to sav
4483105197Ssam			 * (such as from SPD).
4484105197Ssam			 */
4485105197Ssam		}
4486105197Ssam	}
4487120585Ssam	SAHTREE_UNLOCK();
4488119643Ssam}
4489105197Ssam
4490119643Ssamstatic void
4491119643Ssamkey_flush_acq(time_t now)
4492119643Ssam{
4493105197Ssam	struct secacq *acq, *nextacq;
4494105197Ssam
4495119643Ssam	/* ACQ tree */
4496120585Ssam	ACQ_LOCK();
4497181803Sbz	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4498105197Ssam		nextacq = LIST_NEXT(acq, chain);
4499181803Sbz		if (now - acq->created > V_key_blockacq_lifetime
4500105197Ssam		 && __LIST_CHAINED(acq)) {
4501105197Ssam			LIST_REMOVE(acq, chain);
4502119643Ssam			free(acq, M_IPSEC_SAQ);
4503105197Ssam		}
4504105197Ssam	}
4505120585Ssam	ACQ_UNLOCK();
4506119643Ssam}
4507105197Ssam
4508119643Ssamstatic void
4509119643Ssamkey_flush_spacq(time_t now)
4510119643Ssam{
4511105197Ssam	struct secspacq *acq, *nextacq;
4512105197Ssam
4513119643Ssam	/* SP ACQ tree */
4514120585Ssam	SPACQ_LOCK();
4515181803Sbz	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4516105197Ssam		nextacq = LIST_NEXT(acq, chain);
4517181803Sbz		if (now - acq->created > V_key_blockacq_lifetime
4518105197Ssam		 && __LIST_CHAINED(acq)) {
4519105197Ssam			LIST_REMOVE(acq, chain);
4520119643Ssam			free(acq, M_IPSEC_SAQ);
4521105197Ssam		}
4522105197Ssam	}
4523120585Ssam	SPACQ_UNLOCK();
4524119643Ssam}
4525105197Ssam
4526119643Ssam/*
4527119643Ssam * time handler.
4528119643Ssam * scanning SPD and SAD to check status for each entries,
4529119643Ssam * and do to remove or to expire.
4530119643Ssam * XXX: year 2038 problem may remain.
4531119643Ssam */
4532119643Ssamvoid
4533119643Ssamkey_timehandler(void)
4534119643Ssam{
4535183550Szec	VNET_ITERATOR_DECL(vnet_iter);
4536119643Ssam	time_t now = time_second;
4537105197Ssam
4538195760Srwatson	VNET_LIST_RLOCK_NOSLEEP();
4539183550Szec	VNET_FOREACH(vnet_iter) {
4540183550Szec		CURVNET_SET(vnet_iter);
4541183550Szec		key_flush_spd(now);
4542183550Szec		key_flush_sad(now);
4543183550Szec		key_flush_acq(now);
4544183550Szec		key_flush_spacq(now);
4545183550Szec		CURVNET_RESTORE();
4546183550Szec	}
4547195760Srwatson	VNET_LIST_RUNLOCK_NOSLEEP();
4548119643Ssam
4549105197Ssam#ifndef IPSEC_DEBUG2
4550105197Ssam	/* do exchange to tick time !! */
4551105197Ssam	(void)timeout((void *)key_timehandler, (void *)0, hz);
4552105197Ssam#endif /* IPSEC_DEBUG2 */
4553105197Ssam}
4554105197Ssam
4555105197Ssamu_long
4556105197Ssamkey_random()
4557105197Ssam{
4558105197Ssam	u_long value;
4559105197Ssam
4560105197Ssam	key_randomfill(&value, sizeof(value));
4561105197Ssam	return value;
4562105197Ssam}
4563105197Ssam
4564105197Ssamvoid
4565105197Ssamkey_randomfill(p, l)
4566105197Ssam	void *p;
4567105197Ssam	size_t l;
4568105197Ssam{
4569105197Ssam	size_t n;
4570105197Ssam	u_long v;
4571105197Ssam	static int warn = 1;
4572105197Ssam
4573105197Ssam	n = 0;
4574105197Ssam	n = (size_t)read_random(p, (u_int)l);
4575105197Ssam	/* last resort */
4576105197Ssam	while (n < l) {
4577105197Ssam		v = random();
4578105197Ssam		bcopy(&v, (u_int8_t *)p + n,
4579105197Ssam		    l - n < sizeof(v) ? l - n : sizeof(v));
4580105197Ssam		n += sizeof(v);
4581105197Ssam
4582105197Ssam		if (warn) {
4583105197Ssam			printf("WARNING: pseudo-random number generator "
4584105197Ssam			    "used for IPsec processing\n");
4585105197Ssam			warn = 0;
4586105197Ssam		}
4587105197Ssam	}
4588105197Ssam}
4589105197Ssam
4590105197Ssam/*
4591105197Ssam * map SADB_SATYPE_* to IPPROTO_*.
4592105197Ssam * if satype == SADB_SATYPE then satype is mapped to ~0.
4593105197Ssam * OUT:
4594105197Ssam *	0: invalid satype.
4595105197Ssam */
4596105197Ssamstatic u_int16_t
4597189004Srdivackykey_satype2proto(u_int8_t satype)
4598105197Ssam{
4599105197Ssam	switch (satype) {
4600105197Ssam	case SADB_SATYPE_UNSPEC:
4601105197Ssam		return IPSEC_PROTO_ANY;
4602105197Ssam	case SADB_SATYPE_AH:
4603105197Ssam		return IPPROTO_AH;
4604105197Ssam	case SADB_SATYPE_ESP:
4605105197Ssam		return IPPROTO_ESP;
4606105197Ssam	case SADB_X_SATYPE_IPCOMP:
4607105197Ssam		return IPPROTO_IPCOMP;
4608125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
4609125680Sbms		return IPPROTO_TCP;
4610105197Ssam	default:
4611105197Ssam		return 0;
4612105197Ssam	}
4613105197Ssam	/* NOTREACHED */
4614105197Ssam}
4615105197Ssam
4616105197Ssam/*
4617105197Ssam * map IPPROTO_* to SADB_SATYPE_*
4618105197Ssam * OUT:
4619105197Ssam *	0: invalid protocol type.
4620105197Ssam */
4621105197Ssamstatic u_int8_t
4622189004Srdivackykey_proto2satype(u_int16_t proto)
4623105197Ssam{
4624105197Ssam	switch (proto) {
4625105197Ssam	case IPPROTO_AH:
4626105197Ssam		return SADB_SATYPE_AH;
4627105197Ssam	case IPPROTO_ESP:
4628105197Ssam		return SADB_SATYPE_ESP;
4629105197Ssam	case IPPROTO_IPCOMP:
4630105197Ssam		return SADB_X_SATYPE_IPCOMP;
4631125680Sbms	case IPPROTO_TCP:
4632125680Sbms		return SADB_X_SATYPE_TCPSIGNATURE;
4633105197Ssam	default:
4634105197Ssam		return 0;
4635105197Ssam	}
4636105197Ssam	/* NOTREACHED */
4637105197Ssam}
4638105197Ssam
4639105197Ssam/* %%% PF_KEY */
4640105197Ssam/*
4641105197Ssam * SADB_GETSPI processing is to receive
4642105197Ssam *	<base, (SA2), src address, dst address, (SPI range)>
4643105197Ssam * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4644105197Ssam * tree with the status of LARVAL, and send
4645105197Ssam *	<base, SA(*), address(SD)>
4646105197Ssam * to the IKMPd.
4647105197Ssam *
4648105197Ssam * IN:	mhp: pointer to the pointer to each header.
4649105197Ssam * OUT:	NULL if fail.
4650105197Ssam *	other if success, return pointer to the message to send.
4651105197Ssam */
4652105197Ssamstatic int
4653105197Ssamkey_getspi(so, m, mhp)
4654105197Ssam	struct socket *so;
4655105197Ssam	struct mbuf *m;
4656105197Ssam	const struct sadb_msghdr *mhp;
4657105197Ssam{
4658105197Ssam	struct sadb_address *src0, *dst0;
4659105197Ssam	struct secasindex saidx;
4660105197Ssam	struct secashead *newsah;
4661105197Ssam	struct secasvar *newsav;
4662105197Ssam	u_int8_t proto;
4663105197Ssam	u_int32_t spi;
4664105197Ssam	u_int8_t mode;
4665105197Ssam	u_int32_t reqid;
4666105197Ssam	int error;
4667105197Ssam
4668120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4669120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4670120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4671120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4672105197Ssam
4673105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4674105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4675120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4676120585Ssam			__func__));
4677105197Ssam		return key_senderror(so, m, EINVAL);
4678105197Ssam	}
4679105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4680105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4681120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4682120585Ssam			__func__));
4683105197Ssam		return key_senderror(so, m, EINVAL);
4684105197Ssam	}
4685105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4686105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4687105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4688105197Ssam	} else {
4689105197Ssam		mode = IPSEC_MODE_ANY;
4690105197Ssam		reqid = 0;
4691105197Ssam	}
4692105197Ssam
4693105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4694105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4695105197Ssam
4696105197Ssam	/* map satype to proto */
4697105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4698120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4699120585Ssam			__func__));
4700105197Ssam		return key_senderror(so, m, EINVAL);
4701105197Ssam	}
4702105197Ssam
4703194062Svanhu	/*
4704194062Svanhu	 * Make sure the port numbers are zero.
4705194062Svanhu	 * In case of NAT-T we will update them later if needed.
4706194062Svanhu	 */
4707105197Ssam	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4708105197Ssam	case AF_INET:
4709105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4710105197Ssam		    sizeof(struct sockaddr_in))
4711105197Ssam			return key_senderror(so, m, EINVAL);
4712105197Ssam		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4713105197Ssam		break;
4714105197Ssam	case AF_INET6:
4715105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4716105197Ssam		    sizeof(struct sockaddr_in6))
4717105197Ssam			return key_senderror(so, m, EINVAL);
4718105197Ssam		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4719105197Ssam		break;
4720105197Ssam	default:
4721105197Ssam		; /*???*/
4722105197Ssam	}
4723105197Ssam	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4724105197Ssam	case AF_INET:
4725105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4726105197Ssam		    sizeof(struct sockaddr_in))
4727105197Ssam			return key_senderror(so, m, EINVAL);
4728105197Ssam		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4729105197Ssam		break;
4730105197Ssam	case AF_INET6:
4731105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4732105197Ssam		    sizeof(struct sockaddr_in6))
4733105197Ssam			return key_senderror(so, m, EINVAL);
4734105197Ssam		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4735105197Ssam		break;
4736105197Ssam	default:
4737105197Ssam		; /*???*/
4738105197Ssam	}
4739105197Ssam
4740105197Ssam	/* XXX boundary check against sa_len */
4741105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4742105197Ssam
4743194062Svanhu#ifdef IPSEC_NAT_T
4744194062Svanhu	/*
4745194062Svanhu	 * Handle NAT-T info if present.
4746194062Svanhu	 * We made sure the port numbers are zero above, so we do
4747194062Svanhu	 * not have to worry in case we do not update them.
4748194062Svanhu	 */
4749194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4750194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4751194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4752194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4753194062Svanhu
4754194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4755194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4756194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4757194062Svanhu		struct sadb_x_nat_t_type *type;
4758194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
4759194062Svanhu
4760194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4761194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4762194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4763194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4764194062Svanhu			    "passed.\n", __func__));
4765194062Svanhu			return key_senderror(so, m, EINVAL);
4766194062Svanhu		}
4767194062Svanhu
4768194062Svanhu		sport = (struct sadb_x_nat_t_port *)
4769194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4770194062Svanhu		dport = (struct sadb_x_nat_t_port *)
4771194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4772194062Svanhu
4773194062Svanhu		if (sport)
4774194062Svanhu			KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4775194062Svanhu		if (dport)
4776194062Svanhu			KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4777194062Svanhu	}
4778194062Svanhu#endif
4779194062Svanhu
4780105197Ssam	/* SPI allocation */
4781105197Ssam	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4782105197Ssam	                       &saidx);
4783105197Ssam	if (spi == 0)
4784105197Ssam		return key_senderror(so, m, EINVAL);
4785105197Ssam
4786105197Ssam	/* get a SA index */
4787105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4788105197Ssam		/* create a new SA index */
4789105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4790120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4791105197Ssam			return key_senderror(so, m, ENOBUFS);
4792105197Ssam		}
4793105197Ssam	}
4794105197Ssam
4795105197Ssam	/* get a new SA */
4796105197Ssam	/* XXX rewrite */
4797105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4798105197Ssam	if (newsav == NULL) {
4799105197Ssam		/* XXX don't free new SA index allocated in above. */
4800105197Ssam		return key_senderror(so, m, error);
4801105197Ssam	}
4802105197Ssam
4803105197Ssam	/* set spi */
4804105197Ssam	newsav->spi = htonl(spi);
4805105197Ssam
4806105197Ssam	/* delete the entry in acqtree */
4807105197Ssam	if (mhp->msg->sadb_msg_seq != 0) {
4808105197Ssam		struct secacq *acq;
4809105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4810105197Ssam			/* reset counter in order to deletion by timehandler. */
4811105197Ssam			acq->created = time_second;
4812105197Ssam			acq->count = 0;
4813105197Ssam		}
4814105197Ssam    	}
4815105197Ssam
4816105197Ssam    {
4817105197Ssam	struct mbuf *n, *nn;
4818105197Ssam	struct sadb_sa *m_sa;
4819105197Ssam	struct sadb_msg *newmsg;
4820105197Ssam	int off, len;
4821105197Ssam
4822105197Ssam	/* create new sadb_msg to reply. */
4823105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4824105197Ssam	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4825105197Ssam
4826111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
4827105197Ssam	if (len > MHLEN) {
4828111119Simp		MCLGET(n, M_DONTWAIT);
4829105197Ssam		if ((n->m_flags & M_EXT) == 0) {
4830105197Ssam			m_freem(n);
4831105197Ssam			n = NULL;
4832105197Ssam		}
4833105197Ssam	}
4834105197Ssam	if (!n)
4835105197Ssam		return key_senderror(so, m, ENOBUFS);
4836105197Ssam
4837105197Ssam	n->m_len = len;
4838105197Ssam	n->m_next = NULL;
4839105197Ssam	off = 0;
4840105197Ssam
4841105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4842105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4843105197Ssam
4844105197Ssam	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4845105197Ssam	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4846105197Ssam	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4847105197Ssam	m_sa->sadb_sa_spi = htonl(spi);
4848105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4849105197Ssam
4850120585Ssam	IPSEC_ASSERT(off == len,
4851120585Ssam		("length inconsistency (off %u len %u)", off, len));
4852105197Ssam
4853105197Ssam	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4854105197Ssam	    SADB_EXT_ADDRESS_DST);
4855105197Ssam	if (!n->m_next) {
4856105197Ssam		m_freem(n);
4857105197Ssam		return key_senderror(so, m, ENOBUFS);
4858105197Ssam	}
4859105197Ssam
4860105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
4861105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
4862105197Ssam		if (n == NULL)
4863105197Ssam			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4864105197Ssam	}
4865105197Ssam
4866105197Ssam	n->m_pkthdr.len = 0;
4867105197Ssam	for (nn = n; nn; nn = nn->m_next)
4868105197Ssam		n->m_pkthdr.len += nn->m_len;
4869105197Ssam
4870105197Ssam	newmsg = mtod(n, struct sadb_msg *);
4871105197Ssam	newmsg->sadb_msg_seq = newsav->seq;
4872105197Ssam	newmsg->sadb_msg_errno = 0;
4873105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4874105197Ssam
4875105197Ssam	m_freem(m);
4876105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4877105197Ssam    }
4878105197Ssam}
4879105197Ssam
4880105197Ssam/*
4881105197Ssam * allocating new SPI
4882105197Ssam * called by key_getspi().
4883105197Ssam * OUT:
4884105197Ssam *	0:	failure.
4885105197Ssam *	others: success.
4886105197Ssam */
4887105197Ssamstatic u_int32_t
4888105197Ssamkey_do_getnewspi(spirange, saidx)
4889105197Ssam	struct sadb_spirange *spirange;
4890105197Ssam	struct secasindex *saidx;
4891105197Ssam{
4892105197Ssam	u_int32_t newspi;
4893105197Ssam	u_int32_t min, max;
4894181803Sbz	int count = V_key_spi_trycnt;
4895105197Ssam
4896105197Ssam	/* set spi range to allocate */
4897105197Ssam	if (spirange != NULL) {
4898105197Ssam		min = spirange->sadb_spirange_min;
4899105197Ssam		max = spirange->sadb_spirange_max;
4900105197Ssam	} else {
4901181803Sbz		min = V_key_spi_minval;
4902181803Sbz		max = V_key_spi_maxval;
4903105197Ssam	}
4904105197Ssam	/* IPCOMP needs 2-byte SPI */
4905105197Ssam	if (saidx->proto == IPPROTO_IPCOMP) {
4906105197Ssam		u_int32_t t;
4907105197Ssam		if (min >= 0x10000)
4908105197Ssam			min = 0xffff;
4909105197Ssam		if (max >= 0x10000)
4910105197Ssam			max = 0xffff;
4911105197Ssam		if (min > max) {
4912105197Ssam			t = min; min = max; max = t;
4913105197Ssam		}
4914105197Ssam	}
4915105197Ssam
4916105197Ssam	if (min == max) {
4917105197Ssam		if (key_checkspidup(saidx, min) != NULL) {
4918120585Ssam			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4919120585Ssam				__func__, min));
4920105197Ssam			return 0;
4921105197Ssam		}
4922105197Ssam
4923105197Ssam		count--; /* taking one cost. */
4924105197Ssam		newspi = min;
4925105197Ssam
4926105197Ssam	} else {
4927105197Ssam
4928105197Ssam		/* init SPI */
4929105197Ssam		newspi = 0;
4930105197Ssam
4931105197Ssam		/* when requesting to allocate spi ranged */
4932105197Ssam		while (count--) {
4933105197Ssam			/* generate pseudo-random SPI value ranged. */
4934105197Ssam			newspi = min + (key_random() % (max - min + 1));
4935105197Ssam
4936105197Ssam			if (key_checkspidup(saidx, newspi) == NULL)
4937105197Ssam				break;
4938105197Ssam		}
4939105197Ssam
4940105197Ssam		if (count == 0 || newspi == 0) {
4941120585Ssam			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4942120585Ssam				__func__));
4943105197Ssam			return 0;
4944105197Ssam		}
4945105197Ssam	}
4946105197Ssam
4947105197Ssam	/* statistics */
4948105197Ssam	keystat.getspi_count =
4949181803Sbz		(keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4950105197Ssam
4951105197Ssam	return newspi;
4952105197Ssam}
4953105197Ssam
4954105197Ssam/*
4955105197Ssam * SADB_UPDATE processing
4956105197Ssam * receive
4957105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4958105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4959105197Ssam * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4960105197Ssam * and send
4961105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4962105197Ssam *       (identity(SD),) (sensitivity)>
4963105197Ssam * to the ikmpd.
4964105197Ssam *
4965105197Ssam * m will always be freed.
4966105197Ssam */
4967105197Ssamstatic int
4968105197Ssamkey_update(so, m, mhp)
4969105197Ssam	struct socket *so;
4970105197Ssam	struct mbuf *m;
4971105197Ssam	const struct sadb_msghdr *mhp;
4972105197Ssam{
4973105197Ssam	struct sadb_sa *sa0;
4974105197Ssam	struct sadb_address *src0, *dst0;
4975194062Svanhu#ifdef IPSEC_NAT_T
4976194062Svanhu	struct sadb_x_nat_t_type *type;
4977194513Sbz	struct sadb_x_nat_t_port *sport, *dport;
4978194062Svanhu	struct sadb_address *iaddr, *raddr;
4979194062Svanhu	struct sadb_x_nat_t_frag *frag;
4980194062Svanhu#endif
4981105197Ssam	struct secasindex saidx;
4982105197Ssam	struct secashead *sah;
4983105197Ssam	struct secasvar *sav;
4984105197Ssam	u_int16_t proto;
4985105197Ssam	u_int8_t mode;
4986105197Ssam	u_int32_t reqid;
4987105197Ssam	int error;
4988105197Ssam
4989120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4990120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4991120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4992120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4993105197Ssam
4994105197Ssam	/* map satype to proto */
4995105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4996120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4997120585Ssam			__func__));
4998105197Ssam		return key_senderror(so, m, EINVAL);
4999105197Ssam	}
5000105197Ssam
5001105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5002105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5003105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5004105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5005105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5006105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5007105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5008105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5009105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5010105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5011105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5012120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5013120585Ssam			__func__));
5014105197Ssam		return key_senderror(so, m, EINVAL);
5015105197Ssam	}
5016105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5017105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5018105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5019120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5020120585Ssam			__func__));
5021105197Ssam		return key_senderror(so, m, EINVAL);
5022105197Ssam	}
5023105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5024105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5025105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5026105197Ssam	} else {
5027105197Ssam		mode = IPSEC_MODE_ANY;
5028105197Ssam		reqid = 0;
5029105197Ssam	}
5030105197Ssam	/* XXX boundary checking for other extensions */
5031105197Ssam
5032105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5033105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5034105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5035105197Ssam
5036105197Ssam	/* XXX boundary check against sa_len */
5037105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5038105197Ssam
5039194062Svanhu	/*
5040194062Svanhu	 * Make sure the port numbers are zero.
5041194062Svanhu	 * In case of NAT-T we will update them later if needed.
5042194062Svanhu	 */
5043194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5044194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5045194062Svanhu
5046194062Svanhu#ifdef IPSEC_NAT_T
5047194062Svanhu	/*
5048194062Svanhu	 * Handle NAT-T info if present.
5049194062Svanhu	 */
5050194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5051194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5052194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5053194062Svanhu
5054194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5055194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5056194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5057194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5058194062Svanhu			    __func__));
5059194062Svanhu			return key_senderror(so, m, EINVAL);
5060194062Svanhu		}
5061194062Svanhu
5062194062Svanhu		type = (struct sadb_x_nat_t_type *)
5063194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5064194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5065194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5066194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5067194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5068194062Svanhu	} else {
5069194062Svanhu		type = 0;
5070194513Sbz		sport = dport = 0;
5071194062Svanhu	}
5072194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5073194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5074194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5075194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5076194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5077194062Svanhu			    __func__));
5078194062Svanhu			return key_senderror(so, m, EINVAL);
5079194062Svanhu		}
5080194062Svanhu		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5081194062Svanhu		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5082194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5083194062Svanhu	} else {
5084194062Svanhu		iaddr = raddr = NULL;
5085194062Svanhu	}
5086194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5087194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5088194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5089194062Svanhu			    __func__));
5090194062Svanhu			return key_senderror(so, m, EINVAL);
5091194062Svanhu		}
5092194062Svanhu		frag = (struct sadb_x_nat_t_frag *)
5093194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5094194062Svanhu	} else {
5095194062Svanhu		frag = 0;
5096194062Svanhu	}
5097194062Svanhu#endif
5098194062Svanhu
5099105197Ssam	/* get a SA header */
5100105197Ssam	if ((sah = key_getsah(&saidx)) == NULL) {
5101120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
5102105197Ssam		return key_senderror(so, m, ENOENT);
5103105197Ssam	}
5104105197Ssam
5105105197Ssam	/* set spidx if there */
5106105197Ssam	/* XXX rewrite */
5107105197Ssam	error = key_setident(sah, m, mhp);
5108105197Ssam	if (error)
5109105197Ssam		return key_senderror(so, m, error);
5110105197Ssam
5111105197Ssam	/* find a SA with sequence number. */
5112105197Ssam#ifdef IPSEC_DOSEQCHECK
5113105197Ssam	if (mhp->msg->sadb_msg_seq != 0
5114105197Ssam	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
5115120585Ssam		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
5116120585Ssam			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
5117105197Ssam		return key_senderror(so, m, ENOENT);
5118105197Ssam	}
5119105197Ssam#else
5120120585Ssam	SAHTREE_LOCK();
5121120585Ssam	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5122120585Ssam	SAHTREE_UNLOCK();
5123120585Ssam	if (sav == NULL) {
5124120585Ssam		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
5125120585Ssam			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5126105197Ssam		return key_senderror(so, m, EINVAL);
5127105197Ssam	}
5128105197Ssam#endif
5129105197Ssam
5130105197Ssam	/* validity check */
5131105197Ssam	if (sav->sah->saidx.proto != proto) {
5132120585Ssam		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
5133120585Ssam			"(DB=%u param=%u)\n", __func__,
5134120585Ssam			sav->sah->saidx.proto, proto));
5135105197Ssam		return key_senderror(so, m, EINVAL);
5136105197Ssam	}
5137105197Ssam#ifdef IPSEC_DOSEQCHECK
5138105197Ssam	if (sav->spi != sa0->sadb_sa_spi) {
5139120585Ssam		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
5140120585Ssam		    __func__,
5141105197Ssam		    (u_int32_t)ntohl(sav->spi),
5142105197Ssam		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5143105197Ssam		return key_senderror(so, m, EINVAL);
5144105197Ssam	}
5145105197Ssam#endif
5146105197Ssam	if (sav->pid != mhp->msg->sadb_msg_pid) {
5147120585Ssam		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
5148120585Ssam		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
5149105197Ssam		return key_senderror(so, m, EINVAL);
5150105197Ssam	}
5151105197Ssam
5152105197Ssam	/* copy sav values */
5153105197Ssam	error = key_setsaval(sav, m, mhp);
5154105197Ssam	if (error) {
5155105197Ssam		KEY_FREESAV(&sav);
5156105197Ssam		return key_senderror(so, m, error);
5157105197Ssam	}
5158105197Ssam
5159194062Svanhu#ifdef IPSEC_NAT_T
5160194062Svanhu	/*
5161194062Svanhu	 * Handle more NAT-T info if present,
5162194062Svanhu	 * now that we have a sav to fill.
5163194062Svanhu	 */
5164194062Svanhu	if (type)
5165194062Svanhu		sav->natt_type = type->sadb_x_nat_t_type_type;
5166194062Svanhu
5167194513Sbz	if (sport)
5168194513Sbz		KEY_PORTTOSADDR(&sav->sah->saidx.src,
5169194513Sbz		    sport->sadb_x_nat_t_port_port);
5170194513Sbz	if (dport)
5171194513Sbz		KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5172194513Sbz		    dport->sadb_x_nat_t_port_port);
5173194513Sbz
5174194062Svanhu#if 0
5175194062Svanhu	/*
5176194062Svanhu	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5177194062Svanhu	 * We should actually check for a minimum MTU here, if we
5178194062Svanhu	 * want to support it in ip_output.
5179194062Svanhu	 */
5180194062Svanhu	if (frag)
5181194062Svanhu		sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5182194062Svanhu#endif
5183194062Svanhu#endif
5184194062Svanhu
5185207651Svanhu	/* check SA values to be mature. */
5186207651Svanhu	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5187207651Svanhu		KEY_FREESAV(&sav);
5188207651Svanhu		return key_senderror(so, m, 0);
5189207651Svanhu	}
5190207651Svanhu
5191105197Ssam    {
5192105197Ssam	struct mbuf *n;
5193105197Ssam
5194105197Ssam	/* set msg buf from mhp */
5195105197Ssam	n = key_getmsgbuf_x1(m, mhp);
5196105197Ssam	if (n == NULL) {
5197120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5198105197Ssam		return key_senderror(so, m, ENOBUFS);
5199105197Ssam	}
5200105197Ssam
5201105197Ssam	m_freem(m);
5202105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5203105197Ssam    }
5204105197Ssam}
5205105197Ssam
5206105197Ssam/*
5207105197Ssam * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5208105197Ssam * only called by key_update().
5209105197Ssam * OUT:
5210105197Ssam *	NULL	: not found
5211105197Ssam *	others	: found, pointer to a SA.
5212105197Ssam */
5213105197Ssam#ifdef IPSEC_DOSEQCHECK
5214105197Ssamstatic struct secasvar *
5215105197Ssamkey_getsavbyseq(sah, seq)
5216105197Ssam	struct secashead *sah;
5217105197Ssam	u_int32_t seq;
5218105197Ssam{
5219105197Ssam	struct secasvar *sav;
5220105197Ssam	u_int state;
5221105197Ssam
5222105197Ssam	state = SADB_SASTATE_LARVAL;
5223105197Ssam
5224105197Ssam	/* search SAD with sequence number ? */
5225105197Ssam	LIST_FOREACH(sav, &sah->savtree[state], chain) {
5226105197Ssam
5227120585Ssam		KEY_CHKSASTATE(state, sav->state, __func__);
5228105197Ssam
5229105197Ssam		if (sav->seq == seq) {
5230158767Spjd			sa_addref(sav);
5231105197Ssam			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5232120585Ssam				printf("DP %s cause refcnt++:%d SA:%p\n",
5233120585Ssam					__func__, sav->refcnt, sav));
5234105197Ssam			return sav;
5235105197Ssam		}
5236105197Ssam	}
5237105197Ssam
5238105197Ssam	return NULL;
5239105197Ssam}
5240105197Ssam#endif
5241105197Ssam
5242105197Ssam/*
5243105197Ssam * SADB_ADD processing
5244108533Sschweikh * add an entry to SA database, when received
5245105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5246105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
5247105197Ssam * from the ikmpd,
5248105197Ssam * and send
5249105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5250105197Ssam *       (identity(SD),) (sensitivity)>
5251105197Ssam * to the ikmpd.
5252105197Ssam *
5253105197Ssam * IGNORE identity and sensitivity messages.
5254105197Ssam *
5255105197Ssam * m will always be freed.
5256105197Ssam */
5257105197Ssamstatic int
5258105197Ssamkey_add(so, m, mhp)
5259105197Ssam	struct socket *so;
5260105197Ssam	struct mbuf *m;
5261105197Ssam	const struct sadb_msghdr *mhp;
5262105197Ssam{
5263105197Ssam	struct sadb_sa *sa0;
5264105197Ssam	struct sadb_address *src0, *dst0;
5265194062Svanhu#ifdef IPSEC_NAT_T
5266194062Svanhu	struct sadb_x_nat_t_type *type;
5267194062Svanhu	struct sadb_address *iaddr, *raddr;
5268194062Svanhu	struct sadb_x_nat_t_frag *frag;
5269194062Svanhu#endif
5270105197Ssam	struct secasindex saidx;
5271105197Ssam	struct secashead *newsah;
5272105197Ssam	struct secasvar *newsav;
5273105197Ssam	u_int16_t proto;
5274105197Ssam	u_int8_t mode;
5275105197Ssam	u_int32_t reqid;
5276105197Ssam	int error;
5277105197Ssam
5278120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5279120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5280120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5281120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5282105197Ssam
5283105197Ssam	/* map satype to proto */
5284105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5285120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5286120585Ssam			__func__));
5287105197Ssam		return key_senderror(so, m, EINVAL);
5288105197Ssam	}
5289105197Ssam
5290105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5291105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5292105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5293105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5294105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5295105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5296105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5297105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5298105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5299105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5300105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5301120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5302120585Ssam			__func__));
5303105197Ssam		return key_senderror(so, m, EINVAL);
5304105197Ssam	}
5305105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5306105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5307105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5308105197Ssam		/* XXX need more */
5309120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5310120585Ssam			__func__));
5311105197Ssam		return key_senderror(so, m, EINVAL);
5312105197Ssam	}
5313105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5314105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5315105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5316105197Ssam	} else {
5317105197Ssam		mode = IPSEC_MODE_ANY;
5318105197Ssam		reqid = 0;
5319105197Ssam	}
5320105197Ssam
5321105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5322105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5323105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5324105197Ssam
5325105197Ssam	/* XXX boundary check against sa_len */
5326105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5327105197Ssam
5328194062Svanhu	/*
5329194062Svanhu	 * Make sure the port numbers are zero.
5330194062Svanhu	 * In case of NAT-T we will update them later if needed.
5331194062Svanhu	 */
5332194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5333194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5334194062Svanhu
5335194062Svanhu#ifdef IPSEC_NAT_T
5336194062Svanhu	/*
5337194062Svanhu	 * Handle NAT-T info if present.
5338194062Svanhu	 */
5339194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5340194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5341194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5342194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5343194062Svanhu
5344194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5345194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5346194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5347194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5348194062Svanhu			    __func__));
5349194062Svanhu			return key_senderror(so, m, EINVAL);
5350194062Svanhu		}
5351194062Svanhu
5352194062Svanhu		type = (struct sadb_x_nat_t_type *)
5353194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5354194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5355194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5356194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5357194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5358194062Svanhu
5359194062Svanhu		if (sport)
5360194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5361194062Svanhu			    sport->sadb_x_nat_t_port_port);
5362194062Svanhu		if (dport)
5363194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5364194062Svanhu			    dport->sadb_x_nat_t_port_port);
5365194062Svanhu	} else {
5366194062Svanhu		type = 0;
5367194062Svanhu	}
5368194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5369194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5370194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5371194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5372194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5373194062Svanhu			    __func__));
5374194062Svanhu			return key_senderror(so, m, EINVAL);
5375194062Svanhu		}
5376194062Svanhu		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5377194062Svanhu		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5378194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5379194062Svanhu	} else {
5380194062Svanhu		iaddr = raddr = NULL;
5381194062Svanhu	}
5382194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5383194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5384194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5385194062Svanhu			    __func__));
5386194062Svanhu			return key_senderror(so, m, EINVAL);
5387194062Svanhu		}
5388194062Svanhu		frag = (struct sadb_x_nat_t_frag *)
5389194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5390194062Svanhu	} else {
5391194062Svanhu		frag = 0;
5392194062Svanhu	}
5393194062Svanhu#endif
5394194062Svanhu
5395105197Ssam	/* get a SA header */
5396105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
5397105197Ssam		/* create a new SA header */
5398105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
5399120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5400105197Ssam			return key_senderror(so, m, ENOBUFS);
5401105197Ssam		}
5402105197Ssam	}
5403105197Ssam
5404105197Ssam	/* set spidx if there */
5405105197Ssam	/* XXX rewrite */
5406105197Ssam	error = key_setident(newsah, m, mhp);
5407105197Ssam	if (error) {
5408105197Ssam		return key_senderror(so, m, error);
5409105197Ssam	}
5410105197Ssam
5411105197Ssam	/* create new SA entry. */
5412105197Ssam	/* We can create new SA only if SPI is differenct. */
5413120585Ssam	SAHTREE_LOCK();
5414120585Ssam	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5415120585Ssam	SAHTREE_UNLOCK();
5416120585Ssam	if (newsav != NULL) {
5417120585Ssam		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5418105197Ssam		return key_senderror(so, m, EEXIST);
5419105197Ssam	}
5420105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5421105197Ssam	if (newsav == NULL) {
5422105197Ssam		return key_senderror(so, m, error);
5423105197Ssam	}
5424105197Ssam
5425105197Ssam	/* check SA values to be mature. */
5426105197Ssam	if ((error = key_mature(newsav)) != 0) {
5427105197Ssam		KEY_FREESAV(&newsav);
5428105197Ssam		return key_senderror(so, m, error);
5429105197Ssam	}
5430105197Ssam
5431194062Svanhu#ifdef IPSEC_NAT_T
5432105197Ssam	/*
5433194062Svanhu	 * Handle more NAT-T info if present,
5434194062Svanhu	 * now that we have a sav to fill.
5435194062Svanhu	 */
5436194062Svanhu	if (type)
5437194062Svanhu		newsav->natt_type = type->sadb_x_nat_t_type_type;
5438194062Svanhu
5439194062Svanhu#if 0
5440194062Svanhu	/*
5441194062Svanhu	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5442194062Svanhu	 * We should actually check for a minimum MTU here, if we
5443194062Svanhu	 * want to support it in ip_output.
5444194062Svanhu	 */
5445194062Svanhu	if (frag)
5446194062Svanhu		newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5447194062Svanhu#endif
5448194062Svanhu#endif
5449194062Svanhu
5450194062Svanhu	/*
5451105197Ssam	 * don't call key_freesav() here, as we would like to keep the SA
5452105197Ssam	 * in the database on success.
5453105197Ssam	 */
5454105197Ssam
5455105197Ssam    {
5456105197Ssam	struct mbuf *n;
5457105197Ssam
5458105197Ssam	/* set msg buf from mhp */
5459105197Ssam	n = key_getmsgbuf_x1(m, mhp);
5460105197Ssam	if (n == NULL) {
5461120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5462105197Ssam		return key_senderror(so, m, ENOBUFS);
5463105197Ssam	}
5464105197Ssam
5465105197Ssam	m_freem(m);
5466105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5467105197Ssam    }
5468105197Ssam}
5469105197Ssam
5470105197Ssam/* m is retained */
5471105197Ssamstatic int
5472105197Ssamkey_setident(sah, m, mhp)
5473105197Ssam	struct secashead *sah;
5474105197Ssam	struct mbuf *m;
5475105197Ssam	const struct sadb_msghdr *mhp;
5476105197Ssam{
5477105197Ssam	const struct sadb_ident *idsrc, *iddst;
5478105197Ssam	int idsrclen, iddstlen;
5479105197Ssam
5480120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5481120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5482120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5483120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5484105197Ssam
5485105197Ssam	/* don't make buffer if not there */
5486105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5487105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5488105197Ssam		sah->idents = NULL;
5489105197Ssam		sah->identd = NULL;
5490105197Ssam		return 0;
5491105197Ssam	}
5492105197Ssam
5493105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5494105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5495120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5496105197Ssam		return EINVAL;
5497105197Ssam	}
5498105197Ssam
5499105197Ssam	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5500105197Ssam	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5501105197Ssam	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5502105197Ssam	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5503105197Ssam
5504105197Ssam	/* validity check */
5505105197Ssam	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5506120585Ssam		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5507105197Ssam		return EINVAL;
5508105197Ssam	}
5509105197Ssam
5510105197Ssam	switch (idsrc->sadb_ident_type) {
5511105197Ssam	case SADB_IDENTTYPE_PREFIX:
5512105197Ssam	case SADB_IDENTTYPE_FQDN:
5513105197Ssam	case SADB_IDENTTYPE_USERFQDN:
5514105197Ssam	default:
5515105197Ssam		/* XXX do nothing */
5516105197Ssam		sah->idents = NULL;
5517105197Ssam		sah->identd = NULL;
5518105197Ssam	 	return 0;
5519105197Ssam	}
5520105197Ssam
5521105197Ssam	/* make structure */
5522157123Sgnn	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5523105197Ssam	if (sah->idents == NULL) {
5524120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5525105197Ssam		return ENOBUFS;
5526105197Ssam	}
5527157123Sgnn	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5528105197Ssam	if (sah->identd == NULL) {
5529119643Ssam		free(sah->idents, M_IPSEC_MISC);
5530105197Ssam		sah->idents = NULL;
5531120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5532105197Ssam		return ENOBUFS;
5533105197Ssam	}
5534157123Sgnn	sah->idents->type = idsrc->sadb_ident_type;
5535157123Sgnn	sah->idents->id = idsrc->sadb_ident_id;
5536105197Ssam
5537157123Sgnn	sah->identd->type = iddst->sadb_ident_type;
5538157123Sgnn	sah->identd->id = iddst->sadb_ident_id;
5539157123Sgnn
5540105197Ssam	return 0;
5541105197Ssam}
5542105197Ssam
5543105197Ssam/*
5544105197Ssam * m will not be freed on return.
5545105197Ssam * it is caller's responsibility to free the result.
5546105197Ssam */
5547105197Ssamstatic struct mbuf *
5548105197Ssamkey_getmsgbuf_x1(m, mhp)
5549105197Ssam	struct mbuf *m;
5550105197Ssam	const struct sadb_msghdr *mhp;
5551105197Ssam{
5552105197Ssam	struct mbuf *n;
5553105197Ssam
5554120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5555120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5556120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5557105197Ssam
5558105197Ssam	/* create new sadb_msg to reply. */
5559105197Ssam	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5560105197Ssam	    SADB_EXT_SA, SADB_X_EXT_SA2,
5561105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5562105197Ssam	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5563105197Ssam	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5564105197Ssam	if (!n)
5565105197Ssam		return NULL;
5566105197Ssam
5567105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5568105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5569105197Ssam		if (n == NULL)
5570105197Ssam			return NULL;
5571105197Ssam	}
5572105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5573105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_len =
5574105197Ssam	    PFKEY_UNIT64(n->m_pkthdr.len);
5575105197Ssam
5576105197Ssam	return n;
5577105197Ssam}
5578105197Ssam
5579105197Ssamstatic int key_delete_all __P((struct socket *, struct mbuf *,
5580105197Ssam	const struct sadb_msghdr *, u_int16_t));
5581105197Ssam
5582105197Ssam/*
5583105197Ssam * SADB_DELETE processing
5584105197Ssam * receive
5585105197Ssam *   <base, SA(*), address(SD)>
5586105197Ssam * from the ikmpd, and set SADB_SASTATE_DEAD,
5587105197Ssam * and send,
5588105197Ssam *   <base, SA(*), address(SD)>
5589105197Ssam * to the ikmpd.
5590105197Ssam *
5591105197Ssam * m will always be freed.
5592105197Ssam */
5593105197Ssamstatic int
5594105197Ssamkey_delete(so, m, mhp)
5595105197Ssam	struct socket *so;
5596105197Ssam	struct mbuf *m;
5597105197Ssam	const struct sadb_msghdr *mhp;
5598105197Ssam{
5599105197Ssam	struct sadb_sa *sa0;
5600105197Ssam	struct sadb_address *src0, *dst0;
5601105197Ssam	struct secasindex saidx;
5602105197Ssam	struct secashead *sah;
5603105197Ssam	struct secasvar *sav = NULL;
5604105197Ssam	u_int16_t proto;
5605105197Ssam
5606120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5607120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5608120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5609120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5610105197Ssam
5611105197Ssam	/* map satype to proto */
5612105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5613120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5614120585Ssam			__func__));
5615105197Ssam		return key_senderror(so, m, EINVAL);
5616105197Ssam	}
5617105197Ssam
5618105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5619105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5620120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5621120585Ssam			__func__));
5622105197Ssam		return key_senderror(so, m, EINVAL);
5623105197Ssam	}
5624105197Ssam
5625105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5626105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5627120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5628120585Ssam			__func__));
5629105197Ssam		return key_senderror(so, m, EINVAL);
5630105197Ssam	}
5631105197Ssam
5632105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL) {
5633105197Ssam		/*
5634105197Ssam		 * Caller wants us to delete all non-LARVAL SAs
5635105197Ssam		 * that match the src/dst.  This is used during
5636105197Ssam		 * IKE INITIAL-CONTACT.
5637105197Ssam		 */
5638120585Ssam		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5639105197Ssam		return key_delete_all(so, m, mhp, proto);
5640105197Ssam	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5641120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5642120585Ssam			__func__));
5643105197Ssam		return key_senderror(so, m, EINVAL);
5644105197Ssam	}
5645105197Ssam
5646105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5647105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5648105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5649105197Ssam
5650105197Ssam	/* XXX boundary check against sa_len */
5651105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5652105197Ssam
5653194062Svanhu	/*
5654194062Svanhu	 * Make sure the port numbers are zero.
5655194062Svanhu	 * In case of NAT-T we will update them later if needed.
5656194062Svanhu	 */
5657194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5658194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5659194062Svanhu
5660194062Svanhu#ifdef IPSEC_NAT_T
5661194062Svanhu	/*
5662194062Svanhu	 * Handle NAT-T info if present.
5663194062Svanhu	 */
5664194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5665194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5666194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5667194062Svanhu
5668194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5669194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5670194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5671194062Svanhu			    __func__));
5672194062Svanhu			return key_senderror(so, m, EINVAL);
5673194062Svanhu		}
5674194062Svanhu
5675194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5676194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5677194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5678194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5679194062Svanhu
5680194062Svanhu		if (sport)
5681194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5682194062Svanhu			    sport->sadb_x_nat_t_port_port);
5683194062Svanhu		if (dport)
5684194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5685194062Svanhu			    dport->sadb_x_nat_t_port_port);
5686194062Svanhu	}
5687194062Svanhu#endif
5688194062Svanhu
5689105197Ssam	/* get a SA header */
5690120585Ssam	SAHTREE_LOCK();
5691181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5692105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5693105197Ssam			continue;
5694105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5695105197Ssam			continue;
5696105197Ssam
5697105197Ssam		/* get a SA with SPI. */
5698105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5699105197Ssam		if (sav)
5700105197Ssam			break;
5701105197Ssam	}
5702105197Ssam	if (sah == NULL) {
5703120585Ssam		SAHTREE_UNLOCK();
5704120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5705105197Ssam		return key_senderror(so, m, ENOENT);
5706105197Ssam	}
5707105197Ssam
5708105197Ssam	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5709199398Svanhu	KEY_FREESAV(&sav);
5710120585Ssam	SAHTREE_UNLOCK();
5711105197Ssam
5712105197Ssam    {
5713105197Ssam	struct mbuf *n;
5714105197Ssam	struct sadb_msg *newmsg;
5715105197Ssam
5716105197Ssam	/* create new sadb_msg to reply. */
5717194062Svanhu	/* XXX-BZ NAT-T extensions? */
5718105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5719105197Ssam	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5720105197Ssam	if (!n)
5721105197Ssam		return key_senderror(so, m, ENOBUFS);
5722105197Ssam
5723105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5724105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5725105197Ssam		if (n == NULL)
5726105197Ssam			return key_senderror(so, m, ENOBUFS);
5727105197Ssam	}
5728105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5729105197Ssam	newmsg->sadb_msg_errno = 0;
5730105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5731105197Ssam
5732105197Ssam	m_freem(m);
5733105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5734105197Ssam    }
5735105197Ssam}
5736105197Ssam
5737105197Ssam/*
5738105197Ssam * delete all SAs for src/dst.  Called from key_delete().
5739105197Ssam */
5740105197Ssamstatic int
5741189004Srdivackykey_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5742189004Srdivacky    u_int16_t proto)
5743105197Ssam{
5744105197Ssam	struct sadb_address *src0, *dst0;
5745105197Ssam	struct secasindex saidx;
5746105197Ssam	struct secashead *sah;
5747105197Ssam	struct secasvar *sav, *nextsav;
5748105197Ssam	u_int stateidx, state;
5749105197Ssam
5750105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5751105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5752105197Ssam
5753105197Ssam	/* XXX boundary check against sa_len */
5754105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5755105197Ssam
5756194062Svanhu	/*
5757194062Svanhu	 * Make sure the port numbers are zero.
5758194062Svanhu	 * In case of NAT-T we will update them later if needed.
5759194062Svanhu	 */
5760194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5761194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5762194062Svanhu
5763194062Svanhu#ifdef IPSEC_NAT_T
5764194062Svanhu	/*
5765194062Svanhu	 * Handle NAT-T info if present.
5766194062Svanhu	 */
5767194062Svanhu
5768194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5769194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5770194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5771194062Svanhu
5772194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5773194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5774194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5775194062Svanhu			    __func__));
5776194062Svanhu			return key_senderror(so, m, EINVAL);
5777194062Svanhu		}
5778194062Svanhu
5779194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5780194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5781194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5782194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5783194062Svanhu
5784194062Svanhu		if (sport)
5785194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5786194062Svanhu			    sport->sadb_x_nat_t_port_port);
5787194062Svanhu		if (dport)
5788194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5789194062Svanhu			    dport->sadb_x_nat_t_port_port);
5790194062Svanhu	}
5791194062Svanhu#endif
5792194062Svanhu
5793120585Ssam	SAHTREE_LOCK();
5794181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5795105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5796105197Ssam			continue;
5797105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5798105197Ssam			continue;
5799105197Ssam
5800105197Ssam		/* Delete all non-LARVAL SAs. */
5801105197Ssam		for (stateidx = 0;
5802185348Szec		     stateidx < _ARRAYLEN(saorder_state_alive);
5803105197Ssam		     stateidx++) {
5804185348Szec			state = saorder_state_alive[stateidx];
5805105197Ssam			if (state == SADB_SASTATE_LARVAL)
5806105197Ssam				continue;
5807105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
5808105197Ssam			     sav != NULL; sav = nextsav) {
5809105197Ssam				nextsav = LIST_NEXT(sav, chain);
5810105197Ssam				/* sanity check */
5811105197Ssam				if (sav->state != state) {
5812120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
5813120585Ssam						"sav->state (queue %d SA %d)\n",
5814120585Ssam						__func__, state, sav->state));
5815105197Ssam					continue;
5816105197Ssam				}
5817105197Ssam
5818105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5819105197Ssam				KEY_FREESAV(&sav);
5820105197Ssam			}
5821105197Ssam		}
5822105197Ssam	}
5823120585Ssam	SAHTREE_UNLOCK();
5824105197Ssam    {
5825105197Ssam	struct mbuf *n;
5826105197Ssam	struct sadb_msg *newmsg;
5827105197Ssam
5828105197Ssam	/* create new sadb_msg to reply. */
5829194062Svanhu	/* XXX-BZ NAT-T extensions? */
5830105197Ssam	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5831105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5832105197Ssam	if (!n)
5833105197Ssam		return key_senderror(so, m, ENOBUFS);
5834105197Ssam
5835105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5836105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5837105197Ssam		if (n == NULL)
5838105197Ssam			return key_senderror(so, m, ENOBUFS);
5839105197Ssam	}
5840105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5841105197Ssam	newmsg->sadb_msg_errno = 0;
5842105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5843105197Ssam
5844105197Ssam	m_freem(m);
5845105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5846105197Ssam    }
5847105197Ssam}
5848105197Ssam
5849105197Ssam/*
5850105197Ssam * SADB_GET processing
5851105197Ssam * receive
5852105197Ssam *   <base, SA(*), address(SD)>
5853105197Ssam * from the ikmpd, and get a SP and a SA to respond,
5854105197Ssam * and send,
5855105197Ssam *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5856105197Ssam *       (identity(SD),) (sensitivity)>
5857105197Ssam * to the ikmpd.
5858105197Ssam *
5859105197Ssam * m will always be freed.
5860105197Ssam */
5861105197Ssamstatic int
5862105197Ssamkey_get(so, m, mhp)
5863105197Ssam	struct socket *so;
5864105197Ssam	struct mbuf *m;
5865105197Ssam	const struct sadb_msghdr *mhp;
5866105197Ssam{
5867105197Ssam	struct sadb_sa *sa0;
5868105197Ssam	struct sadb_address *src0, *dst0;
5869105197Ssam	struct secasindex saidx;
5870105197Ssam	struct secashead *sah;
5871105197Ssam	struct secasvar *sav = NULL;
5872105197Ssam	u_int16_t proto;
5873105197Ssam
5874120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5875120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5876120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5877120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5878105197Ssam
5879105197Ssam	/* map satype to proto */
5880105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5881120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5882120585Ssam			__func__));
5883105197Ssam		return key_senderror(so, m, EINVAL);
5884105197Ssam	}
5885105197Ssam
5886105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5887105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5888105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5889120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5890120585Ssam			__func__));
5891105197Ssam		return key_senderror(so, m, EINVAL);
5892105197Ssam	}
5893105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5894105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5895105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5896120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5897120585Ssam			__func__));
5898105197Ssam		return key_senderror(so, m, EINVAL);
5899105197Ssam	}
5900105197Ssam
5901105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5902105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5903105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5904105197Ssam
5905105197Ssam	/* XXX boundary check against sa_len */
5906105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5907105197Ssam
5908194062Svanhu	/*
5909194062Svanhu	 * Make sure the port numbers are zero.
5910194062Svanhu	 * In case of NAT-T we will update them later if needed.
5911194062Svanhu	 */
5912194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5913194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5914194062Svanhu
5915194062Svanhu#ifdef IPSEC_NAT_T
5916194062Svanhu	/*
5917194062Svanhu	 * Handle NAT-T info if present.
5918194062Svanhu	 */
5919194062Svanhu
5920194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5921194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5922194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5923194062Svanhu
5924194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5925194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5926194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5927194062Svanhu			    __func__));
5928194062Svanhu			return key_senderror(so, m, EINVAL);
5929194062Svanhu		}
5930194062Svanhu
5931194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5932194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5933194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5934194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5935194062Svanhu
5936194062Svanhu		if (sport)
5937194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5938194062Svanhu			    sport->sadb_x_nat_t_port_port);
5939194062Svanhu		if (dport)
5940194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5941194062Svanhu			    dport->sadb_x_nat_t_port_port);
5942194062Svanhu	}
5943194062Svanhu#endif
5944194062Svanhu
5945105197Ssam	/* get a SA header */
5946120585Ssam	SAHTREE_LOCK();
5947181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5948105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5949105197Ssam			continue;
5950105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5951105197Ssam			continue;
5952105197Ssam
5953105197Ssam		/* get a SA with SPI. */
5954105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5955105197Ssam		if (sav)
5956105197Ssam			break;
5957105197Ssam	}
5958120585Ssam	SAHTREE_UNLOCK();
5959105197Ssam	if (sah == NULL) {
5960120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5961105197Ssam		return key_senderror(so, m, ENOENT);
5962105197Ssam	}
5963105197Ssam
5964105197Ssam    {
5965105197Ssam	struct mbuf *n;
5966105197Ssam	u_int8_t satype;
5967105197Ssam
5968105197Ssam	/* map proto to satype */
5969105197Ssam	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5970120585Ssam		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5971120585Ssam			__func__));
5972105197Ssam		return key_senderror(so, m, EINVAL);
5973105197Ssam	}
5974105197Ssam
5975105197Ssam	/* create new sadb_msg to reply. */
5976105197Ssam	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5977105197Ssam	    mhp->msg->sadb_msg_pid);
5978105197Ssam	if (!n)
5979105197Ssam		return key_senderror(so, m, ENOBUFS);
5980105197Ssam
5981105197Ssam	m_freem(m);
5982105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5983105197Ssam    }
5984105197Ssam}
5985105197Ssam
5986105197Ssam/* XXX make it sysctl-configurable? */
5987105197Ssamstatic void
5988105197Ssamkey_getcomb_setlifetime(comb)
5989105197Ssam	struct sadb_comb *comb;
5990105197Ssam{
5991105197Ssam
5992105197Ssam	comb->sadb_comb_soft_allocations = 1;
5993105197Ssam	comb->sadb_comb_hard_allocations = 1;
5994105197Ssam	comb->sadb_comb_soft_bytes = 0;
5995105197Ssam	comb->sadb_comb_hard_bytes = 0;
5996105197Ssam	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5997105197Ssam	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5998105197Ssam	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5999105197Ssam	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
6000105197Ssam}
6001105197Ssam
6002105197Ssam/*
6003105197Ssam * XXX reorder combinations by preference
6004105197Ssam * XXX no idea if the user wants ESP authentication or not
6005105197Ssam */
6006105197Ssamstatic struct mbuf *
6007105197Ssamkey_getcomb_esp()
6008105197Ssam{
6009105197Ssam	struct sadb_comb *comb;
6010105197Ssam	struct enc_xform *algo;
6011105197Ssam	struct mbuf *result = NULL, *m, *n;
6012105197Ssam	int encmin;
6013105197Ssam	int i, off, o;
6014105197Ssam	int totlen;
6015105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6016105197Ssam
6017105197Ssam	m = NULL;
6018105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6019105197Ssam		algo = esp_algorithm_lookup(i);
6020105197Ssam		if (algo == NULL)
6021105197Ssam			continue;
6022105197Ssam
6023105197Ssam		/* discard algorithms with key size smaller than system min */
6024181803Sbz		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6025105197Ssam			continue;
6026181803Sbz		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6027181803Sbz			encmin = V_ipsec_esp_keymin;
6028105197Ssam		else
6029105197Ssam			encmin = _BITS(algo->minkey);
6030105197Ssam
6031181803Sbz		if (V_ipsec_esp_auth)
6032105197Ssam			m = key_getcomb_ah();
6033105197Ssam		else {
6034120585Ssam			IPSEC_ASSERT(l <= MLEN,
6035120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6036111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
6037105197Ssam			if (m) {
6038105197Ssam				M_ALIGN(m, l);
6039105197Ssam				m->m_len = l;
6040105197Ssam				m->m_next = NULL;
6041105197Ssam				bzero(mtod(m, caddr_t), m->m_len);
6042105197Ssam			}
6043105197Ssam		}
6044105197Ssam		if (!m)
6045105197Ssam			goto fail;
6046105197Ssam
6047105197Ssam		totlen = 0;
6048105197Ssam		for (n = m; n; n = n->m_next)
6049105197Ssam			totlen += n->m_len;
6050120585Ssam		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6051105197Ssam
6052105197Ssam		for (off = 0; off < totlen; off += l) {
6053105197Ssam			n = m_pulldown(m, off, l, &o);
6054105197Ssam			if (!n) {
6055105197Ssam				/* m is already freed */
6056105197Ssam				goto fail;
6057105197Ssam			}
6058105197Ssam			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6059105197Ssam			bzero(comb, sizeof(*comb));
6060105197Ssam			key_getcomb_setlifetime(comb);
6061105197Ssam			comb->sadb_comb_encrypt = i;
6062105197Ssam			comb->sadb_comb_encrypt_minbits = encmin;
6063105197Ssam			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6064105197Ssam		}
6065105197Ssam
6066105197Ssam		if (!result)
6067105197Ssam			result = m;
6068105197Ssam		else
6069105197Ssam			m_cat(result, m);
6070105197Ssam	}
6071105197Ssam
6072105197Ssam	return result;
6073105197Ssam
6074105197Ssam fail:
6075105197Ssam	if (result)
6076105197Ssam		m_freem(result);
6077105197Ssam	return NULL;
6078105197Ssam}
6079105197Ssam
6080105197Ssamstatic void
6081105197Ssamkey_getsizes_ah(
6082105197Ssam	const struct auth_hash *ah,
6083105197Ssam	int alg,
6084105197Ssam	u_int16_t* min,
6085105197Ssam	u_int16_t* max)
6086105197Ssam{
6087183550Szec
6088105197Ssam	*min = *max = ah->keysize;
6089105197Ssam	if (ah->keysize == 0) {
6090105197Ssam		/*
6091105197Ssam		 * Transform takes arbitrary key size but algorithm
6092105197Ssam		 * key size is restricted.  Enforce this here.
6093105197Ssam		 */
6094105197Ssam		switch (alg) {
6095105197Ssam		case SADB_X_AALG_MD5:	*min = *max = 16; break;
6096105197Ssam		case SADB_X_AALG_SHA:	*min = *max = 20; break;
6097105197Ssam		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
6098105197Ssam		default:
6099120585Ssam			DPRINTF(("%s: unknown AH algorithm %u\n",
6100120585Ssam				__func__, alg));
6101105197Ssam			break;
6102105197Ssam		}
6103105197Ssam	}
6104105197Ssam}
6105105197Ssam
6106105197Ssam/*
6107105197Ssam * XXX reorder combinations by preference
6108105197Ssam */
6109105197Ssamstatic struct mbuf *
6110105197Ssamkey_getcomb_ah()
6111105197Ssam{
6112105197Ssam	struct sadb_comb *comb;
6113105197Ssam	struct auth_hash *algo;
6114105197Ssam	struct mbuf *m;
6115105197Ssam	u_int16_t minkeysize, maxkeysize;
6116105197Ssam	int i;
6117105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6118105197Ssam
6119105197Ssam	m = NULL;
6120105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6121105197Ssam#if 1
6122105197Ssam		/* we prefer HMAC algorithms, not old algorithms */
6123105197Ssam		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
6124105197Ssam			continue;
6125105197Ssam#endif
6126105197Ssam		algo = ah_algorithm_lookup(i);
6127105197Ssam		if (!algo)
6128105197Ssam			continue;
6129105197Ssam		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6130105197Ssam		/* discard algorithms with key size smaller than system min */
6131181803Sbz		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6132105197Ssam			continue;
6133105197Ssam
6134105197Ssam		if (!m) {
6135120585Ssam			IPSEC_ASSERT(l <= MLEN,
6136120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6137111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
6138105197Ssam			if (m) {
6139105197Ssam				M_ALIGN(m, l);
6140105197Ssam				m->m_len = l;
6141105197Ssam				m->m_next = NULL;
6142105197Ssam			}
6143105197Ssam		} else
6144111119Simp			M_PREPEND(m, l, M_DONTWAIT);
6145105197Ssam		if (!m)
6146105197Ssam			return NULL;
6147105197Ssam
6148105197Ssam		comb = mtod(m, struct sadb_comb *);
6149105197Ssam		bzero(comb, sizeof(*comb));
6150105197Ssam		key_getcomb_setlifetime(comb);
6151105197Ssam		comb->sadb_comb_auth = i;
6152105197Ssam		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6153105197Ssam		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6154105197Ssam	}
6155105197Ssam
6156105197Ssam	return m;
6157105197Ssam}
6158105197Ssam
6159105197Ssam/*
6160105197Ssam * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6161105197Ssam * XXX reorder combinations by preference
6162105197Ssam */
6163105197Ssamstatic struct mbuf *
6164105197Ssamkey_getcomb_ipcomp()
6165105197Ssam{
6166105197Ssam	struct sadb_comb *comb;
6167105197Ssam	struct comp_algo *algo;
6168105197Ssam	struct mbuf *m;
6169105197Ssam	int i;
6170105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6171105197Ssam
6172105197Ssam	m = NULL;
6173105197Ssam	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6174105197Ssam		algo = ipcomp_algorithm_lookup(i);
6175105197Ssam		if (!algo)
6176105197Ssam			continue;
6177105197Ssam
6178105197Ssam		if (!m) {
6179120585Ssam			IPSEC_ASSERT(l <= MLEN,
6180120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6181111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
6182105197Ssam			if (m) {
6183105197Ssam				M_ALIGN(m, l);
6184105197Ssam				m->m_len = l;
6185105197Ssam				m->m_next = NULL;
6186105197Ssam			}
6187105197Ssam		} else
6188111119Simp			M_PREPEND(m, l, M_DONTWAIT);
6189105197Ssam		if (!m)
6190105197Ssam			return NULL;
6191105197Ssam
6192105197Ssam		comb = mtod(m, struct sadb_comb *);
6193105197Ssam		bzero(comb, sizeof(*comb));
6194105197Ssam		key_getcomb_setlifetime(comb);
6195105197Ssam		comb->sadb_comb_encrypt = i;
6196105197Ssam		/* what should we set into sadb_comb_*_{min,max}bits? */
6197105197Ssam	}
6198105197Ssam
6199105197Ssam	return m;
6200105197Ssam}
6201105197Ssam
6202105197Ssam/*
6203105197Ssam * XXX no way to pass mode (transport/tunnel) to userland
6204105197Ssam * XXX replay checking?
6205105197Ssam * XXX sysctl interface to ipsec_{ah,esp}_keymin
6206105197Ssam */
6207105197Ssamstatic struct mbuf *
6208105197Ssamkey_getprop(saidx)
6209105197Ssam	const struct secasindex *saidx;
6210105197Ssam{
6211105197Ssam	struct sadb_prop *prop;
6212105197Ssam	struct mbuf *m, *n;
6213105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6214105197Ssam	int totlen;
6215105197Ssam
6216105197Ssam	switch (saidx->proto)  {
6217105197Ssam	case IPPROTO_ESP:
6218105197Ssam		m = key_getcomb_esp();
6219105197Ssam		break;
6220105197Ssam	case IPPROTO_AH:
6221105197Ssam		m = key_getcomb_ah();
6222105197Ssam		break;
6223105197Ssam	case IPPROTO_IPCOMP:
6224105197Ssam		m = key_getcomb_ipcomp();
6225105197Ssam		break;
6226105197Ssam	default:
6227105197Ssam		return NULL;
6228105197Ssam	}
6229105197Ssam
6230105197Ssam	if (!m)
6231105197Ssam		return NULL;
6232111119Simp	M_PREPEND(m, l, M_DONTWAIT);
6233105197Ssam	if (!m)
6234105197Ssam		return NULL;
6235105197Ssam
6236105197Ssam	totlen = 0;
6237105197Ssam	for (n = m; n; n = n->m_next)
6238105197Ssam		totlen += n->m_len;
6239105197Ssam
6240105197Ssam	prop = mtod(m, struct sadb_prop *);
6241105197Ssam	bzero(prop, sizeof(*prop));
6242105197Ssam	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6243105197Ssam	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6244105197Ssam	prop->sadb_prop_replay = 32;	/* XXX */
6245105197Ssam
6246105197Ssam	return m;
6247105197Ssam}
6248105197Ssam
6249105197Ssam/*
6250105197Ssam * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6251105197Ssam * send
6252105197Ssam *   <base, SA, address(SD), (address(P)), x_policy,
6253105197Ssam *       (identity(SD),) (sensitivity,) proposal>
6254105197Ssam * to KMD, and expect to receive
6255105197Ssam *   <base> with SADB_ACQUIRE if error occured,
6256105197Ssam * or
6257105197Ssam *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6258105197Ssam * from KMD by PF_KEY.
6259105197Ssam *
6260105197Ssam * XXX x_policy is outside of RFC2367 (KAME extension).
6261105197Ssam * XXX sensitivity is not supported.
6262105197Ssam * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6263105197Ssam * see comment for key_getcomb_ipcomp().
6264105197Ssam *
6265105197Ssam * OUT:
6266105197Ssam *    0     : succeed
6267105197Ssam *    others: error number
6268105197Ssam */
6269105197Ssamstatic int
6270105197Ssamkey_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6271105197Ssam{
6272105197Ssam	struct mbuf *result = NULL, *m;
6273105197Ssam	struct secacq *newacq;
6274105197Ssam	u_int8_t satype;
6275105197Ssam	int error = -1;
6276105197Ssam	u_int32_t seq;
6277105197Ssam
6278120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6279105197Ssam	satype = key_proto2satype(saidx->proto);
6280120585Ssam	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6281105197Ssam
6282105197Ssam	/*
6283105197Ssam	 * We never do anything about acquirng SA.  There is anather
6284105197Ssam	 * solution that kernel blocks to send SADB_ACQUIRE message until
6285105197Ssam	 * getting something message from IKEd.  In later case, to be
6286105197Ssam	 * managed with ACQUIRING list.
6287105197Ssam	 */
6288108533Sschweikh	/* Get an entry to check whether sending message or not. */
6289105197Ssam	if ((newacq = key_getacq(saidx)) != NULL) {
6290181803Sbz		if (V_key_blockacq_count < newacq->count) {
6291105197Ssam			/* reset counter and do send message. */
6292105197Ssam			newacq->count = 0;
6293105197Ssam		} else {
6294105197Ssam			/* increment counter and do nothing. */
6295105197Ssam			newacq->count++;
6296105197Ssam			return 0;
6297105197Ssam		}
6298105197Ssam	} else {
6299105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
6300105197Ssam		if ((newacq = key_newacq(saidx)) == NULL)
6301105197Ssam			return ENOBUFS;
6302105197Ssam	}
6303105197Ssam
6304105197Ssam
6305105197Ssam	seq = newacq->seq;
6306105197Ssam	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6307105197Ssam	if (!m) {
6308105197Ssam		error = ENOBUFS;
6309105197Ssam		goto fail;
6310105197Ssam	}
6311105197Ssam	result = m;
6312105197Ssam
6313194062Svanhu	/*
6314194062Svanhu	 * No SADB_X_EXT_NAT_T_* here: we do not know
6315194062Svanhu	 * anything related to NAT-T at this time.
6316194062Svanhu	 */
6317194062Svanhu
6318105197Ssam	/* set sadb_address for saidx's. */
6319105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6320105197Ssam	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6321105197Ssam	if (!m) {
6322105197Ssam		error = ENOBUFS;
6323105197Ssam		goto fail;
6324105197Ssam	}
6325105197Ssam	m_cat(result, m);
6326105197Ssam
6327105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6328105197Ssam	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6329105197Ssam	if (!m) {
6330105197Ssam		error = ENOBUFS;
6331105197Ssam		goto fail;
6332105197Ssam	}
6333105197Ssam	m_cat(result, m);
6334105197Ssam
6335105197Ssam	/* XXX proxy address (optional) */
6336105197Ssam
6337105197Ssam	/* set sadb_x_policy */
6338105197Ssam	if (sp) {
6339105197Ssam		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6340105197Ssam		if (!m) {
6341105197Ssam			error = ENOBUFS;
6342105197Ssam			goto fail;
6343105197Ssam		}
6344105197Ssam		m_cat(result, m);
6345105197Ssam	}
6346105197Ssam
6347105197Ssam	/* XXX identity (optional) */
6348105197Ssam#if 0
6349105197Ssam	if (idexttype && fqdn) {
6350105197Ssam		/* create identity extension (FQDN) */
6351105197Ssam		struct sadb_ident *id;
6352105197Ssam		int fqdnlen;
6353105197Ssam
6354105197Ssam		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
6355105197Ssam		id = (struct sadb_ident *)p;
6356105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6357105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6358105197Ssam		id->sadb_ident_exttype = idexttype;
6359105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6360105197Ssam		bcopy(fqdn, id + 1, fqdnlen);
6361105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6362105197Ssam	}
6363105197Ssam
6364105197Ssam	if (idexttype) {
6365105197Ssam		/* create identity extension (USERFQDN) */
6366105197Ssam		struct sadb_ident *id;
6367105197Ssam		int userfqdnlen;
6368105197Ssam
6369105197Ssam		if (userfqdn) {
6370105197Ssam			/* +1 for terminating-NUL */
6371105197Ssam			userfqdnlen = strlen(userfqdn) + 1;
6372105197Ssam		} else
6373105197Ssam			userfqdnlen = 0;
6374105197Ssam		id = (struct sadb_ident *)p;
6375105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6376105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6377105197Ssam		id->sadb_ident_exttype = idexttype;
6378105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6379105197Ssam		/* XXX is it correct? */
6380105197Ssam		if (curproc && curproc->p_cred)
6381105197Ssam			id->sadb_ident_id = curproc->p_cred->p_ruid;
6382105197Ssam		if (userfqdn && userfqdnlen)
6383105197Ssam			bcopy(userfqdn, id + 1, userfqdnlen);
6384105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6385105197Ssam	}
6386105197Ssam#endif
6387105197Ssam
6388105197Ssam	/* XXX sensitivity (optional) */
6389105197Ssam
6390105197Ssam	/* create proposal/combination extension */
6391105197Ssam	m = key_getprop(saidx);
6392105197Ssam#if 0
6393105197Ssam	/*
6394105197Ssam	 * spec conformant: always attach proposal/combination extension,
6395105197Ssam	 * the problem is that we have no way to attach it for ipcomp,
6396105197Ssam	 * due to the way sadb_comb is declared in RFC2367.
6397105197Ssam	 */
6398105197Ssam	if (!m) {
6399105197Ssam		error = ENOBUFS;
6400105197Ssam		goto fail;
6401105197Ssam	}
6402105197Ssam	m_cat(result, m);
6403105197Ssam#else
6404105197Ssam	/*
6405105197Ssam	 * outside of spec; make proposal/combination extension optional.
6406105197Ssam	 */
6407105197Ssam	if (m)
6408105197Ssam		m_cat(result, m);
6409105197Ssam#endif
6410105197Ssam
6411105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
6412105197Ssam		error = EINVAL;
6413105197Ssam		goto fail;
6414105197Ssam	}
6415105197Ssam
6416105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
6417105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
6418105197Ssam		if (result == NULL) {
6419105197Ssam			error = ENOBUFS;
6420105197Ssam			goto fail;
6421105197Ssam		}
6422105197Ssam	}
6423105197Ssam
6424105197Ssam	result->m_pkthdr.len = 0;
6425105197Ssam	for (m = result; m; m = m->m_next)
6426105197Ssam		result->m_pkthdr.len += m->m_len;
6427105197Ssam
6428105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
6429105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
6430105197Ssam
6431105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6432105197Ssam
6433105197Ssam fail:
6434105197Ssam	if (result)
6435105197Ssam		m_freem(result);
6436105197Ssam	return error;
6437105197Ssam}
6438105197Ssam
6439105197Ssamstatic struct secacq *
6440105197Ssamkey_newacq(const struct secasindex *saidx)
6441105197Ssam{
6442105197Ssam	struct secacq *newacq;
6443105197Ssam
6444105197Ssam	/* get new entry */
6445119643Ssam	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6446105197Ssam	if (newacq == NULL) {
6447120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6448105197Ssam		return NULL;
6449105197Ssam	}
6450105197Ssam
6451105197Ssam	/* copy secindex */
6452105197Ssam	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6453181803Sbz	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6454105197Ssam	newacq->created = time_second;
6455105197Ssam	newacq->count = 0;
6456105197Ssam
6457119643Ssam	/* add to acqtree */
6458120585Ssam	ACQ_LOCK();
6459181803Sbz	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6460120585Ssam	ACQ_UNLOCK();
6461119643Ssam
6462105197Ssam	return newacq;
6463105197Ssam}
6464105197Ssam
6465105197Ssamstatic struct secacq *
6466105197Ssamkey_getacq(const struct secasindex *saidx)
6467105197Ssam{
6468105197Ssam	struct secacq *acq;
6469105197Ssam
6470120585Ssam	ACQ_LOCK();
6471181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
6472105197Ssam		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6473119643Ssam			break;
6474105197Ssam	}
6475120585Ssam	ACQ_UNLOCK();
6476105197Ssam
6477119643Ssam	return acq;
6478105197Ssam}
6479105197Ssam
6480105197Ssamstatic struct secacq *
6481105197Ssamkey_getacqbyseq(seq)
6482105197Ssam	u_int32_t seq;
6483105197Ssam{
6484105197Ssam	struct secacq *acq;
6485105197Ssam
6486120585Ssam	ACQ_LOCK();
6487181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
6488105197Ssam		if (acq->seq == seq)
6489119643Ssam			break;
6490105197Ssam	}
6491120585Ssam	ACQ_UNLOCK();
6492105197Ssam
6493119643Ssam	return acq;
6494105197Ssam}
6495105197Ssam
6496105197Ssamstatic struct secspacq *
6497105197Ssamkey_newspacq(spidx)
6498105197Ssam	struct secpolicyindex *spidx;
6499105197Ssam{
6500105197Ssam	struct secspacq *acq;
6501105197Ssam
6502105197Ssam	/* get new entry */
6503119643Ssam	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6504105197Ssam	if (acq == NULL) {
6505120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6506105197Ssam		return NULL;
6507105197Ssam	}
6508105197Ssam
6509105197Ssam	/* copy secindex */
6510105197Ssam	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6511105197Ssam	acq->created = time_second;
6512105197Ssam	acq->count = 0;
6513105197Ssam
6514119643Ssam	/* add to spacqtree */
6515120585Ssam	SPACQ_LOCK();
6516181803Sbz	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6517120585Ssam	SPACQ_UNLOCK();
6518119643Ssam
6519105197Ssam	return acq;
6520105197Ssam}
6521105197Ssam
6522105197Ssamstatic struct secspacq *
6523105197Ssamkey_getspacq(spidx)
6524105197Ssam	struct secpolicyindex *spidx;
6525105197Ssam{
6526105197Ssam	struct secspacq *acq;
6527105197Ssam
6528120585Ssam	SPACQ_LOCK();
6529181803Sbz	LIST_FOREACH(acq, &V_spacqtree, chain) {
6530119643Ssam		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6531119643Ssam			/* NB: return holding spacq_lock */
6532105197Ssam			return acq;
6533119643Ssam		}
6534105197Ssam	}
6535120585Ssam	SPACQ_UNLOCK();
6536105197Ssam
6537105197Ssam	return NULL;
6538105197Ssam}
6539105197Ssam
6540105197Ssam/*
6541105197Ssam * SADB_ACQUIRE processing,
6542105197Ssam * in first situation, is receiving
6543105197Ssam *   <base>
6544105197Ssam * from the ikmpd, and clear sequence of its secasvar entry.
6545105197Ssam *
6546105197Ssam * In second situation, is receiving
6547105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6548105197Ssam * from a user land process, and return
6549105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6550105197Ssam * to the socket.
6551105197Ssam *
6552105197Ssam * m will always be freed.
6553105197Ssam */
6554105197Ssamstatic int
6555105197Ssamkey_acquire2(so, m, mhp)
6556105197Ssam	struct socket *so;
6557105197Ssam	struct mbuf *m;
6558105197Ssam	const struct sadb_msghdr *mhp;
6559105197Ssam{
6560105197Ssam	const struct sadb_address *src0, *dst0;
6561105197Ssam	struct secasindex saidx;
6562105197Ssam	struct secashead *sah;
6563105197Ssam	u_int16_t proto;
6564105197Ssam	int error;
6565105197Ssam
6566120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6567120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6568120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6569120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6570105197Ssam
6571105197Ssam	/*
6572105197Ssam	 * Error message from KMd.
6573105197Ssam	 * We assume that if error was occured in IKEd, the length of PFKEY
6574105197Ssam	 * message is equal to the size of sadb_msg structure.
6575105197Ssam	 * We do not raise error even if error occured in this function.
6576105197Ssam	 */
6577105197Ssam	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6578105197Ssam		struct secacq *acq;
6579105197Ssam
6580105197Ssam		/* check sequence number */
6581105197Ssam		if (mhp->msg->sadb_msg_seq == 0) {
6582120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6583120585Ssam				"number.\n", __func__));
6584105197Ssam			m_freem(m);
6585105197Ssam			return 0;
6586105197Ssam		}
6587105197Ssam
6588105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6589105197Ssam			/*
6590105197Ssam			 * the specified larval SA is already gone, or we got
6591105197Ssam			 * a bogus sequence number.  we can silently ignore it.
6592105197Ssam			 */
6593105197Ssam			m_freem(m);
6594105197Ssam			return 0;
6595105197Ssam		}
6596105197Ssam
6597105197Ssam		/* reset acq counter in order to deletion by timehander. */
6598105197Ssam		acq->created = time_second;
6599105197Ssam		acq->count = 0;
6600105197Ssam		m_freem(m);
6601105197Ssam		return 0;
6602105197Ssam	}
6603105197Ssam
6604105197Ssam	/*
6605105197Ssam	 * This message is from user land.
6606105197Ssam	 */
6607105197Ssam
6608105197Ssam	/* map satype to proto */
6609105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6610120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6611120585Ssam			__func__));
6612105197Ssam		return key_senderror(so, m, EINVAL);
6613105197Ssam	}
6614105197Ssam
6615105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6616105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6617105197Ssam	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6618105197Ssam		/* error */
6619120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6620120585Ssam			__func__));
6621105197Ssam		return key_senderror(so, m, EINVAL);
6622105197Ssam	}
6623105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6624105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6625105197Ssam	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6626105197Ssam		/* error */
6627120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6628120585Ssam			__func__));
6629105197Ssam		return key_senderror(so, m, EINVAL);
6630105197Ssam	}
6631105197Ssam
6632105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6633105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6634105197Ssam
6635105197Ssam	/* XXX boundary check against sa_len */
6636105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6637105197Ssam
6638194062Svanhu	/*
6639194062Svanhu	 * Make sure the port numbers are zero.
6640194062Svanhu	 * In case of NAT-T we will update them later if needed.
6641194062Svanhu	 */
6642194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
6643194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
6644194062Svanhu
6645194062Svanhu#ifndef IPSEC_NAT_T
6646194062Svanhu	/*
6647194062Svanhu	 * Handle NAT-T info if present.
6648194062Svanhu	 */
6649194062Svanhu
6650194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6651194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6652194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
6653194062Svanhu
6654194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6655194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6656194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6657194062Svanhu			    __func__));
6658194062Svanhu			return key_senderror(so, m, EINVAL);
6659194062Svanhu		}
6660194062Svanhu
6661194062Svanhu		sport = (struct sadb_x_nat_t_port *)
6662194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6663194062Svanhu		dport = (struct sadb_x_nat_t_port *)
6664194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6665194062Svanhu
6666194062Svanhu		if (sport)
6667194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
6668194062Svanhu			    sport->sadb_x_nat_t_port_port);
6669194062Svanhu		if (dport)
6670194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
6671194062Svanhu			    dport->sadb_x_nat_t_port_port);
6672194062Svanhu	}
6673194062Svanhu#endif
6674194062Svanhu
6675105197Ssam	/* get a SA index */
6676120585Ssam	SAHTREE_LOCK();
6677181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
6678105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
6679105197Ssam			continue;
6680105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6681105197Ssam			break;
6682105197Ssam	}
6683120585Ssam	SAHTREE_UNLOCK();
6684105197Ssam	if (sah != NULL) {
6685120585Ssam		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6686105197Ssam		return key_senderror(so, m, EEXIST);
6687105197Ssam	}
6688105197Ssam
6689105197Ssam	error = key_acquire(&saidx, NULL);
6690105197Ssam	if (error != 0) {
6691120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6692120585Ssam			__func__, mhp->msg->sadb_msg_errno));
6693105197Ssam		return key_senderror(so, m, error);
6694105197Ssam	}
6695105197Ssam
6696105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6697105197Ssam}
6698105197Ssam
6699105197Ssam/*
6700105197Ssam * SADB_REGISTER processing.
6701105197Ssam * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6702105197Ssam * receive
6703105197Ssam *   <base>
6704105197Ssam * from the ikmpd, and register a socket to send PF_KEY messages,
6705105197Ssam * and send
6706105197Ssam *   <base, supported>
6707105197Ssam * to KMD by PF_KEY.
6708105197Ssam * If socket is detached, must free from regnode.
6709105197Ssam *
6710105197Ssam * m will always be freed.
6711105197Ssam */
6712105197Ssamstatic int
6713105197Ssamkey_register(so, m, mhp)
6714105197Ssam	struct socket *so;
6715105197Ssam	struct mbuf *m;
6716105197Ssam	const struct sadb_msghdr *mhp;
6717105197Ssam{
6718105197Ssam	struct secreg *reg, *newreg = 0;
6719105197Ssam
6720120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6721120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6722120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6723120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6724105197Ssam
6725105197Ssam	/* check for invalid register message */
6726181803Sbz	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6727105197Ssam		return key_senderror(so, m, EINVAL);
6728105197Ssam
6729105197Ssam	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6730105197Ssam	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6731105197Ssam		goto setmsg;
6732105197Ssam
6733105197Ssam	/* check whether existing or not */
6734120585Ssam	REGTREE_LOCK();
6735181803Sbz	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6736105197Ssam		if (reg->so == so) {
6737120585Ssam			REGTREE_UNLOCK();
6738120585Ssam			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6739120585Ssam				__func__));
6740105197Ssam			return key_senderror(so, m, EEXIST);
6741105197Ssam		}
6742105197Ssam	}
6743105197Ssam
6744105197Ssam	/* create regnode */
6745119643Ssam	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6746105197Ssam	if (newreg == NULL) {
6747120585Ssam		REGTREE_UNLOCK();
6748120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6749105197Ssam		return key_senderror(so, m, ENOBUFS);
6750105197Ssam	}
6751105197Ssam
6752105197Ssam	newreg->so = so;
6753105197Ssam	((struct keycb *)sotorawcb(so))->kp_registered++;
6754105197Ssam
6755105197Ssam	/* add regnode to regtree. */
6756181803Sbz	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6757120585Ssam	REGTREE_UNLOCK();
6758105197Ssam
6759105197Ssam  setmsg:
6760105197Ssam    {
6761105197Ssam	struct mbuf *n;
6762105197Ssam	struct sadb_msg *newmsg;
6763105197Ssam	struct sadb_supported *sup;
6764105197Ssam	u_int len, alen, elen;
6765105197Ssam	int off;
6766105197Ssam	int i;
6767105197Ssam	struct sadb_alg *alg;
6768105197Ssam
6769105197Ssam	/* create new sadb_msg to reply. */
6770105197Ssam	alen = 0;
6771105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6772105197Ssam		if (ah_algorithm_lookup(i))
6773105197Ssam			alen += sizeof(struct sadb_alg);
6774105197Ssam	}
6775105197Ssam	if (alen)
6776105197Ssam		alen += sizeof(struct sadb_supported);
6777105197Ssam	elen = 0;
6778105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6779105197Ssam		if (esp_algorithm_lookup(i))
6780105197Ssam			elen += sizeof(struct sadb_alg);
6781105197Ssam	}
6782105197Ssam	if (elen)
6783105197Ssam		elen += sizeof(struct sadb_supported);
6784105197Ssam
6785105197Ssam	len = sizeof(struct sadb_msg) + alen + elen;
6786105197Ssam
6787105197Ssam	if (len > MCLBYTES)
6788105197Ssam		return key_senderror(so, m, ENOBUFS);
6789105197Ssam
6790111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
6791105197Ssam	if (len > MHLEN) {
6792111119Simp		MCLGET(n, M_DONTWAIT);
6793105197Ssam		if ((n->m_flags & M_EXT) == 0) {
6794105197Ssam			m_freem(n);
6795105197Ssam			n = NULL;
6796105197Ssam		}
6797105197Ssam	}
6798105197Ssam	if (!n)
6799105197Ssam		return key_senderror(so, m, ENOBUFS);
6800105197Ssam
6801105197Ssam	n->m_pkthdr.len = n->m_len = len;
6802105197Ssam	n->m_next = NULL;
6803105197Ssam	off = 0;
6804105197Ssam
6805105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6806105197Ssam	newmsg = mtod(n, struct sadb_msg *);
6807105197Ssam	newmsg->sadb_msg_errno = 0;
6808105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6809105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6810105197Ssam
6811105197Ssam	/* for authentication algorithm */
6812105197Ssam	if (alen) {
6813105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6814105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6815105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6816105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6817105197Ssam
6818105197Ssam		for (i = 1; i <= SADB_AALG_MAX; i++) {
6819105197Ssam			struct auth_hash *aalgo;
6820105197Ssam			u_int16_t minkeysize, maxkeysize;
6821105197Ssam
6822105197Ssam			aalgo = ah_algorithm_lookup(i);
6823105197Ssam			if (!aalgo)
6824105197Ssam				continue;
6825105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6826105197Ssam			alg->sadb_alg_id = i;
6827105197Ssam			alg->sadb_alg_ivlen = 0;
6828105197Ssam			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6829105197Ssam			alg->sadb_alg_minbits = _BITS(minkeysize);
6830105197Ssam			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6831105197Ssam			off += PFKEY_ALIGN8(sizeof(*alg));
6832105197Ssam		}
6833105197Ssam	}
6834105197Ssam
6835105197Ssam	/* for encryption algorithm */
6836105197Ssam	if (elen) {
6837105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6838105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6839105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6840105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6841105197Ssam
6842105197Ssam		for (i = 1; i <= SADB_EALG_MAX; i++) {
6843105197Ssam			struct enc_xform *ealgo;
6844105197Ssam
6845105197Ssam			ealgo = esp_algorithm_lookup(i);
6846105197Ssam			if (!ealgo)
6847105197Ssam				continue;
6848105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6849105197Ssam			alg->sadb_alg_id = i;
6850105197Ssam			alg->sadb_alg_ivlen = ealgo->blocksize;
6851105197Ssam			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6852105197Ssam			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6853105197Ssam			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6854105197Ssam		}
6855105197Ssam	}
6856105197Ssam
6857120585Ssam	IPSEC_ASSERT(off == len,
6858120585Ssam		("length assumption failed (off %u len %u)", off, len));
6859105197Ssam
6860105197Ssam	m_freem(m);
6861105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6862105197Ssam    }
6863105197Ssam}
6864105197Ssam
6865105197Ssam/*
6866105197Ssam * free secreg entry registered.
6867105197Ssam * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6868105197Ssam */
6869105197Ssamvoid
6870119643Ssamkey_freereg(struct socket *so)
6871105197Ssam{
6872105197Ssam	struct secreg *reg;
6873105197Ssam	int i;
6874105197Ssam
6875120585Ssam	IPSEC_ASSERT(so != NULL, ("NULL so"));
6876105197Ssam
6877105197Ssam	/*
6878105197Ssam	 * check whether existing or not.
6879105197Ssam	 * check all type of SA, because there is a potential that
6880105197Ssam	 * one socket is registered to multiple type of SA.
6881105197Ssam	 */
6882120585Ssam	REGTREE_LOCK();
6883105197Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6884181803Sbz		LIST_FOREACH(reg, &V_regtree[i], chain) {
6885119643Ssam			if (reg->so == so && __LIST_CHAINED(reg)) {
6886105197Ssam				LIST_REMOVE(reg, chain);
6887119643Ssam				free(reg, M_IPSEC_SAR);
6888105197Ssam				break;
6889105197Ssam			}
6890105197Ssam		}
6891105197Ssam	}
6892120585Ssam	REGTREE_UNLOCK();
6893105197Ssam}
6894105197Ssam
6895105197Ssam/*
6896105197Ssam * SADB_EXPIRE processing
6897105197Ssam * send
6898105197Ssam *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6899105197Ssam * to KMD by PF_KEY.
6900105197Ssam * NOTE: We send only soft lifetime extension.
6901105197Ssam *
6902105197Ssam * OUT:	0	: succeed
6903105197Ssam *	others	: error number
6904105197Ssam */
6905105197Ssamstatic int
6906119643Ssamkey_expire(struct secasvar *sav)
6907105197Ssam{
6908105197Ssam	int s;
6909105197Ssam	int satype;
6910105197Ssam	struct mbuf *result = NULL, *m;
6911105197Ssam	int len;
6912105197Ssam	int error = -1;
6913105197Ssam	struct sadb_lifetime *lt;
6914105197Ssam
6915105197Ssam	/* XXX: Why do we lock ? */
6916105197Ssam	s = splnet();	/*called from softclock()*/
6917105197Ssam
6918120585Ssam	IPSEC_ASSERT (sav != NULL, ("null sav"));
6919120585Ssam	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6920105197Ssam
6921105197Ssam	/* set msg header */
6922120585Ssam	satype = key_proto2satype(sav->sah->saidx.proto);
6923120585Ssam	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6924105197Ssam	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6925105197Ssam	if (!m) {
6926105197Ssam		error = ENOBUFS;
6927105197Ssam		goto fail;
6928105197Ssam	}
6929105197Ssam	result = m;
6930105197Ssam
6931105197Ssam	/* create SA extension */
6932105197Ssam	m = key_setsadbsa(sav);
6933105197Ssam	if (!m) {
6934105197Ssam		error = ENOBUFS;
6935105197Ssam		goto fail;
6936105197Ssam	}
6937105197Ssam	m_cat(result, m);
6938105197Ssam
6939105197Ssam	/* create SA extension */
6940105197Ssam	m = key_setsadbxsa2(sav->sah->saidx.mode,
6941105197Ssam			sav->replay ? sav->replay->count : 0,
6942105197Ssam			sav->sah->saidx.reqid);
6943105197Ssam	if (!m) {
6944105197Ssam		error = ENOBUFS;
6945105197Ssam		goto fail;
6946105197Ssam	}
6947105197Ssam	m_cat(result, m);
6948105197Ssam
6949105197Ssam	/* create lifetime extension (current and soft) */
6950105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6951105197Ssam	m = key_alloc_mbuf(len);
6952105197Ssam	if (!m || m->m_next) {	/*XXX*/
6953105197Ssam		if (m)
6954105197Ssam			m_freem(m);
6955105197Ssam		error = ENOBUFS;
6956105197Ssam		goto fail;
6957105197Ssam	}
6958105197Ssam	bzero(mtod(m, caddr_t), len);
6959105197Ssam	lt = mtod(m, struct sadb_lifetime *);
6960105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6961105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6962157123Sgnn	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6963157123Sgnn	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6964157123Sgnn	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6965157123Sgnn	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6966105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6967176743Sbz	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6968176743Sbz	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6969176743Sbz	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6970176743Sbz	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6971176743Sbz	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6972176743Sbz	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6973105197Ssam	m_cat(result, m);
6974105197Ssam
6975105197Ssam	/* set sadb_address for source */
6976105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6977105197Ssam	    &sav->sah->saidx.src.sa,
6978105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6979105197Ssam	if (!m) {
6980105197Ssam		error = ENOBUFS;
6981105197Ssam		goto fail;
6982105197Ssam	}
6983105197Ssam	m_cat(result, m);
6984105197Ssam
6985105197Ssam	/* set sadb_address for destination */
6986105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6987105197Ssam	    &sav->sah->saidx.dst.sa,
6988105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6989105197Ssam	if (!m) {
6990105197Ssam		error = ENOBUFS;
6991105197Ssam		goto fail;
6992105197Ssam	}
6993105197Ssam	m_cat(result, m);
6994105197Ssam
6995194062Svanhu	/*
6996194062Svanhu	 * XXX-BZ Handle NAT-T extensions here.
6997194062Svanhu	 */
6998194062Svanhu
6999105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
7000105197Ssam		error = EINVAL;
7001105197Ssam		goto fail;
7002105197Ssam	}
7003105197Ssam
7004105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
7005105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
7006105197Ssam		if (result == NULL) {
7007105197Ssam			error = ENOBUFS;
7008105197Ssam			goto fail;
7009105197Ssam		}
7010105197Ssam	}
7011105197Ssam
7012105197Ssam	result->m_pkthdr.len = 0;
7013105197Ssam	for (m = result; m; m = m->m_next)
7014105197Ssam		result->m_pkthdr.len += m->m_len;
7015105197Ssam
7016105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
7017105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
7018105197Ssam
7019105197Ssam	splx(s);
7020105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7021105197Ssam
7022105197Ssam fail:
7023105197Ssam	if (result)
7024105197Ssam		m_freem(result);
7025105197Ssam	splx(s);
7026105197Ssam	return error;
7027105197Ssam}
7028105197Ssam
7029105197Ssam/*
7030105197Ssam * SADB_FLUSH processing
7031105197Ssam * receive
7032105197Ssam *   <base>
7033105197Ssam * from the ikmpd, and free all entries in secastree.
7034105197Ssam * and send,
7035105197Ssam *   <base>
7036105197Ssam * to the ikmpd.
7037105197Ssam * NOTE: to do is only marking SADB_SASTATE_DEAD.
7038105197Ssam *
7039105197Ssam * m will always be freed.
7040105197Ssam */
7041105197Ssamstatic int
7042105197Ssamkey_flush(so, m, mhp)
7043105197Ssam	struct socket *so;
7044105197Ssam	struct mbuf *m;
7045105197Ssam	const struct sadb_msghdr *mhp;
7046105197Ssam{
7047105197Ssam	struct sadb_msg *newmsg;
7048105197Ssam	struct secashead *sah, *nextsah;
7049105197Ssam	struct secasvar *sav, *nextsav;
7050105197Ssam	u_int16_t proto;
7051105197Ssam	u_int8_t state;
7052105197Ssam	u_int stateidx;
7053105197Ssam
7054120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7055120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7056120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7057105197Ssam
7058105197Ssam	/* map satype to proto */
7059105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7060120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7061120585Ssam			__func__));
7062105197Ssam		return key_senderror(so, m, EINVAL);
7063105197Ssam	}
7064105197Ssam
7065105197Ssam	/* no SATYPE specified, i.e. flushing all SA. */
7066120585Ssam	SAHTREE_LOCK();
7067181803Sbz	for (sah = LIST_FIRST(&V_sahtree);
7068105197Ssam	     sah != NULL;
7069105197Ssam	     sah = nextsah) {
7070105197Ssam		nextsah = LIST_NEXT(sah, chain);
7071105197Ssam
7072105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7073105197Ssam		 && proto != sah->saidx.proto)
7074105197Ssam			continue;
7075105197Ssam
7076105197Ssam		for (stateidx = 0;
7077185348Szec		     stateidx < _ARRAYLEN(saorder_state_alive);
7078105197Ssam		     stateidx++) {
7079185348Szec			state = saorder_state_any[stateidx];
7080105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
7081105197Ssam			     sav != NULL;
7082105197Ssam			     sav = nextsav) {
7083105197Ssam
7084105197Ssam				nextsav = LIST_NEXT(sav, chain);
7085105197Ssam
7086105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7087105197Ssam				KEY_FREESAV(&sav);
7088105197Ssam			}
7089105197Ssam		}
7090105197Ssam
7091105197Ssam		sah->state = SADB_SASTATE_DEAD;
7092105197Ssam	}
7093120585Ssam	SAHTREE_UNLOCK();
7094105197Ssam
7095105197Ssam	if (m->m_len < sizeof(struct sadb_msg) ||
7096105197Ssam	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7097120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7098105197Ssam		return key_senderror(so, m, ENOBUFS);
7099105197Ssam	}
7100105197Ssam
7101105197Ssam	if (m->m_next)
7102105197Ssam		m_freem(m->m_next);
7103105197Ssam	m->m_next = NULL;
7104105197Ssam	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7105105197Ssam	newmsg = mtod(m, struct sadb_msg *);
7106105197Ssam	newmsg->sadb_msg_errno = 0;
7107105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7108105197Ssam
7109105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7110105197Ssam}
7111105197Ssam
7112105197Ssam/*
7113105197Ssam * SADB_DUMP processing
7114105197Ssam * dump all entries including status of DEAD in SAD.
7115105197Ssam * receive
7116105197Ssam *   <base>
7117105197Ssam * from the ikmpd, and dump all secasvar leaves
7118105197Ssam * and send,
7119105197Ssam *   <base> .....
7120105197Ssam * to the ikmpd.
7121105197Ssam *
7122105197Ssam * m will always be freed.
7123105197Ssam */
7124105197Ssamstatic int
7125105197Ssamkey_dump(so, m, mhp)
7126105197Ssam	struct socket *so;
7127105197Ssam	struct mbuf *m;
7128105197Ssam	const struct sadb_msghdr *mhp;
7129105197Ssam{
7130105197Ssam	struct secashead *sah;
7131105197Ssam	struct secasvar *sav;
7132105197Ssam	u_int16_t proto;
7133105197Ssam	u_int stateidx;
7134105197Ssam	u_int8_t satype;
7135105197Ssam	u_int8_t state;
7136105197Ssam	int cnt;
7137105197Ssam	struct sadb_msg *newmsg;
7138105197Ssam	struct mbuf *n;
7139105197Ssam
7140120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7141120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7142120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7143120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7144105197Ssam
7145105197Ssam	/* map satype to proto */
7146105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7147120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7148120585Ssam			__func__));
7149105197Ssam		return key_senderror(so, m, EINVAL);
7150105197Ssam	}
7151105197Ssam
7152105197Ssam	/* count sav entries to be sent to the userland. */
7153105197Ssam	cnt = 0;
7154120585Ssam	SAHTREE_LOCK();
7155181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7156105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7157105197Ssam		 && proto != sah->saidx.proto)
7158105197Ssam			continue;
7159105197Ssam
7160105197Ssam		for (stateidx = 0;
7161185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
7162105197Ssam		     stateidx++) {
7163185348Szec			state = saorder_state_any[stateidx];
7164105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7165105197Ssam				cnt++;
7166105197Ssam			}
7167105197Ssam		}
7168105197Ssam	}
7169105197Ssam
7170119643Ssam	if (cnt == 0) {
7171120585Ssam		SAHTREE_UNLOCK();
7172105197Ssam		return key_senderror(so, m, ENOENT);
7173119643Ssam	}
7174105197Ssam
7175105197Ssam	/* send this to the userland, one at a time. */
7176105197Ssam	newmsg = NULL;
7177181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7178105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7179105197Ssam		 && proto != sah->saidx.proto)
7180105197Ssam			continue;
7181105197Ssam
7182105197Ssam		/* map proto to satype */
7183105197Ssam		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7184120585Ssam			SAHTREE_UNLOCK();
7185120585Ssam			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7186120585Ssam				"SAD.\n", __func__));
7187105197Ssam			return key_senderror(so, m, EINVAL);
7188105197Ssam		}
7189105197Ssam
7190105197Ssam		for (stateidx = 0;
7191185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
7192105197Ssam		     stateidx++) {
7193185348Szec			state = saorder_state_any[stateidx];
7194105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7195105197Ssam				n = key_setdumpsa(sav, SADB_DUMP, satype,
7196105197Ssam				    --cnt, mhp->msg->sadb_msg_pid);
7197119643Ssam				if (!n) {
7198120585Ssam					SAHTREE_UNLOCK();
7199105197Ssam					return key_senderror(so, m, ENOBUFS);
7200119643Ssam				}
7201105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7202105197Ssam			}
7203105197Ssam		}
7204105197Ssam	}
7205120585Ssam	SAHTREE_UNLOCK();
7206105197Ssam
7207105197Ssam	m_freem(m);
7208105197Ssam	return 0;
7209105197Ssam}
7210105197Ssam
7211105197Ssam/*
7212105197Ssam * SADB_X_PROMISC processing
7213105197Ssam *
7214105197Ssam * m will always be freed.
7215105197Ssam */
7216105197Ssamstatic int
7217105197Ssamkey_promisc(so, m, mhp)
7218105197Ssam	struct socket *so;
7219105197Ssam	struct mbuf *m;
7220105197Ssam	const struct sadb_msghdr *mhp;
7221105197Ssam{
7222105197Ssam	int olen;
7223105197Ssam
7224120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7225120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7226120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7227120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7228105197Ssam
7229105197Ssam	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7230105197Ssam
7231105197Ssam	if (olen < sizeof(struct sadb_msg)) {
7232105197Ssam#if 1
7233105197Ssam		return key_senderror(so, m, EINVAL);
7234105197Ssam#else
7235105197Ssam		m_freem(m);
7236105197Ssam		return 0;
7237105197Ssam#endif
7238105197Ssam	} else if (olen == sizeof(struct sadb_msg)) {
7239105197Ssam		/* enable/disable promisc mode */
7240105197Ssam		struct keycb *kp;
7241105197Ssam
7242105197Ssam		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7243105197Ssam			return key_senderror(so, m, EINVAL);
7244105197Ssam		mhp->msg->sadb_msg_errno = 0;
7245105197Ssam		switch (mhp->msg->sadb_msg_satype) {
7246105197Ssam		case 0:
7247105197Ssam		case 1:
7248105197Ssam			kp->kp_promisc = mhp->msg->sadb_msg_satype;
7249105197Ssam			break;
7250105197Ssam		default:
7251105197Ssam			return key_senderror(so, m, EINVAL);
7252105197Ssam		}
7253105197Ssam
7254105197Ssam		/* send the original message back to everyone */
7255105197Ssam		mhp->msg->sadb_msg_errno = 0;
7256105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7257105197Ssam	} else {
7258105197Ssam		/* send packet as is */
7259105197Ssam
7260105197Ssam		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7261105197Ssam
7262105197Ssam		/* TODO: if sadb_msg_seq is specified, send to specific pid */
7263105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7264105197Ssam	}
7265105197Ssam}
7266105197Ssam
7267105197Ssamstatic int (*key_typesw[]) __P((struct socket *, struct mbuf *,
7268105197Ssam		const struct sadb_msghdr *)) = {
7269105197Ssam	NULL,		/* SADB_RESERVED */
7270105197Ssam	key_getspi,	/* SADB_GETSPI */
7271105197Ssam	key_update,	/* SADB_UPDATE */
7272105197Ssam	key_add,	/* SADB_ADD */
7273105197Ssam	key_delete,	/* SADB_DELETE */
7274105197Ssam	key_get,	/* SADB_GET */
7275105197Ssam	key_acquire2,	/* SADB_ACQUIRE */
7276105197Ssam	key_register,	/* SADB_REGISTER */
7277105197Ssam	NULL,		/* SADB_EXPIRE */
7278105197Ssam	key_flush,	/* SADB_FLUSH */
7279105197Ssam	key_dump,	/* SADB_DUMP */
7280105197Ssam	key_promisc,	/* SADB_X_PROMISC */
7281105197Ssam	NULL,		/* SADB_X_PCHANGE */
7282105197Ssam	key_spdadd,	/* SADB_X_SPDUPDATE */
7283105197Ssam	key_spdadd,	/* SADB_X_SPDADD */
7284105197Ssam	key_spddelete,	/* SADB_X_SPDDELETE */
7285105197Ssam	key_spdget,	/* SADB_X_SPDGET */
7286105197Ssam	NULL,		/* SADB_X_SPDACQUIRE */
7287105197Ssam	key_spddump,	/* SADB_X_SPDDUMP */
7288105197Ssam	key_spdflush,	/* SADB_X_SPDFLUSH */
7289105197Ssam	key_spdadd,	/* SADB_X_SPDSETIDX */
7290105197Ssam	NULL,		/* SADB_X_SPDEXPIRE */
7291105197Ssam	key_spddelete2,	/* SADB_X_SPDDELETE2 */
7292105197Ssam};
7293105197Ssam
7294105197Ssam/*
7295105197Ssam * parse sadb_msg buffer to process PFKEYv2,
7296105197Ssam * and create a data to response if needed.
7297105197Ssam * I think to be dealed with mbuf directly.
7298105197Ssam * IN:
7299105197Ssam *     msgp  : pointer to pointer to a received buffer pulluped.
7300105197Ssam *             This is rewrited to response.
7301105197Ssam *     so    : pointer to socket.
7302105197Ssam * OUT:
7303105197Ssam *    length for buffer to send to user process.
7304105197Ssam */
7305105197Ssamint
7306105197Ssamkey_parse(m, so)
7307105197Ssam	struct mbuf *m;
7308105197Ssam	struct socket *so;
7309105197Ssam{
7310105197Ssam	struct sadb_msg *msg;
7311105197Ssam	struct sadb_msghdr mh;
7312105197Ssam	u_int orglen;
7313105197Ssam	int error;
7314105197Ssam	int target;
7315105197Ssam
7316120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7317120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7318105197Ssam
7319105197Ssam#if 0	/*kdebug_sadb assumes msg in linear buffer*/
7320105197Ssam	KEYDEBUG(KEYDEBUG_KEY_DUMP,
7321120585Ssam		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7322105197Ssam		kdebug_sadb(msg));
7323105197Ssam#endif
7324105197Ssam
7325105197Ssam	if (m->m_len < sizeof(struct sadb_msg)) {
7326105197Ssam		m = m_pullup(m, sizeof(struct sadb_msg));
7327105197Ssam		if (!m)
7328105197Ssam			return ENOBUFS;
7329105197Ssam	}
7330105197Ssam	msg = mtod(m, struct sadb_msg *);
7331105197Ssam	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7332105197Ssam	target = KEY_SENDUP_ONE;
7333105197Ssam
7334105197Ssam	if ((m->m_flags & M_PKTHDR) == 0 ||
7335105197Ssam	    m->m_pkthdr.len != m->m_pkthdr.len) {
7336120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7337181803Sbz		V_pfkeystat.out_invlen++;
7338105197Ssam		error = EINVAL;
7339105197Ssam		goto senderror;
7340105197Ssam	}
7341105197Ssam
7342105197Ssam	if (msg->sadb_msg_version != PF_KEY_V2) {
7343120585Ssam		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7344120585Ssam		    __func__, msg->sadb_msg_version));
7345181803Sbz		V_pfkeystat.out_invver++;
7346105197Ssam		error = EINVAL;
7347105197Ssam		goto senderror;
7348105197Ssam	}
7349105197Ssam
7350105197Ssam	if (msg->sadb_msg_type > SADB_MAX) {
7351120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7352120585Ssam		    __func__, msg->sadb_msg_type));
7353181803Sbz		V_pfkeystat.out_invmsgtype++;
7354105197Ssam		error = EINVAL;
7355105197Ssam		goto senderror;
7356105197Ssam	}
7357105197Ssam
7358105197Ssam	/* for old-fashioned code - should be nuked */
7359105197Ssam	if (m->m_pkthdr.len > MCLBYTES) {
7360105197Ssam		m_freem(m);
7361105197Ssam		return ENOBUFS;
7362105197Ssam	}
7363105197Ssam	if (m->m_next) {
7364105197Ssam		struct mbuf *n;
7365105197Ssam
7366111119Simp		MGETHDR(n, M_DONTWAIT, MT_DATA);
7367105197Ssam		if (n && m->m_pkthdr.len > MHLEN) {
7368111119Simp			MCLGET(n, M_DONTWAIT);
7369105197Ssam			if ((n->m_flags & M_EXT) == 0) {
7370105197Ssam				m_free(n);
7371105197Ssam				n = NULL;
7372105197Ssam			}
7373105197Ssam		}
7374105197Ssam		if (!n) {
7375105197Ssam			m_freem(m);
7376105197Ssam			return ENOBUFS;
7377105197Ssam		}
7378105197Ssam		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7379105197Ssam		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7380105197Ssam		n->m_next = NULL;
7381105197Ssam		m_freem(m);
7382105197Ssam		m = n;
7383105197Ssam	}
7384105197Ssam
7385105197Ssam	/* align the mbuf chain so that extensions are in contiguous region. */
7386105197Ssam	error = key_align(m, &mh);
7387105197Ssam	if (error)
7388105197Ssam		return error;
7389105197Ssam
7390105197Ssam	msg = mh.msg;
7391105197Ssam
7392105197Ssam	/* check SA type */
7393105197Ssam	switch (msg->sadb_msg_satype) {
7394105197Ssam	case SADB_SATYPE_UNSPEC:
7395105197Ssam		switch (msg->sadb_msg_type) {
7396105197Ssam		case SADB_GETSPI:
7397105197Ssam		case SADB_UPDATE:
7398105197Ssam		case SADB_ADD:
7399105197Ssam		case SADB_DELETE:
7400105197Ssam		case SADB_GET:
7401105197Ssam		case SADB_ACQUIRE:
7402105197Ssam		case SADB_EXPIRE:
7403120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify satype "
7404120585Ssam			    "when msg type=%u.\n", __func__,
7405120585Ssam			    msg->sadb_msg_type));
7406181803Sbz			V_pfkeystat.out_invsatype++;
7407105197Ssam			error = EINVAL;
7408105197Ssam			goto senderror;
7409105197Ssam		}
7410105197Ssam		break;
7411105197Ssam	case SADB_SATYPE_AH:
7412105197Ssam	case SADB_SATYPE_ESP:
7413105197Ssam	case SADB_X_SATYPE_IPCOMP:
7414125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
7415105197Ssam		switch (msg->sadb_msg_type) {
7416105197Ssam		case SADB_X_SPDADD:
7417105197Ssam		case SADB_X_SPDDELETE:
7418105197Ssam		case SADB_X_SPDGET:
7419105197Ssam		case SADB_X_SPDDUMP:
7420105197Ssam		case SADB_X_SPDFLUSH:
7421105197Ssam		case SADB_X_SPDSETIDX:
7422105197Ssam		case SADB_X_SPDUPDATE:
7423105197Ssam		case SADB_X_SPDDELETE2:
7424120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7425120585Ssam				__func__, msg->sadb_msg_type));
7426181803Sbz			V_pfkeystat.out_invsatype++;
7427105197Ssam			error = EINVAL;
7428105197Ssam			goto senderror;
7429105197Ssam		}
7430105197Ssam		break;
7431105197Ssam	case SADB_SATYPE_RSVP:
7432105197Ssam	case SADB_SATYPE_OSPFV2:
7433105197Ssam	case SADB_SATYPE_RIPV2:
7434105197Ssam	case SADB_SATYPE_MIP:
7435120585Ssam		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7436120585Ssam			__func__, msg->sadb_msg_satype));
7437181803Sbz		V_pfkeystat.out_invsatype++;
7438105197Ssam		error = EOPNOTSUPP;
7439105197Ssam		goto senderror;
7440105197Ssam	case 1:	/* XXX: What does it do? */
7441105197Ssam		if (msg->sadb_msg_type == SADB_X_PROMISC)
7442105197Ssam			break;
7443105197Ssam		/*FALLTHROUGH*/
7444105197Ssam	default:
7445120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7446120585Ssam			__func__, msg->sadb_msg_satype));
7447181803Sbz		V_pfkeystat.out_invsatype++;
7448105197Ssam		error = EINVAL;
7449105197Ssam		goto senderror;
7450105197Ssam	}
7451105197Ssam
7452105197Ssam	/* check field of upper layer protocol and address family */
7453105197Ssam	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7454105197Ssam	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7455105197Ssam		struct sadb_address *src0, *dst0;
7456105197Ssam		u_int plen;
7457105197Ssam
7458105197Ssam		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7459105197Ssam		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7460105197Ssam
7461105197Ssam		/* check upper layer protocol */
7462105197Ssam		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7463120585Ssam			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7464120585Ssam				"mismatched.\n", __func__));
7465181803Sbz			V_pfkeystat.out_invaddr++;
7466105197Ssam			error = EINVAL;
7467105197Ssam			goto senderror;
7468105197Ssam		}
7469105197Ssam
7470105197Ssam		/* check family */
7471105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7472105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
7473120585Ssam			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7474120585Ssam				__func__));
7475181803Sbz			V_pfkeystat.out_invaddr++;
7476105197Ssam			error = EINVAL;
7477105197Ssam			goto senderror;
7478105197Ssam		}
7479105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7480105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
7481120585Ssam			ipseclog((LOG_DEBUG, "%s: address struct size "
7482120585Ssam				"mismatched.\n", __func__));
7483181803Sbz			V_pfkeystat.out_invaddr++;
7484105197Ssam			error = EINVAL;
7485105197Ssam			goto senderror;
7486105197Ssam		}
7487105197Ssam
7488105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7489105197Ssam		case AF_INET:
7490105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7491105197Ssam			    sizeof(struct sockaddr_in)) {
7492181803Sbz				V_pfkeystat.out_invaddr++;
7493105197Ssam				error = EINVAL;
7494105197Ssam				goto senderror;
7495105197Ssam			}
7496105197Ssam			break;
7497105197Ssam		case AF_INET6:
7498105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7499105197Ssam			    sizeof(struct sockaddr_in6)) {
7500181803Sbz				V_pfkeystat.out_invaddr++;
7501105197Ssam				error = EINVAL;
7502105197Ssam				goto senderror;
7503105197Ssam			}
7504105197Ssam			break;
7505105197Ssam		default:
7506120585Ssam			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7507120585Ssam				__func__));
7508181803Sbz			V_pfkeystat.out_invaddr++;
7509105197Ssam			error = EAFNOSUPPORT;
7510105197Ssam			goto senderror;
7511105197Ssam		}
7512105197Ssam
7513105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7514105197Ssam		case AF_INET:
7515105197Ssam			plen = sizeof(struct in_addr) << 3;
7516105197Ssam			break;
7517105197Ssam		case AF_INET6:
7518105197Ssam			plen = sizeof(struct in6_addr) << 3;
7519105197Ssam			break;
7520105197Ssam		default:
7521105197Ssam			plen = 0;	/*fool gcc*/
7522105197Ssam			break;
7523105197Ssam		}
7524105197Ssam
7525105197Ssam		/* check max prefix length */
7526105197Ssam		if (src0->sadb_address_prefixlen > plen ||
7527105197Ssam		    dst0->sadb_address_prefixlen > plen) {
7528120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7529120585Ssam				__func__));
7530181803Sbz			V_pfkeystat.out_invaddr++;
7531105197Ssam			error = EINVAL;
7532105197Ssam			goto senderror;
7533105197Ssam		}
7534105197Ssam
7535105197Ssam		/*
7536105197Ssam		 * prefixlen == 0 is valid because there can be a case when
7537105197Ssam		 * all addresses are matched.
7538105197Ssam		 */
7539105197Ssam	}
7540105197Ssam
7541105197Ssam	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7542105197Ssam	    key_typesw[msg->sadb_msg_type] == NULL) {
7543181803Sbz		V_pfkeystat.out_invmsgtype++;
7544105197Ssam		error = EINVAL;
7545105197Ssam		goto senderror;
7546105197Ssam	}
7547105197Ssam
7548105197Ssam	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7549105197Ssam
7550105197Ssamsenderror:
7551105197Ssam	msg->sadb_msg_errno = error;
7552105197Ssam	return key_sendup_mbuf(so, m, target);
7553105197Ssam}
7554105197Ssam
7555105197Ssamstatic int
7556105197Ssamkey_senderror(so, m, code)
7557105197Ssam	struct socket *so;
7558105197Ssam	struct mbuf *m;
7559105197Ssam	int code;
7560105197Ssam{
7561105197Ssam	struct sadb_msg *msg;
7562105197Ssam
7563120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7564120585Ssam		("mbuf too small, len %u", m->m_len));
7565105197Ssam
7566105197Ssam	msg = mtod(m, struct sadb_msg *);
7567105197Ssam	msg->sadb_msg_errno = code;
7568105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7569105197Ssam}
7570105197Ssam
7571105197Ssam/*
7572105197Ssam * set the pointer to each header into message buffer.
7573105197Ssam * m will be freed on error.
7574105197Ssam * XXX larger-than-MCLBYTES extension?
7575105197Ssam */
7576105197Ssamstatic int
7577105197Ssamkey_align(m, mhp)
7578105197Ssam	struct mbuf *m;
7579105197Ssam	struct sadb_msghdr *mhp;
7580105197Ssam{
7581105197Ssam	struct mbuf *n;
7582105197Ssam	struct sadb_ext *ext;
7583105197Ssam	size_t off, end;
7584105197Ssam	int extlen;
7585105197Ssam	int toff;
7586105197Ssam
7587120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7588120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7589120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7590120585Ssam		("mbuf too small, len %u", m->m_len));
7591105197Ssam
7592105197Ssam	/* initialize */
7593105197Ssam	bzero(mhp, sizeof(*mhp));
7594105197Ssam
7595105197Ssam	mhp->msg = mtod(m, struct sadb_msg *);
7596105197Ssam	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7597105197Ssam
7598105197Ssam	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7599105197Ssam	extlen = end;	/*just in case extlen is not updated*/
7600105197Ssam	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7601105197Ssam		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7602105197Ssam		if (!n) {
7603105197Ssam			/* m is already freed */
7604105197Ssam			return ENOBUFS;
7605105197Ssam		}
7606105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7607105197Ssam
7608105197Ssam		/* set pointer */
7609105197Ssam		switch (ext->sadb_ext_type) {
7610105197Ssam		case SADB_EXT_SA:
7611105197Ssam		case SADB_EXT_ADDRESS_SRC:
7612105197Ssam		case SADB_EXT_ADDRESS_DST:
7613105197Ssam		case SADB_EXT_ADDRESS_PROXY:
7614105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
7615105197Ssam		case SADB_EXT_LIFETIME_HARD:
7616105197Ssam		case SADB_EXT_LIFETIME_SOFT:
7617105197Ssam		case SADB_EXT_KEY_AUTH:
7618105197Ssam		case SADB_EXT_KEY_ENCRYPT:
7619105197Ssam		case SADB_EXT_IDENTITY_SRC:
7620105197Ssam		case SADB_EXT_IDENTITY_DST:
7621105197Ssam		case SADB_EXT_SENSITIVITY:
7622105197Ssam		case SADB_EXT_PROPOSAL:
7623105197Ssam		case SADB_EXT_SUPPORTED_AUTH:
7624105197Ssam		case SADB_EXT_SUPPORTED_ENCRYPT:
7625105197Ssam		case SADB_EXT_SPIRANGE:
7626105197Ssam		case SADB_X_EXT_POLICY:
7627105197Ssam		case SADB_X_EXT_SA2:
7628194062Svanhu#ifdef IPSEC_NAT_T
7629194062Svanhu		case SADB_X_EXT_NAT_T_TYPE:
7630194062Svanhu		case SADB_X_EXT_NAT_T_SPORT:
7631194062Svanhu		case SADB_X_EXT_NAT_T_DPORT:
7632194062Svanhu		case SADB_X_EXT_NAT_T_OAI:
7633194062Svanhu		case SADB_X_EXT_NAT_T_OAR:
7634194062Svanhu		case SADB_X_EXT_NAT_T_FRAG:
7635194062Svanhu#endif
7636105197Ssam			/* duplicate check */
7637105197Ssam			/*
7638105197Ssam			 * XXX Are there duplication payloads of either
7639105197Ssam			 * KEY_AUTH or KEY_ENCRYPT ?
7640105197Ssam			 */
7641105197Ssam			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7642120585Ssam				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7643120585Ssam					"%u\n", __func__, ext->sadb_ext_type));
7644105197Ssam				m_freem(m);
7645181803Sbz				V_pfkeystat.out_dupext++;
7646105197Ssam				return EINVAL;
7647105197Ssam			}
7648105197Ssam			break;
7649105197Ssam		default:
7650120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7651120585Ssam				__func__, ext->sadb_ext_type));
7652105197Ssam			m_freem(m);
7653181803Sbz			V_pfkeystat.out_invexttype++;
7654105197Ssam			return EINVAL;
7655105197Ssam		}
7656105197Ssam
7657105197Ssam		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7658105197Ssam
7659105197Ssam		if (key_validate_ext(ext, extlen)) {
7660105197Ssam			m_freem(m);
7661181803Sbz			V_pfkeystat.out_invlen++;
7662105197Ssam			return EINVAL;
7663105197Ssam		}
7664105197Ssam
7665105197Ssam		n = m_pulldown(m, off, extlen, &toff);
7666105197Ssam		if (!n) {
7667105197Ssam			/* m is already freed */
7668105197Ssam			return ENOBUFS;
7669105197Ssam		}
7670105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7671105197Ssam
7672105197Ssam		mhp->ext[ext->sadb_ext_type] = ext;
7673105197Ssam		mhp->extoff[ext->sadb_ext_type] = off;
7674105197Ssam		mhp->extlen[ext->sadb_ext_type] = extlen;
7675105197Ssam	}
7676105197Ssam
7677105197Ssam	if (off != end) {
7678105197Ssam		m_freem(m);
7679181803Sbz		V_pfkeystat.out_invlen++;
7680105197Ssam		return EINVAL;
7681105197Ssam	}
7682105197Ssam
7683105197Ssam	return 0;
7684105197Ssam}
7685105197Ssam
7686105197Ssamstatic int
7687105197Ssamkey_validate_ext(ext, len)
7688105197Ssam	const struct sadb_ext *ext;
7689105197Ssam	int len;
7690105197Ssam{
7691105197Ssam	const struct sockaddr *sa;
7692105197Ssam	enum { NONE, ADDR } checktype = NONE;
7693105197Ssam	int baselen = 0;
7694105197Ssam	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7695105197Ssam
7696105197Ssam	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7697105197Ssam		return EINVAL;
7698105197Ssam
7699105197Ssam	/* if it does not match minimum/maximum length, bail */
7700105197Ssam	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7701105197Ssam	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7702105197Ssam		return EINVAL;
7703105197Ssam	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7704105197Ssam		return EINVAL;
7705105197Ssam	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7706105197Ssam		return EINVAL;
7707105197Ssam
7708105197Ssam	/* more checks based on sadb_ext_type XXX need more */
7709105197Ssam	switch (ext->sadb_ext_type) {
7710105197Ssam	case SADB_EXT_ADDRESS_SRC:
7711105197Ssam	case SADB_EXT_ADDRESS_DST:
7712105197Ssam	case SADB_EXT_ADDRESS_PROXY:
7713105197Ssam		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7714105197Ssam		checktype = ADDR;
7715105197Ssam		break;
7716105197Ssam	case SADB_EXT_IDENTITY_SRC:
7717105197Ssam	case SADB_EXT_IDENTITY_DST:
7718105197Ssam		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7719105197Ssam		    SADB_X_IDENTTYPE_ADDR) {
7720105197Ssam			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7721105197Ssam			checktype = ADDR;
7722105197Ssam		} else
7723105197Ssam			checktype = NONE;
7724105197Ssam		break;
7725105197Ssam	default:
7726105197Ssam		checktype = NONE;
7727105197Ssam		break;
7728105197Ssam	}
7729105197Ssam
7730105197Ssam	switch (checktype) {
7731105197Ssam	case NONE:
7732105197Ssam		break;
7733105197Ssam	case ADDR:
7734105197Ssam		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7735105197Ssam		if (len < baselen + sal)
7736105197Ssam			return EINVAL;
7737105197Ssam		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7738105197Ssam			return EINVAL;
7739105197Ssam		break;
7740105197Ssam	}
7741105197Ssam
7742105197Ssam	return 0;
7743105197Ssam}
7744105197Ssam
7745105197Ssamvoid
7746180086Sjuliankey_init(void)
7747105197Ssam{
7748105197Ssam	int i;
7749105197Ssam
7750119643Ssam	for (i = 0; i < IPSEC_DIR_MAX; i++)
7751181803Sbz		LIST_INIT(&V_sptree[i]);
7752105197Ssam
7753181803Sbz	LIST_INIT(&V_sahtree);
7754105197Ssam
7755119643Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7756181803Sbz		LIST_INIT(&V_regtree[i]);
7757105197Ssam
7758181803Sbz	LIST_INIT(&V_acqtree);
7759181803Sbz	LIST_INIT(&V_spacqtree);
7760105197Ssam
7761105197Ssam	/* system default */
7762181803Sbz	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7763181803Sbz	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7764105197Ssam
7765190787Szec	if (!IS_DEFAULT_VNET(curvnet))
7766190787Szec		return;
7767190787Szec
7768190787Szec	SPTREE_LOCK_INIT();
7769190787Szec	REGTREE_LOCK_INIT();
7770190787Szec	SAHTREE_LOCK_INIT();
7771190787Szec	ACQ_LOCK_INIT();
7772190787Szec	SPACQ_LOCK_INIT();
7773190787Szec
7774105197Ssam#ifndef IPSEC_DEBUG2
7775105197Ssam	timeout((void *)key_timehandler, (void *)0, hz);
7776105197Ssam#endif /*IPSEC_DEBUG2*/
7777105197Ssam
7778105197Ssam	/* initialize key statistics */
7779105197Ssam	keystat.getspi_count = 1;
7780105197Ssam
7781177173Sbz	printf("IPsec: Initialized Security Association Processing.\n");
7782193731Szec}
7783105197Ssam
7784193731Szec#ifdef VIMAGE
7785193731Szecvoid
7786193731Szeckey_destroy(void)
7787193731Szec{
7788193731Szec	struct secpolicy *sp, *nextsp;
7789205789Sbz	struct secacq *acq, *nextacq;
7790205789Sbz	struct secspacq *spacq, *nextspacq;
7791193731Szec	struct secashead *sah, *nextsah;
7792193731Szec	struct secreg *reg;
7793193731Szec	int i;
7794193731Szec
7795193731Szec	SPTREE_LOCK();
7796193731Szec	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7797193731Szec		for (sp = LIST_FIRST(&V_sptree[i]);
7798193731Szec		    sp != NULL; sp = nextsp) {
7799193731Szec			nextsp = LIST_NEXT(sp, chain);
7800193731Szec			if (__LIST_CHAINED(sp)) {
7801193731Szec				LIST_REMOVE(sp, chain);
7802193731Szec				free(sp, M_IPSEC_SP);
7803193731Szec			}
7804193731Szec		}
7805193731Szec	}
7806193731Szec	SPTREE_UNLOCK();
7807193731Szec
7808193731Szec	SAHTREE_LOCK();
7809193731Szec	for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7810193731Szec		nextsah = LIST_NEXT(sah, chain);
7811193731Szec		if (__LIST_CHAINED(sah)) {
7812193731Szec			LIST_REMOVE(sah, chain);
7813193731Szec			free(sah, M_IPSEC_SAH);
7814193731Szec		}
7815193731Szec	}
7816193731Szec	SAHTREE_UNLOCK();
7817193731Szec
7818193731Szec	REGTREE_LOCK();
7819193731Szec	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7820193731Szec		LIST_FOREACH(reg, &V_regtree[i], chain) {
7821193731Szec			if (__LIST_CHAINED(reg)) {
7822193731Szec				LIST_REMOVE(reg, chain);
7823193731Szec				free(reg, M_IPSEC_SAR);
7824193731Szec				break;
7825193731Szec			}
7826193731Szec		}
7827193731Szec	}
7828193731Szec	REGTREE_UNLOCK();
7829193731Szec
7830193731Szec	ACQ_LOCK();
7831205789Sbz	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
7832193731Szec		nextacq = LIST_NEXT(acq, chain);
7833193731Szec		if (__LIST_CHAINED(acq)) {
7834193731Szec			LIST_REMOVE(acq, chain);
7835193731Szec			free(acq, M_IPSEC_SAQ);
7836193731Szec		}
7837193731Szec	}
7838193731Szec	ACQ_UNLOCK();
7839193731Szec
7840193731Szec	SPACQ_LOCK();
7841205789Sbz	for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
7842205789Sbz	    spacq = nextspacq) {
7843205789Sbz		nextspacq = LIST_NEXT(spacq, chain);
7844205789Sbz		if (__LIST_CHAINED(spacq)) {
7845205789Sbz			LIST_REMOVE(spacq, chain);
7846205789Sbz			free(spacq, M_IPSEC_SAQ);
7847193731Szec		}
7848193731Szec	}
7849193731Szec	SPACQ_UNLOCK();
7850105197Ssam}
7851193731Szec#endif
7852105197Ssam
7853105197Ssam/*
7854105197Ssam * XXX: maybe This function is called after INBOUND IPsec processing.
7855105197Ssam *
7856105197Ssam * Special check for tunnel-mode packets.
7857105197Ssam * We must make some checks for consistency between inner and outer IP header.
7858105197Ssam *
7859105197Ssam * xxx more checks to be provided
7860105197Ssam */
7861105197Ssamint
7862105197Ssamkey_checktunnelsanity(sav, family, src, dst)
7863105197Ssam	struct secasvar *sav;
7864105197Ssam	u_int family;
7865105197Ssam	caddr_t src;
7866105197Ssam	caddr_t dst;
7867105197Ssam{
7868120585Ssam	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7869105197Ssam
7870105197Ssam	/* XXX: check inner IP header */
7871105197Ssam
7872105197Ssam	return 1;
7873105197Ssam}
7874105197Ssam
7875105197Ssam/* record data transfer on SA, and update timestamps */
7876105197Ssamvoid
7877105197Ssamkey_sa_recordxfer(sav, m)
7878105197Ssam	struct secasvar *sav;
7879105197Ssam	struct mbuf *m;
7880105197Ssam{
7881120585Ssam	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7882120585Ssam	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7883105197Ssam	if (!sav->lft_c)
7884105197Ssam		return;
7885105197Ssam
7886105197Ssam	/*
7887105197Ssam	 * XXX Currently, there is a difference of bytes size
7888105197Ssam	 * between inbound and outbound processing.
7889105197Ssam	 */
7890157123Sgnn	sav->lft_c->bytes += m->m_pkthdr.len;
7891105197Ssam	/* to check bytes lifetime is done in key_timehandler(). */
7892105197Ssam
7893105197Ssam	/*
7894105197Ssam	 * We use the number of packets as the unit of
7895157123Sgnn	 * allocations.  We increment the variable
7896105197Ssam	 * whenever {esp,ah}_{in,out}put is called.
7897105197Ssam	 */
7898157123Sgnn	sav->lft_c->allocations++;
7899105197Ssam	/* XXX check for expires? */
7900105197Ssam
7901105197Ssam	/*
7902157123Sgnn	 * NOTE: We record CURRENT usetime by using wall clock,
7903105197Ssam	 * in seconds.  HARD and SOFT lifetime are measured by the time
7904157123Sgnn	 * difference (again in seconds) from usetime.
7905105197Ssam	 *
7906105197Ssam	 *	usetime
7907105197Ssam	 *	v     expire   expire
7908105197Ssam	 * -----+-----+--------+---> t
7909105197Ssam	 *	<--------------> HARD
7910105197Ssam	 *	<-----> SOFT
7911105197Ssam	 */
7912157123Sgnn	sav->lft_c->usetime = time_second;
7913105197Ssam	/* XXX check for expires? */
7914105197Ssam
7915105197Ssam	return;
7916105197Ssam}
7917105197Ssam
7918105197Ssam/* dumb version */
7919105197Ssamvoid
7920105197Ssamkey_sa_routechange(dst)
7921105197Ssam	struct sockaddr *dst;
7922105197Ssam{
7923105197Ssam	struct secashead *sah;
7924105197Ssam	struct route *ro;
7925105197Ssam
7926120585Ssam	SAHTREE_LOCK();
7927181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7928105197Ssam		ro = &sah->sa_route;
7929105197Ssam		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7930105197Ssam		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7931105197Ssam			RTFREE(ro->ro_rt);
7932105197Ssam			ro->ro_rt = (struct rtentry *)NULL;
7933105197Ssam		}
7934105197Ssam	}
7935120585Ssam	SAHTREE_UNLOCK();
7936105197Ssam}
7937105197Ssam
7938105197Ssamstatic void
7939189004Srdivackykey_sa_chgstate(struct secasvar *sav, u_int8_t state)
7940105197Ssam{
7941120585Ssam	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7942120585Ssam	SAHTREE_LOCK_ASSERT();
7943105197Ssam
7944119643Ssam	if (sav->state != state) {
7945119643Ssam		if (__LIST_CHAINED(sav))
7946119643Ssam			LIST_REMOVE(sav, chain);
7947119643Ssam		sav->state = state;
7948119643Ssam		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7949119643Ssam	}
7950105197Ssam}
7951105197Ssam
7952105197Ssamvoid
7953105197Ssamkey_sa_stir_iv(sav)
7954105197Ssam	struct secasvar *sav;
7955105197Ssam{
7956105197Ssam
7957120585Ssam	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7958105197Ssam	key_randomfill(sav->iv, sav->ivlen);
7959105197Ssam}
7960105197Ssam
7961105197Ssam/* XXX too much? */
7962105197Ssamstatic struct mbuf *
7963105197Ssamkey_alloc_mbuf(l)
7964105197Ssam	int l;
7965105197Ssam{
7966105197Ssam	struct mbuf *m = NULL, *n;
7967105197Ssam	int len, t;
7968105197Ssam
7969105197Ssam	len = l;
7970105197Ssam	while (len > 0) {
7971111119Simp		MGET(n, M_DONTWAIT, MT_DATA);
7972105197Ssam		if (n && len > MLEN)
7973111119Simp			MCLGET(n, M_DONTWAIT);
7974105197Ssam		if (!n) {
7975105197Ssam			m_freem(m);
7976105197Ssam			return NULL;
7977105197Ssam		}
7978105197Ssam
7979105197Ssam		n->m_next = NULL;
7980105197Ssam		n->m_len = 0;
7981105197Ssam		n->m_len = M_TRAILINGSPACE(n);
7982105197Ssam		/* use the bottom of mbuf, hoping we can prepend afterwards */
7983105197Ssam		if (n->m_len > len) {
7984105197Ssam			t = (n->m_len - len) & ~(sizeof(long) - 1);
7985105197Ssam			n->m_data += t;
7986105197Ssam			n->m_len = len;
7987105197Ssam		}
7988105197Ssam
7989105197Ssam		len -= n->m_len;
7990105197Ssam
7991105197Ssam		if (m)
7992105197Ssam			m_cat(m, n);
7993105197Ssam		else
7994105197Ssam			m = n;
7995105197Ssam	}
7996105197Ssam
7997105197Ssam	return m;
7998105197Ssam}
7999157123Sgnn
8000157123Sgnn/*
8001157123Sgnn * Take one of the kernel's security keys and convert it into a PF_KEY
8002157123Sgnn * structure within an mbuf, suitable for sending up to a waiting
8003157123Sgnn * application in user land.
8004157123Sgnn *
8005157123Sgnn * IN:
8006157123Sgnn *    src: A pointer to a kernel security key.
8007157123Sgnn *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
8008157123Sgnn * OUT:
8009157123Sgnn *    a valid mbuf or NULL indicating an error
8010157123Sgnn *
8011157123Sgnn */
8012157123Sgnn
8013157123Sgnnstatic struct mbuf *
8014157123Sgnnkey_setkey(struct seckey *src, u_int16_t exttype)
8015157123Sgnn{
8016157123Sgnn	struct mbuf *m;
8017157123Sgnn	struct sadb_key *p;
8018170799Sbz	int len;
8019157123Sgnn
8020157123Sgnn	if (src == NULL)
8021157123Sgnn		return NULL;
8022157123Sgnn
8023170799Sbz	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8024157123Sgnn	m = key_alloc_mbuf(len);
8025157123Sgnn	if (m == NULL)
8026157123Sgnn		return NULL;
8027157123Sgnn	p = mtod(m, struct sadb_key *);
8028157123Sgnn	bzero(p, len);
8029157123Sgnn	p->sadb_key_len = PFKEY_UNIT64(len);
8030157123Sgnn	p->sadb_key_exttype = exttype;
8031157123Sgnn	p->sadb_key_bits = src->bits;
8032157123Sgnn	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8033157123Sgnn
8034157123Sgnn	return m;
8035157123Sgnn}
8036157123Sgnn
8037157123Sgnn/*
8038157123Sgnn * Take one of the kernel's lifetime data structures and convert it
8039157123Sgnn * into a PF_KEY structure within an mbuf, suitable for sending up to
8040157123Sgnn * a waiting application in user land.
8041157123Sgnn *
8042157123Sgnn * IN:
8043157123Sgnn *    src: A pointer to a kernel lifetime structure.
8044157123Sgnn *    exttype: Which type of lifetime this is. Refer to the PF_KEY
8045157123Sgnn *             data structures for more information.
8046157123Sgnn * OUT:
8047157123Sgnn *    a valid mbuf or NULL indicating an error
8048157123Sgnn *
8049157123Sgnn */
8050157123Sgnn
8051157123Sgnnstatic struct mbuf *
8052157123Sgnnkey_setlifetime(struct seclifetime *src, u_int16_t exttype)
8053157123Sgnn{
8054157123Sgnn	struct mbuf *m = NULL;
8055157123Sgnn	struct sadb_lifetime *p;
8056157123Sgnn	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8057157123Sgnn
8058157123Sgnn	if (src == NULL)
8059157123Sgnn		return NULL;
8060157123Sgnn
8061157123Sgnn	m = key_alloc_mbuf(len);
8062157123Sgnn	if (m == NULL)
8063157123Sgnn		return m;
8064157123Sgnn	p = mtod(m, struct sadb_lifetime *);
8065157123Sgnn
8066157123Sgnn	bzero(p, len);
8067157123Sgnn	p->sadb_lifetime_len = PFKEY_UNIT64(len);
8068157123Sgnn	p->sadb_lifetime_exttype = exttype;
8069157123Sgnn	p->sadb_lifetime_allocations = src->allocations;
8070157123Sgnn	p->sadb_lifetime_bytes = src->bytes;
8071157123Sgnn	p->sadb_lifetime_addtime = src->addtime;
8072157123Sgnn	p->sadb_lifetime_usetime = src->usetime;
8073157123Sgnn
8074157123Sgnn	return m;
8075157123Sgnn
8076157123Sgnn}
8077