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