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