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