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