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