1105197Ssam/*	$FreeBSD$	*/
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
76221129Sbz#if defined(INET) || defined(INET6)
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;
116215701Sdimstatic VNET_DEFINE(u_int, key_spi_trycnt) = 1000;
117215701Sdimstatic VNET_DEFINE(u_int32_t, key_spi_minval) = 0x100;
118215701Sdimstatic VNET_DEFINE(u_int32_t, key_spi_maxval) = 0x0fffffff;	/* XXX */
119215701Sdimstatic VNET_DEFINE(u_int32_t, policy_id) = 0;
120195699Srwatson/*interval to initialize randseed,1(m)*/
121215701Sdimstatic VNET_DEFINE(u_int, key_int_random) = 60;
122195699Srwatson/* interval to expire acquiring, 30(s)*/
123215701Sdimstatic VNET_DEFINE(u_int, key_larval_lifetime) = 30;
124195699Srwatson/* counter for blocking SADB_ACQUIRE.*/
125215701Sdimstatic VNET_DEFINE(int, key_blockacq_count) = 10;
126195699Srwatson/* lifetime for blocking SADB_ACQUIRE.*/
127215701Sdimstatic VNET_DEFINE(int, key_blockacq_lifetime) = 20;
128195699Srwatson/* preferred old sa rather than new sa.*/
129215701Sdimstatic VNET_DEFINE(int, key_preferred_oldsa) = 1;
130207369Sbz#define	V_key_spi_trycnt	VNET(key_spi_trycnt)
131207369Sbz#define	V_key_spi_minval	VNET(key_spi_minval)
132207369Sbz#define	V_key_spi_maxval	VNET(key_spi_maxval)
133207369Sbz#define	V_policy_id		VNET(policy_id)
134207369Sbz#define	V_key_int_random	VNET(key_int_random)
135207369Sbz#define	V_key_larval_lifetime	VNET(key_larval_lifetime)
136207369Sbz#define	V_key_blockacq_count	VNET(key_blockacq_count)
137207369Sbz#define	V_key_blockacq_lifetime	VNET(key_blockacq_lifetime)
138195727Srwatson#define	V_key_preferred_oldsa	VNET(key_preferred_oldsa)
139105197Ssam
140215701Sdimstatic VNET_DEFINE(u_int32_t, acq_seq) = 0;
141195727Srwatson#define	V_acq_seq		VNET(acq_seq)
142105197Ssam
143195699Srwatson								/* SPD */
144215701Sdimstatic 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
155215701Sdimstatic 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 */
167215701Sdimstatic 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
177215701Sdimstatic 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 */
188215701Sdimstatic 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
272215701Sdimstatic VNET_DEFINE(int, ipsec_esp_keymin) = 256;
273215701Sdimstatic VNET_DEFINE(int, ipsec_esp_auth) = 0;
274215701Sdimstatic VNET_DEFINE(int, ipsec_ah_keymin) = 128;
275207369Sbz
276195727Srwatson#define	V_ipsec_esp_keymin	VNET(ipsec_esp_keymin)
277195727Srwatson#define	V_ipsec_esp_auth	VNET(ipsec_esp_auth)
278195727Srwatson#define	V_ipsec_ah_keymin	VNET(ipsec_ah_keymin)
279195699Srwatson
280105197Ssam#ifdef SYSCTL_DECL
281105197SsamSYSCTL_DECL(_net_key);
282105197Ssam#endif
283105197Ssam
284195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,
285195699Srwatson	CTLFLAG_RW, &VNET_NAME(key_debug_level),	0,	"");
286105197Ssam
287105197Ssam/* max count of trial for the decision of spi value */
288195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
289195699Srwatson	CTLFLAG_RW, &VNET_NAME(key_spi_trycnt),	0,	"");
290105197Ssam
291105197Ssam/* minimum spi value to allocate automatically. */
292195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MIN_VALUE,
293195699Srwatson	spi_minval,	CTLFLAG_RW, &VNET_NAME(key_spi_minval),	0,	"");
294105197Ssam
295105197Ssam/* maximun spi value to allocate automatically. */
296195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MAX_VALUE,
297195699Srwatson	spi_maxval,	CTLFLAG_RW, &VNET_NAME(key_spi_maxval),	0,	"");
298105197Ssam
299105197Ssam/* interval to initialize randseed */
300195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_RANDOM_INT,
301195699Srwatson	int_random,	CTLFLAG_RW, &VNET_NAME(key_int_random),	0,	"");
302105197Ssam
303105197Ssam/* lifetime for larval SA */
304195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_LARVAL_LIFETIME,
305195699Srwatson	larval_lifetime, CTLFLAG_RW, &VNET_NAME(key_larval_lifetime),	0, "");
306105197Ssam
307105197Ssam/* counter for blocking to send SADB_ACQUIRE to IKEd */
308195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,
309195699Srwatson	blockacq_count,	CTLFLAG_RW, &VNET_NAME(key_blockacq_count),	0, "");
310105197Ssam
311105197Ssam/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
312195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,
313195699Srwatson	blockacq_lifetime, CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
314105197Ssam
315105197Ssam/* ESP auth */
316195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth,
317195699Srwatson	CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth),	0,	"");
318105197Ssam
319105197Ssam/* minimum ESP key length */
320195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_ESP_KEYMIN,
321195699Srwatson	esp_keymin, CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin),	0,	"");
322105197Ssam
323105197Ssam/* minimum AH key length */
324195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin,
325195699Srwatson	CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin),	0,	"");
326105197Ssam
327105197Ssam/* perfered old SA rather than new SA */
328195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_PREFERED_OLDSA,
329195699Srwatson	preferred_oldsa, CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa),	0, "");
330105197Ssam
331105197Ssam#define __LIST_CHAINED(elm) \
332105197Ssam	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
333105197Ssam#define LIST_INSERT_TAIL(head, elm, type, field) \
334105197Ssamdo {\
335105197Ssam	struct type *curelm = LIST_FIRST(head); \
336105197Ssam	if (curelm == NULL) {\
337105197Ssam		LIST_INSERT_HEAD(head, elm, field); \
338105197Ssam	} else { \
339105197Ssam		while (LIST_NEXT(curelm, field)) \
340105197Ssam			curelm = LIST_NEXT(curelm, field);\
341105197Ssam		LIST_INSERT_AFTER(curelm, elm, field);\
342105197Ssam	}\
343105197Ssam} while (0)
344105197Ssam
345105197Ssam#define KEY_CHKSASTATE(head, sav, name) \
346105197Ssamdo { \
347105197Ssam	if ((head) != (sav)) {						\
348105197Ssam		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
349105197Ssam			(name), (head), (sav)));			\
350105197Ssam		continue;						\
351105197Ssam	}								\
352105197Ssam} while (0)
353105197Ssam
354105197Ssam#define KEY_CHKSPDIR(head, sp, name) \
355105197Ssamdo { \
356105197Ssam	if ((head) != (sp)) {						\
357105197Ssam		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
358105197Ssam			"anyway continue.\n",				\
359105197Ssam			(name), (head), (sp)));				\
360105197Ssam	}								\
361105197Ssam} while (0)
362105197Ssam
363119643SsamMALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
364119643SsamMALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
365119643SsamMALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
366119643SsamMALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
367119643SsamMALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
368119643SsamMALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
369119643SsamMALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
370105197Ssam
371105197Ssam/*
372105197Ssam * set parameters into secpolicyindex buffer.
373105197Ssam * Must allocate secpolicyindex buffer passed to this function.
374105197Ssam */
375105197Ssam#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
376105197Ssamdo { \
377105197Ssam	bzero((idx), sizeof(struct secpolicyindex));                         \
378105197Ssam	(idx)->dir = (_dir);                                                 \
379105197Ssam	(idx)->prefs = (ps);                                                 \
380105197Ssam	(idx)->prefd = (pd);                                                 \
381105197Ssam	(idx)->ul_proto = (ulp);                                             \
382105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
383105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
384105197Ssam} while (0)
385105197Ssam
386105197Ssam/*
387105197Ssam * set parameters into secasindex buffer.
388105197Ssam * Must allocate secasindex buffer before calling this function.
389105197Ssam */
390105197Ssam#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
391105197Ssamdo { \
392105197Ssam	bzero((idx), sizeof(struct secasindex));                             \
393105197Ssam	(idx)->proto = (p);                                                  \
394105197Ssam	(idx)->mode = (m);                                                   \
395105197Ssam	(idx)->reqid = (r);                                                  \
396105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
397105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
398105197Ssam} while (0)
399105197Ssam
400105197Ssam/* key statistics */
401105197Ssamstruct _keystat {
402105197Ssam	u_long getspi_count; /* the avarage of count to try to get new SPI */
403105197Ssam} keystat;
404105197Ssam
405105197Ssamstruct sadb_msghdr {
406105197Ssam	struct sadb_msg *msg;
407105197Ssam	struct sadb_ext *ext[SADB_EXT_MAX + 1];
408105197Ssam	int extoff[SADB_EXT_MAX + 1];
409105197Ssam	int extlen[SADB_EXT_MAX + 1];
410105197Ssam};
411105197Ssam
412105197Ssamstatic struct secasvar *key_allocsa_policy __P((const struct secasindex *));
413105197Ssamstatic void key_freesp_so __P((struct secpolicy **));
414105197Ssamstatic struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
415105197Ssamstatic void key_delsp __P((struct secpolicy *));
416105197Ssamstatic struct secpolicy *key_getsp __P((struct secpolicyindex *));
417119643Ssamstatic void _key_delsp(struct secpolicy *sp);
418105197Ssamstatic struct secpolicy *key_getspbyid __P((u_int32_t));
419105197Ssamstatic u_int32_t key_newreqid __P((void));
420105197Ssamstatic struct mbuf *key_gather_mbuf __P((struct mbuf *,
421105197Ssam	const struct sadb_msghdr *, int, int, ...));
422105197Ssamstatic int key_spdadd __P((struct socket *, struct mbuf *,
423105197Ssam	const struct sadb_msghdr *));
424105197Ssamstatic u_int32_t key_getnewspid __P((void));
425105197Ssamstatic int key_spddelete __P((struct socket *, struct mbuf *,
426105197Ssam	const struct sadb_msghdr *));
427105197Ssamstatic int key_spddelete2 __P((struct socket *, struct mbuf *,
428105197Ssam	const struct sadb_msghdr *));
429105197Ssamstatic int key_spdget __P((struct socket *, struct mbuf *,
430105197Ssam	const struct sadb_msghdr *));
431105197Ssamstatic int key_spdflush __P((struct socket *, struct mbuf *,
432105197Ssam	const struct sadb_msghdr *));
433105197Ssamstatic int key_spddump __P((struct socket *, struct mbuf *,
434105197Ssam	const struct sadb_msghdr *));
435105197Ssamstatic struct mbuf *key_setdumpsp __P((struct secpolicy *,
436105197Ssam	u_int8_t, u_int32_t, u_int32_t));
437105197Ssamstatic u_int key_getspreqmsglen __P((struct secpolicy *));
438105197Ssamstatic int key_spdexpire __P((struct secpolicy *));
439105197Ssamstatic struct secashead *key_newsah __P((struct secasindex *));
440105197Ssamstatic void key_delsah __P((struct secashead *));
441105197Ssamstatic struct secasvar *key_newsav __P((struct mbuf *,
442105197Ssam	const struct sadb_msghdr *, struct secashead *, int *,
443105197Ssam	const char*, int));
444105197Ssam#define	KEY_NEWSAV(m, sadb, sah, e)				\
445105197Ssam	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
446105197Ssamstatic void key_delsav __P((struct secasvar *));
447105197Ssamstatic struct secashead *key_getsah __P((struct secasindex *));
448105197Ssamstatic struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
449105197Ssamstatic struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
450105197Ssamstatic int key_setsaval __P((struct secasvar *, struct mbuf *,
451105197Ssam	const struct sadb_msghdr *));
452105197Ssamstatic int key_mature __P((struct secasvar *));
453105197Ssamstatic struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
454105197Ssam	u_int8_t, u_int32_t, u_int32_t));
455105197Ssamstatic struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
456105197Ssam	u_int32_t, pid_t, u_int16_t));
457105197Ssamstatic struct mbuf *key_setsadbsa __P((struct secasvar *));
458105197Ssamstatic struct mbuf *key_setsadbaddr __P((u_int16_t,
459105197Ssam	const struct sockaddr *, u_int8_t, u_int16_t));
460194062Svanhu#ifdef IPSEC_NAT_T
461194062Svanhustatic struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
462194062Svanhustatic struct mbuf *key_setsadbxtype(u_int16_t);
463194062Svanhu#endif
464194062Svanhustatic void key_porttosaddr(struct sockaddr *, u_int16_t);
465194062Svanhu#define	KEY_PORTTOSADDR(saddr, port)				\
466194062Svanhu	key_porttosaddr((struct sockaddr *)(saddr), (port))
467105197Ssamstatic struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
468105197Ssamstatic struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
469105197Ssam	u_int32_t));
470157123Sgnnstatic struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
471157123Sgnn				     struct malloc_type *);
472157123Sgnnstatic struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
473157123Sgnn					    struct malloc_type *type);
474105197Ssam#ifdef INET6
475105197Ssamstatic int key_ismyaddr6 __P((struct sockaddr_in6 *));
476105197Ssam#endif
477105197Ssam
478105197Ssam/* flags for key_cmpsaidx() */
479105197Ssam#define CMP_HEAD	1	/* protocol, addresses. */
480105197Ssam#define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
481105197Ssam#define CMP_REQID	3	/* additionally HEAD, reaid. */
482105197Ssam#define CMP_EXACTLY	4	/* all elements. */
483105197Ssamstatic int key_cmpsaidx
484105197Ssam	__P((const struct secasindex *, const struct secasindex *, int));
485105197Ssam
486105197Ssamstatic int key_cmpspidx_exactly
487105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
488105197Ssamstatic int key_cmpspidx_withmask
489105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
490105197Ssamstatic int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
491105197Ssamstatic int key_bbcmp __P((const void *, const void *, u_int));
492105197Ssamstatic u_int16_t key_satype2proto __P((u_int8_t));
493105197Ssamstatic u_int8_t key_proto2satype __P((u_int16_t));
494105197Ssam
495105197Ssamstatic int key_getspi __P((struct socket *, struct mbuf *,
496105197Ssam	const struct sadb_msghdr *));
497105197Ssamstatic u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
498105197Ssam					struct secasindex *));
499105197Ssamstatic int key_update __P((struct socket *, struct mbuf *,
500105197Ssam	const struct sadb_msghdr *));
501105197Ssam#ifdef IPSEC_DOSEQCHECK
502105197Ssamstatic struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
503105197Ssam#endif
504105197Ssamstatic int key_add __P((struct socket *, struct mbuf *,
505105197Ssam	const struct sadb_msghdr *));
506105197Ssamstatic int key_setident __P((struct secashead *, struct mbuf *,
507105197Ssam	const struct sadb_msghdr *));
508105197Ssamstatic struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
509105197Ssam	const struct sadb_msghdr *));
510105197Ssamstatic int key_delete __P((struct socket *, struct mbuf *,
511105197Ssam	const struct sadb_msghdr *));
512105197Ssamstatic int key_get __P((struct socket *, struct mbuf *,
513105197Ssam	const struct sadb_msghdr *));
514105197Ssam
515105197Ssamstatic void key_getcomb_setlifetime __P((struct sadb_comb *));
516105197Ssamstatic struct mbuf *key_getcomb_esp __P((void));
517105197Ssamstatic struct mbuf *key_getcomb_ah __P((void));
518105197Ssamstatic struct mbuf *key_getcomb_ipcomp __P((void));
519105197Ssamstatic struct mbuf *key_getprop __P((const struct secasindex *));
520105197Ssam
521105197Ssamstatic int key_acquire __P((const struct secasindex *, struct secpolicy *));
522105197Ssamstatic struct secacq *key_newacq __P((const struct secasindex *));
523105197Ssamstatic struct secacq *key_getacq __P((const struct secasindex *));
524105197Ssamstatic struct secacq *key_getacqbyseq __P((u_int32_t));
525105197Ssamstatic struct secspacq *key_newspacq __P((struct secpolicyindex *));
526105197Ssamstatic struct secspacq *key_getspacq __P((struct secpolicyindex *));
527105197Ssamstatic int key_acquire2 __P((struct socket *, struct mbuf *,
528105197Ssam	const struct sadb_msghdr *));
529105197Ssamstatic int key_register __P((struct socket *, struct mbuf *,
530105197Ssam	const struct sadb_msghdr *));
531105197Ssamstatic int key_expire __P((struct secasvar *));
532105197Ssamstatic int key_flush __P((struct socket *, struct mbuf *,
533105197Ssam	const struct sadb_msghdr *));
534105197Ssamstatic int key_dump __P((struct socket *, struct mbuf *,
535105197Ssam	const struct sadb_msghdr *));
536105197Ssamstatic int key_promisc __P((struct socket *, struct mbuf *,
537105197Ssam	const struct sadb_msghdr *));
538105197Ssamstatic int key_senderror __P((struct socket *, struct mbuf *, int));
539105197Ssamstatic int key_validate_ext __P((const struct sadb_ext *, int));
540105197Ssamstatic int key_align __P((struct mbuf *, struct sadb_msghdr *));
541157123Sgnnstatic struct mbuf *key_setlifetime(struct seclifetime *src,
542157123Sgnn				     u_int16_t exttype);
543157123Sgnnstatic struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
544157123Sgnn
545105197Ssam#if 0
546105197Ssamstatic const char *key_getfqdn __P((void));
547105197Ssamstatic const char *key_getuserfqdn __P((void));
548105197Ssam#endif
549105197Ssamstatic void key_sa_chgstate __P((struct secasvar *, u_int8_t));
550105197Ssamstatic struct mbuf *key_alloc_mbuf __P((int));
551105197Ssam
552158767Spjdstatic __inline void
553158767Spjdsa_initref(struct secasvar *sav)
554158767Spjd{
555105197Ssam
556158767Spjd	refcount_init(&sav->refcnt, 1);
557158767Spjd}
558158767Spjdstatic __inline void
559158767Spjdsa_addref(struct secasvar *sav)
560158767Spjd{
561158767Spjd
562158767Spjd	refcount_acquire(&sav->refcnt);
563158767Spjd	IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
564158767Spjd}
565158767Spjdstatic __inline int
566158767Spjdsa_delref(struct secasvar *sav)
567158767Spjd{
568158767Spjd
569158767Spjd	IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
570158767Spjd	return (refcount_release(&sav->refcnt));
571158767Spjd}
572158767Spjd
573105197Ssam#define	SP_ADDREF(p) do {						\
574105197Ssam	(p)->refcnt++;							\
575120585Ssam	IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));		\
576105197Ssam} while (0)
577105197Ssam#define	SP_DELREF(p) do {						\
578120585Ssam	IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));		\
579105197Ssam	(p)->refcnt--;							\
580105197Ssam} while (0)
581135947Ssam
582105197Ssam
583105197Ssam/*
584135947Ssam * Update the refcnt while holding the SPTREE lock.
585135947Ssam */
586135947Ssamvoid
587135947Ssamkey_addref(struct secpolicy *sp)
588135947Ssam{
589135947Ssam	SPTREE_LOCK();
590135947Ssam	SP_ADDREF(sp);
591135947Ssam	SPTREE_UNLOCK();
592135947Ssam}
593135947Ssam
594135947Ssam/*
595105197Ssam * Return 0 when there are known to be no SP's for the specified
596105197Ssam * direction.  Otherwise return 1.  This is used by IPsec code
597105197Ssam * to optimize performance.
598105197Ssam */
599105197Ssamint
600105197Ssamkey_havesp(u_int dir)
601105197Ssam{
602183550Szec
603105197Ssam	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
604181803Sbz		LIST_FIRST(&V_sptree[dir]) != NULL : 1);
605105197Ssam}
606105197Ssam
607105197Ssam/* %%% IPsec policy management */
608105197Ssam/*
609105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
610105197Ssam * Must call key_freesp() later.
611105197Ssam * OUT:	NULL:	not found
612105197Ssam *	others:	found and return the pointer.
613105197Ssam */
614105197Ssamstruct secpolicy *
615105197Ssamkey_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
616105197Ssam{
617105197Ssam	struct secpolicy *sp;
618105197Ssam
619120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
620120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
621120585Ssam		("invalid direction %u", dir));
622105197Ssam
623105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
624120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
625105197Ssam
626105197Ssam	/* get a SP entry */
627105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
628105197Ssam		printf("*** objects\n");
629105197Ssam		kdebug_secpolicyindex(spidx));
630105197Ssam
631120585Ssam	SPTREE_LOCK();
632181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
633105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
634105197Ssam			printf("*** in SPD\n");
635105197Ssam			kdebug_secpolicyindex(&sp->spidx));
636105197Ssam
637105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
638105197Ssam			continue;
639105197Ssam		if (key_cmpspidx_withmask(&sp->spidx, spidx))
640105197Ssam			goto found;
641105197Ssam	}
642105197Ssam	sp = NULL;
643105197Ssamfound:
644105197Ssam	if (sp) {
645105197Ssam		/* sanity check */
646120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
647105197Ssam
648105197Ssam		/* found a SPD entry */
649105197Ssam		sp->lastused = time_second;
650105197Ssam		SP_ADDREF(sp);
651105197Ssam	}
652120585Ssam	SPTREE_UNLOCK();
653105197Ssam
654105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
655120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
656105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
657105197Ssam	return sp;
658105197Ssam}
659105197Ssam
660105197Ssam/*
661105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
662105197Ssam * Must call key_freesp() later.
663105197Ssam * OUT:	NULL:	not found
664105197Ssam *	others:	found and return the pointer.
665105197Ssam */
666105197Ssamstruct secpolicy *
667105197Ssamkey_allocsp2(u_int32_t spi,
668105197Ssam	     union sockaddr_union *dst,
669105197Ssam	     u_int8_t proto,
670105197Ssam	     u_int dir,
671105197Ssam	     const char* where, int tag)
672105197Ssam{
673105197Ssam	struct secpolicy *sp;
674105197Ssam
675120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst"));
676120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
677120585Ssam		("invalid direction %u", dir));
678105197Ssam
679105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
680120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
681105197Ssam
682105197Ssam	/* get a SP entry */
683105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
684105197Ssam		printf("*** objects\n");
685105197Ssam		printf("spi %u proto %u dir %u\n", spi, proto, dir);
686105197Ssam		kdebug_sockaddr(&dst->sa));
687105197Ssam
688120585Ssam	SPTREE_LOCK();
689181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
690105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
691105197Ssam			printf("*** in SPD\n");
692105197Ssam			kdebug_secpolicyindex(&sp->spidx));
693105197Ssam
694105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
695105197Ssam			continue;
696105197Ssam		/* compare simple values, then dst address */
697105197Ssam		if (sp->spidx.ul_proto != proto)
698105197Ssam			continue;
699105197Ssam		/* NB: spi's must exist and match */
700105197Ssam		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
701105197Ssam			continue;
702105197Ssam		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
703105197Ssam			goto found;
704105197Ssam	}
705105197Ssam	sp = NULL;
706105197Ssamfound:
707105197Ssam	if (sp) {
708105197Ssam		/* sanity check */
709120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
710105197Ssam
711105197Ssam		/* found a SPD entry */
712105197Ssam		sp->lastused = time_second;
713105197Ssam		SP_ADDREF(sp);
714105197Ssam	}
715120585Ssam	SPTREE_UNLOCK();
716105197Ssam
717105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
718120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
719105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
720105197Ssam	return sp;
721105197Ssam}
722105197Ssam
723191599Sbz#if 0
724105197Ssam/*
725105197Ssam * return a policy that matches this particular inbound packet.
726105197Ssam * XXX slow
727105197Ssam */
728105197Ssamstruct secpolicy *
729105197Ssamkey_gettunnel(const struct sockaddr *osrc,
730105197Ssam	      const struct sockaddr *odst,
731105197Ssam	      const struct sockaddr *isrc,
732105197Ssam	      const struct sockaddr *idst,
733105197Ssam	      const char* where, int tag)
734105197Ssam{
735105197Ssam	struct secpolicy *sp;
736105197Ssam	const int dir = IPSEC_DIR_INBOUND;
737105197Ssam	struct ipsecrequest *r1, *r2, *p;
738105197Ssam	struct secpolicyindex spidx;
739105197Ssam
740105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
741120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
742105197Ssam
743105197Ssam	if (isrc->sa_family != idst->sa_family) {
744120585Ssam		ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
745120585Ssam			__func__, isrc->sa_family, idst->sa_family));
746105197Ssam		sp = NULL;
747105197Ssam		goto done;
748105197Ssam	}
749105197Ssam
750120585Ssam	SPTREE_LOCK();
751181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
752105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
753105197Ssam			continue;
754105197Ssam
755105197Ssam		r1 = r2 = NULL;
756105197Ssam		for (p = sp->req; p; p = p->next) {
757105197Ssam			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
758105197Ssam				continue;
759105197Ssam
760105197Ssam			r1 = r2;
761105197Ssam			r2 = p;
762105197Ssam
763105197Ssam			if (!r1) {
764105197Ssam				/* here we look at address matches only */
765105197Ssam				spidx = sp->spidx;
766105197Ssam				if (isrc->sa_len > sizeof(spidx.src) ||
767105197Ssam				    idst->sa_len > sizeof(spidx.dst))
768105197Ssam					continue;
769105197Ssam				bcopy(isrc, &spidx.src, isrc->sa_len);
770105197Ssam				bcopy(idst, &spidx.dst, idst->sa_len);
771105197Ssam				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
772105197Ssam					continue;
773105197Ssam			} else {
774105197Ssam				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
775105197Ssam				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
776105197Ssam					continue;
777105197Ssam			}
778105197Ssam
779105197Ssam			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
780105197Ssam			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
781105197Ssam				continue;
782105197Ssam
783105197Ssam			goto found;
784105197Ssam		}
785105197Ssam	}
786105197Ssam	sp = NULL;
787105197Ssamfound:
788105197Ssam	if (sp) {
789105197Ssam		sp->lastused = time_second;
790105197Ssam		SP_ADDREF(sp);
791105197Ssam	}
792120585Ssam	SPTREE_UNLOCK();
793105197Ssamdone:
794105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
795120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
796105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
797105197Ssam	return sp;
798105197Ssam}
799191599Sbz#endif
800105197Ssam
801105197Ssam/*
802105197Ssam * allocating an SA entry for an *OUTBOUND* packet.
803105197Ssam * checking each request entries in SP, and acquire an SA if need.
804105197Ssam * OUT:	0: there are valid requests.
805105197Ssam *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
806105197Ssam */
807105197Ssamint
808105197Ssamkey_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
809105197Ssam{
810105197Ssam	u_int level;
811105197Ssam	int error;
812220206Sfabient	struct secasvar *sav;
813105197Ssam
814120585Ssam	IPSEC_ASSERT(isr != NULL, ("null isr"));
815120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
816120585Ssam	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
817105197Ssam		saidx->mode == IPSEC_MODE_TUNNEL,
818120585Ssam		("unexpected policy %u", saidx->mode));
819105197Ssam
820105197Ssam	/*
821105197Ssam	 * XXX guard against protocol callbacks from the crypto
822105197Ssam	 * thread as they reference ipsecrequest.sav which we
823105197Ssam	 * temporarily null out below.  Need to rethink how we
824105197Ssam	 * handle bundled SA's in the callback thread.
825105197Ssam	 */
826120585Ssam	IPSECREQUEST_LOCK_ASSERT(isr);
827119643Ssam
828119643Ssam	/* get current level */
829119643Ssam	level = ipsec_get_reqlevel(isr);
830220206Sfabient
831105197Ssam	/*
832220206Sfabient	 * We check new SA in the IPsec request because a different
833105197Ssam	 * SA may be involved each time this request is checked, either
834105197Ssam	 * because new SAs are being configured, or this request is
835105197Ssam	 * associated with an unconnected datagram socket, or this request
836105197Ssam	 * is associated with a system default policy.
837105197Ssam	 *
838105197Ssam	 * key_allocsa_policy should allocate the oldest SA available.
839105197Ssam	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
840105197Ssam	 */
841220206Sfabient	sav = key_allocsa_policy(saidx);
842220206Sfabient	if (sav != isr->sav) {
843220206Sfabient		/* SA need to be updated. */
844220206Sfabient		if (!IPSECREQUEST_UPGRADE(isr)) {
845220206Sfabient			/* Kick everyone off. */
846220206Sfabient			IPSECREQUEST_UNLOCK(isr);
847220206Sfabient			IPSECREQUEST_WLOCK(isr);
848220206Sfabient		}
849220206Sfabient		if (isr->sav != NULL)
850220206Sfabient			KEY_FREESAV(&isr->sav);
851220206Sfabient		isr->sav = sav;
852220206Sfabient		IPSECREQUEST_DOWNGRADE(isr);
853220206Sfabient	} else if (sav != NULL)
854220206Sfabient		KEY_FREESAV(&sav);
855105197Ssam
856105197Ssam	/* When there is SA. */
857105197Ssam	if (isr->sav != NULL) {
858105197Ssam		if (isr->sav->state != SADB_SASTATE_MATURE &&
859105197Ssam		    isr->sav->state != SADB_SASTATE_DYING)
860105197Ssam			return EINVAL;
861105197Ssam		return 0;
862105197Ssam	}
863105197Ssam
864105197Ssam	/* there is no SA */
865105197Ssam	error = key_acquire(saidx, isr->sp);
866105197Ssam	if (error != 0) {
867105197Ssam		/* XXX What should I do ? */
868120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
869120585Ssam			__func__, error));
870105197Ssam		return error;
871105197Ssam	}
872105197Ssam
873105197Ssam	if (level != IPSEC_LEVEL_REQUIRE) {
874105197Ssam		/* XXX sigh, the interface to this routine is botched */
875120585Ssam		IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
876105197Ssam		return 0;
877105197Ssam	} else {
878105197Ssam		return ENOENT;
879105197Ssam	}
880105197Ssam}
881105197Ssam
882105197Ssam/*
883105197Ssam * allocating a SA for policy entry from SAD.
884105197Ssam * NOTE: searching SAD of aliving state.
885105197Ssam * OUT:	NULL:	not found.
886105197Ssam *	others:	found and return the pointer.
887105197Ssam */
888105197Ssamstatic struct secasvar *
889105197Ssamkey_allocsa_policy(const struct secasindex *saidx)
890105197Ssam{
891128856Ssam#define	N(a)	_ARRAYLEN(a)
892105197Ssam	struct secashead *sah;
893105197Ssam	struct secasvar *sav;
894128856Ssam	u_int stateidx, arraysize;
895128856Ssam	const u_int *state_valid;
896105197Ssam
897196902Spjd	state_valid = NULL;	/* silence gcc */
898196902Spjd	arraysize = 0;		/* silence gcc */
899196896Spjd
900120585Ssam	SAHTREE_LOCK();
901181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
902105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
903105197Ssam			continue;
904119643Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
905181803Sbz			if (V_key_preferred_oldsa) {
906128856Ssam				state_valid = saorder_state_valid_prefer_old;
907128856Ssam				arraysize = N(saorder_state_valid_prefer_old);
908128856Ssam			} else {
909128856Ssam				state_valid = saorder_state_valid_prefer_new;
910128856Ssam				arraysize = N(saorder_state_valid_prefer_new);
911128856Ssam			}
912196883Spjd			break;
913119643Ssam		}
914105197Ssam	}
915120585Ssam	SAHTREE_UNLOCK();
916196883Spjd	if (sah == NULL)
917196883Spjd		return NULL;
918105197Ssam
919105197Ssam	/* search valid state */
920128856Ssam	for (stateidx = 0; stateidx < arraysize; stateidx++) {
921128856Ssam		sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
922105197Ssam		if (sav != NULL)
923105197Ssam			return sav;
924105197Ssam	}
925105197Ssam
926105197Ssam	return NULL;
927128856Ssam#undef N
928105197Ssam}
929105197Ssam
930105197Ssam/*
931105197Ssam * searching SAD with direction, protocol, mode and state.
932105197Ssam * called by key_allocsa_policy().
933105197Ssam * OUT:
934105197Ssam *	NULL	: not found
935105197Ssam *	others	: found, pointer to a SA.
936105197Ssam */
937105197Ssamstatic struct secasvar *
938105197Ssamkey_do_allocsa_policy(struct secashead *sah, u_int state)
939105197Ssam{
940105197Ssam	struct secasvar *sav, *nextsav, *candidate, *d;
941105197Ssam
942105197Ssam	/* initilize */
943105197Ssam	candidate = NULL;
944105197Ssam
945120585Ssam	SAHTREE_LOCK();
946105197Ssam	for (sav = LIST_FIRST(&sah->savtree[state]);
947105197Ssam	     sav != NULL;
948105197Ssam	     sav = nextsav) {
949105197Ssam
950105197Ssam		nextsav = LIST_NEXT(sav, chain);
951105197Ssam
952105197Ssam		/* sanity check */
953120585Ssam		KEY_CHKSASTATE(sav->state, state, __func__);
954105197Ssam
955105197Ssam		/* initialize */
956105197Ssam		if (candidate == NULL) {
957105197Ssam			candidate = sav;
958105197Ssam			continue;
959105197Ssam		}
960105197Ssam
961105197Ssam		/* Which SA is the better ? */
962105197Ssam
963120585Ssam		IPSEC_ASSERT(candidate->lft_c != NULL,
964120585Ssam			("null candidate lifetime"));
965120585Ssam		IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
966105197Ssam
967105197Ssam		/* What the best method is to compare ? */
968181803Sbz		if (V_key_preferred_oldsa) {
969157123Sgnn			if (candidate->lft_c->addtime >
970157123Sgnn					sav->lft_c->addtime) {
971105197Ssam				candidate = sav;
972105197Ssam			}
973105197Ssam			continue;
974105197Ssam			/*NOTREACHED*/
975105197Ssam		}
976105197Ssam
977125876Sguido		/* preferred new sa rather than old sa */
978157123Sgnn		if (candidate->lft_c->addtime <
979157123Sgnn				sav->lft_c->addtime) {
980105197Ssam			d = candidate;
981105197Ssam			candidate = sav;
982105197Ssam		} else
983105197Ssam			d = sav;
984105197Ssam
985105197Ssam		/*
986105197Ssam		 * prepared to delete the SA when there is more
987105197Ssam		 * suitable candidate and the lifetime of the SA is not
988105197Ssam		 * permanent.
989105197Ssam		 */
990177553Sbz		if (d->lft_h->addtime != 0) {
991105197Ssam			struct mbuf *m, *result;
992125508Ssam			u_int8_t satype;
993105197Ssam
994105197Ssam			key_sa_chgstate(d, SADB_SASTATE_DEAD);
995105197Ssam
996120585Ssam			IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
997125508Ssam
998125508Ssam			satype = key_proto2satype(d->sah->saidx.proto);
999125508Ssam			if (satype == 0)
1000125508Ssam				goto msgfail;
1001125508Ssam
1002105197Ssam			m = key_setsadbmsg(SADB_DELETE, 0,
1003125508Ssam			    satype, 0, 0, d->refcnt - 1);
1004105197Ssam			if (!m)
1005105197Ssam				goto msgfail;
1006105197Ssam			result = m;
1007105197Ssam
1008105197Ssam			/* set sadb_address for saidx's. */
1009105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
1010105197Ssam				&d->sah->saidx.src.sa,
1011105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
1012105197Ssam				IPSEC_ULPROTO_ANY);
1013105197Ssam			if (!m)
1014105197Ssam				goto msgfail;
1015105197Ssam			m_cat(result, m);
1016105197Ssam
1017105197Ssam			/* set sadb_address for saidx's. */
1018105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
1019128860Ssam				&d->sah->saidx.dst.sa,
1020128860Ssam				d->sah->saidx.dst.sa.sa_len << 3,
1021105197Ssam				IPSEC_ULPROTO_ANY);
1022105197Ssam			if (!m)
1023105197Ssam				goto msgfail;
1024105197Ssam			m_cat(result, m);
1025105197Ssam
1026105197Ssam			/* create SA extension */
1027105197Ssam			m = key_setsadbsa(d);
1028105197Ssam			if (!m)
1029105197Ssam				goto msgfail;
1030105197Ssam			m_cat(result, m);
1031105197Ssam
1032105197Ssam			if (result->m_len < sizeof(struct sadb_msg)) {
1033105197Ssam				result = m_pullup(result,
1034105197Ssam						sizeof(struct sadb_msg));
1035105197Ssam				if (result == NULL)
1036105197Ssam					goto msgfail;
1037105197Ssam			}
1038105197Ssam
1039105197Ssam			result->m_pkthdr.len = 0;
1040105197Ssam			for (m = result; m; m = m->m_next)
1041105197Ssam				result->m_pkthdr.len += m->m_len;
1042105197Ssam			mtod(result, struct sadb_msg *)->sadb_msg_len =
1043105197Ssam				PFKEY_UNIT64(result->m_pkthdr.len);
1044105197Ssam
1045105197Ssam			if (key_sendup_mbuf(NULL, result,
1046105197Ssam					KEY_SENDUP_REGISTERED))
1047105197Ssam				goto msgfail;
1048105197Ssam		 msgfail:
1049105197Ssam			KEY_FREESAV(&d);
1050105197Ssam		}
1051105197Ssam	}
1052105197Ssam	if (candidate) {
1053158767Spjd		sa_addref(candidate);
1054105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1055120585Ssam			printf("DP %s cause refcnt++:%d SA:%p\n",
1056120585Ssam				__func__, candidate->refcnt, candidate));
1057105197Ssam	}
1058120585Ssam	SAHTREE_UNLOCK();
1059119643Ssam
1060105197Ssam	return candidate;
1061105197Ssam}
1062105197Ssam
1063105197Ssam/*
1064105197Ssam * allocating a usable SA entry for a *INBOUND* packet.
1065105197Ssam * Must call key_freesav() later.
1066105197Ssam * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
1067105197Ssam *	NULL:		not found, or error occured.
1068105197Ssam *
1069105197Ssam * In the comparison, no source address is used--for RFC2401 conformance.
1070105197Ssam * To quote, from section 4.1:
1071105197Ssam *	A security association is uniquely identified by a triple consisting
1072105197Ssam *	of a Security Parameter Index (SPI), an IP Destination Address, and a
1073105197Ssam *	security protocol (AH or ESP) identifier.
1074105197Ssam * Note that, however, we do need to keep source address in IPsec SA.
1075105197Ssam * IKE specification and PF_KEY specification do assume that we
1076105197Ssam * keep source address in IPsec SA.  We see a tricky situation here.
1077105197Ssam */
1078105197Ssamstruct secasvar *
1079105197Ssamkey_allocsa(
1080105197Ssam	union sockaddr_union *dst,
1081105197Ssam	u_int proto,
1082105197Ssam	u_int32_t spi,
1083105197Ssam	const char* where, int tag)
1084105197Ssam{
1085105197Ssam	struct secashead *sah;
1086105197Ssam	struct secasvar *sav;
1087128856Ssam	u_int stateidx, arraysize, state;
1088128856Ssam	const u_int *saorder_state_valid;
1089194062Svanhu	int chkport;
1090105197Ssam
1091120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst address"));
1092105197Ssam
1093105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1094120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
1095105197Ssam
1096194062Svanhu#ifdef IPSEC_NAT_T
1097194062Svanhu        chkport = (dst->sa.sa_family == AF_INET &&
1098194062Svanhu	    dst->sa.sa_len == sizeof(struct sockaddr_in) &&
1099194062Svanhu	    dst->sin.sin_port != 0);
1100194062Svanhu#else
1101194062Svanhu	chkport = 0;
1102194062Svanhu#endif
1103194062Svanhu
1104105197Ssam	/*
1105105197Ssam	 * searching SAD.
1106105197Ssam	 * XXX: to be checked internal IP header somewhere.  Also when
1107105197Ssam	 * IPsec tunnel packet is received.  But ESP tunnel mode is
1108105197Ssam	 * encrypted so we can't check internal IP header.
1109105197Ssam	 */
1110120585Ssam	SAHTREE_LOCK();
1111181803Sbz	if (V_key_preferred_oldsa) {
1112128856Ssam		saorder_state_valid = saorder_state_valid_prefer_old;
1113128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1114128856Ssam	} else {
1115128856Ssam		saorder_state_valid = saorder_state_valid_prefer_new;
1116128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1117128856Ssam	}
1118181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
1119105197Ssam		/* search valid state */
1120128856Ssam		for (stateidx = 0; stateidx < arraysize; stateidx++) {
1121105197Ssam			state = saorder_state_valid[stateidx];
1122105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
1123105197Ssam				/* sanity check */
1124120585Ssam				KEY_CHKSASTATE(sav->state, state, __func__);
1125105197Ssam				/* do not return entries w/ unusable state */
1126105197Ssam				if (sav->state != SADB_SASTATE_MATURE &&
1127105197Ssam				    sav->state != SADB_SASTATE_DYING)
1128105197Ssam					continue;
1129105197Ssam				if (proto != sav->sah->saidx.proto)
1130105197Ssam					continue;
1131105197Ssam				if (spi != sav->spi)
1132105197Ssam					continue;
1133105197Ssam#if 0	/* don't check src */
1134105197Ssam				/* check src address */
1135194062Svanhu				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, chkport) != 0)
1136105197Ssam					continue;
1137105197Ssam#endif
1138105197Ssam				/* check dst address */
1139194062Svanhu				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, chkport) != 0)
1140105197Ssam					continue;
1141158767Spjd				sa_addref(sav);
1142105197Ssam				goto done;
1143105197Ssam			}
1144105197Ssam		}
1145105197Ssam	}
1146105197Ssam	sav = NULL;
1147105197Ssamdone:
1148120585Ssam	SAHTREE_UNLOCK();
1149105197Ssam
1150105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1151120585Ssam		printf("DP %s return SA:%p; refcnt %u\n", __func__,
1152105197Ssam			sav, sav ? sav->refcnt : 0));
1153105197Ssam	return sav;
1154105197Ssam}
1155105197Ssam
1156105197Ssam/*
1157105197Ssam * Must be called after calling key_allocsp().
1158105197Ssam * For both the packet without socket and key_freeso().
1159105197Ssam */
1160105197Ssamvoid
1161105197Ssam_key_freesp(struct secpolicy **spp, const char* where, int tag)
1162105197Ssam{
1163105197Ssam	struct secpolicy *sp = *spp;
1164105197Ssam
1165120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1166105197Ssam
1167120585Ssam	SPTREE_LOCK();
1168105197Ssam	SP_DELREF(sp);
1169105197Ssam
1170105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1171120585Ssam		printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1172120585Ssam			__func__, sp, sp->id, where, tag, sp->refcnt));
1173105197Ssam
1174105197Ssam	if (sp->refcnt == 0) {
1175105197Ssam		*spp = NULL;
1176105197Ssam		key_delsp(sp);
1177105197Ssam	}
1178120585Ssam	SPTREE_UNLOCK();
1179105197Ssam}
1180105197Ssam
1181105197Ssam/*
1182105197Ssam * Must be called after calling key_allocsp().
1183105197Ssam * For the packet with socket.
1184105197Ssam */
1185105197Ssamvoid
1186105197Ssamkey_freeso(struct socket *so)
1187105197Ssam{
1188120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
1189105197Ssam
1190105197Ssam	switch (so->so_proto->pr_domain->dom_family) {
1191186141Sbz#if defined(INET) || defined(INET6)
1192105197Ssam#ifdef INET
1193105197Ssam	case PF_INET:
1194105197Ssam#endif
1195105197Ssam#ifdef INET6
1196105197Ssam	case PF_INET6:
1197186141Sbz#endif
1198105197Ssam	    {
1199186141Sbz		struct inpcb *pcb = sotoinpcb(so);
1200105197Ssam
1201105197Ssam		/* Does it have a PCB ? */
1202105197Ssam		if (pcb == NULL)
1203105197Ssam			return;
1204105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1205105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1206105197Ssam	    }
1207105197Ssam		break;
1208186141Sbz#endif /* INET || INET6 */
1209105197Ssam	default:
1210120585Ssam		ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1211120585Ssam		    __func__, so->so_proto->pr_domain->dom_family));
1212105197Ssam		return;
1213105197Ssam	}
1214105197Ssam}
1215105197Ssam
1216105197Ssamstatic void
1217105197Ssamkey_freesp_so(struct secpolicy **sp)
1218105197Ssam{
1219120585Ssam	IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1220105197Ssam
1221105197Ssam	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1222105197Ssam	    (*sp)->policy == IPSEC_POLICY_BYPASS)
1223105197Ssam		return;
1224105197Ssam
1225120585Ssam	IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1226120585Ssam		("invalid policy %u", (*sp)->policy));
1227105197Ssam	KEY_FREESP(sp);
1228105197Ssam}
1229105197Ssam
1230220206Sfabientvoid
1231220206Sfabientkey_addrefsa(struct secasvar *sav, const char* where, int tag)
1232220206Sfabient{
1233220206Sfabient
1234220206Sfabient	IPSEC_ASSERT(sav != NULL, ("null sav"));
1235220206Sfabient	IPSEC_ASSERT(sav->refcnt > 0, ("refcount must exist"));
1236220206Sfabient
1237220206Sfabient	sa_addref(sav);
1238220206Sfabient}
1239220206Sfabient
1240105197Ssam/*
1241105197Ssam * Must be called after calling key_allocsa().
1242105197Ssam * This function is called by key_freesp() to free some SA allocated
1243105197Ssam * for a policy.
1244105197Ssam */
1245105197Ssamvoid
1246105197Ssamkey_freesav(struct secasvar **psav, const char* where, int tag)
1247105197Ssam{
1248105197Ssam	struct secasvar *sav = *psav;
1249105197Ssam
1250120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
1251105197Ssam
1252158767Spjd	if (sa_delref(sav)) {
1253158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1254158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1255158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1256105197Ssam		*psav = NULL;
1257105197Ssam		key_delsav(sav);
1258158767Spjd	} else {
1259158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1260158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1261158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1262105197Ssam	}
1263105197Ssam}
1264105197Ssam
1265105197Ssam/* %%% SPD management */
1266105197Ssam/*
1267105197Ssam * free security policy entry.
1268105197Ssam */
1269105197Ssamstatic void
1270105197Ssamkey_delsp(struct secpolicy *sp)
1271105197Ssam{
1272119643Ssam	struct ipsecrequest *isr, *nextisr;
1273105197Ssam
1274120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1275120585Ssam	SPTREE_LOCK_ASSERT();
1276105197Ssam
1277105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
1278105197Ssam
1279120585Ssam	IPSEC_ASSERT(sp->refcnt == 0,
1280120585Ssam		("SP with references deleted (refcnt %u)", sp->refcnt));
1281105197Ssam
1282105197Ssam	/* remove from SP index */
1283105197Ssam	if (__LIST_CHAINED(sp))
1284105197Ssam		LIST_REMOVE(sp, chain);
1285105197Ssam
1286119643Ssam	for (isr = sp->req; isr != NULL; isr = nextisr) {
1287105197Ssam		if (isr->sav != NULL) {
1288105197Ssam			KEY_FREESAV(&isr->sav);
1289105197Ssam			isr->sav = NULL;
1290105197Ssam		}
1291105197Ssam
1292105197Ssam		nextisr = isr->next;
1293119643Ssam		ipsec_delisr(isr);
1294105197Ssam	}
1295119643Ssam	_key_delsp(sp);
1296105197Ssam}
1297105197Ssam
1298105197Ssam/*
1299105197Ssam * search SPD
1300105197Ssam * OUT:	NULL	: not found
1301105197Ssam *	others	: found, pointer to a SP.
1302105197Ssam */
1303105197Ssamstatic struct secpolicy *
1304105197Ssamkey_getsp(struct secpolicyindex *spidx)
1305105197Ssam{
1306105197Ssam	struct secpolicy *sp;
1307105197Ssam
1308120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1309105197Ssam
1310120585Ssam	SPTREE_LOCK();
1311181803Sbz	LIST_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1312105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1313105197Ssam			continue;
1314105197Ssam		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1315105197Ssam			SP_ADDREF(sp);
1316119643Ssam			break;
1317105197Ssam		}
1318105197Ssam	}
1319120585Ssam	SPTREE_UNLOCK();
1320105197Ssam
1321119643Ssam	return sp;
1322105197Ssam}
1323105197Ssam
1324105197Ssam/*
1325105197Ssam * get SP by index.
1326105197Ssam * OUT:	NULL	: not found
1327105197Ssam *	others	: found, pointer to a SP.
1328105197Ssam */
1329105197Ssamstatic struct secpolicy *
1330105197Ssamkey_getspbyid(u_int32_t id)
1331105197Ssam{
1332105197Ssam	struct secpolicy *sp;
1333105197Ssam
1334120585Ssam	SPTREE_LOCK();
1335181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
1336105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1337105197Ssam			continue;
1338105197Ssam		if (sp->id == id) {
1339105197Ssam			SP_ADDREF(sp);
1340119643Ssam			goto done;
1341105197Ssam		}
1342105197Ssam	}
1343105197Ssam
1344181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
1345105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1346105197Ssam			continue;
1347105197Ssam		if (sp->id == id) {
1348105197Ssam			SP_ADDREF(sp);
1349119643Ssam			goto done;
1350105197Ssam		}
1351105197Ssam	}
1352119643Ssamdone:
1353120585Ssam	SPTREE_UNLOCK();
1354105197Ssam
1355119643Ssam	return sp;
1356105197Ssam}
1357105197Ssam
1358105197Ssamstruct secpolicy *
1359105197Ssamkey_newsp(const char* where, int tag)
1360105197Ssam{
1361105197Ssam	struct secpolicy *newsp = NULL;
1362105197Ssam
1363105197Ssam	newsp = (struct secpolicy *)
1364119643Ssam		malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1365105197Ssam	if (newsp) {
1366120585Ssam		SECPOLICY_LOCK_INIT(newsp);
1367105197Ssam		newsp->refcnt = 1;
1368105197Ssam		newsp->req = NULL;
1369105197Ssam	}
1370105197Ssam
1371105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1372120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
1373105197Ssam			where, tag, newsp));
1374105197Ssam	return newsp;
1375105197Ssam}
1376105197Ssam
1377119643Ssamstatic void
1378119643Ssam_key_delsp(struct secpolicy *sp)
1379119643Ssam{
1380120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
1381119643Ssam	free(sp, M_IPSEC_SP);
1382119643Ssam}
1383119643Ssam
1384105197Ssam/*
1385105197Ssam * create secpolicy structure from sadb_x_policy structure.
1386105197Ssam * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1387105197Ssam * so must be set properly later.
1388105197Ssam */
1389105197Ssamstruct secpolicy *
1390105197Ssamkey_msg2sp(xpl0, len, error)
1391105197Ssam	struct sadb_x_policy *xpl0;
1392105197Ssam	size_t len;
1393105197Ssam	int *error;
1394105197Ssam{
1395105197Ssam	struct secpolicy *newsp;
1396105197Ssam
1397120585Ssam	IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1398127972Spjd	IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1399120585Ssam
1400105197Ssam	if (len != PFKEY_EXTLEN(xpl0)) {
1401120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1402105197Ssam		*error = EINVAL;
1403105197Ssam		return NULL;
1404105197Ssam	}
1405105197Ssam
1406105197Ssam	if ((newsp = KEY_NEWSP()) == NULL) {
1407105197Ssam		*error = ENOBUFS;
1408105197Ssam		return NULL;
1409105197Ssam	}
1410105197Ssam
1411105197Ssam	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1412105197Ssam	newsp->policy = xpl0->sadb_x_policy_type;
1413105197Ssam
1414105197Ssam	/* check policy */
1415105197Ssam	switch (xpl0->sadb_x_policy_type) {
1416105197Ssam	case IPSEC_POLICY_DISCARD:
1417105197Ssam	case IPSEC_POLICY_NONE:
1418105197Ssam	case IPSEC_POLICY_ENTRUST:
1419105197Ssam	case IPSEC_POLICY_BYPASS:
1420105197Ssam		newsp->req = NULL;
1421105197Ssam		break;
1422105197Ssam
1423105197Ssam	case IPSEC_POLICY_IPSEC:
1424105197Ssam	    {
1425105197Ssam		int tlen;
1426105197Ssam		struct sadb_x_ipsecrequest *xisr;
1427105197Ssam		struct ipsecrequest **p_isr = &newsp->req;
1428105197Ssam
1429105197Ssam		/* validity check */
1430105197Ssam		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1431120585Ssam			ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1432120585Ssam				__func__));
1433105197Ssam			KEY_FREESP(&newsp);
1434105197Ssam			*error = EINVAL;
1435105197Ssam			return NULL;
1436105197Ssam		}
1437105197Ssam
1438105197Ssam		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1439105197Ssam		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1440105197Ssam
1441105197Ssam		while (tlen > 0) {
1442105197Ssam			/* length check */
1443105197Ssam			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1444120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1445120585Ssam					"length.\n", __func__));
1446105197Ssam				KEY_FREESP(&newsp);
1447105197Ssam				*error = EINVAL;
1448105197Ssam				return NULL;
1449105197Ssam			}
1450105197Ssam
1451105197Ssam			/* allocate request buffer */
1452119643Ssam			/* NB: data structure is zero'd */
1453119643Ssam			*p_isr = ipsec_newisr();
1454105197Ssam			if ((*p_isr) == NULL) {
1455105197Ssam				ipseclog((LOG_DEBUG,
1456120585Ssam				    "%s: No more memory.\n", __func__));
1457105197Ssam				KEY_FREESP(&newsp);
1458105197Ssam				*error = ENOBUFS;
1459105197Ssam				return NULL;
1460105197Ssam			}
1461105197Ssam
1462105197Ssam			/* set values */
1463105197Ssam			switch (xisr->sadb_x_ipsecrequest_proto) {
1464105197Ssam			case IPPROTO_ESP:
1465105197Ssam			case IPPROTO_AH:
1466105197Ssam			case IPPROTO_IPCOMP:
1467105197Ssam				break;
1468105197Ssam			default:
1469105197Ssam				ipseclog((LOG_DEBUG,
1470120585Ssam				    "%s: invalid proto type=%u\n", __func__,
1471105197Ssam				    xisr->sadb_x_ipsecrequest_proto));
1472105197Ssam				KEY_FREESP(&newsp);
1473105197Ssam				*error = EPROTONOSUPPORT;
1474105197Ssam				return NULL;
1475105197Ssam			}
1476105197Ssam			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1477105197Ssam
1478105197Ssam			switch (xisr->sadb_x_ipsecrequest_mode) {
1479105197Ssam			case IPSEC_MODE_TRANSPORT:
1480105197Ssam			case IPSEC_MODE_TUNNEL:
1481105197Ssam				break;
1482105197Ssam			case IPSEC_MODE_ANY:
1483105197Ssam			default:
1484105197Ssam				ipseclog((LOG_DEBUG,
1485120585Ssam				    "%s: invalid mode=%u\n", __func__,
1486105197Ssam				    xisr->sadb_x_ipsecrequest_mode));
1487105197Ssam				KEY_FREESP(&newsp);
1488105197Ssam				*error = EINVAL;
1489105197Ssam				return NULL;
1490105197Ssam			}
1491105197Ssam			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1492105197Ssam
1493105197Ssam			switch (xisr->sadb_x_ipsecrequest_level) {
1494105197Ssam			case IPSEC_LEVEL_DEFAULT:
1495105197Ssam			case IPSEC_LEVEL_USE:
1496105197Ssam			case IPSEC_LEVEL_REQUIRE:
1497105197Ssam				break;
1498105197Ssam			case IPSEC_LEVEL_UNIQUE:
1499105197Ssam				/* validity check */
1500105197Ssam				/*
1501105197Ssam				 * If range violation of reqid, kernel will
1502105197Ssam				 * update it, don't refuse it.
1503105197Ssam				 */
1504105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid
1505105197Ssam						> IPSEC_MANUAL_REQID_MAX) {
1506105197Ssam					ipseclog((LOG_DEBUG,
1507120585Ssam					    "%s: reqid=%d range "
1508105197Ssam					    "violation, updated by kernel.\n",
1509120585Ssam					    __func__,
1510105197Ssam					    xisr->sadb_x_ipsecrequest_reqid));
1511105197Ssam					xisr->sadb_x_ipsecrequest_reqid = 0;
1512105197Ssam				}
1513105197Ssam
1514105197Ssam				/* allocate new reqid id if reqid is zero. */
1515105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1516105197Ssam					u_int32_t reqid;
1517105197Ssam					if ((reqid = key_newreqid()) == 0) {
1518105197Ssam						KEY_FREESP(&newsp);
1519105197Ssam						*error = ENOBUFS;
1520105197Ssam						return NULL;
1521105197Ssam					}
1522105197Ssam					(*p_isr)->saidx.reqid = reqid;
1523105197Ssam					xisr->sadb_x_ipsecrequest_reqid = reqid;
1524105197Ssam				} else {
1525105197Ssam				/* set it for manual keying. */
1526105197Ssam					(*p_isr)->saidx.reqid =
1527105197Ssam						xisr->sadb_x_ipsecrequest_reqid;
1528105197Ssam				}
1529105197Ssam				break;
1530105197Ssam
1531105197Ssam			default:
1532120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1533120585Ssam					__func__,
1534105197Ssam					xisr->sadb_x_ipsecrequest_level));
1535105197Ssam				KEY_FREESP(&newsp);
1536105197Ssam				*error = EINVAL;
1537105197Ssam				return NULL;
1538105197Ssam			}
1539105197Ssam			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1540105197Ssam
1541105197Ssam			/* set IP addresses if there */
1542105197Ssam			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1543105197Ssam				struct sockaddr *paddr;
1544105197Ssam
1545105197Ssam				paddr = (struct sockaddr *)(xisr + 1);
1546105197Ssam
1547105197Ssam				/* validity check */
1548105197Ssam				if (paddr->sa_len
1549105197Ssam				    > sizeof((*p_isr)->saidx.src)) {
1550120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1551120585Ssam						"request address length.\n",
1552120585Ssam						__func__));
1553105197Ssam					KEY_FREESP(&newsp);
1554105197Ssam					*error = EINVAL;
1555105197Ssam					return NULL;
1556105197Ssam				}
1557105197Ssam				bcopy(paddr, &(*p_isr)->saidx.src,
1558105197Ssam					paddr->sa_len);
1559105197Ssam
1560105197Ssam				paddr = (struct sockaddr *)((caddr_t)paddr
1561105197Ssam							+ paddr->sa_len);
1562105197Ssam
1563105197Ssam				/* validity check */
1564105197Ssam				if (paddr->sa_len
1565105197Ssam				    > sizeof((*p_isr)->saidx.dst)) {
1566120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1567120585Ssam						"request address length.\n",
1568120585Ssam						__func__));
1569105197Ssam					KEY_FREESP(&newsp);
1570105197Ssam					*error = EINVAL;
1571105197Ssam					return NULL;
1572105197Ssam				}
1573105197Ssam				bcopy(paddr, &(*p_isr)->saidx.dst,
1574105197Ssam					paddr->sa_len);
1575105197Ssam			}
1576105197Ssam
1577105197Ssam			(*p_isr)->sp = newsp;
1578105197Ssam
1579105197Ssam			/* initialization for the next. */
1580105197Ssam			p_isr = &(*p_isr)->next;
1581105197Ssam			tlen -= xisr->sadb_x_ipsecrequest_len;
1582105197Ssam
1583105197Ssam			/* validity check */
1584105197Ssam			if (tlen < 0) {
1585120585Ssam				ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1586120585Ssam					__func__));
1587105197Ssam				KEY_FREESP(&newsp);
1588105197Ssam				*error = EINVAL;
1589105197Ssam				return NULL;
1590105197Ssam			}
1591105197Ssam
1592105197Ssam			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1593105197Ssam			                 + xisr->sadb_x_ipsecrequest_len);
1594105197Ssam		}
1595105197Ssam	    }
1596105197Ssam		break;
1597105197Ssam	default:
1598120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1599105197Ssam		KEY_FREESP(&newsp);
1600105197Ssam		*error = EINVAL;
1601105197Ssam		return NULL;
1602105197Ssam	}
1603105197Ssam
1604105197Ssam	*error = 0;
1605105197Ssam	return newsp;
1606105197Ssam}
1607105197Ssam
1608105197Ssamstatic u_int32_t
1609105197Ssamkey_newreqid()
1610105197Ssam{
1611105197Ssam	static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1612105197Ssam
1613105197Ssam	auto_reqid = (auto_reqid == ~0
1614105197Ssam			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1615105197Ssam
1616105197Ssam	/* XXX should be unique check */
1617105197Ssam
1618105197Ssam	return auto_reqid;
1619105197Ssam}
1620105197Ssam
1621105197Ssam/*
1622105197Ssam * copy secpolicy struct to sadb_x_policy structure indicated.
1623105197Ssam */
1624105197Ssamstruct mbuf *
1625105197Ssamkey_sp2msg(sp)
1626105197Ssam	struct secpolicy *sp;
1627105197Ssam{
1628105197Ssam	struct sadb_x_policy *xpl;
1629105197Ssam	int tlen;
1630105197Ssam	caddr_t p;
1631105197Ssam	struct mbuf *m;
1632105197Ssam
1633120585Ssam	IPSEC_ASSERT(sp != NULL, ("null policy"));
1634105197Ssam
1635105197Ssam	tlen = key_getspreqmsglen(sp);
1636105197Ssam
1637105197Ssam	m = key_alloc_mbuf(tlen);
1638105197Ssam	if (!m || m->m_next) {	/*XXX*/
1639105197Ssam		if (m)
1640105197Ssam			m_freem(m);
1641105197Ssam		return NULL;
1642105197Ssam	}
1643105197Ssam
1644105197Ssam	m->m_len = tlen;
1645105197Ssam	m->m_next = NULL;
1646105197Ssam	xpl = mtod(m, struct sadb_x_policy *);
1647105197Ssam	bzero(xpl, tlen);
1648105197Ssam
1649105197Ssam	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1650105197Ssam	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1651105197Ssam	xpl->sadb_x_policy_type = sp->policy;
1652105197Ssam	xpl->sadb_x_policy_dir = sp->spidx.dir;
1653105197Ssam	xpl->sadb_x_policy_id = sp->id;
1654105197Ssam	p = (caddr_t)xpl + sizeof(*xpl);
1655105197Ssam
1656105197Ssam	/* if is the policy for ipsec ? */
1657105197Ssam	if (sp->policy == IPSEC_POLICY_IPSEC) {
1658105197Ssam		struct sadb_x_ipsecrequest *xisr;
1659105197Ssam		struct ipsecrequest *isr;
1660105197Ssam
1661105197Ssam		for (isr = sp->req; isr != NULL; isr = isr->next) {
1662105197Ssam
1663105197Ssam			xisr = (struct sadb_x_ipsecrequest *)p;
1664105197Ssam
1665105197Ssam			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1666105197Ssam			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1667105197Ssam			xisr->sadb_x_ipsecrequest_level = isr->level;
1668105197Ssam			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1669105197Ssam
1670105197Ssam			p += sizeof(*xisr);
1671105197Ssam			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1672105197Ssam			p += isr->saidx.src.sa.sa_len;
1673105197Ssam			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1674105197Ssam			p += isr->saidx.src.sa.sa_len;
1675105197Ssam
1676105197Ssam			xisr->sadb_x_ipsecrequest_len =
1677105197Ssam				PFKEY_ALIGN8(sizeof(*xisr)
1678105197Ssam					+ isr->saidx.src.sa.sa_len
1679105197Ssam					+ isr->saidx.dst.sa.sa_len);
1680105197Ssam		}
1681105197Ssam	}
1682105197Ssam
1683105197Ssam	return m;
1684105197Ssam}
1685105197Ssam
1686105197Ssam/* m will not be freed nor modified */
1687105197Ssamstatic struct mbuf *
1688105197Ssam#ifdef __STDC__
1689105197Ssamkey_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1690105197Ssam	int ndeep, int nitem, ...)
1691105197Ssam#else
1692105197Ssamkey_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1693105197Ssam	struct mbuf *m;
1694105197Ssam	const struct sadb_msghdr *mhp;
1695105197Ssam	int ndeep;
1696105197Ssam	int nitem;
1697105197Ssam	va_dcl
1698105197Ssam#endif
1699105197Ssam{
1700105197Ssam	va_list ap;
1701105197Ssam	int idx;
1702105197Ssam	int i;
1703105197Ssam	struct mbuf *result = NULL, *n;
1704105197Ssam	int len;
1705105197Ssam
1706120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1707120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1708105197Ssam
1709105197Ssam	va_start(ap, nitem);
1710105197Ssam	for (i = 0; i < nitem; i++) {
1711105197Ssam		idx = va_arg(ap, int);
1712105197Ssam		if (idx < 0 || idx > SADB_EXT_MAX)
1713105197Ssam			goto fail;
1714105197Ssam		/* don't attempt to pull empty extension */
1715105197Ssam		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1716105197Ssam			continue;
1717105197Ssam		if (idx != SADB_EXT_RESERVED  &&
1718105197Ssam		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1719105197Ssam			continue;
1720105197Ssam
1721105197Ssam		if (idx == SADB_EXT_RESERVED) {
1722105197Ssam			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1723120585Ssam
1724120585Ssam			IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1725120585Ssam
1726111119Simp			MGETHDR(n, M_DONTWAIT, MT_DATA);
1727105197Ssam			if (!n)
1728105197Ssam				goto fail;
1729105197Ssam			n->m_len = len;
1730105197Ssam			n->m_next = NULL;
1731105197Ssam			m_copydata(m, 0, sizeof(struct sadb_msg),
1732105197Ssam			    mtod(n, caddr_t));
1733105197Ssam		} else if (i < ndeep) {
1734105197Ssam			len = mhp->extlen[idx];
1735105197Ssam			n = key_alloc_mbuf(len);
1736105197Ssam			if (!n || n->m_next) {	/*XXX*/
1737105197Ssam				if (n)
1738105197Ssam					m_freem(n);
1739105197Ssam				goto fail;
1740105197Ssam			}
1741105197Ssam			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1742105197Ssam			    mtod(n, caddr_t));
1743105197Ssam		} else {
1744105197Ssam			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1745111119Simp			    M_DONTWAIT);
1746105197Ssam		}
1747105197Ssam		if (n == NULL)
1748105197Ssam			goto fail;
1749105197Ssam
1750105197Ssam		if (result)
1751105197Ssam			m_cat(result, n);
1752105197Ssam		else
1753105197Ssam			result = n;
1754105197Ssam	}
1755105197Ssam	va_end(ap);
1756105197Ssam
1757105197Ssam	if ((result->m_flags & M_PKTHDR) != 0) {
1758105197Ssam		result->m_pkthdr.len = 0;
1759105197Ssam		for (n = result; n; n = n->m_next)
1760105197Ssam			result->m_pkthdr.len += n->m_len;
1761105197Ssam	}
1762105197Ssam
1763105197Ssam	return result;
1764105197Ssam
1765105197Ssamfail:
1766105197Ssam	m_freem(result);
1767226386Sbrueffer	va_end(ap);
1768105197Ssam	return NULL;
1769105197Ssam}
1770105197Ssam
1771105197Ssam/*
1772105197Ssam * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1773108533Sschweikh * add an entry to SP database, when received
1774105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1775105197Ssam * from the user(?).
1776105197Ssam * Adding to SP database,
1777105197Ssam * and send
1778105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1779105197Ssam * to the socket which was send.
1780105197Ssam *
1781105197Ssam * SPDADD set a unique policy entry.
1782105197Ssam * SPDSETIDX like SPDADD without a part of policy requests.
1783105197Ssam * SPDUPDATE replace a unique policy entry.
1784105197Ssam *
1785105197Ssam * m will always be freed.
1786105197Ssam */
1787105197Ssamstatic int
1788105197Ssamkey_spdadd(so, m, mhp)
1789105197Ssam	struct socket *so;
1790105197Ssam	struct mbuf *m;
1791105197Ssam	const struct sadb_msghdr *mhp;
1792105197Ssam{
1793105197Ssam	struct sadb_address *src0, *dst0;
1794105197Ssam	struct sadb_x_policy *xpl0, *xpl;
1795105197Ssam	struct sadb_lifetime *lft = NULL;
1796105197Ssam	struct secpolicyindex spidx;
1797105197Ssam	struct secpolicy *newsp;
1798105197Ssam	int error;
1799105197Ssam
1800120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
1801120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1802120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1803120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1804105197Ssam
1805105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1806105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1807105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1808105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1809105197Ssam		return key_senderror(so, m, EINVAL);
1810105197Ssam	}
1811105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1812105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1813105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1814120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1815120585Ssam			__func__));
1816105197Ssam		return key_senderror(so, m, EINVAL);
1817105197Ssam	}
1818105197Ssam	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1819105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1820105197Ssam			< sizeof(struct sadb_lifetime)) {
1821120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1822120585Ssam				__func__));
1823105197Ssam			return key_senderror(so, m, EINVAL);
1824105197Ssam		}
1825105197Ssam		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1826105197Ssam	}
1827105197Ssam
1828105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1829105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1830105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1831105197Ssam
1832194062Svanhu	/*
1833194062Svanhu	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
1834194062Svanhu	 * we are processing traffic endpoints.
1835194062Svanhu	 */
1836194062Svanhu
1837105197Ssam	/* make secindex */
1838105197Ssam	/* XXX boundary check against sa_len */
1839105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1840105197Ssam	                src0 + 1,
1841105197Ssam	                dst0 + 1,
1842105197Ssam	                src0->sadb_address_prefixlen,
1843105197Ssam	                dst0->sadb_address_prefixlen,
1844105197Ssam	                src0->sadb_address_proto,
1845105197Ssam	                &spidx);
1846105197Ssam
1847105197Ssam	/* checking the direciton. */
1848105197Ssam	switch (xpl0->sadb_x_policy_dir) {
1849105197Ssam	case IPSEC_DIR_INBOUND:
1850105197Ssam	case IPSEC_DIR_OUTBOUND:
1851105197Ssam		break;
1852105197Ssam	default:
1853120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1854105197Ssam		mhp->msg->sadb_msg_errno = EINVAL;
1855105197Ssam		return 0;
1856105197Ssam	}
1857105197Ssam
1858105197Ssam	/* check policy */
1859105197Ssam	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1860105197Ssam	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1861105197Ssam	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1862120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1863105197Ssam		return key_senderror(so, m, EINVAL);
1864105197Ssam	}
1865105197Ssam
1866105197Ssam	/* policy requests are mandatory when action is ipsec. */
1867105197Ssam        if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1868105197Ssam	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1869105197Ssam	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1870120585Ssam		ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1871120585Ssam			__func__));
1872105197Ssam		return key_senderror(so, m, EINVAL);
1873105197Ssam	}
1874105197Ssam
1875105197Ssam	/*
1876105197Ssam	 * checking there is SP already or not.
1877105197Ssam	 * SPDUPDATE doesn't depend on whether there is a SP or not.
1878105197Ssam	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1879105197Ssam	 * then error.
1880105197Ssam	 */
1881105197Ssam	newsp = key_getsp(&spidx);
1882105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1883105197Ssam		if (newsp) {
1884206659Svanhu			SPTREE_LOCK();
1885105197Ssam			newsp->state = IPSEC_SPSTATE_DEAD;
1886206659Svanhu			SPTREE_UNLOCK();
1887105197Ssam			KEY_FREESP(&newsp);
1888105197Ssam		}
1889105197Ssam	} else {
1890105197Ssam		if (newsp != NULL) {
1891105197Ssam			KEY_FREESP(&newsp);
1892120585Ssam			ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1893120585Ssam				__func__));
1894105197Ssam			return key_senderror(so, m, EEXIST);
1895105197Ssam		}
1896105197Ssam	}
1897105197Ssam
1898105197Ssam	/* allocation new SP entry */
1899105197Ssam	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1900105197Ssam		return key_senderror(so, m, error);
1901105197Ssam	}
1902105197Ssam
1903105197Ssam	if ((newsp->id = key_getnewspid()) == 0) {
1904119643Ssam		_key_delsp(newsp);
1905105197Ssam		return key_senderror(so, m, ENOBUFS);
1906105197Ssam	}
1907105197Ssam
1908105197Ssam	/* XXX boundary check against sa_len */
1909105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1910105197Ssam	                src0 + 1,
1911105197Ssam	                dst0 + 1,
1912105197Ssam	                src0->sadb_address_prefixlen,
1913105197Ssam	                dst0->sadb_address_prefixlen,
1914105197Ssam	                src0->sadb_address_proto,
1915105197Ssam	                &newsp->spidx);
1916105197Ssam
1917105197Ssam	/* sanity check on addr pair */
1918105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1919105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_family) {
1920119643Ssam		_key_delsp(newsp);
1921105197Ssam		return key_senderror(so, m, EINVAL);
1922105197Ssam	}
1923105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1924105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_len) {
1925119643Ssam		_key_delsp(newsp);
1926105197Ssam		return key_senderror(so, m, EINVAL);
1927105197Ssam	}
1928105197Ssam#if 1
1929197250Svanhu	if (newsp->req && newsp->req->saidx.src.sa.sa_family && newsp->req->saidx.dst.sa.sa_family) {
1930197250Svanhu		if (newsp->req->saidx.src.sa.sa_family != newsp->req->saidx.dst.sa.sa_family) {
1931119643Ssam			_key_delsp(newsp);
1932105197Ssam			return key_senderror(so, m, EINVAL);
1933105197Ssam		}
1934105197Ssam	}
1935105197Ssam#endif
1936105197Ssam
1937105197Ssam	newsp->created = time_second;
1938105197Ssam	newsp->lastused = newsp->created;
1939105197Ssam	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1940105197Ssam	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1941105197Ssam
1942105197Ssam	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1943105197Ssam	newsp->state = IPSEC_SPSTATE_ALIVE;
1944181803Sbz	LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1945105197Ssam
1946105197Ssam	/* delete the entry in spacqtree */
1947105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1948119643Ssam		struct secspacq *spacq = key_getspacq(&spidx);
1949119643Ssam		if (spacq != NULL) {
1950105197Ssam			/* reset counter in order to deletion by timehandler. */
1951105197Ssam			spacq->created = time_second;
1952105197Ssam			spacq->count = 0;
1953120585Ssam			SPACQ_UNLOCK();
1954105197Ssam		}
1955105197Ssam    	}
1956105197Ssam
1957105197Ssam    {
1958105197Ssam	struct mbuf *n, *mpolicy;
1959105197Ssam	struct sadb_msg *newmsg;
1960105197Ssam	int off;
1961105197Ssam
1962194062Svanhu	/*
1963194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
1964194062Svanhu	 * we are sending traffic endpoints.
1965194062Svanhu	 */
1966194062Svanhu
1967105197Ssam	/* create new sadb_msg to reply. */
1968105197Ssam	if (lft) {
1969105197Ssam		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1970105197Ssam		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1971105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1972105197Ssam	} else {
1973105197Ssam		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1974105197Ssam		    SADB_X_EXT_POLICY,
1975105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1976105197Ssam	}
1977105197Ssam	if (!n)
1978105197Ssam		return key_senderror(so, m, ENOBUFS);
1979105197Ssam
1980105197Ssam	if (n->m_len < sizeof(*newmsg)) {
1981105197Ssam		n = m_pullup(n, sizeof(*newmsg));
1982105197Ssam		if (!n)
1983105197Ssam			return key_senderror(so, m, ENOBUFS);
1984105197Ssam	}
1985105197Ssam	newmsg = mtod(n, struct sadb_msg *);
1986105197Ssam	newmsg->sadb_msg_errno = 0;
1987105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1988105197Ssam
1989105197Ssam	off = 0;
1990105197Ssam	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1991105197Ssam	    sizeof(*xpl), &off);
1992105197Ssam	if (mpolicy == NULL) {
1993105197Ssam		/* n is already freed */
1994105197Ssam		return key_senderror(so, m, ENOBUFS);
1995105197Ssam	}
1996105197Ssam	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1997105197Ssam	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1998105197Ssam		m_freem(n);
1999105197Ssam		return key_senderror(so, m, EINVAL);
2000105197Ssam	}
2001105197Ssam	xpl->sadb_x_policy_id = newsp->id;
2002105197Ssam
2003105197Ssam	m_freem(m);
2004105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2005105197Ssam    }
2006105197Ssam}
2007105197Ssam
2008105197Ssam/*
2009105197Ssam * get new policy id.
2010105197Ssam * OUT:
2011105197Ssam *	0:	failure.
2012105197Ssam *	others: success.
2013105197Ssam */
2014105197Ssamstatic u_int32_t
2015105197Ssamkey_getnewspid()
2016105197Ssam{
2017105197Ssam	u_int32_t newid = 0;
2018181803Sbz	int count = V_key_spi_trycnt;	/* XXX */
2019105197Ssam	struct secpolicy *sp;
2020105197Ssam
2021105197Ssam	/* when requesting to allocate spi ranged */
2022105197Ssam	while (count--) {
2023181803Sbz		newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
2024105197Ssam
2025105197Ssam		if ((sp = key_getspbyid(newid)) == NULL)
2026105197Ssam			break;
2027105197Ssam
2028105197Ssam		KEY_FREESP(&sp);
2029105197Ssam	}
2030105197Ssam
2031105197Ssam	if (count == 0 || newid == 0) {
2032120585Ssam		ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2033120585Ssam			__func__));
2034105197Ssam		return 0;
2035105197Ssam	}
2036105197Ssam
2037105197Ssam	return newid;
2038105197Ssam}
2039105197Ssam
2040105197Ssam/*
2041105197Ssam * SADB_SPDDELETE processing
2042105197Ssam * receive
2043105197Ssam *   <base, address(SD), policy(*)>
2044105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2045105197Ssam * and send,
2046105197Ssam *   <base, address(SD), policy(*)>
2047105197Ssam * to the ikmpd.
2048105197Ssam * policy(*) including direction of policy.
2049105197Ssam *
2050105197Ssam * m will always be freed.
2051105197Ssam */
2052105197Ssamstatic int
2053105197Ssamkey_spddelete(so, m, mhp)
2054105197Ssam	struct socket *so;
2055105197Ssam	struct mbuf *m;
2056105197Ssam	const struct sadb_msghdr *mhp;
2057105197Ssam{
2058105197Ssam	struct sadb_address *src0, *dst0;
2059105197Ssam	struct sadb_x_policy *xpl0;
2060105197Ssam	struct secpolicyindex spidx;
2061105197Ssam	struct secpolicy *sp;
2062105197Ssam
2063120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
2064120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2065120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2066120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2067105197Ssam
2068105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2069105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2070105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2071120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2072120585Ssam			__func__));
2073105197Ssam		return key_senderror(so, m, EINVAL);
2074105197Ssam	}
2075105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2076105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2077105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2078120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2079120585Ssam			__func__));
2080105197Ssam		return key_senderror(so, m, EINVAL);
2081105197Ssam	}
2082105197Ssam
2083105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2084105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2085105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2086105197Ssam
2087194062Svanhu	/*
2088194062Svanhu	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
2089194062Svanhu	 * we are processing traffic endpoints.
2090194062Svanhu	 */
2091194062Svanhu
2092105197Ssam	/* make secindex */
2093105197Ssam	/* XXX boundary check against sa_len */
2094105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2095105197Ssam	                src0 + 1,
2096105197Ssam	                dst0 + 1,
2097105197Ssam	                src0->sadb_address_prefixlen,
2098105197Ssam	                dst0->sadb_address_prefixlen,
2099105197Ssam	                src0->sadb_address_proto,
2100105197Ssam	                &spidx);
2101105197Ssam
2102105197Ssam	/* checking the direciton. */
2103105197Ssam	switch (xpl0->sadb_x_policy_dir) {
2104105197Ssam	case IPSEC_DIR_INBOUND:
2105105197Ssam	case IPSEC_DIR_OUTBOUND:
2106105197Ssam		break;
2107105197Ssam	default:
2108120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2109105197Ssam		return key_senderror(so, m, EINVAL);
2110105197Ssam	}
2111105197Ssam
2112105197Ssam	/* Is there SP in SPD ? */
2113105197Ssam	if ((sp = key_getsp(&spidx)) == NULL) {
2114120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2115105197Ssam		return key_senderror(so, m, EINVAL);
2116105197Ssam	}
2117105197Ssam
2118105197Ssam	/* save policy id to buffer to be returned. */
2119105197Ssam	xpl0->sadb_x_policy_id = sp->id;
2120105197Ssam
2121206659Svanhu	SPTREE_LOCK();
2122105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2123206659Svanhu	SPTREE_UNLOCK();
2124105197Ssam	KEY_FREESP(&sp);
2125105197Ssam
2126105197Ssam    {
2127105197Ssam	struct mbuf *n;
2128105197Ssam	struct sadb_msg *newmsg;
2129105197Ssam
2130194062Svanhu	/*
2131194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2132194062Svanhu	 * we are sending traffic endpoints.
2133194062Svanhu	 */
2134194062Svanhu
2135105197Ssam	/* create new sadb_msg to reply. */
2136105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2137105197Ssam	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2138105197Ssam	if (!n)
2139105197Ssam		return key_senderror(so, m, ENOBUFS);
2140105197Ssam
2141105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2142105197Ssam	newmsg->sadb_msg_errno = 0;
2143105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2144105197Ssam
2145105197Ssam	m_freem(m);
2146105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2147105197Ssam    }
2148105197Ssam}
2149105197Ssam
2150105197Ssam/*
2151105197Ssam * SADB_SPDDELETE2 processing
2152105197Ssam * receive
2153105197Ssam *   <base, policy(*)>
2154105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2155105197Ssam * and send,
2156105197Ssam *   <base, policy(*)>
2157105197Ssam * to the ikmpd.
2158105197Ssam * policy(*) including direction of policy.
2159105197Ssam *
2160105197Ssam * m will always be freed.
2161105197Ssam */
2162105197Ssamstatic int
2163105197Ssamkey_spddelete2(so, m, mhp)
2164105197Ssam	struct socket *so;
2165105197Ssam	struct mbuf *m;
2166105197Ssam	const struct sadb_msghdr *mhp;
2167105197Ssam{
2168105197Ssam	u_int32_t id;
2169105197Ssam	struct secpolicy *sp;
2170105197Ssam
2171120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2172120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2173120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2174120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2175105197Ssam
2176105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2177105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2178120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2179170803Sbz		return key_senderror(so, m, EINVAL);
2180105197Ssam	}
2181105197Ssam
2182105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2183105197Ssam
2184105197Ssam	/* Is there SP in SPD ? */
2185105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2186120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2187170803Sbz		return key_senderror(so, m, EINVAL);
2188105197Ssam	}
2189105197Ssam
2190206659Svanhu	SPTREE_LOCK();
2191105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2192206659Svanhu	SPTREE_UNLOCK();
2193105197Ssam	KEY_FREESP(&sp);
2194105197Ssam
2195105197Ssam    {
2196105197Ssam	struct mbuf *n, *nn;
2197105197Ssam	struct sadb_msg *newmsg;
2198105197Ssam	int off, len;
2199105197Ssam
2200105197Ssam	/* create new sadb_msg to reply. */
2201105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2202105197Ssam
2203111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
2204105197Ssam	if (n && len > MHLEN) {
2205111119Simp		MCLGET(n, M_DONTWAIT);
2206105197Ssam		if ((n->m_flags & M_EXT) == 0) {
2207105197Ssam			m_freem(n);
2208105197Ssam			n = NULL;
2209105197Ssam		}
2210105197Ssam	}
2211105197Ssam	if (!n)
2212105197Ssam		return key_senderror(so, m, ENOBUFS);
2213105197Ssam
2214105197Ssam	n->m_len = len;
2215105197Ssam	n->m_next = NULL;
2216105197Ssam	off = 0;
2217105197Ssam
2218105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2219105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2220105197Ssam
2221120585Ssam	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2222120585Ssam		off, len));
2223105197Ssam
2224105197Ssam	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2225111119Simp	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2226105197Ssam	if (!n->m_next) {
2227105197Ssam		m_freem(n);
2228105197Ssam		return key_senderror(so, m, ENOBUFS);
2229105197Ssam	}
2230105197Ssam
2231105197Ssam	n->m_pkthdr.len = 0;
2232105197Ssam	for (nn = n; nn; nn = nn->m_next)
2233105197Ssam		n->m_pkthdr.len += nn->m_len;
2234105197Ssam
2235105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2236105197Ssam	newmsg->sadb_msg_errno = 0;
2237105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2238105197Ssam
2239105197Ssam	m_freem(m);
2240105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2241105197Ssam    }
2242105197Ssam}
2243105197Ssam
2244105197Ssam/*
2245105197Ssam * SADB_X_GET processing
2246105197Ssam * receive
2247105197Ssam *   <base, policy(*)>
2248105197Ssam * from the user(?),
2249105197Ssam * and send,
2250105197Ssam *   <base, address(SD), policy>
2251105197Ssam * to the ikmpd.
2252105197Ssam * policy(*) including direction of policy.
2253105197Ssam *
2254105197Ssam * m will always be freed.
2255105197Ssam */
2256105197Ssamstatic int
2257105197Ssamkey_spdget(so, m, mhp)
2258105197Ssam	struct socket *so;
2259105197Ssam	struct mbuf *m;
2260105197Ssam	const struct sadb_msghdr *mhp;
2261105197Ssam{
2262105197Ssam	u_int32_t id;
2263105197Ssam	struct secpolicy *sp;
2264105197Ssam	struct mbuf *n;
2265105197Ssam
2266120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2267120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2268120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2269120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2270105197Ssam
2271105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2272105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2273120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2274120585Ssam			__func__));
2275105197Ssam		return key_senderror(so, m, EINVAL);
2276105197Ssam	}
2277105197Ssam
2278105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2279105197Ssam
2280105197Ssam	/* Is there SP in SPD ? */
2281105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2282120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2283105197Ssam		return key_senderror(so, m, ENOENT);
2284105197Ssam	}
2285105197Ssam
2286105197Ssam	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2287221692Svanhu	KEY_FREESP(&sp);
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);
2760214250Sbz		if (sah->route_cache.sa_route.ro_rt) {
2761214250Sbz			RTFREE(sah->route_cache.sa_route.ro_rt);
2762214250Sbz			sah->route_cache.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
5158194062Svanhu#ifdef IPSEC_NAT_T
5159194062Svanhu	/*
5160194062Svanhu	 * Handle more NAT-T info if present,
5161194062Svanhu	 * now that we have a sav to fill.
5162194062Svanhu	 */
5163194062Svanhu	if (type)
5164194062Svanhu		sav->natt_type = type->sadb_x_nat_t_type_type;
5165194062Svanhu
5166194513Sbz	if (sport)
5167194513Sbz		KEY_PORTTOSADDR(&sav->sah->saidx.src,
5168194513Sbz		    sport->sadb_x_nat_t_port_port);
5169194513Sbz	if (dport)
5170194513Sbz		KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5171194513Sbz		    dport->sadb_x_nat_t_port_port);
5172194513Sbz
5173194062Svanhu#if 0
5174194062Svanhu	/*
5175194062Svanhu	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5176194062Svanhu	 * We should actually check for a minimum MTU here, if we
5177194062Svanhu	 * want to support it in ip_output.
5178194062Svanhu	 */
5179194062Svanhu	if (frag)
5180194062Svanhu		sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5181194062Svanhu#endif
5182194062Svanhu#endif
5183194062Svanhu
5184207651Svanhu	/* check SA values to be mature. */
5185207651Svanhu	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5186207651Svanhu		KEY_FREESAV(&sav);
5187207651Svanhu		return key_senderror(so, m, 0);
5188207651Svanhu	}
5189207651Svanhu
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
5424194062Svanhu#ifdef IPSEC_NAT_T
5425105197Ssam	/*
5426194062Svanhu	 * Handle more NAT-T info if present,
5427194062Svanhu	 * now that we have a sav to fill.
5428194062Svanhu	 */
5429194062Svanhu	if (type)
5430194062Svanhu		newsav->natt_type = type->sadb_x_nat_t_type_type;
5431194062Svanhu
5432194062Svanhu#if 0
5433194062Svanhu	/*
5434194062Svanhu	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5435194062Svanhu	 * We should actually check for a minimum MTU here, if we
5436194062Svanhu	 * want to support it in ip_output.
5437194062Svanhu	 */
5438194062Svanhu	if (frag)
5439194062Svanhu		newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5440194062Svanhu#endif
5441194062Svanhu#endif
5442194062Svanhu
5443207652Svanhu	/* check SA values to be mature. */
5444207652Svanhu	if ((error = key_mature(newsav)) != 0) {
5445207652Svanhu		KEY_FREESAV(&newsav);
5446207652Svanhu		return key_senderror(so, m, error);
5447207652Svanhu	}
5448207652Svanhu
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;
6097218794Svanhu		case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
6098218794Svanhu		case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
6099218794Svanhu		case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
6100105197Ssam		default:
6101120585Ssam			DPRINTF(("%s: unknown AH algorithm %u\n",
6102120585Ssam				__func__, alg));
6103105197Ssam			break;
6104105197Ssam		}
6105105197Ssam	}
6106105197Ssam}
6107105197Ssam
6108105197Ssam/*
6109105197Ssam * XXX reorder combinations by preference
6110105197Ssam */
6111105197Ssamstatic struct mbuf *
6112105197Ssamkey_getcomb_ah()
6113105197Ssam{
6114105197Ssam	struct sadb_comb *comb;
6115105197Ssam	struct auth_hash *algo;
6116105197Ssam	struct mbuf *m;
6117105197Ssam	u_int16_t minkeysize, maxkeysize;
6118105197Ssam	int i;
6119105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6120105197Ssam
6121105197Ssam	m = NULL;
6122105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6123105197Ssam#if 1
6124105197Ssam		/* we prefer HMAC algorithms, not old algorithms */
6125218794Svanhu		if (i != SADB_AALG_SHA1HMAC &&
6126218794Svanhu		    i != SADB_AALG_MD5HMAC  &&
6127218794Svanhu		    i != SADB_X_AALG_SHA2_256 &&
6128218794Svanhu		    i != SADB_X_AALG_SHA2_384 &&
6129218794Svanhu		    i != SADB_X_AALG_SHA2_512)
6130105197Ssam			continue;
6131105197Ssam#endif
6132105197Ssam		algo = ah_algorithm_lookup(i);
6133105197Ssam		if (!algo)
6134105197Ssam			continue;
6135105197Ssam		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6136105197Ssam		/* discard algorithms with key size smaller than system min */
6137181803Sbz		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6138105197Ssam			continue;
6139105197Ssam
6140105197Ssam		if (!m) {
6141120585Ssam			IPSEC_ASSERT(l <= MLEN,
6142120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6143111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
6144105197Ssam			if (m) {
6145105197Ssam				M_ALIGN(m, l);
6146105197Ssam				m->m_len = l;
6147105197Ssam				m->m_next = NULL;
6148105197Ssam			}
6149105197Ssam		} else
6150111119Simp			M_PREPEND(m, l, M_DONTWAIT);
6151105197Ssam		if (!m)
6152105197Ssam			return NULL;
6153105197Ssam
6154105197Ssam		comb = mtod(m, struct sadb_comb *);
6155105197Ssam		bzero(comb, sizeof(*comb));
6156105197Ssam		key_getcomb_setlifetime(comb);
6157105197Ssam		comb->sadb_comb_auth = i;
6158105197Ssam		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6159105197Ssam		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6160105197Ssam	}
6161105197Ssam
6162105197Ssam	return m;
6163105197Ssam}
6164105197Ssam
6165105197Ssam/*
6166105197Ssam * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6167105197Ssam * XXX reorder combinations by preference
6168105197Ssam */
6169105197Ssamstatic struct mbuf *
6170105197Ssamkey_getcomb_ipcomp()
6171105197Ssam{
6172105197Ssam	struct sadb_comb *comb;
6173105197Ssam	struct comp_algo *algo;
6174105197Ssam	struct mbuf *m;
6175105197Ssam	int i;
6176105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6177105197Ssam
6178105197Ssam	m = NULL;
6179105197Ssam	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6180105197Ssam		algo = ipcomp_algorithm_lookup(i);
6181105197Ssam		if (!algo)
6182105197Ssam			continue;
6183105197Ssam
6184105197Ssam		if (!m) {
6185120585Ssam			IPSEC_ASSERT(l <= MLEN,
6186120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6187111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
6188105197Ssam			if (m) {
6189105197Ssam				M_ALIGN(m, l);
6190105197Ssam				m->m_len = l;
6191105197Ssam				m->m_next = NULL;
6192105197Ssam			}
6193105197Ssam		} else
6194111119Simp			M_PREPEND(m, l, M_DONTWAIT);
6195105197Ssam		if (!m)
6196105197Ssam			return NULL;
6197105197Ssam
6198105197Ssam		comb = mtod(m, struct sadb_comb *);
6199105197Ssam		bzero(comb, sizeof(*comb));
6200105197Ssam		key_getcomb_setlifetime(comb);
6201105197Ssam		comb->sadb_comb_encrypt = i;
6202105197Ssam		/* what should we set into sadb_comb_*_{min,max}bits? */
6203105197Ssam	}
6204105197Ssam
6205105197Ssam	return m;
6206105197Ssam}
6207105197Ssam
6208105197Ssam/*
6209105197Ssam * XXX no way to pass mode (transport/tunnel) to userland
6210105197Ssam * XXX replay checking?
6211105197Ssam * XXX sysctl interface to ipsec_{ah,esp}_keymin
6212105197Ssam */
6213105197Ssamstatic struct mbuf *
6214105197Ssamkey_getprop(saidx)
6215105197Ssam	const struct secasindex *saidx;
6216105197Ssam{
6217105197Ssam	struct sadb_prop *prop;
6218105197Ssam	struct mbuf *m, *n;
6219105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6220105197Ssam	int totlen;
6221105197Ssam
6222105197Ssam	switch (saidx->proto)  {
6223105197Ssam	case IPPROTO_ESP:
6224105197Ssam		m = key_getcomb_esp();
6225105197Ssam		break;
6226105197Ssam	case IPPROTO_AH:
6227105197Ssam		m = key_getcomb_ah();
6228105197Ssam		break;
6229105197Ssam	case IPPROTO_IPCOMP:
6230105197Ssam		m = key_getcomb_ipcomp();
6231105197Ssam		break;
6232105197Ssam	default:
6233105197Ssam		return NULL;
6234105197Ssam	}
6235105197Ssam
6236105197Ssam	if (!m)
6237105197Ssam		return NULL;
6238111119Simp	M_PREPEND(m, l, M_DONTWAIT);
6239105197Ssam	if (!m)
6240105197Ssam		return NULL;
6241105197Ssam
6242105197Ssam	totlen = 0;
6243105197Ssam	for (n = m; n; n = n->m_next)
6244105197Ssam		totlen += n->m_len;
6245105197Ssam
6246105197Ssam	prop = mtod(m, struct sadb_prop *);
6247105197Ssam	bzero(prop, sizeof(*prop));
6248105197Ssam	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6249105197Ssam	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6250105197Ssam	prop->sadb_prop_replay = 32;	/* XXX */
6251105197Ssam
6252105197Ssam	return m;
6253105197Ssam}
6254105197Ssam
6255105197Ssam/*
6256105197Ssam * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6257105197Ssam * send
6258105197Ssam *   <base, SA, address(SD), (address(P)), x_policy,
6259105197Ssam *       (identity(SD),) (sensitivity,) proposal>
6260105197Ssam * to KMD, and expect to receive
6261105197Ssam *   <base> with SADB_ACQUIRE if error occured,
6262105197Ssam * or
6263105197Ssam *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6264105197Ssam * from KMD by PF_KEY.
6265105197Ssam *
6266105197Ssam * XXX x_policy is outside of RFC2367 (KAME extension).
6267105197Ssam * XXX sensitivity is not supported.
6268105197Ssam * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6269105197Ssam * see comment for key_getcomb_ipcomp().
6270105197Ssam *
6271105197Ssam * OUT:
6272105197Ssam *    0     : succeed
6273105197Ssam *    others: error number
6274105197Ssam */
6275105197Ssamstatic int
6276105197Ssamkey_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6277105197Ssam{
6278105197Ssam	struct mbuf *result = NULL, *m;
6279105197Ssam	struct secacq *newacq;
6280105197Ssam	u_int8_t satype;
6281105197Ssam	int error = -1;
6282105197Ssam	u_int32_t seq;
6283105197Ssam
6284120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6285105197Ssam	satype = key_proto2satype(saidx->proto);
6286120585Ssam	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6287105197Ssam
6288105197Ssam	/*
6289105197Ssam	 * We never do anything about acquirng SA.  There is anather
6290105197Ssam	 * solution that kernel blocks to send SADB_ACQUIRE message until
6291105197Ssam	 * getting something message from IKEd.  In later case, to be
6292105197Ssam	 * managed with ACQUIRING list.
6293105197Ssam	 */
6294108533Sschweikh	/* Get an entry to check whether sending message or not. */
6295105197Ssam	if ((newacq = key_getacq(saidx)) != NULL) {
6296181803Sbz		if (V_key_blockacq_count < newacq->count) {
6297105197Ssam			/* reset counter and do send message. */
6298105197Ssam			newacq->count = 0;
6299105197Ssam		} else {
6300105197Ssam			/* increment counter and do nothing. */
6301105197Ssam			newacq->count++;
6302105197Ssam			return 0;
6303105197Ssam		}
6304105197Ssam	} else {
6305105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
6306105197Ssam		if ((newacq = key_newacq(saidx)) == NULL)
6307105197Ssam			return ENOBUFS;
6308105197Ssam	}
6309105197Ssam
6310105197Ssam
6311105197Ssam	seq = newacq->seq;
6312105197Ssam	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6313105197Ssam	if (!m) {
6314105197Ssam		error = ENOBUFS;
6315105197Ssam		goto fail;
6316105197Ssam	}
6317105197Ssam	result = m;
6318105197Ssam
6319194062Svanhu	/*
6320194062Svanhu	 * No SADB_X_EXT_NAT_T_* here: we do not know
6321194062Svanhu	 * anything related to NAT-T at this time.
6322194062Svanhu	 */
6323194062Svanhu
6324105197Ssam	/* set sadb_address for saidx's. */
6325105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6326105197Ssam	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6327105197Ssam	if (!m) {
6328105197Ssam		error = ENOBUFS;
6329105197Ssam		goto fail;
6330105197Ssam	}
6331105197Ssam	m_cat(result, m);
6332105197Ssam
6333105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6334105197Ssam	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6335105197Ssam	if (!m) {
6336105197Ssam		error = ENOBUFS;
6337105197Ssam		goto fail;
6338105197Ssam	}
6339105197Ssam	m_cat(result, m);
6340105197Ssam
6341105197Ssam	/* XXX proxy address (optional) */
6342105197Ssam
6343105197Ssam	/* set sadb_x_policy */
6344105197Ssam	if (sp) {
6345105197Ssam		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6346105197Ssam		if (!m) {
6347105197Ssam			error = ENOBUFS;
6348105197Ssam			goto fail;
6349105197Ssam		}
6350105197Ssam		m_cat(result, m);
6351105197Ssam	}
6352105197Ssam
6353105197Ssam	/* XXX identity (optional) */
6354105197Ssam#if 0
6355105197Ssam	if (idexttype && fqdn) {
6356105197Ssam		/* create identity extension (FQDN) */
6357105197Ssam		struct sadb_ident *id;
6358105197Ssam		int fqdnlen;
6359105197Ssam
6360105197Ssam		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
6361105197Ssam		id = (struct sadb_ident *)p;
6362105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6363105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6364105197Ssam		id->sadb_ident_exttype = idexttype;
6365105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6366105197Ssam		bcopy(fqdn, id + 1, fqdnlen);
6367105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6368105197Ssam	}
6369105197Ssam
6370105197Ssam	if (idexttype) {
6371105197Ssam		/* create identity extension (USERFQDN) */
6372105197Ssam		struct sadb_ident *id;
6373105197Ssam		int userfqdnlen;
6374105197Ssam
6375105197Ssam		if (userfqdn) {
6376105197Ssam			/* +1 for terminating-NUL */
6377105197Ssam			userfqdnlen = strlen(userfqdn) + 1;
6378105197Ssam		} else
6379105197Ssam			userfqdnlen = 0;
6380105197Ssam		id = (struct sadb_ident *)p;
6381105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6382105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6383105197Ssam		id->sadb_ident_exttype = idexttype;
6384105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6385105197Ssam		/* XXX is it correct? */
6386105197Ssam		if (curproc && curproc->p_cred)
6387105197Ssam			id->sadb_ident_id = curproc->p_cred->p_ruid;
6388105197Ssam		if (userfqdn && userfqdnlen)
6389105197Ssam			bcopy(userfqdn, id + 1, userfqdnlen);
6390105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6391105197Ssam	}
6392105197Ssam#endif
6393105197Ssam
6394105197Ssam	/* XXX sensitivity (optional) */
6395105197Ssam
6396105197Ssam	/* create proposal/combination extension */
6397105197Ssam	m = key_getprop(saidx);
6398105197Ssam#if 0
6399105197Ssam	/*
6400105197Ssam	 * spec conformant: always attach proposal/combination extension,
6401105197Ssam	 * the problem is that we have no way to attach it for ipcomp,
6402105197Ssam	 * due to the way sadb_comb is declared in RFC2367.
6403105197Ssam	 */
6404105197Ssam	if (!m) {
6405105197Ssam		error = ENOBUFS;
6406105197Ssam		goto fail;
6407105197Ssam	}
6408105197Ssam	m_cat(result, m);
6409105197Ssam#else
6410105197Ssam	/*
6411105197Ssam	 * outside of spec; make proposal/combination extension optional.
6412105197Ssam	 */
6413105197Ssam	if (m)
6414105197Ssam		m_cat(result, m);
6415105197Ssam#endif
6416105197Ssam
6417105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
6418105197Ssam		error = EINVAL;
6419105197Ssam		goto fail;
6420105197Ssam	}
6421105197Ssam
6422105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
6423105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
6424105197Ssam		if (result == NULL) {
6425105197Ssam			error = ENOBUFS;
6426105197Ssam			goto fail;
6427105197Ssam		}
6428105197Ssam	}
6429105197Ssam
6430105197Ssam	result->m_pkthdr.len = 0;
6431105197Ssam	for (m = result; m; m = m->m_next)
6432105197Ssam		result->m_pkthdr.len += m->m_len;
6433105197Ssam
6434105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
6435105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
6436105197Ssam
6437105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6438105197Ssam
6439105197Ssam fail:
6440105197Ssam	if (result)
6441105197Ssam		m_freem(result);
6442105197Ssam	return error;
6443105197Ssam}
6444105197Ssam
6445105197Ssamstatic struct secacq *
6446105197Ssamkey_newacq(const struct secasindex *saidx)
6447105197Ssam{
6448105197Ssam	struct secacq *newacq;
6449105197Ssam
6450105197Ssam	/* get new entry */
6451119643Ssam	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6452105197Ssam	if (newacq == NULL) {
6453120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6454105197Ssam		return NULL;
6455105197Ssam	}
6456105197Ssam
6457105197Ssam	/* copy secindex */
6458105197Ssam	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6459181803Sbz	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6460105197Ssam	newacq->created = time_second;
6461105197Ssam	newacq->count = 0;
6462105197Ssam
6463119643Ssam	/* add to acqtree */
6464120585Ssam	ACQ_LOCK();
6465181803Sbz	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6466120585Ssam	ACQ_UNLOCK();
6467119643Ssam
6468105197Ssam	return newacq;
6469105197Ssam}
6470105197Ssam
6471105197Ssamstatic struct secacq *
6472105197Ssamkey_getacq(const struct secasindex *saidx)
6473105197Ssam{
6474105197Ssam	struct secacq *acq;
6475105197Ssam
6476120585Ssam	ACQ_LOCK();
6477181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
6478105197Ssam		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6479119643Ssam			break;
6480105197Ssam	}
6481120585Ssam	ACQ_UNLOCK();
6482105197Ssam
6483119643Ssam	return acq;
6484105197Ssam}
6485105197Ssam
6486105197Ssamstatic struct secacq *
6487105197Ssamkey_getacqbyseq(seq)
6488105197Ssam	u_int32_t seq;
6489105197Ssam{
6490105197Ssam	struct secacq *acq;
6491105197Ssam
6492120585Ssam	ACQ_LOCK();
6493181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
6494105197Ssam		if (acq->seq == seq)
6495119643Ssam			break;
6496105197Ssam	}
6497120585Ssam	ACQ_UNLOCK();
6498105197Ssam
6499119643Ssam	return acq;
6500105197Ssam}
6501105197Ssam
6502105197Ssamstatic struct secspacq *
6503105197Ssamkey_newspacq(spidx)
6504105197Ssam	struct secpolicyindex *spidx;
6505105197Ssam{
6506105197Ssam	struct secspacq *acq;
6507105197Ssam
6508105197Ssam	/* get new entry */
6509119643Ssam	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6510105197Ssam	if (acq == NULL) {
6511120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6512105197Ssam		return NULL;
6513105197Ssam	}
6514105197Ssam
6515105197Ssam	/* copy secindex */
6516105197Ssam	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6517105197Ssam	acq->created = time_second;
6518105197Ssam	acq->count = 0;
6519105197Ssam
6520119643Ssam	/* add to spacqtree */
6521120585Ssam	SPACQ_LOCK();
6522181803Sbz	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6523120585Ssam	SPACQ_UNLOCK();
6524119643Ssam
6525105197Ssam	return acq;
6526105197Ssam}
6527105197Ssam
6528105197Ssamstatic struct secspacq *
6529105197Ssamkey_getspacq(spidx)
6530105197Ssam	struct secpolicyindex *spidx;
6531105197Ssam{
6532105197Ssam	struct secspacq *acq;
6533105197Ssam
6534120585Ssam	SPACQ_LOCK();
6535181803Sbz	LIST_FOREACH(acq, &V_spacqtree, chain) {
6536119643Ssam		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6537119643Ssam			/* NB: return holding spacq_lock */
6538105197Ssam			return acq;
6539119643Ssam		}
6540105197Ssam	}
6541120585Ssam	SPACQ_UNLOCK();
6542105197Ssam
6543105197Ssam	return NULL;
6544105197Ssam}
6545105197Ssam
6546105197Ssam/*
6547105197Ssam * SADB_ACQUIRE processing,
6548105197Ssam * in first situation, is receiving
6549105197Ssam *   <base>
6550105197Ssam * from the ikmpd, and clear sequence of its secasvar entry.
6551105197Ssam *
6552105197Ssam * In second situation, is receiving
6553105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6554105197Ssam * from a user land process, and return
6555105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6556105197Ssam * to the socket.
6557105197Ssam *
6558105197Ssam * m will always be freed.
6559105197Ssam */
6560105197Ssamstatic int
6561105197Ssamkey_acquire2(so, m, mhp)
6562105197Ssam	struct socket *so;
6563105197Ssam	struct mbuf *m;
6564105197Ssam	const struct sadb_msghdr *mhp;
6565105197Ssam{
6566105197Ssam	const struct sadb_address *src0, *dst0;
6567105197Ssam	struct secasindex saidx;
6568105197Ssam	struct secashead *sah;
6569105197Ssam	u_int16_t proto;
6570105197Ssam	int error;
6571105197Ssam
6572120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6573120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6574120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6575120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6576105197Ssam
6577105197Ssam	/*
6578105197Ssam	 * Error message from KMd.
6579105197Ssam	 * We assume that if error was occured in IKEd, the length of PFKEY
6580105197Ssam	 * message is equal to the size of sadb_msg structure.
6581105197Ssam	 * We do not raise error even if error occured in this function.
6582105197Ssam	 */
6583105197Ssam	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6584105197Ssam		struct secacq *acq;
6585105197Ssam
6586105197Ssam		/* check sequence number */
6587105197Ssam		if (mhp->msg->sadb_msg_seq == 0) {
6588120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6589120585Ssam				"number.\n", __func__));
6590105197Ssam			m_freem(m);
6591105197Ssam			return 0;
6592105197Ssam		}
6593105197Ssam
6594105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6595105197Ssam			/*
6596105197Ssam			 * the specified larval SA is already gone, or we got
6597105197Ssam			 * a bogus sequence number.  we can silently ignore it.
6598105197Ssam			 */
6599105197Ssam			m_freem(m);
6600105197Ssam			return 0;
6601105197Ssam		}
6602105197Ssam
6603105197Ssam		/* reset acq counter in order to deletion by timehander. */
6604105197Ssam		acq->created = time_second;
6605105197Ssam		acq->count = 0;
6606105197Ssam		m_freem(m);
6607105197Ssam		return 0;
6608105197Ssam	}
6609105197Ssam
6610105197Ssam	/*
6611105197Ssam	 * This message is from user land.
6612105197Ssam	 */
6613105197Ssam
6614105197Ssam	/* map satype to proto */
6615105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6616120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6617120585Ssam			__func__));
6618105197Ssam		return key_senderror(so, m, EINVAL);
6619105197Ssam	}
6620105197Ssam
6621105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6622105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6623105197Ssam	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6624105197Ssam		/* error */
6625120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6626120585Ssam			__func__));
6627105197Ssam		return key_senderror(so, m, EINVAL);
6628105197Ssam	}
6629105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6630105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6631105197Ssam	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6632105197Ssam		/* error */
6633120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6634120585Ssam			__func__));
6635105197Ssam		return key_senderror(so, m, EINVAL);
6636105197Ssam	}
6637105197Ssam
6638105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6639105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6640105197Ssam
6641105197Ssam	/* XXX boundary check against sa_len */
6642105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6643105197Ssam
6644194062Svanhu	/*
6645194062Svanhu	 * Make sure the port numbers are zero.
6646194062Svanhu	 * In case of NAT-T we will update them later if needed.
6647194062Svanhu	 */
6648194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
6649194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
6650194062Svanhu
6651194062Svanhu#ifndef IPSEC_NAT_T
6652194062Svanhu	/*
6653194062Svanhu	 * Handle NAT-T info if present.
6654194062Svanhu	 */
6655194062Svanhu
6656194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6657194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6658194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
6659194062Svanhu
6660194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6661194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6662194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6663194062Svanhu			    __func__));
6664194062Svanhu			return key_senderror(so, m, EINVAL);
6665194062Svanhu		}
6666194062Svanhu
6667194062Svanhu		sport = (struct sadb_x_nat_t_port *)
6668194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6669194062Svanhu		dport = (struct sadb_x_nat_t_port *)
6670194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6671194062Svanhu
6672194062Svanhu		if (sport)
6673194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
6674194062Svanhu			    sport->sadb_x_nat_t_port_port);
6675194062Svanhu		if (dport)
6676194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
6677194062Svanhu			    dport->sadb_x_nat_t_port_port);
6678194062Svanhu	}
6679194062Svanhu#endif
6680194062Svanhu
6681105197Ssam	/* get a SA index */
6682120585Ssam	SAHTREE_LOCK();
6683181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
6684105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
6685105197Ssam			continue;
6686105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6687105197Ssam			break;
6688105197Ssam	}
6689120585Ssam	SAHTREE_UNLOCK();
6690105197Ssam	if (sah != NULL) {
6691120585Ssam		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6692105197Ssam		return key_senderror(so, m, EEXIST);
6693105197Ssam	}
6694105197Ssam
6695105197Ssam	error = key_acquire(&saidx, NULL);
6696105197Ssam	if (error != 0) {
6697120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6698120585Ssam			__func__, mhp->msg->sadb_msg_errno));
6699105197Ssam		return key_senderror(so, m, error);
6700105197Ssam	}
6701105197Ssam
6702105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6703105197Ssam}
6704105197Ssam
6705105197Ssam/*
6706105197Ssam * SADB_REGISTER processing.
6707105197Ssam * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6708105197Ssam * receive
6709105197Ssam *   <base>
6710105197Ssam * from the ikmpd, and register a socket to send PF_KEY messages,
6711105197Ssam * and send
6712105197Ssam *   <base, supported>
6713105197Ssam * to KMD by PF_KEY.
6714105197Ssam * If socket is detached, must free from regnode.
6715105197Ssam *
6716105197Ssam * m will always be freed.
6717105197Ssam */
6718105197Ssamstatic int
6719105197Ssamkey_register(so, m, mhp)
6720105197Ssam	struct socket *so;
6721105197Ssam	struct mbuf *m;
6722105197Ssam	const struct sadb_msghdr *mhp;
6723105197Ssam{
6724105197Ssam	struct secreg *reg, *newreg = 0;
6725105197Ssam
6726120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6727120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6728120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6729120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6730105197Ssam
6731105197Ssam	/* check for invalid register message */
6732181803Sbz	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6733105197Ssam		return key_senderror(so, m, EINVAL);
6734105197Ssam
6735105197Ssam	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6736105197Ssam	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6737105197Ssam		goto setmsg;
6738105197Ssam
6739105197Ssam	/* check whether existing or not */
6740120585Ssam	REGTREE_LOCK();
6741181803Sbz	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6742105197Ssam		if (reg->so == so) {
6743120585Ssam			REGTREE_UNLOCK();
6744120585Ssam			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6745120585Ssam				__func__));
6746105197Ssam			return key_senderror(so, m, EEXIST);
6747105197Ssam		}
6748105197Ssam	}
6749105197Ssam
6750105197Ssam	/* create regnode */
6751119643Ssam	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6752105197Ssam	if (newreg == NULL) {
6753120585Ssam		REGTREE_UNLOCK();
6754120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6755105197Ssam		return key_senderror(so, m, ENOBUFS);
6756105197Ssam	}
6757105197Ssam
6758105197Ssam	newreg->so = so;
6759105197Ssam	((struct keycb *)sotorawcb(so))->kp_registered++;
6760105197Ssam
6761105197Ssam	/* add regnode to regtree. */
6762181803Sbz	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6763120585Ssam	REGTREE_UNLOCK();
6764105197Ssam
6765105197Ssam  setmsg:
6766105197Ssam    {
6767105197Ssam	struct mbuf *n;
6768105197Ssam	struct sadb_msg *newmsg;
6769105197Ssam	struct sadb_supported *sup;
6770105197Ssam	u_int len, alen, elen;
6771105197Ssam	int off;
6772105197Ssam	int i;
6773105197Ssam	struct sadb_alg *alg;
6774105197Ssam
6775105197Ssam	/* create new sadb_msg to reply. */
6776105197Ssam	alen = 0;
6777105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6778105197Ssam		if (ah_algorithm_lookup(i))
6779105197Ssam			alen += sizeof(struct sadb_alg);
6780105197Ssam	}
6781105197Ssam	if (alen)
6782105197Ssam		alen += sizeof(struct sadb_supported);
6783105197Ssam	elen = 0;
6784105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6785105197Ssam		if (esp_algorithm_lookup(i))
6786105197Ssam			elen += sizeof(struct sadb_alg);
6787105197Ssam	}
6788105197Ssam	if (elen)
6789105197Ssam		elen += sizeof(struct sadb_supported);
6790105197Ssam
6791105197Ssam	len = sizeof(struct sadb_msg) + alen + elen;
6792105197Ssam
6793105197Ssam	if (len > MCLBYTES)
6794105197Ssam		return key_senderror(so, m, ENOBUFS);
6795105197Ssam
6796111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
6797105197Ssam	if (len > MHLEN) {
6798111119Simp		MCLGET(n, M_DONTWAIT);
6799105197Ssam		if ((n->m_flags & M_EXT) == 0) {
6800105197Ssam			m_freem(n);
6801105197Ssam			n = NULL;
6802105197Ssam		}
6803105197Ssam	}
6804105197Ssam	if (!n)
6805105197Ssam		return key_senderror(so, m, ENOBUFS);
6806105197Ssam
6807105197Ssam	n->m_pkthdr.len = n->m_len = len;
6808105197Ssam	n->m_next = NULL;
6809105197Ssam	off = 0;
6810105197Ssam
6811105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6812105197Ssam	newmsg = mtod(n, struct sadb_msg *);
6813105197Ssam	newmsg->sadb_msg_errno = 0;
6814105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6815105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6816105197Ssam
6817105197Ssam	/* for authentication algorithm */
6818105197Ssam	if (alen) {
6819105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6820105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6821105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6822105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6823105197Ssam
6824105197Ssam		for (i = 1; i <= SADB_AALG_MAX; i++) {
6825105197Ssam			struct auth_hash *aalgo;
6826105197Ssam			u_int16_t minkeysize, maxkeysize;
6827105197Ssam
6828105197Ssam			aalgo = ah_algorithm_lookup(i);
6829105197Ssam			if (!aalgo)
6830105197Ssam				continue;
6831105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6832105197Ssam			alg->sadb_alg_id = i;
6833105197Ssam			alg->sadb_alg_ivlen = 0;
6834105197Ssam			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6835105197Ssam			alg->sadb_alg_minbits = _BITS(minkeysize);
6836105197Ssam			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6837105197Ssam			off += PFKEY_ALIGN8(sizeof(*alg));
6838105197Ssam		}
6839105197Ssam	}
6840105197Ssam
6841105197Ssam	/* for encryption algorithm */
6842105197Ssam	if (elen) {
6843105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6844105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6845105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6846105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6847105197Ssam
6848105197Ssam		for (i = 1; i <= SADB_EALG_MAX; i++) {
6849105197Ssam			struct enc_xform *ealgo;
6850105197Ssam
6851105197Ssam			ealgo = esp_algorithm_lookup(i);
6852105197Ssam			if (!ealgo)
6853105197Ssam				continue;
6854105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6855105197Ssam			alg->sadb_alg_id = i;
6856105197Ssam			alg->sadb_alg_ivlen = ealgo->blocksize;
6857105197Ssam			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6858105197Ssam			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6859105197Ssam			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6860105197Ssam		}
6861105197Ssam	}
6862105197Ssam
6863120585Ssam	IPSEC_ASSERT(off == len,
6864120585Ssam		("length assumption failed (off %u len %u)", off, len));
6865105197Ssam
6866105197Ssam	m_freem(m);
6867105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6868105197Ssam    }
6869105197Ssam}
6870105197Ssam
6871105197Ssam/*
6872105197Ssam * free secreg entry registered.
6873105197Ssam * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6874105197Ssam */
6875105197Ssamvoid
6876119643Ssamkey_freereg(struct socket *so)
6877105197Ssam{
6878105197Ssam	struct secreg *reg;
6879105197Ssam	int i;
6880105197Ssam
6881120585Ssam	IPSEC_ASSERT(so != NULL, ("NULL so"));
6882105197Ssam
6883105197Ssam	/*
6884105197Ssam	 * check whether existing or not.
6885105197Ssam	 * check all type of SA, because there is a potential that
6886105197Ssam	 * one socket is registered to multiple type of SA.
6887105197Ssam	 */
6888120585Ssam	REGTREE_LOCK();
6889105197Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6890181803Sbz		LIST_FOREACH(reg, &V_regtree[i], chain) {
6891119643Ssam			if (reg->so == so && __LIST_CHAINED(reg)) {
6892105197Ssam				LIST_REMOVE(reg, chain);
6893119643Ssam				free(reg, M_IPSEC_SAR);
6894105197Ssam				break;
6895105197Ssam			}
6896105197Ssam		}
6897105197Ssam	}
6898120585Ssam	REGTREE_UNLOCK();
6899105197Ssam}
6900105197Ssam
6901105197Ssam/*
6902105197Ssam * SADB_EXPIRE processing
6903105197Ssam * send
6904105197Ssam *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6905105197Ssam * to KMD by PF_KEY.
6906105197Ssam * NOTE: We send only soft lifetime extension.
6907105197Ssam *
6908105197Ssam * OUT:	0	: succeed
6909105197Ssam *	others	: error number
6910105197Ssam */
6911105197Ssamstatic int
6912119643Ssamkey_expire(struct secasvar *sav)
6913105197Ssam{
6914105197Ssam	int s;
6915105197Ssam	int satype;
6916105197Ssam	struct mbuf *result = NULL, *m;
6917105197Ssam	int len;
6918105197Ssam	int error = -1;
6919105197Ssam	struct sadb_lifetime *lt;
6920105197Ssam
6921105197Ssam	/* XXX: Why do we lock ? */
6922105197Ssam	s = splnet();	/*called from softclock()*/
6923105197Ssam
6924120585Ssam	IPSEC_ASSERT (sav != NULL, ("null sav"));
6925120585Ssam	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6926105197Ssam
6927105197Ssam	/* set msg header */
6928120585Ssam	satype = key_proto2satype(sav->sah->saidx.proto);
6929120585Ssam	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6930105197Ssam	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6931105197Ssam	if (!m) {
6932105197Ssam		error = ENOBUFS;
6933105197Ssam		goto fail;
6934105197Ssam	}
6935105197Ssam	result = m;
6936105197Ssam
6937105197Ssam	/* create SA extension */
6938105197Ssam	m = key_setsadbsa(sav);
6939105197Ssam	if (!m) {
6940105197Ssam		error = ENOBUFS;
6941105197Ssam		goto fail;
6942105197Ssam	}
6943105197Ssam	m_cat(result, m);
6944105197Ssam
6945105197Ssam	/* create SA extension */
6946105197Ssam	m = key_setsadbxsa2(sav->sah->saidx.mode,
6947105197Ssam			sav->replay ? sav->replay->count : 0,
6948105197Ssam			sav->sah->saidx.reqid);
6949105197Ssam	if (!m) {
6950105197Ssam		error = ENOBUFS;
6951105197Ssam		goto fail;
6952105197Ssam	}
6953105197Ssam	m_cat(result, m);
6954105197Ssam
6955105197Ssam	/* create lifetime extension (current and soft) */
6956105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6957105197Ssam	m = key_alloc_mbuf(len);
6958105197Ssam	if (!m || m->m_next) {	/*XXX*/
6959105197Ssam		if (m)
6960105197Ssam			m_freem(m);
6961105197Ssam		error = ENOBUFS;
6962105197Ssam		goto fail;
6963105197Ssam	}
6964105197Ssam	bzero(mtod(m, caddr_t), len);
6965105197Ssam	lt = mtod(m, struct sadb_lifetime *);
6966105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6967105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6968157123Sgnn	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6969157123Sgnn	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6970157123Sgnn	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6971157123Sgnn	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6972105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6973176743Sbz	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6974176743Sbz	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6975176743Sbz	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6976176743Sbz	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6977176743Sbz	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6978176743Sbz	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6979105197Ssam	m_cat(result, m);
6980105197Ssam
6981105197Ssam	/* set sadb_address for source */
6982105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6983105197Ssam	    &sav->sah->saidx.src.sa,
6984105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6985105197Ssam	if (!m) {
6986105197Ssam		error = ENOBUFS;
6987105197Ssam		goto fail;
6988105197Ssam	}
6989105197Ssam	m_cat(result, m);
6990105197Ssam
6991105197Ssam	/* set sadb_address for destination */
6992105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6993105197Ssam	    &sav->sah->saidx.dst.sa,
6994105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6995105197Ssam	if (!m) {
6996105197Ssam		error = ENOBUFS;
6997105197Ssam		goto fail;
6998105197Ssam	}
6999105197Ssam	m_cat(result, m);
7000105197Ssam
7001194062Svanhu	/*
7002194062Svanhu	 * XXX-BZ Handle NAT-T extensions here.
7003194062Svanhu	 */
7004194062Svanhu
7005105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
7006105197Ssam		error = EINVAL;
7007105197Ssam		goto fail;
7008105197Ssam	}
7009105197Ssam
7010105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
7011105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
7012105197Ssam		if (result == NULL) {
7013105197Ssam			error = ENOBUFS;
7014105197Ssam			goto fail;
7015105197Ssam		}
7016105197Ssam	}
7017105197Ssam
7018105197Ssam	result->m_pkthdr.len = 0;
7019105197Ssam	for (m = result; m; m = m->m_next)
7020105197Ssam		result->m_pkthdr.len += m->m_len;
7021105197Ssam
7022105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
7023105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
7024105197Ssam
7025105197Ssam	splx(s);
7026105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7027105197Ssam
7028105197Ssam fail:
7029105197Ssam	if (result)
7030105197Ssam		m_freem(result);
7031105197Ssam	splx(s);
7032105197Ssam	return error;
7033105197Ssam}
7034105197Ssam
7035105197Ssam/*
7036105197Ssam * SADB_FLUSH processing
7037105197Ssam * receive
7038105197Ssam *   <base>
7039105197Ssam * from the ikmpd, and free all entries in secastree.
7040105197Ssam * and send,
7041105197Ssam *   <base>
7042105197Ssam * to the ikmpd.
7043105197Ssam * NOTE: to do is only marking SADB_SASTATE_DEAD.
7044105197Ssam *
7045105197Ssam * m will always be freed.
7046105197Ssam */
7047105197Ssamstatic int
7048105197Ssamkey_flush(so, m, mhp)
7049105197Ssam	struct socket *so;
7050105197Ssam	struct mbuf *m;
7051105197Ssam	const struct sadb_msghdr *mhp;
7052105197Ssam{
7053105197Ssam	struct sadb_msg *newmsg;
7054105197Ssam	struct secashead *sah, *nextsah;
7055105197Ssam	struct secasvar *sav, *nextsav;
7056105197Ssam	u_int16_t proto;
7057105197Ssam	u_int8_t state;
7058105197Ssam	u_int stateidx;
7059105197Ssam
7060120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7061120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7062120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7063105197Ssam
7064105197Ssam	/* map satype to proto */
7065105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7066120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7067120585Ssam			__func__));
7068105197Ssam		return key_senderror(so, m, EINVAL);
7069105197Ssam	}
7070105197Ssam
7071105197Ssam	/* no SATYPE specified, i.e. flushing all SA. */
7072120585Ssam	SAHTREE_LOCK();
7073181803Sbz	for (sah = LIST_FIRST(&V_sahtree);
7074105197Ssam	     sah != NULL;
7075105197Ssam	     sah = nextsah) {
7076105197Ssam		nextsah = LIST_NEXT(sah, chain);
7077105197Ssam
7078105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7079105197Ssam		 && proto != sah->saidx.proto)
7080105197Ssam			continue;
7081105197Ssam
7082105197Ssam		for (stateidx = 0;
7083185348Szec		     stateidx < _ARRAYLEN(saorder_state_alive);
7084105197Ssam		     stateidx++) {
7085185348Szec			state = saorder_state_any[stateidx];
7086105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
7087105197Ssam			     sav != NULL;
7088105197Ssam			     sav = nextsav) {
7089105197Ssam
7090105197Ssam				nextsav = LIST_NEXT(sav, chain);
7091105197Ssam
7092105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7093105197Ssam				KEY_FREESAV(&sav);
7094105197Ssam			}
7095105197Ssam		}
7096105197Ssam
7097105197Ssam		sah->state = SADB_SASTATE_DEAD;
7098105197Ssam	}
7099120585Ssam	SAHTREE_UNLOCK();
7100105197Ssam
7101105197Ssam	if (m->m_len < sizeof(struct sadb_msg) ||
7102105197Ssam	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7103120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7104105197Ssam		return key_senderror(so, m, ENOBUFS);
7105105197Ssam	}
7106105197Ssam
7107105197Ssam	if (m->m_next)
7108105197Ssam		m_freem(m->m_next);
7109105197Ssam	m->m_next = NULL;
7110105197Ssam	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7111105197Ssam	newmsg = mtod(m, struct sadb_msg *);
7112105197Ssam	newmsg->sadb_msg_errno = 0;
7113105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7114105197Ssam
7115105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7116105197Ssam}
7117105197Ssam
7118105197Ssam/*
7119105197Ssam * SADB_DUMP processing
7120105197Ssam * dump all entries including status of DEAD in SAD.
7121105197Ssam * receive
7122105197Ssam *   <base>
7123105197Ssam * from the ikmpd, and dump all secasvar leaves
7124105197Ssam * and send,
7125105197Ssam *   <base> .....
7126105197Ssam * to the ikmpd.
7127105197Ssam *
7128105197Ssam * m will always be freed.
7129105197Ssam */
7130105197Ssamstatic int
7131105197Ssamkey_dump(so, m, mhp)
7132105197Ssam	struct socket *so;
7133105197Ssam	struct mbuf *m;
7134105197Ssam	const struct sadb_msghdr *mhp;
7135105197Ssam{
7136105197Ssam	struct secashead *sah;
7137105197Ssam	struct secasvar *sav;
7138105197Ssam	u_int16_t proto;
7139105197Ssam	u_int stateidx;
7140105197Ssam	u_int8_t satype;
7141105197Ssam	u_int8_t state;
7142105197Ssam	int cnt;
7143105197Ssam	struct sadb_msg *newmsg;
7144105197Ssam	struct mbuf *n;
7145105197Ssam
7146120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7147120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7148120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7149120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7150105197Ssam
7151105197Ssam	/* map satype to proto */
7152105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7153120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7154120585Ssam			__func__));
7155105197Ssam		return key_senderror(so, m, EINVAL);
7156105197Ssam	}
7157105197Ssam
7158105197Ssam	/* count sav entries to be sent to the userland. */
7159105197Ssam	cnt = 0;
7160120585Ssam	SAHTREE_LOCK();
7161181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7162105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7163105197Ssam		 && proto != sah->saidx.proto)
7164105197Ssam			continue;
7165105197Ssam
7166105197Ssam		for (stateidx = 0;
7167185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
7168105197Ssam		     stateidx++) {
7169185348Szec			state = saorder_state_any[stateidx];
7170105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7171105197Ssam				cnt++;
7172105197Ssam			}
7173105197Ssam		}
7174105197Ssam	}
7175105197Ssam
7176119643Ssam	if (cnt == 0) {
7177120585Ssam		SAHTREE_UNLOCK();
7178105197Ssam		return key_senderror(so, m, ENOENT);
7179119643Ssam	}
7180105197Ssam
7181105197Ssam	/* send this to the userland, one at a time. */
7182105197Ssam	newmsg = NULL;
7183181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7184105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7185105197Ssam		 && proto != sah->saidx.proto)
7186105197Ssam			continue;
7187105197Ssam
7188105197Ssam		/* map proto to satype */
7189105197Ssam		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7190120585Ssam			SAHTREE_UNLOCK();
7191120585Ssam			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7192120585Ssam				"SAD.\n", __func__));
7193105197Ssam			return key_senderror(so, m, EINVAL);
7194105197Ssam		}
7195105197Ssam
7196105197Ssam		for (stateidx = 0;
7197185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
7198105197Ssam		     stateidx++) {
7199185348Szec			state = saorder_state_any[stateidx];
7200105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7201105197Ssam				n = key_setdumpsa(sav, SADB_DUMP, satype,
7202105197Ssam				    --cnt, mhp->msg->sadb_msg_pid);
7203119643Ssam				if (!n) {
7204120585Ssam					SAHTREE_UNLOCK();
7205105197Ssam					return key_senderror(so, m, ENOBUFS);
7206119643Ssam				}
7207105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7208105197Ssam			}
7209105197Ssam		}
7210105197Ssam	}
7211120585Ssam	SAHTREE_UNLOCK();
7212105197Ssam
7213105197Ssam	m_freem(m);
7214105197Ssam	return 0;
7215105197Ssam}
7216105197Ssam
7217105197Ssam/*
7218105197Ssam * SADB_X_PROMISC processing
7219105197Ssam *
7220105197Ssam * m will always be freed.
7221105197Ssam */
7222105197Ssamstatic int
7223105197Ssamkey_promisc(so, m, mhp)
7224105197Ssam	struct socket *so;
7225105197Ssam	struct mbuf *m;
7226105197Ssam	const struct sadb_msghdr *mhp;
7227105197Ssam{
7228105197Ssam	int olen;
7229105197Ssam
7230120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7231120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7232120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7233120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7234105197Ssam
7235105197Ssam	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7236105197Ssam
7237105197Ssam	if (olen < sizeof(struct sadb_msg)) {
7238105197Ssam#if 1
7239105197Ssam		return key_senderror(so, m, EINVAL);
7240105197Ssam#else
7241105197Ssam		m_freem(m);
7242105197Ssam		return 0;
7243105197Ssam#endif
7244105197Ssam	} else if (olen == sizeof(struct sadb_msg)) {
7245105197Ssam		/* enable/disable promisc mode */
7246105197Ssam		struct keycb *kp;
7247105197Ssam
7248105197Ssam		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7249105197Ssam			return key_senderror(so, m, EINVAL);
7250105197Ssam		mhp->msg->sadb_msg_errno = 0;
7251105197Ssam		switch (mhp->msg->sadb_msg_satype) {
7252105197Ssam		case 0:
7253105197Ssam		case 1:
7254105197Ssam			kp->kp_promisc = mhp->msg->sadb_msg_satype;
7255105197Ssam			break;
7256105197Ssam		default:
7257105197Ssam			return key_senderror(so, m, EINVAL);
7258105197Ssam		}
7259105197Ssam
7260105197Ssam		/* send the original message back to everyone */
7261105197Ssam		mhp->msg->sadb_msg_errno = 0;
7262105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7263105197Ssam	} else {
7264105197Ssam		/* send packet as is */
7265105197Ssam
7266105197Ssam		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7267105197Ssam
7268105197Ssam		/* TODO: if sadb_msg_seq is specified, send to specific pid */
7269105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7270105197Ssam	}
7271105197Ssam}
7272105197Ssam
7273105197Ssamstatic int (*key_typesw[]) __P((struct socket *, struct mbuf *,
7274105197Ssam		const struct sadb_msghdr *)) = {
7275105197Ssam	NULL,		/* SADB_RESERVED */
7276105197Ssam	key_getspi,	/* SADB_GETSPI */
7277105197Ssam	key_update,	/* SADB_UPDATE */
7278105197Ssam	key_add,	/* SADB_ADD */
7279105197Ssam	key_delete,	/* SADB_DELETE */
7280105197Ssam	key_get,	/* SADB_GET */
7281105197Ssam	key_acquire2,	/* SADB_ACQUIRE */
7282105197Ssam	key_register,	/* SADB_REGISTER */
7283105197Ssam	NULL,		/* SADB_EXPIRE */
7284105197Ssam	key_flush,	/* SADB_FLUSH */
7285105197Ssam	key_dump,	/* SADB_DUMP */
7286105197Ssam	key_promisc,	/* SADB_X_PROMISC */
7287105197Ssam	NULL,		/* SADB_X_PCHANGE */
7288105197Ssam	key_spdadd,	/* SADB_X_SPDUPDATE */
7289105197Ssam	key_spdadd,	/* SADB_X_SPDADD */
7290105197Ssam	key_spddelete,	/* SADB_X_SPDDELETE */
7291105197Ssam	key_spdget,	/* SADB_X_SPDGET */
7292105197Ssam	NULL,		/* SADB_X_SPDACQUIRE */
7293105197Ssam	key_spddump,	/* SADB_X_SPDDUMP */
7294105197Ssam	key_spdflush,	/* SADB_X_SPDFLUSH */
7295105197Ssam	key_spdadd,	/* SADB_X_SPDSETIDX */
7296105197Ssam	NULL,		/* SADB_X_SPDEXPIRE */
7297105197Ssam	key_spddelete2,	/* SADB_X_SPDDELETE2 */
7298105197Ssam};
7299105197Ssam
7300105197Ssam/*
7301105197Ssam * parse sadb_msg buffer to process PFKEYv2,
7302105197Ssam * and create a data to response if needed.
7303105197Ssam * I think to be dealed with mbuf directly.
7304105197Ssam * IN:
7305105197Ssam *     msgp  : pointer to pointer to a received buffer pulluped.
7306105197Ssam *             This is rewrited to response.
7307105197Ssam *     so    : pointer to socket.
7308105197Ssam * OUT:
7309105197Ssam *    length for buffer to send to user process.
7310105197Ssam */
7311105197Ssamint
7312105197Ssamkey_parse(m, so)
7313105197Ssam	struct mbuf *m;
7314105197Ssam	struct socket *so;
7315105197Ssam{
7316105197Ssam	struct sadb_msg *msg;
7317105197Ssam	struct sadb_msghdr mh;
7318105197Ssam	u_int orglen;
7319105197Ssam	int error;
7320105197Ssam	int target;
7321105197Ssam
7322120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7323120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7324105197Ssam
7325105197Ssam#if 0	/*kdebug_sadb assumes msg in linear buffer*/
7326105197Ssam	KEYDEBUG(KEYDEBUG_KEY_DUMP,
7327120585Ssam		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7328105197Ssam		kdebug_sadb(msg));
7329105197Ssam#endif
7330105197Ssam
7331105197Ssam	if (m->m_len < sizeof(struct sadb_msg)) {
7332105197Ssam		m = m_pullup(m, sizeof(struct sadb_msg));
7333105197Ssam		if (!m)
7334105197Ssam			return ENOBUFS;
7335105197Ssam	}
7336105197Ssam	msg = mtod(m, struct sadb_msg *);
7337105197Ssam	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7338105197Ssam	target = KEY_SENDUP_ONE;
7339105197Ssam
7340105197Ssam	if ((m->m_flags & M_PKTHDR) == 0 ||
7341105197Ssam	    m->m_pkthdr.len != m->m_pkthdr.len) {
7342120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7343252693Sae		PFKEYSTAT_INC(out_invlen);
7344105197Ssam		error = EINVAL;
7345105197Ssam		goto senderror;
7346105197Ssam	}
7347105197Ssam
7348105197Ssam	if (msg->sadb_msg_version != PF_KEY_V2) {
7349120585Ssam		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7350120585Ssam		    __func__, msg->sadb_msg_version));
7351252693Sae		PFKEYSTAT_INC(out_invver);
7352105197Ssam		error = EINVAL;
7353105197Ssam		goto senderror;
7354105197Ssam	}
7355105197Ssam
7356105197Ssam	if (msg->sadb_msg_type > SADB_MAX) {
7357120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7358120585Ssam		    __func__, msg->sadb_msg_type));
7359252693Sae		PFKEYSTAT_INC(out_invmsgtype);
7360105197Ssam		error = EINVAL;
7361105197Ssam		goto senderror;
7362105197Ssam	}
7363105197Ssam
7364105197Ssam	/* for old-fashioned code - should be nuked */
7365105197Ssam	if (m->m_pkthdr.len > MCLBYTES) {
7366105197Ssam		m_freem(m);
7367105197Ssam		return ENOBUFS;
7368105197Ssam	}
7369105197Ssam	if (m->m_next) {
7370105197Ssam		struct mbuf *n;
7371105197Ssam
7372111119Simp		MGETHDR(n, M_DONTWAIT, MT_DATA);
7373105197Ssam		if (n && m->m_pkthdr.len > MHLEN) {
7374111119Simp			MCLGET(n, M_DONTWAIT);
7375105197Ssam			if ((n->m_flags & M_EXT) == 0) {
7376105197Ssam				m_free(n);
7377105197Ssam				n = NULL;
7378105197Ssam			}
7379105197Ssam		}
7380105197Ssam		if (!n) {
7381105197Ssam			m_freem(m);
7382105197Ssam			return ENOBUFS;
7383105197Ssam		}
7384105197Ssam		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7385105197Ssam		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7386105197Ssam		n->m_next = NULL;
7387105197Ssam		m_freem(m);
7388105197Ssam		m = n;
7389105197Ssam	}
7390105197Ssam
7391105197Ssam	/* align the mbuf chain so that extensions are in contiguous region. */
7392105197Ssam	error = key_align(m, &mh);
7393105197Ssam	if (error)
7394105197Ssam		return error;
7395105197Ssam
7396105197Ssam	msg = mh.msg;
7397105197Ssam
7398105197Ssam	/* check SA type */
7399105197Ssam	switch (msg->sadb_msg_satype) {
7400105197Ssam	case SADB_SATYPE_UNSPEC:
7401105197Ssam		switch (msg->sadb_msg_type) {
7402105197Ssam		case SADB_GETSPI:
7403105197Ssam		case SADB_UPDATE:
7404105197Ssam		case SADB_ADD:
7405105197Ssam		case SADB_DELETE:
7406105197Ssam		case SADB_GET:
7407105197Ssam		case SADB_ACQUIRE:
7408105197Ssam		case SADB_EXPIRE:
7409120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify satype "
7410120585Ssam			    "when msg type=%u.\n", __func__,
7411120585Ssam			    msg->sadb_msg_type));
7412252693Sae			PFKEYSTAT_INC(out_invsatype);
7413105197Ssam			error = EINVAL;
7414105197Ssam			goto senderror;
7415105197Ssam		}
7416105197Ssam		break;
7417105197Ssam	case SADB_SATYPE_AH:
7418105197Ssam	case SADB_SATYPE_ESP:
7419105197Ssam	case SADB_X_SATYPE_IPCOMP:
7420125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
7421105197Ssam		switch (msg->sadb_msg_type) {
7422105197Ssam		case SADB_X_SPDADD:
7423105197Ssam		case SADB_X_SPDDELETE:
7424105197Ssam		case SADB_X_SPDGET:
7425105197Ssam		case SADB_X_SPDDUMP:
7426105197Ssam		case SADB_X_SPDFLUSH:
7427105197Ssam		case SADB_X_SPDSETIDX:
7428105197Ssam		case SADB_X_SPDUPDATE:
7429105197Ssam		case SADB_X_SPDDELETE2:
7430120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7431120585Ssam				__func__, msg->sadb_msg_type));
7432252693Sae			PFKEYSTAT_INC(out_invsatype);
7433105197Ssam			error = EINVAL;
7434105197Ssam			goto senderror;
7435105197Ssam		}
7436105197Ssam		break;
7437105197Ssam	case SADB_SATYPE_RSVP:
7438105197Ssam	case SADB_SATYPE_OSPFV2:
7439105197Ssam	case SADB_SATYPE_RIPV2:
7440105197Ssam	case SADB_SATYPE_MIP:
7441120585Ssam		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7442120585Ssam			__func__, msg->sadb_msg_satype));
7443252693Sae		PFKEYSTAT_INC(out_invsatype);
7444105197Ssam		error = EOPNOTSUPP;
7445105197Ssam		goto senderror;
7446105197Ssam	case 1:	/* XXX: What does it do? */
7447105197Ssam		if (msg->sadb_msg_type == SADB_X_PROMISC)
7448105197Ssam			break;
7449105197Ssam		/*FALLTHROUGH*/
7450105197Ssam	default:
7451120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7452120585Ssam			__func__, msg->sadb_msg_satype));
7453252693Sae		PFKEYSTAT_INC(out_invsatype);
7454105197Ssam		error = EINVAL;
7455105197Ssam		goto senderror;
7456105197Ssam	}
7457105197Ssam
7458105197Ssam	/* check field of upper layer protocol and address family */
7459105197Ssam	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7460105197Ssam	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7461105197Ssam		struct sadb_address *src0, *dst0;
7462105197Ssam		u_int plen;
7463105197Ssam
7464105197Ssam		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7465105197Ssam		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7466105197Ssam
7467105197Ssam		/* check upper layer protocol */
7468105197Ssam		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7469120585Ssam			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7470120585Ssam				"mismatched.\n", __func__));
7471252693Sae			PFKEYSTAT_INC(out_invaddr);
7472105197Ssam			error = EINVAL;
7473105197Ssam			goto senderror;
7474105197Ssam		}
7475105197Ssam
7476105197Ssam		/* check family */
7477105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7478105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
7479120585Ssam			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7480120585Ssam				__func__));
7481252693Sae			PFKEYSTAT_INC(out_invaddr);
7482105197Ssam			error = EINVAL;
7483105197Ssam			goto senderror;
7484105197Ssam		}
7485105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7486105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
7487120585Ssam			ipseclog((LOG_DEBUG, "%s: address struct size "
7488120585Ssam				"mismatched.\n", __func__));
7489252693Sae			PFKEYSTAT_INC(out_invaddr);
7490105197Ssam			error = EINVAL;
7491105197Ssam			goto senderror;
7492105197Ssam		}
7493105197Ssam
7494105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7495105197Ssam		case AF_INET:
7496105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7497105197Ssam			    sizeof(struct sockaddr_in)) {
7498252693Sae				PFKEYSTAT_INC(out_invaddr);
7499105197Ssam				error = EINVAL;
7500105197Ssam				goto senderror;
7501105197Ssam			}
7502105197Ssam			break;
7503105197Ssam		case AF_INET6:
7504105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7505105197Ssam			    sizeof(struct sockaddr_in6)) {
7506252693Sae				PFKEYSTAT_INC(out_invaddr);
7507105197Ssam				error = EINVAL;
7508105197Ssam				goto senderror;
7509105197Ssam			}
7510105197Ssam			break;
7511105197Ssam		default:
7512120585Ssam			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7513120585Ssam				__func__));
7514252693Sae			PFKEYSTAT_INC(out_invaddr);
7515105197Ssam			error = EAFNOSUPPORT;
7516105197Ssam			goto senderror;
7517105197Ssam		}
7518105197Ssam
7519105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7520105197Ssam		case AF_INET:
7521105197Ssam			plen = sizeof(struct in_addr) << 3;
7522105197Ssam			break;
7523105197Ssam		case AF_INET6:
7524105197Ssam			plen = sizeof(struct in6_addr) << 3;
7525105197Ssam			break;
7526105197Ssam		default:
7527105197Ssam			plen = 0;	/*fool gcc*/
7528105197Ssam			break;
7529105197Ssam		}
7530105197Ssam
7531105197Ssam		/* check max prefix length */
7532105197Ssam		if (src0->sadb_address_prefixlen > plen ||
7533105197Ssam		    dst0->sadb_address_prefixlen > plen) {
7534120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7535120585Ssam				__func__));
7536252693Sae			PFKEYSTAT_INC(out_invaddr);
7537105197Ssam			error = EINVAL;
7538105197Ssam			goto senderror;
7539105197Ssam		}
7540105197Ssam
7541105197Ssam		/*
7542105197Ssam		 * prefixlen == 0 is valid because there can be a case when
7543105197Ssam		 * all addresses are matched.
7544105197Ssam		 */
7545105197Ssam	}
7546105197Ssam
7547105197Ssam	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7548105197Ssam	    key_typesw[msg->sadb_msg_type] == NULL) {
7549252693Sae		PFKEYSTAT_INC(out_invmsgtype);
7550105197Ssam		error = EINVAL;
7551105197Ssam		goto senderror;
7552105197Ssam	}
7553105197Ssam
7554105197Ssam	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7555105197Ssam
7556105197Ssamsenderror:
7557105197Ssam	msg->sadb_msg_errno = error;
7558105197Ssam	return key_sendup_mbuf(so, m, target);
7559105197Ssam}
7560105197Ssam
7561105197Ssamstatic int
7562105197Ssamkey_senderror(so, m, code)
7563105197Ssam	struct socket *so;
7564105197Ssam	struct mbuf *m;
7565105197Ssam	int code;
7566105197Ssam{
7567105197Ssam	struct sadb_msg *msg;
7568105197Ssam
7569120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7570120585Ssam		("mbuf too small, len %u", m->m_len));
7571105197Ssam
7572105197Ssam	msg = mtod(m, struct sadb_msg *);
7573105197Ssam	msg->sadb_msg_errno = code;
7574105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7575105197Ssam}
7576105197Ssam
7577105197Ssam/*
7578105197Ssam * set the pointer to each header into message buffer.
7579105197Ssam * m will be freed on error.
7580105197Ssam * XXX larger-than-MCLBYTES extension?
7581105197Ssam */
7582105197Ssamstatic int
7583105197Ssamkey_align(m, mhp)
7584105197Ssam	struct mbuf *m;
7585105197Ssam	struct sadb_msghdr *mhp;
7586105197Ssam{
7587105197Ssam	struct mbuf *n;
7588105197Ssam	struct sadb_ext *ext;
7589105197Ssam	size_t off, end;
7590105197Ssam	int extlen;
7591105197Ssam	int toff;
7592105197Ssam
7593120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7594120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7595120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7596120585Ssam		("mbuf too small, len %u", m->m_len));
7597105197Ssam
7598105197Ssam	/* initialize */
7599105197Ssam	bzero(mhp, sizeof(*mhp));
7600105197Ssam
7601105197Ssam	mhp->msg = mtod(m, struct sadb_msg *);
7602105197Ssam	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7603105197Ssam
7604105197Ssam	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7605105197Ssam	extlen = end;	/*just in case extlen is not updated*/
7606105197Ssam	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7607105197Ssam		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7608105197Ssam		if (!n) {
7609105197Ssam			/* m is already freed */
7610105197Ssam			return ENOBUFS;
7611105197Ssam		}
7612105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7613105197Ssam
7614105197Ssam		/* set pointer */
7615105197Ssam		switch (ext->sadb_ext_type) {
7616105197Ssam		case SADB_EXT_SA:
7617105197Ssam		case SADB_EXT_ADDRESS_SRC:
7618105197Ssam		case SADB_EXT_ADDRESS_DST:
7619105197Ssam		case SADB_EXT_ADDRESS_PROXY:
7620105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
7621105197Ssam		case SADB_EXT_LIFETIME_HARD:
7622105197Ssam		case SADB_EXT_LIFETIME_SOFT:
7623105197Ssam		case SADB_EXT_KEY_AUTH:
7624105197Ssam		case SADB_EXT_KEY_ENCRYPT:
7625105197Ssam		case SADB_EXT_IDENTITY_SRC:
7626105197Ssam		case SADB_EXT_IDENTITY_DST:
7627105197Ssam		case SADB_EXT_SENSITIVITY:
7628105197Ssam		case SADB_EXT_PROPOSAL:
7629105197Ssam		case SADB_EXT_SUPPORTED_AUTH:
7630105197Ssam		case SADB_EXT_SUPPORTED_ENCRYPT:
7631105197Ssam		case SADB_EXT_SPIRANGE:
7632105197Ssam		case SADB_X_EXT_POLICY:
7633105197Ssam		case SADB_X_EXT_SA2:
7634194062Svanhu#ifdef IPSEC_NAT_T
7635194062Svanhu		case SADB_X_EXT_NAT_T_TYPE:
7636194062Svanhu		case SADB_X_EXT_NAT_T_SPORT:
7637194062Svanhu		case SADB_X_EXT_NAT_T_DPORT:
7638194062Svanhu		case SADB_X_EXT_NAT_T_OAI:
7639194062Svanhu		case SADB_X_EXT_NAT_T_OAR:
7640194062Svanhu		case SADB_X_EXT_NAT_T_FRAG:
7641194062Svanhu#endif
7642105197Ssam			/* duplicate check */
7643105197Ssam			/*
7644105197Ssam			 * XXX Are there duplication payloads of either
7645105197Ssam			 * KEY_AUTH or KEY_ENCRYPT ?
7646105197Ssam			 */
7647105197Ssam			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7648120585Ssam				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7649120585Ssam					"%u\n", __func__, ext->sadb_ext_type));
7650105197Ssam				m_freem(m);
7651252693Sae				PFKEYSTAT_INC(out_dupext);
7652105197Ssam				return EINVAL;
7653105197Ssam			}
7654105197Ssam			break;
7655105197Ssam		default:
7656120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7657120585Ssam				__func__, ext->sadb_ext_type));
7658105197Ssam			m_freem(m);
7659252693Sae			PFKEYSTAT_INC(out_invexttype);
7660105197Ssam			return EINVAL;
7661105197Ssam		}
7662105197Ssam
7663105197Ssam		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7664105197Ssam
7665105197Ssam		if (key_validate_ext(ext, extlen)) {
7666105197Ssam			m_freem(m);
7667252693Sae			PFKEYSTAT_INC(out_invlen);
7668105197Ssam			return EINVAL;
7669105197Ssam		}
7670105197Ssam
7671105197Ssam		n = m_pulldown(m, off, extlen, &toff);
7672105197Ssam		if (!n) {
7673105197Ssam			/* m is already freed */
7674105197Ssam			return ENOBUFS;
7675105197Ssam		}
7676105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7677105197Ssam
7678105197Ssam		mhp->ext[ext->sadb_ext_type] = ext;
7679105197Ssam		mhp->extoff[ext->sadb_ext_type] = off;
7680105197Ssam		mhp->extlen[ext->sadb_ext_type] = extlen;
7681105197Ssam	}
7682105197Ssam
7683105197Ssam	if (off != end) {
7684105197Ssam		m_freem(m);
7685252693Sae		PFKEYSTAT_INC(out_invlen);
7686105197Ssam		return EINVAL;
7687105197Ssam	}
7688105197Ssam
7689105197Ssam	return 0;
7690105197Ssam}
7691105197Ssam
7692105197Ssamstatic int
7693105197Ssamkey_validate_ext(ext, len)
7694105197Ssam	const struct sadb_ext *ext;
7695105197Ssam	int len;
7696105197Ssam{
7697105197Ssam	const struct sockaddr *sa;
7698105197Ssam	enum { NONE, ADDR } checktype = NONE;
7699105197Ssam	int baselen = 0;
7700105197Ssam	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7701105197Ssam
7702105197Ssam	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7703105197Ssam		return EINVAL;
7704105197Ssam
7705105197Ssam	/* if it does not match minimum/maximum length, bail */
7706105197Ssam	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7707105197Ssam	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7708105197Ssam		return EINVAL;
7709105197Ssam	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7710105197Ssam		return EINVAL;
7711105197Ssam	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7712105197Ssam		return EINVAL;
7713105197Ssam
7714105197Ssam	/* more checks based on sadb_ext_type XXX need more */
7715105197Ssam	switch (ext->sadb_ext_type) {
7716105197Ssam	case SADB_EXT_ADDRESS_SRC:
7717105197Ssam	case SADB_EXT_ADDRESS_DST:
7718105197Ssam	case SADB_EXT_ADDRESS_PROXY:
7719105197Ssam		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7720105197Ssam		checktype = ADDR;
7721105197Ssam		break;
7722105197Ssam	case SADB_EXT_IDENTITY_SRC:
7723105197Ssam	case SADB_EXT_IDENTITY_DST:
7724105197Ssam		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7725105197Ssam		    SADB_X_IDENTTYPE_ADDR) {
7726105197Ssam			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7727105197Ssam			checktype = ADDR;
7728105197Ssam		} else
7729105197Ssam			checktype = NONE;
7730105197Ssam		break;
7731105197Ssam	default:
7732105197Ssam		checktype = NONE;
7733105197Ssam		break;
7734105197Ssam	}
7735105197Ssam
7736105197Ssam	switch (checktype) {
7737105197Ssam	case NONE:
7738105197Ssam		break;
7739105197Ssam	case ADDR:
7740105197Ssam		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7741105197Ssam		if (len < baselen + sal)
7742105197Ssam			return EINVAL;
7743105197Ssam		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7744105197Ssam			return EINVAL;
7745105197Ssam		break;
7746105197Ssam	}
7747105197Ssam
7748105197Ssam	return 0;
7749105197Ssam}
7750105197Ssam
7751105197Ssamvoid
7752180086Sjuliankey_init(void)
7753105197Ssam{
7754105197Ssam	int i;
7755105197Ssam
7756119643Ssam	for (i = 0; i < IPSEC_DIR_MAX; i++)
7757181803Sbz		LIST_INIT(&V_sptree[i]);
7758105197Ssam
7759181803Sbz	LIST_INIT(&V_sahtree);
7760105197Ssam
7761119643Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7762181803Sbz		LIST_INIT(&V_regtree[i]);
7763105197Ssam
7764181803Sbz	LIST_INIT(&V_acqtree);
7765181803Sbz	LIST_INIT(&V_spacqtree);
7766105197Ssam
7767105197Ssam	/* system default */
7768181803Sbz	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7769181803Sbz	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7770105197Ssam
7771190787Szec	if (!IS_DEFAULT_VNET(curvnet))
7772190787Szec		return;
7773190787Szec
7774190787Szec	SPTREE_LOCK_INIT();
7775190787Szec	REGTREE_LOCK_INIT();
7776190787Szec	SAHTREE_LOCK_INIT();
7777190787Szec	ACQ_LOCK_INIT();
7778190787Szec	SPACQ_LOCK_INIT();
7779190787Szec
7780105197Ssam#ifndef IPSEC_DEBUG2
7781105197Ssam	timeout((void *)key_timehandler, (void *)0, hz);
7782105197Ssam#endif /*IPSEC_DEBUG2*/
7783105197Ssam
7784105197Ssam	/* initialize key statistics */
7785105197Ssam	keystat.getspi_count = 1;
7786105197Ssam
7787177173Sbz	printf("IPsec: Initialized Security Association Processing.\n");
7788193731Szec}
7789105197Ssam
7790193731Szec#ifdef VIMAGE
7791193731Szecvoid
7792193731Szeckey_destroy(void)
7793193731Szec{
7794193731Szec	struct secpolicy *sp, *nextsp;
7795205789Sbz	struct secacq *acq, *nextacq;
7796205789Sbz	struct secspacq *spacq, *nextspacq;
7797193731Szec	struct secashead *sah, *nextsah;
7798193731Szec	struct secreg *reg;
7799193731Szec	int i;
7800193731Szec
7801193731Szec	SPTREE_LOCK();
7802193731Szec	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7803193731Szec		for (sp = LIST_FIRST(&V_sptree[i]);
7804193731Szec		    sp != NULL; sp = nextsp) {
7805193731Szec			nextsp = LIST_NEXT(sp, chain);
7806193731Szec			if (__LIST_CHAINED(sp)) {
7807193731Szec				LIST_REMOVE(sp, chain);
7808193731Szec				free(sp, M_IPSEC_SP);
7809193731Szec			}
7810193731Szec		}
7811193731Szec	}
7812193731Szec	SPTREE_UNLOCK();
7813193731Szec
7814193731Szec	SAHTREE_LOCK();
7815193731Szec	for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7816193731Szec		nextsah = LIST_NEXT(sah, chain);
7817193731Szec		if (__LIST_CHAINED(sah)) {
7818193731Szec			LIST_REMOVE(sah, chain);
7819193731Szec			free(sah, M_IPSEC_SAH);
7820193731Szec		}
7821193731Szec	}
7822193731Szec	SAHTREE_UNLOCK();
7823193731Szec
7824193731Szec	REGTREE_LOCK();
7825193731Szec	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7826193731Szec		LIST_FOREACH(reg, &V_regtree[i], chain) {
7827193731Szec			if (__LIST_CHAINED(reg)) {
7828193731Szec				LIST_REMOVE(reg, chain);
7829193731Szec				free(reg, M_IPSEC_SAR);
7830193731Szec				break;
7831193731Szec			}
7832193731Szec		}
7833193731Szec	}
7834193731Szec	REGTREE_UNLOCK();
7835193731Szec
7836193731Szec	ACQ_LOCK();
7837205789Sbz	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
7838193731Szec		nextacq = LIST_NEXT(acq, chain);
7839193731Szec		if (__LIST_CHAINED(acq)) {
7840193731Szec			LIST_REMOVE(acq, chain);
7841193731Szec			free(acq, M_IPSEC_SAQ);
7842193731Szec		}
7843193731Szec	}
7844193731Szec	ACQ_UNLOCK();
7845193731Szec
7846193731Szec	SPACQ_LOCK();
7847205789Sbz	for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
7848205789Sbz	    spacq = nextspacq) {
7849205789Sbz		nextspacq = LIST_NEXT(spacq, chain);
7850205789Sbz		if (__LIST_CHAINED(spacq)) {
7851205789Sbz			LIST_REMOVE(spacq, chain);
7852205789Sbz			free(spacq, M_IPSEC_SAQ);
7853193731Szec		}
7854193731Szec	}
7855193731Szec	SPACQ_UNLOCK();
7856105197Ssam}
7857193731Szec#endif
7858105197Ssam
7859105197Ssam/*
7860105197Ssam * XXX: maybe This function is called after INBOUND IPsec processing.
7861105197Ssam *
7862105197Ssam * Special check for tunnel-mode packets.
7863105197Ssam * We must make some checks for consistency between inner and outer IP header.
7864105197Ssam *
7865105197Ssam * xxx more checks to be provided
7866105197Ssam */
7867105197Ssamint
7868105197Ssamkey_checktunnelsanity(sav, family, src, dst)
7869105197Ssam	struct secasvar *sav;
7870105197Ssam	u_int family;
7871105197Ssam	caddr_t src;
7872105197Ssam	caddr_t dst;
7873105197Ssam{
7874120585Ssam	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7875105197Ssam
7876105197Ssam	/* XXX: check inner IP header */
7877105197Ssam
7878105197Ssam	return 1;
7879105197Ssam}
7880105197Ssam
7881105197Ssam/* record data transfer on SA, and update timestamps */
7882105197Ssamvoid
7883105197Ssamkey_sa_recordxfer(sav, m)
7884105197Ssam	struct secasvar *sav;
7885105197Ssam	struct mbuf *m;
7886105197Ssam{
7887120585Ssam	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7888120585Ssam	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7889105197Ssam	if (!sav->lft_c)
7890105197Ssam		return;
7891105197Ssam
7892105197Ssam	/*
7893105197Ssam	 * XXX Currently, there is a difference of bytes size
7894105197Ssam	 * between inbound and outbound processing.
7895105197Ssam	 */
7896157123Sgnn	sav->lft_c->bytes += m->m_pkthdr.len;
7897105197Ssam	/* to check bytes lifetime is done in key_timehandler(). */
7898105197Ssam
7899105197Ssam	/*
7900105197Ssam	 * We use the number of packets as the unit of
7901157123Sgnn	 * allocations.  We increment the variable
7902105197Ssam	 * whenever {esp,ah}_{in,out}put is called.
7903105197Ssam	 */
7904157123Sgnn	sav->lft_c->allocations++;
7905105197Ssam	/* XXX check for expires? */
7906105197Ssam
7907105197Ssam	/*
7908157123Sgnn	 * NOTE: We record CURRENT usetime by using wall clock,
7909105197Ssam	 * in seconds.  HARD and SOFT lifetime are measured by the time
7910157123Sgnn	 * difference (again in seconds) from usetime.
7911105197Ssam	 *
7912105197Ssam	 *	usetime
7913105197Ssam	 *	v     expire   expire
7914105197Ssam	 * -----+-----+--------+---> t
7915105197Ssam	 *	<--------------> HARD
7916105197Ssam	 *	<-----> SOFT
7917105197Ssam	 */
7918157123Sgnn	sav->lft_c->usetime = time_second;
7919105197Ssam	/* XXX check for expires? */
7920105197Ssam
7921105197Ssam	return;
7922105197Ssam}
7923105197Ssam
7924105197Ssam/* dumb version */
7925105197Ssamvoid
7926105197Ssamkey_sa_routechange(dst)
7927105197Ssam	struct sockaddr *dst;
7928105197Ssam{
7929105197Ssam	struct secashead *sah;
7930105197Ssam	struct route *ro;
7931105197Ssam
7932120585Ssam	SAHTREE_LOCK();
7933181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7934214250Sbz		ro = &sah->route_cache.sa_route;
7935105197Ssam		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7936105197Ssam		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7937105197Ssam			RTFREE(ro->ro_rt);
7938105197Ssam			ro->ro_rt = (struct rtentry *)NULL;
7939105197Ssam		}
7940105197Ssam	}
7941120585Ssam	SAHTREE_UNLOCK();
7942105197Ssam}
7943105197Ssam
7944105197Ssamstatic void
7945189004Srdivackykey_sa_chgstate(struct secasvar *sav, u_int8_t state)
7946105197Ssam{
7947120585Ssam	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7948120585Ssam	SAHTREE_LOCK_ASSERT();
7949105197Ssam
7950119643Ssam	if (sav->state != state) {
7951119643Ssam		if (__LIST_CHAINED(sav))
7952119643Ssam			LIST_REMOVE(sav, chain);
7953119643Ssam		sav->state = state;
7954119643Ssam		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7955119643Ssam	}
7956105197Ssam}
7957105197Ssam
7958105197Ssamvoid
7959105197Ssamkey_sa_stir_iv(sav)
7960105197Ssam	struct secasvar *sav;
7961105197Ssam{
7962105197Ssam
7963120585Ssam	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7964105197Ssam	key_randomfill(sav->iv, sav->ivlen);
7965105197Ssam}
7966105197Ssam
7967105197Ssam/* XXX too much? */
7968105197Ssamstatic struct mbuf *
7969105197Ssamkey_alloc_mbuf(l)
7970105197Ssam	int l;
7971105197Ssam{
7972105197Ssam	struct mbuf *m = NULL, *n;
7973105197Ssam	int len, t;
7974105197Ssam
7975105197Ssam	len = l;
7976105197Ssam	while (len > 0) {
7977111119Simp		MGET(n, M_DONTWAIT, MT_DATA);
7978105197Ssam		if (n && len > MLEN)
7979111119Simp			MCLGET(n, M_DONTWAIT);
7980105197Ssam		if (!n) {
7981105197Ssam			m_freem(m);
7982105197Ssam			return NULL;
7983105197Ssam		}
7984105197Ssam
7985105197Ssam		n->m_next = NULL;
7986105197Ssam		n->m_len = 0;
7987105197Ssam		n->m_len = M_TRAILINGSPACE(n);
7988105197Ssam		/* use the bottom of mbuf, hoping we can prepend afterwards */
7989105197Ssam		if (n->m_len > len) {
7990105197Ssam			t = (n->m_len - len) & ~(sizeof(long) - 1);
7991105197Ssam			n->m_data += t;
7992105197Ssam			n->m_len = len;
7993105197Ssam		}
7994105197Ssam
7995105197Ssam		len -= n->m_len;
7996105197Ssam
7997105197Ssam		if (m)
7998105197Ssam			m_cat(m, n);
7999105197Ssam		else
8000105197Ssam			m = n;
8001105197Ssam	}
8002105197Ssam
8003105197Ssam	return m;
8004105197Ssam}
8005157123Sgnn
8006157123Sgnn/*
8007157123Sgnn * Take one of the kernel's security keys and convert it into a PF_KEY
8008157123Sgnn * structure within an mbuf, suitable for sending up to a waiting
8009157123Sgnn * application in user land.
8010157123Sgnn *
8011157123Sgnn * IN:
8012157123Sgnn *    src: A pointer to a kernel security key.
8013157123Sgnn *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
8014157123Sgnn * OUT:
8015157123Sgnn *    a valid mbuf or NULL indicating an error
8016157123Sgnn *
8017157123Sgnn */
8018157123Sgnn
8019157123Sgnnstatic struct mbuf *
8020157123Sgnnkey_setkey(struct seckey *src, u_int16_t exttype)
8021157123Sgnn{
8022157123Sgnn	struct mbuf *m;
8023157123Sgnn	struct sadb_key *p;
8024170799Sbz	int len;
8025157123Sgnn
8026157123Sgnn	if (src == NULL)
8027157123Sgnn		return NULL;
8028157123Sgnn
8029170799Sbz	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8030157123Sgnn	m = key_alloc_mbuf(len);
8031157123Sgnn	if (m == NULL)
8032157123Sgnn		return NULL;
8033157123Sgnn	p = mtod(m, struct sadb_key *);
8034157123Sgnn	bzero(p, len);
8035157123Sgnn	p->sadb_key_len = PFKEY_UNIT64(len);
8036157123Sgnn	p->sadb_key_exttype = exttype;
8037157123Sgnn	p->sadb_key_bits = src->bits;
8038157123Sgnn	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8039157123Sgnn
8040157123Sgnn	return m;
8041157123Sgnn}
8042157123Sgnn
8043157123Sgnn/*
8044157123Sgnn * Take one of the kernel's lifetime data structures and convert it
8045157123Sgnn * into a PF_KEY structure within an mbuf, suitable for sending up to
8046157123Sgnn * a waiting application in user land.
8047157123Sgnn *
8048157123Sgnn * IN:
8049157123Sgnn *    src: A pointer to a kernel lifetime structure.
8050157123Sgnn *    exttype: Which type of lifetime this is. Refer to the PF_KEY
8051157123Sgnn *             data structures for more information.
8052157123Sgnn * OUT:
8053157123Sgnn *    a valid mbuf or NULL indicating an error
8054157123Sgnn *
8055157123Sgnn */
8056157123Sgnn
8057157123Sgnnstatic struct mbuf *
8058157123Sgnnkey_setlifetime(struct seclifetime *src, u_int16_t exttype)
8059157123Sgnn{
8060157123Sgnn	struct mbuf *m = NULL;
8061157123Sgnn	struct sadb_lifetime *p;
8062157123Sgnn	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8063157123Sgnn
8064157123Sgnn	if (src == NULL)
8065157123Sgnn		return NULL;
8066157123Sgnn
8067157123Sgnn	m = key_alloc_mbuf(len);
8068157123Sgnn	if (m == NULL)
8069157123Sgnn		return m;
8070157123Sgnn	p = mtod(m, struct sadb_lifetime *);
8071157123Sgnn
8072157123Sgnn	bzero(p, len);
8073157123Sgnn	p->sadb_lifetime_len = PFKEY_UNIT64(len);
8074157123Sgnn	p->sadb_lifetime_exttype = exttype;
8075157123Sgnn	p->sadb_lifetime_allocations = src->allocations;
8076157123Sgnn	p->sadb_lifetime_bytes = src->bytes;
8077157123Sgnn	p->sadb_lifetime_addtime = src->addtime;
8078157123Sgnn	p->sadb_lifetime_usetime = src->usetime;
8079157123Sgnn
8080157123Sgnn	return m;
8081157123Sgnn
8082157123Sgnn}
8083