key.c revision 109623
1/*	$FreeBSD: head/sys/netipsec/key.c 109623 2003-01-21 08:56:16Z alfred $	*/
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_NOWAIT, 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_NOWAIT);
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_NOWAIT, MT_DATA);
2083	if (n && len > MHLEN) {
2084		MCLGET(n, M_NOWAIT);
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_NOWAIT);
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_NOWAIT);
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_NOWAIT, MT_DATA);
3392	if (m && len > MHLEN) {
3393		MCLGET(m, M_NOWAIT);
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	srandom(time_second);
4271}
4272
4273u_long
4274key_random()
4275{
4276	u_long value;
4277
4278	key_randomfill(&value, sizeof(value));
4279	return value;
4280}
4281
4282void
4283key_randomfill(p, l)
4284	void *p;
4285	size_t l;
4286{
4287	size_t n;
4288	u_long v;
4289	static int warn = 1;
4290
4291	n = 0;
4292	n = (size_t)read_random(p, (u_int)l);
4293	/* last resort */
4294	while (n < l) {
4295		v = random();
4296		bcopy(&v, (u_int8_t *)p + n,
4297		    l - n < sizeof(v) ? l - n : sizeof(v));
4298		n += sizeof(v);
4299
4300		if (warn) {
4301			printf("WARNING: pseudo-random number generator "
4302			    "used for IPsec processing\n");
4303			warn = 0;
4304		}
4305	}
4306}
4307
4308/*
4309 * map SADB_SATYPE_* to IPPROTO_*.
4310 * if satype == SADB_SATYPE then satype is mapped to ~0.
4311 * OUT:
4312 *	0: invalid satype.
4313 */
4314static u_int16_t
4315key_satype2proto(satype)
4316	u_int8_t satype;
4317{
4318	switch (satype) {
4319	case SADB_SATYPE_UNSPEC:
4320		return IPSEC_PROTO_ANY;
4321	case SADB_SATYPE_AH:
4322		return IPPROTO_AH;
4323	case SADB_SATYPE_ESP:
4324		return IPPROTO_ESP;
4325	case SADB_X_SATYPE_IPCOMP:
4326		return IPPROTO_IPCOMP;
4327	default:
4328		return 0;
4329	}
4330	/* NOTREACHED */
4331}
4332
4333/*
4334 * map IPPROTO_* to SADB_SATYPE_*
4335 * OUT:
4336 *	0: invalid protocol type.
4337 */
4338static u_int8_t
4339key_proto2satype(proto)
4340	u_int16_t proto;
4341{
4342	switch (proto) {
4343	case IPPROTO_AH:
4344		return SADB_SATYPE_AH;
4345	case IPPROTO_ESP:
4346		return SADB_SATYPE_ESP;
4347	case IPPROTO_IPCOMP:
4348		return SADB_X_SATYPE_IPCOMP;
4349	default:
4350		return 0;
4351	}
4352	/* NOTREACHED */
4353}
4354
4355/* %%% PF_KEY */
4356/*
4357 * SADB_GETSPI processing is to receive
4358 *	<base, (SA2), src address, dst address, (SPI range)>
4359 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4360 * tree with the status of LARVAL, and send
4361 *	<base, SA(*), address(SD)>
4362 * to the IKMPd.
4363 *
4364 * IN:	mhp: pointer to the pointer to each header.
4365 * OUT:	NULL if fail.
4366 *	other if success, return pointer to the message to send.
4367 */
4368static int
4369key_getspi(so, m, mhp)
4370	struct socket *so;
4371	struct mbuf *m;
4372	const struct sadb_msghdr *mhp;
4373{
4374	struct sadb_address *src0, *dst0;
4375	struct secasindex saidx;
4376	struct secashead *newsah;
4377	struct secasvar *newsav;
4378	u_int8_t proto;
4379	u_int32_t spi;
4380	u_int8_t mode;
4381	u_int32_t reqid;
4382	int error;
4383
4384	/* sanity check */
4385	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4386		panic("key_getspi: NULL pointer is passed.\n");
4387
4388	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4389	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4390		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4391		return key_senderror(so, m, EINVAL);
4392	}
4393	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4394	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4395		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4396		return key_senderror(so, m, EINVAL);
4397	}
4398	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4399		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4400		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4401	} else {
4402		mode = IPSEC_MODE_ANY;
4403		reqid = 0;
4404	}
4405
4406	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4407	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4408
4409	/* map satype to proto */
4410	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4411		ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
4412		return key_senderror(so, m, EINVAL);
4413	}
4414
4415	/* make sure if port number is zero. */
4416	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4417	case AF_INET:
4418		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4419		    sizeof(struct sockaddr_in))
4420			return key_senderror(so, m, EINVAL);
4421		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4422		break;
4423	case AF_INET6:
4424		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4425		    sizeof(struct sockaddr_in6))
4426			return key_senderror(so, m, EINVAL);
4427		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4428		break;
4429	default:
4430		; /*???*/
4431	}
4432	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4433	case AF_INET:
4434		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4435		    sizeof(struct sockaddr_in))
4436			return key_senderror(so, m, EINVAL);
4437		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4438		break;
4439	case AF_INET6:
4440		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4441		    sizeof(struct sockaddr_in6))
4442			return key_senderror(so, m, EINVAL);
4443		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4444		break;
4445	default:
4446		; /*???*/
4447	}
4448
4449	/* XXX boundary check against sa_len */
4450	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4451
4452	/* SPI allocation */
4453	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4454	                       &saidx);
4455	if (spi == 0)
4456		return key_senderror(so, m, EINVAL);
4457
4458	/* get a SA index */
4459	if ((newsah = key_getsah(&saidx)) == NULL) {
4460		/* create a new SA index */
4461		if ((newsah = key_newsah(&saidx)) == NULL) {
4462			ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
4463			return key_senderror(so, m, ENOBUFS);
4464		}
4465	}
4466
4467	/* get a new SA */
4468	/* XXX rewrite */
4469	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4470	if (newsav == NULL) {
4471		/* XXX don't free new SA index allocated in above. */
4472		return key_senderror(so, m, error);
4473	}
4474
4475	/* set spi */
4476	newsav->spi = htonl(spi);
4477
4478#ifndef IPSEC_NONBLOCK_ACQUIRE
4479	/* delete the entry in acqtree */
4480	if (mhp->msg->sadb_msg_seq != 0) {
4481		struct secacq *acq;
4482		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4483			/* reset counter in order to deletion by timehandler. */
4484			acq->created = time_second;
4485			acq->count = 0;
4486		}
4487    	}
4488#endif
4489
4490    {
4491	struct mbuf *n, *nn;
4492	struct sadb_sa *m_sa;
4493	struct sadb_msg *newmsg;
4494	int off, len;
4495
4496	/* create new sadb_msg to reply. */
4497	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4498	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4499	if (len > MCLBYTES)
4500		return key_senderror(so, m, ENOBUFS);
4501
4502	MGETHDR(n, M_NOWAIT, MT_DATA);
4503	if (len > MHLEN) {
4504		MCLGET(n, M_NOWAIT);
4505		if ((n->m_flags & M_EXT) == 0) {
4506			m_freem(n);
4507			n = NULL;
4508		}
4509	}
4510	if (!n)
4511		return key_senderror(so, m, ENOBUFS);
4512
4513	n->m_len = len;
4514	n->m_next = NULL;
4515	off = 0;
4516
4517	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4518	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4519
4520	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4521	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4522	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4523	m_sa->sadb_sa_spi = htonl(spi);
4524	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4525
4526#ifdef DIAGNOSTIC
4527	if (off != len)
4528		panic("length inconsistency in key_getspi");
4529#endif
4530
4531	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4532	    SADB_EXT_ADDRESS_DST);
4533	if (!n->m_next) {
4534		m_freem(n);
4535		return key_senderror(so, m, ENOBUFS);
4536	}
4537
4538	if (n->m_len < sizeof(struct sadb_msg)) {
4539		n = m_pullup(n, sizeof(struct sadb_msg));
4540		if (n == NULL)
4541			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4542	}
4543
4544	n->m_pkthdr.len = 0;
4545	for (nn = n; nn; nn = nn->m_next)
4546		n->m_pkthdr.len += nn->m_len;
4547
4548	newmsg = mtod(n, struct sadb_msg *);
4549	newmsg->sadb_msg_seq = newsav->seq;
4550	newmsg->sadb_msg_errno = 0;
4551	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4552
4553	m_freem(m);
4554	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4555    }
4556}
4557
4558/*
4559 * allocating new SPI
4560 * called by key_getspi().
4561 * OUT:
4562 *	0:	failure.
4563 *	others: success.
4564 */
4565static u_int32_t
4566key_do_getnewspi(spirange, saidx)
4567	struct sadb_spirange *spirange;
4568	struct secasindex *saidx;
4569{
4570	u_int32_t newspi;
4571	u_int32_t min, max;
4572	int count = key_spi_trycnt;
4573
4574	/* set spi range to allocate */
4575	if (spirange != NULL) {
4576		min = spirange->sadb_spirange_min;
4577		max = spirange->sadb_spirange_max;
4578	} else {
4579		min = key_spi_minval;
4580		max = key_spi_maxval;
4581	}
4582	/* IPCOMP needs 2-byte SPI */
4583	if (saidx->proto == IPPROTO_IPCOMP) {
4584		u_int32_t t;
4585		if (min >= 0x10000)
4586			min = 0xffff;
4587		if (max >= 0x10000)
4588			max = 0xffff;
4589		if (min > max) {
4590			t = min; min = max; max = t;
4591		}
4592	}
4593
4594	if (min == max) {
4595		if (key_checkspidup(saidx, min) != NULL) {
4596			ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", min));
4597			return 0;
4598		}
4599
4600		count--; /* taking one cost. */
4601		newspi = min;
4602
4603	} else {
4604
4605		/* init SPI */
4606		newspi = 0;
4607
4608		/* when requesting to allocate spi ranged */
4609		while (count--) {
4610			/* generate pseudo-random SPI value ranged. */
4611			newspi = min + (key_random() % (max - min + 1));
4612
4613			if (key_checkspidup(saidx, newspi) == NULL)
4614				break;
4615		}
4616
4617		if (count == 0 || newspi == 0) {
4618			ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
4619			return 0;
4620		}
4621	}
4622
4623	/* statistics */
4624	keystat.getspi_count =
4625		(keystat.getspi_count + key_spi_trycnt - count) / 2;
4626
4627	return newspi;
4628}
4629
4630/*
4631 * SADB_UPDATE processing
4632 * receive
4633 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4634 *       key(AE), (identity(SD),) (sensitivity)>
4635 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4636 * and send
4637 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4638 *       (identity(SD),) (sensitivity)>
4639 * to the ikmpd.
4640 *
4641 * m will always be freed.
4642 */
4643static int
4644key_update(so, m, mhp)
4645	struct socket *so;
4646	struct mbuf *m;
4647	const struct sadb_msghdr *mhp;
4648{
4649	struct sadb_sa *sa0;
4650	struct sadb_address *src0, *dst0;
4651	struct secasindex saidx;
4652	struct secashead *sah;
4653	struct secasvar *sav;
4654	u_int16_t proto;
4655	u_int8_t mode;
4656	u_int32_t reqid;
4657	int error;
4658
4659	/* sanity check */
4660	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4661		panic("key_update: NULL pointer is passed.\n");
4662
4663	/* map satype to proto */
4664	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4665		ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
4666		return key_senderror(so, m, EINVAL);
4667	}
4668
4669	if (mhp->ext[SADB_EXT_SA] == NULL ||
4670	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4671	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4672	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4673	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4674	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4675	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4676	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4677	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4678	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4679	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4680		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4681		return key_senderror(so, m, EINVAL);
4682	}
4683	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4684	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4685	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4686		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4687		return key_senderror(so, m, EINVAL);
4688	}
4689	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4690		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4691		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4692	} else {
4693		mode = IPSEC_MODE_ANY;
4694		reqid = 0;
4695	}
4696	/* XXX boundary checking for other extensions */
4697
4698	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4699	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4700	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4701
4702	/* XXX boundary check against sa_len */
4703	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4704
4705	/* get a SA header */
4706	if ((sah = key_getsah(&saidx)) == NULL) {
4707		ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
4708		return key_senderror(so, m, ENOENT);
4709	}
4710
4711	/* set spidx if there */
4712	/* XXX rewrite */
4713	error = key_setident(sah, m, mhp);
4714	if (error)
4715		return key_senderror(so, m, error);
4716
4717	/* find a SA with sequence number. */
4718#ifdef IPSEC_DOSEQCHECK
4719	if (mhp->msg->sadb_msg_seq != 0
4720	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4721		ipseclog((LOG_DEBUG,
4722		    "key_update: no larval SA with sequence %u exists.\n",
4723		    mhp->msg->sadb_msg_seq));
4724		return key_senderror(so, m, ENOENT);
4725	}
4726#else
4727	if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
4728		ipseclog((LOG_DEBUG,
4729		    "key_update: no such a SA found (spi:%u)\n",
4730		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4731		return key_senderror(so, m, EINVAL);
4732	}
4733#endif
4734
4735	/* validity check */
4736	if (sav->sah->saidx.proto != proto) {
4737		ipseclog((LOG_DEBUG,
4738		    "key_update: protocol mismatched (DB=%u param=%u)\n",
4739		    sav->sah->saidx.proto, proto));
4740		return key_senderror(so, m, EINVAL);
4741	}
4742#ifdef IPSEC_DOSEQCHECK
4743	if (sav->spi != sa0->sadb_sa_spi) {
4744		ipseclog((LOG_DEBUG,
4745		    "key_update: SPI mismatched (DB:%u param:%u)\n",
4746		    (u_int32_t)ntohl(sav->spi),
4747		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4748		return key_senderror(so, m, EINVAL);
4749	}
4750#endif
4751	if (sav->pid != mhp->msg->sadb_msg_pid) {
4752		ipseclog((LOG_DEBUG,
4753		    "key_update: pid mismatched (DB:%u param:%u)\n",
4754		    sav->pid, mhp->msg->sadb_msg_pid));
4755		return key_senderror(so, m, EINVAL);
4756	}
4757
4758	/* copy sav values */
4759	error = key_setsaval(sav, m, mhp);
4760	if (error) {
4761		KEY_FREESAV(&sav);
4762		return key_senderror(so, m, error);
4763	}
4764
4765	/* check SA values to be mature. */
4766	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4767		KEY_FREESAV(&sav);
4768		return key_senderror(so, m, 0);
4769	}
4770
4771    {
4772	struct mbuf *n;
4773
4774	/* set msg buf from mhp */
4775	n = key_getmsgbuf_x1(m, mhp);
4776	if (n == NULL) {
4777		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
4778		return key_senderror(so, m, ENOBUFS);
4779	}
4780
4781	m_freem(m);
4782	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4783    }
4784}
4785
4786/*
4787 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4788 * only called by key_update().
4789 * OUT:
4790 *	NULL	: not found
4791 *	others	: found, pointer to a SA.
4792 */
4793#ifdef IPSEC_DOSEQCHECK
4794static struct secasvar *
4795key_getsavbyseq(sah, seq)
4796	struct secashead *sah;
4797	u_int32_t seq;
4798{
4799	struct secasvar *sav;
4800	u_int state;
4801
4802	state = SADB_SASTATE_LARVAL;
4803
4804	/* search SAD with sequence number ? */
4805	LIST_FOREACH(sav, &sah->savtree[state], chain) {
4806
4807		KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
4808
4809		if (sav->seq == seq) {
4810			SA_ADDREF(sav);
4811			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4812				printf("DP key_getsavbyseq cause "
4813					"refcnt++:%d SA:%p\n",
4814					sav->refcnt, sav));
4815			return sav;
4816		}
4817	}
4818
4819	return NULL;
4820}
4821#endif
4822
4823/*
4824 * SADB_ADD processing
4825 * add an entry to SA database, when received
4826 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4827 *       key(AE), (identity(SD),) (sensitivity)>
4828 * from the ikmpd,
4829 * and send
4830 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4831 *       (identity(SD),) (sensitivity)>
4832 * to the ikmpd.
4833 *
4834 * IGNORE identity and sensitivity messages.
4835 *
4836 * m will always be freed.
4837 */
4838static int
4839key_add(so, m, mhp)
4840	struct socket *so;
4841	struct mbuf *m;
4842	const struct sadb_msghdr *mhp;
4843{
4844	struct sadb_sa *sa0;
4845	struct sadb_address *src0, *dst0;
4846	struct secasindex saidx;
4847	struct secashead *newsah;
4848	struct secasvar *newsav;
4849	u_int16_t proto;
4850	u_int8_t mode;
4851	u_int32_t reqid;
4852	int error;
4853
4854	/* sanity check */
4855	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4856		panic("key_add: NULL pointer is passed.\n");
4857
4858	/* map satype to proto */
4859	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4860		ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
4861		return key_senderror(so, m, EINVAL);
4862	}
4863
4864	if (mhp->ext[SADB_EXT_SA] == NULL ||
4865	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4866	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4867	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4868	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4869	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4870	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4871	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4872	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4873	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4874	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4875		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
4876		return key_senderror(so, m, EINVAL);
4877	}
4878	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4879	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4880	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4881		/* XXX need more */
4882		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
4883		return key_senderror(so, m, EINVAL);
4884	}
4885	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4886		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4887		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4888	} else {
4889		mode = IPSEC_MODE_ANY;
4890		reqid = 0;
4891	}
4892
4893	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4894	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4895	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4896
4897	/* XXX boundary check against sa_len */
4898	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4899
4900	/* get a SA header */
4901	if ((newsah = key_getsah(&saidx)) == NULL) {
4902		/* create a new SA header */
4903		if ((newsah = key_newsah(&saidx)) == NULL) {
4904			ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
4905			return key_senderror(so, m, ENOBUFS);
4906		}
4907	}
4908
4909	/* set spidx if there */
4910	/* XXX rewrite */
4911	error = key_setident(newsah, m, mhp);
4912	if (error) {
4913		return key_senderror(so, m, error);
4914	}
4915
4916	/* create new SA entry. */
4917	/* We can create new SA only if SPI is differenct. */
4918	if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
4919		ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
4920		return key_senderror(so, m, EEXIST);
4921	}
4922	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4923	if (newsav == NULL) {
4924		return key_senderror(so, m, error);
4925	}
4926
4927	/* check SA values to be mature. */
4928	if ((error = key_mature(newsav)) != 0) {
4929		KEY_FREESAV(&newsav);
4930		return key_senderror(so, m, error);
4931	}
4932
4933	/*
4934	 * don't call key_freesav() here, as we would like to keep the SA
4935	 * in the database on success.
4936	 */
4937
4938    {
4939	struct mbuf *n;
4940
4941	/* set msg buf from mhp */
4942	n = key_getmsgbuf_x1(m, mhp);
4943	if (n == NULL) {
4944		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
4945		return key_senderror(so, m, ENOBUFS);
4946	}
4947
4948	m_freem(m);
4949	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4950    }
4951}
4952
4953/* m is retained */
4954static int
4955key_setident(sah, m, mhp)
4956	struct secashead *sah;
4957	struct mbuf *m;
4958	const struct sadb_msghdr *mhp;
4959{
4960	const struct sadb_ident *idsrc, *iddst;
4961	int idsrclen, iddstlen;
4962
4963	/* sanity check */
4964	if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4965		panic("key_setident: NULL pointer is passed.\n");
4966
4967	/* don't make buffer if not there */
4968	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
4969	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4970		sah->idents = NULL;
4971		sah->identd = NULL;
4972		return 0;
4973	}
4974
4975	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
4976	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4977		ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
4978		return EINVAL;
4979	}
4980
4981	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
4982	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
4983	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
4984	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
4985
4986	/* validity check */
4987	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
4988		ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
4989		return EINVAL;
4990	}
4991
4992	switch (idsrc->sadb_ident_type) {
4993	case SADB_IDENTTYPE_PREFIX:
4994	case SADB_IDENTTYPE_FQDN:
4995	case SADB_IDENTTYPE_USERFQDN:
4996	default:
4997		/* XXX do nothing */
4998		sah->idents = NULL;
4999		sah->identd = NULL;
5000	 	return 0;
5001	}
5002
5003	/* make structure */
5004	KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
5005	if (sah->idents == NULL) {
5006		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5007		return ENOBUFS;
5008	}
5009	KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
5010	if (sah->identd == NULL) {
5011		KFREE(sah->idents);
5012		sah->idents = NULL;
5013		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5014		return ENOBUFS;
5015	}
5016	bcopy(idsrc, sah->idents, idsrclen);
5017	bcopy(iddst, sah->identd, iddstlen);
5018
5019	return 0;
5020}
5021
5022/*
5023 * m will not be freed on return.
5024 * it is caller's responsibility to free the result.
5025 */
5026static struct mbuf *
5027key_getmsgbuf_x1(m, mhp)
5028	struct mbuf *m;
5029	const struct sadb_msghdr *mhp;
5030{
5031	struct mbuf *n;
5032
5033	/* sanity check */
5034	if (m == NULL || mhp == NULL || mhp->msg == NULL)
5035		panic("key_getmsgbuf_x1: NULL pointer is passed.\n");
5036
5037	/* create new sadb_msg to reply. */
5038	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5039	    SADB_EXT_SA, SADB_X_EXT_SA2,
5040	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5041	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5042	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5043	if (!n)
5044		return NULL;
5045
5046	if (n->m_len < sizeof(struct sadb_msg)) {
5047		n = m_pullup(n, sizeof(struct sadb_msg));
5048		if (n == NULL)
5049			return NULL;
5050	}
5051	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5052	mtod(n, struct sadb_msg *)->sadb_msg_len =
5053	    PFKEY_UNIT64(n->m_pkthdr.len);
5054
5055	return n;
5056}
5057
5058static int key_delete_all __P((struct socket *, struct mbuf *,
5059	const struct sadb_msghdr *, u_int16_t));
5060
5061/*
5062 * SADB_DELETE processing
5063 * receive
5064 *   <base, SA(*), address(SD)>
5065 * from the ikmpd, and set SADB_SASTATE_DEAD,
5066 * and send,
5067 *   <base, SA(*), address(SD)>
5068 * to the ikmpd.
5069 *
5070 * m will always be freed.
5071 */
5072static int
5073key_delete(so, m, mhp)
5074	struct socket *so;
5075	struct mbuf *m;
5076	const struct sadb_msghdr *mhp;
5077{
5078	struct sadb_sa *sa0;
5079	struct sadb_address *src0, *dst0;
5080	struct secasindex saidx;
5081	struct secashead *sah;
5082	struct secasvar *sav = NULL;
5083	u_int16_t proto;
5084
5085	/* sanity check */
5086	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5087		panic("key_delete: NULL pointer is passed.\n");
5088
5089	/* map satype to proto */
5090	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5091		ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
5092		return key_senderror(so, m, EINVAL);
5093	}
5094
5095	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5096	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5097		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5098		return key_senderror(so, m, EINVAL);
5099	}
5100
5101	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5102	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5103		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5104		return key_senderror(so, m, EINVAL);
5105	}
5106
5107	if (mhp->ext[SADB_EXT_SA] == NULL) {
5108		/*
5109		 * Caller wants us to delete all non-LARVAL SAs
5110		 * that match the src/dst.  This is used during
5111		 * IKE INITIAL-CONTACT.
5112		 */
5113		ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
5114		return key_delete_all(so, m, mhp, proto);
5115	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5116		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5117		return key_senderror(so, m, EINVAL);
5118	}
5119
5120	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5121	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5122	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5123
5124	/* XXX boundary check against sa_len */
5125	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5126
5127	/* get a SA header */
5128	LIST_FOREACH(sah, &sahtree, chain) {
5129		if (sah->state == SADB_SASTATE_DEAD)
5130			continue;
5131		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5132			continue;
5133
5134		/* get a SA with SPI. */
5135		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5136		if (sav)
5137			break;
5138	}
5139	if (sah == NULL) {
5140		ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
5141		return key_senderror(so, m, ENOENT);
5142	}
5143
5144	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5145	KEY_FREESAV(&sav);
5146
5147    {
5148	struct mbuf *n;
5149	struct sadb_msg *newmsg;
5150
5151	/* create new sadb_msg to reply. */
5152	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5153	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5154	if (!n)
5155		return key_senderror(so, m, ENOBUFS);
5156
5157	if (n->m_len < sizeof(struct sadb_msg)) {
5158		n = m_pullup(n, sizeof(struct sadb_msg));
5159		if (n == NULL)
5160			return key_senderror(so, m, ENOBUFS);
5161	}
5162	newmsg = mtod(n, struct sadb_msg *);
5163	newmsg->sadb_msg_errno = 0;
5164	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5165
5166	m_freem(m);
5167	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5168    }
5169}
5170
5171/*
5172 * delete all SAs for src/dst.  Called from key_delete().
5173 */
5174static int
5175key_delete_all(so, m, mhp, proto)
5176	struct socket *so;
5177	struct mbuf *m;
5178	const struct sadb_msghdr *mhp;
5179	u_int16_t proto;
5180{
5181	struct sadb_address *src0, *dst0;
5182	struct secasindex saidx;
5183	struct secashead *sah;
5184	struct secasvar *sav, *nextsav;
5185	u_int stateidx, state;
5186
5187	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5188	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5189
5190	/* XXX boundary check against sa_len */
5191	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5192
5193	LIST_FOREACH(sah, &sahtree, chain) {
5194		if (sah->state == SADB_SASTATE_DEAD)
5195			continue;
5196		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5197			continue;
5198
5199		/* Delete all non-LARVAL SAs. */
5200		for (stateidx = 0;
5201		     stateidx < _ARRAYLEN(saorder_state_alive);
5202		     stateidx++) {
5203			state = saorder_state_alive[stateidx];
5204			if (state == SADB_SASTATE_LARVAL)
5205				continue;
5206			for (sav = LIST_FIRST(&sah->savtree[state]);
5207			     sav != NULL; sav = nextsav) {
5208				nextsav = LIST_NEXT(sav, chain);
5209				/* sanity check */
5210				if (sav->state != state) {
5211					ipseclog((LOG_DEBUG, "key_delete_all: "
5212					       "invalid sav->state "
5213					       "(queue: %d SA: %d)\n",
5214					       state, sav->state));
5215					continue;
5216				}
5217
5218				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5219				KEY_FREESAV(&sav);
5220			}
5221		}
5222	}
5223    {
5224	struct mbuf *n;
5225	struct sadb_msg *newmsg;
5226
5227	/* create new sadb_msg to reply. */
5228	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5229	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5230	if (!n)
5231		return key_senderror(so, m, ENOBUFS);
5232
5233	if (n->m_len < sizeof(struct sadb_msg)) {
5234		n = m_pullup(n, sizeof(struct sadb_msg));
5235		if (n == NULL)
5236			return key_senderror(so, m, ENOBUFS);
5237	}
5238	newmsg = mtod(n, struct sadb_msg *);
5239	newmsg->sadb_msg_errno = 0;
5240	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5241
5242	m_freem(m);
5243	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5244    }
5245}
5246
5247/*
5248 * SADB_GET processing
5249 * receive
5250 *   <base, SA(*), address(SD)>
5251 * from the ikmpd, and get a SP and a SA to respond,
5252 * and send,
5253 *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5254 *       (identity(SD),) (sensitivity)>
5255 * to the ikmpd.
5256 *
5257 * m will always be freed.
5258 */
5259static int
5260key_get(so, m, mhp)
5261	struct socket *so;
5262	struct mbuf *m;
5263	const struct sadb_msghdr *mhp;
5264{
5265	struct sadb_sa *sa0;
5266	struct sadb_address *src0, *dst0;
5267	struct secasindex saidx;
5268	struct secashead *sah;
5269	struct secasvar *sav = NULL;
5270	u_int16_t proto;
5271
5272	/* sanity check */
5273	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5274		panic("key_get: NULL pointer is passed.\n");
5275
5276	/* map satype to proto */
5277	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5278		ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
5279		return key_senderror(so, m, EINVAL);
5280	}
5281
5282	if (mhp->ext[SADB_EXT_SA] == NULL ||
5283	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5284	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5285		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5286		return key_senderror(so, m, EINVAL);
5287	}
5288	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5289	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5290	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5291		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5292		return key_senderror(so, m, EINVAL);
5293	}
5294
5295	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5296	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5297	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5298
5299	/* XXX boundary check against sa_len */
5300	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5301
5302	/* get a SA header */
5303	LIST_FOREACH(sah, &sahtree, chain) {
5304		if (sah->state == SADB_SASTATE_DEAD)
5305			continue;
5306		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5307			continue;
5308
5309		/* get a SA with SPI. */
5310		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5311		if (sav)
5312			break;
5313	}
5314	if (sah == NULL) {
5315		ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
5316		return key_senderror(so, m, ENOENT);
5317	}
5318
5319    {
5320	struct mbuf *n;
5321	u_int8_t satype;
5322
5323	/* map proto to satype */
5324	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5325		ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
5326		return key_senderror(so, m, EINVAL);
5327	}
5328
5329	/* create new sadb_msg to reply. */
5330	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5331	    mhp->msg->sadb_msg_pid);
5332	if (!n)
5333		return key_senderror(so, m, ENOBUFS);
5334
5335	m_freem(m);
5336	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5337    }
5338}
5339
5340/* XXX make it sysctl-configurable? */
5341static void
5342key_getcomb_setlifetime(comb)
5343	struct sadb_comb *comb;
5344{
5345
5346	comb->sadb_comb_soft_allocations = 1;
5347	comb->sadb_comb_hard_allocations = 1;
5348	comb->sadb_comb_soft_bytes = 0;
5349	comb->sadb_comb_hard_bytes = 0;
5350	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
5351	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5352	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
5353	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5354}
5355
5356/*
5357 * XXX reorder combinations by preference
5358 * XXX no idea if the user wants ESP authentication or not
5359 */
5360static struct mbuf *
5361key_getcomb_esp()
5362{
5363	struct sadb_comb *comb;
5364	struct enc_xform *algo;
5365	struct mbuf *result = NULL, *m, *n;
5366	int encmin;
5367	int i, off, o;
5368	int totlen;
5369	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5370
5371	m = NULL;
5372	for (i = 1; i <= SADB_EALG_MAX; i++) {
5373		algo = esp_algorithm_lookup(i);
5374		if (algo == NULL)
5375			continue;
5376
5377		/* discard algorithms with key size smaller than system min */
5378		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
5379			continue;
5380		if (_BITS(algo->minkey) < ipsec_esp_keymin)
5381			encmin = ipsec_esp_keymin;
5382		else
5383			encmin = _BITS(algo->minkey);
5384
5385		if (ipsec_esp_auth)
5386			m = key_getcomb_ah();
5387		else {
5388			KASSERT(l <= MLEN,
5389				("key_getcomb_esp: l=%u > MLEN=%lu",
5390				l, (u_long) MLEN));
5391			MGET(m, M_NOWAIT, MT_DATA);
5392			if (m) {
5393				M_ALIGN(m, l);
5394				m->m_len = l;
5395				m->m_next = NULL;
5396				bzero(mtod(m, caddr_t), m->m_len);
5397			}
5398		}
5399		if (!m)
5400			goto fail;
5401
5402		totlen = 0;
5403		for (n = m; n; n = n->m_next)
5404			totlen += n->m_len;
5405		KASSERT((totlen % l) == 0,
5406			("key_getcomb_esp: totlen=%u, l=%u", totlen, l));
5407
5408		for (off = 0; off < totlen; off += l) {
5409			n = m_pulldown(m, off, l, &o);
5410			if (!n) {
5411				/* m is already freed */
5412				goto fail;
5413			}
5414			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5415			bzero(comb, sizeof(*comb));
5416			key_getcomb_setlifetime(comb);
5417			comb->sadb_comb_encrypt = i;
5418			comb->sadb_comb_encrypt_minbits = encmin;
5419			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5420		}
5421
5422		if (!result)
5423			result = m;
5424		else
5425			m_cat(result, m);
5426	}
5427
5428	return result;
5429
5430 fail:
5431	if (result)
5432		m_freem(result);
5433	return NULL;
5434}
5435
5436static void
5437key_getsizes_ah(
5438	const struct auth_hash *ah,
5439	int alg,
5440	u_int16_t* min,
5441	u_int16_t* max)
5442{
5443	*min = *max = ah->keysize;
5444	if (ah->keysize == 0) {
5445		/*
5446		 * Transform takes arbitrary key size but algorithm
5447		 * key size is restricted.  Enforce this here.
5448		 */
5449		switch (alg) {
5450		case SADB_X_AALG_MD5:	*min = *max = 16; break;
5451		case SADB_X_AALG_SHA:	*min = *max = 20; break;
5452		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
5453		default:
5454			DPRINTF(("key_getsizes_ah: unknown AH algorithm %u\n",
5455				alg));
5456			break;
5457		}
5458	}
5459}
5460
5461/*
5462 * XXX reorder combinations by preference
5463 */
5464static struct mbuf *
5465key_getcomb_ah()
5466{
5467	struct sadb_comb *comb;
5468	struct auth_hash *algo;
5469	struct mbuf *m;
5470	u_int16_t minkeysize, maxkeysize;
5471	int i;
5472	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5473
5474	m = NULL;
5475	for (i = 1; i <= SADB_AALG_MAX; i++) {
5476#if 1
5477		/* we prefer HMAC algorithms, not old algorithms */
5478		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5479			continue;
5480#endif
5481		algo = ah_algorithm_lookup(i);
5482		if (!algo)
5483			continue;
5484		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5485		/* discard algorithms with key size smaller than system min */
5486		if (_BITS(minkeysize) < ipsec_ah_keymin)
5487			continue;
5488
5489		if (!m) {
5490			KASSERT(l <= MLEN,
5491				("key_getcomb_ah: l=%u > MLEN=%lu",
5492				l, (u_long) MLEN));
5493			MGET(m, M_NOWAIT, MT_DATA);
5494			if (m) {
5495				M_ALIGN(m, l);
5496				m->m_len = l;
5497				m->m_next = NULL;
5498			}
5499		} else
5500			M_PREPEND(m, l, M_NOWAIT);
5501		if (!m)
5502			return NULL;
5503
5504		comb = mtod(m, struct sadb_comb *);
5505		bzero(comb, sizeof(*comb));
5506		key_getcomb_setlifetime(comb);
5507		comb->sadb_comb_auth = i;
5508		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5509		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5510	}
5511
5512	return m;
5513}
5514
5515/*
5516 * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5517 * XXX reorder combinations by preference
5518 */
5519static struct mbuf *
5520key_getcomb_ipcomp()
5521{
5522	struct sadb_comb *comb;
5523	struct comp_algo *algo;
5524	struct mbuf *m;
5525	int i;
5526	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5527
5528	m = NULL;
5529	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5530		algo = ipcomp_algorithm_lookup(i);
5531		if (!algo)
5532			continue;
5533
5534		if (!m) {
5535			KASSERT(l <= MLEN,
5536				("key_getcomb_ipcomp: l=%u > MLEN=%lu",
5537				l, (u_long) MLEN));
5538			MGET(m, M_NOWAIT, MT_DATA);
5539			if (m) {
5540				M_ALIGN(m, l);
5541				m->m_len = l;
5542				m->m_next = NULL;
5543			}
5544		} else
5545			M_PREPEND(m, l, M_NOWAIT);
5546		if (!m)
5547			return NULL;
5548
5549		comb = mtod(m, struct sadb_comb *);
5550		bzero(comb, sizeof(*comb));
5551		key_getcomb_setlifetime(comb);
5552		comb->sadb_comb_encrypt = i;
5553		/* what should we set into sadb_comb_*_{min,max}bits? */
5554	}
5555
5556	return m;
5557}
5558
5559/*
5560 * XXX no way to pass mode (transport/tunnel) to userland
5561 * XXX replay checking?
5562 * XXX sysctl interface to ipsec_{ah,esp}_keymin
5563 */
5564static struct mbuf *
5565key_getprop(saidx)
5566	const struct secasindex *saidx;
5567{
5568	struct sadb_prop *prop;
5569	struct mbuf *m, *n;
5570	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5571	int totlen;
5572
5573	switch (saidx->proto)  {
5574	case IPPROTO_ESP:
5575		m = key_getcomb_esp();
5576		break;
5577	case IPPROTO_AH:
5578		m = key_getcomb_ah();
5579		break;
5580	case IPPROTO_IPCOMP:
5581		m = key_getcomb_ipcomp();
5582		break;
5583	default:
5584		return NULL;
5585	}
5586
5587	if (!m)
5588		return NULL;
5589	M_PREPEND(m, l, M_NOWAIT);
5590	if (!m)
5591		return NULL;
5592
5593	totlen = 0;
5594	for (n = m; n; n = n->m_next)
5595		totlen += n->m_len;
5596
5597	prop = mtod(m, struct sadb_prop *);
5598	bzero(prop, sizeof(*prop));
5599	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5600	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5601	prop->sadb_prop_replay = 32;	/* XXX */
5602
5603	return m;
5604}
5605
5606/*
5607 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5608 * send
5609 *   <base, SA, address(SD), (address(P)), x_policy,
5610 *       (identity(SD),) (sensitivity,) proposal>
5611 * to KMD, and expect to receive
5612 *   <base> with SADB_ACQUIRE if error occured,
5613 * or
5614 *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5615 * from KMD by PF_KEY.
5616 *
5617 * XXX x_policy is outside of RFC2367 (KAME extension).
5618 * XXX sensitivity is not supported.
5619 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5620 * see comment for key_getcomb_ipcomp().
5621 *
5622 * OUT:
5623 *    0     : succeed
5624 *    others: error number
5625 */
5626static int
5627key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5628{
5629	struct mbuf *result = NULL, *m;
5630#ifndef IPSEC_NONBLOCK_ACQUIRE
5631	struct secacq *newacq;
5632#endif
5633	u_int8_t satype;
5634	int error = -1;
5635	u_int32_t seq;
5636
5637	/* sanity check */
5638	KASSERT(saidx != NULL, ("key_acquire: null saidx"));
5639	satype = key_proto2satype(saidx->proto);
5640	KASSERT(satype != 0,
5641		("key_acquire: null satype, protocol %u", saidx->proto));
5642
5643#ifndef IPSEC_NONBLOCK_ACQUIRE
5644	/*
5645	 * We never do anything about acquirng SA.  There is anather
5646	 * solution that kernel blocks to send SADB_ACQUIRE message until
5647	 * getting something message from IKEd.  In later case, to be
5648	 * managed with ACQUIRING list.
5649	 */
5650	/* Get an entry to check whether sending message or not. */
5651	if ((newacq = key_getacq(saidx)) != NULL) {
5652		if (key_blockacq_count < newacq->count) {
5653			/* reset counter and do send message. */
5654			newacq->count = 0;
5655		} else {
5656			/* increment counter and do nothing. */
5657			newacq->count++;
5658			return 0;
5659		}
5660	} else {
5661		/* make new entry for blocking to send SADB_ACQUIRE. */
5662		if ((newacq = key_newacq(saidx)) == NULL)
5663			return ENOBUFS;
5664
5665		/* add to acqtree */
5666		LIST_INSERT_HEAD(&acqtree, newacq, chain);
5667	}
5668#endif
5669
5670
5671#ifndef IPSEC_NONBLOCK_ACQUIRE
5672	seq = newacq->seq;
5673#else
5674	seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
5675#endif
5676	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5677	if (!m) {
5678		error = ENOBUFS;
5679		goto fail;
5680	}
5681	result = m;
5682
5683	/* set sadb_address for saidx's. */
5684	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5685	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5686	if (!m) {
5687		error = ENOBUFS;
5688		goto fail;
5689	}
5690	m_cat(result, m);
5691
5692	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5693	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5694	if (!m) {
5695		error = ENOBUFS;
5696		goto fail;
5697	}
5698	m_cat(result, m);
5699
5700	/* XXX proxy address (optional) */
5701
5702	/* set sadb_x_policy */
5703	if (sp) {
5704		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5705		if (!m) {
5706			error = ENOBUFS;
5707			goto fail;
5708		}
5709		m_cat(result, m);
5710	}
5711
5712	/* XXX identity (optional) */
5713#if 0
5714	if (idexttype && fqdn) {
5715		/* create identity extension (FQDN) */
5716		struct sadb_ident *id;
5717		int fqdnlen;
5718
5719		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
5720		id = (struct sadb_ident *)p;
5721		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5722		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5723		id->sadb_ident_exttype = idexttype;
5724		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5725		bcopy(fqdn, id + 1, fqdnlen);
5726		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5727	}
5728
5729	if (idexttype) {
5730		/* create identity extension (USERFQDN) */
5731		struct sadb_ident *id;
5732		int userfqdnlen;
5733
5734		if (userfqdn) {
5735			/* +1 for terminating-NUL */
5736			userfqdnlen = strlen(userfqdn) + 1;
5737		} else
5738			userfqdnlen = 0;
5739		id = (struct sadb_ident *)p;
5740		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5741		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5742		id->sadb_ident_exttype = idexttype;
5743		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5744		/* XXX is it correct? */
5745		if (curproc && curproc->p_cred)
5746			id->sadb_ident_id = curproc->p_cred->p_ruid;
5747		if (userfqdn && userfqdnlen)
5748			bcopy(userfqdn, id + 1, userfqdnlen);
5749		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5750	}
5751#endif
5752
5753	/* XXX sensitivity (optional) */
5754
5755	/* create proposal/combination extension */
5756	m = key_getprop(saidx);
5757#if 0
5758	/*
5759	 * spec conformant: always attach proposal/combination extension,
5760	 * the problem is that we have no way to attach it for ipcomp,
5761	 * due to the way sadb_comb is declared in RFC2367.
5762	 */
5763	if (!m) {
5764		error = ENOBUFS;
5765		goto fail;
5766	}
5767	m_cat(result, m);
5768#else
5769	/*
5770	 * outside of spec; make proposal/combination extension optional.
5771	 */
5772	if (m)
5773		m_cat(result, m);
5774#endif
5775
5776	if ((result->m_flags & M_PKTHDR) == 0) {
5777		error = EINVAL;
5778		goto fail;
5779	}
5780
5781	if (result->m_len < sizeof(struct sadb_msg)) {
5782		result = m_pullup(result, sizeof(struct sadb_msg));
5783		if (result == NULL) {
5784			error = ENOBUFS;
5785			goto fail;
5786		}
5787	}
5788
5789	result->m_pkthdr.len = 0;
5790	for (m = result; m; m = m->m_next)
5791		result->m_pkthdr.len += m->m_len;
5792
5793	mtod(result, struct sadb_msg *)->sadb_msg_len =
5794	    PFKEY_UNIT64(result->m_pkthdr.len);
5795
5796	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5797
5798 fail:
5799	if (result)
5800		m_freem(result);
5801	return error;
5802}
5803
5804#ifndef IPSEC_NONBLOCK_ACQUIRE
5805static struct secacq *
5806key_newacq(const struct secasindex *saidx)
5807{
5808	struct secacq *newacq;
5809
5810	/* get new entry */
5811	KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
5812	if (newacq == NULL) {
5813		ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
5814		return NULL;
5815	}
5816	bzero(newacq, sizeof(*newacq));
5817
5818	/* copy secindex */
5819	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5820	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
5821	newacq->created = time_second;
5822	newacq->count = 0;
5823
5824	return newacq;
5825}
5826
5827static struct secacq *
5828key_getacq(const struct secasindex *saidx)
5829{
5830	struct secacq *acq;
5831
5832	LIST_FOREACH(acq, &acqtree, chain) {
5833		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5834			return acq;
5835	}
5836
5837	return NULL;
5838}
5839
5840static struct secacq *
5841key_getacqbyseq(seq)
5842	u_int32_t seq;
5843{
5844	struct secacq *acq;
5845
5846	LIST_FOREACH(acq, &acqtree, chain) {
5847		if (acq->seq == seq)
5848			return acq;
5849	}
5850
5851	return NULL;
5852}
5853#endif
5854
5855static struct secspacq *
5856key_newspacq(spidx)
5857	struct secpolicyindex *spidx;
5858{
5859	struct secspacq *acq;
5860
5861	/* get new entry */
5862	KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
5863	if (acq == NULL) {
5864		ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
5865		return NULL;
5866	}
5867	bzero(acq, sizeof(*acq));
5868
5869	/* copy secindex */
5870	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5871	acq->created = time_second;
5872	acq->count = 0;
5873
5874	return acq;
5875}
5876
5877static struct secspacq *
5878key_getspacq(spidx)
5879	struct secpolicyindex *spidx;
5880{
5881	struct secspacq *acq;
5882
5883	LIST_FOREACH(acq, &spacqtree, chain) {
5884		if (key_cmpspidx_exactly(spidx, &acq->spidx))
5885			return acq;
5886	}
5887
5888	return NULL;
5889}
5890
5891/*
5892 * SADB_ACQUIRE processing,
5893 * in first situation, is receiving
5894 *   <base>
5895 * from the ikmpd, and clear sequence of its secasvar entry.
5896 *
5897 * In second situation, is receiving
5898 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5899 * from a user land process, and return
5900 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5901 * to the socket.
5902 *
5903 * m will always be freed.
5904 */
5905static int
5906key_acquire2(so, m, mhp)
5907	struct socket *so;
5908	struct mbuf *m;
5909	const struct sadb_msghdr *mhp;
5910{
5911	const struct sadb_address *src0, *dst0;
5912	struct secasindex saidx;
5913	struct secashead *sah;
5914	u_int16_t proto;
5915	int error;
5916
5917	/* sanity check */
5918	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5919		panic("key_acquire2: NULL pointer is passed.\n");
5920
5921	/*
5922	 * Error message from KMd.
5923	 * We assume that if error was occured in IKEd, the length of PFKEY
5924	 * message is equal to the size of sadb_msg structure.
5925	 * We do not raise error even if error occured in this function.
5926	 */
5927	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
5928#ifndef IPSEC_NONBLOCK_ACQUIRE
5929		struct secacq *acq;
5930
5931		/* check sequence number */
5932		if (mhp->msg->sadb_msg_seq == 0) {
5933			ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
5934			m_freem(m);
5935			return 0;
5936		}
5937
5938		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
5939			/*
5940			 * the specified larval SA is already gone, or we got
5941			 * a bogus sequence number.  we can silently ignore it.
5942			 */
5943			m_freem(m);
5944			return 0;
5945		}
5946
5947		/* reset acq counter in order to deletion by timehander. */
5948		acq->created = time_second;
5949		acq->count = 0;
5950#endif
5951		m_freem(m);
5952		return 0;
5953	}
5954
5955	/*
5956	 * This message is from user land.
5957	 */
5958
5959	/* map satype to proto */
5960	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5961		ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
5962		return key_senderror(so, m, EINVAL);
5963	}
5964
5965	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5966	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5967	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
5968		/* error */
5969		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
5970		return key_senderror(so, m, EINVAL);
5971	}
5972	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5973	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
5974	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
5975		/* error */
5976		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
5977		return key_senderror(so, m, EINVAL);
5978	}
5979
5980	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5981	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5982
5983	/* XXX boundary check against sa_len */
5984	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5985
5986	/* get a SA index */
5987	LIST_FOREACH(sah, &sahtree, chain) {
5988		if (sah->state == SADB_SASTATE_DEAD)
5989			continue;
5990		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
5991			break;
5992	}
5993	if (sah != NULL) {
5994		ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
5995		return key_senderror(so, m, EEXIST);
5996	}
5997
5998	error = key_acquire(&saidx, NULL);
5999	if (error != 0) {
6000		ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
6001			"from key_acquire.\n", mhp->msg->sadb_msg_errno));
6002		return key_senderror(so, m, error);
6003	}
6004
6005	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6006}
6007
6008/*
6009 * SADB_REGISTER processing.
6010 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6011 * receive
6012 *   <base>
6013 * from the ikmpd, and register a socket to send PF_KEY messages,
6014 * and send
6015 *   <base, supported>
6016 * to KMD by PF_KEY.
6017 * If socket is detached, must free from regnode.
6018 *
6019 * m will always be freed.
6020 */
6021static int
6022key_register(so, m, mhp)
6023	struct socket *so;
6024	struct mbuf *m;
6025	const struct sadb_msghdr *mhp;
6026{
6027	struct secreg *reg, *newreg = 0;
6028
6029	/* sanity check */
6030	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6031		panic("key_register: NULL pointer is passed.\n");
6032
6033	/* check for invalid register message */
6034	if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
6035		return key_senderror(so, m, EINVAL);
6036
6037	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6038	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6039		goto setmsg;
6040
6041	/* check whether existing or not */
6042	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
6043		if (reg->so == so) {
6044			ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
6045			return key_senderror(so, m, EEXIST);
6046		}
6047	}
6048
6049	/* create regnode */
6050	KMALLOC(newreg, struct secreg *, sizeof(*newreg));
6051	if (newreg == NULL) {
6052		ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
6053		return key_senderror(so, m, ENOBUFS);
6054	}
6055	bzero((caddr_t)newreg, sizeof(*newreg));
6056
6057	newreg->so = so;
6058	((struct keycb *)sotorawcb(so))->kp_registered++;
6059
6060	/* add regnode to regtree. */
6061	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6062
6063  setmsg:
6064    {
6065	struct mbuf *n;
6066	struct sadb_msg *newmsg;
6067	struct sadb_supported *sup;
6068	u_int len, alen, elen;
6069	int off;
6070	int i;
6071	struct sadb_alg *alg;
6072
6073	/* create new sadb_msg to reply. */
6074	alen = 0;
6075	for (i = 1; i <= SADB_AALG_MAX; i++) {
6076		if (ah_algorithm_lookup(i))
6077			alen += sizeof(struct sadb_alg);
6078	}
6079	if (alen)
6080		alen += sizeof(struct sadb_supported);
6081	elen = 0;
6082	for (i = 1; i <= SADB_EALG_MAX; i++) {
6083		if (esp_algorithm_lookup(i))
6084			elen += sizeof(struct sadb_alg);
6085	}
6086	if (elen)
6087		elen += sizeof(struct sadb_supported);
6088
6089	len = sizeof(struct sadb_msg) + alen + elen;
6090
6091	if (len > MCLBYTES)
6092		return key_senderror(so, m, ENOBUFS);
6093
6094	MGETHDR(n, M_NOWAIT, MT_DATA);
6095	if (len > MHLEN) {
6096		MCLGET(n, M_NOWAIT);
6097		if ((n->m_flags & M_EXT) == 0) {
6098			m_freem(n);
6099			n = NULL;
6100		}
6101	}
6102	if (!n)
6103		return key_senderror(so, m, ENOBUFS);
6104
6105	n->m_pkthdr.len = n->m_len = len;
6106	n->m_next = NULL;
6107	off = 0;
6108
6109	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6110	newmsg = mtod(n, struct sadb_msg *);
6111	newmsg->sadb_msg_errno = 0;
6112	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6113	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6114
6115	/* for authentication algorithm */
6116	if (alen) {
6117		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6118		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6119		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6120		off += PFKEY_ALIGN8(sizeof(*sup));
6121
6122		for (i = 1; i <= SADB_AALG_MAX; i++) {
6123			struct auth_hash *aalgo;
6124			u_int16_t minkeysize, maxkeysize;
6125
6126			aalgo = ah_algorithm_lookup(i);
6127			if (!aalgo)
6128				continue;
6129			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6130			alg->sadb_alg_id = i;
6131			alg->sadb_alg_ivlen = 0;
6132			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6133			alg->sadb_alg_minbits = _BITS(minkeysize);
6134			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6135			off += PFKEY_ALIGN8(sizeof(*alg));
6136		}
6137	}
6138
6139	/* for encryption algorithm */
6140	if (elen) {
6141		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6142		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6143		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6144		off += PFKEY_ALIGN8(sizeof(*sup));
6145
6146		for (i = 1; i <= SADB_EALG_MAX; i++) {
6147			struct enc_xform *ealgo;
6148
6149			ealgo = esp_algorithm_lookup(i);
6150			if (!ealgo)
6151				continue;
6152			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6153			alg->sadb_alg_id = i;
6154			alg->sadb_alg_ivlen = ealgo->blocksize;
6155			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6156			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6157			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6158		}
6159	}
6160
6161#ifdef DIGAGNOSTIC
6162	if (off != len)
6163		panic("length assumption failed in key_register");
6164#endif
6165
6166	m_freem(m);
6167	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6168    }
6169}
6170
6171/*
6172 * free secreg entry registered.
6173 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6174 */
6175void
6176key_freereg(so)
6177	struct socket *so;
6178{
6179	struct secreg *reg;
6180	int i;
6181
6182	/* sanity check */
6183	if (so == NULL)
6184		panic("key_freereg: NULL pointer is passed.\n");
6185
6186	/*
6187	 * check whether existing or not.
6188	 * check all type of SA, because there is a potential that
6189	 * one socket is registered to multiple type of SA.
6190	 */
6191	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6192		LIST_FOREACH(reg, &regtree[i], chain) {
6193			if (reg->so == so
6194			 && __LIST_CHAINED(reg)) {
6195				LIST_REMOVE(reg, chain);
6196				KFREE(reg);
6197				break;
6198			}
6199		}
6200	}
6201
6202	return;
6203}
6204
6205/*
6206 * SADB_EXPIRE processing
6207 * send
6208 *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6209 * to KMD by PF_KEY.
6210 * NOTE: We send only soft lifetime extension.
6211 *
6212 * OUT:	0	: succeed
6213 *	others	: error number
6214 */
6215static int
6216key_expire(sav)
6217	struct secasvar *sav;
6218{
6219	int s;
6220	int satype;
6221	struct mbuf *result = NULL, *m;
6222	int len;
6223	int error = -1;
6224	struct sadb_lifetime *lt;
6225
6226	/* XXX: Why do we lock ? */
6227	s = splnet();	/*called from softclock()*/
6228
6229	/* sanity check */
6230	if (sav == NULL)
6231		panic("key_expire: NULL pointer is passed.\n");
6232	if (sav->sah == NULL)
6233		panic("key_expire: Why was SA index in SA NULL.\n");
6234	if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
6235		panic("key_expire: invalid proto is passed.\n");
6236
6237	/* set msg header */
6238	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6239	if (!m) {
6240		error = ENOBUFS;
6241		goto fail;
6242	}
6243	result = m;
6244
6245	/* create SA extension */
6246	m = key_setsadbsa(sav);
6247	if (!m) {
6248		error = ENOBUFS;
6249		goto fail;
6250	}
6251	m_cat(result, m);
6252
6253	/* create SA extension */
6254	m = key_setsadbxsa2(sav->sah->saidx.mode,
6255			sav->replay ? sav->replay->count : 0,
6256			sav->sah->saidx.reqid);
6257	if (!m) {
6258		error = ENOBUFS;
6259		goto fail;
6260	}
6261	m_cat(result, m);
6262
6263	/* create lifetime extension (current and soft) */
6264	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6265	m = key_alloc_mbuf(len);
6266	if (!m || m->m_next) {	/*XXX*/
6267		if (m)
6268			m_freem(m);
6269		error = ENOBUFS;
6270		goto fail;
6271	}
6272	bzero(mtod(m, caddr_t), len);
6273	lt = mtod(m, struct sadb_lifetime *);
6274	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6275	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6276	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6277	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6278	lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
6279	lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
6280	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6281	bcopy(sav->lft_s, lt, sizeof(*lt));
6282	m_cat(result, m);
6283
6284	/* set sadb_address for source */
6285	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6286	    &sav->sah->saidx.src.sa,
6287	    FULLMASK, IPSEC_ULPROTO_ANY);
6288	if (!m) {
6289		error = ENOBUFS;
6290		goto fail;
6291	}
6292	m_cat(result, m);
6293
6294	/* set sadb_address for destination */
6295	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6296	    &sav->sah->saidx.dst.sa,
6297	    FULLMASK, IPSEC_ULPROTO_ANY);
6298	if (!m) {
6299		error = ENOBUFS;
6300		goto fail;
6301	}
6302	m_cat(result, m);
6303
6304	if ((result->m_flags & M_PKTHDR) == 0) {
6305		error = EINVAL;
6306		goto fail;
6307	}
6308
6309	if (result->m_len < sizeof(struct sadb_msg)) {
6310		result = m_pullup(result, sizeof(struct sadb_msg));
6311		if (result == NULL) {
6312			error = ENOBUFS;
6313			goto fail;
6314		}
6315	}
6316
6317	result->m_pkthdr.len = 0;
6318	for (m = result; m; m = m->m_next)
6319		result->m_pkthdr.len += m->m_len;
6320
6321	mtod(result, struct sadb_msg *)->sadb_msg_len =
6322	    PFKEY_UNIT64(result->m_pkthdr.len);
6323
6324	splx(s);
6325	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6326
6327 fail:
6328	if (result)
6329		m_freem(result);
6330	splx(s);
6331	return error;
6332}
6333
6334/*
6335 * SADB_FLUSH processing
6336 * receive
6337 *   <base>
6338 * from the ikmpd, and free all entries in secastree.
6339 * and send,
6340 *   <base>
6341 * to the ikmpd.
6342 * NOTE: to do is only marking SADB_SASTATE_DEAD.
6343 *
6344 * m will always be freed.
6345 */
6346static int
6347key_flush(so, m, mhp)
6348	struct socket *so;
6349	struct mbuf *m;
6350	const struct sadb_msghdr *mhp;
6351{
6352	struct sadb_msg *newmsg;
6353	struct secashead *sah, *nextsah;
6354	struct secasvar *sav, *nextsav;
6355	u_int16_t proto;
6356	u_int8_t state;
6357	u_int stateidx;
6358
6359	/* sanity check */
6360	if (so == NULL || mhp == NULL || mhp->msg == NULL)
6361		panic("key_flush: NULL pointer is passed.\n");
6362
6363	/* map satype to proto */
6364	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6365		ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
6366		return key_senderror(so, m, EINVAL);
6367	}
6368
6369	/* no SATYPE specified, i.e. flushing all SA. */
6370	for (sah = LIST_FIRST(&sahtree);
6371	     sah != NULL;
6372	     sah = nextsah) {
6373		nextsah = LIST_NEXT(sah, chain);
6374
6375		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6376		 && proto != sah->saidx.proto)
6377			continue;
6378
6379		for (stateidx = 0;
6380		     stateidx < _ARRAYLEN(saorder_state_alive);
6381		     stateidx++) {
6382			state = saorder_state_any[stateidx];
6383			for (sav = LIST_FIRST(&sah->savtree[state]);
6384			     sav != NULL;
6385			     sav = nextsav) {
6386
6387				nextsav = LIST_NEXT(sav, chain);
6388
6389				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6390				KEY_FREESAV(&sav);
6391			}
6392		}
6393
6394		sah->state = SADB_SASTATE_DEAD;
6395	}
6396
6397	if (m->m_len < sizeof(struct sadb_msg) ||
6398	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6399		ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
6400		return key_senderror(so, m, ENOBUFS);
6401	}
6402
6403	if (m->m_next)
6404		m_freem(m->m_next);
6405	m->m_next = NULL;
6406	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6407	newmsg = mtod(m, struct sadb_msg *);
6408	newmsg->sadb_msg_errno = 0;
6409	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6410
6411	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6412}
6413
6414/*
6415 * SADB_DUMP processing
6416 * dump all entries including status of DEAD in SAD.
6417 * receive
6418 *   <base>
6419 * from the ikmpd, and dump all secasvar leaves
6420 * and send,
6421 *   <base> .....
6422 * to the ikmpd.
6423 *
6424 * m will always be freed.
6425 */
6426static int
6427key_dump(so, m, mhp)
6428	struct socket *so;
6429	struct mbuf *m;
6430	const struct sadb_msghdr *mhp;
6431{
6432	struct secashead *sah;
6433	struct secasvar *sav;
6434	u_int16_t proto;
6435	u_int stateidx;
6436	u_int8_t satype;
6437	u_int8_t state;
6438	int cnt;
6439	struct sadb_msg *newmsg;
6440	struct mbuf *n;
6441
6442	/* sanity check */
6443	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6444		panic("key_dump: NULL pointer is passed.\n");
6445
6446	/* map satype to proto */
6447	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6448		ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
6449		return key_senderror(so, m, EINVAL);
6450	}
6451
6452	/* count sav entries to be sent to the userland. */
6453	cnt = 0;
6454	LIST_FOREACH(sah, &sahtree, chain) {
6455		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6456		 && proto != sah->saidx.proto)
6457			continue;
6458
6459		for (stateidx = 0;
6460		     stateidx < _ARRAYLEN(saorder_state_any);
6461		     stateidx++) {
6462			state = saorder_state_any[stateidx];
6463			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6464				cnt++;
6465			}
6466		}
6467	}
6468
6469	if (cnt == 0)
6470		return key_senderror(so, m, ENOENT);
6471
6472	/* send this to the userland, one at a time. */
6473	newmsg = NULL;
6474	LIST_FOREACH(sah, &sahtree, chain) {
6475		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6476		 && proto != sah->saidx.proto)
6477			continue;
6478
6479		/* map proto to satype */
6480		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6481			ipseclog((LOG_DEBUG, "key_dump: there was invalid proto in SAD.\n"));
6482			return key_senderror(so, m, EINVAL);
6483		}
6484
6485		for (stateidx = 0;
6486		     stateidx < _ARRAYLEN(saorder_state_any);
6487		     stateidx++) {
6488			state = saorder_state_any[stateidx];
6489			LIST_FOREACH(sav, &sah->savtree[state], chain) {
6490				n = key_setdumpsa(sav, SADB_DUMP, satype,
6491				    --cnt, mhp->msg->sadb_msg_pid);
6492				if (!n)
6493					return key_senderror(so, m, ENOBUFS);
6494
6495				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6496			}
6497		}
6498	}
6499
6500	m_freem(m);
6501	return 0;
6502}
6503
6504/*
6505 * SADB_X_PROMISC processing
6506 *
6507 * m will always be freed.
6508 */
6509static int
6510key_promisc(so, m, mhp)
6511	struct socket *so;
6512	struct mbuf *m;
6513	const struct sadb_msghdr *mhp;
6514{
6515	int olen;
6516
6517	/* sanity check */
6518	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6519		panic("key_promisc: NULL pointer is passed.\n");
6520
6521	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6522
6523	if (olen < sizeof(struct sadb_msg)) {
6524#if 1
6525		return key_senderror(so, m, EINVAL);
6526#else
6527		m_freem(m);
6528		return 0;
6529#endif
6530	} else if (olen == sizeof(struct sadb_msg)) {
6531		/* enable/disable promisc mode */
6532		struct keycb *kp;
6533
6534		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6535			return key_senderror(so, m, EINVAL);
6536		mhp->msg->sadb_msg_errno = 0;
6537		switch (mhp->msg->sadb_msg_satype) {
6538		case 0:
6539		case 1:
6540			kp->kp_promisc = mhp->msg->sadb_msg_satype;
6541			break;
6542		default:
6543			return key_senderror(so, m, EINVAL);
6544		}
6545
6546		/* send the original message back to everyone */
6547		mhp->msg->sadb_msg_errno = 0;
6548		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6549	} else {
6550		/* send packet as is */
6551
6552		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6553
6554		/* TODO: if sadb_msg_seq is specified, send to specific pid */
6555		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6556	}
6557}
6558
6559static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
6560		const struct sadb_msghdr *)) = {
6561	NULL,		/* SADB_RESERVED */
6562	key_getspi,	/* SADB_GETSPI */
6563	key_update,	/* SADB_UPDATE */
6564	key_add,	/* SADB_ADD */
6565	key_delete,	/* SADB_DELETE */
6566	key_get,	/* SADB_GET */
6567	key_acquire2,	/* SADB_ACQUIRE */
6568	key_register,	/* SADB_REGISTER */
6569	NULL,		/* SADB_EXPIRE */
6570	key_flush,	/* SADB_FLUSH */
6571	key_dump,	/* SADB_DUMP */
6572	key_promisc,	/* SADB_X_PROMISC */
6573	NULL,		/* SADB_X_PCHANGE */
6574	key_spdadd,	/* SADB_X_SPDUPDATE */
6575	key_spdadd,	/* SADB_X_SPDADD */
6576	key_spddelete,	/* SADB_X_SPDDELETE */
6577	key_spdget,	/* SADB_X_SPDGET */
6578	NULL,		/* SADB_X_SPDACQUIRE */
6579	key_spddump,	/* SADB_X_SPDDUMP */
6580	key_spdflush,	/* SADB_X_SPDFLUSH */
6581	key_spdadd,	/* SADB_X_SPDSETIDX */
6582	NULL,		/* SADB_X_SPDEXPIRE */
6583	key_spddelete2,	/* SADB_X_SPDDELETE2 */
6584};
6585
6586/*
6587 * parse sadb_msg buffer to process PFKEYv2,
6588 * and create a data to response if needed.
6589 * I think to be dealed with mbuf directly.
6590 * IN:
6591 *     msgp  : pointer to pointer to a received buffer pulluped.
6592 *             This is rewrited to response.
6593 *     so    : pointer to socket.
6594 * OUT:
6595 *    length for buffer to send to user process.
6596 */
6597int
6598key_parse(m, so)
6599	struct mbuf *m;
6600	struct socket *so;
6601{
6602	struct sadb_msg *msg;
6603	struct sadb_msghdr mh;
6604	u_int orglen;
6605	int error;
6606	int target;
6607
6608	/* sanity check */
6609	if (m == NULL || so == NULL)
6610		panic("key_parse: NULL pointer is passed.\n");
6611
6612#if 0	/*kdebug_sadb assumes msg in linear buffer*/
6613	KEYDEBUG(KEYDEBUG_KEY_DUMP,
6614		ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
6615		kdebug_sadb(msg));
6616#endif
6617
6618	if (m->m_len < sizeof(struct sadb_msg)) {
6619		m = m_pullup(m, sizeof(struct sadb_msg));
6620		if (!m)
6621			return ENOBUFS;
6622	}
6623	msg = mtod(m, struct sadb_msg *);
6624	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6625	target = KEY_SENDUP_ONE;
6626
6627	if ((m->m_flags & M_PKTHDR) == 0 ||
6628	    m->m_pkthdr.len != m->m_pkthdr.len) {
6629		ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
6630		pfkeystat.out_invlen++;
6631		error = EINVAL;
6632		goto senderror;
6633	}
6634
6635	if (msg->sadb_msg_version != PF_KEY_V2) {
6636		ipseclog((LOG_DEBUG,
6637		    "key_parse: PF_KEY version %u is mismatched.\n",
6638		    msg->sadb_msg_version));
6639		pfkeystat.out_invver++;
6640		error = EINVAL;
6641		goto senderror;
6642	}
6643
6644	if (msg->sadb_msg_type > SADB_MAX) {
6645		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6646		    msg->sadb_msg_type));
6647		pfkeystat.out_invmsgtype++;
6648		error = EINVAL;
6649		goto senderror;
6650	}
6651
6652	/* for old-fashioned code - should be nuked */
6653	if (m->m_pkthdr.len > MCLBYTES) {
6654		m_freem(m);
6655		return ENOBUFS;
6656	}
6657	if (m->m_next) {
6658		struct mbuf *n;
6659
6660		MGETHDR(n, M_NOWAIT, MT_DATA);
6661		if (n && m->m_pkthdr.len > MHLEN) {
6662			MCLGET(n, M_NOWAIT);
6663			if ((n->m_flags & M_EXT) == 0) {
6664				m_free(n);
6665				n = NULL;
6666			}
6667		}
6668		if (!n) {
6669			m_freem(m);
6670			return ENOBUFS;
6671		}
6672		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6673		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6674		n->m_next = NULL;
6675		m_freem(m);
6676		m = n;
6677	}
6678
6679	/* align the mbuf chain so that extensions are in contiguous region. */
6680	error = key_align(m, &mh);
6681	if (error)
6682		return error;
6683
6684	if (m->m_next) {	/*XXX*/
6685		m_freem(m);
6686		return ENOBUFS;
6687	}
6688
6689	msg = mh.msg;
6690
6691	/* check SA type */
6692	switch (msg->sadb_msg_satype) {
6693	case SADB_SATYPE_UNSPEC:
6694		switch (msg->sadb_msg_type) {
6695		case SADB_GETSPI:
6696		case SADB_UPDATE:
6697		case SADB_ADD:
6698		case SADB_DELETE:
6699		case SADB_GET:
6700		case SADB_ACQUIRE:
6701		case SADB_EXPIRE:
6702			ipseclog((LOG_DEBUG, "key_parse: must specify satype "
6703			    "when msg type=%u.\n", msg->sadb_msg_type));
6704			pfkeystat.out_invsatype++;
6705			error = EINVAL;
6706			goto senderror;
6707		}
6708		break;
6709	case SADB_SATYPE_AH:
6710	case SADB_SATYPE_ESP:
6711	case SADB_X_SATYPE_IPCOMP:
6712		switch (msg->sadb_msg_type) {
6713		case SADB_X_SPDADD:
6714		case SADB_X_SPDDELETE:
6715		case SADB_X_SPDGET:
6716		case SADB_X_SPDDUMP:
6717		case SADB_X_SPDFLUSH:
6718		case SADB_X_SPDSETIDX:
6719		case SADB_X_SPDUPDATE:
6720		case SADB_X_SPDDELETE2:
6721			ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
6722			    msg->sadb_msg_type));
6723			pfkeystat.out_invsatype++;
6724			error = EINVAL;
6725			goto senderror;
6726		}
6727		break;
6728	case SADB_SATYPE_RSVP:
6729	case SADB_SATYPE_OSPFV2:
6730	case SADB_SATYPE_RIPV2:
6731	case SADB_SATYPE_MIP:
6732		ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
6733		    msg->sadb_msg_satype));
6734		pfkeystat.out_invsatype++;
6735		error = EOPNOTSUPP;
6736		goto senderror;
6737	case 1:	/* XXX: What does it do? */
6738		if (msg->sadb_msg_type == SADB_X_PROMISC)
6739			break;
6740		/*FALLTHROUGH*/
6741	default:
6742		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6743		    msg->sadb_msg_satype));
6744		pfkeystat.out_invsatype++;
6745		error = EINVAL;
6746		goto senderror;
6747	}
6748
6749	/* check field of upper layer protocol and address family */
6750	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6751	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6752		struct sadb_address *src0, *dst0;
6753		u_int plen;
6754
6755		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6756		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6757
6758		/* check upper layer protocol */
6759		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6760			ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
6761			pfkeystat.out_invaddr++;
6762			error = EINVAL;
6763			goto senderror;
6764		}
6765
6766		/* check family */
6767		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6768		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
6769			ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
6770			pfkeystat.out_invaddr++;
6771			error = EINVAL;
6772			goto senderror;
6773		}
6774		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6775		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
6776			ipseclog((LOG_DEBUG,
6777			    "key_parse: address struct size mismatched.\n"));
6778			pfkeystat.out_invaddr++;
6779			error = EINVAL;
6780			goto senderror;
6781		}
6782
6783		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6784		case AF_INET:
6785			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6786			    sizeof(struct sockaddr_in)) {
6787				pfkeystat.out_invaddr++;
6788				error = EINVAL;
6789				goto senderror;
6790			}
6791			break;
6792		case AF_INET6:
6793			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6794			    sizeof(struct sockaddr_in6)) {
6795				pfkeystat.out_invaddr++;
6796				error = EINVAL;
6797				goto senderror;
6798			}
6799			break;
6800		default:
6801			ipseclog((LOG_DEBUG,
6802			    "key_parse: unsupported address family.\n"));
6803			pfkeystat.out_invaddr++;
6804			error = EAFNOSUPPORT;
6805			goto senderror;
6806		}
6807
6808		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6809		case AF_INET:
6810			plen = sizeof(struct in_addr) << 3;
6811			break;
6812		case AF_INET6:
6813			plen = sizeof(struct in6_addr) << 3;
6814			break;
6815		default:
6816			plen = 0;	/*fool gcc*/
6817			break;
6818		}
6819
6820		/* check max prefix length */
6821		if (src0->sadb_address_prefixlen > plen ||
6822		    dst0->sadb_address_prefixlen > plen) {
6823			ipseclog((LOG_DEBUG,
6824			    "key_parse: illegal prefixlen.\n"));
6825			pfkeystat.out_invaddr++;
6826			error = EINVAL;
6827			goto senderror;
6828		}
6829
6830		/*
6831		 * prefixlen == 0 is valid because there can be a case when
6832		 * all addresses are matched.
6833		 */
6834	}
6835
6836	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
6837	    key_typesw[msg->sadb_msg_type] == NULL) {
6838		pfkeystat.out_invmsgtype++;
6839		error = EINVAL;
6840		goto senderror;
6841	}
6842
6843	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6844
6845senderror:
6846	msg->sadb_msg_errno = error;
6847	return key_sendup_mbuf(so, m, target);
6848}
6849
6850static int
6851key_senderror(so, m, code)
6852	struct socket *so;
6853	struct mbuf *m;
6854	int code;
6855{
6856	struct sadb_msg *msg;
6857
6858	if (m->m_len < sizeof(struct sadb_msg))
6859		panic("invalid mbuf passed to key_senderror");
6860
6861	msg = mtod(m, struct sadb_msg *);
6862	msg->sadb_msg_errno = code;
6863	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
6864}
6865
6866/*
6867 * set the pointer to each header into message buffer.
6868 * m will be freed on error.
6869 * XXX larger-than-MCLBYTES extension?
6870 */
6871static int
6872key_align(m, mhp)
6873	struct mbuf *m;
6874	struct sadb_msghdr *mhp;
6875{
6876	struct mbuf *n;
6877	struct sadb_ext *ext;
6878	size_t off, end;
6879	int extlen;
6880	int toff;
6881
6882	/* sanity check */
6883	if (m == NULL || mhp == NULL)
6884		panic("key_align: NULL pointer is passed.\n");
6885	if (m->m_len < sizeof(struct sadb_msg))
6886		panic("invalid mbuf passed to key_align");
6887
6888	/* initialize */
6889	bzero(mhp, sizeof(*mhp));
6890
6891	mhp->msg = mtod(m, struct sadb_msg *);
6892	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
6893
6894	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6895	extlen = end;	/*just in case extlen is not updated*/
6896	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
6897		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
6898		if (!n) {
6899			/* m is already freed */
6900			return ENOBUFS;
6901		}
6902		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6903
6904		/* set pointer */
6905		switch (ext->sadb_ext_type) {
6906		case SADB_EXT_SA:
6907		case SADB_EXT_ADDRESS_SRC:
6908		case SADB_EXT_ADDRESS_DST:
6909		case SADB_EXT_ADDRESS_PROXY:
6910		case SADB_EXT_LIFETIME_CURRENT:
6911		case SADB_EXT_LIFETIME_HARD:
6912		case SADB_EXT_LIFETIME_SOFT:
6913		case SADB_EXT_KEY_AUTH:
6914		case SADB_EXT_KEY_ENCRYPT:
6915		case SADB_EXT_IDENTITY_SRC:
6916		case SADB_EXT_IDENTITY_DST:
6917		case SADB_EXT_SENSITIVITY:
6918		case SADB_EXT_PROPOSAL:
6919		case SADB_EXT_SUPPORTED_AUTH:
6920		case SADB_EXT_SUPPORTED_ENCRYPT:
6921		case SADB_EXT_SPIRANGE:
6922		case SADB_X_EXT_POLICY:
6923		case SADB_X_EXT_SA2:
6924			/* duplicate check */
6925			/*
6926			 * XXX Are there duplication payloads of either
6927			 * KEY_AUTH or KEY_ENCRYPT ?
6928			 */
6929			if (mhp->ext[ext->sadb_ext_type] != NULL) {
6930				ipseclog((LOG_DEBUG,
6931				    "key_align: duplicate ext_type %u "
6932				    "is passed.\n", ext->sadb_ext_type));
6933				m_freem(m);
6934				pfkeystat.out_dupext++;
6935				return EINVAL;
6936			}
6937			break;
6938		default:
6939			ipseclog((LOG_DEBUG,
6940			    "key_align: invalid ext_type %u is passed.\n",
6941			    ext->sadb_ext_type));
6942			m_freem(m);
6943			pfkeystat.out_invexttype++;
6944			return EINVAL;
6945		}
6946
6947		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
6948
6949		if (key_validate_ext(ext, extlen)) {
6950			m_freem(m);
6951			pfkeystat.out_invlen++;
6952			return EINVAL;
6953		}
6954
6955		n = m_pulldown(m, off, extlen, &toff);
6956		if (!n) {
6957			/* m is already freed */
6958			return ENOBUFS;
6959		}
6960		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6961
6962		mhp->ext[ext->sadb_ext_type] = ext;
6963		mhp->extoff[ext->sadb_ext_type] = off;
6964		mhp->extlen[ext->sadb_ext_type] = extlen;
6965	}
6966
6967	if (off != end) {
6968		m_freem(m);
6969		pfkeystat.out_invlen++;
6970		return EINVAL;
6971	}
6972
6973	return 0;
6974}
6975
6976static int
6977key_validate_ext(ext, len)
6978	const struct sadb_ext *ext;
6979	int len;
6980{
6981	const struct sockaddr *sa;
6982	enum { NONE, ADDR } checktype = NONE;
6983	int baselen = 0;
6984	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
6985
6986	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
6987		return EINVAL;
6988
6989	/* if it does not match minimum/maximum length, bail */
6990	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
6991	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
6992		return EINVAL;
6993	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
6994		return EINVAL;
6995	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
6996		return EINVAL;
6997
6998	/* more checks based on sadb_ext_type XXX need more */
6999	switch (ext->sadb_ext_type) {
7000	case SADB_EXT_ADDRESS_SRC:
7001	case SADB_EXT_ADDRESS_DST:
7002	case SADB_EXT_ADDRESS_PROXY:
7003		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7004		checktype = ADDR;
7005		break;
7006	case SADB_EXT_IDENTITY_SRC:
7007	case SADB_EXT_IDENTITY_DST:
7008		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7009		    SADB_X_IDENTTYPE_ADDR) {
7010			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7011			checktype = ADDR;
7012		} else
7013			checktype = NONE;
7014		break;
7015	default:
7016		checktype = NONE;
7017		break;
7018	}
7019
7020	switch (checktype) {
7021	case NONE:
7022		break;
7023	case ADDR:
7024		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7025		if (len < baselen + sal)
7026			return EINVAL;
7027		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7028			return EINVAL;
7029		break;
7030	}
7031
7032	return 0;
7033}
7034
7035void
7036key_init()
7037{
7038	int i;
7039
7040	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7041		LIST_INIT(&sptree[i]);
7042	}
7043
7044	LIST_INIT(&sahtree);
7045
7046	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7047		LIST_INIT(&regtree[i]);
7048	}
7049
7050#ifndef IPSEC_NONBLOCK_ACQUIRE
7051	LIST_INIT(&acqtree);
7052#endif
7053	LIST_INIT(&spacqtree);
7054
7055	/* system default */
7056	ip4_def_policy.policy = IPSEC_POLICY_NONE;
7057	ip4_def_policy.refcnt++;	/*never reclaim this*/
7058
7059#ifndef IPSEC_DEBUG2
7060	timeout((void *)key_timehandler, (void *)0, hz);
7061#endif /*IPSEC_DEBUG2*/
7062
7063	/* initialize key statistics */
7064	keystat.getspi_count = 1;
7065
7066	printf("IPsec: Initialized Security Association Processing.\n");
7067
7068	return;
7069}
7070
7071/*
7072 * XXX: maybe This function is called after INBOUND IPsec processing.
7073 *
7074 * Special check for tunnel-mode packets.
7075 * We must make some checks for consistency between inner and outer IP header.
7076 *
7077 * xxx more checks to be provided
7078 */
7079int
7080key_checktunnelsanity(sav, family, src, dst)
7081	struct secasvar *sav;
7082	u_int family;
7083	caddr_t src;
7084	caddr_t dst;
7085{
7086	/* sanity check */
7087	if (sav->sah == NULL)
7088		panic("sav->sah == NULL at key_checktunnelsanity");
7089
7090	/* XXX: check inner IP header */
7091
7092	return 1;
7093}
7094
7095#if 0
7096#define hostnamelen	strlen(hostname)
7097
7098/*
7099 * Get FQDN for the host.
7100 * If the administrator configured hostname (by hostname(1)) without
7101 * domain name, returns nothing.
7102 */
7103static const char *
7104key_getfqdn()
7105{
7106	int i;
7107	int hasdot;
7108	static char fqdn[MAXHOSTNAMELEN + 1];
7109
7110	if (!hostnamelen)
7111		return NULL;
7112
7113	/* check if it comes with domain name. */
7114	hasdot = 0;
7115	for (i = 0; i < hostnamelen; i++) {
7116		if (hostname[i] == '.')
7117			hasdot++;
7118	}
7119	if (!hasdot)
7120		return NULL;
7121
7122	/* NOTE: hostname may not be NUL-terminated. */
7123	bzero(fqdn, sizeof(fqdn));
7124	bcopy(hostname, fqdn, hostnamelen);
7125	fqdn[hostnamelen] = '\0';
7126	return fqdn;
7127}
7128
7129/*
7130 * get username@FQDN for the host/user.
7131 */
7132static const char *
7133key_getuserfqdn()
7134{
7135	const char *host;
7136	static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
7137	struct proc *p = curproc;
7138	char *q;
7139
7140	if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
7141		return NULL;
7142	if (!(host = key_getfqdn()))
7143		return NULL;
7144
7145	/* NOTE: s_login may not be-NUL terminated. */
7146	bzero(userfqdn, sizeof(userfqdn));
7147	bcopy(p->p_pgrp->pg_session->s_login, userfqdn, MAXLOGNAME);
7148	userfqdn[MAXLOGNAME] = '\0';	/* safeguard */
7149	q = userfqdn + strlen(userfqdn);
7150	*q++ = '@';
7151	bcopy(host, q, strlen(host));
7152	q += strlen(host);
7153	*q++ = '\0';
7154
7155	return userfqdn;
7156}
7157#endif
7158
7159/* record data transfer on SA, and update timestamps */
7160void
7161key_sa_recordxfer(sav, m)
7162	struct secasvar *sav;
7163	struct mbuf *m;
7164{
7165	KASSERT(sav != NULL, ("key_sa_recordxfer: Null secasvar"));
7166	KASSERT(m != NULL, ("key_sa_recordxfer: Null mbuf"));
7167	if (!sav->lft_c)
7168		return;
7169
7170	/*
7171	 * XXX Currently, there is a difference of bytes size
7172	 * between inbound and outbound processing.
7173	 */
7174	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
7175	/* to check bytes lifetime is done in key_timehandler(). */
7176
7177	/*
7178	 * We use the number of packets as the unit of
7179	 * sadb_lifetime_allocations.  We increment the variable
7180	 * whenever {esp,ah}_{in,out}put is called.
7181	 */
7182	sav->lft_c->sadb_lifetime_allocations++;
7183	/* XXX check for expires? */
7184
7185	/*
7186	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
7187	 * in seconds.  HARD and SOFT lifetime are measured by the time
7188	 * difference (again in seconds) from sadb_lifetime_usetime.
7189	 *
7190	 *	usetime
7191	 *	v     expire   expire
7192	 * -----+-----+--------+---> t
7193	 *	<--------------> HARD
7194	 *	<-----> SOFT
7195	 */
7196	sav->lft_c->sadb_lifetime_usetime = time_second;
7197	/* XXX check for expires? */
7198
7199	return;
7200}
7201
7202/* dumb version */
7203void
7204key_sa_routechange(dst)
7205	struct sockaddr *dst;
7206{
7207	struct secashead *sah;
7208	struct route *ro;
7209
7210	LIST_FOREACH(sah, &sahtree, chain) {
7211		ro = &sah->sa_route;
7212		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7213		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7214			RTFREE(ro->ro_rt);
7215			ro->ro_rt = (struct rtentry *)NULL;
7216		}
7217	}
7218
7219	return;
7220}
7221
7222static void
7223key_sa_chgstate(sav, state)
7224	struct secasvar *sav;
7225	u_int8_t state;
7226{
7227	if (sav == NULL)
7228		panic("key_sa_chgstate called with sav == NULL");
7229
7230	if (sav->state == state)
7231		return;
7232
7233	if (__LIST_CHAINED(sav))
7234		LIST_REMOVE(sav, chain);
7235
7236	sav->state = state;
7237	LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7238}
7239
7240void
7241key_sa_stir_iv(sav)
7242	struct secasvar *sav;
7243{
7244
7245	if (!sav->iv)
7246		panic("key_sa_stir_iv called with sav == NULL");
7247	key_randomfill(sav->iv, sav->ivlen);
7248}
7249
7250/* XXX too much? */
7251static struct mbuf *
7252key_alloc_mbuf(l)
7253	int l;
7254{
7255	struct mbuf *m = NULL, *n;
7256	int len, t;
7257
7258	len = l;
7259	while (len > 0) {
7260		MGET(n, M_NOWAIT, MT_DATA);
7261		if (n && len > MLEN)
7262			MCLGET(n, M_NOWAIT);
7263		if (!n) {
7264			m_freem(m);
7265			return NULL;
7266		}
7267
7268		n->m_next = NULL;
7269		n->m_len = 0;
7270		n->m_len = M_TRAILINGSPACE(n);
7271		/* use the bottom of mbuf, hoping we can prepend afterwards */
7272		if (n->m_len > len) {
7273			t = (n->m_len - len) & ~(sizeof(long) - 1);
7274			n->m_data += t;
7275			n->m_len = len;
7276		}
7277
7278		len -= n->m_len;
7279
7280		if (m)
7281			m_cat(m, n);
7282		else
7283			m = n;
7284	}
7285
7286	return m;
7287}
7288