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