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