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