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