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