key.c revision 206659
1105197Ssam/*	$FreeBSD: head/sys/netipsec/key.c 206659 2010-04-15 12:40:33Z 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;
117195727Srwatson#define	V_key_spi_trycnt	VNET(key_spi_trycnt)
118195699Srwatsonstatic VNET_DEFINE(u_int32_t, key_spi_minval) = 0x100;
119195727Srwatson#define	V_key_spi_minval	VNET(key_spi_minval)
120195699Srwatsonstatic VNET_DEFINE(u_int32_t, key_spi_maxval) = 0x0fffffff;	/* XXX */
121195727Srwatson#define	V_key_spi_maxval	VNET(key_spi_maxval)
122195699Srwatsonstatic VNET_DEFINE(u_int32_t, policy_id) = 0;
123195727Srwatson#define	V_policy_id		VNET(policy_id)
124195699Srwatson/*interval to initialize randseed,1(m)*/
125195699Srwatsonstatic VNET_DEFINE(u_int, key_int_random) = 60;
126195727Srwatson#define	V_key_int_random	VNET(key_int_random)
127195699Srwatson/* interval to expire acquiring, 30(s)*/
128195699Srwatsonstatic VNET_DEFINE(u_int, key_larval_lifetime) = 30;
129195727Srwatson#define	V_key_larval_lifetime	VNET(key_larval_lifetime)
130195699Srwatson/* counter for blocking SADB_ACQUIRE.*/
131195699Srwatsonstatic VNET_DEFINE(int, key_blockacq_count) = 10;
132195727Srwatson#define	V_key_blockacq_count	VNET(key_blockacq_count)
133195699Srwatson/* lifetime for blocking SADB_ACQUIRE.*/
134195699Srwatsonstatic VNET_DEFINE(int, key_blockacq_lifetime) = 20;
135195727Srwatson#define	V_key_blockacq_lifetime	VNET(key_blockacq_lifetime)
136195699Srwatson/* preferred old sa rather than new sa.*/
137195699Srwatsonstatic VNET_DEFINE(int, key_preferred_oldsa) = 1;
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;
273195727Srwatson#define	V_ipsec_esp_keymin	VNET(ipsec_esp_keymin)
274195699Srwatsonstatic VNET_DEFINE(int, ipsec_esp_auth) = 0;
275195727Srwatson#define	V_ipsec_esp_auth	VNET(ipsec_esp_auth)
276195699Srwatsonstatic VNET_DEFINE(int, ipsec_ah_keymin) = 128;
277195727Srwatson#define	V_ipsec_ah_keymin	VNET(ipsec_ah_keymin)
278195699Srwatson
279105197Ssam#ifdef SYSCTL_DECL
280105197SsamSYSCTL_DECL(_net_key);
281105197Ssam#endif
282105197Ssam
283195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,
284195699Srwatson	CTLFLAG_RW, &VNET_NAME(key_debug_level),	0,	"");
285105197Ssam
286105197Ssam/* max count of trial for the decision of spi value */
287195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
288195699Srwatson	CTLFLAG_RW, &VNET_NAME(key_spi_trycnt),	0,	"");
289105197Ssam
290105197Ssam/* minimum spi value to allocate automatically. */
291195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MIN_VALUE,
292195699Srwatson	spi_minval,	CTLFLAG_RW, &VNET_NAME(key_spi_minval),	0,	"");
293105197Ssam
294105197Ssam/* maximun spi value to allocate automatically. */
295195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MAX_VALUE,
296195699Srwatson	spi_maxval,	CTLFLAG_RW, &VNET_NAME(key_spi_maxval),	0,	"");
297105197Ssam
298105197Ssam/* interval to initialize randseed */
299195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_RANDOM_INT,
300195699Srwatson	int_random,	CTLFLAG_RW, &VNET_NAME(key_int_random),	0,	"");
301105197Ssam
302105197Ssam/* lifetime for larval SA */
303195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_LARVAL_LIFETIME,
304195699Srwatson	larval_lifetime, CTLFLAG_RW, &VNET_NAME(key_larval_lifetime),	0, "");
305105197Ssam
306105197Ssam/* counter for blocking to send SADB_ACQUIRE to IKEd */
307195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,
308195699Srwatson	blockacq_count,	CTLFLAG_RW, &VNET_NAME(key_blockacq_count),	0, "");
309105197Ssam
310105197Ssam/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
311195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,
312195699Srwatson	blockacq_lifetime, CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
313105197Ssam
314105197Ssam/* ESP auth */
315195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth,
316195699Srwatson	CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth),	0,	"");
317105197Ssam
318105197Ssam/* minimum ESP key length */
319195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_ESP_KEYMIN,
320195699Srwatson	esp_keymin, CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin),	0,	"");
321105197Ssam
322105197Ssam/* minimum AH key length */
323195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin,
324195699Srwatson	CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin),	0,	"");
325105197Ssam
326105197Ssam/* perfered old SA rather than new SA */
327195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_PREFERED_OLDSA,
328195699Srwatson	preferred_oldsa, CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa),	0, "");
329105197Ssam
330105197Ssam#define __LIST_CHAINED(elm) \
331105197Ssam	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
332105197Ssam#define LIST_INSERT_TAIL(head, elm, type, field) \
333105197Ssamdo {\
334105197Ssam	struct type *curelm = LIST_FIRST(head); \
335105197Ssam	if (curelm == NULL) {\
336105197Ssam		LIST_INSERT_HEAD(head, elm, field); \
337105197Ssam	} else { \
338105197Ssam		while (LIST_NEXT(curelm, field)) \
339105197Ssam			curelm = LIST_NEXT(curelm, field);\
340105197Ssam		LIST_INSERT_AFTER(curelm, elm, field);\
341105197Ssam	}\
342105197Ssam} while (0)
343105197Ssam
344105197Ssam#define KEY_CHKSASTATE(head, sav, name) \
345105197Ssamdo { \
346105197Ssam	if ((head) != (sav)) {						\
347105197Ssam		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
348105197Ssam			(name), (head), (sav)));			\
349105197Ssam		continue;						\
350105197Ssam	}								\
351105197Ssam} while (0)
352105197Ssam
353105197Ssam#define KEY_CHKSPDIR(head, sp, name) \
354105197Ssamdo { \
355105197Ssam	if ((head) != (sp)) {						\
356105197Ssam		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
357105197Ssam			"anyway continue.\n",				\
358105197Ssam			(name), (head), (sp)));				\
359105197Ssam	}								\
360105197Ssam} while (0)
361105197Ssam
362119643SsamMALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
363119643SsamMALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
364119643SsamMALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
365119643SsamMALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
366119643SsamMALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
367119643SsamMALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
368119643SsamMALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
369105197Ssam
370105197Ssam/*
371105197Ssam * set parameters into secpolicyindex buffer.
372105197Ssam * Must allocate secpolicyindex buffer passed to this function.
373105197Ssam */
374105197Ssam#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
375105197Ssamdo { \
376105197Ssam	bzero((idx), sizeof(struct secpolicyindex));                         \
377105197Ssam	(idx)->dir = (_dir);                                                 \
378105197Ssam	(idx)->prefs = (ps);                                                 \
379105197Ssam	(idx)->prefd = (pd);                                                 \
380105197Ssam	(idx)->ul_proto = (ulp);                                             \
381105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
382105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
383105197Ssam} while (0)
384105197Ssam
385105197Ssam/*
386105197Ssam * set parameters into secasindex buffer.
387105197Ssam * Must allocate secasindex buffer before calling this function.
388105197Ssam */
389105197Ssam#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
390105197Ssamdo { \
391105197Ssam	bzero((idx), sizeof(struct secasindex));                             \
392105197Ssam	(idx)->proto = (p);                                                  \
393105197Ssam	(idx)->mode = (m);                                                   \
394105197Ssam	(idx)->reqid = (r);                                                  \
395105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
396105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
397105197Ssam} while (0)
398105197Ssam
399105197Ssam/* key statistics */
400105197Ssamstruct _keystat {
401105197Ssam	u_long getspi_count; /* the avarage of count to try to get new SPI */
402105197Ssam} keystat;
403105197Ssam
404105197Ssamstruct sadb_msghdr {
405105197Ssam	struct sadb_msg *msg;
406105197Ssam	struct sadb_ext *ext[SADB_EXT_MAX + 1];
407105197Ssam	int extoff[SADB_EXT_MAX + 1];
408105197Ssam	int extlen[SADB_EXT_MAX + 1];
409105197Ssam};
410105197Ssam
411105197Ssamstatic struct secasvar *key_allocsa_policy __P((const struct secasindex *));
412105197Ssamstatic void key_freesp_so __P((struct secpolicy **));
413105197Ssamstatic struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
414105197Ssamstatic void key_delsp __P((struct secpolicy *));
415105197Ssamstatic struct secpolicy *key_getsp __P((struct secpolicyindex *));
416119643Ssamstatic void _key_delsp(struct secpolicy *sp);
417105197Ssamstatic struct secpolicy *key_getspbyid __P((u_int32_t));
418105197Ssamstatic u_int32_t key_newreqid __P((void));
419105197Ssamstatic struct mbuf *key_gather_mbuf __P((struct mbuf *,
420105197Ssam	const struct sadb_msghdr *, int, int, ...));
421105197Ssamstatic int key_spdadd __P((struct socket *, struct mbuf *,
422105197Ssam	const struct sadb_msghdr *));
423105197Ssamstatic u_int32_t key_getnewspid __P((void));
424105197Ssamstatic int key_spddelete __P((struct socket *, struct mbuf *,
425105197Ssam	const struct sadb_msghdr *));
426105197Ssamstatic int key_spddelete2 __P((struct socket *, struct mbuf *,
427105197Ssam	const struct sadb_msghdr *));
428105197Ssamstatic int key_spdget __P((struct socket *, struct mbuf *,
429105197Ssam	const struct sadb_msghdr *));
430105197Ssamstatic int key_spdflush __P((struct socket *, struct mbuf *,
431105197Ssam	const struct sadb_msghdr *));
432105197Ssamstatic int key_spddump __P((struct socket *, struct mbuf *,
433105197Ssam	const struct sadb_msghdr *));
434105197Ssamstatic struct mbuf *key_setdumpsp __P((struct secpolicy *,
435105197Ssam	u_int8_t, u_int32_t, u_int32_t));
436105197Ssamstatic u_int key_getspreqmsglen __P((struct secpolicy *));
437105197Ssamstatic int key_spdexpire __P((struct secpolicy *));
438105197Ssamstatic struct secashead *key_newsah __P((struct secasindex *));
439105197Ssamstatic void key_delsah __P((struct secashead *));
440105197Ssamstatic struct secasvar *key_newsav __P((struct mbuf *,
441105197Ssam	const struct sadb_msghdr *, struct secashead *, int *,
442105197Ssam	const char*, int));
443105197Ssam#define	KEY_NEWSAV(m, sadb, sah, e)				\
444105197Ssam	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
445105197Ssamstatic void key_delsav __P((struct secasvar *));
446105197Ssamstatic struct secashead *key_getsah __P((struct secasindex *));
447105197Ssamstatic struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
448105197Ssamstatic struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
449105197Ssamstatic int key_setsaval __P((struct secasvar *, struct mbuf *,
450105197Ssam	const struct sadb_msghdr *));
451105197Ssamstatic int key_mature __P((struct secasvar *));
452105197Ssamstatic struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
453105197Ssam	u_int8_t, u_int32_t, u_int32_t));
454105197Ssamstatic struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
455105197Ssam	u_int32_t, pid_t, u_int16_t));
456105197Ssamstatic struct mbuf *key_setsadbsa __P((struct secasvar *));
457105197Ssamstatic struct mbuf *key_setsadbaddr __P((u_int16_t,
458105197Ssam	const struct sockaddr *, u_int8_t, u_int16_t));
459194062Svanhu#ifdef IPSEC_NAT_T
460194062Svanhustatic struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
461194062Svanhustatic struct mbuf *key_setsadbxtype(u_int16_t);
462194062Svanhu#endif
463194062Svanhustatic void key_porttosaddr(struct sockaddr *, u_int16_t);
464194062Svanhu#define	KEY_PORTTOSADDR(saddr, port)				\
465194062Svanhu	key_porttosaddr((struct sockaddr *)(saddr), (port))
466105197Ssamstatic struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
467105197Ssamstatic struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
468105197Ssam	u_int32_t));
469157123Sgnnstatic struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
470157123Sgnn				     struct malloc_type *);
471157123Sgnnstatic struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
472157123Sgnn					    struct malloc_type *type);
473105197Ssam#ifdef INET6
474105197Ssamstatic int key_ismyaddr6 __P((struct sockaddr_in6 *));
475105197Ssam#endif
476105197Ssam
477105197Ssam/* flags for key_cmpsaidx() */
478105197Ssam#define CMP_HEAD	1	/* protocol, addresses. */
479105197Ssam#define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
480105197Ssam#define CMP_REQID	3	/* additionally HEAD, reaid. */
481105197Ssam#define CMP_EXACTLY	4	/* all elements. */
482105197Ssamstatic int key_cmpsaidx
483105197Ssam	__P((const struct secasindex *, const struct secasindex *, int));
484105197Ssam
485105197Ssamstatic int key_cmpspidx_exactly
486105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
487105197Ssamstatic int key_cmpspidx_withmask
488105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
489105197Ssamstatic int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
490105197Ssamstatic int key_bbcmp __P((const void *, const void *, u_int));
491105197Ssamstatic u_int16_t key_satype2proto __P((u_int8_t));
492105197Ssamstatic u_int8_t key_proto2satype __P((u_int16_t));
493105197Ssam
494105197Ssamstatic int key_getspi __P((struct socket *, struct mbuf *,
495105197Ssam	const struct sadb_msghdr *));
496105197Ssamstatic u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
497105197Ssam					struct secasindex *));
498105197Ssamstatic int key_update __P((struct socket *, struct mbuf *,
499105197Ssam	const struct sadb_msghdr *));
500105197Ssam#ifdef IPSEC_DOSEQCHECK
501105197Ssamstatic struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
502105197Ssam#endif
503105197Ssamstatic int key_add __P((struct socket *, struct mbuf *,
504105197Ssam	const struct sadb_msghdr *));
505105197Ssamstatic int key_setident __P((struct secashead *, struct mbuf *,
506105197Ssam	const struct sadb_msghdr *));
507105197Ssamstatic struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
508105197Ssam	const struct sadb_msghdr *));
509105197Ssamstatic int key_delete __P((struct socket *, struct mbuf *,
510105197Ssam	const struct sadb_msghdr *));
511105197Ssamstatic int key_get __P((struct socket *, struct mbuf *,
512105197Ssam	const struct sadb_msghdr *));
513105197Ssam
514105197Ssamstatic void key_getcomb_setlifetime __P((struct sadb_comb *));
515105197Ssamstatic struct mbuf *key_getcomb_esp __P((void));
516105197Ssamstatic struct mbuf *key_getcomb_ah __P((void));
517105197Ssamstatic struct mbuf *key_getcomb_ipcomp __P((void));
518105197Ssamstatic struct mbuf *key_getprop __P((const struct secasindex *));
519105197Ssam
520105197Ssamstatic int key_acquire __P((const struct secasindex *, struct secpolicy *));
521105197Ssamstatic struct secacq *key_newacq __P((const struct secasindex *));
522105197Ssamstatic struct secacq *key_getacq __P((const struct secasindex *));
523105197Ssamstatic struct secacq *key_getacqbyseq __P((u_int32_t));
524105197Ssamstatic struct secspacq *key_newspacq __P((struct secpolicyindex *));
525105197Ssamstatic struct secspacq *key_getspacq __P((struct secpolicyindex *));
526105197Ssamstatic int key_acquire2 __P((struct socket *, struct mbuf *,
527105197Ssam	const struct sadb_msghdr *));
528105197Ssamstatic int key_register __P((struct socket *, struct mbuf *,
529105197Ssam	const struct sadb_msghdr *));
530105197Ssamstatic int key_expire __P((struct secasvar *));
531105197Ssamstatic int key_flush __P((struct socket *, struct mbuf *,
532105197Ssam	const struct sadb_msghdr *));
533105197Ssamstatic int key_dump __P((struct socket *, struct mbuf *,
534105197Ssam	const struct sadb_msghdr *));
535105197Ssamstatic int key_promisc __P((struct socket *, struct mbuf *,
536105197Ssam	const struct sadb_msghdr *));
537105197Ssamstatic int key_senderror __P((struct socket *, struct mbuf *, int));
538105197Ssamstatic int key_validate_ext __P((const struct sadb_ext *, int));
539105197Ssamstatic int key_align __P((struct mbuf *, struct sadb_msghdr *));
540157123Sgnnstatic struct mbuf *key_setlifetime(struct seclifetime *src,
541157123Sgnn				     u_int16_t exttype);
542157123Sgnnstatic struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
543157123Sgnn
544105197Ssam#if 0
545105197Ssamstatic const char *key_getfqdn __P((void));
546105197Ssamstatic const char *key_getuserfqdn __P((void));
547105197Ssam#endif
548105197Ssamstatic void key_sa_chgstate __P((struct secasvar *, u_int8_t));
549105197Ssamstatic struct mbuf *key_alloc_mbuf __P((int));
550105197Ssam
551158767Spjdstatic __inline void
552158767Spjdsa_initref(struct secasvar *sav)
553158767Spjd{
554105197Ssam
555158767Spjd	refcount_init(&sav->refcnt, 1);
556158767Spjd}
557158767Spjdstatic __inline void
558158767Spjdsa_addref(struct secasvar *sav)
559158767Spjd{
560158767Spjd
561158767Spjd	refcount_acquire(&sav->refcnt);
562158767Spjd	IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
563158767Spjd}
564158767Spjdstatic __inline int
565158767Spjdsa_delref(struct secasvar *sav)
566158767Spjd{
567158767Spjd
568158767Spjd	IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
569158767Spjd	return (refcount_release(&sav->refcnt));
570158767Spjd}
571158767Spjd
572105197Ssam#define	SP_ADDREF(p) do {						\
573105197Ssam	(p)->refcnt++;							\
574120585Ssam	IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));		\
575105197Ssam} while (0)
576105197Ssam#define	SP_DELREF(p) do {						\
577120585Ssam	IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));		\
578105197Ssam	(p)->refcnt--;							\
579105197Ssam} while (0)
580135947Ssam
581105197Ssam
582105197Ssam/*
583135947Ssam * Update the refcnt while holding the SPTREE lock.
584135947Ssam */
585135947Ssamvoid
586135947Ssamkey_addref(struct secpolicy *sp)
587135947Ssam{
588135947Ssam	SPTREE_LOCK();
589135947Ssam	SP_ADDREF(sp);
590135947Ssam	SPTREE_UNLOCK();
591135947Ssam}
592135947Ssam
593135947Ssam/*
594105197Ssam * Return 0 when there are known to be no SP's for the specified
595105197Ssam * direction.  Otherwise return 1.  This is used by IPsec code
596105197Ssam * to optimize performance.
597105197Ssam */
598105197Ssamint
599105197Ssamkey_havesp(u_int dir)
600105197Ssam{
601183550Szec
602105197Ssam	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
603181803Sbz		LIST_FIRST(&V_sptree[dir]) != NULL : 1);
604105197Ssam}
605105197Ssam
606105197Ssam/* %%% IPsec policy management */
607105197Ssam/*
608105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
609105197Ssam * Must call key_freesp() later.
610105197Ssam * OUT:	NULL:	not found
611105197Ssam *	others:	found and return the pointer.
612105197Ssam */
613105197Ssamstruct secpolicy *
614105197Ssamkey_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
615105197Ssam{
616105197Ssam	struct secpolicy *sp;
617105197Ssam
618120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
619120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
620120585Ssam		("invalid direction %u", dir));
621105197Ssam
622105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
623120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
624105197Ssam
625105197Ssam	/* get a SP entry */
626105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
627105197Ssam		printf("*** objects\n");
628105197Ssam		kdebug_secpolicyindex(spidx));
629105197Ssam
630120585Ssam	SPTREE_LOCK();
631181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
632105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
633105197Ssam			printf("*** in SPD\n");
634105197Ssam			kdebug_secpolicyindex(&sp->spidx));
635105197Ssam
636105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
637105197Ssam			continue;
638105197Ssam		if (key_cmpspidx_withmask(&sp->spidx, spidx))
639105197Ssam			goto found;
640105197Ssam	}
641105197Ssam	sp = NULL;
642105197Ssamfound:
643105197Ssam	if (sp) {
644105197Ssam		/* sanity check */
645120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
646105197Ssam
647105197Ssam		/* found a SPD entry */
648105197Ssam		sp->lastused = time_second;
649105197Ssam		SP_ADDREF(sp);
650105197Ssam	}
651120585Ssam	SPTREE_UNLOCK();
652105197Ssam
653105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
654120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
655105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
656105197Ssam	return sp;
657105197Ssam}
658105197Ssam
659105197Ssam/*
660105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
661105197Ssam * Must call key_freesp() later.
662105197Ssam * OUT:	NULL:	not found
663105197Ssam *	others:	found and return the pointer.
664105197Ssam */
665105197Ssamstruct secpolicy *
666105197Ssamkey_allocsp2(u_int32_t spi,
667105197Ssam	     union sockaddr_union *dst,
668105197Ssam	     u_int8_t proto,
669105197Ssam	     u_int dir,
670105197Ssam	     const char* where, int tag)
671105197Ssam{
672105197Ssam	struct secpolicy *sp;
673105197Ssam
674120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst"));
675120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
676120585Ssam		("invalid direction %u", dir));
677105197Ssam
678105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
679120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
680105197Ssam
681105197Ssam	/* get a SP entry */
682105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
683105197Ssam		printf("*** objects\n");
684105197Ssam		printf("spi %u proto %u dir %u\n", spi, proto, dir);
685105197Ssam		kdebug_sockaddr(&dst->sa));
686105197Ssam
687120585Ssam	SPTREE_LOCK();
688181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
689105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
690105197Ssam			printf("*** in SPD\n");
691105197Ssam			kdebug_secpolicyindex(&sp->spidx));
692105197Ssam
693105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
694105197Ssam			continue;
695105197Ssam		/* compare simple values, then dst address */
696105197Ssam		if (sp->spidx.ul_proto != proto)
697105197Ssam			continue;
698105197Ssam		/* NB: spi's must exist and match */
699105197Ssam		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
700105197Ssam			continue;
701105197Ssam		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
702105197Ssam			goto found;
703105197Ssam	}
704105197Ssam	sp = NULL;
705105197Ssamfound:
706105197Ssam	if (sp) {
707105197Ssam		/* sanity check */
708120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
709105197Ssam
710105197Ssam		/* found a SPD entry */
711105197Ssam		sp->lastused = time_second;
712105197Ssam		SP_ADDREF(sp);
713105197Ssam	}
714120585Ssam	SPTREE_UNLOCK();
715105197Ssam
716105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
717120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
718105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
719105197Ssam	return sp;
720105197Ssam}
721105197Ssam
722191599Sbz#if 0
723105197Ssam/*
724105197Ssam * return a policy that matches this particular inbound packet.
725105197Ssam * XXX slow
726105197Ssam */
727105197Ssamstruct secpolicy *
728105197Ssamkey_gettunnel(const struct sockaddr *osrc,
729105197Ssam	      const struct sockaddr *odst,
730105197Ssam	      const struct sockaddr *isrc,
731105197Ssam	      const struct sockaddr *idst,
732105197Ssam	      const char* where, int tag)
733105197Ssam{
734105197Ssam	struct secpolicy *sp;
735105197Ssam	const int dir = IPSEC_DIR_INBOUND;
736105197Ssam	struct ipsecrequest *r1, *r2, *p;
737105197Ssam	struct secpolicyindex spidx;
738105197Ssam
739105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
740120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
741105197Ssam
742105197Ssam	if (isrc->sa_family != idst->sa_family) {
743120585Ssam		ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
744120585Ssam			__func__, isrc->sa_family, idst->sa_family));
745105197Ssam		sp = NULL;
746105197Ssam		goto done;
747105197Ssam	}
748105197Ssam
749120585Ssam	SPTREE_LOCK();
750181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
751105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
752105197Ssam			continue;
753105197Ssam
754105197Ssam		r1 = r2 = NULL;
755105197Ssam		for (p = sp->req; p; p = p->next) {
756105197Ssam			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
757105197Ssam				continue;
758105197Ssam
759105197Ssam			r1 = r2;
760105197Ssam			r2 = p;
761105197Ssam
762105197Ssam			if (!r1) {
763105197Ssam				/* here we look at address matches only */
764105197Ssam				spidx = sp->spidx;
765105197Ssam				if (isrc->sa_len > sizeof(spidx.src) ||
766105197Ssam				    idst->sa_len > sizeof(spidx.dst))
767105197Ssam					continue;
768105197Ssam				bcopy(isrc, &spidx.src, isrc->sa_len);
769105197Ssam				bcopy(idst, &spidx.dst, idst->sa_len);
770105197Ssam				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
771105197Ssam					continue;
772105197Ssam			} else {
773105197Ssam				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
774105197Ssam				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
775105197Ssam					continue;
776105197Ssam			}
777105197Ssam
778105197Ssam			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
779105197Ssam			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
780105197Ssam				continue;
781105197Ssam
782105197Ssam			goto found;
783105197Ssam		}
784105197Ssam	}
785105197Ssam	sp = NULL;
786105197Ssamfound:
787105197Ssam	if (sp) {
788105197Ssam		sp->lastused = time_second;
789105197Ssam		SP_ADDREF(sp);
790105197Ssam	}
791120585Ssam	SPTREE_UNLOCK();
792105197Ssamdone:
793105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
794120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
795105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
796105197Ssam	return sp;
797105197Ssam}
798191599Sbz#endif
799105197Ssam
800105197Ssam/*
801105197Ssam * allocating an SA entry for an *OUTBOUND* packet.
802105197Ssam * checking each request entries in SP, and acquire an SA if need.
803105197Ssam * OUT:	0: there are valid requests.
804105197Ssam *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
805105197Ssam */
806105197Ssamint
807105197Ssamkey_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
808105197Ssam{
809105197Ssam	u_int level;
810105197Ssam	int error;
811105197Ssam
812120585Ssam	IPSEC_ASSERT(isr != NULL, ("null isr"));
813120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
814120585Ssam	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
815105197Ssam		saidx->mode == IPSEC_MODE_TUNNEL,
816120585Ssam		("unexpected policy %u", saidx->mode));
817105197Ssam
818105197Ssam	/*
819105197Ssam	 * XXX guard against protocol callbacks from the crypto
820105197Ssam	 * thread as they reference ipsecrequest.sav which we
821105197Ssam	 * temporarily null out below.  Need to rethink how we
822105197Ssam	 * handle bundled SA's in the callback thread.
823105197Ssam	 */
824120585Ssam	IPSECREQUEST_LOCK_ASSERT(isr);
825119643Ssam
826119643Ssam	/* get current level */
827119643Ssam	level = ipsec_get_reqlevel(isr);
828105197Ssam#if 0
829105197Ssam	/*
830105197Ssam	 * We do allocate new SA only if the state of SA in the holder is
831105197Ssam	 * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
832105197Ssam	 */
833105197Ssam	if (isr->sav != NULL) {
834105197Ssam		if (isr->sav->sah == NULL)
835120585Ssam			panic("%s: sah is null.\n", __func__);
836105197Ssam		if (isr->sav == (struct secasvar *)LIST_FIRST(
837105197Ssam			    &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
838105197Ssam			KEY_FREESAV(&isr->sav);
839105197Ssam			isr->sav = NULL;
840105197Ssam		}
841105197Ssam	}
842105197Ssam#else
843105197Ssam	/*
844105197Ssam	 * we free any SA stashed in the IPsec request because a different
845105197Ssam	 * SA may be involved each time this request is checked, either
846105197Ssam	 * because new SAs are being configured, or this request is
847105197Ssam	 * associated with an unconnected datagram socket, or this request
848105197Ssam	 * is associated with a system default policy.
849105197Ssam	 *
850105197Ssam	 * The operation may have negative impact to performance.  We may
851105197Ssam	 * want to check cached SA carefully, rather than picking new SA
852105197Ssam	 * every time.
853105197Ssam	 */
854105197Ssam	if (isr->sav != NULL) {
855105197Ssam		KEY_FREESAV(&isr->sav);
856105197Ssam		isr->sav = NULL;
857105197Ssam	}
858105197Ssam#endif
859105197Ssam
860105197Ssam	/*
861105197Ssam	 * new SA allocation if no SA found.
862105197Ssam	 * key_allocsa_policy should allocate the oldest SA available.
863105197Ssam	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
864105197Ssam	 */
865105197Ssam	if (isr->sav == NULL)
866105197Ssam		isr->sav = key_allocsa_policy(saidx);
867105197Ssam
868105197Ssam	/* When there is SA. */
869105197Ssam	if (isr->sav != NULL) {
870105197Ssam		if (isr->sav->state != SADB_SASTATE_MATURE &&
871105197Ssam		    isr->sav->state != SADB_SASTATE_DYING)
872105197Ssam			return EINVAL;
873105197Ssam		return 0;
874105197Ssam	}
875105197Ssam
876105197Ssam	/* there is no SA */
877105197Ssam	error = key_acquire(saidx, isr->sp);
878105197Ssam	if (error != 0) {
879105197Ssam		/* XXX What should I do ? */
880120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
881120585Ssam			__func__, error));
882105197Ssam		return error;
883105197Ssam	}
884105197Ssam
885105197Ssam	if (level != IPSEC_LEVEL_REQUIRE) {
886105197Ssam		/* XXX sigh, the interface to this routine is botched */
887120585Ssam		IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
888105197Ssam		return 0;
889105197Ssam	} else {
890105197Ssam		return ENOENT;
891105197Ssam	}
892105197Ssam}
893105197Ssam
894105197Ssam/*
895105197Ssam * allocating a SA for policy entry from SAD.
896105197Ssam * NOTE: searching SAD of aliving state.
897105197Ssam * OUT:	NULL:	not found.
898105197Ssam *	others:	found and return the pointer.
899105197Ssam */
900105197Ssamstatic struct secasvar *
901105197Ssamkey_allocsa_policy(const struct secasindex *saidx)
902105197Ssam{
903128856Ssam#define	N(a)	_ARRAYLEN(a)
904105197Ssam	struct secashead *sah;
905105197Ssam	struct secasvar *sav;
906128856Ssam	u_int stateidx, arraysize;
907128856Ssam	const u_int *state_valid;
908105197Ssam
909196902Spjd	state_valid = NULL;	/* silence gcc */
910196902Spjd	arraysize = 0;		/* silence gcc */
911196896Spjd
912120585Ssam	SAHTREE_LOCK();
913181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
914105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
915105197Ssam			continue;
916119643Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
917181803Sbz			if (V_key_preferred_oldsa) {
918128856Ssam				state_valid = saorder_state_valid_prefer_old;
919128856Ssam				arraysize = N(saorder_state_valid_prefer_old);
920128856Ssam			} else {
921128856Ssam				state_valid = saorder_state_valid_prefer_new;
922128856Ssam				arraysize = N(saorder_state_valid_prefer_new);
923128856Ssam			}
924196883Spjd			break;
925119643Ssam		}
926105197Ssam	}
927120585Ssam	SAHTREE_UNLOCK();
928196883Spjd	if (sah == NULL)
929196883Spjd		return NULL;
930105197Ssam
931105197Ssam	/* search valid state */
932128856Ssam	for (stateidx = 0; stateidx < arraysize; stateidx++) {
933128856Ssam		sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
934105197Ssam		if (sav != NULL)
935105197Ssam			return sav;
936105197Ssam	}
937105197Ssam
938105197Ssam	return NULL;
939128856Ssam#undef N
940105197Ssam}
941105197Ssam
942105197Ssam/*
943105197Ssam * searching SAD with direction, protocol, mode and state.
944105197Ssam * called by key_allocsa_policy().
945105197Ssam * OUT:
946105197Ssam *	NULL	: not found
947105197Ssam *	others	: found, pointer to a SA.
948105197Ssam */
949105197Ssamstatic struct secasvar *
950105197Ssamkey_do_allocsa_policy(struct secashead *sah, u_int state)
951105197Ssam{
952105197Ssam	struct secasvar *sav, *nextsav, *candidate, *d;
953105197Ssam
954105197Ssam	/* initilize */
955105197Ssam	candidate = NULL;
956105197Ssam
957120585Ssam	SAHTREE_LOCK();
958105197Ssam	for (sav = LIST_FIRST(&sah->savtree[state]);
959105197Ssam	     sav != NULL;
960105197Ssam	     sav = nextsav) {
961105197Ssam
962105197Ssam		nextsav = LIST_NEXT(sav, chain);
963105197Ssam
964105197Ssam		/* sanity check */
965120585Ssam		KEY_CHKSASTATE(sav->state, state, __func__);
966105197Ssam
967105197Ssam		/* initialize */
968105197Ssam		if (candidate == NULL) {
969105197Ssam			candidate = sav;
970105197Ssam			continue;
971105197Ssam		}
972105197Ssam
973105197Ssam		/* Which SA is the better ? */
974105197Ssam
975120585Ssam		IPSEC_ASSERT(candidate->lft_c != NULL,
976120585Ssam			("null candidate lifetime"));
977120585Ssam		IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
978105197Ssam
979105197Ssam		/* What the best method is to compare ? */
980181803Sbz		if (V_key_preferred_oldsa) {
981157123Sgnn			if (candidate->lft_c->addtime >
982157123Sgnn					sav->lft_c->addtime) {
983105197Ssam				candidate = sav;
984105197Ssam			}
985105197Ssam			continue;
986105197Ssam			/*NOTREACHED*/
987105197Ssam		}
988105197Ssam
989125876Sguido		/* preferred new sa rather than old sa */
990157123Sgnn		if (candidate->lft_c->addtime <
991157123Sgnn				sav->lft_c->addtime) {
992105197Ssam			d = candidate;
993105197Ssam			candidate = sav;
994105197Ssam		} else
995105197Ssam			d = sav;
996105197Ssam
997105197Ssam		/*
998105197Ssam		 * prepared to delete the SA when there is more
999105197Ssam		 * suitable candidate and the lifetime of the SA is not
1000105197Ssam		 * permanent.
1001105197Ssam		 */
1002177553Sbz		if (d->lft_h->addtime != 0) {
1003105197Ssam			struct mbuf *m, *result;
1004125508Ssam			u_int8_t satype;
1005105197Ssam
1006105197Ssam			key_sa_chgstate(d, SADB_SASTATE_DEAD);
1007105197Ssam
1008120585Ssam			IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
1009125508Ssam
1010125508Ssam			satype = key_proto2satype(d->sah->saidx.proto);
1011125508Ssam			if (satype == 0)
1012125508Ssam				goto msgfail;
1013125508Ssam
1014105197Ssam			m = key_setsadbmsg(SADB_DELETE, 0,
1015125508Ssam			    satype, 0, 0, d->refcnt - 1);
1016105197Ssam			if (!m)
1017105197Ssam				goto msgfail;
1018105197Ssam			result = m;
1019105197Ssam
1020105197Ssam			/* set sadb_address for saidx's. */
1021105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
1022105197Ssam				&d->sah->saidx.src.sa,
1023105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
1024105197Ssam				IPSEC_ULPROTO_ANY);
1025105197Ssam			if (!m)
1026105197Ssam				goto msgfail;
1027105197Ssam			m_cat(result, m);
1028105197Ssam
1029105197Ssam			/* set sadb_address for saidx's. */
1030105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
1031128860Ssam				&d->sah->saidx.dst.sa,
1032128860Ssam				d->sah->saidx.dst.sa.sa_len << 3,
1033105197Ssam				IPSEC_ULPROTO_ANY);
1034105197Ssam			if (!m)
1035105197Ssam				goto msgfail;
1036105197Ssam			m_cat(result, m);
1037105197Ssam
1038105197Ssam			/* create SA extension */
1039105197Ssam			m = key_setsadbsa(d);
1040105197Ssam			if (!m)
1041105197Ssam				goto msgfail;
1042105197Ssam			m_cat(result, m);
1043105197Ssam
1044105197Ssam			if (result->m_len < sizeof(struct sadb_msg)) {
1045105197Ssam				result = m_pullup(result,
1046105197Ssam						sizeof(struct sadb_msg));
1047105197Ssam				if (result == NULL)
1048105197Ssam					goto msgfail;
1049105197Ssam			}
1050105197Ssam
1051105197Ssam			result->m_pkthdr.len = 0;
1052105197Ssam			for (m = result; m; m = m->m_next)
1053105197Ssam				result->m_pkthdr.len += m->m_len;
1054105197Ssam			mtod(result, struct sadb_msg *)->sadb_msg_len =
1055105197Ssam				PFKEY_UNIT64(result->m_pkthdr.len);
1056105197Ssam
1057105197Ssam			if (key_sendup_mbuf(NULL, result,
1058105197Ssam					KEY_SENDUP_REGISTERED))
1059105197Ssam				goto msgfail;
1060105197Ssam		 msgfail:
1061105197Ssam			KEY_FREESAV(&d);
1062105197Ssam		}
1063105197Ssam	}
1064105197Ssam	if (candidate) {
1065158767Spjd		sa_addref(candidate);
1066105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1067120585Ssam			printf("DP %s cause refcnt++:%d SA:%p\n",
1068120585Ssam				__func__, candidate->refcnt, candidate));
1069105197Ssam	}
1070120585Ssam	SAHTREE_UNLOCK();
1071119643Ssam
1072105197Ssam	return candidate;
1073105197Ssam}
1074105197Ssam
1075105197Ssam/*
1076105197Ssam * allocating a usable SA entry for a *INBOUND* packet.
1077105197Ssam * Must call key_freesav() later.
1078105197Ssam * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
1079105197Ssam *	NULL:		not found, or error occured.
1080105197Ssam *
1081105197Ssam * In the comparison, no source address is used--for RFC2401 conformance.
1082105197Ssam * To quote, from section 4.1:
1083105197Ssam *	A security association is uniquely identified by a triple consisting
1084105197Ssam *	of a Security Parameter Index (SPI), an IP Destination Address, and a
1085105197Ssam *	security protocol (AH or ESP) identifier.
1086105197Ssam * Note that, however, we do need to keep source address in IPsec SA.
1087105197Ssam * IKE specification and PF_KEY specification do assume that we
1088105197Ssam * keep source address in IPsec SA.  We see a tricky situation here.
1089105197Ssam */
1090105197Ssamstruct secasvar *
1091105197Ssamkey_allocsa(
1092105197Ssam	union sockaddr_union *dst,
1093105197Ssam	u_int proto,
1094105197Ssam	u_int32_t spi,
1095105197Ssam	const char* where, int tag)
1096105197Ssam{
1097105197Ssam	struct secashead *sah;
1098105197Ssam	struct secasvar *sav;
1099128856Ssam	u_int stateidx, arraysize, state;
1100128856Ssam	const u_int *saorder_state_valid;
1101194062Svanhu	int chkport;
1102105197Ssam
1103120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst address"));
1104105197Ssam
1105105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1106120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
1107105197Ssam
1108194062Svanhu#ifdef IPSEC_NAT_T
1109194062Svanhu        chkport = (dst->sa.sa_family == AF_INET &&
1110194062Svanhu	    dst->sa.sa_len == sizeof(struct sockaddr_in) &&
1111194062Svanhu	    dst->sin.sin_port != 0);
1112194062Svanhu#else
1113194062Svanhu	chkport = 0;
1114194062Svanhu#endif
1115194062Svanhu
1116105197Ssam	/*
1117105197Ssam	 * searching SAD.
1118105197Ssam	 * XXX: to be checked internal IP header somewhere.  Also when
1119105197Ssam	 * IPsec tunnel packet is received.  But ESP tunnel mode is
1120105197Ssam	 * encrypted so we can't check internal IP header.
1121105197Ssam	 */
1122120585Ssam	SAHTREE_LOCK();
1123181803Sbz	if (V_key_preferred_oldsa) {
1124128856Ssam		saorder_state_valid = saorder_state_valid_prefer_old;
1125128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1126128856Ssam	} else {
1127128856Ssam		saorder_state_valid = saorder_state_valid_prefer_new;
1128128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1129128856Ssam	}
1130181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
1131105197Ssam		/* search valid state */
1132128856Ssam		for (stateidx = 0; stateidx < arraysize; stateidx++) {
1133105197Ssam			state = saorder_state_valid[stateidx];
1134105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
1135105197Ssam				/* sanity check */
1136120585Ssam				KEY_CHKSASTATE(sav->state, state, __func__);
1137105197Ssam				/* do not return entries w/ unusable state */
1138105197Ssam				if (sav->state != SADB_SASTATE_MATURE &&
1139105197Ssam				    sav->state != SADB_SASTATE_DYING)
1140105197Ssam					continue;
1141105197Ssam				if (proto != sav->sah->saidx.proto)
1142105197Ssam					continue;
1143105197Ssam				if (spi != sav->spi)
1144105197Ssam					continue;
1145105197Ssam#if 0	/* don't check src */
1146105197Ssam				/* check src address */
1147194062Svanhu				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, chkport) != 0)
1148105197Ssam					continue;
1149105197Ssam#endif
1150105197Ssam				/* check dst address */
1151194062Svanhu				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, chkport) != 0)
1152105197Ssam					continue;
1153158767Spjd				sa_addref(sav);
1154105197Ssam				goto done;
1155105197Ssam			}
1156105197Ssam		}
1157105197Ssam	}
1158105197Ssam	sav = NULL;
1159105197Ssamdone:
1160120585Ssam	SAHTREE_UNLOCK();
1161105197Ssam
1162105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1163120585Ssam		printf("DP %s return SA:%p; refcnt %u\n", __func__,
1164105197Ssam			sav, sav ? sav->refcnt : 0));
1165105197Ssam	return sav;
1166105197Ssam}
1167105197Ssam
1168105197Ssam/*
1169105197Ssam * Must be called after calling key_allocsp().
1170105197Ssam * For both the packet without socket and key_freeso().
1171105197Ssam */
1172105197Ssamvoid
1173105197Ssam_key_freesp(struct secpolicy **spp, const char* where, int tag)
1174105197Ssam{
1175105197Ssam	struct secpolicy *sp = *spp;
1176105197Ssam
1177120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1178105197Ssam
1179120585Ssam	SPTREE_LOCK();
1180105197Ssam	SP_DELREF(sp);
1181105197Ssam
1182105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1183120585Ssam		printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1184120585Ssam			__func__, sp, sp->id, where, tag, sp->refcnt));
1185105197Ssam
1186105197Ssam	if (sp->refcnt == 0) {
1187105197Ssam		*spp = NULL;
1188105197Ssam		key_delsp(sp);
1189105197Ssam	}
1190120585Ssam	SPTREE_UNLOCK();
1191105197Ssam}
1192105197Ssam
1193105197Ssam/*
1194105197Ssam * Must be called after calling key_allocsp().
1195105197Ssam * For the packet with socket.
1196105197Ssam */
1197105197Ssamvoid
1198105197Ssamkey_freeso(struct socket *so)
1199105197Ssam{
1200120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
1201105197Ssam
1202105197Ssam	switch (so->so_proto->pr_domain->dom_family) {
1203186141Sbz#if defined(INET) || defined(INET6)
1204105197Ssam#ifdef INET
1205105197Ssam	case PF_INET:
1206105197Ssam#endif
1207105197Ssam#ifdef INET6
1208105197Ssam	case PF_INET6:
1209186141Sbz#endif
1210105197Ssam	    {
1211186141Sbz		struct inpcb *pcb = sotoinpcb(so);
1212105197Ssam
1213105197Ssam		/* Does it have a PCB ? */
1214105197Ssam		if (pcb == NULL)
1215105197Ssam			return;
1216105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1217105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1218105197Ssam	    }
1219105197Ssam		break;
1220186141Sbz#endif /* INET || INET6 */
1221105197Ssam	default:
1222120585Ssam		ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1223120585Ssam		    __func__, so->so_proto->pr_domain->dom_family));
1224105197Ssam		return;
1225105197Ssam	}
1226105197Ssam}
1227105197Ssam
1228105197Ssamstatic void
1229105197Ssamkey_freesp_so(struct secpolicy **sp)
1230105197Ssam{
1231120585Ssam	IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1232105197Ssam
1233105197Ssam	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1234105197Ssam	    (*sp)->policy == IPSEC_POLICY_BYPASS)
1235105197Ssam		return;
1236105197Ssam
1237120585Ssam	IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1238120585Ssam		("invalid policy %u", (*sp)->policy));
1239105197Ssam	KEY_FREESP(sp);
1240105197Ssam}
1241105197Ssam
1242105197Ssam/*
1243105197Ssam * Must be called after calling key_allocsa().
1244105197Ssam * This function is called by key_freesp() to free some SA allocated
1245105197Ssam * for a policy.
1246105197Ssam */
1247105197Ssamvoid
1248105197Ssamkey_freesav(struct secasvar **psav, const char* where, int tag)
1249105197Ssam{
1250105197Ssam	struct secasvar *sav = *psav;
1251105197Ssam
1252120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
1253105197Ssam
1254158767Spjd	if (sa_delref(sav)) {
1255158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1256158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1257158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1258105197Ssam		*psav = NULL;
1259105197Ssam		key_delsav(sav);
1260158767Spjd	} else {
1261158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1262158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1263158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1264105197Ssam	}
1265105197Ssam}
1266105197Ssam
1267105197Ssam/* %%% SPD management */
1268105197Ssam/*
1269105197Ssam * free security policy entry.
1270105197Ssam */
1271105197Ssamstatic void
1272105197Ssamkey_delsp(struct secpolicy *sp)
1273105197Ssam{
1274119643Ssam	struct ipsecrequest *isr, *nextisr;
1275105197Ssam
1276120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1277120585Ssam	SPTREE_LOCK_ASSERT();
1278105197Ssam
1279105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
1280105197Ssam
1281120585Ssam	IPSEC_ASSERT(sp->refcnt == 0,
1282120585Ssam		("SP with references deleted (refcnt %u)", sp->refcnt));
1283105197Ssam
1284105197Ssam	/* remove from SP index */
1285105197Ssam	if (__LIST_CHAINED(sp))
1286105197Ssam		LIST_REMOVE(sp, chain);
1287105197Ssam
1288119643Ssam	for (isr = sp->req; isr != NULL; isr = nextisr) {
1289105197Ssam		if (isr->sav != NULL) {
1290105197Ssam			KEY_FREESAV(&isr->sav);
1291105197Ssam			isr->sav = NULL;
1292105197Ssam		}
1293105197Ssam
1294105197Ssam		nextisr = isr->next;
1295119643Ssam		ipsec_delisr(isr);
1296105197Ssam	}
1297119643Ssam	_key_delsp(sp);
1298105197Ssam}
1299105197Ssam
1300105197Ssam/*
1301105197Ssam * search SPD
1302105197Ssam * OUT:	NULL	: not found
1303105197Ssam *	others	: found, pointer to a SP.
1304105197Ssam */
1305105197Ssamstatic struct secpolicy *
1306105197Ssamkey_getsp(struct secpolicyindex *spidx)
1307105197Ssam{
1308105197Ssam	struct secpolicy *sp;
1309105197Ssam
1310120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1311105197Ssam
1312120585Ssam	SPTREE_LOCK();
1313181803Sbz	LIST_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1314105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1315105197Ssam			continue;
1316105197Ssam		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1317105197Ssam			SP_ADDREF(sp);
1318119643Ssam			break;
1319105197Ssam		}
1320105197Ssam	}
1321120585Ssam	SPTREE_UNLOCK();
1322105197Ssam
1323119643Ssam	return sp;
1324105197Ssam}
1325105197Ssam
1326105197Ssam/*
1327105197Ssam * get SP by index.
1328105197Ssam * OUT:	NULL	: not found
1329105197Ssam *	others	: found, pointer to a SP.
1330105197Ssam */
1331105197Ssamstatic struct secpolicy *
1332105197Ssamkey_getspbyid(u_int32_t id)
1333105197Ssam{
1334105197Ssam	struct secpolicy *sp;
1335105197Ssam
1336120585Ssam	SPTREE_LOCK();
1337181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
1338105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1339105197Ssam			continue;
1340105197Ssam		if (sp->id == id) {
1341105197Ssam			SP_ADDREF(sp);
1342119643Ssam			goto done;
1343105197Ssam		}
1344105197Ssam	}
1345105197Ssam
1346181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
1347105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1348105197Ssam			continue;
1349105197Ssam		if (sp->id == id) {
1350105197Ssam			SP_ADDREF(sp);
1351119643Ssam			goto done;
1352105197Ssam		}
1353105197Ssam	}
1354119643Ssamdone:
1355120585Ssam	SPTREE_UNLOCK();
1356105197Ssam
1357119643Ssam	return sp;
1358105197Ssam}
1359105197Ssam
1360105197Ssamstruct secpolicy *
1361105197Ssamkey_newsp(const char* where, int tag)
1362105197Ssam{
1363105197Ssam	struct secpolicy *newsp = NULL;
1364105197Ssam
1365105197Ssam	newsp = (struct secpolicy *)
1366119643Ssam		malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1367105197Ssam	if (newsp) {
1368120585Ssam		SECPOLICY_LOCK_INIT(newsp);
1369105197Ssam		newsp->refcnt = 1;
1370105197Ssam		newsp->req = NULL;
1371105197Ssam	}
1372105197Ssam
1373105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1374120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
1375105197Ssam			where, tag, newsp));
1376105197Ssam	return newsp;
1377105197Ssam}
1378105197Ssam
1379119643Ssamstatic void
1380119643Ssam_key_delsp(struct secpolicy *sp)
1381119643Ssam{
1382120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
1383119643Ssam	free(sp, M_IPSEC_SP);
1384119643Ssam}
1385119643Ssam
1386105197Ssam/*
1387105197Ssam * create secpolicy structure from sadb_x_policy structure.
1388105197Ssam * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1389105197Ssam * so must be set properly later.
1390105197Ssam */
1391105197Ssamstruct secpolicy *
1392105197Ssamkey_msg2sp(xpl0, len, error)
1393105197Ssam	struct sadb_x_policy *xpl0;
1394105197Ssam	size_t len;
1395105197Ssam	int *error;
1396105197Ssam{
1397105197Ssam	struct secpolicy *newsp;
1398105197Ssam
1399120585Ssam	IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1400127972Spjd	IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1401120585Ssam
1402105197Ssam	if (len != PFKEY_EXTLEN(xpl0)) {
1403120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1404105197Ssam		*error = EINVAL;
1405105197Ssam		return NULL;
1406105197Ssam	}
1407105197Ssam
1408105197Ssam	if ((newsp = KEY_NEWSP()) == NULL) {
1409105197Ssam		*error = ENOBUFS;
1410105197Ssam		return NULL;
1411105197Ssam	}
1412105197Ssam
1413105197Ssam	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1414105197Ssam	newsp->policy = xpl0->sadb_x_policy_type;
1415105197Ssam
1416105197Ssam	/* check policy */
1417105197Ssam	switch (xpl0->sadb_x_policy_type) {
1418105197Ssam	case IPSEC_POLICY_DISCARD:
1419105197Ssam	case IPSEC_POLICY_NONE:
1420105197Ssam	case IPSEC_POLICY_ENTRUST:
1421105197Ssam	case IPSEC_POLICY_BYPASS:
1422105197Ssam		newsp->req = NULL;
1423105197Ssam		break;
1424105197Ssam
1425105197Ssam	case IPSEC_POLICY_IPSEC:
1426105197Ssam	    {
1427105197Ssam		int tlen;
1428105197Ssam		struct sadb_x_ipsecrequest *xisr;
1429105197Ssam		struct ipsecrequest **p_isr = &newsp->req;
1430105197Ssam
1431105197Ssam		/* validity check */
1432105197Ssam		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1433120585Ssam			ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1434120585Ssam				__func__));
1435105197Ssam			KEY_FREESP(&newsp);
1436105197Ssam			*error = EINVAL;
1437105197Ssam			return NULL;
1438105197Ssam		}
1439105197Ssam
1440105197Ssam		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1441105197Ssam		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1442105197Ssam
1443105197Ssam		while (tlen > 0) {
1444105197Ssam			/* length check */
1445105197Ssam			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1446120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1447120585Ssam					"length.\n", __func__));
1448105197Ssam				KEY_FREESP(&newsp);
1449105197Ssam				*error = EINVAL;
1450105197Ssam				return NULL;
1451105197Ssam			}
1452105197Ssam
1453105197Ssam			/* allocate request buffer */
1454119643Ssam			/* NB: data structure is zero'd */
1455119643Ssam			*p_isr = ipsec_newisr();
1456105197Ssam			if ((*p_isr) == NULL) {
1457105197Ssam				ipseclog((LOG_DEBUG,
1458120585Ssam				    "%s: No more memory.\n", __func__));
1459105197Ssam				KEY_FREESP(&newsp);
1460105197Ssam				*error = ENOBUFS;
1461105197Ssam				return NULL;
1462105197Ssam			}
1463105197Ssam
1464105197Ssam			/* set values */
1465105197Ssam			switch (xisr->sadb_x_ipsecrequest_proto) {
1466105197Ssam			case IPPROTO_ESP:
1467105197Ssam			case IPPROTO_AH:
1468105197Ssam			case IPPROTO_IPCOMP:
1469105197Ssam				break;
1470105197Ssam			default:
1471105197Ssam				ipseclog((LOG_DEBUG,
1472120585Ssam				    "%s: invalid proto type=%u\n", __func__,
1473105197Ssam				    xisr->sadb_x_ipsecrequest_proto));
1474105197Ssam				KEY_FREESP(&newsp);
1475105197Ssam				*error = EPROTONOSUPPORT;
1476105197Ssam				return NULL;
1477105197Ssam			}
1478105197Ssam			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1479105197Ssam
1480105197Ssam			switch (xisr->sadb_x_ipsecrequest_mode) {
1481105197Ssam			case IPSEC_MODE_TRANSPORT:
1482105197Ssam			case IPSEC_MODE_TUNNEL:
1483105197Ssam				break;
1484105197Ssam			case IPSEC_MODE_ANY:
1485105197Ssam			default:
1486105197Ssam				ipseclog((LOG_DEBUG,
1487120585Ssam				    "%s: invalid mode=%u\n", __func__,
1488105197Ssam				    xisr->sadb_x_ipsecrequest_mode));
1489105197Ssam				KEY_FREESP(&newsp);
1490105197Ssam				*error = EINVAL;
1491105197Ssam				return NULL;
1492105197Ssam			}
1493105197Ssam			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1494105197Ssam
1495105197Ssam			switch (xisr->sadb_x_ipsecrequest_level) {
1496105197Ssam			case IPSEC_LEVEL_DEFAULT:
1497105197Ssam			case IPSEC_LEVEL_USE:
1498105197Ssam			case IPSEC_LEVEL_REQUIRE:
1499105197Ssam				break;
1500105197Ssam			case IPSEC_LEVEL_UNIQUE:
1501105197Ssam				/* validity check */
1502105197Ssam				/*
1503105197Ssam				 * If range violation of reqid, kernel will
1504105197Ssam				 * update it, don't refuse it.
1505105197Ssam				 */
1506105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid
1507105197Ssam						> IPSEC_MANUAL_REQID_MAX) {
1508105197Ssam					ipseclog((LOG_DEBUG,
1509120585Ssam					    "%s: reqid=%d range "
1510105197Ssam					    "violation, updated by kernel.\n",
1511120585Ssam					    __func__,
1512105197Ssam					    xisr->sadb_x_ipsecrequest_reqid));
1513105197Ssam					xisr->sadb_x_ipsecrequest_reqid = 0;
1514105197Ssam				}
1515105197Ssam
1516105197Ssam				/* allocate new reqid id if reqid is zero. */
1517105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1518105197Ssam					u_int32_t reqid;
1519105197Ssam					if ((reqid = key_newreqid()) == 0) {
1520105197Ssam						KEY_FREESP(&newsp);
1521105197Ssam						*error = ENOBUFS;
1522105197Ssam						return NULL;
1523105197Ssam					}
1524105197Ssam					(*p_isr)->saidx.reqid = reqid;
1525105197Ssam					xisr->sadb_x_ipsecrequest_reqid = reqid;
1526105197Ssam				} else {
1527105197Ssam				/* set it for manual keying. */
1528105197Ssam					(*p_isr)->saidx.reqid =
1529105197Ssam						xisr->sadb_x_ipsecrequest_reqid;
1530105197Ssam				}
1531105197Ssam				break;
1532105197Ssam
1533105197Ssam			default:
1534120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1535120585Ssam					__func__,
1536105197Ssam					xisr->sadb_x_ipsecrequest_level));
1537105197Ssam				KEY_FREESP(&newsp);
1538105197Ssam				*error = EINVAL;
1539105197Ssam				return NULL;
1540105197Ssam			}
1541105197Ssam			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1542105197Ssam
1543105197Ssam			/* set IP addresses if there */
1544105197Ssam			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1545105197Ssam				struct sockaddr *paddr;
1546105197Ssam
1547105197Ssam				paddr = (struct sockaddr *)(xisr + 1);
1548105197Ssam
1549105197Ssam				/* validity check */
1550105197Ssam				if (paddr->sa_len
1551105197Ssam				    > sizeof((*p_isr)->saidx.src)) {
1552120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1553120585Ssam						"request address length.\n",
1554120585Ssam						__func__));
1555105197Ssam					KEY_FREESP(&newsp);
1556105197Ssam					*error = EINVAL;
1557105197Ssam					return NULL;
1558105197Ssam				}
1559105197Ssam				bcopy(paddr, &(*p_isr)->saidx.src,
1560105197Ssam					paddr->sa_len);
1561105197Ssam
1562105197Ssam				paddr = (struct sockaddr *)((caddr_t)paddr
1563105197Ssam							+ paddr->sa_len);
1564105197Ssam
1565105197Ssam				/* validity check */
1566105197Ssam				if (paddr->sa_len
1567105197Ssam				    > sizeof((*p_isr)->saidx.dst)) {
1568120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1569120585Ssam						"request address length.\n",
1570120585Ssam						__func__));
1571105197Ssam					KEY_FREESP(&newsp);
1572105197Ssam					*error = EINVAL;
1573105197Ssam					return NULL;
1574105197Ssam				}
1575105197Ssam				bcopy(paddr, &(*p_isr)->saidx.dst,
1576105197Ssam					paddr->sa_len);
1577105197Ssam			}
1578105197Ssam
1579105197Ssam			(*p_isr)->sp = newsp;
1580105197Ssam
1581105197Ssam			/* initialization for the next. */
1582105197Ssam			p_isr = &(*p_isr)->next;
1583105197Ssam			tlen -= xisr->sadb_x_ipsecrequest_len;
1584105197Ssam
1585105197Ssam			/* validity check */
1586105197Ssam			if (tlen < 0) {
1587120585Ssam				ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1588120585Ssam					__func__));
1589105197Ssam				KEY_FREESP(&newsp);
1590105197Ssam				*error = EINVAL;
1591105197Ssam				return NULL;
1592105197Ssam			}
1593105197Ssam
1594105197Ssam			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1595105197Ssam			                 + xisr->sadb_x_ipsecrequest_len);
1596105197Ssam		}
1597105197Ssam	    }
1598105197Ssam		break;
1599105197Ssam	default:
1600120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1601105197Ssam		KEY_FREESP(&newsp);
1602105197Ssam		*error = EINVAL;
1603105197Ssam		return NULL;
1604105197Ssam	}
1605105197Ssam
1606105197Ssam	*error = 0;
1607105197Ssam	return newsp;
1608105197Ssam}
1609105197Ssam
1610105197Ssamstatic u_int32_t
1611105197Ssamkey_newreqid()
1612105197Ssam{
1613105197Ssam	static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1614105197Ssam
1615105197Ssam	auto_reqid = (auto_reqid == ~0
1616105197Ssam			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1617105197Ssam
1618105197Ssam	/* XXX should be unique check */
1619105197Ssam
1620105197Ssam	return auto_reqid;
1621105197Ssam}
1622105197Ssam
1623105197Ssam/*
1624105197Ssam * copy secpolicy struct to sadb_x_policy structure indicated.
1625105197Ssam */
1626105197Ssamstruct mbuf *
1627105197Ssamkey_sp2msg(sp)
1628105197Ssam	struct secpolicy *sp;
1629105197Ssam{
1630105197Ssam	struct sadb_x_policy *xpl;
1631105197Ssam	int tlen;
1632105197Ssam	caddr_t p;
1633105197Ssam	struct mbuf *m;
1634105197Ssam
1635120585Ssam	IPSEC_ASSERT(sp != NULL, ("null policy"));
1636105197Ssam
1637105197Ssam	tlen = key_getspreqmsglen(sp);
1638105197Ssam
1639105197Ssam	m = key_alloc_mbuf(tlen);
1640105197Ssam	if (!m || m->m_next) {	/*XXX*/
1641105197Ssam		if (m)
1642105197Ssam			m_freem(m);
1643105197Ssam		return NULL;
1644105197Ssam	}
1645105197Ssam
1646105197Ssam	m->m_len = tlen;
1647105197Ssam	m->m_next = NULL;
1648105197Ssam	xpl = mtod(m, struct sadb_x_policy *);
1649105197Ssam	bzero(xpl, tlen);
1650105197Ssam
1651105197Ssam	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1652105197Ssam	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1653105197Ssam	xpl->sadb_x_policy_type = sp->policy;
1654105197Ssam	xpl->sadb_x_policy_dir = sp->spidx.dir;
1655105197Ssam	xpl->sadb_x_policy_id = sp->id;
1656105197Ssam	p = (caddr_t)xpl + sizeof(*xpl);
1657105197Ssam
1658105197Ssam	/* if is the policy for ipsec ? */
1659105197Ssam	if (sp->policy == IPSEC_POLICY_IPSEC) {
1660105197Ssam		struct sadb_x_ipsecrequest *xisr;
1661105197Ssam		struct ipsecrequest *isr;
1662105197Ssam
1663105197Ssam		for (isr = sp->req; isr != NULL; isr = isr->next) {
1664105197Ssam
1665105197Ssam			xisr = (struct sadb_x_ipsecrequest *)p;
1666105197Ssam
1667105197Ssam			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1668105197Ssam			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1669105197Ssam			xisr->sadb_x_ipsecrequest_level = isr->level;
1670105197Ssam			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1671105197Ssam
1672105197Ssam			p += sizeof(*xisr);
1673105197Ssam			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1674105197Ssam			p += isr->saidx.src.sa.sa_len;
1675105197Ssam			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1676105197Ssam			p += isr->saidx.src.sa.sa_len;
1677105197Ssam
1678105197Ssam			xisr->sadb_x_ipsecrequest_len =
1679105197Ssam				PFKEY_ALIGN8(sizeof(*xisr)
1680105197Ssam					+ isr->saidx.src.sa.sa_len
1681105197Ssam					+ isr->saidx.dst.sa.sa_len);
1682105197Ssam		}
1683105197Ssam	}
1684105197Ssam
1685105197Ssam	return m;
1686105197Ssam}
1687105197Ssam
1688105197Ssam/* m will not be freed nor modified */
1689105197Ssamstatic struct mbuf *
1690105197Ssam#ifdef __STDC__
1691105197Ssamkey_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1692105197Ssam	int ndeep, int nitem, ...)
1693105197Ssam#else
1694105197Ssamkey_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1695105197Ssam	struct mbuf *m;
1696105197Ssam	const struct sadb_msghdr *mhp;
1697105197Ssam	int ndeep;
1698105197Ssam	int nitem;
1699105197Ssam	va_dcl
1700105197Ssam#endif
1701105197Ssam{
1702105197Ssam	va_list ap;
1703105197Ssam	int idx;
1704105197Ssam	int i;
1705105197Ssam	struct mbuf *result = NULL, *n;
1706105197Ssam	int len;
1707105197Ssam
1708120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1709120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1710105197Ssam
1711105197Ssam	va_start(ap, nitem);
1712105197Ssam	for (i = 0; i < nitem; i++) {
1713105197Ssam		idx = va_arg(ap, int);
1714105197Ssam		if (idx < 0 || idx > SADB_EXT_MAX)
1715105197Ssam			goto fail;
1716105197Ssam		/* don't attempt to pull empty extension */
1717105197Ssam		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1718105197Ssam			continue;
1719105197Ssam		if (idx != SADB_EXT_RESERVED  &&
1720105197Ssam		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1721105197Ssam			continue;
1722105197Ssam
1723105197Ssam		if (idx == SADB_EXT_RESERVED) {
1724105197Ssam			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1725120585Ssam
1726120585Ssam			IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1727120585Ssam
1728111119Simp			MGETHDR(n, M_DONTWAIT, MT_DATA);
1729105197Ssam			if (!n)
1730105197Ssam				goto fail;
1731105197Ssam			n->m_len = len;
1732105197Ssam			n->m_next = NULL;
1733105197Ssam			m_copydata(m, 0, sizeof(struct sadb_msg),
1734105197Ssam			    mtod(n, caddr_t));
1735105197Ssam		} else if (i < ndeep) {
1736105197Ssam			len = mhp->extlen[idx];
1737105197Ssam			n = key_alloc_mbuf(len);
1738105197Ssam			if (!n || n->m_next) {	/*XXX*/
1739105197Ssam				if (n)
1740105197Ssam					m_freem(n);
1741105197Ssam				goto fail;
1742105197Ssam			}
1743105197Ssam			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1744105197Ssam			    mtod(n, caddr_t));
1745105197Ssam		} else {
1746105197Ssam			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1747111119Simp			    M_DONTWAIT);
1748105197Ssam		}
1749105197Ssam		if (n == NULL)
1750105197Ssam			goto fail;
1751105197Ssam
1752105197Ssam		if (result)
1753105197Ssam			m_cat(result, n);
1754105197Ssam		else
1755105197Ssam			result = n;
1756105197Ssam	}
1757105197Ssam	va_end(ap);
1758105197Ssam
1759105197Ssam	if ((result->m_flags & M_PKTHDR) != 0) {
1760105197Ssam		result->m_pkthdr.len = 0;
1761105197Ssam		for (n = result; n; n = n->m_next)
1762105197Ssam			result->m_pkthdr.len += n->m_len;
1763105197Ssam	}
1764105197Ssam
1765105197Ssam	return result;
1766105197Ssam
1767105197Ssamfail:
1768105197Ssam	m_freem(result);
1769105197Ssam	return NULL;
1770105197Ssam}
1771105197Ssam
1772105197Ssam/*
1773105197Ssam * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1774108533Sschweikh * add an entry to SP database, when received
1775105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1776105197Ssam * from the user(?).
1777105197Ssam * Adding to SP database,
1778105197Ssam * and send
1779105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1780105197Ssam * to the socket which was send.
1781105197Ssam *
1782105197Ssam * SPDADD set a unique policy entry.
1783105197Ssam * SPDSETIDX like SPDADD without a part of policy requests.
1784105197Ssam * SPDUPDATE replace a unique policy entry.
1785105197Ssam *
1786105197Ssam * m will always be freed.
1787105197Ssam */
1788105197Ssamstatic int
1789105197Ssamkey_spdadd(so, m, mhp)
1790105197Ssam	struct socket *so;
1791105197Ssam	struct mbuf *m;
1792105197Ssam	const struct sadb_msghdr *mhp;
1793105197Ssam{
1794105197Ssam	struct sadb_address *src0, *dst0;
1795105197Ssam	struct sadb_x_policy *xpl0, *xpl;
1796105197Ssam	struct sadb_lifetime *lft = NULL;
1797105197Ssam	struct secpolicyindex spidx;
1798105197Ssam	struct secpolicy *newsp;
1799105197Ssam	int error;
1800105197Ssam
1801120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
1802120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1803120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1804120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1805105197Ssam
1806105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1807105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1808105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1809105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1810105197Ssam		return key_senderror(so, m, EINVAL);
1811105197Ssam	}
1812105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1813105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1814105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1815120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1816120585Ssam			__func__));
1817105197Ssam		return key_senderror(so, m, EINVAL);
1818105197Ssam	}
1819105197Ssam	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1820105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1821105197Ssam			< sizeof(struct sadb_lifetime)) {
1822120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1823120585Ssam				__func__));
1824105197Ssam			return key_senderror(so, m, EINVAL);
1825105197Ssam		}
1826105197Ssam		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1827105197Ssam	}
1828105197Ssam
1829105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1830105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1831105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1832105197Ssam
1833194062Svanhu	/*
1834194062Svanhu	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
1835194062Svanhu	 * we are processing traffic endpoints.
1836194062Svanhu	 */
1837194062Svanhu
1838105197Ssam	/* make secindex */
1839105197Ssam	/* XXX boundary check against sa_len */
1840105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1841105197Ssam	                src0 + 1,
1842105197Ssam	                dst0 + 1,
1843105197Ssam	                src0->sadb_address_prefixlen,
1844105197Ssam	                dst0->sadb_address_prefixlen,
1845105197Ssam	                src0->sadb_address_proto,
1846105197Ssam	                &spidx);
1847105197Ssam
1848105197Ssam	/* checking the direciton. */
1849105197Ssam	switch (xpl0->sadb_x_policy_dir) {
1850105197Ssam	case IPSEC_DIR_INBOUND:
1851105197Ssam	case IPSEC_DIR_OUTBOUND:
1852105197Ssam		break;
1853105197Ssam	default:
1854120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1855105197Ssam		mhp->msg->sadb_msg_errno = EINVAL;
1856105197Ssam		return 0;
1857105197Ssam	}
1858105197Ssam
1859105197Ssam	/* check policy */
1860105197Ssam	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1861105197Ssam	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1862105197Ssam	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1863120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1864105197Ssam		return key_senderror(so, m, EINVAL);
1865105197Ssam	}
1866105197Ssam
1867105197Ssam	/* policy requests are mandatory when action is ipsec. */
1868105197Ssam        if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1869105197Ssam	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1870105197Ssam	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1871120585Ssam		ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1872120585Ssam			__func__));
1873105197Ssam		return key_senderror(so, m, EINVAL);
1874105197Ssam	}
1875105197Ssam
1876105197Ssam	/*
1877105197Ssam	 * checking there is SP already or not.
1878105197Ssam	 * SPDUPDATE doesn't depend on whether there is a SP or not.
1879105197Ssam	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1880105197Ssam	 * then error.
1881105197Ssam	 */
1882105197Ssam	newsp = key_getsp(&spidx);
1883105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1884105197Ssam		if (newsp) {
1885206659Svanhu			SPTREE_LOCK();
1886105197Ssam			newsp->state = IPSEC_SPSTATE_DEAD;
1887206659Svanhu			SPTREE_UNLOCK();
1888105197Ssam			KEY_FREESP(&newsp);
1889105197Ssam		}
1890105197Ssam	} else {
1891105197Ssam		if (newsp != NULL) {
1892105197Ssam			KEY_FREESP(&newsp);
1893120585Ssam			ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1894120585Ssam				__func__));
1895105197Ssam			return key_senderror(so, m, EEXIST);
1896105197Ssam		}
1897105197Ssam	}
1898105197Ssam
1899105197Ssam	/* allocation new SP entry */
1900105197Ssam	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1901105197Ssam		return key_senderror(so, m, error);
1902105197Ssam	}
1903105197Ssam
1904105197Ssam	if ((newsp->id = key_getnewspid()) == 0) {
1905119643Ssam		_key_delsp(newsp);
1906105197Ssam		return key_senderror(so, m, ENOBUFS);
1907105197Ssam	}
1908105197Ssam
1909105197Ssam	/* XXX boundary check against sa_len */
1910105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1911105197Ssam	                src0 + 1,
1912105197Ssam	                dst0 + 1,
1913105197Ssam	                src0->sadb_address_prefixlen,
1914105197Ssam	                dst0->sadb_address_prefixlen,
1915105197Ssam	                src0->sadb_address_proto,
1916105197Ssam	                &newsp->spidx);
1917105197Ssam
1918105197Ssam	/* sanity check on addr pair */
1919105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1920105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_family) {
1921119643Ssam		_key_delsp(newsp);
1922105197Ssam		return key_senderror(so, m, EINVAL);
1923105197Ssam	}
1924105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1925105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_len) {
1926119643Ssam		_key_delsp(newsp);
1927105197Ssam		return key_senderror(so, m, EINVAL);
1928105197Ssam	}
1929105197Ssam#if 1
1930197250Svanhu	if (newsp->req && newsp->req->saidx.src.sa.sa_family && newsp->req->saidx.dst.sa.sa_family) {
1931197250Svanhu		if (newsp->req->saidx.src.sa.sa_family != newsp->req->saidx.dst.sa.sa_family) {
1932119643Ssam			_key_delsp(newsp);
1933105197Ssam			return key_senderror(so, m, EINVAL);
1934105197Ssam		}
1935105197Ssam	}
1936105197Ssam#endif
1937105197Ssam
1938105197Ssam	newsp->created = time_second;
1939105197Ssam	newsp->lastused = newsp->created;
1940105197Ssam	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1941105197Ssam	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1942105197Ssam
1943105197Ssam	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1944105197Ssam	newsp->state = IPSEC_SPSTATE_ALIVE;
1945181803Sbz	LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1946105197Ssam
1947105197Ssam	/* delete the entry in spacqtree */
1948105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1949119643Ssam		struct secspacq *spacq = key_getspacq(&spidx);
1950119643Ssam		if (spacq != NULL) {
1951105197Ssam			/* reset counter in order to deletion by timehandler. */
1952105197Ssam			spacq->created = time_second;
1953105197Ssam			spacq->count = 0;
1954120585Ssam			SPACQ_UNLOCK();
1955105197Ssam		}
1956105197Ssam    	}
1957105197Ssam
1958105197Ssam    {
1959105197Ssam	struct mbuf *n, *mpolicy;
1960105197Ssam	struct sadb_msg *newmsg;
1961105197Ssam	int off;
1962105197Ssam
1963194062Svanhu	/*
1964194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
1965194062Svanhu	 * we are sending traffic endpoints.
1966194062Svanhu	 */
1967194062Svanhu
1968105197Ssam	/* create new sadb_msg to reply. */
1969105197Ssam	if (lft) {
1970105197Ssam		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1971105197Ssam		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1972105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1973105197Ssam	} else {
1974105197Ssam		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1975105197Ssam		    SADB_X_EXT_POLICY,
1976105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1977105197Ssam	}
1978105197Ssam	if (!n)
1979105197Ssam		return key_senderror(so, m, ENOBUFS);
1980105197Ssam
1981105197Ssam	if (n->m_len < sizeof(*newmsg)) {
1982105197Ssam		n = m_pullup(n, sizeof(*newmsg));
1983105197Ssam		if (!n)
1984105197Ssam			return key_senderror(so, m, ENOBUFS);
1985105197Ssam	}
1986105197Ssam	newmsg = mtod(n, struct sadb_msg *);
1987105197Ssam	newmsg->sadb_msg_errno = 0;
1988105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1989105197Ssam
1990105197Ssam	off = 0;
1991105197Ssam	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1992105197Ssam	    sizeof(*xpl), &off);
1993105197Ssam	if (mpolicy == NULL) {
1994105197Ssam		/* n is already freed */
1995105197Ssam		return key_senderror(so, m, ENOBUFS);
1996105197Ssam	}
1997105197Ssam	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1998105197Ssam	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1999105197Ssam		m_freem(n);
2000105197Ssam		return key_senderror(so, m, EINVAL);
2001105197Ssam	}
2002105197Ssam	xpl->sadb_x_policy_id = newsp->id;
2003105197Ssam
2004105197Ssam	m_freem(m);
2005105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2006105197Ssam    }
2007105197Ssam}
2008105197Ssam
2009105197Ssam/*
2010105197Ssam * get new policy id.
2011105197Ssam * OUT:
2012105197Ssam *	0:	failure.
2013105197Ssam *	others: success.
2014105197Ssam */
2015105197Ssamstatic u_int32_t
2016105197Ssamkey_getnewspid()
2017105197Ssam{
2018105197Ssam	u_int32_t newid = 0;
2019181803Sbz	int count = V_key_spi_trycnt;	/* XXX */
2020105197Ssam	struct secpolicy *sp;
2021105197Ssam
2022105197Ssam	/* when requesting to allocate spi ranged */
2023105197Ssam	while (count--) {
2024181803Sbz		newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
2025105197Ssam
2026105197Ssam		if ((sp = key_getspbyid(newid)) == NULL)
2027105197Ssam			break;
2028105197Ssam
2029105197Ssam		KEY_FREESP(&sp);
2030105197Ssam	}
2031105197Ssam
2032105197Ssam	if (count == 0 || newid == 0) {
2033120585Ssam		ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2034120585Ssam			__func__));
2035105197Ssam		return 0;
2036105197Ssam	}
2037105197Ssam
2038105197Ssam	return newid;
2039105197Ssam}
2040105197Ssam
2041105197Ssam/*
2042105197Ssam * SADB_SPDDELETE processing
2043105197Ssam * receive
2044105197Ssam *   <base, address(SD), policy(*)>
2045105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2046105197Ssam * and send,
2047105197Ssam *   <base, address(SD), policy(*)>
2048105197Ssam * to the ikmpd.
2049105197Ssam * policy(*) including direction of policy.
2050105197Ssam *
2051105197Ssam * m will always be freed.
2052105197Ssam */
2053105197Ssamstatic int
2054105197Ssamkey_spddelete(so, m, mhp)
2055105197Ssam	struct socket *so;
2056105197Ssam	struct mbuf *m;
2057105197Ssam	const struct sadb_msghdr *mhp;
2058105197Ssam{
2059105197Ssam	struct sadb_address *src0, *dst0;
2060105197Ssam	struct sadb_x_policy *xpl0;
2061105197Ssam	struct secpolicyindex spidx;
2062105197Ssam	struct secpolicy *sp;
2063105197Ssam
2064120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
2065120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2066120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2067120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2068105197Ssam
2069105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2070105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2071105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2072120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2073120585Ssam			__func__));
2074105197Ssam		return key_senderror(so, m, EINVAL);
2075105197Ssam	}
2076105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2077105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2078105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2079120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2080120585Ssam			__func__));
2081105197Ssam		return key_senderror(so, m, EINVAL);
2082105197Ssam	}
2083105197Ssam
2084105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2085105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2086105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2087105197Ssam
2088194062Svanhu	/*
2089194062Svanhu	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
2090194062Svanhu	 * we are processing traffic endpoints.
2091194062Svanhu	 */
2092194062Svanhu
2093105197Ssam	/* make secindex */
2094105197Ssam	/* XXX boundary check against sa_len */
2095105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2096105197Ssam	                src0 + 1,
2097105197Ssam	                dst0 + 1,
2098105197Ssam	                src0->sadb_address_prefixlen,
2099105197Ssam	                dst0->sadb_address_prefixlen,
2100105197Ssam	                src0->sadb_address_proto,
2101105197Ssam	                &spidx);
2102105197Ssam
2103105197Ssam	/* checking the direciton. */
2104105197Ssam	switch (xpl0->sadb_x_policy_dir) {
2105105197Ssam	case IPSEC_DIR_INBOUND:
2106105197Ssam	case IPSEC_DIR_OUTBOUND:
2107105197Ssam		break;
2108105197Ssam	default:
2109120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2110105197Ssam		return key_senderror(so, m, EINVAL);
2111105197Ssam	}
2112105197Ssam
2113105197Ssam	/* Is there SP in SPD ? */
2114105197Ssam	if ((sp = key_getsp(&spidx)) == NULL) {
2115120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2116105197Ssam		return key_senderror(so, m, EINVAL);
2117105197Ssam	}
2118105197Ssam
2119105197Ssam	/* save policy id to buffer to be returned. */
2120105197Ssam	xpl0->sadb_x_policy_id = sp->id;
2121105197Ssam
2122206659Svanhu	SPTREE_LOCK();
2123105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2124206659Svanhu	SPTREE_UNLOCK();
2125105197Ssam	KEY_FREESP(&sp);
2126105197Ssam
2127105197Ssam    {
2128105197Ssam	struct mbuf *n;
2129105197Ssam	struct sadb_msg *newmsg;
2130105197Ssam
2131194062Svanhu	/*
2132194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2133194062Svanhu	 * we are sending traffic endpoints.
2134194062Svanhu	 */
2135194062Svanhu
2136105197Ssam	/* create new sadb_msg to reply. */
2137105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2138105197Ssam	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2139105197Ssam	if (!n)
2140105197Ssam		return key_senderror(so, m, ENOBUFS);
2141105197Ssam
2142105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2143105197Ssam	newmsg->sadb_msg_errno = 0;
2144105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2145105197Ssam
2146105197Ssam	m_freem(m);
2147105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2148105197Ssam    }
2149105197Ssam}
2150105197Ssam
2151105197Ssam/*
2152105197Ssam * SADB_SPDDELETE2 processing
2153105197Ssam * receive
2154105197Ssam *   <base, policy(*)>
2155105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2156105197Ssam * and send,
2157105197Ssam *   <base, policy(*)>
2158105197Ssam * to the ikmpd.
2159105197Ssam * policy(*) including direction of policy.
2160105197Ssam *
2161105197Ssam * m will always be freed.
2162105197Ssam */
2163105197Ssamstatic int
2164105197Ssamkey_spddelete2(so, m, mhp)
2165105197Ssam	struct socket *so;
2166105197Ssam	struct mbuf *m;
2167105197Ssam	const struct sadb_msghdr *mhp;
2168105197Ssam{
2169105197Ssam	u_int32_t id;
2170105197Ssam	struct secpolicy *sp;
2171105197Ssam
2172120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2173120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2174120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2175120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2176105197Ssam
2177105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2178105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2179120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2180170803Sbz		return key_senderror(so, m, EINVAL);
2181105197Ssam	}
2182105197Ssam
2183105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2184105197Ssam
2185105197Ssam	/* Is there SP in SPD ? */
2186105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2187120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2188170803Sbz		return key_senderror(so, m, EINVAL);
2189105197Ssam	}
2190105197Ssam
2191206659Svanhu	SPTREE_LOCK();
2192105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2193206659Svanhu	SPTREE_UNLOCK();
2194105197Ssam	KEY_FREESP(&sp);
2195105197Ssam
2196105197Ssam    {
2197105197Ssam	struct mbuf *n, *nn;
2198105197Ssam	struct sadb_msg *newmsg;
2199105197Ssam	int off, len;
2200105197Ssam
2201105197Ssam	/* create new sadb_msg to reply. */
2202105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2203105197Ssam
2204111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
2205105197Ssam	if (n && len > MHLEN) {
2206111119Simp		MCLGET(n, M_DONTWAIT);
2207105197Ssam		if ((n->m_flags & M_EXT) == 0) {
2208105197Ssam			m_freem(n);
2209105197Ssam			n = NULL;
2210105197Ssam		}
2211105197Ssam	}
2212105197Ssam	if (!n)
2213105197Ssam		return key_senderror(so, m, ENOBUFS);
2214105197Ssam
2215105197Ssam	n->m_len = len;
2216105197Ssam	n->m_next = NULL;
2217105197Ssam	off = 0;
2218105197Ssam
2219105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2220105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2221105197Ssam
2222120585Ssam	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2223120585Ssam		off, len));
2224105197Ssam
2225105197Ssam	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2226111119Simp	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2227105197Ssam	if (!n->m_next) {
2228105197Ssam		m_freem(n);
2229105197Ssam		return key_senderror(so, m, ENOBUFS);
2230105197Ssam	}
2231105197Ssam
2232105197Ssam	n->m_pkthdr.len = 0;
2233105197Ssam	for (nn = n; nn; nn = nn->m_next)
2234105197Ssam		n->m_pkthdr.len += nn->m_len;
2235105197Ssam
2236105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2237105197Ssam	newmsg->sadb_msg_errno = 0;
2238105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2239105197Ssam
2240105197Ssam	m_freem(m);
2241105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2242105197Ssam    }
2243105197Ssam}
2244105197Ssam
2245105197Ssam/*
2246105197Ssam * SADB_X_GET processing
2247105197Ssam * receive
2248105197Ssam *   <base, policy(*)>
2249105197Ssam * from the user(?),
2250105197Ssam * and send,
2251105197Ssam *   <base, address(SD), policy>
2252105197Ssam * to the ikmpd.
2253105197Ssam * policy(*) including direction of policy.
2254105197Ssam *
2255105197Ssam * m will always be freed.
2256105197Ssam */
2257105197Ssamstatic int
2258105197Ssamkey_spdget(so, m, mhp)
2259105197Ssam	struct socket *so;
2260105197Ssam	struct mbuf *m;
2261105197Ssam	const struct sadb_msghdr *mhp;
2262105197Ssam{
2263105197Ssam	u_int32_t id;
2264105197Ssam	struct secpolicy *sp;
2265105197Ssam	struct mbuf *n;
2266105197Ssam
2267120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2268120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2269120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2270120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2271105197Ssam
2272105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2273105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2274120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2275120585Ssam			__func__));
2276105197Ssam		return key_senderror(so, m, EINVAL);
2277105197Ssam	}
2278105197Ssam
2279105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2280105197Ssam
2281105197Ssam	/* Is there SP in SPD ? */
2282105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2283120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2284105197Ssam		return key_senderror(so, m, ENOENT);
2285105197Ssam	}
2286105197Ssam
2287105197Ssam	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2288105197Ssam	if (n != NULL) {
2289105197Ssam		m_freem(m);
2290105197Ssam		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2291105197Ssam	} else
2292105197Ssam		return key_senderror(so, m, ENOBUFS);
2293105197Ssam}
2294105197Ssam
2295105197Ssam/*
2296105197Ssam * SADB_X_SPDACQUIRE processing.
2297105197Ssam * Acquire policy and SA(s) for a *OUTBOUND* packet.
2298105197Ssam * send
2299105197Ssam *   <base, policy(*)>
2300105197Ssam * to KMD, and expect to receive
2301105197Ssam *   <base> with SADB_X_SPDACQUIRE if error occured,
2302105197Ssam * or
2303105197Ssam *   <base, policy>
2304105197Ssam * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2305105197Ssam * policy(*) is without policy requests.
2306105197Ssam *
2307105197Ssam *    0     : succeed
2308105197Ssam *    others: error number
2309105197Ssam */
2310105197Ssamint
2311105197Ssamkey_spdacquire(sp)
2312105197Ssam	struct secpolicy *sp;
2313105197Ssam{
2314105197Ssam	struct mbuf *result = NULL, *m;
2315105197Ssam	struct secspacq *newspacq;
2316105197Ssam
2317120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2318120585Ssam	IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2319120585Ssam	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2320120585Ssam		("policy not IPSEC %u", sp->policy));
2321105197Ssam
2322108533Sschweikh	/* Get an entry to check whether sent message or not. */
2323119643Ssam	newspacq = key_getspacq(&sp->spidx);
2324119643Ssam	if (newspacq != NULL) {
2325181803Sbz		if (V_key_blockacq_count < newspacq->count) {
2326105197Ssam			/* reset counter and do send message. */
2327105197Ssam			newspacq->count = 0;
2328105197Ssam		} else {
2329105197Ssam			/* increment counter and do nothing. */
2330105197Ssam			newspacq->count++;
2331105197Ssam			return 0;
2332105197Ssam		}
2333120585Ssam		SPACQ_UNLOCK();
2334105197Ssam	} else {
2335105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
2336119643Ssam		newspacq = key_newspacq(&sp->spidx);
2337119643Ssam		if (newspacq == NULL)
2338105197Ssam			return ENOBUFS;
2339105197Ssam	}
2340105197Ssam
2341105197Ssam	/* create new sadb_msg to reply. */
2342105197Ssam	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2343170805Sbz	if (!m)
2344170805Sbz		return ENOBUFS;
2345170805Sbz
2346105197Ssam	result = m;
2347105197Ssam
2348105197Ssam	result->m_pkthdr.len = 0;
2349105197Ssam	for (m = result; m; m = m->m_next)
2350105197Ssam		result->m_pkthdr.len += m->m_len;
2351105197Ssam
2352105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2353105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2354105197Ssam
2355105197Ssam	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2356105197Ssam}
2357105197Ssam
2358105197Ssam/*
2359105197Ssam * SADB_SPDFLUSH processing
2360105197Ssam * receive
2361105197Ssam *   <base>
2362105197Ssam * from the user, and free all entries in secpctree.
2363105197Ssam * and send,
2364105197Ssam *   <base>
2365105197Ssam * to the user.
2366105197Ssam * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2367105197Ssam *
2368105197Ssam * m will always be freed.
2369105197Ssam */
2370105197Ssamstatic int
2371105197Ssamkey_spdflush(so, m, mhp)
2372105197Ssam	struct socket *so;
2373105197Ssam	struct mbuf *m;
2374105197Ssam	const struct sadb_msghdr *mhp;
2375105197Ssam{
2376105197Ssam	struct sadb_msg *newmsg;
2377105197Ssam	struct secpolicy *sp;
2378105197Ssam	u_int dir;
2379105197Ssam
2380120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2381120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2382120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2383120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2384105197Ssam
2385105197Ssam	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2386105197Ssam		return key_senderror(so, m, EINVAL);
2387105197Ssam
2388105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2389120585Ssam		SPTREE_LOCK();
2390181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain)
2391105197Ssam			sp->state = IPSEC_SPSTATE_DEAD;
2392120585Ssam		SPTREE_UNLOCK();
2393105197Ssam	}
2394105197Ssam
2395105197Ssam	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2396120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2397105197Ssam		return key_senderror(so, m, ENOBUFS);
2398105197Ssam	}
2399105197Ssam
2400105197Ssam	if (m->m_next)
2401105197Ssam		m_freem(m->m_next);
2402105197Ssam	m->m_next = NULL;
2403105197Ssam	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2404105197Ssam	newmsg = mtod(m, struct sadb_msg *);
2405105197Ssam	newmsg->sadb_msg_errno = 0;
2406105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2407105197Ssam
2408105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2409105197Ssam}
2410105197Ssam
2411105197Ssam/*
2412105197Ssam * SADB_SPDDUMP processing
2413105197Ssam * receive
2414105197Ssam *   <base>
2415105197Ssam * from the user, and dump all SP leaves
2416105197Ssam * and send,
2417105197Ssam *   <base> .....
2418105197Ssam * to the ikmpd.
2419105197Ssam *
2420105197Ssam * m will always be freed.
2421105197Ssam */
2422105197Ssamstatic int
2423105197Ssamkey_spddump(so, m, mhp)
2424105197Ssam	struct socket *so;
2425105197Ssam	struct mbuf *m;
2426105197Ssam	const struct sadb_msghdr *mhp;
2427105197Ssam{
2428105197Ssam	struct secpolicy *sp;
2429105197Ssam	int cnt;
2430105197Ssam	u_int dir;
2431105197Ssam	struct mbuf *n;
2432105197Ssam
2433120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2434120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2435120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2436120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2437105197Ssam
2438105197Ssam	/* search SPD entry and get buffer size. */
2439105197Ssam	cnt = 0;
2440192882Svanhu	SPTREE_LOCK();
2441105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2442181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2443105197Ssam			cnt++;
2444105197Ssam		}
2445105197Ssam	}
2446105197Ssam
2447192882Svanhu	if (cnt == 0) {
2448192882Svanhu		SPTREE_UNLOCK();
2449105197Ssam		return key_senderror(so, m, ENOENT);
2450192882Svanhu	}
2451105197Ssam
2452105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2453181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2454105197Ssam			--cnt;
2455105197Ssam			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2456105197Ssam			    mhp->msg->sadb_msg_pid);
2457105197Ssam
2458105197Ssam			if (n)
2459105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2460105197Ssam		}
2461105197Ssam	}
2462105197Ssam
2463192882Svanhu	SPTREE_UNLOCK();
2464105197Ssam	m_freem(m);
2465105197Ssam	return 0;
2466105197Ssam}
2467105197Ssam
2468105197Ssamstatic struct mbuf *
2469189004Srdivackykey_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid)
2470105197Ssam{
2471105197Ssam	struct mbuf *result = NULL, *m;
2472181330Svanhu	struct seclifetime lt;
2473105197Ssam
2474105197Ssam	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2475105197Ssam	if (!m)
2476105197Ssam		goto fail;
2477105197Ssam	result = m;
2478105197Ssam
2479194062Svanhu	/*
2480194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2481194062Svanhu	 * we are sending traffic endpoints.
2482194062Svanhu	 */
2483105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2484105197Ssam	    &sp->spidx.src.sa, sp->spidx.prefs,
2485105197Ssam	    sp->spidx.ul_proto);
2486105197Ssam	if (!m)
2487105197Ssam		goto fail;
2488105197Ssam	m_cat(result, m);
2489105197Ssam
2490105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2491105197Ssam	    &sp->spidx.dst.sa, sp->spidx.prefd,
2492105197Ssam	    sp->spidx.ul_proto);
2493105197Ssam	if (!m)
2494105197Ssam		goto fail;
2495105197Ssam	m_cat(result, m);
2496105197Ssam
2497105197Ssam	m = key_sp2msg(sp);
2498105197Ssam	if (!m)
2499105197Ssam		goto fail;
2500105197Ssam	m_cat(result, m);
2501105197Ssam
2502181330Svanhu	if(sp->lifetime){
2503181330Svanhu		lt.addtime=sp->created;
2504181330Svanhu		lt.usetime= sp->lastused;
2505181330Svanhu		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_CURRENT);
2506181330Svanhu		if (!m)
2507181330Svanhu			goto fail;
2508181330Svanhu		m_cat(result, m);
2509181330Svanhu
2510181330Svanhu		lt.addtime=sp->lifetime;
2511181330Svanhu		lt.usetime= sp->validtime;
2512181330Svanhu		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_HARD);
2513181330Svanhu		if (!m)
2514181330Svanhu			goto fail;
2515181330Svanhu		m_cat(result, m);
2516181330Svanhu	}
2517181330Svanhu
2518105197Ssam	if ((result->m_flags & M_PKTHDR) == 0)
2519105197Ssam		goto fail;
2520105197Ssam
2521105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2522105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2523105197Ssam		if (result == NULL)
2524105197Ssam			goto fail;
2525105197Ssam	}
2526105197Ssam
2527105197Ssam	result->m_pkthdr.len = 0;
2528105197Ssam	for (m = result; m; m = m->m_next)
2529105197Ssam		result->m_pkthdr.len += m->m_len;
2530105197Ssam
2531105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2532105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2533105197Ssam
2534105197Ssam	return result;
2535105197Ssam
2536105197Ssamfail:
2537105197Ssam	m_freem(result);
2538105197Ssam	return NULL;
2539105197Ssam}
2540105197Ssam
2541105197Ssam/*
2542105197Ssam * get PFKEY message length for security policy and request.
2543105197Ssam */
2544105197Ssamstatic u_int
2545105197Ssamkey_getspreqmsglen(sp)
2546105197Ssam	struct secpolicy *sp;
2547105197Ssam{
2548105197Ssam	u_int tlen;
2549105197Ssam
2550105197Ssam	tlen = sizeof(struct sadb_x_policy);
2551105197Ssam
2552105197Ssam	/* if is the policy for ipsec ? */
2553105197Ssam	if (sp->policy != IPSEC_POLICY_IPSEC)
2554105197Ssam		return tlen;
2555105197Ssam
2556105197Ssam	/* get length of ipsec requests */
2557105197Ssam    {
2558105197Ssam	struct ipsecrequest *isr;
2559105197Ssam	int len;
2560105197Ssam
2561105197Ssam	for (isr = sp->req; isr != NULL; isr = isr->next) {
2562105197Ssam		len = sizeof(struct sadb_x_ipsecrequest)
2563105197Ssam			+ isr->saidx.src.sa.sa_len
2564105197Ssam			+ isr->saidx.dst.sa.sa_len;
2565105197Ssam
2566105197Ssam		tlen += PFKEY_ALIGN8(len);
2567105197Ssam	}
2568105197Ssam    }
2569105197Ssam
2570105197Ssam	return tlen;
2571105197Ssam}
2572105197Ssam
2573105197Ssam/*
2574105197Ssam * SADB_SPDEXPIRE processing
2575105197Ssam * send
2576105197Ssam *   <base, address(SD), lifetime(CH), policy>
2577105197Ssam * to KMD by PF_KEY.
2578105197Ssam *
2579105197Ssam * OUT:	0	: succeed
2580105197Ssam *	others	: error number
2581105197Ssam */
2582105197Ssamstatic int
2583105197Ssamkey_spdexpire(sp)
2584105197Ssam	struct secpolicy *sp;
2585105197Ssam{
2586105197Ssam	struct mbuf *result = NULL, *m;
2587105197Ssam	int len;
2588105197Ssam	int error = -1;
2589105197Ssam	struct sadb_lifetime *lt;
2590105197Ssam
2591105197Ssam	/* XXX: Why do we lock ? */
2592105197Ssam
2593120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2594105197Ssam
2595105197Ssam	/* set msg header */
2596105197Ssam	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2597105197Ssam	if (!m) {
2598105197Ssam		error = ENOBUFS;
2599105197Ssam		goto fail;
2600105197Ssam	}
2601105197Ssam	result = m;
2602105197Ssam
2603105197Ssam	/* create lifetime extension (current and hard) */
2604105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2605105197Ssam	m = key_alloc_mbuf(len);
2606105197Ssam	if (!m || m->m_next) {	/*XXX*/
2607105197Ssam		if (m)
2608105197Ssam			m_freem(m);
2609105197Ssam		error = ENOBUFS;
2610105197Ssam		goto fail;
2611105197Ssam	}
2612105197Ssam	bzero(mtod(m, caddr_t), len);
2613105197Ssam	lt = mtod(m, struct sadb_lifetime *);
2614105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2615105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2616105197Ssam	lt->sadb_lifetime_allocations = 0;
2617105197Ssam	lt->sadb_lifetime_bytes = 0;
2618105197Ssam	lt->sadb_lifetime_addtime = sp->created;
2619105197Ssam	lt->sadb_lifetime_usetime = sp->lastused;
2620105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2621105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2622105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2623105197Ssam	lt->sadb_lifetime_allocations = 0;
2624105197Ssam	lt->sadb_lifetime_bytes = 0;
2625105197Ssam	lt->sadb_lifetime_addtime = sp->lifetime;
2626105197Ssam	lt->sadb_lifetime_usetime = sp->validtime;
2627105197Ssam	m_cat(result, m);
2628105197Ssam
2629194062Svanhu	/*
2630194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2631194062Svanhu	 * we are sending traffic endpoints.
2632194062Svanhu	 */
2633194062Svanhu
2634105197Ssam	/* set sadb_address for source */
2635105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2636105197Ssam	    &sp->spidx.src.sa,
2637105197Ssam	    sp->spidx.prefs, sp->spidx.ul_proto);
2638105197Ssam	if (!m) {
2639105197Ssam		error = ENOBUFS;
2640105197Ssam		goto fail;
2641105197Ssam	}
2642105197Ssam	m_cat(result, m);
2643105197Ssam
2644105197Ssam	/* set sadb_address for destination */
2645105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2646105197Ssam	    &sp->spidx.dst.sa,
2647105197Ssam	    sp->spidx.prefd, sp->spidx.ul_proto);
2648105197Ssam	if (!m) {
2649105197Ssam		error = ENOBUFS;
2650105197Ssam		goto fail;
2651105197Ssam	}
2652105197Ssam	m_cat(result, m);
2653105197Ssam
2654105197Ssam	/* set secpolicy */
2655105197Ssam	m = key_sp2msg(sp);
2656105197Ssam	if (!m) {
2657105197Ssam		error = ENOBUFS;
2658105197Ssam		goto fail;
2659105197Ssam	}
2660105197Ssam	m_cat(result, m);
2661105197Ssam
2662105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
2663105197Ssam		error = EINVAL;
2664105197Ssam		goto fail;
2665105197Ssam	}
2666105197Ssam
2667105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2668105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2669105197Ssam		if (result == NULL) {
2670105197Ssam			error = ENOBUFS;
2671105197Ssam			goto fail;
2672105197Ssam		}
2673105197Ssam	}
2674105197Ssam
2675105197Ssam	result->m_pkthdr.len = 0;
2676105197Ssam	for (m = result; m; m = m->m_next)
2677105197Ssam		result->m_pkthdr.len += m->m_len;
2678105197Ssam
2679105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2680105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2681105197Ssam
2682105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2683105197Ssam
2684105197Ssam fail:
2685105197Ssam	if (result)
2686105197Ssam		m_freem(result);
2687105197Ssam	return error;
2688105197Ssam}
2689105197Ssam
2690105197Ssam/* %%% SAD management */
2691105197Ssam/*
2692105197Ssam * allocating a memory for new SA head, and copy from the values of mhp.
2693105197Ssam * OUT:	NULL	: failure due to the lack of memory.
2694105197Ssam *	others	: pointer to new SA head.
2695105197Ssam */
2696105197Ssamstatic struct secashead *
2697105197Ssamkey_newsah(saidx)
2698105197Ssam	struct secasindex *saidx;
2699105197Ssam{
2700105197Ssam	struct secashead *newsah;
2701105197Ssam
2702120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2703105197Ssam
2704119643Ssam	newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2705105197Ssam	if (newsah != NULL) {
2706105197Ssam		int i;
2707105197Ssam		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2708105197Ssam			LIST_INIT(&newsah->savtree[i]);
2709105197Ssam		newsah->saidx = *saidx;
2710105197Ssam
2711105197Ssam		/* add to saidxtree */
2712105197Ssam		newsah->state = SADB_SASTATE_MATURE;
2713119643Ssam
2714120585Ssam		SAHTREE_LOCK();
2715181803Sbz		LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2716120585Ssam		SAHTREE_UNLOCK();
2717105197Ssam	}
2718105197Ssam	return(newsah);
2719105197Ssam}
2720105197Ssam
2721105197Ssam/*
2722105197Ssam * delete SA index and all SA registerd.
2723105197Ssam */
2724105197Ssamstatic void
2725105197Ssamkey_delsah(sah)
2726105197Ssam	struct secashead *sah;
2727105197Ssam{
2728105197Ssam	struct secasvar *sav, *nextsav;
2729120585Ssam	u_int stateidx;
2730105197Ssam	int zombie = 0;
2731105197Ssam
2732120585Ssam	IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2733120585Ssam	SAHTREE_LOCK_ASSERT();
2734105197Ssam
2735105197Ssam	/* searching all SA registerd in the secindex. */
2736105197Ssam	for (stateidx = 0;
2737185348Szec	     stateidx < _ARRAYLEN(saorder_state_any);
2738105197Ssam	     stateidx++) {
2739185348Szec		u_int state = saorder_state_any[stateidx];
2740120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2741105197Ssam			if (sav->refcnt == 0) {
2742105197Ssam				/* sanity check */
2743120585Ssam				KEY_CHKSASTATE(state, sav->state, __func__);
2744190071Svanhu				/*
2745190071Svanhu				 * do NOT call KEY_FREESAV here:
2746190071Svanhu				 * it will only delete the sav if refcnt == 1,
2747189962Svanhu				 * where we already know that refcnt == 0
2748189962Svanhu				 */
2749189962Svanhu				key_delsav(sav);
2750105197Ssam			} else {
2751105197Ssam				/* give up to delete this sa */
2752105197Ssam				zombie++;
2753105197Ssam			}
2754105197Ssam		}
2755105197Ssam	}
2756120585Ssam	if (!zombie) {		/* delete only if there are savs */
2757120585Ssam		/* remove from tree of SA index */
2758120585Ssam		if (__LIST_CHAINED(sah))
2759120585Ssam			LIST_REMOVE(sah, chain);
2760120585Ssam		if (sah->sa_route.ro_rt) {
2761120585Ssam			RTFREE(sah->sa_route.ro_rt);
2762120585Ssam			sah->sa_route.ro_rt = (struct rtentry *)NULL;
2763120585Ssam		}
2764120585Ssam		free(sah, M_IPSEC_SAH);
2765105197Ssam	}
2766105197Ssam}
2767105197Ssam
2768105197Ssam/*
2769105197Ssam * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2770105197Ssam * and copy the values of mhp into new buffer.
2771105197Ssam * When SAD message type is GETSPI:
2772105197Ssam *	to set sequence number from acq_seq++,
2773105197Ssam *	to set zero to SPI.
2774105197Ssam *	not to call key_setsava().
2775105197Ssam * OUT:	NULL	: fail
2776105197Ssam *	others	: pointer to new secasvar.
2777105197Ssam *
2778105197Ssam * does not modify mbuf.  does not free mbuf on error.
2779105197Ssam */
2780105197Ssamstatic struct secasvar *
2781105197Ssamkey_newsav(m, mhp, sah, errp, where, tag)
2782105197Ssam	struct mbuf *m;
2783105197Ssam	const struct sadb_msghdr *mhp;
2784105197Ssam	struct secashead *sah;
2785105197Ssam	int *errp;
2786105197Ssam	const char* where;
2787105197Ssam	int tag;
2788105197Ssam{
2789105197Ssam	struct secasvar *newsav;
2790105197Ssam	const struct sadb_sa *xsa;
2791105197Ssam
2792120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2793120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2794120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2795120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
2796105197Ssam
2797119643Ssam	newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2798105197Ssam	if (newsav == NULL) {
2799120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2800105197Ssam		*errp = ENOBUFS;
2801105197Ssam		goto done;
2802105197Ssam	}
2803105197Ssam
2804105197Ssam	switch (mhp->msg->sadb_msg_type) {
2805105197Ssam	case SADB_GETSPI:
2806105197Ssam		newsav->spi = 0;
2807105197Ssam
2808105197Ssam#ifdef IPSEC_DOSEQCHECK
2809105197Ssam		/* sync sequence number */
2810105197Ssam		if (mhp->msg->sadb_msg_seq == 0)
2811105197Ssam			newsav->seq =
2812181803Sbz				(V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2813105197Ssam		else
2814105197Ssam#endif
2815105197Ssam			newsav->seq = mhp->msg->sadb_msg_seq;
2816105197Ssam		break;
2817105197Ssam
2818105197Ssam	case SADB_ADD:
2819105197Ssam		/* sanity check */
2820105197Ssam		if (mhp->ext[SADB_EXT_SA] == NULL) {
2821119643Ssam			free(newsav, M_IPSEC_SA);
2822119643Ssam			newsav = NULL;
2823120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2824120585Ssam				__func__));
2825105197Ssam			*errp = EINVAL;
2826105197Ssam			goto done;
2827105197Ssam		}
2828105197Ssam		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2829105197Ssam		newsav->spi = xsa->sadb_sa_spi;
2830105197Ssam		newsav->seq = mhp->msg->sadb_msg_seq;
2831105197Ssam		break;
2832105197Ssam	default:
2833119643Ssam		free(newsav, M_IPSEC_SA);
2834119643Ssam		newsav = NULL;
2835105197Ssam		*errp = EINVAL;
2836105197Ssam		goto done;
2837105197Ssam	}
2838105197Ssam
2839119643Ssam
2840105197Ssam	/* copy sav values */
2841105197Ssam	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2842105197Ssam		*errp = key_setsaval(newsav, m, mhp);
2843105197Ssam		if (*errp) {
2844119643Ssam			free(newsav, M_IPSEC_SA);
2845119643Ssam			newsav = NULL;
2846105197Ssam			goto done;
2847105197Ssam		}
2848105197Ssam	}
2849105197Ssam
2850120585Ssam	SECASVAR_LOCK_INIT(newsav);
2851119643Ssam
2852105197Ssam	/* reset created */
2853105197Ssam	newsav->created = time_second;
2854105197Ssam	newsav->pid = mhp->msg->sadb_msg_pid;
2855105197Ssam
2856105197Ssam	/* add to satree */
2857105197Ssam	newsav->sah = sah;
2858158767Spjd	sa_initref(newsav);
2859105197Ssam	newsav->state = SADB_SASTATE_LARVAL;
2860119643Ssam
2861199398Svanhu	SAHTREE_LOCK();
2862105197Ssam	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2863105197Ssam			secasvar, chain);
2864199398Svanhu	SAHTREE_UNLOCK();
2865105197Ssamdone:
2866105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2867120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
2868105197Ssam			where, tag, newsav));
2869105197Ssam
2870105197Ssam	return newsav;
2871105197Ssam}
2872105197Ssam
2873105197Ssam/*
2874105197Ssam * free() SA variable entry.
2875105197Ssam */
2876105197Ssamstatic void
2877119643Ssamkey_cleansav(struct secasvar *sav)
2878105197Ssam{
2879117051Ssam	/*
2880117051Ssam	 * Cleanup xform state.  Note that zeroize'ing causes the
2881117051Ssam	 * keys to be cleared; otherwise we must do it ourself.
2882117051Ssam	 */
2883117051Ssam	if (sav->tdb_xform != NULL) {
2884117051Ssam		sav->tdb_xform->xf_zeroize(sav);
2885117051Ssam		sav->tdb_xform = NULL;
2886117051Ssam	} else {
2887120585Ssam		KASSERT(sav->iv == NULL, ("iv but no xform"));
2888117051Ssam		if (sav->key_auth != NULL)
2889157123Sgnn			bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2890117051Ssam		if (sav->key_enc != NULL)
2891157123Sgnn			bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2892117051Ssam	}
2893105197Ssam	if (sav->key_auth != NULL) {
2894157123Sgnn		if (sav->key_auth->key_data != NULL)
2895157123Sgnn			free(sav->key_auth->key_data, M_IPSEC_MISC);
2896119643Ssam		free(sav->key_auth, M_IPSEC_MISC);
2897105197Ssam		sav->key_auth = NULL;
2898105197Ssam	}
2899105197Ssam	if (sav->key_enc != NULL) {
2900157123Sgnn		if (sav->key_enc->key_data != NULL)
2901157123Sgnn			free(sav->key_enc->key_data, M_IPSEC_MISC);
2902119643Ssam		free(sav->key_enc, M_IPSEC_MISC);
2903105197Ssam		sav->key_enc = NULL;
2904105197Ssam	}
2905105197Ssam	if (sav->sched) {
2906105197Ssam		bzero(sav->sched, sav->schedlen);
2907119643Ssam		free(sav->sched, M_IPSEC_MISC);
2908105197Ssam		sav->sched = NULL;
2909105197Ssam	}
2910105197Ssam	if (sav->replay != NULL) {
2911119643Ssam		free(sav->replay, M_IPSEC_MISC);
2912105197Ssam		sav->replay = NULL;
2913105197Ssam	}
2914105197Ssam	if (sav->lft_c != NULL) {
2915119643Ssam		free(sav->lft_c, M_IPSEC_MISC);
2916105197Ssam		sav->lft_c = NULL;
2917105197Ssam	}
2918105197Ssam	if (sav->lft_h != NULL) {
2919119643Ssam		free(sav->lft_h, M_IPSEC_MISC);
2920105197Ssam		sav->lft_h = NULL;
2921105197Ssam	}
2922105197Ssam	if (sav->lft_s != NULL) {
2923119643Ssam		free(sav->lft_s, M_IPSEC_MISC);
2924105197Ssam		sav->lft_s = NULL;
2925105197Ssam	}
2926119643Ssam}
2927105197Ssam
2928119643Ssam/*
2929119643Ssam * free() SA variable entry.
2930119643Ssam */
2931119643Ssamstatic void
2932119643Ssamkey_delsav(sav)
2933119643Ssam	struct secasvar *sav;
2934119643Ssam{
2935120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
2936120585Ssam	IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2937105197Ssam
2938119643Ssam	/* remove from SA header */
2939119643Ssam	if (__LIST_CHAINED(sav))
2940119643Ssam		LIST_REMOVE(sav, chain);
2941119643Ssam	key_cleansav(sav);
2942120585Ssam	SECASVAR_LOCK_DESTROY(sav);
2943119643Ssam	free(sav, M_IPSEC_SA);
2944105197Ssam}
2945105197Ssam
2946105197Ssam/*
2947105197Ssam * search SAD.
2948105197Ssam * OUT:
2949105197Ssam *	NULL	: not found
2950105197Ssam *	others	: found, pointer to a SA.
2951105197Ssam */
2952105197Ssamstatic struct secashead *
2953105197Ssamkey_getsah(saidx)
2954105197Ssam	struct secasindex *saidx;
2955105197Ssam{
2956105197Ssam	struct secashead *sah;
2957105197Ssam
2958120585Ssam	SAHTREE_LOCK();
2959181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
2960105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
2961105197Ssam			continue;
2962105197Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2963119643Ssam			break;
2964105197Ssam	}
2965120585Ssam	SAHTREE_UNLOCK();
2966105197Ssam
2967119643Ssam	return sah;
2968105197Ssam}
2969105197Ssam
2970105197Ssam/*
2971105197Ssam * check not to be duplicated SPI.
2972105197Ssam * NOTE: this function is too slow due to searching all SAD.
2973105197Ssam * OUT:
2974105197Ssam *	NULL	: not found
2975105197Ssam *	others	: found, pointer to a SA.
2976105197Ssam */
2977105197Ssamstatic struct secasvar *
2978105197Ssamkey_checkspidup(saidx, spi)
2979105197Ssam	struct secasindex *saidx;
2980105197Ssam	u_int32_t spi;
2981105197Ssam{
2982105197Ssam	struct secashead *sah;
2983105197Ssam	struct secasvar *sav;
2984105197Ssam
2985105197Ssam	/* check address family */
2986105197Ssam	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2987120585Ssam		ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2988120585Ssam			__func__));
2989105197Ssam		return NULL;
2990105197Ssam	}
2991105197Ssam
2992119643Ssam	sav = NULL;
2993105197Ssam	/* check all SAD */
2994120585Ssam	SAHTREE_LOCK();
2995181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
2996105197Ssam		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2997105197Ssam			continue;
2998105197Ssam		sav = key_getsavbyspi(sah, spi);
2999105197Ssam		if (sav != NULL)
3000119643Ssam			break;
3001105197Ssam	}
3002120585Ssam	SAHTREE_UNLOCK();
3003105197Ssam
3004119643Ssam	return sav;
3005105197Ssam}
3006105197Ssam
3007105197Ssam/*
3008105197Ssam * search SAD litmited alive SA, protocol, SPI.
3009105197Ssam * OUT:
3010105197Ssam *	NULL	: not found
3011105197Ssam *	others	: found, pointer to a SA.
3012105197Ssam */
3013105197Ssamstatic struct secasvar *
3014105197Ssamkey_getsavbyspi(sah, spi)
3015105197Ssam	struct secashead *sah;
3016105197Ssam	u_int32_t spi;
3017105197Ssam{
3018105197Ssam	struct secasvar *sav;
3019105197Ssam	u_int stateidx, state;
3020105197Ssam
3021119643Ssam	sav = NULL;
3022120585Ssam	SAHTREE_LOCK_ASSERT();
3023105197Ssam	/* search all status */
3024105197Ssam	for (stateidx = 0;
3025185348Szec	     stateidx < _ARRAYLEN(saorder_state_alive);
3026105197Ssam	     stateidx++) {
3027105197Ssam
3028185348Szec		state = saorder_state_alive[stateidx];
3029105197Ssam		LIST_FOREACH(sav, &sah->savtree[state], chain) {
3030105197Ssam
3031105197Ssam			/* sanity check */
3032105197Ssam			if (sav->state != state) {
3033120585Ssam				ipseclog((LOG_DEBUG, "%s: "
3034105197Ssam				    "invalid sav->state (queue: %d SA: %d)\n",
3035120585Ssam				    __func__, state, sav->state));
3036105197Ssam				continue;
3037105197Ssam			}
3038105197Ssam
3039105197Ssam			if (sav->spi == spi)
3040128859Ssam				return sav;
3041105197Ssam		}
3042105197Ssam	}
3043105197Ssam
3044128859Ssam	return NULL;
3045105197Ssam}
3046105197Ssam
3047105197Ssam/*
3048105197Ssam * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3049105197Ssam * You must update these if need.
3050105197Ssam * OUT:	0:	success.
3051105197Ssam *	!0:	failure.
3052105197Ssam *
3053105197Ssam * does not modify mbuf.  does not free mbuf on error.
3054105197Ssam */
3055105197Ssamstatic int
3056105197Ssamkey_setsaval(sav, m, mhp)
3057105197Ssam	struct secasvar *sav;
3058105197Ssam	struct mbuf *m;
3059105197Ssam	const struct sadb_msghdr *mhp;
3060105197Ssam{
3061105197Ssam	int error = 0;
3062105197Ssam
3063120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
3064120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3065120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3066105197Ssam
3067105197Ssam	/* initialization */
3068105197Ssam	sav->replay = NULL;
3069105197Ssam	sav->key_auth = NULL;
3070105197Ssam	sav->key_enc = NULL;
3071105197Ssam	sav->sched = NULL;
3072105197Ssam	sav->schedlen = 0;
3073105197Ssam	sav->iv = NULL;
3074105197Ssam	sav->lft_c = NULL;
3075105197Ssam	sav->lft_h = NULL;
3076105197Ssam	sav->lft_s = NULL;
3077105197Ssam	sav->tdb_xform = NULL;		/* transform */
3078105197Ssam	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
3079105197Ssam	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
3080105197Ssam	sav->tdb_compalgxform = NULL;	/* compression algorithm */
3081194062Svanhu	/*  Initialize even if NAT-T not compiled in: */
3082194062Svanhu	sav->natt_type = 0;
3083194062Svanhu	sav->natt_esp_frag_len = 0;
3084105197Ssam
3085105197Ssam	/* SA */
3086105197Ssam	if (mhp->ext[SADB_EXT_SA] != NULL) {
3087105197Ssam		const struct sadb_sa *sa0;
3088105197Ssam
3089105197Ssam		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3090105197Ssam		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3091105197Ssam			error = EINVAL;
3092105197Ssam			goto fail;
3093105197Ssam		}
3094105197Ssam
3095105197Ssam		sav->alg_auth = sa0->sadb_sa_auth;
3096105197Ssam		sav->alg_enc = sa0->sadb_sa_encrypt;
3097105197Ssam		sav->flags = sa0->sadb_sa_flags;
3098105197Ssam
3099105197Ssam		/* replay window */
3100105197Ssam		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3101105197Ssam			sav->replay = (struct secreplay *)
3102119643Ssam				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3103105197Ssam			if (sav->replay == NULL) {
3104120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3105120585Ssam					__func__));
3106105197Ssam				error = ENOBUFS;
3107105197Ssam				goto fail;
3108105197Ssam			}
3109105197Ssam			if (sa0->sadb_sa_replay != 0)
3110105197Ssam				sav->replay->bitmap = (caddr_t)(sav->replay+1);
3111105197Ssam			sav->replay->wsize = sa0->sadb_sa_replay;
3112105197Ssam		}
3113105197Ssam	}
3114105197Ssam
3115105197Ssam	/* Authentication keys */
3116105197Ssam	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3117105197Ssam		const struct sadb_key *key0;
3118105197Ssam		int len;
3119105197Ssam
3120105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3121105197Ssam		len = mhp->extlen[SADB_EXT_KEY_AUTH];
3122105197Ssam
3123105197Ssam		error = 0;
3124105197Ssam		if (len < sizeof(*key0)) {
3125105197Ssam			error = EINVAL;
3126105197Ssam			goto fail;
3127105197Ssam		}
3128105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3129105197Ssam		case SADB_SATYPE_AH:
3130105197Ssam		case SADB_SATYPE_ESP:
3131125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3132105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3133105197Ssam			    sav->alg_auth != SADB_X_AALG_NULL)
3134105197Ssam				error = EINVAL;
3135105197Ssam			break;
3136105197Ssam		case SADB_X_SATYPE_IPCOMP:
3137105197Ssam		default:
3138105197Ssam			error = EINVAL;
3139105197Ssam			break;
3140105197Ssam		}
3141105197Ssam		if (error) {
3142120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3143120585Ssam				__func__));
3144105197Ssam			goto fail;
3145105197Ssam		}
3146105197Ssam
3147157123Sgnn		sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3148157123Sgnn								M_IPSEC_MISC);
3149157123Sgnn		if (sav->key_auth == NULL ) {
3150157123Sgnn			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3151157123Sgnn				  __func__));
3152105197Ssam			error = ENOBUFS;
3153105197Ssam			goto fail;
3154105197Ssam		}
3155105197Ssam	}
3156105197Ssam
3157105197Ssam	/* Encryption key */
3158105197Ssam	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3159105197Ssam		const struct sadb_key *key0;
3160105197Ssam		int len;
3161105197Ssam
3162105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3163105197Ssam		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3164105197Ssam
3165105197Ssam		error = 0;
3166105197Ssam		if (len < sizeof(*key0)) {
3167105197Ssam			error = EINVAL;
3168105197Ssam			goto fail;
3169105197Ssam		}
3170105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3171105197Ssam		case SADB_SATYPE_ESP:
3172105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3173105197Ssam			    sav->alg_enc != SADB_EALG_NULL) {
3174105197Ssam				error = EINVAL;
3175105197Ssam				break;
3176105197Ssam			}
3177157123Sgnn			sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3178157123Sgnn								       len,
3179157123Sgnn								       M_IPSEC_MISC);
3180105197Ssam			if (sav->key_enc == NULL) {
3181120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3182120585Ssam					__func__));
3183105197Ssam				error = ENOBUFS;
3184105197Ssam				goto fail;
3185105197Ssam			}
3186105197Ssam			break;
3187105197Ssam		case SADB_X_SATYPE_IPCOMP:
3188105197Ssam			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3189105197Ssam				error = EINVAL;
3190105197Ssam			sav->key_enc = NULL;	/*just in case*/
3191105197Ssam			break;
3192105197Ssam		case SADB_SATYPE_AH:
3193125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3194105197Ssam		default:
3195105197Ssam			error = EINVAL;
3196105197Ssam			break;
3197105197Ssam		}
3198105197Ssam		if (error) {
3199120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3200120585Ssam				__func__));
3201105197Ssam			goto fail;
3202105197Ssam		}
3203105197Ssam	}
3204105197Ssam
3205105197Ssam	/* set iv */
3206105197Ssam	sav->ivlen = 0;
3207105197Ssam
3208105197Ssam	switch (mhp->msg->sadb_msg_satype) {
3209105197Ssam	case SADB_SATYPE_AH:
3210105197Ssam		error = xform_init(sav, XF_AH);
3211105197Ssam		break;
3212105197Ssam	case SADB_SATYPE_ESP:
3213105197Ssam		error = xform_init(sav, XF_ESP);
3214105197Ssam		break;
3215105197Ssam	case SADB_X_SATYPE_IPCOMP:
3216105197Ssam		error = xform_init(sav, XF_IPCOMP);
3217105197Ssam		break;
3218125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
3219125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3220125680Sbms		break;
3221105197Ssam	}
3222105197Ssam	if (error) {
3223120585Ssam		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3224120585Ssam		        __func__, mhp->msg->sadb_msg_satype));
3225105197Ssam		goto fail;
3226105197Ssam	}
3227105197Ssam
3228105197Ssam	/* reset created */
3229105197Ssam	sav->created = time_second;
3230105197Ssam
3231105197Ssam	/* make lifetime for CURRENT */
3232176743Sbz	sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3233105197Ssam	if (sav->lft_c == NULL) {
3234120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3235105197Ssam		error = ENOBUFS;
3236105197Ssam		goto fail;
3237105197Ssam	}
3238105197Ssam
3239157123Sgnn	sav->lft_c->allocations = 0;
3240157123Sgnn	sav->lft_c->bytes = 0;
3241157123Sgnn	sav->lft_c->addtime = time_second;
3242157123Sgnn	sav->lft_c->usetime = 0;
3243105197Ssam
3244105197Ssam	/* lifetimes for HARD and SOFT */
3245105197Ssam    {
3246105197Ssam	const struct sadb_lifetime *lft0;
3247105197Ssam
3248105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3249105197Ssam	if (lft0 != NULL) {
3250105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3251105197Ssam			error = EINVAL;
3252105197Ssam			goto fail;
3253105197Ssam		}
3254157123Sgnn		sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3255105197Ssam		if (sav->lft_h == NULL) {
3256120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3257105197Ssam			error = ENOBUFS;
3258105197Ssam			goto fail;
3259105197Ssam		}
3260105197Ssam		/* to be initialize ? */
3261105197Ssam	}
3262105197Ssam
3263105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3264105197Ssam	if (lft0 != NULL) {
3265105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3266105197Ssam			error = EINVAL;
3267105197Ssam			goto fail;
3268105197Ssam		}
3269157123Sgnn		sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3270105197Ssam		if (sav->lft_s == NULL) {
3271120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3272105197Ssam			error = ENOBUFS;
3273105197Ssam			goto fail;
3274105197Ssam		}
3275105197Ssam		/* to be initialize ? */
3276105197Ssam	}
3277105197Ssam    }
3278105197Ssam
3279105197Ssam	return 0;
3280105197Ssam
3281105197Ssam fail:
3282105197Ssam	/* initialization */
3283119643Ssam	key_cleansav(sav);
3284105197Ssam
3285105197Ssam	return error;
3286105197Ssam}
3287105197Ssam
3288105197Ssam/*
3289105197Ssam * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3290105197Ssam * OUT:	0:	valid
3291105197Ssam *	other:	errno
3292105197Ssam */
3293105197Ssamstatic int
3294119643Ssamkey_mature(struct secasvar *sav)
3295105197Ssam{
3296105197Ssam	int error;
3297105197Ssam
3298105197Ssam	/* check SPI value */
3299105197Ssam	switch (sav->sah->saidx.proto) {
3300105197Ssam	case IPPROTO_ESP:
3301105197Ssam	case IPPROTO_AH:
3302170823Sbz		/*
3303170823Sbz		 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3304170823Sbz		 * 1-255 reserved by IANA for future use,
3305170823Sbz		 * 0 for implementation specific, local use.
3306170823Sbz		 */
3307170823Sbz		if (ntohl(sav->spi) <= 255) {
3308120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3309120585Ssam			    __func__, (u_int32_t)ntohl(sav->spi)));
3310105197Ssam			return EINVAL;
3311105197Ssam		}
3312105197Ssam		break;
3313105197Ssam	}
3314105197Ssam
3315105197Ssam	/* check satype */
3316105197Ssam	switch (sav->sah->saidx.proto) {
3317105197Ssam	case IPPROTO_ESP:
3318105197Ssam		/* check flags */
3319105197Ssam		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3320105197Ssam		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3321120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3322120585Ssam				"given to old-esp.\n", __func__));
3323105197Ssam			return EINVAL;
3324105197Ssam		}
3325105197Ssam		error = xform_init(sav, XF_ESP);
3326105197Ssam		break;
3327105197Ssam	case IPPROTO_AH:
3328105197Ssam		/* check flags */
3329105197Ssam		if (sav->flags & SADB_X_EXT_DERIV) {
3330120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3331120585Ssam				"given to AH SA.\n", __func__));
3332105197Ssam			return EINVAL;
3333105197Ssam		}
3334105197Ssam		if (sav->alg_enc != SADB_EALG_NONE) {
3335120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3336120585Ssam				"mismated.\n", __func__));
3337105197Ssam			return(EINVAL);
3338105197Ssam		}
3339105197Ssam		error = xform_init(sav, XF_AH);
3340105197Ssam		break;
3341105197Ssam	case IPPROTO_IPCOMP:
3342105197Ssam		if (sav->alg_auth != SADB_AALG_NONE) {
3343120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3344120585Ssam				"mismated.\n", __func__));
3345105197Ssam			return(EINVAL);
3346105197Ssam		}
3347105197Ssam		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3348105197Ssam		 && ntohl(sav->spi) >= 0x10000) {
3349120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3350120585Ssam				__func__));
3351105197Ssam			return(EINVAL);
3352105197Ssam		}
3353105197Ssam		error = xform_init(sav, XF_IPCOMP);
3354105197Ssam		break;
3355125680Sbms	case IPPROTO_TCP:
3356125680Sbms		if (sav->alg_enc != SADB_EALG_NONE) {
3357125680Sbms			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3358125680Sbms				"mismated.\n", __func__));
3359125680Sbms			return(EINVAL);
3360125680Sbms		}
3361125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3362125680Sbms		break;
3363105197Ssam	default:
3364120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3365105197Ssam		error = EPROTONOSUPPORT;
3366105197Ssam		break;
3367105197Ssam	}
3368119643Ssam	if (error == 0) {
3369120585Ssam		SAHTREE_LOCK();
3370105197Ssam		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3371120585Ssam		SAHTREE_UNLOCK();
3372119643Ssam	}
3373105197Ssam	return (error);
3374105197Ssam}
3375105197Ssam
3376105197Ssam/*
3377105197Ssam * subroutine for SADB_GET and SADB_DUMP.
3378105197Ssam */
3379105197Ssamstatic struct mbuf *
3380189004Srdivackykey_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3381189004Srdivacky    u_int32_t seq, u_int32_t pid)
3382105197Ssam{
3383105197Ssam	struct mbuf *result = NULL, *tres = NULL, *m;
3384105197Ssam	int i;
3385105197Ssam	int dumporder[] = {
3386105197Ssam		SADB_EXT_SA, SADB_X_EXT_SA2,
3387105197Ssam		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3388105197Ssam		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3389105197Ssam		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3390105197Ssam		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3391105197Ssam		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3392194062Svanhu#ifdef IPSEC_NAT_T
3393194062Svanhu		SADB_X_EXT_NAT_T_TYPE,
3394194062Svanhu		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3395194062Svanhu		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3396194062Svanhu		SADB_X_EXT_NAT_T_FRAG,
3397194062Svanhu#endif
3398105197Ssam	};
3399105197Ssam
3400105197Ssam	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3401105197Ssam	if (m == NULL)
3402105197Ssam		goto fail;
3403105197Ssam	result = m;
3404105197Ssam
3405105197Ssam	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3406105197Ssam		m = NULL;
3407105197Ssam		switch (dumporder[i]) {
3408105197Ssam		case SADB_EXT_SA:
3409105197Ssam			m = key_setsadbsa(sav);
3410105197Ssam			if (!m)
3411105197Ssam				goto fail;
3412105197Ssam			break;
3413105197Ssam
3414105197Ssam		case SADB_X_EXT_SA2:
3415105197Ssam			m = key_setsadbxsa2(sav->sah->saidx.mode,
3416105197Ssam					sav->replay ? sav->replay->count : 0,
3417105197Ssam					sav->sah->saidx.reqid);
3418105197Ssam			if (!m)
3419105197Ssam				goto fail;
3420105197Ssam			break;
3421105197Ssam
3422105197Ssam		case SADB_EXT_ADDRESS_SRC:
3423105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3424105197Ssam			    &sav->sah->saidx.src.sa,
3425105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3426105197Ssam			if (!m)
3427105197Ssam				goto fail;
3428105197Ssam			break;
3429105197Ssam
3430105197Ssam		case SADB_EXT_ADDRESS_DST:
3431105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3432105197Ssam			    &sav->sah->saidx.dst.sa,
3433105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3434105197Ssam			if (!m)
3435105197Ssam				goto fail;
3436105197Ssam			break;
3437105197Ssam
3438105197Ssam		case SADB_EXT_KEY_AUTH:
3439105197Ssam			if (!sav->key_auth)
3440105197Ssam				continue;
3441157123Sgnn			m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3442157123Sgnn			if (!m)
3443157123Sgnn				goto fail;
3444105197Ssam			break;
3445105197Ssam
3446105197Ssam		case SADB_EXT_KEY_ENCRYPT:
3447105197Ssam			if (!sav->key_enc)
3448105197Ssam				continue;
3449157123Sgnn			m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3450157123Sgnn			if (!m)
3451157123Sgnn				goto fail;
3452105197Ssam			break;
3453105197Ssam
3454105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
3455105197Ssam			if (!sav->lft_c)
3456105197Ssam				continue;
3457157123Sgnn			m = key_setlifetime(sav->lft_c,
3458157123Sgnn					    SADB_EXT_LIFETIME_CURRENT);
3459157123Sgnn			if (!m)
3460157123Sgnn				goto fail;
3461105197Ssam			break;
3462105197Ssam
3463105197Ssam		case SADB_EXT_LIFETIME_HARD:
3464105197Ssam			if (!sav->lft_h)
3465105197Ssam				continue;
3466157123Sgnn			m = key_setlifetime(sav->lft_h,
3467157123Sgnn					    SADB_EXT_LIFETIME_HARD);
3468157123Sgnn			if (!m)
3469157123Sgnn				goto fail;
3470105197Ssam			break;
3471105197Ssam
3472105197Ssam		case SADB_EXT_LIFETIME_SOFT:
3473105197Ssam			if (!sav->lft_s)
3474105197Ssam				continue;
3475177554Sbz			m = key_setlifetime(sav->lft_s,
3476157123Sgnn					    SADB_EXT_LIFETIME_SOFT);
3477157123Sgnn
3478157123Sgnn			if (!m)
3479157123Sgnn				goto fail;
3480105197Ssam			break;
3481105197Ssam
3482194062Svanhu#ifdef IPSEC_NAT_T
3483194062Svanhu		case SADB_X_EXT_NAT_T_TYPE:
3484194062Svanhu			m = key_setsadbxtype(sav->natt_type);
3485194062Svanhu			if (!m)
3486194062Svanhu				goto fail;
3487194062Svanhu			break;
3488194062Svanhu
3489194062Svanhu		case SADB_X_EXT_NAT_T_DPORT:
3490194062Svanhu			m = key_setsadbxport(
3491194062Svanhu			    KEY_PORTFROMSADDR(&sav->sah->saidx.dst),
3492194062Svanhu			    SADB_X_EXT_NAT_T_DPORT);
3493194062Svanhu			if (!m)
3494194062Svanhu				goto fail;
3495194062Svanhu			break;
3496194062Svanhu
3497194062Svanhu		case SADB_X_EXT_NAT_T_SPORT:
3498194062Svanhu			m = key_setsadbxport(
3499194062Svanhu			    KEY_PORTFROMSADDR(&sav->sah->saidx.src),
3500194062Svanhu			    SADB_X_EXT_NAT_T_SPORT);
3501194062Svanhu			if (!m)
3502194062Svanhu				goto fail;
3503194062Svanhu			break;
3504194062Svanhu
3505194062Svanhu		case SADB_X_EXT_NAT_T_OAI:
3506194062Svanhu		case SADB_X_EXT_NAT_T_OAR:
3507194062Svanhu		case SADB_X_EXT_NAT_T_FRAG:
3508194062Svanhu			/* We do not (yet) support those. */
3509194062Svanhu			continue;
3510194062Svanhu#endif
3511194062Svanhu
3512105197Ssam		case SADB_EXT_ADDRESS_PROXY:
3513105197Ssam		case SADB_EXT_IDENTITY_SRC:
3514105197Ssam		case SADB_EXT_IDENTITY_DST:
3515105197Ssam			/* XXX: should we brought from SPD ? */
3516105197Ssam		case SADB_EXT_SENSITIVITY:
3517105197Ssam		default:
3518105197Ssam			continue;
3519105197Ssam		}
3520105197Ssam
3521157123Sgnn		if (!m)
3522105197Ssam			goto fail;
3523105197Ssam		if (tres)
3524105197Ssam			m_cat(m, tres);
3525105197Ssam		tres = m;
3526157123Sgnn
3527105197Ssam	}
3528105197Ssam
3529105197Ssam	m_cat(result, tres);
3530105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
3531105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
3532105197Ssam		if (result == NULL)
3533105197Ssam			goto fail;
3534105197Ssam	}
3535105197Ssam
3536105197Ssam	result->m_pkthdr.len = 0;
3537105197Ssam	for (m = result; m; m = m->m_next)
3538105197Ssam		result->m_pkthdr.len += m->m_len;
3539105197Ssam
3540105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
3541105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
3542105197Ssam
3543105197Ssam	return result;
3544105197Ssam
3545105197Ssamfail:
3546105197Ssam	m_freem(result);
3547105197Ssam	m_freem(tres);
3548105197Ssam	return NULL;
3549105197Ssam}
3550105197Ssam
3551105197Ssam/*
3552105197Ssam * set data into sadb_msg.
3553105197Ssam */
3554105197Ssamstatic struct mbuf *
3555189004Srdivackykey_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3556189004Srdivacky    pid_t pid, u_int16_t reserved)
3557105197Ssam{
3558105197Ssam	struct mbuf *m;
3559105197Ssam	struct sadb_msg *p;
3560105197Ssam	int len;
3561105197Ssam
3562105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3563105197Ssam	if (len > MCLBYTES)
3564105197Ssam		return NULL;
3565111119Simp	MGETHDR(m, M_DONTWAIT, MT_DATA);
3566105197Ssam	if (m && len > MHLEN) {
3567111119Simp		MCLGET(m, M_DONTWAIT);
3568105197Ssam		if ((m->m_flags & M_EXT) == 0) {
3569105197Ssam			m_freem(m);
3570105197Ssam			m = NULL;
3571105197Ssam		}
3572105197Ssam	}
3573105197Ssam	if (!m)
3574105197Ssam		return NULL;
3575105197Ssam	m->m_pkthdr.len = m->m_len = len;
3576105197Ssam	m->m_next = NULL;
3577105197Ssam
3578105197Ssam	p = mtod(m, struct sadb_msg *);
3579105197Ssam
3580105197Ssam	bzero(p, len);
3581105197Ssam	p->sadb_msg_version = PF_KEY_V2;
3582105197Ssam	p->sadb_msg_type = type;
3583105197Ssam	p->sadb_msg_errno = 0;
3584105197Ssam	p->sadb_msg_satype = satype;
3585105197Ssam	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3586105197Ssam	p->sadb_msg_reserved = reserved;
3587105197Ssam	p->sadb_msg_seq = seq;
3588105197Ssam	p->sadb_msg_pid = (u_int32_t)pid;
3589105197Ssam
3590105197Ssam	return m;
3591105197Ssam}
3592105197Ssam
3593105197Ssam/*
3594105197Ssam * copy secasvar data into sadb_address.
3595105197Ssam */
3596105197Ssamstatic struct mbuf *
3597105197Ssamkey_setsadbsa(sav)
3598105197Ssam	struct secasvar *sav;
3599105197Ssam{
3600105197Ssam	struct mbuf *m;
3601105197Ssam	struct sadb_sa *p;
3602105197Ssam	int len;
3603105197Ssam
3604105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3605105197Ssam	m = key_alloc_mbuf(len);
3606105197Ssam	if (!m || m->m_next) {	/*XXX*/
3607105197Ssam		if (m)
3608105197Ssam			m_freem(m);
3609105197Ssam		return NULL;
3610105197Ssam	}
3611105197Ssam
3612105197Ssam	p = mtod(m, struct sadb_sa *);
3613105197Ssam
3614105197Ssam	bzero(p, len);
3615105197Ssam	p->sadb_sa_len = PFKEY_UNIT64(len);
3616105197Ssam	p->sadb_sa_exttype = SADB_EXT_SA;
3617105197Ssam	p->sadb_sa_spi = sav->spi;
3618105197Ssam	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3619105197Ssam	p->sadb_sa_state = sav->state;
3620105197Ssam	p->sadb_sa_auth = sav->alg_auth;
3621105197Ssam	p->sadb_sa_encrypt = sav->alg_enc;
3622105197Ssam	p->sadb_sa_flags = sav->flags;
3623105197Ssam
3624105197Ssam	return m;
3625105197Ssam}
3626105197Ssam
3627105197Ssam/*
3628105197Ssam * set data into sadb_address.
3629105197Ssam */
3630105197Ssamstatic struct mbuf *
3631189004Srdivackykey_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto)
3632105197Ssam{
3633105197Ssam	struct mbuf *m;
3634105197Ssam	struct sadb_address *p;
3635105197Ssam	size_t len;
3636105197Ssam
3637105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3638105197Ssam	    PFKEY_ALIGN8(saddr->sa_len);
3639105197Ssam	m = key_alloc_mbuf(len);
3640105197Ssam	if (!m || m->m_next) {	/*XXX*/
3641105197Ssam		if (m)
3642105197Ssam			m_freem(m);
3643105197Ssam		return NULL;
3644105197Ssam	}
3645105197Ssam
3646105197Ssam	p = mtod(m, struct sadb_address *);
3647105197Ssam
3648105197Ssam	bzero(p, len);
3649105197Ssam	p->sadb_address_len = PFKEY_UNIT64(len);
3650105197Ssam	p->sadb_address_exttype = exttype;
3651105197Ssam	p->sadb_address_proto = ul_proto;
3652105197Ssam	if (prefixlen == FULLMASK) {
3653105197Ssam		switch (saddr->sa_family) {
3654105197Ssam		case AF_INET:
3655105197Ssam			prefixlen = sizeof(struct in_addr) << 3;
3656105197Ssam			break;
3657105197Ssam		case AF_INET6:
3658105197Ssam			prefixlen = sizeof(struct in6_addr) << 3;
3659105197Ssam			break;
3660105197Ssam		default:
3661105197Ssam			; /*XXX*/
3662105197Ssam		}
3663105197Ssam	}
3664105197Ssam	p->sadb_address_prefixlen = prefixlen;
3665105197Ssam	p->sadb_address_reserved = 0;
3666105197Ssam
3667105197Ssam	bcopy(saddr,
3668105197Ssam	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3669105197Ssam	    saddr->sa_len);
3670105197Ssam
3671105197Ssam	return m;
3672105197Ssam}
3673105197Ssam
3674105197Ssam/*
3675105197Ssam * set data into sadb_x_sa2.
3676105197Ssam */
3677105197Ssamstatic struct mbuf *
3678189004Srdivackykey_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3679105197Ssam{
3680105197Ssam	struct mbuf *m;
3681105197Ssam	struct sadb_x_sa2 *p;
3682105197Ssam	size_t len;
3683105197Ssam
3684105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3685105197Ssam	m = key_alloc_mbuf(len);
3686105197Ssam	if (!m || m->m_next) {	/*XXX*/
3687105197Ssam		if (m)
3688105197Ssam			m_freem(m);
3689105197Ssam		return NULL;
3690105197Ssam	}
3691105197Ssam
3692105197Ssam	p = mtod(m, struct sadb_x_sa2 *);
3693105197Ssam
3694105197Ssam	bzero(p, len);
3695105197Ssam	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3696105197Ssam	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3697105197Ssam	p->sadb_x_sa2_mode = mode;
3698105197Ssam	p->sadb_x_sa2_reserved1 = 0;
3699105197Ssam	p->sadb_x_sa2_reserved2 = 0;
3700105197Ssam	p->sadb_x_sa2_sequence = seq;
3701105197Ssam	p->sadb_x_sa2_reqid = reqid;
3702105197Ssam
3703105197Ssam	return m;
3704105197Ssam}
3705105197Ssam
3706194062Svanhu#ifdef IPSEC_NAT_T
3707105197Ssam/*
3708194062Svanhu * Set a type in sadb_x_nat_t_type.
3709194062Svanhu */
3710194062Svanhustatic struct mbuf *
3711194062Svanhukey_setsadbxtype(u_int16_t type)
3712194062Svanhu{
3713194062Svanhu	struct mbuf *m;
3714194062Svanhu	size_t len;
3715194062Svanhu	struct sadb_x_nat_t_type *p;
3716194062Svanhu
3717194062Svanhu	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3718194062Svanhu
3719194062Svanhu	m = key_alloc_mbuf(len);
3720194062Svanhu	if (!m || m->m_next) {	/*XXX*/
3721194062Svanhu		if (m)
3722194062Svanhu			m_freem(m);
3723194062Svanhu		return (NULL);
3724194062Svanhu	}
3725194062Svanhu
3726194062Svanhu	p = mtod(m, struct sadb_x_nat_t_type *);
3727194062Svanhu
3728194062Svanhu	bzero(p, len);
3729194062Svanhu	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3730194062Svanhu	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3731194062Svanhu	p->sadb_x_nat_t_type_type = type;
3732194062Svanhu
3733194062Svanhu	return (m);
3734194062Svanhu}
3735194062Svanhu/*
3736194062Svanhu * Set a port in sadb_x_nat_t_port.
3737194062Svanhu * In contrast to default RFC 2367 behaviour, port is in network byte order.
3738194062Svanhu */
3739194062Svanhustatic struct mbuf *
3740194062Svanhukey_setsadbxport(u_int16_t port, u_int16_t type)
3741194062Svanhu{
3742194062Svanhu	struct mbuf *m;
3743194062Svanhu	size_t len;
3744194062Svanhu	struct sadb_x_nat_t_port *p;
3745194062Svanhu
3746194062Svanhu	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3747194062Svanhu
3748194062Svanhu	m = key_alloc_mbuf(len);
3749194062Svanhu	if (!m || m->m_next) {	/*XXX*/
3750194062Svanhu		if (m)
3751194062Svanhu			m_freem(m);
3752194062Svanhu		return (NULL);
3753194062Svanhu	}
3754194062Svanhu
3755194062Svanhu	p = mtod(m, struct sadb_x_nat_t_port *);
3756194062Svanhu
3757194062Svanhu	bzero(p, len);
3758194062Svanhu	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3759194062Svanhu	p->sadb_x_nat_t_port_exttype = type;
3760194062Svanhu	p->sadb_x_nat_t_port_port = port;
3761194062Svanhu
3762194062Svanhu	return (m);
3763194062Svanhu}
3764194062Svanhu
3765194062Svanhu/*
3766194062Svanhu * Get port from sockaddr. Port is in network byte order.
3767194062Svanhu */
3768194062Svanhuu_int16_t
3769194062Svanhukey_portfromsaddr(struct sockaddr *sa)
3770194062Svanhu{
3771194062Svanhu
3772194062Svanhu	switch (sa->sa_family) {
3773194062Svanhu#ifdef INET
3774194062Svanhu	case AF_INET:
3775194062Svanhu		return ((struct sockaddr_in *)sa)->sin_port;
3776194062Svanhu#endif
3777194062Svanhu#ifdef INET6
3778194062Svanhu	case AF_INET6:
3779194062Svanhu		return ((struct sockaddr_in6 *)sa)->sin6_port;
3780194062Svanhu#endif
3781194062Svanhu	}
3782194062Svanhu	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
3783194062Svanhu		printf("DP %s unexpected address family %d\n",
3784194062Svanhu			__func__, sa->sa_family));
3785194062Svanhu	return (0);
3786194062Svanhu}
3787194062Svanhu#endif /* IPSEC_NAT_T */
3788194062Svanhu
3789194062Svanhu/*
3790194062Svanhu * Set port in struct sockaddr. Port is in network byte order.
3791194062Svanhu */
3792194062Svanhustatic void
3793194062Svanhukey_porttosaddr(struct sockaddr *sa, u_int16_t port)
3794194062Svanhu{
3795194062Svanhu
3796194062Svanhu	switch (sa->sa_family) {
3797194062Svanhu#ifdef INET
3798194062Svanhu	case AF_INET:
3799194062Svanhu		((struct sockaddr_in *)sa)->sin_port = port;
3800194062Svanhu		break;
3801194062Svanhu#endif
3802194062Svanhu#ifdef INET6
3803194062Svanhu	case AF_INET6:
3804194062Svanhu		((struct sockaddr_in6 *)sa)->sin6_port = port;
3805194062Svanhu		break;
3806194062Svanhu#endif
3807194062Svanhu	default:
3808194062Svanhu		ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
3809194062Svanhu			__func__, sa->sa_family));
3810194062Svanhu		break;
3811194062Svanhu	}
3812194062Svanhu}
3813194062Svanhu
3814194062Svanhu/*
3815105197Ssam * set data into sadb_x_policy
3816105197Ssam */
3817105197Ssamstatic struct mbuf *
3818189004Srdivackykey_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3819105197Ssam{
3820105197Ssam	struct mbuf *m;
3821105197Ssam	struct sadb_x_policy *p;
3822105197Ssam	size_t len;
3823105197Ssam
3824105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3825105197Ssam	m = key_alloc_mbuf(len);
3826105197Ssam	if (!m || m->m_next) {	/*XXX*/
3827105197Ssam		if (m)
3828105197Ssam			m_freem(m);
3829105197Ssam		return NULL;
3830105197Ssam	}
3831105197Ssam
3832105197Ssam	p = mtod(m, struct sadb_x_policy *);
3833105197Ssam
3834105197Ssam	bzero(p, len);
3835105197Ssam	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3836105197Ssam	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3837105197Ssam	p->sadb_x_policy_type = type;
3838105197Ssam	p->sadb_x_policy_dir = dir;
3839105197Ssam	p->sadb_x_policy_id = id;
3840105197Ssam
3841105197Ssam	return m;
3842105197Ssam}
3843105197Ssam
3844105197Ssam/* %%% utilities */
3845157123Sgnn/* Take a key message (sadb_key) from the socket and turn it into one
3846157123Sgnn * of the kernel's key structures (seckey).
3847157123Sgnn *
3848157123Sgnn * IN: pointer to the src
3849157123Sgnn * OUT: NULL no more memory
3850105197Ssam */
3851157123Sgnnstruct seckey *
3852157123Sgnnkey_dup_keymsg(const struct sadb_key *src, u_int len,
3853157123Sgnn	       struct malloc_type *type)
3854105197Ssam{
3855157123Sgnn	struct seckey *dst;
3856157123Sgnn	dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3857157123Sgnn	if (dst != NULL) {
3858157123Sgnn		dst->bits = src->sadb_key_bits;
3859157123Sgnn		dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3860157123Sgnn		if (dst->key_data != NULL) {
3861157123Sgnn			bcopy((const char *)src + sizeof(struct sadb_key),
3862157123Sgnn			      dst->key_data, len);
3863157123Sgnn		} else {
3864157123Sgnn			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3865157123Sgnn				  __func__));
3866157123Sgnn			free(dst, type);
3867157123Sgnn			dst = NULL;
3868157123Sgnn		}
3869157123Sgnn	} else {
3870157123Sgnn		ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3871157123Sgnn			  __func__));
3872105197Ssam
3873157123Sgnn	}
3874157123Sgnn	return dst;
3875157123Sgnn}
3876157123Sgnn
3877157123Sgnn/* Take a lifetime message (sadb_lifetime) passed in on a socket and
3878157123Sgnn * turn it into one of the kernel's lifetime structures (seclifetime).
3879157123Sgnn *
3880157123Sgnn * IN: pointer to the destination, source and malloc type
3881157123Sgnn * OUT: NULL, no more memory
3882157123Sgnn */
3883157123Sgnn
3884157123Sgnnstatic struct seclifetime *
3885157123Sgnnkey_dup_lifemsg(const struct sadb_lifetime *src,
3886157123Sgnn		 struct malloc_type *type)
3887157123Sgnn{
3888157123Sgnn	struct seclifetime *dst = NULL;
3889157123Sgnn
3890157123Sgnn	dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3891157123Sgnn					   type, M_NOWAIT);
3892157123Sgnn	if (dst == NULL) {
3893119643Ssam		/* XXX counter */
3894120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3895157123Sgnn	} else {
3896157123Sgnn		dst->allocations = src->sadb_lifetime_allocations;
3897157123Sgnn		dst->bytes = src->sadb_lifetime_bytes;
3898157123Sgnn		dst->addtime = src->sadb_lifetime_addtime;
3899157123Sgnn		dst->usetime = src->sadb_lifetime_usetime;
3900157123Sgnn	}
3901157123Sgnn	return dst;
3902105197Ssam}
3903105197Ssam
3904105197Ssam/* compare my own address
3905105197Ssam * OUT:	1: true, i.e. my address.
3906105197Ssam *	0: false
3907105197Ssam */
3908105197Ssamint
3909105197Ssamkey_ismyaddr(sa)
3910105197Ssam	struct sockaddr *sa;
3911105197Ssam{
3912105197Ssam#ifdef INET
3913105197Ssam	struct sockaddr_in *sin;
3914105197Ssam	struct in_ifaddr *ia;
3915105197Ssam#endif
3916105197Ssam
3917120585Ssam	IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3918105197Ssam
3919105197Ssam	switch (sa->sa_family) {
3920105197Ssam#ifdef INET
3921105197Ssam	case AF_INET:
3922105197Ssam		sin = (struct sockaddr_in *)sa;
3923194951Srwatson		IN_IFADDR_RLOCK();
3924181803Sbz		for (ia = V_in_ifaddrhead.tqh_first; ia;
3925105197Ssam		     ia = ia->ia_link.tqe_next)
3926105197Ssam		{
3927105197Ssam			if (sin->sin_family == ia->ia_addr.sin_family &&
3928105197Ssam			    sin->sin_len == ia->ia_addr.sin_len &&
3929105197Ssam			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3930105197Ssam			{
3931194951Srwatson				IN_IFADDR_RUNLOCK();
3932105197Ssam				return 1;
3933105197Ssam			}
3934105197Ssam		}
3935194951Srwatson		IN_IFADDR_RUNLOCK();
3936105197Ssam		break;
3937105197Ssam#endif
3938105197Ssam#ifdef INET6
3939105197Ssam	case AF_INET6:
3940105197Ssam		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3941105197Ssam#endif
3942105197Ssam	}
3943105197Ssam
3944105197Ssam	return 0;
3945105197Ssam}
3946105197Ssam
3947105197Ssam#ifdef INET6
3948105197Ssam/*
3949105197Ssam * compare my own address for IPv6.
3950105197Ssam * 1: ours
3951105197Ssam * 0: other
3952105197Ssam * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3953105197Ssam */
3954105197Ssam#include <netinet6/in6_var.h>
3955105197Ssam
3956105197Ssamstatic int
3957105197Ssamkey_ismyaddr6(sin6)
3958105197Ssam	struct sockaddr_in6 *sin6;
3959105197Ssam{
3960105197Ssam	struct in6_ifaddr *ia;
3961191663Sbms#if 0
3962105197Ssam	struct in6_multi *in6m;
3963191663Sbms#endif
3964105197Ssam
3965194971Srwatson	IN6_IFADDR_RLOCK();
3966194907Srwatson	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
3967105197Ssam		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3968194971Srwatson		    (struct sockaddr *)&ia->ia_addr, 0) == 0) {
3969194971Srwatson			IN6_IFADDR_RUNLOCK();
3970105197Ssam			return 1;
3971194971Srwatson		}
3972105197Ssam
3973191663Sbms#if 0
3974105197Ssam		/*
3975105197Ssam		 * XXX Multicast
3976105197Ssam		 * XXX why do we care about multlicast here while we don't care
3977105197Ssam		 * about IPv4 multicast??
3978105197Ssam		 * XXX scope
3979105197Ssam		 */
3980105197Ssam		in6m = NULL;
3981105197Ssam		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3982194971Srwatson		if (in6m) {
3983194971Srwatson			IN6_IFADDR_RUNLOCK();
3984105197Ssam			return 1;
3985194971Srwatson		}
3986191663Sbms#endif
3987105197Ssam	}
3988194971Srwatson	IN6_IFADDR_RUNLOCK();
3989105197Ssam
3990105197Ssam	/* loopback, just for safety */
3991105197Ssam	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3992105197Ssam		return 1;
3993105197Ssam
3994105197Ssam	return 0;
3995105197Ssam}
3996105197Ssam#endif /*INET6*/
3997105197Ssam
3998105197Ssam/*
3999105197Ssam * compare two secasindex structure.
4000105197Ssam * flag can specify to compare 2 saidxes.
4001105197Ssam * compare two secasindex structure without both mode and reqid.
4002105197Ssam * don't compare port.
4003105197Ssam * IN:
4004105197Ssam *      saidx0: source, it can be in SAD.
4005105197Ssam *      saidx1: object.
4006105197Ssam * OUT:
4007105197Ssam *      1 : equal
4008105197Ssam *      0 : not equal
4009105197Ssam */
4010105197Ssamstatic int
4011105197Ssamkey_cmpsaidx(
4012105197Ssam	const struct secasindex *saidx0,
4013105197Ssam	const struct secasindex *saidx1,
4014105197Ssam	int flag)
4015105197Ssam{
4016194062Svanhu	int chkport = 0;
4017194062Svanhu
4018105197Ssam	/* sanity */
4019105197Ssam	if (saidx0 == NULL && saidx1 == NULL)
4020105197Ssam		return 1;
4021105197Ssam
4022105197Ssam	if (saidx0 == NULL || saidx1 == NULL)
4023105197Ssam		return 0;
4024105197Ssam
4025105197Ssam	if (saidx0->proto != saidx1->proto)
4026105197Ssam		return 0;
4027105197Ssam
4028105197Ssam	if (flag == CMP_EXACTLY) {
4029105197Ssam		if (saidx0->mode != saidx1->mode)
4030105197Ssam			return 0;
4031105197Ssam		if (saidx0->reqid != saidx1->reqid)
4032105197Ssam			return 0;
4033105197Ssam		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4034105197Ssam		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4035105197Ssam			return 0;
4036105197Ssam	} else {
4037105197Ssam
4038105197Ssam		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4039105197Ssam		if (flag == CMP_MODE_REQID
4040105197Ssam		  ||flag == CMP_REQID) {
4041105197Ssam			/*
4042105197Ssam			 * If reqid of SPD is non-zero, unique SA is required.
4043105197Ssam			 * The result must be of same reqid in this case.
4044105197Ssam			 */
4045105197Ssam			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4046105197Ssam				return 0;
4047105197Ssam		}
4048105197Ssam
4049105197Ssam		if (flag == CMP_MODE_REQID) {
4050105197Ssam			if (saidx0->mode != IPSEC_MODE_ANY
4051105197Ssam			 && saidx0->mode != saidx1->mode)
4052105197Ssam				return 0;
4053105197Ssam		}
4054105197Ssam
4055194062Svanhu#ifdef IPSEC_NAT_T
4056194062Svanhu		/*
4057194062Svanhu		 * If NAT-T is enabled, check ports for tunnel mode.
4058194062Svanhu		 * Do not check ports if they are set to zero in the SPD.
4059194062Svanhu		 * Also do not do it for transport mode, as there is no
4060194062Svanhu		 * port information available in the SP.
4061194062Svanhu		 */
4062194062Svanhu		if (saidx1->mode == IPSEC_MODE_TUNNEL &&
4063194062Svanhu		    saidx1->src.sa.sa_family == AF_INET &&
4064194062Svanhu		    saidx1->dst.sa.sa_family == AF_INET &&
4065194062Svanhu		    ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
4066194062Svanhu		    ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
4067194062Svanhu			chkport = 1;
4068194062Svanhu#endif /* IPSEC_NAT_T */
4069194062Svanhu
4070194062Svanhu		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
4071105197Ssam			return 0;
4072105197Ssam		}
4073194062Svanhu		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
4074105197Ssam			return 0;
4075105197Ssam		}
4076105197Ssam	}
4077105197Ssam
4078105197Ssam	return 1;
4079105197Ssam}
4080105197Ssam
4081105197Ssam/*
4082105197Ssam * compare two secindex structure exactly.
4083105197Ssam * IN:
4084105197Ssam *	spidx0: source, it is often in SPD.
4085105197Ssam *	spidx1: object, it is often from PFKEY message.
4086105197Ssam * OUT:
4087105197Ssam *	1 : equal
4088105197Ssam *	0 : not equal
4089105197Ssam */
4090105197Ssamstatic int
4091105197Ssamkey_cmpspidx_exactly(
4092105197Ssam	struct secpolicyindex *spidx0,
4093105197Ssam	struct secpolicyindex *spidx1)
4094105197Ssam{
4095105197Ssam	/* sanity */
4096105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
4097105197Ssam		return 1;
4098105197Ssam
4099105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
4100105197Ssam		return 0;
4101105197Ssam
4102105197Ssam	if (spidx0->prefs != spidx1->prefs
4103105197Ssam	 || spidx0->prefd != spidx1->prefd
4104105197Ssam	 || spidx0->ul_proto != spidx1->ul_proto)
4105105197Ssam		return 0;
4106105197Ssam
4107105197Ssam	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4108105197Ssam	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4109105197Ssam}
4110105197Ssam
4111105197Ssam/*
4112105197Ssam * compare two secindex structure with mask.
4113105197Ssam * IN:
4114105197Ssam *	spidx0: source, it is often in SPD.
4115105197Ssam *	spidx1: object, it is often from IP header.
4116105197Ssam * OUT:
4117105197Ssam *	1 : equal
4118105197Ssam *	0 : not equal
4119105197Ssam */
4120105197Ssamstatic int
4121105197Ssamkey_cmpspidx_withmask(
4122105197Ssam	struct secpolicyindex *spidx0,
4123105197Ssam	struct secpolicyindex *spidx1)
4124105197Ssam{
4125105197Ssam	/* sanity */
4126105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
4127105197Ssam		return 1;
4128105197Ssam
4129105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
4130105197Ssam		return 0;
4131105197Ssam
4132105197Ssam	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4133105197Ssam	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4134105197Ssam	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4135105197Ssam	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4136105197Ssam		return 0;
4137105197Ssam
4138105197Ssam	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4139105197Ssam	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4140105197Ssam	 && spidx0->ul_proto != spidx1->ul_proto)
4141105197Ssam		return 0;
4142105197Ssam
4143105197Ssam	switch (spidx0->src.sa.sa_family) {
4144105197Ssam	case AF_INET:
4145105197Ssam		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4146105197Ssam		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4147105197Ssam			return 0;
4148105197Ssam		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4149105197Ssam		    &spidx1->src.sin.sin_addr, spidx0->prefs))
4150105197Ssam			return 0;
4151105197Ssam		break;
4152105197Ssam	case AF_INET6:
4153105197Ssam		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4154105197Ssam		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4155105197Ssam			return 0;
4156105197Ssam		/*
4157105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
4158105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
4159105197Ssam		 */
4160105197Ssam		if (spidx0->src.sin6.sin6_scope_id &&
4161105197Ssam		    spidx1->src.sin6.sin6_scope_id &&
4162105197Ssam		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4163105197Ssam			return 0;
4164105197Ssam		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4165105197Ssam		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4166105197Ssam			return 0;
4167105197Ssam		break;
4168105197Ssam	default:
4169105197Ssam		/* XXX */
4170105197Ssam		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4171105197Ssam			return 0;
4172105197Ssam		break;
4173105197Ssam	}
4174105197Ssam
4175105197Ssam	switch (spidx0->dst.sa.sa_family) {
4176105197Ssam	case AF_INET:
4177105197Ssam		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4178105197Ssam		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4179105197Ssam			return 0;
4180105197Ssam		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4181105197Ssam		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
4182105197Ssam			return 0;
4183105197Ssam		break;
4184105197Ssam	case AF_INET6:
4185105197Ssam		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4186105197Ssam		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4187105197Ssam			return 0;
4188105197Ssam		/*
4189105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
4190105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
4191105197Ssam		 */
4192130928Sbms		if (spidx0->dst.sin6.sin6_scope_id &&
4193130928Sbms		    spidx1->dst.sin6.sin6_scope_id &&
4194105197Ssam		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4195105197Ssam			return 0;
4196105197Ssam		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4197105197Ssam		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4198105197Ssam			return 0;
4199105197Ssam		break;
4200105197Ssam	default:
4201105197Ssam		/* XXX */
4202105197Ssam		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4203105197Ssam			return 0;
4204105197Ssam		break;
4205105197Ssam	}
4206105197Ssam
4207105197Ssam	/* XXX Do we check other field ?  e.g. flowinfo */
4208105197Ssam
4209105197Ssam	return 1;
4210105197Ssam}
4211105197Ssam
4212105197Ssam/* returns 0 on match */
4213105197Ssamstatic int
4214105197Ssamkey_sockaddrcmp(
4215105197Ssam	const struct sockaddr *sa1,
4216105197Ssam	const struct sockaddr *sa2,
4217105197Ssam	int port)
4218105197Ssam{
4219105197Ssam#ifdef satosin
4220105197Ssam#undef satosin
4221105197Ssam#endif
4222105197Ssam#define satosin(s) ((const struct sockaddr_in *)s)
4223105197Ssam#ifdef satosin6
4224105197Ssam#undef satosin6
4225105197Ssam#endif
4226105197Ssam#define satosin6(s) ((const struct sockaddr_in6 *)s)
4227105197Ssam	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4228105197Ssam		return 1;
4229105197Ssam
4230105197Ssam	switch (sa1->sa_family) {
4231105197Ssam	case AF_INET:
4232105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in))
4233105197Ssam			return 1;
4234105197Ssam		if (satosin(sa1)->sin_addr.s_addr !=
4235105197Ssam		    satosin(sa2)->sin_addr.s_addr) {
4236105197Ssam			return 1;
4237105197Ssam		}
4238105197Ssam		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4239105197Ssam			return 1;
4240105197Ssam		break;
4241105197Ssam	case AF_INET6:
4242105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4243105197Ssam			return 1;	/*EINVAL*/
4244105197Ssam		if (satosin6(sa1)->sin6_scope_id !=
4245105197Ssam		    satosin6(sa2)->sin6_scope_id) {
4246105197Ssam			return 1;
4247105197Ssam		}
4248105197Ssam		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4249105197Ssam		    &satosin6(sa2)->sin6_addr)) {
4250105197Ssam			return 1;
4251105197Ssam		}
4252105197Ssam		if (port &&
4253105197Ssam		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4254105197Ssam			return 1;
4255105197Ssam		}
4256170120Sbz		break;
4257105197Ssam	default:
4258105197Ssam		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4259105197Ssam			return 1;
4260105197Ssam		break;
4261105197Ssam	}
4262105197Ssam
4263105197Ssam	return 0;
4264105197Ssam#undef satosin
4265105197Ssam#undef satosin6
4266105197Ssam}
4267105197Ssam
4268105197Ssam/*
4269105197Ssam * compare two buffers with mask.
4270105197Ssam * IN:
4271105197Ssam *	addr1: source
4272105197Ssam *	addr2: object
4273105197Ssam *	bits:  Number of bits to compare
4274105197Ssam * OUT:
4275105197Ssam *	1 : equal
4276105197Ssam *	0 : not equal
4277105197Ssam */
4278105197Ssamstatic int
4279105197Ssamkey_bbcmp(const void *a1, const void *a2, u_int bits)
4280105197Ssam{
4281105197Ssam	const unsigned char *p1 = a1;
4282105197Ssam	const unsigned char *p2 = a2;
4283105197Ssam
4284105197Ssam	/* XXX: This could be considerably faster if we compare a word
4285105197Ssam	 * at a time, but it is complicated on LSB Endian machines */
4286105197Ssam
4287105197Ssam	/* Handle null pointers */
4288105197Ssam	if (p1 == NULL || p2 == NULL)
4289105197Ssam		return (p1 == p2);
4290105197Ssam
4291105197Ssam	while (bits >= 8) {
4292105197Ssam		if (*p1++ != *p2++)
4293105197Ssam			return 0;
4294105197Ssam		bits -= 8;
4295105197Ssam	}
4296105197Ssam
4297105197Ssam	if (bits > 0) {
4298105197Ssam		u_int8_t mask = ~((1<<(8-bits))-1);
4299105197Ssam		if ((*p1 & mask) != (*p2 & mask))
4300105197Ssam			return 0;
4301105197Ssam	}
4302105197Ssam	return 1;	/* Match! */
4303105197Ssam}
4304105197Ssam
4305119643Ssamstatic void
4306119643Ssamkey_flush_spd(time_t now)
4307105197Ssam{
4308120585Ssam	static u_int16_t sptree_scangen = 0;
4309120585Ssam	u_int16_t gen = sptree_scangen++;
4310120585Ssam	struct secpolicy *sp;
4311105197Ssam	u_int dir;
4312105197Ssam
4313105197Ssam	/* SPD */
4314105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4315120585Ssamrestart:
4316120585Ssam		SPTREE_LOCK();
4317181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
4318120585Ssam			if (sp->scangen == gen)		/* previously handled */
4319120585Ssam				continue;
4320120585Ssam			sp->scangen = gen;
4321192880Svanhu			if (sp->state == IPSEC_SPSTATE_DEAD &&
4322192880Svanhu			    sp->refcnt == 1) {
4323192880Svanhu				/*
4324192880Svanhu				 * Ensure that we only decrease refcnt once,
4325192880Svanhu				 * when we're the last consumer.
4326192880Svanhu				 * Directly call SP_DELREF/key_delsp instead
4327192880Svanhu				 * of KEY_FREESP to avoid unlocking/relocking
4328192880Svanhu				 * SPTREE_LOCK before key_delsp: may refcnt
4329192880Svanhu				 * be increased again during that time ?
4330192880Svanhu				 * NB: also clean entries created by
4331192880Svanhu				 * key_spdflush
4332192880Svanhu				 */
4333192880Svanhu				SP_DELREF(sp);
4334192880Svanhu				key_delsp(sp);
4335120585Ssam				SPTREE_UNLOCK();
4336120585Ssam				goto restart;
4337105197Ssam			}
4338105197Ssam			if (sp->lifetime == 0 && sp->validtime == 0)
4339105197Ssam				continue;
4340105197Ssam			if ((sp->lifetime && now - sp->created > sp->lifetime)
4341105197Ssam			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4342105197Ssam				sp->state = IPSEC_SPSTATE_DEAD;
4343120585Ssam				SPTREE_UNLOCK();
4344105197Ssam				key_spdexpire(sp);
4345120585Ssam				goto restart;
4346105197Ssam			}
4347105197Ssam		}
4348120585Ssam		SPTREE_UNLOCK();
4349105197Ssam	}
4350119643Ssam}
4351105197Ssam
4352119643Ssamstatic void
4353119643Ssamkey_flush_sad(time_t now)
4354119643Ssam{
4355105197Ssam	struct secashead *sah, *nextsah;
4356105197Ssam	struct secasvar *sav, *nextsav;
4357105197Ssam
4358119643Ssam	/* SAD */
4359120585Ssam	SAHTREE_LOCK();
4360181803Sbz	LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4361105197Ssam		/* if sah has been dead, then delete it and process next sah. */
4362105197Ssam		if (sah->state == SADB_SASTATE_DEAD) {
4363105197Ssam			key_delsah(sah);
4364105197Ssam			continue;
4365105197Ssam		}
4366105197Ssam
4367105197Ssam		/* if LARVAL entry doesn't become MATURE, delete it. */
4368120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4369190071Svanhu			/* Need to also check refcnt for a larval SA ??? */
4370181803Sbz			if (now - sav->created > V_key_larval_lifetime)
4371105197Ssam				KEY_FREESAV(&sav);
4372105197Ssam		}
4373105197Ssam
4374105197Ssam		/*
4375105197Ssam		 * check MATURE entry to start to send expire message
4376105197Ssam		 * whether or not.
4377105197Ssam		 */
4378120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4379105197Ssam			/* we don't need to check. */
4380105197Ssam			if (sav->lft_s == NULL)
4381105197Ssam				continue;
4382105197Ssam
4383105197Ssam			/* sanity check */
4384105197Ssam			if (sav->lft_c == NULL) {
4385120585Ssam				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4386120585Ssam					"time, why?\n", __func__));
4387105197Ssam				continue;
4388105197Ssam			}
4389105197Ssam
4390105197Ssam			/* check SOFT lifetime */
4391157123Sgnn			if (sav->lft_s->addtime != 0 &&
4392157123Sgnn			    now - sav->created > sav->lft_s->addtime) {
4393189406Svanhu				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4394190075Svanhu				/*
4395190323Svanhu				 * Actually, only send expire message if
4396190323Svanhu				 * SA has been used, as it was done before,
4397190323Svanhu				 * but should we always send such message,
4398190323Svanhu				 * and let IKE daemon decide if it should be
4399190323Svanhu				 * renegotiated or not ?
4400190323Svanhu				 * XXX expire message will actually NOT be
4401190323Svanhu				 * sent if SA is only used after soft
4402190323Svanhu				 * lifetime has been reached, see below
4403190323Svanhu				 * (DYING state)
4404105197Ssam				 */
4405189406Svanhu				if (sav->lft_c->usetime != 0)
4406105197Ssam					key_expire(sav);
4407105197Ssam			}
4408105197Ssam			/* check SOFT lifetime by bytes */
4409105197Ssam			/*
4410105197Ssam			 * XXX I don't know the way to delete this SA
4411105197Ssam			 * when new SA is installed.  Caution when it's
4412105197Ssam			 * installed too big lifetime by time.
4413105197Ssam			 */
4414157123Sgnn			else if (sav->lft_s->bytes != 0 &&
4415157123Sgnn			    sav->lft_s->bytes < sav->lft_c->bytes) {
4416105197Ssam
4417105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4418105197Ssam				/*
4419105197Ssam				 * XXX If we keep to send expire
4420105197Ssam				 * message in the status of
4421105197Ssam				 * DYING. Do remove below code.
4422105197Ssam				 */
4423105197Ssam				key_expire(sav);
4424105197Ssam			}
4425105197Ssam		}
4426105197Ssam
4427105197Ssam		/* check DYING entry to change status to DEAD. */
4428120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4429105197Ssam			/* we don't need to check. */
4430105197Ssam			if (sav->lft_h == NULL)
4431105197Ssam				continue;
4432105197Ssam
4433105197Ssam			/* sanity check */
4434105197Ssam			if (sav->lft_c == NULL) {
4435120585Ssam				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4436120585Ssam					"time, why?\n", __func__));
4437105197Ssam				continue;
4438105197Ssam			}
4439105197Ssam
4440157123Sgnn			if (sav->lft_h->addtime != 0 &&
4441157123Sgnn			    now - sav->created > sav->lft_h->addtime) {
4442105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4443105197Ssam				KEY_FREESAV(&sav);
4444105197Ssam			}
4445105197Ssam#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4446105197Ssam			else if (sav->lft_s != NULL
4447157123Sgnn			      && sav->lft_s->addtime != 0
4448157123Sgnn			      && now - sav->created > sav->lft_s->addtime) {
4449105197Ssam				/*
4450105197Ssam				 * XXX: should be checked to be
4451105197Ssam				 * installed the valid SA.
4452105197Ssam				 */
4453105197Ssam
4454105197Ssam				/*
4455105197Ssam				 * If there is no SA then sending
4456105197Ssam				 * expire message.
4457105197Ssam				 */
4458105197Ssam				key_expire(sav);
4459105197Ssam			}
4460105197Ssam#endif
4461105197Ssam			/* check HARD lifetime by bytes */
4462157123Sgnn			else if (sav->lft_h->bytes != 0 &&
4463157123Sgnn			    sav->lft_h->bytes < sav->lft_c->bytes) {
4464105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4465105197Ssam				KEY_FREESAV(&sav);
4466105197Ssam			}
4467105197Ssam		}
4468105197Ssam
4469105197Ssam		/* delete entry in DEAD */
4470120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4471105197Ssam			/* sanity check */
4472105197Ssam			if (sav->state != SADB_SASTATE_DEAD) {
4473120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4474120585Ssam					"(queue: %d SA: %d): kill it anyway\n",
4475120585Ssam					__func__,
4476105197Ssam					SADB_SASTATE_DEAD, sav->state));
4477105197Ssam			}
4478105197Ssam			/*
4479105197Ssam			 * do not call key_freesav() here.
4480105197Ssam			 * sav should already be freed, and sav->refcnt
4481105197Ssam			 * shows other references to sav
4482105197Ssam			 * (such as from SPD).
4483105197Ssam			 */
4484105197Ssam		}
4485105197Ssam	}
4486120585Ssam	SAHTREE_UNLOCK();
4487119643Ssam}
4488105197Ssam
4489119643Ssamstatic void
4490119643Ssamkey_flush_acq(time_t now)
4491119643Ssam{
4492105197Ssam	struct secacq *acq, *nextacq;
4493105197Ssam
4494119643Ssam	/* ACQ tree */
4495120585Ssam	ACQ_LOCK();
4496181803Sbz	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4497105197Ssam		nextacq = LIST_NEXT(acq, chain);
4498181803Sbz		if (now - acq->created > V_key_blockacq_lifetime
4499105197Ssam		 && __LIST_CHAINED(acq)) {
4500105197Ssam			LIST_REMOVE(acq, chain);
4501119643Ssam			free(acq, M_IPSEC_SAQ);
4502105197Ssam		}
4503105197Ssam	}
4504120585Ssam	ACQ_UNLOCK();
4505119643Ssam}
4506105197Ssam
4507119643Ssamstatic void
4508119643Ssamkey_flush_spacq(time_t now)
4509119643Ssam{
4510105197Ssam	struct secspacq *acq, *nextacq;
4511105197Ssam
4512119643Ssam	/* SP ACQ tree */
4513120585Ssam	SPACQ_LOCK();
4514181803Sbz	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4515105197Ssam		nextacq = LIST_NEXT(acq, chain);
4516181803Sbz		if (now - acq->created > V_key_blockacq_lifetime
4517105197Ssam		 && __LIST_CHAINED(acq)) {
4518105197Ssam			LIST_REMOVE(acq, chain);
4519119643Ssam			free(acq, M_IPSEC_SAQ);
4520105197Ssam		}
4521105197Ssam	}
4522120585Ssam	SPACQ_UNLOCK();
4523119643Ssam}
4524105197Ssam
4525119643Ssam/*
4526119643Ssam * time handler.
4527119643Ssam * scanning SPD and SAD to check status for each entries,
4528119643Ssam * and do to remove or to expire.
4529119643Ssam * XXX: year 2038 problem may remain.
4530119643Ssam */
4531119643Ssamvoid
4532119643Ssamkey_timehandler(void)
4533119643Ssam{
4534183550Szec	VNET_ITERATOR_DECL(vnet_iter);
4535119643Ssam	time_t now = time_second;
4536105197Ssam
4537195760Srwatson	VNET_LIST_RLOCK_NOSLEEP();
4538183550Szec	VNET_FOREACH(vnet_iter) {
4539183550Szec		CURVNET_SET(vnet_iter);
4540183550Szec		key_flush_spd(now);
4541183550Szec		key_flush_sad(now);
4542183550Szec		key_flush_acq(now);
4543183550Szec		key_flush_spacq(now);
4544183550Szec		CURVNET_RESTORE();
4545183550Szec	}
4546195760Srwatson	VNET_LIST_RUNLOCK_NOSLEEP();
4547119643Ssam
4548105197Ssam#ifndef IPSEC_DEBUG2
4549105197Ssam	/* do exchange to tick time !! */
4550105197Ssam	(void)timeout((void *)key_timehandler, (void *)0, hz);
4551105197Ssam#endif /* IPSEC_DEBUG2 */
4552105197Ssam}
4553105197Ssam
4554105197Ssamu_long
4555105197Ssamkey_random()
4556105197Ssam{
4557105197Ssam	u_long value;
4558105197Ssam
4559105197Ssam	key_randomfill(&value, sizeof(value));
4560105197Ssam	return value;
4561105197Ssam}
4562105197Ssam
4563105197Ssamvoid
4564105197Ssamkey_randomfill(p, l)
4565105197Ssam	void *p;
4566105197Ssam	size_t l;
4567105197Ssam{
4568105197Ssam	size_t n;
4569105197Ssam	u_long v;
4570105197Ssam	static int warn = 1;
4571105197Ssam
4572105197Ssam	n = 0;
4573105197Ssam	n = (size_t)read_random(p, (u_int)l);
4574105197Ssam	/* last resort */
4575105197Ssam	while (n < l) {
4576105197Ssam		v = random();
4577105197Ssam		bcopy(&v, (u_int8_t *)p + n,
4578105197Ssam		    l - n < sizeof(v) ? l - n : sizeof(v));
4579105197Ssam		n += sizeof(v);
4580105197Ssam
4581105197Ssam		if (warn) {
4582105197Ssam			printf("WARNING: pseudo-random number generator "
4583105197Ssam			    "used for IPsec processing\n");
4584105197Ssam			warn = 0;
4585105197Ssam		}
4586105197Ssam	}
4587105197Ssam}
4588105197Ssam
4589105197Ssam/*
4590105197Ssam * map SADB_SATYPE_* to IPPROTO_*.
4591105197Ssam * if satype == SADB_SATYPE then satype is mapped to ~0.
4592105197Ssam * OUT:
4593105197Ssam *	0: invalid satype.
4594105197Ssam */
4595105197Ssamstatic u_int16_t
4596189004Srdivackykey_satype2proto(u_int8_t satype)
4597105197Ssam{
4598105197Ssam	switch (satype) {
4599105197Ssam	case SADB_SATYPE_UNSPEC:
4600105197Ssam		return IPSEC_PROTO_ANY;
4601105197Ssam	case SADB_SATYPE_AH:
4602105197Ssam		return IPPROTO_AH;
4603105197Ssam	case SADB_SATYPE_ESP:
4604105197Ssam		return IPPROTO_ESP;
4605105197Ssam	case SADB_X_SATYPE_IPCOMP:
4606105197Ssam		return IPPROTO_IPCOMP;
4607125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
4608125680Sbms		return IPPROTO_TCP;
4609105197Ssam	default:
4610105197Ssam		return 0;
4611105197Ssam	}
4612105197Ssam	/* NOTREACHED */
4613105197Ssam}
4614105197Ssam
4615105197Ssam/*
4616105197Ssam * map IPPROTO_* to SADB_SATYPE_*
4617105197Ssam * OUT:
4618105197Ssam *	0: invalid protocol type.
4619105197Ssam */
4620105197Ssamstatic u_int8_t
4621189004Srdivackykey_proto2satype(u_int16_t proto)
4622105197Ssam{
4623105197Ssam	switch (proto) {
4624105197Ssam	case IPPROTO_AH:
4625105197Ssam		return SADB_SATYPE_AH;
4626105197Ssam	case IPPROTO_ESP:
4627105197Ssam		return SADB_SATYPE_ESP;
4628105197Ssam	case IPPROTO_IPCOMP:
4629105197Ssam		return SADB_X_SATYPE_IPCOMP;
4630125680Sbms	case IPPROTO_TCP:
4631125680Sbms		return SADB_X_SATYPE_TCPSIGNATURE;
4632105197Ssam	default:
4633105197Ssam		return 0;
4634105197Ssam	}
4635105197Ssam	/* NOTREACHED */
4636105197Ssam}
4637105197Ssam
4638105197Ssam/* %%% PF_KEY */
4639105197Ssam/*
4640105197Ssam * SADB_GETSPI processing is to receive
4641105197Ssam *	<base, (SA2), src address, dst address, (SPI range)>
4642105197Ssam * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4643105197Ssam * tree with the status of LARVAL, and send
4644105197Ssam *	<base, SA(*), address(SD)>
4645105197Ssam * to the IKMPd.
4646105197Ssam *
4647105197Ssam * IN:	mhp: pointer to the pointer to each header.
4648105197Ssam * OUT:	NULL if fail.
4649105197Ssam *	other if success, return pointer to the message to send.
4650105197Ssam */
4651105197Ssamstatic int
4652105197Ssamkey_getspi(so, m, mhp)
4653105197Ssam	struct socket *so;
4654105197Ssam	struct mbuf *m;
4655105197Ssam	const struct sadb_msghdr *mhp;
4656105197Ssam{
4657105197Ssam	struct sadb_address *src0, *dst0;
4658105197Ssam	struct secasindex saidx;
4659105197Ssam	struct secashead *newsah;
4660105197Ssam	struct secasvar *newsav;
4661105197Ssam	u_int8_t proto;
4662105197Ssam	u_int32_t spi;
4663105197Ssam	u_int8_t mode;
4664105197Ssam	u_int32_t reqid;
4665105197Ssam	int error;
4666105197Ssam
4667120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4668120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4669120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4670120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4671105197Ssam
4672105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4673105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4674120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4675120585Ssam			__func__));
4676105197Ssam		return key_senderror(so, m, EINVAL);
4677105197Ssam	}
4678105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4679105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4680120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4681120585Ssam			__func__));
4682105197Ssam		return key_senderror(so, m, EINVAL);
4683105197Ssam	}
4684105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4685105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4686105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4687105197Ssam	} else {
4688105197Ssam		mode = IPSEC_MODE_ANY;
4689105197Ssam		reqid = 0;
4690105197Ssam	}
4691105197Ssam
4692105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4693105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4694105197Ssam
4695105197Ssam	/* map satype to proto */
4696105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4697120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4698120585Ssam			__func__));
4699105197Ssam		return key_senderror(so, m, EINVAL);
4700105197Ssam	}
4701105197Ssam
4702194062Svanhu	/*
4703194062Svanhu	 * Make sure the port numbers are zero.
4704194062Svanhu	 * In case of NAT-T we will update them later if needed.
4705194062Svanhu	 */
4706105197Ssam	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4707105197Ssam	case AF_INET:
4708105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4709105197Ssam		    sizeof(struct sockaddr_in))
4710105197Ssam			return key_senderror(so, m, EINVAL);
4711105197Ssam		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4712105197Ssam		break;
4713105197Ssam	case AF_INET6:
4714105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4715105197Ssam		    sizeof(struct sockaddr_in6))
4716105197Ssam			return key_senderror(so, m, EINVAL);
4717105197Ssam		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4718105197Ssam		break;
4719105197Ssam	default:
4720105197Ssam		; /*???*/
4721105197Ssam	}
4722105197Ssam	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4723105197Ssam	case AF_INET:
4724105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4725105197Ssam		    sizeof(struct sockaddr_in))
4726105197Ssam			return key_senderror(so, m, EINVAL);
4727105197Ssam		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4728105197Ssam		break;
4729105197Ssam	case AF_INET6:
4730105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4731105197Ssam		    sizeof(struct sockaddr_in6))
4732105197Ssam			return key_senderror(so, m, EINVAL);
4733105197Ssam		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4734105197Ssam		break;
4735105197Ssam	default:
4736105197Ssam		; /*???*/
4737105197Ssam	}
4738105197Ssam
4739105197Ssam	/* XXX boundary check against sa_len */
4740105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4741105197Ssam
4742194062Svanhu#ifdef IPSEC_NAT_T
4743194062Svanhu	/*
4744194062Svanhu	 * Handle NAT-T info if present.
4745194062Svanhu	 * We made sure the port numbers are zero above, so we do
4746194062Svanhu	 * not have to worry in case we do not update them.
4747194062Svanhu	 */
4748194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4749194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4750194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4751194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4752194062Svanhu
4753194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4754194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4755194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4756194062Svanhu		struct sadb_x_nat_t_type *type;
4757194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
4758194062Svanhu
4759194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4760194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4761194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4762194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4763194062Svanhu			    "passed.\n", __func__));
4764194062Svanhu			return key_senderror(so, m, EINVAL);
4765194062Svanhu		}
4766194062Svanhu
4767194062Svanhu		sport = (struct sadb_x_nat_t_port *)
4768194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4769194062Svanhu		dport = (struct sadb_x_nat_t_port *)
4770194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4771194062Svanhu
4772194062Svanhu		if (sport)
4773194062Svanhu			KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4774194062Svanhu		if (dport)
4775194062Svanhu			KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4776194062Svanhu	}
4777194062Svanhu#endif
4778194062Svanhu
4779105197Ssam	/* SPI allocation */
4780105197Ssam	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4781105197Ssam	                       &saidx);
4782105197Ssam	if (spi == 0)
4783105197Ssam		return key_senderror(so, m, EINVAL);
4784105197Ssam
4785105197Ssam	/* get a SA index */
4786105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4787105197Ssam		/* create a new SA index */
4788105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4789120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4790105197Ssam			return key_senderror(so, m, ENOBUFS);
4791105197Ssam		}
4792105197Ssam	}
4793105197Ssam
4794105197Ssam	/* get a new SA */
4795105197Ssam	/* XXX rewrite */
4796105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4797105197Ssam	if (newsav == NULL) {
4798105197Ssam		/* XXX don't free new SA index allocated in above. */
4799105197Ssam		return key_senderror(so, m, error);
4800105197Ssam	}
4801105197Ssam
4802105197Ssam	/* set spi */
4803105197Ssam	newsav->spi = htonl(spi);
4804105197Ssam
4805105197Ssam	/* delete the entry in acqtree */
4806105197Ssam	if (mhp->msg->sadb_msg_seq != 0) {
4807105197Ssam		struct secacq *acq;
4808105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4809105197Ssam			/* reset counter in order to deletion by timehandler. */
4810105197Ssam			acq->created = time_second;
4811105197Ssam			acq->count = 0;
4812105197Ssam		}
4813105197Ssam    	}
4814105197Ssam
4815105197Ssam    {
4816105197Ssam	struct mbuf *n, *nn;
4817105197Ssam	struct sadb_sa *m_sa;
4818105197Ssam	struct sadb_msg *newmsg;
4819105197Ssam	int off, len;
4820105197Ssam
4821105197Ssam	/* create new sadb_msg to reply. */
4822105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4823105197Ssam	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4824105197Ssam
4825111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
4826105197Ssam	if (len > MHLEN) {
4827111119Simp		MCLGET(n, M_DONTWAIT);
4828105197Ssam		if ((n->m_flags & M_EXT) == 0) {
4829105197Ssam			m_freem(n);
4830105197Ssam			n = NULL;
4831105197Ssam		}
4832105197Ssam	}
4833105197Ssam	if (!n)
4834105197Ssam		return key_senderror(so, m, ENOBUFS);
4835105197Ssam
4836105197Ssam	n->m_len = len;
4837105197Ssam	n->m_next = NULL;
4838105197Ssam	off = 0;
4839105197Ssam
4840105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4841105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4842105197Ssam
4843105197Ssam	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4844105197Ssam	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4845105197Ssam	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4846105197Ssam	m_sa->sadb_sa_spi = htonl(spi);
4847105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4848105197Ssam
4849120585Ssam	IPSEC_ASSERT(off == len,
4850120585Ssam		("length inconsistency (off %u len %u)", off, len));
4851105197Ssam
4852105197Ssam	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4853105197Ssam	    SADB_EXT_ADDRESS_DST);
4854105197Ssam	if (!n->m_next) {
4855105197Ssam		m_freem(n);
4856105197Ssam		return key_senderror(so, m, ENOBUFS);
4857105197Ssam	}
4858105197Ssam
4859105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
4860105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
4861105197Ssam		if (n == NULL)
4862105197Ssam			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4863105197Ssam	}
4864105197Ssam
4865105197Ssam	n->m_pkthdr.len = 0;
4866105197Ssam	for (nn = n; nn; nn = nn->m_next)
4867105197Ssam		n->m_pkthdr.len += nn->m_len;
4868105197Ssam
4869105197Ssam	newmsg = mtod(n, struct sadb_msg *);
4870105197Ssam	newmsg->sadb_msg_seq = newsav->seq;
4871105197Ssam	newmsg->sadb_msg_errno = 0;
4872105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4873105197Ssam
4874105197Ssam	m_freem(m);
4875105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4876105197Ssam    }
4877105197Ssam}
4878105197Ssam
4879105197Ssam/*
4880105197Ssam * allocating new SPI
4881105197Ssam * called by key_getspi().
4882105197Ssam * OUT:
4883105197Ssam *	0:	failure.
4884105197Ssam *	others: success.
4885105197Ssam */
4886105197Ssamstatic u_int32_t
4887105197Ssamkey_do_getnewspi(spirange, saidx)
4888105197Ssam	struct sadb_spirange *spirange;
4889105197Ssam	struct secasindex *saidx;
4890105197Ssam{
4891105197Ssam	u_int32_t newspi;
4892105197Ssam	u_int32_t min, max;
4893181803Sbz	int count = V_key_spi_trycnt;
4894105197Ssam
4895105197Ssam	/* set spi range to allocate */
4896105197Ssam	if (spirange != NULL) {
4897105197Ssam		min = spirange->sadb_spirange_min;
4898105197Ssam		max = spirange->sadb_spirange_max;
4899105197Ssam	} else {
4900181803Sbz		min = V_key_spi_minval;
4901181803Sbz		max = V_key_spi_maxval;
4902105197Ssam	}
4903105197Ssam	/* IPCOMP needs 2-byte SPI */
4904105197Ssam	if (saidx->proto == IPPROTO_IPCOMP) {
4905105197Ssam		u_int32_t t;
4906105197Ssam		if (min >= 0x10000)
4907105197Ssam			min = 0xffff;
4908105197Ssam		if (max >= 0x10000)
4909105197Ssam			max = 0xffff;
4910105197Ssam		if (min > max) {
4911105197Ssam			t = min; min = max; max = t;
4912105197Ssam		}
4913105197Ssam	}
4914105197Ssam
4915105197Ssam	if (min == max) {
4916105197Ssam		if (key_checkspidup(saidx, min) != NULL) {
4917120585Ssam			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4918120585Ssam				__func__, min));
4919105197Ssam			return 0;
4920105197Ssam		}
4921105197Ssam
4922105197Ssam		count--; /* taking one cost. */
4923105197Ssam		newspi = min;
4924105197Ssam
4925105197Ssam	} else {
4926105197Ssam
4927105197Ssam		/* init SPI */
4928105197Ssam		newspi = 0;
4929105197Ssam
4930105197Ssam		/* when requesting to allocate spi ranged */
4931105197Ssam		while (count--) {
4932105197Ssam			/* generate pseudo-random SPI value ranged. */
4933105197Ssam			newspi = min + (key_random() % (max - min + 1));
4934105197Ssam
4935105197Ssam			if (key_checkspidup(saidx, newspi) == NULL)
4936105197Ssam				break;
4937105197Ssam		}
4938105197Ssam
4939105197Ssam		if (count == 0 || newspi == 0) {
4940120585Ssam			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4941120585Ssam				__func__));
4942105197Ssam			return 0;
4943105197Ssam		}
4944105197Ssam	}
4945105197Ssam
4946105197Ssam	/* statistics */
4947105197Ssam	keystat.getspi_count =
4948181803Sbz		(keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4949105197Ssam
4950105197Ssam	return newspi;
4951105197Ssam}
4952105197Ssam
4953105197Ssam/*
4954105197Ssam * SADB_UPDATE processing
4955105197Ssam * receive
4956105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4957105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4958105197Ssam * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4959105197Ssam * and send
4960105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4961105197Ssam *       (identity(SD),) (sensitivity)>
4962105197Ssam * to the ikmpd.
4963105197Ssam *
4964105197Ssam * m will always be freed.
4965105197Ssam */
4966105197Ssamstatic int
4967105197Ssamkey_update(so, m, mhp)
4968105197Ssam	struct socket *so;
4969105197Ssam	struct mbuf *m;
4970105197Ssam	const struct sadb_msghdr *mhp;
4971105197Ssam{
4972105197Ssam	struct sadb_sa *sa0;
4973105197Ssam	struct sadb_address *src0, *dst0;
4974194062Svanhu#ifdef IPSEC_NAT_T
4975194062Svanhu	struct sadb_x_nat_t_type *type;
4976194513Sbz	struct sadb_x_nat_t_port *sport, *dport;
4977194062Svanhu	struct sadb_address *iaddr, *raddr;
4978194062Svanhu	struct sadb_x_nat_t_frag *frag;
4979194062Svanhu#endif
4980105197Ssam	struct secasindex saidx;
4981105197Ssam	struct secashead *sah;
4982105197Ssam	struct secasvar *sav;
4983105197Ssam	u_int16_t proto;
4984105197Ssam	u_int8_t mode;
4985105197Ssam	u_int32_t reqid;
4986105197Ssam	int error;
4987105197Ssam
4988120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4989120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4990120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4991120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4992105197Ssam
4993105197Ssam	/* map satype to proto */
4994105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4995120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4996120585Ssam			__func__));
4997105197Ssam		return key_senderror(so, m, EINVAL);
4998105197Ssam	}
4999105197Ssam
5000105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5001105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5002105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5003105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5004105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5005105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5006105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5007105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5008105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5009105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5010105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5011120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5012120585Ssam			__func__));
5013105197Ssam		return key_senderror(so, m, EINVAL);
5014105197Ssam	}
5015105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5016105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5017105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5018120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5019120585Ssam			__func__));
5020105197Ssam		return key_senderror(so, m, EINVAL);
5021105197Ssam	}
5022105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5023105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5024105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5025105197Ssam	} else {
5026105197Ssam		mode = IPSEC_MODE_ANY;
5027105197Ssam		reqid = 0;
5028105197Ssam	}
5029105197Ssam	/* XXX boundary checking for other extensions */
5030105197Ssam
5031105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5032105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5033105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5034105197Ssam
5035105197Ssam	/* XXX boundary check against sa_len */
5036105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5037105197Ssam
5038194062Svanhu	/*
5039194062Svanhu	 * Make sure the port numbers are zero.
5040194062Svanhu	 * In case of NAT-T we will update them later if needed.
5041194062Svanhu	 */
5042194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5043194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5044194062Svanhu
5045194062Svanhu#ifdef IPSEC_NAT_T
5046194062Svanhu	/*
5047194062Svanhu	 * Handle NAT-T info if present.
5048194062Svanhu	 */
5049194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5050194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5051194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5052194062Svanhu
5053194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5054194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5055194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5056194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5057194062Svanhu			    __func__));
5058194062Svanhu			return key_senderror(so, m, EINVAL);
5059194062Svanhu		}
5060194062Svanhu
5061194062Svanhu		type = (struct sadb_x_nat_t_type *)
5062194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5063194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5064194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5065194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5066194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5067194062Svanhu	} else {
5068194062Svanhu		type = 0;
5069194513Sbz		sport = dport = 0;
5070194062Svanhu	}
5071194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5072194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5073194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5074194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5075194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5076194062Svanhu			    __func__));
5077194062Svanhu			return key_senderror(so, m, EINVAL);
5078194062Svanhu		}
5079194062Svanhu		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5080194062Svanhu		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5081194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5082194062Svanhu	} else {
5083194062Svanhu		iaddr = raddr = NULL;
5084194062Svanhu	}
5085194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5086194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5087194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5088194062Svanhu			    __func__));
5089194062Svanhu			return key_senderror(so, m, EINVAL);
5090194062Svanhu		}
5091194062Svanhu		frag = (struct sadb_x_nat_t_frag *)
5092194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5093194062Svanhu	} else {
5094194062Svanhu		frag = 0;
5095194062Svanhu	}
5096194062Svanhu#endif
5097194062Svanhu
5098105197Ssam	/* get a SA header */
5099105197Ssam	if ((sah = key_getsah(&saidx)) == NULL) {
5100120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
5101105197Ssam		return key_senderror(so, m, ENOENT);
5102105197Ssam	}
5103105197Ssam
5104105197Ssam	/* set spidx if there */
5105105197Ssam	/* XXX rewrite */
5106105197Ssam	error = key_setident(sah, m, mhp);
5107105197Ssam	if (error)
5108105197Ssam		return key_senderror(so, m, error);
5109105197Ssam
5110105197Ssam	/* find a SA with sequence number. */
5111105197Ssam#ifdef IPSEC_DOSEQCHECK
5112105197Ssam	if (mhp->msg->sadb_msg_seq != 0
5113105197Ssam	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
5114120585Ssam		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
5115120585Ssam			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
5116105197Ssam		return key_senderror(so, m, ENOENT);
5117105197Ssam	}
5118105197Ssam#else
5119120585Ssam	SAHTREE_LOCK();
5120120585Ssam	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5121120585Ssam	SAHTREE_UNLOCK();
5122120585Ssam	if (sav == NULL) {
5123120585Ssam		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
5124120585Ssam			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5125105197Ssam		return key_senderror(so, m, EINVAL);
5126105197Ssam	}
5127105197Ssam#endif
5128105197Ssam
5129105197Ssam	/* validity check */
5130105197Ssam	if (sav->sah->saidx.proto != proto) {
5131120585Ssam		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
5132120585Ssam			"(DB=%u param=%u)\n", __func__,
5133120585Ssam			sav->sah->saidx.proto, proto));
5134105197Ssam		return key_senderror(so, m, EINVAL);
5135105197Ssam	}
5136105197Ssam#ifdef IPSEC_DOSEQCHECK
5137105197Ssam	if (sav->spi != sa0->sadb_sa_spi) {
5138120585Ssam		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
5139120585Ssam		    __func__,
5140105197Ssam		    (u_int32_t)ntohl(sav->spi),
5141105197Ssam		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5142105197Ssam		return key_senderror(so, m, EINVAL);
5143105197Ssam	}
5144105197Ssam#endif
5145105197Ssam	if (sav->pid != mhp->msg->sadb_msg_pid) {
5146120585Ssam		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
5147120585Ssam		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
5148105197Ssam		return key_senderror(so, m, EINVAL);
5149105197Ssam	}
5150105197Ssam
5151105197Ssam	/* copy sav values */
5152105197Ssam	error = key_setsaval(sav, m, mhp);
5153105197Ssam	if (error) {
5154105197Ssam		KEY_FREESAV(&sav);
5155105197Ssam		return key_senderror(so, m, error);
5156105197Ssam	}
5157105197Ssam
5158105197Ssam	/* check SA values to be mature. */
5159105197Ssam	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5160105197Ssam		KEY_FREESAV(&sav);
5161105197Ssam		return key_senderror(so, m, 0);
5162105197Ssam	}
5163105197Ssam
5164194062Svanhu#ifdef IPSEC_NAT_T
5165194062Svanhu	/*
5166194062Svanhu	 * Handle more NAT-T info if present,
5167194062Svanhu	 * now that we have a sav to fill.
5168194062Svanhu	 */
5169194062Svanhu	if (type)
5170194062Svanhu		sav->natt_type = type->sadb_x_nat_t_type_type;
5171194062Svanhu
5172194513Sbz	if (sport)
5173194513Sbz		KEY_PORTTOSADDR(&sav->sah->saidx.src,
5174194513Sbz		    sport->sadb_x_nat_t_port_port);
5175194513Sbz	if (dport)
5176194513Sbz		KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5177194513Sbz		    dport->sadb_x_nat_t_port_port);
5178194513Sbz
5179194062Svanhu#if 0
5180194062Svanhu	/*
5181194062Svanhu	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5182194062Svanhu	 * We should actually check for a minimum MTU here, if we
5183194062Svanhu	 * want to support it in ip_output.
5184194062Svanhu	 */
5185194062Svanhu	if (frag)
5186194062Svanhu		sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5187194062Svanhu#endif
5188194062Svanhu#endif
5189194062Svanhu
5190105197Ssam    {
5191105197Ssam	struct mbuf *n;
5192105197Ssam
5193105197Ssam	/* set msg buf from mhp */
5194105197Ssam	n = key_getmsgbuf_x1(m, mhp);
5195105197Ssam	if (n == NULL) {
5196120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5197105197Ssam		return key_senderror(so, m, ENOBUFS);
5198105197Ssam	}
5199105197Ssam
5200105197Ssam	m_freem(m);
5201105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5202105197Ssam    }
5203105197Ssam}
5204105197Ssam
5205105197Ssam/*
5206105197Ssam * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5207105197Ssam * only called by key_update().
5208105197Ssam * OUT:
5209105197Ssam *	NULL	: not found
5210105197Ssam *	others	: found, pointer to a SA.
5211105197Ssam */
5212105197Ssam#ifdef IPSEC_DOSEQCHECK
5213105197Ssamstatic struct secasvar *
5214105197Ssamkey_getsavbyseq(sah, seq)
5215105197Ssam	struct secashead *sah;
5216105197Ssam	u_int32_t seq;
5217105197Ssam{
5218105197Ssam	struct secasvar *sav;
5219105197Ssam	u_int state;
5220105197Ssam
5221105197Ssam	state = SADB_SASTATE_LARVAL;
5222105197Ssam
5223105197Ssam	/* search SAD with sequence number ? */
5224105197Ssam	LIST_FOREACH(sav, &sah->savtree[state], chain) {
5225105197Ssam
5226120585Ssam		KEY_CHKSASTATE(state, sav->state, __func__);
5227105197Ssam
5228105197Ssam		if (sav->seq == seq) {
5229158767Spjd			sa_addref(sav);
5230105197Ssam			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5231120585Ssam				printf("DP %s cause refcnt++:%d SA:%p\n",
5232120585Ssam					__func__, sav->refcnt, sav));
5233105197Ssam			return sav;
5234105197Ssam		}
5235105197Ssam	}
5236105197Ssam
5237105197Ssam	return NULL;
5238105197Ssam}
5239105197Ssam#endif
5240105197Ssam
5241105197Ssam/*
5242105197Ssam * SADB_ADD processing
5243108533Sschweikh * add an entry to SA database, when received
5244105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5245105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
5246105197Ssam * from the ikmpd,
5247105197Ssam * and send
5248105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5249105197Ssam *       (identity(SD),) (sensitivity)>
5250105197Ssam * to the ikmpd.
5251105197Ssam *
5252105197Ssam * IGNORE identity and sensitivity messages.
5253105197Ssam *
5254105197Ssam * m will always be freed.
5255105197Ssam */
5256105197Ssamstatic int
5257105197Ssamkey_add(so, m, mhp)
5258105197Ssam	struct socket *so;
5259105197Ssam	struct mbuf *m;
5260105197Ssam	const struct sadb_msghdr *mhp;
5261105197Ssam{
5262105197Ssam	struct sadb_sa *sa0;
5263105197Ssam	struct sadb_address *src0, *dst0;
5264194062Svanhu#ifdef IPSEC_NAT_T
5265194062Svanhu	struct sadb_x_nat_t_type *type;
5266194062Svanhu	struct sadb_address *iaddr, *raddr;
5267194062Svanhu	struct sadb_x_nat_t_frag *frag;
5268194062Svanhu#endif
5269105197Ssam	struct secasindex saidx;
5270105197Ssam	struct secashead *newsah;
5271105197Ssam	struct secasvar *newsav;
5272105197Ssam	u_int16_t proto;
5273105197Ssam	u_int8_t mode;
5274105197Ssam	u_int32_t reqid;
5275105197Ssam	int error;
5276105197Ssam
5277120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5278120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5279120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5280120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5281105197Ssam
5282105197Ssam	/* map satype to proto */
5283105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5284120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5285120585Ssam			__func__));
5286105197Ssam		return key_senderror(so, m, EINVAL);
5287105197Ssam	}
5288105197Ssam
5289105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5290105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5291105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5292105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5293105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5294105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5295105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5296105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5297105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5298105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5299105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5300120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5301120585Ssam			__func__));
5302105197Ssam		return key_senderror(so, m, EINVAL);
5303105197Ssam	}
5304105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5305105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5306105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5307105197Ssam		/* XXX need more */
5308120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5309120585Ssam			__func__));
5310105197Ssam		return key_senderror(so, m, EINVAL);
5311105197Ssam	}
5312105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5313105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5314105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5315105197Ssam	} else {
5316105197Ssam		mode = IPSEC_MODE_ANY;
5317105197Ssam		reqid = 0;
5318105197Ssam	}
5319105197Ssam
5320105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5321105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5322105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5323105197Ssam
5324105197Ssam	/* XXX boundary check against sa_len */
5325105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5326105197Ssam
5327194062Svanhu	/*
5328194062Svanhu	 * Make sure the port numbers are zero.
5329194062Svanhu	 * In case of NAT-T we will update them later if needed.
5330194062Svanhu	 */
5331194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5332194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5333194062Svanhu
5334194062Svanhu#ifdef IPSEC_NAT_T
5335194062Svanhu	/*
5336194062Svanhu	 * Handle NAT-T info if present.
5337194062Svanhu	 */
5338194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5339194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5340194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5341194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5342194062Svanhu
5343194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5344194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5345194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5346194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5347194062Svanhu			    __func__));
5348194062Svanhu			return key_senderror(so, m, EINVAL);
5349194062Svanhu		}
5350194062Svanhu
5351194062Svanhu		type = (struct sadb_x_nat_t_type *)
5352194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5353194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5354194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5355194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5356194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5357194062Svanhu
5358194062Svanhu		if (sport)
5359194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5360194062Svanhu			    sport->sadb_x_nat_t_port_port);
5361194062Svanhu		if (dport)
5362194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5363194062Svanhu			    dport->sadb_x_nat_t_port_port);
5364194062Svanhu	} else {
5365194062Svanhu		type = 0;
5366194062Svanhu	}
5367194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5368194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5369194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5370194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5371194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5372194062Svanhu			    __func__));
5373194062Svanhu			return key_senderror(so, m, EINVAL);
5374194062Svanhu		}
5375194062Svanhu		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5376194062Svanhu		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5377194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5378194062Svanhu	} else {
5379194062Svanhu		iaddr = raddr = NULL;
5380194062Svanhu	}
5381194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5382194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5383194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5384194062Svanhu			    __func__));
5385194062Svanhu			return key_senderror(so, m, EINVAL);
5386194062Svanhu		}
5387194062Svanhu		frag = (struct sadb_x_nat_t_frag *)
5388194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5389194062Svanhu	} else {
5390194062Svanhu		frag = 0;
5391194062Svanhu	}
5392194062Svanhu#endif
5393194062Svanhu
5394105197Ssam	/* get a SA header */
5395105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
5396105197Ssam		/* create a new SA header */
5397105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
5398120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5399105197Ssam			return key_senderror(so, m, ENOBUFS);
5400105197Ssam		}
5401105197Ssam	}
5402105197Ssam
5403105197Ssam	/* set spidx if there */
5404105197Ssam	/* XXX rewrite */
5405105197Ssam	error = key_setident(newsah, m, mhp);
5406105197Ssam	if (error) {
5407105197Ssam		return key_senderror(so, m, error);
5408105197Ssam	}
5409105197Ssam
5410105197Ssam	/* create new SA entry. */
5411105197Ssam	/* We can create new SA only if SPI is differenct. */
5412120585Ssam	SAHTREE_LOCK();
5413120585Ssam	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5414120585Ssam	SAHTREE_UNLOCK();
5415120585Ssam	if (newsav != NULL) {
5416120585Ssam		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5417105197Ssam		return key_senderror(so, m, EEXIST);
5418105197Ssam	}
5419105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5420105197Ssam	if (newsav == NULL) {
5421105197Ssam		return key_senderror(so, m, error);
5422105197Ssam	}
5423105197Ssam
5424105197Ssam	/* check SA values to be mature. */
5425105197Ssam	if ((error = key_mature(newsav)) != 0) {
5426105197Ssam		KEY_FREESAV(&newsav);
5427105197Ssam		return key_senderror(so, m, error);
5428105197Ssam	}
5429105197Ssam
5430194062Svanhu#ifdef IPSEC_NAT_T
5431105197Ssam	/*
5432194062Svanhu	 * Handle more NAT-T info if present,
5433194062Svanhu	 * now that we have a sav to fill.
5434194062Svanhu	 */
5435194062Svanhu	if (type)
5436194062Svanhu		newsav->natt_type = type->sadb_x_nat_t_type_type;
5437194062Svanhu
5438194062Svanhu#if 0
5439194062Svanhu	/*
5440194062Svanhu	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5441194062Svanhu	 * We should actually check for a minimum MTU here, if we
5442194062Svanhu	 * want to support it in ip_output.
5443194062Svanhu	 */
5444194062Svanhu	if (frag)
5445194062Svanhu		newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5446194062Svanhu#endif
5447194062Svanhu#endif
5448194062Svanhu
5449194062Svanhu	/*
5450105197Ssam	 * don't call key_freesav() here, as we would like to keep the SA
5451105197Ssam	 * in the database on success.
5452105197Ssam	 */
5453105197Ssam
5454105197Ssam    {
5455105197Ssam	struct mbuf *n;
5456105197Ssam
5457105197Ssam	/* set msg buf from mhp */
5458105197Ssam	n = key_getmsgbuf_x1(m, mhp);
5459105197Ssam	if (n == NULL) {
5460120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5461105197Ssam		return key_senderror(so, m, ENOBUFS);
5462105197Ssam	}
5463105197Ssam
5464105197Ssam	m_freem(m);
5465105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5466105197Ssam    }
5467105197Ssam}
5468105197Ssam
5469105197Ssam/* m is retained */
5470105197Ssamstatic int
5471105197Ssamkey_setident(sah, m, mhp)
5472105197Ssam	struct secashead *sah;
5473105197Ssam	struct mbuf *m;
5474105197Ssam	const struct sadb_msghdr *mhp;
5475105197Ssam{
5476105197Ssam	const struct sadb_ident *idsrc, *iddst;
5477105197Ssam	int idsrclen, iddstlen;
5478105197Ssam
5479120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5480120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5481120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5482120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5483105197Ssam
5484105197Ssam	/* don't make buffer if not there */
5485105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5486105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5487105197Ssam		sah->idents = NULL;
5488105197Ssam		sah->identd = NULL;
5489105197Ssam		return 0;
5490105197Ssam	}
5491105197Ssam
5492105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5493105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5494120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5495105197Ssam		return EINVAL;
5496105197Ssam	}
5497105197Ssam
5498105197Ssam	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5499105197Ssam	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5500105197Ssam	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5501105197Ssam	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5502105197Ssam
5503105197Ssam	/* validity check */
5504105197Ssam	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5505120585Ssam		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5506105197Ssam		return EINVAL;
5507105197Ssam	}
5508105197Ssam
5509105197Ssam	switch (idsrc->sadb_ident_type) {
5510105197Ssam	case SADB_IDENTTYPE_PREFIX:
5511105197Ssam	case SADB_IDENTTYPE_FQDN:
5512105197Ssam	case SADB_IDENTTYPE_USERFQDN:
5513105197Ssam	default:
5514105197Ssam		/* XXX do nothing */
5515105197Ssam		sah->idents = NULL;
5516105197Ssam		sah->identd = NULL;
5517105197Ssam	 	return 0;
5518105197Ssam	}
5519105197Ssam
5520105197Ssam	/* make structure */
5521157123Sgnn	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5522105197Ssam	if (sah->idents == NULL) {
5523120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5524105197Ssam		return ENOBUFS;
5525105197Ssam	}
5526157123Sgnn	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5527105197Ssam	if (sah->identd == NULL) {
5528119643Ssam		free(sah->idents, M_IPSEC_MISC);
5529105197Ssam		sah->idents = NULL;
5530120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5531105197Ssam		return ENOBUFS;
5532105197Ssam	}
5533157123Sgnn	sah->idents->type = idsrc->sadb_ident_type;
5534157123Sgnn	sah->idents->id = idsrc->sadb_ident_id;
5535105197Ssam
5536157123Sgnn	sah->identd->type = iddst->sadb_ident_type;
5537157123Sgnn	sah->identd->id = iddst->sadb_ident_id;
5538157123Sgnn
5539105197Ssam	return 0;
5540105197Ssam}
5541105197Ssam
5542105197Ssam/*
5543105197Ssam * m will not be freed on return.
5544105197Ssam * it is caller's responsibility to free the result.
5545105197Ssam */
5546105197Ssamstatic struct mbuf *
5547105197Ssamkey_getmsgbuf_x1(m, mhp)
5548105197Ssam	struct mbuf *m;
5549105197Ssam	const struct sadb_msghdr *mhp;
5550105197Ssam{
5551105197Ssam	struct mbuf *n;
5552105197Ssam
5553120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5554120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5555120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5556105197Ssam
5557105197Ssam	/* create new sadb_msg to reply. */
5558105197Ssam	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5559105197Ssam	    SADB_EXT_SA, SADB_X_EXT_SA2,
5560105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5561105197Ssam	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5562105197Ssam	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5563105197Ssam	if (!n)
5564105197Ssam		return NULL;
5565105197Ssam
5566105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5567105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5568105197Ssam		if (n == NULL)
5569105197Ssam			return NULL;
5570105197Ssam	}
5571105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5572105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_len =
5573105197Ssam	    PFKEY_UNIT64(n->m_pkthdr.len);
5574105197Ssam
5575105197Ssam	return n;
5576105197Ssam}
5577105197Ssam
5578105197Ssamstatic int key_delete_all __P((struct socket *, struct mbuf *,
5579105197Ssam	const struct sadb_msghdr *, u_int16_t));
5580105197Ssam
5581105197Ssam/*
5582105197Ssam * SADB_DELETE processing
5583105197Ssam * receive
5584105197Ssam *   <base, SA(*), address(SD)>
5585105197Ssam * from the ikmpd, and set SADB_SASTATE_DEAD,
5586105197Ssam * and send,
5587105197Ssam *   <base, SA(*), address(SD)>
5588105197Ssam * to the ikmpd.
5589105197Ssam *
5590105197Ssam * m will always be freed.
5591105197Ssam */
5592105197Ssamstatic int
5593105197Ssamkey_delete(so, m, mhp)
5594105197Ssam	struct socket *so;
5595105197Ssam	struct mbuf *m;
5596105197Ssam	const struct sadb_msghdr *mhp;
5597105197Ssam{
5598105197Ssam	struct sadb_sa *sa0;
5599105197Ssam	struct sadb_address *src0, *dst0;
5600105197Ssam	struct secasindex saidx;
5601105197Ssam	struct secashead *sah;
5602105197Ssam	struct secasvar *sav = NULL;
5603105197Ssam	u_int16_t proto;
5604105197Ssam
5605120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5606120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5607120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5608120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5609105197Ssam
5610105197Ssam	/* map satype to proto */
5611105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5612120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5613120585Ssam			__func__));
5614105197Ssam		return key_senderror(so, m, EINVAL);
5615105197Ssam	}
5616105197Ssam
5617105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5618105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5619120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5620120585Ssam			__func__));
5621105197Ssam		return key_senderror(so, m, EINVAL);
5622105197Ssam	}
5623105197Ssam
5624105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5625105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5626120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5627120585Ssam			__func__));
5628105197Ssam		return key_senderror(so, m, EINVAL);
5629105197Ssam	}
5630105197Ssam
5631105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL) {
5632105197Ssam		/*
5633105197Ssam		 * Caller wants us to delete all non-LARVAL SAs
5634105197Ssam		 * that match the src/dst.  This is used during
5635105197Ssam		 * IKE INITIAL-CONTACT.
5636105197Ssam		 */
5637120585Ssam		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5638105197Ssam		return key_delete_all(so, m, mhp, proto);
5639105197Ssam	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5640120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5641120585Ssam			__func__));
5642105197Ssam		return key_senderror(so, m, EINVAL);
5643105197Ssam	}
5644105197Ssam
5645105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5646105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5647105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5648105197Ssam
5649105197Ssam	/* XXX boundary check against sa_len */
5650105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5651105197Ssam
5652194062Svanhu	/*
5653194062Svanhu	 * Make sure the port numbers are zero.
5654194062Svanhu	 * In case of NAT-T we will update them later if needed.
5655194062Svanhu	 */
5656194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5657194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5658194062Svanhu
5659194062Svanhu#ifdef IPSEC_NAT_T
5660194062Svanhu	/*
5661194062Svanhu	 * Handle NAT-T info if present.
5662194062Svanhu	 */
5663194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5664194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5665194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5666194062Svanhu
5667194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5668194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5669194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5670194062Svanhu			    __func__));
5671194062Svanhu			return key_senderror(so, m, EINVAL);
5672194062Svanhu		}
5673194062Svanhu
5674194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5675194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5676194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5677194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5678194062Svanhu
5679194062Svanhu		if (sport)
5680194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5681194062Svanhu			    sport->sadb_x_nat_t_port_port);
5682194062Svanhu		if (dport)
5683194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5684194062Svanhu			    dport->sadb_x_nat_t_port_port);
5685194062Svanhu	}
5686194062Svanhu#endif
5687194062Svanhu
5688105197Ssam	/* get a SA header */
5689120585Ssam	SAHTREE_LOCK();
5690181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5691105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5692105197Ssam			continue;
5693105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5694105197Ssam			continue;
5695105197Ssam
5696105197Ssam		/* get a SA with SPI. */
5697105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5698105197Ssam		if (sav)
5699105197Ssam			break;
5700105197Ssam	}
5701105197Ssam	if (sah == NULL) {
5702120585Ssam		SAHTREE_UNLOCK();
5703120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5704105197Ssam		return key_senderror(so, m, ENOENT);
5705105197Ssam	}
5706105197Ssam
5707105197Ssam	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5708199398Svanhu	KEY_FREESAV(&sav);
5709120585Ssam	SAHTREE_UNLOCK();
5710105197Ssam
5711105197Ssam    {
5712105197Ssam	struct mbuf *n;
5713105197Ssam	struct sadb_msg *newmsg;
5714105197Ssam
5715105197Ssam	/* create new sadb_msg to reply. */
5716194062Svanhu	/* XXX-BZ NAT-T extensions? */
5717105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5718105197Ssam	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5719105197Ssam	if (!n)
5720105197Ssam		return key_senderror(so, m, ENOBUFS);
5721105197Ssam
5722105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5723105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5724105197Ssam		if (n == NULL)
5725105197Ssam			return key_senderror(so, m, ENOBUFS);
5726105197Ssam	}
5727105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5728105197Ssam	newmsg->sadb_msg_errno = 0;
5729105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5730105197Ssam
5731105197Ssam	m_freem(m);
5732105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5733105197Ssam    }
5734105197Ssam}
5735105197Ssam
5736105197Ssam/*
5737105197Ssam * delete all SAs for src/dst.  Called from key_delete().
5738105197Ssam */
5739105197Ssamstatic int
5740189004Srdivackykey_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5741189004Srdivacky    u_int16_t proto)
5742105197Ssam{
5743105197Ssam	struct sadb_address *src0, *dst0;
5744105197Ssam	struct secasindex saidx;
5745105197Ssam	struct secashead *sah;
5746105197Ssam	struct secasvar *sav, *nextsav;
5747105197Ssam	u_int stateidx, state;
5748105197Ssam
5749105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5750105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5751105197Ssam
5752105197Ssam	/* XXX boundary check against sa_len */
5753105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5754105197Ssam
5755194062Svanhu	/*
5756194062Svanhu	 * Make sure the port numbers are zero.
5757194062Svanhu	 * In case of NAT-T we will update them later if needed.
5758194062Svanhu	 */
5759194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5760194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5761194062Svanhu
5762194062Svanhu#ifdef IPSEC_NAT_T
5763194062Svanhu	/*
5764194062Svanhu	 * Handle NAT-T info if present.
5765194062Svanhu	 */
5766194062Svanhu
5767194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5768194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5769194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5770194062Svanhu
5771194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5772194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5773194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5774194062Svanhu			    __func__));
5775194062Svanhu			return key_senderror(so, m, EINVAL);
5776194062Svanhu		}
5777194062Svanhu
5778194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5779194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5780194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5781194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5782194062Svanhu
5783194062Svanhu		if (sport)
5784194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5785194062Svanhu			    sport->sadb_x_nat_t_port_port);
5786194062Svanhu		if (dport)
5787194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5788194062Svanhu			    dport->sadb_x_nat_t_port_port);
5789194062Svanhu	}
5790194062Svanhu#endif
5791194062Svanhu
5792120585Ssam	SAHTREE_LOCK();
5793181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5794105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5795105197Ssam			continue;
5796105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5797105197Ssam			continue;
5798105197Ssam
5799105197Ssam		/* Delete all non-LARVAL SAs. */
5800105197Ssam		for (stateidx = 0;
5801185348Szec		     stateidx < _ARRAYLEN(saorder_state_alive);
5802105197Ssam		     stateidx++) {
5803185348Szec			state = saorder_state_alive[stateidx];
5804105197Ssam			if (state == SADB_SASTATE_LARVAL)
5805105197Ssam				continue;
5806105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
5807105197Ssam			     sav != NULL; sav = nextsav) {
5808105197Ssam				nextsav = LIST_NEXT(sav, chain);
5809105197Ssam				/* sanity check */
5810105197Ssam				if (sav->state != state) {
5811120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
5812120585Ssam						"sav->state (queue %d SA %d)\n",
5813120585Ssam						__func__, state, sav->state));
5814105197Ssam					continue;
5815105197Ssam				}
5816105197Ssam
5817105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5818105197Ssam				KEY_FREESAV(&sav);
5819105197Ssam			}
5820105197Ssam		}
5821105197Ssam	}
5822120585Ssam	SAHTREE_UNLOCK();
5823105197Ssam    {
5824105197Ssam	struct mbuf *n;
5825105197Ssam	struct sadb_msg *newmsg;
5826105197Ssam
5827105197Ssam	/* create new sadb_msg to reply. */
5828194062Svanhu	/* XXX-BZ NAT-T extensions? */
5829105197Ssam	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5830105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5831105197Ssam	if (!n)
5832105197Ssam		return key_senderror(so, m, ENOBUFS);
5833105197Ssam
5834105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5835105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5836105197Ssam		if (n == NULL)
5837105197Ssam			return key_senderror(so, m, ENOBUFS);
5838105197Ssam	}
5839105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5840105197Ssam	newmsg->sadb_msg_errno = 0;
5841105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5842105197Ssam
5843105197Ssam	m_freem(m);
5844105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5845105197Ssam    }
5846105197Ssam}
5847105197Ssam
5848105197Ssam/*
5849105197Ssam * SADB_GET processing
5850105197Ssam * receive
5851105197Ssam *   <base, SA(*), address(SD)>
5852105197Ssam * from the ikmpd, and get a SP and a SA to respond,
5853105197Ssam * and send,
5854105197Ssam *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5855105197Ssam *       (identity(SD),) (sensitivity)>
5856105197Ssam * to the ikmpd.
5857105197Ssam *
5858105197Ssam * m will always be freed.
5859105197Ssam */
5860105197Ssamstatic int
5861105197Ssamkey_get(so, m, mhp)
5862105197Ssam	struct socket *so;
5863105197Ssam	struct mbuf *m;
5864105197Ssam	const struct sadb_msghdr *mhp;
5865105197Ssam{
5866105197Ssam	struct sadb_sa *sa0;
5867105197Ssam	struct sadb_address *src0, *dst0;
5868105197Ssam	struct secasindex saidx;
5869105197Ssam	struct secashead *sah;
5870105197Ssam	struct secasvar *sav = NULL;
5871105197Ssam	u_int16_t proto;
5872105197Ssam
5873120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5874120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5875120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5876120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5877105197Ssam
5878105197Ssam	/* map satype to proto */
5879105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5880120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5881120585Ssam			__func__));
5882105197Ssam		return key_senderror(so, m, EINVAL);
5883105197Ssam	}
5884105197Ssam
5885105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5886105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5887105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5888120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5889120585Ssam			__func__));
5890105197Ssam		return key_senderror(so, m, EINVAL);
5891105197Ssam	}
5892105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5893105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5894105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5895120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5896120585Ssam			__func__));
5897105197Ssam		return key_senderror(so, m, EINVAL);
5898105197Ssam	}
5899105197Ssam
5900105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5901105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5902105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5903105197Ssam
5904105197Ssam	/* XXX boundary check against sa_len */
5905105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5906105197Ssam
5907194062Svanhu	/*
5908194062Svanhu	 * Make sure the port numbers are zero.
5909194062Svanhu	 * In case of NAT-T we will update them later if needed.
5910194062Svanhu	 */
5911194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5912194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5913194062Svanhu
5914194062Svanhu#ifdef IPSEC_NAT_T
5915194062Svanhu	/*
5916194062Svanhu	 * Handle NAT-T info if present.
5917194062Svanhu	 */
5918194062Svanhu
5919194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5920194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5921194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5922194062Svanhu
5923194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5924194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5925194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5926194062Svanhu			    __func__));
5927194062Svanhu			return key_senderror(so, m, EINVAL);
5928194062Svanhu		}
5929194062Svanhu
5930194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5931194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5932194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5933194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5934194062Svanhu
5935194062Svanhu		if (sport)
5936194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5937194062Svanhu			    sport->sadb_x_nat_t_port_port);
5938194062Svanhu		if (dport)
5939194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5940194062Svanhu			    dport->sadb_x_nat_t_port_port);
5941194062Svanhu	}
5942194062Svanhu#endif
5943194062Svanhu
5944105197Ssam	/* get a SA header */
5945120585Ssam	SAHTREE_LOCK();
5946181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5947105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5948105197Ssam			continue;
5949105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5950105197Ssam			continue;
5951105197Ssam
5952105197Ssam		/* get a SA with SPI. */
5953105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5954105197Ssam		if (sav)
5955105197Ssam			break;
5956105197Ssam	}
5957120585Ssam	SAHTREE_UNLOCK();
5958105197Ssam	if (sah == NULL) {
5959120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5960105197Ssam		return key_senderror(so, m, ENOENT);
5961105197Ssam	}
5962105197Ssam
5963105197Ssam    {
5964105197Ssam	struct mbuf *n;
5965105197Ssam	u_int8_t satype;
5966105197Ssam
5967105197Ssam	/* map proto to satype */
5968105197Ssam	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5969120585Ssam		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5970120585Ssam			__func__));
5971105197Ssam		return key_senderror(so, m, EINVAL);
5972105197Ssam	}
5973105197Ssam
5974105197Ssam	/* create new sadb_msg to reply. */
5975105197Ssam	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5976105197Ssam	    mhp->msg->sadb_msg_pid);
5977105197Ssam	if (!n)
5978105197Ssam		return key_senderror(so, m, ENOBUFS);
5979105197Ssam
5980105197Ssam	m_freem(m);
5981105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5982105197Ssam    }
5983105197Ssam}
5984105197Ssam
5985105197Ssam/* XXX make it sysctl-configurable? */
5986105197Ssamstatic void
5987105197Ssamkey_getcomb_setlifetime(comb)
5988105197Ssam	struct sadb_comb *comb;
5989105197Ssam{
5990105197Ssam
5991105197Ssam	comb->sadb_comb_soft_allocations = 1;
5992105197Ssam	comb->sadb_comb_hard_allocations = 1;
5993105197Ssam	comb->sadb_comb_soft_bytes = 0;
5994105197Ssam	comb->sadb_comb_hard_bytes = 0;
5995105197Ssam	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5996105197Ssam	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5997105197Ssam	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5998105197Ssam	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5999105197Ssam}
6000105197Ssam
6001105197Ssam/*
6002105197Ssam * XXX reorder combinations by preference
6003105197Ssam * XXX no idea if the user wants ESP authentication or not
6004105197Ssam */
6005105197Ssamstatic struct mbuf *
6006105197Ssamkey_getcomb_esp()
6007105197Ssam{
6008105197Ssam	struct sadb_comb *comb;
6009105197Ssam	struct enc_xform *algo;
6010105197Ssam	struct mbuf *result = NULL, *m, *n;
6011105197Ssam	int encmin;
6012105197Ssam	int i, off, o;
6013105197Ssam	int totlen;
6014105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6015105197Ssam
6016105197Ssam	m = NULL;
6017105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6018105197Ssam		algo = esp_algorithm_lookup(i);
6019105197Ssam		if (algo == NULL)
6020105197Ssam			continue;
6021105197Ssam
6022105197Ssam		/* discard algorithms with key size smaller than system min */
6023181803Sbz		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6024105197Ssam			continue;
6025181803Sbz		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6026181803Sbz			encmin = V_ipsec_esp_keymin;
6027105197Ssam		else
6028105197Ssam			encmin = _BITS(algo->minkey);
6029105197Ssam
6030181803Sbz		if (V_ipsec_esp_auth)
6031105197Ssam			m = key_getcomb_ah();
6032105197Ssam		else {
6033120585Ssam			IPSEC_ASSERT(l <= MLEN,
6034120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6035111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
6036105197Ssam			if (m) {
6037105197Ssam				M_ALIGN(m, l);
6038105197Ssam				m->m_len = l;
6039105197Ssam				m->m_next = NULL;
6040105197Ssam				bzero(mtod(m, caddr_t), m->m_len);
6041105197Ssam			}
6042105197Ssam		}
6043105197Ssam		if (!m)
6044105197Ssam			goto fail;
6045105197Ssam
6046105197Ssam		totlen = 0;
6047105197Ssam		for (n = m; n; n = n->m_next)
6048105197Ssam			totlen += n->m_len;
6049120585Ssam		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6050105197Ssam
6051105197Ssam		for (off = 0; off < totlen; off += l) {
6052105197Ssam			n = m_pulldown(m, off, l, &o);
6053105197Ssam			if (!n) {
6054105197Ssam				/* m is already freed */
6055105197Ssam				goto fail;
6056105197Ssam			}
6057105197Ssam			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6058105197Ssam			bzero(comb, sizeof(*comb));
6059105197Ssam			key_getcomb_setlifetime(comb);
6060105197Ssam			comb->sadb_comb_encrypt = i;
6061105197Ssam			comb->sadb_comb_encrypt_minbits = encmin;
6062105197Ssam			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6063105197Ssam		}
6064105197Ssam
6065105197Ssam		if (!result)
6066105197Ssam			result = m;
6067105197Ssam		else
6068105197Ssam			m_cat(result, m);
6069105197Ssam	}
6070105197Ssam
6071105197Ssam	return result;
6072105197Ssam
6073105197Ssam fail:
6074105197Ssam	if (result)
6075105197Ssam		m_freem(result);
6076105197Ssam	return NULL;
6077105197Ssam}
6078105197Ssam
6079105197Ssamstatic void
6080105197Ssamkey_getsizes_ah(
6081105197Ssam	const struct auth_hash *ah,
6082105197Ssam	int alg,
6083105197Ssam	u_int16_t* min,
6084105197Ssam	u_int16_t* max)
6085105197Ssam{
6086183550Szec
6087105197Ssam	*min = *max = ah->keysize;
6088105197Ssam	if (ah->keysize == 0) {
6089105197Ssam		/*
6090105197Ssam		 * Transform takes arbitrary key size but algorithm
6091105197Ssam		 * key size is restricted.  Enforce this here.
6092105197Ssam		 */
6093105197Ssam		switch (alg) {
6094105197Ssam		case SADB_X_AALG_MD5:	*min = *max = 16; break;
6095105197Ssam		case SADB_X_AALG_SHA:	*min = *max = 20; break;
6096105197Ssam		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
6097105197Ssam		default:
6098120585Ssam			DPRINTF(("%s: unknown AH algorithm %u\n",
6099120585Ssam				__func__, alg));
6100105197Ssam			break;
6101105197Ssam		}
6102105197Ssam	}
6103105197Ssam}
6104105197Ssam
6105105197Ssam/*
6106105197Ssam * XXX reorder combinations by preference
6107105197Ssam */
6108105197Ssamstatic struct mbuf *
6109105197Ssamkey_getcomb_ah()
6110105197Ssam{
6111105197Ssam	struct sadb_comb *comb;
6112105197Ssam	struct auth_hash *algo;
6113105197Ssam	struct mbuf *m;
6114105197Ssam	u_int16_t minkeysize, maxkeysize;
6115105197Ssam	int i;
6116105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6117105197Ssam
6118105197Ssam	m = NULL;
6119105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6120105197Ssam#if 1
6121105197Ssam		/* we prefer HMAC algorithms, not old algorithms */
6122105197Ssam		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
6123105197Ssam			continue;
6124105197Ssam#endif
6125105197Ssam		algo = ah_algorithm_lookup(i);
6126105197Ssam		if (!algo)
6127105197Ssam			continue;
6128105197Ssam		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6129105197Ssam		/* discard algorithms with key size smaller than system min */
6130181803Sbz		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6131105197Ssam			continue;
6132105197Ssam
6133105197Ssam		if (!m) {
6134120585Ssam			IPSEC_ASSERT(l <= MLEN,
6135120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6136111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
6137105197Ssam			if (m) {
6138105197Ssam				M_ALIGN(m, l);
6139105197Ssam				m->m_len = l;
6140105197Ssam				m->m_next = NULL;
6141105197Ssam			}
6142105197Ssam		} else
6143111119Simp			M_PREPEND(m, l, M_DONTWAIT);
6144105197Ssam		if (!m)
6145105197Ssam			return NULL;
6146105197Ssam
6147105197Ssam		comb = mtod(m, struct sadb_comb *);
6148105197Ssam		bzero(comb, sizeof(*comb));
6149105197Ssam		key_getcomb_setlifetime(comb);
6150105197Ssam		comb->sadb_comb_auth = i;
6151105197Ssam		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6152105197Ssam		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6153105197Ssam	}
6154105197Ssam
6155105197Ssam	return m;
6156105197Ssam}
6157105197Ssam
6158105197Ssam/*
6159105197Ssam * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6160105197Ssam * XXX reorder combinations by preference
6161105197Ssam */
6162105197Ssamstatic struct mbuf *
6163105197Ssamkey_getcomb_ipcomp()
6164105197Ssam{
6165105197Ssam	struct sadb_comb *comb;
6166105197Ssam	struct comp_algo *algo;
6167105197Ssam	struct mbuf *m;
6168105197Ssam	int i;
6169105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6170105197Ssam
6171105197Ssam	m = NULL;
6172105197Ssam	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6173105197Ssam		algo = ipcomp_algorithm_lookup(i);
6174105197Ssam		if (!algo)
6175105197Ssam			continue;
6176105197Ssam
6177105197Ssam		if (!m) {
6178120585Ssam			IPSEC_ASSERT(l <= MLEN,
6179120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6180111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
6181105197Ssam			if (m) {
6182105197Ssam				M_ALIGN(m, l);
6183105197Ssam				m->m_len = l;
6184105197Ssam				m->m_next = NULL;
6185105197Ssam			}
6186105197Ssam		} else
6187111119Simp			M_PREPEND(m, l, M_DONTWAIT);
6188105197Ssam		if (!m)
6189105197Ssam			return NULL;
6190105197Ssam
6191105197Ssam		comb = mtod(m, struct sadb_comb *);
6192105197Ssam		bzero(comb, sizeof(*comb));
6193105197Ssam		key_getcomb_setlifetime(comb);
6194105197Ssam		comb->sadb_comb_encrypt = i;
6195105197Ssam		/* what should we set into sadb_comb_*_{min,max}bits? */
6196105197Ssam	}
6197105197Ssam
6198105197Ssam	return m;
6199105197Ssam}
6200105197Ssam
6201105197Ssam/*
6202105197Ssam * XXX no way to pass mode (transport/tunnel) to userland
6203105197Ssam * XXX replay checking?
6204105197Ssam * XXX sysctl interface to ipsec_{ah,esp}_keymin
6205105197Ssam */
6206105197Ssamstatic struct mbuf *
6207105197Ssamkey_getprop(saidx)
6208105197Ssam	const struct secasindex *saidx;
6209105197Ssam{
6210105197Ssam	struct sadb_prop *prop;
6211105197Ssam	struct mbuf *m, *n;
6212105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6213105197Ssam	int totlen;
6214105197Ssam
6215105197Ssam	switch (saidx->proto)  {
6216105197Ssam	case IPPROTO_ESP:
6217105197Ssam		m = key_getcomb_esp();
6218105197Ssam		break;
6219105197Ssam	case IPPROTO_AH:
6220105197Ssam		m = key_getcomb_ah();
6221105197Ssam		break;
6222105197Ssam	case IPPROTO_IPCOMP:
6223105197Ssam		m = key_getcomb_ipcomp();
6224105197Ssam		break;
6225105197Ssam	default:
6226105197Ssam		return NULL;
6227105197Ssam	}
6228105197Ssam
6229105197Ssam	if (!m)
6230105197Ssam		return NULL;
6231111119Simp	M_PREPEND(m, l, M_DONTWAIT);
6232105197Ssam	if (!m)
6233105197Ssam		return NULL;
6234105197Ssam
6235105197Ssam	totlen = 0;
6236105197Ssam	for (n = m; n; n = n->m_next)
6237105197Ssam		totlen += n->m_len;
6238105197Ssam
6239105197Ssam	prop = mtod(m, struct sadb_prop *);
6240105197Ssam	bzero(prop, sizeof(*prop));
6241105197Ssam	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6242105197Ssam	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6243105197Ssam	prop->sadb_prop_replay = 32;	/* XXX */
6244105197Ssam
6245105197Ssam	return m;
6246105197Ssam}
6247105197Ssam
6248105197Ssam/*
6249105197Ssam * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6250105197Ssam * send
6251105197Ssam *   <base, SA, address(SD), (address(P)), x_policy,
6252105197Ssam *       (identity(SD),) (sensitivity,) proposal>
6253105197Ssam * to KMD, and expect to receive
6254105197Ssam *   <base> with SADB_ACQUIRE if error occured,
6255105197Ssam * or
6256105197Ssam *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6257105197Ssam * from KMD by PF_KEY.
6258105197Ssam *
6259105197Ssam * XXX x_policy is outside of RFC2367 (KAME extension).
6260105197Ssam * XXX sensitivity is not supported.
6261105197Ssam * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6262105197Ssam * see comment for key_getcomb_ipcomp().
6263105197Ssam *
6264105197Ssam * OUT:
6265105197Ssam *    0     : succeed
6266105197Ssam *    others: error number
6267105197Ssam */
6268105197Ssamstatic int
6269105197Ssamkey_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6270105197Ssam{
6271105197Ssam	struct mbuf *result = NULL, *m;
6272105197Ssam	struct secacq *newacq;
6273105197Ssam	u_int8_t satype;
6274105197Ssam	int error = -1;
6275105197Ssam	u_int32_t seq;
6276105197Ssam
6277120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6278105197Ssam	satype = key_proto2satype(saidx->proto);
6279120585Ssam	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6280105197Ssam
6281105197Ssam	/*
6282105197Ssam	 * We never do anything about acquirng SA.  There is anather
6283105197Ssam	 * solution that kernel blocks to send SADB_ACQUIRE message until
6284105197Ssam	 * getting something message from IKEd.  In later case, to be
6285105197Ssam	 * managed with ACQUIRING list.
6286105197Ssam	 */
6287108533Sschweikh	/* Get an entry to check whether sending message or not. */
6288105197Ssam	if ((newacq = key_getacq(saidx)) != NULL) {
6289181803Sbz		if (V_key_blockacq_count < newacq->count) {
6290105197Ssam			/* reset counter and do send message. */
6291105197Ssam			newacq->count = 0;
6292105197Ssam		} else {
6293105197Ssam			/* increment counter and do nothing. */
6294105197Ssam			newacq->count++;
6295105197Ssam			return 0;
6296105197Ssam		}
6297105197Ssam	} else {
6298105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
6299105197Ssam		if ((newacq = key_newacq(saidx)) == NULL)
6300105197Ssam			return ENOBUFS;
6301105197Ssam	}
6302105197Ssam
6303105197Ssam
6304105197Ssam	seq = newacq->seq;
6305105197Ssam	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6306105197Ssam	if (!m) {
6307105197Ssam		error = ENOBUFS;
6308105197Ssam		goto fail;
6309105197Ssam	}
6310105197Ssam	result = m;
6311105197Ssam
6312194062Svanhu	/*
6313194062Svanhu	 * No SADB_X_EXT_NAT_T_* here: we do not know
6314194062Svanhu	 * anything related to NAT-T at this time.
6315194062Svanhu	 */
6316194062Svanhu
6317105197Ssam	/* set sadb_address for saidx's. */
6318105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6319105197Ssam	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6320105197Ssam	if (!m) {
6321105197Ssam		error = ENOBUFS;
6322105197Ssam		goto fail;
6323105197Ssam	}
6324105197Ssam	m_cat(result, m);
6325105197Ssam
6326105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6327105197Ssam	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6328105197Ssam	if (!m) {
6329105197Ssam		error = ENOBUFS;
6330105197Ssam		goto fail;
6331105197Ssam	}
6332105197Ssam	m_cat(result, m);
6333105197Ssam
6334105197Ssam	/* XXX proxy address (optional) */
6335105197Ssam
6336105197Ssam	/* set sadb_x_policy */
6337105197Ssam	if (sp) {
6338105197Ssam		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6339105197Ssam		if (!m) {
6340105197Ssam			error = ENOBUFS;
6341105197Ssam			goto fail;
6342105197Ssam		}
6343105197Ssam		m_cat(result, m);
6344105197Ssam	}
6345105197Ssam
6346105197Ssam	/* XXX identity (optional) */
6347105197Ssam#if 0
6348105197Ssam	if (idexttype && fqdn) {
6349105197Ssam		/* create identity extension (FQDN) */
6350105197Ssam		struct sadb_ident *id;
6351105197Ssam		int fqdnlen;
6352105197Ssam
6353105197Ssam		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
6354105197Ssam		id = (struct sadb_ident *)p;
6355105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6356105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6357105197Ssam		id->sadb_ident_exttype = idexttype;
6358105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6359105197Ssam		bcopy(fqdn, id + 1, fqdnlen);
6360105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6361105197Ssam	}
6362105197Ssam
6363105197Ssam	if (idexttype) {
6364105197Ssam		/* create identity extension (USERFQDN) */
6365105197Ssam		struct sadb_ident *id;
6366105197Ssam		int userfqdnlen;
6367105197Ssam
6368105197Ssam		if (userfqdn) {
6369105197Ssam			/* +1 for terminating-NUL */
6370105197Ssam			userfqdnlen = strlen(userfqdn) + 1;
6371105197Ssam		} else
6372105197Ssam			userfqdnlen = 0;
6373105197Ssam		id = (struct sadb_ident *)p;
6374105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6375105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6376105197Ssam		id->sadb_ident_exttype = idexttype;
6377105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6378105197Ssam		/* XXX is it correct? */
6379105197Ssam		if (curproc && curproc->p_cred)
6380105197Ssam			id->sadb_ident_id = curproc->p_cred->p_ruid;
6381105197Ssam		if (userfqdn && userfqdnlen)
6382105197Ssam			bcopy(userfqdn, id + 1, userfqdnlen);
6383105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6384105197Ssam	}
6385105197Ssam#endif
6386105197Ssam
6387105197Ssam	/* XXX sensitivity (optional) */
6388105197Ssam
6389105197Ssam	/* create proposal/combination extension */
6390105197Ssam	m = key_getprop(saidx);
6391105197Ssam#if 0
6392105197Ssam	/*
6393105197Ssam	 * spec conformant: always attach proposal/combination extension,
6394105197Ssam	 * the problem is that we have no way to attach it for ipcomp,
6395105197Ssam	 * due to the way sadb_comb is declared in RFC2367.
6396105197Ssam	 */
6397105197Ssam	if (!m) {
6398105197Ssam		error = ENOBUFS;
6399105197Ssam		goto fail;
6400105197Ssam	}
6401105197Ssam	m_cat(result, m);
6402105197Ssam#else
6403105197Ssam	/*
6404105197Ssam	 * outside of spec; make proposal/combination extension optional.
6405105197Ssam	 */
6406105197Ssam	if (m)
6407105197Ssam		m_cat(result, m);
6408105197Ssam#endif
6409105197Ssam
6410105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
6411105197Ssam		error = EINVAL;
6412105197Ssam		goto fail;
6413105197Ssam	}
6414105197Ssam
6415105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
6416105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
6417105197Ssam		if (result == NULL) {
6418105197Ssam			error = ENOBUFS;
6419105197Ssam			goto fail;
6420105197Ssam		}
6421105197Ssam	}
6422105197Ssam
6423105197Ssam	result->m_pkthdr.len = 0;
6424105197Ssam	for (m = result; m; m = m->m_next)
6425105197Ssam		result->m_pkthdr.len += m->m_len;
6426105197Ssam
6427105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
6428105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
6429105197Ssam
6430105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6431105197Ssam
6432105197Ssam fail:
6433105197Ssam	if (result)
6434105197Ssam		m_freem(result);
6435105197Ssam	return error;
6436105197Ssam}
6437105197Ssam
6438105197Ssamstatic struct secacq *
6439105197Ssamkey_newacq(const struct secasindex *saidx)
6440105197Ssam{
6441105197Ssam	struct secacq *newacq;
6442105197Ssam
6443105197Ssam	/* get new entry */
6444119643Ssam	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6445105197Ssam	if (newacq == NULL) {
6446120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6447105197Ssam		return NULL;
6448105197Ssam	}
6449105197Ssam
6450105197Ssam	/* copy secindex */
6451105197Ssam	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6452181803Sbz	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6453105197Ssam	newacq->created = time_second;
6454105197Ssam	newacq->count = 0;
6455105197Ssam
6456119643Ssam	/* add to acqtree */
6457120585Ssam	ACQ_LOCK();
6458181803Sbz	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6459120585Ssam	ACQ_UNLOCK();
6460119643Ssam
6461105197Ssam	return newacq;
6462105197Ssam}
6463105197Ssam
6464105197Ssamstatic struct secacq *
6465105197Ssamkey_getacq(const struct secasindex *saidx)
6466105197Ssam{
6467105197Ssam	struct secacq *acq;
6468105197Ssam
6469120585Ssam	ACQ_LOCK();
6470181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
6471105197Ssam		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6472119643Ssam			break;
6473105197Ssam	}
6474120585Ssam	ACQ_UNLOCK();
6475105197Ssam
6476119643Ssam	return acq;
6477105197Ssam}
6478105197Ssam
6479105197Ssamstatic struct secacq *
6480105197Ssamkey_getacqbyseq(seq)
6481105197Ssam	u_int32_t seq;
6482105197Ssam{
6483105197Ssam	struct secacq *acq;
6484105197Ssam
6485120585Ssam	ACQ_LOCK();
6486181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
6487105197Ssam		if (acq->seq == seq)
6488119643Ssam			break;
6489105197Ssam	}
6490120585Ssam	ACQ_UNLOCK();
6491105197Ssam
6492119643Ssam	return acq;
6493105197Ssam}
6494105197Ssam
6495105197Ssamstatic struct secspacq *
6496105197Ssamkey_newspacq(spidx)
6497105197Ssam	struct secpolicyindex *spidx;
6498105197Ssam{
6499105197Ssam	struct secspacq *acq;
6500105197Ssam
6501105197Ssam	/* get new entry */
6502119643Ssam	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6503105197Ssam	if (acq == NULL) {
6504120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6505105197Ssam		return NULL;
6506105197Ssam	}
6507105197Ssam
6508105197Ssam	/* copy secindex */
6509105197Ssam	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6510105197Ssam	acq->created = time_second;
6511105197Ssam	acq->count = 0;
6512105197Ssam
6513119643Ssam	/* add to spacqtree */
6514120585Ssam	SPACQ_LOCK();
6515181803Sbz	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6516120585Ssam	SPACQ_UNLOCK();
6517119643Ssam
6518105197Ssam	return acq;
6519105197Ssam}
6520105197Ssam
6521105197Ssamstatic struct secspacq *
6522105197Ssamkey_getspacq(spidx)
6523105197Ssam	struct secpolicyindex *spidx;
6524105197Ssam{
6525105197Ssam	struct secspacq *acq;
6526105197Ssam
6527120585Ssam	SPACQ_LOCK();
6528181803Sbz	LIST_FOREACH(acq, &V_spacqtree, chain) {
6529119643Ssam		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6530119643Ssam			/* NB: return holding spacq_lock */
6531105197Ssam			return acq;
6532119643Ssam		}
6533105197Ssam	}
6534120585Ssam	SPACQ_UNLOCK();
6535105197Ssam
6536105197Ssam	return NULL;
6537105197Ssam}
6538105197Ssam
6539105197Ssam/*
6540105197Ssam * SADB_ACQUIRE processing,
6541105197Ssam * in first situation, is receiving
6542105197Ssam *   <base>
6543105197Ssam * from the ikmpd, and clear sequence of its secasvar entry.
6544105197Ssam *
6545105197Ssam * In second situation, is receiving
6546105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6547105197Ssam * from a user land process, and return
6548105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6549105197Ssam * to the socket.
6550105197Ssam *
6551105197Ssam * m will always be freed.
6552105197Ssam */
6553105197Ssamstatic int
6554105197Ssamkey_acquire2(so, m, mhp)
6555105197Ssam	struct socket *so;
6556105197Ssam	struct mbuf *m;
6557105197Ssam	const struct sadb_msghdr *mhp;
6558105197Ssam{
6559105197Ssam	const struct sadb_address *src0, *dst0;
6560105197Ssam	struct secasindex saidx;
6561105197Ssam	struct secashead *sah;
6562105197Ssam	u_int16_t proto;
6563105197Ssam	int error;
6564105197Ssam
6565120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6566120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6567120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6568120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6569105197Ssam
6570105197Ssam	/*
6571105197Ssam	 * Error message from KMd.
6572105197Ssam	 * We assume that if error was occured in IKEd, the length of PFKEY
6573105197Ssam	 * message is equal to the size of sadb_msg structure.
6574105197Ssam	 * We do not raise error even if error occured in this function.
6575105197Ssam	 */
6576105197Ssam	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6577105197Ssam		struct secacq *acq;
6578105197Ssam
6579105197Ssam		/* check sequence number */
6580105197Ssam		if (mhp->msg->sadb_msg_seq == 0) {
6581120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6582120585Ssam				"number.\n", __func__));
6583105197Ssam			m_freem(m);
6584105197Ssam			return 0;
6585105197Ssam		}
6586105197Ssam
6587105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6588105197Ssam			/*
6589105197Ssam			 * the specified larval SA is already gone, or we got
6590105197Ssam			 * a bogus sequence number.  we can silently ignore it.
6591105197Ssam			 */
6592105197Ssam			m_freem(m);
6593105197Ssam			return 0;
6594105197Ssam		}
6595105197Ssam
6596105197Ssam		/* reset acq counter in order to deletion by timehander. */
6597105197Ssam		acq->created = time_second;
6598105197Ssam		acq->count = 0;
6599105197Ssam		m_freem(m);
6600105197Ssam		return 0;
6601105197Ssam	}
6602105197Ssam
6603105197Ssam	/*
6604105197Ssam	 * This message is from user land.
6605105197Ssam	 */
6606105197Ssam
6607105197Ssam	/* map satype to proto */
6608105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6609120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6610120585Ssam			__func__));
6611105197Ssam		return key_senderror(so, m, EINVAL);
6612105197Ssam	}
6613105197Ssam
6614105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6615105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6616105197Ssam	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6617105197Ssam		/* error */
6618120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6619120585Ssam			__func__));
6620105197Ssam		return key_senderror(so, m, EINVAL);
6621105197Ssam	}
6622105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6623105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6624105197Ssam	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6625105197Ssam		/* error */
6626120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6627120585Ssam			__func__));
6628105197Ssam		return key_senderror(so, m, EINVAL);
6629105197Ssam	}
6630105197Ssam
6631105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6632105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6633105197Ssam
6634105197Ssam	/* XXX boundary check against sa_len */
6635105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6636105197Ssam
6637194062Svanhu	/*
6638194062Svanhu	 * Make sure the port numbers are zero.
6639194062Svanhu	 * In case of NAT-T we will update them later if needed.
6640194062Svanhu	 */
6641194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
6642194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
6643194062Svanhu
6644194062Svanhu#ifndef IPSEC_NAT_T
6645194062Svanhu	/*
6646194062Svanhu	 * Handle NAT-T info if present.
6647194062Svanhu	 */
6648194062Svanhu
6649194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6650194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6651194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
6652194062Svanhu
6653194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6654194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6655194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6656194062Svanhu			    __func__));
6657194062Svanhu			return key_senderror(so, m, EINVAL);
6658194062Svanhu		}
6659194062Svanhu
6660194062Svanhu		sport = (struct sadb_x_nat_t_port *)
6661194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6662194062Svanhu		dport = (struct sadb_x_nat_t_port *)
6663194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6664194062Svanhu
6665194062Svanhu		if (sport)
6666194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
6667194062Svanhu			    sport->sadb_x_nat_t_port_port);
6668194062Svanhu		if (dport)
6669194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
6670194062Svanhu			    dport->sadb_x_nat_t_port_port);
6671194062Svanhu	}
6672194062Svanhu#endif
6673194062Svanhu
6674105197Ssam	/* get a SA index */
6675120585Ssam	SAHTREE_LOCK();
6676181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
6677105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
6678105197Ssam			continue;
6679105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6680105197Ssam			break;
6681105197Ssam	}
6682120585Ssam	SAHTREE_UNLOCK();
6683105197Ssam	if (sah != NULL) {
6684120585Ssam		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6685105197Ssam		return key_senderror(so, m, EEXIST);
6686105197Ssam	}
6687105197Ssam
6688105197Ssam	error = key_acquire(&saidx, NULL);
6689105197Ssam	if (error != 0) {
6690120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6691120585Ssam			__func__, mhp->msg->sadb_msg_errno));
6692105197Ssam		return key_senderror(so, m, error);
6693105197Ssam	}
6694105197Ssam
6695105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6696105197Ssam}
6697105197Ssam
6698105197Ssam/*
6699105197Ssam * SADB_REGISTER processing.
6700105197Ssam * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6701105197Ssam * receive
6702105197Ssam *   <base>
6703105197Ssam * from the ikmpd, and register a socket to send PF_KEY messages,
6704105197Ssam * and send
6705105197Ssam *   <base, supported>
6706105197Ssam * to KMD by PF_KEY.
6707105197Ssam * If socket is detached, must free from regnode.
6708105197Ssam *
6709105197Ssam * m will always be freed.
6710105197Ssam */
6711105197Ssamstatic int
6712105197Ssamkey_register(so, m, mhp)
6713105197Ssam	struct socket *so;
6714105197Ssam	struct mbuf *m;
6715105197Ssam	const struct sadb_msghdr *mhp;
6716105197Ssam{
6717105197Ssam	struct secreg *reg, *newreg = 0;
6718105197Ssam
6719120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6720120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6721120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6722120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6723105197Ssam
6724105197Ssam	/* check for invalid register message */
6725181803Sbz	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6726105197Ssam		return key_senderror(so, m, EINVAL);
6727105197Ssam
6728105197Ssam	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6729105197Ssam	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6730105197Ssam		goto setmsg;
6731105197Ssam
6732105197Ssam	/* check whether existing or not */
6733120585Ssam	REGTREE_LOCK();
6734181803Sbz	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6735105197Ssam		if (reg->so == so) {
6736120585Ssam			REGTREE_UNLOCK();
6737120585Ssam			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6738120585Ssam				__func__));
6739105197Ssam			return key_senderror(so, m, EEXIST);
6740105197Ssam		}
6741105197Ssam	}
6742105197Ssam
6743105197Ssam	/* create regnode */
6744119643Ssam	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6745105197Ssam	if (newreg == NULL) {
6746120585Ssam		REGTREE_UNLOCK();
6747120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6748105197Ssam		return key_senderror(so, m, ENOBUFS);
6749105197Ssam	}
6750105197Ssam
6751105197Ssam	newreg->so = so;
6752105197Ssam	((struct keycb *)sotorawcb(so))->kp_registered++;
6753105197Ssam
6754105197Ssam	/* add regnode to regtree. */
6755181803Sbz	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6756120585Ssam	REGTREE_UNLOCK();
6757105197Ssam
6758105197Ssam  setmsg:
6759105197Ssam    {
6760105197Ssam	struct mbuf *n;
6761105197Ssam	struct sadb_msg *newmsg;
6762105197Ssam	struct sadb_supported *sup;
6763105197Ssam	u_int len, alen, elen;
6764105197Ssam	int off;
6765105197Ssam	int i;
6766105197Ssam	struct sadb_alg *alg;
6767105197Ssam
6768105197Ssam	/* create new sadb_msg to reply. */
6769105197Ssam	alen = 0;
6770105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6771105197Ssam		if (ah_algorithm_lookup(i))
6772105197Ssam			alen += sizeof(struct sadb_alg);
6773105197Ssam	}
6774105197Ssam	if (alen)
6775105197Ssam		alen += sizeof(struct sadb_supported);
6776105197Ssam	elen = 0;
6777105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6778105197Ssam		if (esp_algorithm_lookup(i))
6779105197Ssam			elen += sizeof(struct sadb_alg);
6780105197Ssam	}
6781105197Ssam	if (elen)
6782105197Ssam		elen += sizeof(struct sadb_supported);
6783105197Ssam
6784105197Ssam	len = sizeof(struct sadb_msg) + alen + elen;
6785105197Ssam
6786105197Ssam	if (len > MCLBYTES)
6787105197Ssam		return key_senderror(so, m, ENOBUFS);
6788105197Ssam
6789111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
6790105197Ssam	if (len > MHLEN) {
6791111119Simp		MCLGET(n, M_DONTWAIT);
6792105197Ssam		if ((n->m_flags & M_EXT) == 0) {
6793105197Ssam			m_freem(n);
6794105197Ssam			n = NULL;
6795105197Ssam		}
6796105197Ssam	}
6797105197Ssam	if (!n)
6798105197Ssam		return key_senderror(so, m, ENOBUFS);
6799105197Ssam
6800105197Ssam	n->m_pkthdr.len = n->m_len = len;
6801105197Ssam	n->m_next = NULL;
6802105197Ssam	off = 0;
6803105197Ssam
6804105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6805105197Ssam	newmsg = mtod(n, struct sadb_msg *);
6806105197Ssam	newmsg->sadb_msg_errno = 0;
6807105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6808105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6809105197Ssam
6810105197Ssam	/* for authentication algorithm */
6811105197Ssam	if (alen) {
6812105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6813105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6814105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6815105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6816105197Ssam
6817105197Ssam		for (i = 1; i <= SADB_AALG_MAX; i++) {
6818105197Ssam			struct auth_hash *aalgo;
6819105197Ssam			u_int16_t minkeysize, maxkeysize;
6820105197Ssam
6821105197Ssam			aalgo = ah_algorithm_lookup(i);
6822105197Ssam			if (!aalgo)
6823105197Ssam				continue;
6824105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6825105197Ssam			alg->sadb_alg_id = i;
6826105197Ssam			alg->sadb_alg_ivlen = 0;
6827105197Ssam			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6828105197Ssam			alg->sadb_alg_minbits = _BITS(minkeysize);
6829105197Ssam			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6830105197Ssam			off += PFKEY_ALIGN8(sizeof(*alg));
6831105197Ssam		}
6832105197Ssam	}
6833105197Ssam
6834105197Ssam	/* for encryption algorithm */
6835105197Ssam	if (elen) {
6836105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6837105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6838105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6839105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6840105197Ssam
6841105197Ssam		for (i = 1; i <= SADB_EALG_MAX; i++) {
6842105197Ssam			struct enc_xform *ealgo;
6843105197Ssam
6844105197Ssam			ealgo = esp_algorithm_lookup(i);
6845105197Ssam			if (!ealgo)
6846105197Ssam				continue;
6847105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6848105197Ssam			alg->sadb_alg_id = i;
6849105197Ssam			alg->sadb_alg_ivlen = ealgo->blocksize;
6850105197Ssam			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6851105197Ssam			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6852105197Ssam			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6853105197Ssam		}
6854105197Ssam	}
6855105197Ssam
6856120585Ssam	IPSEC_ASSERT(off == len,
6857120585Ssam		("length assumption failed (off %u len %u)", off, len));
6858105197Ssam
6859105197Ssam	m_freem(m);
6860105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6861105197Ssam    }
6862105197Ssam}
6863105197Ssam
6864105197Ssam/*
6865105197Ssam * free secreg entry registered.
6866105197Ssam * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6867105197Ssam */
6868105197Ssamvoid
6869119643Ssamkey_freereg(struct socket *so)
6870105197Ssam{
6871105197Ssam	struct secreg *reg;
6872105197Ssam	int i;
6873105197Ssam
6874120585Ssam	IPSEC_ASSERT(so != NULL, ("NULL so"));
6875105197Ssam
6876105197Ssam	/*
6877105197Ssam	 * check whether existing or not.
6878105197Ssam	 * check all type of SA, because there is a potential that
6879105197Ssam	 * one socket is registered to multiple type of SA.
6880105197Ssam	 */
6881120585Ssam	REGTREE_LOCK();
6882105197Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6883181803Sbz		LIST_FOREACH(reg, &V_regtree[i], chain) {
6884119643Ssam			if (reg->so == so && __LIST_CHAINED(reg)) {
6885105197Ssam				LIST_REMOVE(reg, chain);
6886119643Ssam				free(reg, M_IPSEC_SAR);
6887105197Ssam				break;
6888105197Ssam			}
6889105197Ssam		}
6890105197Ssam	}
6891120585Ssam	REGTREE_UNLOCK();
6892105197Ssam}
6893105197Ssam
6894105197Ssam/*
6895105197Ssam * SADB_EXPIRE processing
6896105197Ssam * send
6897105197Ssam *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6898105197Ssam * to KMD by PF_KEY.
6899105197Ssam * NOTE: We send only soft lifetime extension.
6900105197Ssam *
6901105197Ssam * OUT:	0	: succeed
6902105197Ssam *	others	: error number
6903105197Ssam */
6904105197Ssamstatic int
6905119643Ssamkey_expire(struct secasvar *sav)
6906105197Ssam{
6907105197Ssam	int s;
6908105197Ssam	int satype;
6909105197Ssam	struct mbuf *result = NULL, *m;
6910105197Ssam	int len;
6911105197Ssam	int error = -1;
6912105197Ssam	struct sadb_lifetime *lt;
6913105197Ssam
6914105197Ssam	/* XXX: Why do we lock ? */
6915105197Ssam	s = splnet();	/*called from softclock()*/
6916105197Ssam
6917120585Ssam	IPSEC_ASSERT (sav != NULL, ("null sav"));
6918120585Ssam	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6919105197Ssam
6920105197Ssam	/* set msg header */
6921120585Ssam	satype = key_proto2satype(sav->sah->saidx.proto);
6922120585Ssam	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6923105197Ssam	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6924105197Ssam	if (!m) {
6925105197Ssam		error = ENOBUFS;
6926105197Ssam		goto fail;
6927105197Ssam	}
6928105197Ssam	result = m;
6929105197Ssam
6930105197Ssam	/* create SA extension */
6931105197Ssam	m = key_setsadbsa(sav);
6932105197Ssam	if (!m) {
6933105197Ssam		error = ENOBUFS;
6934105197Ssam		goto fail;
6935105197Ssam	}
6936105197Ssam	m_cat(result, m);
6937105197Ssam
6938105197Ssam	/* create SA extension */
6939105197Ssam	m = key_setsadbxsa2(sav->sah->saidx.mode,
6940105197Ssam			sav->replay ? sav->replay->count : 0,
6941105197Ssam			sav->sah->saidx.reqid);
6942105197Ssam	if (!m) {
6943105197Ssam		error = ENOBUFS;
6944105197Ssam		goto fail;
6945105197Ssam	}
6946105197Ssam	m_cat(result, m);
6947105197Ssam
6948105197Ssam	/* create lifetime extension (current and soft) */
6949105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6950105197Ssam	m = key_alloc_mbuf(len);
6951105197Ssam	if (!m || m->m_next) {	/*XXX*/
6952105197Ssam		if (m)
6953105197Ssam			m_freem(m);
6954105197Ssam		error = ENOBUFS;
6955105197Ssam		goto fail;
6956105197Ssam	}
6957105197Ssam	bzero(mtod(m, caddr_t), len);
6958105197Ssam	lt = mtod(m, struct sadb_lifetime *);
6959105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6960105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6961157123Sgnn	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6962157123Sgnn	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6963157123Sgnn	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6964157123Sgnn	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6965105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6966176743Sbz	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6967176743Sbz	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6968176743Sbz	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6969176743Sbz	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6970176743Sbz	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6971176743Sbz	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6972105197Ssam	m_cat(result, m);
6973105197Ssam
6974105197Ssam	/* set sadb_address for source */
6975105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6976105197Ssam	    &sav->sah->saidx.src.sa,
6977105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6978105197Ssam	if (!m) {
6979105197Ssam		error = ENOBUFS;
6980105197Ssam		goto fail;
6981105197Ssam	}
6982105197Ssam	m_cat(result, m);
6983105197Ssam
6984105197Ssam	/* set sadb_address for destination */
6985105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6986105197Ssam	    &sav->sah->saidx.dst.sa,
6987105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6988105197Ssam	if (!m) {
6989105197Ssam		error = ENOBUFS;
6990105197Ssam		goto fail;
6991105197Ssam	}
6992105197Ssam	m_cat(result, m);
6993105197Ssam
6994194062Svanhu	/*
6995194062Svanhu	 * XXX-BZ Handle NAT-T extensions here.
6996194062Svanhu	 */
6997194062Svanhu
6998105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
6999105197Ssam		error = EINVAL;
7000105197Ssam		goto fail;
7001105197Ssam	}
7002105197Ssam
7003105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
7004105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
7005105197Ssam		if (result == NULL) {
7006105197Ssam			error = ENOBUFS;
7007105197Ssam			goto fail;
7008105197Ssam		}
7009105197Ssam	}
7010105197Ssam
7011105197Ssam	result->m_pkthdr.len = 0;
7012105197Ssam	for (m = result; m; m = m->m_next)
7013105197Ssam		result->m_pkthdr.len += m->m_len;
7014105197Ssam
7015105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
7016105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
7017105197Ssam
7018105197Ssam	splx(s);
7019105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7020105197Ssam
7021105197Ssam fail:
7022105197Ssam	if (result)
7023105197Ssam		m_freem(result);
7024105197Ssam	splx(s);
7025105197Ssam	return error;
7026105197Ssam}
7027105197Ssam
7028105197Ssam/*
7029105197Ssam * SADB_FLUSH processing
7030105197Ssam * receive
7031105197Ssam *   <base>
7032105197Ssam * from the ikmpd, and free all entries in secastree.
7033105197Ssam * and send,
7034105197Ssam *   <base>
7035105197Ssam * to the ikmpd.
7036105197Ssam * NOTE: to do is only marking SADB_SASTATE_DEAD.
7037105197Ssam *
7038105197Ssam * m will always be freed.
7039105197Ssam */
7040105197Ssamstatic int
7041105197Ssamkey_flush(so, m, mhp)
7042105197Ssam	struct socket *so;
7043105197Ssam	struct mbuf *m;
7044105197Ssam	const struct sadb_msghdr *mhp;
7045105197Ssam{
7046105197Ssam	struct sadb_msg *newmsg;
7047105197Ssam	struct secashead *sah, *nextsah;
7048105197Ssam	struct secasvar *sav, *nextsav;
7049105197Ssam	u_int16_t proto;
7050105197Ssam	u_int8_t state;
7051105197Ssam	u_int stateidx;
7052105197Ssam
7053120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7054120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7055120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7056105197Ssam
7057105197Ssam	/* map satype to proto */
7058105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7059120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7060120585Ssam			__func__));
7061105197Ssam		return key_senderror(so, m, EINVAL);
7062105197Ssam	}
7063105197Ssam
7064105197Ssam	/* no SATYPE specified, i.e. flushing all SA. */
7065120585Ssam	SAHTREE_LOCK();
7066181803Sbz	for (sah = LIST_FIRST(&V_sahtree);
7067105197Ssam	     sah != NULL;
7068105197Ssam	     sah = nextsah) {
7069105197Ssam		nextsah = LIST_NEXT(sah, chain);
7070105197Ssam
7071105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7072105197Ssam		 && proto != sah->saidx.proto)
7073105197Ssam			continue;
7074105197Ssam
7075105197Ssam		for (stateidx = 0;
7076185348Szec		     stateidx < _ARRAYLEN(saorder_state_alive);
7077105197Ssam		     stateidx++) {
7078185348Szec			state = saorder_state_any[stateidx];
7079105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
7080105197Ssam			     sav != NULL;
7081105197Ssam			     sav = nextsav) {
7082105197Ssam
7083105197Ssam				nextsav = LIST_NEXT(sav, chain);
7084105197Ssam
7085105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7086105197Ssam				KEY_FREESAV(&sav);
7087105197Ssam			}
7088105197Ssam		}
7089105197Ssam
7090105197Ssam		sah->state = SADB_SASTATE_DEAD;
7091105197Ssam	}
7092120585Ssam	SAHTREE_UNLOCK();
7093105197Ssam
7094105197Ssam	if (m->m_len < sizeof(struct sadb_msg) ||
7095105197Ssam	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7096120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7097105197Ssam		return key_senderror(so, m, ENOBUFS);
7098105197Ssam	}
7099105197Ssam
7100105197Ssam	if (m->m_next)
7101105197Ssam		m_freem(m->m_next);
7102105197Ssam	m->m_next = NULL;
7103105197Ssam	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7104105197Ssam	newmsg = mtod(m, struct sadb_msg *);
7105105197Ssam	newmsg->sadb_msg_errno = 0;
7106105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7107105197Ssam
7108105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7109105197Ssam}
7110105197Ssam
7111105197Ssam/*
7112105197Ssam * SADB_DUMP processing
7113105197Ssam * dump all entries including status of DEAD in SAD.
7114105197Ssam * receive
7115105197Ssam *   <base>
7116105197Ssam * from the ikmpd, and dump all secasvar leaves
7117105197Ssam * and send,
7118105197Ssam *   <base> .....
7119105197Ssam * to the ikmpd.
7120105197Ssam *
7121105197Ssam * m will always be freed.
7122105197Ssam */
7123105197Ssamstatic int
7124105197Ssamkey_dump(so, m, mhp)
7125105197Ssam	struct socket *so;
7126105197Ssam	struct mbuf *m;
7127105197Ssam	const struct sadb_msghdr *mhp;
7128105197Ssam{
7129105197Ssam	struct secashead *sah;
7130105197Ssam	struct secasvar *sav;
7131105197Ssam	u_int16_t proto;
7132105197Ssam	u_int stateidx;
7133105197Ssam	u_int8_t satype;
7134105197Ssam	u_int8_t state;
7135105197Ssam	int cnt;
7136105197Ssam	struct sadb_msg *newmsg;
7137105197Ssam	struct mbuf *n;
7138105197Ssam
7139120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7140120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7141120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7142120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7143105197Ssam
7144105197Ssam	/* map satype to proto */
7145105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7146120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7147120585Ssam			__func__));
7148105197Ssam		return key_senderror(so, m, EINVAL);
7149105197Ssam	}
7150105197Ssam
7151105197Ssam	/* count sav entries to be sent to the userland. */
7152105197Ssam	cnt = 0;
7153120585Ssam	SAHTREE_LOCK();
7154181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7155105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7156105197Ssam		 && proto != sah->saidx.proto)
7157105197Ssam			continue;
7158105197Ssam
7159105197Ssam		for (stateidx = 0;
7160185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
7161105197Ssam		     stateidx++) {
7162185348Szec			state = saorder_state_any[stateidx];
7163105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7164105197Ssam				cnt++;
7165105197Ssam			}
7166105197Ssam		}
7167105197Ssam	}
7168105197Ssam
7169119643Ssam	if (cnt == 0) {
7170120585Ssam		SAHTREE_UNLOCK();
7171105197Ssam		return key_senderror(so, m, ENOENT);
7172119643Ssam	}
7173105197Ssam
7174105197Ssam	/* send this to the userland, one at a time. */
7175105197Ssam	newmsg = NULL;
7176181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7177105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7178105197Ssam		 && proto != sah->saidx.proto)
7179105197Ssam			continue;
7180105197Ssam
7181105197Ssam		/* map proto to satype */
7182105197Ssam		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7183120585Ssam			SAHTREE_UNLOCK();
7184120585Ssam			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7185120585Ssam				"SAD.\n", __func__));
7186105197Ssam			return key_senderror(so, m, EINVAL);
7187105197Ssam		}
7188105197Ssam
7189105197Ssam		for (stateidx = 0;
7190185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
7191105197Ssam		     stateidx++) {
7192185348Szec			state = saorder_state_any[stateidx];
7193105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7194105197Ssam				n = key_setdumpsa(sav, SADB_DUMP, satype,
7195105197Ssam				    --cnt, mhp->msg->sadb_msg_pid);
7196119643Ssam				if (!n) {
7197120585Ssam					SAHTREE_UNLOCK();
7198105197Ssam					return key_senderror(so, m, ENOBUFS);
7199119643Ssam				}
7200105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7201105197Ssam			}
7202105197Ssam		}
7203105197Ssam	}
7204120585Ssam	SAHTREE_UNLOCK();
7205105197Ssam
7206105197Ssam	m_freem(m);
7207105197Ssam	return 0;
7208105197Ssam}
7209105197Ssam
7210105197Ssam/*
7211105197Ssam * SADB_X_PROMISC processing
7212105197Ssam *
7213105197Ssam * m will always be freed.
7214105197Ssam */
7215105197Ssamstatic int
7216105197Ssamkey_promisc(so, m, mhp)
7217105197Ssam	struct socket *so;
7218105197Ssam	struct mbuf *m;
7219105197Ssam	const struct sadb_msghdr *mhp;
7220105197Ssam{
7221105197Ssam	int olen;
7222105197Ssam
7223120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7224120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7225120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7226120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7227105197Ssam
7228105197Ssam	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7229105197Ssam
7230105197Ssam	if (olen < sizeof(struct sadb_msg)) {
7231105197Ssam#if 1
7232105197Ssam		return key_senderror(so, m, EINVAL);
7233105197Ssam#else
7234105197Ssam		m_freem(m);
7235105197Ssam		return 0;
7236105197Ssam#endif
7237105197Ssam	} else if (olen == sizeof(struct sadb_msg)) {
7238105197Ssam		/* enable/disable promisc mode */
7239105197Ssam		struct keycb *kp;
7240105197Ssam
7241105197Ssam		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7242105197Ssam			return key_senderror(so, m, EINVAL);
7243105197Ssam		mhp->msg->sadb_msg_errno = 0;
7244105197Ssam		switch (mhp->msg->sadb_msg_satype) {
7245105197Ssam		case 0:
7246105197Ssam		case 1:
7247105197Ssam			kp->kp_promisc = mhp->msg->sadb_msg_satype;
7248105197Ssam			break;
7249105197Ssam		default:
7250105197Ssam			return key_senderror(so, m, EINVAL);
7251105197Ssam		}
7252105197Ssam
7253105197Ssam		/* send the original message back to everyone */
7254105197Ssam		mhp->msg->sadb_msg_errno = 0;
7255105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7256105197Ssam	} else {
7257105197Ssam		/* send packet as is */
7258105197Ssam
7259105197Ssam		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7260105197Ssam
7261105197Ssam		/* TODO: if sadb_msg_seq is specified, send to specific pid */
7262105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7263105197Ssam	}
7264105197Ssam}
7265105197Ssam
7266105197Ssamstatic int (*key_typesw[]) __P((struct socket *, struct mbuf *,
7267105197Ssam		const struct sadb_msghdr *)) = {
7268105197Ssam	NULL,		/* SADB_RESERVED */
7269105197Ssam	key_getspi,	/* SADB_GETSPI */
7270105197Ssam	key_update,	/* SADB_UPDATE */
7271105197Ssam	key_add,	/* SADB_ADD */
7272105197Ssam	key_delete,	/* SADB_DELETE */
7273105197Ssam	key_get,	/* SADB_GET */
7274105197Ssam	key_acquire2,	/* SADB_ACQUIRE */
7275105197Ssam	key_register,	/* SADB_REGISTER */
7276105197Ssam	NULL,		/* SADB_EXPIRE */
7277105197Ssam	key_flush,	/* SADB_FLUSH */
7278105197Ssam	key_dump,	/* SADB_DUMP */
7279105197Ssam	key_promisc,	/* SADB_X_PROMISC */
7280105197Ssam	NULL,		/* SADB_X_PCHANGE */
7281105197Ssam	key_spdadd,	/* SADB_X_SPDUPDATE */
7282105197Ssam	key_spdadd,	/* SADB_X_SPDADD */
7283105197Ssam	key_spddelete,	/* SADB_X_SPDDELETE */
7284105197Ssam	key_spdget,	/* SADB_X_SPDGET */
7285105197Ssam	NULL,		/* SADB_X_SPDACQUIRE */
7286105197Ssam	key_spddump,	/* SADB_X_SPDDUMP */
7287105197Ssam	key_spdflush,	/* SADB_X_SPDFLUSH */
7288105197Ssam	key_spdadd,	/* SADB_X_SPDSETIDX */
7289105197Ssam	NULL,		/* SADB_X_SPDEXPIRE */
7290105197Ssam	key_spddelete2,	/* SADB_X_SPDDELETE2 */
7291105197Ssam};
7292105197Ssam
7293105197Ssam/*
7294105197Ssam * parse sadb_msg buffer to process PFKEYv2,
7295105197Ssam * and create a data to response if needed.
7296105197Ssam * I think to be dealed with mbuf directly.
7297105197Ssam * IN:
7298105197Ssam *     msgp  : pointer to pointer to a received buffer pulluped.
7299105197Ssam *             This is rewrited to response.
7300105197Ssam *     so    : pointer to socket.
7301105197Ssam * OUT:
7302105197Ssam *    length for buffer to send to user process.
7303105197Ssam */
7304105197Ssamint
7305105197Ssamkey_parse(m, so)
7306105197Ssam	struct mbuf *m;
7307105197Ssam	struct socket *so;
7308105197Ssam{
7309105197Ssam	struct sadb_msg *msg;
7310105197Ssam	struct sadb_msghdr mh;
7311105197Ssam	u_int orglen;
7312105197Ssam	int error;
7313105197Ssam	int target;
7314105197Ssam
7315120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7316120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7317105197Ssam
7318105197Ssam#if 0	/*kdebug_sadb assumes msg in linear buffer*/
7319105197Ssam	KEYDEBUG(KEYDEBUG_KEY_DUMP,
7320120585Ssam		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7321105197Ssam		kdebug_sadb(msg));
7322105197Ssam#endif
7323105197Ssam
7324105197Ssam	if (m->m_len < sizeof(struct sadb_msg)) {
7325105197Ssam		m = m_pullup(m, sizeof(struct sadb_msg));
7326105197Ssam		if (!m)
7327105197Ssam			return ENOBUFS;
7328105197Ssam	}
7329105197Ssam	msg = mtod(m, struct sadb_msg *);
7330105197Ssam	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7331105197Ssam	target = KEY_SENDUP_ONE;
7332105197Ssam
7333105197Ssam	if ((m->m_flags & M_PKTHDR) == 0 ||
7334105197Ssam	    m->m_pkthdr.len != m->m_pkthdr.len) {
7335120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7336181803Sbz		V_pfkeystat.out_invlen++;
7337105197Ssam		error = EINVAL;
7338105197Ssam		goto senderror;
7339105197Ssam	}
7340105197Ssam
7341105197Ssam	if (msg->sadb_msg_version != PF_KEY_V2) {
7342120585Ssam		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7343120585Ssam		    __func__, msg->sadb_msg_version));
7344181803Sbz		V_pfkeystat.out_invver++;
7345105197Ssam		error = EINVAL;
7346105197Ssam		goto senderror;
7347105197Ssam	}
7348105197Ssam
7349105197Ssam	if (msg->sadb_msg_type > SADB_MAX) {
7350120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7351120585Ssam		    __func__, msg->sadb_msg_type));
7352181803Sbz		V_pfkeystat.out_invmsgtype++;
7353105197Ssam		error = EINVAL;
7354105197Ssam		goto senderror;
7355105197Ssam	}
7356105197Ssam
7357105197Ssam	/* for old-fashioned code - should be nuked */
7358105197Ssam	if (m->m_pkthdr.len > MCLBYTES) {
7359105197Ssam		m_freem(m);
7360105197Ssam		return ENOBUFS;
7361105197Ssam	}
7362105197Ssam	if (m->m_next) {
7363105197Ssam		struct mbuf *n;
7364105197Ssam
7365111119Simp		MGETHDR(n, M_DONTWAIT, MT_DATA);
7366105197Ssam		if (n && m->m_pkthdr.len > MHLEN) {
7367111119Simp			MCLGET(n, M_DONTWAIT);
7368105197Ssam			if ((n->m_flags & M_EXT) == 0) {
7369105197Ssam				m_free(n);
7370105197Ssam				n = NULL;
7371105197Ssam			}
7372105197Ssam		}
7373105197Ssam		if (!n) {
7374105197Ssam			m_freem(m);
7375105197Ssam			return ENOBUFS;
7376105197Ssam		}
7377105197Ssam		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7378105197Ssam		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7379105197Ssam		n->m_next = NULL;
7380105197Ssam		m_freem(m);
7381105197Ssam		m = n;
7382105197Ssam	}
7383105197Ssam
7384105197Ssam	/* align the mbuf chain so that extensions are in contiguous region. */
7385105197Ssam	error = key_align(m, &mh);
7386105197Ssam	if (error)
7387105197Ssam		return error;
7388105197Ssam
7389105197Ssam	msg = mh.msg;
7390105197Ssam
7391105197Ssam	/* check SA type */
7392105197Ssam	switch (msg->sadb_msg_satype) {
7393105197Ssam	case SADB_SATYPE_UNSPEC:
7394105197Ssam		switch (msg->sadb_msg_type) {
7395105197Ssam		case SADB_GETSPI:
7396105197Ssam		case SADB_UPDATE:
7397105197Ssam		case SADB_ADD:
7398105197Ssam		case SADB_DELETE:
7399105197Ssam		case SADB_GET:
7400105197Ssam		case SADB_ACQUIRE:
7401105197Ssam		case SADB_EXPIRE:
7402120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify satype "
7403120585Ssam			    "when msg type=%u.\n", __func__,
7404120585Ssam			    msg->sadb_msg_type));
7405181803Sbz			V_pfkeystat.out_invsatype++;
7406105197Ssam			error = EINVAL;
7407105197Ssam			goto senderror;
7408105197Ssam		}
7409105197Ssam		break;
7410105197Ssam	case SADB_SATYPE_AH:
7411105197Ssam	case SADB_SATYPE_ESP:
7412105197Ssam	case SADB_X_SATYPE_IPCOMP:
7413125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
7414105197Ssam		switch (msg->sadb_msg_type) {
7415105197Ssam		case SADB_X_SPDADD:
7416105197Ssam		case SADB_X_SPDDELETE:
7417105197Ssam		case SADB_X_SPDGET:
7418105197Ssam		case SADB_X_SPDDUMP:
7419105197Ssam		case SADB_X_SPDFLUSH:
7420105197Ssam		case SADB_X_SPDSETIDX:
7421105197Ssam		case SADB_X_SPDUPDATE:
7422105197Ssam		case SADB_X_SPDDELETE2:
7423120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7424120585Ssam				__func__, msg->sadb_msg_type));
7425181803Sbz			V_pfkeystat.out_invsatype++;
7426105197Ssam			error = EINVAL;
7427105197Ssam			goto senderror;
7428105197Ssam		}
7429105197Ssam		break;
7430105197Ssam	case SADB_SATYPE_RSVP:
7431105197Ssam	case SADB_SATYPE_OSPFV2:
7432105197Ssam	case SADB_SATYPE_RIPV2:
7433105197Ssam	case SADB_SATYPE_MIP:
7434120585Ssam		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7435120585Ssam			__func__, msg->sadb_msg_satype));
7436181803Sbz		V_pfkeystat.out_invsatype++;
7437105197Ssam		error = EOPNOTSUPP;
7438105197Ssam		goto senderror;
7439105197Ssam	case 1:	/* XXX: What does it do? */
7440105197Ssam		if (msg->sadb_msg_type == SADB_X_PROMISC)
7441105197Ssam			break;
7442105197Ssam		/*FALLTHROUGH*/
7443105197Ssam	default:
7444120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7445120585Ssam			__func__, msg->sadb_msg_satype));
7446181803Sbz		V_pfkeystat.out_invsatype++;
7447105197Ssam		error = EINVAL;
7448105197Ssam		goto senderror;
7449105197Ssam	}
7450105197Ssam
7451105197Ssam	/* check field of upper layer protocol and address family */
7452105197Ssam	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7453105197Ssam	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7454105197Ssam		struct sadb_address *src0, *dst0;
7455105197Ssam		u_int plen;
7456105197Ssam
7457105197Ssam		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7458105197Ssam		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7459105197Ssam
7460105197Ssam		/* check upper layer protocol */
7461105197Ssam		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7462120585Ssam			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7463120585Ssam				"mismatched.\n", __func__));
7464181803Sbz			V_pfkeystat.out_invaddr++;
7465105197Ssam			error = EINVAL;
7466105197Ssam			goto senderror;
7467105197Ssam		}
7468105197Ssam
7469105197Ssam		/* check family */
7470105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7471105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
7472120585Ssam			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7473120585Ssam				__func__));
7474181803Sbz			V_pfkeystat.out_invaddr++;
7475105197Ssam			error = EINVAL;
7476105197Ssam			goto senderror;
7477105197Ssam		}
7478105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7479105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
7480120585Ssam			ipseclog((LOG_DEBUG, "%s: address struct size "
7481120585Ssam				"mismatched.\n", __func__));
7482181803Sbz			V_pfkeystat.out_invaddr++;
7483105197Ssam			error = EINVAL;
7484105197Ssam			goto senderror;
7485105197Ssam		}
7486105197Ssam
7487105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7488105197Ssam		case AF_INET:
7489105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7490105197Ssam			    sizeof(struct sockaddr_in)) {
7491181803Sbz				V_pfkeystat.out_invaddr++;
7492105197Ssam				error = EINVAL;
7493105197Ssam				goto senderror;
7494105197Ssam			}
7495105197Ssam			break;
7496105197Ssam		case AF_INET6:
7497105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7498105197Ssam			    sizeof(struct sockaddr_in6)) {
7499181803Sbz				V_pfkeystat.out_invaddr++;
7500105197Ssam				error = EINVAL;
7501105197Ssam				goto senderror;
7502105197Ssam			}
7503105197Ssam			break;
7504105197Ssam		default:
7505120585Ssam			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7506120585Ssam				__func__));
7507181803Sbz			V_pfkeystat.out_invaddr++;
7508105197Ssam			error = EAFNOSUPPORT;
7509105197Ssam			goto senderror;
7510105197Ssam		}
7511105197Ssam
7512105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7513105197Ssam		case AF_INET:
7514105197Ssam			plen = sizeof(struct in_addr) << 3;
7515105197Ssam			break;
7516105197Ssam		case AF_INET6:
7517105197Ssam			plen = sizeof(struct in6_addr) << 3;
7518105197Ssam			break;
7519105197Ssam		default:
7520105197Ssam			plen = 0;	/*fool gcc*/
7521105197Ssam			break;
7522105197Ssam		}
7523105197Ssam
7524105197Ssam		/* check max prefix length */
7525105197Ssam		if (src0->sadb_address_prefixlen > plen ||
7526105197Ssam		    dst0->sadb_address_prefixlen > plen) {
7527120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7528120585Ssam				__func__));
7529181803Sbz			V_pfkeystat.out_invaddr++;
7530105197Ssam			error = EINVAL;
7531105197Ssam			goto senderror;
7532105197Ssam		}
7533105197Ssam
7534105197Ssam		/*
7535105197Ssam		 * prefixlen == 0 is valid because there can be a case when
7536105197Ssam		 * all addresses are matched.
7537105197Ssam		 */
7538105197Ssam	}
7539105197Ssam
7540105197Ssam	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7541105197Ssam	    key_typesw[msg->sadb_msg_type] == NULL) {
7542181803Sbz		V_pfkeystat.out_invmsgtype++;
7543105197Ssam		error = EINVAL;
7544105197Ssam		goto senderror;
7545105197Ssam	}
7546105197Ssam
7547105197Ssam	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7548105197Ssam
7549105197Ssamsenderror:
7550105197Ssam	msg->sadb_msg_errno = error;
7551105197Ssam	return key_sendup_mbuf(so, m, target);
7552105197Ssam}
7553105197Ssam
7554105197Ssamstatic int
7555105197Ssamkey_senderror(so, m, code)
7556105197Ssam	struct socket *so;
7557105197Ssam	struct mbuf *m;
7558105197Ssam	int code;
7559105197Ssam{
7560105197Ssam	struct sadb_msg *msg;
7561105197Ssam
7562120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7563120585Ssam		("mbuf too small, len %u", m->m_len));
7564105197Ssam
7565105197Ssam	msg = mtod(m, struct sadb_msg *);
7566105197Ssam	msg->sadb_msg_errno = code;
7567105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7568105197Ssam}
7569105197Ssam
7570105197Ssam/*
7571105197Ssam * set the pointer to each header into message buffer.
7572105197Ssam * m will be freed on error.
7573105197Ssam * XXX larger-than-MCLBYTES extension?
7574105197Ssam */
7575105197Ssamstatic int
7576105197Ssamkey_align(m, mhp)
7577105197Ssam	struct mbuf *m;
7578105197Ssam	struct sadb_msghdr *mhp;
7579105197Ssam{
7580105197Ssam	struct mbuf *n;
7581105197Ssam	struct sadb_ext *ext;
7582105197Ssam	size_t off, end;
7583105197Ssam	int extlen;
7584105197Ssam	int toff;
7585105197Ssam
7586120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7587120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7588120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7589120585Ssam		("mbuf too small, len %u", m->m_len));
7590105197Ssam
7591105197Ssam	/* initialize */
7592105197Ssam	bzero(mhp, sizeof(*mhp));
7593105197Ssam
7594105197Ssam	mhp->msg = mtod(m, struct sadb_msg *);
7595105197Ssam	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7596105197Ssam
7597105197Ssam	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7598105197Ssam	extlen = end;	/*just in case extlen is not updated*/
7599105197Ssam	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7600105197Ssam		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7601105197Ssam		if (!n) {
7602105197Ssam			/* m is already freed */
7603105197Ssam			return ENOBUFS;
7604105197Ssam		}
7605105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7606105197Ssam
7607105197Ssam		/* set pointer */
7608105197Ssam		switch (ext->sadb_ext_type) {
7609105197Ssam		case SADB_EXT_SA:
7610105197Ssam		case SADB_EXT_ADDRESS_SRC:
7611105197Ssam		case SADB_EXT_ADDRESS_DST:
7612105197Ssam		case SADB_EXT_ADDRESS_PROXY:
7613105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
7614105197Ssam		case SADB_EXT_LIFETIME_HARD:
7615105197Ssam		case SADB_EXT_LIFETIME_SOFT:
7616105197Ssam		case SADB_EXT_KEY_AUTH:
7617105197Ssam		case SADB_EXT_KEY_ENCRYPT:
7618105197Ssam		case SADB_EXT_IDENTITY_SRC:
7619105197Ssam		case SADB_EXT_IDENTITY_DST:
7620105197Ssam		case SADB_EXT_SENSITIVITY:
7621105197Ssam		case SADB_EXT_PROPOSAL:
7622105197Ssam		case SADB_EXT_SUPPORTED_AUTH:
7623105197Ssam		case SADB_EXT_SUPPORTED_ENCRYPT:
7624105197Ssam		case SADB_EXT_SPIRANGE:
7625105197Ssam		case SADB_X_EXT_POLICY:
7626105197Ssam		case SADB_X_EXT_SA2:
7627194062Svanhu#ifdef IPSEC_NAT_T
7628194062Svanhu		case SADB_X_EXT_NAT_T_TYPE:
7629194062Svanhu		case SADB_X_EXT_NAT_T_SPORT:
7630194062Svanhu		case SADB_X_EXT_NAT_T_DPORT:
7631194062Svanhu		case SADB_X_EXT_NAT_T_OAI:
7632194062Svanhu		case SADB_X_EXT_NAT_T_OAR:
7633194062Svanhu		case SADB_X_EXT_NAT_T_FRAG:
7634194062Svanhu#endif
7635105197Ssam			/* duplicate check */
7636105197Ssam			/*
7637105197Ssam			 * XXX Are there duplication payloads of either
7638105197Ssam			 * KEY_AUTH or KEY_ENCRYPT ?
7639105197Ssam			 */
7640105197Ssam			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7641120585Ssam				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7642120585Ssam					"%u\n", __func__, ext->sadb_ext_type));
7643105197Ssam				m_freem(m);
7644181803Sbz				V_pfkeystat.out_dupext++;
7645105197Ssam				return EINVAL;
7646105197Ssam			}
7647105197Ssam			break;
7648105197Ssam		default:
7649120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7650120585Ssam				__func__, ext->sadb_ext_type));
7651105197Ssam			m_freem(m);
7652181803Sbz			V_pfkeystat.out_invexttype++;
7653105197Ssam			return EINVAL;
7654105197Ssam		}
7655105197Ssam
7656105197Ssam		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7657105197Ssam
7658105197Ssam		if (key_validate_ext(ext, extlen)) {
7659105197Ssam			m_freem(m);
7660181803Sbz			V_pfkeystat.out_invlen++;
7661105197Ssam			return EINVAL;
7662105197Ssam		}
7663105197Ssam
7664105197Ssam		n = m_pulldown(m, off, extlen, &toff);
7665105197Ssam		if (!n) {
7666105197Ssam			/* m is already freed */
7667105197Ssam			return ENOBUFS;
7668105197Ssam		}
7669105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7670105197Ssam
7671105197Ssam		mhp->ext[ext->sadb_ext_type] = ext;
7672105197Ssam		mhp->extoff[ext->sadb_ext_type] = off;
7673105197Ssam		mhp->extlen[ext->sadb_ext_type] = extlen;
7674105197Ssam	}
7675105197Ssam
7676105197Ssam	if (off != end) {
7677105197Ssam		m_freem(m);
7678181803Sbz		V_pfkeystat.out_invlen++;
7679105197Ssam		return EINVAL;
7680105197Ssam	}
7681105197Ssam
7682105197Ssam	return 0;
7683105197Ssam}
7684105197Ssam
7685105197Ssamstatic int
7686105197Ssamkey_validate_ext(ext, len)
7687105197Ssam	const struct sadb_ext *ext;
7688105197Ssam	int len;
7689105197Ssam{
7690105197Ssam	const struct sockaddr *sa;
7691105197Ssam	enum { NONE, ADDR } checktype = NONE;
7692105197Ssam	int baselen = 0;
7693105197Ssam	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7694105197Ssam
7695105197Ssam	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7696105197Ssam		return EINVAL;
7697105197Ssam
7698105197Ssam	/* if it does not match minimum/maximum length, bail */
7699105197Ssam	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7700105197Ssam	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7701105197Ssam		return EINVAL;
7702105197Ssam	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7703105197Ssam		return EINVAL;
7704105197Ssam	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7705105197Ssam		return EINVAL;
7706105197Ssam
7707105197Ssam	/* more checks based on sadb_ext_type XXX need more */
7708105197Ssam	switch (ext->sadb_ext_type) {
7709105197Ssam	case SADB_EXT_ADDRESS_SRC:
7710105197Ssam	case SADB_EXT_ADDRESS_DST:
7711105197Ssam	case SADB_EXT_ADDRESS_PROXY:
7712105197Ssam		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7713105197Ssam		checktype = ADDR;
7714105197Ssam		break;
7715105197Ssam	case SADB_EXT_IDENTITY_SRC:
7716105197Ssam	case SADB_EXT_IDENTITY_DST:
7717105197Ssam		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7718105197Ssam		    SADB_X_IDENTTYPE_ADDR) {
7719105197Ssam			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7720105197Ssam			checktype = ADDR;
7721105197Ssam		} else
7722105197Ssam			checktype = NONE;
7723105197Ssam		break;
7724105197Ssam	default:
7725105197Ssam		checktype = NONE;
7726105197Ssam		break;
7727105197Ssam	}
7728105197Ssam
7729105197Ssam	switch (checktype) {
7730105197Ssam	case NONE:
7731105197Ssam		break;
7732105197Ssam	case ADDR:
7733105197Ssam		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7734105197Ssam		if (len < baselen + sal)
7735105197Ssam			return EINVAL;
7736105197Ssam		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7737105197Ssam			return EINVAL;
7738105197Ssam		break;
7739105197Ssam	}
7740105197Ssam
7741105197Ssam	return 0;
7742105197Ssam}
7743105197Ssam
7744105197Ssamvoid
7745180086Sjuliankey_init(void)
7746105197Ssam{
7747105197Ssam	int i;
7748105197Ssam
7749119643Ssam	for (i = 0; i < IPSEC_DIR_MAX; i++)
7750181803Sbz		LIST_INIT(&V_sptree[i]);
7751105197Ssam
7752181803Sbz	LIST_INIT(&V_sahtree);
7753105197Ssam
7754119643Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7755181803Sbz		LIST_INIT(&V_regtree[i]);
7756105197Ssam
7757181803Sbz	LIST_INIT(&V_acqtree);
7758181803Sbz	LIST_INIT(&V_spacqtree);
7759105197Ssam
7760105197Ssam	/* system default */
7761181803Sbz	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7762181803Sbz	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7763105197Ssam
7764190787Szec	if (!IS_DEFAULT_VNET(curvnet))
7765190787Szec		return;
7766190787Szec
7767190787Szec	SPTREE_LOCK_INIT();
7768190787Szec	REGTREE_LOCK_INIT();
7769190787Szec	SAHTREE_LOCK_INIT();
7770190787Szec	ACQ_LOCK_INIT();
7771190787Szec	SPACQ_LOCK_INIT();
7772190787Szec
7773105197Ssam#ifndef IPSEC_DEBUG2
7774105197Ssam	timeout((void *)key_timehandler, (void *)0, hz);
7775105197Ssam#endif /*IPSEC_DEBUG2*/
7776105197Ssam
7777105197Ssam	/* initialize key statistics */
7778105197Ssam	keystat.getspi_count = 1;
7779105197Ssam
7780177173Sbz	printf("IPsec: Initialized Security Association Processing.\n");
7781193731Szec}
7782105197Ssam
7783193731Szec#ifdef VIMAGE
7784193731Szecvoid
7785193731Szeckey_destroy(void)
7786193731Szec{
7787193731Szec	struct secpolicy *sp, *nextsp;
7788205789Sbz	struct secacq *acq, *nextacq;
7789205789Sbz	struct secspacq *spacq, *nextspacq;
7790193731Szec	struct secashead *sah, *nextsah;
7791193731Szec	struct secreg *reg;
7792193731Szec	int i;
7793193731Szec
7794193731Szec	SPTREE_LOCK();
7795193731Szec	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7796193731Szec		for (sp = LIST_FIRST(&V_sptree[i]);
7797193731Szec		    sp != NULL; sp = nextsp) {
7798193731Szec			nextsp = LIST_NEXT(sp, chain);
7799193731Szec			if (__LIST_CHAINED(sp)) {
7800193731Szec				LIST_REMOVE(sp, chain);
7801193731Szec				free(sp, M_IPSEC_SP);
7802193731Szec			}
7803193731Szec		}
7804193731Szec	}
7805193731Szec	SPTREE_UNLOCK();
7806193731Szec
7807193731Szec	SAHTREE_LOCK();
7808193731Szec	for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7809193731Szec		nextsah = LIST_NEXT(sah, chain);
7810193731Szec		if (__LIST_CHAINED(sah)) {
7811193731Szec			LIST_REMOVE(sah, chain);
7812193731Szec			free(sah, M_IPSEC_SAH);
7813193731Szec		}
7814193731Szec	}
7815193731Szec	SAHTREE_UNLOCK();
7816193731Szec
7817193731Szec	REGTREE_LOCK();
7818193731Szec	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7819193731Szec		LIST_FOREACH(reg, &V_regtree[i], chain) {
7820193731Szec			if (__LIST_CHAINED(reg)) {
7821193731Szec				LIST_REMOVE(reg, chain);
7822193731Szec				free(reg, M_IPSEC_SAR);
7823193731Szec				break;
7824193731Szec			}
7825193731Szec		}
7826193731Szec	}
7827193731Szec	REGTREE_UNLOCK();
7828193731Szec
7829193731Szec	ACQ_LOCK();
7830205789Sbz	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
7831193731Szec		nextacq = LIST_NEXT(acq, chain);
7832193731Szec		if (__LIST_CHAINED(acq)) {
7833193731Szec			LIST_REMOVE(acq, chain);
7834193731Szec			free(acq, M_IPSEC_SAQ);
7835193731Szec		}
7836193731Szec	}
7837193731Szec	ACQ_UNLOCK();
7838193731Szec
7839193731Szec	SPACQ_LOCK();
7840205789Sbz	for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
7841205789Sbz	    spacq = nextspacq) {
7842205789Sbz		nextspacq = LIST_NEXT(spacq, chain);
7843205789Sbz		if (__LIST_CHAINED(spacq)) {
7844205789Sbz			LIST_REMOVE(spacq, chain);
7845205789Sbz			free(spacq, M_IPSEC_SAQ);
7846193731Szec		}
7847193731Szec	}
7848193731Szec	SPACQ_UNLOCK();
7849105197Ssam}
7850193731Szec#endif
7851105197Ssam
7852105197Ssam/*
7853105197Ssam * XXX: maybe This function is called after INBOUND IPsec processing.
7854105197Ssam *
7855105197Ssam * Special check for tunnel-mode packets.
7856105197Ssam * We must make some checks for consistency between inner and outer IP header.
7857105197Ssam *
7858105197Ssam * xxx more checks to be provided
7859105197Ssam */
7860105197Ssamint
7861105197Ssamkey_checktunnelsanity(sav, family, src, dst)
7862105197Ssam	struct secasvar *sav;
7863105197Ssam	u_int family;
7864105197Ssam	caddr_t src;
7865105197Ssam	caddr_t dst;
7866105197Ssam{
7867120585Ssam	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7868105197Ssam
7869105197Ssam	/* XXX: check inner IP header */
7870105197Ssam
7871105197Ssam	return 1;
7872105197Ssam}
7873105197Ssam
7874105197Ssam/* record data transfer on SA, and update timestamps */
7875105197Ssamvoid
7876105197Ssamkey_sa_recordxfer(sav, m)
7877105197Ssam	struct secasvar *sav;
7878105197Ssam	struct mbuf *m;
7879105197Ssam{
7880120585Ssam	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7881120585Ssam	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7882105197Ssam	if (!sav->lft_c)
7883105197Ssam		return;
7884105197Ssam
7885105197Ssam	/*
7886105197Ssam	 * XXX Currently, there is a difference of bytes size
7887105197Ssam	 * between inbound and outbound processing.
7888105197Ssam	 */
7889157123Sgnn	sav->lft_c->bytes += m->m_pkthdr.len;
7890105197Ssam	/* to check bytes lifetime is done in key_timehandler(). */
7891105197Ssam
7892105197Ssam	/*
7893105197Ssam	 * We use the number of packets as the unit of
7894157123Sgnn	 * allocations.  We increment the variable
7895105197Ssam	 * whenever {esp,ah}_{in,out}put is called.
7896105197Ssam	 */
7897157123Sgnn	sav->lft_c->allocations++;
7898105197Ssam	/* XXX check for expires? */
7899105197Ssam
7900105197Ssam	/*
7901157123Sgnn	 * NOTE: We record CURRENT usetime by using wall clock,
7902105197Ssam	 * in seconds.  HARD and SOFT lifetime are measured by the time
7903157123Sgnn	 * difference (again in seconds) from usetime.
7904105197Ssam	 *
7905105197Ssam	 *	usetime
7906105197Ssam	 *	v     expire   expire
7907105197Ssam	 * -----+-----+--------+---> t
7908105197Ssam	 *	<--------------> HARD
7909105197Ssam	 *	<-----> SOFT
7910105197Ssam	 */
7911157123Sgnn	sav->lft_c->usetime = time_second;
7912105197Ssam	/* XXX check for expires? */
7913105197Ssam
7914105197Ssam	return;
7915105197Ssam}
7916105197Ssam
7917105197Ssam/* dumb version */
7918105197Ssamvoid
7919105197Ssamkey_sa_routechange(dst)
7920105197Ssam	struct sockaddr *dst;
7921105197Ssam{
7922105197Ssam	struct secashead *sah;
7923105197Ssam	struct route *ro;
7924105197Ssam
7925120585Ssam	SAHTREE_LOCK();
7926181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7927105197Ssam		ro = &sah->sa_route;
7928105197Ssam		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7929105197Ssam		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7930105197Ssam			RTFREE(ro->ro_rt);
7931105197Ssam			ro->ro_rt = (struct rtentry *)NULL;
7932105197Ssam		}
7933105197Ssam	}
7934120585Ssam	SAHTREE_UNLOCK();
7935105197Ssam}
7936105197Ssam
7937105197Ssamstatic void
7938189004Srdivackykey_sa_chgstate(struct secasvar *sav, u_int8_t state)
7939105197Ssam{
7940120585Ssam	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7941120585Ssam	SAHTREE_LOCK_ASSERT();
7942105197Ssam
7943119643Ssam	if (sav->state != state) {
7944119643Ssam		if (__LIST_CHAINED(sav))
7945119643Ssam			LIST_REMOVE(sav, chain);
7946119643Ssam		sav->state = state;
7947119643Ssam		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7948119643Ssam	}
7949105197Ssam}
7950105197Ssam
7951105197Ssamvoid
7952105197Ssamkey_sa_stir_iv(sav)
7953105197Ssam	struct secasvar *sav;
7954105197Ssam{
7955105197Ssam
7956120585Ssam	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7957105197Ssam	key_randomfill(sav->iv, sav->ivlen);
7958105197Ssam}
7959105197Ssam
7960105197Ssam/* XXX too much? */
7961105197Ssamstatic struct mbuf *
7962105197Ssamkey_alloc_mbuf(l)
7963105197Ssam	int l;
7964105197Ssam{
7965105197Ssam	struct mbuf *m = NULL, *n;
7966105197Ssam	int len, t;
7967105197Ssam
7968105197Ssam	len = l;
7969105197Ssam	while (len > 0) {
7970111119Simp		MGET(n, M_DONTWAIT, MT_DATA);
7971105197Ssam		if (n && len > MLEN)
7972111119Simp			MCLGET(n, M_DONTWAIT);
7973105197Ssam		if (!n) {
7974105197Ssam			m_freem(m);
7975105197Ssam			return NULL;
7976105197Ssam		}
7977105197Ssam
7978105197Ssam		n->m_next = NULL;
7979105197Ssam		n->m_len = 0;
7980105197Ssam		n->m_len = M_TRAILINGSPACE(n);
7981105197Ssam		/* use the bottom of mbuf, hoping we can prepend afterwards */
7982105197Ssam		if (n->m_len > len) {
7983105197Ssam			t = (n->m_len - len) & ~(sizeof(long) - 1);
7984105197Ssam			n->m_data += t;
7985105197Ssam			n->m_len = len;
7986105197Ssam		}
7987105197Ssam
7988105197Ssam		len -= n->m_len;
7989105197Ssam
7990105197Ssam		if (m)
7991105197Ssam			m_cat(m, n);
7992105197Ssam		else
7993105197Ssam			m = n;
7994105197Ssam	}
7995105197Ssam
7996105197Ssam	return m;
7997105197Ssam}
7998157123Sgnn
7999157123Sgnn/*
8000157123Sgnn * Take one of the kernel's security keys and convert it into a PF_KEY
8001157123Sgnn * structure within an mbuf, suitable for sending up to a waiting
8002157123Sgnn * application in user land.
8003157123Sgnn *
8004157123Sgnn * IN:
8005157123Sgnn *    src: A pointer to a kernel security key.
8006157123Sgnn *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
8007157123Sgnn * OUT:
8008157123Sgnn *    a valid mbuf or NULL indicating an error
8009157123Sgnn *
8010157123Sgnn */
8011157123Sgnn
8012157123Sgnnstatic struct mbuf *
8013157123Sgnnkey_setkey(struct seckey *src, u_int16_t exttype)
8014157123Sgnn{
8015157123Sgnn	struct mbuf *m;
8016157123Sgnn	struct sadb_key *p;
8017170799Sbz	int len;
8018157123Sgnn
8019157123Sgnn	if (src == NULL)
8020157123Sgnn		return NULL;
8021157123Sgnn
8022170799Sbz	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8023157123Sgnn	m = key_alloc_mbuf(len);
8024157123Sgnn	if (m == NULL)
8025157123Sgnn		return NULL;
8026157123Sgnn	p = mtod(m, struct sadb_key *);
8027157123Sgnn	bzero(p, len);
8028157123Sgnn	p->sadb_key_len = PFKEY_UNIT64(len);
8029157123Sgnn	p->sadb_key_exttype = exttype;
8030157123Sgnn	p->sadb_key_bits = src->bits;
8031157123Sgnn	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8032157123Sgnn
8033157123Sgnn	return m;
8034157123Sgnn}
8035157123Sgnn
8036157123Sgnn/*
8037157123Sgnn * Take one of the kernel's lifetime data structures and convert it
8038157123Sgnn * into a PF_KEY structure within an mbuf, suitable for sending up to
8039157123Sgnn * a waiting application in user land.
8040157123Sgnn *
8041157123Sgnn * IN:
8042157123Sgnn *    src: A pointer to a kernel lifetime structure.
8043157123Sgnn *    exttype: Which type of lifetime this is. Refer to the PF_KEY
8044157123Sgnn *             data structures for more information.
8045157123Sgnn * OUT:
8046157123Sgnn *    a valid mbuf or NULL indicating an error
8047157123Sgnn *
8048157123Sgnn */
8049157123Sgnn
8050157123Sgnnstatic struct mbuf *
8051157123Sgnnkey_setlifetime(struct seclifetime *src, u_int16_t exttype)
8052157123Sgnn{
8053157123Sgnn	struct mbuf *m = NULL;
8054157123Sgnn	struct sadb_lifetime *p;
8055157123Sgnn	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8056157123Sgnn
8057157123Sgnn	if (src == NULL)
8058157123Sgnn		return NULL;
8059157123Sgnn
8060157123Sgnn	m = key_alloc_mbuf(len);
8061157123Sgnn	if (m == NULL)
8062157123Sgnn		return m;
8063157123Sgnn	p = mtod(m, struct sadb_lifetime *);
8064157123Sgnn
8065157123Sgnn	bzero(p, len);
8066157123Sgnn	p->sadb_lifetime_len = PFKEY_UNIT64(len);
8067157123Sgnn	p->sadb_lifetime_exttype = exttype;
8068157123Sgnn	p->sadb_lifetime_allocations = src->allocations;
8069157123Sgnn	p->sadb_lifetime_bytes = src->bytes;
8070157123Sgnn	p->sadb_lifetime_addtime = src->addtime;
8071157123Sgnn	p->sadb_lifetime_usetime = src->usetime;
8072157123Sgnn
8073157123Sgnn	return m;
8074157123Sgnn
8075157123Sgnn}
8076