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