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