key.c revision 197250
1/*	$FreeBSD: head/sys/netipsec/key.c 197250 2009-09-16 11:56:44Z vanhu $	*/
2/*	$KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $	*/
3
4/*-
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/*
34 * This code is referd to RFC 2367
35 */
36
37#include "opt_inet.h"
38#include "opt_inet6.h"
39#include "opt_ipsec.h"
40
41#include <sys/types.h>
42#include <sys/param.h>
43#include <sys/systm.h>
44#include <sys/kernel.h>
45#include <sys/lock.h>
46#include <sys/mutex.h>
47#include <sys/mbuf.h>
48#include <sys/domain.h>
49#include <sys/protosw.h>
50#include <sys/malloc.h>
51#include <sys/socket.h>
52#include <sys/socketvar.h>
53#include <sys/sysctl.h>
54#include <sys/errno.h>
55#include <sys/proc.h>
56#include <sys/queue.h>
57#include <sys/refcount.h>
58#include <sys/syslog.h>
59
60#include <net/if.h>
61#include <net/route.h>
62#include <net/raw_cb.h>
63#include <net/vnet.h>
64
65#include <netinet/in.h>
66#include <netinet/in_systm.h>
67#include <netinet/ip.h>
68#include <netinet/in_var.h>
69
70#ifdef INET6
71#include <netinet/ip6.h>
72#include <netinet6/in6_var.h>
73#include <netinet6/ip6_var.h>
74#endif /* INET6 */
75
76#ifdef INET
77#include <netinet/in_pcb.h>
78#endif
79#ifdef INET6
80#include <netinet6/in6_pcb.h>
81#endif /* INET6 */
82
83#include <net/pfkeyv2.h>
84#include <netipsec/keydb.h>
85#include <netipsec/key.h>
86#include <netipsec/keysock.h>
87#include <netipsec/key_debug.h>
88
89#include <netipsec/ipsec.h>
90#ifdef INET6
91#include <netipsec/ipsec6.h>
92#endif
93
94#include <netipsec/xform.h>
95
96#include <machine/stdarg.h>
97
98/* randomness */
99#include <sys/random.h>
100
101#define FULLMASK	0xff
102#define	_BITS(bytes)	((bytes) << 3)
103
104/*
105 * Note on SA reference counting:
106 * - SAs that are not in DEAD state will have (total external reference + 1)
107 *   following value in reference count field.  they cannot be freed and are
108 *   referenced from SA header.
109 * - SAs that are in DEAD state will have (total external reference)
110 *   in reference count field.  they are ready to be freed.  reference from
111 *   SA header will be removed in key_delsav(), when the reference count
112 *   field hits 0 (= no external reference other than from SA header.
113 */
114
115VNET_DEFINE(u_int32_t, key_debug_level) = 0;
116static VNET_DEFINE(u_int, key_spi_trycnt) = 1000;
117#define	V_key_spi_trycnt	VNET(key_spi_trycnt)
118static VNET_DEFINE(u_int32_t, key_spi_minval) = 0x100;
119#define	V_key_spi_minval	VNET(key_spi_minval)
120static VNET_DEFINE(u_int32_t, key_spi_maxval) = 0x0fffffff;	/* XXX */
121#define	V_key_spi_maxval	VNET(key_spi_maxval)
122static VNET_DEFINE(u_int32_t, policy_id) = 0;
123#define	V_policy_id		VNET(policy_id)
124/*interval to initialize randseed,1(m)*/
125static VNET_DEFINE(u_int, key_int_random) = 60;
126#define	V_key_int_random	VNET(key_int_random)
127/* interval to expire acquiring, 30(s)*/
128static VNET_DEFINE(u_int, key_larval_lifetime) = 30;
129#define	V_key_larval_lifetime	VNET(key_larval_lifetime)
130/* counter for blocking SADB_ACQUIRE.*/
131static VNET_DEFINE(int, key_blockacq_count) = 10;
132#define	V_key_blockacq_count	VNET(key_blockacq_count)
133/* lifetime for blocking SADB_ACQUIRE.*/
134static VNET_DEFINE(int, key_blockacq_lifetime) = 20;
135#define	V_key_blockacq_lifetime	VNET(key_blockacq_lifetime)
136/* preferred old sa rather than new sa.*/
137static VNET_DEFINE(int, key_preferred_oldsa) = 1;
138#define	V_key_preferred_oldsa	VNET(key_preferred_oldsa)
139
140static VNET_DEFINE(u_int32_t, acq_seq) = 0;
141#define	V_acq_seq		VNET(acq_seq)
142
143								/* SPD */
144static VNET_DEFINE(LIST_HEAD(_sptree, secpolicy), sptree[IPSEC_DIR_MAX]);
145#define	V_sptree		VNET(sptree)
146static struct mtx sptree_lock;
147#define	SPTREE_LOCK_INIT() \
148	mtx_init(&sptree_lock, "sptree", \
149		"fast ipsec security policy database", MTX_DEF)
150#define	SPTREE_LOCK_DESTROY()	mtx_destroy(&sptree_lock)
151#define	SPTREE_LOCK()		mtx_lock(&sptree_lock)
152#define	SPTREE_UNLOCK()	mtx_unlock(&sptree_lock)
153#define	SPTREE_LOCK_ASSERT()	mtx_assert(&sptree_lock, MA_OWNED)
154
155static VNET_DEFINE(LIST_HEAD(_sahtree, secashead), sahtree);	/* SAD */
156#define	V_sahtree		VNET(sahtree)
157static struct mtx sahtree_lock;
158#define	SAHTREE_LOCK_INIT() \
159	mtx_init(&sahtree_lock, "sahtree", \
160		"fast ipsec security association database", MTX_DEF)
161#define	SAHTREE_LOCK_DESTROY()	mtx_destroy(&sahtree_lock)
162#define	SAHTREE_LOCK()		mtx_lock(&sahtree_lock)
163#define	SAHTREE_UNLOCK()	mtx_unlock(&sahtree_lock)
164#define	SAHTREE_LOCK_ASSERT()	mtx_assert(&sahtree_lock, MA_OWNED)
165
166							/* registed list */
167static VNET_DEFINE(LIST_HEAD(_regtree, secreg), regtree[SADB_SATYPE_MAX + 1]);
168#define	V_regtree		VNET(regtree)
169static struct mtx regtree_lock;
170#define	REGTREE_LOCK_INIT() \
171	mtx_init(&regtree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
172#define	REGTREE_LOCK_DESTROY()	mtx_destroy(&regtree_lock)
173#define	REGTREE_LOCK()		mtx_lock(&regtree_lock)
174#define	REGTREE_UNLOCK()	mtx_unlock(&regtree_lock)
175#define	REGTREE_LOCK_ASSERT()	mtx_assert(&regtree_lock, MA_OWNED)
176
177static VNET_DEFINE(LIST_HEAD(_acqtree, secacq), acqtree); /* acquiring list */
178#define	V_acqtree		VNET(acqtree)
179static struct mtx acq_lock;
180#define	ACQ_LOCK_INIT() \
181	mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
182#define	ACQ_LOCK_DESTROY()	mtx_destroy(&acq_lock)
183#define	ACQ_LOCK()		mtx_lock(&acq_lock)
184#define	ACQ_UNLOCK()		mtx_unlock(&acq_lock)
185#define	ACQ_LOCK_ASSERT()	mtx_assert(&acq_lock, MA_OWNED)
186
187							/* SP acquiring list */
188static VNET_DEFINE(LIST_HEAD(_spacqtree, secspacq), spacqtree);
189#define	V_spacqtree		VNET(spacqtree)
190static struct mtx spacq_lock;
191#define	SPACQ_LOCK_INIT() \
192	mtx_init(&spacq_lock, "spacqtree", \
193		"fast ipsec security policy acquire list", MTX_DEF)
194#define	SPACQ_LOCK_DESTROY()	mtx_destroy(&spacq_lock)
195#define	SPACQ_LOCK()		mtx_lock(&spacq_lock)
196#define	SPACQ_UNLOCK()		mtx_unlock(&spacq_lock)
197#define	SPACQ_LOCK_ASSERT()	mtx_assert(&spacq_lock, MA_OWNED)
198
199/* search order for SAs */
200static const u_int saorder_state_valid_prefer_old[] = {
201	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
202};
203static const u_int saorder_state_valid_prefer_new[] = {
204	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
205};
206static const u_int saorder_state_alive[] = {
207	/* except DEAD */
208	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
209};
210static const u_int saorder_state_any[] = {
211	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
212	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
213};
214
215static const int minsize[] = {
216	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
217	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
218	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
219	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
220	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
221	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
222	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
223	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
224	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
225	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
226	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
227	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
228	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
229	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
230	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
231	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
232	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
233	0,				/* SADB_X_EXT_KMPRIVATE */
234	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
235	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
236	sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
237	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
238	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
239	sizeof(struct sadb_address),	/* SADB_X_EXT_NAT_T_OAI */
240	sizeof(struct sadb_address),	/* SADB_X_EXT_NAT_T_OAR */
241	sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
242};
243static const int maxsize[] = {
244	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
245	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
246	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
247	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
248	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
249	0,				/* SADB_EXT_ADDRESS_SRC */
250	0,				/* SADB_EXT_ADDRESS_DST */
251	0,				/* SADB_EXT_ADDRESS_PROXY */
252	0,				/* SADB_EXT_KEY_AUTH */
253	0,				/* SADB_EXT_KEY_ENCRYPT */
254	0,				/* SADB_EXT_IDENTITY_SRC */
255	0,				/* SADB_EXT_IDENTITY_DST */
256	0,				/* SADB_EXT_SENSITIVITY */
257	0,				/* SADB_EXT_PROPOSAL */
258	0,				/* SADB_EXT_SUPPORTED_AUTH */
259	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
260	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
261	0,				/* SADB_X_EXT_KMPRIVATE */
262	0,				/* SADB_X_EXT_POLICY */
263	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
264	sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
265	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
266	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
267	0,				/* SADB_X_EXT_NAT_T_OAI */
268	0,				/* SADB_X_EXT_NAT_T_OAR */
269	sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
270};
271
272static VNET_DEFINE(int, ipsec_esp_keymin) = 256;
273#define	V_ipsec_esp_keymin	VNET(ipsec_esp_keymin)
274static VNET_DEFINE(int, ipsec_esp_auth) = 0;
275#define	V_ipsec_esp_auth	VNET(ipsec_esp_auth)
276static VNET_DEFINE(int, ipsec_ah_keymin) = 128;
277#define	V_ipsec_ah_keymin	VNET(ipsec_ah_keymin)
278
279#ifdef SYSCTL_DECL
280SYSCTL_DECL(_net_key);
281#endif
282
283SYSCTL_VNET_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,
284	CTLFLAG_RW, &VNET_NAME(key_debug_level),	0,	"");
285
286/* max count of trial for the decision of spi value */
287SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
288	CTLFLAG_RW, &VNET_NAME(key_spi_trycnt),	0,	"");
289
290/* minimum spi value to allocate automatically. */
291SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MIN_VALUE,
292	spi_minval,	CTLFLAG_RW, &VNET_NAME(key_spi_minval),	0,	"");
293
294/* maximun spi value to allocate automatically. */
295SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MAX_VALUE,
296	spi_maxval,	CTLFLAG_RW, &VNET_NAME(key_spi_maxval),	0,	"");
297
298/* interval to initialize randseed */
299SYSCTL_VNET_INT(_net_key, KEYCTL_RANDOM_INT,
300	int_random,	CTLFLAG_RW, &VNET_NAME(key_int_random),	0,	"");
301
302/* lifetime for larval SA */
303SYSCTL_VNET_INT(_net_key, KEYCTL_LARVAL_LIFETIME,
304	larval_lifetime, CTLFLAG_RW, &VNET_NAME(key_larval_lifetime),	0, "");
305
306/* counter for blocking to send SADB_ACQUIRE to IKEd */
307SYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,
308	blockacq_count,	CTLFLAG_RW, &VNET_NAME(key_blockacq_count),	0, "");
309
310/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
311SYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,
312	blockacq_lifetime, CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
313
314/* ESP auth */
315SYSCTL_VNET_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth,
316	CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth),	0,	"");
317
318/* minimum ESP key length */
319SYSCTL_VNET_INT(_net_key, KEYCTL_ESP_KEYMIN,
320	esp_keymin, CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin),	0,	"");
321
322/* minimum AH key length */
323SYSCTL_VNET_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin,
324	CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin),	0,	"");
325
326/* perfered old SA rather than new SA */
327SYSCTL_VNET_INT(_net_key, KEYCTL_PREFERED_OLDSA,
328	preferred_oldsa, CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa),	0, "");
329
330#define __LIST_CHAINED(elm) \
331	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
332#define LIST_INSERT_TAIL(head, elm, type, field) \
333do {\
334	struct type *curelm = LIST_FIRST(head); \
335	if (curelm == NULL) {\
336		LIST_INSERT_HEAD(head, elm, field); \
337	} else { \
338		while (LIST_NEXT(curelm, field)) \
339			curelm = LIST_NEXT(curelm, field);\
340		LIST_INSERT_AFTER(curelm, elm, field);\
341	}\
342} while (0)
343
344#define KEY_CHKSASTATE(head, sav, name) \
345do { \
346	if ((head) != (sav)) {						\
347		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
348			(name), (head), (sav)));			\
349		continue;						\
350	}								\
351} while (0)
352
353#define KEY_CHKSPDIR(head, sp, name) \
354do { \
355	if ((head) != (sp)) {						\
356		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
357			"anyway continue.\n",				\
358			(name), (head), (sp)));				\
359	}								\
360} while (0)
361
362MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
363MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
364MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
365MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
366MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
367MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
368MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
369
370/*
371 * set parameters into secpolicyindex buffer.
372 * Must allocate secpolicyindex buffer passed to this function.
373 */
374#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
375do { \
376	bzero((idx), sizeof(struct secpolicyindex));                         \
377	(idx)->dir = (_dir);                                                 \
378	(idx)->prefs = (ps);                                                 \
379	(idx)->prefd = (pd);                                                 \
380	(idx)->ul_proto = (ulp);                                             \
381	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
382	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
383} while (0)
384
385/*
386 * set parameters into secasindex buffer.
387 * Must allocate secasindex buffer before calling this function.
388 */
389#define KEY_SETSECASIDX(p, m, r, s, d, idx) \
390do { \
391	bzero((idx), sizeof(struct secasindex));                             \
392	(idx)->proto = (p);                                                  \
393	(idx)->mode = (m);                                                   \
394	(idx)->reqid = (r);                                                  \
395	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
396	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
397} while (0)
398
399/* key statistics */
400struct _keystat {
401	u_long getspi_count; /* the avarage of count to try to get new SPI */
402} keystat;
403
404struct sadb_msghdr {
405	struct sadb_msg *msg;
406	struct sadb_ext *ext[SADB_EXT_MAX + 1];
407	int extoff[SADB_EXT_MAX + 1];
408	int extlen[SADB_EXT_MAX + 1];
409};
410
411static struct secasvar *key_allocsa_policy __P((const struct secasindex *));
412static void key_freesp_so __P((struct secpolicy **));
413static struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
414static void key_delsp __P((struct secpolicy *));
415static struct secpolicy *key_getsp __P((struct secpolicyindex *));
416static void _key_delsp(struct secpolicy *sp);
417static struct secpolicy *key_getspbyid __P((u_int32_t));
418static u_int32_t key_newreqid __P((void));
419static struct mbuf *key_gather_mbuf __P((struct mbuf *,
420	const struct sadb_msghdr *, int, int, ...));
421static int key_spdadd __P((struct socket *, struct mbuf *,
422	const struct sadb_msghdr *));
423static u_int32_t key_getnewspid __P((void));
424static int key_spddelete __P((struct socket *, struct mbuf *,
425	const struct sadb_msghdr *));
426static int key_spddelete2 __P((struct socket *, struct mbuf *,
427	const struct sadb_msghdr *));
428static int key_spdget __P((struct socket *, struct mbuf *,
429	const struct sadb_msghdr *));
430static int key_spdflush __P((struct socket *, struct mbuf *,
431	const struct sadb_msghdr *));
432static int key_spddump __P((struct socket *, struct mbuf *,
433	const struct sadb_msghdr *));
434static struct mbuf *key_setdumpsp __P((struct secpolicy *,
435	u_int8_t, u_int32_t, u_int32_t));
436static u_int key_getspreqmsglen __P((struct secpolicy *));
437static int key_spdexpire __P((struct secpolicy *));
438static struct secashead *key_newsah __P((struct secasindex *));
439static void key_delsah __P((struct secashead *));
440static struct secasvar *key_newsav __P((struct mbuf *,
441	const struct sadb_msghdr *, struct secashead *, int *,
442	const char*, int));
443#define	KEY_NEWSAV(m, sadb, sah, e)				\
444	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
445static void key_delsav __P((struct secasvar *));
446static struct secashead *key_getsah __P((struct secasindex *));
447static struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
448static struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
449static int key_setsaval __P((struct secasvar *, struct mbuf *,
450	const struct sadb_msghdr *));
451static int key_mature __P((struct secasvar *));
452static struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
453	u_int8_t, u_int32_t, u_int32_t));
454static struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
455	u_int32_t, pid_t, u_int16_t));
456static struct mbuf *key_setsadbsa __P((struct secasvar *));
457static struct mbuf *key_setsadbaddr __P((u_int16_t,
458	const struct sockaddr *, u_int8_t, u_int16_t));
459#ifdef IPSEC_NAT_T
460static struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
461static struct mbuf *key_setsadbxtype(u_int16_t);
462#endif
463static void key_porttosaddr(struct sockaddr *, u_int16_t);
464#define	KEY_PORTTOSADDR(saddr, port)				\
465	key_porttosaddr((struct sockaddr *)(saddr), (port))
466static struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
467static struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
468	u_int32_t));
469static struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
470				     struct malloc_type *);
471static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
472					    struct malloc_type *type);
473#ifdef INET6
474static int key_ismyaddr6 __P((struct sockaddr_in6 *));
475#endif
476
477/* flags for key_cmpsaidx() */
478#define CMP_HEAD	1	/* protocol, addresses. */
479#define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
480#define CMP_REQID	3	/* additionally HEAD, reaid. */
481#define CMP_EXACTLY	4	/* all elements. */
482static int key_cmpsaidx
483	__P((const struct secasindex *, const struct secasindex *, int));
484
485static int key_cmpspidx_exactly
486	__P((struct secpolicyindex *, struct secpolicyindex *));
487static int key_cmpspidx_withmask
488	__P((struct secpolicyindex *, struct secpolicyindex *));
489static int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
490static int key_bbcmp __P((const void *, const void *, u_int));
491static u_int16_t key_satype2proto __P((u_int8_t));
492static u_int8_t key_proto2satype __P((u_int16_t));
493
494static int key_getspi __P((struct socket *, struct mbuf *,
495	const struct sadb_msghdr *));
496static u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
497					struct secasindex *));
498static int key_update __P((struct socket *, struct mbuf *,
499	const struct sadb_msghdr *));
500#ifdef IPSEC_DOSEQCHECK
501static struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
502#endif
503static int key_add __P((struct socket *, struct mbuf *,
504	const struct sadb_msghdr *));
505static int key_setident __P((struct secashead *, struct mbuf *,
506	const struct sadb_msghdr *));
507static struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
508	const struct sadb_msghdr *));
509static int key_delete __P((struct socket *, struct mbuf *,
510	const struct sadb_msghdr *));
511static int key_get __P((struct socket *, struct mbuf *,
512	const struct sadb_msghdr *));
513
514static void key_getcomb_setlifetime __P((struct sadb_comb *));
515static struct mbuf *key_getcomb_esp __P((void));
516static struct mbuf *key_getcomb_ah __P((void));
517static struct mbuf *key_getcomb_ipcomp __P((void));
518static struct mbuf *key_getprop __P((const struct secasindex *));
519
520static int key_acquire __P((const struct secasindex *, struct secpolicy *));
521static struct secacq *key_newacq __P((const struct secasindex *));
522static struct secacq *key_getacq __P((const struct secasindex *));
523static struct secacq *key_getacqbyseq __P((u_int32_t));
524static struct secspacq *key_newspacq __P((struct secpolicyindex *));
525static struct secspacq *key_getspacq __P((struct secpolicyindex *));
526static int key_acquire2 __P((struct socket *, struct mbuf *,
527	const struct sadb_msghdr *));
528static int key_register __P((struct socket *, struct mbuf *,
529	const struct sadb_msghdr *));
530static int key_expire __P((struct secasvar *));
531static int key_flush __P((struct socket *, struct mbuf *,
532	const struct sadb_msghdr *));
533static int key_dump __P((struct socket *, struct mbuf *,
534	const struct sadb_msghdr *));
535static int key_promisc __P((struct socket *, struct mbuf *,
536	const struct sadb_msghdr *));
537static int key_senderror __P((struct socket *, struct mbuf *, int));
538static int key_validate_ext __P((const struct sadb_ext *, int));
539static int key_align __P((struct mbuf *, struct sadb_msghdr *));
540static struct mbuf *key_setlifetime(struct seclifetime *src,
541				     u_int16_t exttype);
542static struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
543
544#if 0
545static const char *key_getfqdn __P((void));
546static const char *key_getuserfqdn __P((void));
547#endif
548static void key_sa_chgstate __P((struct secasvar *, u_int8_t));
549static struct mbuf *key_alloc_mbuf __P((int));
550
551static __inline void
552sa_initref(struct secasvar *sav)
553{
554
555	refcount_init(&sav->refcnt, 1);
556}
557static __inline void
558sa_addref(struct secasvar *sav)
559{
560
561	refcount_acquire(&sav->refcnt);
562	IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
563}
564static __inline int
565sa_delref(struct secasvar *sav)
566{
567
568	IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
569	return (refcount_release(&sav->refcnt));
570}
571
572#define	SP_ADDREF(p) do {						\
573	(p)->refcnt++;							\
574	IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));		\
575} while (0)
576#define	SP_DELREF(p) do {						\
577	IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));		\
578	(p)->refcnt--;							\
579} while (0)
580
581
582/*
583 * Update the refcnt while holding the SPTREE lock.
584 */
585void
586key_addref(struct secpolicy *sp)
587{
588	SPTREE_LOCK();
589	SP_ADDREF(sp);
590	SPTREE_UNLOCK();
591}
592
593/*
594 * Return 0 when there are known to be no SP's for the specified
595 * direction.  Otherwise return 1.  This is used by IPsec code
596 * to optimize performance.
597 */
598int
599key_havesp(u_int dir)
600{
601
602	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
603		LIST_FIRST(&V_sptree[dir]) != NULL : 1);
604}
605
606/* %%% IPsec policy management */
607/*
608 * allocating a SP for OUTBOUND or INBOUND packet.
609 * Must call key_freesp() later.
610 * OUT:	NULL:	not found
611 *	others:	found and return the pointer.
612 */
613struct secpolicy *
614key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
615{
616	struct secpolicy *sp;
617
618	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
619	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
620		("invalid direction %u", dir));
621
622	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
623		printf("DP %s from %s:%u\n", __func__, where, tag));
624
625	/* get a SP entry */
626	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
627		printf("*** objects\n");
628		kdebug_secpolicyindex(spidx));
629
630	SPTREE_LOCK();
631	LIST_FOREACH(sp, &V_sptree[dir], chain) {
632		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
633			printf("*** in SPD\n");
634			kdebug_secpolicyindex(&sp->spidx));
635
636		if (sp->state == IPSEC_SPSTATE_DEAD)
637			continue;
638		if (key_cmpspidx_withmask(&sp->spidx, spidx))
639			goto found;
640	}
641	sp = NULL;
642found:
643	if (sp) {
644		/* sanity check */
645		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
646
647		/* found a SPD entry */
648		sp->lastused = time_second;
649		SP_ADDREF(sp);
650	}
651	SPTREE_UNLOCK();
652
653	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
654		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
655			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
656	return sp;
657}
658
659/*
660 * allocating a SP for OUTBOUND or INBOUND packet.
661 * Must call key_freesp() later.
662 * OUT:	NULL:	not found
663 *	others:	found and return the pointer.
664 */
665struct secpolicy *
666key_allocsp2(u_int32_t spi,
667	     union sockaddr_union *dst,
668	     u_int8_t proto,
669	     u_int dir,
670	     const char* where, int tag)
671{
672	struct secpolicy *sp;
673
674	IPSEC_ASSERT(dst != NULL, ("null dst"));
675	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
676		("invalid direction %u", dir));
677
678	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
679		printf("DP %s from %s:%u\n", __func__, where, tag));
680
681	/* get a SP entry */
682	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
683		printf("*** objects\n");
684		printf("spi %u proto %u dir %u\n", spi, proto, dir);
685		kdebug_sockaddr(&dst->sa));
686
687	SPTREE_LOCK();
688	LIST_FOREACH(sp, &V_sptree[dir], chain) {
689		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
690			printf("*** in SPD\n");
691			kdebug_secpolicyindex(&sp->spidx));
692
693		if (sp->state == IPSEC_SPSTATE_DEAD)
694			continue;
695		/* compare simple values, then dst address */
696		if (sp->spidx.ul_proto != proto)
697			continue;
698		/* NB: spi's must exist and match */
699		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
700			continue;
701		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
702			goto found;
703	}
704	sp = NULL;
705found:
706	if (sp) {
707		/* sanity check */
708		KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
709
710		/* found a SPD entry */
711		sp->lastused = time_second;
712		SP_ADDREF(sp);
713	}
714	SPTREE_UNLOCK();
715
716	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
717		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
718			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
719	return sp;
720}
721
722#if 0
723/*
724 * return a policy that matches this particular inbound packet.
725 * XXX slow
726 */
727struct secpolicy *
728key_gettunnel(const struct sockaddr *osrc,
729	      const struct sockaddr *odst,
730	      const struct sockaddr *isrc,
731	      const struct sockaddr *idst,
732	      const char* where, int tag)
733{
734	struct secpolicy *sp;
735	const int dir = IPSEC_DIR_INBOUND;
736	struct ipsecrequest *r1, *r2, *p;
737	struct secpolicyindex spidx;
738
739	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
740		printf("DP %s from %s:%u\n", __func__, where, tag));
741
742	if (isrc->sa_family != idst->sa_family) {
743		ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
744			__func__, isrc->sa_family, idst->sa_family));
745		sp = NULL;
746		goto done;
747	}
748
749	SPTREE_LOCK();
750	LIST_FOREACH(sp, &V_sptree[dir], chain) {
751		if (sp->state == IPSEC_SPSTATE_DEAD)
752			continue;
753
754		r1 = r2 = NULL;
755		for (p = sp->req; p; p = p->next) {
756			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
757				continue;
758
759			r1 = r2;
760			r2 = p;
761
762			if (!r1) {
763				/* here we look at address matches only */
764				spidx = sp->spidx;
765				if (isrc->sa_len > sizeof(spidx.src) ||
766				    idst->sa_len > sizeof(spidx.dst))
767					continue;
768				bcopy(isrc, &spidx.src, isrc->sa_len);
769				bcopy(idst, &spidx.dst, idst->sa_len);
770				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
771					continue;
772			} else {
773				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
774				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
775					continue;
776			}
777
778			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
779			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
780				continue;
781
782			goto found;
783		}
784	}
785	sp = NULL;
786found:
787	if (sp) {
788		sp->lastused = time_second;
789		SP_ADDREF(sp);
790	}
791	SPTREE_UNLOCK();
792done:
793	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
794		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
795			sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
796	return sp;
797}
798#endif
799
800/*
801 * allocating an SA entry for an *OUTBOUND* packet.
802 * checking each request entries in SP, and acquire an SA if need.
803 * OUT:	0: there are valid requests.
804 *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
805 */
806int
807key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
808{
809	u_int level;
810	int error;
811
812	IPSEC_ASSERT(isr != NULL, ("null isr"));
813	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
814	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
815		saidx->mode == IPSEC_MODE_TUNNEL,
816		("unexpected policy %u", saidx->mode));
817
818	/*
819	 * XXX guard against protocol callbacks from the crypto
820	 * thread as they reference ipsecrequest.sav which we
821	 * temporarily null out below.  Need to rethink how we
822	 * handle bundled SA's in the callback thread.
823	 */
824	IPSECREQUEST_LOCK_ASSERT(isr);
825
826	/* get current level */
827	level = ipsec_get_reqlevel(isr);
828#if 0
829	/*
830	 * We do allocate new SA only if the state of SA in the holder is
831	 * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
832	 */
833	if (isr->sav != NULL) {
834		if (isr->sav->sah == NULL)
835			panic("%s: sah is null.\n", __func__);
836		if (isr->sav == (struct secasvar *)LIST_FIRST(
837			    &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
838			KEY_FREESAV(&isr->sav);
839			isr->sav = NULL;
840		}
841	}
842#else
843	/*
844	 * we free any SA stashed in the IPsec request because a different
845	 * SA may be involved each time this request is checked, either
846	 * because new SAs are being configured, or this request is
847	 * associated with an unconnected datagram socket, or this request
848	 * is associated with a system default policy.
849	 *
850	 * The operation may have negative impact to performance.  We may
851	 * want to check cached SA carefully, rather than picking new SA
852	 * every time.
853	 */
854	if (isr->sav != NULL) {
855		KEY_FREESAV(&isr->sav);
856		isr->sav = NULL;
857	}
858#endif
859
860	/*
861	 * new SA allocation if no SA found.
862	 * key_allocsa_policy should allocate the oldest SA available.
863	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
864	 */
865	if (isr->sav == NULL)
866		isr->sav = key_allocsa_policy(saidx);
867
868	/* When there is SA. */
869	if (isr->sav != NULL) {
870		if (isr->sav->state != SADB_SASTATE_MATURE &&
871		    isr->sav->state != SADB_SASTATE_DYING)
872			return EINVAL;
873		return 0;
874	}
875
876	/* there is no SA */
877	error = key_acquire(saidx, isr->sp);
878	if (error != 0) {
879		/* XXX What should I do ? */
880		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
881			__func__, error));
882		return error;
883	}
884
885	if (level != IPSEC_LEVEL_REQUIRE) {
886		/* XXX sigh, the interface to this routine is botched */
887		IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
888		return 0;
889	} else {
890		return ENOENT;
891	}
892}
893
894/*
895 * allocating a SA for policy entry from SAD.
896 * NOTE: searching SAD of aliving state.
897 * OUT:	NULL:	not found.
898 *	others:	found and return the pointer.
899 */
900static struct secasvar *
901key_allocsa_policy(const struct secasindex *saidx)
902{
903#define	N(a)	_ARRAYLEN(a)
904	struct secashead *sah;
905	struct secasvar *sav;
906	u_int stateidx, arraysize;
907	const u_int *state_valid;
908
909	state_valid = NULL;	/* silence gcc */
910	arraysize = 0;		/* silence gcc */
911
912	SAHTREE_LOCK();
913	LIST_FOREACH(sah, &V_sahtree, chain) {
914		if (sah->state == SADB_SASTATE_DEAD)
915			continue;
916		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
917			if (V_key_preferred_oldsa) {
918				state_valid = saorder_state_valid_prefer_old;
919				arraysize = N(saorder_state_valid_prefer_old);
920			} else {
921				state_valid = saorder_state_valid_prefer_new;
922				arraysize = N(saorder_state_valid_prefer_new);
923			}
924			break;
925		}
926	}
927	SAHTREE_UNLOCK();
928	if (sah == NULL)
929		return NULL;
930
931	/* search valid state */
932	for (stateidx = 0; stateidx < arraysize; stateidx++) {
933		sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
934		if (sav != NULL)
935			return sav;
936	}
937
938	return NULL;
939#undef N
940}
941
942/*
943 * searching SAD with direction, protocol, mode and state.
944 * called by key_allocsa_policy().
945 * OUT:
946 *	NULL	: not found
947 *	others	: found, pointer to a SA.
948 */
949static struct secasvar *
950key_do_allocsa_policy(struct secashead *sah, u_int state)
951{
952	struct secasvar *sav, *nextsav, *candidate, *d;
953
954	/* initilize */
955	candidate = NULL;
956
957	SAHTREE_LOCK();
958	for (sav = LIST_FIRST(&sah->savtree[state]);
959	     sav != NULL;
960	     sav = nextsav) {
961
962		nextsav = LIST_NEXT(sav, chain);
963
964		/* sanity check */
965		KEY_CHKSASTATE(sav->state, state, __func__);
966
967		/* initialize */
968		if (candidate == NULL) {
969			candidate = sav;
970			continue;
971		}
972
973		/* Which SA is the better ? */
974
975		IPSEC_ASSERT(candidate->lft_c != NULL,
976			("null candidate lifetime"));
977		IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
978
979		/* What the best method is to compare ? */
980		if (V_key_preferred_oldsa) {
981			if (candidate->lft_c->addtime >
982					sav->lft_c->addtime) {
983				candidate = sav;
984			}
985			continue;
986			/*NOTREACHED*/
987		}
988
989		/* preferred new sa rather than old sa */
990		if (candidate->lft_c->addtime <
991				sav->lft_c->addtime) {
992			d = candidate;
993			candidate = sav;
994		} else
995			d = sav;
996
997		/*
998		 * prepared to delete the SA when there is more
999		 * suitable candidate and the lifetime of the SA is not
1000		 * permanent.
1001		 */
1002		if (d->lft_h->addtime != 0) {
1003			struct mbuf *m, *result;
1004			u_int8_t satype;
1005
1006			key_sa_chgstate(d, SADB_SASTATE_DEAD);
1007
1008			IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
1009
1010			satype = key_proto2satype(d->sah->saidx.proto);
1011			if (satype == 0)
1012				goto msgfail;
1013
1014			m = key_setsadbmsg(SADB_DELETE, 0,
1015			    satype, 0, 0, d->refcnt - 1);
1016			if (!m)
1017				goto msgfail;
1018			result = m;
1019
1020			/* set sadb_address for saidx's. */
1021			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
1022				&d->sah->saidx.src.sa,
1023				d->sah->saidx.src.sa.sa_len << 3,
1024				IPSEC_ULPROTO_ANY);
1025			if (!m)
1026				goto msgfail;
1027			m_cat(result, m);
1028
1029			/* set sadb_address for saidx's. */
1030			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
1031				&d->sah->saidx.dst.sa,
1032				d->sah->saidx.dst.sa.sa_len << 3,
1033				IPSEC_ULPROTO_ANY);
1034			if (!m)
1035				goto msgfail;
1036			m_cat(result, m);
1037
1038			/* create SA extension */
1039			m = key_setsadbsa(d);
1040			if (!m)
1041				goto msgfail;
1042			m_cat(result, m);
1043
1044			if (result->m_len < sizeof(struct sadb_msg)) {
1045				result = m_pullup(result,
1046						sizeof(struct sadb_msg));
1047				if (result == NULL)
1048					goto msgfail;
1049			}
1050
1051			result->m_pkthdr.len = 0;
1052			for (m = result; m; m = m->m_next)
1053				result->m_pkthdr.len += m->m_len;
1054			mtod(result, struct sadb_msg *)->sadb_msg_len =
1055				PFKEY_UNIT64(result->m_pkthdr.len);
1056
1057			if (key_sendup_mbuf(NULL, result,
1058					KEY_SENDUP_REGISTERED))
1059				goto msgfail;
1060		 msgfail:
1061			KEY_FREESAV(&d);
1062		}
1063	}
1064	if (candidate) {
1065		sa_addref(candidate);
1066		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1067			printf("DP %s cause refcnt++:%d SA:%p\n",
1068				__func__, candidate->refcnt, candidate));
1069	}
1070	SAHTREE_UNLOCK();
1071
1072	return candidate;
1073}
1074
1075/*
1076 * allocating a usable SA entry for a *INBOUND* packet.
1077 * Must call key_freesav() later.
1078 * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
1079 *	NULL:		not found, or error occured.
1080 *
1081 * In the comparison, no source address is used--for RFC2401 conformance.
1082 * To quote, from section 4.1:
1083 *	A security association is uniquely identified by a triple consisting
1084 *	of a Security Parameter Index (SPI), an IP Destination Address, and a
1085 *	security protocol (AH or ESP) identifier.
1086 * Note that, however, we do need to keep source address in IPsec SA.
1087 * IKE specification and PF_KEY specification do assume that we
1088 * keep source address in IPsec SA.  We see a tricky situation here.
1089 */
1090struct secasvar *
1091key_allocsa(
1092	union sockaddr_union *dst,
1093	u_int proto,
1094	u_int32_t spi,
1095	const char* where, int tag)
1096{
1097	struct secashead *sah;
1098	struct secasvar *sav;
1099	u_int stateidx, arraysize, state;
1100	const u_int *saorder_state_valid;
1101	int chkport;
1102
1103	IPSEC_ASSERT(dst != NULL, ("null dst address"));
1104
1105	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1106		printf("DP %s from %s:%u\n", __func__, where, tag));
1107
1108#ifdef IPSEC_NAT_T
1109        chkport = (dst->sa.sa_family == AF_INET &&
1110	    dst->sa.sa_len == sizeof(struct sockaddr_in) &&
1111	    dst->sin.sin_port != 0);
1112#else
1113	chkport = 0;
1114#endif
1115
1116	/*
1117	 * searching SAD.
1118	 * XXX: to be checked internal IP header somewhere.  Also when
1119	 * IPsec tunnel packet is received.  But ESP tunnel mode is
1120	 * encrypted so we can't check internal IP header.
1121	 */
1122	SAHTREE_LOCK();
1123	if (V_key_preferred_oldsa) {
1124		saorder_state_valid = saorder_state_valid_prefer_old;
1125		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1126	} else {
1127		saorder_state_valid = saorder_state_valid_prefer_new;
1128		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1129	}
1130	LIST_FOREACH(sah, &V_sahtree, chain) {
1131		/* search valid state */
1132		for (stateidx = 0; stateidx < arraysize; stateidx++) {
1133			state = saorder_state_valid[stateidx];
1134			LIST_FOREACH(sav, &sah->savtree[state], chain) {
1135				/* sanity check */
1136				KEY_CHKSASTATE(sav->state, state, __func__);
1137				/* do not return entries w/ unusable state */
1138				if (sav->state != SADB_SASTATE_MATURE &&
1139				    sav->state != SADB_SASTATE_DYING)
1140					continue;
1141				if (proto != sav->sah->saidx.proto)
1142					continue;
1143				if (spi != sav->spi)
1144					continue;
1145#if 0	/* don't check src */
1146				/* check src address */
1147				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, chkport) != 0)
1148					continue;
1149#endif
1150				/* check dst address */
1151				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, chkport) != 0)
1152					continue;
1153				sa_addref(sav);
1154				goto done;
1155			}
1156		}
1157	}
1158	sav = NULL;
1159done:
1160	SAHTREE_UNLOCK();
1161
1162	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1163		printf("DP %s return SA:%p; refcnt %u\n", __func__,
1164			sav, sav ? sav->refcnt : 0));
1165	return sav;
1166}
1167
1168/*
1169 * Must be called after calling key_allocsp().
1170 * For both the packet without socket and key_freeso().
1171 */
1172void
1173_key_freesp(struct secpolicy **spp, const char* where, int tag)
1174{
1175	struct secpolicy *sp = *spp;
1176
1177	IPSEC_ASSERT(sp != NULL, ("null sp"));
1178
1179	SPTREE_LOCK();
1180	SP_DELREF(sp);
1181
1182	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1183		printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1184			__func__, sp, sp->id, where, tag, sp->refcnt));
1185
1186	if (sp->refcnt == 0) {
1187		*spp = NULL;
1188		key_delsp(sp);
1189	}
1190	SPTREE_UNLOCK();
1191}
1192
1193/*
1194 * Must be called after calling key_allocsp().
1195 * For the packet with socket.
1196 */
1197void
1198key_freeso(struct socket *so)
1199{
1200	IPSEC_ASSERT(so != NULL, ("null so"));
1201
1202	switch (so->so_proto->pr_domain->dom_family) {
1203#if defined(INET) || defined(INET6)
1204#ifdef INET
1205	case PF_INET:
1206#endif
1207#ifdef INET6
1208	case PF_INET6:
1209#endif
1210	    {
1211		struct inpcb *pcb = sotoinpcb(so);
1212
1213		/* Does it have a PCB ? */
1214		if (pcb == NULL)
1215			return;
1216		key_freesp_so(&pcb->inp_sp->sp_in);
1217		key_freesp_so(&pcb->inp_sp->sp_out);
1218	    }
1219		break;
1220#endif /* INET || INET6 */
1221	default:
1222		ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1223		    __func__, so->so_proto->pr_domain->dom_family));
1224		return;
1225	}
1226}
1227
1228static void
1229key_freesp_so(struct secpolicy **sp)
1230{
1231	IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1232
1233	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1234	    (*sp)->policy == IPSEC_POLICY_BYPASS)
1235		return;
1236
1237	IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1238		("invalid policy %u", (*sp)->policy));
1239	KEY_FREESP(sp);
1240}
1241
1242/*
1243 * Must be called after calling key_allocsa().
1244 * This function is called by key_freesp() to free some SA allocated
1245 * for a policy.
1246 */
1247void
1248key_freesav(struct secasvar **psav, const char* where, int tag)
1249{
1250	struct secasvar *sav = *psav;
1251
1252	IPSEC_ASSERT(sav != NULL, ("null sav"));
1253
1254	if (sa_delref(sav)) {
1255		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1256			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1257				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1258		*psav = NULL;
1259		key_delsav(sav);
1260	} else {
1261		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1262			printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1263				__func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1264	}
1265}
1266
1267/* %%% SPD management */
1268/*
1269 * free security policy entry.
1270 */
1271static void
1272key_delsp(struct secpolicy *sp)
1273{
1274	struct ipsecrequest *isr, *nextisr;
1275
1276	IPSEC_ASSERT(sp != NULL, ("null sp"));
1277	SPTREE_LOCK_ASSERT();
1278
1279	sp->state = IPSEC_SPSTATE_DEAD;
1280
1281	IPSEC_ASSERT(sp->refcnt == 0,
1282		("SP with references deleted (refcnt %u)", sp->refcnt));
1283
1284	/* remove from SP index */
1285	if (__LIST_CHAINED(sp))
1286		LIST_REMOVE(sp, chain);
1287
1288	for (isr = sp->req; isr != NULL; isr = nextisr) {
1289		if (isr->sav != NULL) {
1290			KEY_FREESAV(&isr->sav);
1291			isr->sav = NULL;
1292		}
1293
1294		nextisr = isr->next;
1295		ipsec_delisr(isr);
1296	}
1297	_key_delsp(sp);
1298}
1299
1300/*
1301 * search SPD
1302 * OUT:	NULL	: not found
1303 *	others	: found, pointer to a SP.
1304 */
1305static struct secpolicy *
1306key_getsp(struct secpolicyindex *spidx)
1307{
1308	struct secpolicy *sp;
1309
1310	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1311
1312	SPTREE_LOCK();
1313	LIST_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1314		if (sp->state == IPSEC_SPSTATE_DEAD)
1315			continue;
1316		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1317			SP_ADDREF(sp);
1318			break;
1319		}
1320	}
1321	SPTREE_UNLOCK();
1322
1323	return sp;
1324}
1325
1326/*
1327 * get SP by index.
1328 * OUT:	NULL	: not found
1329 *	others	: found, pointer to a SP.
1330 */
1331static struct secpolicy *
1332key_getspbyid(u_int32_t id)
1333{
1334	struct secpolicy *sp;
1335
1336	SPTREE_LOCK();
1337	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
1338		if (sp->state == IPSEC_SPSTATE_DEAD)
1339			continue;
1340		if (sp->id == id) {
1341			SP_ADDREF(sp);
1342			goto done;
1343		}
1344	}
1345
1346	LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
1347		if (sp->state == IPSEC_SPSTATE_DEAD)
1348			continue;
1349		if (sp->id == id) {
1350			SP_ADDREF(sp);
1351			goto done;
1352		}
1353	}
1354done:
1355	SPTREE_UNLOCK();
1356
1357	return sp;
1358}
1359
1360struct secpolicy *
1361key_newsp(const char* where, int tag)
1362{
1363	struct secpolicy *newsp = NULL;
1364
1365	newsp = (struct secpolicy *)
1366		malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1367	if (newsp) {
1368		SECPOLICY_LOCK_INIT(newsp);
1369		newsp->refcnt = 1;
1370		newsp->req = NULL;
1371	}
1372
1373	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1374		printf("DP %s from %s:%u return SP:%p\n", __func__,
1375			where, tag, newsp));
1376	return newsp;
1377}
1378
1379static void
1380_key_delsp(struct secpolicy *sp)
1381{
1382	SECPOLICY_LOCK_DESTROY(sp);
1383	free(sp, M_IPSEC_SP);
1384}
1385
1386/*
1387 * create secpolicy structure from sadb_x_policy structure.
1388 * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1389 * so must be set properly later.
1390 */
1391struct secpolicy *
1392key_msg2sp(xpl0, len, error)
1393	struct sadb_x_policy *xpl0;
1394	size_t len;
1395	int *error;
1396{
1397	struct secpolicy *newsp;
1398
1399	IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1400	IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1401
1402	if (len != PFKEY_EXTLEN(xpl0)) {
1403		ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1404		*error = EINVAL;
1405		return NULL;
1406	}
1407
1408	if ((newsp = KEY_NEWSP()) == NULL) {
1409		*error = ENOBUFS;
1410		return NULL;
1411	}
1412
1413	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1414	newsp->policy = xpl0->sadb_x_policy_type;
1415
1416	/* check policy */
1417	switch (xpl0->sadb_x_policy_type) {
1418	case IPSEC_POLICY_DISCARD:
1419	case IPSEC_POLICY_NONE:
1420	case IPSEC_POLICY_ENTRUST:
1421	case IPSEC_POLICY_BYPASS:
1422		newsp->req = NULL;
1423		break;
1424
1425	case IPSEC_POLICY_IPSEC:
1426	    {
1427		int tlen;
1428		struct sadb_x_ipsecrequest *xisr;
1429		struct ipsecrequest **p_isr = &newsp->req;
1430
1431		/* validity check */
1432		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1433			ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1434				__func__));
1435			KEY_FREESP(&newsp);
1436			*error = EINVAL;
1437			return NULL;
1438		}
1439
1440		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1441		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1442
1443		while (tlen > 0) {
1444			/* length check */
1445			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1446				ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1447					"length.\n", __func__));
1448				KEY_FREESP(&newsp);
1449				*error = EINVAL;
1450				return NULL;
1451			}
1452
1453			/* allocate request buffer */
1454			/* NB: data structure is zero'd */
1455			*p_isr = ipsec_newisr();
1456			if ((*p_isr) == NULL) {
1457				ipseclog((LOG_DEBUG,
1458				    "%s: No more memory.\n", __func__));
1459				KEY_FREESP(&newsp);
1460				*error = ENOBUFS;
1461				return NULL;
1462			}
1463
1464			/* set values */
1465			switch (xisr->sadb_x_ipsecrequest_proto) {
1466			case IPPROTO_ESP:
1467			case IPPROTO_AH:
1468			case IPPROTO_IPCOMP:
1469				break;
1470			default:
1471				ipseclog((LOG_DEBUG,
1472				    "%s: invalid proto type=%u\n", __func__,
1473				    xisr->sadb_x_ipsecrequest_proto));
1474				KEY_FREESP(&newsp);
1475				*error = EPROTONOSUPPORT;
1476				return NULL;
1477			}
1478			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1479
1480			switch (xisr->sadb_x_ipsecrequest_mode) {
1481			case IPSEC_MODE_TRANSPORT:
1482			case IPSEC_MODE_TUNNEL:
1483				break;
1484			case IPSEC_MODE_ANY:
1485			default:
1486				ipseclog((LOG_DEBUG,
1487				    "%s: invalid mode=%u\n", __func__,
1488				    xisr->sadb_x_ipsecrequest_mode));
1489				KEY_FREESP(&newsp);
1490				*error = EINVAL;
1491				return NULL;
1492			}
1493			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1494
1495			switch (xisr->sadb_x_ipsecrequest_level) {
1496			case IPSEC_LEVEL_DEFAULT:
1497			case IPSEC_LEVEL_USE:
1498			case IPSEC_LEVEL_REQUIRE:
1499				break;
1500			case IPSEC_LEVEL_UNIQUE:
1501				/* validity check */
1502				/*
1503				 * If range violation of reqid, kernel will
1504				 * update it, don't refuse it.
1505				 */
1506				if (xisr->sadb_x_ipsecrequest_reqid
1507						> IPSEC_MANUAL_REQID_MAX) {
1508					ipseclog((LOG_DEBUG,
1509					    "%s: reqid=%d range "
1510					    "violation, updated by kernel.\n",
1511					    __func__,
1512					    xisr->sadb_x_ipsecrequest_reqid));
1513					xisr->sadb_x_ipsecrequest_reqid = 0;
1514				}
1515
1516				/* allocate new reqid id if reqid is zero. */
1517				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1518					u_int32_t reqid;
1519					if ((reqid = key_newreqid()) == 0) {
1520						KEY_FREESP(&newsp);
1521						*error = ENOBUFS;
1522						return NULL;
1523					}
1524					(*p_isr)->saidx.reqid = reqid;
1525					xisr->sadb_x_ipsecrequest_reqid = reqid;
1526				} else {
1527				/* set it for manual keying. */
1528					(*p_isr)->saidx.reqid =
1529						xisr->sadb_x_ipsecrequest_reqid;
1530				}
1531				break;
1532
1533			default:
1534				ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1535					__func__,
1536					xisr->sadb_x_ipsecrequest_level));
1537				KEY_FREESP(&newsp);
1538				*error = EINVAL;
1539				return NULL;
1540			}
1541			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1542
1543			/* set IP addresses if there */
1544			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1545				struct sockaddr *paddr;
1546
1547				paddr = (struct sockaddr *)(xisr + 1);
1548
1549				/* validity check */
1550				if (paddr->sa_len
1551				    > sizeof((*p_isr)->saidx.src)) {
1552					ipseclog((LOG_DEBUG, "%s: invalid "
1553						"request address length.\n",
1554						__func__));
1555					KEY_FREESP(&newsp);
1556					*error = EINVAL;
1557					return NULL;
1558				}
1559				bcopy(paddr, &(*p_isr)->saidx.src,
1560					paddr->sa_len);
1561
1562				paddr = (struct sockaddr *)((caddr_t)paddr
1563							+ paddr->sa_len);
1564
1565				/* validity check */
1566				if (paddr->sa_len
1567				    > sizeof((*p_isr)->saidx.dst)) {
1568					ipseclog((LOG_DEBUG, "%s: invalid "
1569						"request address length.\n",
1570						__func__));
1571					KEY_FREESP(&newsp);
1572					*error = EINVAL;
1573					return NULL;
1574				}
1575				bcopy(paddr, &(*p_isr)->saidx.dst,
1576					paddr->sa_len);
1577			}
1578
1579			(*p_isr)->sp = newsp;
1580
1581			/* initialization for the next. */
1582			p_isr = &(*p_isr)->next;
1583			tlen -= xisr->sadb_x_ipsecrequest_len;
1584
1585			/* validity check */
1586			if (tlen < 0) {
1587				ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1588					__func__));
1589				KEY_FREESP(&newsp);
1590				*error = EINVAL;
1591				return NULL;
1592			}
1593
1594			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1595			                 + xisr->sadb_x_ipsecrequest_len);
1596		}
1597	    }
1598		break;
1599	default:
1600		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1601		KEY_FREESP(&newsp);
1602		*error = EINVAL;
1603		return NULL;
1604	}
1605
1606	*error = 0;
1607	return newsp;
1608}
1609
1610static u_int32_t
1611key_newreqid()
1612{
1613	static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1614
1615	auto_reqid = (auto_reqid == ~0
1616			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1617
1618	/* XXX should be unique check */
1619
1620	return auto_reqid;
1621}
1622
1623/*
1624 * copy secpolicy struct to sadb_x_policy structure indicated.
1625 */
1626struct mbuf *
1627key_sp2msg(sp)
1628	struct secpolicy *sp;
1629{
1630	struct sadb_x_policy *xpl;
1631	int tlen;
1632	caddr_t p;
1633	struct mbuf *m;
1634
1635	IPSEC_ASSERT(sp != NULL, ("null policy"));
1636
1637	tlen = key_getspreqmsglen(sp);
1638
1639	m = key_alloc_mbuf(tlen);
1640	if (!m || m->m_next) {	/*XXX*/
1641		if (m)
1642			m_freem(m);
1643		return NULL;
1644	}
1645
1646	m->m_len = tlen;
1647	m->m_next = NULL;
1648	xpl = mtod(m, struct sadb_x_policy *);
1649	bzero(xpl, tlen);
1650
1651	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1652	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1653	xpl->sadb_x_policy_type = sp->policy;
1654	xpl->sadb_x_policy_dir = sp->spidx.dir;
1655	xpl->sadb_x_policy_id = sp->id;
1656	p = (caddr_t)xpl + sizeof(*xpl);
1657
1658	/* if is the policy for ipsec ? */
1659	if (sp->policy == IPSEC_POLICY_IPSEC) {
1660		struct sadb_x_ipsecrequest *xisr;
1661		struct ipsecrequest *isr;
1662
1663		for (isr = sp->req; isr != NULL; isr = isr->next) {
1664
1665			xisr = (struct sadb_x_ipsecrequest *)p;
1666
1667			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1668			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1669			xisr->sadb_x_ipsecrequest_level = isr->level;
1670			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1671
1672			p += sizeof(*xisr);
1673			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1674			p += isr->saidx.src.sa.sa_len;
1675			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1676			p += isr->saidx.src.sa.sa_len;
1677
1678			xisr->sadb_x_ipsecrequest_len =
1679				PFKEY_ALIGN8(sizeof(*xisr)
1680					+ isr->saidx.src.sa.sa_len
1681					+ isr->saidx.dst.sa.sa_len);
1682		}
1683	}
1684
1685	return m;
1686}
1687
1688/* m will not be freed nor modified */
1689static struct mbuf *
1690#ifdef __STDC__
1691key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1692	int ndeep, int nitem, ...)
1693#else
1694key_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1695	struct mbuf *m;
1696	const struct sadb_msghdr *mhp;
1697	int ndeep;
1698	int nitem;
1699	va_dcl
1700#endif
1701{
1702	va_list ap;
1703	int idx;
1704	int i;
1705	struct mbuf *result = NULL, *n;
1706	int len;
1707
1708	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1709	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1710
1711	va_start(ap, nitem);
1712	for (i = 0; i < nitem; i++) {
1713		idx = va_arg(ap, int);
1714		if (idx < 0 || idx > SADB_EXT_MAX)
1715			goto fail;
1716		/* don't attempt to pull empty extension */
1717		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1718			continue;
1719		if (idx != SADB_EXT_RESERVED  &&
1720		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1721			continue;
1722
1723		if (idx == SADB_EXT_RESERVED) {
1724			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1725
1726			IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1727
1728			MGETHDR(n, M_DONTWAIT, MT_DATA);
1729			if (!n)
1730				goto fail;
1731			n->m_len = len;
1732			n->m_next = NULL;
1733			m_copydata(m, 0, sizeof(struct sadb_msg),
1734			    mtod(n, caddr_t));
1735		} else if (i < ndeep) {
1736			len = mhp->extlen[idx];
1737			n = key_alloc_mbuf(len);
1738			if (!n || n->m_next) {	/*XXX*/
1739				if (n)
1740					m_freem(n);
1741				goto fail;
1742			}
1743			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1744			    mtod(n, caddr_t));
1745		} else {
1746			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1747			    M_DONTWAIT);
1748		}
1749		if (n == NULL)
1750			goto fail;
1751
1752		if (result)
1753			m_cat(result, n);
1754		else
1755			result = n;
1756	}
1757	va_end(ap);
1758
1759	if ((result->m_flags & M_PKTHDR) != 0) {
1760		result->m_pkthdr.len = 0;
1761		for (n = result; n; n = n->m_next)
1762			result->m_pkthdr.len += n->m_len;
1763	}
1764
1765	return result;
1766
1767fail:
1768	m_freem(result);
1769	return NULL;
1770}
1771
1772/*
1773 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1774 * add an entry to SP database, when received
1775 *   <base, address(SD), (lifetime(H),) policy>
1776 * from the user(?).
1777 * Adding to SP database,
1778 * and send
1779 *   <base, address(SD), (lifetime(H),) policy>
1780 * to the socket which was send.
1781 *
1782 * SPDADD set a unique policy entry.
1783 * SPDSETIDX like SPDADD without a part of policy requests.
1784 * SPDUPDATE replace a unique policy entry.
1785 *
1786 * m will always be freed.
1787 */
1788static int
1789key_spdadd(so, m, mhp)
1790	struct socket *so;
1791	struct mbuf *m;
1792	const struct sadb_msghdr *mhp;
1793{
1794	struct sadb_address *src0, *dst0;
1795	struct sadb_x_policy *xpl0, *xpl;
1796	struct sadb_lifetime *lft = NULL;
1797	struct secpolicyindex spidx;
1798	struct secpolicy *newsp;
1799	int error;
1800
1801	IPSEC_ASSERT(so != NULL, ("null socket"));
1802	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1803	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1804	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1805
1806	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1807	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1808	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1809		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1810		return key_senderror(so, m, EINVAL);
1811	}
1812	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1813	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1814	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1815		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1816			__func__));
1817		return key_senderror(so, m, EINVAL);
1818	}
1819	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1820		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1821			< sizeof(struct sadb_lifetime)) {
1822			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1823				__func__));
1824			return key_senderror(so, m, EINVAL);
1825		}
1826		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1827	}
1828
1829	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1830	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1831	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1832
1833	/*
1834	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
1835	 * we are processing traffic endpoints.
1836	 */
1837
1838	/* make secindex */
1839	/* XXX boundary check against sa_len */
1840	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1841	                src0 + 1,
1842	                dst0 + 1,
1843	                src0->sadb_address_prefixlen,
1844	                dst0->sadb_address_prefixlen,
1845	                src0->sadb_address_proto,
1846	                &spidx);
1847
1848	/* checking the direciton. */
1849	switch (xpl0->sadb_x_policy_dir) {
1850	case IPSEC_DIR_INBOUND:
1851	case IPSEC_DIR_OUTBOUND:
1852		break;
1853	default:
1854		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1855		mhp->msg->sadb_msg_errno = EINVAL;
1856		return 0;
1857	}
1858
1859	/* check policy */
1860	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1861	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1862	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1863		ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1864		return key_senderror(so, m, EINVAL);
1865	}
1866
1867	/* policy requests are mandatory when action is ipsec. */
1868        if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1869	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1870	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1871		ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1872			__func__));
1873		return key_senderror(so, m, EINVAL);
1874	}
1875
1876	/*
1877	 * checking there is SP already or not.
1878	 * SPDUPDATE doesn't depend on whether there is a SP or not.
1879	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1880	 * then error.
1881	 */
1882	newsp = key_getsp(&spidx);
1883	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1884		if (newsp) {
1885			newsp->state = IPSEC_SPSTATE_DEAD;
1886			KEY_FREESP(&newsp);
1887		}
1888	} else {
1889		if (newsp != NULL) {
1890			KEY_FREESP(&newsp);
1891			ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1892				__func__));
1893			return key_senderror(so, m, EEXIST);
1894		}
1895	}
1896
1897	/* allocation new SP entry */
1898	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1899		return key_senderror(so, m, error);
1900	}
1901
1902	if ((newsp->id = key_getnewspid()) == 0) {
1903		_key_delsp(newsp);
1904		return key_senderror(so, m, ENOBUFS);
1905	}
1906
1907	/* XXX boundary check against sa_len */
1908	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1909	                src0 + 1,
1910	                dst0 + 1,
1911	                src0->sadb_address_prefixlen,
1912	                dst0->sadb_address_prefixlen,
1913	                src0->sadb_address_proto,
1914	                &newsp->spidx);
1915
1916	/* sanity check on addr pair */
1917	if (((struct sockaddr *)(src0 + 1))->sa_family !=
1918			((struct sockaddr *)(dst0+ 1))->sa_family) {
1919		_key_delsp(newsp);
1920		return key_senderror(so, m, EINVAL);
1921	}
1922	if (((struct sockaddr *)(src0 + 1))->sa_len !=
1923			((struct sockaddr *)(dst0+ 1))->sa_len) {
1924		_key_delsp(newsp);
1925		return key_senderror(so, m, EINVAL);
1926	}
1927#if 1
1928	if (newsp->req && newsp->req->saidx.src.sa.sa_family && newsp->req->saidx.dst.sa.sa_family) {
1929		if (newsp->req->saidx.src.sa.sa_family != newsp->req->saidx.dst.sa.sa_family) {
1930			_key_delsp(newsp);
1931			return key_senderror(so, m, EINVAL);
1932		}
1933	}
1934#endif
1935
1936	newsp->created = time_second;
1937	newsp->lastused = newsp->created;
1938	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1939	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1940
1941	newsp->refcnt = 1;	/* do not reclaim until I say I do */
1942	newsp->state = IPSEC_SPSTATE_ALIVE;
1943	LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1944
1945	/* delete the entry in spacqtree */
1946	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1947		struct secspacq *spacq = key_getspacq(&spidx);
1948		if (spacq != NULL) {
1949			/* reset counter in order to deletion by timehandler. */
1950			spacq->created = time_second;
1951			spacq->count = 0;
1952			SPACQ_UNLOCK();
1953		}
1954    	}
1955
1956    {
1957	struct mbuf *n, *mpolicy;
1958	struct sadb_msg *newmsg;
1959	int off;
1960
1961	/*
1962	 * Note: do not send SADB_X_EXT_NAT_T_* here:
1963	 * we are sending traffic endpoints.
1964	 */
1965
1966	/* create new sadb_msg to reply. */
1967	if (lft) {
1968		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1969		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1970		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1971	} else {
1972		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1973		    SADB_X_EXT_POLICY,
1974		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1975	}
1976	if (!n)
1977		return key_senderror(so, m, ENOBUFS);
1978
1979	if (n->m_len < sizeof(*newmsg)) {
1980		n = m_pullup(n, sizeof(*newmsg));
1981		if (!n)
1982			return key_senderror(so, m, ENOBUFS);
1983	}
1984	newmsg = mtod(n, struct sadb_msg *);
1985	newmsg->sadb_msg_errno = 0;
1986	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1987
1988	off = 0;
1989	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1990	    sizeof(*xpl), &off);
1991	if (mpolicy == NULL) {
1992		/* n is already freed */
1993		return key_senderror(so, m, ENOBUFS);
1994	}
1995	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1996	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1997		m_freem(n);
1998		return key_senderror(so, m, EINVAL);
1999	}
2000	xpl->sadb_x_policy_id = newsp->id;
2001
2002	m_freem(m);
2003	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2004    }
2005}
2006
2007/*
2008 * get new policy id.
2009 * OUT:
2010 *	0:	failure.
2011 *	others: success.
2012 */
2013static u_int32_t
2014key_getnewspid()
2015{
2016	u_int32_t newid = 0;
2017	int count = V_key_spi_trycnt;	/* XXX */
2018	struct secpolicy *sp;
2019
2020	/* when requesting to allocate spi ranged */
2021	while (count--) {
2022		newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
2023
2024		if ((sp = key_getspbyid(newid)) == NULL)
2025			break;
2026
2027		KEY_FREESP(&sp);
2028	}
2029
2030	if (count == 0 || newid == 0) {
2031		ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2032			__func__));
2033		return 0;
2034	}
2035
2036	return newid;
2037}
2038
2039/*
2040 * SADB_SPDDELETE processing
2041 * receive
2042 *   <base, address(SD), policy(*)>
2043 * from the user(?), and set SADB_SASTATE_DEAD,
2044 * and send,
2045 *   <base, address(SD), policy(*)>
2046 * to the ikmpd.
2047 * policy(*) including direction of policy.
2048 *
2049 * m will always be freed.
2050 */
2051static int
2052key_spddelete(so, m, mhp)
2053	struct socket *so;
2054	struct mbuf *m;
2055	const struct sadb_msghdr *mhp;
2056{
2057	struct sadb_address *src0, *dst0;
2058	struct sadb_x_policy *xpl0;
2059	struct secpolicyindex spidx;
2060	struct secpolicy *sp;
2061
2062	IPSEC_ASSERT(so != NULL, ("null so"));
2063	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2064	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2065	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2066
2067	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2068	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2069	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2070		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2071			__func__));
2072		return key_senderror(so, m, EINVAL);
2073	}
2074	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2075	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2076	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2077		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2078			__func__));
2079		return key_senderror(so, m, EINVAL);
2080	}
2081
2082	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2083	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2084	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2085
2086	/*
2087	 * Note: do not parse SADB_X_EXT_NAT_T_* here:
2088	 * we are processing traffic endpoints.
2089	 */
2090
2091	/* make secindex */
2092	/* XXX boundary check against sa_len */
2093	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2094	                src0 + 1,
2095	                dst0 + 1,
2096	                src0->sadb_address_prefixlen,
2097	                dst0->sadb_address_prefixlen,
2098	                src0->sadb_address_proto,
2099	                &spidx);
2100
2101	/* checking the direciton. */
2102	switch (xpl0->sadb_x_policy_dir) {
2103	case IPSEC_DIR_INBOUND:
2104	case IPSEC_DIR_OUTBOUND:
2105		break;
2106	default:
2107		ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2108		return key_senderror(so, m, EINVAL);
2109	}
2110
2111	/* Is there SP in SPD ? */
2112	if ((sp = key_getsp(&spidx)) == NULL) {
2113		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2114		return key_senderror(so, m, EINVAL);
2115	}
2116
2117	/* save policy id to buffer to be returned. */
2118	xpl0->sadb_x_policy_id = sp->id;
2119
2120	sp->state = IPSEC_SPSTATE_DEAD;
2121	KEY_FREESP(&sp);
2122
2123    {
2124	struct mbuf *n;
2125	struct sadb_msg *newmsg;
2126
2127	/*
2128	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2129	 * we are sending traffic endpoints.
2130	 */
2131
2132	/* create new sadb_msg to reply. */
2133	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2134	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2135	if (!n)
2136		return key_senderror(so, m, ENOBUFS);
2137
2138	newmsg = mtod(n, struct sadb_msg *);
2139	newmsg->sadb_msg_errno = 0;
2140	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2141
2142	m_freem(m);
2143	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2144    }
2145}
2146
2147/*
2148 * SADB_SPDDELETE2 processing
2149 * receive
2150 *   <base, policy(*)>
2151 * from the user(?), and set SADB_SASTATE_DEAD,
2152 * and send,
2153 *   <base, policy(*)>
2154 * to the ikmpd.
2155 * policy(*) including direction of policy.
2156 *
2157 * m will always be freed.
2158 */
2159static int
2160key_spddelete2(so, m, mhp)
2161	struct socket *so;
2162	struct mbuf *m;
2163	const struct sadb_msghdr *mhp;
2164{
2165	u_int32_t id;
2166	struct secpolicy *sp;
2167
2168	IPSEC_ASSERT(so != NULL, ("null socket"));
2169	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2170	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2171	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2172
2173	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2174	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2175		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2176		return key_senderror(so, m, EINVAL);
2177	}
2178
2179	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2180
2181	/* Is there SP in SPD ? */
2182	if ((sp = key_getspbyid(id)) == NULL) {
2183		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2184		return key_senderror(so, m, EINVAL);
2185	}
2186
2187	sp->state = IPSEC_SPSTATE_DEAD;
2188	KEY_FREESP(&sp);
2189
2190    {
2191	struct mbuf *n, *nn;
2192	struct sadb_msg *newmsg;
2193	int off, len;
2194
2195	/* create new sadb_msg to reply. */
2196	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2197
2198	MGETHDR(n, M_DONTWAIT, MT_DATA);
2199	if (n && len > MHLEN) {
2200		MCLGET(n, M_DONTWAIT);
2201		if ((n->m_flags & M_EXT) == 0) {
2202			m_freem(n);
2203			n = NULL;
2204		}
2205	}
2206	if (!n)
2207		return key_senderror(so, m, ENOBUFS);
2208
2209	n->m_len = len;
2210	n->m_next = NULL;
2211	off = 0;
2212
2213	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2214	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2215
2216	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2217		off, len));
2218
2219	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2220	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2221	if (!n->m_next) {
2222		m_freem(n);
2223		return key_senderror(so, m, ENOBUFS);
2224	}
2225
2226	n->m_pkthdr.len = 0;
2227	for (nn = n; nn; nn = nn->m_next)
2228		n->m_pkthdr.len += nn->m_len;
2229
2230	newmsg = mtod(n, struct sadb_msg *);
2231	newmsg->sadb_msg_errno = 0;
2232	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2233
2234	m_freem(m);
2235	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2236    }
2237}
2238
2239/*
2240 * SADB_X_GET processing
2241 * receive
2242 *   <base, policy(*)>
2243 * from the user(?),
2244 * and send,
2245 *   <base, address(SD), policy>
2246 * to the ikmpd.
2247 * policy(*) including direction of policy.
2248 *
2249 * m will always be freed.
2250 */
2251static int
2252key_spdget(so, m, mhp)
2253	struct socket *so;
2254	struct mbuf *m;
2255	const struct sadb_msghdr *mhp;
2256{
2257	u_int32_t id;
2258	struct secpolicy *sp;
2259	struct mbuf *n;
2260
2261	IPSEC_ASSERT(so != NULL, ("null socket"));
2262	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2263	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2264	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2265
2266	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2267	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2268		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2269			__func__));
2270		return key_senderror(so, m, EINVAL);
2271	}
2272
2273	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2274
2275	/* Is there SP in SPD ? */
2276	if ((sp = key_getspbyid(id)) == NULL) {
2277		ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2278		return key_senderror(so, m, ENOENT);
2279	}
2280
2281	n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2282	if (n != NULL) {
2283		m_freem(m);
2284		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2285	} else
2286		return key_senderror(so, m, ENOBUFS);
2287}
2288
2289/*
2290 * SADB_X_SPDACQUIRE processing.
2291 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2292 * send
2293 *   <base, policy(*)>
2294 * to KMD, and expect to receive
2295 *   <base> with SADB_X_SPDACQUIRE if error occured,
2296 * or
2297 *   <base, policy>
2298 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2299 * policy(*) is without policy requests.
2300 *
2301 *    0     : succeed
2302 *    others: error number
2303 */
2304int
2305key_spdacquire(sp)
2306	struct secpolicy *sp;
2307{
2308	struct mbuf *result = NULL, *m;
2309	struct secspacq *newspacq;
2310
2311	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2312	IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2313	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2314		("policy not IPSEC %u", sp->policy));
2315
2316	/* Get an entry to check whether sent message or not. */
2317	newspacq = key_getspacq(&sp->spidx);
2318	if (newspacq != NULL) {
2319		if (V_key_blockacq_count < newspacq->count) {
2320			/* reset counter and do send message. */
2321			newspacq->count = 0;
2322		} else {
2323			/* increment counter and do nothing. */
2324			newspacq->count++;
2325			return 0;
2326		}
2327		SPACQ_UNLOCK();
2328	} else {
2329		/* make new entry for blocking to send SADB_ACQUIRE. */
2330		newspacq = key_newspacq(&sp->spidx);
2331		if (newspacq == NULL)
2332			return ENOBUFS;
2333	}
2334
2335	/* create new sadb_msg to reply. */
2336	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2337	if (!m)
2338		return ENOBUFS;
2339
2340	result = m;
2341
2342	result->m_pkthdr.len = 0;
2343	for (m = result; m; m = m->m_next)
2344		result->m_pkthdr.len += m->m_len;
2345
2346	mtod(result, struct sadb_msg *)->sadb_msg_len =
2347	    PFKEY_UNIT64(result->m_pkthdr.len);
2348
2349	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2350}
2351
2352/*
2353 * SADB_SPDFLUSH processing
2354 * receive
2355 *   <base>
2356 * from the user, and free all entries in secpctree.
2357 * and send,
2358 *   <base>
2359 * to the user.
2360 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2361 *
2362 * m will always be freed.
2363 */
2364static int
2365key_spdflush(so, m, mhp)
2366	struct socket *so;
2367	struct mbuf *m;
2368	const struct sadb_msghdr *mhp;
2369{
2370	struct sadb_msg *newmsg;
2371	struct secpolicy *sp;
2372	u_int dir;
2373
2374	IPSEC_ASSERT(so != NULL, ("null socket"));
2375	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2376	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2377	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2378
2379	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2380		return key_senderror(so, m, EINVAL);
2381
2382	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2383		SPTREE_LOCK();
2384		LIST_FOREACH(sp, &V_sptree[dir], chain)
2385			sp->state = IPSEC_SPSTATE_DEAD;
2386		SPTREE_UNLOCK();
2387	}
2388
2389	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2390		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2391		return key_senderror(so, m, ENOBUFS);
2392	}
2393
2394	if (m->m_next)
2395		m_freem(m->m_next);
2396	m->m_next = NULL;
2397	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2398	newmsg = mtod(m, struct sadb_msg *);
2399	newmsg->sadb_msg_errno = 0;
2400	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2401
2402	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2403}
2404
2405/*
2406 * SADB_SPDDUMP processing
2407 * receive
2408 *   <base>
2409 * from the user, and dump all SP leaves
2410 * and send,
2411 *   <base> .....
2412 * to the ikmpd.
2413 *
2414 * m will always be freed.
2415 */
2416static int
2417key_spddump(so, m, mhp)
2418	struct socket *so;
2419	struct mbuf *m;
2420	const struct sadb_msghdr *mhp;
2421{
2422	struct secpolicy *sp;
2423	int cnt;
2424	u_int dir;
2425	struct mbuf *n;
2426
2427	IPSEC_ASSERT(so != NULL, ("null socket"));
2428	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2429	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2430	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2431
2432	/* search SPD entry and get buffer size. */
2433	cnt = 0;
2434	SPTREE_LOCK();
2435	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2436		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2437			cnt++;
2438		}
2439	}
2440
2441	if (cnt == 0) {
2442		SPTREE_UNLOCK();
2443		return key_senderror(so, m, ENOENT);
2444	}
2445
2446	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2447		LIST_FOREACH(sp, &V_sptree[dir], chain) {
2448			--cnt;
2449			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2450			    mhp->msg->sadb_msg_pid);
2451
2452			if (n)
2453				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2454		}
2455	}
2456
2457	SPTREE_UNLOCK();
2458	m_freem(m);
2459	return 0;
2460}
2461
2462static struct mbuf *
2463key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid)
2464{
2465	struct mbuf *result = NULL, *m;
2466	struct seclifetime lt;
2467
2468	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2469	if (!m)
2470		goto fail;
2471	result = m;
2472
2473	/*
2474	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2475	 * we are sending traffic endpoints.
2476	 */
2477	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2478	    &sp->spidx.src.sa, sp->spidx.prefs,
2479	    sp->spidx.ul_proto);
2480	if (!m)
2481		goto fail;
2482	m_cat(result, m);
2483
2484	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2485	    &sp->spidx.dst.sa, sp->spidx.prefd,
2486	    sp->spidx.ul_proto);
2487	if (!m)
2488		goto fail;
2489	m_cat(result, m);
2490
2491	m = key_sp2msg(sp);
2492	if (!m)
2493		goto fail;
2494	m_cat(result, m);
2495
2496	if(sp->lifetime){
2497		lt.addtime=sp->created;
2498		lt.usetime= sp->lastused;
2499		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_CURRENT);
2500		if (!m)
2501			goto fail;
2502		m_cat(result, m);
2503
2504		lt.addtime=sp->lifetime;
2505		lt.usetime= sp->validtime;
2506		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_HARD);
2507		if (!m)
2508			goto fail;
2509		m_cat(result, m);
2510	}
2511
2512	if ((result->m_flags & M_PKTHDR) == 0)
2513		goto fail;
2514
2515	if (result->m_len < sizeof(struct sadb_msg)) {
2516		result = m_pullup(result, sizeof(struct sadb_msg));
2517		if (result == NULL)
2518			goto fail;
2519	}
2520
2521	result->m_pkthdr.len = 0;
2522	for (m = result; m; m = m->m_next)
2523		result->m_pkthdr.len += m->m_len;
2524
2525	mtod(result, struct sadb_msg *)->sadb_msg_len =
2526	    PFKEY_UNIT64(result->m_pkthdr.len);
2527
2528	return result;
2529
2530fail:
2531	m_freem(result);
2532	return NULL;
2533}
2534
2535/*
2536 * get PFKEY message length for security policy and request.
2537 */
2538static u_int
2539key_getspreqmsglen(sp)
2540	struct secpolicy *sp;
2541{
2542	u_int tlen;
2543
2544	tlen = sizeof(struct sadb_x_policy);
2545
2546	/* if is the policy for ipsec ? */
2547	if (sp->policy != IPSEC_POLICY_IPSEC)
2548		return tlen;
2549
2550	/* get length of ipsec requests */
2551    {
2552	struct ipsecrequest *isr;
2553	int len;
2554
2555	for (isr = sp->req; isr != NULL; isr = isr->next) {
2556		len = sizeof(struct sadb_x_ipsecrequest)
2557			+ isr->saidx.src.sa.sa_len
2558			+ isr->saidx.dst.sa.sa_len;
2559
2560		tlen += PFKEY_ALIGN8(len);
2561	}
2562    }
2563
2564	return tlen;
2565}
2566
2567/*
2568 * SADB_SPDEXPIRE processing
2569 * send
2570 *   <base, address(SD), lifetime(CH), policy>
2571 * to KMD by PF_KEY.
2572 *
2573 * OUT:	0	: succeed
2574 *	others	: error number
2575 */
2576static int
2577key_spdexpire(sp)
2578	struct secpolicy *sp;
2579{
2580	struct mbuf *result = NULL, *m;
2581	int len;
2582	int error = -1;
2583	struct sadb_lifetime *lt;
2584
2585	/* XXX: Why do we lock ? */
2586
2587	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2588
2589	/* set msg header */
2590	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2591	if (!m) {
2592		error = ENOBUFS;
2593		goto fail;
2594	}
2595	result = m;
2596
2597	/* create lifetime extension (current and hard) */
2598	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2599	m = key_alloc_mbuf(len);
2600	if (!m || m->m_next) {	/*XXX*/
2601		if (m)
2602			m_freem(m);
2603		error = ENOBUFS;
2604		goto fail;
2605	}
2606	bzero(mtod(m, caddr_t), len);
2607	lt = mtod(m, struct sadb_lifetime *);
2608	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2609	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2610	lt->sadb_lifetime_allocations = 0;
2611	lt->sadb_lifetime_bytes = 0;
2612	lt->sadb_lifetime_addtime = sp->created;
2613	lt->sadb_lifetime_usetime = sp->lastused;
2614	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2615	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2616	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2617	lt->sadb_lifetime_allocations = 0;
2618	lt->sadb_lifetime_bytes = 0;
2619	lt->sadb_lifetime_addtime = sp->lifetime;
2620	lt->sadb_lifetime_usetime = sp->validtime;
2621	m_cat(result, m);
2622
2623	/*
2624	 * Note: do not send SADB_X_EXT_NAT_T_* here:
2625	 * we are sending traffic endpoints.
2626	 */
2627
2628	/* set sadb_address for source */
2629	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2630	    &sp->spidx.src.sa,
2631	    sp->spidx.prefs, sp->spidx.ul_proto);
2632	if (!m) {
2633		error = ENOBUFS;
2634		goto fail;
2635	}
2636	m_cat(result, m);
2637
2638	/* set sadb_address for destination */
2639	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2640	    &sp->spidx.dst.sa,
2641	    sp->spidx.prefd, sp->spidx.ul_proto);
2642	if (!m) {
2643		error = ENOBUFS;
2644		goto fail;
2645	}
2646	m_cat(result, m);
2647
2648	/* set secpolicy */
2649	m = key_sp2msg(sp);
2650	if (!m) {
2651		error = ENOBUFS;
2652		goto fail;
2653	}
2654	m_cat(result, m);
2655
2656	if ((result->m_flags & M_PKTHDR) == 0) {
2657		error = EINVAL;
2658		goto fail;
2659	}
2660
2661	if (result->m_len < sizeof(struct sadb_msg)) {
2662		result = m_pullup(result, sizeof(struct sadb_msg));
2663		if (result == NULL) {
2664			error = ENOBUFS;
2665			goto fail;
2666		}
2667	}
2668
2669	result->m_pkthdr.len = 0;
2670	for (m = result; m; m = m->m_next)
2671		result->m_pkthdr.len += m->m_len;
2672
2673	mtod(result, struct sadb_msg *)->sadb_msg_len =
2674	    PFKEY_UNIT64(result->m_pkthdr.len);
2675
2676	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2677
2678 fail:
2679	if (result)
2680		m_freem(result);
2681	return error;
2682}
2683
2684/* %%% SAD management */
2685/*
2686 * allocating a memory for new SA head, and copy from the values of mhp.
2687 * OUT:	NULL	: failure due to the lack of memory.
2688 *	others	: pointer to new SA head.
2689 */
2690static struct secashead *
2691key_newsah(saidx)
2692	struct secasindex *saidx;
2693{
2694	struct secashead *newsah;
2695
2696	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2697
2698	newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2699	if (newsah != NULL) {
2700		int i;
2701		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2702			LIST_INIT(&newsah->savtree[i]);
2703		newsah->saidx = *saidx;
2704
2705		/* add to saidxtree */
2706		newsah->state = SADB_SASTATE_MATURE;
2707
2708		SAHTREE_LOCK();
2709		LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2710		SAHTREE_UNLOCK();
2711	}
2712	return(newsah);
2713}
2714
2715/*
2716 * delete SA index and all SA registerd.
2717 */
2718static void
2719key_delsah(sah)
2720	struct secashead *sah;
2721{
2722	struct secasvar *sav, *nextsav;
2723	u_int stateidx;
2724	int zombie = 0;
2725
2726	IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2727	SAHTREE_LOCK_ASSERT();
2728
2729	/* searching all SA registerd in the secindex. */
2730	for (stateidx = 0;
2731	     stateidx < _ARRAYLEN(saorder_state_any);
2732	     stateidx++) {
2733		u_int state = saorder_state_any[stateidx];
2734		LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2735			if (sav->refcnt == 0) {
2736				/* sanity check */
2737				KEY_CHKSASTATE(state, sav->state, __func__);
2738				/*
2739				 * do NOT call KEY_FREESAV here:
2740				 * it will only delete the sav if refcnt == 1,
2741				 * where we already know that refcnt == 0
2742				 */
2743				key_delsav(sav);
2744			} else {
2745				/* give up to delete this sa */
2746				zombie++;
2747			}
2748		}
2749	}
2750	if (!zombie) {		/* delete only if there are savs */
2751		/* remove from tree of SA index */
2752		if (__LIST_CHAINED(sah))
2753			LIST_REMOVE(sah, chain);
2754		if (sah->sa_route.ro_rt) {
2755			RTFREE(sah->sa_route.ro_rt);
2756			sah->sa_route.ro_rt = (struct rtentry *)NULL;
2757		}
2758		free(sah, M_IPSEC_SAH);
2759	}
2760}
2761
2762/*
2763 * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2764 * and copy the values of mhp into new buffer.
2765 * When SAD message type is GETSPI:
2766 *	to set sequence number from acq_seq++,
2767 *	to set zero to SPI.
2768 *	not to call key_setsava().
2769 * OUT:	NULL	: fail
2770 *	others	: pointer to new secasvar.
2771 *
2772 * does not modify mbuf.  does not free mbuf on error.
2773 */
2774static struct secasvar *
2775key_newsav(m, mhp, sah, errp, where, tag)
2776	struct mbuf *m;
2777	const struct sadb_msghdr *mhp;
2778	struct secashead *sah;
2779	int *errp;
2780	const char* where;
2781	int tag;
2782{
2783	struct secasvar *newsav;
2784	const struct sadb_sa *xsa;
2785
2786	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2787	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2788	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2789	IPSEC_ASSERT(sah != NULL, ("null secashead"));
2790
2791	newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2792	if (newsav == NULL) {
2793		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2794		*errp = ENOBUFS;
2795		goto done;
2796	}
2797
2798	switch (mhp->msg->sadb_msg_type) {
2799	case SADB_GETSPI:
2800		newsav->spi = 0;
2801
2802#ifdef IPSEC_DOSEQCHECK
2803		/* sync sequence number */
2804		if (mhp->msg->sadb_msg_seq == 0)
2805			newsav->seq =
2806				(V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2807		else
2808#endif
2809			newsav->seq = mhp->msg->sadb_msg_seq;
2810		break;
2811
2812	case SADB_ADD:
2813		/* sanity check */
2814		if (mhp->ext[SADB_EXT_SA] == NULL) {
2815			free(newsav, M_IPSEC_SA);
2816			newsav = NULL;
2817			ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2818				__func__));
2819			*errp = EINVAL;
2820			goto done;
2821		}
2822		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2823		newsav->spi = xsa->sadb_sa_spi;
2824		newsav->seq = mhp->msg->sadb_msg_seq;
2825		break;
2826	default:
2827		free(newsav, M_IPSEC_SA);
2828		newsav = NULL;
2829		*errp = EINVAL;
2830		goto done;
2831	}
2832
2833
2834	/* copy sav values */
2835	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2836		*errp = key_setsaval(newsav, m, mhp);
2837		if (*errp) {
2838			free(newsav, M_IPSEC_SA);
2839			newsav = NULL;
2840			goto done;
2841		}
2842	}
2843
2844	SECASVAR_LOCK_INIT(newsav);
2845
2846	/* reset created */
2847	newsav->created = time_second;
2848	newsav->pid = mhp->msg->sadb_msg_pid;
2849
2850	/* add to satree */
2851	newsav->sah = sah;
2852	sa_initref(newsav);
2853	newsav->state = SADB_SASTATE_LARVAL;
2854
2855	/* XXX locking??? */
2856	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2857			secasvar, chain);
2858done:
2859	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2860		printf("DP %s from %s:%u return SP:%p\n", __func__,
2861			where, tag, newsav));
2862
2863	return newsav;
2864}
2865
2866/*
2867 * free() SA variable entry.
2868 */
2869static void
2870key_cleansav(struct secasvar *sav)
2871{
2872	/*
2873	 * Cleanup xform state.  Note that zeroize'ing causes the
2874	 * keys to be cleared; otherwise we must do it ourself.
2875	 */
2876	if (sav->tdb_xform != NULL) {
2877		sav->tdb_xform->xf_zeroize(sav);
2878		sav->tdb_xform = NULL;
2879	} else {
2880		KASSERT(sav->iv == NULL, ("iv but no xform"));
2881		if (sav->key_auth != NULL)
2882			bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2883		if (sav->key_enc != NULL)
2884			bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2885	}
2886	if (sav->key_auth != NULL) {
2887		if (sav->key_auth->key_data != NULL)
2888			free(sav->key_auth->key_data, M_IPSEC_MISC);
2889		free(sav->key_auth, M_IPSEC_MISC);
2890		sav->key_auth = NULL;
2891	}
2892	if (sav->key_enc != NULL) {
2893		if (sav->key_enc->key_data != NULL)
2894			free(sav->key_enc->key_data, M_IPSEC_MISC);
2895		free(sav->key_enc, M_IPSEC_MISC);
2896		sav->key_enc = NULL;
2897	}
2898	if (sav->sched) {
2899		bzero(sav->sched, sav->schedlen);
2900		free(sav->sched, M_IPSEC_MISC);
2901		sav->sched = NULL;
2902	}
2903	if (sav->replay != NULL) {
2904		free(sav->replay, M_IPSEC_MISC);
2905		sav->replay = NULL;
2906	}
2907	if (sav->lft_c != NULL) {
2908		free(sav->lft_c, M_IPSEC_MISC);
2909		sav->lft_c = NULL;
2910	}
2911	if (sav->lft_h != NULL) {
2912		free(sav->lft_h, M_IPSEC_MISC);
2913		sav->lft_h = NULL;
2914	}
2915	if (sav->lft_s != NULL) {
2916		free(sav->lft_s, M_IPSEC_MISC);
2917		sav->lft_s = NULL;
2918	}
2919}
2920
2921/*
2922 * free() SA variable entry.
2923 */
2924static void
2925key_delsav(sav)
2926	struct secasvar *sav;
2927{
2928	IPSEC_ASSERT(sav != NULL, ("null sav"));
2929	IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2930
2931	/* remove from SA header */
2932	if (__LIST_CHAINED(sav))
2933		LIST_REMOVE(sav, chain);
2934	key_cleansav(sav);
2935	SECASVAR_LOCK_DESTROY(sav);
2936	free(sav, M_IPSEC_SA);
2937}
2938
2939/*
2940 * search SAD.
2941 * OUT:
2942 *	NULL	: not found
2943 *	others	: found, pointer to a SA.
2944 */
2945static struct secashead *
2946key_getsah(saidx)
2947	struct secasindex *saidx;
2948{
2949	struct secashead *sah;
2950
2951	SAHTREE_LOCK();
2952	LIST_FOREACH(sah, &V_sahtree, chain) {
2953		if (sah->state == SADB_SASTATE_DEAD)
2954			continue;
2955		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2956			break;
2957	}
2958	SAHTREE_UNLOCK();
2959
2960	return sah;
2961}
2962
2963/*
2964 * check not to be duplicated SPI.
2965 * NOTE: this function is too slow due to searching all SAD.
2966 * OUT:
2967 *	NULL	: not found
2968 *	others	: found, pointer to a SA.
2969 */
2970static struct secasvar *
2971key_checkspidup(saidx, spi)
2972	struct secasindex *saidx;
2973	u_int32_t spi;
2974{
2975	struct secashead *sah;
2976	struct secasvar *sav;
2977
2978	/* check address family */
2979	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2980		ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2981			__func__));
2982		return NULL;
2983	}
2984
2985	sav = NULL;
2986	/* check all SAD */
2987	SAHTREE_LOCK();
2988	LIST_FOREACH(sah, &V_sahtree, chain) {
2989		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2990			continue;
2991		sav = key_getsavbyspi(sah, spi);
2992		if (sav != NULL)
2993			break;
2994	}
2995	SAHTREE_UNLOCK();
2996
2997	return sav;
2998}
2999
3000/*
3001 * search SAD litmited alive SA, protocol, SPI.
3002 * OUT:
3003 *	NULL	: not found
3004 *	others	: found, pointer to a SA.
3005 */
3006static struct secasvar *
3007key_getsavbyspi(sah, spi)
3008	struct secashead *sah;
3009	u_int32_t spi;
3010{
3011	struct secasvar *sav;
3012	u_int stateidx, state;
3013
3014	sav = NULL;
3015	SAHTREE_LOCK_ASSERT();
3016	/* search all status */
3017	for (stateidx = 0;
3018	     stateidx < _ARRAYLEN(saorder_state_alive);
3019	     stateidx++) {
3020
3021		state = saorder_state_alive[stateidx];
3022		LIST_FOREACH(sav, &sah->savtree[state], chain) {
3023
3024			/* sanity check */
3025			if (sav->state != state) {
3026				ipseclog((LOG_DEBUG, "%s: "
3027				    "invalid sav->state (queue: %d SA: %d)\n",
3028				    __func__, state, sav->state));
3029				continue;
3030			}
3031
3032			if (sav->spi == spi)
3033				return sav;
3034		}
3035	}
3036
3037	return NULL;
3038}
3039
3040/*
3041 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3042 * You must update these if need.
3043 * OUT:	0:	success.
3044 *	!0:	failure.
3045 *
3046 * does not modify mbuf.  does not free mbuf on error.
3047 */
3048static int
3049key_setsaval(sav, m, mhp)
3050	struct secasvar *sav;
3051	struct mbuf *m;
3052	const struct sadb_msghdr *mhp;
3053{
3054	int error = 0;
3055
3056	IPSEC_ASSERT(m != NULL, ("null mbuf"));
3057	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3058	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3059
3060	/* initialization */
3061	sav->replay = NULL;
3062	sav->key_auth = NULL;
3063	sav->key_enc = NULL;
3064	sav->sched = NULL;
3065	sav->schedlen = 0;
3066	sav->iv = NULL;
3067	sav->lft_c = NULL;
3068	sav->lft_h = NULL;
3069	sav->lft_s = NULL;
3070	sav->tdb_xform = NULL;		/* transform */
3071	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
3072	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
3073	sav->tdb_compalgxform = NULL;	/* compression algorithm */
3074	/*  Initialize even if NAT-T not compiled in: */
3075	sav->natt_type = 0;
3076	sav->natt_esp_frag_len = 0;
3077
3078	/* SA */
3079	if (mhp->ext[SADB_EXT_SA] != NULL) {
3080		const struct sadb_sa *sa0;
3081
3082		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3083		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3084			error = EINVAL;
3085			goto fail;
3086		}
3087
3088		sav->alg_auth = sa0->sadb_sa_auth;
3089		sav->alg_enc = sa0->sadb_sa_encrypt;
3090		sav->flags = sa0->sadb_sa_flags;
3091
3092		/* replay window */
3093		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3094			sav->replay = (struct secreplay *)
3095				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3096			if (sav->replay == NULL) {
3097				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3098					__func__));
3099				error = ENOBUFS;
3100				goto fail;
3101			}
3102			if (sa0->sadb_sa_replay != 0)
3103				sav->replay->bitmap = (caddr_t)(sav->replay+1);
3104			sav->replay->wsize = sa0->sadb_sa_replay;
3105		}
3106	}
3107
3108	/* Authentication keys */
3109	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3110		const struct sadb_key *key0;
3111		int len;
3112
3113		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3114		len = mhp->extlen[SADB_EXT_KEY_AUTH];
3115
3116		error = 0;
3117		if (len < sizeof(*key0)) {
3118			error = EINVAL;
3119			goto fail;
3120		}
3121		switch (mhp->msg->sadb_msg_satype) {
3122		case SADB_SATYPE_AH:
3123		case SADB_SATYPE_ESP:
3124		case SADB_X_SATYPE_TCPSIGNATURE:
3125			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3126			    sav->alg_auth != SADB_X_AALG_NULL)
3127				error = EINVAL;
3128			break;
3129		case SADB_X_SATYPE_IPCOMP:
3130		default:
3131			error = EINVAL;
3132			break;
3133		}
3134		if (error) {
3135			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3136				__func__));
3137			goto fail;
3138		}
3139
3140		sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3141								M_IPSEC_MISC);
3142		if (sav->key_auth == NULL ) {
3143			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3144				  __func__));
3145			error = ENOBUFS;
3146			goto fail;
3147		}
3148	}
3149
3150	/* Encryption key */
3151	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3152		const struct sadb_key *key0;
3153		int len;
3154
3155		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3156		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3157
3158		error = 0;
3159		if (len < sizeof(*key0)) {
3160			error = EINVAL;
3161			goto fail;
3162		}
3163		switch (mhp->msg->sadb_msg_satype) {
3164		case SADB_SATYPE_ESP:
3165			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3166			    sav->alg_enc != SADB_EALG_NULL) {
3167				error = EINVAL;
3168				break;
3169			}
3170			sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3171								       len,
3172								       M_IPSEC_MISC);
3173			if (sav->key_enc == NULL) {
3174				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3175					__func__));
3176				error = ENOBUFS;
3177				goto fail;
3178			}
3179			break;
3180		case SADB_X_SATYPE_IPCOMP:
3181			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3182				error = EINVAL;
3183			sav->key_enc = NULL;	/*just in case*/
3184			break;
3185		case SADB_SATYPE_AH:
3186		case SADB_X_SATYPE_TCPSIGNATURE:
3187		default:
3188			error = EINVAL;
3189			break;
3190		}
3191		if (error) {
3192			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3193				__func__));
3194			goto fail;
3195		}
3196	}
3197
3198	/* set iv */
3199	sav->ivlen = 0;
3200
3201	switch (mhp->msg->sadb_msg_satype) {
3202	case SADB_SATYPE_AH:
3203		error = xform_init(sav, XF_AH);
3204		break;
3205	case SADB_SATYPE_ESP:
3206		error = xform_init(sav, XF_ESP);
3207		break;
3208	case SADB_X_SATYPE_IPCOMP:
3209		error = xform_init(sav, XF_IPCOMP);
3210		break;
3211	case SADB_X_SATYPE_TCPSIGNATURE:
3212		error = xform_init(sav, XF_TCPSIGNATURE);
3213		break;
3214	}
3215	if (error) {
3216		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3217		        __func__, mhp->msg->sadb_msg_satype));
3218		goto fail;
3219	}
3220
3221	/* reset created */
3222	sav->created = time_second;
3223
3224	/* make lifetime for CURRENT */
3225	sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3226	if (sav->lft_c == NULL) {
3227		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3228		error = ENOBUFS;
3229		goto fail;
3230	}
3231
3232	sav->lft_c->allocations = 0;
3233	sav->lft_c->bytes = 0;
3234	sav->lft_c->addtime = time_second;
3235	sav->lft_c->usetime = 0;
3236
3237	/* lifetimes for HARD and SOFT */
3238    {
3239	const struct sadb_lifetime *lft0;
3240
3241	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3242	if (lft0 != NULL) {
3243		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3244			error = EINVAL;
3245			goto fail;
3246		}
3247		sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3248		if (sav->lft_h == NULL) {
3249			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3250			error = ENOBUFS;
3251			goto fail;
3252		}
3253		/* to be initialize ? */
3254	}
3255
3256	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3257	if (lft0 != NULL) {
3258		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3259			error = EINVAL;
3260			goto fail;
3261		}
3262		sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3263		if (sav->lft_s == NULL) {
3264			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3265			error = ENOBUFS;
3266			goto fail;
3267		}
3268		/* to be initialize ? */
3269	}
3270    }
3271
3272	return 0;
3273
3274 fail:
3275	/* initialization */
3276	key_cleansav(sav);
3277
3278	return error;
3279}
3280
3281/*
3282 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3283 * OUT:	0:	valid
3284 *	other:	errno
3285 */
3286static int
3287key_mature(struct secasvar *sav)
3288{
3289	int error;
3290
3291	/* check SPI value */
3292	switch (sav->sah->saidx.proto) {
3293	case IPPROTO_ESP:
3294	case IPPROTO_AH:
3295		/*
3296		 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3297		 * 1-255 reserved by IANA for future use,
3298		 * 0 for implementation specific, local use.
3299		 */
3300		if (ntohl(sav->spi) <= 255) {
3301			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3302			    __func__, (u_int32_t)ntohl(sav->spi)));
3303			return EINVAL;
3304		}
3305		break;
3306	}
3307
3308	/* check satype */
3309	switch (sav->sah->saidx.proto) {
3310	case IPPROTO_ESP:
3311		/* check flags */
3312		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3313		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3314			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3315				"given to old-esp.\n", __func__));
3316			return EINVAL;
3317		}
3318		error = xform_init(sav, XF_ESP);
3319		break;
3320	case IPPROTO_AH:
3321		/* check flags */
3322		if (sav->flags & SADB_X_EXT_DERIV) {
3323			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3324				"given to AH SA.\n", __func__));
3325			return EINVAL;
3326		}
3327		if (sav->alg_enc != SADB_EALG_NONE) {
3328			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3329				"mismated.\n", __func__));
3330			return(EINVAL);
3331		}
3332		error = xform_init(sav, XF_AH);
3333		break;
3334	case IPPROTO_IPCOMP:
3335		if (sav->alg_auth != SADB_AALG_NONE) {
3336			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3337				"mismated.\n", __func__));
3338			return(EINVAL);
3339		}
3340		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3341		 && ntohl(sav->spi) >= 0x10000) {
3342			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3343				__func__));
3344			return(EINVAL);
3345		}
3346		error = xform_init(sav, XF_IPCOMP);
3347		break;
3348	case IPPROTO_TCP:
3349		if (sav->alg_enc != SADB_EALG_NONE) {
3350			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3351				"mismated.\n", __func__));
3352			return(EINVAL);
3353		}
3354		error = xform_init(sav, XF_TCPSIGNATURE);
3355		break;
3356	default:
3357		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3358		error = EPROTONOSUPPORT;
3359		break;
3360	}
3361	if (error == 0) {
3362		SAHTREE_LOCK();
3363		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3364		SAHTREE_UNLOCK();
3365	}
3366	return (error);
3367}
3368
3369/*
3370 * subroutine for SADB_GET and SADB_DUMP.
3371 */
3372static struct mbuf *
3373key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3374    u_int32_t seq, u_int32_t pid)
3375{
3376	struct mbuf *result = NULL, *tres = NULL, *m;
3377	int i;
3378	int dumporder[] = {
3379		SADB_EXT_SA, SADB_X_EXT_SA2,
3380		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3381		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3382		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3383		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3384		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3385#ifdef IPSEC_NAT_T
3386		SADB_X_EXT_NAT_T_TYPE,
3387		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3388		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3389		SADB_X_EXT_NAT_T_FRAG,
3390#endif
3391	};
3392
3393	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3394	if (m == NULL)
3395		goto fail;
3396	result = m;
3397
3398	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3399		m = NULL;
3400		switch (dumporder[i]) {
3401		case SADB_EXT_SA:
3402			m = key_setsadbsa(sav);
3403			if (!m)
3404				goto fail;
3405			break;
3406
3407		case SADB_X_EXT_SA2:
3408			m = key_setsadbxsa2(sav->sah->saidx.mode,
3409					sav->replay ? sav->replay->count : 0,
3410					sav->sah->saidx.reqid);
3411			if (!m)
3412				goto fail;
3413			break;
3414
3415		case SADB_EXT_ADDRESS_SRC:
3416			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3417			    &sav->sah->saidx.src.sa,
3418			    FULLMASK, IPSEC_ULPROTO_ANY);
3419			if (!m)
3420				goto fail;
3421			break;
3422
3423		case SADB_EXT_ADDRESS_DST:
3424			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3425			    &sav->sah->saidx.dst.sa,
3426			    FULLMASK, IPSEC_ULPROTO_ANY);
3427			if (!m)
3428				goto fail;
3429			break;
3430
3431		case SADB_EXT_KEY_AUTH:
3432			if (!sav->key_auth)
3433				continue;
3434			m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3435			if (!m)
3436				goto fail;
3437			break;
3438
3439		case SADB_EXT_KEY_ENCRYPT:
3440			if (!sav->key_enc)
3441				continue;
3442			m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3443			if (!m)
3444				goto fail;
3445			break;
3446
3447		case SADB_EXT_LIFETIME_CURRENT:
3448			if (!sav->lft_c)
3449				continue;
3450			m = key_setlifetime(sav->lft_c,
3451					    SADB_EXT_LIFETIME_CURRENT);
3452			if (!m)
3453				goto fail;
3454			break;
3455
3456		case SADB_EXT_LIFETIME_HARD:
3457			if (!sav->lft_h)
3458				continue;
3459			m = key_setlifetime(sav->lft_h,
3460					    SADB_EXT_LIFETIME_HARD);
3461			if (!m)
3462				goto fail;
3463			break;
3464
3465		case SADB_EXT_LIFETIME_SOFT:
3466			if (!sav->lft_s)
3467				continue;
3468			m = key_setlifetime(sav->lft_s,
3469					    SADB_EXT_LIFETIME_SOFT);
3470
3471			if (!m)
3472				goto fail;
3473			break;
3474
3475#ifdef IPSEC_NAT_T
3476		case SADB_X_EXT_NAT_T_TYPE:
3477			m = key_setsadbxtype(sav->natt_type);
3478			if (!m)
3479				goto fail;
3480			break;
3481
3482		case SADB_X_EXT_NAT_T_DPORT:
3483			m = key_setsadbxport(
3484			    KEY_PORTFROMSADDR(&sav->sah->saidx.dst),
3485			    SADB_X_EXT_NAT_T_DPORT);
3486			if (!m)
3487				goto fail;
3488			break;
3489
3490		case SADB_X_EXT_NAT_T_SPORT:
3491			m = key_setsadbxport(
3492			    KEY_PORTFROMSADDR(&sav->sah->saidx.src),
3493			    SADB_X_EXT_NAT_T_SPORT);
3494			if (!m)
3495				goto fail;
3496			break;
3497
3498		case SADB_X_EXT_NAT_T_OAI:
3499		case SADB_X_EXT_NAT_T_OAR:
3500		case SADB_X_EXT_NAT_T_FRAG:
3501			/* We do not (yet) support those. */
3502			continue;
3503#endif
3504
3505		case SADB_EXT_ADDRESS_PROXY:
3506		case SADB_EXT_IDENTITY_SRC:
3507		case SADB_EXT_IDENTITY_DST:
3508			/* XXX: should we brought from SPD ? */
3509		case SADB_EXT_SENSITIVITY:
3510		default:
3511			continue;
3512		}
3513
3514		if (!m)
3515			goto fail;
3516		if (tres)
3517			m_cat(m, tres);
3518		tres = m;
3519
3520	}
3521
3522	m_cat(result, tres);
3523	if (result->m_len < sizeof(struct sadb_msg)) {
3524		result = m_pullup(result, sizeof(struct sadb_msg));
3525		if (result == NULL)
3526			goto fail;
3527	}
3528
3529	result->m_pkthdr.len = 0;
3530	for (m = result; m; m = m->m_next)
3531		result->m_pkthdr.len += m->m_len;
3532
3533	mtod(result, struct sadb_msg *)->sadb_msg_len =
3534	    PFKEY_UNIT64(result->m_pkthdr.len);
3535
3536	return result;
3537
3538fail:
3539	m_freem(result);
3540	m_freem(tres);
3541	return NULL;
3542}
3543
3544/*
3545 * set data into sadb_msg.
3546 */
3547static struct mbuf *
3548key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3549    pid_t pid, u_int16_t reserved)
3550{
3551	struct mbuf *m;
3552	struct sadb_msg *p;
3553	int len;
3554
3555	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3556	if (len > MCLBYTES)
3557		return NULL;
3558	MGETHDR(m, M_DONTWAIT, MT_DATA);
3559	if (m && len > MHLEN) {
3560		MCLGET(m, M_DONTWAIT);
3561		if ((m->m_flags & M_EXT) == 0) {
3562			m_freem(m);
3563			m = NULL;
3564		}
3565	}
3566	if (!m)
3567		return NULL;
3568	m->m_pkthdr.len = m->m_len = len;
3569	m->m_next = NULL;
3570
3571	p = mtod(m, struct sadb_msg *);
3572
3573	bzero(p, len);
3574	p->sadb_msg_version = PF_KEY_V2;
3575	p->sadb_msg_type = type;
3576	p->sadb_msg_errno = 0;
3577	p->sadb_msg_satype = satype;
3578	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3579	p->sadb_msg_reserved = reserved;
3580	p->sadb_msg_seq = seq;
3581	p->sadb_msg_pid = (u_int32_t)pid;
3582
3583	return m;
3584}
3585
3586/*
3587 * copy secasvar data into sadb_address.
3588 */
3589static struct mbuf *
3590key_setsadbsa(sav)
3591	struct secasvar *sav;
3592{
3593	struct mbuf *m;
3594	struct sadb_sa *p;
3595	int len;
3596
3597	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3598	m = key_alloc_mbuf(len);
3599	if (!m || m->m_next) {	/*XXX*/
3600		if (m)
3601			m_freem(m);
3602		return NULL;
3603	}
3604
3605	p = mtod(m, struct sadb_sa *);
3606
3607	bzero(p, len);
3608	p->sadb_sa_len = PFKEY_UNIT64(len);
3609	p->sadb_sa_exttype = SADB_EXT_SA;
3610	p->sadb_sa_spi = sav->spi;
3611	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3612	p->sadb_sa_state = sav->state;
3613	p->sadb_sa_auth = sav->alg_auth;
3614	p->sadb_sa_encrypt = sav->alg_enc;
3615	p->sadb_sa_flags = sav->flags;
3616
3617	return m;
3618}
3619
3620/*
3621 * set data into sadb_address.
3622 */
3623static struct mbuf *
3624key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto)
3625{
3626	struct mbuf *m;
3627	struct sadb_address *p;
3628	size_t len;
3629
3630	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3631	    PFKEY_ALIGN8(saddr->sa_len);
3632	m = key_alloc_mbuf(len);
3633	if (!m || m->m_next) {	/*XXX*/
3634		if (m)
3635			m_freem(m);
3636		return NULL;
3637	}
3638
3639	p = mtod(m, struct sadb_address *);
3640
3641	bzero(p, len);
3642	p->sadb_address_len = PFKEY_UNIT64(len);
3643	p->sadb_address_exttype = exttype;
3644	p->sadb_address_proto = ul_proto;
3645	if (prefixlen == FULLMASK) {
3646		switch (saddr->sa_family) {
3647		case AF_INET:
3648			prefixlen = sizeof(struct in_addr) << 3;
3649			break;
3650		case AF_INET6:
3651			prefixlen = sizeof(struct in6_addr) << 3;
3652			break;
3653		default:
3654			; /*XXX*/
3655		}
3656	}
3657	p->sadb_address_prefixlen = prefixlen;
3658	p->sadb_address_reserved = 0;
3659
3660	bcopy(saddr,
3661	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3662	    saddr->sa_len);
3663
3664	return m;
3665}
3666
3667/*
3668 * set data into sadb_x_sa2.
3669 */
3670static struct mbuf *
3671key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3672{
3673	struct mbuf *m;
3674	struct sadb_x_sa2 *p;
3675	size_t len;
3676
3677	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3678	m = key_alloc_mbuf(len);
3679	if (!m || m->m_next) {	/*XXX*/
3680		if (m)
3681			m_freem(m);
3682		return NULL;
3683	}
3684
3685	p = mtod(m, struct sadb_x_sa2 *);
3686
3687	bzero(p, len);
3688	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3689	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3690	p->sadb_x_sa2_mode = mode;
3691	p->sadb_x_sa2_reserved1 = 0;
3692	p->sadb_x_sa2_reserved2 = 0;
3693	p->sadb_x_sa2_sequence = seq;
3694	p->sadb_x_sa2_reqid = reqid;
3695
3696	return m;
3697}
3698
3699#ifdef IPSEC_NAT_T
3700/*
3701 * Set a type in sadb_x_nat_t_type.
3702 */
3703static struct mbuf *
3704key_setsadbxtype(u_int16_t type)
3705{
3706	struct mbuf *m;
3707	size_t len;
3708	struct sadb_x_nat_t_type *p;
3709
3710	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3711
3712	m = key_alloc_mbuf(len);
3713	if (!m || m->m_next) {	/*XXX*/
3714		if (m)
3715			m_freem(m);
3716		return (NULL);
3717	}
3718
3719	p = mtod(m, struct sadb_x_nat_t_type *);
3720
3721	bzero(p, len);
3722	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3723	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3724	p->sadb_x_nat_t_type_type = type;
3725
3726	return (m);
3727}
3728/*
3729 * Set a port in sadb_x_nat_t_port.
3730 * In contrast to default RFC 2367 behaviour, port is in network byte order.
3731 */
3732static struct mbuf *
3733key_setsadbxport(u_int16_t port, u_int16_t type)
3734{
3735	struct mbuf *m;
3736	size_t len;
3737	struct sadb_x_nat_t_port *p;
3738
3739	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3740
3741	m = key_alloc_mbuf(len);
3742	if (!m || m->m_next) {	/*XXX*/
3743		if (m)
3744			m_freem(m);
3745		return (NULL);
3746	}
3747
3748	p = mtod(m, struct sadb_x_nat_t_port *);
3749
3750	bzero(p, len);
3751	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3752	p->sadb_x_nat_t_port_exttype = type;
3753	p->sadb_x_nat_t_port_port = port;
3754
3755	return (m);
3756}
3757
3758/*
3759 * Get port from sockaddr. Port is in network byte order.
3760 */
3761u_int16_t
3762key_portfromsaddr(struct sockaddr *sa)
3763{
3764
3765	switch (sa->sa_family) {
3766#ifdef INET
3767	case AF_INET:
3768		return ((struct sockaddr_in *)sa)->sin_port;
3769#endif
3770#ifdef INET6
3771	case AF_INET6:
3772		return ((struct sockaddr_in6 *)sa)->sin6_port;
3773#endif
3774	}
3775	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
3776		printf("DP %s unexpected address family %d\n",
3777			__func__, sa->sa_family));
3778	return (0);
3779}
3780#endif /* IPSEC_NAT_T */
3781
3782/*
3783 * Set port in struct sockaddr. Port is in network byte order.
3784 */
3785static void
3786key_porttosaddr(struct sockaddr *sa, u_int16_t port)
3787{
3788
3789	switch (sa->sa_family) {
3790#ifdef INET
3791	case AF_INET:
3792		((struct sockaddr_in *)sa)->sin_port = port;
3793		break;
3794#endif
3795#ifdef INET6
3796	case AF_INET6:
3797		((struct sockaddr_in6 *)sa)->sin6_port = port;
3798		break;
3799#endif
3800	default:
3801		ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
3802			__func__, sa->sa_family));
3803		break;
3804	}
3805}
3806
3807/*
3808 * set data into sadb_x_policy
3809 */
3810static struct mbuf *
3811key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3812{
3813	struct mbuf *m;
3814	struct sadb_x_policy *p;
3815	size_t len;
3816
3817	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3818	m = key_alloc_mbuf(len);
3819	if (!m || m->m_next) {	/*XXX*/
3820		if (m)
3821			m_freem(m);
3822		return NULL;
3823	}
3824
3825	p = mtod(m, struct sadb_x_policy *);
3826
3827	bzero(p, len);
3828	p->sadb_x_policy_len = PFKEY_UNIT64(len);
3829	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3830	p->sadb_x_policy_type = type;
3831	p->sadb_x_policy_dir = dir;
3832	p->sadb_x_policy_id = id;
3833
3834	return m;
3835}
3836
3837/* %%% utilities */
3838/* Take a key message (sadb_key) from the socket and turn it into one
3839 * of the kernel's key structures (seckey).
3840 *
3841 * IN: pointer to the src
3842 * OUT: NULL no more memory
3843 */
3844struct seckey *
3845key_dup_keymsg(const struct sadb_key *src, u_int len,
3846	       struct malloc_type *type)
3847{
3848	struct seckey *dst;
3849	dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3850	if (dst != NULL) {
3851		dst->bits = src->sadb_key_bits;
3852		dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3853		if (dst->key_data != NULL) {
3854			bcopy((const char *)src + sizeof(struct sadb_key),
3855			      dst->key_data, len);
3856		} else {
3857			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3858				  __func__));
3859			free(dst, type);
3860			dst = NULL;
3861		}
3862	} else {
3863		ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3864			  __func__));
3865
3866	}
3867	return dst;
3868}
3869
3870/* Take a lifetime message (sadb_lifetime) passed in on a socket and
3871 * turn it into one of the kernel's lifetime structures (seclifetime).
3872 *
3873 * IN: pointer to the destination, source and malloc type
3874 * OUT: NULL, no more memory
3875 */
3876
3877static struct seclifetime *
3878key_dup_lifemsg(const struct sadb_lifetime *src,
3879		 struct malloc_type *type)
3880{
3881	struct seclifetime *dst = NULL;
3882
3883	dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3884					   type, M_NOWAIT);
3885	if (dst == NULL) {
3886		/* XXX counter */
3887		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3888	} else {
3889		dst->allocations = src->sadb_lifetime_allocations;
3890		dst->bytes = src->sadb_lifetime_bytes;
3891		dst->addtime = src->sadb_lifetime_addtime;
3892		dst->usetime = src->sadb_lifetime_usetime;
3893	}
3894	return dst;
3895}
3896
3897/* compare my own address
3898 * OUT:	1: true, i.e. my address.
3899 *	0: false
3900 */
3901int
3902key_ismyaddr(sa)
3903	struct sockaddr *sa;
3904{
3905#ifdef INET
3906	struct sockaddr_in *sin;
3907	struct in_ifaddr *ia;
3908#endif
3909
3910	IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3911
3912	switch (sa->sa_family) {
3913#ifdef INET
3914	case AF_INET:
3915		sin = (struct sockaddr_in *)sa;
3916		IN_IFADDR_RLOCK();
3917		for (ia = V_in_ifaddrhead.tqh_first; ia;
3918		     ia = ia->ia_link.tqe_next)
3919		{
3920			if (sin->sin_family == ia->ia_addr.sin_family &&
3921			    sin->sin_len == ia->ia_addr.sin_len &&
3922			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3923			{
3924				IN_IFADDR_RUNLOCK();
3925				return 1;
3926			}
3927		}
3928		IN_IFADDR_RUNLOCK();
3929		break;
3930#endif
3931#ifdef INET6
3932	case AF_INET6:
3933		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3934#endif
3935	}
3936
3937	return 0;
3938}
3939
3940#ifdef INET6
3941/*
3942 * compare my own address for IPv6.
3943 * 1: ours
3944 * 0: other
3945 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3946 */
3947#include <netinet6/in6_var.h>
3948
3949static int
3950key_ismyaddr6(sin6)
3951	struct sockaddr_in6 *sin6;
3952{
3953	struct in6_ifaddr *ia;
3954#if 0
3955	struct in6_multi *in6m;
3956#endif
3957
3958	IN6_IFADDR_RLOCK();
3959	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
3960		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3961		    (struct sockaddr *)&ia->ia_addr, 0) == 0) {
3962			IN6_IFADDR_RUNLOCK();
3963			return 1;
3964		}
3965
3966#if 0
3967		/*
3968		 * XXX Multicast
3969		 * XXX why do we care about multlicast here while we don't care
3970		 * about IPv4 multicast??
3971		 * XXX scope
3972		 */
3973		in6m = NULL;
3974		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3975		if (in6m) {
3976			IN6_IFADDR_RUNLOCK();
3977			return 1;
3978		}
3979#endif
3980	}
3981	IN6_IFADDR_RUNLOCK();
3982
3983	/* loopback, just for safety */
3984	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3985		return 1;
3986
3987	return 0;
3988}
3989#endif /*INET6*/
3990
3991/*
3992 * compare two secasindex structure.
3993 * flag can specify to compare 2 saidxes.
3994 * compare two secasindex structure without both mode and reqid.
3995 * don't compare port.
3996 * IN:
3997 *      saidx0: source, it can be in SAD.
3998 *      saidx1: object.
3999 * OUT:
4000 *      1 : equal
4001 *      0 : not equal
4002 */
4003static int
4004key_cmpsaidx(
4005	const struct secasindex *saidx0,
4006	const struct secasindex *saidx1,
4007	int flag)
4008{
4009	int chkport = 0;
4010
4011	/* sanity */
4012	if (saidx0 == NULL && saidx1 == NULL)
4013		return 1;
4014
4015	if (saidx0 == NULL || saidx1 == NULL)
4016		return 0;
4017
4018	if (saidx0->proto != saidx1->proto)
4019		return 0;
4020
4021	if (flag == CMP_EXACTLY) {
4022		if (saidx0->mode != saidx1->mode)
4023			return 0;
4024		if (saidx0->reqid != saidx1->reqid)
4025			return 0;
4026		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4027		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4028			return 0;
4029	} else {
4030
4031		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4032		if (flag == CMP_MODE_REQID
4033		  ||flag == CMP_REQID) {
4034			/*
4035			 * If reqid of SPD is non-zero, unique SA is required.
4036			 * The result must be of same reqid in this case.
4037			 */
4038			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4039				return 0;
4040		}
4041
4042		if (flag == CMP_MODE_REQID) {
4043			if (saidx0->mode != IPSEC_MODE_ANY
4044			 && saidx0->mode != saidx1->mode)
4045				return 0;
4046		}
4047
4048#ifdef IPSEC_NAT_T
4049		/*
4050		 * If NAT-T is enabled, check ports for tunnel mode.
4051		 * Do not check ports if they are set to zero in the SPD.
4052		 * Also do not do it for transport mode, as there is no
4053		 * port information available in the SP.
4054		 */
4055		if (saidx1->mode == IPSEC_MODE_TUNNEL &&
4056		    saidx1->src.sa.sa_family == AF_INET &&
4057		    saidx1->dst.sa.sa_family == AF_INET &&
4058		    ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
4059		    ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
4060			chkport = 1;
4061#endif /* IPSEC_NAT_T */
4062
4063		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
4064			return 0;
4065		}
4066		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
4067			return 0;
4068		}
4069	}
4070
4071	return 1;
4072}
4073
4074/*
4075 * compare two secindex structure exactly.
4076 * IN:
4077 *	spidx0: source, it is often in SPD.
4078 *	spidx1: object, it is often from PFKEY message.
4079 * OUT:
4080 *	1 : equal
4081 *	0 : not equal
4082 */
4083static int
4084key_cmpspidx_exactly(
4085	struct secpolicyindex *spidx0,
4086	struct secpolicyindex *spidx1)
4087{
4088	/* sanity */
4089	if (spidx0 == NULL && spidx1 == NULL)
4090		return 1;
4091
4092	if (spidx0 == NULL || spidx1 == NULL)
4093		return 0;
4094
4095	if (spidx0->prefs != spidx1->prefs
4096	 || spidx0->prefd != spidx1->prefd
4097	 || spidx0->ul_proto != spidx1->ul_proto)
4098		return 0;
4099
4100	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4101	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4102}
4103
4104/*
4105 * compare two secindex structure with mask.
4106 * IN:
4107 *	spidx0: source, it is often in SPD.
4108 *	spidx1: object, it is often from IP header.
4109 * OUT:
4110 *	1 : equal
4111 *	0 : not equal
4112 */
4113static int
4114key_cmpspidx_withmask(
4115	struct secpolicyindex *spidx0,
4116	struct secpolicyindex *spidx1)
4117{
4118	/* sanity */
4119	if (spidx0 == NULL && spidx1 == NULL)
4120		return 1;
4121
4122	if (spidx0 == NULL || spidx1 == NULL)
4123		return 0;
4124
4125	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4126	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4127	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4128	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4129		return 0;
4130
4131	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4132	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4133	 && spidx0->ul_proto != spidx1->ul_proto)
4134		return 0;
4135
4136	switch (spidx0->src.sa.sa_family) {
4137	case AF_INET:
4138		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4139		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4140			return 0;
4141		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4142		    &spidx1->src.sin.sin_addr, spidx0->prefs))
4143			return 0;
4144		break;
4145	case AF_INET6:
4146		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4147		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4148			return 0;
4149		/*
4150		 * scope_id check. if sin6_scope_id is 0, we regard it
4151		 * as a wildcard scope, which matches any scope zone ID.
4152		 */
4153		if (spidx0->src.sin6.sin6_scope_id &&
4154		    spidx1->src.sin6.sin6_scope_id &&
4155		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4156			return 0;
4157		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4158		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4159			return 0;
4160		break;
4161	default:
4162		/* XXX */
4163		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4164			return 0;
4165		break;
4166	}
4167
4168	switch (spidx0->dst.sa.sa_family) {
4169	case AF_INET:
4170		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4171		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4172			return 0;
4173		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4174		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
4175			return 0;
4176		break;
4177	case AF_INET6:
4178		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4179		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4180			return 0;
4181		/*
4182		 * scope_id check. if sin6_scope_id is 0, we regard it
4183		 * as a wildcard scope, which matches any scope zone ID.
4184		 */
4185		if (spidx0->dst.sin6.sin6_scope_id &&
4186		    spidx1->dst.sin6.sin6_scope_id &&
4187		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4188			return 0;
4189		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4190		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4191			return 0;
4192		break;
4193	default:
4194		/* XXX */
4195		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4196			return 0;
4197		break;
4198	}
4199
4200	/* XXX Do we check other field ?  e.g. flowinfo */
4201
4202	return 1;
4203}
4204
4205/* returns 0 on match */
4206static int
4207key_sockaddrcmp(
4208	const struct sockaddr *sa1,
4209	const struct sockaddr *sa2,
4210	int port)
4211{
4212#ifdef satosin
4213#undef satosin
4214#endif
4215#define satosin(s) ((const struct sockaddr_in *)s)
4216#ifdef satosin6
4217#undef satosin6
4218#endif
4219#define satosin6(s) ((const struct sockaddr_in6 *)s)
4220	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4221		return 1;
4222
4223	switch (sa1->sa_family) {
4224	case AF_INET:
4225		if (sa1->sa_len != sizeof(struct sockaddr_in))
4226			return 1;
4227		if (satosin(sa1)->sin_addr.s_addr !=
4228		    satosin(sa2)->sin_addr.s_addr) {
4229			return 1;
4230		}
4231		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4232			return 1;
4233		break;
4234	case AF_INET6:
4235		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4236			return 1;	/*EINVAL*/
4237		if (satosin6(sa1)->sin6_scope_id !=
4238		    satosin6(sa2)->sin6_scope_id) {
4239			return 1;
4240		}
4241		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4242		    &satosin6(sa2)->sin6_addr)) {
4243			return 1;
4244		}
4245		if (port &&
4246		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4247			return 1;
4248		}
4249		break;
4250	default:
4251		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4252			return 1;
4253		break;
4254	}
4255
4256	return 0;
4257#undef satosin
4258#undef satosin6
4259}
4260
4261/*
4262 * compare two buffers with mask.
4263 * IN:
4264 *	addr1: source
4265 *	addr2: object
4266 *	bits:  Number of bits to compare
4267 * OUT:
4268 *	1 : equal
4269 *	0 : not equal
4270 */
4271static int
4272key_bbcmp(const void *a1, const void *a2, u_int bits)
4273{
4274	const unsigned char *p1 = a1;
4275	const unsigned char *p2 = a2;
4276
4277	/* XXX: This could be considerably faster if we compare a word
4278	 * at a time, but it is complicated on LSB Endian machines */
4279
4280	/* Handle null pointers */
4281	if (p1 == NULL || p2 == NULL)
4282		return (p1 == p2);
4283
4284	while (bits >= 8) {
4285		if (*p1++ != *p2++)
4286			return 0;
4287		bits -= 8;
4288	}
4289
4290	if (bits > 0) {
4291		u_int8_t mask = ~((1<<(8-bits))-1);
4292		if ((*p1 & mask) != (*p2 & mask))
4293			return 0;
4294	}
4295	return 1;	/* Match! */
4296}
4297
4298static void
4299key_flush_spd(time_t now)
4300{
4301	static u_int16_t sptree_scangen = 0;
4302	u_int16_t gen = sptree_scangen++;
4303	struct secpolicy *sp;
4304	u_int dir;
4305
4306	/* SPD */
4307	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4308restart:
4309		SPTREE_LOCK();
4310		LIST_FOREACH(sp, &V_sptree[dir], chain) {
4311			if (sp->scangen == gen)		/* previously handled */
4312				continue;
4313			sp->scangen = gen;
4314			if (sp->state == IPSEC_SPSTATE_DEAD &&
4315			    sp->refcnt == 1) {
4316				/*
4317				 * Ensure that we only decrease refcnt once,
4318				 * when we're the last consumer.
4319				 * Directly call SP_DELREF/key_delsp instead
4320				 * of KEY_FREESP to avoid unlocking/relocking
4321				 * SPTREE_LOCK before key_delsp: may refcnt
4322				 * be increased again during that time ?
4323				 * NB: also clean entries created by
4324				 * key_spdflush
4325				 */
4326				SP_DELREF(sp);
4327				key_delsp(sp);
4328				SPTREE_UNLOCK();
4329				goto restart;
4330			}
4331			if (sp->lifetime == 0 && sp->validtime == 0)
4332				continue;
4333			if ((sp->lifetime && now - sp->created > sp->lifetime)
4334			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4335				sp->state = IPSEC_SPSTATE_DEAD;
4336				SPTREE_UNLOCK();
4337				key_spdexpire(sp);
4338				goto restart;
4339			}
4340		}
4341		SPTREE_UNLOCK();
4342	}
4343}
4344
4345static void
4346key_flush_sad(time_t now)
4347{
4348	struct secashead *sah, *nextsah;
4349	struct secasvar *sav, *nextsav;
4350
4351	/* SAD */
4352	SAHTREE_LOCK();
4353	LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4354		/* if sah has been dead, then delete it and process next sah. */
4355		if (sah->state == SADB_SASTATE_DEAD) {
4356			key_delsah(sah);
4357			continue;
4358		}
4359
4360		/* if LARVAL entry doesn't become MATURE, delete it. */
4361		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4362			/* Need to also check refcnt for a larval SA ??? */
4363			if (now - sav->created > V_key_larval_lifetime)
4364				KEY_FREESAV(&sav);
4365		}
4366
4367		/*
4368		 * check MATURE entry to start to send expire message
4369		 * whether or not.
4370		 */
4371		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4372			/* we don't need to check. */
4373			if (sav->lft_s == NULL)
4374				continue;
4375
4376			/* sanity check */
4377			if (sav->lft_c == NULL) {
4378				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4379					"time, why?\n", __func__));
4380				continue;
4381			}
4382
4383			/* check SOFT lifetime */
4384			if (sav->lft_s->addtime != 0 &&
4385			    now - sav->created > sav->lft_s->addtime) {
4386				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4387				/*
4388				 * Actually, only send expire message if
4389				 * SA has been used, as it was done before,
4390				 * but should we always send such message,
4391				 * and let IKE daemon decide if it should be
4392				 * renegotiated or not ?
4393				 * XXX expire message will actually NOT be
4394				 * sent if SA is only used after soft
4395				 * lifetime has been reached, see below
4396				 * (DYING state)
4397				 */
4398				if (sav->lft_c->usetime != 0)
4399					key_expire(sav);
4400			}
4401			/* check SOFT lifetime by bytes */
4402			/*
4403			 * XXX I don't know the way to delete this SA
4404			 * when new SA is installed.  Caution when it's
4405			 * installed too big lifetime by time.
4406			 */
4407			else if (sav->lft_s->bytes != 0 &&
4408			    sav->lft_s->bytes < sav->lft_c->bytes) {
4409
4410				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4411				/*
4412				 * XXX If we keep to send expire
4413				 * message in the status of
4414				 * DYING. Do remove below code.
4415				 */
4416				key_expire(sav);
4417			}
4418		}
4419
4420		/* check DYING entry to change status to DEAD. */
4421		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4422			/* we don't need to check. */
4423			if (sav->lft_h == NULL)
4424				continue;
4425
4426			/* sanity check */
4427			if (sav->lft_c == NULL) {
4428				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4429					"time, why?\n", __func__));
4430				continue;
4431			}
4432
4433			if (sav->lft_h->addtime != 0 &&
4434			    now - sav->created > sav->lft_h->addtime) {
4435				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4436				KEY_FREESAV(&sav);
4437			}
4438#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4439			else if (sav->lft_s != NULL
4440			      && sav->lft_s->addtime != 0
4441			      && now - sav->created > sav->lft_s->addtime) {
4442				/*
4443				 * XXX: should be checked to be
4444				 * installed the valid SA.
4445				 */
4446
4447				/*
4448				 * If there is no SA then sending
4449				 * expire message.
4450				 */
4451				key_expire(sav);
4452			}
4453#endif
4454			/* check HARD lifetime by bytes */
4455			else if (sav->lft_h->bytes != 0 &&
4456			    sav->lft_h->bytes < sav->lft_c->bytes) {
4457				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4458				KEY_FREESAV(&sav);
4459			}
4460		}
4461
4462		/* delete entry in DEAD */
4463		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4464			/* sanity check */
4465			if (sav->state != SADB_SASTATE_DEAD) {
4466				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4467					"(queue: %d SA: %d): kill it anyway\n",
4468					__func__,
4469					SADB_SASTATE_DEAD, sav->state));
4470			}
4471			/*
4472			 * do not call key_freesav() here.
4473			 * sav should already be freed, and sav->refcnt
4474			 * shows other references to sav
4475			 * (such as from SPD).
4476			 */
4477		}
4478	}
4479	SAHTREE_UNLOCK();
4480}
4481
4482static void
4483key_flush_acq(time_t now)
4484{
4485	struct secacq *acq, *nextacq;
4486
4487	/* ACQ tree */
4488	ACQ_LOCK();
4489	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4490		nextacq = LIST_NEXT(acq, chain);
4491		if (now - acq->created > V_key_blockacq_lifetime
4492		 && __LIST_CHAINED(acq)) {
4493			LIST_REMOVE(acq, chain);
4494			free(acq, M_IPSEC_SAQ);
4495		}
4496	}
4497	ACQ_UNLOCK();
4498}
4499
4500static void
4501key_flush_spacq(time_t now)
4502{
4503	struct secspacq *acq, *nextacq;
4504
4505	/* SP ACQ tree */
4506	SPACQ_LOCK();
4507	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4508		nextacq = LIST_NEXT(acq, chain);
4509		if (now - acq->created > V_key_blockacq_lifetime
4510		 && __LIST_CHAINED(acq)) {
4511			LIST_REMOVE(acq, chain);
4512			free(acq, M_IPSEC_SAQ);
4513		}
4514	}
4515	SPACQ_UNLOCK();
4516}
4517
4518/*
4519 * time handler.
4520 * scanning SPD and SAD to check status for each entries,
4521 * and do to remove or to expire.
4522 * XXX: year 2038 problem may remain.
4523 */
4524void
4525key_timehandler(void)
4526{
4527	VNET_ITERATOR_DECL(vnet_iter);
4528	time_t now = time_second;
4529
4530	VNET_LIST_RLOCK_NOSLEEP();
4531	VNET_FOREACH(vnet_iter) {
4532		CURVNET_SET(vnet_iter);
4533		key_flush_spd(now);
4534		key_flush_sad(now);
4535		key_flush_acq(now);
4536		key_flush_spacq(now);
4537		CURVNET_RESTORE();
4538	}
4539	VNET_LIST_RUNLOCK_NOSLEEP();
4540
4541#ifndef IPSEC_DEBUG2
4542	/* do exchange to tick time !! */
4543	(void)timeout((void *)key_timehandler, (void *)0, hz);
4544#endif /* IPSEC_DEBUG2 */
4545}
4546
4547u_long
4548key_random()
4549{
4550	u_long value;
4551
4552	key_randomfill(&value, sizeof(value));
4553	return value;
4554}
4555
4556void
4557key_randomfill(p, l)
4558	void *p;
4559	size_t l;
4560{
4561	size_t n;
4562	u_long v;
4563	static int warn = 1;
4564
4565	n = 0;
4566	n = (size_t)read_random(p, (u_int)l);
4567	/* last resort */
4568	while (n < l) {
4569		v = random();
4570		bcopy(&v, (u_int8_t *)p + n,
4571		    l - n < sizeof(v) ? l - n : sizeof(v));
4572		n += sizeof(v);
4573
4574		if (warn) {
4575			printf("WARNING: pseudo-random number generator "
4576			    "used for IPsec processing\n");
4577			warn = 0;
4578		}
4579	}
4580}
4581
4582/*
4583 * map SADB_SATYPE_* to IPPROTO_*.
4584 * if satype == SADB_SATYPE then satype is mapped to ~0.
4585 * OUT:
4586 *	0: invalid satype.
4587 */
4588static u_int16_t
4589key_satype2proto(u_int8_t satype)
4590{
4591	switch (satype) {
4592	case SADB_SATYPE_UNSPEC:
4593		return IPSEC_PROTO_ANY;
4594	case SADB_SATYPE_AH:
4595		return IPPROTO_AH;
4596	case SADB_SATYPE_ESP:
4597		return IPPROTO_ESP;
4598	case SADB_X_SATYPE_IPCOMP:
4599		return IPPROTO_IPCOMP;
4600	case SADB_X_SATYPE_TCPSIGNATURE:
4601		return IPPROTO_TCP;
4602	default:
4603		return 0;
4604	}
4605	/* NOTREACHED */
4606}
4607
4608/*
4609 * map IPPROTO_* to SADB_SATYPE_*
4610 * OUT:
4611 *	0: invalid protocol type.
4612 */
4613static u_int8_t
4614key_proto2satype(u_int16_t proto)
4615{
4616	switch (proto) {
4617	case IPPROTO_AH:
4618		return SADB_SATYPE_AH;
4619	case IPPROTO_ESP:
4620		return SADB_SATYPE_ESP;
4621	case IPPROTO_IPCOMP:
4622		return SADB_X_SATYPE_IPCOMP;
4623	case IPPROTO_TCP:
4624		return SADB_X_SATYPE_TCPSIGNATURE;
4625	default:
4626		return 0;
4627	}
4628	/* NOTREACHED */
4629}
4630
4631/* %%% PF_KEY */
4632/*
4633 * SADB_GETSPI processing is to receive
4634 *	<base, (SA2), src address, dst address, (SPI range)>
4635 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4636 * tree with the status of LARVAL, and send
4637 *	<base, SA(*), address(SD)>
4638 * to the IKMPd.
4639 *
4640 * IN:	mhp: pointer to the pointer to each header.
4641 * OUT:	NULL if fail.
4642 *	other if success, return pointer to the message to send.
4643 */
4644static int
4645key_getspi(so, m, mhp)
4646	struct socket *so;
4647	struct mbuf *m;
4648	const struct sadb_msghdr *mhp;
4649{
4650	struct sadb_address *src0, *dst0;
4651	struct secasindex saidx;
4652	struct secashead *newsah;
4653	struct secasvar *newsav;
4654	u_int8_t proto;
4655	u_int32_t spi;
4656	u_int8_t mode;
4657	u_int32_t reqid;
4658	int error;
4659
4660	IPSEC_ASSERT(so != NULL, ("null socket"));
4661	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4662	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4663	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4664
4665	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4666	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4667		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4668			__func__));
4669		return key_senderror(so, m, EINVAL);
4670	}
4671	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4672	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4673		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4674			__func__));
4675		return key_senderror(so, m, EINVAL);
4676	}
4677	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4678		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4679		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4680	} else {
4681		mode = IPSEC_MODE_ANY;
4682		reqid = 0;
4683	}
4684
4685	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4686	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4687
4688	/* map satype to proto */
4689	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4690		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4691			__func__));
4692		return key_senderror(so, m, EINVAL);
4693	}
4694
4695	/*
4696	 * Make sure the port numbers are zero.
4697	 * In case of NAT-T we will update them later if needed.
4698	 */
4699	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4700	case AF_INET:
4701		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4702		    sizeof(struct sockaddr_in))
4703			return key_senderror(so, m, EINVAL);
4704		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4705		break;
4706	case AF_INET6:
4707		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4708		    sizeof(struct sockaddr_in6))
4709			return key_senderror(so, m, EINVAL);
4710		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4711		break;
4712	default:
4713		; /*???*/
4714	}
4715	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4716	case AF_INET:
4717		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4718		    sizeof(struct sockaddr_in))
4719			return key_senderror(so, m, EINVAL);
4720		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4721		break;
4722	case AF_INET6:
4723		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4724		    sizeof(struct sockaddr_in6))
4725			return key_senderror(so, m, EINVAL);
4726		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4727		break;
4728	default:
4729		; /*???*/
4730	}
4731
4732	/* XXX boundary check against sa_len */
4733	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4734
4735#ifdef IPSEC_NAT_T
4736	/*
4737	 * Handle NAT-T info if present.
4738	 * We made sure the port numbers are zero above, so we do
4739	 * not have to worry in case we do not update them.
4740	 */
4741	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4742		ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4743	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4744		ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4745
4746	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4747	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4748	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4749		struct sadb_x_nat_t_type *type;
4750		struct sadb_x_nat_t_port *sport, *dport;
4751
4752		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4753		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4754		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4755			ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4756			    "passed.\n", __func__));
4757			return key_senderror(so, m, EINVAL);
4758		}
4759
4760		sport = (struct sadb_x_nat_t_port *)
4761		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4762		dport = (struct sadb_x_nat_t_port *)
4763		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4764
4765		if (sport)
4766			KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4767		if (dport)
4768			KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4769	}
4770#endif
4771
4772	/* SPI allocation */
4773	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4774	                       &saidx);
4775	if (spi == 0)
4776		return key_senderror(so, m, EINVAL);
4777
4778	/* get a SA index */
4779	if ((newsah = key_getsah(&saidx)) == NULL) {
4780		/* create a new SA index */
4781		if ((newsah = key_newsah(&saidx)) == NULL) {
4782			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4783			return key_senderror(so, m, ENOBUFS);
4784		}
4785	}
4786
4787	/* get a new SA */
4788	/* XXX rewrite */
4789	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4790	if (newsav == NULL) {
4791		/* XXX don't free new SA index allocated in above. */
4792		return key_senderror(so, m, error);
4793	}
4794
4795	/* set spi */
4796	newsav->spi = htonl(spi);
4797
4798	/* delete the entry in acqtree */
4799	if (mhp->msg->sadb_msg_seq != 0) {
4800		struct secacq *acq;
4801		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4802			/* reset counter in order to deletion by timehandler. */
4803			acq->created = time_second;
4804			acq->count = 0;
4805		}
4806    	}
4807
4808    {
4809	struct mbuf *n, *nn;
4810	struct sadb_sa *m_sa;
4811	struct sadb_msg *newmsg;
4812	int off, len;
4813
4814	/* create new sadb_msg to reply. */
4815	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4816	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4817
4818	MGETHDR(n, M_DONTWAIT, MT_DATA);
4819	if (len > MHLEN) {
4820		MCLGET(n, M_DONTWAIT);
4821		if ((n->m_flags & M_EXT) == 0) {
4822			m_freem(n);
4823			n = NULL;
4824		}
4825	}
4826	if (!n)
4827		return key_senderror(so, m, ENOBUFS);
4828
4829	n->m_len = len;
4830	n->m_next = NULL;
4831	off = 0;
4832
4833	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4834	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4835
4836	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4837	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4838	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4839	m_sa->sadb_sa_spi = htonl(spi);
4840	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4841
4842	IPSEC_ASSERT(off == len,
4843		("length inconsistency (off %u len %u)", off, len));
4844
4845	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4846	    SADB_EXT_ADDRESS_DST);
4847	if (!n->m_next) {
4848		m_freem(n);
4849		return key_senderror(so, m, ENOBUFS);
4850	}
4851
4852	if (n->m_len < sizeof(struct sadb_msg)) {
4853		n = m_pullup(n, sizeof(struct sadb_msg));
4854		if (n == NULL)
4855			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4856	}
4857
4858	n->m_pkthdr.len = 0;
4859	for (nn = n; nn; nn = nn->m_next)
4860		n->m_pkthdr.len += nn->m_len;
4861
4862	newmsg = mtod(n, struct sadb_msg *);
4863	newmsg->sadb_msg_seq = newsav->seq;
4864	newmsg->sadb_msg_errno = 0;
4865	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4866
4867	m_freem(m);
4868	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4869    }
4870}
4871
4872/*
4873 * allocating new SPI
4874 * called by key_getspi().
4875 * OUT:
4876 *	0:	failure.
4877 *	others: success.
4878 */
4879static u_int32_t
4880key_do_getnewspi(spirange, saidx)
4881	struct sadb_spirange *spirange;
4882	struct secasindex *saidx;
4883{
4884	u_int32_t newspi;
4885	u_int32_t min, max;
4886	int count = V_key_spi_trycnt;
4887
4888	/* set spi range to allocate */
4889	if (spirange != NULL) {
4890		min = spirange->sadb_spirange_min;
4891		max = spirange->sadb_spirange_max;
4892	} else {
4893		min = V_key_spi_minval;
4894		max = V_key_spi_maxval;
4895	}
4896	/* IPCOMP needs 2-byte SPI */
4897	if (saidx->proto == IPPROTO_IPCOMP) {
4898		u_int32_t t;
4899		if (min >= 0x10000)
4900			min = 0xffff;
4901		if (max >= 0x10000)
4902			max = 0xffff;
4903		if (min > max) {
4904			t = min; min = max; max = t;
4905		}
4906	}
4907
4908	if (min == max) {
4909		if (key_checkspidup(saidx, min) != NULL) {
4910			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4911				__func__, min));
4912			return 0;
4913		}
4914
4915		count--; /* taking one cost. */
4916		newspi = min;
4917
4918	} else {
4919
4920		/* init SPI */
4921		newspi = 0;
4922
4923		/* when requesting to allocate spi ranged */
4924		while (count--) {
4925			/* generate pseudo-random SPI value ranged. */
4926			newspi = min + (key_random() % (max - min + 1));
4927
4928			if (key_checkspidup(saidx, newspi) == NULL)
4929				break;
4930		}
4931
4932		if (count == 0 || newspi == 0) {
4933			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4934				__func__));
4935			return 0;
4936		}
4937	}
4938
4939	/* statistics */
4940	keystat.getspi_count =
4941		(keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4942
4943	return newspi;
4944}
4945
4946/*
4947 * SADB_UPDATE processing
4948 * receive
4949 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4950 *       key(AE), (identity(SD),) (sensitivity)>
4951 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4952 * and send
4953 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4954 *       (identity(SD),) (sensitivity)>
4955 * to the ikmpd.
4956 *
4957 * m will always be freed.
4958 */
4959static int
4960key_update(so, m, mhp)
4961	struct socket *so;
4962	struct mbuf *m;
4963	const struct sadb_msghdr *mhp;
4964{
4965	struct sadb_sa *sa0;
4966	struct sadb_address *src0, *dst0;
4967#ifdef IPSEC_NAT_T
4968	struct sadb_x_nat_t_type *type;
4969	struct sadb_x_nat_t_port *sport, *dport;
4970	struct sadb_address *iaddr, *raddr;
4971	struct sadb_x_nat_t_frag *frag;
4972#endif
4973	struct secasindex saidx;
4974	struct secashead *sah;
4975	struct secasvar *sav;
4976	u_int16_t proto;
4977	u_int8_t mode;
4978	u_int32_t reqid;
4979	int error;
4980
4981	IPSEC_ASSERT(so != NULL, ("null socket"));
4982	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4983	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4984	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4985
4986	/* map satype to proto */
4987	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4988		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4989			__func__));
4990		return key_senderror(so, m, EINVAL);
4991	}
4992
4993	if (mhp->ext[SADB_EXT_SA] == NULL ||
4994	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4995	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4996	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4997	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4998	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4999	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5000	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5001	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5002	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5003	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5004		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5005			__func__));
5006		return key_senderror(so, m, EINVAL);
5007	}
5008	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5009	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5010	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5011		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5012			__func__));
5013		return key_senderror(so, m, EINVAL);
5014	}
5015	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5016		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5017		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5018	} else {
5019		mode = IPSEC_MODE_ANY;
5020		reqid = 0;
5021	}
5022	/* XXX boundary checking for other extensions */
5023
5024	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5025	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5026	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5027
5028	/* XXX boundary check against sa_len */
5029	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5030
5031	/*
5032	 * Make sure the port numbers are zero.
5033	 * In case of NAT-T we will update them later if needed.
5034	 */
5035	KEY_PORTTOSADDR(&saidx.src, 0);
5036	KEY_PORTTOSADDR(&saidx.dst, 0);
5037
5038#ifdef IPSEC_NAT_T
5039	/*
5040	 * Handle NAT-T info if present.
5041	 */
5042	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5043	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5044	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5045
5046		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5047		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5048		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5049			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5050			    __func__));
5051			return key_senderror(so, m, EINVAL);
5052		}
5053
5054		type = (struct sadb_x_nat_t_type *)
5055		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5056		sport = (struct sadb_x_nat_t_port *)
5057		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5058		dport = (struct sadb_x_nat_t_port *)
5059		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5060	} else {
5061		type = 0;
5062		sport = dport = 0;
5063	}
5064	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5065	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5066		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5067		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5068			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5069			    __func__));
5070			return key_senderror(so, m, EINVAL);
5071		}
5072		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5073		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5074		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5075	} else {
5076		iaddr = raddr = NULL;
5077	}
5078	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5079		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5080			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5081			    __func__));
5082			return key_senderror(so, m, EINVAL);
5083		}
5084		frag = (struct sadb_x_nat_t_frag *)
5085		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5086	} else {
5087		frag = 0;
5088	}
5089#endif
5090
5091	/* get a SA header */
5092	if ((sah = key_getsah(&saidx)) == NULL) {
5093		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
5094		return key_senderror(so, m, ENOENT);
5095	}
5096
5097	/* set spidx if there */
5098	/* XXX rewrite */
5099	error = key_setident(sah, m, mhp);
5100	if (error)
5101		return key_senderror(so, m, error);
5102
5103	/* find a SA with sequence number. */
5104#ifdef IPSEC_DOSEQCHECK
5105	if (mhp->msg->sadb_msg_seq != 0
5106	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
5107		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
5108			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
5109		return key_senderror(so, m, ENOENT);
5110	}
5111#else
5112	SAHTREE_LOCK();
5113	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5114	SAHTREE_UNLOCK();
5115	if (sav == NULL) {
5116		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
5117			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5118		return key_senderror(so, m, EINVAL);
5119	}
5120#endif
5121
5122	/* validity check */
5123	if (sav->sah->saidx.proto != proto) {
5124		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
5125			"(DB=%u param=%u)\n", __func__,
5126			sav->sah->saidx.proto, proto));
5127		return key_senderror(so, m, EINVAL);
5128	}
5129#ifdef IPSEC_DOSEQCHECK
5130	if (sav->spi != sa0->sadb_sa_spi) {
5131		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
5132		    __func__,
5133		    (u_int32_t)ntohl(sav->spi),
5134		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5135		return key_senderror(so, m, EINVAL);
5136	}
5137#endif
5138	if (sav->pid != mhp->msg->sadb_msg_pid) {
5139		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
5140		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
5141		return key_senderror(so, m, EINVAL);
5142	}
5143
5144	/* copy sav values */
5145	error = key_setsaval(sav, m, mhp);
5146	if (error) {
5147		KEY_FREESAV(&sav);
5148		return key_senderror(so, m, error);
5149	}
5150
5151	/* check SA values to be mature. */
5152	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5153		KEY_FREESAV(&sav);
5154		return key_senderror(so, m, 0);
5155	}
5156
5157#ifdef IPSEC_NAT_T
5158	/*
5159	 * Handle more NAT-T info if present,
5160	 * now that we have a sav to fill.
5161	 */
5162	if (type)
5163		sav->natt_type = type->sadb_x_nat_t_type_type;
5164
5165	if (sport)
5166		KEY_PORTTOSADDR(&sav->sah->saidx.src,
5167		    sport->sadb_x_nat_t_port_port);
5168	if (dport)
5169		KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5170		    dport->sadb_x_nat_t_port_port);
5171
5172#if 0
5173	/*
5174	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5175	 * We should actually check for a minimum MTU here, if we
5176	 * want to support it in ip_output.
5177	 */
5178	if (frag)
5179		sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5180#endif
5181#endif
5182
5183    {
5184	struct mbuf *n;
5185
5186	/* set msg buf from mhp */
5187	n = key_getmsgbuf_x1(m, mhp);
5188	if (n == NULL) {
5189		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5190		return key_senderror(so, m, ENOBUFS);
5191	}
5192
5193	m_freem(m);
5194	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5195    }
5196}
5197
5198/*
5199 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5200 * only called by key_update().
5201 * OUT:
5202 *	NULL	: not found
5203 *	others	: found, pointer to a SA.
5204 */
5205#ifdef IPSEC_DOSEQCHECK
5206static struct secasvar *
5207key_getsavbyseq(sah, seq)
5208	struct secashead *sah;
5209	u_int32_t seq;
5210{
5211	struct secasvar *sav;
5212	u_int state;
5213
5214	state = SADB_SASTATE_LARVAL;
5215
5216	/* search SAD with sequence number ? */
5217	LIST_FOREACH(sav, &sah->savtree[state], chain) {
5218
5219		KEY_CHKSASTATE(state, sav->state, __func__);
5220
5221		if (sav->seq == seq) {
5222			sa_addref(sav);
5223			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5224				printf("DP %s cause refcnt++:%d SA:%p\n",
5225					__func__, sav->refcnt, sav));
5226			return sav;
5227		}
5228	}
5229
5230	return NULL;
5231}
5232#endif
5233
5234/*
5235 * SADB_ADD processing
5236 * add an entry to SA database, when received
5237 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5238 *       key(AE), (identity(SD),) (sensitivity)>
5239 * from the ikmpd,
5240 * and send
5241 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5242 *       (identity(SD),) (sensitivity)>
5243 * to the ikmpd.
5244 *
5245 * IGNORE identity and sensitivity messages.
5246 *
5247 * m will always be freed.
5248 */
5249static int
5250key_add(so, m, mhp)
5251	struct socket *so;
5252	struct mbuf *m;
5253	const struct sadb_msghdr *mhp;
5254{
5255	struct sadb_sa *sa0;
5256	struct sadb_address *src0, *dst0;
5257#ifdef IPSEC_NAT_T
5258	struct sadb_x_nat_t_type *type;
5259	struct sadb_address *iaddr, *raddr;
5260	struct sadb_x_nat_t_frag *frag;
5261#endif
5262	struct secasindex saidx;
5263	struct secashead *newsah;
5264	struct secasvar *newsav;
5265	u_int16_t proto;
5266	u_int8_t mode;
5267	u_int32_t reqid;
5268	int error;
5269
5270	IPSEC_ASSERT(so != NULL, ("null socket"));
5271	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5272	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5273	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5274
5275	/* map satype to proto */
5276	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5277		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5278			__func__));
5279		return key_senderror(so, m, EINVAL);
5280	}
5281
5282	if (mhp->ext[SADB_EXT_SA] == NULL ||
5283	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5284	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5285	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5286	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5287	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5288	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5289	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5290	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5291	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5292	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5293		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5294			__func__));
5295		return key_senderror(so, m, EINVAL);
5296	}
5297	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5298	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5299	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5300		/* XXX need more */
5301		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5302			__func__));
5303		return key_senderror(so, m, EINVAL);
5304	}
5305	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5306		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5307		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5308	} else {
5309		mode = IPSEC_MODE_ANY;
5310		reqid = 0;
5311	}
5312
5313	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5314	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5315	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5316
5317	/* XXX boundary check against sa_len */
5318	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5319
5320	/*
5321	 * Make sure the port numbers are zero.
5322	 * In case of NAT-T we will update them later if needed.
5323	 */
5324	KEY_PORTTOSADDR(&saidx.src, 0);
5325	KEY_PORTTOSADDR(&saidx.dst, 0);
5326
5327#ifdef IPSEC_NAT_T
5328	/*
5329	 * Handle NAT-T info if present.
5330	 */
5331	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5332	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5333	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5334		struct sadb_x_nat_t_port *sport, *dport;
5335
5336		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5337		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5338		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5339			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5340			    __func__));
5341			return key_senderror(so, m, EINVAL);
5342		}
5343
5344		type = (struct sadb_x_nat_t_type *)
5345		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5346		sport = (struct sadb_x_nat_t_port *)
5347		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5348		dport = (struct sadb_x_nat_t_port *)
5349		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5350
5351		if (sport)
5352			KEY_PORTTOSADDR(&saidx.src,
5353			    sport->sadb_x_nat_t_port_port);
5354		if (dport)
5355			KEY_PORTTOSADDR(&saidx.dst,
5356			    dport->sadb_x_nat_t_port_port);
5357	} else {
5358		type = 0;
5359	}
5360	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5361	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5362		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5363		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5364			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5365			    __func__));
5366			return key_senderror(so, m, EINVAL);
5367		}
5368		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5369		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5370		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5371	} else {
5372		iaddr = raddr = NULL;
5373	}
5374	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5375		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5376			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5377			    __func__));
5378			return key_senderror(so, m, EINVAL);
5379		}
5380		frag = (struct sadb_x_nat_t_frag *)
5381		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5382	} else {
5383		frag = 0;
5384	}
5385#endif
5386
5387	/* get a SA header */
5388	if ((newsah = key_getsah(&saidx)) == NULL) {
5389		/* create a new SA header */
5390		if ((newsah = key_newsah(&saidx)) == NULL) {
5391			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5392			return key_senderror(so, m, ENOBUFS);
5393		}
5394	}
5395
5396	/* set spidx if there */
5397	/* XXX rewrite */
5398	error = key_setident(newsah, m, mhp);
5399	if (error) {
5400		return key_senderror(so, m, error);
5401	}
5402
5403	/* create new SA entry. */
5404	/* We can create new SA only if SPI is differenct. */
5405	SAHTREE_LOCK();
5406	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5407	SAHTREE_UNLOCK();
5408	if (newsav != NULL) {
5409		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5410		return key_senderror(so, m, EEXIST);
5411	}
5412	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5413	if (newsav == NULL) {
5414		return key_senderror(so, m, error);
5415	}
5416
5417	/* check SA values to be mature. */
5418	if ((error = key_mature(newsav)) != 0) {
5419		KEY_FREESAV(&newsav);
5420		return key_senderror(so, m, error);
5421	}
5422
5423#ifdef IPSEC_NAT_T
5424	/*
5425	 * Handle more NAT-T info if present,
5426	 * now that we have a sav to fill.
5427	 */
5428	if (type)
5429		newsav->natt_type = type->sadb_x_nat_t_type_type;
5430
5431#if 0
5432	/*
5433	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5434	 * We should actually check for a minimum MTU here, if we
5435	 * want to support it in ip_output.
5436	 */
5437	if (frag)
5438		newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5439#endif
5440#endif
5441
5442	/*
5443	 * don't call key_freesav() here, as we would like to keep the SA
5444	 * in the database on success.
5445	 */
5446
5447    {
5448	struct mbuf *n;
5449
5450	/* set msg buf from mhp */
5451	n = key_getmsgbuf_x1(m, mhp);
5452	if (n == NULL) {
5453		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5454		return key_senderror(so, m, ENOBUFS);
5455	}
5456
5457	m_freem(m);
5458	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5459    }
5460}
5461
5462/* m is retained */
5463static int
5464key_setident(sah, m, mhp)
5465	struct secashead *sah;
5466	struct mbuf *m;
5467	const struct sadb_msghdr *mhp;
5468{
5469	const struct sadb_ident *idsrc, *iddst;
5470	int idsrclen, iddstlen;
5471
5472	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5473	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5474	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5475	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5476
5477	/* don't make buffer if not there */
5478	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5479	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5480		sah->idents = NULL;
5481		sah->identd = NULL;
5482		return 0;
5483	}
5484
5485	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5486	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5487		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5488		return EINVAL;
5489	}
5490
5491	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5492	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5493	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5494	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5495
5496	/* validity check */
5497	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5498		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5499		return EINVAL;
5500	}
5501
5502	switch (idsrc->sadb_ident_type) {
5503	case SADB_IDENTTYPE_PREFIX:
5504	case SADB_IDENTTYPE_FQDN:
5505	case SADB_IDENTTYPE_USERFQDN:
5506	default:
5507		/* XXX do nothing */
5508		sah->idents = NULL;
5509		sah->identd = NULL;
5510	 	return 0;
5511	}
5512
5513	/* make structure */
5514	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5515	if (sah->idents == NULL) {
5516		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5517		return ENOBUFS;
5518	}
5519	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5520	if (sah->identd == NULL) {
5521		free(sah->idents, M_IPSEC_MISC);
5522		sah->idents = NULL;
5523		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5524		return ENOBUFS;
5525	}
5526	sah->idents->type = idsrc->sadb_ident_type;
5527	sah->idents->id = idsrc->sadb_ident_id;
5528
5529	sah->identd->type = iddst->sadb_ident_type;
5530	sah->identd->id = iddst->sadb_ident_id;
5531
5532	return 0;
5533}
5534
5535/*
5536 * m will not be freed on return.
5537 * it is caller's responsibility to free the result.
5538 */
5539static struct mbuf *
5540key_getmsgbuf_x1(m, mhp)
5541	struct mbuf *m;
5542	const struct sadb_msghdr *mhp;
5543{
5544	struct mbuf *n;
5545
5546	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5547	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5548	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5549
5550	/* create new sadb_msg to reply. */
5551	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5552	    SADB_EXT_SA, SADB_X_EXT_SA2,
5553	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5554	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5555	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5556	if (!n)
5557		return NULL;
5558
5559	if (n->m_len < sizeof(struct sadb_msg)) {
5560		n = m_pullup(n, sizeof(struct sadb_msg));
5561		if (n == NULL)
5562			return NULL;
5563	}
5564	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5565	mtod(n, struct sadb_msg *)->sadb_msg_len =
5566	    PFKEY_UNIT64(n->m_pkthdr.len);
5567
5568	return n;
5569}
5570
5571static int key_delete_all __P((struct socket *, struct mbuf *,
5572	const struct sadb_msghdr *, u_int16_t));
5573
5574/*
5575 * SADB_DELETE processing
5576 * receive
5577 *   <base, SA(*), address(SD)>
5578 * from the ikmpd, and set SADB_SASTATE_DEAD,
5579 * and send,
5580 *   <base, SA(*), address(SD)>
5581 * to the ikmpd.
5582 *
5583 * m will always be freed.
5584 */
5585static int
5586key_delete(so, m, mhp)
5587	struct socket *so;
5588	struct mbuf *m;
5589	const struct sadb_msghdr *mhp;
5590{
5591	struct sadb_sa *sa0;
5592	struct sadb_address *src0, *dst0;
5593	struct secasindex saidx;
5594	struct secashead *sah;
5595	struct secasvar *sav = NULL;
5596	u_int16_t proto;
5597
5598	IPSEC_ASSERT(so != NULL, ("null socket"));
5599	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5600	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5601	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5602
5603	/* map satype to proto */
5604	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5605		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5606			__func__));
5607		return key_senderror(so, m, EINVAL);
5608	}
5609
5610	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5611	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5612		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5613			__func__));
5614		return key_senderror(so, m, EINVAL);
5615	}
5616
5617	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5618	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5619		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5620			__func__));
5621		return key_senderror(so, m, EINVAL);
5622	}
5623
5624	if (mhp->ext[SADB_EXT_SA] == NULL) {
5625		/*
5626		 * Caller wants us to delete all non-LARVAL SAs
5627		 * that match the src/dst.  This is used during
5628		 * IKE INITIAL-CONTACT.
5629		 */
5630		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5631		return key_delete_all(so, m, mhp, proto);
5632	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5633		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5634			__func__));
5635		return key_senderror(so, m, EINVAL);
5636	}
5637
5638	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5639	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5640	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5641
5642	/* XXX boundary check against sa_len */
5643	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5644
5645	/*
5646	 * Make sure the port numbers are zero.
5647	 * In case of NAT-T we will update them later if needed.
5648	 */
5649	KEY_PORTTOSADDR(&saidx.src, 0);
5650	KEY_PORTTOSADDR(&saidx.dst, 0);
5651
5652#ifdef IPSEC_NAT_T
5653	/*
5654	 * Handle NAT-T info if present.
5655	 */
5656	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5657	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5658		struct sadb_x_nat_t_port *sport, *dport;
5659
5660		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5661		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5662			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5663			    __func__));
5664			return key_senderror(so, m, EINVAL);
5665		}
5666
5667		sport = (struct sadb_x_nat_t_port *)
5668		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5669		dport = (struct sadb_x_nat_t_port *)
5670		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5671
5672		if (sport)
5673			KEY_PORTTOSADDR(&saidx.src,
5674			    sport->sadb_x_nat_t_port_port);
5675		if (dport)
5676			KEY_PORTTOSADDR(&saidx.dst,
5677			    dport->sadb_x_nat_t_port_port);
5678	}
5679#endif
5680
5681	/* get a SA header */
5682	SAHTREE_LOCK();
5683	LIST_FOREACH(sah, &V_sahtree, chain) {
5684		if (sah->state == SADB_SASTATE_DEAD)
5685			continue;
5686		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5687			continue;
5688
5689		/* get a SA with SPI. */
5690		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5691		if (sav)
5692			break;
5693	}
5694	if (sah == NULL) {
5695		SAHTREE_UNLOCK();
5696		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5697		return key_senderror(so, m, ENOENT);
5698	}
5699
5700	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5701	SAHTREE_UNLOCK();
5702	KEY_FREESAV(&sav);
5703
5704    {
5705	struct mbuf *n;
5706	struct sadb_msg *newmsg;
5707
5708	/* create new sadb_msg to reply. */
5709	/* XXX-BZ NAT-T extensions? */
5710	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5711	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5712	if (!n)
5713		return key_senderror(so, m, ENOBUFS);
5714
5715	if (n->m_len < sizeof(struct sadb_msg)) {
5716		n = m_pullup(n, sizeof(struct sadb_msg));
5717		if (n == NULL)
5718			return key_senderror(so, m, ENOBUFS);
5719	}
5720	newmsg = mtod(n, struct sadb_msg *);
5721	newmsg->sadb_msg_errno = 0;
5722	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5723
5724	m_freem(m);
5725	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5726    }
5727}
5728
5729/*
5730 * delete all SAs for src/dst.  Called from key_delete().
5731 */
5732static int
5733key_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5734    u_int16_t proto)
5735{
5736	struct sadb_address *src0, *dst0;
5737	struct secasindex saidx;
5738	struct secashead *sah;
5739	struct secasvar *sav, *nextsav;
5740	u_int stateidx, state;
5741
5742	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5743	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5744
5745	/* XXX boundary check against sa_len */
5746	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5747
5748	/*
5749	 * Make sure the port numbers are zero.
5750	 * In case of NAT-T we will update them later if needed.
5751	 */
5752	KEY_PORTTOSADDR(&saidx.src, 0);
5753	KEY_PORTTOSADDR(&saidx.dst, 0);
5754
5755#ifdef IPSEC_NAT_T
5756	/*
5757	 * Handle NAT-T info if present.
5758	 */
5759
5760	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5761	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5762		struct sadb_x_nat_t_port *sport, *dport;
5763
5764		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5765		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5766			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5767			    __func__));
5768			return key_senderror(so, m, EINVAL);
5769		}
5770
5771		sport = (struct sadb_x_nat_t_port *)
5772		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5773		dport = (struct sadb_x_nat_t_port *)
5774		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5775
5776		if (sport)
5777			KEY_PORTTOSADDR(&saidx.src,
5778			    sport->sadb_x_nat_t_port_port);
5779		if (dport)
5780			KEY_PORTTOSADDR(&saidx.dst,
5781			    dport->sadb_x_nat_t_port_port);
5782	}
5783#endif
5784
5785	SAHTREE_LOCK();
5786	LIST_FOREACH(sah, &V_sahtree, chain) {
5787		if (sah->state == SADB_SASTATE_DEAD)
5788			continue;
5789		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5790			continue;
5791
5792		/* Delete all non-LARVAL SAs. */
5793		for (stateidx = 0;
5794		     stateidx < _ARRAYLEN(saorder_state_alive);
5795		     stateidx++) {
5796			state = saorder_state_alive[stateidx];
5797			if (state == SADB_SASTATE_LARVAL)
5798				continue;
5799			for (sav = LIST_FIRST(&sah->savtree[state]);
5800			     sav != NULL; sav = nextsav) {
5801				nextsav = LIST_NEXT(sav, chain);
5802				/* sanity check */
5803				if (sav->state != state) {
5804					ipseclog((LOG_DEBUG, "%s: invalid "
5805						"sav->state (queue %d SA %d)\n",
5806						__func__, state, sav->state));
5807					continue;
5808				}
5809
5810				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5811				KEY_FREESAV(&sav);
5812			}
5813		}
5814	}
5815	SAHTREE_UNLOCK();
5816    {
5817	struct mbuf *n;
5818	struct sadb_msg *newmsg;
5819
5820	/* create new sadb_msg to reply. */
5821	/* XXX-BZ NAT-T extensions? */
5822	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5823	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5824	if (!n)
5825		return key_senderror(so, m, ENOBUFS);
5826
5827	if (n->m_len < sizeof(struct sadb_msg)) {
5828		n = m_pullup(n, sizeof(struct sadb_msg));
5829		if (n == NULL)
5830			return key_senderror(so, m, ENOBUFS);
5831	}
5832	newmsg = mtod(n, struct sadb_msg *);
5833	newmsg->sadb_msg_errno = 0;
5834	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5835
5836	m_freem(m);
5837	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5838    }
5839}
5840
5841/*
5842 * SADB_GET processing
5843 * receive
5844 *   <base, SA(*), address(SD)>
5845 * from the ikmpd, and get a SP and a SA to respond,
5846 * and send,
5847 *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5848 *       (identity(SD),) (sensitivity)>
5849 * to the ikmpd.
5850 *
5851 * m will always be freed.
5852 */
5853static int
5854key_get(so, m, mhp)
5855	struct socket *so;
5856	struct mbuf *m;
5857	const struct sadb_msghdr *mhp;
5858{
5859	struct sadb_sa *sa0;
5860	struct sadb_address *src0, *dst0;
5861	struct secasindex saidx;
5862	struct secashead *sah;
5863	struct secasvar *sav = NULL;
5864	u_int16_t proto;
5865
5866	IPSEC_ASSERT(so != NULL, ("null socket"));
5867	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5868	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5869	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5870
5871	/* map satype to proto */
5872	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5873		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5874			__func__));
5875		return key_senderror(so, m, EINVAL);
5876	}
5877
5878	if (mhp->ext[SADB_EXT_SA] == NULL ||
5879	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5880	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5881		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5882			__func__));
5883		return key_senderror(so, m, EINVAL);
5884	}
5885	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5886	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5887	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5888		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5889			__func__));
5890		return key_senderror(so, m, EINVAL);
5891	}
5892
5893	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5894	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5895	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5896
5897	/* XXX boundary check against sa_len */
5898	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5899
5900	/*
5901	 * Make sure the port numbers are zero.
5902	 * In case of NAT-T we will update them later if needed.
5903	 */
5904	KEY_PORTTOSADDR(&saidx.src, 0);
5905	KEY_PORTTOSADDR(&saidx.dst, 0);
5906
5907#ifdef IPSEC_NAT_T
5908	/*
5909	 * Handle NAT-T info if present.
5910	 */
5911
5912	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5913	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5914		struct sadb_x_nat_t_port *sport, *dport;
5915
5916		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5917		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5918			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5919			    __func__));
5920			return key_senderror(so, m, EINVAL);
5921		}
5922
5923		sport = (struct sadb_x_nat_t_port *)
5924		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5925		dport = (struct sadb_x_nat_t_port *)
5926		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5927
5928		if (sport)
5929			KEY_PORTTOSADDR(&saidx.src,
5930			    sport->sadb_x_nat_t_port_port);
5931		if (dport)
5932			KEY_PORTTOSADDR(&saidx.dst,
5933			    dport->sadb_x_nat_t_port_port);
5934	}
5935#endif
5936
5937	/* get a SA header */
5938	SAHTREE_LOCK();
5939	LIST_FOREACH(sah, &V_sahtree, chain) {
5940		if (sah->state == SADB_SASTATE_DEAD)
5941			continue;
5942		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5943			continue;
5944
5945		/* get a SA with SPI. */
5946		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5947		if (sav)
5948			break;
5949	}
5950	SAHTREE_UNLOCK();
5951	if (sah == NULL) {
5952		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5953		return key_senderror(so, m, ENOENT);
5954	}
5955
5956    {
5957	struct mbuf *n;
5958	u_int8_t satype;
5959
5960	/* map proto to satype */
5961	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5962		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5963			__func__));
5964		return key_senderror(so, m, EINVAL);
5965	}
5966
5967	/* create new sadb_msg to reply. */
5968	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5969	    mhp->msg->sadb_msg_pid);
5970	if (!n)
5971		return key_senderror(so, m, ENOBUFS);
5972
5973	m_freem(m);
5974	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5975    }
5976}
5977
5978/* XXX make it sysctl-configurable? */
5979static void
5980key_getcomb_setlifetime(comb)
5981	struct sadb_comb *comb;
5982{
5983
5984	comb->sadb_comb_soft_allocations = 1;
5985	comb->sadb_comb_hard_allocations = 1;
5986	comb->sadb_comb_soft_bytes = 0;
5987	comb->sadb_comb_hard_bytes = 0;
5988	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5989	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5990	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5991	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5992}
5993
5994/*
5995 * XXX reorder combinations by preference
5996 * XXX no idea if the user wants ESP authentication or not
5997 */
5998static struct mbuf *
5999key_getcomb_esp()
6000{
6001	struct sadb_comb *comb;
6002	struct enc_xform *algo;
6003	struct mbuf *result = NULL, *m, *n;
6004	int encmin;
6005	int i, off, o;
6006	int totlen;
6007	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6008
6009	m = NULL;
6010	for (i = 1; i <= SADB_EALG_MAX; i++) {
6011		algo = esp_algorithm_lookup(i);
6012		if (algo == NULL)
6013			continue;
6014
6015		/* discard algorithms with key size smaller than system min */
6016		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6017			continue;
6018		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6019			encmin = V_ipsec_esp_keymin;
6020		else
6021			encmin = _BITS(algo->minkey);
6022
6023		if (V_ipsec_esp_auth)
6024			m = key_getcomb_ah();
6025		else {
6026			IPSEC_ASSERT(l <= MLEN,
6027				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6028			MGET(m, M_DONTWAIT, MT_DATA);
6029			if (m) {
6030				M_ALIGN(m, l);
6031				m->m_len = l;
6032				m->m_next = NULL;
6033				bzero(mtod(m, caddr_t), m->m_len);
6034			}
6035		}
6036		if (!m)
6037			goto fail;
6038
6039		totlen = 0;
6040		for (n = m; n; n = n->m_next)
6041			totlen += n->m_len;
6042		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6043
6044		for (off = 0; off < totlen; off += l) {
6045			n = m_pulldown(m, off, l, &o);
6046			if (!n) {
6047				/* m is already freed */
6048				goto fail;
6049			}
6050			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6051			bzero(comb, sizeof(*comb));
6052			key_getcomb_setlifetime(comb);
6053			comb->sadb_comb_encrypt = i;
6054			comb->sadb_comb_encrypt_minbits = encmin;
6055			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6056		}
6057
6058		if (!result)
6059			result = m;
6060		else
6061			m_cat(result, m);
6062	}
6063
6064	return result;
6065
6066 fail:
6067	if (result)
6068		m_freem(result);
6069	return NULL;
6070}
6071
6072static void
6073key_getsizes_ah(
6074	const struct auth_hash *ah,
6075	int alg,
6076	u_int16_t* min,
6077	u_int16_t* max)
6078{
6079
6080	*min = *max = ah->keysize;
6081	if (ah->keysize == 0) {
6082		/*
6083		 * Transform takes arbitrary key size but algorithm
6084		 * key size is restricted.  Enforce this here.
6085		 */
6086		switch (alg) {
6087		case SADB_X_AALG_MD5:	*min = *max = 16; break;
6088		case SADB_X_AALG_SHA:	*min = *max = 20; break;
6089		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
6090		default:
6091			DPRINTF(("%s: unknown AH algorithm %u\n",
6092				__func__, alg));
6093			break;
6094		}
6095	}
6096}
6097
6098/*
6099 * XXX reorder combinations by preference
6100 */
6101static struct mbuf *
6102key_getcomb_ah()
6103{
6104	struct sadb_comb *comb;
6105	struct auth_hash *algo;
6106	struct mbuf *m;
6107	u_int16_t minkeysize, maxkeysize;
6108	int i;
6109	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6110
6111	m = NULL;
6112	for (i = 1; i <= SADB_AALG_MAX; i++) {
6113#if 1
6114		/* we prefer HMAC algorithms, not old algorithms */
6115		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
6116			continue;
6117#endif
6118		algo = ah_algorithm_lookup(i);
6119		if (!algo)
6120			continue;
6121		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6122		/* discard algorithms with key size smaller than system min */
6123		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6124			continue;
6125
6126		if (!m) {
6127			IPSEC_ASSERT(l <= MLEN,
6128				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6129			MGET(m, M_DONTWAIT, MT_DATA);
6130			if (m) {
6131				M_ALIGN(m, l);
6132				m->m_len = l;
6133				m->m_next = NULL;
6134			}
6135		} else
6136			M_PREPEND(m, l, M_DONTWAIT);
6137		if (!m)
6138			return NULL;
6139
6140		comb = mtod(m, struct sadb_comb *);
6141		bzero(comb, sizeof(*comb));
6142		key_getcomb_setlifetime(comb);
6143		comb->sadb_comb_auth = i;
6144		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6145		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6146	}
6147
6148	return m;
6149}
6150
6151/*
6152 * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6153 * XXX reorder combinations by preference
6154 */
6155static struct mbuf *
6156key_getcomb_ipcomp()
6157{
6158	struct sadb_comb *comb;
6159	struct comp_algo *algo;
6160	struct mbuf *m;
6161	int i;
6162	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6163
6164	m = NULL;
6165	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6166		algo = ipcomp_algorithm_lookup(i);
6167		if (!algo)
6168			continue;
6169
6170		if (!m) {
6171			IPSEC_ASSERT(l <= MLEN,
6172				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6173			MGET(m, M_DONTWAIT, MT_DATA);
6174			if (m) {
6175				M_ALIGN(m, l);
6176				m->m_len = l;
6177				m->m_next = NULL;
6178			}
6179		} else
6180			M_PREPEND(m, l, M_DONTWAIT);
6181		if (!m)
6182			return NULL;
6183
6184		comb = mtod(m, struct sadb_comb *);
6185		bzero(comb, sizeof(*comb));
6186		key_getcomb_setlifetime(comb);
6187		comb->sadb_comb_encrypt = i;
6188		/* what should we set into sadb_comb_*_{min,max}bits? */
6189	}
6190
6191	return m;
6192}
6193
6194/*
6195 * XXX no way to pass mode (transport/tunnel) to userland
6196 * XXX replay checking?
6197 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6198 */
6199static struct mbuf *
6200key_getprop(saidx)
6201	const struct secasindex *saidx;
6202{
6203	struct sadb_prop *prop;
6204	struct mbuf *m, *n;
6205	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6206	int totlen;
6207
6208	switch (saidx->proto)  {
6209	case IPPROTO_ESP:
6210		m = key_getcomb_esp();
6211		break;
6212	case IPPROTO_AH:
6213		m = key_getcomb_ah();
6214		break;
6215	case IPPROTO_IPCOMP:
6216		m = key_getcomb_ipcomp();
6217		break;
6218	default:
6219		return NULL;
6220	}
6221
6222	if (!m)
6223		return NULL;
6224	M_PREPEND(m, l, M_DONTWAIT);
6225	if (!m)
6226		return NULL;
6227
6228	totlen = 0;
6229	for (n = m; n; n = n->m_next)
6230		totlen += n->m_len;
6231
6232	prop = mtod(m, struct sadb_prop *);
6233	bzero(prop, sizeof(*prop));
6234	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6235	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6236	prop->sadb_prop_replay = 32;	/* XXX */
6237
6238	return m;
6239}
6240
6241/*
6242 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6243 * send
6244 *   <base, SA, address(SD), (address(P)), x_policy,
6245 *       (identity(SD),) (sensitivity,) proposal>
6246 * to KMD, and expect to receive
6247 *   <base> with SADB_ACQUIRE if error occured,
6248 * or
6249 *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6250 * from KMD by PF_KEY.
6251 *
6252 * XXX x_policy is outside of RFC2367 (KAME extension).
6253 * XXX sensitivity is not supported.
6254 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6255 * see comment for key_getcomb_ipcomp().
6256 *
6257 * OUT:
6258 *    0     : succeed
6259 *    others: error number
6260 */
6261static int
6262key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6263{
6264	struct mbuf *result = NULL, *m;
6265	struct secacq *newacq;
6266	u_int8_t satype;
6267	int error = -1;
6268	u_int32_t seq;
6269
6270	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6271	satype = key_proto2satype(saidx->proto);
6272	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6273
6274	/*
6275	 * We never do anything about acquirng SA.  There is anather
6276	 * solution that kernel blocks to send SADB_ACQUIRE message until
6277	 * getting something message from IKEd.  In later case, to be
6278	 * managed with ACQUIRING list.
6279	 */
6280	/* Get an entry to check whether sending message or not. */
6281	if ((newacq = key_getacq(saidx)) != NULL) {
6282		if (V_key_blockacq_count < newacq->count) {
6283			/* reset counter and do send message. */
6284			newacq->count = 0;
6285		} else {
6286			/* increment counter and do nothing. */
6287			newacq->count++;
6288			return 0;
6289		}
6290	} else {
6291		/* make new entry for blocking to send SADB_ACQUIRE. */
6292		if ((newacq = key_newacq(saidx)) == NULL)
6293			return ENOBUFS;
6294	}
6295
6296
6297	seq = newacq->seq;
6298	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6299	if (!m) {
6300		error = ENOBUFS;
6301		goto fail;
6302	}
6303	result = m;
6304
6305	/*
6306	 * No SADB_X_EXT_NAT_T_* here: we do not know
6307	 * anything related to NAT-T at this time.
6308	 */
6309
6310	/* set sadb_address for saidx's. */
6311	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6312	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6313	if (!m) {
6314		error = ENOBUFS;
6315		goto fail;
6316	}
6317	m_cat(result, m);
6318
6319	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6320	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6321	if (!m) {
6322		error = ENOBUFS;
6323		goto fail;
6324	}
6325	m_cat(result, m);
6326
6327	/* XXX proxy address (optional) */
6328
6329	/* set sadb_x_policy */
6330	if (sp) {
6331		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6332		if (!m) {
6333			error = ENOBUFS;
6334			goto fail;
6335		}
6336		m_cat(result, m);
6337	}
6338
6339	/* XXX identity (optional) */
6340#if 0
6341	if (idexttype && fqdn) {
6342		/* create identity extension (FQDN) */
6343		struct sadb_ident *id;
6344		int fqdnlen;
6345
6346		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
6347		id = (struct sadb_ident *)p;
6348		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6349		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6350		id->sadb_ident_exttype = idexttype;
6351		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6352		bcopy(fqdn, id + 1, fqdnlen);
6353		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6354	}
6355
6356	if (idexttype) {
6357		/* create identity extension (USERFQDN) */
6358		struct sadb_ident *id;
6359		int userfqdnlen;
6360
6361		if (userfqdn) {
6362			/* +1 for terminating-NUL */
6363			userfqdnlen = strlen(userfqdn) + 1;
6364		} else
6365			userfqdnlen = 0;
6366		id = (struct sadb_ident *)p;
6367		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6368		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6369		id->sadb_ident_exttype = idexttype;
6370		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6371		/* XXX is it correct? */
6372		if (curproc && curproc->p_cred)
6373			id->sadb_ident_id = curproc->p_cred->p_ruid;
6374		if (userfqdn && userfqdnlen)
6375			bcopy(userfqdn, id + 1, userfqdnlen);
6376		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6377	}
6378#endif
6379
6380	/* XXX sensitivity (optional) */
6381
6382	/* create proposal/combination extension */
6383	m = key_getprop(saidx);
6384#if 0
6385	/*
6386	 * spec conformant: always attach proposal/combination extension,
6387	 * the problem is that we have no way to attach it for ipcomp,
6388	 * due to the way sadb_comb is declared in RFC2367.
6389	 */
6390	if (!m) {
6391		error = ENOBUFS;
6392		goto fail;
6393	}
6394	m_cat(result, m);
6395#else
6396	/*
6397	 * outside of spec; make proposal/combination extension optional.
6398	 */
6399	if (m)
6400		m_cat(result, m);
6401#endif
6402
6403	if ((result->m_flags & M_PKTHDR) == 0) {
6404		error = EINVAL;
6405		goto fail;
6406	}
6407
6408	if (result->m_len < sizeof(struct sadb_msg)) {
6409		result = m_pullup(result, sizeof(struct sadb_msg));
6410		if (result == NULL) {
6411			error = ENOBUFS;
6412			goto fail;
6413		}
6414	}
6415
6416	result->m_pkthdr.len = 0;
6417	for (m = result; m; m = m->m_next)
6418		result->m_pkthdr.len += m->m_len;
6419
6420	mtod(result, struct sadb_msg *)->sadb_msg_len =
6421	    PFKEY_UNIT64(result->m_pkthdr.len);
6422
6423	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6424
6425 fail:
6426	if (result)
6427		m_freem(result);
6428	return error;
6429}
6430
6431static struct secacq *
6432key_newacq(const struct secasindex *saidx)
6433{
6434	struct secacq *newacq;
6435
6436	/* get new entry */
6437	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6438	if (newacq == NULL) {
6439		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6440		return NULL;
6441	}
6442
6443	/* copy secindex */
6444	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6445	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6446	newacq->created = time_second;
6447	newacq->count = 0;
6448
6449	/* add to acqtree */
6450	ACQ_LOCK();
6451	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6452	ACQ_UNLOCK();
6453
6454	return newacq;
6455}
6456
6457static struct secacq *
6458key_getacq(const struct secasindex *saidx)
6459{
6460	struct secacq *acq;
6461
6462	ACQ_LOCK();
6463	LIST_FOREACH(acq, &V_acqtree, chain) {
6464		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6465			break;
6466	}
6467	ACQ_UNLOCK();
6468
6469	return acq;
6470}
6471
6472static struct secacq *
6473key_getacqbyseq(seq)
6474	u_int32_t seq;
6475{
6476	struct secacq *acq;
6477
6478	ACQ_LOCK();
6479	LIST_FOREACH(acq, &V_acqtree, chain) {
6480		if (acq->seq == seq)
6481			break;
6482	}
6483	ACQ_UNLOCK();
6484
6485	return acq;
6486}
6487
6488static struct secspacq *
6489key_newspacq(spidx)
6490	struct secpolicyindex *spidx;
6491{
6492	struct secspacq *acq;
6493
6494	/* get new entry */
6495	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6496	if (acq == NULL) {
6497		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6498		return NULL;
6499	}
6500
6501	/* copy secindex */
6502	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6503	acq->created = time_second;
6504	acq->count = 0;
6505
6506	/* add to spacqtree */
6507	SPACQ_LOCK();
6508	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6509	SPACQ_UNLOCK();
6510
6511	return acq;
6512}
6513
6514static struct secspacq *
6515key_getspacq(spidx)
6516	struct secpolicyindex *spidx;
6517{
6518	struct secspacq *acq;
6519
6520	SPACQ_LOCK();
6521	LIST_FOREACH(acq, &V_spacqtree, chain) {
6522		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6523			/* NB: return holding spacq_lock */
6524			return acq;
6525		}
6526	}
6527	SPACQ_UNLOCK();
6528
6529	return NULL;
6530}
6531
6532/*
6533 * SADB_ACQUIRE processing,
6534 * in first situation, is receiving
6535 *   <base>
6536 * from the ikmpd, and clear sequence of its secasvar entry.
6537 *
6538 * In second situation, is receiving
6539 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6540 * from a user land process, and return
6541 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6542 * to the socket.
6543 *
6544 * m will always be freed.
6545 */
6546static int
6547key_acquire2(so, m, mhp)
6548	struct socket *so;
6549	struct mbuf *m;
6550	const struct sadb_msghdr *mhp;
6551{
6552	const struct sadb_address *src0, *dst0;
6553	struct secasindex saidx;
6554	struct secashead *sah;
6555	u_int16_t proto;
6556	int error;
6557
6558	IPSEC_ASSERT(so != NULL, ("null socket"));
6559	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6560	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6561	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6562
6563	/*
6564	 * Error message from KMd.
6565	 * We assume that if error was occured in IKEd, the length of PFKEY
6566	 * message is equal to the size of sadb_msg structure.
6567	 * We do not raise error even if error occured in this function.
6568	 */
6569	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6570		struct secacq *acq;
6571
6572		/* check sequence number */
6573		if (mhp->msg->sadb_msg_seq == 0) {
6574			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6575				"number.\n", __func__));
6576			m_freem(m);
6577			return 0;
6578		}
6579
6580		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6581			/*
6582			 * the specified larval SA is already gone, or we got
6583			 * a bogus sequence number.  we can silently ignore it.
6584			 */
6585			m_freem(m);
6586			return 0;
6587		}
6588
6589		/* reset acq counter in order to deletion by timehander. */
6590		acq->created = time_second;
6591		acq->count = 0;
6592		m_freem(m);
6593		return 0;
6594	}
6595
6596	/*
6597	 * This message is from user land.
6598	 */
6599
6600	/* map satype to proto */
6601	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6602		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6603			__func__));
6604		return key_senderror(so, m, EINVAL);
6605	}
6606
6607	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6608	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6609	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6610		/* error */
6611		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6612			__func__));
6613		return key_senderror(so, m, EINVAL);
6614	}
6615	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6616	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6617	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6618		/* error */
6619		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6620			__func__));
6621		return key_senderror(so, m, EINVAL);
6622	}
6623
6624	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6625	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6626
6627	/* XXX boundary check against sa_len */
6628	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6629
6630	/*
6631	 * Make sure the port numbers are zero.
6632	 * In case of NAT-T we will update them later if needed.
6633	 */
6634	KEY_PORTTOSADDR(&saidx.src, 0);
6635	KEY_PORTTOSADDR(&saidx.dst, 0);
6636
6637#ifndef IPSEC_NAT_T
6638	/*
6639	 * Handle NAT-T info if present.
6640	 */
6641
6642	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6643	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6644		struct sadb_x_nat_t_port *sport, *dport;
6645
6646		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6647		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6648			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6649			    __func__));
6650			return key_senderror(so, m, EINVAL);
6651		}
6652
6653		sport = (struct sadb_x_nat_t_port *)
6654		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6655		dport = (struct sadb_x_nat_t_port *)
6656		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6657
6658		if (sport)
6659			KEY_PORTTOSADDR(&saidx.src,
6660			    sport->sadb_x_nat_t_port_port);
6661		if (dport)
6662			KEY_PORTTOSADDR(&saidx.dst,
6663			    dport->sadb_x_nat_t_port_port);
6664	}
6665#endif
6666
6667	/* get a SA index */
6668	SAHTREE_LOCK();
6669	LIST_FOREACH(sah, &V_sahtree, chain) {
6670		if (sah->state == SADB_SASTATE_DEAD)
6671			continue;
6672		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6673			break;
6674	}
6675	SAHTREE_UNLOCK();
6676	if (sah != NULL) {
6677		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6678		return key_senderror(so, m, EEXIST);
6679	}
6680
6681	error = key_acquire(&saidx, NULL);
6682	if (error != 0) {
6683		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6684			__func__, mhp->msg->sadb_msg_errno));
6685		return key_senderror(so, m, error);
6686	}
6687
6688	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6689}
6690
6691/*
6692 * SADB_REGISTER processing.
6693 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6694 * receive
6695 *   <base>
6696 * from the ikmpd, and register a socket to send PF_KEY messages,
6697 * and send
6698 *   <base, supported>
6699 * to KMD by PF_KEY.
6700 * If socket is detached, must free from regnode.
6701 *
6702 * m will always be freed.
6703 */
6704static int
6705key_register(so, m, mhp)
6706	struct socket *so;
6707	struct mbuf *m;
6708	const struct sadb_msghdr *mhp;
6709{
6710	struct secreg *reg, *newreg = 0;
6711
6712	IPSEC_ASSERT(so != NULL, ("null socket"));
6713	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6714	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6715	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6716
6717	/* check for invalid register message */
6718	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6719		return key_senderror(so, m, EINVAL);
6720
6721	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6722	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6723		goto setmsg;
6724
6725	/* check whether existing or not */
6726	REGTREE_LOCK();
6727	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6728		if (reg->so == so) {
6729			REGTREE_UNLOCK();
6730			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6731				__func__));
6732			return key_senderror(so, m, EEXIST);
6733		}
6734	}
6735
6736	/* create regnode */
6737	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6738	if (newreg == NULL) {
6739		REGTREE_UNLOCK();
6740		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6741		return key_senderror(so, m, ENOBUFS);
6742	}
6743
6744	newreg->so = so;
6745	((struct keycb *)sotorawcb(so))->kp_registered++;
6746
6747	/* add regnode to regtree. */
6748	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6749	REGTREE_UNLOCK();
6750
6751  setmsg:
6752    {
6753	struct mbuf *n;
6754	struct sadb_msg *newmsg;
6755	struct sadb_supported *sup;
6756	u_int len, alen, elen;
6757	int off;
6758	int i;
6759	struct sadb_alg *alg;
6760
6761	/* create new sadb_msg to reply. */
6762	alen = 0;
6763	for (i = 1; i <= SADB_AALG_MAX; i++) {
6764		if (ah_algorithm_lookup(i))
6765			alen += sizeof(struct sadb_alg);
6766	}
6767	if (alen)
6768		alen += sizeof(struct sadb_supported);
6769	elen = 0;
6770	for (i = 1; i <= SADB_EALG_MAX; i++) {
6771		if (esp_algorithm_lookup(i))
6772			elen += sizeof(struct sadb_alg);
6773	}
6774	if (elen)
6775		elen += sizeof(struct sadb_supported);
6776
6777	len = sizeof(struct sadb_msg) + alen + elen;
6778
6779	if (len > MCLBYTES)
6780		return key_senderror(so, m, ENOBUFS);
6781
6782	MGETHDR(n, M_DONTWAIT, MT_DATA);
6783	if (len > MHLEN) {
6784		MCLGET(n, M_DONTWAIT);
6785		if ((n->m_flags & M_EXT) == 0) {
6786			m_freem(n);
6787			n = NULL;
6788		}
6789	}
6790	if (!n)
6791		return key_senderror(so, m, ENOBUFS);
6792
6793	n->m_pkthdr.len = n->m_len = len;
6794	n->m_next = NULL;
6795	off = 0;
6796
6797	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6798	newmsg = mtod(n, struct sadb_msg *);
6799	newmsg->sadb_msg_errno = 0;
6800	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6801	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6802
6803	/* for authentication algorithm */
6804	if (alen) {
6805		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6806		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6807		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6808		off += PFKEY_ALIGN8(sizeof(*sup));
6809
6810		for (i = 1; i <= SADB_AALG_MAX; i++) {
6811			struct auth_hash *aalgo;
6812			u_int16_t minkeysize, maxkeysize;
6813
6814			aalgo = ah_algorithm_lookup(i);
6815			if (!aalgo)
6816				continue;
6817			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6818			alg->sadb_alg_id = i;
6819			alg->sadb_alg_ivlen = 0;
6820			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6821			alg->sadb_alg_minbits = _BITS(minkeysize);
6822			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6823			off += PFKEY_ALIGN8(sizeof(*alg));
6824		}
6825	}
6826
6827	/* for encryption algorithm */
6828	if (elen) {
6829		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6830		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6831		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6832		off += PFKEY_ALIGN8(sizeof(*sup));
6833
6834		for (i = 1; i <= SADB_EALG_MAX; i++) {
6835			struct enc_xform *ealgo;
6836
6837			ealgo = esp_algorithm_lookup(i);
6838			if (!ealgo)
6839				continue;
6840			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6841			alg->sadb_alg_id = i;
6842			alg->sadb_alg_ivlen = ealgo->blocksize;
6843			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6844			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6845			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6846		}
6847	}
6848
6849	IPSEC_ASSERT(off == len,
6850		("length assumption failed (off %u len %u)", off, len));
6851
6852	m_freem(m);
6853	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6854    }
6855}
6856
6857/*
6858 * free secreg entry registered.
6859 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6860 */
6861void
6862key_freereg(struct socket *so)
6863{
6864	struct secreg *reg;
6865	int i;
6866
6867	IPSEC_ASSERT(so != NULL, ("NULL so"));
6868
6869	/*
6870	 * check whether existing or not.
6871	 * check all type of SA, because there is a potential that
6872	 * one socket is registered to multiple type of SA.
6873	 */
6874	REGTREE_LOCK();
6875	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6876		LIST_FOREACH(reg, &V_regtree[i], chain) {
6877			if (reg->so == so && __LIST_CHAINED(reg)) {
6878				LIST_REMOVE(reg, chain);
6879				free(reg, M_IPSEC_SAR);
6880				break;
6881			}
6882		}
6883	}
6884	REGTREE_UNLOCK();
6885}
6886
6887/*
6888 * SADB_EXPIRE processing
6889 * send
6890 *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6891 * to KMD by PF_KEY.
6892 * NOTE: We send only soft lifetime extension.
6893 *
6894 * OUT:	0	: succeed
6895 *	others	: error number
6896 */
6897static int
6898key_expire(struct secasvar *sav)
6899{
6900	int s;
6901	int satype;
6902	struct mbuf *result = NULL, *m;
6903	int len;
6904	int error = -1;
6905	struct sadb_lifetime *lt;
6906
6907	/* XXX: Why do we lock ? */
6908	s = splnet();	/*called from softclock()*/
6909
6910	IPSEC_ASSERT (sav != NULL, ("null sav"));
6911	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6912
6913	/* set msg header */
6914	satype = key_proto2satype(sav->sah->saidx.proto);
6915	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6916	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6917	if (!m) {
6918		error = ENOBUFS;
6919		goto fail;
6920	}
6921	result = m;
6922
6923	/* create SA extension */
6924	m = key_setsadbsa(sav);
6925	if (!m) {
6926		error = ENOBUFS;
6927		goto fail;
6928	}
6929	m_cat(result, m);
6930
6931	/* create SA extension */
6932	m = key_setsadbxsa2(sav->sah->saidx.mode,
6933			sav->replay ? sav->replay->count : 0,
6934			sav->sah->saidx.reqid);
6935	if (!m) {
6936		error = ENOBUFS;
6937		goto fail;
6938	}
6939	m_cat(result, m);
6940
6941	/* create lifetime extension (current and soft) */
6942	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6943	m = key_alloc_mbuf(len);
6944	if (!m || m->m_next) {	/*XXX*/
6945		if (m)
6946			m_freem(m);
6947		error = ENOBUFS;
6948		goto fail;
6949	}
6950	bzero(mtod(m, caddr_t), len);
6951	lt = mtod(m, struct sadb_lifetime *);
6952	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6953	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6954	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6955	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6956	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6957	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6958	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6959	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6960	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6961	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6962	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6963	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6964	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6965	m_cat(result, m);
6966
6967	/* set sadb_address for source */
6968	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6969	    &sav->sah->saidx.src.sa,
6970	    FULLMASK, IPSEC_ULPROTO_ANY);
6971	if (!m) {
6972		error = ENOBUFS;
6973		goto fail;
6974	}
6975	m_cat(result, m);
6976
6977	/* set sadb_address for destination */
6978	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6979	    &sav->sah->saidx.dst.sa,
6980	    FULLMASK, IPSEC_ULPROTO_ANY);
6981	if (!m) {
6982		error = ENOBUFS;
6983		goto fail;
6984	}
6985	m_cat(result, m);
6986
6987	/*
6988	 * XXX-BZ Handle NAT-T extensions here.
6989	 */
6990
6991	if ((result->m_flags & M_PKTHDR) == 0) {
6992		error = EINVAL;
6993		goto fail;
6994	}
6995
6996	if (result->m_len < sizeof(struct sadb_msg)) {
6997		result = m_pullup(result, sizeof(struct sadb_msg));
6998		if (result == NULL) {
6999			error = ENOBUFS;
7000			goto fail;
7001		}
7002	}
7003
7004	result->m_pkthdr.len = 0;
7005	for (m = result; m; m = m->m_next)
7006		result->m_pkthdr.len += m->m_len;
7007
7008	mtod(result, struct sadb_msg *)->sadb_msg_len =
7009	    PFKEY_UNIT64(result->m_pkthdr.len);
7010
7011	splx(s);
7012	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7013
7014 fail:
7015	if (result)
7016		m_freem(result);
7017	splx(s);
7018	return error;
7019}
7020
7021/*
7022 * SADB_FLUSH processing
7023 * receive
7024 *   <base>
7025 * from the ikmpd, and free all entries in secastree.
7026 * and send,
7027 *   <base>
7028 * to the ikmpd.
7029 * NOTE: to do is only marking SADB_SASTATE_DEAD.
7030 *
7031 * m will always be freed.
7032 */
7033static int
7034key_flush(so, m, mhp)
7035	struct socket *so;
7036	struct mbuf *m;
7037	const struct sadb_msghdr *mhp;
7038{
7039	struct sadb_msg *newmsg;
7040	struct secashead *sah, *nextsah;
7041	struct secasvar *sav, *nextsav;
7042	u_int16_t proto;
7043	u_int8_t state;
7044	u_int stateidx;
7045
7046	IPSEC_ASSERT(so != NULL, ("null socket"));
7047	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7048	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7049
7050	/* map satype to proto */
7051	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7052		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7053			__func__));
7054		return key_senderror(so, m, EINVAL);
7055	}
7056
7057	/* no SATYPE specified, i.e. flushing all SA. */
7058	SAHTREE_LOCK();
7059	for (sah = LIST_FIRST(&V_sahtree);
7060	     sah != NULL;
7061	     sah = nextsah) {
7062		nextsah = LIST_NEXT(sah, chain);
7063
7064		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7065		 && proto != sah->saidx.proto)
7066			continue;
7067
7068		for (stateidx = 0;
7069		     stateidx < _ARRAYLEN(saorder_state_alive);
7070		     stateidx++) {
7071			state = saorder_state_any[stateidx];
7072			for (sav = LIST_FIRST(&sah->savtree[state]);
7073			     sav != NULL;
7074			     sav = nextsav) {
7075
7076				nextsav = LIST_NEXT(sav, chain);
7077
7078				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7079				KEY_FREESAV(&sav);
7080			}
7081		}
7082
7083		sah->state = SADB_SASTATE_DEAD;
7084	}
7085	SAHTREE_UNLOCK();
7086
7087	if (m->m_len < sizeof(struct sadb_msg) ||
7088	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7089		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7090		return key_senderror(so, m, ENOBUFS);
7091	}
7092
7093	if (m->m_next)
7094		m_freem(m->m_next);
7095	m->m_next = NULL;
7096	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7097	newmsg = mtod(m, struct sadb_msg *);
7098	newmsg->sadb_msg_errno = 0;
7099	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7100
7101	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7102}
7103
7104/*
7105 * SADB_DUMP processing
7106 * dump all entries including status of DEAD in SAD.
7107 * receive
7108 *   <base>
7109 * from the ikmpd, and dump all secasvar leaves
7110 * and send,
7111 *   <base> .....
7112 * to the ikmpd.
7113 *
7114 * m will always be freed.
7115 */
7116static int
7117key_dump(so, m, mhp)
7118	struct socket *so;
7119	struct mbuf *m;
7120	const struct sadb_msghdr *mhp;
7121{
7122	struct secashead *sah;
7123	struct secasvar *sav;
7124	u_int16_t proto;
7125	u_int stateidx;
7126	u_int8_t satype;
7127	u_int8_t state;
7128	int cnt;
7129	struct sadb_msg *newmsg;
7130	struct mbuf *n;
7131
7132	IPSEC_ASSERT(so != NULL, ("null socket"));
7133	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7134	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7135	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7136
7137	/* map satype to proto */
7138	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7139		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7140			__func__));
7141		return key_senderror(so, m, EINVAL);
7142	}
7143
7144	/* count sav entries to be sent to the userland. */
7145	cnt = 0;
7146	SAHTREE_LOCK();
7147	LIST_FOREACH(sah, &V_sahtree, chain) {
7148		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7149		 && proto != sah->saidx.proto)
7150			continue;
7151
7152		for (stateidx = 0;
7153		     stateidx < _ARRAYLEN(saorder_state_any);
7154		     stateidx++) {
7155			state = saorder_state_any[stateidx];
7156			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7157				cnt++;
7158			}
7159		}
7160	}
7161
7162	if (cnt == 0) {
7163		SAHTREE_UNLOCK();
7164		return key_senderror(so, m, ENOENT);
7165	}
7166
7167	/* send this to the userland, one at a time. */
7168	newmsg = NULL;
7169	LIST_FOREACH(sah, &V_sahtree, chain) {
7170		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7171		 && proto != sah->saidx.proto)
7172			continue;
7173
7174		/* map proto to satype */
7175		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7176			SAHTREE_UNLOCK();
7177			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7178				"SAD.\n", __func__));
7179			return key_senderror(so, m, EINVAL);
7180		}
7181
7182		for (stateidx = 0;
7183		     stateidx < _ARRAYLEN(saorder_state_any);
7184		     stateidx++) {
7185			state = saorder_state_any[stateidx];
7186			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7187				n = key_setdumpsa(sav, SADB_DUMP, satype,
7188				    --cnt, mhp->msg->sadb_msg_pid);
7189				if (!n) {
7190					SAHTREE_UNLOCK();
7191					return key_senderror(so, m, ENOBUFS);
7192				}
7193				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7194			}
7195		}
7196	}
7197	SAHTREE_UNLOCK();
7198
7199	m_freem(m);
7200	return 0;
7201}
7202
7203/*
7204 * SADB_X_PROMISC processing
7205 *
7206 * m will always be freed.
7207 */
7208static int
7209key_promisc(so, m, mhp)
7210	struct socket *so;
7211	struct mbuf *m;
7212	const struct sadb_msghdr *mhp;
7213{
7214	int olen;
7215
7216	IPSEC_ASSERT(so != NULL, ("null socket"));
7217	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7218	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7219	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7220
7221	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7222
7223	if (olen < sizeof(struct sadb_msg)) {
7224#if 1
7225		return key_senderror(so, m, EINVAL);
7226#else
7227		m_freem(m);
7228		return 0;
7229#endif
7230	} else if (olen == sizeof(struct sadb_msg)) {
7231		/* enable/disable promisc mode */
7232		struct keycb *kp;
7233
7234		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7235			return key_senderror(so, m, EINVAL);
7236		mhp->msg->sadb_msg_errno = 0;
7237		switch (mhp->msg->sadb_msg_satype) {
7238		case 0:
7239		case 1:
7240			kp->kp_promisc = mhp->msg->sadb_msg_satype;
7241			break;
7242		default:
7243			return key_senderror(so, m, EINVAL);
7244		}
7245
7246		/* send the original message back to everyone */
7247		mhp->msg->sadb_msg_errno = 0;
7248		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7249	} else {
7250		/* send packet as is */
7251
7252		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7253
7254		/* TODO: if sadb_msg_seq is specified, send to specific pid */
7255		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7256	}
7257}
7258
7259static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
7260		const struct sadb_msghdr *)) = {
7261	NULL,		/* SADB_RESERVED */
7262	key_getspi,	/* SADB_GETSPI */
7263	key_update,	/* SADB_UPDATE */
7264	key_add,	/* SADB_ADD */
7265	key_delete,	/* SADB_DELETE */
7266	key_get,	/* SADB_GET */
7267	key_acquire2,	/* SADB_ACQUIRE */
7268	key_register,	/* SADB_REGISTER */
7269	NULL,		/* SADB_EXPIRE */
7270	key_flush,	/* SADB_FLUSH */
7271	key_dump,	/* SADB_DUMP */
7272	key_promisc,	/* SADB_X_PROMISC */
7273	NULL,		/* SADB_X_PCHANGE */
7274	key_spdadd,	/* SADB_X_SPDUPDATE */
7275	key_spdadd,	/* SADB_X_SPDADD */
7276	key_spddelete,	/* SADB_X_SPDDELETE */
7277	key_spdget,	/* SADB_X_SPDGET */
7278	NULL,		/* SADB_X_SPDACQUIRE */
7279	key_spddump,	/* SADB_X_SPDDUMP */
7280	key_spdflush,	/* SADB_X_SPDFLUSH */
7281	key_spdadd,	/* SADB_X_SPDSETIDX */
7282	NULL,		/* SADB_X_SPDEXPIRE */
7283	key_spddelete2,	/* SADB_X_SPDDELETE2 */
7284};
7285
7286/*
7287 * parse sadb_msg buffer to process PFKEYv2,
7288 * and create a data to response if needed.
7289 * I think to be dealed with mbuf directly.
7290 * IN:
7291 *     msgp  : pointer to pointer to a received buffer pulluped.
7292 *             This is rewrited to response.
7293 *     so    : pointer to socket.
7294 * OUT:
7295 *    length for buffer to send to user process.
7296 */
7297int
7298key_parse(m, so)
7299	struct mbuf *m;
7300	struct socket *so;
7301{
7302	struct sadb_msg *msg;
7303	struct sadb_msghdr mh;
7304	u_int orglen;
7305	int error;
7306	int target;
7307
7308	IPSEC_ASSERT(so != NULL, ("null socket"));
7309	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7310
7311#if 0	/*kdebug_sadb assumes msg in linear buffer*/
7312	KEYDEBUG(KEYDEBUG_KEY_DUMP,
7313		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7314		kdebug_sadb(msg));
7315#endif
7316
7317	if (m->m_len < sizeof(struct sadb_msg)) {
7318		m = m_pullup(m, sizeof(struct sadb_msg));
7319		if (!m)
7320			return ENOBUFS;
7321	}
7322	msg = mtod(m, struct sadb_msg *);
7323	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7324	target = KEY_SENDUP_ONE;
7325
7326	if ((m->m_flags & M_PKTHDR) == 0 ||
7327	    m->m_pkthdr.len != m->m_pkthdr.len) {
7328		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7329		V_pfkeystat.out_invlen++;
7330		error = EINVAL;
7331		goto senderror;
7332	}
7333
7334	if (msg->sadb_msg_version != PF_KEY_V2) {
7335		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7336		    __func__, msg->sadb_msg_version));
7337		V_pfkeystat.out_invver++;
7338		error = EINVAL;
7339		goto senderror;
7340	}
7341
7342	if (msg->sadb_msg_type > SADB_MAX) {
7343		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7344		    __func__, msg->sadb_msg_type));
7345		V_pfkeystat.out_invmsgtype++;
7346		error = EINVAL;
7347		goto senderror;
7348	}
7349
7350	/* for old-fashioned code - should be nuked */
7351	if (m->m_pkthdr.len > MCLBYTES) {
7352		m_freem(m);
7353		return ENOBUFS;
7354	}
7355	if (m->m_next) {
7356		struct mbuf *n;
7357
7358		MGETHDR(n, M_DONTWAIT, MT_DATA);
7359		if (n && m->m_pkthdr.len > MHLEN) {
7360			MCLGET(n, M_DONTWAIT);
7361			if ((n->m_flags & M_EXT) == 0) {
7362				m_free(n);
7363				n = NULL;
7364			}
7365		}
7366		if (!n) {
7367			m_freem(m);
7368			return ENOBUFS;
7369		}
7370		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7371		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7372		n->m_next = NULL;
7373		m_freem(m);
7374		m = n;
7375	}
7376
7377	/* align the mbuf chain so that extensions are in contiguous region. */
7378	error = key_align(m, &mh);
7379	if (error)
7380		return error;
7381
7382	msg = mh.msg;
7383
7384	/* check SA type */
7385	switch (msg->sadb_msg_satype) {
7386	case SADB_SATYPE_UNSPEC:
7387		switch (msg->sadb_msg_type) {
7388		case SADB_GETSPI:
7389		case SADB_UPDATE:
7390		case SADB_ADD:
7391		case SADB_DELETE:
7392		case SADB_GET:
7393		case SADB_ACQUIRE:
7394		case SADB_EXPIRE:
7395			ipseclog((LOG_DEBUG, "%s: must specify satype "
7396			    "when msg type=%u.\n", __func__,
7397			    msg->sadb_msg_type));
7398			V_pfkeystat.out_invsatype++;
7399			error = EINVAL;
7400			goto senderror;
7401		}
7402		break;
7403	case SADB_SATYPE_AH:
7404	case SADB_SATYPE_ESP:
7405	case SADB_X_SATYPE_IPCOMP:
7406	case SADB_X_SATYPE_TCPSIGNATURE:
7407		switch (msg->sadb_msg_type) {
7408		case SADB_X_SPDADD:
7409		case SADB_X_SPDDELETE:
7410		case SADB_X_SPDGET:
7411		case SADB_X_SPDDUMP:
7412		case SADB_X_SPDFLUSH:
7413		case SADB_X_SPDSETIDX:
7414		case SADB_X_SPDUPDATE:
7415		case SADB_X_SPDDELETE2:
7416			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7417				__func__, msg->sadb_msg_type));
7418			V_pfkeystat.out_invsatype++;
7419			error = EINVAL;
7420			goto senderror;
7421		}
7422		break;
7423	case SADB_SATYPE_RSVP:
7424	case SADB_SATYPE_OSPFV2:
7425	case SADB_SATYPE_RIPV2:
7426	case SADB_SATYPE_MIP:
7427		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7428			__func__, msg->sadb_msg_satype));
7429		V_pfkeystat.out_invsatype++;
7430		error = EOPNOTSUPP;
7431		goto senderror;
7432	case 1:	/* XXX: What does it do? */
7433		if (msg->sadb_msg_type == SADB_X_PROMISC)
7434			break;
7435		/*FALLTHROUGH*/
7436	default:
7437		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7438			__func__, msg->sadb_msg_satype));
7439		V_pfkeystat.out_invsatype++;
7440		error = EINVAL;
7441		goto senderror;
7442	}
7443
7444	/* check field of upper layer protocol and address family */
7445	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7446	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7447		struct sadb_address *src0, *dst0;
7448		u_int plen;
7449
7450		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7451		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7452
7453		/* check upper layer protocol */
7454		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7455			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7456				"mismatched.\n", __func__));
7457			V_pfkeystat.out_invaddr++;
7458			error = EINVAL;
7459			goto senderror;
7460		}
7461
7462		/* check family */
7463		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7464		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
7465			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7466				__func__));
7467			V_pfkeystat.out_invaddr++;
7468			error = EINVAL;
7469			goto senderror;
7470		}
7471		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7472		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
7473			ipseclog((LOG_DEBUG, "%s: address struct size "
7474				"mismatched.\n", __func__));
7475			V_pfkeystat.out_invaddr++;
7476			error = EINVAL;
7477			goto senderror;
7478		}
7479
7480		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7481		case AF_INET:
7482			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7483			    sizeof(struct sockaddr_in)) {
7484				V_pfkeystat.out_invaddr++;
7485				error = EINVAL;
7486				goto senderror;
7487			}
7488			break;
7489		case AF_INET6:
7490			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7491			    sizeof(struct sockaddr_in6)) {
7492				V_pfkeystat.out_invaddr++;
7493				error = EINVAL;
7494				goto senderror;
7495			}
7496			break;
7497		default:
7498			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7499				__func__));
7500			V_pfkeystat.out_invaddr++;
7501			error = EAFNOSUPPORT;
7502			goto senderror;
7503		}
7504
7505		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7506		case AF_INET:
7507			plen = sizeof(struct in_addr) << 3;
7508			break;
7509		case AF_INET6:
7510			plen = sizeof(struct in6_addr) << 3;
7511			break;
7512		default:
7513			plen = 0;	/*fool gcc*/
7514			break;
7515		}
7516
7517		/* check max prefix length */
7518		if (src0->sadb_address_prefixlen > plen ||
7519		    dst0->sadb_address_prefixlen > plen) {
7520			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7521				__func__));
7522			V_pfkeystat.out_invaddr++;
7523			error = EINVAL;
7524			goto senderror;
7525		}
7526
7527		/*
7528		 * prefixlen == 0 is valid because there can be a case when
7529		 * all addresses are matched.
7530		 */
7531	}
7532
7533	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7534	    key_typesw[msg->sadb_msg_type] == NULL) {
7535		V_pfkeystat.out_invmsgtype++;
7536		error = EINVAL;
7537		goto senderror;
7538	}
7539
7540	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7541
7542senderror:
7543	msg->sadb_msg_errno = error;
7544	return key_sendup_mbuf(so, m, target);
7545}
7546
7547static int
7548key_senderror(so, m, code)
7549	struct socket *so;
7550	struct mbuf *m;
7551	int code;
7552{
7553	struct sadb_msg *msg;
7554
7555	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7556		("mbuf too small, len %u", m->m_len));
7557
7558	msg = mtod(m, struct sadb_msg *);
7559	msg->sadb_msg_errno = code;
7560	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7561}
7562
7563/*
7564 * set the pointer to each header into message buffer.
7565 * m will be freed on error.
7566 * XXX larger-than-MCLBYTES extension?
7567 */
7568static int
7569key_align(m, mhp)
7570	struct mbuf *m;
7571	struct sadb_msghdr *mhp;
7572{
7573	struct mbuf *n;
7574	struct sadb_ext *ext;
7575	size_t off, end;
7576	int extlen;
7577	int toff;
7578
7579	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7580	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7581	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7582		("mbuf too small, len %u", m->m_len));
7583
7584	/* initialize */
7585	bzero(mhp, sizeof(*mhp));
7586
7587	mhp->msg = mtod(m, struct sadb_msg *);
7588	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7589
7590	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7591	extlen = end;	/*just in case extlen is not updated*/
7592	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7593		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7594		if (!n) {
7595			/* m is already freed */
7596			return ENOBUFS;
7597		}
7598		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7599
7600		/* set pointer */
7601		switch (ext->sadb_ext_type) {
7602		case SADB_EXT_SA:
7603		case SADB_EXT_ADDRESS_SRC:
7604		case SADB_EXT_ADDRESS_DST:
7605		case SADB_EXT_ADDRESS_PROXY:
7606		case SADB_EXT_LIFETIME_CURRENT:
7607		case SADB_EXT_LIFETIME_HARD:
7608		case SADB_EXT_LIFETIME_SOFT:
7609		case SADB_EXT_KEY_AUTH:
7610		case SADB_EXT_KEY_ENCRYPT:
7611		case SADB_EXT_IDENTITY_SRC:
7612		case SADB_EXT_IDENTITY_DST:
7613		case SADB_EXT_SENSITIVITY:
7614		case SADB_EXT_PROPOSAL:
7615		case SADB_EXT_SUPPORTED_AUTH:
7616		case SADB_EXT_SUPPORTED_ENCRYPT:
7617		case SADB_EXT_SPIRANGE:
7618		case SADB_X_EXT_POLICY:
7619		case SADB_X_EXT_SA2:
7620#ifdef IPSEC_NAT_T
7621		case SADB_X_EXT_NAT_T_TYPE:
7622		case SADB_X_EXT_NAT_T_SPORT:
7623		case SADB_X_EXT_NAT_T_DPORT:
7624		case SADB_X_EXT_NAT_T_OAI:
7625		case SADB_X_EXT_NAT_T_OAR:
7626		case SADB_X_EXT_NAT_T_FRAG:
7627#endif
7628			/* duplicate check */
7629			/*
7630			 * XXX Are there duplication payloads of either
7631			 * KEY_AUTH or KEY_ENCRYPT ?
7632			 */
7633			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7634				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7635					"%u\n", __func__, ext->sadb_ext_type));
7636				m_freem(m);
7637				V_pfkeystat.out_dupext++;
7638				return EINVAL;
7639			}
7640			break;
7641		default:
7642			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7643				__func__, ext->sadb_ext_type));
7644			m_freem(m);
7645			V_pfkeystat.out_invexttype++;
7646			return EINVAL;
7647		}
7648
7649		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7650
7651		if (key_validate_ext(ext, extlen)) {
7652			m_freem(m);
7653			V_pfkeystat.out_invlen++;
7654			return EINVAL;
7655		}
7656
7657		n = m_pulldown(m, off, extlen, &toff);
7658		if (!n) {
7659			/* m is already freed */
7660			return ENOBUFS;
7661		}
7662		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7663
7664		mhp->ext[ext->sadb_ext_type] = ext;
7665		mhp->extoff[ext->sadb_ext_type] = off;
7666		mhp->extlen[ext->sadb_ext_type] = extlen;
7667	}
7668
7669	if (off != end) {
7670		m_freem(m);
7671		V_pfkeystat.out_invlen++;
7672		return EINVAL;
7673	}
7674
7675	return 0;
7676}
7677
7678static int
7679key_validate_ext(ext, len)
7680	const struct sadb_ext *ext;
7681	int len;
7682{
7683	const struct sockaddr *sa;
7684	enum { NONE, ADDR } checktype = NONE;
7685	int baselen = 0;
7686	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7687
7688	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7689		return EINVAL;
7690
7691	/* if it does not match minimum/maximum length, bail */
7692	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7693	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7694		return EINVAL;
7695	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7696		return EINVAL;
7697	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7698		return EINVAL;
7699
7700	/* more checks based on sadb_ext_type XXX need more */
7701	switch (ext->sadb_ext_type) {
7702	case SADB_EXT_ADDRESS_SRC:
7703	case SADB_EXT_ADDRESS_DST:
7704	case SADB_EXT_ADDRESS_PROXY:
7705		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7706		checktype = ADDR;
7707		break;
7708	case SADB_EXT_IDENTITY_SRC:
7709	case SADB_EXT_IDENTITY_DST:
7710		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7711		    SADB_X_IDENTTYPE_ADDR) {
7712			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7713			checktype = ADDR;
7714		} else
7715			checktype = NONE;
7716		break;
7717	default:
7718		checktype = NONE;
7719		break;
7720	}
7721
7722	switch (checktype) {
7723	case NONE:
7724		break;
7725	case ADDR:
7726		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7727		if (len < baselen + sal)
7728			return EINVAL;
7729		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7730			return EINVAL;
7731		break;
7732	}
7733
7734	return 0;
7735}
7736
7737void
7738key_init(void)
7739{
7740	int i;
7741
7742	for (i = 0; i < IPSEC_DIR_MAX; i++)
7743		LIST_INIT(&V_sptree[i]);
7744
7745	LIST_INIT(&V_sahtree);
7746
7747	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7748		LIST_INIT(&V_regtree[i]);
7749
7750	LIST_INIT(&V_acqtree);
7751	LIST_INIT(&V_spacqtree);
7752
7753	/* system default */
7754	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7755	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7756
7757	if (!IS_DEFAULT_VNET(curvnet))
7758		return;
7759
7760	SPTREE_LOCK_INIT();
7761	REGTREE_LOCK_INIT();
7762	SAHTREE_LOCK_INIT();
7763	ACQ_LOCK_INIT();
7764	SPACQ_LOCK_INIT();
7765
7766#ifndef IPSEC_DEBUG2
7767	timeout((void *)key_timehandler, (void *)0, hz);
7768#endif /*IPSEC_DEBUG2*/
7769
7770	/* initialize key statistics */
7771	keystat.getspi_count = 1;
7772
7773	printf("IPsec: Initialized Security Association Processing.\n");
7774}
7775
7776#ifdef VIMAGE
7777void
7778key_destroy(void)
7779{
7780	struct secpolicy *sp, *nextsp;
7781	struct secspacq *acq, *nextacq;
7782	struct secashead *sah, *nextsah;
7783	struct secreg *reg;
7784	int i;
7785
7786	SPTREE_LOCK();
7787	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7788		for (sp = LIST_FIRST(&V_sptree[i]);
7789		    sp != NULL; sp = nextsp) {
7790			nextsp = LIST_NEXT(sp, chain);
7791			if (__LIST_CHAINED(sp)) {
7792				LIST_REMOVE(sp, chain);
7793				free(sp, M_IPSEC_SP);
7794			}
7795		}
7796	}
7797	SPTREE_UNLOCK();
7798
7799	SAHTREE_LOCK();
7800	for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7801		nextsah = LIST_NEXT(sah, chain);
7802		if (__LIST_CHAINED(sah)) {
7803			LIST_REMOVE(sah, chain);
7804			free(sah, M_IPSEC_SAH);
7805		}
7806	}
7807	SAHTREE_UNLOCK();
7808
7809	REGTREE_LOCK();
7810	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7811		LIST_FOREACH(reg, &V_regtree[i], chain) {
7812			if (__LIST_CHAINED(reg)) {
7813				LIST_REMOVE(reg, chain);
7814				free(reg, M_IPSEC_SAR);
7815				break;
7816			}
7817		}
7818	}
7819	REGTREE_UNLOCK();
7820
7821	ACQ_LOCK();
7822	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
7823		nextacq = LIST_NEXT(acq, chain);
7824		if (__LIST_CHAINED(acq)) {
7825			LIST_REMOVE(acq, chain);
7826			free(acq, M_IPSEC_SAQ);
7827		}
7828	}
7829	ACQ_UNLOCK();
7830
7831	SPACQ_LOCK();
7832	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
7833		nextacq = LIST_NEXT(acq, chain);
7834		if (__LIST_CHAINED(acq)) {
7835			LIST_REMOVE(acq, chain);
7836			free(acq, M_IPSEC_SAQ);
7837		}
7838	}
7839	SPACQ_UNLOCK();
7840}
7841#endif
7842
7843/*
7844 * XXX: maybe This function is called after INBOUND IPsec processing.
7845 *
7846 * Special check for tunnel-mode packets.
7847 * We must make some checks for consistency between inner and outer IP header.
7848 *
7849 * xxx more checks to be provided
7850 */
7851int
7852key_checktunnelsanity(sav, family, src, dst)
7853	struct secasvar *sav;
7854	u_int family;
7855	caddr_t src;
7856	caddr_t dst;
7857{
7858	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7859
7860	/* XXX: check inner IP header */
7861
7862	return 1;
7863}
7864
7865/* record data transfer on SA, and update timestamps */
7866void
7867key_sa_recordxfer(sav, m)
7868	struct secasvar *sav;
7869	struct mbuf *m;
7870{
7871	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7872	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7873	if (!sav->lft_c)
7874		return;
7875
7876	/*
7877	 * XXX Currently, there is a difference of bytes size
7878	 * between inbound and outbound processing.
7879	 */
7880	sav->lft_c->bytes += m->m_pkthdr.len;
7881	/* to check bytes lifetime is done in key_timehandler(). */
7882
7883	/*
7884	 * We use the number of packets as the unit of
7885	 * allocations.  We increment the variable
7886	 * whenever {esp,ah}_{in,out}put is called.
7887	 */
7888	sav->lft_c->allocations++;
7889	/* XXX check for expires? */
7890
7891	/*
7892	 * NOTE: We record CURRENT usetime by using wall clock,
7893	 * in seconds.  HARD and SOFT lifetime are measured by the time
7894	 * difference (again in seconds) from usetime.
7895	 *
7896	 *	usetime
7897	 *	v     expire   expire
7898	 * -----+-----+--------+---> t
7899	 *	<--------------> HARD
7900	 *	<-----> SOFT
7901	 */
7902	sav->lft_c->usetime = time_second;
7903	/* XXX check for expires? */
7904
7905	return;
7906}
7907
7908/* dumb version */
7909void
7910key_sa_routechange(dst)
7911	struct sockaddr *dst;
7912{
7913	struct secashead *sah;
7914	struct route *ro;
7915
7916	SAHTREE_LOCK();
7917	LIST_FOREACH(sah, &V_sahtree, chain) {
7918		ro = &sah->sa_route;
7919		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7920		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7921			RTFREE(ro->ro_rt);
7922			ro->ro_rt = (struct rtentry *)NULL;
7923		}
7924	}
7925	SAHTREE_UNLOCK();
7926}
7927
7928static void
7929key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7930{
7931	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7932	SAHTREE_LOCK_ASSERT();
7933
7934	if (sav->state != state) {
7935		if (__LIST_CHAINED(sav))
7936			LIST_REMOVE(sav, chain);
7937		sav->state = state;
7938		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7939	}
7940}
7941
7942void
7943key_sa_stir_iv(sav)
7944	struct secasvar *sav;
7945{
7946
7947	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7948	key_randomfill(sav->iv, sav->ivlen);
7949}
7950
7951/* XXX too much? */
7952static struct mbuf *
7953key_alloc_mbuf(l)
7954	int l;
7955{
7956	struct mbuf *m = NULL, *n;
7957	int len, t;
7958
7959	len = l;
7960	while (len > 0) {
7961		MGET(n, M_DONTWAIT, MT_DATA);
7962		if (n && len > MLEN)
7963			MCLGET(n, M_DONTWAIT);
7964		if (!n) {
7965			m_freem(m);
7966			return NULL;
7967		}
7968
7969		n->m_next = NULL;
7970		n->m_len = 0;
7971		n->m_len = M_TRAILINGSPACE(n);
7972		/* use the bottom of mbuf, hoping we can prepend afterwards */
7973		if (n->m_len > len) {
7974			t = (n->m_len - len) & ~(sizeof(long) - 1);
7975			n->m_data += t;
7976			n->m_len = len;
7977		}
7978
7979		len -= n->m_len;
7980
7981		if (m)
7982			m_cat(m, n);
7983		else
7984			m = n;
7985	}
7986
7987	return m;
7988}
7989
7990/*
7991 * Take one of the kernel's security keys and convert it into a PF_KEY
7992 * structure within an mbuf, suitable for sending up to a waiting
7993 * application in user land.
7994 *
7995 * IN:
7996 *    src: A pointer to a kernel security key.
7997 *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
7998 * OUT:
7999 *    a valid mbuf or NULL indicating an error
8000 *
8001 */
8002
8003static struct mbuf *
8004key_setkey(struct seckey *src, u_int16_t exttype)
8005{
8006	struct mbuf *m;
8007	struct sadb_key *p;
8008	int len;
8009
8010	if (src == NULL)
8011		return NULL;
8012
8013	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8014	m = key_alloc_mbuf(len);
8015	if (m == NULL)
8016		return NULL;
8017	p = mtod(m, struct sadb_key *);
8018	bzero(p, len);
8019	p->sadb_key_len = PFKEY_UNIT64(len);
8020	p->sadb_key_exttype = exttype;
8021	p->sadb_key_bits = src->bits;
8022	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8023
8024	return m;
8025}
8026
8027/*
8028 * Take one of the kernel's lifetime data structures and convert it
8029 * into a PF_KEY structure within an mbuf, suitable for sending up to
8030 * a waiting application in user land.
8031 *
8032 * IN:
8033 *    src: A pointer to a kernel lifetime structure.
8034 *    exttype: Which type of lifetime this is. Refer to the PF_KEY
8035 *             data structures for more information.
8036 * OUT:
8037 *    a valid mbuf or NULL indicating an error
8038 *
8039 */
8040
8041static struct mbuf *
8042key_setlifetime(struct seclifetime *src, u_int16_t exttype)
8043{
8044	struct mbuf *m = NULL;
8045	struct sadb_lifetime *p;
8046	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8047
8048	if (src == NULL)
8049		return NULL;
8050
8051	m = key_alloc_mbuf(len);
8052	if (m == NULL)
8053		return m;
8054	p = mtod(m, struct sadb_lifetime *);
8055
8056	bzero(p, len);
8057	p->sadb_lifetime_len = PFKEY_UNIT64(len);
8058	p->sadb_lifetime_exttype = exttype;
8059	p->sadb_lifetime_allocations = src->allocations;
8060	p->sadb_lifetime_bytes = src->bytes;
8061	p->sadb_lifetime_addtime = src->addtime;
8062	p->sadb_lifetime_usetime = src->usetime;
8063
8064	return m;
8065
8066}
8067