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