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