Coverage Report

Created: 2026-04-09 06:21

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