key.c revision 194971
1/*	$FreeBSD: head/sys/netipsec/key.c 194971 2009-06-25 16:35:28Z rwatson $	*/
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		IN_IFADDR_RLOCK();
3943		for (ia = V_in_ifaddrhead.tqh_first; ia;
3944		     ia = ia->ia_link.tqe_next)
3945		{
3946			if (sin->sin_family == ia->ia_addr.sin_family &&
3947			    sin->sin_len == ia->ia_addr.sin_len &&
3948			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3949			{
3950				IN_IFADDR_RUNLOCK();
3951				return 1;
3952			}
3953		}
3954		IN_IFADDR_RUNLOCK();
3955		break;
3956#endif
3957#ifdef INET6
3958	case AF_INET6:
3959		return key_ismyaddr6((struct sockaddr_in6 *)sa);
3960#endif
3961	}
3962
3963	return 0;
3964}
3965
3966#ifdef INET6
3967/*
3968 * compare my own address for IPv6.
3969 * 1: ours
3970 * 0: other
3971 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3972 */
3973#include <netinet6/in6_var.h>
3974
3975static int
3976key_ismyaddr6(sin6)
3977	struct sockaddr_in6 *sin6;
3978{
3979	INIT_VNET_INET6(curvnet);
3980	struct in6_ifaddr *ia;
3981#if 0
3982	struct in6_multi *in6m;
3983#endif
3984
3985	IN6_IFADDR_RLOCK();
3986	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
3987		if (key_sockaddrcmp((struct sockaddr *)&sin6,
3988		    (struct sockaddr *)&ia->ia_addr, 0) == 0) {
3989			IN6_IFADDR_RUNLOCK();
3990			return 1;
3991		}
3992
3993#if 0
3994		/*
3995		 * XXX Multicast
3996		 * XXX why do we care about multlicast here while we don't care
3997		 * about IPv4 multicast??
3998		 * XXX scope
3999		 */
4000		in6m = NULL;
4001		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
4002		if (in6m) {
4003			IN6_IFADDR_RUNLOCK();
4004			return 1;
4005		}
4006#endif
4007	}
4008	IN6_IFADDR_RUNLOCK();
4009
4010	/* loopback, just for safety */
4011	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
4012		return 1;
4013
4014	return 0;
4015}
4016#endif /*INET6*/
4017
4018/*
4019 * compare two secasindex structure.
4020 * flag can specify to compare 2 saidxes.
4021 * compare two secasindex structure without both mode and reqid.
4022 * don't compare port.
4023 * IN:
4024 *      saidx0: source, it can be in SAD.
4025 *      saidx1: object.
4026 * OUT:
4027 *      1 : equal
4028 *      0 : not equal
4029 */
4030static int
4031key_cmpsaidx(
4032	const struct secasindex *saidx0,
4033	const struct secasindex *saidx1,
4034	int flag)
4035{
4036	int chkport = 0;
4037
4038	/* sanity */
4039	if (saidx0 == NULL && saidx1 == NULL)
4040		return 1;
4041
4042	if (saidx0 == NULL || saidx1 == NULL)
4043		return 0;
4044
4045	if (saidx0->proto != saidx1->proto)
4046		return 0;
4047
4048	if (flag == CMP_EXACTLY) {
4049		if (saidx0->mode != saidx1->mode)
4050			return 0;
4051		if (saidx0->reqid != saidx1->reqid)
4052			return 0;
4053		if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4054		    bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4055			return 0;
4056	} else {
4057
4058		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4059		if (flag == CMP_MODE_REQID
4060		  ||flag == CMP_REQID) {
4061			/*
4062			 * If reqid of SPD is non-zero, unique SA is required.
4063			 * The result must be of same reqid in this case.
4064			 */
4065			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4066				return 0;
4067		}
4068
4069		if (flag == CMP_MODE_REQID) {
4070			if (saidx0->mode != IPSEC_MODE_ANY
4071			 && saidx0->mode != saidx1->mode)
4072				return 0;
4073		}
4074
4075#ifdef IPSEC_NAT_T
4076		/*
4077		 * If NAT-T is enabled, check ports for tunnel mode.
4078		 * Do not check ports if they are set to zero in the SPD.
4079		 * Also do not do it for transport mode, as there is no
4080		 * port information available in the SP.
4081		 */
4082		if (saidx1->mode == IPSEC_MODE_TUNNEL &&
4083		    saidx1->src.sa.sa_family == AF_INET &&
4084		    saidx1->dst.sa.sa_family == AF_INET &&
4085		    ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
4086		    ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
4087			chkport = 1;
4088#endif /* IPSEC_NAT_T */
4089
4090		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
4091			return 0;
4092		}
4093		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
4094			return 0;
4095		}
4096	}
4097
4098	return 1;
4099}
4100
4101/*
4102 * compare two secindex structure exactly.
4103 * IN:
4104 *	spidx0: source, it is often in SPD.
4105 *	spidx1: object, it is often from PFKEY message.
4106 * OUT:
4107 *	1 : equal
4108 *	0 : not equal
4109 */
4110static int
4111key_cmpspidx_exactly(
4112	struct secpolicyindex *spidx0,
4113	struct secpolicyindex *spidx1)
4114{
4115	/* sanity */
4116	if (spidx0 == NULL && spidx1 == NULL)
4117		return 1;
4118
4119	if (spidx0 == NULL || spidx1 == NULL)
4120		return 0;
4121
4122	if (spidx0->prefs != spidx1->prefs
4123	 || spidx0->prefd != spidx1->prefd
4124	 || spidx0->ul_proto != spidx1->ul_proto)
4125		return 0;
4126
4127	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4128	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4129}
4130
4131/*
4132 * compare two secindex structure with mask.
4133 * IN:
4134 *	spidx0: source, it is often in SPD.
4135 *	spidx1: object, it is often from IP header.
4136 * OUT:
4137 *	1 : equal
4138 *	0 : not equal
4139 */
4140static int
4141key_cmpspidx_withmask(
4142	struct secpolicyindex *spidx0,
4143	struct secpolicyindex *spidx1)
4144{
4145	/* sanity */
4146	if (spidx0 == NULL && spidx1 == NULL)
4147		return 1;
4148
4149	if (spidx0 == NULL || spidx1 == NULL)
4150		return 0;
4151
4152	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4153	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4154	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4155	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4156		return 0;
4157
4158	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4159	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4160	 && spidx0->ul_proto != spidx1->ul_proto)
4161		return 0;
4162
4163	switch (spidx0->src.sa.sa_family) {
4164	case AF_INET:
4165		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4166		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4167			return 0;
4168		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4169		    &spidx1->src.sin.sin_addr, spidx0->prefs))
4170			return 0;
4171		break;
4172	case AF_INET6:
4173		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4174		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4175			return 0;
4176		/*
4177		 * scope_id check. if sin6_scope_id is 0, we regard it
4178		 * as a wildcard scope, which matches any scope zone ID.
4179		 */
4180		if (spidx0->src.sin6.sin6_scope_id &&
4181		    spidx1->src.sin6.sin6_scope_id &&
4182		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4183			return 0;
4184		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4185		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4186			return 0;
4187		break;
4188	default:
4189		/* XXX */
4190		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4191			return 0;
4192		break;
4193	}
4194
4195	switch (spidx0->dst.sa.sa_family) {
4196	case AF_INET:
4197		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4198		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4199			return 0;
4200		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4201		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
4202			return 0;
4203		break;
4204	case AF_INET6:
4205		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4206		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4207			return 0;
4208		/*
4209		 * scope_id check. if sin6_scope_id is 0, we regard it
4210		 * as a wildcard scope, which matches any scope zone ID.
4211		 */
4212		if (spidx0->dst.sin6.sin6_scope_id &&
4213		    spidx1->dst.sin6.sin6_scope_id &&
4214		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4215			return 0;
4216		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4217		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4218			return 0;
4219		break;
4220	default:
4221		/* XXX */
4222		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4223			return 0;
4224		break;
4225	}
4226
4227	/* XXX Do we check other field ?  e.g. flowinfo */
4228
4229	return 1;
4230}
4231
4232/* returns 0 on match */
4233static int
4234key_sockaddrcmp(
4235	const struct sockaddr *sa1,
4236	const struct sockaddr *sa2,
4237	int port)
4238{
4239#ifdef satosin
4240#undef satosin
4241#endif
4242#define satosin(s) ((const struct sockaddr_in *)s)
4243#ifdef satosin6
4244#undef satosin6
4245#endif
4246#define satosin6(s) ((const struct sockaddr_in6 *)s)
4247	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4248		return 1;
4249
4250	switch (sa1->sa_family) {
4251	case AF_INET:
4252		if (sa1->sa_len != sizeof(struct sockaddr_in))
4253			return 1;
4254		if (satosin(sa1)->sin_addr.s_addr !=
4255		    satosin(sa2)->sin_addr.s_addr) {
4256			return 1;
4257		}
4258		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4259			return 1;
4260		break;
4261	case AF_INET6:
4262		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4263			return 1;	/*EINVAL*/
4264		if (satosin6(sa1)->sin6_scope_id !=
4265		    satosin6(sa2)->sin6_scope_id) {
4266			return 1;
4267		}
4268		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4269		    &satosin6(sa2)->sin6_addr)) {
4270			return 1;
4271		}
4272		if (port &&
4273		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4274			return 1;
4275		}
4276		break;
4277	default:
4278		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4279			return 1;
4280		break;
4281	}
4282
4283	return 0;
4284#undef satosin
4285#undef satosin6
4286}
4287
4288/*
4289 * compare two buffers with mask.
4290 * IN:
4291 *	addr1: source
4292 *	addr2: object
4293 *	bits:  Number of bits to compare
4294 * OUT:
4295 *	1 : equal
4296 *	0 : not equal
4297 */
4298static int
4299key_bbcmp(const void *a1, const void *a2, u_int bits)
4300{
4301	const unsigned char *p1 = a1;
4302	const unsigned char *p2 = a2;
4303
4304	/* XXX: This could be considerably faster if we compare a word
4305	 * at a time, but it is complicated on LSB Endian machines */
4306
4307	/* Handle null pointers */
4308	if (p1 == NULL || p2 == NULL)
4309		return (p1 == p2);
4310
4311	while (bits >= 8) {
4312		if (*p1++ != *p2++)
4313			return 0;
4314		bits -= 8;
4315	}
4316
4317	if (bits > 0) {
4318		u_int8_t mask = ~((1<<(8-bits))-1);
4319		if ((*p1 & mask) != (*p2 & mask))
4320			return 0;
4321	}
4322	return 1;	/* Match! */
4323}
4324
4325static void
4326key_flush_spd(time_t now)
4327{
4328	INIT_VNET_IPSEC(curvnet);
4329	static u_int16_t sptree_scangen = 0;
4330	u_int16_t gen = sptree_scangen++;
4331	struct secpolicy *sp;
4332	u_int dir;
4333
4334	/* SPD */
4335	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4336restart:
4337		SPTREE_LOCK();
4338		LIST_FOREACH(sp, &V_sptree[dir], chain) {
4339			if (sp->scangen == gen)		/* previously handled */
4340				continue;
4341			sp->scangen = gen;
4342			if (sp->state == IPSEC_SPSTATE_DEAD &&
4343			    sp->refcnt == 1) {
4344				/*
4345				 * Ensure that we only decrease refcnt once,
4346				 * when we're the last consumer.
4347				 * Directly call SP_DELREF/key_delsp instead
4348				 * of KEY_FREESP to avoid unlocking/relocking
4349				 * SPTREE_LOCK before key_delsp: may refcnt
4350				 * be increased again during that time ?
4351				 * NB: also clean entries created by
4352				 * key_spdflush
4353				 */
4354				SP_DELREF(sp);
4355				key_delsp(sp);
4356				SPTREE_UNLOCK();
4357				goto restart;
4358			}
4359			if (sp->lifetime == 0 && sp->validtime == 0)
4360				continue;
4361			if ((sp->lifetime && now - sp->created > sp->lifetime)
4362			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4363				sp->state = IPSEC_SPSTATE_DEAD;
4364				SPTREE_UNLOCK();
4365				key_spdexpire(sp);
4366				goto restart;
4367			}
4368		}
4369		SPTREE_UNLOCK();
4370	}
4371}
4372
4373static void
4374key_flush_sad(time_t now)
4375{
4376	INIT_VNET_IPSEC(curvnet);
4377	struct secashead *sah, *nextsah;
4378	struct secasvar *sav, *nextsav;
4379
4380	/* SAD */
4381	SAHTREE_LOCK();
4382	LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4383		/* if sah has been dead, then delete it and process next sah. */
4384		if (sah->state == SADB_SASTATE_DEAD) {
4385			key_delsah(sah);
4386			continue;
4387		}
4388
4389		/* if LARVAL entry doesn't become MATURE, delete it. */
4390		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4391			/* Need to also check refcnt for a larval SA ??? */
4392			if (now - sav->created > V_key_larval_lifetime)
4393				KEY_FREESAV(&sav);
4394		}
4395
4396		/*
4397		 * check MATURE entry to start to send expire message
4398		 * whether or not.
4399		 */
4400		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4401			/* we don't need to check. */
4402			if (sav->lft_s == NULL)
4403				continue;
4404
4405			/* sanity check */
4406			if (sav->lft_c == NULL) {
4407				ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4408					"time, why?\n", __func__));
4409				continue;
4410			}
4411
4412			/* check SOFT lifetime */
4413			if (sav->lft_s->addtime != 0 &&
4414			    now - sav->created > sav->lft_s->addtime) {
4415				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4416				/*
4417				 * Actually, only send expire message if
4418				 * SA has been used, as it was done before,
4419				 * but should we always send such message,
4420				 * and let IKE daemon decide if it should be
4421				 * renegotiated or not ?
4422				 * XXX expire message will actually NOT be
4423				 * sent if SA is only used after soft
4424				 * lifetime has been reached, see below
4425				 * (DYING state)
4426				 */
4427				if (sav->lft_c->usetime != 0)
4428					key_expire(sav);
4429			}
4430			/* check SOFT lifetime by bytes */
4431			/*
4432			 * XXX I don't know the way to delete this SA
4433			 * when new SA is installed.  Caution when it's
4434			 * installed too big lifetime by time.
4435			 */
4436			else if (sav->lft_s->bytes != 0 &&
4437			    sav->lft_s->bytes < sav->lft_c->bytes) {
4438
4439				key_sa_chgstate(sav, SADB_SASTATE_DYING);
4440				/*
4441				 * XXX If we keep to send expire
4442				 * message in the status of
4443				 * DYING. Do remove below code.
4444				 */
4445				key_expire(sav);
4446			}
4447		}
4448
4449		/* check DYING entry to change status to DEAD. */
4450		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4451			/* we don't need to check. */
4452			if (sav->lft_h == NULL)
4453				continue;
4454
4455			/* sanity check */
4456			if (sav->lft_c == NULL) {
4457				ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4458					"time, why?\n", __func__));
4459				continue;
4460			}
4461
4462			if (sav->lft_h->addtime != 0 &&
4463			    now - sav->created > sav->lft_h->addtime) {
4464				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4465				KEY_FREESAV(&sav);
4466			}
4467#if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
4468			else if (sav->lft_s != NULL
4469			      && sav->lft_s->addtime != 0
4470			      && now - sav->created > sav->lft_s->addtime) {
4471				/*
4472				 * XXX: should be checked to be
4473				 * installed the valid SA.
4474				 */
4475
4476				/*
4477				 * If there is no SA then sending
4478				 * expire message.
4479				 */
4480				key_expire(sav);
4481			}
4482#endif
4483			/* check HARD lifetime by bytes */
4484			else if (sav->lft_h->bytes != 0 &&
4485			    sav->lft_h->bytes < sav->lft_c->bytes) {
4486				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4487				KEY_FREESAV(&sav);
4488			}
4489		}
4490
4491		/* delete entry in DEAD */
4492		LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4493			/* sanity check */
4494			if (sav->state != SADB_SASTATE_DEAD) {
4495				ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4496					"(queue: %d SA: %d): kill it anyway\n",
4497					__func__,
4498					SADB_SASTATE_DEAD, sav->state));
4499			}
4500			/*
4501			 * do not call key_freesav() here.
4502			 * sav should already be freed, and sav->refcnt
4503			 * shows other references to sav
4504			 * (such as from SPD).
4505			 */
4506		}
4507	}
4508	SAHTREE_UNLOCK();
4509}
4510
4511static void
4512key_flush_acq(time_t now)
4513{
4514	INIT_VNET_IPSEC(curvnet);
4515	struct secacq *acq, *nextacq;
4516
4517	/* ACQ tree */
4518	ACQ_LOCK();
4519	for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4520		nextacq = LIST_NEXT(acq, chain);
4521		if (now - acq->created > V_key_blockacq_lifetime
4522		 && __LIST_CHAINED(acq)) {
4523			LIST_REMOVE(acq, chain);
4524			free(acq, M_IPSEC_SAQ);
4525		}
4526	}
4527	ACQ_UNLOCK();
4528}
4529
4530static void
4531key_flush_spacq(time_t now)
4532{
4533	INIT_VNET_IPSEC(curvnet);
4534	struct secspacq *acq, *nextacq;
4535
4536	/* SP ACQ tree */
4537	SPACQ_LOCK();
4538	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4539		nextacq = LIST_NEXT(acq, chain);
4540		if (now - acq->created > V_key_blockacq_lifetime
4541		 && __LIST_CHAINED(acq)) {
4542			LIST_REMOVE(acq, chain);
4543			free(acq, M_IPSEC_SAQ);
4544		}
4545	}
4546	SPACQ_UNLOCK();
4547}
4548
4549/*
4550 * time handler.
4551 * scanning SPD and SAD to check status for each entries,
4552 * and do to remove or to expire.
4553 * XXX: year 2038 problem may remain.
4554 */
4555void
4556key_timehandler(void)
4557{
4558	VNET_ITERATOR_DECL(vnet_iter);
4559	time_t now = time_second;
4560
4561	VNET_LIST_RLOCK();
4562	VNET_FOREACH(vnet_iter) {
4563		CURVNET_SET(vnet_iter);
4564		key_flush_spd(now);
4565		key_flush_sad(now);
4566		key_flush_acq(now);
4567		key_flush_spacq(now);
4568		CURVNET_RESTORE();
4569	}
4570	VNET_LIST_RUNLOCK();
4571
4572#ifndef IPSEC_DEBUG2
4573	/* do exchange to tick time !! */
4574	(void)timeout((void *)key_timehandler, (void *)0, hz);
4575#endif /* IPSEC_DEBUG2 */
4576}
4577
4578u_long
4579key_random()
4580{
4581	u_long value;
4582
4583	key_randomfill(&value, sizeof(value));
4584	return value;
4585}
4586
4587void
4588key_randomfill(p, l)
4589	void *p;
4590	size_t l;
4591{
4592	size_t n;
4593	u_long v;
4594	static int warn = 1;
4595
4596	n = 0;
4597	n = (size_t)read_random(p, (u_int)l);
4598	/* last resort */
4599	while (n < l) {
4600		v = random();
4601		bcopy(&v, (u_int8_t *)p + n,
4602		    l - n < sizeof(v) ? l - n : sizeof(v));
4603		n += sizeof(v);
4604
4605		if (warn) {
4606			printf("WARNING: pseudo-random number generator "
4607			    "used for IPsec processing\n");
4608			warn = 0;
4609		}
4610	}
4611}
4612
4613/*
4614 * map SADB_SATYPE_* to IPPROTO_*.
4615 * if satype == SADB_SATYPE then satype is mapped to ~0.
4616 * OUT:
4617 *	0: invalid satype.
4618 */
4619static u_int16_t
4620key_satype2proto(u_int8_t satype)
4621{
4622	switch (satype) {
4623	case SADB_SATYPE_UNSPEC:
4624		return IPSEC_PROTO_ANY;
4625	case SADB_SATYPE_AH:
4626		return IPPROTO_AH;
4627	case SADB_SATYPE_ESP:
4628		return IPPROTO_ESP;
4629	case SADB_X_SATYPE_IPCOMP:
4630		return IPPROTO_IPCOMP;
4631	case SADB_X_SATYPE_TCPSIGNATURE:
4632		return IPPROTO_TCP;
4633	default:
4634		return 0;
4635	}
4636	/* NOTREACHED */
4637}
4638
4639/*
4640 * map IPPROTO_* to SADB_SATYPE_*
4641 * OUT:
4642 *	0: invalid protocol type.
4643 */
4644static u_int8_t
4645key_proto2satype(u_int16_t proto)
4646{
4647	switch (proto) {
4648	case IPPROTO_AH:
4649		return SADB_SATYPE_AH;
4650	case IPPROTO_ESP:
4651		return SADB_SATYPE_ESP;
4652	case IPPROTO_IPCOMP:
4653		return SADB_X_SATYPE_IPCOMP;
4654	case IPPROTO_TCP:
4655		return SADB_X_SATYPE_TCPSIGNATURE;
4656	default:
4657		return 0;
4658	}
4659	/* NOTREACHED */
4660}
4661
4662/* %%% PF_KEY */
4663/*
4664 * SADB_GETSPI processing is to receive
4665 *	<base, (SA2), src address, dst address, (SPI range)>
4666 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4667 * tree with the status of LARVAL, and send
4668 *	<base, SA(*), address(SD)>
4669 * to the IKMPd.
4670 *
4671 * IN:	mhp: pointer to the pointer to each header.
4672 * OUT:	NULL if fail.
4673 *	other if success, return pointer to the message to send.
4674 */
4675static int
4676key_getspi(so, m, mhp)
4677	struct socket *so;
4678	struct mbuf *m;
4679	const struct sadb_msghdr *mhp;
4680{
4681	INIT_VNET_IPSEC(curvnet);
4682	struct sadb_address *src0, *dst0;
4683	struct secasindex saidx;
4684	struct secashead *newsah;
4685	struct secasvar *newsav;
4686	u_int8_t proto;
4687	u_int32_t spi;
4688	u_int8_t mode;
4689	u_int32_t reqid;
4690	int error;
4691
4692	IPSEC_ASSERT(so != NULL, ("null socket"));
4693	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4694	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4695	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4696
4697	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4698	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4699		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4700			__func__));
4701		return key_senderror(so, m, EINVAL);
4702	}
4703	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4704	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4705		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4706			__func__));
4707		return key_senderror(so, m, EINVAL);
4708	}
4709	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4710		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4711		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4712	} else {
4713		mode = IPSEC_MODE_ANY;
4714		reqid = 0;
4715	}
4716
4717	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4718	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4719
4720	/* map satype to proto */
4721	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4722		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4723			__func__));
4724		return key_senderror(so, m, EINVAL);
4725	}
4726
4727	/*
4728	 * Make sure the port numbers are zero.
4729	 * In case of NAT-T we will update them later if needed.
4730	 */
4731	switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4732	case AF_INET:
4733		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4734		    sizeof(struct sockaddr_in))
4735			return key_senderror(so, m, EINVAL);
4736		((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4737		break;
4738	case AF_INET6:
4739		if (((struct sockaddr *)(src0 + 1))->sa_len !=
4740		    sizeof(struct sockaddr_in6))
4741			return key_senderror(so, m, EINVAL);
4742		((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4743		break;
4744	default:
4745		; /*???*/
4746	}
4747	switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4748	case AF_INET:
4749		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4750		    sizeof(struct sockaddr_in))
4751			return key_senderror(so, m, EINVAL);
4752		((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4753		break;
4754	case AF_INET6:
4755		if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4756		    sizeof(struct sockaddr_in6))
4757			return key_senderror(so, m, EINVAL);
4758		((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4759		break;
4760	default:
4761		; /*???*/
4762	}
4763
4764	/* XXX boundary check against sa_len */
4765	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4766
4767#ifdef IPSEC_NAT_T
4768	/*
4769	 * Handle NAT-T info if present.
4770	 * We made sure the port numbers are zero above, so we do
4771	 * not have to worry in case we do not update them.
4772	 */
4773	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4774		ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4775	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4776		ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4777
4778	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4779	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4780	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4781		struct sadb_x_nat_t_type *type;
4782		struct sadb_x_nat_t_port *sport, *dport;
4783
4784		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4785		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4786		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4787			ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4788			    "passed.\n", __func__));
4789			return key_senderror(so, m, EINVAL);
4790		}
4791
4792		sport = (struct sadb_x_nat_t_port *)
4793		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4794		dport = (struct sadb_x_nat_t_port *)
4795		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4796
4797		if (sport)
4798			KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4799		if (dport)
4800			KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4801	}
4802#endif
4803
4804	/* SPI allocation */
4805	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4806	                       &saidx);
4807	if (spi == 0)
4808		return key_senderror(so, m, EINVAL);
4809
4810	/* get a SA index */
4811	if ((newsah = key_getsah(&saidx)) == NULL) {
4812		/* create a new SA index */
4813		if ((newsah = key_newsah(&saidx)) == NULL) {
4814			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4815			return key_senderror(so, m, ENOBUFS);
4816		}
4817	}
4818
4819	/* get a new SA */
4820	/* XXX rewrite */
4821	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4822	if (newsav == NULL) {
4823		/* XXX don't free new SA index allocated in above. */
4824		return key_senderror(so, m, error);
4825	}
4826
4827	/* set spi */
4828	newsav->spi = htonl(spi);
4829
4830	/* delete the entry in acqtree */
4831	if (mhp->msg->sadb_msg_seq != 0) {
4832		struct secacq *acq;
4833		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4834			/* reset counter in order to deletion by timehandler. */
4835			acq->created = time_second;
4836			acq->count = 0;
4837		}
4838    	}
4839
4840    {
4841	struct mbuf *n, *nn;
4842	struct sadb_sa *m_sa;
4843	struct sadb_msg *newmsg;
4844	int off, len;
4845
4846	/* create new sadb_msg to reply. */
4847	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4848	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4849
4850	MGETHDR(n, M_DONTWAIT, MT_DATA);
4851	if (len > MHLEN) {
4852		MCLGET(n, M_DONTWAIT);
4853		if ((n->m_flags & M_EXT) == 0) {
4854			m_freem(n);
4855			n = NULL;
4856		}
4857	}
4858	if (!n)
4859		return key_senderror(so, m, ENOBUFS);
4860
4861	n->m_len = len;
4862	n->m_next = NULL;
4863	off = 0;
4864
4865	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4866	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4867
4868	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4869	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4870	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4871	m_sa->sadb_sa_spi = htonl(spi);
4872	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4873
4874	IPSEC_ASSERT(off == len,
4875		("length inconsistency (off %u len %u)", off, len));
4876
4877	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4878	    SADB_EXT_ADDRESS_DST);
4879	if (!n->m_next) {
4880		m_freem(n);
4881		return key_senderror(so, m, ENOBUFS);
4882	}
4883
4884	if (n->m_len < sizeof(struct sadb_msg)) {
4885		n = m_pullup(n, sizeof(struct sadb_msg));
4886		if (n == NULL)
4887			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4888	}
4889
4890	n->m_pkthdr.len = 0;
4891	for (nn = n; nn; nn = nn->m_next)
4892		n->m_pkthdr.len += nn->m_len;
4893
4894	newmsg = mtod(n, struct sadb_msg *);
4895	newmsg->sadb_msg_seq = newsav->seq;
4896	newmsg->sadb_msg_errno = 0;
4897	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4898
4899	m_freem(m);
4900	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4901    }
4902}
4903
4904/*
4905 * allocating new SPI
4906 * called by key_getspi().
4907 * OUT:
4908 *	0:	failure.
4909 *	others: success.
4910 */
4911static u_int32_t
4912key_do_getnewspi(spirange, saidx)
4913	struct sadb_spirange *spirange;
4914	struct secasindex *saidx;
4915{
4916	INIT_VNET_IPSEC(curvnet);
4917	u_int32_t newspi;
4918	u_int32_t min, max;
4919	int count = V_key_spi_trycnt;
4920
4921	/* set spi range to allocate */
4922	if (spirange != NULL) {
4923		min = spirange->sadb_spirange_min;
4924		max = spirange->sadb_spirange_max;
4925	} else {
4926		min = V_key_spi_minval;
4927		max = V_key_spi_maxval;
4928	}
4929	/* IPCOMP needs 2-byte SPI */
4930	if (saidx->proto == IPPROTO_IPCOMP) {
4931		u_int32_t t;
4932		if (min >= 0x10000)
4933			min = 0xffff;
4934		if (max >= 0x10000)
4935			max = 0xffff;
4936		if (min > max) {
4937			t = min; min = max; max = t;
4938		}
4939	}
4940
4941	if (min == max) {
4942		if (key_checkspidup(saidx, min) != NULL) {
4943			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4944				__func__, min));
4945			return 0;
4946		}
4947
4948		count--; /* taking one cost. */
4949		newspi = min;
4950
4951	} else {
4952
4953		/* init SPI */
4954		newspi = 0;
4955
4956		/* when requesting to allocate spi ranged */
4957		while (count--) {
4958			/* generate pseudo-random SPI value ranged. */
4959			newspi = min + (key_random() % (max - min + 1));
4960
4961			if (key_checkspidup(saidx, newspi) == NULL)
4962				break;
4963		}
4964
4965		if (count == 0 || newspi == 0) {
4966			ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4967				__func__));
4968			return 0;
4969		}
4970	}
4971
4972	/* statistics */
4973	keystat.getspi_count =
4974		(keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4975
4976	return newspi;
4977}
4978
4979/*
4980 * SADB_UPDATE processing
4981 * receive
4982 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4983 *       key(AE), (identity(SD),) (sensitivity)>
4984 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4985 * and send
4986 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4987 *       (identity(SD),) (sensitivity)>
4988 * to the ikmpd.
4989 *
4990 * m will always be freed.
4991 */
4992static int
4993key_update(so, m, mhp)
4994	struct socket *so;
4995	struct mbuf *m;
4996	const struct sadb_msghdr *mhp;
4997{
4998	INIT_VNET_IPSEC(curvnet);
4999	struct sadb_sa *sa0;
5000	struct sadb_address *src0, *dst0;
5001#ifdef IPSEC_NAT_T
5002	struct sadb_x_nat_t_type *type;
5003	struct sadb_x_nat_t_port *sport, *dport;
5004	struct sadb_address *iaddr, *raddr;
5005	struct sadb_x_nat_t_frag *frag;
5006#endif
5007	struct secasindex saidx;
5008	struct secashead *sah;
5009	struct secasvar *sav;
5010	u_int16_t proto;
5011	u_int8_t mode;
5012	u_int32_t reqid;
5013	int error;
5014
5015	IPSEC_ASSERT(so != NULL, ("null socket"));
5016	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5017	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5018	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5019
5020	/* map satype to proto */
5021	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5022		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5023			__func__));
5024		return key_senderror(so, m, EINVAL);
5025	}
5026
5027	if (mhp->ext[SADB_EXT_SA] == NULL ||
5028	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5029	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5030	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5031	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5032	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5033	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5034	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5035	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5036	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5037	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5038		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5039			__func__));
5040		return key_senderror(so, m, EINVAL);
5041	}
5042	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5043	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5044	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5045		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5046			__func__));
5047		return key_senderror(so, m, EINVAL);
5048	}
5049	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5050		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5051		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5052	} else {
5053		mode = IPSEC_MODE_ANY;
5054		reqid = 0;
5055	}
5056	/* XXX boundary checking for other extensions */
5057
5058	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5059	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5060	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5061
5062	/* XXX boundary check against sa_len */
5063	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5064
5065	/*
5066	 * Make sure the port numbers are zero.
5067	 * In case of NAT-T we will update them later if needed.
5068	 */
5069	KEY_PORTTOSADDR(&saidx.src, 0);
5070	KEY_PORTTOSADDR(&saidx.dst, 0);
5071
5072#ifdef IPSEC_NAT_T
5073	/*
5074	 * Handle NAT-T info if present.
5075	 */
5076	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5077	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5078	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5079
5080		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5081		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5082		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5083			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5084			    __func__));
5085			return key_senderror(so, m, EINVAL);
5086		}
5087
5088		type = (struct sadb_x_nat_t_type *)
5089		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5090		sport = (struct sadb_x_nat_t_port *)
5091		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5092		dport = (struct sadb_x_nat_t_port *)
5093		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5094	} else {
5095		type = 0;
5096		sport = dport = 0;
5097	}
5098	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5099	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5100		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5101		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5102			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5103			    __func__));
5104			return key_senderror(so, m, EINVAL);
5105		}
5106		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5107		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5108		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5109	} else {
5110		iaddr = raddr = NULL;
5111	}
5112	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5113		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5114			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5115			    __func__));
5116			return key_senderror(so, m, EINVAL);
5117		}
5118		frag = (struct sadb_x_nat_t_frag *)
5119		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5120	} else {
5121		frag = 0;
5122	}
5123#endif
5124
5125	/* get a SA header */
5126	if ((sah = key_getsah(&saidx)) == NULL) {
5127		ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
5128		return key_senderror(so, m, ENOENT);
5129	}
5130
5131	/* set spidx if there */
5132	/* XXX rewrite */
5133	error = key_setident(sah, m, mhp);
5134	if (error)
5135		return key_senderror(so, m, error);
5136
5137	/* find a SA with sequence number. */
5138#ifdef IPSEC_DOSEQCHECK
5139	if (mhp->msg->sadb_msg_seq != 0
5140	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
5141		ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
5142			"exists.\n", __func__, mhp->msg->sadb_msg_seq));
5143		return key_senderror(so, m, ENOENT);
5144	}
5145#else
5146	SAHTREE_LOCK();
5147	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5148	SAHTREE_UNLOCK();
5149	if (sav == NULL) {
5150		ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
5151			__func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5152		return key_senderror(so, m, EINVAL);
5153	}
5154#endif
5155
5156	/* validity check */
5157	if (sav->sah->saidx.proto != proto) {
5158		ipseclog((LOG_DEBUG, "%s: protocol mismatched "
5159			"(DB=%u param=%u)\n", __func__,
5160			sav->sah->saidx.proto, proto));
5161		return key_senderror(so, m, EINVAL);
5162	}
5163#ifdef IPSEC_DOSEQCHECK
5164	if (sav->spi != sa0->sadb_sa_spi) {
5165		ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
5166		    __func__,
5167		    (u_int32_t)ntohl(sav->spi),
5168		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5169		return key_senderror(so, m, EINVAL);
5170	}
5171#endif
5172	if (sav->pid != mhp->msg->sadb_msg_pid) {
5173		ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
5174		    __func__, sav->pid, mhp->msg->sadb_msg_pid));
5175		return key_senderror(so, m, EINVAL);
5176	}
5177
5178	/* copy sav values */
5179	error = key_setsaval(sav, m, mhp);
5180	if (error) {
5181		KEY_FREESAV(&sav);
5182		return key_senderror(so, m, error);
5183	}
5184
5185	/* check SA values to be mature. */
5186	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5187		KEY_FREESAV(&sav);
5188		return key_senderror(so, m, 0);
5189	}
5190
5191#ifdef IPSEC_NAT_T
5192	/*
5193	 * Handle more NAT-T info if present,
5194	 * now that we have a sav to fill.
5195	 */
5196	if (type)
5197		sav->natt_type = type->sadb_x_nat_t_type_type;
5198
5199	if (sport)
5200		KEY_PORTTOSADDR(&sav->sah->saidx.src,
5201		    sport->sadb_x_nat_t_port_port);
5202	if (dport)
5203		KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5204		    dport->sadb_x_nat_t_port_port);
5205
5206#if 0
5207	/*
5208	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5209	 * We should actually check for a minimum MTU here, if we
5210	 * want to support it in ip_output.
5211	 */
5212	if (frag)
5213		sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5214#endif
5215#endif
5216
5217    {
5218	struct mbuf *n;
5219
5220	/* set msg buf from mhp */
5221	n = key_getmsgbuf_x1(m, mhp);
5222	if (n == NULL) {
5223		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5224		return key_senderror(so, m, ENOBUFS);
5225	}
5226
5227	m_freem(m);
5228	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5229    }
5230}
5231
5232/*
5233 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5234 * only called by key_update().
5235 * OUT:
5236 *	NULL	: not found
5237 *	others	: found, pointer to a SA.
5238 */
5239#ifdef IPSEC_DOSEQCHECK
5240static struct secasvar *
5241key_getsavbyseq(sah, seq)
5242	struct secashead *sah;
5243	u_int32_t seq;
5244{
5245	struct secasvar *sav;
5246	u_int state;
5247
5248	state = SADB_SASTATE_LARVAL;
5249
5250	/* search SAD with sequence number ? */
5251	LIST_FOREACH(sav, &sah->savtree[state], chain) {
5252
5253		KEY_CHKSASTATE(state, sav->state, __func__);
5254
5255		if (sav->seq == seq) {
5256			sa_addref(sav);
5257			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5258				printf("DP %s cause refcnt++:%d SA:%p\n",
5259					__func__, sav->refcnt, sav));
5260			return sav;
5261		}
5262	}
5263
5264	return NULL;
5265}
5266#endif
5267
5268/*
5269 * SADB_ADD processing
5270 * add an entry to SA database, when received
5271 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5272 *       key(AE), (identity(SD),) (sensitivity)>
5273 * from the ikmpd,
5274 * and send
5275 *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5276 *       (identity(SD),) (sensitivity)>
5277 * to the ikmpd.
5278 *
5279 * IGNORE identity and sensitivity messages.
5280 *
5281 * m will always be freed.
5282 */
5283static int
5284key_add(so, m, mhp)
5285	struct socket *so;
5286	struct mbuf *m;
5287	const struct sadb_msghdr *mhp;
5288{
5289	INIT_VNET_IPSEC(curvnet);
5290	struct sadb_sa *sa0;
5291	struct sadb_address *src0, *dst0;
5292#ifdef IPSEC_NAT_T
5293	struct sadb_x_nat_t_type *type;
5294	struct sadb_address *iaddr, *raddr;
5295	struct sadb_x_nat_t_frag *frag;
5296#endif
5297	struct secasindex saidx;
5298	struct secashead *newsah;
5299	struct secasvar *newsav;
5300	u_int16_t proto;
5301	u_int8_t mode;
5302	u_int32_t reqid;
5303	int error;
5304
5305	IPSEC_ASSERT(so != NULL, ("null socket"));
5306	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5307	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5308	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5309
5310	/* map satype to proto */
5311	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5312		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5313			__func__));
5314		return key_senderror(so, m, EINVAL);
5315	}
5316
5317	if (mhp->ext[SADB_EXT_SA] == NULL ||
5318	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5319	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5320	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5321	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5322	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5323	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5324	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5325	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5326	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5327	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5328		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5329			__func__));
5330		return key_senderror(so, m, EINVAL);
5331	}
5332	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5333	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5334	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5335		/* XXX need more */
5336		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5337			__func__));
5338		return key_senderror(so, m, EINVAL);
5339	}
5340	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5341		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5342		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5343	} else {
5344		mode = IPSEC_MODE_ANY;
5345		reqid = 0;
5346	}
5347
5348	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5349	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5350	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5351
5352	/* XXX boundary check against sa_len */
5353	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5354
5355	/*
5356	 * Make sure the port numbers are zero.
5357	 * In case of NAT-T we will update them later if needed.
5358	 */
5359	KEY_PORTTOSADDR(&saidx.src, 0);
5360	KEY_PORTTOSADDR(&saidx.dst, 0);
5361
5362#ifdef IPSEC_NAT_T
5363	/*
5364	 * Handle NAT-T info if present.
5365	 */
5366	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5367	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5368	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5369		struct sadb_x_nat_t_port *sport, *dport;
5370
5371		if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5372		    mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5373		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5374			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5375			    __func__));
5376			return key_senderror(so, m, EINVAL);
5377		}
5378
5379		type = (struct sadb_x_nat_t_type *)
5380		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5381		sport = (struct sadb_x_nat_t_port *)
5382		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5383		dport = (struct sadb_x_nat_t_port *)
5384		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5385
5386		if (sport)
5387			KEY_PORTTOSADDR(&saidx.src,
5388			    sport->sadb_x_nat_t_port_port);
5389		if (dport)
5390			KEY_PORTTOSADDR(&saidx.dst,
5391			    dport->sadb_x_nat_t_port_port);
5392	} else {
5393		type = 0;
5394	}
5395	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5396	    mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5397		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5398		    mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5399			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5400			    __func__));
5401			return key_senderror(so, m, EINVAL);
5402		}
5403		iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5404		raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5405		ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5406	} else {
5407		iaddr = raddr = NULL;
5408	}
5409	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5410		if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5411			ipseclog((LOG_DEBUG, "%s: invalid message\n",
5412			    __func__));
5413			return key_senderror(so, m, EINVAL);
5414		}
5415		frag = (struct sadb_x_nat_t_frag *)
5416		    mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5417	} else {
5418		frag = 0;
5419	}
5420#endif
5421
5422	/* get a SA header */
5423	if ((newsah = key_getsah(&saidx)) == NULL) {
5424		/* create a new SA header */
5425		if ((newsah = key_newsah(&saidx)) == NULL) {
5426			ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5427			return key_senderror(so, m, ENOBUFS);
5428		}
5429	}
5430
5431	/* set spidx if there */
5432	/* XXX rewrite */
5433	error = key_setident(newsah, m, mhp);
5434	if (error) {
5435		return key_senderror(so, m, error);
5436	}
5437
5438	/* create new SA entry. */
5439	/* We can create new SA only if SPI is differenct. */
5440	SAHTREE_LOCK();
5441	newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5442	SAHTREE_UNLOCK();
5443	if (newsav != NULL) {
5444		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5445		return key_senderror(so, m, EEXIST);
5446	}
5447	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5448	if (newsav == NULL) {
5449		return key_senderror(so, m, error);
5450	}
5451
5452	/* check SA values to be mature. */
5453	if ((error = key_mature(newsav)) != 0) {
5454		KEY_FREESAV(&newsav);
5455		return key_senderror(so, m, error);
5456	}
5457
5458#ifdef IPSEC_NAT_T
5459	/*
5460	 * Handle more NAT-T info if present,
5461	 * now that we have a sav to fill.
5462	 */
5463	if (type)
5464		newsav->natt_type = type->sadb_x_nat_t_type_type;
5465
5466#if 0
5467	/*
5468	 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5469	 * We should actually check for a minimum MTU here, if we
5470	 * want to support it in ip_output.
5471	 */
5472	if (frag)
5473		newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5474#endif
5475#endif
5476
5477	/*
5478	 * don't call key_freesav() here, as we would like to keep the SA
5479	 * in the database on success.
5480	 */
5481
5482    {
5483	struct mbuf *n;
5484
5485	/* set msg buf from mhp */
5486	n = key_getmsgbuf_x1(m, mhp);
5487	if (n == NULL) {
5488		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5489		return key_senderror(so, m, ENOBUFS);
5490	}
5491
5492	m_freem(m);
5493	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5494    }
5495}
5496
5497/* m is retained */
5498static int
5499key_setident(sah, m, mhp)
5500	struct secashead *sah;
5501	struct mbuf *m;
5502	const struct sadb_msghdr *mhp;
5503{
5504	INIT_VNET_IPSEC(curvnet);
5505	const struct sadb_ident *idsrc, *iddst;
5506	int idsrclen, iddstlen;
5507
5508	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5509	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5510	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5511	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5512
5513	/* don't make buffer if not there */
5514	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5515	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5516		sah->idents = NULL;
5517		sah->identd = NULL;
5518		return 0;
5519	}
5520
5521	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5522	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5523		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5524		return EINVAL;
5525	}
5526
5527	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5528	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5529	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5530	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5531
5532	/* validity check */
5533	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5534		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5535		return EINVAL;
5536	}
5537
5538	switch (idsrc->sadb_ident_type) {
5539	case SADB_IDENTTYPE_PREFIX:
5540	case SADB_IDENTTYPE_FQDN:
5541	case SADB_IDENTTYPE_USERFQDN:
5542	default:
5543		/* XXX do nothing */
5544		sah->idents = NULL;
5545		sah->identd = NULL;
5546	 	return 0;
5547	}
5548
5549	/* make structure */
5550	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5551	if (sah->idents == NULL) {
5552		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5553		return ENOBUFS;
5554	}
5555	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5556	if (sah->identd == NULL) {
5557		free(sah->idents, M_IPSEC_MISC);
5558		sah->idents = NULL;
5559		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5560		return ENOBUFS;
5561	}
5562	sah->idents->type = idsrc->sadb_ident_type;
5563	sah->idents->id = idsrc->sadb_ident_id;
5564
5565	sah->identd->type = iddst->sadb_ident_type;
5566	sah->identd->id = iddst->sadb_ident_id;
5567
5568	return 0;
5569}
5570
5571/*
5572 * m will not be freed on return.
5573 * it is caller's responsibility to free the result.
5574 */
5575static struct mbuf *
5576key_getmsgbuf_x1(m, mhp)
5577	struct mbuf *m;
5578	const struct sadb_msghdr *mhp;
5579{
5580	struct mbuf *n;
5581
5582	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5583	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5584	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5585
5586	/* create new sadb_msg to reply. */
5587	n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5588	    SADB_EXT_SA, SADB_X_EXT_SA2,
5589	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5590	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5591	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5592	if (!n)
5593		return NULL;
5594
5595	if (n->m_len < sizeof(struct sadb_msg)) {
5596		n = m_pullup(n, sizeof(struct sadb_msg));
5597		if (n == NULL)
5598			return NULL;
5599	}
5600	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5601	mtod(n, struct sadb_msg *)->sadb_msg_len =
5602	    PFKEY_UNIT64(n->m_pkthdr.len);
5603
5604	return n;
5605}
5606
5607static int key_delete_all __P((struct socket *, struct mbuf *,
5608	const struct sadb_msghdr *, u_int16_t));
5609
5610/*
5611 * SADB_DELETE processing
5612 * receive
5613 *   <base, SA(*), address(SD)>
5614 * from the ikmpd, and set SADB_SASTATE_DEAD,
5615 * and send,
5616 *   <base, SA(*), address(SD)>
5617 * to the ikmpd.
5618 *
5619 * m will always be freed.
5620 */
5621static int
5622key_delete(so, m, mhp)
5623	struct socket *so;
5624	struct mbuf *m;
5625	const struct sadb_msghdr *mhp;
5626{
5627	INIT_VNET_IPSEC(curvnet);
5628	struct sadb_sa *sa0;
5629	struct sadb_address *src0, *dst0;
5630	struct secasindex saidx;
5631	struct secashead *sah;
5632	struct secasvar *sav = NULL;
5633	u_int16_t proto;
5634
5635	IPSEC_ASSERT(so != NULL, ("null socket"));
5636	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5637	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5638	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5639
5640	/* map satype to proto */
5641	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5642		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5643			__func__));
5644		return key_senderror(so, m, EINVAL);
5645	}
5646
5647	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5648	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5649		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5650			__func__));
5651		return key_senderror(so, m, EINVAL);
5652	}
5653
5654	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5655	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5656		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5657			__func__));
5658		return key_senderror(so, m, EINVAL);
5659	}
5660
5661	if (mhp->ext[SADB_EXT_SA] == NULL) {
5662		/*
5663		 * Caller wants us to delete all non-LARVAL SAs
5664		 * that match the src/dst.  This is used during
5665		 * IKE INITIAL-CONTACT.
5666		 */
5667		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5668		return key_delete_all(so, m, mhp, proto);
5669	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5670		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5671			__func__));
5672		return key_senderror(so, m, EINVAL);
5673	}
5674
5675	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5676	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5677	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5678
5679	/* XXX boundary check against sa_len */
5680	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5681
5682	/*
5683	 * Make sure the port numbers are zero.
5684	 * In case of NAT-T we will update them later if needed.
5685	 */
5686	KEY_PORTTOSADDR(&saidx.src, 0);
5687	KEY_PORTTOSADDR(&saidx.dst, 0);
5688
5689#ifdef IPSEC_NAT_T
5690	/*
5691	 * Handle NAT-T info if present.
5692	 */
5693	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5694	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5695		struct sadb_x_nat_t_port *sport, *dport;
5696
5697		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5698		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5699			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5700			    __func__));
5701			return key_senderror(so, m, EINVAL);
5702		}
5703
5704		sport = (struct sadb_x_nat_t_port *)
5705		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5706		dport = (struct sadb_x_nat_t_port *)
5707		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5708
5709		if (sport)
5710			KEY_PORTTOSADDR(&saidx.src,
5711			    sport->sadb_x_nat_t_port_port);
5712		if (dport)
5713			KEY_PORTTOSADDR(&saidx.dst,
5714			    dport->sadb_x_nat_t_port_port);
5715	}
5716#endif
5717
5718	/* get a SA header */
5719	SAHTREE_LOCK();
5720	LIST_FOREACH(sah, &V_sahtree, chain) {
5721		if (sah->state == SADB_SASTATE_DEAD)
5722			continue;
5723		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5724			continue;
5725
5726		/* get a SA with SPI. */
5727		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5728		if (sav)
5729			break;
5730	}
5731	if (sah == NULL) {
5732		SAHTREE_UNLOCK();
5733		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5734		return key_senderror(so, m, ENOENT);
5735	}
5736
5737	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5738	SAHTREE_UNLOCK();
5739	KEY_FREESAV(&sav);
5740
5741    {
5742	struct mbuf *n;
5743	struct sadb_msg *newmsg;
5744
5745	/* create new sadb_msg to reply. */
5746	/* XXX-BZ NAT-T extensions? */
5747	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5748	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5749	if (!n)
5750		return key_senderror(so, m, ENOBUFS);
5751
5752	if (n->m_len < sizeof(struct sadb_msg)) {
5753		n = m_pullup(n, sizeof(struct sadb_msg));
5754		if (n == NULL)
5755			return key_senderror(so, m, ENOBUFS);
5756	}
5757	newmsg = mtod(n, struct sadb_msg *);
5758	newmsg->sadb_msg_errno = 0;
5759	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5760
5761	m_freem(m);
5762	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5763    }
5764}
5765
5766/*
5767 * delete all SAs for src/dst.  Called from key_delete().
5768 */
5769static int
5770key_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5771    u_int16_t proto)
5772{
5773	INIT_VNET_IPSEC(curvnet);
5774	struct sadb_address *src0, *dst0;
5775	struct secasindex saidx;
5776	struct secashead *sah;
5777	struct secasvar *sav, *nextsav;
5778	u_int stateidx, state;
5779
5780	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5781	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5782
5783	/* XXX boundary check against sa_len */
5784	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5785
5786	/*
5787	 * Make sure the port numbers are zero.
5788	 * In case of NAT-T we will update them later if needed.
5789	 */
5790	KEY_PORTTOSADDR(&saidx.src, 0);
5791	KEY_PORTTOSADDR(&saidx.dst, 0);
5792
5793#ifdef IPSEC_NAT_T
5794	/*
5795	 * Handle NAT-T info if present.
5796	 */
5797
5798	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5799	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5800		struct sadb_x_nat_t_port *sport, *dport;
5801
5802		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5803		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5804			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5805			    __func__));
5806			return key_senderror(so, m, EINVAL);
5807		}
5808
5809		sport = (struct sadb_x_nat_t_port *)
5810		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5811		dport = (struct sadb_x_nat_t_port *)
5812		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5813
5814		if (sport)
5815			KEY_PORTTOSADDR(&saidx.src,
5816			    sport->sadb_x_nat_t_port_port);
5817		if (dport)
5818			KEY_PORTTOSADDR(&saidx.dst,
5819			    dport->sadb_x_nat_t_port_port);
5820	}
5821#endif
5822
5823	SAHTREE_LOCK();
5824	LIST_FOREACH(sah, &V_sahtree, chain) {
5825		if (sah->state == SADB_SASTATE_DEAD)
5826			continue;
5827		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5828			continue;
5829
5830		/* Delete all non-LARVAL SAs. */
5831		for (stateidx = 0;
5832		     stateidx < _ARRAYLEN(saorder_state_alive);
5833		     stateidx++) {
5834			state = saorder_state_alive[stateidx];
5835			if (state == SADB_SASTATE_LARVAL)
5836				continue;
5837			for (sav = LIST_FIRST(&sah->savtree[state]);
5838			     sav != NULL; sav = nextsav) {
5839				nextsav = LIST_NEXT(sav, chain);
5840				/* sanity check */
5841				if (sav->state != state) {
5842					ipseclog((LOG_DEBUG, "%s: invalid "
5843						"sav->state (queue %d SA %d)\n",
5844						__func__, state, sav->state));
5845					continue;
5846				}
5847
5848				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5849				KEY_FREESAV(&sav);
5850			}
5851		}
5852	}
5853	SAHTREE_UNLOCK();
5854    {
5855	struct mbuf *n;
5856	struct sadb_msg *newmsg;
5857
5858	/* create new sadb_msg to reply. */
5859	/* XXX-BZ NAT-T extensions? */
5860	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5861	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5862	if (!n)
5863		return key_senderror(so, m, ENOBUFS);
5864
5865	if (n->m_len < sizeof(struct sadb_msg)) {
5866		n = m_pullup(n, sizeof(struct sadb_msg));
5867		if (n == NULL)
5868			return key_senderror(so, m, ENOBUFS);
5869	}
5870	newmsg = mtod(n, struct sadb_msg *);
5871	newmsg->sadb_msg_errno = 0;
5872	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5873
5874	m_freem(m);
5875	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5876    }
5877}
5878
5879/*
5880 * SADB_GET processing
5881 * receive
5882 *   <base, SA(*), address(SD)>
5883 * from the ikmpd, and get a SP and a SA to respond,
5884 * and send,
5885 *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5886 *       (identity(SD),) (sensitivity)>
5887 * to the ikmpd.
5888 *
5889 * m will always be freed.
5890 */
5891static int
5892key_get(so, m, mhp)
5893	struct socket *so;
5894	struct mbuf *m;
5895	const struct sadb_msghdr *mhp;
5896{
5897	INIT_VNET_IPSEC(curvnet);
5898	struct sadb_sa *sa0;
5899	struct sadb_address *src0, *dst0;
5900	struct secasindex saidx;
5901	struct secashead *sah;
5902	struct secasvar *sav = NULL;
5903	u_int16_t proto;
5904
5905	IPSEC_ASSERT(so != NULL, ("null socket"));
5906	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5907	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5908	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5909
5910	/* map satype to proto */
5911	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5912		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5913			__func__));
5914		return key_senderror(so, m, EINVAL);
5915	}
5916
5917	if (mhp->ext[SADB_EXT_SA] == NULL ||
5918	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5919	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5920		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5921			__func__));
5922		return key_senderror(so, m, EINVAL);
5923	}
5924	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5925	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5926	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5927		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5928			__func__));
5929		return key_senderror(so, m, EINVAL);
5930	}
5931
5932	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5933	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5934	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5935
5936	/* XXX boundary check against sa_len */
5937	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5938
5939	/*
5940	 * Make sure the port numbers are zero.
5941	 * In case of NAT-T we will update them later if needed.
5942	 */
5943	KEY_PORTTOSADDR(&saidx.src, 0);
5944	KEY_PORTTOSADDR(&saidx.dst, 0);
5945
5946#ifdef IPSEC_NAT_T
5947	/*
5948	 * Handle NAT-T info if present.
5949	 */
5950
5951	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5952	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5953		struct sadb_x_nat_t_port *sport, *dport;
5954
5955		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5956		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5957			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5958			    __func__));
5959			return key_senderror(so, m, EINVAL);
5960		}
5961
5962		sport = (struct sadb_x_nat_t_port *)
5963		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5964		dport = (struct sadb_x_nat_t_port *)
5965		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5966
5967		if (sport)
5968			KEY_PORTTOSADDR(&saidx.src,
5969			    sport->sadb_x_nat_t_port_port);
5970		if (dport)
5971			KEY_PORTTOSADDR(&saidx.dst,
5972			    dport->sadb_x_nat_t_port_port);
5973	}
5974#endif
5975
5976	/* get a SA header */
5977	SAHTREE_LOCK();
5978	LIST_FOREACH(sah, &V_sahtree, chain) {
5979		if (sah->state == SADB_SASTATE_DEAD)
5980			continue;
5981		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5982			continue;
5983
5984		/* get a SA with SPI. */
5985		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5986		if (sav)
5987			break;
5988	}
5989	SAHTREE_UNLOCK();
5990	if (sah == NULL) {
5991		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5992		return key_senderror(so, m, ENOENT);
5993	}
5994
5995    {
5996	struct mbuf *n;
5997	u_int8_t satype;
5998
5999	/* map proto to satype */
6000	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6001		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
6002			__func__));
6003		return key_senderror(so, m, EINVAL);
6004	}
6005
6006	/* create new sadb_msg to reply. */
6007	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
6008	    mhp->msg->sadb_msg_pid);
6009	if (!n)
6010		return key_senderror(so, m, ENOBUFS);
6011
6012	m_freem(m);
6013	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6014    }
6015}
6016
6017/* XXX make it sysctl-configurable? */
6018static void
6019key_getcomb_setlifetime(comb)
6020	struct sadb_comb *comb;
6021{
6022
6023	comb->sadb_comb_soft_allocations = 1;
6024	comb->sadb_comb_hard_allocations = 1;
6025	comb->sadb_comb_soft_bytes = 0;
6026	comb->sadb_comb_hard_bytes = 0;
6027	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
6028	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
6029	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
6030	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
6031}
6032
6033/*
6034 * XXX reorder combinations by preference
6035 * XXX no idea if the user wants ESP authentication or not
6036 */
6037static struct mbuf *
6038key_getcomb_esp()
6039{
6040	INIT_VNET_IPSEC(curvnet);
6041	struct sadb_comb *comb;
6042	struct enc_xform *algo;
6043	struct mbuf *result = NULL, *m, *n;
6044	int encmin;
6045	int i, off, o;
6046	int totlen;
6047	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6048
6049	m = NULL;
6050	for (i = 1; i <= SADB_EALG_MAX; i++) {
6051		algo = esp_algorithm_lookup(i);
6052		if (algo == NULL)
6053			continue;
6054
6055		/* discard algorithms with key size smaller than system min */
6056		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6057			continue;
6058		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6059			encmin = V_ipsec_esp_keymin;
6060		else
6061			encmin = _BITS(algo->minkey);
6062
6063		if (V_ipsec_esp_auth)
6064			m = key_getcomb_ah();
6065		else {
6066			IPSEC_ASSERT(l <= MLEN,
6067				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6068			MGET(m, M_DONTWAIT, MT_DATA);
6069			if (m) {
6070				M_ALIGN(m, l);
6071				m->m_len = l;
6072				m->m_next = NULL;
6073				bzero(mtod(m, caddr_t), m->m_len);
6074			}
6075		}
6076		if (!m)
6077			goto fail;
6078
6079		totlen = 0;
6080		for (n = m; n; n = n->m_next)
6081			totlen += n->m_len;
6082		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6083
6084		for (off = 0; off < totlen; off += l) {
6085			n = m_pulldown(m, off, l, &o);
6086			if (!n) {
6087				/* m is already freed */
6088				goto fail;
6089			}
6090			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6091			bzero(comb, sizeof(*comb));
6092			key_getcomb_setlifetime(comb);
6093			comb->sadb_comb_encrypt = i;
6094			comb->sadb_comb_encrypt_minbits = encmin;
6095			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6096		}
6097
6098		if (!result)
6099			result = m;
6100		else
6101			m_cat(result, m);
6102	}
6103
6104	return result;
6105
6106 fail:
6107	if (result)
6108		m_freem(result);
6109	return NULL;
6110}
6111
6112static void
6113key_getsizes_ah(
6114	const struct auth_hash *ah,
6115	int alg,
6116	u_int16_t* min,
6117	u_int16_t* max)
6118{
6119	INIT_VNET_IPSEC(curvnet);
6120
6121	*min = *max = ah->keysize;
6122	if (ah->keysize == 0) {
6123		/*
6124		 * Transform takes arbitrary key size but algorithm
6125		 * key size is restricted.  Enforce this here.
6126		 */
6127		switch (alg) {
6128		case SADB_X_AALG_MD5:	*min = *max = 16; break;
6129		case SADB_X_AALG_SHA:	*min = *max = 20; break;
6130		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
6131		default:
6132			DPRINTF(("%s: unknown AH algorithm %u\n",
6133				__func__, alg));
6134			break;
6135		}
6136	}
6137}
6138
6139/*
6140 * XXX reorder combinations by preference
6141 */
6142static struct mbuf *
6143key_getcomb_ah()
6144{
6145	INIT_VNET_IPSEC(curvnet);
6146	struct sadb_comb *comb;
6147	struct auth_hash *algo;
6148	struct mbuf *m;
6149	u_int16_t minkeysize, maxkeysize;
6150	int i;
6151	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6152
6153	m = NULL;
6154	for (i = 1; i <= SADB_AALG_MAX; i++) {
6155#if 1
6156		/* we prefer HMAC algorithms, not old algorithms */
6157		if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
6158			continue;
6159#endif
6160		algo = ah_algorithm_lookup(i);
6161		if (!algo)
6162			continue;
6163		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6164		/* discard algorithms with key size smaller than system min */
6165		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6166			continue;
6167
6168		if (!m) {
6169			IPSEC_ASSERT(l <= MLEN,
6170				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6171			MGET(m, M_DONTWAIT, MT_DATA);
6172			if (m) {
6173				M_ALIGN(m, l);
6174				m->m_len = l;
6175				m->m_next = NULL;
6176			}
6177		} else
6178			M_PREPEND(m, l, M_DONTWAIT);
6179		if (!m)
6180			return NULL;
6181
6182		comb = mtod(m, struct sadb_comb *);
6183		bzero(comb, sizeof(*comb));
6184		key_getcomb_setlifetime(comb);
6185		comb->sadb_comb_auth = i;
6186		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6187		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6188	}
6189
6190	return m;
6191}
6192
6193/*
6194 * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6195 * XXX reorder combinations by preference
6196 */
6197static struct mbuf *
6198key_getcomb_ipcomp()
6199{
6200	struct sadb_comb *comb;
6201	struct comp_algo *algo;
6202	struct mbuf *m;
6203	int i;
6204	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6205
6206	m = NULL;
6207	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6208		algo = ipcomp_algorithm_lookup(i);
6209		if (!algo)
6210			continue;
6211
6212		if (!m) {
6213			IPSEC_ASSERT(l <= MLEN,
6214				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6215			MGET(m, M_DONTWAIT, MT_DATA);
6216			if (m) {
6217				M_ALIGN(m, l);
6218				m->m_len = l;
6219				m->m_next = NULL;
6220			}
6221		} else
6222			M_PREPEND(m, l, M_DONTWAIT);
6223		if (!m)
6224			return NULL;
6225
6226		comb = mtod(m, struct sadb_comb *);
6227		bzero(comb, sizeof(*comb));
6228		key_getcomb_setlifetime(comb);
6229		comb->sadb_comb_encrypt = i;
6230		/* what should we set into sadb_comb_*_{min,max}bits? */
6231	}
6232
6233	return m;
6234}
6235
6236/*
6237 * XXX no way to pass mode (transport/tunnel) to userland
6238 * XXX replay checking?
6239 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6240 */
6241static struct mbuf *
6242key_getprop(saidx)
6243	const struct secasindex *saidx;
6244{
6245	struct sadb_prop *prop;
6246	struct mbuf *m, *n;
6247	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6248	int totlen;
6249
6250	switch (saidx->proto)  {
6251	case IPPROTO_ESP:
6252		m = key_getcomb_esp();
6253		break;
6254	case IPPROTO_AH:
6255		m = key_getcomb_ah();
6256		break;
6257	case IPPROTO_IPCOMP:
6258		m = key_getcomb_ipcomp();
6259		break;
6260	default:
6261		return NULL;
6262	}
6263
6264	if (!m)
6265		return NULL;
6266	M_PREPEND(m, l, M_DONTWAIT);
6267	if (!m)
6268		return NULL;
6269
6270	totlen = 0;
6271	for (n = m; n; n = n->m_next)
6272		totlen += n->m_len;
6273
6274	prop = mtod(m, struct sadb_prop *);
6275	bzero(prop, sizeof(*prop));
6276	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6277	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6278	prop->sadb_prop_replay = 32;	/* XXX */
6279
6280	return m;
6281}
6282
6283/*
6284 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6285 * send
6286 *   <base, SA, address(SD), (address(P)), x_policy,
6287 *       (identity(SD),) (sensitivity,) proposal>
6288 * to KMD, and expect to receive
6289 *   <base> with SADB_ACQUIRE if error occured,
6290 * or
6291 *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6292 * from KMD by PF_KEY.
6293 *
6294 * XXX x_policy is outside of RFC2367 (KAME extension).
6295 * XXX sensitivity is not supported.
6296 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6297 * see comment for key_getcomb_ipcomp().
6298 *
6299 * OUT:
6300 *    0     : succeed
6301 *    others: error number
6302 */
6303static int
6304key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6305{
6306	INIT_VNET_IPSEC(curvnet);
6307	struct mbuf *result = NULL, *m;
6308	struct secacq *newacq;
6309	u_int8_t satype;
6310	int error = -1;
6311	u_int32_t seq;
6312
6313	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6314	satype = key_proto2satype(saidx->proto);
6315	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6316
6317	/*
6318	 * We never do anything about acquirng SA.  There is anather
6319	 * solution that kernel blocks to send SADB_ACQUIRE message until
6320	 * getting something message from IKEd.  In later case, to be
6321	 * managed with ACQUIRING list.
6322	 */
6323	/* Get an entry to check whether sending message or not. */
6324	if ((newacq = key_getacq(saidx)) != NULL) {
6325		if (V_key_blockacq_count < newacq->count) {
6326			/* reset counter and do send message. */
6327			newacq->count = 0;
6328		} else {
6329			/* increment counter and do nothing. */
6330			newacq->count++;
6331			return 0;
6332		}
6333	} else {
6334		/* make new entry for blocking to send SADB_ACQUIRE. */
6335		if ((newacq = key_newacq(saidx)) == NULL)
6336			return ENOBUFS;
6337	}
6338
6339
6340	seq = newacq->seq;
6341	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6342	if (!m) {
6343		error = ENOBUFS;
6344		goto fail;
6345	}
6346	result = m;
6347
6348	/*
6349	 * No SADB_X_EXT_NAT_T_* here: we do not know
6350	 * anything related to NAT-T at this time.
6351	 */
6352
6353	/* set sadb_address for saidx's. */
6354	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6355	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6356	if (!m) {
6357		error = ENOBUFS;
6358		goto fail;
6359	}
6360	m_cat(result, m);
6361
6362	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6363	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6364	if (!m) {
6365		error = ENOBUFS;
6366		goto fail;
6367	}
6368	m_cat(result, m);
6369
6370	/* XXX proxy address (optional) */
6371
6372	/* set sadb_x_policy */
6373	if (sp) {
6374		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6375		if (!m) {
6376			error = ENOBUFS;
6377			goto fail;
6378		}
6379		m_cat(result, m);
6380	}
6381
6382	/* XXX identity (optional) */
6383#if 0
6384	if (idexttype && fqdn) {
6385		/* create identity extension (FQDN) */
6386		struct sadb_ident *id;
6387		int fqdnlen;
6388
6389		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
6390		id = (struct sadb_ident *)p;
6391		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6392		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6393		id->sadb_ident_exttype = idexttype;
6394		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6395		bcopy(fqdn, id + 1, fqdnlen);
6396		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6397	}
6398
6399	if (idexttype) {
6400		/* create identity extension (USERFQDN) */
6401		struct sadb_ident *id;
6402		int userfqdnlen;
6403
6404		if (userfqdn) {
6405			/* +1 for terminating-NUL */
6406			userfqdnlen = strlen(userfqdn) + 1;
6407		} else
6408			userfqdnlen = 0;
6409		id = (struct sadb_ident *)p;
6410		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6411		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6412		id->sadb_ident_exttype = idexttype;
6413		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6414		/* XXX is it correct? */
6415		if (curproc && curproc->p_cred)
6416			id->sadb_ident_id = curproc->p_cred->p_ruid;
6417		if (userfqdn && userfqdnlen)
6418			bcopy(userfqdn, id + 1, userfqdnlen);
6419		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6420	}
6421#endif
6422
6423	/* XXX sensitivity (optional) */
6424
6425	/* create proposal/combination extension */
6426	m = key_getprop(saidx);
6427#if 0
6428	/*
6429	 * spec conformant: always attach proposal/combination extension,
6430	 * the problem is that we have no way to attach it for ipcomp,
6431	 * due to the way sadb_comb is declared in RFC2367.
6432	 */
6433	if (!m) {
6434		error = ENOBUFS;
6435		goto fail;
6436	}
6437	m_cat(result, m);
6438#else
6439	/*
6440	 * outside of spec; make proposal/combination extension optional.
6441	 */
6442	if (m)
6443		m_cat(result, m);
6444#endif
6445
6446	if ((result->m_flags & M_PKTHDR) == 0) {
6447		error = EINVAL;
6448		goto fail;
6449	}
6450
6451	if (result->m_len < sizeof(struct sadb_msg)) {
6452		result = m_pullup(result, sizeof(struct sadb_msg));
6453		if (result == NULL) {
6454			error = ENOBUFS;
6455			goto fail;
6456		}
6457	}
6458
6459	result->m_pkthdr.len = 0;
6460	for (m = result; m; m = m->m_next)
6461		result->m_pkthdr.len += m->m_len;
6462
6463	mtod(result, struct sadb_msg *)->sadb_msg_len =
6464	    PFKEY_UNIT64(result->m_pkthdr.len);
6465
6466	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6467
6468 fail:
6469	if (result)
6470		m_freem(result);
6471	return error;
6472}
6473
6474static struct secacq *
6475key_newacq(const struct secasindex *saidx)
6476{
6477	INIT_VNET_IPSEC(curvnet);
6478	struct secacq *newacq;
6479
6480	/* get new entry */
6481	newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6482	if (newacq == NULL) {
6483		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6484		return NULL;
6485	}
6486
6487	/* copy secindex */
6488	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6489	newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6490	newacq->created = time_second;
6491	newacq->count = 0;
6492
6493	/* add to acqtree */
6494	ACQ_LOCK();
6495	LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6496	ACQ_UNLOCK();
6497
6498	return newacq;
6499}
6500
6501static struct secacq *
6502key_getacq(const struct secasindex *saidx)
6503{
6504	INIT_VNET_IPSEC(curvnet);
6505	struct secacq *acq;
6506
6507	ACQ_LOCK();
6508	LIST_FOREACH(acq, &V_acqtree, chain) {
6509		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6510			break;
6511	}
6512	ACQ_UNLOCK();
6513
6514	return acq;
6515}
6516
6517static struct secacq *
6518key_getacqbyseq(seq)
6519	u_int32_t seq;
6520{
6521	INIT_VNET_IPSEC(curvnet);
6522	struct secacq *acq;
6523
6524	ACQ_LOCK();
6525	LIST_FOREACH(acq, &V_acqtree, chain) {
6526		if (acq->seq == seq)
6527			break;
6528	}
6529	ACQ_UNLOCK();
6530
6531	return acq;
6532}
6533
6534static struct secspacq *
6535key_newspacq(spidx)
6536	struct secpolicyindex *spidx;
6537{
6538	INIT_VNET_IPSEC(curvnet);
6539	struct secspacq *acq;
6540
6541	/* get new entry */
6542	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6543	if (acq == NULL) {
6544		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6545		return NULL;
6546	}
6547
6548	/* copy secindex */
6549	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6550	acq->created = time_second;
6551	acq->count = 0;
6552
6553	/* add to spacqtree */
6554	SPACQ_LOCK();
6555	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6556	SPACQ_UNLOCK();
6557
6558	return acq;
6559}
6560
6561static struct secspacq *
6562key_getspacq(spidx)
6563	struct secpolicyindex *spidx;
6564{
6565	INIT_VNET_IPSEC(curvnet);
6566	struct secspacq *acq;
6567
6568	SPACQ_LOCK();
6569	LIST_FOREACH(acq, &V_spacqtree, chain) {
6570		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6571			/* NB: return holding spacq_lock */
6572			return acq;
6573		}
6574	}
6575	SPACQ_UNLOCK();
6576
6577	return NULL;
6578}
6579
6580/*
6581 * SADB_ACQUIRE processing,
6582 * in first situation, is receiving
6583 *   <base>
6584 * from the ikmpd, and clear sequence of its secasvar entry.
6585 *
6586 * In second situation, is receiving
6587 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6588 * from a user land process, and return
6589 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6590 * to the socket.
6591 *
6592 * m will always be freed.
6593 */
6594static int
6595key_acquire2(so, m, mhp)
6596	struct socket *so;
6597	struct mbuf *m;
6598	const struct sadb_msghdr *mhp;
6599{
6600	INIT_VNET_IPSEC(curvnet);
6601	const struct sadb_address *src0, *dst0;
6602	struct secasindex saidx;
6603	struct secashead *sah;
6604	u_int16_t proto;
6605	int error;
6606
6607	IPSEC_ASSERT(so != NULL, ("null socket"));
6608	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6609	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6610	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6611
6612	/*
6613	 * Error message from KMd.
6614	 * We assume that if error was occured in IKEd, the length of PFKEY
6615	 * message is equal to the size of sadb_msg structure.
6616	 * We do not raise error even if error occured in this function.
6617	 */
6618	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6619		struct secacq *acq;
6620
6621		/* check sequence number */
6622		if (mhp->msg->sadb_msg_seq == 0) {
6623			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6624				"number.\n", __func__));
6625			m_freem(m);
6626			return 0;
6627		}
6628
6629		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6630			/*
6631			 * the specified larval SA is already gone, or we got
6632			 * a bogus sequence number.  we can silently ignore it.
6633			 */
6634			m_freem(m);
6635			return 0;
6636		}
6637
6638		/* reset acq counter in order to deletion by timehander. */
6639		acq->created = time_second;
6640		acq->count = 0;
6641		m_freem(m);
6642		return 0;
6643	}
6644
6645	/*
6646	 * This message is from user land.
6647	 */
6648
6649	/* map satype to proto */
6650	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6651		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6652			__func__));
6653		return key_senderror(so, m, EINVAL);
6654	}
6655
6656	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6657	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6658	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6659		/* error */
6660		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6661			__func__));
6662		return key_senderror(so, m, EINVAL);
6663	}
6664	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6665	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6666	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6667		/* error */
6668		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6669			__func__));
6670		return key_senderror(so, m, EINVAL);
6671	}
6672
6673	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6674	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6675
6676	/* XXX boundary check against sa_len */
6677	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6678
6679	/*
6680	 * Make sure the port numbers are zero.
6681	 * In case of NAT-T we will update them later if needed.
6682	 */
6683	KEY_PORTTOSADDR(&saidx.src, 0);
6684	KEY_PORTTOSADDR(&saidx.dst, 0);
6685
6686#ifndef IPSEC_NAT_T
6687	/*
6688	 * Handle NAT-T info if present.
6689	 */
6690
6691	if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6692	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6693		struct sadb_x_nat_t_port *sport, *dport;
6694
6695		if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6696		    mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6697			ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6698			    __func__));
6699			return key_senderror(so, m, EINVAL);
6700		}
6701
6702		sport = (struct sadb_x_nat_t_port *)
6703		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6704		dport = (struct sadb_x_nat_t_port *)
6705		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6706
6707		if (sport)
6708			KEY_PORTTOSADDR(&saidx.src,
6709			    sport->sadb_x_nat_t_port_port);
6710		if (dport)
6711			KEY_PORTTOSADDR(&saidx.dst,
6712			    dport->sadb_x_nat_t_port_port);
6713	}
6714#endif
6715
6716	/* get a SA index */
6717	SAHTREE_LOCK();
6718	LIST_FOREACH(sah, &V_sahtree, chain) {
6719		if (sah->state == SADB_SASTATE_DEAD)
6720			continue;
6721		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6722			break;
6723	}
6724	SAHTREE_UNLOCK();
6725	if (sah != NULL) {
6726		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6727		return key_senderror(so, m, EEXIST);
6728	}
6729
6730	error = key_acquire(&saidx, NULL);
6731	if (error != 0) {
6732		ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6733			__func__, mhp->msg->sadb_msg_errno));
6734		return key_senderror(so, m, error);
6735	}
6736
6737	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6738}
6739
6740/*
6741 * SADB_REGISTER processing.
6742 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6743 * receive
6744 *   <base>
6745 * from the ikmpd, and register a socket to send PF_KEY messages,
6746 * and send
6747 *   <base, supported>
6748 * to KMD by PF_KEY.
6749 * If socket is detached, must free from regnode.
6750 *
6751 * m will always be freed.
6752 */
6753static int
6754key_register(so, m, mhp)
6755	struct socket *so;
6756	struct mbuf *m;
6757	const struct sadb_msghdr *mhp;
6758{
6759	INIT_VNET_IPSEC(curvnet);
6760	struct secreg *reg, *newreg = 0;
6761
6762	IPSEC_ASSERT(so != NULL, ("null socket"));
6763	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6764	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6765	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6766
6767	/* check for invalid register message */
6768	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6769		return key_senderror(so, m, EINVAL);
6770
6771	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6772	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6773		goto setmsg;
6774
6775	/* check whether existing or not */
6776	REGTREE_LOCK();
6777	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6778		if (reg->so == so) {
6779			REGTREE_UNLOCK();
6780			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6781				__func__));
6782			return key_senderror(so, m, EEXIST);
6783		}
6784	}
6785
6786	/* create regnode */
6787	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6788	if (newreg == NULL) {
6789		REGTREE_UNLOCK();
6790		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6791		return key_senderror(so, m, ENOBUFS);
6792	}
6793
6794	newreg->so = so;
6795	((struct keycb *)sotorawcb(so))->kp_registered++;
6796
6797	/* add regnode to regtree. */
6798	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6799	REGTREE_UNLOCK();
6800
6801  setmsg:
6802    {
6803	struct mbuf *n;
6804	struct sadb_msg *newmsg;
6805	struct sadb_supported *sup;
6806	u_int len, alen, elen;
6807	int off;
6808	int i;
6809	struct sadb_alg *alg;
6810
6811	/* create new sadb_msg to reply. */
6812	alen = 0;
6813	for (i = 1; i <= SADB_AALG_MAX; i++) {
6814		if (ah_algorithm_lookup(i))
6815			alen += sizeof(struct sadb_alg);
6816	}
6817	if (alen)
6818		alen += sizeof(struct sadb_supported);
6819	elen = 0;
6820	for (i = 1; i <= SADB_EALG_MAX; i++) {
6821		if (esp_algorithm_lookup(i))
6822			elen += sizeof(struct sadb_alg);
6823	}
6824	if (elen)
6825		elen += sizeof(struct sadb_supported);
6826
6827	len = sizeof(struct sadb_msg) + alen + elen;
6828
6829	if (len > MCLBYTES)
6830		return key_senderror(so, m, ENOBUFS);
6831
6832	MGETHDR(n, M_DONTWAIT, MT_DATA);
6833	if (len > MHLEN) {
6834		MCLGET(n, M_DONTWAIT);
6835		if ((n->m_flags & M_EXT) == 0) {
6836			m_freem(n);
6837			n = NULL;
6838		}
6839	}
6840	if (!n)
6841		return key_senderror(so, m, ENOBUFS);
6842
6843	n->m_pkthdr.len = n->m_len = len;
6844	n->m_next = NULL;
6845	off = 0;
6846
6847	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6848	newmsg = mtod(n, struct sadb_msg *);
6849	newmsg->sadb_msg_errno = 0;
6850	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6851	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6852
6853	/* for authentication algorithm */
6854	if (alen) {
6855		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6856		sup->sadb_supported_len = PFKEY_UNIT64(alen);
6857		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6858		off += PFKEY_ALIGN8(sizeof(*sup));
6859
6860		for (i = 1; i <= SADB_AALG_MAX; i++) {
6861			struct auth_hash *aalgo;
6862			u_int16_t minkeysize, maxkeysize;
6863
6864			aalgo = ah_algorithm_lookup(i);
6865			if (!aalgo)
6866				continue;
6867			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6868			alg->sadb_alg_id = i;
6869			alg->sadb_alg_ivlen = 0;
6870			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6871			alg->sadb_alg_minbits = _BITS(minkeysize);
6872			alg->sadb_alg_maxbits = _BITS(maxkeysize);
6873			off += PFKEY_ALIGN8(sizeof(*alg));
6874		}
6875	}
6876
6877	/* for encryption algorithm */
6878	if (elen) {
6879		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6880		sup->sadb_supported_len = PFKEY_UNIT64(elen);
6881		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6882		off += PFKEY_ALIGN8(sizeof(*sup));
6883
6884		for (i = 1; i <= SADB_EALG_MAX; i++) {
6885			struct enc_xform *ealgo;
6886
6887			ealgo = esp_algorithm_lookup(i);
6888			if (!ealgo)
6889				continue;
6890			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6891			alg->sadb_alg_id = i;
6892			alg->sadb_alg_ivlen = ealgo->blocksize;
6893			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6894			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6895			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6896		}
6897	}
6898
6899	IPSEC_ASSERT(off == len,
6900		("length assumption failed (off %u len %u)", off, len));
6901
6902	m_freem(m);
6903	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6904    }
6905}
6906
6907/*
6908 * free secreg entry registered.
6909 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6910 */
6911void
6912key_freereg(struct socket *so)
6913{
6914	INIT_VNET_IPSEC(curvnet);
6915	struct secreg *reg;
6916	int i;
6917
6918	IPSEC_ASSERT(so != NULL, ("NULL so"));
6919
6920	/*
6921	 * check whether existing or not.
6922	 * check all type of SA, because there is a potential that
6923	 * one socket is registered to multiple type of SA.
6924	 */
6925	REGTREE_LOCK();
6926	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6927		LIST_FOREACH(reg, &V_regtree[i], chain) {
6928			if (reg->so == so && __LIST_CHAINED(reg)) {
6929				LIST_REMOVE(reg, chain);
6930				free(reg, M_IPSEC_SAR);
6931				break;
6932			}
6933		}
6934	}
6935	REGTREE_UNLOCK();
6936}
6937
6938/*
6939 * SADB_EXPIRE processing
6940 * send
6941 *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6942 * to KMD by PF_KEY.
6943 * NOTE: We send only soft lifetime extension.
6944 *
6945 * OUT:	0	: succeed
6946 *	others	: error number
6947 */
6948static int
6949key_expire(struct secasvar *sav)
6950{
6951	int s;
6952	int satype;
6953	struct mbuf *result = NULL, *m;
6954	int len;
6955	int error = -1;
6956	struct sadb_lifetime *lt;
6957
6958	/* XXX: Why do we lock ? */
6959	s = splnet();	/*called from softclock()*/
6960
6961	IPSEC_ASSERT (sav != NULL, ("null sav"));
6962	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6963
6964	/* set msg header */
6965	satype = key_proto2satype(sav->sah->saidx.proto);
6966	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6967	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6968	if (!m) {
6969		error = ENOBUFS;
6970		goto fail;
6971	}
6972	result = m;
6973
6974	/* create SA extension */
6975	m = key_setsadbsa(sav);
6976	if (!m) {
6977		error = ENOBUFS;
6978		goto fail;
6979	}
6980	m_cat(result, m);
6981
6982	/* create SA extension */
6983	m = key_setsadbxsa2(sav->sah->saidx.mode,
6984			sav->replay ? sav->replay->count : 0,
6985			sav->sah->saidx.reqid);
6986	if (!m) {
6987		error = ENOBUFS;
6988		goto fail;
6989	}
6990	m_cat(result, m);
6991
6992	/* create lifetime extension (current and soft) */
6993	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6994	m = key_alloc_mbuf(len);
6995	if (!m || m->m_next) {	/*XXX*/
6996		if (m)
6997			m_freem(m);
6998		error = ENOBUFS;
6999		goto fail;
7000	}
7001	bzero(mtod(m, caddr_t), len);
7002	lt = mtod(m, struct sadb_lifetime *);
7003	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7004	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
7005	lt->sadb_lifetime_allocations = sav->lft_c->allocations;
7006	lt->sadb_lifetime_bytes = sav->lft_c->bytes;
7007	lt->sadb_lifetime_addtime = sav->lft_c->addtime;
7008	lt->sadb_lifetime_usetime = sav->lft_c->usetime;
7009	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
7010	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7011	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
7012	lt->sadb_lifetime_allocations = sav->lft_s->allocations;
7013	lt->sadb_lifetime_bytes = sav->lft_s->bytes;
7014	lt->sadb_lifetime_addtime = sav->lft_s->addtime;
7015	lt->sadb_lifetime_usetime = sav->lft_s->usetime;
7016	m_cat(result, m);
7017
7018	/* set sadb_address for source */
7019	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
7020	    &sav->sah->saidx.src.sa,
7021	    FULLMASK, IPSEC_ULPROTO_ANY);
7022	if (!m) {
7023		error = ENOBUFS;
7024		goto fail;
7025	}
7026	m_cat(result, m);
7027
7028	/* set sadb_address for destination */
7029	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
7030	    &sav->sah->saidx.dst.sa,
7031	    FULLMASK, IPSEC_ULPROTO_ANY);
7032	if (!m) {
7033		error = ENOBUFS;
7034		goto fail;
7035	}
7036	m_cat(result, m);
7037
7038	/*
7039	 * XXX-BZ Handle NAT-T extensions here.
7040	 */
7041
7042	if ((result->m_flags & M_PKTHDR) == 0) {
7043		error = EINVAL;
7044		goto fail;
7045	}
7046
7047	if (result->m_len < sizeof(struct sadb_msg)) {
7048		result = m_pullup(result, sizeof(struct sadb_msg));
7049		if (result == NULL) {
7050			error = ENOBUFS;
7051			goto fail;
7052		}
7053	}
7054
7055	result->m_pkthdr.len = 0;
7056	for (m = result; m; m = m->m_next)
7057		result->m_pkthdr.len += m->m_len;
7058
7059	mtod(result, struct sadb_msg *)->sadb_msg_len =
7060	    PFKEY_UNIT64(result->m_pkthdr.len);
7061
7062	splx(s);
7063	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7064
7065 fail:
7066	if (result)
7067		m_freem(result);
7068	splx(s);
7069	return error;
7070}
7071
7072/*
7073 * SADB_FLUSH processing
7074 * receive
7075 *   <base>
7076 * from the ikmpd, and free all entries in secastree.
7077 * and send,
7078 *   <base>
7079 * to the ikmpd.
7080 * NOTE: to do is only marking SADB_SASTATE_DEAD.
7081 *
7082 * m will always be freed.
7083 */
7084static int
7085key_flush(so, m, mhp)
7086	struct socket *so;
7087	struct mbuf *m;
7088	const struct sadb_msghdr *mhp;
7089{
7090	INIT_VNET_IPSEC(curvnet);
7091	struct sadb_msg *newmsg;
7092	struct secashead *sah, *nextsah;
7093	struct secasvar *sav, *nextsav;
7094	u_int16_t proto;
7095	u_int8_t state;
7096	u_int stateidx;
7097
7098	IPSEC_ASSERT(so != NULL, ("null socket"));
7099	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7100	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7101
7102	/* map satype to proto */
7103	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7104		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7105			__func__));
7106		return key_senderror(so, m, EINVAL);
7107	}
7108
7109	/* no SATYPE specified, i.e. flushing all SA. */
7110	SAHTREE_LOCK();
7111	for (sah = LIST_FIRST(&V_sahtree);
7112	     sah != NULL;
7113	     sah = nextsah) {
7114		nextsah = LIST_NEXT(sah, chain);
7115
7116		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7117		 && proto != sah->saidx.proto)
7118			continue;
7119
7120		for (stateidx = 0;
7121		     stateidx < _ARRAYLEN(saorder_state_alive);
7122		     stateidx++) {
7123			state = saorder_state_any[stateidx];
7124			for (sav = LIST_FIRST(&sah->savtree[state]);
7125			     sav != NULL;
7126			     sav = nextsav) {
7127
7128				nextsav = LIST_NEXT(sav, chain);
7129
7130				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7131				KEY_FREESAV(&sav);
7132			}
7133		}
7134
7135		sah->state = SADB_SASTATE_DEAD;
7136	}
7137	SAHTREE_UNLOCK();
7138
7139	if (m->m_len < sizeof(struct sadb_msg) ||
7140	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7141		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7142		return key_senderror(so, m, ENOBUFS);
7143	}
7144
7145	if (m->m_next)
7146		m_freem(m->m_next);
7147	m->m_next = NULL;
7148	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7149	newmsg = mtod(m, struct sadb_msg *);
7150	newmsg->sadb_msg_errno = 0;
7151	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7152
7153	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7154}
7155
7156/*
7157 * SADB_DUMP processing
7158 * dump all entries including status of DEAD in SAD.
7159 * receive
7160 *   <base>
7161 * from the ikmpd, and dump all secasvar leaves
7162 * and send,
7163 *   <base> .....
7164 * to the ikmpd.
7165 *
7166 * m will always be freed.
7167 */
7168static int
7169key_dump(so, m, mhp)
7170	struct socket *so;
7171	struct mbuf *m;
7172	const struct sadb_msghdr *mhp;
7173{
7174	INIT_VNET_IPSEC(curvnet);
7175	struct secashead *sah;
7176	struct secasvar *sav;
7177	u_int16_t proto;
7178	u_int stateidx;
7179	u_int8_t satype;
7180	u_int8_t state;
7181	int cnt;
7182	struct sadb_msg *newmsg;
7183	struct mbuf *n;
7184
7185	IPSEC_ASSERT(so != NULL, ("null socket"));
7186	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7187	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7188	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7189
7190	/* map satype to proto */
7191	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7192		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7193			__func__));
7194		return key_senderror(so, m, EINVAL);
7195	}
7196
7197	/* count sav entries to be sent to the userland. */
7198	cnt = 0;
7199	SAHTREE_LOCK();
7200	LIST_FOREACH(sah, &V_sahtree, chain) {
7201		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7202		 && proto != sah->saidx.proto)
7203			continue;
7204
7205		for (stateidx = 0;
7206		     stateidx < _ARRAYLEN(saorder_state_any);
7207		     stateidx++) {
7208			state = saorder_state_any[stateidx];
7209			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7210				cnt++;
7211			}
7212		}
7213	}
7214
7215	if (cnt == 0) {
7216		SAHTREE_UNLOCK();
7217		return key_senderror(so, m, ENOENT);
7218	}
7219
7220	/* send this to the userland, one at a time. */
7221	newmsg = NULL;
7222	LIST_FOREACH(sah, &V_sahtree, chain) {
7223		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7224		 && proto != sah->saidx.proto)
7225			continue;
7226
7227		/* map proto to satype */
7228		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7229			SAHTREE_UNLOCK();
7230			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7231				"SAD.\n", __func__));
7232			return key_senderror(so, m, EINVAL);
7233		}
7234
7235		for (stateidx = 0;
7236		     stateidx < _ARRAYLEN(saorder_state_any);
7237		     stateidx++) {
7238			state = saorder_state_any[stateidx];
7239			LIST_FOREACH(sav, &sah->savtree[state], chain) {
7240				n = key_setdumpsa(sav, SADB_DUMP, satype,
7241				    --cnt, mhp->msg->sadb_msg_pid);
7242				if (!n) {
7243					SAHTREE_UNLOCK();
7244					return key_senderror(so, m, ENOBUFS);
7245				}
7246				key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7247			}
7248		}
7249	}
7250	SAHTREE_UNLOCK();
7251
7252	m_freem(m);
7253	return 0;
7254}
7255
7256/*
7257 * SADB_X_PROMISC processing
7258 *
7259 * m will always be freed.
7260 */
7261static int
7262key_promisc(so, m, mhp)
7263	struct socket *so;
7264	struct mbuf *m;
7265	const struct sadb_msghdr *mhp;
7266{
7267	int olen;
7268
7269	IPSEC_ASSERT(so != NULL, ("null socket"));
7270	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7271	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7272	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7273
7274	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7275
7276	if (olen < sizeof(struct sadb_msg)) {
7277#if 1
7278		return key_senderror(so, m, EINVAL);
7279#else
7280		m_freem(m);
7281		return 0;
7282#endif
7283	} else if (olen == sizeof(struct sadb_msg)) {
7284		/* enable/disable promisc mode */
7285		struct keycb *kp;
7286
7287		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7288			return key_senderror(so, m, EINVAL);
7289		mhp->msg->sadb_msg_errno = 0;
7290		switch (mhp->msg->sadb_msg_satype) {
7291		case 0:
7292		case 1:
7293			kp->kp_promisc = mhp->msg->sadb_msg_satype;
7294			break;
7295		default:
7296			return key_senderror(so, m, EINVAL);
7297		}
7298
7299		/* send the original message back to everyone */
7300		mhp->msg->sadb_msg_errno = 0;
7301		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7302	} else {
7303		/* send packet as is */
7304
7305		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7306
7307		/* TODO: if sadb_msg_seq is specified, send to specific pid */
7308		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7309	}
7310}
7311
7312static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
7313		const struct sadb_msghdr *)) = {
7314	NULL,		/* SADB_RESERVED */
7315	key_getspi,	/* SADB_GETSPI */
7316	key_update,	/* SADB_UPDATE */
7317	key_add,	/* SADB_ADD */
7318	key_delete,	/* SADB_DELETE */
7319	key_get,	/* SADB_GET */
7320	key_acquire2,	/* SADB_ACQUIRE */
7321	key_register,	/* SADB_REGISTER */
7322	NULL,		/* SADB_EXPIRE */
7323	key_flush,	/* SADB_FLUSH */
7324	key_dump,	/* SADB_DUMP */
7325	key_promisc,	/* SADB_X_PROMISC */
7326	NULL,		/* SADB_X_PCHANGE */
7327	key_spdadd,	/* SADB_X_SPDUPDATE */
7328	key_spdadd,	/* SADB_X_SPDADD */
7329	key_spddelete,	/* SADB_X_SPDDELETE */
7330	key_spdget,	/* SADB_X_SPDGET */
7331	NULL,		/* SADB_X_SPDACQUIRE */
7332	key_spddump,	/* SADB_X_SPDDUMP */
7333	key_spdflush,	/* SADB_X_SPDFLUSH */
7334	key_spdadd,	/* SADB_X_SPDSETIDX */
7335	NULL,		/* SADB_X_SPDEXPIRE */
7336	key_spddelete2,	/* SADB_X_SPDDELETE2 */
7337};
7338
7339/*
7340 * parse sadb_msg buffer to process PFKEYv2,
7341 * and create a data to response if needed.
7342 * I think to be dealed with mbuf directly.
7343 * IN:
7344 *     msgp  : pointer to pointer to a received buffer pulluped.
7345 *             This is rewrited to response.
7346 *     so    : pointer to socket.
7347 * OUT:
7348 *    length for buffer to send to user process.
7349 */
7350int
7351key_parse(m, so)
7352	struct mbuf *m;
7353	struct socket *so;
7354{
7355	INIT_VNET_IPSEC(curvnet);
7356	struct sadb_msg *msg;
7357	struct sadb_msghdr mh;
7358	u_int orglen;
7359	int error;
7360	int target;
7361
7362	IPSEC_ASSERT(so != NULL, ("null socket"));
7363	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7364
7365#if 0	/*kdebug_sadb assumes msg in linear buffer*/
7366	KEYDEBUG(KEYDEBUG_KEY_DUMP,
7367		ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7368		kdebug_sadb(msg));
7369#endif
7370
7371	if (m->m_len < sizeof(struct sadb_msg)) {
7372		m = m_pullup(m, sizeof(struct sadb_msg));
7373		if (!m)
7374			return ENOBUFS;
7375	}
7376	msg = mtod(m, struct sadb_msg *);
7377	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7378	target = KEY_SENDUP_ONE;
7379
7380	if ((m->m_flags & M_PKTHDR) == 0 ||
7381	    m->m_pkthdr.len != m->m_pkthdr.len) {
7382		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7383		V_pfkeystat.out_invlen++;
7384		error = EINVAL;
7385		goto senderror;
7386	}
7387
7388	if (msg->sadb_msg_version != PF_KEY_V2) {
7389		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7390		    __func__, msg->sadb_msg_version));
7391		V_pfkeystat.out_invver++;
7392		error = EINVAL;
7393		goto senderror;
7394	}
7395
7396	if (msg->sadb_msg_type > SADB_MAX) {
7397		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7398		    __func__, msg->sadb_msg_type));
7399		V_pfkeystat.out_invmsgtype++;
7400		error = EINVAL;
7401		goto senderror;
7402	}
7403
7404	/* for old-fashioned code - should be nuked */
7405	if (m->m_pkthdr.len > MCLBYTES) {
7406		m_freem(m);
7407		return ENOBUFS;
7408	}
7409	if (m->m_next) {
7410		struct mbuf *n;
7411
7412		MGETHDR(n, M_DONTWAIT, MT_DATA);
7413		if (n && m->m_pkthdr.len > MHLEN) {
7414			MCLGET(n, M_DONTWAIT);
7415			if ((n->m_flags & M_EXT) == 0) {
7416				m_free(n);
7417				n = NULL;
7418			}
7419		}
7420		if (!n) {
7421			m_freem(m);
7422			return ENOBUFS;
7423		}
7424		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7425		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7426		n->m_next = NULL;
7427		m_freem(m);
7428		m = n;
7429	}
7430
7431	/* align the mbuf chain so that extensions are in contiguous region. */
7432	error = key_align(m, &mh);
7433	if (error)
7434		return error;
7435
7436	msg = mh.msg;
7437
7438	/* check SA type */
7439	switch (msg->sadb_msg_satype) {
7440	case SADB_SATYPE_UNSPEC:
7441		switch (msg->sadb_msg_type) {
7442		case SADB_GETSPI:
7443		case SADB_UPDATE:
7444		case SADB_ADD:
7445		case SADB_DELETE:
7446		case SADB_GET:
7447		case SADB_ACQUIRE:
7448		case SADB_EXPIRE:
7449			ipseclog((LOG_DEBUG, "%s: must specify satype "
7450			    "when msg type=%u.\n", __func__,
7451			    msg->sadb_msg_type));
7452			V_pfkeystat.out_invsatype++;
7453			error = EINVAL;
7454			goto senderror;
7455		}
7456		break;
7457	case SADB_SATYPE_AH:
7458	case SADB_SATYPE_ESP:
7459	case SADB_X_SATYPE_IPCOMP:
7460	case SADB_X_SATYPE_TCPSIGNATURE:
7461		switch (msg->sadb_msg_type) {
7462		case SADB_X_SPDADD:
7463		case SADB_X_SPDDELETE:
7464		case SADB_X_SPDGET:
7465		case SADB_X_SPDDUMP:
7466		case SADB_X_SPDFLUSH:
7467		case SADB_X_SPDSETIDX:
7468		case SADB_X_SPDUPDATE:
7469		case SADB_X_SPDDELETE2:
7470			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7471				__func__, msg->sadb_msg_type));
7472			V_pfkeystat.out_invsatype++;
7473			error = EINVAL;
7474			goto senderror;
7475		}
7476		break;
7477	case SADB_SATYPE_RSVP:
7478	case SADB_SATYPE_OSPFV2:
7479	case SADB_SATYPE_RIPV2:
7480	case SADB_SATYPE_MIP:
7481		ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7482			__func__, msg->sadb_msg_satype));
7483		V_pfkeystat.out_invsatype++;
7484		error = EOPNOTSUPP;
7485		goto senderror;
7486	case 1:	/* XXX: What does it do? */
7487		if (msg->sadb_msg_type == SADB_X_PROMISC)
7488			break;
7489		/*FALLTHROUGH*/
7490	default:
7491		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7492			__func__, msg->sadb_msg_satype));
7493		V_pfkeystat.out_invsatype++;
7494		error = EINVAL;
7495		goto senderror;
7496	}
7497
7498	/* check field of upper layer protocol and address family */
7499	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7500	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7501		struct sadb_address *src0, *dst0;
7502		u_int plen;
7503
7504		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7505		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7506
7507		/* check upper layer protocol */
7508		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7509			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7510				"mismatched.\n", __func__));
7511			V_pfkeystat.out_invaddr++;
7512			error = EINVAL;
7513			goto senderror;
7514		}
7515
7516		/* check family */
7517		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7518		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
7519			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7520				__func__));
7521			V_pfkeystat.out_invaddr++;
7522			error = EINVAL;
7523			goto senderror;
7524		}
7525		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7526		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
7527			ipseclog((LOG_DEBUG, "%s: address struct size "
7528				"mismatched.\n", __func__));
7529			V_pfkeystat.out_invaddr++;
7530			error = EINVAL;
7531			goto senderror;
7532		}
7533
7534		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7535		case AF_INET:
7536			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7537			    sizeof(struct sockaddr_in)) {
7538				V_pfkeystat.out_invaddr++;
7539				error = EINVAL;
7540				goto senderror;
7541			}
7542			break;
7543		case AF_INET6:
7544			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7545			    sizeof(struct sockaddr_in6)) {
7546				V_pfkeystat.out_invaddr++;
7547				error = EINVAL;
7548				goto senderror;
7549			}
7550			break;
7551		default:
7552			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7553				__func__));
7554			V_pfkeystat.out_invaddr++;
7555			error = EAFNOSUPPORT;
7556			goto senderror;
7557		}
7558
7559		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7560		case AF_INET:
7561			plen = sizeof(struct in_addr) << 3;
7562			break;
7563		case AF_INET6:
7564			plen = sizeof(struct in6_addr) << 3;
7565			break;
7566		default:
7567			plen = 0;	/*fool gcc*/
7568			break;
7569		}
7570
7571		/* check max prefix length */
7572		if (src0->sadb_address_prefixlen > plen ||
7573		    dst0->sadb_address_prefixlen > plen) {
7574			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7575				__func__));
7576			V_pfkeystat.out_invaddr++;
7577			error = EINVAL;
7578			goto senderror;
7579		}
7580
7581		/*
7582		 * prefixlen == 0 is valid because there can be a case when
7583		 * all addresses are matched.
7584		 */
7585	}
7586
7587	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7588	    key_typesw[msg->sadb_msg_type] == NULL) {
7589		V_pfkeystat.out_invmsgtype++;
7590		error = EINVAL;
7591		goto senderror;
7592	}
7593
7594	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7595
7596senderror:
7597	msg->sadb_msg_errno = error;
7598	return key_sendup_mbuf(so, m, target);
7599}
7600
7601static int
7602key_senderror(so, m, code)
7603	struct socket *so;
7604	struct mbuf *m;
7605	int code;
7606{
7607	struct sadb_msg *msg;
7608
7609	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7610		("mbuf too small, len %u", m->m_len));
7611
7612	msg = mtod(m, struct sadb_msg *);
7613	msg->sadb_msg_errno = code;
7614	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7615}
7616
7617/*
7618 * set the pointer to each header into message buffer.
7619 * m will be freed on error.
7620 * XXX larger-than-MCLBYTES extension?
7621 */
7622static int
7623key_align(m, mhp)
7624	struct mbuf *m;
7625	struct sadb_msghdr *mhp;
7626{
7627	INIT_VNET_IPSEC(curvnet);
7628	struct mbuf *n;
7629	struct sadb_ext *ext;
7630	size_t off, end;
7631	int extlen;
7632	int toff;
7633
7634	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7635	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7636	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7637		("mbuf too small, len %u", m->m_len));
7638
7639	/* initialize */
7640	bzero(mhp, sizeof(*mhp));
7641
7642	mhp->msg = mtod(m, struct sadb_msg *);
7643	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
7644
7645	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7646	extlen = end;	/*just in case extlen is not updated*/
7647	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7648		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7649		if (!n) {
7650			/* m is already freed */
7651			return ENOBUFS;
7652		}
7653		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7654
7655		/* set pointer */
7656		switch (ext->sadb_ext_type) {
7657		case SADB_EXT_SA:
7658		case SADB_EXT_ADDRESS_SRC:
7659		case SADB_EXT_ADDRESS_DST:
7660		case SADB_EXT_ADDRESS_PROXY:
7661		case SADB_EXT_LIFETIME_CURRENT:
7662		case SADB_EXT_LIFETIME_HARD:
7663		case SADB_EXT_LIFETIME_SOFT:
7664		case SADB_EXT_KEY_AUTH:
7665		case SADB_EXT_KEY_ENCRYPT:
7666		case SADB_EXT_IDENTITY_SRC:
7667		case SADB_EXT_IDENTITY_DST:
7668		case SADB_EXT_SENSITIVITY:
7669		case SADB_EXT_PROPOSAL:
7670		case SADB_EXT_SUPPORTED_AUTH:
7671		case SADB_EXT_SUPPORTED_ENCRYPT:
7672		case SADB_EXT_SPIRANGE:
7673		case SADB_X_EXT_POLICY:
7674		case SADB_X_EXT_SA2:
7675#ifdef IPSEC_NAT_T
7676		case SADB_X_EXT_NAT_T_TYPE:
7677		case SADB_X_EXT_NAT_T_SPORT:
7678		case SADB_X_EXT_NAT_T_DPORT:
7679		case SADB_X_EXT_NAT_T_OAI:
7680		case SADB_X_EXT_NAT_T_OAR:
7681		case SADB_X_EXT_NAT_T_FRAG:
7682#endif
7683			/* duplicate check */
7684			/*
7685			 * XXX Are there duplication payloads of either
7686			 * KEY_AUTH or KEY_ENCRYPT ?
7687			 */
7688			if (mhp->ext[ext->sadb_ext_type] != NULL) {
7689				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7690					"%u\n", __func__, ext->sadb_ext_type));
7691				m_freem(m);
7692				V_pfkeystat.out_dupext++;
7693				return EINVAL;
7694			}
7695			break;
7696		default:
7697			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7698				__func__, ext->sadb_ext_type));
7699			m_freem(m);
7700			V_pfkeystat.out_invexttype++;
7701			return EINVAL;
7702		}
7703
7704		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7705
7706		if (key_validate_ext(ext, extlen)) {
7707			m_freem(m);
7708			V_pfkeystat.out_invlen++;
7709			return EINVAL;
7710		}
7711
7712		n = m_pulldown(m, off, extlen, &toff);
7713		if (!n) {
7714			/* m is already freed */
7715			return ENOBUFS;
7716		}
7717		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7718
7719		mhp->ext[ext->sadb_ext_type] = ext;
7720		mhp->extoff[ext->sadb_ext_type] = off;
7721		mhp->extlen[ext->sadb_ext_type] = extlen;
7722	}
7723
7724	if (off != end) {
7725		m_freem(m);
7726		V_pfkeystat.out_invlen++;
7727		return EINVAL;
7728	}
7729
7730	return 0;
7731}
7732
7733static int
7734key_validate_ext(ext, len)
7735	const struct sadb_ext *ext;
7736	int len;
7737{
7738	const struct sockaddr *sa;
7739	enum { NONE, ADDR } checktype = NONE;
7740	int baselen = 0;
7741	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7742
7743	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7744		return EINVAL;
7745
7746	/* if it does not match minimum/maximum length, bail */
7747	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7748	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7749		return EINVAL;
7750	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7751		return EINVAL;
7752	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7753		return EINVAL;
7754
7755	/* more checks based on sadb_ext_type XXX need more */
7756	switch (ext->sadb_ext_type) {
7757	case SADB_EXT_ADDRESS_SRC:
7758	case SADB_EXT_ADDRESS_DST:
7759	case SADB_EXT_ADDRESS_PROXY:
7760		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7761		checktype = ADDR;
7762		break;
7763	case SADB_EXT_IDENTITY_SRC:
7764	case SADB_EXT_IDENTITY_DST:
7765		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7766		    SADB_X_IDENTTYPE_ADDR) {
7767			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7768			checktype = ADDR;
7769		} else
7770			checktype = NONE;
7771		break;
7772	default:
7773		checktype = NONE;
7774		break;
7775	}
7776
7777	switch (checktype) {
7778	case NONE:
7779		break;
7780	case ADDR:
7781		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7782		if (len < baselen + sal)
7783			return EINVAL;
7784		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7785			return EINVAL;
7786		break;
7787	}
7788
7789	return 0;
7790}
7791
7792void
7793key_init(void)
7794{
7795	INIT_VNET_IPSEC(curvnet);
7796	int i;
7797
7798	V_key_debug_level = 0;
7799	V_key_spi_trycnt = 1000;
7800	V_key_spi_minval = 0x100;
7801	V_key_spi_maxval = 0x0fffffff;	/* XXX */
7802	V_policy_id = 0;
7803	V_key_int_random = 60;		/*interval to initialize randseed,1(m)*/
7804	V_key_larval_lifetime = 30;	/* interval to expire acquiring, 30(s)*/
7805	V_key_blockacq_count = 10;	/* counter for blocking SADB_ACQUIRE.*/
7806	V_key_blockacq_lifetime = 20;	/* lifetime for blocking SADB_ACQUIRE.*/
7807	V_key_preferred_oldsa = 1;	/* preferred old sa rather than new sa*/
7808
7809	V_acq_seq = 0;
7810
7811	V_ipsec_esp_keymin = 256;
7812	V_ipsec_esp_auth = 0;
7813	V_ipsec_ah_keymin = 128;
7814
7815	for (i = 0; i < IPSEC_DIR_MAX; i++)
7816		LIST_INIT(&V_sptree[i]);
7817
7818	LIST_INIT(&V_sahtree);
7819
7820	for (i = 0; i <= SADB_SATYPE_MAX; i++)
7821		LIST_INIT(&V_regtree[i]);
7822
7823	LIST_INIT(&V_acqtree);
7824	LIST_INIT(&V_spacqtree);
7825
7826	/* system default */
7827	V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7828	V_ip4_def_policy.refcnt++;	/*never reclaim this*/
7829
7830	if (!IS_DEFAULT_VNET(curvnet))
7831		return;
7832
7833	SPTREE_LOCK_INIT();
7834	REGTREE_LOCK_INIT();
7835	SAHTREE_LOCK_INIT();
7836	ACQ_LOCK_INIT();
7837	SPACQ_LOCK_INIT();
7838
7839#ifndef IPSEC_DEBUG2
7840	timeout((void *)key_timehandler, (void *)0, hz);
7841#endif /*IPSEC_DEBUG2*/
7842
7843	/* initialize key statistics */
7844	keystat.getspi_count = 1;
7845
7846	printf("IPsec: Initialized Security Association Processing.\n");
7847}
7848
7849#ifdef VIMAGE
7850void
7851key_destroy(void)
7852{
7853	INIT_VNET_IPSEC(curvnet);
7854	struct secpolicy *sp, *nextsp;
7855	struct secspacq *acq, *nextacq;
7856	struct secashead *sah, *nextsah;
7857	struct secreg *reg;
7858	int i;
7859
7860	SPTREE_LOCK();
7861	for (i = 0; i < IPSEC_DIR_MAX; i++) {
7862		for (sp = LIST_FIRST(&V_sptree[i]);
7863		    sp != NULL; sp = nextsp) {
7864			nextsp = LIST_NEXT(sp, chain);
7865			if (__LIST_CHAINED(sp)) {
7866				LIST_REMOVE(sp, chain);
7867				free(sp, M_IPSEC_SP);
7868			}
7869		}
7870	}
7871	SPTREE_UNLOCK();
7872
7873	SAHTREE_LOCK();
7874	for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7875		nextsah = LIST_NEXT(sah, chain);
7876		if (__LIST_CHAINED(sah)) {
7877			LIST_REMOVE(sah, chain);
7878			free(sah, M_IPSEC_SAH);
7879		}
7880	}
7881	SAHTREE_UNLOCK();
7882
7883	REGTREE_LOCK();
7884	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7885		LIST_FOREACH(reg, &V_regtree[i], chain) {
7886			if (__LIST_CHAINED(reg)) {
7887				LIST_REMOVE(reg, chain);
7888				free(reg, M_IPSEC_SAR);
7889				break;
7890			}
7891		}
7892	}
7893	REGTREE_UNLOCK();
7894
7895	ACQ_LOCK();
7896	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
7897		nextacq = LIST_NEXT(acq, chain);
7898		if (__LIST_CHAINED(acq)) {
7899			LIST_REMOVE(acq, chain);
7900			free(acq, M_IPSEC_SAQ);
7901		}
7902	}
7903	ACQ_UNLOCK();
7904
7905	SPACQ_LOCK();
7906	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
7907		nextacq = LIST_NEXT(acq, chain);
7908		if (__LIST_CHAINED(acq)) {
7909			LIST_REMOVE(acq, chain);
7910			free(acq, M_IPSEC_SAQ);
7911		}
7912	}
7913	SPACQ_UNLOCK();
7914}
7915#endif
7916
7917/*
7918 * XXX: maybe This function is called after INBOUND IPsec processing.
7919 *
7920 * Special check for tunnel-mode packets.
7921 * We must make some checks for consistency between inner and outer IP header.
7922 *
7923 * xxx more checks to be provided
7924 */
7925int
7926key_checktunnelsanity(sav, family, src, dst)
7927	struct secasvar *sav;
7928	u_int family;
7929	caddr_t src;
7930	caddr_t dst;
7931{
7932	IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7933
7934	/* XXX: check inner IP header */
7935
7936	return 1;
7937}
7938
7939/* record data transfer on SA, and update timestamps */
7940void
7941key_sa_recordxfer(sav, m)
7942	struct secasvar *sav;
7943	struct mbuf *m;
7944{
7945	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7946	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7947	if (!sav->lft_c)
7948		return;
7949
7950	/*
7951	 * XXX Currently, there is a difference of bytes size
7952	 * between inbound and outbound processing.
7953	 */
7954	sav->lft_c->bytes += m->m_pkthdr.len;
7955	/* to check bytes lifetime is done in key_timehandler(). */
7956
7957	/*
7958	 * We use the number of packets as the unit of
7959	 * allocations.  We increment the variable
7960	 * whenever {esp,ah}_{in,out}put is called.
7961	 */
7962	sav->lft_c->allocations++;
7963	/* XXX check for expires? */
7964
7965	/*
7966	 * NOTE: We record CURRENT usetime by using wall clock,
7967	 * in seconds.  HARD and SOFT lifetime are measured by the time
7968	 * difference (again in seconds) from usetime.
7969	 *
7970	 *	usetime
7971	 *	v     expire   expire
7972	 * -----+-----+--------+---> t
7973	 *	<--------------> HARD
7974	 *	<-----> SOFT
7975	 */
7976	sav->lft_c->usetime = time_second;
7977	/* XXX check for expires? */
7978
7979	return;
7980}
7981
7982/* dumb version */
7983void
7984key_sa_routechange(dst)
7985	struct sockaddr *dst;
7986{
7987	INIT_VNET_IPSEC(curvnet);
7988	struct secashead *sah;
7989	struct route *ro;
7990
7991	SAHTREE_LOCK();
7992	LIST_FOREACH(sah, &V_sahtree, chain) {
7993		ro = &sah->sa_route;
7994		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7995		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7996			RTFREE(ro->ro_rt);
7997			ro->ro_rt = (struct rtentry *)NULL;
7998		}
7999	}
8000	SAHTREE_UNLOCK();
8001}
8002
8003static void
8004key_sa_chgstate(struct secasvar *sav, u_int8_t state)
8005{
8006	IPSEC_ASSERT(sav != NULL, ("NULL sav"));
8007	SAHTREE_LOCK_ASSERT();
8008
8009	if (sav->state != state) {
8010		if (__LIST_CHAINED(sav))
8011			LIST_REMOVE(sav, chain);
8012		sav->state = state;
8013		LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
8014	}
8015}
8016
8017void
8018key_sa_stir_iv(sav)
8019	struct secasvar *sav;
8020{
8021
8022	IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
8023	key_randomfill(sav->iv, sav->ivlen);
8024}
8025
8026/* XXX too much? */
8027static struct mbuf *
8028key_alloc_mbuf(l)
8029	int l;
8030{
8031	struct mbuf *m = NULL, *n;
8032	int len, t;
8033
8034	len = l;
8035	while (len > 0) {
8036		MGET(n, M_DONTWAIT, MT_DATA);
8037		if (n && len > MLEN)
8038			MCLGET(n, M_DONTWAIT);
8039		if (!n) {
8040			m_freem(m);
8041			return NULL;
8042		}
8043
8044		n->m_next = NULL;
8045		n->m_len = 0;
8046		n->m_len = M_TRAILINGSPACE(n);
8047		/* use the bottom of mbuf, hoping we can prepend afterwards */
8048		if (n->m_len > len) {
8049			t = (n->m_len - len) & ~(sizeof(long) - 1);
8050			n->m_data += t;
8051			n->m_len = len;
8052		}
8053
8054		len -= n->m_len;
8055
8056		if (m)
8057			m_cat(m, n);
8058		else
8059			m = n;
8060	}
8061
8062	return m;
8063}
8064
8065/*
8066 * Take one of the kernel's security keys and convert it into a PF_KEY
8067 * structure within an mbuf, suitable for sending up to a waiting
8068 * application in user land.
8069 *
8070 * IN:
8071 *    src: A pointer to a kernel security key.
8072 *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
8073 * OUT:
8074 *    a valid mbuf or NULL indicating an error
8075 *
8076 */
8077
8078static struct mbuf *
8079key_setkey(struct seckey *src, u_int16_t exttype)
8080{
8081	struct mbuf *m;
8082	struct sadb_key *p;
8083	int len;
8084
8085	if (src == NULL)
8086		return NULL;
8087
8088	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8089	m = key_alloc_mbuf(len);
8090	if (m == NULL)
8091		return NULL;
8092	p = mtod(m, struct sadb_key *);
8093	bzero(p, len);
8094	p->sadb_key_len = PFKEY_UNIT64(len);
8095	p->sadb_key_exttype = exttype;
8096	p->sadb_key_bits = src->bits;
8097	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8098
8099	return m;
8100}
8101
8102/*
8103 * Take one of the kernel's lifetime data structures and convert it
8104 * into a PF_KEY structure within an mbuf, suitable for sending up to
8105 * a waiting application in user land.
8106 *
8107 * IN:
8108 *    src: A pointer to a kernel lifetime structure.
8109 *    exttype: Which type of lifetime this is. Refer to the PF_KEY
8110 *             data structures for more information.
8111 * OUT:
8112 *    a valid mbuf or NULL indicating an error
8113 *
8114 */
8115
8116static struct mbuf *
8117key_setlifetime(struct seclifetime *src, u_int16_t exttype)
8118{
8119	struct mbuf *m = NULL;
8120	struct sadb_lifetime *p;
8121	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8122
8123	if (src == NULL)
8124		return NULL;
8125
8126	m = key_alloc_mbuf(len);
8127	if (m == NULL)
8128		return m;
8129	p = mtod(m, struct sadb_lifetime *);
8130
8131	bzero(p, len);
8132	p->sadb_lifetime_len = PFKEY_UNIT64(len);
8133	p->sadb_lifetime_exttype = exttype;
8134	p->sadb_lifetime_allocations = src->allocations;
8135	p->sadb_lifetime_bytes = src->bytes;
8136	p->sadb_lifetime_addtime = src->addtime;
8137	p->sadb_lifetime_usetime = src->usetime;
8138
8139	return m;
8140
8141}
8142