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