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