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