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