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