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