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