key.c revision 195727
1105197Ssam/*	$FreeBSD: head/sys/netipsec/key.c 195727 2009-07-16 21:13:04Z rwatson $	*/
2105197Ssam/*	$KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $	*/
3105197Ssam
4139823Simp/*-
5105197Ssam * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6105197Ssam * All rights reserved.
7105197Ssam *
8105197Ssam * Redistribution and use in source and binary forms, with or without
9105197Ssam * modification, are permitted provided that the following conditions
10105197Ssam * are met:
11105197Ssam * 1. Redistributions of source code must retain the above copyright
12105197Ssam *    notice, this list of conditions and the following disclaimer.
13105197Ssam * 2. Redistributions in binary form must reproduce the above copyright
14105197Ssam *    notice, this list of conditions and the following disclaimer in the
15105197Ssam *    documentation and/or other materials provided with the distribution.
16105197Ssam * 3. Neither the name of the project nor the names of its contributors
17105197Ssam *    may be used to endorse or promote products derived from this software
18105197Ssam *    without specific prior written permission.
19105197Ssam *
20105197Ssam * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21105197Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22105197Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23105197Ssam * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24105197Ssam * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25105197Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26105197Ssam * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27105197Ssam * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28105197Ssam * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29105197Ssam * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30105197Ssam * SUCH DAMAGE.
31105197Ssam */
32105197Ssam
33105197Ssam/*
34105197Ssam * This code is referd to RFC 2367
35105197Ssam */
36105197Ssam
37105197Ssam#include "opt_inet.h"
38105197Ssam#include "opt_inet6.h"
39105197Ssam#include "opt_ipsec.h"
40105197Ssam
41105197Ssam#include <sys/types.h>
42105197Ssam#include <sys/param.h>
43105197Ssam#include <sys/systm.h>
44105197Ssam#include <sys/kernel.h>
45119643Ssam#include <sys/lock.h>
46119643Ssam#include <sys/mutex.h>
47105197Ssam#include <sys/mbuf.h>
48105197Ssam#include <sys/domain.h>
49105197Ssam#include <sys/protosw.h>
50105197Ssam#include <sys/malloc.h>
51105197Ssam#include <sys/socket.h>
52105197Ssam#include <sys/socketvar.h>
53105197Ssam#include <sys/sysctl.h>
54105197Ssam#include <sys/errno.h>
55105197Ssam#include <sys/proc.h>
56105197Ssam#include <sys/queue.h>
57158767Spjd#include <sys/refcount.h>
58105197Ssam#include <sys/syslog.h>
59183550Szec#include <sys/vimage.h>
60105197Ssam
61105197Ssam#include <net/if.h>
62105197Ssam#include <net/route.h>
63105197Ssam#include <net/raw_cb.h>
64195699Srwatson#include <net/vnet.h>
65105197Ssam
66105197Ssam#include <netinet/in.h>
67105197Ssam#include <netinet/in_systm.h>
68105197Ssam#include <netinet/ip.h>
69105197Ssam#include <netinet/in_var.h>
70105197Ssam
71105197Ssam#ifdef INET6
72105197Ssam#include <netinet/ip6.h>
73105197Ssam#include <netinet6/in6_var.h>
74105197Ssam#include <netinet6/ip6_var.h>
75105197Ssam#endif /* INET6 */
76105197Ssam
77105197Ssam#ifdef INET
78105197Ssam#include <netinet/in_pcb.h>
79105197Ssam#endif
80105197Ssam#ifdef INET6
81105197Ssam#include <netinet6/in6_pcb.h>
82105197Ssam#endif /* INET6 */
83105197Ssam
84105197Ssam#include <net/pfkeyv2.h>
85105197Ssam#include <netipsec/keydb.h>
86105197Ssam#include <netipsec/key.h>
87105197Ssam#include <netipsec/keysock.h>
88105197Ssam#include <netipsec/key_debug.h>
89105197Ssam
90105197Ssam#include <netipsec/ipsec.h>
91105197Ssam#ifdef INET6
92105197Ssam#include <netipsec/ipsec6.h>
93105197Ssam#endif
94105197Ssam
95105197Ssam#include <netipsec/xform.h>
96105197Ssam
97105197Ssam#include <machine/stdarg.h>
98105197Ssam
99105197Ssam/* randomness */
100105197Ssam#include <sys/random.h>
101105197Ssam
102105197Ssam#define FULLMASK	0xff
103105197Ssam#define	_BITS(bytes)	((bytes) << 3)
104105197Ssam
105105197Ssam/*
106105197Ssam * Note on SA reference counting:
107105197Ssam * - SAs that are not in DEAD state will have (total external reference + 1)
108105197Ssam *   following value in reference count field.  they cannot be freed and are
109105197Ssam *   referenced from SA header.
110105197Ssam * - SAs that are in DEAD state will have (total external reference)
111105197Ssam *   in reference count field.  they are ready to be freed.  reference from
112105197Ssam *   SA header will be removed in key_delsav(), when the reference count
113105197Ssam *   field hits 0 (= no external reference other than from SA header.
114105197Ssam */
115105197Ssam
116195699SrwatsonVNET_DEFINE(u_int32_t, key_debug_level) = 0;
117195699Srwatsonstatic VNET_DEFINE(u_int, key_spi_trycnt) = 1000;
118195727Srwatson#define	V_key_spi_trycnt	VNET(key_spi_trycnt)
119195699Srwatsonstatic VNET_DEFINE(u_int32_t, key_spi_minval) = 0x100;
120195727Srwatson#define	V_key_spi_minval	VNET(key_spi_minval)
121195699Srwatsonstatic VNET_DEFINE(u_int32_t, key_spi_maxval) = 0x0fffffff;	/* XXX */
122195727Srwatson#define	V_key_spi_maxval	VNET(key_spi_maxval)
123195699Srwatsonstatic VNET_DEFINE(u_int32_t, policy_id) = 0;
124195727Srwatson#define	V_policy_id		VNET(policy_id)
125195699Srwatson/*interval to initialize randseed,1(m)*/
126195699Srwatsonstatic VNET_DEFINE(u_int, key_int_random) = 60;
127195727Srwatson#define	V_key_int_random	VNET(key_int_random)
128195699Srwatson/* interval to expire acquiring, 30(s)*/
129195699Srwatsonstatic VNET_DEFINE(u_int, key_larval_lifetime) = 30;
130195727Srwatson#define	V_key_larval_lifetime	VNET(key_larval_lifetime)
131195699Srwatson/* counter for blocking SADB_ACQUIRE.*/
132195699Srwatsonstatic VNET_DEFINE(int, key_blockacq_count) = 10;
133195727Srwatson#define	V_key_blockacq_count	VNET(key_blockacq_count)
134195699Srwatson/* lifetime for blocking SADB_ACQUIRE.*/
135195699Srwatsonstatic VNET_DEFINE(int, key_blockacq_lifetime) = 20;
136195727Srwatson#define	V_key_blockacq_lifetime	VNET(key_blockacq_lifetime)
137195699Srwatson/* preferred old sa rather than new sa.*/
138195699Srwatsonstatic VNET_DEFINE(int, key_preferred_oldsa) = 1;
139195727Srwatson#define	V_key_preferred_oldsa	VNET(key_preferred_oldsa)
140105197Ssam
141195699Srwatsonstatic VNET_DEFINE(u_int32_t, acq_seq) = 0;
142195727Srwatson#define	V_acq_seq		VNET(acq_seq)
143105197Ssam
144195699Srwatson								/* SPD */
145195699Srwatsonstatic VNET_DEFINE(LIST_HEAD(_sptree, secpolicy), sptree[IPSEC_DIR_MAX]);
146195727Srwatson#define	V_sptree		VNET(sptree)
147119643Ssamstatic struct mtx sptree_lock;
148120585Ssam#define	SPTREE_LOCK_INIT() \
149120585Ssam	mtx_init(&sptree_lock, "sptree", \
150120585Ssam		"fast ipsec security policy database", MTX_DEF)
151120585Ssam#define	SPTREE_LOCK_DESTROY()	mtx_destroy(&sptree_lock)
152120585Ssam#define	SPTREE_LOCK()		mtx_lock(&sptree_lock)
153120585Ssam#define	SPTREE_UNLOCK()	mtx_unlock(&sptree_lock)
154120585Ssam#define	SPTREE_LOCK_ASSERT()	mtx_assert(&sptree_lock, MA_OWNED)
155120585Ssam
156195699Srwatsonstatic VNET_DEFINE(LIST_HEAD(_sahtree, secashead), sahtree);	/* SAD */
157195727Srwatson#define	V_sahtree		VNET(sahtree)
158119643Ssamstatic struct mtx sahtree_lock;
159120585Ssam#define	SAHTREE_LOCK_INIT() \
160120585Ssam	mtx_init(&sahtree_lock, "sahtree", \
161120585Ssam		"fast ipsec security association database", MTX_DEF)
162120585Ssam#define	SAHTREE_LOCK_DESTROY()	mtx_destroy(&sahtree_lock)
163120585Ssam#define	SAHTREE_LOCK()		mtx_lock(&sahtree_lock)
164120585Ssam#define	SAHTREE_UNLOCK()	mtx_unlock(&sahtree_lock)
165120585Ssam#define	SAHTREE_LOCK_ASSERT()	mtx_assert(&sahtree_lock, MA_OWNED)
166120585Ssam
167119643Ssam							/* registed list */
168195699Srwatsonstatic VNET_DEFINE(LIST_HEAD(_regtree, secreg), regtree[SADB_SATYPE_MAX + 1]);
169195727Srwatson#define	V_regtree		VNET(regtree)
170119643Ssamstatic struct mtx regtree_lock;
171120585Ssam#define	REGTREE_LOCK_INIT() \
172120585Ssam	mtx_init(&regtree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
173120585Ssam#define	REGTREE_LOCK_DESTROY()	mtx_destroy(&regtree_lock)
174120585Ssam#define	REGTREE_LOCK()		mtx_lock(&regtree_lock)
175120585Ssam#define	REGTREE_UNLOCK()	mtx_unlock(&regtree_lock)
176120585Ssam#define	REGTREE_LOCK_ASSERT()	mtx_assert(&regtree_lock, MA_OWNED)
177120585Ssam
178195699Srwatsonstatic VNET_DEFINE(LIST_HEAD(_acqtree, secacq), acqtree); /* acquiring list */
179195727Srwatson#define	V_acqtree		VNET(acqtree)
180119643Ssamstatic struct mtx acq_lock;
181120585Ssam#define	ACQ_LOCK_INIT() \
182120585Ssam	mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
183120585Ssam#define	ACQ_LOCK_DESTROY()	mtx_destroy(&acq_lock)
184120585Ssam#define	ACQ_LOCK()		mtx_lock(&acq_lock)
185120585Ssam#define	ACQ_UNLOCK()		mtx_unlock(&acq_lock)
186120585Ssam#define	ACQ_LOCK_ASSERT()	mtx_assert(&acq_lock, MA_OWNED)
187120585Ssam
188195699Srwatson							/* SP acquiring list */
189195699Srwatsonstatic VNET_DEFINE(LIST_HEAD(_spacqtree, secspacq), spacqtree);
190195727Srwatson#define	V_spacqtree		VNET(spacqtree)
191119643Ssamstatic struct mtx spacq_lock;
192120585Ssam#define	SPACQ_LOCK_INIT() \
193120585Ssam	mtx_init(&spacq_lock, "spacqtree", \
194120585Ssam		"fast ipsec security policy acquire list", MTX_DEF)
195120585Ssam#define	SPACQ_LOCK_DESTROY()	mtx_destroy(&spacq_lock)
196120585Ssam#define	SPACQ_LOCK()		mtx_lock(&spacq_lock)
197120585Ssam#define	SPACQ_UNLOCK()		mtx_unlock(&spacq_lock)
198120585Ssam#define	SPACQ_LOCK_ASSERT()	mtx_assert(&spacq_lock, MA_OWNED)
199105197Ssam
200105197Ssam/* search order for SAs */
201128856Ssamstatic const u_int saorder_state_valid_prefer_old[] = {
202105197Ssam	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
203105197Ssam};
204128856Ssamstatic const u_int saorder_state_valid_prefer_new[] = {
205128856Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
206128856Ssam};
207185348Szecstatic const u_int saorder_state_alive[] = {
208105197Ssam	/* except DEAD */
209105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
210105197Ssam};
211185348Szecstatic const u_int saorder_state_any[] = {
212105197Ssam	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
213105197Ssam	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
214105197Ssam};
215105197Ssam
216105197Ssamstatic const int minsize[] = {
217105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
218105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
219105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
220105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
221105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
222105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
223105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
224105197Ssam	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
225105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
226105197Ssam	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
227105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
228105197Ssam	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
229105197Ssam	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
230105197Ssam	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
231105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
232105197Ssam	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
233105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
234105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
235105197Ssam	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
236105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
237194062Svanhu	sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
238194062Svanhu	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
239194062Svanhu	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
240194062Svanhu	sizeof(struct sadb_address),	/* SADB_X_EXT_NAT_T_OAI */
241194062Svanhu	sizeof(struct sadb_address),	/* SADB_X_EXT_NAT_T_OAR */
242194062Svanhu	sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
243105197Ssam};
244105197Ssamstatic const int maxsize[] = {
245105197Ssam	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
246105197Ssam	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
247105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
248105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
249105197Ssam	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
250105197Ssam	0,				/* SADB_EXT_ADDRESS_SRC */
251105197Ssam	0,				/* SADB_EXT_ADDRESS_DST */
252105197Ssam	0,				/* SADB_EXT_ADDRESS_PROXY */
253105197Ssam	0,				/* SADB_EXT_KEY_AUTH */
254105197Ssam	0,				/* SADB_EXT_KEY_ENCRYPT */
255105197Ssam	0,				/* SADB_EXT_IDENTITY_SRC */
256105197Ssam	0,				/* SADB_EXT_IDENTITY_DST */
257105197Ssam	0,				/* SADB_EXT_SENSITIVITY */
258105197Ssam	0,				/* SADB_EXT_PROPOSAL */
259105197Ssam	0,				/* SADB_EXT_SUPPORTED_AUTH */
260105197Ssam	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
261105197Ssam	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
262105197Ssam	0,				/* SADB_X_EXT_KMPRIVATE */
263105197Ssam	0,				/* SADB_X_EXT_POLICY */
264105197Ssam	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
265194062Svanhu	sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
266194062Svanhu	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
267194062Svanhu	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
268194062Svanhu	0,				/* SADB_X_EXT_NAT_T_OAI */
269194062Svanhu	0,				/* SADB_X_EXT_NAT_T_OAR */
270194062Svanhu	sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
271105197Ssam};
272105197Ssam
273195699Srwatsonstatic VNET_DEFINE(int, ipsec_esp_keymin) = 256;
274195727Srwatson#define	V_ipsec_esp_keymin	VNET(ipsec_esp_keymin)
275195699Srwatsonstatic VNET_DEFINE(int, ipsec_esp_auth) = 0;
276195727Srwatson#define	V_ipsec_esp_auth	VNET(ipsec_esp_auth)
277195699Srwatsonstatic VNET_DEFINE(int, ipsec_ah_keymin) = 128;
278195727Srwatson#define	V_ipsec_ah_keymin	VNET(ipsec_ah_keymin)
279195699Srwatson
280105197Ssam#ifdef SYSCTL_DECL
281105197SsamSYSCTL_DECL(_net_key);
282105197Ssam#endif
283105197Ssam
284195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,
285195699Srwatson	CTLFLAG_RW, &VNET_NAME(key_debug_level),	0,	"");
286105197Ssam
287105197Ssam/* max count of trial for the decision of spi value */
288195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
289195699Srwatson	CTLFLAG_RW, &VNET_NAME(key_spi_trycnt),	0,	"");
290105197Ssam
291105197Ssam/* minimum spi value to allocate automatically. */
292195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MIN_VALUE,
293195699Srwatson	spi_minval,	CTLFLAG_RW, &VNET_NAME(key_spi_minval),	0,	"");
294105197Ssam
295105197Ssam/* maximun spi value to allocate automatically. */
296195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MAX_VALUE,
297195699Srwatson	spi_maxval,	CTLFLAG_RW, &VNET_NAME(key_spi_maxval),	0,	"");
298105197Ssam
299105197Ssam/* interval to initialize randseed */
300195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_RANDOM_INT,
301195699Srwatson	int_random,	CTLFLAG_RW, &VNET_NAME(key_int_random),	0,	"");
302105197Ssam
303105197Ssam/* lifetime for larval SA */
304195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_LARVAL_LIFETIME,
305195699Srwatson	larval_lifetime, CTLFLAG_RW, &VNET_NAME(key_larval_lifetime),	0, "");
306105197Ssam
307105197Ssam/* counter for blocking to send SADB_ACQUIRE to IKEd */
308195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,
309195699Srwatson	blockacq_count,	CTLFLAG_RW, &VNET_NAME(key_blockacq_count),	0, "");
310105197Ssam
311105197Ssam/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
312195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,
313195699Srwatson	blockacq_lifetime, CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
314105197Ssam
315105197Ssam/* ESP auth */
316195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth,
317195699Srwatson	CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth),	0,	"");
318105197Ssam
319105197Ssam/* minimum ESP key length */
320195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_ESP_KEYMIN,
321195699Srwatson	esp_keymin, CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin),	0,	"");
322105197Ssam
323105197Ssam/* minimum AH key length */
324195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin,
325195699Srwatson	CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin),	0,	"");
326105197Ssam
327105197Ssam/* perfered old SA rather than new SA */
328195699SrwatsonSYSCTL_VNET_INT(_net_key, KEYCTL_PREFERED_OLDSA,
329195699Srwatson	preferred_oldsa, CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa),	0, "");
330105197Ssam
331105197Ssam#define __LIST_CHAINED(elm) \
332105197Ssam	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
333105197Ssam#define LIST_INSERT_TAIL(head, elm, type, field) \
334105197Ssamdo {\
335105197Ssam	struct type *curelm = LIST_FIRST(head); \
336105197Ssam	if (curelm == NULL) {\
337105197Ssam		LIST_INSERT_HEAD(head, elm, field); \
338105197Ssam	} else { \
339105197Ssam		while (LIST_NEXT(curelm, field)) \
340105197Ssam			curelm = LIST_NEXT(curelm, field);\
341105197Ssam		LIST_INSERT_AFTER(curelm, elm, field);\
342105197Ssam	}\
343105197Ssam} while (0)
344105197Ssam
345105197Ssam#define KEY_CHKSASTATE(head, sav, name) \
346105197Ssamdo { \
347105197Ssam	if ((head) != (sav)) {						\
348105197Ssam		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
349105197Ssam			(name), (head), (sav)));			\
350105197Ssam		continue;						\
351105197Ssam	}								\
352105197Ssam} while (0)
353105197Ssam
354105197Ssam#define KEY_CHKSPDIR(head, sp, name) \
355105197Ssamdo { \
356105197Ssam	if ((head) != (sp)) {						\
357105197Ssam		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
358105197Ssam			"anyway continue.\n",				\
359105197Ssam			(name), (head), (sp)));				\
360105197Ssam	}								\
361105197Ssam} while (0)
362105197Ssam
363119643SsamMALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
364119643SsamMALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
365119643SsamMALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
366119643SsamMALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
367119643SsamMALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
368119643SsamMALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
369119643SsamMALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
370105197Ssam
371105197Ssam/*
372105197Ssam * set parameters into secpolicyindex buffer.
373105197Ssam * Must allocate secpolicyindex buffer passed to this function.
374105197Ssam */
375105197Ssam#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
376105197Ssamdo { \
377105197Ssam	bzero((idx), sizeof(struct secpolicyindex));                         \
378105197Ssam	(idx)->dir = (_dir);                                                 \
379105197Ssam	(idx)->prefs = (ps);                                                 \
380105197Ssam	(idx)->prefd = (pd);                                                 \
381105197Ssam	(idx)->ul_proto = (ulp);                                             \
382105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
383105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
384105197Ssam} while (0)
385105197Ssam
386105197Ssam/*
387105197Ssam * set parameters into secasindex buffer.
388105197Ssam * Must allocate secasindex buffer before calling this function.
389105197Ssam */
390105197Ssam#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
391105197Ssamdo { \
392105197Ssam	bzero((idx), sizeof(struct secasindex));                             \
393105197Ssam	(idx)->proto = (p);                                                  \
394105197Ssam	(idx)->mode = (m);                                                   \
395105197Ssam	(idx)->reqid = (r);                                                  \
396105197Ssam	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
397105197Ssam	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
398105197Ssam} while (0)
399105197Ssam
400105197Ssam/* key statistics */
401105197Ssamstruct _keystat {
402105197Ssam	u_long getspi_count; /* the avarage of count to try to get new SPI */
403105197Ssam} keystat;
404105197Ssam
405105197Ssamstruct sadb_msghdr {
406105197Ssam	struct sadb_msg *msg;
407105197Ssam	struct sadb_ext *ext[SADB_EXT_MAX + 1];
408105197Ssam	int extoff[SADB_EXT_MAX + 1];
409105197Ssam	int extlen[SADB_EXT_MAX + 1];
410105197Ssam};
411105197Ssam
412105197Ssamstatic struct secasvar *key_allocsa_policy __P((const struct secasindex *));
413105197Ssamstatic void key_freesp_so __P((struct secpolicy **));
414105197Ssamstatic struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
415105197Ssamstatic void key_delsp __P((struct secpolicy *));
416105197Ssamstatic struct secpolicy *key_getsp __P((struct secpolicyindex *));
417119643Ssamstatic void _key_delsp(struct secpolicy *sp);
418105197Ssamstatic struct secpolicy *key_getspbyid __P((u_int32_t));
419105197Ssamstatic u_int32_t key_newreqid __P((void));
420105197Ssamstatic struct mbuf *key_gather_mbuf __P((struct mbuf *,
421105197Ssam	const struct sadb_msghdr *, int, int, ...));
422105197Ssamstatic int key_spdadd __P((struct socket *, struct mbuf *,
423105197Ssam	const struct sadb_msghdr *));
424105197Ssamstatic u_int32_t key_getnewspid __P((void));
425105197Ssamstatic int key_spddelete __P((struct socket *, struct mbuf *,
426105197Ssam	const struct sadb_msghdr *));
427105197Ssamstatic int key_spddelete2 __P((struct socket *, struct mbuf *,
428105197Ssam	const struct sadb_msghdr *));
429105197Ssamstatic int key_spdget __P((struct socket *, struct mbuf *,
430105197Ssam	const struct sadb_msghdr *));
431105197Ssamstatic int key_spdflush __P((struct socket *, struct mbuf *,
432105197Ssam	const struct sadb_msghdr *));
433105197Ssamstatic int key_spddump __P((struct socket *, struct mbuf *,
434105197Ssam	const struct sadb_msghdr *));
435105197Ssamstatic struct mbuf *key_setdumpsp __P((struct secpolicy *,
436105197Ssam	u_int8_t, u_int32_t, u_int32_t));
437105197Ssamstatic u_int key_getspreqmsglen __P((struct secpolicy *));
438105197Ssamstatic int key_spdexpire __P((struct secpolicy *));
439105197Ssamstatic struct secashead *key_newsah __P((struct secasindex *));
440105197Ssamstatic void key_delsah __P((struct secashead *));
441105197Ssamstatic struct secasvar *key_newsav __P((struct mbuf *,
442105197Ssam	const struct sadb_msghdr *, struct secashead *, int *,
443105197Ssam	const char*, int));
444105197Ssam#define	KEY_NEWSAV(m, sadb, sah, e)				\
445105197Ssam	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
446105197Ssamstatic void key_delsav __P((struct secasvar *));
447105197Ssamstatic struct secashead *key_getsah __P((struct secasindex *));
448105197Ssamstatic struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
449105197Ssamstatic struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
450105197Ssamstatic int key_setsaval __P((struct secasvar *, struct mbuf *,
451105197Ssam	const struct sadb_msghdr *));
452105197Ssamstatic int key_mature __P((struct secasvar *));
453105197Ssamstatic struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
454105197Ssam	u_int8_t, u_int32_t, u_int32_t));
455105197Ssamstatic struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
456105197Ssam	u_int32_t, pid_t, u_int16_t));
457105197Ssamstatic struct mbuf *key_setsadbsa __P((struct secasvar *));
458105197Ssamstatic struct mbuf *key_setsadbaddr __P((u_int16_t,
459105197Ssam	const struct sockaddr *, u_int8_t, u_int16_t));
460194062Svanhu#ifdef IPSEC_NAT_T
461194062Svanhustatic struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
462194062Svanhustatic struct mbuf *key_setsadbxtype(u_int16_t);
463194062Svanhu#endif
464194062Svanhustatic void key_porttosaddr(struct sockaddr *, u_int16_t);
465194062Svanhu#define	KEY_PORTTOSADDR(saddr, port)				\
466194062Svanhu	key_porttosaddr((struct sockaddr *)(saddr), (port))
467105197Ssamstatic struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
468105197Ssamstatic struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
469105197Ssam	u_int32_t));
470157123Sgnnstatic struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
471157123Sgnn				     struct malloc_type *);
472157123Sgnnstatic struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
473157123Sgnn					    struct malloc_type *type);
474105197Ssam#ifdef INET6
475105197Ssamstatic int key_ismyaddr6 __P((struct sockaddr_in6 *));
476105197Ssam#endif
477105197Ssam
478105197Ssam/* flags for key_cmpsaidx() */
479105197Ssam#define CMP_HEAD	1	/* protocol, addresses. */
480105197Ssam#define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
481105197Ssam#define CMP_REQID	3	/* additionally HEAD, reaid. */
482105197Ssam#define CMP_EXACTLY	4	/* all elements. */
483105197Ssamstatic int key_cmpsaidx
484105197Ssam	__P((const struct secasindex *, const struct secasindex *, int));
485105197Ssam
486105197Ssamstatic int key_cmpspidx_exactly
487105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
488105197Ssamstatic int key_cmpspidx_withmask
489105197Ssam	__P((struct secpolicyindex *, struct secpolicyindex *));
490105197Ssamstatic int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
491105197Ssamstatic int key_bbcmp __P((const void *, const void *, u_int));
492105197Ssamstatic u_int16_t key_satype2proto __P((u_int8_t));
493105197Ssamstatic u_int8_t key_proto2satype __P((u_int16_t));
494105197Ssam
495105197Ssamstatic int key_getspi __P((struct socket *, struct mbuf *,
496105197Ssam	const struct sadb_msghdr *));
497105197Ssamstatic u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
498105197Ssam					struct secasindex *));
499105197Ssamstatic int key_update __P((struct socket *, struct mbuf *,
500105197Ssam	const struct sadb_msghdr *));
501105197Ssam#ifdef IPSEC_DOSEQCHECK
502105197Ssamstatic struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
503105197Ssam#endif
504105197Ssamstatic int key_add __P((struct socket *, struct mbuf *,
505105197Ssam	const struct sadb_msghdr *));
506105197Ssamstatic int key_setident __P((struct secashead *, struct mbuf *,
507105197Ssam	const struct sadb_msghdr *));
508105197Ssamstatic struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
509105197Ssam	const struct sadb_msghdr *));
510105197Ssamstatic int key_delete __P((struct socket *, struct mbuf *,
511105197Ssam	const struct sadb_msghdr *));
512105197Ssamstatic int key_get __P((struct socket *, struct mbuf *,
513105197Ssam	const struct sadb_msghdr *));
514105197Ssam
515105197Ssamstatic void key_getcomb_setlifetime __P((struct sadb_comb *));
516105197Ssamstatic struct mbuf *key_getcomb_esp __P((void));
517105197Ssamstatic struct mbuf *key_getcomb_ah __P((void));
518105197Ssamstatic struct mbuf *key_getcomb_ipcomp __P((void));
519105197Ssamstatic struct mbuf *key_getprop __P((const struct secasindex *));
520105197Ssam
521105197Ssamstatic int key_acquire __P((const struct secasindex *, struct secpolicy *));
522105197Ssamstatic struct secacq *key_newacq __P((const struct secasindex *));
523105197Ssamstatic struct secacq *key_getacq __P((const struct secasindex *));
524105197Ssamstatic struct secacq *key_getacqbyseq __P((u_int32_t));
525105197Ssamstatic struct secspacq *key_newspacq __P((struct secpolicyindex *));
526105197Ssamstatic struct secspacq *key_getspacq __P((struct secpolicyindex *));
527105197Ssamstatic int key_acquire2 __P((struct socket *, struct mbuf *,
528105197Ssam	const struct sadb_msghdr *));
529105197Ssamstatic int key_register __P((struct socket *, struct mbuf *,
530105197Ssam	const struct sadb_msghdr *));
531105197Ssamstatic int key_expire __P((struct secasvar *));
532105197Ssamstatic int key_flush __P((struct socket *, struct mbuf *,
533105197Ssam	const struct sadb_msghdr *));
534105197Ssamstatic int key_dump __P((struct socket *, struct mbuf *,
535105197Ssam	const struct sadb_msghdr *));
536105197Ssamstatic int key_promisc __P((struct socket *, struct mbuf *,
537105197Ssam	const struct sadb_msghdr *));
538105197Ssamstatic int key_senderror __P((struct socket *, struct mbuf *, int));
539105197Ssamstatic int key_validate_ext __P((const struct sadb_ext *, int));
540105197Ssamstatic int key_align __P((struct mbuf *, struct sadb_msghdr *));
541157123Sgnnstatic struct mbuf *key_setlifetime(struct seclifetime *src,
542157123Sgnn				     u_int16_t exttype);
543157123Sgnnstatic struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
544157123Sgnn
545105197Ssam#if 0
546105197Ssamstatic const char *key_getfqdn __P((void));
547105197Ssamstatic const char *key_getuserfqdn __P((void));
548105197Ssam#endif
549105197Ssamstatic void key_sa_chgstate __P((struct secasvar *, u_int8_t));
550105197Ssamstatic struct mbuf *key_alloc_mbuf __P((int));
551105197Ssam
552158767Spjdstatic __inline void
553158767Spjdsa_initref(struct secasvar *sav)
554158767Spjd{
555105197Ssam
556158767Spjd	refcount_init(&sav->refcnt, 1);
557158767Spjd}
558158767Spjdstatic __inline void
559158767Spjdsa_addref(struct secasvar *sav)
560158767Spjd{
561158767Spjd
562158767Spjd	refcount_acquire(&sav->refcnt);
563158767Spjd	IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
564158767Spjd}
565158767Spjdstatic __inline int
566158767Spjdsa_delref(struct secasvar *sav)
567158767Spjd{
568158767Spjd
569158767Spjd	IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
570158767Spjd	return (refcount_release(&sav->refcnt));
571158767Spjd}
572158767Spjd
573105197Ssam#define	SP_ADDREF(p) do {						\
574105197Ssam	(p)->refcnt++;							\
575120585Ssam	IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));		\
576105197Ssam} while (0)
577105197Ssam#define	SP_DELREF(p) do {						\
578120585Ssam	IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));		\
579105197Ssam	(p)->refcnt--;							\
580105197Ssam} while (0)
581135947Ssam
582105197Ssam
583105197Ssam/*
584135947Ssam * Update the refcnt while holding the SPTREE lock.
585135947Ssam */
586135947Ssamvoid
587135947Ssamkey_addref(struct secpolicy *sp)
588135947Ssam{
589135947Ssam	SPTREE_LOCK();
590135947Ssam	SP_ADDREF(sp);
591135947Ssam	SPTREE_UNLOCK();
592135947Ssam}
593135947Ssam
594135947Ssam/*
595105197Ssam * Return 0 when there are known to be no SP's for the specified
596105197Ssam * direction.  Otherwise return 1.  This is used by IPsec code
597105197Ssam * to optimize performance.
598105197Ssam */
599105197Ssamint
600105197Ssamkey_havesp(u_int dir)
601105197Ssam{
602183550Szec
603105197Ssam	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
604181803Sbz		LIST_FIRST(&V_sptree[dir]) != NULL : 1);
605105197Ssam}
606105197Ssam
607105197Ssam/* %%% IPsec policy management */
608105197Ssam/*
609105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
610105197Ssam * Must call key_freesp() later.
611105197Ssam * OUT:	NULL:	not found
612105197Ssam *	others:	found and return the pointer.
613105197Ssam */
614105197Ssamstruct secpolicy *
615105197Ssamkey_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
616105197Ssam{
617105197Ssam	struct secpolicy *sp;
618105197Ssam
619120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
620120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
621120585Ssam		("invalid direction %u", dir));
622105197Ssam
623105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
624120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
625105197Ssam
626105197Ssam	/* get a SP entry */
627105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
628105197Ssam		printf("*** objects\n");
629105197Ssam		kdebug_secpolicyindex(spidx));
630105197Ssam
631120585Ssam	SPTREE_LOCK();
632181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
633105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
634105197Ssam			printf("*** in SPD\n");
635105197Ssam			kdebug_secpolicyindex(&sp->spidx));
636105197Ssam
637105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
638105197Ssam			continue;
639105197Ssam		if (key_cmpspidx_withmask(&sp->spidx, spidx))
640105197Ssam			goto found;
641105197Ssam	}
642105197Ssam	sp = NULL;
643105197Ssamfound:
644105197Ssam	if (sp) {
645105197Ssam		/* sanity check */
646120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
647105197Ssam
648105197Ssam		/* found a SPD entry */
649105197Ssam		sp->lastused = time_second;
650105197Ssam		SP_ADDREF(sp);
651105197Ssam	}
652120585Ssam	SPTREE_UNLOCK();
653105197Ssam
654105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
655120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
656105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
657105197Ssam	return sp;
658105197Ssam}
659105197Ssam
660105197Ssam/*
661105197Ssam * allocating a SP for OUTBOUND or INBOUND packet.
662105197Ssam * Must call key_freesp() later.
663105197Ssam * OUT:	NULL:	not found
664105197Ssam *	others:	found and return the pointer.
665105197Ssam */
666105197Ssamstruct secpolicy *
667105197Ssamkey_allocsp2(u_int32_t spi,
668105197Ssam	     union sockaddr_union *dst,
669105197Ssam	     u_int8_t proto,
670105197Ssam	     u_int dir,
671105197Ssam	     const char* where, int tag)
672105197Ssam{
673105197Ssam	struct secpolicy *sp;
674105197Ssam
675120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst"));
676120585Ssam	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
677120585Ssam		("invalid direction %u", dir));
678105197Ssam
679105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
680120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
681105197Ssam
682105197Ssam	/* get a SP entry */
683105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
684105197Ssam		printf("*** objects\n");
685105197Ssam		printf("spi %u proto %u dir %u\n", spi, proto, dir);
686105197Ssam		kdebug_sockaddr(&dst->sa));
687105197Ssam
688120585Ssam	SPTREE_LOCK();
689181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
690105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
691105197Ssam			printf("*** in SPD\n");
692105197Ssam			kdebug_secpolicyindex(&sp->spidx));
693105197Ssam
694105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
695105197Ssam			continue;
696105197Ssam		/* compare simple values, then dst address */
697105197Ssam		if (sp->spidx.ul_proto != proto)
698105197Ssam			continue;
699105197Ssam		/* NB: spi's must exist and match */
700105197Ssam		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
701105197Ssam			continue;
702105197Ssam		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
703105197Ssam			goto found;
704105197Ssam	}
705105197Ssam	sp = NULL;
706105197Ssamfound:
707105197Ssam	if (sp) {
708105197Ssam		/* sanity check */
709120585Ssam		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
710105197Ssam
711105197Ssam		/* found a SPD entry */
712105197Ssam		sp->lastused = time_second;
713105197Ssam		SP_ADDREF(sp);
714105197Ssam	}
715120585Ssam	SPTREE_UNLOCK();
716105197Ssam
717105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
718120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
719105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
720105197Ssam	return sp;
721105197Ssam}
722105197Ssam
723191599Sbz#if 0
724105197Ssam/*
725105197Ssam * return a policy that matches this particular inbound packet.
726105197Ssam * XXX slow
727105197Ssam */
728105197Ssamstruct secpolicy *
729105197Ssamkey_gettunnel(const struct sockaddr *osrc,
730105197Ssam	      const struct sockaddr *odst,
731105197Ssam	      const struct sockaddr *isrc,
732105197Ssam	      const struct sockaddr *idst,
733105197Ssam	      const char* where, int tag)
734105197Ssam{
735105197Ssam	struct secpolicy *sp;
736105197Ssam	const int dir = IPSEC_DIR_INBOUND;
737105197Ssam	struct ipsecrequest *r1, *r2, *p;
738105197Ssam	struct secpolicyindex spidx;
739105197Ssam
740105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
741120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
742105197Ssam
743105197Ssam	if (isrc->sa_family != idst->sa_family) {
744120585Ssam		ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
745120585Ssam			__func__, isrc->sa_family, idst->sa_family));
746105197Ssam		sp = NULL;
747105197Ssam		goto done;
748105197Ssam	}
749105197Ssam
750120585Ssam	SPTREE_LOCK();
751181803Sbz	LIST_FOREACH(sp, &V_sptree[dir], chain) {
752105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
753105197Ssam			continue;
754105197Ssam
755105197Ssam		r1 = r2 = NULL;
756105197Ssam		for (p = sp->req; p; p = p->next) {
757105197Ssam			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
758105197Ssam				continue;
759105197Ssam
760105197Ssam			r1 = r2;
761105197Ssam			r2 = p;
762105197Ssam
763105197Ssam			if (!r1) {
764105197Ssam				/* here we look at address matches only */
765105197Ssam				spidx = sp->spidx;
766105197Ssam				if (isrc->sa_len > sizeof(spidx.src) ||
767105197Ssam				    idst->sa_len > sizeof(spidx.dst))
768105197Ssam					continue;
769105197Ssam				bcopy(isrc, &spidx.src, isrc->sa_len);
770105197Ssam				bcopy(idst, &spidx.dst, idst->sa_len);
771105197Ssam				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
772105197Ssam					continue;
773105197Ssam			} else {
774105197Ssam				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
775105197Ssam				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
776105197Ssam					continue;
777105197Ssam			}
778105197Ssam
779105197Ssam			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
780105197Ssam			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
781105197Ssam				continue;
782105197Ssam
783105197Ssam			goto found;
784105197Ssam		}
785105197Ssam	}
786105197Ssam	sp = NULL;
787105197Ssamfound:
788105197Ssam	if (sp) {
789105197Ssam		sp->lastused = time_second;
790105197Ssam		SP_ADDREF(sp);
791105197Ssam	}
792120585Ssam	SPTREE_UNLOCK();
793105197Ssamdone:
794105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
795120585Ssam		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
796105197Ssam			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
797105197Ssam	return sp;
798105197Ssam}
799191599Sbz#endif
800105197Ssam
801105197Ssam/*
802105197Ssam * allocating an SA entry for an *OUTBOUND* packet.
803105197Ssam * checking each request entries in SP, and acquire an SA if need.
804105197Ssam * OUT:	0: there are valid requests.
805105197Ssam *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
806105197Ssam */
807105197Ssamint
808105197Ssamkey_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
809105197Ssam{
810105197Ssam	u_int level;
811105197Ssam	int error;
812105197Ssam
813120585Ssam	IPSEC_ASSERT(isr != NULL, ("null isr"));
814120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
815120585Ssam	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
816105197Ssam		saidx->mode == IPSEC_MODE_TUNNEL,
817120585Ssam		("unexpected policy %u", saidx->mode));
818105197Ssam
819105197Ssam	/*
820105197Ssam	 * XXX guard against protocol callbacks from the crypto
821105197Ssam	 * thread as they reference ipsecrequest.sav which we
822105197Ssam	 * temporarily null out below.  Need to rethink how we
823105197Ssam	 * handle bundled SA's in the callback thread.
824105197Ssam	 */
825120585Ssam	IPSECREQUEST_LOCK_ASSERT(isr);
826119643Ssam
827119643Ssam	/* get current level */
828119643Ssam	level = ipsec_get_reqlevel(isr);
829105197Ssam#if 0
830105197Ssam	/*
831105197Ssam	 * We do allocate new SA only if the state of SA in the holder is
832105197Ssam	 * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
833105197Ssam	 */
834105197Ssam	if (isr->sav != NULL) {
835105197Ssam		if (isr->sav->sah == NULL)
836120585Ssam			panic("%s: sah is null.\n", __func__);
837105197Ssam		if (isr->sav == (struct secasvar *)LIST_FIRST(
838105197Ssam			    &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
839105197Ssam			KEY_FREESAV(&isr->sav);
840105197Ssam			isr->sav = NULL;
841105197Ssam		}
842105197Ssam	}
843105197Ssam#else
844105197Ssam	/*
845105197Ssam	 * we free any SA stashed in the IPsec request because a different
846105197Ssam	 * SA may be involved each time this request is checked, either
847105197Ssam	 * because new SAs are being configured, or this request is
848105197Ssam	 * associated with an unconnected datagram socket, or this request
849105197Ssam	 * is associated with a system default policy.
850105197Ssam	 *
851105197Ssam	 * The operation may have negative impact to performance.  We may
852105197Ssam	 * want to check cached SA carefully, rather than picking new SA
853105197Ssam	 * every time.
854105197Ssam	 */
855105197Ssam	if (isr->sav != NULL) {
856105197Ssam		KEY_FREESAV(&isr->sav);
857105197Ssam		isr->sav = NULL;
858105197Ssam	}
859105197Ssam#endif
860105197Ssam
861105197Ssam	/*
862105197Ssam	 * new SA allocation if no SA found.
863105197Ssam	 * key_allocsa_policy should allocate the oldest SA available.
864105197Ssam	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
865105197Ssam	 */
866105197Ssam	if (isr->sav == NULL)
867105197Ssam		isr->sav = key_allocsa_policy(saidx);
868105197Ssam
869105197Ssam	/* When there is SA. */
870105197Ssam	if (isr->sav != NULL) {
871105197Ssam		if (isr->sav->state != SADB_SASTATE_MATURE &&
872105197Ssam		    isr->sav->state != SADB_SASTATE_DYING)
873105197Ssam			return EINVAL;
874105197Ssam		return 0;
875105197Ssam	}
876105197Ssam
877105197Ssam	/* there is no SA */
878105197Ssam	error = key_acquire(saidx, isr->sp);
879105197Ssam	if (error != 0) {
880105197Ssam		/* XXX What should I do ? */
881120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
882120585Ssam			__func__, error));
883105197Ssam		return error;
884105197Ssam	}
885105197Ssam
886105197Ssam	if (level != IPSEC_LEVEL_REQUIRE) {
887105197Ssam		/* XXX sigh, the interface to this routine is botched */
888120585Ssam		IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
889105197Ssam		return 0;
890105197Ssam	} else {
891105197Ssam		return ENOENT;
892105197Ssam	}
893105197Ssam}
894105197Ssam
895105197Ssam/*
896105197Ssam * allocating a SA for policy entry from SAD.
897105197Ssam * NOTE: searching SAD of aliving state.
898105197Ssam * OUT:	NULL:	not found.
899105197Ssam *	others:	found and return the pointer.
900105197Ssam */
901105197Ssamstatic struct secasvar *
902105197Ssamkey_allocsa_policy(const struct secasindex *saidx)
903105197Ssam{
904128856Ssam#define	N(a)	_ARRAYLEN(a)
905105197Ssam	struct secashead *sah;
906105197Ssam	struct secasvar *sav;
907128856Ssam	u_int stateidx, arraysize;
908128856Ssam	const u_int *state_valid;
909105197Ssam
910120585Ssam	SAHTREE_LOCK();
911181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
912105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
913105197Ssam			continue;
914119643Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
915181803Sbz			if (V_key_preferred_oldsa) {
916128856Ssam				state_valid = saorder_state_valid_prefer_old;
917128856Ssam				arraysize = N(saorder_state_valid_prefer_old);
918128856Ssam			} else {
919128856Ssam				state_valid = saorder_state_valid_prefer_new;
920128856Ssam				arraysize = N(saorder_state_valid_prefer_new);
921128856Ssam			}
922120585Ssam			SAHTREE_UNLOCK();
923105197Ssam			goto found;
924119643Ssam		}
925105197Ssam	}
926120585Ssam	SAHTREE_UNLOCK();
927105197Ssam
928105197Ssam	return NULL;
929105197Ssam
930105197Ssam    found:
931105197Ssam	/* search valid state */
932128856Ssam	for (stateidx = 0; stateidx < arraysize; stateidx++) {
933128856Ssam		sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
934105197Ssam		if (sav != NULL)
935105197Ssam			return sav;
936105197Ssam	}
937105197Ssam
938105197Ssam	return NULL;
939128856Ssam#undef N
940105197Ssam}
941105197Ssam
942105197Ssam/*
943105197Ssam * searching SAD with direction, protocol, mode and state.
944105197Ssam * called by key_allocsa_policy().
945105197Ssam * OUT:
946105197Ssam *	NULL	: not found
947105197Ssam *	others	: found, pointer to a SA.
948105197Ssam */
949105197Ssamstatic struct secasvar *
950105197Ssamkey_do_allocsa_policy(struct secashead *sah, u_int state)
951105197Ssam{
952105197Ssam	struct secasvar *sav, *nextsav, *candidate, *d;
953105197Ssam
954105197Ssam	/* initilize */
955105197Ssam	candidate = NULL;
956105197Ssam
957120585Ssam	SAHTREE_LOCK();
958105197Ssam	for (sav = LIST_FIRST(&sah->savtree[state]);
959105197Ssam	     sav != NULL;
960105197Ssam	     sav = nextsav) {
961105197Ssam
962105197Ssam		nextsav = LIST_NEXT(sav, chain);
963105197Ssam
964105197Ssam		/* sanity check */
965120585Ssam		KEY_CHKSASTATE(sav->state, state, __func__);
966105197Ssam
967105197Ssam		/* initialize */
968105197Ssam		if (candidate == NULL) {
969105197Ssam			candidate = sav;
970105197Ssam			continue;
971105197Ssam		}
972105197Ssam
973105197Ssam		/* Which SA is the better ? */
974105197Ssam
975120585Ssam		IPSEC_ASSERT(candidate->lft_c != NULL,
976120585Ssam			("null candidate lifetime"));
977120585Ssam		IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
978105197Ssam
979105197Ssam		/* What the best method is to compare ? */
980181803Sbz		if (V_key_preferred_oldsa) {
981157123Sgnn			if (candidate->lft_c->addtime >
982157123Sgnn					sav->lft_c->addtime) {
983105197Ssam				candidate = sav;
984105197Ssam			}
985105197Ssam			continue;
986105197Ssam			/*NOTREACHED*/
987105197Ssam		}
988105197Ssam
989125876Sguido		/* preferred new sa rather than old sa */
990157123Sgnn		if (candidate->lft_c->addtime <
991157123Sgnn				sav->lft_c->addtime) {
992105197Ssam			d = candidate;
993105197Ssam			candidate = sav;
994105197Ssam		} else
995105197Ssam			d = sav;
996105197Ssam
997105197Ssam		/*
998105197Ssam		 * prepared to delete the SA when there is more
999105197Ssam		 * suitable candidate and the lifetime of the SA is not
1000105197Ssam		 * permanent.
1001105197Ssam		 */
1002177553Sbz		if (d->lft_h->addtime != 0) {
1003105197Ssam			struct mbuf *m, *result;
1004125508Ssam			u_int8_t satype;
1005105197Ssam
1006105197Ssam			key_sa_chgstate(d, SADB_SASTATE_DEAD);
1007105197Ssam
1008120585Ssam			IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
1009125508Ssam
1010125508Ssam			satype = key_proto2satype(d->sah->saidx.proto);
1011125508Ssam			if (satype == 0)
1012125508Ssam				goto msgfail;
1013125508Ssam
1014105197Ssam			m = key_setsadbmsg(SADB_DELETE, 0,
1015125508Ssam			    satype, 0, 0, d->refcnt - 1);
1016105197Ssam			if (!m)
1017105197Ssam				goto msgfail;
1018105197Ssam			result = m;
1019105197Ssam
1020105197Ssam			/* set sadb_address for saidx's. */
1021105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
1022105197Ssam				&d->sah->saidx.src.sa,
1023105197Ssam				d->sah->saidx.src.sa.sa_len << 3,
1024105197Ssam				IPSEC_ULPROTO_ANY);
1025105197Ssam			if (!m)
1026105197Ssam				goto msgfail;
1027105197Ssam			m_cat(result, m);
1028105197Ssam
1029105197Ssam			/* set sadb_address for saidx's. */
1030105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
1031128860Ssam				&d->sah->saidx.dst.sa,
1032128860Ssam				d->sah->saidx.dst.sa.sa_len << 3,
1033105197Ssam				IPSEC_ULPROTO_ANY);
1034105197Ssam			if (!m)
1035105197Ssam				goto msgfail;
1036105197Ssam			m_cat(result, m);
1037105197Ssam
1038105197Ssam			/* create SA extension */
1039105197Ssam			m = key_setsadbsa(d);
1040105197Ssam			if (!m)
1041105197Ssam				goto msgfail;
1042105197Ssam			m_cat(result, m);
1043105197Ssam
1044105197Ssam			if (result->m_len < sizeof(struct sadb_msg)) {
1045105197Ssam				result = m_pullup(result,
1046105197Ssam						sizeof(struct sadb_msg));
1047105197Ssam				if (result == NULL)
1048105197Ssam					goto msgfail;
1049105197Ssam			}
1050105197Ssam
1051105197Ssam			result->m_pkthdr.len = 0;
1052105197Ssam			for (m = result; m; m = m->m_next)
1053105197Ssam				result->m_pkthdr.len += m->m_len;
1054105197Ssam			mtod(result, struct sadb_msg *)->sadb_msg_len =
1055105197Ssam				PFKEY_UNIT64(result->m_pkthdr.len);
1056105197Ssam
1057105197Ssam			if (key_sendup_mbuf(NULL, result,
1058105197Ssam					KEY_SENDUP_REGISTERED))
1059105197Ssam				goto msgfail;
1060105197Ssam		 msgfail:
1061105197Ssam			KEY_FREESAV(&d);
1062105197Ssam		}
1063105197Ssam	}
1064105197Ssam	if (candidate) {
1065158767Spjd		sa_addref(candidate);
1066105197Ssam		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1067120585Ssam			printf("DP %s cause refcnt++:%d SA:%p\n",
1068120585Ssam				__func__, candidate->refcnt, candidate));
1069105197Ssam	}
1070120585Ssam	SAHTREE_UNLOCK();
1071119643Ssam
1072105197Ssam	return candidate;
1073105197Ssam}
1074105197Ssam
1075105197Ssam/*
1076105197Ssam * allocating a usable SA entry for a *INBOUND* packet.
1077105197Ssam * Must call key_freesav() later.
1078105197Ssam * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
1079105197Ssam *	NULL:		not found, or error occured.
1080105197Ssam *
1081105197Ssam * In the comparison, no source address is used--for RFC2401 conformance.
1082105197Ssam * To quote, from section 4.1:
1083105197Ssam *	A security association is uniquely identified by a triple consisting
1084105197Ssam *	of a Security Parameter Index (SPI), an IP Destination Address, and a
1085105197Ssam *	security protocol (AH or ESP) identifier.
1086105197Ssam * Note that, however, we do need to keep source address in IPsec SA.
1087105197Ssam * IKE specification and PF_KEY specification do assume that we
1088105197Ssam * keep source address in IPsec SA.  We see a tricky situation here.
1089105197Ssam */
1090105197Ssamstruct secasvar *
1091105197Ssamkey_allocsa(
1092105197Ssam	union sockaddr_union *dst,
1093105197Ssam	u_int proto,
1094105197Ssam	u_int32_t spi,
1095105197Ssam	const char* where, int tag)
1096105197Ssam{
1097105197Ssam	struct secashead *sah;
1098105197Ssam	struct secasvar *sav;
1099128856Ssam	u_int stateidx, arraysize, state;
1100128856Ssam	const u_int *saorder_state_valid;
1101194062Svanhu	int chkport;
1102105197Ssam
1103120585Ssam	IPSEC_ASSERT(dst != NULL, ("null dst address"));
1104105197Ssam
1105105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1106120585Ssam		printf("DP %s from %s:%u\n", __func__, where, tag));
1107105197Ssam
1108194062Svanhu#ifdef IPSEC_NAT_T
1109194062Svanhu        chkport = (dst->sa.sa_family == AF_INET &&
1110194062Svanhu	    dst->sa.sa_len == sizeof(struct sockaddr_in) &&
1111194062Svanhu	    dst->sin.sin_port != 0);
1112194062Svanhu#else
1113194062Svanhu	chkport = 0;
1114194062Svanhu#endif
1115194062Svanhu
1116105197Ssam	/*
1117105197Ssam	 * searching SAD.
1118105197Ssam	 * XXX: to be checked internal IP header somewhere.  Also when
1119105197Ssam	 * IPsec tunnel packet is received.  But ESP tunnel mode is
1120105197Ssam	 * encrypted so we can't check internal IP header.
1121105197Ssam	 */
1122120585Ssam	SAHTREE_LOCK();
1123181803Sbz	if (V_key_preferred_oldsa) {
1124128856Ssam		saorder_state_valid = saorder_state_valid_prefer_old;
1125128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1126128856Ssam	} else {
1127128856Ssam		saorder_state_valid = saorder_state_valid_prefer_new;
1128128856Ssam		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1129128856Ssam	}
1130181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
1131105197Ssam		/* search valid state */
1132128856Ssam		for (stateidx = 0; stateidx < arraysize; stateidx++) {
1133105197Ssam			state = saorder_state_valid[stateidx];
1134105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
1135105197Ssam				/* sanity check */
1136120585Ssam				KEY_CHKSASTATE(sav->state, state, __func__);
1137105197Ssam				/* do not return entries w/ unusable state */
1138105197Ssam				if (sav->state != SADB_SASTATE_MATURE &&
1139105197Ssam				    sav->state != SADB_SASTATE_DYING)
1140105197Ssam					continue;
1141105197Ssam				if (proto != sav->sah->saidx.proto)
1142105197Ssam					continue;
1143105197Ssam				if (spi != sav->spi)
1144105197Ssam					continue;
1145105197Ssam#if 0	/* don't check src */
1146105197Ssam				/* check src address */
1147194062Svanhu				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, chkport) != 0)
1148105197Ssam					continue;
1149105197Ssam#endif
1150105197Ssam				/* check dst address */
1151194062Svanhu				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, chkport) != 0)
1152105197Ssam					continue;
1153158767Spjd				sa_addref(sav);
1154105197Ssam				goto done;
1155105197Ssam			}
1156105197Ssam		}
1157105197Ssam	}
1158105197Ssam	sav = NULL;
1159105197Ssamdone:
1160120585Ssam	SAHTREE_UNLOCK();
1161105197Ssam
1162105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1163120585Ssam		printf("DP %s return SA:%p; refcnt %u\n", __func__,
1164105197Ssam			sav, sav ? sav->refcnt : 0));
1165105197Ssam	return sav;
1166105197Ssam}
1167105197Ssam
1168105197Ssam/*
1169105197Ssam * Must be called after calling key_allocsp().
1170105197Ssam * For both the packet without socket and key_freeso().
1171105197Ssam */
1172105197Ssamvoid
1173105197Ssam_key_freesp(struct secpolicy **spp, const char* where, int tag)
1174105197Ssam{
1175105197Ssam	struct secpolicy *sp = *spp;
1176105197Ssam
1177120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1178105197Ssam
1179120585Ssam	SPTREE_LOCK();
1180105197Ssam	SP_DELREF(sp);
1181105197Ssam
1182105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1183120585Ssam		printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1184120585Ssam			__func__, sp, sp->id, where, tag, sp->refcnt));
1185105197Ssam
1186105197Ssam	if (sp->refcnt == 0) {
1187105197Ssam		*spp = NULL;
1188105197Ssam		key_delsp(sp);
1189105197Ssam	}
1190120585Ssam	SPTREE_UNLOCK();
1191105197Ssam}
1192105197Ssam
1193105197Ssam/*
1194105197Ssam * Must be called after calling key_allocsp().
1195105197Ssam * For the packet with socket.
1196105197Ssam */
1197105197Ssamvoid
1198105197Ssamkey_freeso(struct socket *so)
1199105197Ssam{
1200120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
1201105197Ssam
1202105197Ssam	switch (so->so_proto->pr_domain->dom_family) {
1203186141Sbz#if defined(INET) || defined(INET6)
1204105197Ssam#ifdef INET
1205105197Ssam	case PF_INET:
1206105197Ssam#endif
1207105197Ssam#ifdef INET6
1208105197Ssam	case PF_INET6:
1209186141Sbz#endif
1210105197Ssam	    {
1211186141Sbz		struct inpcb *pcb = sotoinpcb(so);
1212105197Ssam
1213105197Ssam		/* Does it have a PCB ? */
1214105197Ssam		if (pcb == NULL)
1215105197Ssam			return;
1216105197Ssam		key_freesp_so(&pcb->inp_sp->sp_in);
1217105197Ssam		key_freesp_so(&pcb->inp_sp->sp_out);
1218105197Ssam	    }
1219105197Ssam		break;
1220186141Sbz#endif /* INET || INET6 */
1221105197Ssam	default:
1222120585Ssam		ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1223120585Ssam		    __func__, so->so_proto->pr_domain->dom_family));
1224105197Ssam		return;
1225105197Ssam	}
1226105197Ssam}
1227105197Ssam
1228105197Ssamstatic void
1229105197Ssamkey_freesp_so(struct secpolicy **sp)
1230105197Ssam{
1231120585Ssam	IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1232105197Ssam
1233105197Ssam	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1234105197Ssam	    (*sp)->policy == IPSEC_POLICY_BYPASS)
1235105197Ssam		return;
1236105197Ssam
1237120585Ssam	IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1238120585Ssam		("invalid policy %u", (*sp)->policy));
1239105197Ssam	KEY_FREESP(sp);
1240105197Ssam}
1241105197Ssam
1242105197Ssam/*
1243105197Ssam * Must be called after calling key_allocsa().
1244105197Ssam * This function is called by key_freesp() to free some SA allocated
1245105197Ssam * for a policy.
1246105197Ssam */
1247105197Ssamvoid
1248105197Ssamkey_freesav(struct secasvar **psav, const char* where, int tag)
1249105197Ssam{
1250105197Ssam	struct secasvar *sav = *psav;
1251105197Ssam
1252120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
1253105197Ssam
1254158767Spjd	if (sa_delref(sav)) {
1255158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1256158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1257158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1258105197Ssam		*psav = NULL;
1259105197Ssam		key_delsav(sav);
1260158767Spjd	} else {
1261158767Spjd		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1262158767Spjd			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1263158767Spjd				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1264105197Ssam	}
1265105197Ssam}
1266105197Ssam
1267105197Ssam/* %%% SPD management */
1268105197Ssam/*
1269105197Ssam * free security policy entry.
1270105197Ssam */
1271105197Ssamstatic void
1272105197Ssamkey_delsp(struct secpolicy *sp)
1273105197Ssam{
1274119643Ssam	struct ipsecrequest *isr, *nextisr;
1275105197Ssam
1276120585Ssam	IPSEC_ASSERT(sp != NULL, ("null sp"));
1277120585Ssam	SPTREE_LOCK_ASSERT();
1278105197Ssam
1279105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
1280105197Ssam
1281120585Ssam	IPSEC_ASSERT(sp->refcnt == 0,
1282120585Ssam		("SP with references deleted (refcnt %u)", sp->refcnt));
1283105197Ssam
1284105197Ssam	/* remove from SP index */
1285105197Ssam	if (__LIST_CHAINED(sp))
1286105197Ssam		LIST_REMOVE(sp, chain);
1287105197Ssam
1288119643Ssam	for (isr = sp->req; isr != NULL; isr = nextisr) {
1289105197Ssam		if (isr->sav != NULL) {
1290105197Ssam			KEY_FREESAV(&isr->sav);
1291105197Ssam			isr->sav = NULL;
1292105197Ssam		}
1293105197Ssam
1294105197Ssam		nextisr = isr->next;
1295119643Ssam		ipsec_delisr(isr);
1296105197Ssam	}
1297119643Ssam	_key_delsp(sp);
1298105197Ssam}
1299105197Ssam
1300105197Ssam/*
1301105197Ssam * search SPD
1302105197Ssam * OUT:	NULL	: not found
1303105197Ssam *	others	: found, pointer to a SP.
1304105197Ssam */
1305105197Ssamstatic struct secpolicy *
1306105197Ssamkey_getsp(struct secpolicyindex *spidx)
1307105197Ssam{
1308105197Ssam	struct secpolicy *sp;
1309105197Ssam
1310120585Ssam	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1311105197Ssam
1312120585Ssam	SPTREE_LOCK();
1313181803Sbz	LIST_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1314105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1315105197Ssam			continue;
1316105197Ssam		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1317105197Ssam			SP_ADDREF(sp);
1318119643Ssam			break;
1319105197Ssam		}
1320105197Ssam	}
1321120585Ssam	SPTREE_UNLOCK();
1322105197Ssam
1323119643Ssam	return sp;
1324105197Ssam}
1325105197Ssam
1326105197Ssam/*
1327105197Ssam * get SP by index.
1328105197Ssam * OUT:	NULL	: not found
1329105197Ssam *	others	: found, pointer to a SP.
1330105197Ssam */
1331105197Ssamstatic struct secpolicy *
1332105197Ssamkey_getspbyid(u_int32_t id)
1333105197Ssam{
1334105197Ssam	struct secpolicy *sp;
1335105197Ssam
1336120585Ssam	SPTREE_LOCK();
1337181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
1338105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1339105197Ssam			continue;
1340105197Ssam		if (sp->id == id) {
1341105197Ssam			SP_ADDREF(sp);
1342119643Ssam			goto done;
1343105197Ssam		}
1344105197Ssam	}
1345105197Ssam
1346181803Sbz	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
1347105197Ssam		if (sp->state == IPSEC_SPSTATE_DEAD)
1348105197Ssam			continue;
1349105197Ssam		if (sp->id == id) {
1350105197Ssam			SP_ADDREF(sp);
1351119643Ssam			goto done;
1352105197Ssam		}
1353105197Ssam	}
1354119643Ssamdone:
1355120585Ssam	SPTREE_UNLOCK();
1356105197Ssam
1357119643Ssam	return sp;
1358105197Ssam}
1359105197Ssam
1360105197Ssamstruct secpolicy *
1361105197Ssamkey_newsp(const char* where, int tag)
1362105197Ssam{
1363105197Ssam	struct secpolicy *newsp = NULL;
1364105197Ssam
1365105197Ssam	newsp = (struct secpolicy *)
1366119643Ssam		malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1367105197Ssam	if (newsp) {
1368120585Ssam		SECPOLICY_LOCK_INIT(newsp);
1369105197Ssam		newsp->refcnt = 1;
1370105197Ssam		newsp->req = NULL;
1371105197Ssam	}
1372105197Ssam
1373105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1374120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
1375105197Ssam			where, tag, newsp));
1376105197Ssam	return newsp;
1377105197Ssam}
1378105197Ssam
1379119643Ssamstatic void
1380119643Ssam_key_delsp(struct secpolicy *sp)
1381119643Ssam{
1382120585Ssam	SECPOLICY_LOCK_DESTROY(sp);
1383119643Ssam	free(sp, M_IPSEC_SP);
1384119643Ssam}
1385119643Ssam
1386105197Ssam/*
1387105197Ssam * create secpolicy structure from sadb_x_policy structure.
1388105197Ssam * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1389105197Ssam * so must be set properly later.
1390105197Ssam */
1391105197Ssamstruct secpolicy *
1392105197Ssamkey_msg2sp(xpl0, len, error)
1393105197Ssam	struct sadb_x_policy *xpl0;
1394105197Ssam	size_t len;
1395105197Ssam	int *error;
1396105197Ssam{
1397105197Ssam	struct secpolicy *newsp;
1398105197Ssam
1399120585Ssam	IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1400127972Spjd	IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1401120585Ssam
1402105197Ssam	if (len != PFKEY_EXTLEN(xpl0)) {
1403120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1404105197Ssam		*error = EINVAL;
1405105197Ssam		return NULL;
1406105197Ssam	}
1407105197Ssam
1408105197Ssam	if ((newsp = KEY_NEWSP()) == NULL) {
1409105197Ssam		*error = ENOBUFS;
1410105197Ssam		return NULL;
1411105197Ssam	}
1412105197Ssam
1413105197Ssam	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1414105197Ssam	newsp->policy = xpl0->sadb_x_policy_type;
1415105197Ssam
1416105197Ssam	/* check policy */
1417105197Ssam	switch (xpl0->sadb_x_policy_type) {
1418105197Ssam	case IPSEC_POLICY_DISCARD:
1419105197Ssam	case IPSEC_POLICY_NONE:
1420105197Ssam	case IPSEC_POLICY_ENTRUST:
1421105197Ssam	case IPSEC_POLICY_BYPASS:
1422105197Ssam		newsp->req = NULL;
1423105197Ssam		break;
1424105197Ssam
1425105197Ssam	case IPSEC_POLICY_IPSEC:
1426105197Ssam	    {
1427105197Ssam		int tlen;
1428105197Ssam		struct sadb_x_ipsecrequest *xisr;
1429105197Ssam		struct ipsecrequest **p_isr = &newsp->req;
1430105197Ssam
1431105197Ssam		/* validity check */
1432105197Ssam		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1433120585Ssam			ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1434120585Ssam				__func__));
1435105197Ssam			KEY_FREESP(&newsp);
1436105197Ssam			*error = EINVAL;
1437105197Ssam			return NULL;
1438105197Ssam		}
1439105197Ssam
1440105197Ssam		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1441105197Ssam		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1442105197Ssam
1443105197Ssam		while (tlen > 0) {
1444105197Ssam			/* length check */
1445105197Ssam			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1446120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1447120585Ssam					"length.\n", __func__));
1448105197Ssam				KEY_FREESP(&newsp);
1449105197Ssam				*error = EINVAL;
1450105197Ssam				return NULL;
1451105197Ssam			}
1452105197Ssam
1453105197Ssam			/* allocate request buffer */
1454119643Ssam			/* NB: data structure is zero'd */
1455119643Ssam			*p_isr = ipsec_newisr();
1456105197Ssam			if ((*p_isr) == NULL) {
1457105197Ssam				ipseclog((LOG_DEBUG,
1458120585Ssam				    "%s: No more memory.\n", __func__));
1459105197Ssam				KEY_FREESP(&newsp);
1460105197Ssam				*error = ENOBUFS;
1461105197Ssam				return NULL;
1462105197Ssam			}
1463105197Ssam
1464105197Ssam			/* set values */
1465105197Ssam			switch (xisr->sadb_x_ipsecrequest_proto) {
1466105197Ssam			case IPPROTO_ESP:
1467105197Ssam			case IPPROTO_AH:
1468105197Ssam			case IPPROTO_IPCOMP:
1469105197Ssam				break;
1470105197Ssam			default:
1471105197Ssam				ipseclog((LOG_DEBUG,
1472120585Ssam				    "%s: invalid proto type=%u\n", __func__,
1473105197Ssam				    xisr->sadb_x_ipsecrequest_proto));
1474105197Ssam				KEY_FREESP(&newsp);
1475105197Ssam				*error = EPROTONOSUPPORT;
1476105197Ssam				return NULL;
1477105197Ssam			}
1478105197Ssam			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1479105197Ssam
1480105197Ssam			switch (xisr->sadb_x_ipsecrequest_mode) {
1481105197Ssam			case IPSEC_MODE_TRANSPORT:
1482105197Ssam			case IPSEC_MODE_TUNNEL:
1483105197Ssam				break;
1484105197Ssam			case IPSEC_MODE_ANY:
1485105197Ssam			default:
1486105197Ssam				ipseclog((LOG_DEBUG,
1487120585Ssam				    "%s: invalid mode=%u\n", __func__,
1488105197Ssam				    xisr->sadb_x_ipsecrequest_mode));
1489105197Ssam				KEY_FREESP(&newsp);
1490105197Ssam				*error = EINVAL;
1491105197Ssam				return NULL;
1492105197Ssam			}
1493105197Ssam			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1494105197Ssam
1495105197Ssam			switch (xisr->sadb_x_ipsecrequest_level) {
1496105197Ssam			case IPSEC_LEVEL_DEFAULT:
1497105197Ssam			case IPSEC_LEVEL_USE:
1498105197Ssam			case IPSEC_LEVEL_REQUIRE:
1499105197Ssam				break;
1500105197Ssam			case IPSEC_LEVEL_UNIQUE:
1501105197Ssam				/* validity check */
1502105197Ssam				/*
1503105197Ssam				 * If range violation of reqid, kernel will
1504105197Ssam				 * update it, don't refuse it.
1505105197Ssam				 */
1506105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid
1507105197Ssam						> IPSEC_MANUAL_REQID_MAX) {
1508105197Ssam					ipseclog((LOG_DEBUG,
1509120585Ssam					    "%s: reqid=%d range "
1510105197Ssam					    "violation, updated by kernel.\n",
1511120585Ssam					    __func__,
1512105197Ssam					    xisr->sadb_x_ipsecrequest_reqid));
1513105197Ssam					xisr->sadb_x_ipsecrequest_reqid = 0;
1514105197Ssam				}
1515105197Ssam
1516105197Ssam				/* allocate new reqid id if reqid is zero. */
1517105197Ssam				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1518105197Ssam					u_int32_t reqid;
1519105197Ssam					if ((reqid = key_newreqid()) == 0) {
1520105197Ssam						KEY_FREESP(&newsp);
1521105197Ssam						*error = ENOBUFS;
1522105197Ssam						return NULL;
1523105197Ssam					}
1524105197Ssam					(*p_isr)->saidx.reqid = reqid;
1525105197Ssam					xisr->sadb_x_ipsecrequest_reqid = reqid;
1526105197Ssam				} else {
1527105197Ssam				/* set it for manual keying. */
1528105197Ssam					(*p_isr)->saidx.reqid =
1529105197Ssam						xisr->sadb_x_ipsecrequest_reqid;
1530105197Ssam				}
1531105197Ssam				break;
1532105197Ssam
1533105197Ssam			default:
1534120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1535120585Ssam					__func__,
1536105197Ssam					xisr->sadb_x_ipsecrequest_level));
1537105197Ssam				KEY_FREESP(&newsp);
1538105197Ssam				*error = EINVAL;
1539105197Ssam				return NULL;
1540105197Ssam			}
1541105197Ssam			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1542105197Ssam
1543105197Ssam			/* set IP addresses if there */
1544105197Ssam			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1545105197Ssam				struct sockaddr *paddr;
1546105197Ssam
1547105197Ssam				paddr = (struct sockaddr *)(xisr + 1);
1548105197Ssam
1549105197Ssam				/* validity check */
1550105197Ssam				if (paddr->sa_len
1551105197Ssam				    > sizeof((*p_isr)->saidx.src)) {
1552120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1553120585Ssam						"request address length.\n",
1554120585Ssam						__func__));
1555105197Ssam					KEY_FREESP(&newsp);
1556105197Ssam					*error = EINVAL;
1557105197Ssam					return NULL;
1558105197Ssam				}
1559105197Ssam				bcopy(paddr, &(*p_isr)->saidx.src,
1560105197Ssam					paddr->sa_len);
1561105197Ssam
1562105197Ssam				paddr = (struct sockaddr *)((caddr_t)paddr
1563105197Ssam							+ paddr->sa_len);
1564105197Ssam
1565105197Ssam				/* validity check */
1566105197Ssam				if (paddr->sa_len
1567105197Ssam				    > sizeof((*p_isr)->saidx.dst)) {
1568120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
1569120585Ssam						"request address length.\n",
1570120585Ssam						__func__));
1571105197Ssam					KEY_FREESP(&newsp);
1572105197Ssam					*error = EINVAL;
1573105197Ssam					return NULL;
1574105197Ssam				}
1575105197Ssam				bcopy(paddr, &(*p_isr)->saidx.dst,
1576105197Ssam					paddr->sa_len);
1577105197Ssam			}
1578105197Ssam
1579105197Ssam			(*p_isr)->sp = newsp;
1580105197Ssam
1581105197Ssam			/* initialization for the next. */
1582105197Ssam			p_isr = &(*p_isr)->next;
1583105197Ssam			tlen -= xisr->sadb_x_ipsecrequest_len;
1584105197Ssam
1585105197Ssam			/* validity check */
1586105197Ssam			if (tlen < 0) {
1587120585Ssam				ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1588120585Ssam					__func__));
1589105197Ssam				KEY_FREESP(&newsp);
1590105197Ssam				*error = EINVAL;
1591105197Ssam				return NULL;
1592105197Ssam			}
1593105197Ssam
1594105197Ssam			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1595105197Ssam			                 + xisr->sadb_x_ipsecrequest_len);
1596105197Ssam		}
1597105197Ssam	    }
1598105197Ssam		break;
1599105197Ssam	default:
1600120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1601105197Ssam		KEY_FREESP(&newsp);
1602105197Ssam		*error = EINVAL;
1603105197Ssam		return NULL;
1604105197Ssam	}
1605105197Ssam
1606105197Ssam	*error = 0;
1607105197Ssam	return newsp;
1608105197Ssam}
1609105197Ssam
1610105197Ssamstatic u_int32_t
1611105197Ssamkey_newreqid()
1612105197Ssam{
1613105197Ssam	static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1614105197Ssam
1615105197Ssam	auto_reqid = (auto_reqid == ~0
1616105197Ssam			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1617105197Ssam
1618105197Ssam	/* XXX should be unique check */
1619105197Ssam
1620105197Ssam	return auto_reqid;
1621105197Ssam}
1622105197Ssam
1623105197Ssam/*
1624105197Ssam * copy secpolicy struct to sadb_x_policy structure indicated.
1625105197Ssam */
1626105197Ssamstruct mbuf *
1627105197Ssamkey_sp2msg(sp)
1628105197Ssam	struct secpolicy *sp;
1629105197Ssam{
1630105197Ssam	struct sadb_x_policy *xpl;
1631105197Ssam	int tlen;
1632105197Ssam	caddr_t p;
1633105197Ssam	struct mbuf *m;
1634105197Ssam
1635120585Ssam	IPSEC_ASSERT(sp != NULL, ("null policy"));
1636105197Ssam
1637105197Ssam	tlen = key_getspreqmsglen(sp);
1638105197Ssam
1639105197Ssam	m = key_alloc_mbuf(tlen);
1640105197Ssam	if (!m || m->m_next) {	/*XXX*/
1641105197Ssam		if (m)
1642105197Ssam			m_freem(m);
1643105197Ssam		return NULL;
1644105197Ssam	}
1645105197Ssam
1646105197Ssam	m->m_len = tlen;
1647105197Ssam	m->m_next = NULL;
1648105197Ssam	xpl = mtod(m, struct sadb_x_policy *);
1649105197Ssam	bzero(xpl, tlen);
1650105197Ssam
1651105197Ssam	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1652105197Ssam	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1653105197Ssam	xpl->sadb_x_policy_type = sp->policy;
1654105197Ssam	xpl->sadb_x_policy_dir = sp->spidx.dir;
1655105197Ssam	xpl->sadb_x_policy_id = sp->id;
1656105197Ssam	p = (caddr_t)xpl + sizeof(*xpl);
1657105197Ssam
1658105197Ssam	/* if is the policy for ipsec ? */
1659105197Ssam	if (sp->policy == IPSEC_POLICY_IPSEC) {
1660105197Ssam		struct sadb_x_ipsecrequest *xisr;
1661105197Ssam		struct ipsecrequest *isr;
1662105197Ssam
1663105197Ssam		for (isr = sp->req; isr != NULL; isr = isr->next) {
1664105197Ssam
1665105197Ssam			xisr = (struct sadb_x_ipsecrequest *)p;
1666105197Ssam
1667105197Ssam			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1668105197Ssam			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1669105197Ssam			xisr->sadb_x_ipsecrequest_level = isr->level;
1670105197Ssam			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1671105197Ssam
1672105197Ssam			p += sizeof(*xisr);
1673105197Ssam			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1674105197Ssam			p += isr->saidx.src.sa.sa_len;
1675105197Ssam			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1676105197Ssam			p += isr->saidx.src.sa.sa_len;
1677105197Ssam
1678105197Ssam			xisr->sadb_x_ipsecrequest_len =
1679105197Ssam				PFKEY_ALIGN8(sizeof(*xisr)
1680105197Ssam					+ isr->saidx.src.sa.sa_len
1681105197Ssam					+ isr->saidx.dst.sa.sa_len);
1682105197Ssam		}
1683105197Ssam	}
1684105197Ssam
1685105197Ssam	return m;
1686105197Ssam}
1687105197Ssam
1688105197Ssam/* m will not be freed nor modified */
1689105197Ssamstatic struct mbuf *
1690105197Ssam#ifdef __STDC__
1691105197Ssamkey_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1692105197Ssam	int ndeep, int nitem, ...)
1693105197Ssam#else
1694105197Ssamkey_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1695105197Ssam	struct mbuf *m;
1696105197Ssam	const struct sadb_msghdr *mhp;
1697105197Ssam	int ndeep;
1698105197Ssam	int nitem;
1699105197Ssam	va_dcl
1700105197Ssam#endif
1701105197Ssam{
1702105197Ssam	va_list ap;
1703105197Ssam	int idx;
1704105197Ssam	int i;
1705105197Ssam	struct mbuf *result = NULL, *n;
1706105197Ssam	int len;
1707105197Ssam
1708120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1709120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1710105197Ssam
1711105197Ssam	va_start(ap, nitem);
1712105197Ssam	for (i = 0; i < nitem; i++) {
1713105197Ssam		idx = va_arg(ap, int);
1714105197Ssam		if (idx < 0 || idx > SADB_EXT_MAX)
1715105197Ssam			goto fail;
1716105197Ssam		/* don't attempt to pull empty extension */
1717105197Ssam		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1718105197Ssam			continue;
1719105197Ssam		if (idx != SADB_EXT_RESERVED  &&
1720105197Ssam		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1721105197Ssam			continue;
1722105197Ssam
1723105197Ssam		if (idx == SADB_EXT_RESERVED) {
1724105197Ssam			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1725120585Ssam
1726120585Ssam			IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1727120585Ssam
1728111119Simp			MGETHDR(n, M_DONTWAIT, MT_DATA);
1729105197Ssam			if (!n)
1730105197Ssam				goto fail;
1731105197Ssam			n->m_len = len;
1732105197Ssam			n->m_next = NULL;
1733105197Ssam			m_copydata(m, 0, sizeof(struct sadb_msg),
1734105197Ssam			    mtod(n, caddr_t));
1735105197Ssam		} else if (i < ndeep) {
1736105197Ssam			len = mhp->extlen[idx];
1737105197Ssam			n = key_alloc_mbuf(len);
1738105197Ssam			if (!n || n->m_next) {	/*XXX*/
1739105197Ssam				if (n)
1740105197Ssam					m_freem(n);
1741105197Ssam				goto fail;
1742105197Ssam			}
1743105197Ssam			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1744105197Ssam			    mtod(n, caddr_t));
1745105197Ssam		} else {
1746105197Ssam			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1747111119Simp			    M_DONTWAIT);
1748105197Ssam		}
1749105197Ssam		if (n == NULL)
1750105197Ssam			goto fail;
1751105197Ssam
1752105197Ssam		if (result)
1753105197Ssam			m_cat(result, n);
1754105197Ssam		else
1755105197Ssam			result = n;
1756105197Ssam	}
1757105197Ssam	va_end(ap);
1758105197Ssam
1759105197Ssam	if ((result->m_flags & M_PKTHDR) != 0) {
1760105197Ssam		result->m_pkthdr.len = 0;
1761105197Ssam		for (n = result; n; n = n->m_next)
1762105197Ssam			result->m_pkthdr.len += n->m_len;
1763105197Ssam	}
1764105197Ssam
1765105197Ssam	return result;
1766105197Ssam
1767105197Ssamfail:
1768105197Ssam	m_freem(result);
1769105197Ssam	return NULL;
1770105197Ssam}
1771105197Ssam
1772105197Ssam/*
1773105197Ssam * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1774108533Sschweikh * add an entry to SP database, when received
1775105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1776105197Ssam * from the user(?).
1777105197Ssam * Adding to SP database,
1778105197Ssam * and send
1779105197Ssam *   <base, address(SD), (lifetime(H),) policy>
1780105197Ssam * to the socket which was send.
1781105197Ssam *
1782105197Ssam * SPDADD set a unique policy entry.
1783105197Ssam * SPDSETIDX like SPDADD without a part of policy requests.
1784105197Ssam * SPDUPDATE replace a unique policy entry.
1785105197Ssam *
1786105197Ssam * m will always be freed.
1787105197Ssam */
1788105197Ssamstatic int
1789105197Ssamkey_spdadd(so, m, mhp)
1790105197Ssam	struct socket *so;
1791105197Ssam	struct mbuf *m;
1792105197Ssam	const struct sadb_msghdr *mhp;
1793105197Ssam{
1794105197Ssam	struct sadb_address *src0, *dst0;
1795105197Ssam	struct sadb_x_policy *xpl0, *xpl;
1796105197Ssam	struct sadb_lifetime *lft = NULL;
1797105197Ssam	struct secpolicyindex spidx;
1798105197Ssam	struct secpolicy *newsp;
1799105197Ssam	int error;
1800105197Ssam
1801120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
1802120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1803120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1804120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1805105197Ssam
1806105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1807105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1808105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1809105197Ssam		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1810105197Ssam		return key_senderror(so, m, EINVAL);
1811105197Ssam	}
1812105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1813105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1814105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1815120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1816120585Ssam			__func__));
1817105197Ssam		return key_senderror(so, m, EINVAL);
1818105197Ssam	}
1819105197Ssam	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1820105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1821105197Ssam			< sizeof(struct sadb_lifetime)) {
1822120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1823120585Ssam				__func__));
1824105197Ssam			return key_senderror(so, m, EINVAL);
1825105197Ssam		}
1826105197Ssam		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1827105197Ssam	}
1828105197Ssam
1829105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1830105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1831105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1832105197Ssam
1833194062Svanhu	/*
1834194062Svanhu	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
1835194062Svanhu	 * we are processing traffic endpoints.
1836194062Svanhu	 */
1837194062Svanhu
1838105197Ssam	/* make secindex */
1839105197Ssam	/* XXX boundary check against sa_len */
1840105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1841105197Ssam	                src0 + 1,
1842105197Ssam	                dst0 + 1,
1843105197Ssam	                src0->sadb_address_prefixlen,
1844105197Ssam	                dst0->sadb_address_prefixlen,
1845105197Ssam	                src0->sadb_address_proto,
1846105197Ssam	                &spidx);
1847105197Ssam
1848105197Ssam	/* checking the direciton. */
1849105197Ssam	switch (xpl0->sadb_x_policy_dir) {
1850105197Ssam	case IPSEC_DIR_INBOUND:
1851105197Ssam	case IPSEC_DIR_OUTBOUND:
1852105197Ssam		break;
1853105197Ssam	default:
1854120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1855105197Ssam		mhp->msg->sadb_msg_errno = EINVAL;
1856105197Ssam		return 0;
1857105197Ssam	}
1858105197Ssam
1859105197Ssam	/* check policy */
1860105197Ssam	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1861105197Ssam	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1862105197Ssam	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1863120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1864105197Ssam		return key_senderror(so, m, EINVAL);
1865105197Ssam	}
1866105197Ssam
1867105197Ssam	/* policy requests are mandatory when action is ipsec. */
1868105197Ssam        if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1869105197Ssam	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1870105197Ssam	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1871120585Ssam		ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1872120585Ssam			__func__));
1873105197Ssam		return key_senderror(so, m, EINVAL);
1874105197Ssam	}
1875105197Ssam
1876105197Ssam	/*
1877105197Ssam	 * checking there is SP already or not.
1878105197Ssam	 * SPDUPDATE doesn't depend on whether there is a SP or not.
1879105197Ssam	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1880105197Ssam	 * then error.
1881105197Ssam	 */
1882105197Ssam	newsp = key_getsp(&spidx);
1883105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1884105197Ssam		if (newsp) {
1885105197Ssam			newsp->state = IPSEC_SPSTATE_DEAD;
1886105197Ssam			KEY_FREESP(&newsp);
1887105197Ssam		}
1888105197Ssam	} else {
1889105197Ssam		if (newsp != NULL) {
1890105197Ssam			KEY_FREESP(&newsp);
1891120585Ssam			ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1892120585Ssam				__func__));
1893105197Ssam			return key_senderror(so, m, EEXIST);
1894105197Ssam		}
1895105197Ssam	}
1896105197Ssam
1897105197Ssam	/* allocation new SP entry */
1898105197Ssam	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1899105197Ssam		return key_senderror(so, m, error);
1900105197Ssam	}
1901105197Ssam
1902105197Ssam	if ((newsp->id = key_getnewspid()) == 0) {
1903119643Ssam		_key_delsp(newsp);
1904105197Ssam		return key_senderror(so, m, ENOBUFS);
1905105197Ssam	}
1906105197Ssam
1907105197Ssam	/* XXX boundary check against sa_len */
1908105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1909105197Ssam	                src0 + 1,
1910105197Ssam	                dst0 + 1,
1911105197Ssam	                src0->sadb_address_prefixlen,
1912105197Ssam	                dst0->sadb_address_prefixlen,
1913105197Ssam	                src0->sadb_address_proto,
1914105197Ssam	                &newsp->spidx);
1915105197Ssam
1916105197Ssam	/* sanity check on addr pair */
1917105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1918105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_family) {
1919119643Ssam		_key_delsp(newsp);
1920105197Ssam		return key_senderror(so, m, EINVAL);
1921105197Ssam	}
1922105197Ssam	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1923105197Ssam			((struct sockaddr *)(dst0+ 1))->sa_len) {
1924119643Ssam		_key_delsp(newsp);
1925105197Ssam		return key_senderror(so, m, EINVAL);
1926105197Ssam	}
1927105197Ssam#if 1
1928105197Ssam	if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
1929105197Ssam		struct sockaddr *sa;
1930105197Ssam		sa = (struct sockaddr *)(src0 + 1);
1931105197Ssam		if (sa->sa_family != newsp->req->saidx.src.sa.sa_family) {
1932119643Ssam			_key_delsp(newsp);
1933105197Ssam			return key_senderror(so, m, EINVAL);
1934105197Ssam		}
1935105197Ssam	}
1936105197Ssam	if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
1937105197Ssam		struct sockaddr *sa;
1938105197Ssam		sa = (struct sockaddr *)(dst0 + 1);
1939105197Ssam		if (sa->sa_family != newsp->req->saidx.dst.sa.sa_family) {
1940119643Ssam			_key_delsp(newsp);
1941105197Ssam			return key_senderror(so, m, EINVAL);
1942105197Ssam		}
1943105197Ssam	}
1944105197Ssam#endif
1945105197Ssam
1946105197Ssam	newsp->created = time_second;
1947105197Ssam	newsp->lastused = newsp->created;
1948105197Ssam	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1949105197Ssam	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1950105197Ssam
1951105197Ssam	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1952105197Ssam	newsp->state = IPSEC_SPSTATE_ALIVE;
1953181803Sbz	LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1954105197Ssam
1955105197Ssam	/* delete the entry in spacqtree */
1956105197Ssam	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1957119643Ssam		struct secspacq *spacq = key_getspacq(&spidx);
1958119643Ssam		if (spacq != NULL) {
1959105197Ssam			/* reset counter in order to deletion by timehandler. */
1960105197Ssam			spacq->created = time_second;
1961105197Ssam			spacq->count = 0;
1962120585Ssam			SPACQ_UNLOCK();
1963105197Ssam		}
1964105197Ssam    	}
1965105197Ssam
1966105197Ssam    {
1967105197Ssam	struct mbuf *n, *mpolicy;
1968105197Ssam	struct sadb_msg *newmsg;
1969105197Ssam	int off;
1970105197Ssam
1971194062Svanhu	/*
1972194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
1973194062Svanhu	 * we are sending traffic endpoints.
1974194062Svanhu	 */
1975194062Svanhu
1976105197Ssam	/* create new sadb_msg to reply. */
1977105197Ssam	if (lft) {
1978105197Ssam		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1979105197Ssam		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1980105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1981105197Ssam	} else {
1982105197Ssam		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1983105197Ssam		    SADB_X_EXT_POLICY,
1984105197Ssam		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1985105197Ssam	}
1986105197Ssam	if (!n)
1987105197Ssam		return key_senderror(so, m, ENOBUFS);
1988105197Ssam
1989105197Ssam	if (n->m_len < sizeof(*newmsg)) {
1990105197Ssam		n = m_pullup(n, sizeof(*newmsg));
1991105197Ssam		if (!n)
1992105197Ssam			return key_senderror(so, m, ENOBUFS);
1993105197Ssam	}
1994105197Ssam	newmsg = mtod(n, struct sadb_msg *);
1995105197Ssam	newmsg->sadb_msg_errno = 0;
1996105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1997105197Ssam
1998105197Ssam	off = 0;
1999105197Ssam	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
2000105197Ssam	    sizeof(*xpl), &off);
2001105197Ssam	if (mpolicy == NULL) {
2002105197Ssam		/* n is already freed */
2003105197Ssam		return key_senderror(so, m, ENOBUFS);
2004105197Ssam	}
2005105197Ssam	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
2006105197Ssam	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
2007105197Ssam		m_freem(n);
2008105197Ssam		return key_senderror(so, m, EINVAL);
2009105197Ssam	}
2010105197Ssam	xpl->sadb_x_policy_id = newsp->id;
2011105197Ssam
2012105197Ssam	m_freem(m);
2013105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2014105197Ssam    }
2015105197Ssam}
2016105197Ssam
2017105197Ssam/*
2018105197Ssam * get new policy id.
2019105197Ssam * OUT:
2020105197Ssam *	0:	failure.
2021105197Ssam *	others: success.
2022105197Ssam */
2023105197Ssamstatic u_int32_t
2024105197Ssamkey_getnewspid()
2025105197Ssam{
2026105197Ssam	u_int32_t newid = 0;
2027181803Sbz	int count = V_key_spi_trycnt;	/* XXX */
2028105197Ssam	struct secpolicy *sp;
2029105197Ssam
2030105197Ssam	/* when requesting to allocate spi ranged */
2031105197Ssam	while (count--) {
2032181803Sbz		newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
2033105197Ssam
2034105197Ssam		if ((sp = key_getspbyid(newid)) == NULL)
2035105197Ssam			break;
2036105197Ssam
2037105197Ssam		KEY_FREESP(&sp);
2038105197Ssam	}
2039105197Ssam
2040105197Ssam	if (count == 0 || newid == 0) {
2041120585Ssam		ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2042120585Ssam			__func__));
2043105197Ssam		return 0;
2044105197Ssam	}
2045105197Ssam
2046105197Ssam	return newid;
2047105197Ssam}
2048105197Ssam
2049105197Ssam/*
2050105197Ssam * SADB_SPDDELETE processing
2051105197Ssam * receive
2052105197Ssam *   <base, address(SD), policy(*)>
2053105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2054105197Ssam * and send,
2055105197Ssam *   <base, address(SD), policy(*)>
2056105197Ssam * to the ikmpd.
2057105197Ssam * policy(*) including direction of policy.
2058105197Ssam *
2059105197Ssam * m will always be freed.
2060105197Ssam */
2061105197Ssamstatic int
2062105197Ssamkey_spddelete(so, m, mhp)
2063105197Ssam	struct socket *so;
2064105197Ssam	struct mbuf *m;
2065105197Ssam	const struct sadb_msghdr *mhp;
2066105197Ssam{
2067105197Ssam	struct sadb_address *src0, *dst0;
2068105197Ssam	struct sadb_x_policy *xpl0;
2069105197Ssam	struct secpolicyindex spidx;
2070105197Ssam	struct secpolicy *sp;
2071105197Ssam
2072120585Ssam	IPSEC_ASSERT(so != NULL, ("null so"));
2073120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2074120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2075120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2076105197Ssam
2077105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2078105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2079105197Ssam	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2080120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2081120585Ssam			__func__));
2082105197Ssam		return key_senderror(so, m, EINVAL);
2083105197Ssam	}
2084105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2085105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2086105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2087120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2088120585Ssam			__func__));
2089105197Ssam		return key_senderror(so, m, EINVAL);
2090105197Ssam	}
2091105197Ssam
2092105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2093105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2094105197Ssam	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2095105197Ssam
2096194062Svanhu	/*
2097194062Svanhu	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
2098194062Svanhu	 * we are processing traffic endpoints.
2099194062Svanhu	 */
2100194062Svanhu
2101105197Ssam	/* make secindex */
2102105197Ssam	/* XXX boundary check against sa_len */
2103105197Ssam	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2104105197Ssam	                src0 + 1,
2105105197Ssam	                dst0 + 1,
2106105197Ssam	                src0->sadb_address_prefixlen,
2107105197Ssam	                dst0->sadb_address_prefixlen,
2108105197Ssam	                src0->sadb_address_proto,
2109105197Ssam	                &spidx);
2110105197Ssam
2111105197Ssam	/* checking the direciton. */
2112105197Ssam	switch (xpl0->sadb_x_policy_dir) {
2113105197Ssam	case IPSEC_DIR_INBOUND:
2114105197Ssam	case IPSEC_DIR_OUTBOUND:
2115105197Ssam		break;
2116105197Ssam	default:
2117120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2118105197Ssam		return key_senderror(so, m, EINVAL);
2119105197Ssam	}
2120105197Ssam
2121105197Ssam	/* Is there SP in SPD ? */
2122105197Ssam	if ((sp = key_getsp(&spidx)) == NULL) {
2123120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2124105197Ssam		return key_senderror(so, m, EINVAL);
2125105197Ssam	}
2126105197Ssam
2127105197Ssam	/* save policy id to buffer to be returned. */
2128105197Ssam	xpl0->sadb_x_policy_id = sp->id;
2129105197Ssam
2130105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2131105197Ssam	KEY_FREESP(&sp);
2132105197Ssam
2133105197Ssam    {
2134105197Ssam	struct mbuf *n;
2135105197Ssam	struct sadb_msg *newmsg;
2136105197Ssam
2137194062Svanhu	/*
2138194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2139194062Svanhu	 * we are sending traffic endpoints.
2140194062Svanhu	 */
2141194062Svanhu
2142105197Ssam	/* create new sadb_msg to reply. */
2143105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2144105197Ssam	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2145105197Ssam	if (!n)
2146105197Ssam		return key_senderror(so, m, ENOBUFS);
2147105197Ssam
2148105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2149105197Ssam	newmsg->sadb_msg_errno = 0;
2150105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2151105197Ssam
2152105197Ssam	m_freem(m);
2153105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2154105197Ssam    }
2155105197Ssam}
2156105197Ssam
2157105197Ssam/*
2158105197Ssam * SADB_SPDDELETE2 processing
2159105197Ssam * receive
2160105197Ssam *   <base, policy(*)>
2161105197Ssam * from the user(?), and set SADB_SASTATE_DEAD,
2162105197Ssam * and send,
2163105197Ssam *   <base, policy(*)>
2164105197Ssam * to the ikmpd.
2165105197Ssam * policy(*) including direction of policy.
2166105197Ssam *
2167105197Ssam * m will always be freed.
2168105197Ssam */
2169105197Ssamstatic int
2170105197Ssamkey_spddelete2(so, m, mhp)
2171105197Ssam	struct socket *so;
2172105197Ssam	struct mbuf *m;
2173105197Ssam	const struct sadb_msghdr *mhp;
2174105197Ssam{
2175105197Ssam	u_int32_t id;
2176105197Ssam	struct secpolicy *sp;
2177105197Ssam
2178120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2179120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2180120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2181120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2182105197Ssam
2183105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2184105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2185120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2186170803Sbz		return key_senderror(so, m, EINVAL);
2187105197Ssam	}
2188105197Ssam
2189105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2190105197Ssam
2191105197Ssam	/* Is there SP in SPD ? */
2192105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2193120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2194170803Sbz		return key_senderror(so, m, EINVAL);
2195105197Ssam	}
2196105197Ssam
2197105197Ssam	sp->state = IPSEC_SPSTATE_DEAD;
2198105197Ssam	KEY_FREESP(&sp);
2199105197Ssam
2200105197Ssam    {
2201105197Ssam	struct mbuf *n, *nn;
2202105197Ssam	struct sadb_msg *newmsg;
2203105197Ssam	int off, len;
2204105197Ssam
2205105197Ssam	/* create new sadb_msg to reply. */
2206105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2207105197Ssam
2208111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
2209105197Ssam	if (n && len > MHLEN) {
2210111119Simp		MCLGET(n, M_DONTWAIT);
2211105197Ssam		if ((n->m_flags & M_EXT) == 0) {
2212105197Ssam			m_freem(n);
2213105197Ssam			n = NULL;
2214105197Ssam		}
2215105197Ssam	}
2216105197Ssam	if (!n)
2217105197Ssam		return key_senderror(so, m, ENOBUFS);
2218105197Ssam
2219105197Ssam	n->m_len = len;
2220105197Ssam	n->m_next = NULL;
2221105197Ssam	off = 0;
2222105197Ssam
2223105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2224105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2225105197Ssam
2226120585Ssam	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2227120585Ssam		off, len));
2228105197Ssam
2229105197Ssam	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2230111119Simp	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2231105197Ssam	if (!n->m_next) {
2232105197Ssam		m_freem(n);
2233105197Ssam		return key_senderror(so, m, ENOBUFS);
2234105197Ssam	}
2235105197Ssam
2236105197Ssam	n->m_pkthdr.len = 0;
2237105197Ssam	for (nn = n; nn; nn = nn->m_next)
2238105197Ssam		n->m_pkthdr.len += nn->m_len;
2239105197Ssam
2240105197Ssam	newmsg = mtod(n, struct sadb_msg *);
2241105197Ssam	newmsg->sadb_msg_errno = 0;
2242105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2243105197Ssam
2244105197Ssam	m_freem(m);
2245105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2246105197Ssam    }
2247105197Ssam}
2248105197Ssam
2249105197Ssam/*
2250105197Ssam * SADB_X_GET processing
2251105197Ssam * receive
2252105197Ssam *   <base, policy(*)>
2253105197Ssam * from the user(?),
2254105197Ssam * and send,
2255105197Ssam *   <base, address(SD), policy>
2256105197Ssam * to the ikmpd.
2257105197Ssam * policy(*) including direction of policy.
2258105197Ssam *
2259105197Ssam * m will always be freed.
2260105197Ssam */
2261105197Ssamstatic int
2262105197Ssamkey_spdget(so, m, mhp)
2263105197Ssam	struct socket *so;
2264105197Ssam	struct mbuf *m;
2265105197Ssam	const struct sadb_msghdr *mhp;
2266105197Ssam{
2267105197Ssam	u_int32_t id;
2268105197Ssam	struct secpolicy *sp;
2269105197Ssam	struct mbuf *n;
2270105197Ssam
2271120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2272120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2273120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2274120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2275105197Ssam
2276105197Ssam	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2277105197Ssam	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2278120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2279120585Ssam			__func__));
2280105197Ssam		return key_senderror(so, m, EINVAL);
2281105197Ssam	}
2282105197Ssam
2283105197Ssam	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2284105197Ssam
2285105197Ssam	/* Is there SP in SPD ? */
2286105197Ssam	if ((sp = key_getspbyid(id)) == NULL) {
2287120585Ssam		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2288105197Ssam		return key_senderror(so, m, ENOENT);
2289105197Ssam	}
2290105197Ssam
2291105197Ssam	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2292105197Ssam	if (n != NULL) {
2293105197Ssam		m_freem(m);
2294105197Ssam		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2295105197Ssam	} else
2296105197Ssam		return key_senderror(so, m, ENOBUFS);
2297105197Ssam}
2298105197Ssam
2299105197Ssam/*
2300105197Ssam * SADB_X_SPDACQUIRE processing.
2301105197Ssam * Acquire policy and SA(s) for a *OUTBOUND* packet.
2302105197Ssam * send
2303105197Ssam *   <base, policy(*)>
2304105197Ssam * to KMD, and expect to receive
2305105197Ssam *   <base> with SADB_X_SPDACQUIRE if error occured,
2306105197Ssam * or
2307105197Ssam *   <base, policy>
2308105197Ssam * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2309105197Ssam * policy(*) is without policy requests.
2310105197Ssam *
2311105197Ssam *    0     : succeed
2312105197Ssam *    others: error number
2313105197Ssam */
2314105197Ssamint
2315105197Ssamkey_spdacquire(sp)
2316105197Ssam	struct secpolicy *sp;
2317105197Ssam{
2318105197Ssam	struct mbuf *result = NULL, *m;
2319105197Ssam	struct secspacq *newspacq;
2320105197Ssam
2321120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2322120585Ssam	IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2323120585Ssam	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2324120585Ssam		("policy not IPSEC %u", sp->policy));
2325105197Ssam
2326108533Sschweikh	/* Get an entry to check whether sent message or not. */
2327119643Ssam	newspacq = key_getspacq(&sp->spidx);
2328119643Ssam	if (newspacq != NULL) {
2329181803Sbz		if (V_key_blockacq_count < newspacq->count) {
2330105197Ssam			/* reset counter and do send message. */
2331105197Ssam			newspacq->count = 0;
2332105197Ssam		} else {
2333105197Ssam			/* increment counter and do nothing. */
2334105197Ssam			newspacq->count++;
2335105197Ssam			return 0;
2336105197Ssam		}
2337120585Ssam		SPACQ_UNLOCK();
2338105197Ssam	} else {
2339105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
2340119643Ssam		newspacq = key_newspacq(&sp->spidx);
2341119643Ssam		if (newspacq == NULL)
2342105197Ssam			return ENOBUFS;
2343105197Ssam	}
2344105197Ssam
2345105197Ssam	/* create new sadb_msg to reply. */
2346105197Ssam	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2347170805Sbz	if (!m)
2348170805Sbz		return ENOBUFS;
2349170805Sbz
2350105197Ssam	result = m;
2351105197Ssam
2352105197Ssam	result->m_pkthdr.len = 0;
2353105197Ssam	for (m = result; m; m = m->m_next)
2354105197Ssam		result->m_pkthdr.len += m->m_len;
2355105197Ssam
2356105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2357105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2358105197Ssam
2359105197Ssam	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2360105197Ssam}
2361105197Ssam
2362105197Ssam/*
2363105197Ssam * SADB_SPDFLUSH processing
2364105197Ssam * receive
2365105197Ssam *   <base>
2366105197Ssam * from the user, and free all entries in secpctree.
2367105197Ssam * and send,
2368105197Ssam *   <base>
2369105197Ssam * to the user.
2370105197Ssam * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2371105197Ssam *
2372105197Ssam * m will always be freed.
2373105197Ssam */
2374105197Ssamstatic int
2375105197Ssamkey_spdflush(so, m, mhp)
2376105197Ssam	struct socket *so;
2377105197Ssam	struct mbuf *m;
2378105197Ssam	const struct sadb_msghdr *mhp;
2379105197Ssam{
2380105197Ssam	struct sadb_msg *newmsg;
2381105197Ssam	struct secpolicy *sp;
2382105197Ssam	u_int dir;
2383105197Ssam
2384120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2385120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2386120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2387120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2388105197Ssam
2389105197Ssam	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2390105197Ssam		return key_senderror(so, m, EINVAL);
2391105197Ssam
2392105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2393120585Ssam		SPTREE_LOCK();
2394181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain)
2395105197Ssam			sp->state = IPSEC_SPSTATE_DEAD;
2396120585Ssam		SPTREE_UNLOCK();
2397105197Ssam	}
2398105197Ssam
2399105197Ssam	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2400120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2401105197Ssam		return key_senderror(so, m, ENOBUFS);
2402105197Ssam	}
2403105197Ssam
2404105197Ssam	if (m->m_next)
2405105197Ssam		m_freem(m->m_next);
2406105197Ssam	m->m_next = NULL;
2407105197Ssam	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2408105197Ssam	newmsg = mtod(m, struct sadb_msg *);
2409105197Ssam	newmsg->sadb_msg_errno = 0;
2410105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2411105197Ssam
2412105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2413105197Ssam}
2414105197Ssam
2415105197Ssam/*
2416105197Ssam * SADB_SPDDUMP processing
2417105197Ssam * receive
2418105197Ssam *   <base>
2419105197Ssam * from the user, and dump all SP leaves
2420105197Ssam * and send,
2421105197Ssam *   <base> .....
2422105197Ssam * to the ikmpd.
2423105197Ssam *
2424105197Ssam * m will always be freed.
2425105197Ssam */
2426105197Ssamstatic int
2427105197Ssamkey_spddump(so, m, mhp)
2428105197Ssam	struct socket *so;
2429105197Ssam	struct mbuf *m;
2430105197Ssam	const struct sadb_msghdr *mhp;
2431105197Ssam{
2432105197Ssam	struct secpolicy *sp;
2433105197Ssam	int cnt;
2434105197Ssam	u_int dir;
2435105197Ssam	struct mbuf *n;
2436105197Ssam
2437120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
2438120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2439120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2440120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2441105197Ssam
2442105197Ssam	/* search SPD entry and get buffer size. */
2443105197Ssam	cnt = 0;
2444192882Svanhu	SPTREE_LOCK();
2445105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2446181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2447105197Ssam			cnt++;
2448105197Ssam		}
2449105197Ssam	}
2450105197Ssam
2451192882Svanhu	if (cnt == 0) {
2452192882Svanhu		SPTREE_UNLOCK();
2453105197Ssam		return key_senderror(so, m, ENOENT);
2454192882Svanhu	}
2455105197Ssam
2456105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2457181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2458105197Ssam			--cnt;
2459105197Ssam			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2460105197Ssam			    mhp->msg->sadb_msg_pid);
2461105197Ssam
2462105197Ssam			if (n)
2463105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2464105197Ssam		}
2465105197Ssam	}
2466105197Ssam
2467192882Svanhu	SPTREE_UNLOCK();
2468105197Ssam	m_freem(m);
2469105197Ssam	return 0;
2470105197Ssam}
2471105197Ssam
2472105197Ssamstatic struct mbuf *
2473189004Srdivackykey_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid)
2474105197Ssam{
2475105197Ssam	struct mbuf *result = NULL, *m;
2476181330Svanhu	struct seclifetime lt;
2477105197Ssam
2478105197Ssam	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2479105197Ssam	if (!m)
2480105197Ssam		goto fail;
2481105197Ssam	result = m;
2482105197Ssam
2483194062Svanhu	/*
2484194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2485194062Svanhu	 * we are sending traffic endpoints.
2486194062Svanhu	 */
2487105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2488105197Ssam	    &sp->spidx.src.sa, sp->spidx.prefs,
2489105197Ssam	    sp->spidx.ul_proto);
2490105197Ssam	if (!m)
2491105197Ssam		goto fail;
2492105197Ssam	m_cat(result, m);
2493105197Ssam
2494105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2495105197Ssam	    &sp->spidx.dst.sa, sp->spidx.prefd,
2496105197Ssam	    sp->spidx.ul_proto);
2497105197Ssam	if (!m)
2498105197Ssam		goto fail;
2499105197Ssam	m_cat(result, m);
2500105197Ssam
2501105197Ssam	m = key_sp2msg(sp);
2502105197Ssam	if (!m)
2503105197Ssam		goto fail;
2504105197Ssam	m_cat(result, m);
2505105197Ssam
2506181330Svanhu	if(sp->lifetime){
2507181330Svanhu		lt.addtime=sp->created;
2508181330Svanhu		lt.usetime= sp->lastused;
2509181330Svanhu		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_CURRENT);
2510181330Svanhu		if (!m)
2511181330Svanhu			goto fail;
2512181330Svanhu		m_cat(result, m);
2513181330Svanhu
2514181330Svanhu		lt.addtime=sp->lifetime;
2515181330Svanhu		lt.usetime= sp->validtime;
2516181330Svanhu		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_HARD);
2517181330Svanhu		if (!m)
2518181330Svanhu			goto fail;
2519181330Svanhu		m_cat(result, m);
2520181330Svanhu	}
2521181330Svanhu
2522105197Ssam	if ((result->m_flags & M_PKTHDR) == 0)
2523105197Ssam		goto fail;
2524105197Ssam
2525105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2526105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2527105197Ssam		if (result == NULL)
2528105197Ssam			goto fail;
2529105197Ssam	}
2530105197Ssam
2531105197Ssam	result->m_pkthdr.len = 0;
2532105197Ssam	for (m = result; m; m = m->m_next)
2533105197Ssam		result->m_pkthdr.len += m->m_len;
2534105197Ssam
2535105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2536105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2537105197Ssam
2538105197Ssam	return result;
2539105197Ssam
2540105197Ssamfail:
2541105197Ssam	m_freem(result);
2542105197Ssam	return NULL;
2543105197Ssam}
2544105197Ssam
2545105197Ssam/*
2546105197Ssam * get PFKEY message length for security policy and request.
2547105197Ssam */
2548105197Ssamstatic u_int
2549105197Ssamkey_getspreqmsglen(sp)
2550105197Ssam	struct secpolicy *sp;
2551105197Ssam{
2552105197Ssam	u_int tlen;
2553105197Ssam
2554105197Ssam	tlen = sizeof(struct sadb_x_policy);
2555105197Ssam
2556105197Ssam	/* if is the policy for ipsec ? */
2557105197Ssam	if (sp->policy != IPSEC_POLICY_IPSEC)
2558105197Ssam		return tlen;
2559105197Ssam
2560105197Ssam	/* get length of ipsec requests */
2561105197Ssam    {
2562105197Ssam	struct ipsecrequest *isr;
2563105197Ssam	int len;
2564105197Ssam
2565105197Ssam	for (isr = sp->req; isr != NULL; isr = isr->next) {
2566105197Ssam		len = sizeof(struct sadb_x_ipsecrequest)
2567105197Ssam			+ isr->saidx.src.sa.sa_len
2568105197Ssam			+ isr->saidx.dst.sa.sa_len;
2569105197Ssam
2570105197Ssam		tlen += PFKEY_ALIGN8(len);
2571105197Ssam	}
2572105197Ssam    }
2573105197Ssam
2574105197Ssam	return tlen;
2575105197Ssam}
2576105197Ssam
2577105197Ssam/*
2578105197Ssam * SADB_SPDEXPIRE processing
2579105197Ssam * send
2580105197Ssam *   <base, address(SD), lifetime(CH), policy>
2581105197Ssam * to KMD by PF_KEY.
2582105197Ssam *
2583105197Ssam * OUT:	0	: succeed
2584105197Ssam *	others	: error number
2585105197Ssam */
2586105197Ssamstatic int
2587105197Ssamkey_spdexpire(sp)
2588105197Ssam	struct secpolicy *sp;
2589105197Ssam{
2590105197Ssam	struct mbuf *result = NULL, *m;
2591105197Ssam	int len;
2592105197Ssam	int error = -1;
2593105197Ssam	struct sadb_lifetime *lt;
2594105197Ssam
2595105197Ssam	/* XXX: Why do we lock ? */
2596105197Ssam
2597120585Ssam	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2598105197Ssam
2599105197Ssam	/* set msg header */
2600105197Ssam	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2601105197Ssam	if (!m) {
2602105197Ssam		error = ENOBUFS;
2603105197Ssam		goto fail;
2604105197Ssam	}
2605105197Ssam	result = m;
2606105197Ssam
2607105197Ssam	/* create lifetime extension (current and hard) */
2608105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2609105197Ssam	m = key_alloc_mbuf(len);
2610105197Ssam	if (!m || m->m_next) {	/*XXX*/
2611105197Ssam		if (m)
2612105197Ssam			m_freem(m);
2613105197Ssam		error = ENOBUFS;
2614105197Ssam		goto fail;
2615105197Ssam	}
2616105197Ssam	bzero(mtod(m, caddr_t), len);
2617105197Ssam	lt = mtod(m, struct sadb_lifetime *);
2618105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2619105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2620105197Ssam	lt->sadb_lifetime_allocations = 0;
2621105197Ssam	lt->sadb_lifetime_bytes = 0;
2622105197Ssam	lt->sadb_lifetime_addtime = sp->created;
2623105197Ssam	lt->sadb_lifetime_usetime = sp->lastused;
2624105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2625105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2626105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2627105197Ssam	lt->sadb_lifetime_allocations = 0;
2628105197Ssam	lt->sadb_lifetime_bytes = 0;
2629105197Ssam	lt->sadb_lifetime_addtime = sp->lifetime;
2630105197Ssam	lt->sadb_lifetime_usetime = sp->validtime;
2631105197Ssam	m_cat(result, m);
2632105197Ssam
2633194062Svanhu	/*
2634194062Svanhu	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2635194062Svanhu	 * we are sending traffic endpoints.
2636194062Svanhu	 */
2637194062Svanhu
2638105197Ssam	/* set sadb_address for source */
2639105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2640105197Ssam	    &sp->spidx.src.sa,
2641105197Ssam	    sp->spidx.prefs, sp->spidx.ul_proto);
2642105197Ssam	if (!m) {
2643105197Ssam		error = ENOBUFS;
2644105197Ssam		goto fail;
2645105197Ssam	}
2646105197Ssam	m_cat(result, m);
2647105197Ssam
2648105197Ssam	/* set sadb_address for destination */
2649105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2650105197Ssam	    &sp->spidx.dst.sa,
2651105197Ssam	    sp->spidx.prefd, sp->spidx.ul_proto);
2652105197Ssam	if (!m) {
2653105197Ssam		error = ENOBUFS;
2654105197Ssam		goto fail;
2655105197Ssam	}
2656105197Ssam	m_cat(result, m);
2657105197Ssam
2658105197Ssam	/* set secpolicy */
2659105197Ssam	m = key_sp2msg(sp);
2660105197Ssam	if (!m) {
2661105197Ssam		error = ENOBUFS;
2662105197Ssam		goto fail;
2663105197Ssam	}
2664105197Ssam	m_cat(result, m);
2665105197Ssam
2666105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
2667105197Ssam		error = EINVAL;
2668105197Ssam		goto fail;
2669105197Ssam	}
2670105197Ssam
2671105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
2672105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
2673105197Ssam		if (result == NULL) {
2674105197Ssam			error = ENOBUFS;
2675105197Ssam			goto fail;
2676105197Ssam		}
2677105197Ssam	}
2678105197Ssam
2679105197Ssam	result->m_pkthdr.len = 0;
2680105197Ssam	for (m = result; m; m = m->m_next)
2681105197Ssam		result->m_pkthdr.len += m->m_len;
2682105197Ssam
2683105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
2684105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
2685105197Ssam
2686105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2687105197Ssam
2688105197Ssam fail:
2689105197Ssam	if (result)
2690105197Ssam		m_freem(result);
2691105197Ssam	return error;
2692105197Ssam}
2693105197Ssam
2694105197Ssam/* %%% SAD management */
2695105197Ssam/*
2696105197Ssam * allocating a memory for new SA head, and copy from the values of mhp.
2697105197Ssam * OUT:	NULL	: failure due to the lack of memory.
2698105197Ssam *	others	: pointer to new SA head.
2699105197Ssam */
2700105197Ssamstatic struct secashead *
2701105197Ssamkey_newsah(saidx)
2702105197Ssam	struct secasindex *saidx;
2703105197Ssam{
2704105197Ssam	struct secashead *newsah;
2705105197Ssam
2706120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2707105197Ssam
2708119643Ssam	newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2709105197Ssam	if (newsah != NULL) {
2710105197Ssam		int i;
2711105197Ssam		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2712105197Ssam			LIST_INIT(&newsah->savtree[i]);
2713105197Ssam		newsah->saidx = *saidx;
2714105197Ssam
2715105197Ssam		/* add to saidxtree */
2716105197Ssam		newsah->state = SADB_SASTATE_MATURE;
2717119643Ssam
2718120585Ssam		SAHTREE_LOCK();
2719181803Sbz		LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2720120585Ssam		SAHTREE_UNLOCK();
2721105197Ssam	}
2722105197Ssam	return(newsah);
2723105197Ssam}
2724105197Ssam
2725105197Ssam/*
2726105197Ssam * delete SA index and all SA registerd.
2727105197Ssam */
2728105197Ssamstatic void
2729105197Ssamkey_delsah(sah)
2730105197Ssam	struct secashead *sah;
2731105197Ssam{
2732105197Ssam	struct secasvar *sav, *nextsav;
2733120585Ssam	u_int stateidx;
2734105197Ssam	int zombie = 0;
2735105197Ssam
2736120585Ssam	IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2737120585Ssam	SAHTREE_LOCK_ASSERT();
2738105197Ssam
2739105197Ssam	/* searching all SA registerd in the secindex. */
2740105197Ssam	for (stateidx = 0;
2741185348Szec	     stateidx < _ARRAYLEN(saorder_state_any);
2742105197Ssam	     stateidx++) {
2743185348Szec		u_int state = saorder_state_any[stateidx];
2744120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2745105197Ssam			if (sav->refcnt == 0) {
2746105197Ssam				/* sanity check */
2747120585Ssam				KEY_CHKSASTATE(state, sav->state, __func__);
2748190071Svanhu				/*
2749190071Svanhu				 * do NOT call KEY_FREESAV here:
2750190071Svanhu				 * it will only delete the sav if refcnt == 1,
2751189962Svanhu				 * where we already know that refcnt == 0
2752189962Svanhu				 */
2753189962Svanhu				key_delsav(sav);
2754105197Ssam			} else {
2755105197Ssam				/* give up to delete this sa */
2756105197Ssam				zombie++;
2757105197Ssam			}
2758105197Ssam		}
2759105197Ssam	}
2760120585Ssam	if (!zombie) {		/* delete only if there are savs */
2761120585Ssam		/* remove from tree of SA index */
2762120585Ssam		if (__LIST_CHAINED(sah))
2763120585Ssam			LIST_REMOVE(sah, chain);
2764120585Ssam		if (sah->sa_route.ro_rt) {
2765120585Ssam			RTFREE(sah->sa_route.ro_rt);
2766120585Ssam			sah->sa_route.ro_rt = (struct rtentry *)NULL;
2767120585Ssam		}
2768120585Ssam		free(sah, M_IPSEC_SAH);
2769105197Ssam	}
2770105197Ssam}
2771105197Ssam
2772105197Ssam/*
2773105197Ssam * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2774105197Ssam * and copy the values of mhp into new buffer.
2775105197Ssam * When SAD message type is GETSPI:
2776105197Ssam *	to set sequence number from acq_seq++,
2777105197Ssam *	to set zero to SPI.
2778105197Ssam *	not to call key_setsava().
2779105197Ssam * OUT:	NULL	: fail
2780105197Ssam *	others	: pointer to new secasvar.
2781105197Ssam *
2782105197Ssam * does not modify mbuf.  does not free mbuf on error.
2783105197Ssam */
2784105197Ssamstatic struct secasvar *
2785105197Ssamkey_newsav(m, mhp, sah, errp, where, tag)
2786105197Ssam	struct mbuf *m;
2787105197Ssam	const struct sadb_msghdr *mhp;
2788105197Ssam	struct secashead *sah;
2789105197Ssam	int *errp;
2790105197Ssam	const char* where;
2791105197Ssam	int tag;
2792105197Ssam{
2793105197Ssam	struct secasvar *newsav;
2794105197Ssam	const struct sadb_sa *xsa;
2795105197Ssam
2796120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2797120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2798120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2799120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
2800105197Ssam
2801119643Ssam	newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2802105197Ssam	if (newsav == NULL) {
2803120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2804105197Ssam		*errp = ENOBUFS;
2805105197Ssam		goto done;
2806105197Ssam	}
2807105197Ssam
2808105197Ssam	switch (mhp->msg->sadb_msg_type) {
2809105197Ssam	case SADB_GETSPI:
2810105197Ssam		newsav->spi = 0;
2811105197Ssam
2812105197Ssam#ifdef IPSEC_DOSEQCHECK
2813105197Ssam		/* sync sequence number */
2814105197Ssam		if (mhp->msg->sadb_msg_seq == 0)
2815105197Ssam			newsav->seq =
2816181803Sbz				(V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2817105197Ssam		else
2818105197Ssam#endif
2819105197Ssam			newsav->seq = mhp->msg->sadb_msg_seq;
2820105197Ssam		break;
2821105197Ssam
2822105197Ssam	case SADB_ADD:
2823105197Ssam		/* sanity check */
2824105197Ssam		if (mhp->ext[SADB_EXT_SA] == NULL) {
2825119643Ssam			free(newsav, M_IPSEC_SA);
2826119643Ssam			newsav = NULL;
2827120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2828120585Ssam				__func__));
2829105197Ssam			*errp = EINVAL;
2830105197Ssam			goto done;
2831105197Ssam		}
2832105197Ssam		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2833105197Ssam		newsav->spi = xsa->sadb_sa_spi;
2834105197Ssam		newsav->seq = mhp->msg->sadb_msg_seq;
2835105197Ssam		break;
2836105197Ssam	default:
2837119643Ssam		free(newsav, M_IPSEC_SA);
2838119643Ssam		newsav = NULL;
2839105197Ssam		*errp = EINVAL;
2840105197Ssam		goto done;
2841105197Ssam	}
2842105197Ssam
2843119643Ssam
2844105197Ssam	/* copy sav values */
2845105197Ssam	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2846105197Ssam		*errp = key_setsaval(newsav, m, mhp);
2847105197Ssam		if (*errp) {
2848119643Ssam			free(newsav, M_IPSEC_SA);
2849119643Ssam			newsav = NULL;
2850105197Ssam			goto done;
2851105197Ssam		}
2852105197Ssam	}
2853105197Ssam
2854120585Ssam	SECASVAR_LOCK_INIT(newsav);
2855119643Ssam
2856105197Ssam	/* reset created */
2857105197Ssam	newsav->created = time_second;
2858105197Ssam	newsav->pid = mhp->msg->sadb_msg_pid;
2859105197Ssam
2860105197Ssam	/* add to satree */
2861105197Ssam	newsav->sah = sah;
2862158767Spjd	sa_initref(newsav);
2863105197Ssam	newsav->state = SADB_SASTATE_LARVAL;
2864119643Ssam
2865119643Ssam	/* XXX locking??? */
2866105197Ssam	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2867105197Ssam			secasvar, chain);
2868105197Ssamdone:
2869105197Ssam	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2870120585Ssam		printf("DP %s from %s:%u return SP:%p\n", __func__,
2871105197Ssam			where, tag, newsav));
2872105197Ssam
2873105197Ssam	return newsav;
2874105197Ssam}
2875105197Ssam
2876105197Ssam/*
2877105197Ssam * free() SA variable entry.
2878105197Ssam */
2879105197Ssamstatic void
2880119643Ssamkey_cleansav(struct secasvar *sav)
2881105197Ssam{
2882117051Ssam	/*
2883117051Ssam	 * Cleanup xform state.  Note that zeroize'ing causes the
2884117051Ssam	 * keys to be cleared; otherwise we must do it ourself.
2885117051Ssam	 */
2886117051Ssam	if (sav->tdb_xform != NULL) {
2887117051Ssam		sav->tdb_xform->xf_zeroize(sav);
2888117051Ssam		sav->tdb_xform = NULL;
2889117051Ssam	} else {
2890120585Ssam		KASSERT(sav->iv == NULL, ("iv but no xform"));
2891117051Ssam		if (sav->key_auth != NULL)
2892157123Sgnn			bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2893117051Ssam		if (sav->key_enc != NULL)
2894157123Sgnn			bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2895117051Ssam	}
2896105197Ssam	if (sav->key_auth != NULL) {
2897157123Sgnn		if (sav->key_auth->key_data != NULL)
2898157123Sgnn			free(sav->key_auth->key_data, M_IPSEC_MISC);
2899119643Ssam		free(sav->key_auth, M_IPSEC_MISC);
2900105197Ssam		sav->key_auth = NULL;
2901105197Ssam	}
2902105197Ssam	if (sav->key_enc != NULL) {
2903157123Sgnn		if (sav->key_enc->key_data != NULL)
2904157123Sgnn			free(sav->key_enc->key_data, M_IPSEC_MISC);
2905119643Ssam		free(sav->key_enc, M_IPSEC_MISC);
2906105197Ssam		sav->key_enc = NULL;
2907105197Ssam	}
2908105197Ssam	if (sav->sched) {
2909105197Ssam		bzero(sav->sched, sav->schedlen);
2910119643Ssam		free(sav->sched, M_IPSEC_MISC);
2911105197Ssam		sav->sched = NULL;
2912105197Ssam	}
2913105197Ssam	if (sav->replay != NULL) {
2914119643Ssam		free(sav->replay, M_IPSEC_MISC);
2915105197Ssam		sav->replay = NULL;
2916105197Ssam	}
2917105197Ssam	if (sav->lft_c != NULL) {
2918119643Ssam		free(sav->lft_c, M_IPSEC_MISC);
2919105197Ssam		sav->lft_c = NULL;
2920105197Ssam	}
2921105197Ssam	if (sav->lft_h != NULL) {
2922119643Ssam		free(sav->lft_h, M_IPSEC_MISC);
2923105197Ssam		sav->lft_h = NULL;
2924105197Ssam	}
2925105197Ssam	if (sav->lft_s != NULL) {
2926119643Ssam		free(sav->lft_s, M_IPSEC_MISC);
2927105197Ssam		sav->lft_s = NULL;
2928105197Ssam	}
2929119643Ssam}
2930105197Ssam
2931119643Ssam/*
2932119643Ssam * free() SA variable entry.
2933119643Ssam */
2934119643Ssamstatic void
2935119643Ssamkey_delsav(sav)
2936119643Ssam	struct secasvar *sav;
2937119643Ssam{
2938120585Ssam	IPSEC_ASSERT(sav != NULL, ("null sav"));
2939120585Ssam	IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2940105197Ssam
2941119643Ssam	/* remove from SA header */
2942119643Ssam	if (__LIST_CHAINED(sav))
2943119643Ssam		LIST_REMOVE(sav, chain);
2944119643Ssam	key_cleansav(sav);
2945120585Ssam	SECASVAR_LOCK_DESTROY(sav);
2946119643Ssam	free(sav, M_IPSEC_SA);
2947105197Ssam}
2948105197Ssam
2949105197Ssam/*
2950105197Ssam * search SAD.
2951105197Ssam * OUT:
2952105197Ssam *	NULL	: not found
2953105197Ssam *	others	: found, pointer to a SA.
2954105197Ssam */
2955105197Ssamstatic struct secashead *
2956105197Ssamkey_getsah(saidx)
2957105197Ssam	struct secasindex *saidx;
2958105197Ssam{
2959105197Ssam	struct secashead *sah;
2960105197Ssam
2961120585Ssam	SAHTREE_LOCK();
2962181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
2963105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
2964105197Ssam			continue;
2965105197Ssam		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2966119643Ssam			break;
2967105197Ssam	}
2968120585Ssam	SAHTREE_UNLOCK();
2969105197Ssam
2970119643Ssam	return sah;
2971105197Ssam}
2972105197Ssam
2973105197Ssam/*
2974105197Ssam * check not to be duplicated SPI.
2975105197Ssam * NOTE: this function is too slow due to searching all SAD.
2976105197Ssam * OUT:
2977105197Ssam *	NULL	: not found
2978105197Ssam *	others	: found, pointer to a SA.
2979105197Ssam */
2980105197Ssamstatic struct secasvar *
2981105197Ssamkey_checkspidup(saidx, spi)
2982105197Ssam	struct secasindex *saidx;
2983105197Ssam	u_int32_t spi;
2984105197Ssam{
2985105197Ssam	struct secashead *sah;
2986105197Ssam	struct secasvar *sav;
2987105197Ssam
2988105197Ssam	/* check address family */
2989105197Ssam	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2990120585Ssam		ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2991120585Ssam			__func__));
2992105197Ssam		return NULL;
2993105197Ssam	}
2994105197Ssam
2995119643Ssam	sav = NULL;
2996105197Ssam	/* check all SAD */
2997120585Ssam	SAHTREE_LOCK();
2998181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
2999105197Ssam		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
3000105197Ssam			continue;
3001105197Ssam		sav = key_getsavbyspi(sah, spi);
3002105197Ssam		if (sav != NULL)
3003119643Ssam			break;
3004105197Ssam	}
3005120585Ssam	SAHTREE_UNLOCK();
3006105197Ssam
3007119643Ssam	return sav;
3008105197Ssam}
3009105197Ssam
3010105197Ssam/*
3011105197Ssam * search SAD litmited alive SA, protocol, SPI.
3012105197Ssam * OUT:
3013105197Ssam *	NULL	: not found
3014105197Ssam *	others	: found, pointer to a SA.
3015105197Ssam */
3016105197Ssamstatic struct secasvar *
3017105197Ssamkey_getsavbyspi(sah, spi)
3018105197Ssam	struct secashead *sah;
3019105197Ssam	u_int32_t spi;
3020105197Ssam{
3021105197Ssam	struct secasvar *sav;
3022105197Ssam	u_int stateidx, state;
3023105197Ssam
3024119643Ssam	sav = NULL;
3025120585Ssam	SAHTREE_LOCK_ASSERT();
3026105197Ssam	/* search all status */
3027105197Ssam	for (stateidx = 0;
3028185348Szec	     stateidx < _ARRAYLEN(saorder_state_alive);
3029105197Ssam	     stateidx++) {
3030105197Ssam
3031185348Szec		state = saorder_state_alive[stateidx];
3032105197Ssam		LIST_FOREACH(sav, &sah->savtree[state], chain) {
3033105197Ssam
3034105197Ssam			/* sanity check */
3035105197Ssam			if (sav->state != state) {
3036120585Ssam				ipseclog((LOG_DEBUG, "%s: "
3037105197Ssam				    "invalid sav->state (queue: %d SA: %d)\n",
3038120585Ssam				    __func__, state, sav->state));
3039105197Ssam				continue;
3040105197Ssam			}
3041105197Ssam
3042105197Ssam			if (sav->spi == spi)
3043128859Ssam				return sav;
3044105197Ssam		}
3045105197Ssam	}
3046105197Ssam
3047128859Ssam	return NULL;
3048105197Ssam}
3049105197Ssam
3050105197Ssam/*
3051105197Ssam * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3052105197Ssam * You must update these if need.
3053105197Ssam * OUT:	0:	success.
3054105197Ssam *	!0:	failure.
3055105197Ssam *
3056105197Ssam * does not modify mbuf.  does not free mbuf on error.
3057105197Ssam */
3058105197Ssamstatic int
3059105197Ssamkey_setsaval(sav, m, mhp)
3060105197Ssam	struct secasvar *sav;
3061105197Ssam	struct mbuf *m;
3062105197Ssam	const struct sadb_msghdr *mhp;
3063105197Ssam{
3064105197Ssam	int error = 0;
3065105197Ssam
3066120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
3067120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3068120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3069105197Ssam
3070105197Ssam	/* initialization */
3071105197Ssam	sav->replay = NULL;
3072105197Ssam	sav->key_auth = NULL;
3073105197Ssam	sav->key_enc = NULL;
3074105197Ssam	sav->sched = NULL;
3075105197Ssam	sav->schedlen = 0;
3076105197Ssam	sav->iv = NULL;
3077105197Ssam	sav->lft_c = NULL;
3078105197Ssam	sav->lft_h = NULL;
3079105197Ssam	sav->lft_s = NULL;
3080105197Ssam	sav->tdb_xform = NULL;		/* transform */
3081105197Ssam	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
3082105197Ssam	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
3083105197Ssam	sav->tdb_compalgxform = NULL;	/* compression algorithm */
3084194062Svanhu	/*  Initialize even if NAT-T not compiled in: */
3085194062Svanhu	sav->natt_type = 0;
3086194062Svanhu	sav->natt_esp_frag_len = 0;
3087105197Ssam
3088105197Ssam	/* SA */
3089105197Ssam	if (mhp->ext[SADB_EXT_SA] != NULL) {
3090105197Ssam		const struct sadb_sa *sa0;
3091105197Ssam
3092105197Ssam		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3093105197Ssam		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3094105197Ssam			error = EINVAL;
3095105197Ssam			goto fail;
3096105197Ssam		}
3097105197Ssam
3098105197Ssam		sav->alg_auth = sa0->sadb_sa_auth;
3099105197Ssam		sav->alg_enc = sa0->sadb_sa_encrypt;
3100105197Ssam		sav->flags = sa0->sadb_sa_flags;
3101105197Ssam
3102105197Ssam		/* replay window */
3103105197Ssam		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3104105197Ssam			sav->replay = (struct secreplay *)
3105119643Ssam				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3106105197Ssam			if (sav->replay == NULL) {
3107120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3108120585Ssam					__func__));
3109105197Ssam				error = ENOBUFS;
3110105197Ssam				goto fail;
3111105197Ssam			}
3112105197Ssam			if (sa0->sadb_sa_replay != 0)
3113105197Ssam				sav->replay->bitmap = (caddr_t)(sav->replay+1);
3114105197Ssam			sav->replay->wsize = sa0->sadb_sa_replay;
3115105197Ssam		}
3116105197Ssam	}
3117105197Ssam
3118105197Ssam	/* Authentication keys */
3119105197Ssam	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3120105197Ssam		const struct sadb_key *key0;
3121105197Ssam		int len;
3122105197Ssam
3123105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3124105197Ssam		len = mhp->extlen[SADB_EXT_KEY_AUTH];
3125105197Ssam
3126105197Ssam		error = 0;
3127105197Ssam		if (len < sizeof(*key0)) {
3128105197Ssam			error = EINVAL;
3129105197Ssam			goto fail;
3130105197Ssam		}
3131105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3132105197Ssam		case SADB_SATYPE_AH:
3133105197Ssam		case SADB_SATYPE_ESP:
3134125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3135105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3136105197Ssam			    sav->alg_auth != SADB_X_AALG_NULL)
3137105197Ssam				error = EINVAL;
3138105197Ssam			break;
3139105197Ssam		case SADB_X_SATYPE_IPCOMP:
3140105197Ssam		default:
3141105197Ssam			error = EINVAL;
3142105197Ssam			break;
3143105197Ssam		}
3144105197Ssam		if (error) {
3145120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3146120585Ssam				__func__));
3147105197Ssam			goto fail;
3148105197Ssam		}
3149105197Ssam
3150157123Sgnn		sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3151157123Sgnn								M_IPSEC_MISC);
3152157123Sgnn		if (sav->key_auth == NULL ) {
3153157123Sgnn			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3154157123Sgnn				  __func__));
3155105197Ssam			error = ENOBUFS;
3156105197Ssam			goto fail;
3157105197Ssam		}
3158105197Ssam	}
3159105197Ssam
3160105197Ssam	/* Encryption key */
3161105197Ssam	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3162105197Ssam		const struct sadb_key *key0;
3163105197Ssam		int len;
3164105197Ssam
3165105197Ssam		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3166105197Ssam		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3167105197Ssam
3168105197Ssam		error = 0;
3169105197Ssam		if (len < sizeof(*key0)) {
3170105197Ssam			error = EINVAL;
3171105197Ssam			goto fail;
3172105197Ssam		}
3173105197Ssam		switch (mhp->msg->sadb_msg_satype) {
3174105197Ssam		case SADB_SATYPE_ESP:
3175105197Ssam			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3176105197Ssam			    sav->alg_enc != SADB_EALG_NULL) {
3177105197Ssam				error = EINVAL;
3178105197Ssam				break;
3179105197Ssam			}
3180157123Sgnn			sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3181157123Sgnn								       len,
3182157123Sgnn								       M_IPSEC_MISC);
3183105197Ssam			if (sav->key_enc == NULL) {
3184120585Ssam				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3185120585Ssam					__func__));
3186105197Ssam				error = ENOBUFS;
3187105197Ssam				goto fail;
3188105197Ssam			}
3189105197Ssam			break;
3190105197Ssam		case SADB_X_SATYPE_IPCOMP:
3191105197Ssam			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3192105197Ssam				error = EINVAL;
3193105197Ssam			sav->key_enc = NULL;	/*just in case*/
3194105197Ssam			break;
3195105197Ssam		case SADB_SATYPE_AH:
3196125680Sbms		case SADB_X_SATYPE_TCPSIGNATURE:
3197105197Ssam		default:
3198105197Ssam			error = EINVAL;
3199105197Ssam			break;
3200105197Ssam		}
3201105197Ssam		if (error) {
3202120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3203120585Ssam				__func__));
3204105197Ssam			goto fail;
3205105197Ssam		}
3206105197Ssam	}
3207105197Ssam
3208105197Ssam	/* set iv */
3209105197Ssam	sav->ivlen = 0;
3210105197Ssam
3211105197Ssam	switch (mhp->msg->sadb_msg_satype) {
3212105197Ssam	case SADB_SATYPE_AH:
3213105197Ssam		error = xform_init(sav, XF_AH);
3214105197Ssam		break;
3215105197Ssam	case SADB_SATYPE_ESP:
3216105197Ssam		error = xform_init(sav, XF_ESP);
3217105197Ssam		break;
3218105197Ssam	case SADB_X_SATYPE_IPCOMP:
3219105197Ssam		error = xform_init(sav, XF_IPCOMP);
3220105197Ssam		break;
3221125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
3222125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3223125680Sbms		break;
3224105197Ssam	}
3225105197Ssam	if (error) {
3226120585Ssam		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3227120585Ssam		        __func__, mhp->msg->sadb_msg_satype));
3228105197Ssam		goto fail;
3229105197Ssam	}
3230105197Ssam
3231105197Ssam	/* reset created */
3232105197Ssam	sav->created = time_second;
3233105197Ssam
3234105197Ssam	/* make lifetime for CURRENT */
3235176743Sbz	sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3236105197Ssam	if (sav->lft_c == NULL) {
3237120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3238105197Ssam		error = ENOBUFS;
3239105197Ssam		goto fail;
3240105197Ssam	}
3241105197Ssam
3242157123Sgnn	sav->lft_c->allocations = 0;
3243157123Sgnn	sav->lft_c->bytes = 0;
3244157123Sgnn	sav->lft_c->addtime = time_second;
3245157123Sgnn	sav->lft_c->usetime = 0;
3246105197Ssam
3247105197Ssam	/* lifetimes for HARD and SOFT */
3248105197Ssam    {
3249105197Ssam	const struct sadb_lifetime *lft0;
3250105197Ssam
3251105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3252105197Ssam	if (lft0 != NULL) {
3253105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3254105197Ssam			error = EINVAL;
3255105197Ssam			goto fail;
3256105197Ssam		}
3257157123Sgnn		sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3258105197Ssam		if (sav->lft_h == NULL) {
3259120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3260105197Ssam			error = ENOBUFS;
3261105197Ssam			goto fail;
3262105197Ssam		}
3263105197Ssam		/* to be initialize ? */
3264105197Ssam	}
3265105197Ssam
3266105197Ssam	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3267105197Ssam	if (lft0 != NULL) {
3268105197Ssam		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3269105197Ssam			error = EINVAL;
3270105197Ssam			goto fail;
3271105197Ssam		}
3272157123Sgnn		sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3273105197Ssam		if (sav->lft_s == NULL) {
3274120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3275105197Ssam			error = ENOBUFS;
3276105197Ssam			goto fail;
3277105197Ssam		}
3278105197Ssam		/* to be initialize ? */
3279105197Ssam	}
3280105197Ssam    }
3281105197Ssam
3282105197Ssam	return 0;
3283105197Ssam
3284105197Ssam fail:
3285105197Ssam	/* initialization */
3286119643Ssam	key_cleansav(sav);
3287105197Ssam
3288105197Ssam	return error;
3289105197Ssam}
3290105197Ssam
3291105197Ssam/*
3292105197Ssam * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3293105197Ssam * OUT:	0:	valid
3294105197Ssam *	other:	errno
3295105197Ssam */
3296105197Ssamstatic int
3297119643Ssamkey_mature(struct secasvar *sav)
3298105197Ssam{
3299105197Ssam	int error;
3300105197Ssam
3301105197Ssam	/* check SPI value */
3302105197Ssam	switch (sav->sah->saidx.proto) {
3303105197Ssam	case IPPROTO_ESP:
3304105197Ssam	case IPPROTO_AH:
3305170823Sbz		/*
3306170823Sbz		 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3307170823Sbz		 * 1-255 reserved by IANA for future use,
3308170823Sbz		 * 0 for implementation specific, local use.
3309170823Sbz		 */
3310170823Sbz		if (ntohl(sav->spi) <= 255) {
3311120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3312120585Ssam			    __func__, (u_int32_t)ntohl(sav->spi)));
3313105197Ssam			return EINVAL;
3314105197Ssam		}
3315105197Ssam		break;
3316105197Ssam	}
3317105197Ssam
3318105197Ssam	/* check satype */
3319105197Ssam	switch (sav->sah->saidx.proto) {
3320105197Ssam	case IPPROTO_ESP:
3321105197Ssam		/* check flags */
3322105197Ssam		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3323105197Ssam		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3324120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3325120585Ssam				"given to old-esp.\n", __func__));
3326105197Ssam			return EINVAL;
3327105197Ssam		}
3328105197Ssam		error = xform_init(sav, XF_ESP);
3329105197Ssam		break;
3330105197Ssam	case IPPROTO_AH:
3331105197Ssam		/* check flags */
3332105197Ssam		if (sav->flags & SADB_X_EXT_DERIV) {
3333120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3334120585Ssam				"given to AH SA.\n", __func__));
3335105197Ssam			return EINVAL;
3336105197Ssam		}
3337105197Ssam		if (sav->alg_enc != SADB_EALG_NONE) {
3338120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3339120585Ssam				"mismated.\n", __func__));
3340105197Ssam			return(EINVAL);
3341105197Ssam		}
3342105197Ssam		error = xform_init(sav, XF_AH);
3343105197Ssam		break;
3344105197Ssam	case IPPROTO_IPCOMP:
3345105197Ssam		if (sav->alg_auth != SADB_AALG_NONE) {
3346120585Ssam			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3347120585Ssam				"mismated.\n", __func__));
3348105197Ssam			return(EINVAL);
3349105197Ssam		}
3350105197Ssam		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3351105197Ssam		 && ntohl(sav->spi) >= 0x10000) {
3352120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3353120585Ssam				__func__));
3354105197Ssam			return(EINVAL);
3355105197Ssam		}
3356105197Ssam		error = xform_init(sav, XF_IPCOMP);
3357105197Ssam		break;
3358125680Sbms	case IPPROTO_TCP:
3359125680Sbms		if (sav->alg_enc != SADB_EALG_NONE) {
3360125680Sbms			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3361125680Sbms				"mismated.\n", __func__));
3362125680Sbms			return(EINVAL);
3363125680Sbms		}
3364125680Sbms		error = xform_init(sav, XF_TCPSIGNATURE);
3365125680Sbms		break;
3366105197Ssam	default:
3367120585Ssam		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3368105197Ssam		error = EPROTONOSUPPORT;
3369105197Ssam		break;
3370105197Ssam	}
3371119643Ssam	if (error == 0) {
3372120585Ssam		SAHTREE_LOCK();
3373105197Ssam		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3374120585Ssam		SAHTREE_UNLOCK();
3375119643Ssam	}
3376105197Ssam	return (error);
3377105197Ssam}
3378105197Ssam
3379105197Ssam/*
3380105197Ssam * subroutine for SADB_GET and SADB_DUMP.
3381105197Ssam */
3382105197Ssamstatic struct mbuf *
3383189004Srdivackykey_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3384189004Srdivacky    u_int32_t seq, u_int32_t pid)
3385105197Ssam{
3386105197Ssam	struct mbuf *result = NULL, *tres = NULL, *m;
3387105197Ssam	int i;
3388105197Ssam	int dumporder[] = {
3389105197Ssam		SADB_EXT_SA, SADB_X_EXT_SA2,
3390105197Ssam		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3391105197Ssam		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3392105197Ssam		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3393105197Ssam		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3394105197Ssam		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3395194062Svanhu#ifdef IPSEC_NAT_T
3396194062Svanhu		SADB_X_EXT_NAT_T_TYPE,
3397194062Svanhu		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3398194062Svanhu		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3399194062Svanhu		SADB_X_EXT_NAT_T_FRAG,
3400194062Svanhu#endif
3401105197Ssam	};
3402105197Ssam
3403105197Ssam	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3404105197Ssam	if (m == NULL)
3405105197Ssam		goto fail;
3406105197Ssam	result = m;
3407105197Ssam
3408105197Ssam	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3409105197Ssam		m = NULL;
3410105197Ssam		switch (dumporder[i]) {
3411105197Ssam		case SADB_EXT_SA:
3412105197Ssam			m = key_setsadbsa(sav);
3413105197Ssam			if (!m)
3414105197Ssam				goto fail;
3415105197Ssam			break;
3416105197Ssam
3417105197Ssam		case SADB_X_EXT_SA2:
3418105197Ssam			m = key_setsadbxsa2(sav->sah->saidx.mode,
3419105197Ssam					sav->replay ? sav->replay->count : 0,
3420105197Ssam					sav->sah->saidx.reqid);
3421105197Ssam			if (!m)
3422105197Ssam				goto fail;
3423105197Ssam			break;
3424105197Ssam
3425105197Ssam		case SADB_EXT_ADDRESS_SRC:
3426105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3427105197Ssam			    &sav->sah->saidx.src.sa,
3428105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3429105197Ssam			if (!m)
3430105197Ssam				goto fail;
3431105197Ssam			break;
3432105197Ssam
3433105197Ssam		case SADB_EXT_ADDRESS_DST:
3434105197Ssam			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3435105197Ssam			    &sav->sah->saidx.dst.sa,
3436105197Ssam			    FULLMASK, IPSEC_ULPROTO_ANY);
3437105197Ssam			if (!m)
3438105197Ssam				goto fail;
3439105197Ssam			break;
3440105197Ssam
3441105197Ssam		case SADB_EXT_KEY_AUTH:
3442105197Ssam			if (!sav->key_auth)
3443105197Ssam				continue;
3444157123Sgnn			m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3445157123Sgnn			if (!m)
3446157123Sgnn				goto fail;
3447105197Ssam			break;
3448105197Ssam
3449105197Ssam		case SADB_EXT_KEY_ENCRYPT:
3450105197Ssam			if (!sav->key_enc)
3451105197Ssam				continue;
3452157123Sgnn			m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3453157123Sgnn			if (!m)
3454157123Sgnn				goto fail;
3455105197Ssam			break;
3456105197Ssam
3457105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
3458105197Ssam			if (!sav->lft_c)
3459105197Ssam				continue;
3460157123Sgnn			m = key_setlifetime(sav->lft_c,
3461157123Sgnn					    SADB_EXT_LIFETIME_CURRENT);
3462157123Sgnn			if (!m)
3463157123Sgnn				goto fail;
3464105197Ssam			break;
3465105197Ssam
3466105197Ssam		case SADB_EXT_LIFETIME_HARD:
3467105197Ssam			if (!sav->lft_h)
3468105197Ssam				continue;
3469157123Sgnn			m = key_setlifetime(sav->lft_h,
3470157123Sgnn					    SADB_EXT_LIFETIME_HARD);
3471157123Sgnn			if (!m)
3472157123Sgnn				goto fail;
3473105197Ssam			break;
3474105197Ssam
3475105197Ssam		case SADB_EXT_LIFETIME_SOFT:
3476105197Ssam			if (!sav->lft_s)
3477105197Ssam				continue;
3478177554Sbz			m = key_setlifetime(sav->lft_s,
3479157123Sgnn					    SADB_EXT_LIFETIME_SOFT);
3480157123Sgnn
3481157123Sgnn			if (!m)
3482157123Sgnn				goto fail;
3483105197Ssam			break;
3484105197Ssam
3485194062Svanhu#ifdef IPSEC_NAT_T
3486194062Svanhu		case SADB_X_EXT_NAT_T_TYPE:
3487194062Svanhu			m = key_setsadbxtype(sav->natt_type);
3488194062Svanhu			if (!m)
3489194062Svanhu				goto fail;
3490194062Svanhu			break;
3491194062Svanhu
3492194062Svanhu		case SADB_X_EXT_NAT_T_DPORT:
3493194062Svanhu			m = key_setsadbxport(
3494194062Svanhu			    KEY_PORTFROMSADDR(&sav->sah->saidx.dst),
3495194062Svanhu			    SADB_X_EXT_NAT_T_DPORT);
3496194062Svanhu			if (!m)
3497194062Svanhu				goto fail;
3498194062Svanhu			break;
3499194062Svanhu
3500194062Svanhu		case SADB_X_EXT_NAT_T_SPORT:
3501194062Svanhu			m = key_setsadbxport(
3502194062Svanhu			    KEY_PORTFROMSADDR(&sav->sah->saidx.src),
3503194062Svanhu			    SADB_X_EXT_NAT_T_SPORT);
3504194062Svanhu			if (!m)
3505194062Svanhu				goto fail;
3506194062Svanhu			break;
3507194062Svanhu
3508194062Svanhu		case SADB_X_EXT_NAT_T_OAI:
3509194062Svanhu		case SADB_X_EXT_NAT_T_OAR:
3510194062Svanhu		case SADB_X_EXT_NAT_T_FRAG:
3511194062Svanhu			/* We do not (yet) support those. */
3512194062Svanhu			continue;
3513194062Svanhu#endif
3514194062Svanhu
3515105197Ssam		case SADB_EXT_ADDRESS_PROXY:
3516105197Ssam		case SADB_EXT_IDENTITY_SRC:
3517105197Ssam		case SADB_EXT_IDENTITY_DST:
3518105197Ssam			/* XXX: should we brought from SPD ? */
3519105197Ssam		case SADB_EXT_SENSITIVITY:
3520105197Ssam		default:
3521105197Ssam			continue;
3522105197Ssam		}
3523105197Ssam
3524157123Sgnn		if (!m)
3525105197Ssam			goto fail;
3526105197Ssam		if (tres)
3527105197Ssam			m_cat(m, tres);
3528105197Ssam		tres = m;
3529157123Sgnn
3530105197Ssam	}
3531105197Ssam
3532105197Ssam	m_cat(result, tres);
3533105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
3534105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
3535105197Ssam		if (result == NULL)
3536105197Ssam			goto fail;
3537105197Ssam	}
3538105197Ssam
3539105197Ssam	result->m_pkthdr.len = 0;
3540105197Ssam	for (m = result; m; m = m->m_next)
3541105197Ssam		result->m_pkthdr.len += m->m_len;
3542105197Ssam
3543105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
3544105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
3545105197Ssam
3546105197Ssam	return result;
3547105197Ssam
3548105197Ssamfail:
3549105197Ssam	m_freem(result);
3550105197Ssam	m_freem(tres);
3551105197Ssam	return NULL;
3552105197Ssam}
3553105197Ssam
3554105197Ssam/*
3555105197Ssam * set data into sadb_msg.
3556105197Ssam */
3557105197Ssamstatic struct mbuf *
3558189004Srdivackykey_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3559189004Srdivacky    pid_t pid, u_int16_t reserved)
3560105197Ssam{
3561105197Ssam	struct mbuf *m;
3562105197Ssam	struct sadb_msg *p;
3563105197Ssam	int len;
3564105197Ssam
3565105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3566105197Ssam	if (len > MCLBYTES)
3567105197Ssam		return NULL;
3568111119Simp	MGETHDR(m, M_DONTWAIT, MT_DATA);
3569105197Ssam	if (m && len > MHLEN) {
3570111119Simp		MCLGET(m, M_DONTWAIT);
3571105197Ssam		if ((m->m_flags & M_EXT) == 0) {
3572105197Ssam			m_freem(m);
3573105197Ssam			m = NULL;
3574105197Ssam		}
3575105197Ssam	}
3576105197Ssam	if (!m)
3577105197Ssam		return NULL;
3578105197Ssam	m->m_pkthdr.len = m->m_len = len;
3579105197Ssam	m->m_next = NULL;
3580105197Ssam
3581105197Ssam	p = mtod(m, struct sadb_msg *);
3582105197Ssam
3583105197Ssam	bzero(p, len);
3584105197Ssam	p->sadb_msg_version = PF_KEY_V2;
3585105197Ssam	p->sadb_msg_type = type;
3586105197Ssam	p->sadb_msg_errno = 0;
3587105197Ssam	p->sadb_msg_satype = satype;
3588105197Ssam	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3589105197Ssam	p->sadb_msg_reserved = reserved;
3590105197Ssam	p->sadb_msg_seq = seq;
3591105197Ssam	p->sadb_msg_pid = (u_int32_t)pid;
3592105197Ssam
3593105197Ssam	return m;
3594105197Ssam}
3595105197Ssam
3596105197Ssam/*
3597105197Ssam * copy secasvar data into sadb_address.
3598105197Ssam */
3599105197Ssamstatic struct mbuf *
3600105197Ssamkey_setsadbsa(sav)
3601105197Ssam	struct secasvar *sav;
3602105197Ssam{
3603105197Ssam	struct mbuf *m;
3604105197Ssam	struct sadb_sa *p;
3605105197Ssam	int len;
3606105197Ssam
3607105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3608105197Ssam	m = key_alloc_mbuf(len);
3609105197Ssam	if (!m || m->m_next) {	/*XXX*/
3610105197Ssam		if (m)
3611105197Ssam			m_freem(m);
3612105197Ssam		return NULL;
3613105197Ssam	}
3614105197Ssam
3615105197Ssam	p = mtod(m, struct sadb_sa *);
3616105197Ssam
3617105197Ssam	bzero(p, len);
3618105197Ssam	p->sadb_sa_len = PFKEY_UNIT64(len);
3619105197Ssam	p->sadb_sa_exttype = SADB_EXT_SA;
3620105197Ssam	p->sadb_sa_spi = sav->spi;
3621105197Ssam	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3622105197Ssam	p->sadb_sa_state = sav->state;
3623105197Ssam	p->sadb_sa_auth = sav->alg_auth;
3624105197Ssam	p->sadb_sa_encrypt = sav->alg_enc;
3625105197Ssam	p->sadb_sa_flags = sav->flags;
3626105197Ssam
3627105197Ssam	return m;
3628105197Ssam}
3629105197Ssam
3630105197Ssam/*
3631105197Ssam * set data into sadb_address.
3632105197Ssam */
3633105197Ssamstatic struct mbuf *
3634189004Srdivackykey_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto)
3635105197Ssam{
3636105197Ssam	struct mbuf *m;
3637105197Ssam	struct sadb_address *p;
3638105197Ssam	size_t len;
3639105197Ssam
3640105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3641105197Ssam	    PFKEY_ALIGN8(saddr->sa_len);
3642105197Ssam	m = key_alloc_mbuf(len);
3643105197Ssam	if (!m || m->m_next) {	/*XXX*/
3644105197Ssam		if (m)
3645105197Ssam			m_freem(m);
3646105197Ssam		return NULL;
3647105197Ssam	}
3648105197Ssam
3649105197Ssam	p = mtod(m, struct sadb_address *);
3650105197Ssam
3651105197Ssam	bzero(p, len);
3652105197Ssam	p->sadb_address_len = PFKEY_UNIT64(len);
3653105197Ssam	p->sadb_address_exttype = exttype;
3654105197Ssam	p->sadb_address_proto = ul_proto;
3655105197Ssam	if (prefixlen == FULLMASK) {
3656105197Ssam		switch (saddr->sa_family) {
3657105197Ssam		case AF_INET:
3658105197Ssam			prefixlen = sizeof(struct in_addr) << 3;
3659105197Ssam			break;
3660105197Ssam		case AF_INET6:
3661105197Ssam			prefixlen = sizeof(struct in6_addr) << 3;
3662105197Ssam			break;
3663105197Ssam		default:
3664105197Ssam			; /*XXX*/
3665105197Ssam		}
3666105197Ssam	}
3667105197Ssam	p->sadb_address_prefixlen = prefixlen;
3668105197Ssam	p->sadb_address_reserved = 0;
3669105197Ssam
3670105197Ssam	bcopy(saddr,
3671105197Ssam	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3672105197Ssam	    saddr->sa_len);
3673105197Ssam
3674105197Ssam	return m;
3675105197Ssam}
3676105197Ssam
3677105197Ssam/*
3678105197Ssam * set data into sadb_x_sa2.
3679105197Ssam */
3680105197Ssamstatic struct mbuf *
3681189004Srdivackykey_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3682105197Ssam{
3683105197Ssam	struct mbuf *m;
3684105197Ssam	struct sadb_x_sa2 *p;
3685105197Ssam	size_t len;
3686105197Ssam
3687105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3688105197Ssam	m = key_alloc_mbuf(len);
3689105197Ssam	if (!m || m->m_next) {	/*XXX*/
3690105197Ssam		if (m)
3691105197Ssam			m_freem(m);
3692105197Ssam		return NULL;
3693105197Ssam	}
3694105197Ssam
3695105197Ssam	p = mtod(m, struct sadb_x_sa2 *);
3696105197Ssam
3697105197Ssam	bzero(p, len);
3698105197Ssam	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3699105197Ssam	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3700105197Ssam	p->sadb_x_sa2_mode = mode;
3701105197Ssam	p->sadb_x_sa2_reserved1 = 0;
3702105197Ssam	p->sadb_x_sa2_reserved2 = 0;
3703105197Ssam	p->sadb_x_sa2_sequence = seq;
3704105197Ssam	p->sadb_x_sa2_reqid = reqid;
3705105197Ssam
3706105197Ssam	return m;
3707105197Ssam}
3708105197Ssam
3709194062Svanhu#ifdef IPSEC_NAT_T
3710105197Ssam/*
3711194062Svanhu * Set a type in sadb_x_nat_t_type.
3712194062Svanhu */
3713194062Svanhustatic struct mbuf *
3714194062Svanhukey_setsadbxtype(u_int16_t type)
3715194062Svanhu{
3716194062Svanhu	struct mbuf *m;
3717194062Svanhu	size_t len;
3718194062Svanhu	struct sadb_x_nat_t_type *p;
3719194062Svanhu
3720194062Svanhu	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3721194062Svanhu
3722194062Svanhu	m = key_alloc_mbuf(len);
3723194062Svanhu	if (!m || m->m_next) {	/*XXX*/
3724194062Svanhu		if (m)
3725194062Svanhu			m_freem(m);
3726194062Svanhu		return (NULL);
3727194062Svanhu	}
3728194062Svanhu
3729194062Svanhu	p = mtod(m, struct sadb_x_nat_t_type *);
3730194062Svanhu
3731194062Svanhu	bzero(p, len);
3732194062Svanhu	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3733194062Svanhu	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3734194062Svanhu	p->sadb_x_nat_t_type_type = type;
3735194062Svanhu
3736194062Svanhu	return (m);
3737194062Svanhu}
3738194062Svanhu/*
3739194062Svanhu * Set a port in sadb_x_nat_t_port.
3740194062Svanhu * In contrast to default RFC 2367 behaviour, port is in network byte order.
3741194062Svanhu */
3742194062Svanhustatic struct mbuf *
3743194062Svanhukey_setsadbxport(u_int16_t port, u_int16_t type)
3744194062Svanhu{
3745194062Svanhu	struct mbuf *m;
3746194062Svanhu	size_t len;
3747194062Svanhu	struct sadb_x_nat_t_port *p;
3748194062Svanhu
3749194062Svanhu	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3750194062Svanhu
3751194062Svanhu	m = key_alloc_mbuf(len);
3752194062Svanhu	if (!m || m->m_next) {	/*XXX*/
3753194062Svanhu		if (m)
3754194062Svanhu			m_freem(m);
3755194062Svanhu		return (NULL);
3756194062Svanhu	}
3757194062Svanhu
3758194062Svanhu	p = mtod(m, struct sadb_x_nat_t_port *);
3759194062Svanhu
3760194062Svanhu	bzero(p, len);
3761194062Svanhu	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3762194062Svanhu	p->sadb_x_nat_t_port_exttype = type;
3763194062Svanhu	p->sadb_x_nat_t_port_port = port;
3764194062Svanhu
3765194062Svanhu	return (m);
3766194062Svanhu}
3767194062Svanhu
3768194062Svanhu/*
3769194062Svanhu * Get port from sockaddr. Port is in network byte order.
3770194062Svanhu */
3771194062Svanhuu_int16_t
3772194062Svanhukey_portfromsaddr(struct sockaddr *sa)
3773194062Svanhu{
3774194062Svanhu
3775194062Svanhu	switch (sa->sa_family) {
3776194062Svanhu#ifdef INET
3777194062Svanhu	case AF_INET:
3778194062Svanhu		return ((struct sockaddr_in *)sa)->sin_port;
3779194062Svanhu#endif
3780194062Svanhu#ifdef INET6
3781194062Svanhu	case AF_INET6:
3782194062Svanhu		return ((struct sockaddr_in6 *)sa)->sin6_port;
3783194062Svanhu#endif
3784194062Svanhu	}
3785194062Svanhu	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
3786194062Svanhu		printf("DP %s unexpected address family %d\n",
3787194062Svanhu			__func__, sa->sa_family));
3788194062Svanhu	return (0);
3789194062Svanhu}
3790194062Svanhu#endif /* IPSEC_NAT_T */
3791194062Svanhu
3792194062Svanhu/*
3793194062Svanhu * Set port in struct sockaddr. Port is in network byte order.
3794194062Svanhu */
3795194062Svanhustatic void
3796194062Svanhukey_porttosaddr(struct sockaddr *sa, u_int16_t port)
3797194062Svanhu{
3798194062Svanhu
3799194062Svanhu	switch (sa->sa_family) {
3800194062Svanhu#ifdef INET
3801194062Svanhu	case AF_INET:
3802194062Svanhu		((struct sockaddr_in *)sa)->sin_port = port;
3803194062Svanhu		break;
3804194062Svanhu#endif
3805194062Svanhu#ifdef INET6
3806194062Svanhu	case AF_INET6:
3807194062Svanhu		((struct sockaddr_in6 *)sa)->sin6_port = port;
3808194062Svanhu		break;
3809194062Svanhu#endif
3810194062Svanhu	default:
3811194062Svanhu		ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
3812194062Svanhu			__func__, sa->sa_family));
3813194062Svanhu		break;
3814194062Svanhu	}
3815194062Svanhu}
3816194062Svanhu
3817194062Svanhu/*
3818105197Ssam * set data into sadb_x_policy
3819105197Ssam */
3820105197Ssamstatic struct mbuf *
3821189004Srdivackykey_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3822105197Ssam{
3823105197Ssam	struct mbuf *m;
3824105197Ssam	struct sadb_x_policy *p;
3825105197Ssam	size_t len;
3826105197Ssam
3827105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3828105197Ssam	m = key_alloc_mbuf(len);
3829105197Ssam	if (!m || m->m_next) {	/*XXX*/
3830105197Ssam		if (m)
3831105197Ssam			m_freem(m);
3832105197Ssam		return NULL;
3833105197Ssam	}
3834105197Ssam
3835105197Ssam	p = mtod(m, struct sadb_x_policy *);
3836105197Ssam
3837105197Ssam	bzero(p, len);
3838105197Ssam	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3839105197Ssam	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3840105197Ssam	p->sadb_x_policy_type = type;
3841105197Ssam	p->sadb_x_policy_dir = dir;
3842105197Ssam	p->sadb_x_policy_id = id;
3843105197Ssam
3844105197Ssam	return m;
3845105197Ssam}
3846105197Ssam
3847105197Ssam/* %%% utilities */
3848157123Sgnn/* Take a key message (sadb_key) from the socket and turn it into one
3849157123Sgnn * of the kernel's key structures (seckey).
3850157123Sgnn *
3851157123Sgnn * IN: pointer to the src
3852157123Sgnn * OUT: NULL no more memory
3853105197Ssam */
3854157123Sgnnstruct seckey *
3855157123Sgnnkey_dup_keymsg(const struct sadb_key *src, u_int len,
3856157123Sgnn	       struct malloc_type *type)
3857105197Ssam{
3858157123Sgnn	struct seckey *dst;
3859157123Sgnn	dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3860157123Sgnn	if (dst != NULL) {
3861157123Sgnn		dst->bits = src->sadb_key_bits;
3862157123Sgnn		dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3863157123Sgnn		if (dst->key_data != NULL) {
3864157123Sgnn			bcopy((const char *)src + sizeof(struct sadb_key),
3865157123Sgnn			      dst->key_data, len);
3866157123Sgnn		} else {
3867157123Sgnn			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3868157123Sgnn				  __func__));
3869157123Sgnn			free(dst, type);
3870157123Sgnn			dst = NULL;
3871157123Sgnn		}
3872157123Sgnn	} else {
3873157123Sgnn		ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3874157123Sgnn			  __func__));
3875105197Ssam
3876157123Sgnn	}
3877157123Sgnn	return dst;
3878157123Sgnn}
3879157123Sgnn
3880157123Sgnn/* Take a lifetime message (sadb_lifetime) passed in on a socket and
3881157123Sgnn * turn it into one of the kernel's lifetime structures (seclifetime).
3882157123Sgnn *
3883157123Sgnn * IN: pointer to the destination, source and malloc type
3884157123Sgnn * OUT: NULL, no more memory
3885157123Sgnn */
3886157123Sgnn
3887157123Sgnnstatic struct seclifetime *
3888157123Sgnnkey_dup_lifemsg(const struct sadb_lifetime *src,
3889157123Sgnn		 struct malloc_type *type)
3890157123Sgnn{
3891157123Sgnn	struct seclifetime *dst = NULL;
3892157123Sgnn
3893157123Sgnn	dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3894157123Sgnn					   type, M_NOWAIT);
3895157123Sgnn	if (dst == NULL) {
3896119643Ssam		/* XXX counter */
3897120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3898157123Sgnn	} else {
3899157123Sgnn		dst->allocations = src->sadb_lifetime_allocations;
3900157123Sgnn		dst->bytes = src->sadb_lifetime_bytes;
3901157123Sgnn		dst->addtime = src->sadb_lifetime_addtime;
3902157123Sgnn		dst->usetime = src->sadb_lifetime_usetime;
3903157123Sgnn	}
3904157123Sgnn	return dst;
3905105197Ssam}
3906105197Ssam
3907105197Ssam/* compare my own address
3908105197Ssam * OUT:	1: true, i.e. my address.
3909105197Ssam *	0: false
3910105197Ssam */
3911105197Ssamint
3912105197Ssamkey_ismyaddr(sa)
3913105197Ssam	struct sockaddr *sa;
3914105197Ssam{
3915105197Ssam#ifdef INET
3916105197Ssam	struct sockaddr_in *sin;
3917105197Ssam	struct in_ifaddr *ia;
3918105197Ssam#endif
3919105197Ssam
3920120585Ssam	IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3921105197Ssam
3922105197Ssam	switch (sa->sa_family) {
3923105197Ssam#ifdef INET
3924105197Ssam	case AF_INET:
3925105197Ssam		sin = (struct sockaddr_in *)sa;
3926194951Srwatson		IN_IFADDR_RLOCK();
3927181803Sbz		for (ia = V_in_ifaddrhead.tqh_first; ia;
3928105197Ssam		     ia = ia->ia_link.tqe_next)
3929105197Ssam		{
3930105197Ssam			if (sin->sin_family == ia->ia_addr.sin_family &&
3931105197Ssam			    sin->sin_len == ia->ia_addr.sin_len &&
3932105197Ssam			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3933105197Ssam			{
3934194951Srwatson				IN_IFADDR_RUNLOCK();
3935105197Ssam				return 1;
3936105197Ssam			}
3937105197Ssam		}
3938194951Srwatson		IN_IFADDR_RUNLOCK();
3939105197Ssam		break;
3940105197Ssam#endif
3941105197Ssam#ifdef INET6
3942105197Ssam	case AF_INET6:
3943105197Ssam		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3944105197Ssam#endif
3945105197Ssam	}
3946105197Ssam
3947105197Ssam	return 0;
3948105197Ssam}
3949105197Ssam
3950105197Ssam#ifdef INET6
3951105197Ssam/*
3952105197Ssam * compare my own address for IPv6.
3953105197Ssam * 1: ours
3954105197Ssam * 0: other
3955105197Ssam * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3956105197Ssam */
3957105197Ssam#include <netinet6/in6_var.h>
3958105197Ssam
3959105197Ssamstatic int
3960105197Ssamkey_ismyaddr6(sin6)
3961105197Ssam	struct sockaddr_in6 *sin6;
3962105197Ssam{
3963105197Ssam	struct in6_ifaddr *ia;
3964191663Sbms#if 0
3965105197Ssam	struct in6_multi *in6m;
3966191663Sbms#endif
3967105197Ssam
3968194971Srwatson	IN6_IFADDR_RLOCK();
3969194907Srwatson	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
3970105197Ssam		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3971194971Srwatson		    (struct sockaddr *)&ia->ia_addr, 0) == 0) {
3972194971Srwatson			IN6_IFADDR_RUNLOCK();
3973105197Ssam			return 1;
3974194971Srwatson		}
3975105197Ssam
3976191663Sbms#if 0
3977105197Ssam		/*
3978105197Ssam		 * XXX Multicast
3979105197Ssam		 * XXX why do we care about multlicast here while we don't care
3980105197Ssam		 * about IPv4 multicast??
3981105197Ssam		 * XXX scope
3982105197Ssam		 */
3983105197Ssam		in6m = NULL;
3984105197Ssam		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3985194971Srwatson		if (in6m) {
3986194971Srwatson			IN6_IFADDR_RUNLOCK();
3987105197Ssam			return 1;
3988194971Srwatson		}
3989191663Sbms#endif
3990105197Ssam	}
3991194971Srwatson	IN6_IFADDR_RUNLOCK();
3992105197Ssam
3993105197Ssam	/* loopback, just for safety */
3994105197Ssam	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3995105197Ssam		return 1;
3996105197Ssam
3997105197Ssam	return 0;
3998105197Ssam}
3999105197Ssam#endif /*INET6*/
4000105197Ssam
4001105197Ssam/*
4002105197Ssam * compare two secasindex structure.
4003105197Ssam * flag can specify to compare 2 saidxes.
4004105197Ssam * compare two secasindex structure without both mode and reqid.
4005105197Ssam * don't compare port.
4006105197Ssam * IN:
4007105197Ssam *      saidx0: source, it can be in SAD.
4008105197Ssam *      saidx1: object.
4009105197Ssam * OUT:
4010105197Ssam *      1 : equal
4011105197Ssam *      0 : not equal
4012105197Ssam */
4013105197Ssamstatic int
4014105197Ssamkey_cmpsaidx(
4015105197Ssam	const struct secasindex *saidx0,
4016105197Ssam	const struct secasindex *saidx1,
4017105197Ssam	int flag)
4018105197Ssam{
4019194062Svanhu	int chkport = 0;
4020194062Svanhu
4021105197Ssam	/* sanity */
4022105197Ssam	if (saidx0 == NULL && saidx1 == NULL)
4023105197Ssam		return 1;
4024105197Ssam
4025105197Ssam	if (saidx0 == NULL || saidx1 == NULL)
4026105197Ssam		return 0;
4027105197Ssam
4028105197Ssam	if (saidx0->proto != saidx1->proto)
4029105197Ssam		return 0;
4030105197Ssam
4031105197Ssam	if (flag == CMP_EXACTLY) {
4032105197Ssam		if (saidx0->mode != saidx1->mode)
4033105197Ssam			return 0;
4034105197Ssam		if (saidx0->reqid != saidx1->reqid)
4035105197Ssam			return 0;
4036105197Ssam		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4037105197Ssam		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4038105197Ssam			return 0;
4039105197Ssam	} else {
4040105197Ssam
4041105197Ssam		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4042105197Ssam		if (flag == CMP_MODE_REQID
4043105197Ssam		  ||flag == CMP_REQID) {
4044105197Ssam			/*
4045105197Ssam			 * If reqid of SPD is non-zero, unique SA is required.
4046105197Ssam			 * The result must be of same reqid in this case.
4047105197Ssam			 */
4048105197Ssam			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4049105197Ssam				return 0;
4050105197Ssam		}
4051105197Ssam
4052105197Ssam		if (flag == CMP_MODE_REQID) {
4053105197Ssam			if (saidx0->mode != IPSEC_MODE_ANY
4054105197Ssam			 && saidx0->mode != saidx1->mode)
4055105197Ssam				return 0;
4056105197Ssam		}
4057105197Ssam
4058194062Svanhu#ifdef IPSEC_NAT_T
4059194062Svanhu		/*
4060194062Svanhu		 * If NAT-T is enabled, check ports for tunnel mode.
4061194062Svanhu		 * Do not check ports if they are set to zero in the SPD.
4062194062Svanhu		 * Also do not do it for transport mode, as there is no
4063194062Svanhu		 * port information available in the SP.
4064194062Svanhu		 */
4065194062Svanhu		if (saidx1->mode == IPSEC_MODE_TUNNEL &&
4066194062Svanhu		    saidx1->src.sa.sa_family == AF_INET &&
4067194062Svanhu		    saidx1->dst.sa.sa_family == AF_INET &&
4068194062Svanhu		    ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
4069194062Svanhu		    ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
4070194062Svanhu			chkport = 1;
4071194062Svanhu#endif /* IPSEC_NAT_T */
4072194062Svanhu
4073194062Svanhu		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
4074105197Ssam			return 0;
4075105197Ssam		}
4076194062Svanhu		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
4077105197Ssam			return 0;
4078105197Ssam		}
4079105197Ssam	}
4080105197Ssam
4081105197Ssam	return 1;
4082105197Ssam}
4083105197Ssam
4084105197Ssam/*
4085105197Ssam * compare two secindex structure exactly.
4086105197Ssam * IN:
4087105197Ssam *	spidx0: source, it is often in SPD.
4088105197Ssam *	spidx1: object, it is often from PFKEY message.
4089105197Ssam * OUT:
4090105197Ssam *	1 : equal
4091105197Ssam *	0 : not equal
4092105197Ssam */
4093105197Ssamstatic int
4094105197Ssamkey_cmpspidx_exactly(
4095105197Ssam	struct secpolicyindex *spidx0,
4096105197Ssam	struct secpolicyindex *spidx1)
4097105197Ssam{
4098105197Ssam	/* sanity */
4099105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
4100105197Ssam		return 1;
4101105197Ssam
4102105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
4103105197Ssam		return 0;
4104105197Ssam
4105105197Ssam	if (spidx0->prefs != spidx1->prefs
4106105197Ssam	 || spidx0->prefd != spidx1->prefd
4107105197Ssam	 || spidx0->ul_proto != spidx1->ul_proto)
4108105197Ssam		return 0;
4109105197Ssam
4110105197Ssam	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4111105197Ssam	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4112105197Ssam}
4113105197Ssam
4114105197Ssam/*
4115105197Ssam * compare two secindex structure with mask.
4116105197Ssam * IN:
4117105197Ssam *	spidx0: source, it is often in SPD.
4118105197Ssam *	spidx1: object, it is often from IP header.
4119105197Ssam * OUT:
4120105197Ssam *	1 : equal
4121105197Ssam *	0 : not equal
4122105197Ssam */
4123105197Ssamstatic int
4124105197Ssamkey_cmpspidx_withmask(
4125105197Ssam	struct secpolicyindex *spidx0,
4126105197Ssam	struct secpolicyindex *spidx1)
4127105197Ssam{
4128105197Ssam	/* sanity */
4129105197Ssam	if (spidx0 == NULL && spidx1 == NULL)
4130105197Ssam		return 1;
4131105197Ssam
4132105197Ssam	if (spidx0 == NULL || spidx1 == NULL)
4133105197Ssam		return 0;
4134105197Ssam
4135105197Ssam	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4136105197Ssam	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4137105197Ssam	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4138105197Ssam	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4139105197Ssam		return 0;
4140105197Ssam
4141105197Ssam	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4142105197Ssam	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4143105197Ssam	 && spidx0->ul_proto != spidx1->ul_proto)
4144105197Ssam		return 0;
4145105197Ssam
4146105197Ssam	switch (spidx0->src.sa.sa_family) {
4147105197Ssam	case AF_INET:
4148105197Ssam		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4149105197Ssam		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4150105197Ssam			return 0;
4151105197Ssam		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4152105197Ssam		    &spidx1->src.sin.sin_addr, spidx0->prefs))
4153105197Ssam			return 0;
4154105197Ssam		break;
4155105197Ssam	case AF_INET6:
4156105197Ssam		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4157105197Ssam		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4158105197Ssam			return 0;
4159105197Ssam		/*
4160105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
4161105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
4162105197Ssam		 */
4163105197Ssam		if (spidx0->src.sin6.sin6_scope_id &&
4164105197Ssam		    spidx1->src.sin6.sin6_scope_id &&
4165105197Ssam		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4166105197Ssam			return 0;
4167105197Ssam		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4168105197Ssam		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4169105197Ssam			return 0;
4170105197Ssam		break;
4171105197Ssam	default:
4172105197Ssam		/* XXX */
4173105197Ssam		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4174105197Ssam			return 0;
4175105197Ssam		break;
4176105197Ssam	}
4177105197Ssam
4178105197Ssam	switch (spidx0->dst.sa.sa_family) {
4179105197Ssam	case AF_INET:
4180105197Ssam		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4181105197Ssam		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4182105197Ssam			return 0;
4183105197Ssam		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4184105197Ssam		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
4185105197Ssam			return 0;
4186105197Ssam		break;
4187105197Ssam	case AF_INET6:
4188105197Ssam		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4189105197Ssam		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4190105197Ssam			return 0;
4191105197Ssam		/*
4192105197Ssam		 * scope_id check. if sin6_scope_id is 0, we regard it
4193105197Ssam		 * as a wildcard scope, which matches any scope zone ID.
4194105197Ssam		 */
4195130928Sbms		if (spidx0->dst.sin6.sin6_scope_id &&
4196130928Sbms		    spidx1->dst.sin6.sin6_scope_id &&
4197105197Ssam		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4198105197Ssam			return 0;
4199105197Ssam		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4200105197Ssam		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4201105197Ssam			return 0;
4202105197Ssam		break;
4203105197Ssam	default:
4204105197Ssam		/* XXX */
4205105197Ssam		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4206105197Ssam			return 0;
4207105197Ssam		break;
4208105197Ssam	}
4209105197Ssam
4210105197Ssam	/* XXX Do we check other field ?  e.g. flowinfo */
4211105197Ssam
4212105197Ssam	return 1;
4213105197Ssam}
4214105197Ssam
4215105197Ssam/* returns 0 on match */
4216105197Ssamstatic int
4217105197Ssamkey_sockaddrcmp(
4218105197Ssam	const struct sockaddr *sa1,
4219105197Ssam	const struct sockaddr *sa2,
4220105197Ssam	int port)
4221105197Ssam{
4222105197Ssam#ifdef satosin
4223105197Ssam#undef satosin
4224105197Ssam#endif
4225105197Ssam#define satosin(s) ((const struct sockaddr_in *)s)
4226105197Ssam#ifdef satosin6
4227105197Ssam#undef satosin6
4228105197Ssam#endif
4229105197Ssam#define satosin6(s) ((const struct sockaddr_in6 *)s)
4230105197Ssam	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4231105197Ssam		return 1;
4232105197Ssam
4233105197Ssam	switch (sa1->sa_family) {
4234105197Ssam	case AF_INET:
4235105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in))
4236105197Ssam			return 1;
4237105197Ssam		if (satosin(sa1)->sin_addr.s_addr !=
4238105197Ssam		    satosin(sa2)->sin_addr.s_addr) {
4239105197Ssam			return 1;
4240105197Ssam		}
4241105197Ssam		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4242105197Ssam			return 1;
4243105197Ssam		break;
4244105197Ssam	case AF_INET6:
4245105197Ssam		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4246105197Ssam			return 1;	/*EINVAL*/
4247105197Ssam		if (satosin6(sa1)->sin6_scope_id !=
4248105197Ssam		    satosin6(sa2)->sin6_scope_id) {
4249105197Ssam			return 1;
4250105197Ssam		}
4251105197Ssam		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4252105197Ssam		    &satosin6(sa2)->sin6_addr)) {
4253105197Ssam			return 1;
4254105197Ssam		}
4255105197Ssam		if (port &&
4256105197Ssam		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4257105197Ssam			return 1;
4258105197Ssam		}
4259170120Sbz		break;
4260105197Ssam	default:
4261105197Ssam		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4262105197Ssam			return 1;
4263105197Ssam		break;
4264105197Ssam	}
4265105197Ssam
4266105197Ssam	return 0;
4267105197Ssam#undef satosin
4268105197Ssam#undef satosin6
4269105197Ssam}
4270105197Ssam
4271105197Ssam/*
4272105197Ssam * compare two buffers with mask.
4273105197Ssam * IN:
4274105197Ssam *	addr1: source
4275105197Ssam *	addr2: object
4276105197Ssam *	bits:  Number of bits to compare
4277105197Ssam * OUT:
4278105197Ssam *	1 : equal
4279105197Ssam *	0 : not equal
4280105197Ssam */
4281105197Ssamstatic int
4282105197Ssamkey_bbcmp(const void *a1, const void *a2, u_int bits)
4283105197Ssam{
4284105197Ssam	const unsigned char *p1 = a1;
4285105197Ssam	const unsigned char *p2 = a2;
4286105197Ssam
4287105197Ssam	/* XXX: This could be considerably faster if we compare a word
4288105197Ssam	 * at a time, but it is complicated on LSB Endian machines */
4289105197Ssam
4290105197Ssam	/* Handle null pointers */
4291105197Ssam	if (p1 == NULL || p2 == NULL)
4292105197Ssam		return (p1 == p2);
4293105197Ssam
4294105197Ssam	while (bits >= 8) {
4295105197Ssam		if (*p1++ != *p2++)
4296105197Ssam			return 0;
4297105197Ssam		bits -= 8;
4298105197Ssam	}
4299105197Ssam
4300105197Ssam	if (bits > 0) {
4301105197Ssam		u_int8_t mask = ~((1<<(8-bits))-1);
4302105197Ssam		if ((*p1 & mask) != (*p2 & mask))
4303105197Ssam			return 0;
4304105197Ssam	}
4305105197Ssam	return 1;	/* Match! */
4306105197Ssam}
4307105197Ssam
4308119643Ssamstatic void
4309119643Ssamkey_flush_spd(time_t now)
4310105197Ssam{
4311120585Ssam	static u_int16_t sptree_scangen = 0;
4312120585Ssam	u_int16_t gen = sptree_scangen++;
4313120585Ssam	struct secpolicy *sp;
4314105197Ssam	u_int dir;
4315105197Ssam
4316105197Ssam	/* SPD */
4317105197Ssam	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4318120585Ssamrestart:
4319120585Ssam		SPTREE_LOCK();
4320181803Sbz		LIST_FOREACH(sp, &V_sptree[dir], chain) {
4321120585Ssam			if (sp->scangen == gen)		/* previously handled */
4322120585Ssam				continue;
4323120585Ssam			sp->scangen = gen;
4324192880Svanhu			if (sp->state == IPSEC_SPSTATE_DEAD &&
4325192880Svanhu			    sp->refcnt == 1) {
4326192880Svanhu				/*
4327192880Svanhu				 * Ensure that we only decrease refcnt once,
4328192880Svanhu				 * when we're the last consumer.
4329192880Svanhu				 * Directly call SP_DELREF/key_delsp instead
4330192880Svanhu				 * of KEY_FREESP to avoid unlocking/relocking
4331192880Svanhu				 * SPTREE_LOCK before key_delsp: may refcnt
4332192880Svanhu				 * be increased again during that time ?
4333192880Svanhu				 * NB: also clean entries created by
4334192880Svanhu				 * key_spdflush
4335192880Svanhu				 */
4336192880Svanhu				SP_DELREF(sp);
4337192880Svanhu				key_delsp(sp);
4338120585Ssam				SPTREE_UNLOCK();
4339120585Ssam				goto restart;
4340105197Ssam			}
4341105197Ssam			if (sp->lifetime == 0 && sp->validtime == 0)
4342105197Ssam				continue;
4343105197Ssam			if ((sp->lifetime && now - sp->created > sp->lifetime)
4344105197Ssam			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4345105197Ssam				sp->state = IPSEC_SPSTATE_DEAD;
4346120585Ssam				SPTREE_UNLOCK();
4347105197Ssam				key_spdexpire(sp);
4348120585Ssam				goto restart;
4349105197Ssam			}
4350105197Ssam		}
4351120585Ssam		SPTREE_UNLOCK();
4352105197Ssam	}
4353119643Ssam}
4354105197Ssam
4355119643Ssamstatic void
4356119643Ssamkey_flush_sad(time_t now)
4357119643Ssam{
4358105197Ssam	struct secashead *sah, *nextsah;
4359105197Ssam	struct secasvar *sav, *nextsav;
4360105197Ssam
4361119643Ssam	/* SAD */
4362120585Ssam	SAHTREE_LOCK();
4363181803Sbz	LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4364105197Ssam		/* if sah has been dead, then delete it and process next sah. */
4365105197Ssam		if (sah->state == SADB_SASTATE_DEAD) {
4366105197Ssam			key_delsah(sah);
4367105197Ssam			continue;
4368105197Ssam		}
4369105197Ssam
4370105197Ssam		/* if LARVAL entry doesn't become MATURE, delete it. */
4371120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4372190071Svanhu			/* Need to also check refcnt for a larval SA ??? */
4373181803Sbz			if (now - sav->created > V_key_larval_lifetime)
4374105197Ssam				KEY_FREESAV(&sav);
4375105197Ssam		}
4376105197Ssam
4377105197Ssam		/*
4378105197Ssam		 * check MATURE entry to start to send expire message
4379105197Ssam		 * whether or not.
4380105197Ssam		 */
4381120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4382105197Ssam			/* we don't need to check. */
4383105197Ssam			if (sav->lft_s == NULL)
4384105197Ssam				continue;
4385105197Ssam
4386105197Ssam			/* sanity check */
4387105197Ssam			if (sav->lft_c == NULL) {
4388120585Ssam				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4389120585Ssam					"time, why?\n", __func__));
4390105197Ssam				continue;
4391105197Ssam			}
4392105197Ssam
4393105197Ssam			/* check SOFT lifetime */
4394157123Sgnn			if (sav->lft_s->addtime != 0 &&
4395157123Sgnn			    now - sav->created > sav->lft_s->addtime) {
4396189406Svanhu				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4397190075Svanhu				/*
4398190323Svanhu				 * Actually, only send expire message if
4399190323Svanhu				 * SA has been used, as it was done before,
4400190323Svanhu				 * but should we always send such message,
4401190323Svanhu				 * and let IKE daemon decide if it should be
4402190323Svanhu				 * renegotiated or not ?
4403190323Svanhu				 * XXX expire message will actually NOT be
4404190323Svanhu				 * sent if SA is only used after soft
4405190323Svanhu				 * lifetime has been reached, see below
4406190323Svanhu				 * (DYING state)
4407105197Ssam				 */
4408189406Svanhu				if (sav->lft_c->usetime != 0)
4409105197Ssam					key_expire(sav);
4410105197Ssam			}
4411105197Ssam			/* check SOFT lifetime by bytes */
4412105197Ssam			/*
4413105197Ssam			 * XXX I don't know the way to delete this SA
4414105197Ssam			 * when new SA is installed.  Caution when it's
4415105197Ssam			 * installed too big lifetime by time.
4416105197Ssam			 */
4417157123Sgnn			else if (sav->lft_s->bytes != 0 &&
4418157123Sgnn			    sav->lft_s->bytes < sav->lft_c->bytes) {
4419105197Ssam
4420105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4421105197Ssam				/*
4422105197Ssam				 * XXX If we keep to send expire
4423105197Ssam				 * message in the status of
4424105197Ssam				 * DYING. Do remove below code.
4425105197Ssam				 */
4426105197Ssam				key_expire(sav);
4427105197Ssam			}
4428105197Ssam		}
4429105197Ssam
4430105197Ssam		/* check DYING entry to change status to DEAD. */
4431120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4432105197Ssam			/* we don't need to check. */
4433105197Ssam			if (sav->lft_h == NULL)
4434105197Ssam				continue;
4435105197Ssam
4436105197Ssam			/* sanity check */
4437105197Ssam			if (sav->lft_c == NULL) {
4438120585Ssam				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4439120585Ssam					"time, why?\n", __func__));
4440105197Ssam				continue;
4441105197Ssam			}
4442105197Ssam
4443157123Sgnn			if (sav->lft_h->addtime != 0 &&
4444157123Sgnn			    now - sav->created > sav->lft_h->addtime) {
4445105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4446105197Ssam				KEY_FREESAV(&sav);
4447105197Ssam			}
4448105197Ssam#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4449105197Ssam			else if (sav->lft_s != NULL
4450157123Sgnn			      && sav->lft_s->addtime != 0
4451157123Sgnn			      && now - sav->created > sav->lft_s->addtime) {
4452105197Ssam				/*
4453105197Ssam				 * XXX: should be checked to be
4454105197Ssam				 * installed the valid SA.
4455105197Ssam				 */
4456105197Ssam
4457105197Ssam				/*
4458105197Ssam				 * If there is no SA then sending
4459105197Ssam				 * expire message.
4460105197Ssam				 */
4461105197Ssam				key_expire(sav);
4462105197Ssam			}
4463105197Ssam#endif
4464105197Ssam			/* check HARD lifetime by bytes */
4465157123Sgnn			else if (sav->lft_h->bytes != 0 &&
4466157123Sgnn			    sav->lft_h->bytes < sav->lft_c->bytes) {
4467105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4468105197Ssam				KEY_FREESAV(&sav);
4469105197Ssam			}
4470105197Ssam		}
4471105197Ssam
4472105197Ssam		/* delete entry in DEAD */
4473120585Ssam		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4474105197Ssam			/* sanity check */
4475105197Ssam			if (sav->state != SADB_SASTATE_DEAD) {
4476120585Ssam				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4477120585Ssam					"(queue: %d SA: %d): kill it anyway\n",
4478120585Ssam					__func__,
4479105197Ssam					SADB_SASTATE_DEAD, sav->state));
4480105197Ssam			}
4481105197Ssam			/*
4482105197Ssam			 * do not call key_freesav() here.
4483105197Ssam			 * sav should already be freed, and sav->refcnt
4484105197Ssam			 * shows other references to sav
4485105197Ssam			 * (such as from SPD).
4486105197Ssam			 */
4487105197Ssam		}
4488105197Ssam	}
4489120585Ssam	SAHTREE_UNLOCK();
4490119643Ssam}
4491105197Ssam
4492119643Ssamstatic void
4493119643Ssamkey_flush_acq(time_t now)
4494119643Ssam{
4495105197Ssam	struct secacq *acq, *nextacq;
4496105197Ssam
4497119643Ssam	/* ACQ tree */
4498120585Ssam	ACQ_LOCK();
4499181803Sbz	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4500105197Ssam		nextacq = LIST_NEXT(acq, chain);
4501181803Sbz		if (now - acq->created > V_key_blockacq_lifetime
4502105197Ssam		 && __LIST_CHAINED(acq)) {
4503105197Ssam			LIST_REMOVE(acq, chain);
4504119643Ssam			free(acq, M_IPSEC_SAQ);
4505105197Ssam		}
4506105197Ssam	}
4507120585Ssam	ACQ_UNLOCK();
4508119643Ssam}
4509105197Ssam
4510119643Ssamstatic void
4511119643Ssamkey_flush_spacq(time_t now)
4512119643Ssam{
4513105197Ssam	struct secspacq *acq, *nextacq;
4514105197Ssam
4515119643Ssam	/* SP ACQ tree */
4516120585Ssam	SPACQ_LOCK();
4517181803Sbz	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4518105197Ssam		nextacq = LIST_NEXT(acq, chain);
4519181803Sbz		if (now - acq->created > V_key_blockacq_lifetime
4520105197Ssam		 && __LIST_CHAINED(acq)) {
4521105197Ssam			LIST_REMOVE(acq, chain);
4522119643Ssam			free(acq, M_IPSEC_SAQ);
4523105197Ssam		}
4524105197Ssam	}
4525120585Ssam	SPACQ_UNLOCK();
4526119643Ssam}
4527105197Ssam
4528119643Ssam/*
4529119643Ssam * time handler.
4530119643Ssam * scanning SPD and SAD to check status for each entries,
4531119643Ssam * and do to remove or to expire.
4532119643Ssam * XXX: year 2038 problem may remain.
4533119643Ssam */
4534119643Ssamvoid
4535119643Ssamkey_timehandler(void)
4536119643Ssam{
4537183550Szec	VNET_ITERATOR_DECL(vnet_iter);
4538119643Ssam	time_t now = time_second;
4539105197Ssam
4540185348Szec	VNET_LIST_RLOCK();
4541183550Szec	VNET_FOREACH(vnet_iter) {
4542183550Szec		CURVNET_SET(vnet_iter);
4543183550Szec		key_flush_spd(now);
4544183550Szec		key_flush_sad(now);
4545183550Szec		key_flush_acq(now);
4546183550Szec		key_flush_spacq(now);
4547183550Szec		CURVNET_RESTORE();
4548183550Szec	}
4549185348Szec	VNET_LIST_RUNLOCK();
4550119643Ssam
4551105197Ssam#ifndef IPSEC_DEBUG2
4552105197Ssam	/* do exchange to tick time !! */
4553105197Ssam	(void)timeout((void *)key_timehandler, (void *)0, hz);
4554105197Ssam#endif /* IPSEC_DEBUG2 */
4555105197Ssam}
4556105197Ssam
4557105197Ssamu_long
4558105197Ssamkey_random()
4559105197Ssam{
4560105197Ssam	u_long value;
4561105197Ssam
4562105197Ssam	key_randomfill(&value, sizeof(value));
4563105197Ssam	return value;
4564105197Ssam}
4565105197Ssam
4566105197Ssamvoid
4567105197Ssamkey_randomfill(p, l)
4568105197Ssam	void *p;
4569105197Ssam	size_t l;
4570105197Ssam{
4571105197Ssam	size_t n;
4572105197Ssam	u_long v;
4573105197Ssam	static int warn = 1;
4574105197Ssam
4575105197Ssam	n = 0;
4576105197Ssam	n = (size_t)read_random(p, (u_int)l);
4577105197Ssam	/* last resort */
4578105197Ssam	while (n < l) {
4579105197Ssam		v = random();
4580105197Ssam		bcopy(&v, (u_int8_t *)p + n,
4581105197Ssam		    l - n < sizeof(v) ? l - n : sizeof(v));
4582105197Ssam		n += sizeof(v);
4583105197Ssam
4584105197Ssam		if (warn) {
4585105197Ssam			printf("WARNING: pseudo-random number generator "
4586105197Ssam			    "used for IPsec processing\n");
4587105197Ssam			warn = 0;
4588105197Ssam		}
4589105197Ssam	}
4590105197Ssam}
4591105197Ssam
4592105197Ssam/*
4593105197Ssam * map SADB_SATYPE_* to IPPROTO_*.
4594105197Ssam * if satype == SADB_SATYPE then satype is mapped to ~0.
4595105197Ssam * OUT:
4596105197Ssam *	0: invalid satype.
4597105197Ssam */
4598105197Ssamstatic u_int16_t
4599189004Srdivackykey_satype2proto(u_int8_t satype)
4600105197Ssam{
4601105197Ssam	switch (satype) {
4602105197Ssam	case SADB_SATYPE_UNSPEC:
4603105197Ssam		return IPSEC_PROTO_ANY;
4604105197Ssam	case SADB_SATYPE_AH:
4605105197Ssam		return IPPROTO_AH;
4606105197Ssam	case SADB_SATYPE_ESP:
4607105197Ssam		return IPPROTO_ESP;
4608105197Ssam	case SADB_X_SATYPE_IPCOMP:
4609105197Ssam		return IPPROTO_IPCOMP;
4610125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
4611125680Sbms		return IPPROTO_TCP;
4612105197Ssam	default:
4613105197Ssam		return 0;
4614105197Ssam	}
4615105197Ssam	/* NOTREACHED */
4616105197Ssam}
4617105197Ssam
4618105197Ssam/*
4619105197Ssam * map IPPROTO_* to SADB_SATYPE_*
4620105197Ssam * OUT:
4621105197Ssam *	0: invalid protocol type.
4622105197Ssam */
4623105197Ssamstatic u_int8_t
4624189004Srdivackykey_proto2satype(u_int16_t proto)
4625105197Ssam{
4626105197Ssam	switch (proto) {
4627105197Ssam	case IPPROTO_AH:
4628105197Ssam		return SADB_SATYPE_AH;
4629105197Ssam	case IPPROTO_ESP:
4630105197Ssam		return SADB_SATYPE_ESP;
4631105197Ssam	case IPPROTO_IPCOMP:
4632105197Ssam		return SADB_X_SATYPE_IPCOMP;
4633125680Sbms	case IPPROTO_TCP:
4634125680Sbms		return SADB_X_SATYPE_TCPSIGNATURE;
4635105197Ssam	default:
4636105197Ssam		return 0;
4637105197Ssam	}
4638105197Ssam	/* NOTREACHED */
4639105197Ssam}
4640105197Ssam
4641105197Ssam/* %%% PF_KEY */
4642105197Ssam/*
4643105197Ssam * SADB_GETSPI processing is to receive
4644105197Ssam *	<base, (SA2), src address, dst address, (SPI range)>
4645105197Ssam * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4646105197Ssam * tree with the status of LARVAL, and send
4647105197Ssam *	<base, SA(*), address(SD)>
4648105197Ssam * to the IKMPd.
4649105197Ssam *
4650105197Ssam * IN:	mhp: pointer to the pointer to each header.
4651105197Ssam * OUT:	NULL if fail.
4652105197Ssam *	other if success, return pointer to the message to send.
4653105197Ssam */
4654105197Ssamstatic int
4655105197Ssamkey_getspi(so, m, mhp)
4656105197Ssam	struct socket *so;
4657105197Ssam	struct mbuf *m;
4658105197Ssam	const struct sadb_msghdr *mhp;
4659105197Ssam{
4660105197Ssam	struct sadb_address *src0, *dst0;
4661105197Ssam	struct secasindex saidx;
4662105197Ssam	struct secashead *newsah;
4663105197Ssam	struct secasvar *newsav;
4664105197Ssam	u_int8_t proto;
4665105197Ssam	u_int32_t spi;
4666105197Ssam	u_int8_t mode;
4667105197Ssam	u_int32_t reqid;
4668105197Ssam	int error;
4669105197Ssam
4670120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4671120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4672120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4673120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4674105197Ssam
4675105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4676105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4677120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4678120585Ssam			__func__));
4679105197Ssam		return key_senderror(so, m, EINVAL);
4680105197Ssam	}
4681105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4682105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4683120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4684120585Ssam			__func__));
4685105197Ssam		return key_senderror(so, m, EINVAL);
4686105197Ssam	}
4687105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4688105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4689105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4690105197Ssam	} else {
4691105197Ssam		mode = IPSEC_MODE_ANY;
4692105197Ssam		reqid = 0;
4693105197Ssam	}
4694105197Ssam
4695105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4696105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4697105197Ssam
4698105197Ssam	/* map satype to proto */
4699105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4700120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4701120585Ssam			__func__));
4702105197Ssam		return key_senderror(so, m, EINVAL);
4703105197Ssam	}
4704105197Ssam
4705194062Svanhu	/*
4706194062Svanhu	 * Make sure the port numbers are zero.
4707194062Svanhu	 * In case of NAT-T we will update them later if needed.
4708194062Svanhu	 */
4709105197Ssam	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4710105197Ssam	case AF_INET:
4711105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4712105197Ssam		    sizeof(struct sockaddr_in))
4713105197Ssam			return key_senderror(so, m, EINVAL);
4714105197Ssam		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4715105197Ssam		break;
4716105197Ssam	case AF_INET6:
4717105197Ssam		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4718105197Ssam		    sizeof(struct sockaddr_in6))
4719105197Ssam			return key_senderror(so, m, EINVAL);
4720105197Ssam		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4721105197Ssam		break;
4722105197Ssam	default:
4723105197Ssam		; /*???*/
4724105197Ssam	}
4725105197Ssam	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4726105197Ssam	case AF_INET:
4727105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4728105197Ssam		    sizeof(struct sockaddr_in))
4729105197Ssam			return key_senderror(so, m, EINVAL);
4730105197Ssam		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4731105197Ssam		break;
4732105197Ssam	case AF_INET6:
4733105197Ssam		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4734105197Ssam		    sizeof(struct sockaddr_in6))
4735105197Ssam			return key_senderror(so, m, EINVAL);
4736105197Ssam		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4737105197Ssam		break;
4738105197Ssam	default:
4739105197Ssam		; /*???*/
4740105197Ssam	}
4741105197Ssam
4742105197Ssam	/* XXX boundary check against sa_len */
4743105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4744105197Ssam
4745194062Svanhu#ifdef IPSEC_NAT_T
4746194062Svanhu	/*
4747194062Svanhu	 * Handle NAT-T info if present.
4748194062Svanhu	 * We made sure the port numbers are zero above, so we do
4749194062Svanhu	 * not have to worry in case we do not update them.
4750194062Svanhu	 */
4751194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4752194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4753194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4754194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4755194062Svanhu
4756194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4757194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4758194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4759194062Svanhu		struct sadb_x_nat_t_type *type;
4760194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
4761194062Svanhu
4762194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4763194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4764194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4765194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4766194062Svanhu			    "passed.\n", __func__));
4767194062Svanhu			return key_senderror(so, m, EINVAL);
4768194062Svanhu		}
4769194062Svanhu
4770194062Svanhu		sport = (struct sadb_x_nat_t_port *)
4771194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4772194062Svanhu		dport = (struct sadb_x_nat_t_port *)
4773194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4774194062Svanhu
4775194062Svanhu		if (sport)
4776194062Svanhu			KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4777194062Svanhu		if (dport)
4778194062Svanhu			KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4779194062Svanhu	}
4780194062Svanhu#endif
4781194062Svanhu
4782105197Ssam	/* SPI allocation */
4783105197Ssam	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4784105197Ssam	                       &saidx);
4785105197Ssam	if (spi == 0)
4786105197Ssam		return key_senderror(so, m, EINVAL);
4787105197Ssam
4788105197Ssam	/* get a SA index */
4789105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
4790105197Ssam		/* create a new SA index */
4791105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
4792120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4793105197Ssam			return key_senderror(so, m, ENOBUFS);
4794105197Ssam		}
4795105197Ssam	}
4796105197Ssam
4797105197Ssam	/* get a new SA */
4798105197Ssam	/* XXX rewrite */
4799105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4800105197Ssam	if (newsav == NULL) {
4801105197Ssam		/* XXX don't free new SA index allocated in above. */
4802105197Ssam		return key_senderror(so, m, error);
4803105197Ssam	}
4804105197Ssam
4805105197Ssam	/* set spi */
4806105197Ssam	newsav->spi = htonl(spi);
4807105197Ssam
4808105197Ssam	/* delete the entry in acqtree */
4809105197Ssam	if (mhp->msg->sadb_msg_seq != 0) {
4810105197Ssam		struct secacq *acq;
4811105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4812105197Ssam			/* reset counter in order to deletion by timehandler. */
4813105197Ssam			acq->created = time_second;
4814105197Ssam			acq->count = 0;
4815105197Ssam		}
4816105197Ssam    	}
4817105197Ssam
4818105197Ssam    {
4819105197Ssam	struct mbuf *n, *nn;
4820105197Ssam	struct sadb_sa *m_sa;
4821105197Ssam	struct sadb_msg *newmsg;
4822105197Ssam	int off, len;
4823105197Ssam
4824105197Ssam	/* create new sadb_msg to reply. */
4825105197Ssam	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4826105197Ssam	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4827105197Ssam
4828111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
4829105197Ssam	if (len > MHLEN) {
4830111119Simp		MCLGET(n, M_DONTWAIT);
4831105197Ssam		if ((n->m_flags & M_EXT) == 0) {
4832105197Ssam			m_freem(n);
4833105197Ssam			n = NULL;
4834105197Ssam		}
4835105197Ssam	}
4836105197Ssam	if (!n)
4837105197Ssam		return key_senderror(so, m, ENOBUFS);
4838105197Ssam
4839105197Ssam	n->m_len = len;
4840105197Ssam	n->m_next = NULL;
4841105197Ssam	off = 0;
4842105197Ssam
4843105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4844105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4845105197Ssam
4846105197Ssam	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4847105197Ssam	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4848105197Ssam	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4849105197Ssam	m_sa->sadb_sa_spi = htonl(spi);
4850105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4851105197Ssam
4852120585Ssam	IPSEC_ASSERT(off == len,
4853120585Ssam		("length inconsistency (off %u len %u)", off, len));
4854105197Ssam
4855105197Ssam	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4856105197Ssam	    SADB_EXT_ADDRESS_DST);
4857105197Ssam	if (!n->m_next) {
4858105197Ssam		m_freem(n);
4859105197Ssam		return key_senderror(so, m, ENOBUFS);
4860105197Ssam	}
4861105197Ssam
4862105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
4863105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
4864105197Ssam		if (n == NULL)
4865105197Ssam			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4866105197Ssam	}
4867105197Ssam
4868105197Ssam	n->m_pkthdr.len = 0;
4869105197Ssam	for (nn = n; nn; nn = nn->m_next)
4870105197Ssam		n->m_pkthdr.len += nn->m_len;
4871105197Ssam
4872105197Ssam	newmsg = mtod(n, struct sadb_msg *);
4873105197Ssam	newmsg->sadb_msg_seq = newsav->seq;
4874105197Ssam	newmsg->sadb_msg_errno = 0;
4875105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4876105197Ssam
4877105197Ssam	m_freem(m);
4878105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4879105197Ssam    }
4880105197Ssam}
4881105197Ssam
4882105197Ssam/*
4883105197Ssam * allocating new SPI
4884105197Ssam * called by key_getspi().
4885105197Ssam * OUT:
4886105197Ssam *	0:	failure.
4887105197Ssam *	others: success.
4888105197Ssam */
4889105197Ssamstatic u_int32_t
4890105197Ssamkey_do_getnewspi(spirange, saidx)
4891105197Ssam	struct sadb_spirange *spirange;
4892105197Ssam	struct secasindex *saidx;
4893105197Ssam{
4894105197Ssam	u_int32_t newspi;
4895105197Ssam	u_int32_t min, max;
4896181803Sbz	int count = V_key_spi_trycnt;
4897105197Ssam
4898105197Ssam	/* set spi range to allocate */
4899105197Ssam	if (spirange != NULL) {
4900105197Ssam		min = spirange->sadb_spirange_min;
4901105197Ssam		max = spirange->sadb_spirange_max;
4902105197Ssam	} else {
4903181803Sbz		min = V_key_spi_minval;
4904181803Sbz		max = V_key_spi_maxval;
4905105197Ssam	}
4906105197Ssam	/* IPCOMP needs 2-byte SPI */
4907105197Ssam	if (saidx->proto == IPPROTO_IPCOMP) {
4908105197Ssam		u_int32_t t;
4909105197Ssam		if (min >= 0x10000)
4910105197Ssam			min = 0xffff;
4911105197Ssam		if (max >= 0x10000)
4912105197Ssam			max = 0xffff;
4913105197Ssam		if (min > max) {
4914105197Ssam			t = min; min = max; max = t;
4915105197Ssam		}
4916105197Ssam	}
4917105197Ssam
4918105197Ssam	if (min == max) {
4919105197Ssam		if (key_checkspidup(saidx, min) != NULL) {
4920120585Ssam			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4921120585Ssam				__func__, min));
4922105197Ssam			return 0;
4923105197Ssam		}
4924105197Ssam
4925105197Ssam		count--; /* taking one cost. */
4926105197Ssam		newspi = min;
4927105197Ssam
4928105197Ssam	} else {
4929105197Ssam
4930105197Ssam		/* init SPI */
4931105197Ssam		newspi = 0;
4932105197Ssam
4933105197Ssam		/* when requesting to allocate spi ranged */
4934105197Ssam		while (count--) {
4935105197Ssam			/* generate pseudo-random SPI value ranged. */
4936105197Ssam			newspi = min + (key_random() % (max - min + 1));
4937105197Ssam
4938105197Ssam			if (key_checkspidup(saidx, newspi) == NULL)
4939105197Ssam				break;
4940105197Ssam		}
4941105197Ssam
4942105197Ssam		if (count == 0 || newspi == 0) {
4943120585Ssam			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4944120585Ssam				__func__));
4945105197Ssam			return 0;
4946105197Ssam		}
4947105197Ssam	}
4948105197Ssam
4949105197Ssam	/* statistics */
4950105197Ssam	keystat.getspi_count =
4951181803Sbz		(keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4952105197Ssam
4953105197Ssam	return newspi;
4954105197Ssam}
4955105197Ssam
4956105197Ssam/*
4957105197Ssam * SADB_UPDATE processing
4958105197Ssam * receive
4959105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4960105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
4961105197Ssam * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4962105197Ssam * and send
4963105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4964105197Ssam *       (identity(SD),) (sensitivity)>
4965105197Ssam * to the ikmpd.
4966105197Ssam *
4967105197Ssam * m will always be freed.
4968105197Ssam */
4969105197Ssamstatic int
4970105197Ssamkey_update(so, m, mhp)
4971105197Ssam	struct socket *so;
4972105197Ssam	struct mbuf *m;
4973105197Ssam	const struct sadb_msghdr *mhp;
4974105197Ssam{
4975105197Ssam	struct sadb_sa *sa0;
4976105197Ssam	struct sadb_address *src0, *dst0;
4977194062Svanhu#ifdef IPSEC_NAT_T
4978194062Svanhu	struct sadb_x_nat_t_type *type;
4979194513Sbz	struct sadb_x_nat_t_port *sport, *dport;
4980194062Svanhu	struct sadb_address *iaddr, *raddr;
4981194062Svanhu	struct sadb_x_nat_t_frag *frag;
4982194062Svanhu#endif
4983105197Ssam	struct secasindex saidx;
4984105197Ssam	struct secashead *sah;
4985105197Ssam	struct secasvar *sav;
4986105197Ssam	u_int16_t proto;
4987105197Ssam	u_int8_t mode;
4988105197Ssam	u_int32_t reqid;
4989105197Ssam	int error;
4990105197Ssam
4991120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
4992120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4993120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4994120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4995105197Ssam
4996105197Ssam	/* map satype to proto */
4997105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4998120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4999120585Ssam			__func__));
5000105197Ssam		return key_senderror(so, m, EINVAL);
5001105197Ssam	}
5002105197Ssam
5003105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5004105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5005105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5006105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5007105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5008105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5009105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5010105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5011105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5012105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5013105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5014120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5015120585Ssam			__func__));
5016105197Ssam		return key_senderror(so, m, EINVAL);
5017105197Ssam	}
5018105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5019105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5020105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5021120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5022120585Ssam			__func__));
5023105197Ssam		return key_senderror(so, m, EINVAL);
5024105197Ssam	}
5025105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5026105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5027105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5028105197Ssam	} else {
5029105197Ssam		mode = IPSEC_MODE_ANY;
5030105197Ssam		reqid = 0;
5031105197Ssam	}
5032105197Ssam	/* XXX boundary checking for other extensions */
5033105197Ssam
5034105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5035105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5036105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5037105197Ssam
5038105197Ssam	/* XXX boundary check against sa_len */
5039105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5040105197Ssam
5041194062Svanhu	/*
5042194062Svanhu	 * Make sure the port numbers are zero.
5043194062Svanhu	 * In case of NAT-T we will update them later if needed.
5044194062Svanhu	 */
5045194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5046194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5047194062Svanhu
5048194062Svanhu#ifdef IPSEC_NAT_T
5049194062Svanhu	/*
5050194062Svanhu	 * Handle NAT-T info if present.
5051194062Svanhu	 */
5052194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5053194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5054194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5055194062Svanhu
5056194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5057194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5058194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5059194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5060194062Svanhu			    __func__));
5061194062Svanhu			return key_senderror(so, m, EINVAL);
5062194062Svanhu		}
5063194062Svanhu
5064194062Svanhu		type = (struct sadb_x_nat_t_type *)
5065194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5066194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5067194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5068194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5069194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5070194062Svanhu	} else {
5071194062Svanhu		type = 0;
5072194513Sbz		sport = dport = 0;
5073194062Svanhu	}
5074194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5075194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5076194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5077194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5078194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5079194062Svanhu			    __func__));
5080194062Svanhu			return key_senderror(so, m, EINVAL);
5081194062Svanhu		}
5082194062Svanhu		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5083194062Svanhu		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5084194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5085194062Svanhu	} else {
5086194062Svanhu		iaddr = raddr = NULL;
5087194062Svanhu	}
5088194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5089194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5090194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5091194062Svanhu			    __func__));
5092194062Svanhu			return key_senderror(so, m, EINVAL);
5093194062Svanhu		}
5094194062Svanhu		frag = (struct sadb_x_nat_t_frag *)
5095194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5096194062Svanhu	} else {
5097194062Svanhu		frag = 0;
5098194062Svanhu	}
5099194062Svanhu#endif
5100194062Svanhu
5101105197Ssam	/* get a SA header */
5102105197Ssam	if ((sah = key_getsah(&saidx)) == NULL) {
5103120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
5104105197Ssam		return key_senderror(so, m, ENOENT);
5105105197Ssam	}
5106105197Ssam
5107105197Ssam	/* set spidx if there */
5108105197Ssam	/* XXX rewrite */
5109105197Ssam	error = key_setident(sah, m, mhp);
5110105197Ssam	if (error)
5111105197Ssam		return key_senderror(so, m, error);
5112105197Ssam
5113105197Ssam	/* find a SA with sequence number. */
5114105197Ssam#ifdef IPSEC_DOSEQCHECK
5115105197Ssam	if (mhp->msg->sadb_msg_seq != 0
5116105197Ssam	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
5117120585Ssam		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
5118120585Ssam			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
5119105197Ssam		return key_senderror(so, m, ENOENT);
5120105197Ssam	}
5121105197Ssam#else
5122120585Ssam	SAHTREE_LOCK();
5123120585Ssam	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5124120585Ssam	SAHTREE_UNLOCK();
5125120585Ssam	if (sav == NULL) {
5126120585Ssam		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
5127120585Ssam			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5128105197Ssam		return key_senderror(so, m, EINVAL);
5129105197Ssam	}
5130105197Ssam#endif
5131105197Ssam
5132105197Ssam	/* validity check */
5133105197Ssam	if (sav->sah->saidx.proto != proto) {
5134120585Ssam		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
5135120585Ssam			"(DB=%u param=%u)\n", __func__,
5136120585Ssam			sav->sah->saidx.proto, proto));
5137105197Ssam		return key_senderror(so, m, EINVAL);
5138105197Ssam	}
5139105197Ssam#ifdef IPSEC_DOSEQCHECK
5140105197Ssam	if (sav->spi != sa0->sadb_sa_spi) {
5141120585Ssam		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
5142120585Ssam		    __func__,
5143105197Ssam		    (u_int32_t)ntohl(sav->spi),
5144105197Ssam		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5145105197Ssam		return key_senderror(so, m, EINVAL);
5146105197Ssam	}
5147105197Ssam#endif
5148105197Ssam	if (sav->pid != mhp->msg->sadb_msg_pid) {
5149120585Ssam		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
5150120585Ssam		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
5151105197Ssam		return key_senderror(so, m, EINVAL);
5152105197Ssam	}
5153105197Ssam
5154105197Ssam	/* copy sav values */
5155105197Ssam	error = key_setsaval(sav, m, mhp);
5156105197Ssam	if (error) {
5157105197Ssam		KEY_FREESAV(&sav);
5158105197Ssam		return key_senderror(so, m, error);
5159105197Ssam	}
5160105197Ssam
5161105197Ssam	/* check SA values to be mature. */
5162105197Ssam	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5163105197Ssam		KEY_FREESAV(&sav);
5164105197Ssam		return key_senderror(so, m, 0);
5165105197Ssam	}
5166105197Ssam
5167194062Svanhu#ifdef IPSEC_NAT_T
5168194062Svanhu	/*
5169194062Svanhu	 * Handle more NAT-T info if present,
5170194062Svanhu	 * now that we have a sav to fill.
5171194062Svanhu	 */
5172194062Svanhu	if (type)
5173194062Svanhu		sav->natt_type = type->sadb_x_nat_t_type_type;
5174194062Svanhu
5175194513Sbz	if (sport)
5176194513Sbz		KEY_PORTTOSADDR(&sav->sah->saidx.src,
5177194513Sbz		    sport->sadb_x_nat_t_port_port);
5178194513Sbz	if (dport)
5179194513Sbz		KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5180194513Sbz		    dport->sadb_x_nat_t_port_port);
5181194513Sbz
5182194062Svanhu#if 0
5183194062Svanhu	/*
5184194062Svanhu	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5185194062Svanhu	 * We should actually check for a minimum MTU here, if we
5186194062Svanhu	 * want to support it in ip_output.
5187194062Svanhu	 */
5188194062Svanhu	if (frag)
5189194062Svanhu		sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5190194062Svanhu#endif
5191194062Svanhu#endif
5192194062Svanhu
5193105197Ssam    {
5194105197Ssam	struct mbuf *n;
5195105197Ssam
5196105197Ssam	/* set msg buf from mhp */
5197105197Ssam	n = key_getmsgbuf_x1(m, mhp);
5198105197Ssam	if (n == NULL) {
5199120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5200105197Ssam		return key_senderror(so, m, ENOBUFS);
5201105197Ssam	}
5202105197Ssam
5203105197Ssam	m_freem(m);
5204105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5205105197Ssam    }
5206105197Ssam}
5207105197Ssam
5208105197Ssam/*
5209105197Ssam * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5210105197Ssam * only called by key_update().
5211105197Ssam * OUT:
5212105197Ssam *	NULL	: not found
5213105197Ssam *	others	: found, pointer to a SA.
5214105197Ssam */
5215105197Ssam#ifdef IPSEC_DOSEQCHECK
5216105197Ssamstatic struct secasvar *
5217105197Ssamkey_getsavbyseq(sah, seq)
5218105197Ssam	struct secashead *sah;
5219105197Ssam	u_int32_t seq;
5220105197Ssam{
5221105197Ssam	struct secasvar *sav;
5222105197Ssam	u_int state;
5223105197Ssam
5224105197Ssam	state = SADB_SASTATE_LARVAL;
5225105197Ssam
5226105197Ssam	/* search SAD with sequence number ? */
5227105197Ssam	LIST_FOREACH(sav, &sah->savtree[state], chain) {
5228105197Ssam
5229120585Ssam		KEY_CHKSASTATE(state, sav->state, __func__);
5230105197Ssam
5231105197Ssam		if (sav->seq == seq) {
5232158767Spjd			sa_addref(sav);
5233105197Ssam			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5234120585Ssam				printf("DP %s cause refcnt++:%d SA:%p\n",
5235120585Ssam					__func__, sav->refcnt, sav));
5236105197Ssam			return sav;
5237105197Ssam		}
5238105197Ssam	}
5239105197Ssam
5240105197Ssam	return NULL;
5241105197Ssam}
5242105197Ssam#endif
5243105197Ssam
5244105197Ssam/*
5245105197Ssam * SADB_ADD processing
5246108533Sschweikh * add an entry to SA database, when received
5247105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5248105197Ssam *       key(AE), (identity(SD),) (sensitivity)>
5249105197Ssam * from the ikmpd,
5250105197Ssam * and send
5251105197Ssam *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5252105197Ssam *       (identity(SD),) (sensitivity)>
5253105197Ssam * to the ikmpd.
5254105197Ssam *
5255105197Ssam * IGNORE identity and sensitivity messages.
5256105197Ssam *
5257105197Ssam * m will always be freed.
5258105197Ssam */
5259105197Ssamstatic int
5260105197Ssamkey_add(so, m, mhp)
5261105197Ssam	struct socket *so;
5262105197Ssam	struct mbuf *m;
5263105197Ssam	const struct sadb_msghdr *mhp;
5264105197Ssam{
5265105197Ssam	struct sadb_sa *sa0;
5266105197Ssam	struct sadb_address *src0, *dst0;
5267194062Svanhu#ifdef IPSEC_NAT_T
5268194062Svanhu	struct sadb_x_nat_t_type *type;
5269194062Svanhu	struct sadb_address *iaddr, *raddr;
5270194062Svanhu	struct sadb_x_nat_t_frag *frag;
5271194062Svanhu#endif
5272105197Ssam	struct secasindex saidx;
5273105197Ssam	struct secashead *newsah;
5274105197Ssam	struct secasvar *newsav;
5275105197Ssam	u_int16_t proto;
5276105197Ssam	u_int8_t mode;
5277105197Ssam	u_int32_t reqid;
5278105197Ssam	int error;
5279105197Ssam
5280120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5281120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5282120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5283120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5284105197Ssam
5285105197Ssam	/* map satype to proto */
5286105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5287120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5288120585Ssam			__func__));
5289105197Ssam		return key_senderror(so, m, EINVAL);
5290105197Ssam	}
5291105197Ssam
5292105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5293105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5294105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5295105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5296105197Ssam	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5297105197Ssam	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5298105197Ssam	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5299105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5300105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5301105197Ssam	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5302105197Ssam	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5303120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5304120585Ssam			__func__));
5305105197Ssam		return key_senderror(so, m, EINVAL);
5306105197Ssam	}
5307105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5308105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5309105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5310105197Ssam		/* XXX need more */
5311120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5312120585Ssam			__func__));
5313105197Ssam		return key_senderror(so, m, EINVAL);
5314105197Ssam	}
5315105197Ssam	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5316105197Ssam		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5317105197Ssam		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5318105197Ssam	} else {
5319105197Ssam		mode = IPSEC_MODE_ANY;
5320105197Ssam		reqid = 0;
5321105197Ssam	}
5322105197Ssam
5323105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5324105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5325105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5326105197Ssam
5327105197Ssam	/* XXX boundary check against sa_len */
5328105197Ssam	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5329105197Ssam
5330194062Svanhu	/*
5331194062Svanhu	 * Make sure the port numbers are zero.
5332194062Svanhu	 * In case of NAT-T we will update them later if needed.
5333194062Svanhu	 */
5334194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5335194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5336194062Svanhu
5337194062Svanhu#ifdef IPSEC_NAT_T
5338194062Svanhu	/*
5339194062Svanhu	 * Handle NAT-T info if present.
5340194062Svanhu	 */
5341194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5342194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5343194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5344194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5345194062Svanhu
5346194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5347194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5348194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5349194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5350194062Svanhu			    __func__));
5351194062Svanhu			return key_senderror(so, m, EINVAL);
5352194062Svanhu		}
5353194062Svanhu
5354194062Svanhu		type = (struct sadb_x_nat_t_type *)
5355194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5356194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5357194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5358194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5359194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5360194062Svanhu
5361194062Svanhu		if (sport)
5362194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5363194062Svanhu			    sport->sadb_x_nat_t_port_port);
5364194062Svanhu		if (dport)
5365194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5366194062Svanhu			    dport->sadb_x_nat_t_port_port);
5367194062Svanhu	} else {
5368194062Svanhu		type = 0;
5369194062Svanhu	}
5370194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5371194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5372194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5373194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5374194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5375194062Svanhu			    __func__));
5376194062Svanhu			return key_senderror(so, m, EINVAL);
5377194062Svanhu		}
5378194062Svanhu		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5379194062Svanhu		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5380194062Svanhu		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5381194062Svanhu	} else {
5382194062Svanhu		iaddr = raddr = NULL;
5383194062Svanhu	}
5384194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5385194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5386194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5387194062Svanhu			    __func__));
5388194062Svanhu			return key_senderror(so, m, EINVAL);
5389194062Svanhu		}
5390194062Svanhu		frag = (struct sadb_x_nat_t_frag *)
5391194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5392194062Svanhu	} else {
5393194062Svanhu		frag = 0;
5394194062Svanhu	}
5395194062Svanhu#endif
5396194062Svanhu
5397105197Ssam	/* get a SA header */
5398105197Ssam	if ((newsah = key_getsah(&saidx)) == NULL) {
5399105197Ssam		/* create a new SA header */
5400105197Ssam		if ((newsah = key_newsah(&saidx)) == NULL) {
5401120585Ssam			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5402105197Ssam			return key_senderror(so, m, ENOBUFS);
5403105197Ssam		}
5404105197Ssam	}
5405105197Ssam
5406105197Ssam	/* set spidx if there */
5407105197Ssam	/* XXX rewrite */
5408105197Ssam	error = key_setident(newsah, m, mhp);
5409105197Ssam	if (error) {
5410105197Ssam		return key_senderror(so, m, error);
5411105197Ssam	}
5412105197Ssam
5413105197Ssam	/* create new SA entry. */
5414105197Ssam	/* We can create new SA only if SPI is differenct. */
5415120585Ssam	SAHTREE_LOCK();
5416120585Ssam	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5417120585Ssam	SAHTREE_UNLOCK();
5418120585Ssam	if (newsav != NULL) {
5419120585Ssam		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5420105197Ssam		return key_senderror(so, m, EEXIST);
5421105197Ssam	}
5422105197Ssam	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5423105197Ssam	if (newsav == NULL) {
5424105197Ssam		return key_senderror(so, m, error);
5425105197Ssam	}
5426105197Ssam
5427105197Ssam	/* check SA values to be mature. */
5428105197Ssam	if ((error = key_mature(newsav)) != 0) {
5429105197Ssam		KEY_FREESAV(&newsav);
5430105197Ssam		return key_senderror(so, m, error);
5431105197Ssam	}
5432105197Ssam
5433194062Svanhu#ifdef IPSEC_NAT_T
5434105197Ssam	/*
5435194062Svanhu	 * Handle more NAT-T info if present,
5436194062Svanhu	 * now that we have a sav to fill.
5437194062Svanhu	 */
5438194062Svanhu	if (type)
5439194062Svanhu		newsav->natt_type = type->sadb_x_nat_t_type_type;
5440194062Svanhu
5441194062Svanhu#if 0
5442194062Svanhu	/*
5443194062Svanhu	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5444194062Svanhu	 * We should actually check for a minimum MTU here, if we
5445194062Svanhu	 * want to support it in ip_output.
5446194062Svanhu	 */
5447194062Svanhu	if (frag)
5448194062Svanhu		newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5449194062Svanhu#endif
5450194062Svanhu#endif
5451194062Svanhu
5452194062Svanhu	/*
5453105197Ssam	 * don't call key_freesav() here, as we would like to keep the SA
5454105197Ssam	 * in the database on success.
5455105197Ssam	 */
5456105197Ssam
5457105197Ssam    {
5458105197Ssam	struct mbuf *n;
5459105197Ssam
5460105197Ssam	/* set msg buf from mhp */
5461105197Ssam	n = key_getmsgbuf_x1(m, mhp);
5462105197Ssam	if (n == NULL) {
5463120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5464105197Ssam		return key_senderror(so, m, ENOBUFS);
5465105197Ssam	}
5466105197Ssam
5467105197Ssam	m_freem(m);
5468105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5469105197Ssam    }
5470105197Ssam}
5471105197Ssam
5472105197Ssam/* m is retained */
5473105197Ssamstatic int
5474105197Ssamkey_setident(sah, m, mhp)
5475105197Ssam	struct secashead *sah;
5476105197Ssam	struct mbuf *m;
5477105197Ssam	const struct sadb_msghdr *mhp;
5478105197Ssam{
5479105197Ssam	const struct sadb_ident *idsrc, *iddst;
5480105197Ssam	int idsrclen, iddstlen;
5481105197Ssam
5482120585Ssam	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5483120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5484120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5485120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5486105197Ssam
5487105197Ssam	/* don't make buffer if not there */
5488105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5489105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5490105197Ssam		sah->idents = NULL;
5491105197Ssam		sah->identd = NULL;
5492105197Ssam		return 0;
5493105197Ssam	}
5494105197Ssam
5495105197Ssam	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5496105197Ssam	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5497120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5498105197Ssam		return EINVAL;
5499105197Ssam	}
5500105197Ssam
5501105197Ssam	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5502105197Ssam	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5503105197Ssam	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5504105197Ssam	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5505105197Ssam
5506105197Ssam	/* validity check */
5507105197Ssam	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5508120585Ssam		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5509105197Ssam		return EINVAL;
5510105197Ssam	}
5511105197Ssam
5512105197Ssam	switch (idsrc->sadb_ident_type) {
5513105197Ssam	case SADB_IDENTTYPE_PREFIX:
5514105197Ssam	case SADB_IDENTTYPE_FQDN:
5515105197Ssam	case SADB_IDENTTYPE_USERFQDN:
5516105197Ssam	default:
5517105197Ssam		/* XXX do nothing */
5518105197Ssam		sah->idents = NULL;
5519105197Ssam		sah->identd = NULL;
5520105197Ssam	 	return 0;
5521105197Ssam	}
5522105197Ssam
5523105197Ssam	/* make structure */
5524157123Sgnn	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5525105197Ssam	if (sah->idents == NULL) {
5526120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5527105197Ssam		return ENOBUFS;
5528105197Ssam	}
5529157123Sgnn	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5530105197Ssam	if (sah->identd == NULL) {
5531119643Ssam		free(sah->idents, M_IPSEC_MISC);
5532105197Ssam		sah->idents = NULL;
5533120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5534105197Ssam		return ENOBUFS;
5535105197Ssam	}
5536157123Sgnn	sah->idents->type = idsrc->sadb_ident_type;
5537157123Sgnn	sah->idents->id = idsrc->sadb_ident_id;
5538105197Ssam
5539157123Sgnn	sah->identd->type = iddst->sadb_ident_type;
5540157123Sgnn	sah->identd->id = iddst->sadb_ident_id;
5541157123Sgnn
5542105197Ssam	return 0;
5543105197Ssam}
5544105197Ssam
5545105197Ssam/*
5546105197Ssam * m will not be freed on return.
5547105197Ssam * it is caller's responsibility to free the result.
5548105197Ssam */
5549105197Ssamstatic struct mbuf *
5550105197Ssamkey_getmsgbuf_x1(m, mhp)
5551105197Ssam	struct mbuf *m;
5552105197Ssam	const struct sadb_msghdr *mhp;
5553105197Ssam{
5554105197Ssam	struct mbuf *n;
5555105197Ssam
5556120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5557120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5558120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5559105197Ssam
5560105197Ssam	/* create new sadb_msg to reply. */
5561105197Ssam	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5562105197Ssam	    SADB_EXT_SA, SADB_X_EXT_SA2,
5563105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5564105197Ssam	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5565105197Ssam	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5566105197Ssam	if (!n)
5567105197Ssam		return NULL;
5568105197Ssam
5569105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5570105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5571105197Ssam		if (n == NULL)
5572105197Ssam			return NULL;
5573105197Ssam	}
5574105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5575105197Ssam	mtod(n, struct sadb_msg *)->sadb_msg_len =
5576105197Ssam	    PFKEY_UNIT64(n->m_pkthdr.len);
5577105197Ssam
5578105197Ssam	return n;
5579105197Ssam}
5580105197Ssam
5581105197Ssamstatic int key_delete_all __P((struct socket *, struct mbuf *,
5582105197Ssam	const struct sadb_msghdr *, u_int16_t));
5583105197Ssam
5584105197Ssam/*
5585105197Ssam * SADB_DELETE processing
5586105197Ssam * receive
5587105197Ssam *   <base, SA(*), address(SD)>
5588105197Ssam * from the ikmpd, and set SADB_SASTATE_DEAD,
5589105197Ssam * and send,
5590105197Ssam *   <base, SA(*), address(SD)>
5591105197Ssam * to the ikmpd.
5592105197Ssam *
5593105197Ssam * m will always be freed.
5594105197Ssam */
5595105197Ssamstatic int
5596105197Ssamkey_delete(so, m, mhp)
5597105197Ssam	struct socket *so;
5598105197Ssam	struct mbuf *m;
5599105197Ssam	const struct sadb_msghdr *mhp;
5600105197Ssam{
5601105197Ssam	struct sadb_sa *sa0;
5602105197Ssam	struct sadb_address *src0, *dst0;
5603105197Ssam	struct secasindex saidx;
5604105197Ssam	struct secashead *sah;
5605105197Ssam	struct secasvar *sav = NULL;
5606105197Ssam	u_int16_t proto;
5607105197Ssam
5608120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5609120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5610120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5611120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5612105197Ssam
5613105197Ssam	/* map satype to proto */
5614105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5615120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5616120585Ssam			__func__));
5617105197Ssam		return key_senderror(so, m, EINVAL);
5618105197Ssam	}
5619105197Ssam
5620105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5621105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5622120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5623120585Ssam			__func__));
5624105197Ssam		return key_senderror(so, m, EINVAL);
5625105197Ssam	}
5626105197Ssam
5627105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5628105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5629120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5630120585Ssam			__func__));
5631105197Ssam		return key_senderror(so, m, EINVAL);
5632105197Ssam	}
5633105197Ssam
5634105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL) {
5635105197Ssam		/*
5636105197Ssam		 * Caller wants us to delete all non-LARVAL SAs
5637105197Ssam		 * that match the src/dst.  This is used during
5638105197Ssam		 * IKE INITIAL-CONTACT.
5639105197Ssam		 */
5640120585Ssam		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5641105197Ssam		return key_delete_all(so, m, mhp, proto);
5642105197Ssam	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5643120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5644120585Ssam			__func__));
5645105197Ssam		return key_senderror(so, m, EINVAL);
5646105197Ssam	}
5647105197Ssam
5648105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5649105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5650105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5651105197Ssam
5652105197Ssam	/* XXX boundary check against sa_len */
5653105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5654105197Ssam
5655194062Svanhu	/*
5656194062Svanhu	 * Make sure the port numbers are zero.
5657194062Svanhu	 * In case of NAT-T we will update them later if needed.
5658194062Svanhu	 */
5659194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5660194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5661194062Svanhu
5662194062Svanhu#ifdef IPSEC_NAT_T
5663194062Svanhu	/*
5664194062Svanhu	 * Handle NAT-T info if present.
5665194062Svanhu	 */
5666194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5667194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5668194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5669194062Svanhu
5670194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5671194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5672194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5673194062Svanhu			    __func__));
5674194062Svanhu			return key_senderror(so, m, EINVAL);
5675194062Svanhu		}
5676194062Svanhu
5677194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5678194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5679194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5680194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5681194062Svanhu
5682194062Svanhu		if (sport)
5683194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5684194062Svanhu			    sport->sadb_x_nat_t_port_port);
5685194062Svanhu		if (dport)
5686194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5687194062Svanhu			    dport->sadb_x_nat_t_port_port);
5688194062Svanhu	}
5689194062Svanhu#endif
5690194062Svanhu
5691105197Ssam	/* get a SA header */
5692120585Ssam	SAHTREE_LOCK();
5693181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5694105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5695105197Ssam			continue;
5696105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5697105197Ssam			continue;
5698105197Ssam
5699105197Ssam		/* get a SA with SPI. */
5700105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5701105197Ssam		if (sav)
5702105197Ssam			break;
5703105197Ssam	}
5704105197Ssam	if (sah == NULL) {
5705120585Ssam		SAHTREE_UNLOCK();
5706120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5707105197Ssam		return key_senderror(so, m, ENOENT);
5708105197Ssam	}
5709105197Ssam
5710105197Ssam	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5711120585Ssam	SAHTREE_UNLOCK();
5712105197Ssam	KEY_FREESAV(&sav);
5713105197Ssam
5714105197Ssam    {
5715105197Ssam	struct mbuf *n;
5716105197Ssam	struct sadb_msg *newmsg;
5717105197Ssam
5718105197Ssam	/* create new sadb_msg to reply. */
5719194062Svanhu	/* XXX-BZ NAT-T extensions? */
5720105197Ssam	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5721105197Ssam	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5722105197Ssam	if (!n)
5723105197Ssam		return key_senderror(so, m, ENOBUFS);
5724105197Ssam
5725105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5726105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5727105197Ssam		if (n == NULL)
5728105197Ssam			return key_senderror(so, m, ENOBUFS);
5729105197Ssam	}
5730105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5731105197Ssam	newmsg->sadb_msg_errno = 0;
5732105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5733105197Ssam
5734105197Ssam	m_freem(m);
5735105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5736105197Ssam    }
5737105197Ssam}
5738105197Ssam
5739105197Ssam/*
5740105197Ssam * delete all SAs for src/dst.  Called from key_delete().
5741105197Ssam */
5742105197Ssamstatic int
5743189004Srdivackykey_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5744189004Srdivacky    u_int16_t proto)
5745105197Ssam{
5746105197Ssam	struct sadb_address *src0, *dst0;
5747105197Ssam	struct secasindex saidx;
5748105197Ssam	struct secashead *sah;
5749105197Ssam	struct secasvar *sav, *nextsav;
5750105197Ssam	u_int stateidx, state;
5751105197Ssam
5752105197Ssam	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5753105197Ssam	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5754105197Ssam
5755105197Ssam	/* XXX boundary check against sa_len */
5756105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5757105197Ssam
5758194062Svanhu	/*
5759194062Svanhu	 * Make sure the port numbers are zero.
5760194062Svanhu	 * In case of NAT-T we will update them later if needed.
5761194062Svanhu	 */
5762194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5763194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5764194062Svanhu
5765194062Svanhu#ifdef IPSEC_NAT_T
5766194062Svanhu	/*
5767194062Svanhu	 * Handle NAT-T info if present.
5768194062Svanhu	 */
5769194062Svanhu
5770194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5771194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5772194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5773194062Svanhu
5774194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5775194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5776194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5777194062Svanhu			    __func__));
5778194062Svanhu			return key_senderror(so, m, EINVAL);
5779194062Svanhu		}
5780194062Svanhu
5781194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5782194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5783194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5784194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5785194062Svanhu
5786194062Svanhu		if (sport)
5787194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5788194062Svanhu			    sport->sadb_x_nat_t_port_port);
5789194062Svanhu		if (dport)
5790194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5791194062Svanhu			    dport->sadb_x_nat_t_port_port);
5792194062Svanhu	}
5793194062Svanhu#endif
5794194062Svanhu
5795120585Ssam	SAHTREE_LOCK();
5796181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5797105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5798105197Ssam			continue;
5799105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5800105197Ssam			continue;
5801105197Ssam
5802105197Ssam		/* Delete all non-LARVAL SAs. */
5803105197Ssam		for (stateidx = 0;
5804185348Szec		     stateidx < _ARRAYLEN(saorder_state_alive);
5805105197Ssam		     stateidx++) {
5806185348Szec			state = saorder_state_alive[stateidx];
5807105197Ssam			if (state == SADB_SASTATE_LARVAL)
5808105197Ssam				continue;
5809105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
5810105197Ssam			     sav != NULL; sav = nextsav) {
5811105197Ssam				nextsav = LIST_NEXT(sav, chain);
5812105197Ssam				/* sanity check */
5813105197Ssam				if (sav->state != state) {
5814120585Ssam					ipseclog((LOG_DEBUG, "%s: invalid "
5815120585Ssam						"sav->state (queue %d SA %d)\n",
5816120585Ssam						__func__, state, sav->state));
5817105197Ssam					continue;
5818105197Ssam				}
5819105197Ssam
5820105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5821105197Ssam				KEY_FREESAV(&sav);
5822105197Ssam			}
5823105197Ssam		}
5824105197Ssam	}
5825120585Ssam	SAHTREE_UNLOCK();
5826105197Ssam    {
5827105197Ssam	struct mbuf *n;
5828105197Ssam	struct sadb_msg *newmsg;
5829105197Ssam
5830105197Ssam	/* create new sadb_msg to reply. */
5831194062Svanhu	/* XXX-BZ NAT-T extensions? */
5832105197Ssam	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5833105197Ssam	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5834105197Ssam	if (!n)
5835105197Ssam		return key_senderror(so, m, ENOBUFS);
5836105197Ssam
5837105197Ssam	if (n->m_len < sizeof(struct sadb_msg)) {
5838105197Ssam		n = m_pullup(n, sizeof(struct sadb_msg));
5839105197Ssam		if (n == NULL)
5840105197Ssam			return key_senderror(so, m, ENOBUFS);
5841105197Ssam	}
5842105197Ssam	newmsg = mtod(n, struct sadb_msg *);
5843105197Ssam	newmsg->sadb_msg_errno = 0;
5844105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5845105197Ssam
5846105197Ssam	m_freem(m);
5847105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5848105197Ssam    }
5849105197Ssam}
5850105197Ssam
5851105197Ssam/*
5852105197Ssam * SADB_GET processing
5853105197Ssam * receive
5854105197Ssam *   <base, SA(*), address(SD)>
5855105197Ssam * from the ikmpd, and get a SP and a SA to respond,
5856105197Ssam * and send,
5857105197Ssam *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5858105197Ssam *       (identity(SD),) (sensitivity)>
5859105197Ssam * to the ikmpd.
5860105197Ssam *
5861105197Ssam * m will always be freed.
5862105197Ssam */
5863105197Ssamstatic int
5864105197Ssamkey_get(so, m, mhp)
5865105197Ssam	struct socket *so;
5866105197Ssam	struct mbuf *m;
5867105197Ssam	const struct sadb_msghdr *mhp;
5868105197Ssam{
5869105197Ssam	struct sadb_sa *sa0;
5870105197Ssam	struct sadb_address *src0, *dst0;
5871105197Ssam	struct secasindex saidx;
5872105197Ssam	struct secashead *sah;
5873105197Ssam	struct secasvar *sav = NULL;
5874105197Ssam	u_int16_t proto;
5875105197Ssam
5876120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
5877120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5878120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5879120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5880105197Ssam
5881105197Ssam	/* map satype to proto */
5882105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5883120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5884120585Ssam			__func__));
5885105197Ssam		return key_senderror(so, m, EINVAL);
5886105197Ssam	}
5887105197Ssam
5888105197Ssam	if (mhp->ext[SADB_EXT_SA] == NULL ||
5889105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5890105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5891120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5892120585Ssam			__func__));
5893105197Ssam		return key_senderror(so, m, EINVAL);
5894105197Ssam	}
5895105197Ssam	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5896105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5897105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5898120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5899120585Ssam			__func__));
5900105197Ssam		return key_senderror(so, m, EINVAL);
5901105197Ssam	}
5902105197Ssam
5903105197Ssam	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5904105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5905105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5906105197Ssam
5907105197Ssam	/* XXX boundary check against sa_len */
5908105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5909105197Ssam
5910194062Svanhu	/*
5911194062Svanhu	 * Make sure the port numbers are zero.
5912194062Svanhu	 * In case of NAT-T we will update them later if needed.
5913194062Svanhu	 */
5914194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
5915194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
5916194062Svanhu
5917194062Svanhu#ifdef IPSEC_NAT_T
5918194062Svanhu	/*
5919194062Svanhu	 * Handle NAT-T info if present.
5920194062Svanhu	 */
5921194062Svanhu
5922194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5923194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5924194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
5925194062Svanhu
5926194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5927194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5928194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5929194062Svanhu			    __func__));
5930194062Svanhu			return key_senderror(so, m, EINVAL);
5931194062Svanhu		}
5932194062Svanhu
5933194062Svanhu		sport = (struct sadb_x_nat_t_port *)
5934194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5935194062Svanhu		dport = (struct sadb_x_nat_t_port *)
5936194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5937194062Svanhu
5938194062Svanhu		if (sport)
5939194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
5940194062Svanhu			    sport->sadb_x_nat_t_port_port);
5941194062Svanhu		if (dport)
5942194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
5943194062Svanhu			    dport->sadb_x_nat_t_port_port);
5944194062Svanhu	}
5945194062Svanhu#endif
5946194062Svanhu
5947105197Ssam	/* get a SA header */
5948120585Ssam	SAHTREE_LOCK();
5949181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
5950105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
5951105197Ssam			continue;
5952105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5953105197Ssam			continue;
5954105197Ssam
5955105197Ssam		/* get a SA with SPI. */
5956105197Ssam		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5957105197Ssam		if (sav)
5958105197Ssam			break;
5959105197Ssam	}
5960120585Ssam	SAHTREE_UNLOCK();
5961105197Ssam	if (sah == NULL) {
5962120585Ssam		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5963105197Ssam		return key_senderror(so, m, ENOENT);
5964105197Ssam	}
5965105197Ssam
5966105197Ssam    {
5967105197Ssam	struct mbuf *n;
5968105197Ssam	u_int8_t satype;
5969105197Ssam
5970105197Ssam	/* map proto to satype */
5971105197Ssam	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5972120585Ssam		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5973120585Ssam			__func__));
5974105197Ssam		return key_senderror(so, m, EINVAL);
5975105197Ssam	}
5976105197Ssam
5977105197Ssam	/* create new sadb_msg to reply. */
5978105197Ssam	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5979105197Ssam	    mhp->msg->sadb_msg_pid);
5980105197Ssam	if (!n)
5981105197Ssam		return key_senderror(so, m, ENOBUFS);
5982105197Ssam
5983105197Ssam	m_freem(m);
5984105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5985105197Ssam    }
5986105197Ssam}
5987105197Ssam
5988105197Ssam/* XXX make it sysctl-configurable? */
5989105197Ssamstatic void
5990105197Ssamkey_getcomb_setlifetime(comb)
5991105197Ssam	struct sadb_comb *comb;
5992105197Ssam{
5993105197Ssam
5994105197Ssam	comb->sadb_comb_soft_allocations = 1;
5995105197Ssam	comb->sadb_comb_hard_allocations = 1;
5996105197Ssam	comb->sadb_comb_soft_bytes = 0;
5997105197Ssam	comb->sadb_comb_hard_bytes = 0;
5998105197Ssam	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5999105197Ssam	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
6000105197Ssam	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
6001105197Ssam	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
6002105197Ssam}
6003105197Ssam
6004105197Ssam/*
6005105197Ssam * XXX reorder combinations by preference
6006105197Ssam * XXX no idea if the user wants ESP authentication or not
6007105197Ssam */
6008105197Ssamstatic struct mbuf *
6009105197Ssamkey_getcomb_esp()
6010105197Ssam{
6011105197Ssam	struct sadb_comb *comb;
6012105197Ssam	struct enc_xform *algo;
6013105197Ssam	struct mbuf *result = NULL, *m, *n;
6014105197Ssam	int encmin;
6015105197Ssam	int i, off, o;
6016105197Ssam	int totlen;
6017105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6018105197Ssam
6019105197Ssam	m = NULL;
6020105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6021105197Ssam		algo = esp_algorithm_lookup(i);
6022105197Ssam		if (algo == NULL)
6023105197Ssam			continue;
6024105197Ssam
6025105197Ssam		/* discard algorithms with key size smaller than system min */
6026181803Sbz		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6027105197Ssam			continue;
6028181803Sbz		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6029181803Sbz			encmin = V_ipsec_esp_keymin;
6030105197Ssam		else
6031105197Ssam			encmin = _BITS(algo->minkey);
6032105197Ssam
6033181803Sbz		if (V_ipsec_esp_auth)
6034105197Ssam			m = key_getcomb_ah();
6035105197Ssam		else {
6036120585Ssam			IPSEC_ASSERT(l <= MLEN,
6037120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6038111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
6039105197Ssam			if (m) {
6040105197Ssam				M_ALIGN(m, l);
6041105197Ssam				m->m_len = l;
6042105197Ssam				m->m_next = NULL;
6043105197Ssam				bzero(mtod(m, caddr_t), m->m_len);
6044105197Ssam			}
6045105197Ssam		}
6046105197Ssam		if (!m)
6047105197Ssam			goto fail;
6048105197Ssam
6049105197Ssam		totlen = 0;
6050105197Ssam		for (n = m; n; n = n->m_next)
6051105197Ssam			totlen += n->m_len;
6052120585Ssam		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6053105197Ssam
6054105197Ssam		for (off = 0; off < totlen; off += l) {
6055105197Ssam			n = m_pulldown(m, off, l, &o);
6056105197Ssam			if (!n) {
6057105197Ssam				/* m is already freed */
6058105197Ssam				goto fail;
6059105197Ssam			}
6060105197Ssam			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6061105197Ssam			bzero(comb, sizeof(*comb));
6062105197Ssam			key_getcomb_setlifetime(comb);
6063105197Ssam			comb->sadb_comb_encrypt = i;
6064105197Ssam			comb->sadb_comb_encrypt_minbits = encmin;
6065105197Ssam			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6066105197Ssam		}
6067105197Ssam
6068105197Ssam		if (!result)
6069105197Ssam			result = m;
6070105197Ssam		else
6071105197Ssam			m_cat(result, m);
6072105197Ssam	}
6073105197Ssam
6074105197Ssam	return result;
6075105197Ssam
6076105197Ssam fail:
6077105197Ssam	if (result)
6078105197Ssam		m_freem(result);
6079105197Ssam	return NULL;
6080105197Ssam}
6081105197Ssam
6082105197Ssamstatic void
6083105197Ssamkey_getsizes_ah(
6084105197Ssam	const struct auth_hash *ah,
6085105197Ssam	int alg,
6086105197Ssam	u_int16_t* min,
6087105197Ssam	u_int16_t* max)
6088105197Ssam{
6089183550Szec
6090105197Ssam	*min = *max = ah->keysize;
6091105197Ssam	if (ah->keysize == 0) {
6092105197Ssam		/*
6093105197Ssam		 * Transform takes arbitrary key size but algorithm
6094105197Ssam		 * key size is restricted.  Enforce this here.
6095105197Ssam		 */
6096105197Ssam		switch (alg) {
6097105197Ssam		case SADB_X_AALG_MD5:	*min = *max = 16; break;
6098105197Ssam		case SADB_X_AALG_SHA:	*min = *max = 20; break;
6099105197Ssam		case SADB_X_AALG_NULL:	*min = 1; *max = 256; 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 */
6125105197Ssam		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
6126105197Ssam			continue;
6127105197Ssam#endif
6128105197Ssam		algo = ah_algorithm_lookup(i);
6129105197Ssam		if (!algo)
6130105197Ssam			continue;
6131105197Ssam		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6132105197Ssam		/* discard algorithms with key size smaller than system min */
6133181803Sbz		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6134105197Ssam			continue;
6135105197Ssam
6136105197Ssam		if (!m) {
6137120585Ssam			IPSEC_ASSERT(l <= MLEN,
6138120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6139111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
6140105197Ssam			if (m) {
6141105197Ssam				M_ALIGN(m, l);
6142105197Ssam				m->m_len = l;
6143105197Ssam				m->m_next = NULL;
6144105197Ssam			}
6145105197Ssam		} else
6146111119Simp			M_PREPEND(m, l, M_DONTWAIT);
6147105197Ssam		if (!m)
6148105197Ssam			return NULL;
6149105197Ssam
6150105197Ssam		comb = mtod(m, struct sadb_comb *);
6151105197Ssam		bzero(comb, sizeof(*comb));
6152105197Ssam		key_getcomb_setlifetime(comb);
6153105197Ssam		comb->sadb_comb_auth = i;
6154105197Ssam		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6155105197Ssam		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6156105197Ssam	}
6157105197Ssam
6158105197Ssam	return m;
6159105197Ssam}
6160105197Ssam
6161105197Ssam/*
6162105197Ssam * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6163105197Ssam * XXX reorder combinations by preference
6164105197Ssam */
6165105197Ssamstatic struct mbuf *
6166105197Ssamkey_getcomb_ipcomp()
6167105197Ssam{
6168105197Ssam	struct sadb_comb *comb;
6169105197Ssam	struct comp_algo *algo;
6170105197Ssam	struct mbuf *m;
6171105197Ssam	int i;
6172105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6173105197Ssam
6174105197Ssam	m = NULL;
6175105197Ssam	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6176105197Ssam		algo = ipcomp_algorithm_lookup(i);
6177105197Ssam		if (!algo)
6178105197Ssam			continue;
6179105197Ssam
6180105197Ssam		if (!m) {
6181120585Ssam			IPSEC_ASSERT(l <= MLEN,
6182120585Ssam				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6183111119Simp			MGET(m, M_DONTWAIT, MT_DATA);
6184105197Ssam			if (m) {
6185105197Ssam				M_ALIGN(m, l);
6186105197Ssam				m->m_len = l;
6187105197Ssam				m->m_next = NULL;
6188105197Ssam			}
6189105197Ssam		} else
6190111119Simp			M_PREPEND(m, l, M_DONTWAIT);
6191105197Ssam		if (!m)
6192105197Ssam			return NULL;
6193105197Ssam
6194105197Ssam		comb = mtod(m, struct sadb_comb *);
6195105197Ssam		bzero(comb, sizeof(*comb));
6196105197Ssam		key_getcomb_setlifetime(comb);
6197105197Ssam		comb->sadb_comb_encrypt = i;
6198105197Ssam		/* what should we set into sadb_comb_*_{min,max}bits? */
6199105197Ssam	}
6200105197Ssam
6201105197Ssam	return m;
6202105197Ssam}
6203105197Ssam
6204105197Ssam/*
6205105197Ssam * XXX no way to pass mode (transport/tunnel) to userland
6206105197Ssam * XXX replay checking?
6207105197Ssam * XXX sysctl interface to ipsec_{ah,esp}_keymin
6208105197Ssam */
6209105197Ssamstatic struct mbuf *
6210105197Ssamkey_getprop(saidx)
6211105197Ssam	const struct secasindex *saidx;
6212105197Ssam{
6213105197Ssam	struct sadb_prop *prop;
6214105197Ssam	struct mbuf *m, *n;
6215105197Ssam	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6216105197Ssam	int totlen;
6217105197Ssam
6218105197Ssam	switch (saidx->proto)  {
6219105197Ssam	case IPPROTO_ESP:
6220105197Ssam		m = key_getcomb_esp();
6221105197Ssam		break;
6222105197Ssam	case IPPROTO_AH:
6223105197Ssam		m = key_getcomb_ah();
6224105197Ssam		break;
6225105197Ssam	case IPPROTO_IPCOMP:
6226105197Ssam		m = key_getcomb_ipcomp();
6227105197Ssam		break;
6228105197Ssam	default:
6229105197Ssam		return NULL;
6230105197Ssam	}
6231105197Ssam
6232105197Ssam	if (!m)
6233105197Ssam		return NULL;
6234111119Simp	M_PREPEND(m, l, M_DONTWAIT);
6235105197Ssam	if (!m)
6236105197Ssam		return NULL;
6237105197Ssam
6238105197Ssam	totlen = 0;
6239105197Ssam	for (n = m; n; n = n->m_next)
6240105197Ssam		totlen += n->m_len;
6241105197Ssam
6242105197Ssam	prop = mtod(m, struct sadb_prop *);
6243105197Ssam	bzero(prop, sizeof(*prop));
6244105197Ssam	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6245105197Ssam	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6246105197Ssam	prop->sadb_prop_replay = 32;	/* XXX */
6247105197Ssam
6248105197Ssam	return m;
6249105197Ssam}
6250105197Ssam
6251105197Ssam/*
6252105197Ssam * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6253105197Ssam * send
6254105197Ssam *   <base, SA, address(SD), (address(P)), x_policy,
6255105197Ssam *       (identity(SD),) (sensitivity,) proposal>
6256105197Ssam * to KMD, and expect to receive
6257105197Ssam *   <base> with SADB_ACQUIRE if error occured,
6258105197Ssam * or
6259105197Ssam *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6260105197Ssam * from KMD by PF_KEY.
6261105197Ssam *
6262105197Ssam * XXX x_policy is outside of RFC2367 (KAME extension).
6263105197Ssam * XXX sensitivity is not supported.
6264105197Ssam * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6265105197Ssam * see comment for key_getcomb_ipcomp().
6266105197Ssam *
6267105197Ssam * OUT:
6268105197Ssam *    0     : succeed
6269105197Ssam *    others: error number
6270105197Ssam */
6271105197Ssamstatic int
6272105197Ssamkey_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6273105197Ssam{
6274105197Ssam	struct mbuf *result = NULL, *m;
6275105197Ssam	struct secacq *newacq;
6276105197Ssam	u_int8_t satype;
6277105197Ssam	int error = -1;
6278105197Ssam	u_int32_t seq;
6279105197Ssam
6280120585Ssam	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6281105197Ssam	satype = key_proto2satype(saidx->proto);
6282120585Ssam	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6283105197Ssam
6284105197Ssam	/*
6285105197Ssam	 * We never do anything about acquirng SA.  There is anather
6286105197Ssam	 * solution that kernel blocks to send SADB_ACQUIRE message until
6287105197Ssam	 * getting something message from IKEd.  In later case, to be
6288105197Ssam	 * managed with ACQUIRING list.
6289105197Ssam	 */
6290108533Sschweikh	/* Get an entry to check whether sending message or not. */
6291105197Ssam	if ((newacq = key_getacq(saidx)) != NULL) {
6292181803Sbz		if (V_key_blockacq_count < newacq->count) {
6293105197Ssam			/* reset counter and do send message. */
6294105197Ssam			newacq->count = 0;
6295105197Ssam		} else {
6296105197Ssam			/* increment counter and do nothing. */
6297105197Ssam			newacq->count++;
6298105197Ssam			return 0;
6299105197Ssam		}
6300105197Ssam	} else {
6301105197Ssam		/* make new entry for blocking to send SADB_ACQUIRE. */
6302105197Ssam		if ((newacq = key_newacq(saidx)) == NULL)
6303105197Ssam			return ENOBUFS;
6304105197Ssam	}
6305105197Ssam
6306105197Ssam
6307105197Ssam	seq = newacq->seq;
6308105197Ssam	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6309105197Ssam	if (!m) {
6310105197Ssam		error = ENOBUFS;
6311105197Ssam		goto fail;
6312105197Ssam	}
6313105197Ssam	result = m;
6314105197Ssam
6315194062Svanhu	/*
6316194062Svanhu	 * No SADB_X_EXT_NAT_T_* here: we do not know
6317194062Svanhu	 * anything related to NAT-T at this time.
6318194062Svanhu	 */
6319194062Svanhu
6320105197Ssam	/* set sadb_address for saidx's. */
6321105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6322105197Ssam	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6323105197Ssam	if (!m) {
6324105197Ssam		error = ENOBUFS;
6325105197Ssam		goto fail;
6326105197Ssam	}
6327105197Ssam	m_cat(result, m);
6328105197Ssam
6329105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6330105197Ssam	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6331105197Ssam	if (!m) {
6332105197Ssam		error = ENOBUFS;
6333105197Ssam		goto fail;
6334105197Ssam	}
6335105197Ssam	m_cat(result, m);
6336105197Ssam
6337105197Ssam	/* XXX proxy address (optional) */
6338105197Ssam
6339105197Ssam	/* set sadb_x_policy */
6340105197Ssam	if (sp) {
6341105197Ssam		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6342105197Ssam		if (!m) {
6343105197Ssam			error = ENOBUFS;
6344105197Ssam			goto fail;
6345105197Ssam		}
6346105197Ssam		m_cat(result, m);
6347105197Ssam	}
6348105197Ssam
6349105197Ssam	/* XXX identity (optional) */
6350105197Ssam#if 0
6351105197Ssam	if (idexttype && fqdn) {
6352105197Ssam		/* create identity extension (FQDN) */
6353105197Ssam		struct sadb_ident *id;
6354105197Ssam		int fqdnlen;
6355105197Ssam
6356105197Ssam		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
6357105197Ssam		id = (struct sadb_ident *)p;
6358105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6359105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6360105197Ssam		id->sadb_ident_exttype = idexttype;
6361105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6362105197Ssam		bcopy(fqdn, id + 1, fqdnlen);
6363105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6364105197Ssam	}
6365105197Ssam
6366105197Ssam	if (idexttype) {
6367105197Ssam		/* create identity extension (USERFQDN) */
6368105197Ssam		struct sadb_ident *id;
6369105197Ssam		int userfqdnlen;
6370105197Ssam
6371105197Ssam		if (userfqdn) {
6372105197Ssam			/* +1 for terminating-NUL */
6373105197Ssam			userfqdnlen = strlen(userfqdn) + 1;
6374105197Ssam		} else
6375105197Ssam			userfqdnlen = 0;
6376105197Ssam		id = (struct sadb_ident *)p;
6377105197Ssam		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6378105197Ssam		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6379105197Ssam		id->sadb_ident_exttype = idexttype;
6380105197Ssam		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6381105197Ssam		/* XXX is it correct? */
6382105197Ssam		if (curproc && curproc->p_cred)
6383105197Ssam			id->sadb_ident_id = curproc->p_cred->p_ruid;
6384105197Ssam		if (userfqdn && userfqdnlen)
6385105197Ssam			bcopy(userfqdn, id + 1, userfqdnlen);
6386105197Ssam		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6387105197Ssam	}
6388105197Ssam#endif
6389105197Ssam
6390105197Ssam	/* XXX sensitivity (optional) */
6391105197Ssam
6392105197Ssam	/* create proposal/combination extension */
6393105197Ssam	m = key_getprop(saidx);
6394105197Ssam#if 0
6395105197Ssam	/*
6396105197Ssam	 * spec conformant: always attach proposal/combination extension,
6397105197Ssam	 * the problem is that we have no way to attach it for ipcomp,
6398105197Ssam	 * due to the way sadb_comb is declared in RFC2367.
6399105197Ssam	 */
6400105197Ssam	if (!m) {
6401105197Ssam		error = ENOBUFS;
6402105197Ssam		goto fail;
6403105197Ssam	}
6404105197Ssam	m_cat(result, m);
6405105197Ssam#else
6406105197Ssam	/*
6407105197Ssam	 * outside of spec; make proposal/combination extension optional.
6408105197Ssam	 */
6409105197Ssam	if (m)
6410105197Ssam		m_cat(result, m);
6411105197Ssam#endif
6412105197Ssam
6413105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
6414105197Ssam		error = EINVAL;
6415105197Ssam		goto fail;
6416105197Ssam	}
6417105197Ssam
6418105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
6419105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
6420105197Ssam		if (result == NULL) {
6421105197Ssam			error = ENOBUFS;
6422105197Ssam			goto fail;
6423105197Ssam		}
6424105197Ssam	}
6425105197Ssam
6426105197Ssam	result->m_pkthdr.len = 0;
6427105197Ssam	for (m = result; m; m = m->m_next)
6428105197Ssam		result->m_pkthdr.len += m->m_len;
6429105197Ssam
6430105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
6431105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
6432105197Ssam
6433105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6434105197Ssam
6435105197Ssam fail:
6436105197Ssam	if (result)
6437105197Ssam		m_freem(result);
6438105197Ssam	return error;
6439105197Ssam}
6440105197Ssam
6441105197Ssamstatic struct secacq *
6442105197Ssamkey_newacq(const struct secasindex *saidx)
6443105197Ssam{
6444105197Ssam	struct secacq *newacq;
6445105197Ssam
6446105197Ssam	/* get new entry */
6447119643Ssam	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6448105197Ssam	if (newacq == NULL) {
6449120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6450105197Ssam		return NULL;
6451105197Ssam	}
6452105197Ssam
6453105197Ssam	/* copy secindex */
6454105197Ssam	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6455181803Sbz	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6456105197Ssam	newacq->created = time_second;
6457105197Ssam	newacq->count = 0;
6458105197Ssam
6459119643Ssam	/* add to acqtree */
6460120585Ssam	ACQ_LOCK();
6461181803Sbz	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6462120585Ssam	ACQ_UNLOCK();
6463119643Ssam
6464105197Ssam	return newacq;
6465105197Ssam}
6466105197Ssam
6467105197Ssamstatic struct secacq *
6468105197Ssamkey_getacq(const struct secasindex *saidx)
6469105197Ssam{
6470105197Ssam	struct secacq *acq;
6471105197Ssam
6472120585Ssam	ACQ_LOCK();
6473181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
6474105197Ssam		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6475119643Ssam			break;
6476105197Ssam	}
6477120585Ssam	ACQ_UNLOCK();
6478105197Ssam
6479119643Ssam	return acq;
6480105197Ssam}
6481105197Ssam
6482105197Ssamstatic struct secacq *
6483105197Ssamkey_getacqbyseq(seq)
6484105197Ssam	u_int32_t seq;
6485105197Ssam{
6486105197Ssam	struct secacq *acq;
6487105197Ssam
6488120585Ssam	ACQ_LOCK();
6489181803Sbz	LIST_FOREACH(acq, &V_acqtree, chain) {
6490105197Ssam		if (acq->seq == seq)
6491119643Ssam			break;
6492105197Ssam	}
6493120585Ssam	ACQ_UNLOCK();
6494105197Ssam
6495119643Ssam	return acq;
6496105197Ssam}
6497105197Ssam
6498105197Ssamstatic struct secspacq *
6499105197Ssamkey_newspacq(spidx)
6500105197Ssam	struct secpolicyindex *spidx;
6501105197Ssam{
6502105197Ssam	struct secspacq *acq;
6503105197Ssam
6504105197Ssam	/* get new entry */
6505119643Ssam	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6506105197Ssam	if (acq == NULL) {
6507120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6508105197Ssam		return NULL;
6509105197Ssam	}
6510105197Ssam
6511105197Ssam	/* copy secindex */
6512105197Ssam	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6513105197Ssam	acq->created = time_second;
6514105197Ssam	acq->count = 0;
6515105197Ssam
6516119643Ssam	/* add to spacqtree */
6517120585Ssam	SPACQ_LOCK();
6518181803Sbz	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6519120585Ssam	SPACQ_UNLOCK();
6520119643Ssam
6521105197Ssam	return acq;
6522105197Ssam}
6523105197Ssam
6524105197Ssamstatic struct secspacq *
6525105197Ssamkey_getspacq(spidx)
6526105197Ssam	struct secpolicyindex *spidx;
6527105197Ssam{
6528105197Ssam	struct secspacq *acq;
6529105197Ssam
6530120585Ssam	SPACQ_LOCK();
6531181803Sbz	LIST_FOREACH(acq, &V_spacqtree, chain) {
6532119643Ssam		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6533119643Ssam			/* NB: return holding spacq_lock */
6534105197Ssam			return acq;
6535119643Ssam		}
6536105197Ssam	}
6537120585Ssam	SPACQ_UNLOCK();
6538105197Ssam
6539105197Ssam	return NULL;
6540105197Ssam}
6541105197Ssam
6542105197Ssam/*
6543105197Ssam * SADB_ACQUIRE processing,
6544105197Ssam * in first situation, is receiving
6545105197Ssam *   <base>
6546105197Ssam * from the ikmpd, and clear sequence of its secasvar entry.
6547105197Ssam *
6548105197Ssam * In second situation, is receiving
6549105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6550105197Ssam * from a user land process, and return
6551105197Ssam *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6552105197Ssam * to the socket.
6553105197Ssam *
6554105197Ssam * m will always be freed.
6555105197Ssam */
6556105197Ssamstatic int
6557105197Ssamkey_acquire2(so, m, mhp)
6558105197Ssam	struct socket *so;
6559105197Ssam	struct mbuf *m;
6560105197Ssam	const struct sadb_msghdr *mhp;
6561105197Ssam{
6562105197Ssam	const struct sadb_address *src0, *dst0;
6563105197Ssam	struct secasindex saidx;
6564105197Ssam	struct secashead *sah;
6565105197Ssam	u_int16_t proto;
6566105197Ssam	int error;
6567105197Ssam
6568120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6569120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6570120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6571120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6572105197Ssam
6573105197Ssam	/*
6574105197Ssam	 * Error message from KMd.
6575105197Ssam	 * We assume that if error was occured in IKEd, the length of PFKEY
6576105197Ssam	 * message is equal to the size of sadb_msg structure.
6577105197Ssam	 * We do not raise error even if error occured in this function.
6578105197Ssam	 */
6579105197Ssam	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6580105197Ssam		struct secacq *acq;
6581105197Ssam
6582105197Ssam		/* check sequence number */
6583105197Ssam		if (mhp->msg->sadb_msg_seq == 0) {
6584120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6585120585Ssam				"number.\n", __func__));
6586105197Ssam			m_freem(m);
6587105197Ssam			return 0;
6588105197Ssam		}
6589105197Ssam
6590105197Ssam		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6591105197Ssam			/*
6592105197Ssam			 * the specified larval SA is already gone, or we got
6593105197Ssam			 * a bogus sequence number.  we can silently ignore it.
6594105197Ssam			 */
6595105197Ssam			m_freem(m);
6596105197Ssam			return 0;
6597105197Ssam		}
6598105197Ssam
6599105197Ssam		/* reset acq counter in order to deletion by timehander. */
6600105197Ssam		acq->created = time_second;
6601105197Ssam		acq->count = 0;
6602105197Ssam		m_freem(m);
6603105197Ssam		return 0;
6604105197Ssam	}
6605105197Ssam
6606105197Ssam	/*
6607105197Ssam	 * This message is from user land.
6608105197Ssam	 */
6609105197Ssam
6610105197Ssam	/* map satype to proto */
6611105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6612120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6613120585Ssam			__func__));
6614105197Ssam		return key_senderror(so, m, EINVAL);
6615105197Ssam	}
6616105197Ssam
6617105197Ssam	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6618105197Ssam	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6619105197Ssam	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6620105197Ssam		/* error */
6621120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6622120585Ssam			__func__));
6623105197Ssam		return key_senderror(so, m, EINVAL);
6624105197Ssam	}
6625105197Ssam	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6626105197Ssam	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6627105197Ssam	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6628105197Ssam		/* error */
6629120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6630120585Ssam			__func__));
6631105197Ssam		return key_senderror(so, m, EINVAL);
6632105197Ssam	}
6633105197Ssam
6634105197Ssam	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6635105197Ssam	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6636105197Ssam
6637105197Ssam	/* XXX boundary check against sa_len */
6638105197Ssam	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6639105197Ssam
6640194062Svanhu	/*
6641194062Svanhu	 * Make sure the port numbers are zero.
6642194062Svanhu	 * In case of NAT-T we will update them later if needed.
6643194062Svanhu	 */
6644194062Svanhu	KEY_PORTTOSADDR(&saidx.src, 0);
6645194062Svanhu	KEY_PORTTOSADDR(&saidx.dst, 0);
6646194062Svanhu
6647194062Svanhu#ifndef IPSEC_NAT_T
6648194062Svanhu	/*
6649194062Svanhu	 * Handle NAT-T info if present.
6650194062Svanhu	 */
6651194062Svanhu
6652194062Svanhu	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6653194062Svanhu	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6654194062Svanhu		struct sadb_x_nat_t_port *sport, *dport;
6655194062Svanhu
6656194062Svanhu		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6657194062Svanhu		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6658194062Svanhu			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6659194062Svanhu			    __func__));
6660194062Svanhu			return key_senderror(so, m, EINVAL);
6661194062Svanhu		}
6662194062Svanhu
6663194062Svanhu		sport = (struct sadb_x_nat_t_port *)
6664194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6665194062Svanhu		dport = (struct sadb_x_nat_t_port *)
6666194062Svanhu		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6667194062Svanhu
6668194062Svanhu		if (sport)
6669194062Svanhu			KEY_PORTTOSADDR(&saidx.src,
6670194062Svanhu			    sport->sadb_x_nat_t_port_port);
6671194062Svanhu		if (dport)
6672194062Svanhu			KEY_PORTTOSADDR(&saidx.dst,
6673194062Svanhu			    dport->sadb_x_nat_t_port_port);
6674194062Svanhu	}
6675194062Svanhu#endif
6676194062Svanhu
6677105197Ssam	/* get a SA index */
6678120585Ssam	SAHTREE_LOCK();
6679181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
6680105197Ssam		if (sah->state == SADB_SASTATE_DEAD)
6681105197Ssam			continue;
6682105197Ssam		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6683105197Ssam			break;
6684105197Ssam	}
6685120585Ssam	SAHTREE_UNLOCK();
6686105197Ssam	if (sah != NULL) {
6687120585Ssam		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6688105197Ssam		return key_senderror(so, m, EEXIST);
6689105197Ssam	}
6690105197Ssam
6691105197Ssam	error = key_acquire(&saidx, NULL);
6692105197Ssam	if (error != 0) {
6693120585Ssam		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6694120585Ssam			__func__, mhp->msg->sadb_msg_errno));
6695105197Ssam		return key_senderror(so, m, error);
6696105197Ssam	}
6697105197Ssam
6698105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6699105197Ssam}
6700105197Ssam
6701105197Ssam/*
6702105197Ssam * SADB_REGISTER processing.
6703105197Ssam * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6704105197Ssam * receive
6705105197Ssam *   <base>
6706105197Ssam * from the ikmpd, and register a socket to send PF_KEY messages,
6707105197Ssam * and send
6708105197Ssam *   <base, supported>
6709105197Ssam * to KMD by PF_KEY.
6710105197Ssam * If socket is detached, must free from regnode.
6711105197Ssam *
6712105197Ssam * m will always be freed.
6713105197Ssam */
6714105197Ssamstatic int
6715105197Ssamkey_register(so, m, mhp)
6716105197Ssam	struct socket *so;
6717105197Ssam	struct mbuf *m;
6718105197Ssam	const struct sadb_msghdr *mhp;
6719105197Ssam{
6720105197Ssam	struct secreg *reg, *newreg = 0;
6721105197Ssam
6722120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
6723120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6724120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6725120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6726105197Ssam
6727105197Ssam	/* check for invalid register message */
6728181803Sbz	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6729105197Ssam		return key_senderror(so, m, EINVAL);
6730105197Ssam
6731105197Ssam	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6732105197Ssam	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6733105197Ssam		goto setmsg;
6734105197Ssam
6735105197Ssam	/* check whether existing or not */
6736120585Ssam	REGTREE_LOCK();
6737181803Sbz	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6738105197Ssam		if (reg->so == so) {
6739120585Ssam			REGTREE_UNLOCK();
6740120585Ssam			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6741120585Ssam				__func__));
6742105197Ssam			return key_senderror(so, m, EEXIST);
6743105197Ssam		}
6744105197Ssam	}
6745105197Ssam
6746105197Ssam	/* create regnode */
6747119643Ssam	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6748105197Ssam	if (newreg == NULL) {
6749120585Ssam		REGTREE_UNLOCK();
6750120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6751105197Ssam		return key_senderror(so, m, ENOBUFS);
6752105197Ssam	}
6753105197Ssam
6754105197Ssam	newreg->so = so;
6755105197Ssam	((struct keycb *)sotorawcb(so))->kp_registered++;
6756105197Ssam
6757105197Ssam	/* add regnode to regtree. */
6758181803Sbz	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6759120585Ssam	REGTREE_UNLOCK();
6760105197Ssam
6761105197Ssam  setmsg:
6762105197Ssam    {
6763105197Ssam	struct mbuf *n;
6764105197Ssam	struct sadb_msg *newmsg;
6765105197Ssam	struct sadb_supported *sup;
6766105197Ssam	u_int len, alen, elen;
6767105197Ssam	int off;
6768105197Ssam	int i;
6769105197Ssam	struct sadb_alg *alg;
6770105197Ssam
6771105197Ssam	/* create new sadb_msg to reply. */
6772105197Ssam	alen = 0;
6773105197Ssam	for (i = 1; i <= SADB_AALG_MAX; i++) {
6774105197Ssam		if (ah_algorithm_lookup(i))
6775105197Ssam			alen += sizeof(struct sadb_alg);
6776105197Ssam	}
6777105197Ssam	if (alen)
6778105197Ssam		alen += sizeof(struct sadb_supported);
6779105197Ssam	elen = 0;
6780105197Ssam	for (i = 1; i <= SADB_EALG_MAX; i++) {
6781105197Ssam		if (esp_algorithm_lookup(i))
6782105197Ssam			elen += sizeof(struct sadb_alg);
6783105197Ssam	}
6784105197Ssam	if (elen)
6785105197Ssam		elen += sizeof(struct sadb_supported);
6786105197Ssam
6787105197Ssam	len = sizeof(struct sadb_msg) + alen + elen;
6788105197Ssam
6789105197Ssam	if (len > MCLBYTES)
6790105197Ssam		return key_senderror(so, m, ENOBUFS);
6791105197Ssam
6792111119Simp	MGETHDR(n, M_DONTWAIT, MT_DATA);
6793105197Ssam	if (len > MHLEN) {
6794111119Simp		MCLGET(n, M_DONTWAIT);
6795105197Ssam		if ((n->m_flags & M_EXT) == 0) {
6796105197Ssam			m_freem(n);
6797105197Ssam			n = NULL;
6798105197Ssam		}
6799105197Ssam	}
6800105197Ssam	if (!n)
6801105197Ssam		return key_senderror(so, m, ENOBUFS);
6802105197Ssam
6803105197Ssam	n->m_pkthdr.len = n->m_len = len;
6804105197Ssam	n->m_next = NULL;
6805105197Ssam	off = 0;
6806105197Ssam
6807105197Ssam	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6808105197Ssam	newmsg = mtod(n, struct sadb_msg *);
6809105197Ssam	newmsg->sadb_msg_errno = 0;
6810105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6811105197Ssam	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6812105197Ssam
6813105197Ssam	/* for authentication algorithm */
6814105197Ssam	if (alen) {
6815105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6816105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6817105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6818105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6819105197Ssam
6820105197Ssam		for (i = 1; i <= SADB_AALG_MAX; i++) {
6821105197Ssam			struct auth_hash *aalgo;
6822105197Ssam			u_int16_t minkeysize, maxkeysize;
6823105197Ssam
6824105197Ssam			aalgo = ah_algorithm_lookup(i);
6825105197Ssam			if (!aalgo)
6826105197Ssam				continue;
6827105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6828105197Ssam			alg->sadb_alg_id = i;
6829105197Ssam			alg->sadb_alg_ivlen = 0;
6830105197Ssam			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6831105197Ssam			alg->sadb_alg_minbits = _BITS(minkeysize);
6832105197Ssam			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6833105197Ssam			off += PFKEY_ALIGN8(sizeof(*alg));
6834105197Ssam		}
6835105197Ssam	}
6836105197Ssam
6837105197Ssam	/* for encryption algorithm */
6838105197Ssam	if (elen) {
6839105197Ssam		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6840105197Ssam		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6841105197Ssam		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6842105197Ssam		off += PFKEY_ALIGN8(sizeof(*sup));
6843105197Ssam
6844105197Ssam		for (i = 1; i <= SADB_EALG_MAX; i++) {
6845105197Ssam			struct enc_xform *ealgo;
6846105197Ssam
6847105197Ssam			ealgo = esp_algorithm_lookup(i);
6848105197Ssam			if (!ealgo)
6849105197Ssam				continue;
6850105197Ssam			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6851105197Ssam			alg->sadb_alg_id = i;
6852105197Ssam			alg->sadb_alg_ivlen = ealgo->blocksize;
6853105197Ssam			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6854105197Ssam			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6855105197Ssam			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6856105197Ssam		}
6857105197Ssam	}
6858105197Ssam
6859120585Ssam	IPSEC_ASSERT(off == len,
6860120585Ssam		("length assumption failed (off %u len %u)", off, len));
6861105197Ssam
6862105197Ssam	m_freem(m);
6863105197Ssam	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6864105197Ssam    }
6865105197Ssam}
6866105197Ssam
6867105197Ssam/*
6868105197Ssam * free secreg entry registered.
6869105197Ssam * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6870105197Ssam */
6871105197Ssamvoid
6872119643Ssamkey_freereg(struct socket *so)
6873105197Ssam{
6874105197Ssam	struct secreg *reg;
6875105197Ssam	int i;
6876105197Ssam
6877120585Ssam	IPSEC_ASSERT(so != NULL, ("NULL so"));
6878105197Ssam
6879105197Ssam	/*
6880105197Ssam	 * check whether existing or not.
6881105197Ssam	 * check all type of SA, because there is a potential that
6882105197Ssam	 * one socket is registered to multiple type of SA.
6883105197Ssam	 */
6884120585Ssam	REGTREE_LOCK();
6885105197Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6886181803Sbz		LIST_FOREACH(reg, &V_regtree[i], chain) {
6887119643Ssam			if (reg->so == so && __LIST_CHAINED(reg)) {
6888105197Ssam				LIST_REMOVE(reg, chain);
6889119643Ssam				free(reg, M_IPSEC_SAR);
6890105197Ssam				break;
6891105197Ssam			}
6892105197Ssam		}
6893105197Ssam	}
6894120585Ssam	REGTREE_UNLOCK();
6895105197Ssam}
6896105197Ssam
6897105197Ssam/*
6898105197Ssam * SADB_EXPIRE processing
6899105197Ssam * send
6900105197Ssam *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6901105197Ssam * to KMD by PF_KEY.
6902105197Ssam * NOTE: We send only soft lifetime extension.
6903105197Ssam *
6904105197Ssam * OUT:	0	: succeed
6905105197Ssam *	others	: error number
6906105197Ssam */
6907105197Ssamstatic int
6908119643Ssamkey_expire(struct secasvar *sav)
6909105197Ssam{
6910105197Ssam	int s;
6911105197Ssam	int satype;
6912105197Ssam	struct mbuf *result = NULL, *m;
6913105197Ssam	int len;
6914105197Ssam	int error = -1;
6915105197Ssam	struct sadb_lifetime *lt;
6916105197Ssam
6917105197Ssam	/* XXX: Why do we lock ? */
6918105197Ssam	s = splnet();	/*called from softclock()*/
6919105197Ssam
6920120585Ssam	IPSEC_ASSERT (sav != NULL, ("null sav"));
6921120585Ssam	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6922105197Ssam
6923105197Ssam	/* set msg header */
6924120585Ssam	satype = key_proto2satype(sav->sah->saidx.proto);
6925120585Ssam	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6926105197Ssam	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6927105197Ssam	if (!m) {
6928105197Ssam		error = ENOBUFS;
6929105197Ssam		goto fail;
6930105197Ssam	}
6931105197Ssam	result = m;
6932105197Ssam
6933105197Ssam	/* create SA extension */
6934105197Ssam	m = key_setsadbsa(sav);
6935105197Ssam	if (!m) {
6936105197Ssam		error = ENOBUFS;
6937105197Ssam		goto fail;
6938105197Ssam	}
6939105197Ssam	m_cat(result, m);
6940105197Ssam
6941105197Ssam	/* create SA extension */
6942105197Ssam	m = key_setsadbxsa2(sav->sah->saidx.mode,
6943105197Ssam			sav->replay ? sav->replay->count : 0,
6944105197Ssam			sav->sah->saidx.reqid);
6945105197Ssam	if (!m) {
6946105197Ssam		error = ENOBUFS;
6947105197Ssam		goto fail;
6948105197Ssam	}
6949105197Ssam	m_cat(result, m);
6950105197Ssam
6951105197Ssam	/* create lifetime extension (current and soft) */
6952105197Ssam	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6953105197Ssam	m = key_alloc_mbuf(len);
6954105197Ssam	if (!m || m->m_next) {	/*XXX*/
6955105197Ssam		if (m)
6956105197Ssam			m_freem(m);
6957105197Ssam		error = ENOBUFS;
6958105197Ssam		goto fail;
6959105197Ssam	}
6960105197Ssam	bzero(mtod(m, caddr_t), len);
6961105197Ssam	lt = mtod(m, struct sadb_lifetime *);
6962105197Ssam	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6963105197Ssam	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6964157123Sgnn	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6965157123Sgnn	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6966157123Sgnn	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6967157123Sgnn	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6968105197Ssam	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6969176743Sbz	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6970176743Sbz	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6971176743Sbz	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6972176743Sbz	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6973176743Sbz	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6974176743Sbz	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6975105197Ssam	m_cat(result, m);
6976105197Ssam
6977105197Ssam	/* set sadb_address for source */
6978105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6979105197Ssam	    &sav->sah->saidx.src.sa,
6980105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6981105197Ssam	if (!m) {
6982105197Ssam		error = ENOBUFS;
6983105197Ssam		goto fail;
6984105197Ssam	}
6985105197Ssam	m_cat(result, m);
6986105197Ssam
6987105197Ssam	/* set sadb_address for destination */
6988105197Ssam	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6989105197Ssam	    &sav->sah->saidx.dst.sa,
6990105197Ssam	    FULLMASK, IPSEC_ULPROTO_ANY);
6991105197Ssam	if (!m) {
6992105197Ssam		error = ENOBUFS;
6993105197Ssam		goto fail;
6994105197Ssam	}
6995105197Ssam	m_cat(result, m);
6996105197Ssam
6997194062Svanhu	/*
6998194062Svanhu	 * XXX-BZ Handle NAT-T extensions here.
6999194062Svanhu	 */
7000194062Svanhu
7001105197Ssam	if ((result->m_flags & M_PKTHDR) == 0) {
7002105197Ssam		error = EINVAL;
7003105197Ssam		goto fail;
7004105197Ssam	}
7005105197Ssam
7006105197Ssam	if (result->m_len < sizeof(struct sadb_msg)) {
7007105197Ssam		result = m_pullup(result, sizeof(struct sadb_msg));
7008105197Ssam		if (result == NULL) {
7009105197Ssam			error = ENOBUFS;
7010105197Ssam			goto fail;
7011105197Ssam		}
7012105197Ssam	}
7013105197Ssam
7014105197Ssam	result->m_pkthdr.len = 0;
7015105197Ssam	for (m = result; m; m = m->m_next)
7016105197Ssam		result->m_pkthdr.len += m->m_len;
7017105197Ssam
7018105197Ssam	mtod(result, struct sadb_msg *)->sadb_msg_len =
7019105197Ssam	    PFKEY_UNIT64(result->m_pkthdr.len);
7020105197Ssam
7021105197Ssam	splx(s);
7022105197Ssam	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7023105197Ssam
7024105197Ssam fail:
7025105197Ssam	if (result)
7026105197Ssam		m_freem(result);
7027105197Ssam	splx(s);
7028105197Ssam	return error;
7029105197Ssam}
7030105197Ssam
7031105197Ssam/*
7032105197Ssam * SADB_FLUSH processing
7033105197Ssam * receive
7034105197Ssam *   <base>
7035105197Ssam * from the ikmpd, and free all entries in secastree.
7036105197Ssam * and send,
7037105197Ssam *   <base>
7038105197Ssam * to the ikmpd.
7039105197Ssam * NOTE: to do is only marking SADB_SASTATE_DEAD.
7040105197Ssam *
7041105197Ssam * m will always be freed.
7042105197Ssam */
7043105197Ssamstatic int
7044105197Ssamkey_flush(so, m, mhp)
7045105197Ssam	struct socket *so;
7046105197Ssam	struct mbuf *m;
7047105197Ssam	const struct sadb_msghdr *mhp;
7048105197Ssam{
7049105197Ssam	struct sadb_msg *newmsg;
7050105197Ssam	struct secashead *sah, *nextsah;
7051105197Ssam	struct secasvar *sav, *nextsav;
7052105197Ssam	u_int16_t proto;
7053105197Ssam	u_int8_t state;
7054105197Ssam	u_int stateidx;
7055105197Ssam
7056120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7057120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7058120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7059105197Ssam
7060105197Ssam	/* map satype to proto */
7061105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7062120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7063120585Ssam			__func__));
7064105197Ssam		return key_senderror(so, m, EINVAL);
7065105197Ssam	}
7066105197Ssam
7067105197Ssam	/* no SATYPE specified, i.e. flushing all SA. */
7068120585Ssam	SAHTREE_LOCK();
7069181803Sbz	for (sah = LIST_FIRST(&V_sahtree);
7070105197Ssam	     sah != NULL;
7071105197Ssam	     sah = nextsah) {
7072105197Ssam		nextsah = LIST_NEXT(sah, chain);
7073105197Ssam
7074105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7075105197Ssam		 && proto != sah->saidx.proto)
7076105197Ssam			continue;
7077105197Ssam
7078105197Ssam		for (stateidx = 0;
7079185348Szec		     stateidx < _ARRAYLEN(saorder_state_alive);
7080105197Ssam		     stateidx++) {
7081185348Szec			state = saorder_state_any[stateidx];
7082105197Ssam			for (sav = LIST_FIRST(&sah->savtree[state]);
7083105197Ssam			     sav != NULL;
7084105197Ssam			     sav = nextsav) {
7085105197Ssam
7086105197Ssam				nextsav = LIST_NEXT(sav, chain);
7087105197Ssam
7088105197Ssam				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7089105197Ssam				KEY_FREESAV(&sav);
7090105197Ssam			}
7091105197Ssam		}
7092105197Ssam
7093105197Ssam		sah->state = SADB_SASTATE_DEAD;
7094105197Ssam	}
7095120585Ssam	SAHTREE_UNLOCK();
7096105197Ssam
7097105197Ssam	if (m->m_len < sizeof(struct sadb_msg) ||
7098105197Ssam	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7099120585Ssam		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7100105197Ssam		return key_senderror(so, m, ENOBUFS);
7101105197Ssam	}
7102105197Ssam
7103105197Ssam	if (m->m_next)
7104105197Ssam		m_freem(m->m_next);
7105105197Ssam	m->m_next = NULL;
7106105197Ssam	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7107105197Ssam	newmsg = mtod(m, struct sadb_msg *);
7108105197Ssam	newmsg->sadb_msg_errno = 0;
7109105197Ssam	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7110105197Ssam
7111105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7112105197Ssam}
7113105197Ssam
7114105197Ssam/*
7115105197Ssam * SADB_DUMP processing
7116105197Ssam * dump all entries including status of DEAD in SAD.
7117105197Ssam * receive
7118105197Ssam *   <base>
7119105197Ssam * from the ikmpd, and dump all secasvar leaves
7120105197Ssam * and send,
7121105197Ssam *   <base> .....
7122105197Ssam * to the ikmpd.
7123105197Ssam *
7124105197Ssam * m will always be freed.
7125105197Ssam */
7126105197Ssamstatic int
7127105197Ssamkey_dump(so, m, mhp)
7128105197Ssam	struct socket *so;
7129105197Ssam	struct mbuf *m;
7130105197Ssam	const struct sadb_msghdr *mhp;
7131105197Ssam{
7132105197Ssam	struct secashead *sah;
7133105197Ssam	struct secasvar *sav;
7134105197Ssam	u_int16_t proto;
7135105197Ssam	u_int stateidx;
7136105197Ssam	u_int8_t satype;
7137105197Ssam	u_int8_t state;
7138105197Ssam	int cnt;
7139105197Ssam	struct sadb_msg *newmsg;
7140105197Ssam	struct mbuf *n;
7141105197Ssam
7142120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7143120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7144120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7145120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7146105197Ssam
7147105197Ssam	/* map satype to proto */
7148105197Ssam	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7149120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7150120585Ssam			__func__));
7151105197Ssam		return key_senderror(so, m, EINVAL);
7152105197Ssam	}
7153105197Ssam
7154105197Ssam	/* count sav entries to be sent to the userland. */
7155105197Ssam	cnt = 0;
7156120585Ssam	SAHTREE_LOCK();
7157181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7158105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7159105197Ssam		 && proto != sah->saidx.proto)
7160105197Ssam			continue;
7161105197Ssam
7162105197Ssam		for (stateidx = 0;
7163185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
7164105197Ssam		     stateidx++) {
7165185348Szec			state = saorder_state_any[stateidx];
7166105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7167105197Ssam				cnt++;
7168105197Ssam			}
7169105197Ssam		}
7170105197Ssam	}
7171105197Ssam
7172119643Ssam	if (cnt == 0) {
7173120585Ssam		SAHTREE_UNLOCK();
7174105197Ssam		return key_senderror(so, m, ENOENT);
7175119643Ssam	}
7176105197Ssam
7177105197Ssam	/* send this to the userland, one at a time. */
7178105197Ssam	newmsg = NULL;
7179181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7180105197Ssam		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7181105197Ssam		 && proto != sah->saidx.proto)
7182105197Ssam			continue;
7183105197Ssam
7184105197Ssam		/* map proto to satype */
7185105197Ssam		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7186120585Ssam			SAHTREE_UNLOCK();
7187120585Ssam			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7188120585Ssam				"SAD.\n", __func__));
7189105197Ssam			return key_senderror(so, m, EINVAL);
7190105197Ssam		}
7191105197Ssam
7192105197Ssam		for (stateidx = 0;
7193185348Szec		     stateidx < _ARRAYLEN(saorder_state_any);
7194105197Ssam		     stateidx++) {
7195185348Szec			state = saorder_state_any[stateidx];
7196105197Ssam			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7197105197Ssam				n = key_setdumpsa(sav, SADB_DUMP, satype,
7198105197Ssam				    --cnt, mhp->msg->sadb_msg_pid);
7199119643Ssam				if (!n) {
7200120585Ssam					SAHTREE_UNLOCK();
7201105197Ssam					return key_senderror(so, m, ENOBUFS);
7202119643Ssam				}
7203105197Ssam				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7204105197Ssam			}
7205105197Ssam		}
7206105197Ssam	}
7207120585Ssam	SAHTREE_UNLOCK();
7208105197Ssam
7209105197Ssam	m_freem(m);
7210105197Ssam	return 0;
7211105197Ssam}
7212105197Ssam
7213105197Ssam/*
7214105197Ssam * SADB_X_PROMISC processing
7215105197Ssam *
7216105197Ssam * m will always be freed.
7217105197Ssam */
7218105197Ssamstatic int
7219105197Ssamkey_promisc(so, m, mhp)
7220105197Ssam	struct socket *so;
7221105197Ssam	struct mbuf *m;
7222105197Ssam	const struct sadb_msghdr *mhp;
7223105197Ssam{
7224105197Ssam	int olen;
7225105197Ssam
7226120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7227120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7228120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7229120585Ssam	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7230105197Ssam
7231105197Ssam	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7232105197Ssam
7233105197Ssam	if (olen < sizeof(struct sadb_msg)) {
7234105197Ssam#if 1
7235105197Ssam		return key_senderror(so, m, EINVAL);
7236105197Ssam#else
7237105197Ssam		m_freem(m);
7238105197Ssam		return 0;
7239105197Ssam#endif
7240105197Ssam	} else if (olen == sizeof(struct sadb_msg)) {
7241105197Ssam		/* enable/disable promisc mode */
7242105197Ssam		struct keycb *kp;
7243105197Ssam
7244105197Ssam		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7245105197Ssam			return key_senderror(so, m, EINVAL);
7246105197Ssam		mhp->msg->sadb_msg_errno = 0;
7247105197Ssam		switch (mhp->msg->sadb_msg_satype) {
7248105197Ssam		case 0:
7249105197Ssam		case 1:
7250105197Ssam			kp->kp_promisc = mhp->msg->sadb_msg_satype;
7251105197Ssam			break;
7252105197Ssam		default:
7253105197Ssam			return key_senderror(so, m, EINVAL);
7254105197Ssam		}
7255105197Ssam
7256105197Ssam		/* send the original message back to everyone */
7257105197Ssam		mhp->msg->sadb_msg_errno = 0;
7258105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7259105197Ssam	} else {
7260105197Ssam		/* send packet as is */
7261105197Ssam
7262105197Ssam		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7263105197Ssam
7264105197Ssam		/* TODO: if sadb_msg_seq is specified, send to specific pid */
7265105197Ssam		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7266105197Ssam	}
7267105197Ssam}
7268105197Ssam
7269105197Ssamstatic int (*key_typesw[]) __P((struct socket *, struct mbuf *,
7270105197Ssam		const struct sadb_msghdr *)) = {
7271105197Ssam	NULL,		/* SADB_RESERVED */
7272105197Ssam	key_getspi,	/* SADB_GETSPI */
7273105197Ssam	key_update,	/* SADB_UPDATE */
7274105197Ssam	key_add,	/* SADB_ADD */
7275105197Ssam	key_delete,	/* SADB_DELETE */
7276105197Ssam	key_get,	/* SADB_GET */
7277105197Ssam	key_acquire2,	/* SADB_ACQUIRE */
7278105197Ssam	key_register,	/* SADB_REGISTER */
7279105197Ssam	NULL,		/* SADB_EXPIRE */
7280105197Ssam	key_flush,	/* SADB_FLUSH */
7281105197Ssam	key_dump,	/* SADB_DUMP */
7282105197Ssam	key_promisc,	/* SADB_X_PROMISC */
7283105197Ssam	NULL,		/* SADB_X_PCHANGE */
7284105197Ssam	key_spdadd,	/* SADB_X_SPDUPDATE */
7285105197Ssam	key_spdadd,	/* SADB_X_SPDADD */
7286105197Ssam	key_spddelete,	/* SADB_X_SPDDELETE */
7287105197Ssam	key_spdget,	/* SADB_X_SPDGET */
7288105197Ssam	NULL,		/* SADB_X_SPDACQUIRE */
7289105197Ssam	key_spddump,	/* SADB_X_SPDDUMP */
7290105197Ssam	key_spdflush,	/* SADB_X_SPDFLUSH */
7291105197Ssam	key_spdadd,	/* SADB_X_SPDSETIDX */
7292105197Ssam	NULL,		/* SADB_X_SPDEXPIRE */
7293105197Ssam	key_spddelete2,	/* SADB_X_SPDDELETE2 */
7294105197Ssam};
7295105197Ssam
7296105197Ssam/*
7297105197Ssam * parse sadb_msg buffer to process PFKEYv2,
7298105197Ssam * and create a data to response if needed.
7299105197Ssam * I think to be dealed with mbuf directly.
7300105197Ssam * IN:
7301105197Ssam *     msgp  : pointer to pointer to a received buffer pulluped.
7302105197Ssam *             This is rewrited to response.
7303105197Ssam *     so    : pointer to socket.
7304105197Ssam * OUT:
7305105197Ssam *    length for buffer to send to user process.
7306105197Ssam */
7307105197Ssamint
7308105197Ssamkey_parse(m, so)
7309105197Ssam	struct mbuf *m;
7310105197Ssam	struct socket *so;
7311105197Ssam{
7312105197Ssam	struct sadb_msg *msg;
7313105197Ssam	struct sadb_msghdr mh;
7314105197Ssam	u_int orglen;
7315105197Ssam	int error;
7316105197Ssam	int target;
7317105197Ssam
7318120585Ssam	IPSEC_ASSERT(so != NULL, ("null socket"));
7319120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7320105197Ssam
7321105197Ssam#if 0	/*kdebug_sadb assumes msg in linear buffer*/
7322105197Ssam	KEYDEBUG(KEYDEBUG_KEY_DUMP,
7323120585Ssam		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7324105197Ssam		kdebug_sadb(msg));
7325105197Ssam#endif
7326105197Ssam
7327105197Ssam	if (m->m_len < sizeof(struct sadb_msg)) {
7328105197Ssam		m = m_pullup(m, sizeof(struct sadb_msg));
7329105197Ssam		if (!m)
7330105197Ssam			return ENOBUFS;
7331105197Ssam	}
7332105197Ssam	msg = mtod(m, struct sadb_msg *);
7333105197Ssam	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7334105197Ssam	target = KEY_SENDUP_ONE;
7335105197Ssam
7336105197Ssam	if ((m->m_flags & M_PKTHDR) == 0 ||
7337105197Ssam	    m->m_pkthdr.len != m->m_pkthdr.len) {
7338120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7339181803Sbz		V_pfkeystat.out_invlen++;
7340105197Ssam		error = EINVAL;
7341105197Ssam		goto senderror;
7342105197Ssam	}
7343105197Ssam
7344105197Ssam	if (msg->sadb_msg_version != PF_KEY_V2) {
7345120585Ssam		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7346120585Ssam		    __func__, msg->sadb_msg_version));
7347181803Sbz		V_pfkeystat.out_invver++;
7348105197Ssam		error = EINVAL;
7349105197Ssam		goto senderror;
7350105197Ssam	}
7351105197Ssam
7352105197Ssam	if (msg->sadb_msg_type > SADB_MAX) {
7353120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7354120585Ssam		    __func__, msg->sadb_msg_type));
7355181803Sbz		V_pfkeystat.out_invmsgtype++;
7356105197Ssam		error = EINVAL;
7357105197Ssam		goto senderror;
7358105197Ssam	}
7359105197Ssam
7360105197Ssam	/* for old-fashioned code - should be nuked */
7361105197Ssam	if (m->m_pkthdr.len > MCLBYTES) {
7362105197Ssam		m_freem(m);
7363105197Ssam		return ENOBUFS;
7364105197Ssam	}
7365105197Ssam	if (m->m_next) {
7366105197Ssam		struct mbuf *n;
7367105197Ssam
7368111119Simp		MGETHDR(n, M_DONTWAIT, MT_DATA);
7369105197Ssam		if (n && m->m_pkthdr.len > MHLEN) {
7370111119Simp			MCLGET(n, M_DONTWAIT);
7371105197Ssam			if ((n->m_flags & M_EXT) == 0) {
7372105197Ssam				m_free(n);
7373105197Ssam				n = NULL;
7374105197Ssam			}
7375105197Ssam		}
7376105197Ssam		if (!n) {
7377105197Ssam			m_freem(m);
7378105197Ssam			return ENOBUFS;
7379105197Ssam		}
7380105197Ssam		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7381105197Ssam		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7382105197Ssam		n->m_next = NULL;
7383105197Ssam		m_freem(m);
7384105197Ssam		m = n;
7385105197Ssam	}
7386105197Ssam
7387105197Ssam	/* align the mbuf chain so that extensions are in contiguous region. */
7388105197Ssam	error = key_align(m, &mh);
7389105197Ssam	if (error)
7390105197Ssam		return error;
7391105197Ssam
7392105197Ssam	msg = mh.msg;
7393105197Ssam
7394105197Ssam	/* check SA type */
7395105197Ssam	switch (msg->sadb_msg_satype) {
7396105197Ssam	case SADB_SATYPE_UNSPEC:
7397105197Ssam		switch (msg->sadb_msg_type) {
7398105197Ssam		case SADB_GETSPI:
7399105197Ssam		case SADB_UPDATE:
7400105197Ssam		case SADB_ADD:
7401105197Ssam		case SADB_DELETE:
7402105197Ssam		case SADB_GET:
7403105197Ssam		case SADB_ACQUIRE:
7404105197Ssam		case SADB_EXPIRE:
7405120585Ssam			ipseclog((LOG_DEBUG, "%s: must specify satype "
7406120585Ssam			    "when msg type=%u.\n", __func__,
7407120585Ssam			    msg->sadb_msg_type));
7408181803Sbz			V_pfkeystat.out_invsatype++;
7409105197Ssam			error = EINVAL;
7410105197Ssam			goto senderror;
7411105197Ssam		}
7412105197Ssam		break;
7413105197Ssam	case SADB_SATYPE_AH:
7414105197Ssam	case SADB_SATYPE_ESP:
7415105197Ssam	case SADB_X_SATYPE_IPCOMP:
7416125680Sbms	case SADB_X_SATYPE_TCPSIGNATURE:
7417105197Ssam		switch (msg->sadb_msg_type) {
7418105197Ssam		case SADB_X_SPDADD:
7419105197Ssam		case SADB_X_SPDDELETE:
7420105197Ssam		case SADB_X_SPDGET:
7421105197Ssam		case SADB_X_SPDDUMP:
7422105197Ssam		case SADB_X_SPDFLUSH:
7423105197Ssam		case SADB_X_SPDSETIDX:
7424105197Ssam		case SADB_X_SPDUPDATE:
7425105197Ssam		case SADB_X_SPDDELETE2:
7426120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7427120585Ssam				__func__, msg->sadb_msg_type));
7428181803Sbz			V_pfkeystat.out_invsatype++;
7429105197Ssam			error = EINVAL;
7430105197Ssam			goto senderror;
7431105197Ssam		}
7432105197Ssam		break;
7433105197Ssam	case SADB_SATYPE_RSVP:
7434105197Ssam	case SADB_SATYPE_OSPFV2:
7435105197Ssam	case SADB_SATYPE_RIPV2:
7436105197Ssam	case SADB_SATYPE_MIP:
7437120585Ssam		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7438120585Ssam			__func__, msg->sadb_msg_satype));
7439181803Sbz		V_pfkeystat.out_invsatype++;
7440105197Ssam		error = EOPNOTSUPP;
7441105197Ssam		goto senderror;
7442105197Ssam	case 1:	/* XXX: What does it do? */
7443105197Ssam		if (msg->sadb_msg_type == SADB_X_PROMISC)
7444105197Ssam			break;
7445105197Ssam		/*FALLTHROUGH*/
7446105197Ssam	default:
7447120585Ssam		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7448120585Ssam			__func__, msg->sadb_msg_satype));
7449181803Sbz		V_pfkeystat.out_invsatype++;
7450105197Ssam		error = EINVAL;
7451105197Ssam		goto senderror;
7452105197Ssam	}
7453105197Ssam
7454105197Ssam	/* check field of upper layer protocol and address family */
7455105197Ssam	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7456105197Ssam	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7457105197Ssam		struct sadb_address *src0, *dst0;
7458105197Ssam		u_int plen;
7459105197Ssam
7460105197Ssam		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7461105197Ssam		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7462105197Ssam
7463105197Ssam		/* check upper layer protocol */
7464105197Ssam		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7465120585Ssam			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7466120585Ssam				"mismatched.\n", __func__));
7467181803Sbz			V_pfkeystat.out_invaddr++;
7468105197Ssam			error = EINVAL;
7469105197Ssam			goto senderror;
7470105197Ssam		}
7471105197Ssam
7472105197Ssam		/* check family */
7473105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7474105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
7475120585Ssam			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7476120585Ssam				__func__));
7477181803Sbz			V_pfkeystat.out_invaddr++;
7478105197Ssam			error = EINVAL;
7479105197Ssam			goto senderror;
7480105197Ssam		}
7481105197Ssam		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7482105197Ssam		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
7483120585Ssam			ipseclog((LOG_DEBUG, "%s: address struct size "
7484120585Ssam				"mismatched.\n", __func__));
7485181803Sbz			V_pfkeystat.out_invaddr++;
7486105197Ssam			error = EINVAL;
7487105197Ssam			goto senderror;
7488105197Ssam		}
7489105197Ssam
7490105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7491105197Ssam		case AF_INET:
7492105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7493105197Ssam			    sizeof(struct sockaddr_in)) {
7494181803Sbz				V_pfkeystat.out_invaddr++;
7495105197Ssam				error = EINVAL;
7496105197Ssam				goto senderror;
7497105197Ssam			}
7498105197Ssam			break;
7499105197Ssam		case AF_INET6:
7500105197Ssam			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7501105197Ssam			    sizeof(struct sockaddr_in6)) {
7502181803Sbz				V_pfkeystat.out_invaddr++;
7503105197Ssam				error = EINVAL;
7504105197Ssam				goto senderror;
7505105197Ssam			}
7506105197Ssam			break;
7507105197Ssam		default:
7508120585Ssam			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7509120585Ssam				__func__));
7510181803Sbz			V_pfkeystat.out_invaddr++;
7511105197Ssam			error = EAFNOSUPPORT;
7512105197Ssam			goto senderror;
7513105197Ssam		}
7514105197Ssam
7515105197Ssam		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7516105197Ssam		case AF_INET:
7517105197Ssam			plen = sizeof(struct in_addr) << 3;
7518105197Ssam			break;
7519105197Ssam		case AF_INET6:
7520105197Ssam			plen = sizeof(struct in6_addr) << 3;
7521105197Ssam			break;
7522105197Ssam		default:
7523105197Ssam			plen = 0;	/*fool gcc*/
7524105197Ssam			break;
7525105197Ssam		}
7526105197Ssam
7527105197Ssam		/* check max prefix length */
7528105197Ssam		if (src0->sadb_address_prefixlen > plen ||
7529105197Ssam		    dst0->sadb_address_prefixlen > plen) {
7530120585Ssam			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7531120585Ssam				__func__));
7532181803Sbz			V_pfkeystat.out_invaddr++;
7533105197Ssam			error = EINVAL;
7534105197Ssam			goto senderror;
7535105197Ssam		}
7536105197Ssam
7537105197Ssam		/*
7538105197Ssam		 * prefixlen == 0 is valid because there can be a case when
7539105197Ssam		 * all addresses are matched.
7540105197Ssam		 */
7541105197Ssam	}
7542105197Ssam
7543105197Ssam	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7544105197Ssam	    key_typesw[msg->sadb_msg_type] == NULL) {
7545181803Sbz		V_pfkeystat.out_invmsgtype++;
7546105197Ssam		error = EINVAL;
7547105197Ssam		goto senderror;
7548105197Ssam	}
7549105197Ssam
7550105197Ssam	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7551105197Ssam
7552105197Ssamsenderror:
7553105197Ssam	msg->sadb_msg_errno = error;
7554105197Ssam	return key_sendup_mbuf(so, m, target);
7555105197Ssam}
7556105197Ssam
7557105197Ssamstatic int
7558105197Ssamkey_senderror(so, m, code)
7559105197Ssam	struct socket *so;
7560105197Ssam	struct mbuf *m;
7561105197Ssam	int code;
7562105197Ssam{
7563105197Ssam	struct sadb_msg *msg;
7564105197Ssam
7565120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7566120585Ssam		("mbuf too small, len %u", m->m_len));
7567105197Ssam
7568105197Ssam	msg = mtod(m, struct sadb_msg *);
7569105197Ssam	msg->sadb_msg_errno = code;
7570105197Ssam	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7571105197Ssam}
7572105197Ssam
7573105197Ssam/*
7574105197Ssam * set the pointer to each header into message buffer.
7575105197Ssam * m will be freed on error.
7576105197Ssam * XXX larger-than-MCLBYTES extension?
7577105197Ssam */
7578105197Ssamstatic int
7579105197Ssamkey_align(m, mhp)
7580105197Ssam	struct mbuf *m;
7581105197Ssam	struct sadb_msghdr *mhp;
7582105197Ssam{
7583105197Ssam	struct mbuf *n;
7584105197Ssam	struct sadb_ext *ext;
7585105197Ssam	size_t off, end;
7586105197Ssam	int extlen;
7587105197Ssam	int toff;
7588105197Ssam
7589120585Ssam	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7590120585Ssam	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7591120585Ssam	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7592120585Ssam		("mbuf too small, len %u", m->m_len));
7593105197Ssam
7594105197Ssam	/* initialize */
7595105197Ssam	bzero(mhp, sizeof(*mhp));
7596105197Ssam
7597105197Ssam	mhp->msg = mtod(m, struct sadb_msg *);
7598105197Ssam	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7599105197Ssam
7600105197Ssam	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7601105197Ssam	extlen = end;	/*just in case extlen is not updated*/
7602105197Ssam	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7603105197Ssam		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7604105197Ssam		if (!n) {
7605105197Ssam			/* m is already freed */
7606105197Ssam			return ENOBUFS;
7607105197Ssam		}
7608105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7609105197Ssam
7610105197Ssam		/* set pointer */
7611105197Ssam		switch (ext->sadb_ext_type) {
7612105197Ssam		case SADB_EXT_SA:
7613105197Ssam		case SADB_EXT_ADDRESS_SRC:
7614105197Ssam		case SADB_EXT_ADDRESS_DST:
7615105197Ssam		case SADB_EXT_ADDRESS_PROXY:
7616105197Ssam		case SADB_EXT_LIFETIME_CURRENT:
7617105197Ssam		case SADB_EXT_LIFETIME_HARD:
7618105197Ssam		case SADB_EXT_LIFETIME_SOFT:
7619105197Ssam		case SADB_EXT_KEY_AUTH:
7620105197Ssam		case SADB_EXT_KEY_ENCRYPT:
7621105197Ssam		case SADB_EXT_IDENTITY_SRC:
7622105197Ssam		case SADB_EXT_IDENTITY_DST:
7623105197Ssam		case SADB_EXT_SENSITIVITY:
7624105197Ssam		case SADB_EXT_PROPOSAL:
7625105197Ssam		case SADB_EXT_SUPPORTED_AUTH:
7626105197Ssam		case SADB_EXT_SUPPORTED_ENCRYPT:
7627105197Ssam		case SADB_EXT_SPIRANGE:
7628105197Ssam		case SADB_X_EXT_POLICY:
7629105197Ssam		case SADB_X_EXT_SA2:
7630194062Svanhu#ifdef IPSEC_NAT_T
7631194062Svanhu		case SADB_X_EXT_NAT_T_TYPE:
7632194062Svanhu		case SADB_X_EXT_NAT_T_SPORT:
7633194062Svanhu		case SADB_X_EXT_NAT_T_DPORT:
7634194062Svanhu		case SADB_X_EXT_NAT_T_OAI:
7635194062Svanhu		case SADB_X_EXT_NAT_T_OAR:
7636194062Svanhu		case SADB_X_EXT_NAT_T_FRAG:
7637194062Svanhu#endif
7638105197Ssam			/* duplicate check */
7639105197Ssam			/*
7640105197Ssam			 * XXX Are there duplication payloads of either
7641105197Ssam			 * KEY_AUTH or KEY_ENCRYPT ?
7642105197Ssam			 */
7643105197Ssam			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7644120585Ssam				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7645120585Ssam					"%u\n", __func__, ext->sadb_ext_type));
7646105197Ssam				m_freem(m);
7647181803Sbz				V_pfkeystat.out_dupext++;
7648105197Ssam				return EINVAL;
7649105197Ssam			}
7650105197Ssam			break;
7651105197Ssam		default:
7652120585Ssam			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7653120585Ssam				__func__, ext->sadb_ext_type));
7654105197Ssam			m_freem(m);
7655181803Sbz			V_pfkeystat.out_invexttype++;
7656105197Ssam			return EINVAL;
7657105197Ssam		}
7658105197Ssam
7659105197Ssam		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7660105197Ssam
7661105197Ssam		if (key_validate_ext(ext, extlen)) {
7662105197Ssam			m_freem(m);
7663181803Sbz			V_pfkeystat.out_invlen++;
7664105197Ssam			return EINVAL;
7665105197Ssam		}
7666105197Ssam
7667105197Ssam		n = m_pulldown(m, off, extlen, &toff);
7668105197Ssam		if (!n) {
7669105197Ssam			/* m is already freed */
7670105197Ssam			return ENOBUFS;
7671105197Ssam		}
7672105197Ssam		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7673105197Ssam
7674105197Ssam		mhp->ext[ext->sadb_ext_type] = ext;
7675105197Ssam		mhp->extoff[ext->sadb_ext_type] = off;
7676105197Ssam		mhp->extlen[ext->sadb_ext_type] = extlen;
7677105197Ssam	}
7678105197Ssam
7679105197Ssam	if (off != end) {
7680105197Ssam		m_freem(m);
7681181803Sbz		V_pfkeystat.out_invlen++;
7682105197Ssam		return EINVAL;
7683105197Ssam	}
7684105197Ssam
7685105197Ssam	return 0;
7686105197Ssam}
7687105197Ssam
7688105197Ssamstatic int
7689105197Ssamkey_validate_ext(ext, len)
7690105197Ssam	const struct sadb_ext *ext;
7691105197Ssam	int len;
7692105197Ssam{
7693105197Ssam	const struct sockaddr *sa;
7694105197Ssam	enum { NONE, ADDR } checktype = NONE;
7695105197Ssam	int baselen = 0;
7696105197Ssam	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7697105197Ssam
7698105197Ssam	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7699105197Ssam		return EINVAL;
7700105197Ssam
7701105197Ssam	/* if it does not match minimum/maximum length, bail */
7702105197Ssam	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7703105197Ssam	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7704105197Ssam		return EINVAL;
7705105197Ssam	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7706105197Ssam		return EINVAL;
7707105197Ssam	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7708105197Ssam		return EINVAL;
7709105197Ssam
7710105197Ssam	/* more checks based on sadb_ext_type XXX need more */
7711105197Ssam	switch (ext->sadb_ext_type) {
7712105197Ssam	case SADB_EXT_ADDRESS_SRC:
7713105197Ssam	case SADB_EXT_ADDRESS_DST:
7714105197Ssam	case SADB_EXT_ADDRESS_PROXY:
7715105197Ssam		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7716105197Ssam		checktype = ADDR;
7717105197Ssam		break;
7718105197Ssam	case SADB_EXT_IDENTITY_SRC:
7719105197Ssam	case SADB_EXT_IDENTITY_DST:
7720105197Ssam		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7721105197Ssam		    SADB_X_IDENTTYPE_ADDR) {
7722105197Ssam			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7723105197Ssam			checktype = ADDR;
7724105197Ssam		} else
7725105197Ssam			checktype = NONE;
7726105197Ssam		break;
7727105197Ssam	default:
7728105197Ssam		checktype = NONE;
7729105197Ssam		break;
7730105197Ssam	}
7731105197Ssam
7732105197Ssam	switch (checktype) {
7733105197Ssam	case NONE:
7734105197Ssam		break;
7735105197Ssam	case ADDR:
7736105197Ssam		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7737105197Ssam		if (len < baselen + sal)
7738105197Ssam			return EINVAL;
7739105197Ssam		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7740105197Ssam			return EINVAL;
7741105197Ssam		break;
7742105197Ssam	}
7743105197Ssam
7744105197Ssam	return 0;
7745105197Ssam}
7746105197Ssam
7747105197Ssamvoid
7748180086Sjuliankey_init(void)
7749105197Ssam{
7750105197Ssam	int i;
7751105197Ssam
7752119643Ssam	for (i = 0; i < IPSEC_DIR_MAX; i++)
7753181803Sbz		LIST_INIT(&V_sptree[i]);
7754105197Ssam
7755181803Sbz	LIST_INIT(&V_sahtree);
7756105197Ssam
7757119643Ssam	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7758181803Sbz		LIST_INIT(&V_regtree[i]);
7759105197Ssam
7760181803Sbz	LIST_INIT(&V_acqtree);
7761181803Sbz	LIST_INIT(&V_spacqtree);
7762105197Ssam
7763105197Ssam	/* system default */
7764181803Sbz	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7765181803Sbz	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7766105197Ssam
7767190787Szec	if (!IS_DEFAULT_VNET(curvnet))
7768190787Szec		return;
7769190787Szec
7770190787Szec	SPTREE_LOCK_INIT();
7771190787Szec	REGTREE_LOCK_INIT();
7772190787Szec	SAHTREE_LOCK_INIT();
7773190787Szec	ACQ_LOCK_INIT();
7774190787Szec	SPACQ_LOCK_INIT();
7775190787Szec
7776105197Ssam#ifndef IPSEC_DEBUG2
7777105197Ssam	timeout((void *)key_timehandler, (void *)0, hz);
7778105197Ssam#endif /*IPSEC_DEBUG2*/
7779105197Ssam
7780105197Ssam	/* initialize key statistics */
7781105197Ssam	keystat.getspi_count = 1;
7782105197Ssam
7783177173Sbz	printf("IPsec: Initialized Security Association Processing.\n");
7784193731Szec}
7785105197Ssam
7786193731Szec#ifdef VIMAGE
7787193731Szecvoid
7788193731Szeckey_destroy(void)
7789193731Szec{
7790193731Szec	struct secpolicy *sp, *nextsp;
7791193731Szec	struct secspacq *acq, *nextacq;
7792193731Szec	struct secashead *sah, *nextsah;
7793193731Szec	struct secreg *reg;
7794193731Szec	int i;
7795193731Szec
7796193731Szec	SPTREE_LOCK();
7797193731Szec	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7798193731Szec		for (sp = LIST_FIRST(&V_sptree[i]);
7799193731Szec		    sp != NULL; sp = nextsp) {
7800193731Szec			nextsp = LIST_NEXT(sp, chain);
7801193731Szec			if (__LIST_CHAINED(sp)) {
7802193731Szec				LIST_REMOVE(sp, chain);
7803193731Szec				free(sp, M_IPSEC_SP);
7804193731Szec			}
7805193731Szec		}
7806193731Szec	}
7807193731Szec	SPTREE_UNLOCK();
7808193731Szec
7809193731Szec	SAHTREE_LOCK();
7810193731Szec	for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7811193731Szec		nextsah = LIST_NEXT(sah, chain);
7812193731Szec		if (__LIST_CHAINED(sah)) {
7813193731Szec			LIST_REMOVE(sah, chain);
7814193731Szec			free(sah, M_IPSEC_SAH);
7815193731Szec		}
7816193731Szec	}
7817193731Szec	SAHTREE_UNLOCK();
7818193731Szec
7819193731Szec	REGTREE_LOCK();
7820193731Szec	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7821193731Szec		LIST_FOREACH(reg, &V_regtree[i], chain) {
7822193731Szec			if (__LIST_CHAINED(reg)) {
7823193731Szec				LIST_REMOVE(reg, chain);
7824193731Szec				free(reg, M_IPSEC_SAR);
7825193731Szec				break;
7826193731Szec			}
7827193731Szec		}
7828193731Szec	}
7829193731Szec	REGTREE_UNLOCK();
7830193731Szec
7831193731Szec	ACQ_LOCK();
7832193731Szec	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
7833193731Szec		nextacq = LIST_NEXT(acq, chain);
7834193731Szec		if (__LIST_CHAINED(acq)) {
7835193731Szec			LIST_REMOVE(acq, chain);
7836193731Szec			free(acq, M_IPSEC_SAQ);
7837193731Szec		}
7838193731Szec	}
7839193731Szec	ACQ_UNLOCK();
7840193731Szec
7841193731Szec	SPACQ_LOCK();
7842193731Szec	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
7843193731Szec		nextacq = LIST_NEXT(acq, chain);
7844193731Szec		if (__LIST_CHAINED(acq)) {
7845193731Szec			LIST_REMOVE(acq, chain);
7846193731Szec			free(acq, M_IPSEC_SAQ);
7847193731Szec		}
7848193731Szec	}
7849193731Szec	SPACQ_UNLOCK();
7850105197Ssam}
7851193731Szec#endif
7852105197Ssam
7853105197Ssam/*
7854105197Ssam * XXX: maybe This function is called after INBOUND IPsec processing.
7855105197Ssam *
7856105197Ssam * Special check for tunnel-mode packets.
7857105197Ssam * We must make some checks for consistency between inner and outer IP header.
7858105197Ssam *
7859105197Ssam * xxx more checks to be provided
7860105197Ssam */
7861105197Ssamint
7862105197Ssamkey_checktunnelsanity(sav, family, src, dst)
7863105197Ssam	struct secasvar *sav;
7864105197Ssam	u_int family;
7865105197Ssam	caddr_t src;
7866105197Ssam	caddr_t dst;
7867105197Ssam{
7868120585Ssam	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7869105197Ssam
7870105197Ssam	/* XXX: check inner IP header */
7871105197Ssam
7872105197Ssam	return 1;
7873105197Ssam}
7874105197Ssam
7875105197Ssam/* record data transfer on SA, and update timestamps */
7876105197Ssamvoid
7877105197Ssamkey_sa_recordxfer(sav, m)
7878105197Ssam	struct secasvar *sav;
7879105197Ssam	struct mbuf *m;
7880105197Ssam{
7881120585Ssam	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7882120585Ssam	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7883105197Ssam	if (!sav->lft_c)
7884105197Ssam		return;
7885105197Ssam
7886105197Ssam	/*
7887105197Ssam	 * XXX Currently, there is a difference of bytes size
7888105197Ssam	 * between inbound and outbound processing.
7889105197Ssam	 */
7890157123Sgnn	sav->lft_c->bytes += m->m_pkthdr.len;
7891105197Ssam	/* to check bytes lifetime is done in key_timehandler(). */
7892105197Ssam
7893105197Ssam	/*
7894105197Ssam	 * We use the number of packets as the unit of
7895157123Sgnn	 * allocations.  We increment the variable
7896105197Ssam	 * whenever {esp,ah}_{in,out}put is called.
7897105197Ssam	 */
7898157123Sgnn	sav->lft_c->allocations++;
7899105197Ssam	/* XXX check for expires? */
7900105197Ssam
7901105197Ssam	/*
7902157123Sgnn	 * NOTE: We record CURRENT usetime by using wall clock,
7903105197Ssam	 * in seconds.  HARD and SOFT lifetime are measured by the time
7904157123Sgnn	 * difference (again in seconds) from usetime.
7905105197Ssam	 *
7906105197Ssam	 *	usetime
7907105197Ssam	 *	v     expire   expire
7908105197Ssam	 * -----+-----+--------+---> t
7909105197Ssam	 *	<--------------> HARD
7910105197Ssam	 *	<-----> SOFT
7911105197Ssam	 */
7912157123Sgnn	sav->lft_c->usetime = time_second;
7913105197Ssam	/* XXX check for expires? */
7914105197Ssam
7915105197Ssam	return;
7916105197Ssam}
7917105197Ssam
7918105197Ssam/* dumb version */
7919105197Ssamvoid
7920105197Ssamkey_sa_routechange(dst)
7921105197Ssam	struct sockaddr *dst;
7922105197Ssam{
7923105197Ssam	struct secashead *sah;
7924105197Ssam	struct route *ro;
7925105197Ssam
7926120585Ssam	SAHTREE_LOCK();
7927181803Sbz	LIST_FOREACH(sah, &V_sahtree, chain) {
7928105197Ssam		ro = &sah->sa_route;
7929105197Ssam		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7930105197Ssam		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7931105197Ssam			RTFREE(ro->ro_rt);
7932105197Ssam			ro->ro_rt = (struct rtentry *)NULL;
7933105197Ssam		}
7934105197Ssam	}
7935120585Ssam	SAHTREE_UNLOCK();
7936105197Ssam}
7937105197Ssam
7938105197Ssamstatic void
7939189004Srdivackykey_sa_chgstate(struct secasvar *sav, u_int8_t state)
7940105197Ssam{
7941120585Ssam	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7942120585Ssam	SAHTREE_LOCK_ASSERT();
7943105197Ssam
7944119643Ssam	if (sav->state != state) {
7945119643Ssam		if (__LIST_CHAINED(sav))
7946119643Ssam			LIST_REMOVE(sav, chain);
7947119643Ssam		sav->state = state;
7948119643Ssam		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7949119643Ssam	}
7950105197Ssam}
7951105197Ssam
7952105197Ssamvoid
7953105197Ssamkey_sa_stir_iv(sav)
7954105197Ssam	struct secasvar *sav;
7955105197Ssam{
7956105197Ssam
7957120585Ssam	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7958105197Ssam	key_randomfill(sav->iv, sav->ivlen);
7959105197Ssam}
7960105197Ssam
7961105197Ssam/* XXX too much? */
7962105197Ssamstatic struct mbuf *
7963105197Ssamkey_alloc_mbuf(l)
7964105197Ssam	int l;
7965105197Ssam{
7966105197Ssam	struct mbuf *m = NULL, *n;
7967105197Ssam	int len, t;
7968105197Ssam
7969105197Ssam	len = l;
7970105197Ssam	while (len > 0) {
7971111119Simp		MGET(n, M_DONTWAIT, MT_DATA);
7972105197Ssam		if (n && len > MLEN)
7973111119Simp			MCLGET(n, M_DONTWAIT);
7974105197Ssam		if (!n) {
7975105197Ssam			m_freem(m);
7976105197Ssam			return NULL;
7977105197Ssam		}
7978105197Ssam
7979105197Ssam		n->m_next = NULL;
7980105197Ssam		n->m_len = 0;
7981105197Ssam		n->m_len = M_TRAILINGSPACE(n);
7982105197Ssam		/* use the bottom of mbuf, hoping we can prepend afterwards */
7983105197Ssam		if (n->m_len > len) {
7984105197Ssam			t = (n->m_len - len) & ~(sizeof(long) - 1);
7985105197Ssam			n->m_data += t;
7986105197Ssam			n->m_len = len;
7987105197Ssam		}
7988105197Ssam
7989105197Ssam		len -= n->m_len;
7990105197Ssam
7991105197Ssam		if (m)
7992105197Ssam			m_cat(m, n);
7993105197Ssam		else
7994105197Ssam			m = n;
7995105197Ssam	}
7996105197Ssam
7997105197Ssam	return m;
7998105197Ssam}
7999157123Sgnn
8000157123Sgnn/*
8001157123Sgnn * Take one of the kernel's security keys and convert it into a PF_KEY
8002157123Sgnn * structure within an mbuf, suitable for sending up to a waiting
8003157123Sgnn * application in user land.
8004157123Sgnn *
8005157123Sgnn * IN:
8006157123Sgnn *    src: A pointer to a kernel security key.
8007157123Sgnn *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
8008157123Sgnn * OUT:
8009157123Sgnn *    a valid mbuf or NULL indicating an error
8010157123Sgnn *
8011157123Sgnn */
8012157123Sgnn
8013157123Sgnnstatic struct mbuf *
8014157123Sgnnkey_setkey(struct seckey *src, u_int16_t exttype)
8015157123Sgnn{
8016157123Sgnn	struct mbuf *m;
8017157123Sgnn	struct sadb_key *p;
8018170799Sbz	int len;
8019157123Sgnn
8020157123Sgnn	if (src == NULL)
8021157123Sgnn		return NULL;
8022157123Sgnn
8023170799Sbz	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8024157123Sgnn	m = key_alloc_mbuf(len);
8025157123Sgnn	if (m == NULL)
8026157123Sgnn		return NULL;
8027157123Sgnn	p = mtod(m, struct sadb_key *);
8028157123Sgnn	bzero(p, len);
8029157123Sgnn	p->sadb_key_len = PFKEY_UNIT64(len);
8030157123Sgnn	p->sadb_key_exttype = exttype;
8031157123Sgnn	p->sadb_key_bits = src->bits;
8032157123Sgnn	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8033157123Sgnn
8034157123Sgnn	return m;
8035157123Sgnn}
8036157123Sgnn
8037157123Sgnn/*
8038157123Sgnn * Take one of the kernel's lifetime data structures and convert it
8039157123Sgnn * into a PF_KEY structure within an mbuf, suitable for sending up to
8040157123Sgnn * a waiting application in user land.
8041157123Sgnn *
8042157123Sgnn * IN:
8043157123Sgnn *    src: A pointer to a kernel lifetime structure.
8044157123Sgnn *    exttype: Which type of lifetime this is. Refer to the PF_KEY
8045157123Sgnn *             data structures for more information.
8046157123Sgnn * OUT:
8047157123Sgnn *    a valid mbuf or NULL indicating an error
8048157123Sgnn *
8049157123Sgnn */
8050157123Sgnn
8051157123Sgnnstatic struct mbuf *
8052157123Sgnnkey_setlifetime(struct seclifetime *src, u_int16_t exttype)
8053157123Sgnn{
8054157123Sgnn	struct mbuf *m = NULL;
8055157123Sgnn	struct sadb_lifetime *p;
8056157123Sgnn	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8057157123Sgnn
8058157123Sgnn	if (src == NULL)
8059157123Sgnn		return NULL;
8060157123Sgnn
8061157123Sgnn	m = key_alloc_mbuf(len);
8062157123Sgnn	if (m == NULL)
8063157123Sgnn		return m;
8064157123Sgnn	p = mtod(m, struct sadb_lifetime *);
8065157123Sgnn
8066157123Sgnn	bzero(p, len);
8067157123Sgnn	p->sadb_lifetime_len = PFKEY_UNIT64(len);
8068157123Sgnn	p->sadb_lifetime_exttype = exttype;
8069157123Sgnn	p->sadb_lifetime_allocations = src->allocations;
8070157123Sgnn	p->sadb_lifetime_bytes = src->bytes;
8071157123Sgnn	p->sadb_lifetime_addtime = src->addtime;
8072157123Sgnn	p->sadb_lifetime_usetime = src->usetime;
8073157123Sgnn
8074157123Sgnn	return m;
8075157123Sgnn
8076157123Sgnn}
8077