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