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