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