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