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