1 /*
2 * Copyright (c) 2000-2020 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 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29 /*
30 * Mach Operating System
31 * Copyright (c) 1987 Carnegie-Mellon University
32 * All rights reserved. The CMU software License Agreement specifies
33 * the terms and conditions for use and redistribution.
34 */
35
36 /*-
37 * Copyright (c) 1982, 1986, 1991, 1993
38 * The Regents of the University of California. All rights reserved.
39 * (c) UNIX System Laboratories, Inc.
40 * All or some portions of this file are derived from material licensed
41 * to the University of California by American Telephone and Telegraph
42 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
43 * the permission of UNIX System Laboratories, Inc.
44 *
45 * Redistribution and use in source and binary forms, with or without
46 * modification, are permitted provided that the following conditions
47 * are met:
48 * 1. Redistributions of source code must retain the above copyright
49 * notice, this list of conditions and the following disclaimer.
50 * 2. Redistributions in binary form must reproduce the above copyright
51 * notice, this list of conditions and the following disclaimer in the
52 * documentation and/or other materials provided with the distribution.
53 * 3. All advertising materials mentioning features or use of this software
54 * must display the following acknowledgement:
55 * This product includes software developed by the University of
56 * California, Berkeley and its contributors.
57 * 4. Neither the name of the University nor the names of its contributors
58 * may be used to endorse or promote products derived from this software
59 * without specific prior written permission.
60 *
61 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
62 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
63 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
65 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
66 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
67 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
68 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
69 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
70 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
71 * SUCH DAMAGE.
72 *
73 * from: @(#)kern_exec.c 8.1 (Berkeley) 6/10/93
74 */
75 /*
76 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
77 * support for mandatory and extensible security protections. This notice
78 * is included in support of clause 2.2 (b) of the Apple Public License,
79 * Version 2.0.
80 */
81 #include <machine/reg.h>
82 #include <machine/cpu_capabilities.h>
83
84 #include <sys/cdefs.h>
85 #include <sys/param.h>
86 #include <sys/systm.h>
87 #include <sys/filedesc.h>
88 #include <sys/kernel.h>
89 #include <sys/proc_internal.h>
90 #include <sys/kauth.h>
91 #include <sys/user.h>
92 #include <sys/socketvar.h>
93 #include <sys/malloc.h>
94 #include <sys/namei.h>
95 #include <sys/mount_internal.h>
96 #include <sys/vnode_internal.h>
97 #include <sys/file_internal.h>
98 #include <sys/stat.h>
99 #include <sys/uio_internal.h>
100 #include <sys/acct.h>
101 #include <sys/exec.h>
102 #include <sys/kdebug.h>
103 #include <sys/signal.h>
104 #include <sys/aio_kern.h>
105 #include <sys/lockdown_mode.h>
106 #include <sys/sysproto.h>
107 #include <sys/sysctl.h>
108 #include <sys/persona.h>
109 #include <sys/reason.h>
110 #if SYSV_SHM
111 #include <sys/shm_internal.h> /* shmexec() */
112 #endif
113 #include <sys/ubc_internal.h> /* ubc_map() */
114 #include <sys/spawn.h>
115 #include <sys/spawn_internal.h>
116 #include <sys/process_policy.h>
117 #include <sys/codesign.h>
118 #include <sys/random.h>
119 #include <crypto/sha1.h>
120
121 #include <libkern/libkern.h>
122 #include <libkern/amfi/amfi.h>
123 #include <libkern/crypto/sha2.h>
124 #include <security/audit/audit.h>
125
126 #include <ipc/ipc_types.h>
127
128 #include <mach/mach_param.h>
129 #include <mach/mach_types.h>
130 #include <mach/port.h>
131 #include <mach/task.h>
132 #include <mach/task_access.h>
133 #include <mach/thread_act.h>
134 #include <mach/vm_map.h>
135 #include <mach/mach_vm.h>
136 #include <mach/vm_param.h>
137 #include <mach_debug/mach_debug_types.h>
138
139 #include <kern/sched_prim.h> /* thread_wakeup() */
140 #include <kern/affinity.h>
141 #include <kern/assert.h>
142 #include <kern/ipc_kobject.h>
143 #include <kern/task.h>
144 #include <kern/thread.h>
145 #include <kern/coalition.h>
146 #include <kern/policy_internal.h>
147 #include <kern/kalloc.h>
148 #include <kern/zalloc.h> /* zone_userspace_reboot_checks() */
149
150 #include <os/log.h>
151
152 #if CONFIG_MACF
153 #include <security/mac_framework.h>
154 #include <security/mac_mach_internal.h>
155 #endif
156
157 #if CONFIG_AUDIT
158 #include <bsm/audit_kevents.h>
159 #endif
160
161 #if CONFIG_ARCADE
162 #include <kern/arcade.h>
163 #endif
164
165 #include <vm/vm_map_xnu.h>
166 #include <vm/vm_kern_xnu.h>
167 #include <vm/vm_protos.h>
168 #include <vm/vm_fault.h>
169 #include <vm/vm_pageout_xnu.h>
170 #include <vm/pmap.h>
171 #include <vm/vm_reclaim_xnu.h>
172
173 #include <kdp/kdp_dyld.h>
174
175 #include <machine/machine_routines.h>
176 #include <machine/pal_routines.h>
177
178 #include <pexpert/pexpert.h>
179 #include <pexpert/device_tree.h>
180
181 #if CONFIG_MEMORYSTATUS
182 #include <sys/kern_memorystatus.h>
183 #endif
184
185 #include <IOKit/IOBSD.h>
186 #include <IOKit/IOKitKeys.h> /* kIODriverKitEntitlementKey */
187
188 #include "kern_exec_internal.h"
189
190 #include <CodeSignature/Entitlements.h>
191
192 #include <mach/exclaves.h>
193
194 #if HAS_MTE
195 #include <arm64/mte_xnu.h>
196 #endif /* HAS_MTE */
197
198 extern boolean_t vm_darkwake_mode;
199
200 /* enable crash reports on various exec failures */
201 static TUNABLE(bool, bootarg_execfailurereports, "execfailurecrashes", false);
202
203 #if XNU_TARGET_OS_OSX
204 #if __has_feature(ptrauth_calls)
205 static TUNABLE(bool, bootarg_arm64e_preview_abi, "-arm64e_preview_abi", false);
206 #endif /* __has_feature(ptrauth_calls) */
207
208 #if DEBUG || DEVELOPMENT
209 static TUNABLE(bool, unentitled_ios_sim_launch, "unentitled_ios_sim_launch", false);
210 #endif /* DEBUG || DEVELOPMENT */
211 #endif /* XNU_TARGET_OS_OSX */
212
213 #if DEVELOPMENT || DEBUG
214 os_log_t exec_log_handle = NULL;
215 #define EXEC_LOG(fmt, ...) \
216 do { \
217 if (exec_log_handle) { \
218 os_log_with_type(exec_log_handle, OS_LOG_TYPE_INFO, "exec - %s:%d " fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__); \
219 } \
220 } while (0)
221 #else /* DEVELOPMENT || DEBUG */
222 #define EXEC_LOG(fmt, ...) do { } while (0)
223 #endif /* DEVELOPMENT || DEBUG */
224
225 #if CONFIG_DTRACE
226 /* Do not include dtrace.h, it redefines kmem_[alloc/free] */
227 extern void dtrace_proc_exec(proc_t);
228 extern void (*dtrace_proc_waitfor_exec_ptr)(proc_t);
229
230 /*
231 * Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c,
232 * we will store its value before actually calling it.
233 */
234 static void (*dtrace_proc_waitfor_hook)(proc_t) = NULL;
235
236 #include <sys/dtrace_ptss.h>
237 #endif
238
239 #if __has_feature(ptrauth_calls)
240 static TUNABLE_DEV_WRITEABLE(int, vm_shared_region_per_team_id,
241 "vm_shared_region_per_team_id", 1);
242 static TUNABLE_DEV_WRITEABLE(int, vm_shared_region_by_entitlement,
243 "vm_shared_region_by_entitlement", 1);
244
245 /* Upon userland request, reslide the shared cache. */
246 static TUNABLE_DEV_WRITEABLE(int, vm_shared_region_reslide_aslr,
247 "vm_shared_region_reslide_aslr",
248 #if CONFIG_RESLIDE_SHARED_CACHE
249 1
250 #else
251 0
252 #endif /* CONFIG_RESLIDE_SHARED_CACHE */
253 );
254
255 /*
256 * Flag to control what processes should get shared cache randomize resliding
257 * after a fault in the shared cache region:
258 *
259 * 0 - all processes get a new randomized slide
260 * 1 - only platform processes get a new randomized slide
261 */
262 TUNABLE_DEV_WRITEABLE(int, vm_shared_region_reslide_restrict,
263 "vm_shared_region_reslide_restrict", 1);
264
265 #if DEVELOPMENT || DEBUG
266 SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_per_team_id,
267 CTLFLAG_RW, &vm_shared_region_per_team_id, 0, "");
268 SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_by_entitlement,
269 CTLFLAG_RW, &vm_shared_region_by_entitlement, 0, "");
270 SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_reslide_restrict,
271 CTLFLAG_RW, &vm_shared_region_reslide_restrict, 0, "");
272 SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_reslide_aslr,
273 CTLFLAG_RW, &vm_shared_region_reslide_aslr, 0, "");
274 #endif
275 #endif /* __has_feature(ptrauth_calls) */
276
277 #if DEVELOPMENT || DEBUG
278 static TUNABLE(bool, enable_dext_coredumps_on_panic, "dext_panic_coredump", true);
279 #else
280 static TUNABLE(bool, enable_dext_coredumps_on_panic, "dext_panic_coredump", false);
281 #endif
282 extern kern_return_t kern_register_userspace_coredump(task_t task, const char * name);
283 #define USERSPACE_COREDUMP_PANIC_ENTITLEMENT "com.apple.private.enable-coredump-on-panic"
284 #define USERSPACE_COREDUMP_PANIC_SEED_ENTITLEMENT \
285 "com.apple.private.enable-coredump-on-panic-seed-privacy-approved"
286
287 extern void proc_apply_task_networkbg_internal(proc_t, thread_t);
288 extern void task_set_did_exec_flag(task_t task);
289 extern void task_clear_exec_copy_flag(task_t task);
290 proc_t proc_exec_switch_task(proc_t old_proc, proc_t new_proc, task_t old_task,
291 task_t new_task, struct image_params *imgp, void **inherit);
292 boolean_t task_is_active(task_t);
293 boolean_t thread_is_active(thread_t thread);
294 void thread_copy_resource_info(thread_t dst_thread, thread_t src_thread);
295 void *ipc_importance_exec_switch_task(task_t old_task, task_t new_task);
296 extern void ipc_importance_release(void *elem);
297 extern boolean_t task_has_watchports(task_t task);
298 extern void task_set_no_smt(task_t task);
299 #if defined(HAS_APPLE_PAC)
300 char *task_get_vm_shared_region_id_and_jop_pid(task_t task, uint64_t *jop_pid);
301 #endif
302 task_t convert_port_to_task(ipc_port_t port);
303
304 #if CONFIG_EXCLAVES
305 int task_add_conclave(task_t task, void *vnode, int64_t off, const char *task_conclave_id);
306 kern_return_t task_inherit_conclave(task_t old_task, task_t new_task, void *vnode, int64_t off);
307 #endif /* CONFIG_EXCLAVES */
308
309 /*
310 * Mach things for which prototypes are unavailable from Mach headers
311 */
312 extern void ipc_task_enable(task_t task);
313 extern void ipc_task_reset(task_t task);
314 extern void ipc_thread_reset(thread_t thread);
315
316 #if DEVELOPMENT || DEBUG
317 void task_importance_update_owner_info(task_t);
318 #endif
319
320 extern struct savearea *get_user_regs(thread_t);
321
322 __attribute__((noinline)) int __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port, int32_t new_pid);
323
324 #include <kern/thread.h>
325 #include <kern/task.h>
326 #include <kern/ast.h>
327 #include <kern/mach_loader.h>
328 #include <kern/mach_fat.h>
329 #include <mach-o/fat.h>
330 #include <mach-o/loader.h>
331 #include <machine/vmparam.h>
332 #include <sys/imgact.h>
333
334 #include <sys/sdt.h>
335
336
337 /*
338 * EAI_ITERLIMIT The maximum number of times to iterate an image
339 * activator in exec_activate_image() before treating
340 * it as malformed/corrupt.
341 */
342 #define EAI_ITERLIMIT 3
343
344 /*
345 * For #! interpreter parsing
346 */
347 #define IS_WHITESPACE(ch) ((ch == ' ') || (ch == '\t'))
348 #define IS_EOL(ch) ((ch == '#') || (ch == '\n'))
349
350 extern vm_map_t bsd_pageable_map;
351 extern const struct fileops vnops;
352 extern int nextpidversion;
353
354
355 #define USER_ADDR_ALIGN(addr, val) \
356 ( ( (user_addr_t)(addr) + (val) - 1) \
357 & ~((val) - 1) )
358
359 /*
360 * For subsystem root support
361 */
362 #define SPAWN_SUBSYSTEM_ROOT_ENTITLEMENT "com.apple.private.spawn-subsystem-root"
363
364 /*
365 * Allow setting p_crash_behavior to trigger panic on crash
366 */
367 #define SPAWN_SET_PANIC_CRASH_BEHAVIOR "com.apple.private.spawn-panic-crash-behavior"
368
369 /* Platform Code Exec Logging */
370 static int platform_exec_logging = 0;
371
372 SYSCTL_DECL(_security_mac);
373
374 SYSCTL_INT(_security_mac, OID_AUTO, platform_exec_logging, CTLFLAG_RW, &platform_exec_logging, 0,
375 "log cdhashes for all platform binary executions");
376
377 static os_log_t peLog = OS_LOG_DEFAULT;
378
379
380 struct exception_port_action_t {
381 ipc_port_t port;
382 _ps_port_action_t *port_action;
383 };
384
385 struct exec_port_actions {
386 uint32_t exception_port_count;
387 uint32_t portwatch_count;
388 uint32_t registered_count;
389 struct exception_port_action_t *excport_array;
390 ipc_port_t *portwatch_array;
391 ipc_port_t registered_array[TASK_PORT_REGISTER_MAX];
392 };
393
394 struct image_params; /* Forward */
395 static int exec_activate_image(struct image_params *imgp);
396 static int exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp);
397 static int load_return_to_errno(load_return_t lrtn);
398 static int execargs_alloc(struct image_params *imgp);
399 static int execargs_free(struct image_params *imgp);
400 static int exec_check_permissions(struct image_params *imgp);
401 static int exec_extract_strings(struct image_params *imgp);
402 static int exec_add_apple_strings(struct image_params *imgp, const load_result_t *load_result, task_t task);
403 static int exec_handle_sugid(struct image_params *imgp);
404 static int sugid_scripts = 0;
405 SYSCTL_INT(_kern, OID_AUTO, sugid_scripts, CTLFLAG_RW | CTLFLAG_LOCKED, &sugid_scripts, 0, "");
406 static kern_return_t create_unix_stack(vm_map_t map, load_result_t* load_result, proc_t p);
407 static int copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size);
408 static void exec_resettextvp(proc_t, struct image_params *);
409 static int process_signature(proc_t, struct image_params *);
410 static void exec_prefault_data(proc_t, struct image_params *, load_result_t *);
411 static errno_t exec_handle_port_actions(struct image_params *imgp,
412 struct exec_port_actions *port_actions);
413 static errno_t exec_handle_exception_port_actions(const struct image_params *imgp,
414 const struct exec_port_actions *port_actions);
415 static errno_t exec_handle_spawnattr_policy(proc_t p, thread_t thread, int psa_apptype, uint64_t psa_qos_clamp,
416 task_role_t psa_darwin_role, struct exec_port_actions *port_actions);
417 static void exec_port_actions_destroy(struct exec_port_actions *port_actions);
418
419 /*
420 * exec_add_user_string
421 *
422 * Add the requested string to the string space area.
423 *
424 * Parameters; struct image_params * image parameter block
425 * user_addr_t string to add to strings area
426 * int segment from which string comes
427 * boolean_t TRUE if string contributes to NCARGS
428 *
429 * Returns: 0 Success
430 * !0 Failure errno from copyinstr()
431 *
432 * Implicit returns:
433 * (imgp->ip_strendp) updated location of next add, if any
434 * (imgp->ip_strspace) updated byte count of space remaining
435 * (imgp->ip_argspace) updated byte count of space in NCARGS
436 */
437 __attribute__((noinline))
438 static int
exec_add_user_string(struct image_params * imgp,user_addr_t str,int seg,boolean_t is_ncargs)439 exec_add_user_string(struct image_params *imgp, user_addr_t str, int seg, boolean_t is_ncargs)
440 {
441 int error = 0;
442
443 do {
444 size_t len = 0;
445 int space;
446
447 if (is_ncargs) {
448 space = imgp->ip_argspace; /* by definition smaller than ip_strspace */
449 } else {
450 space = imgp->ip_strspace;
451 }
452
453 if (space <= 0) {
454 error = E2BIG;
455 break;
456 }
457
458 if (!UIO_SEG_IS_USER_SPACE(seg)) {
459 char *kstr = CAST_DOWN(char *, str); /* SAFE */
460 error = copystr(kstr, imgp->ip_strendp, space, &len);
461 } else {
462 error = copyinstr(str, imgp->ip_strendp, space, &len);
463 }
464
465 imgp->ip_strendp += len;
466 imgp->ip_strspace -= len;
467 if (is_ncargs) {
468 imgp->ip_argspace -= len;
469 }
470 } while (error == ENAMETOOLONG);
471
472 return error;
473 }
474
475 /*
476 * dyld is now passed the executable path as a getenv-like variable
477 * in the same fashion as the stack_guard and malloc_entropy keys.
478 */
479 #define EXECUTABLE_KEY "executable_path="
480
481 /*
482 * exec_save_path
483 *
484 * To support new app package launching for Mac OS X, the dyld needs the
485 * first argument to execve() stored on the user stack.
486 *
487 * Save the executable path name at the bottom of the strings area and set
488 * the argument vector pointer to the location following that to indicate
489 * the start of the argument and environment tuples, setting the remaining
490 * string space count to the size of the string area minus the path length.
491 *
492 * Parameters; struct image_params * image parameter block
493 * char * path used to invoke program
494 * int segment from which path comes
495 *
496 * Returns: int 0 Success
497 * EFAULT Bad address
498 * copy[in]str:EFAULT Bad address
499 * copy[in]str:ENAMETOOLONG Filename too long
500 *
501 * Implicit returns:
502 * (imgp->ip_strings) saved path
503 * (imgp->ip_strspace) space remaining in ip_strings
504 * (imgp->ip_strendp) start of remaining copy area
505 * (imgp->ip_argspace) space remaining of NCARGS
506 * (imgp->ip_applec) Initial applev[0]
507 *
508 * Note: We have to do this before the initial namei() since in the
509 * path contains symbolic links, namei() will overwrite the
510 * original path buffer contents. If the last symbolic link
511 * resolved was a relative pathname, we would lose the original
512 * "path", which could be an absolute pathname. This might be
513 * unacceptable for dyld.
514 */
515 static int
exec_save_path(struct image_params * imgp,user_addr_t path,int seg,const char ** excpath)516 exec_save_path(struct image_params *imgp, user_addr_t path, int seg, const char **excpath)
517 {
518 int error;
519 size_t len;
520 char *kpath;
521
522 // imgp->ip_strings can come out of a cache, so we need to obliterate the
523 // old path.
524 memset(imgp->ip_strings, '\0', strlen(EXECUTABLE_KEY) + MAXPATHLEN);
525
526 len = MIN(MAXPATHLEN, imgp->ip_strspace);
527
528 switch (seg) {
529 case UIO_USERSPACE32:
530 case UIO_USERSPACE64: /* Same for copyin()... */
531 error = copyinstr(path, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len);
532 break;
533 case UIO_SYSSPACE:
534 kpath = CAST_DOWN(char *, path); /* SAFE */
535 error = copystr(kpath, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len);
536 break;
537 default:
538 error = EFAULT;
539 break;
540 }
541
542 if (!error) {
543 bcopy(EXECUTABLE_KEY, imgp->ip_strings, strlen(EXECUTABLE_KEY));
544 len += strlen(EXECUTABLE_KEY);
545
546 imgp->ip_strendp += len;
547 imgp->ip_strspace -= len;
548
549 if (excpath) {
550 *excpath = imgp->ip_strings + strlen(EXECUTABLE_KEY);
551 }
552 }
553
554 return error;
555 }
556
557 /*
558 * exec_reset_save_path
559 *
560 * If we detect a shell script, we need to reset the string area
561 * state so that the interpreter can be saved onto the stack.
562 *
563 * Parameters; struct image_params * image parameter block
564 *
565 * Returns: int 0 Success
566 *
567 * Implicit returns:
568 * (imgp->ip_strings) saved path
569 * (imgp->ip_strspace) space remaining in ip_strings
570 * (imgp->ip_strendp) start of remaining copy area
571 * (imgp->ip_argspace) space remaining of NCARGS
572 *
573 */
574 static int
exec_reset_save_path(struct image_params * imgp)575 exec_reset_save_path(struct image_params *imgp)
576 {
577 imgp->ip_strendp = imgp->ip_strings;
578 imgp->ip_argspace = NCARGS;
579 imgp->ip_strspace = (NCARGS + PAGE_SIZE);
580
581 return 0;
582 }
583
584 /*
585 * exec_shell_imgact
586 *
587 * Image activator for interpreter scripts. If the image begins with
588 * the characters "#!", then it is an interpreter script. Verify the
589 * length of the script line indicating the interpreter is not in
590 * excess of the maximum allowed size. If this is the case, then
591 * break out the arguments, if any, which are separated by white
592 * space, and copy them into the argument save area as if they were
593 * provided on the command line before all other arguments. The line
594 * ends when we encounter a comment character ('#') or newline.
595 *
596 * Parameters; struct image_params * image parameter block
597 *
598 * Returns: -1 not an interpreter (keep looking)
599 * -3 Success: interpreter: relookup
600 * >0 Failure: interpreter: error number
601 *
602 * A return value other than -1 indicates subsequent image activators should
603 * not be given the opportunity to attempt to activate the image.
604 */
605 static int
exec_shell_imgact(struct image_params * imgp)606 exec_shell_imgact(struct image_params *imgp)
607 {
608 char *vdata = imgp->ip_vdata;
609 char *ihp;
610 char *line_startp, *line_endp;
611 char *interp;
612
613 /*
614 * Make sure it's a shell script. If we've already redirected
615 * from an interpreted file once, don't do it again.
616 */
617 if (vdata[0] != '#' ||
618 vdata[1] != '!' ||
619 (imgp->ip_flags & IMGPF_INTERPRET) != 0) {
620 return -1;
621 }
622
623 if (imgp->ip_origcputype != 0) {
624 /* Fat header previously matched, don't allow shell script inside */
625 return -1;
626 }
627
628 imgp->ip_flags |= IMGPF_INTERPRET;
629 imgp->ip_interp_sugid_fd = -1;
630 imgp->ip_interp_buffer[0] = '\0';
631
632 /* Check to see if SUGID scripts are permitted. If they aren't then
633 * clear the SUGID bits.
634 * imgp->ip_vattr is known to be valid.
635 */
636 if (sugid_scripts == 0) {
637 imgp->ip_origvattr->va_mode &= ~(VSUID | VSGID);
638 }
639
640 /* Try to find the first non-whitespace character */
641 for (ihp = &vdata[2]; ihp < &vdata[IMG_SHSIZE]; ihp++) {
642 if (IS_EOL(*ihp)) {
643 /* Did not find interpreter, "#!\n" */
644 return ENOEXEC;
645 } else if (IS_WHITESPACE(*ihp)) {
646 /* Whitespace, like "#! /bin/sh\n", keep going. */
647 } else {
648 /* Found start of interpreter */
649 break;
650 }
651 }
652
653 if (ihp == &vdata[IMG_SHSIZE]) {
654 /* All whitespace, like "#! " */
655 return ENOEXEC;
656 }
657
658 line_startp = ihp;
659
660 /* Try to find the end of the interpreter+args string */
661 for (; ihp < &vdata[IMG_SHSIZE]; ihp++) {
662 if (IS_EOL(*ihp)) {
663 /* Got it */
664 break;
665 } else {
666 /* Still part of interpreter or args */
667 }
668 }
669
670 if (ihp == &vdata[IMG_SHSIZE]) {
671 /* A long line, like "#! blah blah blah" without end */
672 return ENOEXEC;
673 }
674
675 /* Backtrack until we find the last non-whitespace */
676 while (IS_EOL(*ihp) || IS_WHITESPACE(*ihp)) {
677 ihp--;
678 }
679
680 /* The character after the last non-whitespace is our logical end of line */
681 line_endp = ihp + 1;
682
683 /*
684 * Now we have pointers to the usable part of:
685 *
686 * "#! /usr/bin/int first second third \n"
687 * ^ line_startp ^ line_endp
688 */
689
690 /* copy the interpreter name */
691 interp = imgp->ip_interp_buffer;
692 for (ihp = line_startp; (ihp < line_endp) && !IS_WHITESPACE(*ihp); ihp++) {
693 *interp++ = *ihp;
694 }
695 *interp = '\0';
696
697 exec_reset_save_path(imgp);
698 exec_save_path(imgp, CAST_USER_ADDR_T(imgp->ip_interp_buffer),
699 UIO_SYSSPACE, NULL);
700
701 /* Copy the entire interpreter + args for later processing into argv[] */
702 interp = imgp->ip_interp_buffer;
703 for (ihp = line_startp; (ihp < line_endp); ihp++) {
704 *interp++ = *ihp;
705 }
706 *interp = '\0';
707
708 #if CONFIG_SETUID
709 /*
710 * If we have an SUID or SGID script, create a file descriptor
711 * from the vnode and pass /dev/fd/%d instead of the actual
712 * path name so that the script does not get opened twice
713 */
714 if (imgp->ip_origvattr->va_mode & (VSUID | VSGID)) {
715 proc_t p;
716 struct fileproc *fp;
717 int fd;
718 int error;
719
720 p = vfs_context_proc(imgp->ip_vfs_context);
721 error = falloc_exec(p, imgp->ip_vfs_context, &fp, &fd);
722 if (error) {
723 return error;
724 }
725
726 fp->fp_glob->fg_flag = FREAD;
727 fp->fp_glob->fg_ops = &vnops;
728 fp_set_data(fp, imgp->ip_vp);
729
730 proc_fdlock(p);
731 procfdtbl_releasefd(p, fd, NULL);
732 fp_drop(p, fd, fp, 1);
733 proc_fdunlock(p);
734 vnode_ref(imgp->ip_vp);
735
736 imgp->ip_interp_sugid_fd = fd;
737 }
738 #endif /* CONFIG_SETUID */
739
740 return -3;
741 }
742
743
744
745 /*
746 * exec_fat_imgact
747 *
748 * Image activator for fat 1.0 binaries. If the binary is fat, then we
749 * need to select an image from it internally, and make that the image
750 * we are going to attempt to execute. At present, this consists of
751 * reloading the first page for the image with a first page from the
752 * offset location indicated by the fat header.
753 *
754 * Parameters; struct image_params * image parameter block
755 *
756 * Returns: -1 not a fat binary (keep looking)
757 * -2 Success: encapsulated binary: reread
758 * >0 Failure: error number
759 *
760 * Important: This image activator is byte order neutral.
761 *
762 * Note: A return value other than -1 indicates subsequent image
763 * activators should not be given the opportunity to attempt
764 * to activate the image.
765 *
766 * If we find an encapsulated binary, we make no assertions
767 * about its validity; instead, we leave that up to a rescan
768 * for an activator to claim it, and, if it is claimed by one,
769 * that activator is responsible for determining validity.
770 */
771 static int
exec_fat_imgact(struct image_params * imgp)772 exec_fat_imgact(struct image_params *imgp)
773 {
774 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
775 kauth_cred_t cred = kauth_cred_proc_ref(p);
776 struct fat_header *fat_header = (struct fat_header *)imgp->ip_vdata;
777 struct _posix_spawnattr *psa = NULL;
778 struct fat_arch fat_arch;
779 int resid, error;
780 load_return_t lret;
781
782 if (imgp->ip_origcputype != 0) {
783 /* Fat header previously matched, don't allow another fat file inside */
784 error = -1; /* not claimed */
785 goto bad;
786 }
787
788 /* Make sure it's a fat binary */
789 if (OSSwapBigToHostInt32(fat_header->magic) != FAT_MAGIC) {
790 error = -1; /* not claimed */
791 goto bad;
792 }
793
794 /* imgp->ip_vdata has PAGE_SIZE, zerofilled if the file is smaller */
795 lret = fatfile_validate_fatarches((vm_offset_t)fat_header, PAGE_SIZE,
796 (off_t)imgp->ip_vattr->va_data_size);
797 if (lret != LOAD_SUCCESS) {
798 error = load_return_to_errno(lret);
799 goto bad;
800 }
801
802 /* If posix_spawn binprefs exist, respect those prefs. */
803 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
804 if (psa != NULL && psa->psa_binprefs[0] != 0) {
805 uint32_t pr = 0;
806
807 /* Check each preference listed against all arches in header */
808 for (pr = 0; pr < NBINPREFS; pr++) {
809 cpu_type_t pref = psa->psa_binprefs[pr];
810 cpu_type_t subpref = psa->psa_subcpuprefs[pr];
811
812 if (pref == 0) {
813 /* No suitable arch in the pref list */
814 error = EBADARCH;
815 goto bad;
816 }
817
818 if (pref == CPU_TYPE_ANY) {
819 /* Fall through to regular grading */
820 goto regular_grading;
821 }
822
823 lret = fatfile_getbestarch_for_cputype(pref,
824 subpref,
825 (vm_offset_t)fat_header,
826 PAGE_SIZE,
827 imgp,
828 &fat_arch);
829 if (lret == LOAD_SUCCESS) {
830 goto use_arch;
831 }
832 }
833
834 /* Requested binary preference was not honored */
835 error = EBADEXEC;
836 goto bad;
837 }
838
839 regular_grading:
840 /* Look up our preferred architecture in the fat file. */
841 lret = fatfile_getbestarch((vm_offset_t)fat_header,
842 PAGE_SIZE,
843 imgp,
844 &fat_arch,
845 (p->p_flag & P_AFFINITY) != 0);
846 if (lret != LOAD_SUCCESS) {
847 error = load_return_to_errno(lret);
848 goto bad;
849 }
850
851 use_arch:
852 /* Read the Mach-O header out of fat_arch */
853 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata,
854 PAGE_SIZE, fat_arch.offset,
855 UIO_SYSSPACE, (IO_UNIT | IO_NODELOCKED),
856 cred, &resid, p);
857 if (error) {
858 if (error == ERESTART) {
859 error = EINTR;
860 }
861 goto bad;
862 }
863
864 if (resid) {
865 memset(imgp->ip_vdata + (PAGE_SIZE - resid), 0x0, resid);
866 }
867
868 /* Success. Indicate we have identified an encapsulated binary */
869 error = -2;
870 imgp->ip_arch_offset = (user_size_t)fat_arch.offset;
871 imgp->ip_arch_size = (user_size_t)fat_arch.size;
872 imgp->ip_origcputype = fat_arch.cputype;
873 imgp->ip_origcpusubtype = fat_arch.cpusubtype;
874
875 bad:
876 kauth_cred_unref(&cred);
877 return error;
878 }
879
880 static int
activate_exec_state(task_t task,proc_t p,thread_t thread,load_result_t * result)881 activate_exec_state(task_t task, proc_t p, thread_t thread, load_result_t *result)
882 {
883 int ret;
884
885 (void)task_set_dyld_info(task, MACH_VM_MIN_ADDRESS, 0, false);
886 task_set_64bit(task, result->is_64bit_addr, result->is_64bit_data);
887 if (result->is_64bit_addr) {
888 OSBitOrAtomic(P_LP64, &p->p_flag);
889 get_bsdthread_info(thread)->uu_flag |= UT_LP64;
890 } else {
891 OSBitAndAtomic(~((uint32_t)P_LP64), &p->p_flag);
892 get_bsdthread_info(thread)->uu_flag &= ~UT_LP64;
893 }
894 task_set_mach_header_address(task, result->mach_header);
895
896 ret = thread_state_initialize(thread);
897 if (ret != KERN_SUCCESS) {
898 return ret;
899 }
900
901 if (result->threadstate) {
902 uint32_t *ts = result->threadstate;
903 uint32_t total_size = (uint32_t)result->threadstate_sz;
904
905 while (total_size > 0) {
906 uint32_t flavor = *ts++;
907 uint32_t size = *ts++;
908
909 ret = thread_setstatus(thread, flavor, (thread_state_t)ts, size);
910 if (ret) {
911 return ret;
912 }
913 ts += size;
914 total_size -= (size + 2) * sizeof(uint32_t);
915 }
916 }
917
918 thread_setentrypoint(thread, result->entry_point);
919
920 return KERN_SUCCESS;
921 }
922
923 #if (DEVELOPMENT || DEBUG)
924 extern char panic_on_proc_crash[];
925 extern int use_panic_on_proc_crash;
926
927 extern char panic_on_proc_exit[];
928 extern int use_panic_on_proc_exit;
929
930 extern char panic_on_proc_spawn_fail[];
931 extern int use_panic_on_proc_spawn_fail;
932
933 static inline void
set_crash_behavior_from_bootarg(proc_t p)934 set_crash_behavior_from_bootarg(proc_t p)
935 {
936 if (use_panic_on_proc_crash && strcmp(p->p_comm, panic_on_proc_crash) == 0) {
937 printf("will panic on proc crash: %s\n", p->p_comm);
938 p->p_crash_behavior |= POSIX_SPAWN_PANIC_ON_CRASH;
939 }
940
941 if (use_panic_on_proc_exit && strcmp(p->p_comm, panic_on_proc_exit) == 0) {
942 printf("will panic on proc exit: %s\n", p->p_comm);
943 p->p_crash_behavior |= POSIX_SPAWN_PANIC_ON_EXIT;
944 }
945
946 if (use_panic_on_proc_spawn_fail && strcmp(p->p_comm, panic_on_proc_spawn_fail) == 0) {
947 printf("will panic on proc spawn fail: %s\n", p->p_comm);
948 p->p_crash_behavior |= POSIX_SPAWN_PANIC_ON_SPAWN_FAIL;
949 }
950 }
951 #endif
952
953 void
set_proc_name(struct image_params * imgp,proc_t p)954 set_proc_name(struct image_params *imgp, proc_t p)
955 {
956 uint64_t buflen = imgp->ip_ndp->ni_cnd.cn_namelen;
957 const int p_name_len = sizeof(p->p_name) - 1;
958 const int p_comm_len = sizeof(p->p_comm) - 1;
959
960 if (buflen > p_name_len) {
961 buflen = p_name_len;
962 }
963
964 bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_name, buflen);
965 p->p_name[buflen] = '\0';
966
967 if (buflen > p_comm_len) {
968 static_assert(MAXCOMLEN + 1 == sizeof(p->p_comm));
969 buflen = p_comm_len;
970 }
971
972 bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_comm, buflen);
973 p->p_comm[buflen] = '\0';
974
975 #if (DEVELOPMENT || DEBUG)
976 /*
977 * This happens during image activation, so the crash behavior flags from
978 * posix_spawn will have already been set. So we don't have to worry about
979 * this being overridden.
980 */
981 set_crash_behavior_from_bootarg(p);
982 #endif
983 }
984
985 #if __has_feature(ptrauth_calls)
986 /**
987 * Returns a team ID string that may be used to assign a shared region.
988 *
989 * Platform binaries do not have team IDs and will return NULL. Non-platform
990 * binaries without a team ID will be assigned an artificial team ID of ""
991 * (empty string) so that they will not be assigned to the default shared
992 * region.
993 *
994 * @param imgp image parameter block
995 * @return NULL if this is a platform binary, or an appropriate team ID string
996 * otherwise
997 */
998 static inline const char *
get_teamid_for_shared_region(struct image_params * imgp)999 get_teamid_for_shared_region(struct image_params *imgp)
1000 {
1001 assert(imgp->ip_vp != NULL);
1002
1003 const char *ret = csvnode_get_teamid(imgp->ip_vp, imgp->ip_arch_offset);
1004 if (ret) {
1005 return ret;
1006 }
1007
1008 struct cs_blob *blob = csvnode_get_blob(imgp->ip_vp, imgp->ip_arch_offset);
1009 if (csblob_get_platform_binary(blob)) {
1010 return NULL;
1011 } else {
1012 static const char *NO_TEAM_ID = "";
1013 return NO_TEAM_ID;
1014 }
1015 }
1016
1017 /**
1018 * Determines whether ptrauth should be enabled for the provided arm64 CPU subtype.
1019 *
1020 * @param cpusubtype Mach-O style CPU subtype
1021 * @return whether the CPU subtype matches arm64e with the current ptrauth ABI
1022 */
1023 static inline bool
arm64_cpusubtype_uses_ptrauth(cpu_subtype_t cpusubtype)1024 arm64_cpusubtype_uses_ptrauth(cpu_subtype_t cpusubtype)
1025 {
1026 int ptrauth_abi_version = (int)CPU_SUBTYPE_ARM64_PTR_AUTH_VERSION(cpusubtype);
1027 return (cpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E &&
1028 (ptrauth_abi_version >= CPU_SUBTYPE_ARM64_PTR_AUTHV0_VERSION &&
1029 ptrauth_abi_version <= CPU_SUBTYPE_ARM64_PTR_AUTH_MAX_PREFERRED_VERSION);
1030 }
1031
1032 #endif /* __has_feature(ptrauth_calls) */
1033
1034 /**
1035 * Returns whether a type/subtype slice matches the requested
1036 * type/subtype.
1037 *
1038 * @param mask Bits to mask from the requested/tested cpu type
1039 * @param req_cpu Requested cpu type
1040 * @param req_subcpu Requested cpu subtype
1041 * @param test_cpu Tested slice cpu type
1042 * @param test_subcpu Tested slice cpu subtype
1043 */
1044 boolean_t
binary_match(cpu_type_t mask,cpu_type_t req_cpu,cpu_subtype_t req_subcpu,cpu_type_t test_cpu,cpu_subtype_t test_subcpu)1045 binary_match(cpu_type_t mask, cpu_type_t req_cpu,
1046 cpu_subtype_t req_subcpu, cpu_type_t test_cpu,
1047 cpu_subtype_t test_subcpu)
1048 {
1049 if ((test_cpu & ~mask) != (req_cpu & ~mask)) {
1050 return FALSE;
1051 }
1052
1053 test_subcpu &= ~CPU_SUBTYPE_MASK;
1054 req_subcpu &= ~CPU_SUBTYPE_MASK;
1055
1056 if (test_subcpu != req_subcpu && req_subcpu != (CPU_SUBTYPE_ANY & ~CPU_SUBTYPE_MASK)) {
1057 return FALSE;
1058 }
1059
1060 return TRUE;
1061 }
1062
1063
1064 /*
1065 * Check entitlements to see if this is a platform restrictions binary.
1066 * Save this in load_result until later for two purposes:
1067 * 1. We can mark the task at a certain security level once it's been created
1068 * 2. We can propagate which entitlements are present to the apple array
1069 */
1070 static inline void
encode_HR_entitlement(const char * entitlement,hardened_browser_flags_t mask,const struct image_params * imgp,load_result_t * load_result)1071 encode_HR_entitlement(const char *entitlement, hardened_browser_flags_t mask,
1072 const struct image_params *imgp, load_result_t *load_result)
1073 {
1074 if (IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, entitlement)) {
1075 load_result->hardened_browser |= mask;
1076 }
1077 }
1078
1079 /*
1080 * If the passed in executable's vnode should use the RSR
1081 * shared region, then this should return TRUE, otherwise, return FALSE.
1082 */
1083 static uint32_t rsr_current_version = 0;
1084 boolean_t (*rsr_check_vnode)(void *vnode) = NULL;
1085
1086 boolean_t
vnode_is_rsr(vnode_t vp)1087 vnode_is_rsr(vnode_t vp)
1088 {
1089 if (!(vnode_isreg(vp) && vnode_tag(vp) == VT_APFS)) {
1090 return FALSE;
1091 }
1092
1093 if (rsr_check_vnode != NULL && rsr_check_vnode((void *)vp)) {
1094 return TRUE;
1095 }
1096 return FALSE;
1097 }
1098
1099 static struct {
1100 char *legacy;
1101 char *security;
1102 } exec_security_mitigation_entitlement[] = {
1103 /* The following entries must match the enum declaration in kern_exec_internal.h */
1104 [HARDENED_PROCESS] = {
1105 "com.apple.developer.hardened-process",
1106 "com.apple.security.hardened-process"
1107 },
1108 [HARDENED_HEAP] = {
1109 "com.apple.developer.hardened-process.hardened-heap",
1110 "com.apple.security.hardened-process.hardened-heap"
1111 },
1112 [TPRO] = {
1113 NULL,
1114 "com.apple.security.hardened-process.dyld-ro",
1115 },
1116 #if HAS_MTE
1117 [CHECKED_ALLOCATIONS] = {
1118 "com.apple.developer.hardened-process.checked-allocations",
1119 "com.apple.security.hardened-process.checked-allocations"
1120 },
1121 [CHECKED_ALLOCATIONS_PURE_DATA] = {
1122 NULL,
1123 "com.apple.security.hardened-process.checked-allocations.enable-pure-data"
1124 },
1125 [CHECKED_ALLOCATIONS_NO_TAGGED_RECEIVE] = {
1126 NULL,
1127 "com.apple.security.hardened-process.checked-allocations.no-tagged-receive"
1128 },
1129 [CHECKED_ALLOCATIONS_SOFT_MODE] = {
1130 NULL,
1131 "com.apple.security.hardened-process.checked-allocations.soft-mode"
1132 },
1133 #endif /* HAS_MTE */
1134 [NO_GUARD_OBJECTS] = {
1135 NULL,
1136 "com.apple.security.hardened-process.no-guard-objects"
1137 }
1138 };
1139
1140 /*
1141 * Platform Restrictions
1142 *
1143 * This mitigation opts you into the grab bag of various kernel mitigations
1144 * including IPC security restrictions
1145 * The presence of the entitlement opts the binary into the feature.
1146 * The entitlement is an <integer> entitlement containing a version number
1147 * for the platform restrictions you are opting into.
1148 */
1149 #define SPAWN_ENABLE_PLATFORM_RESTRICTIONS "com.apple.security.hardened-process.platform-restrictions"
1150
1151 /* See kern_exec_internal.h for the extensive documentation. */
1152 exec_security_err_t
exec_check_security_entitlement(struct image_params * imgp,exec_security_mitigation_entitlement_t entitlement)1153 exec_check_security_entitlement(struct image_params *imgp,
1154 exec_security_mitigation_entitlement_t entitlement)
1155 {
1156 bool has_legacy_entitlement = false, has_security_entitlement = false;
1157 assert(exec_security_mitigation_entitlement[entitlement].security != NULL);
1158
1159 if (exec_security_mitigation_entitlement[entitlement].legacy != NULL) {
1160 has_legacy_entitlement =
1161 IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset,
1162 exec_security_mitigation_entitlement[entitlement].legacy);
1163 }
1164
1165 has_security_entitlement =
1166 IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset,
1167 exec_security_mitigation_entitlement[entitlement].security);
1168
1169 /* If both entitlements are present, this is an invalid configuration. */
1170 if (has_legacy_entitlement && has_security_entitlement) {
1171 EXEC_LOG("Binary has both legacy (%s) and security (%s) entitlements\n",
1172 exec_security_mitigation_entitlement[entitlement].legacy,
1173 exec_security_mitigation_entitlement[entitlement].security);
1174
1175 return EXEC_SECURITY_INVALID_CONFIG;
1176 }
1177
1178 if (has_legacy_entitlement || has_security_entitlement) {
1179 return EXEC_SECURITY_ENTITLED;
1180 }
1181
1182 return EXEC_SECURITY_NOT_ENTITLED;
1183 }
1184
1185
1186 /*
1187 * Entitled binaries get hardened_heap
1188 */
1189 static inline errno_t
imgact_setup_hardened_heap(struct image_params * imgp,task_t task)1190 imgact_setup_hardened_heap(struct image_params *imgp, task_t task)
1191 {
1192 exec_security_err_t ret = exec_check_security_entitlement(imgp, HARDENED_HEAP);
1193 if (ret == EXEC_SECURITY_ENTITLED) {
1194 task_set_hardened_heap(task);
1195 } else {
1196 task_clear_hardened_heap(task);
1197 }
1198 switch (ret) {
1199 case EXEC_SECURITY_INVALID_CONFIG:
1200 return EINVAL;
1201 case EXEC_SECURITY_ENTITLED:
1202 case EXEC_SECURITY_NOT_ENTITLED:
1203 return 0;
1204 }
1205 }
1206
1207 /*
1208 * Configure the platform restrictions security features on the task
1209 * This must be done before `ipc_task_enable` so that the bits
1210 * can be propagated to the ipc space.
1211 *
1212 * Requires `exectextresetvp` to be called on `task` previously so
1213 * that we can use the `IOTaskGetEntitlement` API
1214 */
1215 static inline void
exec_setup_platform_restrictions(task_t task)1216 exec_setup_platform_restrictions(task_t task)
1217 {
1218 uint64_t value = 0;
1219 /* Set platform restrictions version */
1220 if (task_get_platform_binary(task)) {
1221 task_set_platform_restrictions_version(task, 2);
1222 } else if (IOTaskGetIntegerEntitlement(task, SPAWN_ENABLE_PLATFORM_RESTRICTIONS, &value) &&
1223 value > 1) {
1224 task_set_platform_restrictions_version(task, value);
1225 }
1226 }
1227
1228 #if HAS_MTE || HAS_MTE_EMULATION_SHIMS
1229
1230 #if DEVELOPMENT || DEBUG
1231 static inline void config_sec_inheritance(task_t, task_t);
1232 #endif /* DEVELOPMENT || DEBUG */
1233 static inline void config_sec_spawnflags(load_result_t *load_result,
1234 struct _posix_spawnattr *, task_t);
1235
1236 #if HAS_MTE
1237
1238 static inline errno_t config_checked_allocations_entitlements(struct image_params *,
1239 load_result_t *, task_t, struct cs_blob *, proc_t);
1240
1241 static inline exec_security_err_t
imgact_setup_has_checked_allocations_entitlement(struct image_params * imgp,load_result_t * load_result,__unused task_t new_task,__unused struct cs_blob * cs_blob)1242 imgact_setup_has_checked_allocations_entitlement(struct image_params *imgp, load_result_t *load_result,
1243 __unused task_t new_task, __unused struct cs_blob *cs_blob)
1244 {
1245 /* First-party DriverKit always gets MTE regardless of our normal entitlement knobs */
1246 if (load_result->platform_binary && IOVnodeHasEntitlement(imgp->ip_vp,
1247 (int64_t)imgp->ip_arch_offset, kIODriverKitEntitlementKey)) {
1248 /* In soft mode, to mitigate risks on the build */
1249 EXEC_LOG("Enabling MTE because we're launching a first-party dext");
1250 return EXEC_SECURITY_ENTITLED;
1251 }
1252
1253 /* If not a hardened-process, bail out. */
1254 if (!load_result->hardened_process_version) {
1255 return EXEC_SECURITY_NOT_ENTITLED;
1256 }
1257
1258 /* Check the entitlement. */
1259 exec_security_err_t ret = exec_check_security_entitlement(imgp, CHECKED_ALLOCATIONS);
1260
1261 /* Bail out early on invalid configuration. These will fail execution. */
1262 if (ret == EXEC_SECURITY_INVALID_CONFIG) {
1263 return ret;
1264 }
1265
1266 /*
1267 * We need a couple of extra checks for first party binaries, mostly around
1268 * AMFI and reporting early (forbidden) usage of the entitlement.
1269 */
1270 if (load_result->platform_binary) {
1271 #if KERN_AMFI_SUPPORTS_MTE >= 2
1272 if (__improbable(amfi->has_mte_opt_out && amfi->has_mte_opt_out(cs_blob))) {
1273 EXEC_LOG("Binary checked-allocations enablement was denied by AMFI static list\n");
1274 return EXEC_SECURITY_NOT_ENTITLED;
1275 }
1276 #endif /* KERN_AMFI_SUPPORTS_MTE */
1277
1278 /*
1279 * At this stage we are an hardened-process and AMFI hasn't said that we should
1280 * not enable MTE, therefore we just force enable even if the entitlement is not
1281 * present (until we can publicly require checked-allocations to be true).
1282 */
1283 return EXEC_SECURITY_ENTITLED;
1284 }
1285
1286 /*
1287 * The third-party flow is more linear: whatever the entitlement said it was the
1288 * setting, we'll run with it.
1289 */
1290 return ret;
1291 }
1292 #endif /* HAS_MTE */
1293
1294 /*
1295 * Checked-allocations is a security feature that leverages MTE (Memory Tagging Extensions)
1296 * inside userspace allocators to protect dynamic memory allocations.
1297 *
1298 * MTE is a hardware security feature available in recent hardware devices. For legacy
1299 * devices, we support an internal-only readiness tool based on Rosetta that aims at
1300 * qualifying binaries for the new hardware, but that is not meant to be used in production.
1301 *
1302 * Checked-allocations enablement (generally referred to as MTE enabled here) and
1303 * configuration is controlled by:
1304 * - inheritance (debugging feature for bringup/readiness/performance evaluation)
1305 * - posix_spawn flags (no downgrade flags supported on RELEASE)
1306 * - entitlements (hardware only, no emulation. Main RELEASE configuration)
1307 *
1308 * The algorithm to decide whether checked-allocations should be enabled on the target
1309 * process is summarized here.
1310 * For Rosetta binaries, only posix_spawn flags are supported.
1311 *
1312 * ┌────────────────┐ ┌───────────────┐
1313 * │ Inheritance │ ┌───────────────┐ │ Configure MTE │
1314 * │ enabled? ├─YES──▶│ Enable MTE │──────▶│ mirroring │
1315 * └──────────┬─────┘ └───────────────┘ │ parent state │
1316 * │ └───────────────┘
1317 * NO
1318 * │
1319 * │ ┌─────────────────────────────┐
1320 * └─────▶│posix_spawn explicit enable? │
1321 * └──┬─────────────┬────────────┘
1322 * │ │
1323 * │ │
1324 * YES NO
1325 * │ │ ┌──────────────────────────────────┐
1326 * ┌───────────────┐ │ └──▶│ hardened-process entitlement or │
1327 * │ Enable MTE │◀────┘ │ (1p && DriverKit entitlement)? │
1328 * └───────┬───────┘ └───────────┬─────────────┬────────┘
1329 * │ YES NO
1330 * ┌───────▼───────┐ │ │
1331 * │ Configure MTE │ ┌──────────▼────┐ ┌────▼─────────┐
1332 * │ through │ │ Enable MTE │ │ Disable MTE │
1333 * │ posix_spawn │ └──────────┬────┘ └──────────────┘
1334 * │ flags │ │
1335 * └───────────────┘ ┌──────────▼────┐
1336 * │ Configure MTE │
1337 * │ through │
1338 * │ entitlements │
1339 * └───────────────┘
1340 *
1341 *
1342 * The above algorithm covers the decision of enabling checked-allocations but doesn't
1343 * cover the configuration options which are described later.
1344 *
1345 * This function returns false only in case POSIX_SPAWN_SECFLAG_EXPLICIT_REQUIRE_ENABLE is passed
1346 * and the binary fails to satisfy the requirement.
1347 */
1348 static inline errno_t
imgact_setup_sec(struct image_params * imgp,__unused load_result_t * load_result,task_t old_task,task_t new_task,__unused vm_map_t new_map,__unused proc_t new_proc)1349 imgact_setup_sec(struct image_params *imgp, __unused load_result_t *load_result, task_t old_task,
1350 task_t new_task, __unused vm_map_t new_map, __unused proc_t new_proc)
1351 {
1352 #if DEVELOPMENT || DEBUG
1353 #if HAS_MTE
1354 /* Nothing to do if we have disabled MTE system-wide */
1355 if (!is_mte_enabled) {
1356 EXEC_LOG("MTE enablement is skipped due to system-wide disablement\n");
1357 return 0;
1358 }
1359 #endif /* HAS_MTE */
1360
1361 #if HAS_MTE_EMULATION_SHIMS
1362 /* Ignore any emulation attempt if we are not running under Rosetta. */
1363 if ((imgp->ip_flags & (IMGPF_ROSETTA | IMGPF_ALT_ROSETTA)) == 0) {
1364 return 0;
1365 }
1366 #endif /* HAS_MTE_EMULATION_SHIMS */
1367 #endif /* DEVELOPMENT || DEBUG */
1368
1369 /* Reset to a clear view on the target task - we'll decide the configuration here. */
1370 task_clear_sec(new_task);
1371 task_clear_sec_policy(new_task);
1372
1373 /*
1374 * If the parent has sec inherit, propagate the security settings.
1375 * Inheritance is currently aimed only at debug sessions and will trump
1376 * any existing configuration. Inheritance should be seen as the same posix_spawn
1377 * flags used to enable it (+ configure the feature) re-applied over and over on
1378 * every descendant.
1379 */
1380 if (task_has_sec_inherit(old_task)) {
1381 EXEC_LOG("Task will be configured based on inheritance\n");
1382 /* Inheritance propagates to the next task. */
1383 task_set_sec_inherit(new_task);
1384
1385 if (task_has_sec(old_task)) {
1386 task_set_sec(new_task);
1387 #if DEVELOPMENT || DEBUG
1388 config_sec_inheritance(old_task, new_task);
1389 #endif /* DEVELOPMENT || DEBUG */
1390 }
1391 return 0;
1392 }
1393
1394 /* Check posix_spawn flags now if any */
1395 struct _posix_spawnattr *px_sa = imgp->ip_px_sa;
1396
1397 if (px_sa != NULL) {
1398 #if DEVELOPMENT || DEBUG
1399 /*
1400 * Do we have a request to explicitly disable?
1401 */
1402 if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_DISABLE) != 0) {
1403 EXEC_LOG("Task configured to disable the security feature due to posix_spawn\n");
1404 /* For A/B testing, allow DISABLE to propagate through inheritance. */
1405 config_sec_spawnflags(load_result, px_sa, new_task);
1406 /* Clear we were, clear we stay. */
1407 return 0;
1408 }
1409 #endif /* DEVELOPMENT || DEBUG */
1410
1411 /* Do we have a request to explicitly enable? */
1412 if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_ENABLE) != 0) {
1413 EXEC_LOG("Task is explicitly enabled via posix_spawn flags\n");
1414 task_set_sec(new_task);
1415 config_sec_spawnflags(load_result, px_sa, new_task);
1416 return 0;
1417 }
1418
1419 #if HAS_MTE
1420 /* Do we have a request to enforce that the target is properly entitled? */
1421 if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_REQUIRE_ENABLE) != 0) {
1422 if (!load_result->hardened_process_version) {
1423 EXEC_LOG("Caller requested the explicit presence of the hardened-process entitlement"
1424 " which the binary doesn't have\n");
1425 return EINVAL;
1426 }
1427 /* FALLTHROUGH to entitlement evaluation */
1428 }
1429 #endif /* HAS_MTE */
1430 }
1431
1432 #if HAS_MTE
1433
1434 #if DEVELOPMENT || DEBUG
1435 /* Runtime options solely affect entitlement-driven choices. */
1436 if (!mte_user_enabled()) {
1437 /* Clear we were, clear we stay. */
1438 return 0;
1439 }
1440 #endif /* DEVELOPMENT || DEBUG */
1441
1442 struct cs_blob* cs_blob = csvnode_get_blob(imgp->ip_vp, imgp->ip_arch_offset);
1443
1444 switch (imgact_setup_has_checked_allocations_entitlement(imgp, load_result, new_task, cs_blob)) {
1445 case EXEC_SECURITY_INVALID_CONFIG:
1446 EXEC_LOG("Invalid configuration detected\n");
1447 return EINVAL;
1448 case EXEC_SECURITY_ENTITLED:
1449 EXEC_LOG("Task is explicitly configured via entitlements\n");
1450 task_set_sec(new_task);
1451 return config_checked_allocations_entitlements(imgp, load_result, new_task, cs_blob,
1452 new_proc);
1453 case EXEC_SECURITY_NOT_ENTITLED:
1454 #if DEVELOPMENT || DEBUG
1455 /* Last chance: everything 1p is force-enabled. */
1456 if (mte_force_all_enabled() && load_result->platform_binary) {
1457 EXEC_LOG("Task is explicitly configured via enable-all boot-arg\n");
1458 task_set_sec(new_task);
1459 }
1460 #endif /* DEVELOPMENT || DEBUG */
1461 return 0;
1462 default:
1463 panic("Invalid return value from entitlement evaluation");
1464 }
1465 #endif /* HAS_MTE */
1466
1467 return 0;
1468 }
1469
1470 /*
1471 * MTE/Checked-allocation configuration.
1472 *
1473 * There are three configuration vectors: inheritance, posix_spawn flags and entitlements.
1474 * Each of the functions below covers one configuration vector.
1475 *
1476 * Configuration vectors are designed to be exclusive when it comes to define how the
1477 * feature will behave. This means that if configurations happens through inheritance,
1478 * it will trump any posix_spawn flag or entitlement and if it happens through
1479 * posix_spawn flag, it will trump entitlements.
1480 *
1481 * Inheritance is provided as a dev feature and needs to be explicitly "enabled" via posix_spawn.
1482 * Just like posix_spawn, it's not allowed to downgrade MTE state.
1483 *
1484 * While there are several posix_spawn flags, the majority of them is again only for
1485 * DEVELOPMENT || DEBUG. Only flags that do not _decrease_ the security posture of the
1486 * target are supported in production (essentially, only flags that _enable_ features).
1487 * posix_spawn flags are also the only way to control the emulation of MTE via the
1488 * readiness tool based on Rosetta.
1489 *
1490 * Entitlements are the expected and preferred way to configure MTE/checked-allocations
1491 * for the system. They are not supported for the Rosetta based emulation.
1492 */
1493
1494 #if DEVELOPMENT || DEBUG
1495 static inline void
config_sec_inheritance(task_t current,task_t new_task)1496 config_sec_inheritance(task_t current, task_t new_task)
1497 {
1498 /* Configure the target task based on current task */
1499 if (task_has_sec_never_check(current)) {
1500 task_set_sec_never_check(new_task);
1501 vm_map_set_sec_disabled(get_task_map(new_task));
1502 }
1503
1504 if (task_has_sec_user_data(current)) {
1505 task_set_sec_user_data(new_task);
1506 }
1507
1508 /* Allow soft-mode to propagate for internal testing */
1509 if (task_has_sec_soft_mode(current)) {
1510 task_set_sec_soft_mode(new_task);
1511 }
1512 }
1513
1514 #endif /* DEVELOPMENT || DEBUG */
1515
1516 static inline void
config_sec_spawnflags(load_result_t * load_result,struct _posix_spawnattr * px_sa,task_t new_task)1517 config_sec_spawnflags(load_result_t *load_result,
1518 struct _posix_spawnattr *px_sa, task_t new_task)
1519 {
1520 /* We cannot be here if there were no posix_spawn attributes */
1521 assert(px_sa);
1522
1523 /*
1524 * Most configurations are not available on RELEASE, but we need to
1525 * allow inheritance for Xcode debugging workflows.
1526 */
1527 if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_ENABLE_INHERIT) != 0) {
1528 EXEC_LOG("Task explicitly enables inheritance via posix_spawn flags\n");
1529 task_set_sec_inherit(new_task);
1530 }
1531
1532 /*
1533 * On both RELEASE and DEVELOPMENT, we allow preflighting MTE through
1534 * posix spawn flags: unlike POSIX_SPAWN_SECFLAG_EXPLICIT_CHECK_BYPASS,
1535 * with POSIX_SPAWN_SECFLAG_EXPLICIT_PREFLIGHT we only allow turning
1536 * on soft mode if the process is not a hardened process.
1537 */
1538 if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_PREFLIGHT) != 0) {
1539 if (!load_result->hardened_process_version) {
1540 EXEC_LOG("Task explicitly enables soft-mode preflight via posix_spawn flags\n");
1541 task_set_sec_soft_mode(new_task);
1542 }
1543 }
1544
1545 #if DEVELOPMENT || DEBUG
1546 if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_ENABLE_PURE_DATA) != 0) {
1547 EXEC_LOG("Task explicitly enables userspace coverage via posix_spawn flags\n");
1548 task_set_sec_user_data(new_task);
1549 }
1550
1551 /* Allow testing of soft-mode via posix_spawn */
1552 if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_CHECK_BYPASS) != 0) {
1553 EXEC_LOG("Task explicitly enables soft-mode via posix_spawn flags\n");
1554 task_set_sec_soft_mode(new_task);
1555 }
1556
1557 if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_NEVER_CHECK_ENABLE) != 0) {
1558 task_set_sec_never_check(new_task);
1559 vm_map_set_sec_disabled(get_task_map(new_task));
1560 }
1561 #endif /* DEVELOPMENT || DEBUG */
1562 }
1563
1564 #if HAS_MTE
1565
1566 static inline errno_t
config_checked_allocations_entitlements(struct image_params * imgp,load_result_t * load_result,task_t new_task,__unused struct cs_blob * cs_blob,__unused proc_t new_proc)1567 config_checked_allocations_entitlements(struct image_params *imgp, load_result_t *load_result,
1568 task_t new_task, __unused struct cs_blob *cs_blob, __unused proc_t new_proc)
1569 {
1570 /* Determine whether we should enable pure-data allocations. */
1571 exec_security_err_t ret = exec_check_security_entitlement(imgp,
1572 CHECKED_ALLOCATIONS_PURE_DATA);
1573 assert(ret == EXEC_SECURITY_ENTITLED || ret == EXEC_SECURITY_NOT_ENTITLED);
1574
1575 if (ret == EXEC_SECURITY_ENTITLED) {
1576 task_set_sec_user_data(new_task);
1577 EXEC_LOG("Enabling user data tagging due to entitlement\n");
1578 }
1579
1580
1581 /*
1582 * Check whether we need to restrict receiving aliases to MTE memory (which are, by policy,
1583 * untagged) from other actors.
1584 */
1585 ret = exec_check_security_entitlement(imgp, CHECKED_ALLOCATIONS_NO_TAGGED_RECEIVE);
1586 assert(ret == EXEC_SECURITY_ENTITLED || ret == EXEC_SECURITY_NOT_ENTITLED);
1587
1588 if (ret == EXEC_SECURITY_ENTITLED) {
1589 EXEC_LOG("Restricting receiving aliases to tagged memory due to entitlement\n");
1590 task_set_sec_restrict_receiving_aliases_to_tagged_memory(new_task);
1591 }
1592
1593
1594 ret = exec_check_security_entitlement(imgp, CHECKED_ALLOCATIONS_SOFT_MODE);
1595 assert(ret == EXEC_SECURITY_ENTITLED || ret == EXEC_SECURITY_NOT_ENTITLED);
1596
1597 /*
1598 * All 1p processes run in hard-mode in lockdown mode, regardless of their
1599 * entitlement configuration.
1600 */
1601 if (load_result->platform_binary && get_lockdown_mode_state() != 0) {
1602 ret = EXEC_SECURITY_NOT_ENTITLED;
1603 }
1604
1605 /*
1606 * Force enable soft-mode for anything that is not a platform binary.
1607 */
1608 if (ret == EXEC_SECURITY_ENTITLED || !load_result->platform_binary) {
1609 EXEC_LOG("Enabling soft-mode from entitlement\n");
1610 task_set_sec_soft_mode(new_task);
1611 }
1612
1613 return EXEC_SECURITY_NOT_ENTITLED;
1614 }
1615
1616 #endif /* HAS_MTE */
1617 #endif /* HAS_MTE || HAS_MTE_EMULATION_SHIMS */
1618
1619 static inline errno_t
imgact_setup_guard_objects(struct image_params * imgp,load_result_t * load_result,task_t task)1620 imgact_setup_guard_objects(struct image_params *imgp, load_result_t *load_result, task_t task)
1621 {
1622 exec_security_err_t ret = exec_check_security_entitlement(imgp, NO_GUARD_OBJECTS);
1623 if (ret == EXEC_SECURITY_NOT_ENTITLED &&
1624 load_result->hardened_process_version >= HARDENED_PROCESS_VERSION_TWO) {
1625 /* apply guard objects entitlement if hardened-process and not disabled */
1626 task_set_guard_objects(task);
1627 return 0;
1628 }
1629
1630 task_clear_guard_objects(task);
1631
1632 if (ret == EXEC_SECURITY_INVALID_CONFIG) {
1633 return EINVAL;
1634 }
1635
1636 return 0;
1637 }
1638
1639 /*
1640 * This routine configures the various runtime mitigations we can apply to a process
1641 * during image activation. This occurs before `imgact_setup_runtime_mitigations`
1642 *
1643 * Returns true on success, false on failure. Failure will be fatal in exec_mach_imgact().
1644 */
1645 static inline errno_t
imgact_setup_runtime_mitigations(struct image_params * imgp,__unused load_result_t * load_result,__unused task_t old_task,task_t new_task,__unused vm_map_t map,__unused proc_t proc)1646 imgact_setup_runtime_mitigations(struct image_params *imgp, __unused load_result_t *load_result,
1647 __unused task_t old_task, task_t new_task, __unused vm_map_t map, __unused proc_t proc)
1648 {
1649 /* Set hardened process version */
1650 task_set_hardened_process_version(new_task, load_result->hardened_process_version);
1651
1652 /*
1653 * It's safe to check entitlements anytime after `load_machfile` if you check
1654 * based on the vnode in imgp. We must perform this entitlement check
1655 * before we start using load_result->hardened_browser further down
1656 */
1657 load_result->hardened_browser = 0;
1658 encode_HR_entitlement(kCSWebBrowserHostEntitlement, BrowserHostEntitlementMask, imgp, load_result);
1659 encode_HR_entitlement(kCSWebBrowserGPUEntitlement, BrowserGPUEntitlementMask, imgp, load_result);
1660 encode_HR_entitlement(kCSWebBrowserNetworkEntitlement, BrowserNetworkEntitlementMask, imgp, load_result);
1661 encode_HR_entitlement(kCSWebBrowserWebContentEntitlement, BrowserWebContentEntitlementMask, imgp, load_result);
1662
1663 if (load_result->hardened_browser) {
1664 task_set_platform_restrictions_version(new_task, 1);
1665 }
1666
1667 errno_t retval = 0;
1668
1669 /*
1670 * Hardened-heap enables a set of extra security features in our system memory allocator.
1671 */
1672 if ((retval = imgact_setup_hardened_heap(imgp, new_task)) != 0) {
1673 EXEC_LOG("Invalid configuration detected for hardened-heap");
1674 return retval;
1675 }
1676
1677 #if HAS_MTE || HAS_MTE_EMULATION_SHIMS
1678 /*
1679 * Sec-shims a.k.a. checked-allocations a.k.a. MTE (due to several hoops around secrecy)
1680 * control whether the target process system allocators leverage MTE or not to provide
1681 * further security mitigations.
1682 */
1683 if ((retval = imgact_setup_sec(imgp, load_result, old_task, new_task, map, proc)) != 0) {
1684 EXEC_LOG("Invalid configuration detected for the security shim");
1685 return retval;
1686 }
1687 #endif /* HAS_MTE || HAS_MTE_EMULATION_SHIMS */
1688
1689 /*
1690 * No-guard-objects disables guards for process deallocated allocations or VM.
1691 */
1692 if ((retval = imgact_setup_guard_objects(imgp, load_result, new_task)) != 0) {
1693 EXEC_LOG("Invalid configuration detected for no-guard-objects");
1694 return retval;
1695 }
1696
1697 return retval;
1698 }
1699
1700 uint32_t
rsr_get_version(void)1701 rsr_get_version(void)
1702 {
1703 return os_atomic_load(&rsr_current_version, relaxed);
1704 }
1705
1706 void
rsr_bump_version(void)1707 rsr_bump_version(void)
1708 {
1709 os_atomic_inc(&rsr_current_version, relaxed);
1710 }
1711
1712 #if XNU_TARGET_OS_OSX
1713 static int
1714 rsr_version_sysctl SYSCTL_HANDLER_ARGS
1715 {
1716 #pragma unused(arg1, arg2, oidp)
1717 int value = rsr_get_version();
1718 int error = SYSCTL_OUT(req, &value, sizeof(int));
1719 if (error) {
1720 return error;
1721 }
1722
1723 if (!req->newptr) {
1724 return 0;
1725 }
1726
1727 error = SYSCTL_IN(req, &value, sizeof(int));
1728 if (error) {
1729 return error;
1730 }
1731 if (value != 0) {
1732 rsr_bump_version();
1733 }
1734 return 0;
1735 }
1736
1737
1738 SYSCTL_PROC(_vm, OID_AUTO, shared_region_control,
1739 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_MASKED,
1740 0, 0, rsr_version_sysctl, "I", "");
1741 #endif /* XNU_TARGET_OS_OSX */
1742
1743 /*
1744 * exec_mach_imgact
1745 *
1746 * Image activator for mach-o 1.0 binaries.
1747 *
1748 * Parameters; struct image_params * image parameter block
1749 *
1750 * Returns: -1 not a fat binary (keep looking)
1751 * -2 Success: encapsulated binary: reread
1752 * >0 Failure: error number
1753 * EBADARCH Mach-o binary, but with an unrecognized
1754 * architecture
1755 * ENOMEM No memory for child process after -
1756 * can only happen after vfork()
1757 *
1758 * Important: This image activator is NOT byte order neutral.
1759 *
1760 * Note: A return value other than -1 indicates subsequent image
1761 * activators should not be given the opportunity to attempt
1762 * to activate the image.
1763 */
1764 static int
exec_mach_imgact(struct image_params * imgp)1765 exec_mach_imgact(struct image_params *imgp)
1766 {
1767 struct mach_header *mach_header = (struct mach_header *)imgp->ip_vdata;
1768 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
1769 int error = 0;
1770 task_t task;
1771 task_t new_task = NULL; /* protected by vfexec */
1772 thread_t thread;
1773 struct uthread *uthread;
1774 vm_map_switch_context_t switch_ctx;
1775 vm_map_t old_map = VM_MAP_NULL;
1776 vm_map_t map = VM_MAP_NULL;
1777 load_return_t lret;
1778 load_result_t load_result = {};
1779 struct _posix_spawnattr *psa = NULL;
1780 int spawn = (imgp->ip_flags & IMGPF_SPAWN);
1781 const int vfexec = 0;
1782 int exec = (imgp->ip_flags & IMGPF_EXEC);
1783 os_reason_t exec_failure_reason = OS_REASON_NULL;
1784 boolean_t reslide = FALSE;
1785 char * userspace_coredump_name = NULL;
1786
1787 /*
1788 * make sure it's a Mach-O 1.0 or Mach-O 2.0 binary; the difference
1789 * is a reserved field on the end, so for the most part, we can
1790 * treat them as if they were identical. Reverse-endian Mach-O
1791 * binaries are recognized but not compatible.
1792 */
1793 if ((mach_header->magic == MH_CIGAM) ||
1794 (mach_header->magic == MH_CIGAM_64)) {
1795 error = EBADARCH;
1796 goto bad;
1797 }
1798
1799 if ((mach_header->magic != MH_MAGIC) &&
1800 (mach_header->magic != MH_MAGIC_64)) {
1801 error = -1;
1802 goto bad;
1803 }
1804
1805 if (mach_header->filetype != MH_EXECUTE) {
1806 error = -1;
1807 goto bad;
1808 }
1809
1810 if (imgp->ip_origcputype != 0) {
1811 /* Fat header previously had an idea about this thin file */
1812 if (imgp->ip_origcputype != mach_header->cputype ||
1813 imgp->ip_origcpusubtype != mach_header->cpusubtype) {
1814 error = EBADARCH;
1815 goto bad;
1816 }
1817 } else {
1818 imgp->ip_origcputype = mach_header->cputype;
1819 imgp->ip_origcpusubtype = mach_header->cpusubtype;
1820 }
1821
1822 task = current_task();
1823 thread = current_thread();
1824 uthread = get_bsdthread_info(thread);
1825
1826 if ((mach_header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64) {
1827 imgp->ip_flags |= IMGPF_IS_64BIT_ADDR | IMGPF_IS_64BIT_DATA;
1828 }
1829
1830
1831 /* If posix_spawn binprefs exist, respect those prefs. */
1832 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
1833 if (psa != NULL && psa->psa_binprefs[0] != 0) {
1834 int pr = 0;
1835 for (pr = 0; pr < NBINPREFS; pr++) {
1836 cpu_type_t pref = psa->psa_binprefs[pr];
1837 cpu_subtype_t subpref = psa->psa_subcpuprefs[pr];
1838
1839 if (pref == 0) {
1840 /* No suitable arch in the pref list */
1841 error = EBADARCH;
1842 goto bad;
1843 }
1844
1845 if (pref == CPU_TYPE_ANY) {
1846 /* Jump to regular grading */
1847 goto grade;
1848 }
1849
1850 if (binary_match(CPU_ARCH_MASK, pref, subpref,
1851 imgp->ip_origcputype, imgp->ip_origcpusubtype)) {
1852 goto grade;
1853 }
1854 }
1855 error = EBADARCH;
1856 goto bad;
1857 }
1858 grade:
1859 if (!grade_binary(imgp->ip_origcputype, imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK,
1860 imgp->ip_origcpusubtype & CPU_SUBTYPE_MASK, TRUE)) {
1861 error = EBADARCH;
1862 goto bad;
1863 }
1864
1865 if (validate_potential_simulator_binary(imgp->ip_origcputype, imgp,
1866 imgp->ip_arch_offset, imgp->ip_arch_size) != LOAD_SUCCESS) {
1867 #if __x86_64__
1868 const char *excpath;
1869 error = exec_save_path(imgp, imgp->ip_user_fname, imgp->ip_seg, &excpath);
1870 os_log_error(OS_LOG_DEFAULT, "Unsupported 32-bit executable: \"%s\"", (error) ? imgp->ip_vp->v_name : excpath);
1871 #endif
1872 error = EBADARCH;
1873 goto bad;
1874 }
1875
1876 #if defined(HAS_APPLE_PAC)
1877 assert(mach_header->cputype == CPU_TYPE_ARM64
1878 );
1879
1880 if ((mach_header->cputype == CPU_TYPE_ARM64 &&
1881 arm64_cpusubtype_uses_ptrauth(mach_header->cpusubtype))
1882 ) {
1883 imgp->ip_flags &= ~IMGPF_NOJOP;
1884 } else {
1885 imgp->ip_flags |= IMGPF_NOJOP;
1886 }
1887 #endif
1888
1889 /* Copy in arguments/environment from the old process */
1890 error = exec_extract_strings(imgp);
1891 if (error) {
1892 goto bad;
1893 }
1894
1895 AUDIT_ARG(argv, imgp->ip_startargv, imgp->ip_argc,
1896 imgp->ip_endargv - imgp->ip_startargv);
1897 AUDIT_ARG(envv, imgp->ip_endargv, imgp->ip_envc,
1898 imgp->ip_endenvv - imgp->ip_endargv);
1899
1900 /* reset local idea of thread, uthread, task */
1901 thread = imgp->ip_new_thread;
1902 uthread = get_bsdthread_info(thread);
1903 task = new_task = get_threadtask(thread);
1904
1905 /*
1906 * Load the Mach-O file.
1907 *
1908 * NOTE: An error after this point indicates we have potentially
1909 * destroyed or overwritten some process state while attempting an
1910 * execve() following a vfork(), which is an unrecoverable condition.
1911 * We send the new process an immediate SIGKILL to avoid it executing
1912 * any instructions in the mutated address space. For true spawns,
1913 * this is not the case, and "too late" is still not too late to
1914 * return an error code to the parent process.
1915 */
1916
1917 /*
1918 * Actually load the image file we previously decided to load.
1919 */
1920 lret = load_machfile(imgp, mach_header, thread, &map, &load_result);
1921 if (lret != LOAD_SUCCESS) {
1922 error = load_return_to_errno(lret);
1923
1924 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1925 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO, 0, 0);
1926 if (lret == LOAD_BADMACHO_UPX) {
1927 set_proc_name(imgp, p);
1928 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_UPX);
1929 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1930 } else {
1931 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO);
1932
1933 if (bootarg_execfailurereports) {
1934 set_proc_name(imgp, p);
1935 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1936 }
1937 }
1938
1939 exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE;
1940
1941 goto badtoolate;
1942 }
1943
1944 assert(imgp->ip_free_map == NULL);
1945
1946 /*
1947 * ERROR RECOVERY
1948 *
1949 * load_machfile() returned the new VM map ("map") but we haven't
1950 * committed to it yet.
1951 * Any error path between here and the point where we commit to using
1952 * the new "map" (with swap_task_map()) should deallocate "map".
1953 */
1954
1955 #ifndef KASAN
1956 /*
1957 * Security: zone sanity checks on fresh boot or initproc re-exec.
1958 * launchd by design does not tear down its own service port on USR (rdar://72797967),
1959 * which means here is the earliest point we can assert on empty service port label zone,
1960 * after load_machfile() above terminates old launchd's IPC space.
1961 *
1962 * Disable on KASAN builds since zone_size_allocated() accounts for elements
1963 * under quarantine.
1964 */
1965 if (task_pid(task) == 1) {
1966 zone_userspace_reboot_checks();
1967 }
1968 #endif
1969
1970 proc_lock(p);
1971 p->p_cputype = imgp->ip_origcputype;
1972 p->p_cpusubtype = imgp->ip_origcpusubtype;
1973 proc_setplatformdata(p, load_result.ip_platform, load_result.lr_min_sdk, load_result.lr_sdk);
1974
1975 vm_map_set_size_limit(map, proc_limitgetcur(p, RLIMIT_AS));
1976 vm_map_set_data_limit(map, proc_limitgetcur(p, RLIMIT_DATA));
1977 vm_map_set_user_wire_limit(map, (vm_size_t)proc_limitgetcur(p, RLIMIT_MEMLOCK));
1978
1979 #if XNU_TARGET_OS_OSX
1980 if (proc_platform(p) == PLATFORM_IOS) {
1981 assert(vm_map_is_alien(map));
1982 } else {
1983 assert(!vm_map_is_alien(map));
1984 }
1985 #endif /* XNU_TARGET_OS_OSX */
1986 proc_unlock(p);
1987
1988 /*
1989 * Setup runtime mitigations.
1990 */
1991 if ((error = imgact_setup_runtime_mitigations(imgp, &load_result, current_task(), new_task, map, p)) != 0) {
1992 set_proc_name(imgp, p);
1993 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO);
1994 if (bootarg_execfailurereports) {
1995 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1996 exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE;
1997 }
1998 /* release new address space since we won't use it */
1999 imgp->ip_free_map = map;
2000 map = VM_MAP_NULL;
2001 goto badtoolate;
2002 }
2003
2004 /*
2005 * Set code-signing flags if this binary is signed, or if parent has
2006 * requested them on exec.
2007 */
2008 if (load_result.csflags & CS_VALID) {
2009 imgp->ip_csflags |= load_result.csflags &
2010 (CS_VALID | CS_SIGNED | CS_DEV_CODE | CS_LINKER_SIGNED |
2011 CS_HARD | CS_KILL | CS_RESTRICT | CS_ENFORCEMENT | CS_REQUIRE_LV |
2012 CS_FORCED_LV | CS_ENTITLEMENTS_VALIDATED | CS_NO_UNTRUSTED_HELPERS | CS_RUNTIME |
2013 CS_ENTITLEMENT_FLAGS |
2014 CS_EXEC_SET_HARD | CS_EXEC_SET_KILL | CS_EXEC_SET_ENFORCEMENT);
2015 } else {
2016 imgp->ip_csflags &= ~CS_VALID;
2017 }
2018
2019 if (proc_getcsflags(p) & CS_EXEC_SET_HARD) {
2020 imgp->ip_csflags |= CS_HARD;
2021 }
2022 if (proc_getcsflags(p) & CS_EXEC_SET_KILL) {
2023 imgp->ip_csflags |= CS_KILL;
2024 }
2025 if (proc_getcsflags(p) & CS_EXEC_SET_ENFORCEMENT) {
2026 imgp->ip_csflags |= CS_ENFORCEMENT;
2027 }
2028 if (proc_getcsflags(p) & CS_EXEC_INHERIT_SIP) {
2029 if (proc_getcsflags(p) & CS_INSTALLER) {
2030 imgp->ip_csflags |= CS_INSTALLER;
2031 }
2032 if (proc_getcsflags(p) & CS_DATAVAULT_CONTROLLER) {
2033 imgp->ip_csflags |= CS_DATAVAULT_CONTROLLER;
2034 }
2035 if (proc_getcsflags(p) & CS_NVRAM_UNRESTRICTED) {
2036 imgp->ip_csflags |= CS_NVRAM_UNRESTRICTED;
2037 }
2038 }
2039
2040 #if __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX)
2041 /*
2042 * ptrauth version 0 is a preview ABI. Developers can opt into running
2043 * their own arm64e binaries for local testing, with the understanding
2044 * that future OSes may break ABI.
2045 */
2046 if ((imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E &&
2047 CPU_SUBTYPE_ARM64_PTR_AUTH_VERSION(imgp->ip_origcpusubtype) == 0 &&
2048 !load_result.platform_binary &&
2049 !bootarg_arm64e_preview_abi) {
2050 static bool logged_once = false;
2051 set_proc_name(imgp, p);
2052
2053 printf("%s: not running binary \"%s\" built against preview arm64e ABI\n", __func__, p->p_name);
2054 if (!os_atomic_xchg(&logged_once, true, relaxed)) {
2055 printf("%s: (to allow this, add \"-arm64e_preview_abi\" to boot-args)\n", __func__);
2056 }
2057
2058 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO);
2059 if (bootarg_execfailurereports) {
2060 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2061 exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE;
2062 }
2063
2064 /* release new address space since we won't use it */
2065 imgp->ip_free_map = map;
2066 map = VM_MAP_NULL;
2067 goto badtoolate;
2068 }
2069
2070 if ((imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK) != CPU_SUBTYPE_ARM64E &&
2071 imgp->ip_origcputype == CPU_TYPE_ARM64 &&
2072 load_result.platform_binary &&
2073 (imgp->ip_flags & IMGPF_DRIVER) != 0) {
2074 set_proc_name(imgp, p);
2075 printf("%s: disallowing arm64 platform driverkit binary \"%s\", should be arm64e\n", __func__, p->p_name);
2076 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO);
2077 if (bootarg_execfailurereports) {
2078 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2079 exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE;
2080 }
2081
2082 /* release new address space since we won't use it */
2083 imgp->ip_free_map = map;
2084 map = VM_MAP_NULL;
2085 goto badtoolate;
2086 }
2087 #endif /* __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX) */
2088
2089
2090
2091 /*
2092 * Set up the shared cache region in the new process.
2093 *
2094 * Normally there is a single shared region per architecture.
2095 * However on systems with Pointer Authentication, we can create
2096 * multiple shared caches with the amount of sharing determined
2097 * by team-id or entitlement. Inherited shared region IDs are used
2098 * for system processes that need to match and be able to inspect
2099 * a pre-existing task.
2100 */
2101 int cpu_subtype = 0; /* all cpu_subtypes use the same shared region */
2102 #if __has_feature(ptrauth_calls)
2103 char *shared_region_id = NULL;
2104 size_t len;
2105 char *base;
2106 const char *cbase;
2107 #define HARDENED_RUNTIME_CONTENT_ID "C-"
2108 #define TEAM_ID_PREFIX "T-"
2109 #define ENTITLE_PREFIX "E-"
2110 #define SR_PREFIX_LEN 2
2111 #define SR_ENTITLEMENT "com.apple.pac.shared_region_id"
2112
2113 if (cpu_type() == CPU_TYPE_ARM64 &&
2114 arm64_cpusubtype_uses_ptrauth(p->p_cpusubtype) &&
2115 (imgp->ip_flags & IMGPF_NOJOP) == 0) {
2116 assertf(p->p_cputype == CPU_TYPE_ARM64,
2117 "p %p cpu_type() 0x%x p->p_cputype 0x%x p->p_cpusubtype 0x%x",
2118 p, cpu_type(), p->p_cputype, p->p_cpusubtype);
2119
2120 /*
2121 * arm64e uses pointer authentication, so request a separate
2122 * shared region for this CPU subtype.
2123 */
2124 cpu_subtype = p->p_cpusubtype & ~CPU_SUBTYPE_MASK;
2125
2126 /*
2127 * Determine which shared cache to select based on being told,
2128 * matching a team-id or matching an entitlement.
2129 */
2130 if (load_result.hardened_browser & BrowserWebContentEntitlementMask) {
2131 len = sizeof(HARDENED_RUNTIME_CONTENT_ID);
2132 shared_region_id = kalloc_data(len, Z_WAITOK | Z_NOFAIL);
2133 strlcpy(shared_region_id, HARDENED_RUNTIME_CONTENT_ID, len);
2134 } else if (imgp->ip_inherited_shared_region_id) {
2135 len = strlen(imgp->ip_inherited_shared_region_id);
2136 shared_region_id = kalloc_data(len + 1, Z_WAITOK | Z_NOFAIL);
2137 memcpy(shared_region_id, imgp->ip_inherited_shared_region_id, len + 1);
2138 } else if ((cbase = get_teamid_for_shared_region(imgp)) != NULL) {
2139 len = strlen(cbase);
2140 if (vm_shared_region_per_team_id) {
2141 shared_region_id = kalloc_data(len + SR_PREFIX_LEN + 1,
2142 Z_WAITOK | Z_NOFAIL);
2143 memcpy(shared_region_id, TEAM_ID_PREFIX, SR_PREFIX_LEN);
2144 memcpy(shared_region_id + SR_PREFIX_LEN, cbase, len + 1);
2145 }
2146 } else if ((base = IOVnodeGetEntitlement(imgp->ip_vp,
2147 (int64_t)imgp->ip_arch_offset, SR_ENTITLEMENT)) != NULL) {
2148 len = strlen(base);
2149 if (vm_shared_region_by_entitlement) {
2150 shared_region_id = kalloc_data(len + SR_PREFIX_LEN + 1,
2151 Z_WAITOK | Z_NOFAIL);
2152 memcpy(shared_region_id, ENTITLE_PREFIX, SR_PREFIX_LEN);
2153 memcpy(shared_region_id + SR_PREFIX_LEN, base, len + 1);
2154 }
2155 /* Discard the copy of the entitlement */
2156 kfree_data(base, len + 1);
2157 }
2158 }
2159
2160 if (imgp->ip_flags & IMGPF_RESLIDE) {
2161 reslide = TRUE;
2162 }
2163
2164 /* use "" as the default shared_region_id */
2165 if (shared_region_id == NULL) {
2166 shared_region_id = kalloc_data(1, Z_WAITOK | Z_ZERO | Z_NOFAIL);
2167 }
2168
2169 /* ensure there's a unique pointer signing key for this shared_region_id */
2170 shared_region_key_alloc(shared_region_id,
2171 imgp->ip_inherited_shared_region_id != NULL, imgp->ip_inherited_jop_pid);
2172 task_set_shared_region_id(task, shared_region_id);
2173 shared_region_id = NULL;
2174 #endif /* __has_feature(ptrauth_calls) */
2175
2176 #if CONFIG_ROSETTA
2177 if (imgp->ip_flags & IMGPF_ROSETTA) {
2178 OSBitOrAtomic(P_TRANSLATED, &p->p_flag);
2179 } else if (p->p_flag & P_TRANSLATED) {
2180 OSBitAndAtomic(~P_TRANSLATED, &p->p_flag);
2181 }
2182 #endif
2183
2184 int cputype = cpu_type();
2185
2186 uint32_t rsr_version = 0;
2187 #if XNU_TARGET_OS_OSX
2188 if (vnode_is_rsr(imgp->ip_vp)) {
2189 rsr_version = rsr_get_version();
2190 os_atomic_or(&p->p_ladvflag, P_RSR, relaxed);
2191 os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_ALTLINK, relaxed);
2192 }
2193 #endif /* XNU_TARGET_OS_OSX */
2194
2195 error = vm_map_exec(map, task, load_result.is_64bit_addr,
2196 (void *)p->p_fd.fd_rdir, cputype, cpu_subtype, reslide,
2197 (imgp->ip_flags & IMGPF_DRIVER) != 0,
2198 rsr_version);
2199
2200 if (error) {
2201 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2202 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_MAP_EXEC_FAILURE, 0, 0);
2203
2204 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_MAP_EXEC_FAILURE);
2205 if (bootarg_execfailurereports) {
2206 set_proc_name(imgp, p);
2207 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2208 exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE;
2209 }
2210 /* release new address space since we won't use it */
2211 imgp->ip_free_map = map;
2212 map = VM_MAP_NULL;
2213 goto badtoolate;
2214 }
2215
2216 /*
2217 * Close file descriptors which specify close-on-exec.
2218 */
2219 fdt_exec(p, vfs_context_ucred(imgp->ip_vfs_context),
2220 psa != NULL ? psa->psa_flags : 0, imgp->ip_new_thread, exec);
2221
2222 /*
2223 * deal with set[ug]id.
2224 */
2225 error = exec_handle_sugid(imgp);
2226 if (error) {
2227 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2228 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_SUGID_FAILURE, 0, 0);
2229
2230 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SUGID_FAILURE);
2231 if (bootarg_execfailurereports) {
2232 set_proc_name(imgp, p);
2233 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2234 }
2235
2236 /* release new address space since we won't use it */
2237 imgp->ip_free_map = map;
2238 map = VM_MAP_NULL;
2239 goto badtoolate;
2240 }
2241
2242 /*
2243 * Commit to new map.
2244 *
2245 * Swap the new map for the old for target task, which consumes
2246 * our new map reference but each leaves us responsible for the
2247 * old_map reference. That lets us get off the pmap associated
2248 * with it, and then we can release it.
2249 *
2250 * The map needs to be set on the target task which is different
2251 * than current task, thus swap_task_map is used instead of
2252 * vm_map_switch.
2253 */
2254 old_map = swap_task_map(task, thread, map);
2255 #if MACH_ASSERT
2256 /*
2257 * Reset the pmap's process info to prevent ledger checks
2258 * which might fail due to the ledgers being shared between
2259 * the old and new pmaps.
2260 */
2261 vm_map_pmap_set_process(old_map, -1, "<old_map>");
2262 #endif /* MACH_ASSERT */
2263 imgp->ip_free_map = old_map;
2264 old_map = NULL;
2265
2266 lret = activate_exec_state(task, p, thread, &load_result);
2267 if (lret != KERN_SUCCESS) {
2268 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2269 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_ACTV_THREADSTATE, 0, 0);
2270
2271 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_ACTV_THREADSTATE);
2272 if (bootarg_execfailurereports) {
2273 set_proc_name(imgp, p);
2274 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2275 }
2276
2277 goto badtoolate;
2278 }
2279
2280 /*
2281 * deal with voucher on exec-calling thread.
2282 */
2283 if (imgp->ip_new_thread == NULL) {
2284 thread_set_mach_voucher(current_thread(), IPC_VOUCHER_NULL);
2285 }
2286
2287 /* Make sure we won't interrupt ourself signalling a partial process */
2288 if (!vfexec && !spawn && (p->p_lflag & P_LTRACED)) {
2289 psignal(p, SIGTRAP);
2290 }
2291
2292 if (load_result.unixproc &&
2293 create_unix_stack(get_task_map(task),
2294 &load_result,
2295 p) != KERN_SUCCESS) {
2296 error = load_return_to_errno(LOAD_NOSPACE);
2297
2298 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2299 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_STACK_ALLOC, 0, 0);
2300
2301 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_STACK_ALLOC);
2302 if (bootarg_execfailurereports) {
2303 set_proc_name(imgp, p);
2304 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2305 }
2306
2307 goto badtoolate;
2308 }
2309
2310 /*
2311 * The load result will have already been munged by AMFI to include the
2312 * platform binary flag if boot-args dictated it (AMFI will mark anything
2313 * that doesn't go through the upcall path as a platform binary if its
2314 * enforcement is disabled).
2315 */
2316 if (load_result.platform_binary) {
2317 if (cs_debug) {
2318 printf("setting platform binary on task: pid = %d\n", proc_getpid(p));
2319 }
2320
2321 /*
2322 * We must use 'task' here because the proc's task has not yet been
2323 * switched to the new one.
2324 */
2325 task_set_platform_binary(task, TRUE);
2326 } else {
2327 if (cs_debug) {
2328 printf("clearing platform binary on task: pid = %d\n", proc_getpid(p));
2329 }
2330
2331 task_set_platform_binary(task, FALSE);
2332 }
2333
2334 #if XNU_TARGET_OS_OSX
2335 /* Disable mach hardening for all 1P tasks which load 3P plugins */
2336 if (imgp->ip_flags & IMGPF_3P_PLUGINS) {
2337 if (cs_debug) {
2338 printf("Disabling some mach hardening on task due to 3P plugins: pid = %d\n", proc_getpid(p));
2339 }
2340 task_disable_mach_hardening(task);
2341 }
2342 #if DEVELOPMENT || DEBUG
2343 /* Disable mach hardening for all tasks if amfi_get_out_of_my_way is set.
2344 * Customers will have to turn SIP off to use this boot-arg, and so this is
2345 * only needed internally since we disable this feature when SIP is off. */
2346 if (AMFI_bootarg_disable_mach_hardening) {
2347 if (cs_debug) {
2348 printf("Disabling some mach hardening on task due to AMFI boot-args: pid = %d\n", proc_getpid(p));
2349 }
2350 task_disable_mach_hardening(task);
2351 }
2352 #endif /* DEVELOPMENT || DEBUG */
2353 #endif /* XNU_TARGET_OS_OSX */
2354
2355 error = exec_add_apple_strings(imgp, &load_result, task); /* copies out main thread port */
2356
2357 if (error) {
2358 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2359 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_APPLE_STRING_INIT, 0, 0);
2360
2361 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_APPLE_STRING_INIT);
2362 if (bootarg_execfailurereports) {
2363 set_proc_name(imgp, p);
2364 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2365 }
2366 goto badtoolate;
2367 }
2368
2369 /* Switch to target task's map to copy out strings */
2370 switch_ctx = vm_map_switch_to(get_task_map(task));
2371
2372 if (load_result.unixproc) {
2373 user_addr_t ap;
2374
2375 /*
2376 * Copy the strings area out into the new process address
2377 * space.
2378 */
2379 ap = p->user_stack;
2380 error = exec_copyout_strings(imgp, &ap);
2381 if (error) {
2382 vm_map_switch_back(switch_ctx);
2383
2384 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2385 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_STRINGS, 0, 0);
2386
2387 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_STRINGS);
2388 if (bootarg_execfailurereports) {
2389 set_proc_name(imgp, p);
2390 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2391 }
2392 goto badtoolate;
2393 }
2394 /* Set the stack */
2395 thread_setuserstack(thread, ap);
2396 }
2397
2398 if (load_result.dynlinker || load_result.is_rosetta) {
2399 user_addr_t ap;
2400 int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4;
2401
2402 /* Adjust the stack */
2403 ap = thread_adjuserstack(thread, -new_ptr_size);
2404 error = copyoutptr(load_result.mach_header, ap, new_ptr_size);
2405
2406 if (error) {
2407 vm_map_switch_back(switch_ctx);
2408
2409 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2410 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_DYNLINKER, 0, 0);
2411
2412 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_DYNLINKER);
2413 if (bootarg_execfailurereports) {
2414 set_proc_name(imgp, p);
2415 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2416 }
2417 goto badtoolate;
2418 }
2419 error = task_set_dyld_info(task, load_result.all_image_info_addr,
2420 load_result.all_image_info_size, false);
2421 if (error) {
2422 vm_map_switch_back(switch_ctx);
2423
2424 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2425 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_SET_DYLD_INFO, 0, 0);
2426
2427 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SET_DYLD_INFO);
2428 if (bootarg_execfailurereports) {
2429 set_proc_name(imgp, p);
2430 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2431 }
2432 error = EINVAL;
2433 goto badtoolate;
2434 }
2435 } else {
2436 /*
2437 * No dyld or rosetta loaded, set the TF_DYLD_ALL_IMAGE_FINAL bit on task.
2438 */
2439 error = task_set_dyld_info(task, MACH_VM_MIN_ADDRESS,
2440 0, true);
2441 if (error) {
2442 vm_map_switch_back(switch_ctx);
2443
2444 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2445 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_SET_DYLD_INFO, 0, 0);
2446
2447 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SET_DYLD_INFO);
2448 if (bootarg_execfailurereports) {
2449 set_proc_name(imgp, p);
2450 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2451 }
2452 error = EINVAL;
2453 goto badtoolate;
2454 }
2455 }
2456
2457 #if CONFIG_ROSETTA
2458 if (load_result.is_rosetta) {
2459 // Add an fd for the executable file for Rosetta's use
2460 int main_binary_fd;
2461 struct fileproc *fp;
2462
2463 error = falloc_exec(p, imgp->ip_vfs_context, &fp, &main_binary_fd);
2464 if (error) {
2465 vm_map_switch_back(switch_ctx);
2466
2467 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2468 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC, 0, 0);
2469
2470 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC);
2471 if (bootarg_execfailurereports) {
2472 set_proc_name(imgp, p);
2473 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2474 }
2475 goto badtoolate;
2476 }
2477
2478 error = VNOP_OPEN(imgp->ip_vp, FREAD, imgp->ip_vfs_context);
2479 if (error) {
2480 vm_map_switch_back(switch_ctx);
2481
2482 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2483 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC, 0, 0);
2484
2485 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC);
2486 if (bootarg_execfailurereports) {
2487 set_proc_name(imgp, p);
2488 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2489 }
2490 goto cleanup_rosetta_fp;
2491 }
2492
2493 fp->fp_glob->fg_flag = FREAD;
2494 fp->fp_glob->fg_ops = &vnops;
2495 fp_set_data(fp, imgp->ip_vp);
2496
2497 proc_fdlock(p);
2498 procfdtbl_releasefd(p, main_binary_fd, NULL);
2499 fp_drop(p, main_binary_fd, fp, 1);
2500 proc_fdunlock(p);
2501
2502 vnode_ref(imgp->ip_vp);
2503
2504 // Pass the dyld load address, main binary fd, and dyld fd on the stack
2505 uint64_t ap = thread_adjuserstack(thread, -24);
2506
2507 error = copyoutptr((user_addr_t)load_result.dynlinker_fd, ap, 8);
2508 if (error) {
2509 vm_map_switch_back(switch_ctx);
2510
2511 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2512 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA, 0, 0);
2513
2514 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA);
2515 if (bootarg_execfailurereports) {
2516 set_proc_name(imgp, p);
2517 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2518 }
2519 goto cleanup_rosetta_fp;
2520 }
2521
2522 error = copyoutptr(load_result.dynlinker_mach_header, ap + 8, 8);
2523 if (error) {
2524 vm_map_switch_back(switch_ctx);
2525
2526 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2527 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA, 0, 0);
2528
2529 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA);
2530 if (bootarg_execfailurereports) {
2531 set_proc_name(imgp, p);
2532 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2533 }
2534 goto cleanup_rosetta_fp;
2535 }
2536
2537 error = copyoutptr((user_addr_t)main_binary_fd, ap + 16, 8);
2538 if (error) {
2539 vm_map_switch_back(switch_ctx);
2540
2541 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
2542 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA, 0, 0);
2543
2544 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA);
2545 if (bootarg_execfailurereports) {
2546 set_proc_name(imgp, p);
2547 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2548 }
2549 goto cleanup_rosetta_fp;
2550 }
2551
2552 cleanup_rosetta_fp:
2553 if (error) {
2554 fp_free(p, load_result.dynlinker_fd, load_result.dynlinker_fp);
2555 fp_free(p, main_binary_fd, fp);
2556 goto badtoolate;
2557 }
2558 }
2559
2560 #endif
2561
2562 /* Avoid immediate VM faults back into kernel */
2563 exec_prefault_data(p, imgp, &load_result);
2564
2565 vm_map_switch_back(switch_ctx);
2566
2567 /*
2568 * Reset signal state.
2569 */
2570 execsigs(p, thread);
2571
2572 /*
2573 * need to cancel async IO requests that can be cancelled and wait for those
2574 * already active. MAY BLOCK!
2575 */
2576 _aio_exec( p );
2577
2578 #if SYSV_SHM
2579 /* FIXME: Till vmspace inherit is fixed: */
2580 if (!vfexec && p->vm_shm) {
2581 shmexec(p);
2582 }
2583 #endif
2584 #if SYSV_SEM
2585 /* Clean up the semaphores */
2586 semexit(p);
2587 #endif
2588
2589 /*
2590 * Remember file name for accounting.
2591 */
2592 p->p_acflag &= ~AFORK;
2593
2594 set_proc_name(imgp, p);
2595
2596 #if CONFIG_SECLUDED_MEMORY
2597 if (secluded_for_apps &&
2598 load_result.platform_binary) {
2599 if (strncmp(p->p_name,
2600 "Camera",
2601 sizeof(p->p_name)) == 0) {
2602 task_set_could_use_secluded_mem(task, TRUE);
2603 } else {
2604 task_set_could_use_secluded_mem(task, FALSE);
2605 }
2606 if (strncmp(p->p_name,
2607 "mediaserverd",
2608 sizeof(p->p_name)) == 0) {
2609 task_set_could_also_use_secluded_mem(task, TRUE);
2610 }
2611 if (strncmp(p->p_name,
2612 "cameracaptured",
2613 sizeof(p->p_name)) == 0) {
2614 task_set_could_also_use_secluded_mem(task, TRUE);
2615 }
2616 }
2617 #endif /* CONFIG_SECLUDED_MEMORY */
2618
2619 #if __arm64__
2620 if (load_result.legacy_footprint) {
2621 task_set_legacy_footprint(task);
2622 }
2623 #endif /* __arm64__ */
2624
2625 pal_dbg_set_task_name(task);
2626
2627 #if DEVELOPMENT || DEBUG
2628 /*
2629 * Update the pid an proc name for importance base if any
2630 */
2631 task_importance_update_owner_info(task);
2632 #endif
2633
2634 proc_setexecutableuuid(p, &load_result.uuid[0]);
2635
2636 #if CONFIG_DTRACE
2637 dtrace_proc_exec(p);
2638 #endif
2639
2640 if (kdebug_enable) {
2641 long args[4] = {};
2642
2643 uintptr_t fsid = 0, fileid = 0;
2644 if (imgp->ip_vattr) {
2645 uint64_t fsid64 = vnode_get_va_fsid(imgp->ip_vattr);
2646 fsid = (uintptr_t)fsid64;
2647 fileid = (uintptr_t)imgp->ip_vattr->va_fileid;
2648 // check for (unexpected) overflow and trace zero in that case
2649 if (fsid != fsid64 || fileid != imgp->ip_vattr->va_fileid) {
2650 fsid = fileid = 0;
2651 }
2652 }
2653 KERNEL_DEBUG_CONSTANT_IST1(TRACE_DATA_EXEC, proc_getpid(p), fsid, fileid, 0,
2654 (uintptr_t)thread_tid(thread));
2655
2656 extern void kdebug_proc_name_args(struct proc *proc, long args[static 4]);
2657 kdebug_proc_name_args(p, args);
2658 KERNEL_DEBUG_CONSTANT_IST1(TRACE_STRING_EXEC, args[0], args[1],
2659 args[2], args[3], (uintptr_t)thread_tid(thread));
2660 }
2661
2662
2663 /*
2664 * If posix_spawned with the START_SUSPENDED flag, stop the
2665 * process before it runs.
2666 */
2667 if (imgp->ip_px_sa != NULL) {
2668 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
2669 if (psa->psa_flags & POSIX_SPAWN_START_SUSPENDED) {
2670 proc_lock(p);
2671 p->p_stat = SSTOP;
2672 proc_unlock(p);
2673 (void) task_suspend_internal(task);
2674 }
2675 }
2676
2677 /*
2678 * mark as execed
2679 */
2680 OSBitOrAtomic(P_EXEC, &p->p_flag);
2681 proc_resetregister(p);
2682 if (p->p_pptr && (p->p_lflag & P_LPPWAIT)) {
2683 proc_lock(p);
2684 p->p_lflag &= ~P_LPPWAIT;
2685 proc_unlock(p);
2686 wakeup((caddr_t)p->p_pptr);
2687 }
2688
2689 /*
2690 * Set up dext coredumps on kernel panic.
2691 * This requires the following:
2692 * - dext_panic_coredump=1 boot-arg (enabled by default on DEVELOPMENT, DEBUG and certain Seed builds)
2693 * - process must be a driver
2694 * - process must have the com.apple.private.enable-coredump-on-panic entitlement, and the
2695 * entitlement has a string value.
2696 * - process must have the com.apple.private.enable-coredump-on-panic-seed-privacy-approved
2697 * entitlement (Seed builds only).
2698 *
2699 * The core dump file name is formatted with the entitlement string value, followed by a hyphen
2700 * and the process PID.
2701 */
2702 if (enable_dext_coredumps_on_panic &&
2703 (imgp->ip_flags & IMGPF_DRIVER) != 0 &&
2704 (userspace_coredump_name = IOVnodeGetEntitlement(imgp->ip_vp,
2705 (int64_t)imgp->ip_arch_offset, USERSPACE_COREDUMP_PANIC_ENTITLEMENT)) != NULL) {
2706 size_t userspace_coredump_name_len = strlen(userspace_coredump_name);
2707
2708 char core_name[MACH_CORE_FILEHEADER_NAMELEN];
2709 /* 16 - NULL char - strlen("-") - maximum of 5 digits for pid */
2710 snprintf(core_name, MACH_CORE_FILEHEADER_NAMELEN, "%.9s-%d", userspace_coredump_name, proc_getpid(p));
2711
2712 kern_register_userspace_coredump(task, core_name);
2713
2714 /* Discard the copy of the entitlement */
2715 kfree_data(userspace_coredump_name, userspace_coredump_name_len + 1);
2716 userspace_coredump_name = NULL;
2717 }
2718
2719 goto done;
2720
2721 badtoolate:
2722 /* Don't allow child process to execute any instructions */
2723 if (!spawn) {
2724 {
2725 assert(exec_failure_reason != OS_REASON_NULL);
2726 if (bootarg_execfailurereports) {
2727 set_proc_name(imgp, current_proc());
2728 }
2729 psignal_with_reason(current_proc(), SIGKILL, exec_failure_reason);
2730 exec_failure_reason = OS_REASON_NULL;
2731
2732 if (exec) {
2733 /* Terminate the exec copy task */
2734 task_terminate_internal(task);
2735 }
2736 }
2737
2738 /* We can't stop this system call at this point, so just pretend we succeeded */
2739 error = 0;
2740 } else {
2741 os_reason_free(exec_failure_reason);
2742 exec_failure_reason = OS_REASON_NULL;
2743 }
2744
2745 done:
2746 if (load_result.threadstate) {
2747 kfree_data(load_result.threadstate, load_result.threadstate_sz);
2748 load_result.threadstate = NULL;
2749 }
2750
2751 bad:
2752 /* If we hit this, we likely would have leaked an exit reason */
2753 assert(exec_failure_reason == OS_REASON_NULL);
2754 return error;
2755 }
2756
2757
2758
2759
2760 /*
2761 * Our image activator table; this is the table of the image types we are
2762 * capable of loading. We list them in order of preference to ensure the
2763 * fastest image load speed.
2764 *
2765 * XXX hardcoded, for now; should use linker sets
2766 */
2767 struct execsw {
2768 int(*const ex_imgact)(struct image_params *);
2769 const char *ex_name;
2770 }const execsw[] = {
2771 { exec_mach_imgact, "Mach-o Binary" },
2772 { exec_fat_imgact, "Fat Binary" },
2773 { exec_shell_imgact, "Interpreter Script" },
2774 { NULL, NULL}
2775 };
2776
2777
2778 /*
2779 * exec_activate_image
2780 *
2781 * Description: Iterate through the available image activators, and activate
2782 * the image associated with the imgp structure. We start with
2783 * the activator for Mach-o binaries followed by that for Fat binaries
2784 * for Interpreter scripts.
2785 *
2786 * Parameters: struct image_params * Image parameter block
2787 *
2788 * Returns: 0 Success
2789 * ENOEXEC No activator for image.
2790 * EBADEXEC The executable is corrupt/unknown
2791 * execargs_alloc:EINVAL Invalid argument
2792 * execargs_alloc:EACCES Permission denied
2793 * execargs_alloc:EINTR Interrupted function
2794 * execargs_alloc:ENOMEM Not enough space
2795 * exec_save_path:EFAULT Bad address
2796 * exec_save_path:ENAMETOOLONG Filename too long
2797 * exec_check_permissions:EACCES Permission denied
2798 * exec_check_permissions:ENOEXEC Executable file format error
2799 * exec_check_permissions:ETXTBSY Text file busy [misuse of error code]
2800 * exec_check_permissions:???
2801 * namei:???
2802 * vn_rdwr:??? [anything vn_rdwr can return]
2803 * <ex_imgact>:??? [anything an imgact can return]
2804 * EDEADLK Process is being terminated
2805 */
2806 static int
exec_activate_image(struct image_params * imgp)2807 exec_activate_image(struct image_params *imgp)
2808 {
2809 struct nameidata *ndp = NULL;
2810 const char *excpath;
2811 int error;
2812 int resid;
2813 int once = 1; /* save SGUID-ness for interpreted files */
2814 int i;
2815 int itercount = 0;
2816 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
2817
2818 /*
2819 * For exec, the translock needs to be taken on old proc and not
2820 * on new shadow proc.
2821 */
2822 if (imgp->ip_flags & IMGPF_EXEC) {
2823 p = current_proc();
2824 }
2825
2826 error = execargs_alloc(imgp);
2827 if (error) {
2828 goto bad_notrans;
2829 }
2830
2831 error = exec_save_path(imgp, imgp->ip_user_fname, imgp->ip_seg, &excpath);
2832 if (error) {
2833 goto bad_notrans;
2834 }
2835
2836 /* Use excpath, which contains the copyin-ed exec path */
2837 DTRACE_PROC1(exec, uintptr_t, excpath);
2838
2839 ndp = kalloc_type(struct nameidata, Z_WAITOK | Z_ZERO | Z_NOFAIL);
2840
2841 NDINIT(ndp, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF | AUDITVNPATH1,
2842 UIO_SYSSPACE, CAST_USER_ADDR_T(excpath), imgp->ip_vfs_context);
2843
2844 again:
2845 error = namei(ndp);
2846 if (error) {
2847 if (error == ERESTART) {
2848 error = EINTR;
2849 }
2850 goto bad_notrans;
2851 }
2852 imgp->ip_ndp = ndp; /* successful namei(); call nameidone() later */
2853 imgp->ip_vp = ndp->ni_vp; /* if set, need to vnode_put() at some point */
2854
2855 /*
2856 * Before we start the transition from binary A to binary B, make
2857 * sure another thread hasn't started exiting the process. We grab
2858 * the proc lock to check p_lflag initially, and the transition
2859 * mechanism ensures that the value doesn't change after we release
2860 * the lock.
2861 */
2862 proc_lock(p);
2863 if (p->p_lflag & P_LEXIT) {
2864 error = EDEADLK;
2865 proc_unlock(p);
2866 goto bad_notrans;
2867 }
2868 error = proc_transstart(p, 1, 0);
2869 proc_unlock(p);
2870 if (error) {
2871 goto bad_notrans;
2872 }
2873
2874 error = exec_check_permissions(imgp);
2875 if (error) {
2876 goto bad;
2877 }
2878
2879 /* Copy; avoid invocation of an interpreter overwriting the original */
2880 if (once) {
2881 once = 0;
2882 *imgp->ip_origvattr = *imgp->ip_vattr;
2883 }
2884
2885 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata, PAGE_SIZE, 0,
2886 UIO_SYSSPACE, IO_NODELOCKED,
2887 vfs_context_ucred(imgp->ip_vfs_context),
2888 &resid, vfs_context_proc(imgp->ip_vfs_context));
2889 if (error) {
2890 goto bad;
2891 }
2892
2893 if (resid) {
2894 memset(imgp->ip_vdata + (PAGE_SIZE - resid), 0x0, resid);
2895 }
2896
2897 encapsulated_binary:
2898 /* Limit the number of iterations we will attempt on each binary */
2899 if (++itercount > EAI_ITERLIMIT) {
2900 error = EBADEXEC;
2901 goto bad;
2902 }
2903 error = -1;
2904 for (i = 0; error == -1 && execsw[i].ex_imgact != NULL; i++) {
2905 error = (*execsw[i].ex_imgact)(imgp);
2906
2907 switch (error) {
2908 /* case -1: not claimed: continue */
2909 case -2: /* Encapsulated binary, imgp->ip_XXX set for next iteration */
2910 goto encapsulated_binary;
2911
2912 case -3: /* Interpreter */
2913 #if CONFIG_MACF
2914 /*
2915 * Copy the script label for later use. Note that
2916 * the label can be different when the script is
2917 * actually read by the interpreter.
2918 */
2919 if (imgp->ip_scriptlabelp) {
2920 mac_vnode_label_free(imgp->ip_scriptlabelp);
2921 imgp->ip_scriptlabelp = NULL;
2922 }
2923 imgp->ip_scriptlabelp = mac_vnode_label_alloc(NULL);
2924 if (imgp->ip_scriptlabelp == NULL) {
2925 error = ENOMEM;
2926 break;
2927 }
2928 mac_vnode_label_copy(mac_vnode_label(imgp->ip_vp),
2929 imgp->ip_scriptlabelp);
2930
2931 /*
2932 * Take a ref of the script vnode for later use.
2933 */
2934 if (imgp->ip_scriptvp) {
2935 vnode_put(imgp->ip_scriptvp);
2936 imgp->ip_scriptvp = NULLVP;
2937 }
2938 if (vnode_getwithref(imgp->ip_vp) == 0) {
2939 imgp->ip_scriptvp = imgp->ip_vp;
2940 }
2941 #endif
2942
2943 nameidone(ndp);
2944
2945 vnode_put(imgp->ip_vp);
2946 imgp->ip_vp = NULL; /* already put */
2947 imgp->ip_ndp = NULL; /* already nameidone */
2948
2949 /* Use excpath, which exec_shell_imgact reset to the interpreter */
2950 NDINIT(ndp, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF,
2951 UIO_SYSSPACE, CAST_USER_ADDR_T(excpath), imgp->ip_vfs_context);
2952
2953 proc_transend(p, 0);
2954 goto again;
2955
2956 default:
2957 break;
2958 }
2959 }
2960
2961 if (error == -1) {
2962 error = ENOEXEC;
2963 } else if (error == 0) {
2964 if (imgp->ip_flags & IMGPF_INTERPRET && ndp->ni_vp) {
2965 AUDIT_ARG(vnpath, ndp->ni_vp, ARG_VNODE2);
2966 }
2967
2968 /*
2969 * Call out to allow 3rd party notification of exec.
2970 * Ignore result of kauth_authorize_fileop call.
2971 */
2972 if (kauth_authorize_fileop_has_listeners()) {
2973 kauth_authorize_fileop(vfs_context_ucred(imgp->ip_vfs_context),
2974 KAUTH_FILEOP_EXEC,
2975 (uintptr_t)ndp->ni_vp, 0);
2976 }
2977 }
2978 bad:
2979 proc_transend(p, 0);
2980
2981 bad_notrans:
2982 if (imgp->ip_strings) {
2983 execargs_free(imgp);
2984 }
2985 if (imgp->ip_ndp) {
2986 nameidone(imgp->ip_ndp);
2987 }
2988 kfree_type(struct nameidata, ndp);
2989
2990 return error;
2991 }
2992
2993
2994 /*
2995 * exec_validate_spawnattr_policy
2996 *
2997 * Description: Validates the entitlements required to set the apptype.
2998 *
2999 * Parameters: int psa_apptype posix spawn attribute apptype
3000 *
3001 * Returns: 0 Success
3002 * EPERM Failure
3003 */
3004 static errno_t
exec_validate_spawnattr_policy(int psa_apptype)3005 exec_validate_spawnattr_policy(int psa_apptype)
3006 {
3007 if ((psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) != 0) {
3008 int proctype = psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK;
3009 if (proctype == POSIX_SPAWN_PROC_TYPE_DRIVER) {
3010 if (!IOCurrentTaskHasEntitlement(POSIX_SPAWN_ENTITLEMENT_DRIVER)) {
3011 return EPERM;
3012 }
3013 }
3014 }
3015
3016 return 0;
3017 }
3018
3019 /*
3020 * exec_handle_spawnattr_policy
3021 *
3022 * Description: Decode and apply the posix_spawn apptype, qos clamp, and watchport ports to the task.
3023 *
3024 * Parameters: proc_t p process to apply attributes to
3025 * int psa_apptype posix spawn attribute apptype
3026 *
3027 * Returns: 0 Success
3028 */
3029 static errno_t
exec_handle_spawnattr_policy(proc_t p,thread_t thread,int psa_apptype,uint64_t psa_qos_clamp,task_role_t psa_darwin_role,struct exec_port_actions * port_actions)3030 exec_handle_spawnattr_policy(proc_t p, thread_t thread, int psa_apptype, uint64_t psa_qos_clamp,
3031 task_role_t psa_darwin_role, struct exec_port_actions *port_actions)
3032 {
3033 int apptype = TASK_APPTYPE_NONE;
3034 int qos_clamp = THREAD_QOS_UNSPECIFIED;
3035 task_role_t role = TASK_UNSPECIFIED;
3036
3037 if ((psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) != 0) {
3038 int proctype = psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK;
3039
3040 switch (proctype) {
3041 case POSIX_SPAWN_PROC_TYPE_DAEMON_INTERACTIVE:
3042 apptype = TASK_APPTYPE_DAEMON_INTERACTIVE;
3043 break;
3044 case POSIX_SPAWN_PROC_TYPE_DAEMON_STANDARD:
3045 apptype = TASK_APPTYPE_DAEMON_STANDARD;
3046 break;
3047 case POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE:
3048 apptype = TASK_APPTYPE_DAEMON_ADAPTIVE;
3049 break;
3050 case POSIX_SPAWN_PROC_TYPE_DAEMON_BACKGROUND:
3051 apptype = TASK_APPTYPE_DAEMON_BACKGROUND;
3052 break;
3053 case POSIX_SPAWN_PROC_TYPE_APP_DEFAULT:
3054 apptype = TASK_APPTYPE_APP_DEFAULT;
3055 break;
3056 case POSIX_SPAWN_PROC_TYPE_APP_NONUI:
3057 apptype = TASK_APPTYPE_APP_NONUI;
3058 break;
3059 case POSIX_SPAWN_PROC_TYPE_DRIVER:
3060 apptype = TASK_APPTYPE_DRIVER;
3061 break;
3062 default:
3063 apptype = TASK_APPTYPE_NONE;
3064 /* TODO: Should an invalid value here fail the spawn? */
3065 break;
3066 }
3067 }
3068
3069 if (psa_qos_clamp != POSIX_SPAWN_PROC_CLAMP_NONE) {
3070 switch (psa_qos_clamp) {
3071 case POSIX_SPAWN_PROC_CLAMP_UTILITY:
3072 qos_clamp = THREAD_QOS_UTILITY;
3073 break;
3074 case POSIX_SPAWN_PROC_CLAMP_BACKGROUND:
3075 qos_clamp = THREAD_QOS_BACKGROUND;
3076 break;
3077 case POSIX_SPAWN_PROC_CLAMP_MAINTENANCE:
3078 qos_clamp = THREAD_QOS_MAINTENANCE;
3079 break;
3080 default:
3081 qos_clamp = THREAD_QOS_UNSPECIFIED;
3082 /* TODO: Should an invalid value here fail the spawn? */
3083 break;
3084 }
3085 }
3086
3087 if (psa_darwin_role != PRIO_DARWIN_ROLE_DEFAULT) {
3088 proc_darwin_role_to_task_role(psa_darwin_role, &role);
3089 }
3090
3091 if (apptype != TASK_APPTYPE_NONE ||
3092 qos_clamp != THREAD_QOS_UNSPECIFIED ||
3093 role != TASK_UNSPECIFIED ||
3094 port_actions->portwatch_count) {
3095 proc_set_task_spawnpolicy(proc_task(p), thread, apptype, qos_clamp, role,
3096 port_actions->portwatch_array, port_actions->portwatch_count);
3097 }
3098
3099 if (port_actions->registered_count) {
3100 if (_kernelrpc_mach_ports_register3(proc_task(p),
3101 port_actions->registered_array[0],
3102 port_actions->registered_array[1],
3103 port_actions->registered_array[2])) {
3104 return EINVAL;
3105 }
3106 /* mach_ports_register() consumed the array */
3107 bzero(port_actions->registered_array,
3108 sizeof(port_actions->registered_array));
3109 port_actions->registered_count = 0;
3110 }
3111
3112 return 0;
3113 }
3114
3115 static void
exec_port_actions_destroy(struct exec_port_actions * port_actions)3116 exec_port_actions_destroy(struct exec_port_actions *port_actions)
3117 {
3118 if (port_actions->excport_array) {
3119 for (uint32_t i = 0; i < port_actions->exception_port_count; i++) {
3120 ipc_port_t port = NULL;
3121 if ((port = port_actions->excport_array[i].port) != NULL) {
3122 ipc_port_release_send(port);
3123 }
3124 }
3125 kfree_type(struct exception_port_action_t, port_actions->exception_port_count,
3126 port_actions->excport_array);
3127 }
3128
3129 if (port_actions->portwatch_array) {
3130 for (uint32_t i = 0; i < port_actions->portwatch_count; i++) {
3131 ipc_port_t port = NULL;
3132 if ((port = port_actions->portwatch_array[i]) != NULL) {
3133 ipc_port_release_send(port);
3134 }
3135 }
3136 kfree_type(ipc_port_t, port_actions->portwatch_count,
3137 port_actions->portwatch_array);
3138 }
3139
3140 for (uint32_t i = 0; i < port_actions->registered_count; i++) {
3141 ipc_port_t port = NULL;
3142 if ((port = port_actions->registered_array[i]) != NULL) {
3143 ipc_port_release_send(port);
3144 }
3145 }
3146 }
3147
3148 /*
3149 * exec_handle_port_actions
3150 *
3151 * Description: Go through the _posix_port_actions_t contents,
3152 * calling task_set_special_port, task_set_exception_ports
3153 * and/or audit_session_spawnjoin for the current task.
3154 *
3155 * Parameters: struct image_params * Image parameter block
3156 *
3157 * Returns: 0 Success
3158 * EINVAL Failure
3159 * ENOTSUP Illegal posix_spawn attr flag was set
3160 */
3161 static errno_t
exec_handle_port_actions(struct image_params * imgp,struct exec_port_actions * actions)3162 exec_handle_port_actions(struct image_params *imgp,
3163 struct exec_port_actions *actions)
3164 {
3165 _posix_spawn_port_actions_t pacts = imgp->ip_px_spa;
3166 #if CONFIG_AUDIT
3167 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
3168 #endif
3169 _ps_port_action_t *act = NULL;
3170 task_t task = get_threadtask(imgp->ip_new_thread);
3171 ipc_port_t port = NULL;
3172 errno_t ret = 0;
3173 int i = 0, portwatch_i = 0, registered_i = 0, excport_i = 0;
3174 kern_return_t kr;
3175 boolean_t task_has_watchport_boost = task_has_watchports(current_task());
3176 boolean_t in_exec = (imgp->ip_flags & IMGPF_EXEC);
3177 int ptrauth_task_port_count = 0;
3178
3179 for (i = 0; i < pacts->pspa_count; i++) {
3180 act = &pacts->pspa_actions[i];
3181
3182 switch (act->port_type) {
3183 case PSPA_SPECIAL:
3184 #if CONFIG_AUDIT
3185 case PSPA_AU_SESSION:
3186 #endif
3187 break;
3188 case PSPA_EXCEPTION:
3189 if (++actions->exception_port_count > TASK_MAX_EXCEPTION_PORT_COUNT) {
3190 ret = EINVAL;
3191 goto done;
3192 }
3193 break;
3194 case PSPA_IMP_WATCHPORTS:
3195 if (++actions->portwatch_count > TASK_MAX_WATCHPORT_COUNT) {
3196 ret = EINVAL;
3197 goto done;
3198 }
3199 break;
3200 case PSPA_REGISTERED_PORTS:
3201 if (++actions->registered_count > TASK_PORT_REGISTER_MAX) {
3202 ret = EINVAL;
3203 goto done;
3204 }
3205 break;
3206 case PSPA_PTRAUTH_TASK_PORT:
3207 if (++ptrauth_task_port_count > 1) {
3208 ret = EINVAL;
3209 goto done;
3210 }
3211 break;
3212 default:
3213 ret = EINVAL;
3214 goto done;
3215 }
3216 }
3217
3218 if (actions->exception_port_count) {
3219 actions->excport_array = kalloc_type(struct exception_port_action_t,
3220 actions->exception_port_count, Z_WAITOK | Z_ZERO);
3221
3222 if (actions->excport_array == NULL) {
3223 ret = ENOMEM;
3224 goto done;
3225 }
3226 }
3227 if (actions->portwatch_count) {
3228 if (in_exec && task_has_watchport_boost) {
3229 ret = EINVAL;
3230 goto done;
3231 }
3232 actions->portwatch_array = kalloc_type(ipc_port_t,
3233 actions->portwatch_count, Z_WAITOK | Z_ZERO);
3234 if (actions->portwatch_array == NULL) {
3235 ret = ENOMEM;
3236 goto done;
3237 }
3238 }
3239
3240 for (i = 0; i < pacts->pspa_count; i++) {
3241 act = &pacts->pspa_actions[i];
3242
3243 if (MACH_PORT_VALID(act->new_port)) {
3244 kr = ipc_typed_port_copyin_send(get_task_ipcspace(current_task()),
3245 act->new_port, IOT_ANY, &port);
3246
3247 if (kr != KERN_SUCCESS) {
3248 ret = EINVAL;
3249 goto done;
3250 }
3251 } else {
3252 /* it's NULL or DEAD */
3253 port = CAST_MACH_NAME_TO_PORT(act->new_port);
3254 }
3255
3256 switch (act->port_type) {
3257 case PSPA_SPECIAL:
3258 kr = task_set_special_port(task, act->which, port);
3259
3260 if (kr != KERN_SUCCESS) {
3261 ret = EINVAL;
3262 }
3263 break;
3264
3265 #if CONFIG_AUDIT
3266 case PSPA_AU_SESSION:
3267 ret = audit_session_spawnjoin(p, port);
3268 if (ret) {
3269 /* audit_session_spawnjoin() has already dropped the reference in case of error. */
3270 goto done;
3271 }
3272
3273 break;
3274 #endif
3275 case PSPA_EXCEPTION:
3276 assert(excport_i < actions->exception_port_count);
3277 /* hold on to this till end of spawn */
3278 actions->excport_array[excport_i].port_action = act;
3279 actions->excport_array[excport_i].port = port;
3280 excport_i++;
3281 break;
3282 case PSPA_IMP_WATCHPORTS:
3283 assert(portwatch_i < actions->portwatch_count);
3284 /* hold on to this till end of spawn */
3285 actions->portwatch_array[portwatch_i++] = port;
3286 break;
3287 case PSPA_REGISTERED_PORTS:
3288 assert(registered_i < actions->registered_count);
3289 /* hold on to this till end of spawn */
3290 actions->registered_array[registered_i++] = port;
3291 break;
3292
3293 case PSPA_PTRAUTH_TASK_PORT:
3294 #if (DEVELOPMENT || DEBUG)
3295 #if defined(HAS_APPLE_PAC)
3296 {
3297 task_t ptr_auth_task = convert_port_to_task(port);
3298
3299 if (ptr_auth_task == TASK_NULL) {
3300 ret = EINVAL;
3301 break;
3302 }
3303
3304 imgp->ip_inherited_shared_region_id =
3305 task_get_vm_shared_region_id_and_jop_pid(ptr_auth_task,
3306 &imgp->ip_inherited_jop_pid);
3307
3308 /* Deallocate task ref returned by convert_port_to_task */
3309 task_deallocate(ptr_auth_task);
3310 }
3311 #endif /* HAS_APPLE_PAC */
3312 #endif /* (DEVELOPMENT || DEBUG) */
3313
3314 /* consume the port right in case of success */
3315 ipc_port_release_send(port);
3316 break;
3317 default:
3318 ret = EINVAL;
3319 break;
3320 }
3321
3322 if (ret) {
3323 /* action failed, so release port resources */
3324 ipc_port_release_send(port);
3325 break;
3326 }
3327 }
3328
3329 done:
3330 if (0 != ret) {
3331 DTRACE_PROC1(spawn__port__failure, mach_port_name_t, act->new_port);
3332 }
3333 return ret;
3334 }
3335
3336
3337 /*
3338 * exec_handle_exception_port_actions
3339 *
3340 * Description: Go through the saved exception ports in exec_port_actions,
3341 * calling task_set_exception_ports for the current Task.
3342 * This must happen after image activation, and after exec_resettextvp()
3343 * because task_set_exception_ports checks the `TF_PLATFORM` bit and entitlements.
3344 *
3345 * Parameters: struct image_params * Image parameter block
3346 * struct exec_port_actions * Saved Port Actions
3347 *
3348 * Returns: 0 Success
3349 * EINVAL task_set_exception_ports failed
3350 */
3351 static errno_t
exec_handle_exception_port_actions(const struct image_params * imgp,const struct exec_port_actions * actions)3352 exec_handle_exception_port_actions(const struct image_params *imgp,
3353 const struct exec_port_actions *actions)
3354 {
3355 task_t task = get_threadtask(imgp->ip_new_thread);
3356
3357 for (int i = 0; i < actions->exception_port_count; i++) {
3358 ipc_port_t port = actions->excport_array[i].port;
3359 _ps_port_action_t *act = actions->excport_array[i].port_action;
3360 assert(act != NULL);
3361 kern_return_t kr = task_set_exception_ports(task, act->mask, port,
3362 act->behavior, act->flavor);
3363 if (kr != KERN_SUCCESS) {
3364 DTRACE_PROC1(spawn__exception__port__failure, mach_port_name_t, act->new_port);
3365 return EINVAL;
3366 }
3367 actions->excport_array[i].port = NULL;
3368 }
3369
3370 return 0;
3371 }
3372
3373
3374 /*
3375 * exec_handle_file_actions
3376 *
3377 * Description: Go through the _posix_file_actions_t contents applying the
3378 * open, close, and dup2 operations to the open file table for
3379 * the current process.
3380 *
3381 * Parameters: struct image_params * Image parameter block
3382 *
3383 * Returns: 0 Success
3384 * ???
3385 *
3386 * Note: Actions are applied in the order specified, with the credential
3387 * of the parent process. This is done to permit the parent
3388 * process to utilize POSIX_SPAWN_RESETIDS to drop privilege in
3389 * the child following operations the child may in fact not be
3390 * normally permitted to perform.
3391 */
3392 static int
exec_handle_file_actions(struct image_params * imgp,short psa_flags)3393 exec_handle_file_actions(struct image_params *imgp, short psa_flags)
3394 {
3395 int error = 0;
3396 int action;
3397 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
3398 kauth_cred_t p_cred = vfs_context_ucred(imgp->ip_vfs_context);
3399 _posix_spawn_file_actions_t px_sfap = imgp->ip_px_sfa;
3400 int ival[2]; /* dummy retval for system calls) */
3401 #if CONFIG_AUDIT
3402 struct uthread *uthread = current_uthread();
3403 #endif
3404
3405 for (action = 0; action < px_sfap->psfa_act_count; action++) {
3406 _psfa_action_t *psfa = &px_sfap->psfa_act_acts[action];
3407
3408 switch (psfa->psfaa_type) {
3409 case PSFA_OPEN: {
3410 /*
3411 * Open is different, in that it requires the use of
3412 * a path argument, which is normally copied in from
3413 * user space; because of this, we have to support an
3414 * open from kernel space that passes an address space
3415 * context of UIO_SYSSPACE, and casts the address
3416 * argument to a user_addr_t.
3417 */
3418 struct vnode_attr *vap;
3419 struct nameidata *ndp;
3420 int mode = psfa->psfaa_openargs.psfao_mode;
3421 int origfd;
3422 struct {
3423 struct vnode_attr va;
3424 struct nameidata nd;
3425 } *__open_data;
3426
3427 __open_data = kalloc_type(typeof(*__open_data), Z_WAITOK | Z_ZERO);
3428 if (__open_data == NULL) {
3429 error = ENOMEM;
3430 break;
3431 }
3432
3433 vap = &__open_data->va;
3434 ndp = &__open_data->nd;
3435
3436 VATTR_INIT(vap);
3437 /* Mask off all but regular access permissions */
3438 mode = ((mode & ~p->p_fd.fd_cmask) & ALLPERMS) & ~S_ISTXT;
3439 VATTR_SET(vap, va_mode, mode & ACCESSPERMS);
3440
3441 AUDIT_SUBCALL_ENTER(OPEN, p, uthread);
3442
3443 NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW | AUDITVNPATH1, UIO_SYSSPACE,
3444 CAST_USER_ADDR_T(psfa->psfaa_openargs.psfao_path),
3445 imgp->ip_vfs_context);
3446
3447 error = open1(imgp->ip_vfs_context, ndp,
3448 psfa->psfaa_openargs.psfao_oflag,
3449 vap, NULL, NULL, &origfd, AUTH_OPEN_NOAUTHFD);
3450
3451 kfree_type(typeof(*__open_data), __open_data);
3452
3453 AUDIT_SUBCALL_EXIT(uthread, error);
3454
3455 /*
3456 * If there's an error, or we get the right fd by
3457 * accident, then drop out here. This is easier than
3458 * reworking all the open code to preallocate fd
3459 * slots, and internally taking one as an argument.
3460 */
3461 if (error || origfd == psfa->psfaa_filedes) {
3462 break;
3463 }
3464
3465 /*
3466 * If we didn't fall out from an error, we ended up
3467 * with the wrong fd; so now we've got to try to dup2
3468 * it to the right one.
3469 */
3470 AUDIT_SUBCALL_ENTER(DUP2, p, uthread);
3471 error = dup2(p, p_cred, origfd, psfa->psfaa_filedes, ival);
3472 AUDIT_SUBCALL_EXIT(uthread, error);
3473 if (error) {
3474 break;
3475 }
3476
3477 /*
3478 * Finally, close the original fd.
3479 */
3480 AUDIT_SUBCALL_ENTER(CLOSE, p, uthread);
3481 error = close_nocancel(p, p_cred, origfd);
3482 AUDIT_SUBCALL_EXIT(uthread, error);
3483 }
3484 break;
3485
3486 case PSFA_DUP2: {
3487 AUDIT_SUBCALL_ENTER(DUP2, p, uthread);
3488 error = dup2(p, p_cred, psfa->psfaa_filedes,
3489 psfa->psfaa_dup2args.psfad_newfiledes, ival);
3490 AUDIT_SUBCALL_EXIT(uthread, error);
3491 }
3492 break;
3493
3494 case PSFA_FILEPORT_DUP2: {
3495 ipc_port_t port;
3496 kern_return_t kr;
3497 int origfd;
3498
3499 if (!MACH_PORT_VALID(psfa->psfaa_fileport)) {
3500 error = EINVAL;
3501 break;
3502 }
3503
3504 kr = ipc_typed_port_copyin_send(get_task_ipcspace(current_task()),
3505 psfa->psfaa_fileport, IKOT_FILEPORT, &port);
3506
3507 if (kr != KERN_SUCCESS) {
3508 error = EINVAL;
3509 break;
3510 }
3511
3512 error = fileport_makefd(p, port, 0, &origfd);
3513
3514 if (IPC_PORT_NULL != port) {
3515 ipc_typed_port_release_send(port, IKOT_FILEPORT);
3516 }
3517
3518 if (error || origfd == psfa->psfaa_dup2args.psfad_newfiledes) {
3519 break;
3520 }
3521
3522 AUDIT_SUBCALL_ENTER(DUP2, p, uthread);
3523 error = dup2(p, p_cred, origfd,
3524 psfa->psfaa_dup2args.psfad_newfiledes, ival);
3525 AUDIT_SUBCALL_EXIT(uthread, error);
3526 if (error) {
3527 break;
3528 }
3529
3530 AUDIT_SUBCALL_ENTER(CLOSE, p, uthread);
3531 error = close_nocancel(p, p_cred, origfd);
3532 AUDIT_SUBCALL_EXIT(uthread, error);
3533 }
3534 break;
3535
3536 case PSFA_CLOSE: {
3537 AUDIT_SUBCALL_ENTER(CLOSE, p, uthread);
3538 error = close_nocancel(p, p_cred, psfa->psfaa_filedes);
3539 AUDIT_SUBCALL_EXIT(uthread, error);
3540 }
3541 break;
3542
3543 case PSFA_INHERIT: {
3544 struct fileproc *fp;
3545
3546 /*
3547 * Check to see if the descriptor exists, and
3548 * ensure it's -not- marked as close-on-exec.
3549 *
3550 * Attempting to "inherit" a guarded fd will
3551 * result in a error.
3552 */
3553
3554 proc_fdlock(p);
3555 if ((fp = fp_get_noref_locked(p, psfa->psfaa_filedes)) == NULL) {
3556 error = EBADF;
3557 } else if (fp->fp_guard_attrs) {
3558 error = fp_guard_exception(p, psfa->psfaa_filedes,
3559 fp, kGUARD_EXC_NOCLOEXEC);
3560 } else {
3561 fp->fp_flags &= ~FP_CLOEXEC;
3562 error = 0;
3563 }
3564 proc_fdunlock(p);
3565 }
3566 break;
3567
3568 case PSFA_CHDIR: {
3569 /*
3570 * Chdir is different, in that it requires the use of
3571 * a path argument, which is normally copied in from
3572 * user space; because of this, we have to support a
3573 * chdir from kernel space that passes an address space
3574 * context of UIO_SYSSPACE, and casts the address
3575 * argument to a user_addr_t.
3576 */
3577 struct nameidata *nd;
3578 nd = kalloc_type(struct nameidata,
3579 Z_WAITOK | Z_ZERO | Z_NOFAIL);
3580
3581 AUDIT_SUBCALL_ENTER(CHDIR, p, uthread);
3582 NDINIT(nd, LOOKUP, OP_CHDIR, FOLLOW | AUDITVNPATH1, UIO_SYSSPACE,
3583 CAST_USER_ADDR_T(psfa->psfaa_chdirargs.psfac_path),
3584 imgp->ip_vfs_context);
3585
3586 error = chdir_internal(p, imgp->ip_vfs_context, nd, 0);
3587 kfree_type(struct nameidata, nd);
3588 AUDIT_SUBCALL_EXIT(uthread, error);
3589 }
3590 break;
3591
3592 case PSFA_FCHDIR: {
3593 AUDIT_SUBCALL_ENTER(FCHDIR, p, uthread);
3594 error = fchdir(p, imgp->ip_vfs_context,
3595 psfa->psfaa_filedes, false);
3596 AUDIT_SUBCALL_EXIT(uthread, error);
3597 }
3598 break;
3599
3600 default:
3601 error = EINVAL;
3602 break;
3603 }
3604
3605 /* All file actions failures are considered fatal, per POSIX */
3606
3607 if (error) {
3608 if (PSFA_OPEN == psfa->psfaa_type) {
3609 DTRACE_PROC1(spawn__open__failure, uintptr_t,
3610 psfa->psfaa_openargs.psfao_path);
3611 } else {
3612 DTRACE_PROC1(spawn__fd__failure, int, psfa->psfaa_filedes);
3613 }
3614 break;
3615 }
3616 }
3617
3618 if (error != 0 || (psa_flags & POSIX_SPAWN_CLOEXEC_DEFAULT) == 0) {
3619 return error;
3620 }
3621
3622 /*
3623 * If POSIX_SPAWN_CLOEXEC_DEFAULT is set, behave (during
3624 * this spawn only) as if "close on exec" is the default
3625 * disposition of all pre-existing file descriptors. In this case,
3626 * the list of file descriptors mentioned in the file actions
3627 * are the only ones that can be inherited, so mark them now.
3628 *
3629 * The actual closing part comes later, in fdt_exec().
3630 */
3631 proc_fdlock(p);
3632 for (action = 0; action < px_sfap->psfa_act_count; action++) {
3633 _psfa_action_t *psfa = &px_sfap->psfa_act_acts[action];
3634 int fd = psfa->psfaa_filedes;
3635
3636 switch (psfa->psfaa_type) {
3637 case PSFA_DUP2:
3638 case PSFA_FILEPORT_DUP2:
3639 fd = psfa->psfaa_dup2args.psfad_newfiledes;
3640 OS_FALLTHROUGH;
3641 case PSFA_OPEN:
3642 case PSFA_INHERIT:
3643 *fdflags(p, fd) |= UF_INHERIT;
3644 break;
3645
3646 case PSFA_CLOSE:
3647 case PSFA_CHDIR:
3648 case PSFA_FCHDIR:
3649 /*
3650 * Although PSFA_FCHDIR does have a file descriptor, it is not
3651 * *creating* one, thus we do not automatically mark it for
3652 * inheritance under POSIX_SPAWN_CLOEXEC_DEFAULT. A client that
3653 * wishes it to be inherited should use the PSFA_INHERIT action
3654 * explicitly.
3655 */
3656 break;
3657 }
3658 }
3659 proc_fdunlock(p);
3660
3661 return 0;
3662 }
3663
3664 #if CONFIG_MACF
3665 /*
3666 * Check that the extension's data is within the bounds of the
3667 * allocation storing all extensions' data
3668 */
3669 static inline errno_t
exec_spawnattr_validate_policyext_data(const struct ip_px_smpx_s * px_s,const _ps_mac_policy_extension_t * ext)3670 exec_spawnattr_validate_policyext_data(const struct ip_px_smpx_s *px_s,
3671 const _ps_mac_policy_extension_t *ext)
3672 {
3673 uint64_t dataend;
3674
3675 if (__improbable(os_add_overflow(ext->dataoff, ext->datalen, &dataend))) {
3676 return EOVERFLOW;
3677 }
3678 if (__improbable(dataend > px_s->datalen)) {
3679 return EINVAL;
3680 }
3681
3682 return 0;
3683 }
3684
3685 /*
3686 * exec_spawnattr_getmacpolicyinfo
3687 */
3688 void *
exec_spawnattr_getmacpolicyinfo(const void * macextensions,const char * policyname,size_t * lenp)3689 exec_spawnattr_getmacpolicyinfo(const void *macextensions, const char *policyname, size_t *lenp)
3690 {
3691 const struct ip_px_smpx_s *px_s = macextensions;
3692 const struct _posix_spawn_mac_policy_extensions *psmx = NULL;
3693 int i;
3694
3695 if (px_s == NULL) {
3696 return NULL;
3697 }
3698
3699 psmx = px_s->array;
3700 if (psmx == NULL) {
3701 return NULL;
3702 }
3703
3704 for (i = 0; i < psmx->psmx_count; i++) {
3705 const _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i];
3706 if (strncmp(extension->policyname, policyname, sizeof(extension->policyname)) == 0) {
3707 if (__improbable(exec_spawnattr_validate_policyext_data(px_s, extension))) {
3708 panic("invalid mac policy extension data");
3709 }
3710 if (lenp != NULL) {
3711 *lenp = (size_t)extension->datalen;
3712 }
3713 return (void *)((uintptr_t)px_s->data + extension->dataoff);
3714 }
3715 }
3716
3717 if (lenp != NULL) {
3718 *lenp = 0;
3719 }
3720 return NULL;
3721 }
3722
3723 static int
spawn_copyin_macpolicyinfo(const struct user__posix_spawn_args_desc * px_args,struct ip_px_smpx_s * pxsp)3724 spawn_copyin_macpolicyinfo(const struct user__posix_spawn_args_desc *px_args,
3725 struct ip_px_smpx_s *pxsp)
3726 {
3727 _posix_spawn_mac_policy_extensions_t psmx = NULL;
3728 uint8_t *data = NULL;
3729 uint64_t datalen = 0;
3730 uint64_t dataoff = 0;
3731 int error = 0;
3732
3733 bzero(pxsp, sizeof(*pxsp));
3734
3735 if (px_args->mac_extensions_size < PS_MAC_EXTENSIONS_SIZE(1) ||
3736 px_args->mac_extensions_size > PAGE_SIZE) {
3737 error = EINVAL;
3738 goto bad;
3739 }
3740
3741 psmx = kalloc_data(px_args->mac_extensions_size, Z_WAITOK);
3742 if (psmx == NULL) {
3743 error = ENOMEM;
3744 goto bad;
3745 }
3746
3747 error = copyin(px_args->mac_extensions, psmx, px_args->mac_extensions_size);
3748 if (error) {
3749 goto bad;
3750 }
3751
3752 size_t extsize = PS_MAC_EXTENSIONS_SIZE(psmx->psmx_count);
3753 if (extsize == 0 || extsize > px_args->mac_extensions_size) {
3754 error = EINVAL;
3755 goto bad;
3756 }
3757
3758 for (int i = 0; i < psmx->psmx_count; i++) {
3759 _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i];
3760 if (extension->datalen == 0 || extension->datalen > PAGE_SIZE) {
3761 error = EINVAL;
3762 goto bad;
3763 }
3764 if (__improbable(os_add_overflow(datalen, extension->datalen, &datalen))) {
3765 error = ENOMEM;
3766 goto bad;
3767 }
3768 }
3769
3770 data = kalloc_data((vm_size_t)datalen, Z_WAITOK);
3771 if (data == NULL) {
3772 error = ENOMEM;
3773 goto bad;
3774 }
3775
3776 for (int i = 0; i < psmx->psmx_count; i++) {
3777 _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i];
3778
3779 #if !__LP64__
3780 if (extension->data > UINT32_MAX) {
3781 goto bad;
3782 }
3783 #endif
3784 error = copyin((user_addr_t)extension->data, &data[dataoff], (size_t)extension->datalen);
3785 if (error) {
3786 error = ENOMEM;
3787 goto bad;
3788 }
3789 extension->dataoff = dataoff;
3790 dataoff += extension->datalen;
3791 }
3792
3793 pxsp->array = psmx;
3794 pxsp->data = data;
3795 pxsp->datalen = datalen;
3796 return 0;
3797
3798 bad:
3799 kfree_data(psmx, px_args->mac_extensions_size);
3800 kfree_data(data, (vm_size_t)datalen);
3801 return error;
3802 }
3803 #endif /* CONFIG_MACF */
3804
3805 #if CONFIG_COALITIONS
3806 static inline void
spawn_coalitions_release_all(coalition_t coal[COALITION_NUM_TYPES])3807 spawn_coalitions_release_all(coalition_t coal[COALITION_NUM_TYPES])
3808 {
3809 for (int c = 0; c < COALITION_NUM_TYPES; c++) {
3810 if (coal[c]) {
3811 coalition_remove_active(coal[c]);
3812 coalition_release(coal[c]);
3813 }
3814 }
3815 }
3816 #endif
3817
3818 #if CONFIG_PERSONAS
3819 static int
spawn_validate_persona(struct _posix_spawn_persona_info * px_persona)3820 spawn_validate_persona(struct _posix_spawn_persona_info *px_persona)
3821 {
3822 int error = 0;
3823 struct persona *persona = NULL;
3824 kauth_cred_t mycred = kauth_cred_get();
3825
3826 if (!IOCurrentTaskHasEntitlement( PERSONA_MGMT_ENTITLEMENT)) {
3827 return EPERM;
3828 }
3829
3830 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) {
3831 if (px_persona->pspi_ngroups > NGROUPS_MAX) {
3832 return EINVAL;
3833 }
3834 }
3835
3836 persona = persona_lookup(px_persona->pspi_id);
3837 if (!persona) {
3838 return ESRCH;
3839 }
3840
3841 // non-root process should not be allowed to set persona with uid/gid 0
3842 if (!kauth_cred_issuser(mycred) &&
3843 (px_persona->pspi_uid == 0 || px_persona->pspi_gid == 0)) {
3844 return EPERM;
3845 }
3846
3847 persona_put(persona);
3848 return error;
3849 }
3850
3851 static bool
kauth_cred_model_setpersona(kauth_cred_t model,struct _posix_spawn_persona_info * px_persona)3852 kauth_cred_model_setpersona(
3853 kauth_cred_t model,
3854 struct _posix_spawn_persona_info *px_persona)
3855 {
3856 bool updated = false;
3857
3858 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_UID) {
3859 updated |= kauth_cred_model_setresuid(model,
3860 px_persona->pspi_uid,
3861 px_persona->pspi_uid,
3862 px_persona->pspi_uid,
3863 KAUTH_UID_NONE);
3864 }
3865
3866 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GID) {
3867 updated |= kauth_cred_model_setresgid(model,
3868 px_persona->pspi_gid,
3869 px_persona->pspi_gid,
3870 px_persona->pspi_gid);
3871 }
3872
3873 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) {
3874 updated |= kauth_cred_model_setgroups(model,
3875 px_persona->pspi_groups,
3876 px_persona->pspi_ngroups,
3877 px_persona->pspi_gmuid);
3878 }
3879
3880 return updated;
3881 }
3882
3883 static int
spawn_persona_adopt(proc_t p,struct _posix_spawn_persona_info * px_persona)3884 spawn_persona_adopt(proc_t p, struct _posix_spawn_persona_info *px_persona)
3885 {
3886 struct persona *persona = NULL;
3887
3888 /*
3889 * we want to spawn into the given persona, but we want to override
3890 * the kauth with a different UID/GID combo
3891 */
3892 persona = persona_lookup(px_persona->pspi_id);
3893 if (!persona) {
3894 return ESRCH;
3895 }
3896
3897 return persona_proc_adopt(p, persona,
3898 ^bool (kauth_cred_t parent __unused, kauth_cred_t model) {
3899 return kauth_cred_model_setpersona(model, px_persona);
3900 });
3901 }
3902 #endif
3903
3904 #if __arm64__
3905 #if DEVELOPMENT || DEBUG
3906 TUNABLE(int, legacy_footprint_entitlement_mode, "legacy_footprint_entitlement_mode",
3907 LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE);
3908
3909 __startup_func
3910 static void
legacy_footprint_entitlement_mode_init(void)3911 legacy_footprint_entitlement_mode_init(void)
3912 {
3913 /*
3914 * legacy_footprint_entitlement_mode specifies the behavior we want associated
3915 * with the entitlement. The supported modes are:
3916 *
3917 * LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE:
3918 * Indicates that we want every process to have the memory accounting
3919 * that is available in iOS 12.0 and beyond.
3920 *
3921 * LEGACY_FOOTPRINT_ENTITLEMENT_IOS11_ACCT:
3922 * Indicates that for every process that has the 'legacy footprint entitlement',
3923 * we want to give it the old iOS 11.0 accounting behavior which accounted some
3924 * of the process's memory to the kernel.
3925 *
3926 * LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE:
3927 * Indicates that for every process that has the 'legacy footprint entitlement',
3928 * we want it to have a higher memory limit which will help them acclimate to the
3929 * iOS 12.0 (& beyond) accounting behavior that does the right accounting.
3930 * The bonus added to the system-wide task limit to calculate this higher memory limit
3931 * is available in legacy_footprint_bonus_mb.
3932 */
3933
3934 if (legacy_footprint_entitlement_mode < LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE ||
3935 legacy_footprint_entitlement_mode > LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE) {
3936 legacy_footprint_entitlement_mode = LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE;
3937 }
3938 }
3939 STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, legacy_footprint_entitlement_mode_init);
3940 #else
3941 const int legacy_footprint_entitlement_mode = LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE;
3942 #endif
3943
3944 static inline void
proc_legacy_footprint_entitled(proc_t p,task_t task)3945 proc_legacy_footprint_entitled(proc_t p, task_t task)
3946 {
3947 #pragma unused(p)
3948 boolean_t legacy_footprint_entitled;
3949
3950 switch (legacy_footprint_entitlement_mode) {
3951 case LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE:
3952 /* the entitlement is ignored */
3953 break;
3954 case LEGACY_FOOTPRINT_ENTITLEMENT_IOS11_ACCT:
3955 /* the entitlement grants iOS11 legacy accounting */
3956 legacy_footprint_entitled = memorystatus_task_has_legacy_footprint_entitlement(proc_task(p));
3957 if (legacy_footprint_entitled) {
3958 task_set_legacy_footprint(task);
3959 }
3960 break;
3961 case LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE:
3962 /* the entitlement grants a footprint limit increase */
3963 legacy_footprint_entitled = memorystatus_task_has_legacy_footprint_entitlement(proc_task(p));
3964 if (legacy_footprint_entitled) {
3965 task_set_extra_footprint_limit(task);
3966 }
3967 break;
3968 default:
3969 break;
3970 }
3971 }
3972
3973 static inline void
proc_ios13extended_footprint_entitled(proc_t p,task_t task)3974 proc_ios13extended_footprint_entitled(proc_t p, task_t task)
3975 {
3976 #pragma unused(p)
3977 boolean_t ios13extended_footprint_entitled;
3978
3979 /* the entitlement grants a footprint limit increase */
3980 ios13extended_footprint_entitled = memorystatus_task_has_ios13extended_footprint_limit(proc_task(p));
3981 if (ios13extended_footprint_entitled) {
3982 task_set_ios13extended_footprint_limit(task);
3983 }
3984 }
3985
3986 static inline void
proc_increased_memory_limit_entitled(proc_t p,task_t task)3987 proc_increased_memory_limit_entitled(proc_t p, task_t task)
3988 {
3989 if (memorystatus_task_has_increased_debugging_memory_limit_entitlement(task)) {
3990 memorystatus_act_on_entitled_developer_task_limit(p);
3991 } else if (memorystatus_task_has_increased_memory_limit_entitlement(task)) {
3992 memorystatus_act_on_entitled_task_limit(p);
3993 }
3994 }
3995
3996 /*
3997 * Check for any of the various entitlements that permit a higher
3998 * task footprint limit or alternate accounting and apply them.
3999 */
4000 static inline void
proc_footprint_entitlement_hacks(proc_t p,task_t task)4001 proc_footprint_entitlement_hacks(proc_t p, task_t task)
4002 {
4003 proc_legacy_footprint_entitled(p, task);
4004 proc_ios13extended_footprint_entitled(p, task);
4005 proc_increased_memory_limit_entitled(p, task);
4006 }
4007 #endif /* __arm64__ */
4008
4009 /*
4010 * Processes with certain entitlements are granted a jumbo-size VM map.
4011 */
4012 static inline void
proc_apply_jit_and_vm_policies(struct image_params * imgp,proc_t p,task_t task)4013 proc_apply_jit_and_vm_policies(struct image_params *imgp, proc_t p, task_t task)
4014 {
4015 #if CONFIG_MACF
4016 bool jit_entitled = false;
4017 #endif /* CONFIG_MACF */
4018 bool needs_jumbo_va = false;
4019 bool needs_extra_jumbo_va = false;
4020 struct _posix_spawnattr *psa = imgp->ip_px_sa;
4021
4022 #if CONFIG_MACF
4023 jit_entitled = (mac_proc_check_map_anon(p, proc_ucred_unsafe(p),
4024 0, 0, 0, MAP_JIT, NULL) == 0);
4025 needs_jumbo_va = jit_entitled || IOTaskHasEntitlement(task,
4026 "com.apple.developer.kernel.extended-virtual-addressing") ||
4027 memorystatus_task_has_increased_memory_limit_entitlement(task) ||
4028 memorystatus_task_has_increased_debugging_memory_limit_entitlement(task);
4029 #else
4030 #pragma unused(p)
4031 #endif /* CONFIG_MACF */
4032
4033 #if HAS_MTE
4034 /*
4035 * If we are MTE enabled, communicate to the pmap layer that
4036 * we need the right configuration at each context switch.
4037 */
4038 if (task_has_sec(task)) {
4039 vm_map_set_sec_enabled(get_task_map(task));
4040
4041 #if KERN_AMFI_SUPPORTS_MTE
4042 if (get_lockdown_mode_state() == 0 &&
4043 amfi->has_mte_soft_mode &&
4044 amfi->has_mte_soft_mode(p)) {
4045 EXEC_LOG("AMFI says: enable soft-mode\n");
4046 task_set_sec_soft_mode(task);
4047 }
4048 #endif /* KERN_AMFI_SUPPORTS_MTE */
4049 }
4050
4051 /* Pipe through alias restrictions onto our backing map */
4052 if (task_has_sec_restrict_receiving_aliases_to_tagged_memory(task)) {
4053 vm_map_set_restrict_receiving_aliases_to_tagged_memory(get_task_map(task), true);
4054 }
4055
4056 #endif /* HAS_MTE */
4057
4058 #if HAS_MTE_EMULATION_SHIMS && XNU_TARGET_OS_IOS
4059 if (task_has_sec(task)) {
4060 /* Give Rosetta some breathing room for the shadow table. */
4061 needs_jumbo_va = true;
4062 }
4063 #endif /* HAS_MTE_EMULATION_SHIMS && XNU_TARGET_OS_IOS */
4064 if (needs_jumbo_va) {
4065 vm_map_set_jumbo(get_task_map(task));
4066 }
4067
4068 if (psa && psa->psa_max_addr) {
4069 vm_map_set_max_addr(get_task_map(task), psa->psa_max_addr, false);
4070 }
4071
4072 #if CONFIG_MAP_RANGES
4073 if ((task_has_hardened_heap(task) ||
4074 (task_get_platform_restrictions_version(task) == 1) ||
4075 task_get_platform_binary(task)) && !proc_is_simulated(p)) {
4076 /*
4077 * This must be done last as it needs to observe
4078 * any kind of VA space growth that was requested.
4079 * This is used by the secure allocator, so
4080 * must be applied to all platform restrictions binaries
4081 */
4082 #if XNU_TARGET_OS_IOS && EXTENDED_USER_VA_SUPPORT
4083 needs_extra_jumbo_va = IOTaskHasEntitlement(task,
4084 "com.apple.kernel.large-file-virtual-addressing");
4085 #endif /* XNU_TARGET_OS_IOS && EXTENDED_USER_VA_SUPPORT */
4086 vm_map_range_configure(get_task_map(task), needs_extra_jumbo_va);
4087 }
4088 #else
4089 #pragma unused(needs_extra_jumbo_va)
4090 #endif /* CONFIG_MAP_RANGES */
4091
4092 #if CONFIG_MACF
4093 if (jit_entitled) {
4094 vm_map_set_jit_entitled(get_task_map(task));
4095
4096 }
4097 #endif /* CONFIG_MACF */
4098
4099 #if XNU_TARGET_OS_OSX
4100 /* TPRO cannot be enforced on binaries that load 3P plugins on macos - rdar://107420220 */
4101 const bool task_loads_3P_plugins = imgp->ip_flags & IMGPF_3P_PLUGINS;
4102 #endif /* XNU_TARGET_OS_OSX */
4103
4104 if (task_has_tpro(task)
4105 #if XNU_TARGET_OS_OSX
4106 && !task_loads_3P_plugins
4107 #endif /* XNU_TARGET_OS_OSX */
4108 ) {
4109 /*
4110 * Pre-emptively disable TPRO remapping for
4111 * platform restrictions binaries (which do not load 3P plugins)
4112 */
4113 vm_map_set_tpro_enforcement(get_task_map(task));
4114 }
4115 }
4116
4117 static int
spawn_posix_cred_adopt(proc_t p,struct _posix_spawn_posix_cred_info * px_pcred_info)4118 spawn_posix_cred_adopt(proc_t p,
4119 struct _posix_spawn_posix_cred_info *px_pcred_info)
4120 {
4121 int error = 0;
4122
4123 if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_GID) {
4124 struct setgid_args args = {
4125 .gid = px_pcred_info->pspci_gid,
4126 };
4127 error = setgid(p, &args, NULL);
4128 if (error) {
4129 return error;
4130 }
4131 }
4132
4133 if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_GROUPS) {
4134 error = setgroups_internal(p,
4135 px_pcred_info->pspci_ngroups,
4136 px_pcred_info->pspci_groups,
4137 px_pcred_info->pspci_gmuid);
4138 if (error) {
4139 return error;
4140 }
4141 }
4142
4143 if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_UID) {
4144 struct setuid_args args = {
4145 .uid = px_pcred_info->pspci_uid,
4146 };
4147 error = setuid(p, &args, NULL);
4148 if (error) {
4149 return error;
4150 }
4151 }
4152 return 0;
4153 }
4154
4155 /*
4156 * posix_spawn
4157 *
4158 * Parameters: uap->pid Pointer to pid return area
4159 * uap->fname File name to exec
4160 * uap->argp Argument list
4161 * uap->envp Environment list
4162 *
4163 * Returns: 0 Success
4164 * EINVAL Invalid argument
4165 * ENOTSUP Not supported
4166 * ENOEXEC Executable file format error
4167 * exec_activate_image:EINVAL Invalid argument
4168 * exec_activate_image:EACCES Permission denied
4169 * exec_activate_image:EINTR Interrupted function
4170 * exec_activate_image:ENOMEM Not enough space
4171 * exec_activate_image:EFAULT Bad address
4172 * exec_activate_image:ENAMETOOLONG Filename too long
4173 * exec_activate_image:ENOEXEC Executable file format error
4174 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
4175 * exec_activate_image:EAUTH Image decryption failed
4176 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
4177 * exec_activate_image:???
4178 * mac_execve_enter:???
4179 *
4180 * TODO: Expect to need __mac_posix_spawn() at some point...
4181 * Handle posix_spawnattr_t
4182 * Handle posix_spawn_file_actions_t
4183 */
4184 int
posix_spawn(proc_t ap,struct posix_spawn_args * uap,int32_t * retval)4185 posix_spawn(proc_t ap, struct posix_spawn_args *uap, int32_t *retval)
4186 {
4187 proc_t p = ap;
4188 user_addr_t pid = uap->pid;
4189 int ival[2]; /* dummy retval for setpgid() */
4190 char *subsystem_root_path = NULL;
4191 struct image_params *imgp = NULL;
4192 struct vnode_attr *vap = NULL;
4193 struct vnode_attr *origvap = NULL;
4194 struct uthread *uthread = 0; /* compiler complains if not set to 0*/
4195 int error, sig;
4196 int is_64 = IS_64BIT_PROCESS(p);
4197 struct vfs_context context;
4198 struct user__posix_spawn_args_desc px_args = {};
4199 struct _posix_spawnattr px_sa = {};
4200 _posix_spawn_file_actions_t px_sfap = NULL;
4201 _posix_spawn_port_actions_t px_spap = NULL;
4202 struct __kern_sigaction vec;
4203 boolean_t spawn_no_exec = FALSE;
4204 boolean_t proc_transit_set = TRUE;
4205 boolean_t proc_signal_set = TRUE;
4206 boolean_t exec_done = FALSE;
4207 os_reason_t exec_failure_reason = NULL;
4208
4209 struct exec_port_actions port_actions = { };
4210 vm_size_t px_sa_offset = offsetof(struct _posix_spawnattr, psa_ports);
4211 task_t old_task = current_task();
4212 task_t new_task = NULL;
4213 boolean_t should_release_proc_ref = FALSE;
4214 void *inherit = NULL;
4215 uint8_t crash_behavior = 0;
4216 uint64_t crash_behavior_deadline = 0;
4217 #if CONFIG_EXCLAVES
4218 char *task_conclave_id = NULL;
4219 #endif
4220 #if CONFIG_PERSONAS
4221 struct _posix_spawn_persona_info *px_persona = NULL;
4222 #endif
4223 struct _posix_spawn_posix_cred_info *px_pcred_info = NULL;
4224 struct {
4225 struct image_params imgp;
4226 struct vnode_attr va;
4227 struct vnode_attr origva;
4228 } *__spawn_data;
4229
4230 /*
4231 * Allocate a big chunk for locals instead of using stack since these
4232 * structures are pretty big.
4233 */
4234 __spawn_data = kalloc_type(typeof(*__spawn_data), Z_WAITOK | Z_ZERO);
4235 if (__spawn_data == NULL) {
4236 error = ENOMEM;
4237 goto bad;
4238 }
4239 imgp = &__spawn_data->imgp;
4240 vap = &__spawn_data->va;
4241 origvap = &__spawn_data->origva;
4242
4243 /* Initialize the common data in the image_params structure */
4244 imgp->ip_user_fname = uap->path;
4245 imgp->ip_user_argv = uap->argv;
4246 imgp->ip_user_envv = uap->envp;
4247 imgp->ip_vattr = vap;
4248 imgp->ip_origvattr = origvap;
4249 imgp->ip_vfs_context = &context;
4250 imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT_ADDR : IMGPF_NONE);
4251 imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
4252 imgp->ip_mac_return = 0;
4253 imgp->ip_px_persona = NULL;
4254 imgp->ip_px_pcred_info = NULL;
4255 imgp->ip_cs_error = OS_REASON_NULL;
4256 imgp->ip_simulator_binary = IMGPF_SB_DEFAULT;
4257 imgp->ip_subsystem_root_path = NULL;
4258 imgp->ip_inherited_shared_region_id = NULL;
4259 imgp->ip_inherited_jop_pid = 0;
4260 uthread_set_exec_data(current_uthread(), imgp);
4261
4262 if (uap->adesc != USER_ADDR_NULL) {
4263 if (is_64) {
4264 error = copyin(uap->adesc, &px_args, sizeof(px_args));
4265 } else {
4266 struct user32__posix_spawn_args_desc px_args32;
4267
4268 error = copyin(uap->adesc, &px_args32, sizeof(px_args32));
4269
4270 /*
4271 * Convert arguments descriptor from external 32 bit
4272 * representation to internal 64 bit representation
4273 */
4274 px_args.attr_size = px_args32.attr_size;
4275 px_args.attrp = CAST_USER_ADDR_T(px_args32.attrp);
4276 px_args.file_actions_size = px_args32.file_actions_size;
4277 px_args.file_actions = CAST_USER_ADDR_T(px_args32.file_actions);
4278 px_args.port_actions_size = px_args32.port_actions_size;
4279 px_args.port_actions = CAST_USER_ADDR_T(px_args32.port_actions);
4280 px_args.mac_extensions_size = px_args32.mac_extensions_size;
4281 px_args.mac_extensions = CAST_USER_ADDR_T(px_args32.mac_extensions);
4282 px_args.coal_info_size = px_args32.coal_info_size;
4283 px_args.coal_info = CAST_USER_ADDR_T(px_args32.coal_info);
4284 px_args.persona_info_size = px_args32.persona_info_size;
4285 px_args.persona_info = CAST_USER_ADDR_T(px_args32.persona_info);
4286 px_args.posix_cred_info_size = px_args32.posix_cred_info_size;
4287 px_args.posix_cred_info = CAST_USER_ADDR_T(px_args32.posix_cred_info);
4288 px_args.subsystem_root_path_size = px_args32.subsystem_root_path_size;
4289 px_args.subsystem_root_path = CAST_USER_ADDR_T(px_args32.subsystem_root_path);
4290 px_args.conclave_id_size = px_args32.conclave_id_size;
4291 px_args.conclave_id = CAST_USER_ADDR_T(px_args32.conclave_id);
4292 }
4293 if (error) {
4294 goto bad;
4295 }
4296
4297 if (px_args.attr_size != 0) {
4298 /*
4299 * We are not copying the port_actions pointer,
4300 * because we already have it from px_args.
4301 * This is a bit fragile: <rdar://problem/16427422>
4302 */
4303
4304 if ((error = copyin(px_args.attrp, &px_sa, px_sa_offset)) != 0) {
4305 goto bad;
4306 }
4307
4308 imgp->ip_px_sa = &px_sa;
4309 }
4310 if (px_args.file_actions_size != 0) {
4311 /* Limit file_actions to allowed number of open files */
4312 size_t maxfa_size = PSF_ACTIONS_SIZE(proc_limitgetcur_nofile(p));
4313
4314 if (px_args.file_actions_size < PSF_ACTIONS_SIZE(1) ||
4315 maxfa_size == 0 || px_args.file_actions_size > maxfa_size) {
4316 error = EINVAL;
4317 goto bad;
4318 }
4319
4320 px_sfap = kalloc_data(px_args.file_actions_size, Z_WAITOK);
4321 if (px_sfap == NULL) {
4322 error = ENOMEM;
4323 goto bad;
4324 }
4325 imgp->ip_px_sfa = px_sfap;
4326
4327 if ((error = copyin(px_args.file_actions, px_sfap,
4328 px_args.file_actions_size)) != 0) {
4329 goto bad;
4330 }
4331
4332 /* Verify that the action count matches the struct size */
4333 size_t psfsize = PSF_ACTIONS_SIZE(px_sfap->psfa_act_count);
4334 if (psfsize == 0 || psfsize != px_args.file_actions_size) {
4335 error = EINVAL;
4336 goto bad;
4337 }
4338 }
4339 if (px_args.port_actions_size != 0) {
4340 /* Limit port_actions to one page of data */
4341 if (px_args.port_actions_size < PS_PORT_ACTIONS_SIZE(1) ||
4342 px_args.port_actions_size > PAGE_SIZE) {
4343 error = EINVAL;
4344 goto bad;
4345 }
4346
4347 px_spap = kalloc_data(px_args.port_actions_size, Z_WAITOK);
4348 if (px_spap == NULL) {
4349 error = ENOMEM;
4350 goto bad;
4351 }
4352 imgp->ip_px_spa = px_spap;
4353
4354 if ((error = copyin(px_args.port_actions, px_spap,
4355 px_args.port_actions_size)) != 0) {
4356 goto bad;
4357 }
4358
4359 /* Verify that the action count matches the struct size */
4360 size_t pasize = PS_PORT_ACTIONS_SIZE(px_spap->pspa_count);
4361 if (pasize == 0 || pasize != px_args.port_actions_size) {
4362 error = EINVAL;
4363 goto bad;
4364 }
4365 }
4366 #if CONFIG_PERSONAS
4367 /* copy in the persona info */
4368 if (px_args.persona_info_size != 0 && px_args.persona_info != 0) {
4369 /* for now, we need the exact same struct in user space */
4370 if (px_args.persona_info_size != sizeof(*px_persona)) {
4371 error = ERANGE;
4372 goto bad;
4373 }
4374
4375 px_persona = kalloc_data(px_args.persona_info_size, Z_WAITOK);
4376 if (px_persona == NULL) {
4377 error = ENOMEM;
4378 goto bad;
4379 }
4380 imgp->ip_px_persona = px_persona;
4381
4382 if ((error = copyin(px_args.persona_info, px_persona,
4383 px_args.persona_info_size)) != 0) {
4384 goto bad;
4385 }
4386 if ((error = spawn_validate_persona(px_persona)) != 0) {
4387 goto bad;
4388 }
4389 }
4390 #endif
4391 /* copy in the posix cred info */
4392 if (px_args.posix_cred_info_size != 0 && px_args.posix_cred_info != 0) {
4393 /* for now, we need the exact same struct in user space */
4394 if (px_args.posix_cred_info_size != sizeof(*px_pcred_info)) {
4395 error = ERANGE;
4396 goto bad;
4397 }
4398
4399 if (!kauth_cred_issuser(kauth_cred_get())) {
4400 error = EPERM;
4401 goto bad;
4402 }
4403
4404 px_pcred_info = kalloc_data(px_args.posix_cred_info_size, Z_WAITOK);
4405 if (px_pcred_info == NULL) {
4406 error = ENOMEM;
4407 goto bad;
4408 }
4409 imgp->ip_px_pcred_info = px_pcred_info;
4410
4411 if ((error = copyin(px_args.posix_cred_info, px_pcred_info,
4412 px_args.posix_cred_info_size)) != 0) {
4413 goto bad;
4414 }
4415
4416 if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_GROUPS) {
4417 if (px_pcred_info->pspci_ngroups > NGROUPS_MAX) {
4418 error = EINVAL;
4419 goto bad;
4420 }
4421 }
4422 }
4423 #if CONFIG_MACF
4424 if (px_args.mac_extensions_size != 0) {
4425 if ((error = spawn_copyin_macpolicyinfo(&px_args, (struct ip_px_smpx_s *)&imgp->ip_px_smpx)) != 0) {
4426 goto bad;
4427 }
4428 }
4429 #endif /* CONFIG_MACF */
4430 if ((px_args.subsystem_root_path_size > 0) && (px_args.subsystem_root_path_size <= MAXPATHLEN)) {
4431 /*
4432 * If a valid-looking subsystem root has been
4433 * specified...
4434 */
4435 if (IOTaskHasEntitlement(old_task, SPAWN_SUBSYSTEM_ROOT_ENTITLEMENT)) {
4436 /*
4437 * ...AND the parent has the entitlement, copy
4438 * the subsystem root path in.
4439 */
4440 subsystem_root_path = zalloc_flags(ZV_NAMEI,
4441 Z_WAITOK | Z_ZERO | Z_NOFAIL);
4442
4443 if ((error = copyin(px_args.subsystem_root_path, subsystem_root_path, px_args.subsystem_root_path_size))) {
4444 goto bad;
4445 }
4446
4447 /* Paranoia */
4448 subsystem_root_path[px_args.subsystem_root_path_size - 1] = 0;
4449 }
4450 }
4451 #if CONFIG_EXCLAVES
4452
4453 /*
4454 * Calling exclaves_boot_wait() ensures that the conclave name
4455 * id will only be set when exclaves are actually
4456 * supported/enabled. In practice this will never actually block
4457 * as by the time this is called the system will have booted to
4458 * EXCLAVECORE if it's supported/enabled.
4459 */
4460 if ((px_args.conclave_id_size > 0) && (px_args.conclave_id_size <= MAXCONCLAVENAME) &&
4461 (exclaves_boot_wait(EXCLAVES_BOOT_STAGE_EXCLAVECORE) == KERN_SUCCESS)) {
4462 if (px_args.conclave_id) {
4463 if (imgp->ip_px_sa != NULL && (px_sa.psa_flags & POSIX_SPAWN_SETEXEC)) {
4464 /* Conclave id could be set only for true spawn */
4465 error = EINVAL;
4466 goto bad;
4467 }
4468 task_conclave_id = kalloc_data(MAXCONCLAVENAME,
4469 Z_WAITOK | Z_ZERO | Z_NOFAIL);
4470 if ((error = copyin(px_args.conclave_id, task_conclave_id, MAXCONCLAVENAME))) {
4471 goto bad;
4472 }
4473 task_conclave_id[MAXCONCLAVENAME - 1] = 0;
4474 }
4475 }
4476 #endif
4477 }
4478
4479 if (IOTaskHasEntitlement(old_task, SPAWN_SET_PANIC_CRASH_BEHAVIOR)) {
4480 /* Truncate to uint8_t since we only support 2 flags for now */
4481 crash_behavior = (uint8_t)px_sa.psa_crash_behavior;
4482 crash_behavior_deadline = px_sa.psa_crash_behavior_deadline;
4483 }
4484
4485 /* set uthread to parent */
4486 uthread = current_uthread();
4487
4488 /*
4489 * <rdar://6640530>; this does not result in a behaviour change
4490 * relative to Leopard, so there should not be any existing code
4491 * which depends on it.
4492 */
4493
4494 if (imgp->ip_px_sa != NULL) {
4495 struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
4496 if ((psa->psa_options & PSA_OPTION_PLUGIN_HOST_DISABLE_A_KEYS) == PSA_OPTION_PLUGIN_HOST_DISABLE_A_KEYS) {
4497 imgp->ip_flags |= IMGPF_PLUGIN_HOST_DISABLE_A_KEYS;
4498 }
4499
4500 #if (DEVELOPMENT || DEBUG)
4501 if ((psa->psa_options & PSA_OPTION_ALT_ROSETTA) == PSA_OPTION_ALT_ROSETTA) {
4502 imgp->ip_flags |= (IMGPF_ROSETTA | IMGPF_ALT_ROSETTA);
4503 }
4504 #if HAS_MTE_EMULATION_SHIMS
4505 /* If the task has inheritance enabled, carry the emulation setup. */
4506 if (task_has_sec(old_task) && task_has_sec_inherit(old_task)) {
4507 imgp->ip_flags |= (IMGPF_ROSETTA | IMGPF_ALT_ROSETTA);
4508 }
4509 #endif /* HAS_MTE_EMULATION_SHIMS */
4510 #endif /* (DEVELOPMENT || DEBUG) */
4511
4512
4513 if ((error = exec_validate_spawnattr_policy(psa->psa_apptype)) != 0) {
4514 goto bad;
4515 }
4516 }
4517
4518 /*
4519 * If we don't have the extension flag that turns "posix_spawn()"
4520 * into "execve() with options", then we will be creating a new
4521 * process which does not inherit memory from the parent process,
4522 * which is one of the most expensive things about using fork()
4523 * and execve().
4524 */
4525 if (imgp->ip_px_sa == NULL || !(px_sa.psa_flags & POSIX_SPAWN_SETEXEC)) {
4526 /* Set the new task's coalition, if it is requested. */
4527 coalition_t coal[COALITION_NUM_TYPES] = { COALITION_NULL };
4528 #if CONFIG_COALITIONS
4529 int i, ncoals;
4530 kern_return_t kr = KERN_SUCCESS;
4531 struct _posix_spawn_coalition_info coal_info;
4532 int coal_role[COALITION_NUM_TYPES];
4533
4534 if (imgp->ip_px_sa == NULL || !px_args.coal_info) {
4535 goto do_fork1;
4536 }
4537
4538 memset(&coal_info, 0, sizeof(coal_info));
4539
4540 if (px_args.coal_info_size > sizeof(coal_info)) {
4541 px_args.coal_info_size = sizeof(coal_info);
4542 }
4543 error = copyin(px_args.coal_info,
4544 &coal_info, px_args.coal_info_size);
4545 if (error != 0) {
4546 goto bad;
4547 }
4548
4549 ncoals = 0;
4550 for (i = 0; i < COALITION_NUM_TYPES; i++) {
4551 uint64_t cid = coal_info.psci_info[i].psci_id;
4552 if (cid != 0) {
4553 /*
4554 * don't allow tasks which are not in a
4555 * privileged coalition to spawn processes
4556 * into coalitions other than their own
4557 */
4558 if (!task_is_in_privileged_coalition(proc_task(p), i) &&
4559 !IOTaskHasEntitlement(proc_task(p), COALITION_SPAWN_ENTITLEMENT)) {
4560 coal_dbg("ERROR: %d not in privilegd "
4561 "coalition of type %d",
4562 proc_getpid(p), i);
4563 spawn_coalitions_release_all(coal);
4564 error = EPERM;
4565 goto bad;
4566 }
4567
4568 coal_dbg("searching for coalition id:%llu", cid);
4569 /*
4570 * take a reference and activation on the
4571 * coalition to guard against free-while-spawn
4572 * races
4573 */
4574 coal[i] = coalition_find_and_activate_by_id(cid);
4575 if (coal[i] == COALITION_NULL) {
4576 coal_dbg("could not find coalition id:%llu "
4577 "(perhaps it has been terminated or reaped)", cid);
4578 /*
4579 * release any other coalition's we
4580 * may have a reference to
4581 */
4582 spawn_coalitions_release_all(coal);
4583 error = ESRCH;
4584 goto bad;
4585 }
4586 if (coalition_type(coal[i]) != i) {
4587 coal_dbg("coalition with id:%lld is not of type:%d"
4588 " (it's type:%d)", cid, i, coalition_type(coal[i]));
4589 spawn_coalitions_release_all(coal);
4590 error = ESRCH;
4591 goto bad;
4592 }
4593 coal_role[i] = coal_info.psci_info[i].psci_role;
4594 ncoals++;
4595 }
4596 }
4597 if (ncoals < COALITION_NUM_TYPES) {
4598 /*
4599 * If the user is attempting to spawn into a subset of
4600 * the known coalition types, then make sure they have
4601 * _at_least_ specified a resource coalition. If not,
4602 * the following fork1() call will implicitly force an
4603 * inheritance from 'p' and won't actually spawn the
4604 * new task into the coalitions the user specified.
4605 * (also the call to coalitions_set_roles will panic)
4606 */
4607 if (coal[COALITION_TYPE_RESOURCE] == COALITION_NULL) {
4608 spawn_coalitions_release_all(coal);
4609 error = EINVAL;
4610 goto bad;
4611 }
4612 }
4613 do_fork1:
4614 #endif /* CONFIG_COALITIONS */
4615
4616 /*
4617 * note that this will implicitly inherit the
4618 * caller's persona (if it exists)
4619 */
4620 error = fork1(p, &imgp->ip_new_thread, PROC_CREATE_SPAWN, coal);
4621 /* returns a thread and task reference */
4622
4623 if (error == 0) {
4624 new_task = get_threadtask(imgp->ip_new_thread);
4625 }
4626 #if CONFIG_COALITIONS
4627 /* set the roles of this task within each given coalition */
4628 if (error == 0) {
4629 kr = coalitions_set_roles(coal, new_task, coal_role);
4630 if (kr != KERN_SUCCESS) {
4631 error = EINVAL;
4632 }
4633 if (kdebug_debugid_enabled(MACHDBG_CODE(DBG_MACH_COALITION,
4634 MACH_COALITION_ADOPT))) {
4635 for (i = 0; i < COALITION_NUM_TYPES; i++) {
4636 if (coal[i] != COALITION_NULL) {
4637 /*
4638 * On 32-bit targets, uniqueid
4639 * will get truncated to 32 bits
4640 */
4641 KDBG_RELEASE(MACHDBG_CODE(
4642 DBG_MACH_COALITION,
4643 MACH_COALITION_ADOPT),
4644 coalition_id(coal[i]),
4645 get_task_uniqueid(new_task));
4646 }
4647 }
4648 }
4649 }
4650
4651 /* drop our references and activations - fork1() now holds them */
4652 spawn_coalitions_release_all(coal);
4653 #endif /* CONFIG_COALITIONS */
4654 if (error != 0) {
4655 goto bad;
4656 }
4657 imgp->ip_flags |= IMGPF_SPAWN; /* spawn w/o exec */
4658 spawn_no_exec = TRUE; /* used in later tests */
4659 } else {
4660 /* Adjust the user proc count */
4661 (void)chgproccnt(kauth_getruid(), 1);
4662 /*
4663 * For execve case, create a new proc, task and thread
4664 * but don't make the proc visible to userland. After
4665 * image activation, the new proc would take place of
4666 * the old proc in pid hash and other lists that make
4667 * the proc visible to the system.
4668 */
4669 imgp->ip_new_thread = cloneproc(old_task, NULL, p, CLONEPROC_EXEC);
4670
4671 /* task and thread ref returned by cloneproc */
4672 if (imgp->ip_new_thread == NULL) {
4673 (void)chgproccnt(kauth_getruid(), -1);
4674 error = ENOMEM;
4675 goto bad;
4676 }
4677
4678 new_task = get_threadtask(imgp->ip_new_thread);
4679 imgp->ip_flags |= IMGPF_EXEC;
4680 }
4681
4682 p = (proc_t)get_bsdthreadtask_info(imgp->ip_new_thread);
4683
4684 if (spawn_no_exec) {
4685 /*
4686 * We had to wait until this point before firing the
4687 * proc:::create probe, otherwise p would not point to the
4688 * child process.
4689 */
4690 DTRACE_PROC1(create, proc_t, p);
4691 }
4692 assert(p != NULL);
4693
4694 if (subsystem_root_path) {
4695 /* If a subsystem root was specified, swap it in */
4696 char * old_subsystem_root_path = p->p_subsystem_root_path;
4697 p->p_subsystem_root_path = subsystem_root_path;
4698 subsystem_root_path = old_subsystem_root_path;
4699 }
4700
4701 p->p_crash_behavior = crash_behavior;
4702 p->p_crash_behavior_deadline = crash_behavior_deadline;
4703
4704 p->p_crash_count = px_sa.psa_crash_count;
4705 p->p_throttle_timeout = px_sa.psa_throttle_timeout;
4706
4707 /* We'll need the subsystem root for setting up Apple strings */
4708 imgp->ip_subsystem_root_path = p->p_subsystem_root_path;
4709
4710 context.vc_thread = imgp->ip_new_thread;
4711 context.vc_ucred = proc_ucred_unsafe(p); /* in init */
4712
4713 /*
4714 * Post fdt_fork(), pre exec_handle_sugid() - this is where we want
4715 * to handle the file_actions.
4716 */
4717
4718 /* Has spawn file actions? */
4719 if (imgp->ip_px_sfa != NULL) {
4720 /*
4721 * The POSIX_SPAWN_CLOEXEC_DEFAULT flag
4722 * is handled in exec_handle_file_actions().
4723 */
4724 #if CONFIG_AUDIT
4725 /*
4726 * The file actions auditing can overwrite the upath of
4727 * AUE_POSIX_SPAWN audit record. Save the audit record.
4728 */
4729 struct kaudit_record *save_uu_ar = uthread->uu_ar;
4730 uthread->uu_ar = NULL;
4731 #endif
4732 error = exec_handle_file_actions(imgp,
4733 imgp->ip_px_sa != NULL ? px_sa.psa_flags : 0);
4734 #if CONFIG_AUDIT
4735 /* Restore the AUE_POSIX_SPAWN audit record. */
4736 uthread->uu_ar = save_uu_ar;
4737 #endif
4738 if (error != 0) {
4739 goto bad;
4740 }
4741 }
4742
4743 /* Has spawn port actions? */
4744 if (imgp->ip_px_spa != NULL) {
4745 #if CONFIG_AUDIT
4746 /*
4747 * Do the same for the port actions as we did for the file
4748 * actions. Save the AUE_POSIX_SPAWN audit record.
4749 */
4750 struct kaudit_record *save_uu_ar = uthread->uu_ar;
4751 uthread->uu_ar = NULL;
4752 #endif
4753 error = exec_handle_port_actions(imgp, &port_actions);
4754 #if CONFIG_AUDIT
4755 /* Restore the AUE_POSIX_SPAWN audit record. */
4756 uthread->uu_ar = save_uu_ar;
4757 #endif
4758 if (error != 0) {
4759 goto bad;
4760 }
4761 }
4762
4763 /* Has spawn attr? */
4764 if (imgp->ip_px_sa != NULL) {
4765 /*
4766 * Reset UID/GID to parent's RUID/RGID; This works only
4767 * because the operation occurs before the call
4768 * to exec_handle_sugid() by the image activator called
4769 * from exec_activate_image().
4770 *
4771 * POSIX requires that any setuid/setgid bits on the process
4772 * image will take precedence over the spawn attributes
4773 * (re)setting them.
4774 *
4775 * Modifications to p_ucred must be guarded using the
4776 * proc's ucred lock. This prevents others from accessing
4777 * a garbage credential.
4778 */
4779 if (px_sa.psa_flags & POSIX_SPAWN_RESETIDS) {
4780 kauth_cred_proc_update(p, PROC_SETTOKEN_NONE,
4781 ^bool (kauth_cred_t parent __unused, kauth_cred_t model){
4782 return kauth_cred_model_setuidgid(model,
4783 kauth_cred_getruid(parent),
4784 kauth_cred_getrgid(parent));
4785 });
4786 }
4787
4788 if (imgp->ip_px_pcred_info) {
4789 if (!spawn_no_exec) {
4790 error = ENOTSUP;
4791 goto bad;
4792 }
4793
4794 error = spawn_posix_cred_adopt(p, imgp->ip_px_pcred_info);
4795 if (error != 0) {
4796 goto bad;
4797 }
4798 }
4799
4800 #if CONFIG_PERSONAS
4801 if (imgp->ip_px_persona != NULL) {
4802 if (!spawn_no_exec) {
4803 error = ENOTSUP;
4804 goto bad;
4805 }
4806
4807 /*
4808 * If we were asked to spawn a process into a new persona,
4809 * do the credential switch now (which may override the UID/GID
4810 * inherit done just above). It's important to do this switch
4811 * before image activation both for reasons stated above, and
4812 * to ensure that the new persona has access to the image/file
4813 * being executed.
4814 */
4815 error = spawn_persona_adopt(p, imgp->ip_px_persona);
4816 if (error != 0) {
4817 goto bad;
4818 }
4819 }
4820 #endif /* CONFIG_PERSONAS */
4821 #if !SECURE_KERNEL
4822 /*
4823 * Disable ASLR for the spawned process.
4824 *
4825 * But only do so if we are not embedded + RELEASE.
4826 * While embedded allows for a boot-arg (-disable_aslr)
4827 * to deal with this (which itself is only honored on
4828 * DEVELOPMENT or DEBUG builds of xnu), it is often
4829 * useful or necessary to disable ASLR on a per-process
4830 * basis for unit testing and debugging.
4831 */
4832 if (px_sa.psa_flags & _POSIX_SPAWN_DISABLE_ASLR) {
4833 OSBitOrAtomic(P_DISABLE_ASLR, &p->p_flag);
4834 }
4835 #endif /* !SECURE_KERNEL */
4836
4837 /* Randomize high bits of ASLR slide */
4838 if (px_sa.psa_flags & _POSIX_SPAWN_HIGH_BITS_ASLR) {
4839 imgp->ip_flags |= IMGPF_HIGH_BITS_ASLR;
4840 }
4841
4842 #if !SECURE_KERNEL
4843 /*
4844 * Forcibly disallow execution from data pages for the spawned process
4845 * even if it would otherwise be permitted by the architecture default.
4846 */
4847 if (px_sa.psa_flags & _POSIX_SPAWN_ALLOW_DATA_EXEC) {
4848 imgp->ip_flags |= IMGPF_ALLOW_DATA_EXEC;
4849 }
4850 #endif /* !SECURE_KERNEL */
4851
4852 #if __has_feature(ptrauth_calls)
4853 if (vm_shared_region_reslide_aslr && is_64 && (px_sa.psa_flags & _POSIX_SPAWN_RESLIDE)) {
4854 imgp->ip_flags |= IMGPF_RESLIDE;
4855 }
4856 #endif /* __has_feature(ptrauth_calls) */
4857
4858 if ((px_sa.psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) ==
4859 POSIX_SPAWN_PROC_TYPE_DRIVER) {
4860 imgp->ip_flags |= IMGPF_DRIVER;
4861 }
4862 }
4863
4864 /*
4865 * Disable ASLR during image activation. This occurs either if the
4866 * _POSIX_SPAWN_DISABLE_ASLR attribute was found above or if
4867 * P_DISABLE_ASLR was inherited from the parent process.
4868 */
4869 if (p->p_flag & P_DISABLE_ASLR) {
4870 imgp->ip_flags |= IMGPF_DISABLE_ASLR;
4871 }
4872
4873 /*
4874 * Clear transition flag so we won't hang if exec_activate_image() causes
4875 * an automount (and launchd does a proc sysctl to service it).
4876 *
4877 * <rdar://problem/6848672>, <rdar://problem/5959568>.
4878 */
4879 proc_transend(p, 0);
4880 proc_transit_set = 0;
4881
4882 if (!spawn_no_exec) {
4883 /*
4884 * Clear the signal lock in case of exec, since
4885 * image activation uses psignal on child process.
4886 */
4887 proc_signalend(p, 0);
4888 proc_signal_set = 0;
4889 }
4890
4891 #if MAC_SPAWN /* XXX */
4892 if (uap->mac_p != USER_ADDR_NULL) {
4893 error = mac_execve_enter(uap->mac_p, imgp);
4894 if (error) {
4895 goto bad;
4896 }
4897 }
4898 #endif
4899 /*
4900 * Activate the image.
4901 * Warning: If activation failed after point of no return, it returns error
4902 * as 0 and pretends the call succeeded.
4903 */
4904 error = exec_activate_image(imgp);
4905 #if defined(HAS_APPLE_PAC)
4906 const uint8_t disable_user_jop = imgp->ip_flags & IMGPF_NOJOP ? TRUE : FALSE;
4907 ml_task_set_jop_pid_from_shared_region(new_task, disable_user_jop);
4908 ml_task_set_disable_user_jop(new_task, disable_user_jop);
4909 ml_thread_set_disable_user_jop(imgp->ip_new_thread, disable_user_jop);
4910 ml_thread_set_jop_pid(imgp->ip_new_thread, new_task);
4911 #endif
4912
4913 /*
4914 * If you've come here to add support for some new HW feature or some per-process or per-vmmap
4915 * or per-pmap flag that needs to be set before the process runs, or are in general lost, here
4916 * is some help. This summary was accurate as of Jul 2022. Use git log as needed. This comment
4917 * is here to prevent a recurrence of rdar://96307913
4918 *
4919 * In posix_spawn, following is what happens:
4920 * 1. Lots of prep and checking work
4921 * 2. Image activation via exec_activate_image(). The new task will get a new pmap here
4922 * 3. More prep work. (YOU ARE HERE)
4923 * 4. exec_resettextvp() is called
4924 * 5. At this point it is safe to check entitlements and code signatures
4925 * 6. task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_INITIAL_WAIT);
4926 * The new thread is allowed to run in kernel. It cannot yet get to userland
4927 * 7. More things done here. This is your chance to affect the task before it runs in
4928 * userspace
4929 * 8. task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_FINAL_WAIT);
4930 * The new thread is allowed to run in userland
4931 */
4932
4933 if (error == 0 && !spawn_no_exec) {
4934 p = proc_exec_switch_task(current_proc(), p, old_task, new_task, imgp, &inherit);
4935 /* proc ref returned */
4936 should_release_proc_ref = TRUE;
4937 }
4938
4939 if (error == 0) {
4940 /* process completed the exec, but may have failed after point of no return */
4941 exec_done = TRUE;
4942 }
4943
4944 #if CONFIG_EXCLAVES
4945 if (!error && task_conclave_id != NULL) {
4946 kern_return_t kr;
4947 kr = task_add_conclave(new_task, imgp->ip_vp, (int64_t)imgp->ip_arch_offset,
4948 task_conclave_id);
4949 if (kr != KERN_SUCCESS) {
4950 error = EINVAL;
4951 goto bad;
4952 }
4953 }
4954 #endif
4955
4956 if (!error && imgp->ip_px_sa != NULL) {
4957 thread_t child_thread = imgp->ip_new_thread;
4958 uthread_t child_uthread = get_bsdthread_info(child_thread);
4959
4960 /*
4961 * Because of POSIX_SPAWN_SETEXEC, we need to handle this after image
4962 * activation, else when image activation fails (before the point of no
4963 * return) would leave the parent process in a modified state.
4964 */
4965 if (px_sa.psa_flags & POSIX_SPAWN_SETPGROUP) {
4966 struct setpgid_args spga;
4967 spga.pid = proc_getpid(p);
4968 spga.pgid = px_sa.psa_pgroup;
4969 /*
4970 * Effectively, call setpgid() system call; works
4971 * because there are no pointer arguments.
4972 */
4973 if ((error = setpgid(p, &spga, ival)) != 0) {
4974 goto bad_px_sa;
4975 }
4976 }
4977
4978 if (px_sa.psa_flags & POSIX_SPAWN_SETSID) {
4979 error = setsid_internal(p);
4980 if (error != 0) {
4981 goto bad_px_sa;
4982 }
4983 }
4984
4985 /*
4986 * If we have a spawn attr, and it contains signal related flags,
4987 * the we need to process them in the "context" of the new child
4988 * process, so we have to process it following image activation,
4989 * prior to making the thread runnable in user space. This is
4990 * necessitated by some signal information being per-thread rather
4991 * than per-process, and we don't have the new allocation in hand
4992 * until after the image is activated.
4993 */
4994
4995 /*
4996 * Mask a list of signals, instead of them being unmasked, if
4997 * they were unmasked in the parent; note that some signals
4998 * are not maskable.
4999 */
5000 if (px_sa.psa_flags & POSIX_SPAWN_SETSIGMASK) {
5001 child_uthread->uu_sigmask = (px_sa.psa_sigmask & ~sigcantmask);
5002 }
5003 /*
5004 * Default a list of signals instead of ignoring them, if
5005 * they were ignored in the parent. Note that we pass
5006 * spawn_no_exec to setsigvec() to indicate that we called
5007 * fork1() and therefore do not need to call proc_signalstart()
5008 * internally.
5009 */
5010 if (px_sa.psa_flags & POSIX_SPAWN_SETSIGDEF) {
5011 vec.sa_handler = SIG_DFL;
5012 vec.sa_tramp = 0;
5013 vec.sa_mask = 0;
5014 vec.sa_flags = 0;
5015 for (sig = 1; sig < NSIG; sig++) {
5016 if (px_sa.psa_sigdefault & (1 << (sig - 1))) {
5017 error = setsigvec(p, child_thread, sig, &vec, spawn_no_exec);
5018 }
5019 }
5020 }
5021
5022 /*
5023 * Activate the CPU usage monitor, if requested. This is done via a task-wide, per-thread CPU
5024 * usage limit, which will generate a resource exceeded exception if any one thread exceeds the
5025 * limit.
5026 *
5027 * Userland gives us interval in seconds, and the kernel SPI expects nanoseconds.
5028 */
5029 if ((px_sa.psa_cpumonitor_percent != 0) && (px_sa.psa_cpumonitor_percent < UINT8_MAX)) {
5030 /*
5031 * Always treat a CPU monitor activation coming from spawn as entitled. Requiring
5032 * an entitlement to configure the monitor a certain way seems silly, since
5033 * whomever is turning it on could just as easily choose not to do so.
5034 */
5035 error = proc_set_task_ruse_cpu(proc_task(p),
5036 TASK_POLICY_RESOURCE_ATTRIBUTE_NOTIFY_EXC,
5037 (uint8_t)px_sa.psa_cpumonitor_percent,
5038 px_sa.psa_cpumonitor_interval * NSEC_PER_SEC,
5039 0, TRUE);
5040 }
5041
5042
5043 if (px_pcred_info &&
5044 (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_LOGIN)) {
5045 /*
5046 * setlogin() must happen after setsid()
5047 */
5048 setlogin_internal(p, px_pcred_info->pspci_login);
5049 }
5050
5051 bad_px_sa:
5052 if (error != 0) {
5053 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
5054 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_PSATTR, 0, 0);
5055 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_PSATTR);
5056 }
5057 }
5058
5059 bad:
5060
5061 if (error == 0) {
5062 /* reset delay idle sleep status if set */
5063 #if CONFIG_DELAY_IDLE_SLEEP
5064 if ((p->p_flag & P_DELAYIDLESLEEP) == P_DELAYIDLESLEEP) {
5065 OSBitAndAtomic(~((uint32_t)P_DELAYIDLESLEEP), &p->p_flag);
5066 }
5067 #endif /* CONFIG_DELAY_IDLE_SLEEP */
5068 /* upon successful spawn, re/set the proc control state */
5069 if (imgp->ip_px_sa != NULL) {
5070 switch (px_sa.psa_pcontrol) {
5071 case POSIX_SPAWN_PCONTROL_THROTTLE:
5072 p->p_pcaction = P_PCTHROTTLE;
5073 break;
5074 case POSIX_SPAWN_PCONTROL_SUSPEND:
5075 p->p_pcaction = P_PCSUSP;
5076 break;
5077 case POSIX_SPAWN_PCONTROL_KILL:
5078 p->p_pcaction = P_PCKILL;
5079 break;
5080 case POSIX_SPAWN_PCONTROL_NONE:
5081 default:
5082 p->p_pcaction = 0;
5083 break;
5084 }
5085 ;
5086 }
5087 exec_resettextvp(p, imgp);
5088
5089 vm_map_setup(get_task_map(new_task), new_task);
5090
5091 exec_setup_platform_restrictions(new_task);
5092
5093 /*
5094 * Set starting EXC_GUARD behavior for task now that platform
5095 * and platform restrictions bits are set.
5096 */
5097 task_set_exc_guard_default(new_task,
5098 proc_best_name(p),
5099 strlen(proc_best_name(p)),
5100 proc_is_simulated(p),
5101 proc_platform(p),
5102 proc_sdk(p));
5103
5104 /*
5105 * Between proc_exec_switch_task and ipc_task_enable, there is a
5106 * window where proc_find will return the new proc, but task_for_pid
5107 * and similar functions will return an error as the task ipc is not
5108 * enabled yet. Configure the task control port during this window
5109 * before other process have access to this task port.
5110 *
5111 * Must enable after resettextvp so that task port policies are not evaluated
5112 * until the csblob in the textvp is accurately reflected.
5113 */
5114 task_set_ctrl_port_default(new_task, imgp->ip_new_thread);
5115
5116 /*
5117 * Enable new task IPC access if exec_activate_image() returned an
5118 * active task. (Checks active bit in ipc_task_enable() under lock).
5119 * Similarly, this must happen after resettextvp.
5120 */
5121 ipc_task_enable(new_task);
5122
5123 /* Set task exception ports now that we can check entitlements */
5124 if (imgp->ip_px_spa != NULL) {
5125 error = exec_handle_exception_port_actions(imgp, &port_actions);
5126 }
5127
5128 #if CONFIG_MEMORYSTATUS
5129 /* Set jetsam priority for DriverKit processes */
5130 if (px_sa.psa_apptype == POSIX_SPAWN_PROC_TYPE_DRIVER) {
5131 px_sa.psa_priority = JETSAM_PRIORITY_DRIVER_APPLE;
5132 }
5133
5134 /* Has jetsam attributes? */
5135 if (imgp->ip_px_sa != NULL && (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_SET)) {
5136 int32_t memlimit_active = px_sa.psa_memlimit_active;
5137 int32_t memlimit_inactive = px_sa.psa_memlimit_inactive;
5138
5139 memstat_priority_options_t priority_options = MEMSTAT_PRIORITY_OPTIONS_NONE;
5140 if ((px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY)) {
5141 priority_options |= MEMSTAT_PRIORITY_IS_EFFECTIVE;
5142 }
5143 memorystatus_set_priority(p, px_sa.psa_priority, 0,
5144 priority_options);
5145
5146 memlimit_options_t memlimit_options = MEMLIMIT_OPTIONS_NONE;
5147 if ((px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_MEMLIMIT_ACTIVE_FATAL)) {
5148 memlimit_options |= MEMLIMIT_ACTIVE_FATAL;
5149 }
5150 if ((px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_MEMLIMIT_INACTIVE_FATAL)) {
5151 memlimit_options |= MEMLIMIT_INACTIVE_FATAL;
5152 }
5153 if (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND) {
5154 /*
5155 * With 2-level high-water-mark support,
5156 * POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is no longer relevant,
5157 * as background limits are described via the inactive limit
5158 * slots. However, if the
5159 * POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is passed in, we
5160 * attempt to mimic previous behavior by forcing the BG limit
5161 * data into the inactive/non-fatal mode and force the active
5162 * slots to hold system_wide/fatal mode.
5163 */
5164 memlimit_options |= MEMLIMIT_ACTIVE_FATAL;
5165 memlimit_options &= ~MEMLIMIT_INACTIVE_FATAL;
5166 memlimit_active = -1;
5167 }
5168 memorystatus_set_memlimits(p, memlimit_active, memlimit_inactive,
5169 memlimit_options);
5170 }
5171
5172 /* Has jetsam relaunch behavior? */
5173 if (imgp->ip_px_sa != NULL && (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_MASK)) {
5174 /*
5175 * Launchd has passed in data indicating the behavior of this process in response to jetsam.
5176 * This data would be used by the jetsam subsystem to determine the position and protection
5177 * offered to this process on dirty -> clean transitions.
5178 */
5179 int relaunch_flags = P_MEMSTAT_RELAUNCH_UNKNOWN;
5180 switch (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_MASK) {
5181 case POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_LOW:
5182 relaunch_flags = P_MEMSTAT_RELAUNCH_LOW;
5183 break;
5184 case POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_MED:
5185 relaunch_flags = P_MEMSTAT_RELAUNCH_MED;
5186 break;
5187 case POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_HIGH:
5188 relaunch_flags = P_MEMSTAT_RELAUNCH_HIGH;
5189 break;
5190 default:
5191 break;
5192 }
5193 memorystatus_relaunch_flags_update(p, relaunch_flags);
5194 }
5195
5196 #endif /* CONFIG_MEMORYSTATUS */
5197 if (imgp->ip_px_sa != NULL && px_sa.psa_thread_limit > 0) {
5198 task_set_thread_limit(new_task, (uint16_t)px_sa.psa_thread_limit);
5199 }
5200 if (imgp->ip_px_sa != NULL && px_sa.psa_conclave_mem_limit > 0) {
5201 task_set_conclave_mem_limit(new_task, px_sa.psa_conclave_mem_limit);
5202 }
5203
5204 #if CONFIG_PROC_RESOURCE_LIMITS
5205 if (imgp->ip_px_sa != NULL && (px_sa.psa_port_soft_limit > 0 || px_sa.psa_port_hard_limit > 0)) {
5206 task_set_port_space_limits(new_task, (uint32_t)px_sa.psa_port_soft_limit,
5207 (uint32_t)px_sa.psa_port_hard_limit);
5208 }
5209
5210 if (imgp->ip_px_sa != NULL && (px_sa.psa_filedesc_soft_limit > 0 || px_sa.psa_filedesc_hard_limit > 0)) {
5211 proc_set_filedesc_limits(p, (int)px_sa.psa_filedesc_soft_limit,
5212 (int)px_sa.psa_filedesc_hard_limit);
5213 }
5214 if (imgp->ip_px_sa != NULL && (px_sa.psa_kqworkloop_soft_limit > 0 || px_sa.psa_kqworkloop_hard_limit > 0)) {
5215 proc_set_kqworkloop_limits(p, (int)px_sa.psa_kqworkloop_soft_limit,
5216 (int)px_sa.psa_kqworkloop_hard_limit);
5217 }
5218 #endif /* CONFIG_PROC_RESOURCE_LIMITS */
5219
5220 if (imgp->ip_px_sa != NULL && (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_REALTIME_AUDIO)) {
5221 task_set_jetsam_realtime_audio(new_task, TRUE);
5222 }
5223 }
5224
5225
5226 /*
5227 * If we successfully called fork1() or cloneproc, we always need
5228 * to do this. This is because we come back from that call with
5229 * signals blocked in the child, and we have to unblock them, for exec
5230 * case they are unblocked before activation, but for true spawn case
5231 * we want to wait until after we've performed any spawn actions.
5232 * This has to happen before process_signature(), which uses psignal.
5233 */
5234 if (proc_transit_set) {
5235 proc_transend(p, 0);
5236 }
5237
5238 /*
5239 * Drop the signal lock on the child which was taken on our
5240 * behalf by forkproc()/cloneproc() to prevent signals being
5241 * received by the child in a partially constructed state.
5242 */
5243 if (proc_signal_set) {
5244 proc_signalend(p, 0);
5245 }
5246
5247 if (error == 0) {
5248 /*
5249 * We need to initialize the bank context behind the protection of
5250 * the proc_trans lock to prevent a race with exit. We can't do this during
5251 * exec_activate_image because task_bank_init checks entitlements that
5252 * aren't loaded until subsequent calls (including exec_resettextvp).
5253 */
5254 error = proc_transstart(p, 0, 0);
5255
5256 if (error == 0) {
5257 task_bank_init(new_task);
5258 proc_transend(p, 0);
5259 }
5260
5261 #if __arm64__
5262 proc_footprint_entitlement_hacks(p, new_task);
5263 #endif /* __arm64__ */
5264
5265 #if XNU_TARGET_OS_OSX
5266 #define SINGLE_JIT_ENTITLEMENT "com.apple.security.cs.single-jit"
5267 if (IOTaskHasEntitlement(new_task, SINGLE_JIT_ENTITLEMENT)) {
5268 vm_map_single_jit(get_task_map(new_task));
5269 }
5270 #endif /* XNU_TARGET_OS_OSX */
5271
5272 #if __has_feature(ptrauth_calls)
5273 task_set_pac_exception_fatal_flag(new_task);
5274 #endif /* __has_feature(ptrauth_calls) */
5275 task_set_jit_flags(new_task);
5276 }
5277
5278 /* Inherit task role from old task to new task for exec */
5279 if (error == 0 && !spawn_no_exec) {
5280 proc_inherit_task_role(new_task, old_task);
5281 }
5282
5283 #if CONFIG_ARCADE
5284 if (error == 0) {
5285 /*
5286 * Check to see if we need to trigger an arcade upcall AST now
5287 * that the vnode has been reset on the task.
5288 */
5289 arcade_prepare(new_task, imgp->ip_new_thread);
5290 }
5291 #endif /* CONFIG_ARCADE */
5292
5293 if (error == 0) {
5294 proc_apply_jit_and_vm_policies(imgp, p, new_task);
5295 }
5296
5297 /* Clear the initial wait on the thread before handling spawn policy */
5298 if (imgp && imgp->ip_new_thread) {
5299 task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_INITIAL_WAIT);
5300 }
5301
5302 /*
5303 * Apply the spawnattr policy, apptype (which primes the task for importance donation),
5304 * and bind any portwatch ports to the new task.
5305 * This must be done after the exec so that the child's thread is ready,
5306 * and after the in transit state has been released, because priority is
5307 * dropped here so we need to be prepared for a potentially long preemption interval
5308 *
5309 * TODO: Consider splitting this up into separate phases
5310 */
5311 if (error == 0 && imgp->ip_px_sa != NULL) {
5312 struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
5313
5314 error = exec_handle_spawnattr_policy(p, imgp->ip_new_thread, psa->psa_apptype, psa->psa_qos_clamp,
5315 psa->psa_darwin_role, &port_actions);
5316 }
5317
5318 /* Transfer the turnstile watchport boost to new task if in exec */
5319 if (error == 0 && !spawn_no_exec) {
5320 task_transfer_turnstile_watchports(old_task, new_task, imgp->ip_new_thread);
5321 }
5322
5323 if (error == 0 && imgp->ip_px_sa != NULL) {
5324 struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
5325
5326 if (psa->psa_no_smt) {
5327 task_set_no_smt(new_task);
5328 }
5329 if (psa->psa_tecs) {
5330 task_set_tecs(new_task);
5331 }
5332 }
5333
5334 struct _iopol_param_t iop_param = {
5335 .iop_scope = IOPOL_SCOPE_PROCESS,
5336 .iop_iotype = IOPOL_TYPE_VFS_MATERIALIZE_DATALESS_FILES,
5337 };
5338
5339 if (error == 0) {
5340 if (imgp->ip_px_sa != NULL) {
5341 struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
5342
5343 if (psa->psa_options & PSA_OPTION_DATALESS_IOPOLICY) {
5344 iop_param.iop_policy = psa->psa_dataless_iopolicy;
5345 }
5346 } else {
5347 error = iopolicysys_vfs_materialize_dataless_files(p, IOPOL_CMD_GET, iop_param.iop_scope,
5348 iop_param.iop_policy, &iop_param);
5349 }
5350 }
5351
5352 if (error == 0 && iop_param.iop_policy != 0) {
5353 error = iopolicysys_vfs_materialize_dataless_files(p, IOPOL_CMD_SET, iop_param.iop_scope,
5354 (iop_param.iop_policy | IOPOL_MATERIALIZE_DATALESS_FILES_ORIG), &iop_param);
5355 }
5356
5357 if (error == 0) {
5358 /* Apply the main thread qos */
5359 thread_t main_thread = imgp->ip_new_thread;
5360 task_set_main_thread_qos(new_task, main_thread);
5361 }
5362
5363 /*
5364 * Release any ports we kept around for binding to the new task
5365 * We need to release the rights even if the posix_spawn has failed.
5366 */
5367 if (imgp->ip_px_spa != NULL) {
5368 exec_port_actions_destroy(&port_actions);
5369 }
5370
5371 /*
5372 * We have to delay operations which might throw a signal until after
5373 * the signals have been unblocked; however, we want that to happen
5374 * after exec_resettextvp() so that the textvp is correct when they
5375 * fire.
5376 */
5377 if (error == 0) {
5378 error = process_signature(p, imgp);
5379
5380 /*
5381 * Pay for our earlier safety; deliver the delayed signals from
5382 * the incomplete spawn process now that it's complete.
5383 */
5384 if (imgp != NULL && spawn_no_exec && (p->p_lflag & P_LTRACED)) {
5385 psignal_vfork(p, proc_task(p), imgp->ip_new_thread, SIGTRAP);
5386 }
5387
5388 if (error == 0 && !spawn_no_exec) {
5389 extern uint64_t kdp_task_exec_meta_flags(task_t task);
5390 KDBG(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXEC),
5391 proc_getpid(p), kdp_task_exec_meta_flags(proc_task(p)));
5392 }
5393 }
5394
5395 if (spawn_no_exec) {
5396 /* flag the 'fork' has occurred */
5397 proc_knote(p->p_pptr, NOTE_FORK | proc_getpid(p));
5398 }
5399
5400 /* flag exec has occurred, notify only if it has not failed due to FP Key error */
5401 if (!error && ((p->p_lflag & P_LTERM_DECRYPTFAIL) == 0)) {
5402 proc_knote(p, NOTE_EXEC);
5403 }
5404
5405 if (imgp != NULL) {
5406 uthread_set_exec_data(current_uthread(), NULL);
5407 if (imgp->ip_vp) {
5408 vnode_put(imgp->ip_vp);
5409 }
5410 if (imgp->ip_scriptvp) {
5411 vnode_put(imgp->ip_scriptvp);
5412 }
5413 if (imgp->ip_strings) {
5414 execargs_free(imgp);
5415 }
5416 if (imgp->ip_free_map) {
5417 /* Free the map after dropping iocount on vnode to avoid deadlock */
5418 vm_map_deallocate(imgp->ip_free_map);
5419 }
5420 kfree_data(imgp->ip_px_sfa,
5421 px_args.file_actions_size);
5422 kfree_data(imgp->ip_px_spa,
5423 px_args.port_actions_size);
5424 #if CONFIG_PERSONAS
5425 kfree_data(imgp->ip_px_persona,
5426 px_args.persona_info_size);
5427 #endif
5428 kfree_data(imgp->ip_px_pcred_info,
5429 px_args.posix_cred_info_size);
5430
5431 if (subsystem_root_path != NULL) {
5432 zfree(ZV_NAMEI, subsystem_root_path);
5433 }
5434 #if CONFIG_MACF
5435 struct ip_px_smpx_s *px_s = &imgp->ip_px_smpx;
5436 kfree_data(px_s->array, px_args.mac_extensions_size);
5437 kfree_data(px_s->data, (vm_size_t)px_s->datalen);
5438
5439 if (imgp->ip_execlabelp) {
5440 mac_cred_label_free(imgp->ip_execlabelp);
5441 imgp->ip_execlabelp = NULL;
5442 }
5443 if (imgp->ip_scriptlabelp) {
5444 mac_vnode_label_free(imgp->ip_scriptlabelp);
5445 imgp->ip_scriptlabelp = NULL;
5446 }
5447 if (imgp->ip_cs_error != OS_REASON_NULL) {
5448 os_reason_free(imgp->ip_cs_error);
5449 imgp->ip_cs_error = OS_REASON_NULL;
5450 }
5451 if (imgp->ip_inherited_shared_region_id != NULL) {
5452 kfree_data(imgp->ip_inherited_shared_region_id,
5453 strlen(imgp->ip_inherited_shared_region_id) + 1);
5454 imgp->ip_inherited_shared_region_id = NULL;
5455 }
5456 #endif
5457 }
5458
5459 #if CONFIG_DTRACE
5460 if (spawn_no_exec) {
5461 /*
5462 * In the original DTrace reference implementation,
5463 * posix_spawn() was a libc routine that just
5464 * did vfork(2) then exec(2). Thus the proc::: probes
5465 * are very fork/exec oriented. The details of this
5466 * in-kernel implementation of posix_spawn() is different
5467 * (while producing the same process-observable effects)
5468 * particularly w.r.t. errors, and which thread/process
5469 * is constructing what on behalf of whom.
5470 */
5471 if (error) {
5472 DTRACE_PROC1(spawn__failure, int, error);
5473 } else {
5474 DTRACE_PROC(spawn__success);
5475 /*
5476 * Some DTrace scripts, e.g. newproc.d in
5477 * /usr/bin, rely on the the 'exec-success'
5478 * probe being fired in the child after the
5479 * new process image has been constructed
5480 * in order to determine the associated pid.
5481 *
5482 * So, even though the parent built the image
5483 * here, for compatibility, mark the new thread
5484 * so 'exec-success' fires on it as it leaves
5485 * the kernel.
5486 */
5487 dtrace_thread_didexec(imgp->ip_new_thread);
5488 }
5489 } else {
5490 if (error) {
5491 DTRACE_PROC1(exec__failure, int, error);
5492 } else {
5493 dtrace_thread_didexec(imgp->ip_new_thread);
5494 }
5495 }
5496
5497 if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL) {
5498 (*dtrace_proc_waitfor_hook)(p);
5499 }
5500 #endif
5501
5502 #if CONFIG_AUDIT
5503 if (!error && AUDIT_ENABLED() && p) {
5504 /* Add the CDHash of the new process to the audit record */
5505 uint8_t *cdhash = cs_get_cdhash(p);
5506 if (cdhash) {
5507 AUDIT_ARG(data, cdhash, sizeof(uint8_t), CS_CDHASH_LEN);
5508 }
5509 }
5510 #endif
5511
5512 /* terminate the new task if exec failed */
5513 if (new_task != NULL && task_is_exec_copy(new_task)) {
5514 task_terminate_internal(new_task);
5515 }
5516
5517 if (exec_failure_reason && !spawn_no_exec) {
5518 psignal_with_reason(p, SIGKILL, exec_failure_reason);
5519 exec_failure_reason = NULL;
5520 }
5521
5522 /* Return to both the parent and the child? */
5523 if (imgp != NULL && spawn_no_exec) {
5524 /*
5525 * If the parent wants the pid, copy it out
5526 */
5527 if (error == 0 && pid != USER_ADDR_NULL) {
5528 _Static_assert(sizeof(pid_t) == 4, "posix_spawn() assumes a 32-bit pid_t");
5529 bool aligned = (pid & 3) == 0;
5530 if (aligned) {
5531 (void)copyout_atomic32(proc_getpid(p), pid);
5532 } else {
5533 (void)suword(pid, proc_getpid(p));
5534 }
5535 }
5536 retval[0] = error;
5537
5538 /*
5539 * If we had an error, perform an internal reap ; this is
5540 * entirely safe, as we have a real process backing us.
5541 */
5542 if (error) {
5543 proc_list_lock();
5544 p->p_listflag |= P_LIST_DEADPARENT;
5545 proc_list_unlock();
5546 proc_lock(p);
5547 /* make sure no one else has killed it off... */
5548 if (p->p_stat != SZOMB && p->exit_thread == NULL) {
5549 p->exit_thread = current_thread();
5550 p->p_posix_spawn_failed = true;
5551 proc_unlock(p);
5552 exit1(p, 1, (int *)NULL);
5553 } else {
5554 /* someone is doing it for us; just skip it */
5555 proc_unlock(p);
5556 }
5557 }
5558 }
5559
5560 /*
5561 * Do not terminate the current task, if proc_exec_switch_task did not
5562 * switch the tasks, terminating the current task without the switch would
5563 * result in loosing the SIGKILL status.
5564 */
5565 if (task_did_exec(old_task)) {
5566 /* Terminate the current task, since exec will start in new task */
5567 task_terminate_internal(old_task);
5568 }
5569
5570 /* Release the thread ref returned by cloneproc/fork1 */
5571 if (imgp != NULL && imgp->ip_new_thread) {
5572 /* clear the exec complete flag if there is an error before point of no-return */
5573 uint32_t clearwait_flags = TCRW_CLEAR_FINAL_WAIT;
5574 if (!spawn_no_exec && !exec_done && error != 0) {
5575 clearwait_flags |= TCRW_CLEAR_EXEC_COMPLETE;
5576 }
5577 /* wake up the new thread */
5578 task_clear_return_wait(get_threadtask(imgp->ip_new_thread), clearwait_flags);
5579 thread_deallocate(imgp->ip_new_thread);
5580 imgp->ip_new_thread = NULL;
5581 }
5582
5583 /* Release the ref returned by cloneproc/fork1 */
5584 if (new_task) {
5585 task_deallocate(new_task);
5586 new_task = NULL;
5587 }
5588
5589 if (should_release_proc_ref) {
5590 proc_rele(p);
5591 }
5592
5593 kfree_type(typeof(*__spawn_data), __spawn_data);
5594
5595 if (inherit != NULL) {
5596 ipc_importance_release(inherit);
5597 }
5598
5599 #if CONFIG_EXCLAVES
5600 if (task_conclave_id != NULL) {
5601 kfree_data(task_conclave_id, MAXCONCLAVENAME);
5602 }
5603 #endif
5604
5605 assert(spawn_no_exec || exec_failure_reason == NULL);
5606 return error;
5607 }
5608
5609 /*
5610 * proc_exec_switch_task
5611 *
5612 * Parameters: old_proc proc before exec
5613 * new_proc proc after exec
5614 * old_task task before exec
5615 * new_task task after exec
5616 * imgp image params
5617 * inherit resulting importance linkage
5618 *
5619 * Returns: proc.
5620 *
5621 * Note: The function will switch proc in pid hash from old proc to new proc.
5622 * The switch needs to happen after draining all proc refs and inside
5623 * a proc list lock. In the case of failure to switch the proc, which
5624 * might happen if the process received a SIGKILL or jetsam killed it,
5625 * it will make sure that the new tasks terminates. User proc ref returned
5626 * to caller.
5627 *
5628 * This function is called after point of no return, in the case
5629 * failure to switch, it will terminate the new task and swallow the
5630 * error and let the terminated process complete exec and die.
5631 */
5632 proc_t
proc_exec_switch_task(proc_t old_proc,proc_t new_proc,task_t old_task,task_t new_task,struct image_params * imgp,void ** inherit)5633 proc_exec_switch_task(proc_t old_proc, proc_t new_proc, task_t old_task, task_t new_task, struct image_params *imgp, void **inherit)
5634 {
5635 boolean_t task_active;
5636 boolean_t proc_active;
5637 boolean_t thread_active;
5638 boolean_t reparent_traced_child = FALSE;
5639 thread_t old_thread = current_thread();
5640 thread_t new_thread = imgp->ip_new_thread;
5641
5642 thread_set_exec_promotion(old_thread);
5643 old_proc = proc_refdrain_will_exec(old_proc);
5644
5645 new_proc = proc_refdrain_will_exec(new_proc);
5646 /* extra proc ref returned to the caller */
5647
5648 assert(get_threadtask(new_thread) == new_task);
5649 task_active = task_is_active(new_task);
5650 proc_active = !(old_proc->p_lflag & P_LEXIT);
5651
5652 /* Check if the current thread is not aborted due to SIGKILL */
5653 thread_active = thread_is_active(old_thread);
5654
5655 /*
5656 * Do not switch the proc if the new task or proc is already terminated
5657 * as a result of error in exec past point of no return
5658 */
5659 if (proc_active && task_active && thread_active) {
5660 uthread_t new_uthread = get_bsdthread_info(new_thread);
5661 uthread_t old_uthread = current_uthread();
5662
5663 /* Clear dispatchqueue and workloop ast offset */
5664 new_proc->p_dispatchqueue_offset = 0;
5665 new_proc->p_dispatchqueue_serialno_offset = 0;
5666 new_proc->p_dispatchqueue_label_offset = 0;
5667 new_proc->p_return_to_kernel_offset = 0;
5668 new_proc->p_pthread_wq_quantum_offset = 0;
5669
5670 /* If old_proc is session leader, change the leader to new proc */
5671 session_replace_leader(old_proc, new_proc);
5672
5673 proc_lock(old_proc);
5674
5675 /* Copy the signal state, dtrace state and set bsd ast on new thread */
5676 act_set_astbsd(new_thread);
5677 new_uthread->uu_siglist |= old_uthread->uu_siglist;
5678 new_uthread->uu_siglist |= old_proc->p_siglist;
5679 new_uthread->uu_sigwait = old_uthread->uu_sigwait;
5680 new_uthread->uu_sigmask = old_uthread->uu_sigmask;
5681 new_uthread->uu_oldmask = old_uthread->uu_oldmask;
5682 new_uthread->uu_exit_reason = old_uthread->uu_exit_reason;
5683 #if CONFIG_DTRACE
5684 new_uthread->t_dtrace_sig = old_uthread->t_dtrace_sig;
5685 new_uthread->t_dtrace_stop = old_uthread->t_dtrace_stop;
5686 new_uthread->t_dtrace_resumepid = old_uthread->t_dtrace_resumepid;
5687 assert(new_uthread->t_dtrace_scratch == NULL);
5688 new_uthread->t_dtrace_scratch = old_uthread->t_dtrace_scratch;
5689
5690 old_uthread->t_dtrace_sig = 0;
5691 old_uthread->t_dtrace_stop = 0;
5692 old_uthread->t_dtrace_resumepid = 0;
5693 old_uthread->t_dtrace_scratch = NULL;
5694 #endif
5695
5696 #if CONFIG_PROC_UDATA_STORAGE
5697 new_proc->p_user_data = old_proc->p_user_data;
5698 #endif /* CONFIG_PROC_UDATA_STORAGE */
5699
5700 /* Copy the resource accounting info */
5701 thread_copy_resource_info(new_thread, current_thread());
5702
5703 /* Clear the exit reason and signal state on old thread */
5704 old_uthread->uu_exit_reason = NULL;
5705 old_uthread->uu_siglist = 0;
5706
5707 task_set_did_exec_flag(old_task);
5708 task_clear_exec_copy_flag(new_task);
5709
5710 task_copy_fields_for_exec(new_task, old_task);
5711
5712 /*
5713 * Need to transfer pending watch port boosts to the new task
5714 * while still making sure that the old task remains in the
5715 * importance linkage. Create an importance linkage from old task
5716 * to new task, then switch the task importance base of old task
5717 * and new task. After the switch the port watch boost will be
5718 * boosting the new task and new task will be donating importance
5719 * to old task.
5720 */
5721 *inherit = ipc_importance_exec_switch_task(old_task, new_task);
5722
5723 /* Transfer parent's ptrace state to child */
5724 new_proc->p_lflag &= ~(P_LTRACED | P_LSIGEXC | P_LNOATTACH);
5725 new_proc->p_lflag |= (old_proc->p_lflag & (P_LTRACED | P_LSIGEXC | P_LNOATTACH));
5726 new_proc->p_oppid = old_proc->p_oppid;
5727
5728 if (old_proc->p_pptr != new_proc->p_pptr) {
5729 reparent_traced_child = TRUE;
5730 new_proc->p_lflag |= P_LTRACE_WAIT;
5731 }
5732
5733 proc_unlock(old_proc);
5734
5735 /* Update the list of proc knotes */
5736 proc_transfer_knotes(old_proc, new_proc);
5737
5738 /* Update the proc interval timers */
5739 proc_inherit_itimers(old_proc, new_proc);
5740
5741 proc_list_lock();
5742
5743 /* Insert the new proc in child list of parent proc */
5744 p_reparentallchildren(old_proc, new_proc);
5745
5746 /* Switch proc in pid hash */
5747 phash_replace_locked(old_proc, new_proc);
5748
5749 /* Transfer the shadow flag to old proc */
5750 os_atomic_andnot(&new_proc->p_refcount, P_REF_SHADOW, relaxed);
5751 os_atomic_or(&old_proc->p_refcount, P_REF_SHADOW, relaxed);
5752
5753 /* Change init proc if launchd exec */
5754 if (old_proc == initproc) {
5755 /* Take the ref on new proc after proc_refwake_did_exec */
5756 initproc = new_proc;
5757 /* Drop the proc ref on old proc */
5758 proc_rele(old_proc);
5759 }
5760
5761 proc_list_unlock();
5762 #if CONFIG_EXCLAVES
5763 if (task_inherit_conclave(old_task, new_task, imgp->ip_vp,
5764 (int64_t)imgp->ip_arch_offset) != KERN_SUCCESS) {
5765 task_terminate_internal(new_task);
5766 }
5767 #endif
5768 } else {
5769 task_terminate_internal(new_task);
5770 }
5771
5772 proc_refwake_did_exec(new_proc);
5773 proc_refwake_did_exec(old_proc);
5774
5775 /* Take a ref on initproc if it changed */
5776 if (new_proc == initproc) {
5777 initproc = proc_ref(new_proc, false);
5778 assert(initproc != PROC_NULL);
5779 }
5780
5781 thread_clear_exec_promotion(old_thread);
5782 proc_rele(old_proc);
5783
5784 if (reparent_traced_child) {
5785 proc_t pp = proc_parent(old_proc);
5786 assert(pp != PROC_NULL);
5787
5788 proc_reparentlocked(new_proc, pp, 1, 0);
5789 proc_rele(pp);
5790
5791 proc_lock(new_proc);
5792 new_proc->p_lflag &= ~P_LTRACE_WAIT;
5793 proc_unlock(new_proc);
5794 }
5795
5796 return new_proc;
5797 }
5798
5799 /*
5800 * execve
5801 *
5802 * Parameters: uap->fname File name to exec
5803 * uap->argp Argument list
5804 * uap->envp Environment list
5805 *
5806 * Returns: 0 Success
5807 * __mac_execve:EINVAL Invalid argument
5808 * __mac_execve:ENOTSUP Invalid argument
5809 * __mac_execve:EACCES Permission denied
5810 * __mac_execve:EINTR Interrupted function
5811 * __mac_execve:ENOMEM Not enough space
5812 * __mac_execve:EFAULT Bad address
5813 * __mac_execve:ENAMETOOLONG Filename too long
5814 * __mac_execve:ENOEXEC Executable file format error
5815 * __mac_execve:ETXTBSY Text file busy [misuse of error code]
5816 * __mac_execve:???
5817 *
5818 * TODO: Dynamic linker header address on stack is copied via suword()
5819 */
5820 /* ARGSUSED */
5821 int
execve(proc_t p,struct execve_args * uap,int32_t * retval)5822 execve(proc_t p, struct execve_args *uap, int32_t *retval)
5823 {
5824 struct __mac_execve_args muap;
5825 int err;
5826
5827 memoryshot(DBG_VM_EXECVE, DBG_FUNC_NONE);
5828
5829 muap.fname = uap->fname;
5830 muap.argp = uap->argp;
5831 muap.envp = uap->envp;
5832 muap.mac_p = USER_ADDR_NULL;
5833 err = __mac_execve(p, &muap, retval);
5834
5835 return err;
5836 }
5837
5838 /*
5839 * __mac_execve
5840 *
5841 * Parameters: uap->fname File name to exec
5842 * uap->argp Argument list
5843 * uap->envp Environment list
5844 * uap->mac_p MAC label supplied by caller
5845 *
5846 * Returns: 0 Success
5847 * EINVAL Invalid argument
5848 * ENOTSUP Not supported
5849 * ENOEXEC Executable file format error
5850 * exec_activate_image:EINVAL Invalid argument
5851 * exec_activate_image:EACCES Permission denied
5852 * exec_activate_image:EINTR Interrupted function
5853 * exec_activate_image:ENOMEM Not enough space
5854 * exec_activate_image:EFAULT Bad address
5855 * exec_activate_image:ENAMETOOLONG Filename too long
5856 * exec_activate_image:ENOEXEC Executable file format error
5857 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
5858 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
5859 * exec_activate_image:???
5860 * mac_execve_enter:???
5861 *
5862 * TODO: Dynamic linker header address on stack is copied via suword()
5863 */
5864 int
__mac_execve(proc_t p,struct __mac_execve_args * uap,int32_t * retval __unused)5865 __mac_execve(proc_t p, struct __mac_execve_args *uap, int32_t *retval __unused)
5866 {
5867 struct image_params *imgp = NULL;
5868 struct vnode_attr *vap = NULL;
5869 struct vnode_attr *origvap = NULL;
5870 int error;
5871 int is_64 = IS_64BIT_PROCESS(p);
5872 struct vfs_context context;
5873 struct uthread *uthread = NULL;
5874 task_t old_task = current_task();
5875 task_t new_task = NULL;
5876 boolean_t should_release_proc_ref = FALSE;
5877 boolean_t exec_done = FALSE;
5878 void *inherit = NULL;
5879 struct {
5880 struct image_params imgp;
5881 struct vnode_attr va;
5882 struct vnode_attr origva;
5883 } *__execve_data;
5884
5885 /* Allocate a big chunk for locals instead of using stack since these
5886 * structures are pretty big.
5887 */
5888 __execve_data = kalloc_type(typeof(*__execve_data), Z_WAITOK | Z_ZERO);
5889 if (__execve_data == NULL) {
5890 error = ENOMEM;
5891 goto exit_with_error;
5892 }
5893 imgp = &__execve_data->imgp;
5894 vap = &__execve_data->va;
5895 origvap = &__execve_data->origva;
5896
5897 /* Initialize the common data in the image_params structure */
5898 imgp->ip_user_fname = uap->fname;
5899 imgp->ip_user_argv = uap->argp;
5900 imgp->ip_user_envv = uap->envp;
5901 imgp->ip_vattr = vap;
5902 imgp->ip_origvattr = origvap;
5903 imgp->ip_vfs_context = &context;
5904 imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT_ADDR : IMGPF_NONE) | ((p->p_flag & P_DISABLE_ASLR) ? IMGPF_DISABLE_ASLR : IMGPF_NONE);
5905 imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
5906 imgp->ip_mac_return = 0;
5907 imgp->ip_cs_error = OS_REASON_NULL;
5908 imgp->ip_simulator_binary = IMGPF_SB_DEFAULT;
5909 imgp->ip_subsystem_root_path = NULL;
5910 uthread_set_exec_data(current_uthread(), imgp);
5911
5912 #if CONFIG_MACF
5913 if (uap->mac_p != USER_ADDR_NULL) {
5914 error = mac_execve_enter(uap->mac_p, imgp);
5915 if (error) {
5916 goto exit_with_error;
5917 }
5918 }
5919 #endif
5920 uthread = current_uthread();
5921 {
5922 imgp->ip_flags |= IMGPF_EXEC;
5923
5924 /* Adjust the user proc count */
5925 (void)chgproccnt(kauth_getruid(), 1);
5926 /*
5927 * For execve case, create a new proc, task and thread
5928 * but don't make the proc visible to userland. After
5929 * image activation, the new proc would take place of
5930 * the old proc in pid hash and other lists that make
5931 * the proc visible to the system.
5932 */
5933 imgp->ip_new_thread = cloneproc(old_task, NULL, p, CLONEPROC_EXEC);
5934 /* task and thread ref returned by cloneproc */
5935 if (imgp->ip_new_thread == NULL) {
5936 (void)chgproccnt(kauth_getruid(), -1);
5937 error = ENOMEM;
5938 goto exit_with_error;
5939 }
5940
5941 new_task = get_threadtask(imgp->ip_new_thread);
5942 }
5943
5944 #if HAS_MTE_EMULATION_SHIMS
5945 /*
5946 * ARM2ARM Rosetta doesn't carry over the configuration from the initial posix_spawn,
5947 * so we key the enablement of the runtime to whether inheritance is enabled or not
5948 * for the task. We will defer any MTE specific configuration to image activation.
5949 */
5950 if (task_has_sec_inherit(old_task) && task_has_sec(old_task)) {
5951 imgp->ip_flags |= (IMGPF_ROSETTA | IMGPF_ALT_ROSETTA);
5952 }
5953 #endif /* HAS_MTE_EMULATION_SHIMS */
5954
5955 p = (proc_t)get_bsdthreadtask_info(imgp->ip_new_thread);
5956
5957 context.vc_thread = imgp->ip_new_thread;
5958 context.vc_ucred = kauth_cred_proc_ref(p); /* XXX must NOT be kauth_cred_get() */
5959
5960 imgp->ip_subsystem_root_path = p->p_subsystem_root_path;
5961
5962 proc_transend(p, 0);
5963 proc_signalend(p, 0);
5964
5965 /*
5966 * Activate the image.
5967 * Warning: If activation failed after point of no return, it returns error
5968 * as 0 and pretends the call succeeded.
5969 */
5970 error = exec_activate_image(imgp);
5971 /* thread and task ref returned for vfexec case */
5972
5973 if (imgp->ip_new_thread != NULL) {
5974 /*
5975 * task reference might be returned by exec_activate_image
5976 * for vfexec.
5977 */
5978 new_task = get_threadtask(imgp->ip_new_thread);
5979 #if defined(HAS_APPLE_PAC)
5980 ml_task_set_disable_user_jop(new_task, imgp->ip_flags & IMGPF_NOJOP ? TRUE : FALSE);
5981 ml_thread_set_disable_user_jop(imgp->ip_new_thread, imgp->ip_flags & IMGPF_NOJOP ? TRUE : FALSE);
5982 #endif
5983 }
5984
5985 if (!error) {
5986 p = proc_exec_switch_task(current_proc(), p, old_task, new_task, imgp, &inherit);
5987 /* proc ref returned */
5988 should_release_proc_ref = TRUE;
5989 }
5990
5991 kauth_cred_unref(&context.vc_ucred);
5992
5993 if (!error) {
5994 exec_done = TRUE;
5995 assert(imgp->ip_new_thread != NULL);
5996
5997 exec_resettextvp(p, imgp);
5998
5999 vm_map_setup(get_task_map(new_task), new_task);
6000
6001 exec_setup_platform_restrictions(new_task);
6002
6003 /*
6004 * Set starting EXC_GUARD behavior for task now that platform
6005 * and platform restrictions bits are set.
6006 */
6007 task_set_exc_guard_default(new_task,
6008 proc_best_name(p),
6009 strlen(proc_best_name(p)),
6010 proc_is_simulated(p),
6011 proc_platform(p),
6012 proc_sdk(p));
6013
6014 /*
6015 * Between proc_exec_switch_task and ipc_task_enable, there is a
6016 * window where proc_find will return the new proc, but task_for_pid
6017 * and similar functions will return an error as the task ipc is not
6018 * enabled yet. Configure the task control port during this window
6019 * before other process have access to this task port.
6020 *
6021 * Must enable after resettextvp so that task port policies are not evaluated
6022 * until the csblob in the textvp is accurately reflected.
6023 */
6024 task_set_ctrl_port_default(new_task, imgp->ip_new_thread);
6025
6026 /*
6027 * Enable new task IPC access if exec_activate_image() returned an
6028 * active task. (Checks active bit in ipc_task_enable() under lock).
6029 * Similarly, this must happen after resettextvp.
6030 */
6031 ipc_task_enable(new_task);
6032 error = process_signature(p, imgp);
6033 }
6034
6035
6036 #if defined(HAS_APPLE_PAC)
6037 if (imgp->ip_new_thread && !error) {
6038 ml_task_set_jop_pid_from_shared_region(new_task, imgp->ip_flags & IMGPF_NOJOP);
6039 ml_thread_set_jop_pid(imgp->ip_new_thread, new_task);
6040 }
6041 #endif /* defined(HAS_APPLE_PAC) */
6042
6043 /* flag exec has occurred, notify only if it has not failed due to FP Key error */
6044 if (exec_done && ((p->p_lflag & P_LTERM_DECRYPTFAIL) == 0)) {
6045 proc_knote(p, NOTE_EXEC);
6046 }
6047
6048 if (imgp->ip_vp != NULLVP) {
6049 vnode_put(imgp->ip_vp);
6050 }
6051 if (imgp->ip_scriptvp != NULLVP) {
6052 vnode_put(imgp->ip_scriptvp);
6053 }
6054 if (imgp->ip_free_map) {
6055 /* Free the map after dropping iocount on vnode to avoid deadlock */
6056 vm_map_deallocate(imgp->ip_free_map);
6057 }
6058 if (imgp->ip_strings) {
6059 execargs_free(imgp);
6060 }
6061 #if CONFIG_MACF
6062 if (imgp->ip_execlabelp) {
6063 mac_cred_label_free(imgp->ip_execlabelp);
6064 imgp->ip_execlabelp = NULL;
6065 }
6066 if (imgp->ip_scriptlabelp) {
6067 mac_vnode_label_free(imgp->ip_scriptlabelp);
6068 imgp->ip_scriptlabelp = NULL;
6069 }
6070 #endif
6071 if (imgp->ip_cs_error != OS_REASON_NULL) {
6072 os_reason_free(imgp->ip_cs_error);
6073 imgp->ip_cs_error = OS_REASON_NULL;
6074 }
6075
6076 if (!error) {
6077 /*
6078 * We need to initialize the bank context behind the protection of
6079 * the proc_trans lock to prevent a race with exit. We can't do this during
6080 * exec_activate_image because task_bank_init checks entitlements that
6081 * aren't loaded until subsequent calls (including exec_resettextvp).
6082 */
6083 error = proc_transstart(p, 0, 0);
6084 }
6085
6086 if (!error) {
6087 task_bank_init(new_task);
6088 proc_transend(p, 0);
6089
6090 // Don't inherit crash behavior across exec, but preserve crash behavior from bootargs
6091 p->p_crash_behavior = 0;
6092 p->p_crash_behavior_deadline = 0;
6093 #if (DEVELOPMENT || DEBUG)
6094 set_crash_behavior_from_bootarg(p);
6095 #endif
6096
6097 #if __arm64__
6098 proc_footprint_entitlement_hacks(p, new_task);
6099 #endif /* __arm64__ */
6100
6101 #if XNU_TARGET_OS_OSX
6102 if (IOTaskHasEntitlement(new_task, SINGLE_JIT_ENTITLEMENT)) {
6103 vm_map_single_jit(get_task_map(new_task));
6104 }
6105 #endif /* XNU_TARGET_OS_OSX */
6106
6107 /* Sever any extant thread affinity */
6108 thread_affinity_exec(current_thread());
6109
6110 /* Inherit task role from old task to new task for exec */
6111 proc_inherit_task_role(new_task, old_task);
6112
6113 thread_t main_thread = imgp->ip_new_thread;
6114
6115 task_set_main_thread_qos(new_task, main_thread);
6116
6117 #if __has_feature(ptrauth_calls)
6118 task_set_pac_exception_fatal_flag(new_task);
6119 #endif /* __has_feature(ptrauth_calls) */
6120 task_set_jit_flags(new_task);
6121
6122 #if CONFIG_ARCADE
6123 /*
6124 * Check to see if we need to trigger an arcade upcall AST now
6125 * that the vnode has been reset on the task.
6126 */
6127 arcade_prepare(new_task, imgp->ip_new_thread);
6128 #endif /* CONFIG_ARCADE */
6129
6130 proc_apply_jit_and_vm_policies(imgp, p, new_task);
6131
6132 if (vm_darkwake_mode == TRUE) {
6133 /*
6134 * This process is being launched when the system
6135 * is in darkwake. So mark it specially. This will
6136 * cause all its pages to be entered in the background Q.
6137 */
6138 task_set_darkwake_mode(new_task, vm_darkwake_mode);
6139 }
6140
6141 #if CONFIG_DTRACE
6142 dtrace_thread_didexec(imgp->ip_new_thread);
6143
6144 if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL) {
6145 (*dtrace_proc_waitfor_hook)(p);
6146 }
6147 #endif
6148
6149 #if CONFIG_AUDIT
6150 if (!error && AUDIT_ENABLED() && p) {
6151 /* Add the CDHash of the new process to the audit record */
6152 uint8_t *cdhash = cs_get_cdhash(p);
6153 if (cdhash) {
6154 AUDIT_ARG(data, cdhash, sizeof(uint8_t), CS_CDHASH_LEN);
6155 }
6156 }
6157 #endif
6158 } else {
6159 DTRACE_PROC1(exec__failure, int, error);
6160 }
6161
6162 exit_with_error:
6163
6164 /* terminate the new task it if exec failed */
6165 if (new_task != NULL && task_is_exec_copy(new_task)) {
6166 task_terminate_internal(new_task);
6167 }
6168
6169 if (imgp != NULL) {
6170 /* Clear the initial wait on the thread transferring watchports */
6171 if (imgp->ip_new_thread) {
6172 task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_INITIAL_WAIT);
6173 }
6174
6175 /* Transfer the watchport boost to new task */
6176 if (!error) {
6177 task_transfer_turnstile_watchports(old_task,
6178 new_task, imgp->ip_new_thread);
6179 }
6180 /*
6181 * Do not terminate the current task, if proc_exec_switch_task did not
6182 * switch the tasks, terminating the current task without the switch would
6183 * result in loosing the SIGKILL status.
6184 */
6185 if (task_did_exec(old_task)) {
6186 /* Terminate the current task, since exec will start in new task */
6187 task_terminate_internal(old_task);
6188 }
6189
6190 /* Release the thread ref returned by cloneproc */
6191 if (imgp->ip_new_thread) {
6192 /* clear the exec complete flag if there is an error before point of no-return */
6193 uint32_t clearwait_flags = TCRW_CLEAR_FINAL_WAIT;
6194 if (!exec_done && error != 0) {
6195 clearwait_flags |= TCRW_CLEAR_EXEC_COMPLETE;
6196 }
6197 /* wake up the new exec thread */
6198 task_clear_return_wait(get_threadtask(imgp->ip_new_thread), clearwait_flags);
6199 thread_deallocate(imgp->ip_new_thread);
6200 imgp->ip_new_thread = NULL;
6201 }
6202 }
6203
6204 /* Release the ref returned by fork_create_child */
6205 if (new_task) {
6206 task_deallocate(new_task);
6207 new_task = NULL;
6208 }
6209
6210 if (should_release_proc_ref) {
6211 proc_rele(p);
6212 }
6213
6214 uthread_set_exec_data(current_uthread(), NULL);
6215 kfree_type(typeof(*__execve_data), __execve_data);
6216
6217 if (inherit != NULL) {
6218 ipc_importance_release(inherit);
6219 }
6220
6221 return error;
6222 }
6223
6224
6225 /*
6226 * copyinptr
6227 *
6228 * Description: Copy a pointer in from user space to a user_addr_t in kernel
6229 * space, based on 32/64 bitness of the user space
6230 *
6231 * Parameters: froma User space address
6232 * toptr Address of kernel space user_addr_t
6233 * ptr_size 4/8, based on 'froma' address space
6234 *
6235 * Returns: 0 Success
6236 * EFAULT Bad 'froma'
6237 *
6238 * Implicit returns:
6239 * *ptr_size Modified
6240 */
6241 static int
copyinptr(user_addr_t froma,user_addr_t * toptr,int ptr_size)6242 copyinptr(user_addr_t froma, user_addr_t *toptr, int ptr_size)
6243 {
6244 int error;
6245
6246 if (ptr_size == 4) {
6247 /* 64 bit value containing 32 bit address */
6248 unsigned int i = 0;
6249
6250 error = copyin(froma, &i, 4);
6251 *toptr = CAST_USER_ADDR_T(i); /* SAFE */
6252 } else {
6253 error = copyin(froma, toptr, 8);
6254 }
6255 return error;
6256 }
6257
6258
6259 /*
6260 * copyoutptr
6261 *
6262 * Description: Copy a pointer out from a user_addr_t in kernel space to
6263 * user space, based on 32/64 bitness of the user space
6264 *
6265 * Parameters: ua User space address to copy to
6266 * ptr Address of kernel space user_addr_t
6267 * ptr_size 4/8, based on 'ua' address space
6268 *
6269 * Returns: 0 Success
6270 * EFAULT Bad 'ua'
6271 *
6272 */
6273 static int
copyoutptr(user_addr_t ua,user_addr_t ptr,int ptr_size)6274 copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size)
6275 {
6276 int error;
6277
6278 if (ptr_size == 4) {
6279 /* 64 bit value containing 32 bit address */
6280 unsigned int i = CAST_DOWN_EXPLICIT(unsigned int, ua); /* SAFE */
6281
6282 error = copyout(&i, ptr, 4);
6283 } else {
6284 error = copyout(&ua, ptr, 8);
6285 }
6286 return error;
6287 }
6288
6289
6290 /*
6291 * exec_copyout_strings
6292 *
6293 * Copy out the strings segment to user space. The strings segment is put
6294 * on a preinitialized stack frame.
6295 *
6296 * Parameters: struct image_params * the image parameter block
6297 * int * a pointer to the stack offset variable
6298 *
6299 * Returns: 0 Success
6300 * !0 Faiure: errno
6301 *
6302 * Implicit returns:
6303 * (*stackp) The stack offset, modified
6304 *
6305 * Note: The strings segment layout is backward, from the beginning
6306 * of the top of the stack to consume the minimal amount of
6307 * space possible; the returned stack pointer points to the
6308 * end of the area consumed (stacks grow downward).
6309 *
6310 * argc is an int; arg[i] are pointers; env[i] are pointers;
6311 * the 0's are (void *)NULL's
6312 *
6313 * The stack frame layout is:
6314 *
6315 * +-------------+ <- p->user_stack
6316 * | 16b |
6317 * +-------------+
6318 * | STRING AREA |
6319 * | : |
6320 * | : |
6321 * | : |
6322 * +- -- -- -- --+
6323 * | PATH AREA |
6324 * +-------------+
6325 * | 0 |
6326 * +-------------+
6327 * | applev[n] |
6328 * +-------------+
6329 * :
6330 * :
6331 * +-------------+
6332 * | applev[1] |
6333 * +-------------+
6334 * | exec_path / |
6335 * | applev[0] |
6336 * +-------------+
6337 * | 0 |
6338 * +-------------+
6339 * | env[n] |
6340 * +-------------+
6341 * :
6342 * :
6343 * +-------------+
6344 * | env[0] |
6345 * +-------------+
6346 * | 0 |
6347 * +-------------+
6348 * | arg[argc-1] |
6349 * +-------------+
6350 * :
6351 * :
6352 * +-------------+
6353 * | arg[0] |
6354 * +-------------+
6355 * | argc |
6356 * sp-> +-------------+
6357 *
6358 * Although technically a part of the STRING AREA, we treat the PATH AREA as
6359 * a separate entity. This allows us to align the beginning of the PATH AREA
6360 * to a pointer boundary so that the exec_path, env[i], and argv[i] pointers
6361 * which preceed it on the stack are properly aligned.
6362 */
6363 __attribute__((noinline))
6364 static int
exec_copyout_strings(struct image_params * imgp,user_addr_t * stackp)6365 exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp)
6366 {
6367 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
6368 int ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4;
6369 int ptr_area_size;
6370 void *ptr_buffer_start, *ptr_buffer;
6371 size_t string_size;
6372
6373 user_addr_t string_area; /* *argv[], *env[] */
6374 user_addr_t ptr_area; /* argv[], env[], applev[] */
6375 user_addr_t argc_area; /* argc */
6376 user_addr_t stack;
6377 int error;
6378
6379 unsigned i;
6380 struct copyout_desc {
6381 char *start_string;
6382 int count;
6383 #if CONFIG_DTRACE
6384 user_addr_t *dtrace_cookie;
6385 #endif
6386 boolean_t null_term;
6387 } descriptors[] = {
6388 {
6389 .start_string = imgp->ip_startargv,
6390 .count = imgp->ip_argc,
6391 #if CONFIG_DTRACE
6392 .dtrace_cookie = &p->p_dtrace_argv,
6393 #endif
6394 .null_term = TRUE
6395 },
6396 {
6397 .start_string = imgp->ip_endargv,
6398 .count = imgp->ip_envc,
6399 #if CONFIG_DTRACE
6400 .dtrace_cookie = &p->p_dtrace_envp,
6401 #endif
6402 .null_term = TRUE
6403 },
6404 {
6405 .start_string = imgp->ip_strings,
6406 .count = 1,
6407 #if CONFIG_DTRACE
6408 .dtrace_cookie = NULL,
6409 #endif
6410 .null_term = FALSE
6411 },
6412 {
6413 .start_string = imgp->ip_endenvv,
6414 .count = imgp->ip_applec - 1, /* exec_path handled above */
6415 #if CONFIG_DTRACE
6416 .dtrace_cookie = NULL,
6417 #endif
6418 .null_term = TRUE
6419 }
6420 };
6421
6422 stack = *stackp;
6423
6424 /*
6425 * All previous contributors to the string area
6426 * should have aligned their sub-area
6427 */
6428 if (imgp->ip_strspace % ptr_size != 0) {
6429 error = EINVAL;
6430 goto bad;
6431 }
6432
6433 /* Grow the stack down for the strings we've been building up */
6434 string_size = imgp->ip_strendp - imgp->ip_strings;
6435 stack -= string_size;
6436 string_area = stack;
6437
6438 /*
6439 * Need room for one pointer for each string, plus
6440 * one for the NULLs terminating the argv, envv, and apple areas.
6441 */
6442 ptr_area_size = (imgp->ip_argc + imgp->ip_envc + imgp->ip_applec + 3) * ptr_size;
6443 stack -= ptr_area_size;
6444 ptr_area = stack;
6445
6446 /* We'll construct all the pointer arrays in our string buffer,
6447 * which we already know is aligned properly, and ip_argspace
6448 * was used to verify we have enough space.
6449 */
6450 ptr_buffer_start = ptr_buffer = (void *)imgp->ip_strendp;
6451
6452 /*
6453 * Need room for pointer-aligned argc slot.
6454 */
6455 stack -= ptr_size;
6456 argc_area = stack;
6457
6458 /*
6459 * Record the size of the arguments area so that sysctl_procargs()
6460 * can return the argument area without having to parse the arguments.
6461 */
6462 proc_lock(p);
6463 p->p_argc = imgp->ip_argc;
6464 p->p_argslen = (int)(*stackp - string_area);
6465 proc_unlock(p);
6466
6467 /* Return the initial stack address: the location of argc */
6468 *stackp = stack;
6469
6470 /*
6471 * Copy out the entire strings area.
6472 */
6473 error = copyout(imgp->ip_strings, string_area,
6474 string_size);
6475 if (error) {
6476 goto bad;
6477 }
6478
6479 for (i = 0; i < sizeof(descriptors) / sizeof(descriptors[0]); i++) {
6480 char *cur_string = descriptors[i].start_string;
6481 int j;
6482
6483 #if CONFIG_DTRACE
6484 if (descriptors[i].dtrace_cookie) {
6485 proc_lock(p);
6486 *descriptors[i].dtrace_cookie = ptr_area + ((uintptr_t)ptr_buffer - (uintptr_t)ptr_buffer_start); /* dtrace convenience */
6487 proc_unlock(p);
6488 }
6489 #endif /* CONFIG_DTRACE */
6490
6491 /*
6492 * For each segment (argv, envv, applev), copy as many pointers as requested
6493 * to our pointer buffer.
6494 */
6495 for (j = 0; j < descriptors[i].count; j++) {
6496 user_addr_t cur_address = string_area + (cur_string - imgp->ip_strings);
6497
6498 /* Copy out the pointer to the current string. Alignment has been verified */
6499 if (ptr_size == 8) {
6500 *(uint64_t *)ptr_buffer = (uint64_t)cur_address;
6501 } else {
6502 *(uint32_t *)ptr_buffer = (uint32_t)cur_address;
6503 }
6504
6505 ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size);
6506 cur_string += strlen(cur_string) + 1; /* Only a NUL between strings in the same area */
6507 }
6508
6509 if (descriptors[i].null_term) {
6510 if (ptr_size == 8) {
6511 *(uint64_t *)ptr_buffer = 0ULL;
6512 } else {
6513 *(uint32_t *)ptr_buffer = 0;
6514 }
6515
6516 ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size);
6517 }
6518 }
6519
6520 /*
6521 * Copy out all our pointer arrays in bulk.
6522 */
6523 error = copyout(ptr_buffer_start, ptr_area,
6524 ptr_area_size);
6525 if (error) {
6526 goto bad;
6527 }
6528
6529 /* argc (int32, stored in a ptr_size area) */
6530 error = copyoutptr((user_addr_t)imgp->ip_argc, argc_area, ptr_size);
6531 if (error) {
6532 goto bad;
6533 }
6534
6535 bad:
6536 return error;
6537 }
6538
6539
6540 /*
6541 * exec_extract_strings
6542 *
6543 * Copy arguments and environment from user space into work area; we may
6544 * have already copied some early arguments into the work area, and if
6545 * so, any arguments opied in are appended to those already there.
6546 * This function is the primary manipulator of ip_argspace, since
6547 * these are the arguments the client of execve(2) knows about. After
6548 * each argv[]/envv[] string is copied, we charge the string length
6549 * and argv[]/envv[] pointer slot to ip_argspace, so that we can
6550 * full preflight the arg list size.
6551 *
6552 * Parameters: struct image_params * the image parameter block
6553 *
6554 * Returns: 0 Success
6555 * !0 Failure: errno
6556 *
6557 * Implicit returns;
6558 * (imgp->ip_argc) Count of arguments, updated
6559 * (imgp->ip_envc) Count of environment strings, updated
6560 * (imgp->ip_argspace) Count of remaining of NCARGS
6561 * (imgp->ip_interp_buffer) Interpreter and args (mutated in place)
6562 *
6563 *
6564 * Note: The argument and environment vectors are user space pointers
6565 * to arrays of user space pointers.
6566 */
6567 __attribute__((noinline))
6568 static int
exec_extract_strings(struct image_params * imgp)6569 exec_extract_strings(struct image_params *imgp)
6570 {
6571 int error = 0;
6572 int ptr_size = (imgp->ip_flags & IMGPF_WAS_64BIT_ADDR) ? 8 : 4;
6573 int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4;
6574 user_addr_t argv = imgp->ip_user_argv;
6575 user_addr_t envv = imgp->ip_user_envv;
6576
6577 /*
6578 * Adjust space reserved for the path name by however much padding it
6579 * needs. Doing this here since we didn't know if this would be a 32-
6580 * or 64-bit process back in exec_save_path.
6581 */
6582 while (imgp->ip_strspace % new_ptr_size != 0) {
6583 *imgp->ip_strendp++ = '\0';
6584 imgp->ip_strspace--;
6585 /* imgp->ip_argspace--; not counted towards exec args total */
6586 }
6587
6588 /*
6589 * From now on, we start attributing string space to ip_argspace
6590 */
6591 imgp->ip_startargv = imgp->ip_strendp;
6592 imgp->ip_argc = 0;
6593
6594 if ((imgp->ip_flags & IMGPF_INTERPRET) != 0) {
6595 user_addr_t arg;
6596 char *argstart, *ch;
6597
6598 /* First, the arguments in the "#!" string are tokenized and extracted. */
6599 argstart = imgp->ip_interp_buffer;
6600 while (argstart) {
6601 ch = argstart;
6602 while (*ch && !IS_WHITESPACE(*ch)) {
6603 ch++;
6604 }
6605
6606 if (*ch == '\0') {
6607 /* last argument, no need to NUL-terminate */
6608 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE);
6609 argstart = NULL;
6610 } else {
6611 /* NUL-terminate */
6612 *ch = '\0';
6613 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE);
6614
6615 /*
6616 * Find the next string. We know spaces at the end of the string have already
6617 * been stripped.
6618 */
6619 argstart = ch + 1;
6620 while (IS_WHITESPACE(*argstart)) {
6621 argstart++;
6622 }
6623 }
6624
6625 /* Error-check, regardless of whether this is the last interpreter arg or not */
6626 if (error) {
6627 goto bad;
6628 }
6629 if (imgp->ip_argspace < new_ptr_size) {
6630 error = E2BIG;
6631 goto bad;
6632 }
6633 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
6634 imgp->ip_argc++;
6635 }
6636
6637 if (argv != 0LL) {
6638 /*
6639 * If we are running an interpreter, replace the av[0] that was
6640 * passed to execve() with the path name that was
6641 * passed to execve() for interpreters which do not use the PATH
6642 * to locate their script arguments.
6643 */
6644 error = copyinptr(argv, &arg, ptr_size);
6645 if (error) {
6646 goto bad;
6647 }
6648 if (arg != 0LL) {
6649 argv += ptr_size; /* consume without using */
6650 }
6651 }
6652
6653 if (imgp->ip_interp_sugid_fd != -1) {
6654 char temp[19]; /* "/dev/fd/" + 10 digits + NUL */
6655 snprintf(temp, sizeof(temp), "/dev/fd/%d", imgp->ip_interp_sugid_fd);
6656 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(temp), UIO_SYSSPACE, TRUE);
6657 } else {
6658 error = exec_add_user_string(imgp, imgp->ip_user_fname, imgp->ip_seg, TRUE);
6659 }
6660
6661 if (error) {
6662 goto bad;
6663 }
6664 if (imgp->ip_argspace < new_ptr_size) {
6665 error = E2BIG;
6666 goto bad;
6667 }
6668 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
6669 imgp->ip_argc++;
6670 }
6671
6672 while (argv != 0LL) {
6673 user_addr_t arg;
6674
6675 error = copyinptr(argv, &arg, ptr_size);
6676 if (error) {
6677 goto bad;
6678 }
6679
6680 if (arg == 0LL) {
6681 break;
6682 }
6683
6684 argv += ptr_size;
6685
6686 /*
6687 * av[n...] = arg[n]
6688 */
6689 error = exec_add_user_string(imgp, arg, imgp->ip_seg, TRUE);
6690 if (error) {
6691 goto bad;
6692 }
6693 if (imgp->ip_argspace < new_ptr_size) {
6694 error = E2BIG;
6695 goto bad;
6696 }
6697 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
6698 imgp->ip_argc++;
6699 }
6700
6701 /* Save space for argv[] NULL terminator */
6702 if (imgp->ip_argspace < new_ptr_size) {
6703 error = E2BIG;
6704 goto bad;
6705 }
6706 imgp->ip_argspace -= new_ptr_size;
6707
6708 /* Note where the args ends and env begins. */
6709 imgp->ip_endargv = imgp->ip_strendp;
6710 imgp->ip_envc = 0;
6711
6712 /* Now, get the environment */
6713 while (envv != 0LL) {
6714 user_addr_t env;
6715
6716 error = copyinptr(envv, &env, ptr_size);
6717 if (error) {
6718 goto bad;
6719 }
6720
6721 envv += ptr_size;
6722 if (env == 0LL) {
6723 break;
6724 }
6725 /*
6726 * av[n...] = env[n]
6727 */
6728 error = exec_add_user_string(imgp, env, imgp->ip_seg, TRUE);
6729 if (error) {
6730 goto bad;
6731 }
6732 if (imgp->ip_argspace < new_ptr_size) {
6733 error = E2BIG;
6734 goto bad;
6735 }
6736 imgp->ip_argspace -= new_ptr_size; /* to hold envv[] entry */
6737 imgp->ip_envc++;
6738 }
6739
6740 /* Save space for envv[] NULL terminator */
6741 if (imgp->ip_argspace < new_ptr_size) {
6742 error = E2BIG;
6743 goto bad;
6744 }
6745 imgp->ip_argspace -= new_ptr_size;
6746
6747 /* Align the tail of the combined argv+envv area */
6748 while (imgp->ip_strspace % new_ptr_size != 0) {
6749 if (imgp->ip_argspace < 1) {
6750 error = E2BIG;
6751 goto bad;
6752 }
6753 *imgp->ip_strendp++ = '\0';
6754 imgp->ip_strspace--;
6755 imgp->ip_argspace--;
6756 }
6757
6758 /* Note where the envv ends and applev begins. */
6759 imgp->ip_endenvv = imgp->ip_strendp;
6760
6761 /*
6762 * From now on, we are no longer charging argument
6763 * space to ip_argspace.
6764 */
6765
6766 bad:
6767 return error;
6768 }
6769
6770 /*
6771 * Libc has an 8-element array set up for stack guard values. It only fills
6772 * in one of those entries, and both gcc and llvm seem to use only a single
6773 * 8-byte guard. Until somebody needs more than an 8-byte guard value, don't
6774 * do the work to construct them.
6775 */
6776 #define GUARD_VALUES 1
6777 #define GUARD_KEY "stack_guard="
6778
6779 /*
6780 * System malloc needs some entropy when it is initialized.
6781 */
6782 #define ENTROPY_VALUES 2
6783 #define ENTROPY_KEY "malloc_entropy="
6784
6785 /*
6786 * libplatform needs a random pointer-obfuscation value when it is initialized.
6787 */
6788 #define PTR_MUNGE_VALUES 1
6789 #define PTR_MUNGE_KEY "ptr_munge="
6790
6791 /*
6792 * System malloc engages nanozone for UIAPP.
6793 */
6794 #define NANO_ENGAGE_KEY "MallocNanoZone=1"
6795
6796 /*
6797 * Used to pass experiment flags up to libmalloc.
6798 */
6799 #define LIBMALLOC_EXPERIMENT_FACTORS_KEY "MallocExperiment="
6800
6801 /*
6802 * Passes information about hardened heap/"hardened runtime" entitlements to libsystem/libmalloc
6803 */
6804 #define HARDENED_RUNTIME_KEY "HardenedRuntime="
6805
6806 #define PFZ_KEY "pfz="
6807 extern user32_addr_t commpage_text32_location;
6808 extern user64_addr_t commpage_text64_location;
6809
6810 extern uuid_string_t bootsessionuuid_string;
6811 static TUNABLE(uint32_t, exe_boothash_salt, "exe_boothash_salt", 0);
6812
6813 __startup_func
6814 static void
exe_boothash_salt_generate(void)6815 exe_boothash_salt_generate(void)
6816 {
6817 if (!PE_parse_boot_argn("exe_boothash_salt", NULL, 0)) {
6818 read_random(&exe_boothash_salt, sizeof(exe_boothash_salt));
6819 }
6820 }
6821 STARTUP(EARLY_BOOT, STARTUP_RANK_MIDDLE, exe_boothash_salt_generate);
6822
6823
6824 #define MAIN_STACK_VALUES 4
6825 #define MAIN_STACK_KEY "main_stack="
6826
6827 #define FSID_KEY "executable_file="
6828 #define DYLD_FSID_KEY "dyld_file="
6829 #define CDHASH_KEY "executable_cdhash="
6830 #define DYLD_FLAGS_KEY "dyld_flags="
6831 #define SUBSYSTEM_ROOT_PATH_KEY "subsystem_root_path="
6832 #define APP_BOOT_SESSION_KEY "executable_boothash="
6833 #if __has_feature(ptrauth_calls)
6834 #define PTRAUTH_DISABLED_FLAG "ptrauth_disabled=1"
6835 #define DYLD_ARM64E_ABI_KEY "arm64e_abi="
6836 #endif /* __has_feature(ptrauth_calls) */
6837 #define MAIN_TH_PORT_KEY "th_port="
6838
6839 #define FSID_MAX_STRING "0x1234567890abcdef,0x1234567890abcdef"
6840
6841 #define HEX_STR_LEN 18 // 64-bit hex value "0x0123456701234567"
6842 #define HEX_STR_LEN32 10 // 32-bit hex value "0x01234567"
6843
6844 #if XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES
6845 #define VM_FORCE_4K_PAGES_KEY "vm_force_4k_pages=1"
6846 #endif /* XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES */
6847
6848 static int
exec_add_entropy_key(struct image_params * imgp,const char * key,int values,boolean_t embedNUL)6849 exec_add_entropy_key(struct image_params *imgp,
6850 const char *key,
6851 int values,
6852 boolean_t embedNUL)
6853 {
6854 const int limit = 8;
6855 uint64_t entropy[limit];
6856 char str[strlen(key) + (HEX_STR_LEN + 1) * limit + 1];
6857 if (values > limit) {
6858 values = limit;
6859 }
6860
6861 read_random(entropy, sizeof(entropy[0]) * values);
6862
6863 if (embedNUL) {
6864 entropy[0] &= ~(0xffull << 8);
6865 }
6866
6867 int len = scnprintf(str, sizeof(str), "%s0x%llx", key, entropy[0]);
6868 size_t remaining = sizeof(str) - len;
6869 for (int i = 1; i < values && remaining > 0; ++i) {
6870 size_t start = sizeof(str) - remaining;
6871 len = scnprintf(&str[start], remaining, ",0x%llx", entropy[i]);
6872 remaining -= len;
6873 }
6874
6875 return exec_add_user_string(imgp, CAST_USER_ADDR_T(str), UIO_SYSSPACE, FALSE);
6876 }
6877
6878 /*
6879 * Build up the contents of the apple[] string vector
6880 */
6881 #if (DEVELOPMENT || DEBUG)
6882 extern uint64_t dyld_flags;
6883 #endif
6884
6885 #if __has_feature(ptrauth_calls)
6886 static inline bool
is_arm64e_running_as_arm64(const struct image_params * imgp)6887 is_arm64e_running_as_arm64(const struct image_params *imgp)
6888 {
6889 return (imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E &&
6890 (imgp->ip_flags & IMGPF_NOJOP);
6891 }
6892 #endif /* __has_feature(ptrauth_calls) */
6893
6894 _Atomic uint64_t libmalloc_experiment_factors = 0;
6895
6896 static int
exec_add_apple_strings(struct image_params * imgp,const load_result_t * load_result,task_t task)6897 exec_add_apple_strings(struct image_params *imgp,
6898 const load_result_t *load_result, task_t task)
6899 {
6900 int error;
6901 int img_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4;
6902 thread_t new_thread;
6903 ipc_port_t sright;
6904 uint64_t local_experiment_factors = 0;
6905
6906 /* exec_save_path stored the first string */
6907 imgp->ip_applec = 1;
6908
6909 /* adding the pfz string */
6910 {
6911 char pfz_string[strlen(PFZ_KEY) + HEX_STR_LEN + 1];
6912
6913 if (img_ptr_size == 8) {
6914 __assert_only size_t ret = snprintf(pfz_string, sizeof(pfz_string), PFZ_KEY "0x%llx", commpage_text64_location);
6915 assert(ret < sizeof(pfz_string));
6916 } else {
6917 snprintf(pfz_string, sizeof(pfz_string), PFZ_KEY "0x%x", commpage_text32_location);
6918 }
6919 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(pfz_string), UIO_SYSSPACE, FALSE);
6920 if (error) {
6921 printf("Failed to add the pfz string with error %d\n", error);
6922 goto bad;
6923 }
6924 imgp->ip_applec++;
6925 }
6926
6927 /* adding the NANO_ENGAGE_KEY key */
6928 if (imgp->ip_px_sa) {
6929 struct _posix_spawnattr* psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
6930 int proc_flags = psa->psa_flags;
6931
6932 if ((proc_flags & _POSIX_SPAWN_NANO_ALLOCATOR) == _POSIX_SPAWN_NANO_ALLOCATOR) {
6933 const char *nano_string = NANO_ENGAGE_KEY;
6934 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(nano_string), UIO_SYSSPACE, FALSE);
6935 if (error) {
6936 goto bad;
6937 }
6938 imgp->ip_applec++;
6939 }
6940 }
6941
6942 /*
6943 * Supply libc with a collection of random values to use when
6944 * implementing -fstack-protector.
6945 *
6946 * (The first random string always contains an embedded NUL so that
6947 * __stack_chk_guard also protects against C string vulnerabilities)
6948 */
6949 error = exec_add_entropy_key(imgp, GUARD_KEY, GUARD_VALUES, TRUE);
6950 if (error) {
6951 goto bad;
6952 }
6953 imgp->ip_applec++;
6954
6955 /*
6956 * Supply libc with entropy for system malloc.
6957 */
6958 error = exec_add_entropy_key(imgp, ENTROPY_KEY, ENTROPY_VALUES, FALSE);
6959 if (error) {
6960 goto bad;
6961 }
6962 imgp->ip_applec++;
6963
6964 /*
6965 * Supply libpthread & libplatform with a random value to use for pointer
6966 * obfuscation.
6967 */
6968 error = exec_add_entropy_key(imgp, PTR_MUNGE_KEY, PTR_MUNGE_VALUES, FALSE);
6969 if (error) {
6970 goto bad;
6971 }
6972 imgp->ip_applec++;
6973
6974 /*
6975 * Add MAIN_STACK_KEY: Supplies the address and size of the main thread's
6976 * stack if it was allocated by the kernel.
6977 *
6978 * The guard page is not included in this stack size as libpthread
6979 * expects to add it back in after receiving this value.
6980 */
6981 if (load_result->unixproc) {
6982 char stack_string[strlen(MAIN_STACK_KEY) + (HEX_STR_LEN + 1) * MAIN_STACK_VALUES + 1];
6983 snprintf(stack_string, sizeof(stack_string),
6984 MAIN_STACK_KEY "0x%llx,0x%llx,0x%llx,0x%llx",
6985 (uint64_t)load_result->user_stack,
6986 (uint64_t)load_result->user_stack_size,
6987 (uint64_t)load_result->user_stack_alloc,
6988 (uint64_t)load_result->user_stack_alloc_size);
6989 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(stack_string), UIO_SYSSPACE, FALSE);
6990 if (error) {
6991 goto bad;
6992 }
6993 imgp->ip_applec++;
6994 }
6995
6996 if (imgp->ip_vattr) {
6997 uint64_t fsid = vnode_get_va_fsid(imgp->ip_vattr);
6998 uint64_t fsobjid = imgp->ip_vattr->va_fileid;
6999
7000 char fsid_string[strlen(FSID_KEY) + strlen(FSID_MAX_STRING) + 1];
7001 snprintf(fsid_string, sizeof(fsid_string),
7002 FSID_KEY "0x%llx,0x%llx", fsid, fsobjid);
7003 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(fsid_string), UIO_SYSSPACE, FALSE);
7004 if (error) {
7005 goto bad;
7006 }
7007 imgp->ip_applec++;
7008 }
7009
7010 if (imgp->ip_dyld_fsid || imgp->ip_dyld_fsobjid) {
7011 char fsid_string[strlen(DYLD_FSID_KEY) + strlen(FSID_MAX_STRING) + 1];
7012 snprintf(fsid_string, sizeof(fsid_string),
7013 DYLD_FSID_KEY "0x%llx,0x%llx", imgp->ip_dyld_fsid, imgp->ip_dyld_fsobjid);
7014 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(fsid_string), UIO_SYSSPACE, FALSE);
7015 if (error) {
7016 goto bad;
7017 }
7018 imgp->ip_applec++;
7019 }
7020
7021 uint8_t cdhash[SHA1_RESULTLEN];
7022 int cdhash_errror = ubc_cs_getcdhash(imgp->ip_vp, imgp->ip_arch_offset, cdhash, NULL);
7023 if (cdhash_errror == 0) {
7024 char hash_string[strlen(CDHASH_KEY) + 2 * SHA1_RESULTLEN + 1];
7025 strncpy(hash_string, CDHASH_KEY, sizeof(hash_string));
7026 char *p = hash_string + sizeof(CDHASH_KEY) - 1;
7027 for (int i = 0; i < SHA1_RESULTLEN; i++) {
7028 snprintf(p, 3, "%02x", (int) cdhash[i]);
7029 p += 2;
7030 }
7031 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(hash_string), UIO_SYSSPACE, FALSE);
7032 if (error) {
7033 goto bad;
7034 }
7035 imgp->ip_applec++;
7036
7037 /* hash together cd-hash and boot-session-uuid */
7038 uint8_t sha_digest[SHA256_DIGEST_LENGTH];
7039 SHA256_CTX sha_ctx;
7040 SHA256_Init(&sha_ctx);
7041 SHA256_Update(&sha_ctx, &exe_boothash_salt, sizeof(exe_boothash_salt));
7042 SHA256_Update(&sha_ctx, bootsessionuuid_string, sizeof(bootsessionuuid_string));
7043 SHA256_Update(&sha_ctx, cdhash, sizeof(cdhash));
7044 SHA256_Final(sha_digest, &sha_ctx);
7045 char app_boot_string[strlen(APP_BOOT_SESSION_KEY) + 2 * SHA1_RESULTLEN + 1];
7046 strncpy(app_boot_string, APP_BOOT_SESSION_KEY, sizeof(app_boot_string));
7047 char *s = app_boot_string + sizeof(APP_BOOT_SESSION_KEY) - 1;
7048 for (int i = 0; i < SHA1_RESULTLEN; i++) {
7049 snprintf(s, 3, "%02x", (int) sha_digest[i]);
7050 s += 2;
7051 }
7052 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(app_boot_string), UIO_SYSSPACE, FALSE);
7053 if (error) {
7054 goto bad;
7055 }
7056 imgp->ip_applec++;
7057 }
7058 #if (DEVELOPMENT || DEBUG)
7059 if (dyld_flags) {
7060 char dyld_flags_string[strlen(DYLD_FLAGS_KEY) + HEX_STR_LEN + 1];
7061 snprintf(dyld_flags_string, sizeof(dyld_flags_string), DYLD_FLAGS_KEY "0x%llx", dyld_flags);
7062 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(dyld_flags_string), UIO_SYSSPACE, FALSE);
7063 if (error) {
7064 goto bad;
7065 }
7066 imgp->ip_applec++;
7067 }
7068 #endif
7069 if (imgp->ip_subsystem_root_path) {
7070 size_t buffer_len = MAXPATHLEN + strlen(SUBSYSTEM_ROOT_PATH_KEY);
7071 char subsystem_root_path_string[buffer_len];
7072 int required_len = snprintf(subsystem_root_path_string, buffer_len, SUBSYSTEM_ROOT_PATH_KEY "%s", imgp->ip_subsystem_root_path);
7073
7074 if (((size_t)required_len >= buffer_len) || (required_len < 0)) {
7075 error = ENAMETOOLONG;
7076 goto bad;
7077 }
7078
7079 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(subsystem_root_path_string), UIO_SYSSPACE, FALSE);
7080 if (error) {
7081 goto bad;
7082 }
7083
7084 imgp->ip_applec++;
7085 }
7086 #if __has_feature(ptrauth_calls)
7087 if (is_arm64e_running_as_arm64(imgp)) {
7088 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(PTRAUTH_DISABLED_FLAG), UIO_SYSSPACE, FALSE);
7089 if (error) {
7090 goto bad;
7091 }
7092
7093 imgp->ip_applec++;
7094 }
7095 #endif /* __has_feature(ptrauth_calls) */
7096
7097
7098 #if __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX)
7099 {
7100 char dyld_abi_string[strlen(DYLD_ARM64E_ABI_KEY) + 8];
7101 strlcpy(dyld_abi_string, DYLD_ARM64E_ABI_KEY, sizeof(dyld_abi_string));
7102 bool allowAll = bootarg_arm64e_preview_abi;
7103 strlcat(dyld_abi_string, (allowAll ? "all" : "os"), sizeof(dyld_abi_string));
7104 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(dyld_abi_string), UIO_SYSSPACE, FALSE);
7105 if (error) {
7106 goto bad;
7107 }
7108
7109 imgp->ip_applec++;
7110 }
7111 #endif
7112 /*
7113 * Add main thread mach port name
7114 * +1 uref on main thread port, this ref will be extracted by libpthread in __pthread_init
7115 * and consumed in _bsdthread_terminate. Leaking the main thread port name if not linked
7116 * against libpthread.
7117 */
7118 if ((new_thread = imgp->ip_new_thread) != THREAD_NULL) {
7119 thread_reference(new_thread);
7120 sright = convert_thread_to_port_immovable(new_thread);
7121 task_t new_task = get_threadtask(new_thread);
7122 mach_port_name_t name = ipc_port_copyout_send_pinned(sright, get_task_ipcspace(new_task));
7123 char port_name_hex_str[strlen(MAIN_TH_PORT_KEY) + HEX_STR_LEN32 + 1];
7124 snprintf(port_name_hex_str, sizeof(port_name_hex_str), MAIN_TH_PORT_KEY "0x%x", name);
7125
7126 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(port_name_hex_str), UIO_SYSSPACE, FALSE);
7127 if (error) {
7128 goto bad;
7129 }
7130 imgp->ip_applec++;
7131 }
7132
7133 #if XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES
7134 if (imgp->ip_px_sa != NULL) {
7135 struct _posix_spawnattr* psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
7136 if (psa->psa_flags & _POSIX_SPAWN_FORCE_4K_PAGES) {
7137 const char *vm_force_4k_string = VM_FORCE_4K_PAGES_KEY;
7138 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(vm_force_4k_string), UIO_SYSSPACE, FALSE);
7139 if (error) {
7140 goto bad;
7141 }
7142 imgp->ip_applec++;
7143 }
7144 }
7145 #endif /* XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES */
7146
7147 /* adding the libmalloc experiment string */
7148 local_experiment_factors = os_atomic_load_wide(&libmalloc_experiment_factors, relaxed);
7149 if (__improbable(local_experiment_factors != 0)) {
7150 char libmalloc_experiment_factors_string[strlen(LIBMALLOC_EXPERIMENT_FACTORS_KEY) + HEX_STR_LEN + 1];
7151
7152 snprintf(
7153 libmalloc_experiment_factors_string,
7154 sizeof(libmalloc_experiment_factors_string),
7155 LIBMALLOC_EXPERIMENT_FACTORS_KEY "0x%llx",
7156 local_experiment_factors);
7157 error = exec_add_user_string(
7158 imgp,
7159 CAST_USER_ADDR_T(libmalloc_experiment_factors_string),
7160 UIO_SYSSPACE,
7161 FALSE);
7162 if (error) {
7163 printf("Failed to add the libmalloc experiment factors string with error %d\n", error);
7164 goto bad;
7165 }
7166 imgp->ip_applec++;
7167 }
7168
7169 /*
7170 * Push down the task security configuration. To reduce confusion when userland parses the information
7171 * still push an empty security configuration if nothing is active.
7172 */
7173 {
7174 #define SECURITY_CONFIG_KEY "security_config="
7175 char security_config_str[strlen(SECURITY_CONFIG_KEY) + HEX_STR_LEN + 1];
7176
7177 snprintf(security_config_str, sizeof(security_config_str),
7178 SECURITY_CONFIG_KEY "0x%x", task_get_security_config(task));
7179
7180 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(security_config_str), UIO_SYSSPACE, FALSE);
7181 if (error) {
7182 printf("Failed to add the security config string with error %d\n", error);
7183 goto bad;
7184 }
7185 imgp->ip_applec++;
7186 }
7187
7188
7189 #if HAS_MTE || HAS_MTE_EMULATION_SHIMS
7190 if (task_has_sec(task)) {
7191 const char *sec_transition_shims = "has_sec_transition=1";
7192 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(sec_transition_shims), UIO_SYSSPACE, FALSE);
7193 if (error) {
7194 printf("Failed to add security translation shims notification\n");
7195 goto bad;
7196 }
7197
7198 imgp->ip_applec++;
7199
7200 /* Push down MTE-specific configuration options that allocators may be interested into. */
7201 #define SEC_TRANSITION_POLICY_KEY "sec_transition_policy="
7202
7203 char sec_transition_policy[strlen(SEC_TRANSITION_POLICY_KEY) + HEX_STR_LEN + 1];
7204
7205 snprintf(sec_transition_policy, sizeof(sec_transition_policy),
7206 SEC_TRANSITION_POLICY_KEY "0x%x", task_get_sec_policy(task));
7207
7208 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(sec_transition_policy), UIO_SYSSPACE, FALSE);
7209 if (error) {
7210 printf("Failed to add the security transition policy string with error %d\n", error);
7211 goto bad;
7212 }
7213 imgp->ip_applec++;
7214 }
7215 #endif /* HAS_MTE || HAS_MTE_EMULATION_SHIMS */
7216
7217
7218 if (load_result->hardened_browser) {
7219 const size_t HR_STRING_SIZE = sizeof(HARDENED_RUNTIME_KEY) + HR_FLAGS_NUM_NIBBLES + 2 + 1;
7220 char hardened_runtime[HR_STRING_SIZE];
7221 snprintf(hardened_runtime, HR_STRING_SIZE, HARDENED_RUNTIME_KEY"0x%x", load_result->hardened_browser);
7222 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(hardened_runtime), UIO_SYSSPACE, FALSE);
7223 if (error) {
7224 printf("Failed to add hardened runtime flag with error %d\n", error);
7225 goto bad;
7226 }
7227 imgp->ip_applec++;
7228 }
7229 /* Align the tail of the combined applev area */
7230 while (imgp->ip_strspace % img_ptr_size != 0) {
7231 *imgp->ip_strendp++ = '\0';
7232 imgp->ip_strspace--;
7233 }
7234
7235 bad:
7236 return error;
7237 }
7238
7239 /*
7240 * exec_check_permissions
7241 *
7242 * Description: Verify that the file that is being attempted to be executed
7243 * is in fact allowed to be executed based on it POSIX file
7244 * permissions and other access control criteria
7245 *
7246 * Parameters: struct image_params * the image parameter block
7247 *
7248 * Returns: 0 Success
7249 * EACCES Permission denied
7250 * ENOEXEC Executable file format error
7251 * ETXTBSY Text file busy [misuse of error code]
7252 * vnode_getattr:???
7253 * vnode_authorize:???
7254 */
7255 static int
exec_check_permissions(struct image_params * imgp)7256 exec_check_permissions(struct image_params *imgp)
7257 {
7258 struct vnode *vp = imgp->ip_vp;
7259 struct vnode_attr *vap = imgp->ip_vattr;
7260 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
7261 int error;
7262 kauth_action_t action;
7263
7264 /* Only allow execution of regular files */
7265 if (!vnode_isreg(vp)) {
7266 return EACCES;
7267 }
7268
7269 /* Get the file attributes that we will be using here and elsewhere */
7270 VATTR_INIT(vap);
7271 VATTR_WANTED(vap, va_uid);
7272 VATTR_WANTED(vap, va_gid);
7273 VATTR_WANTED(vap, va_mode);
7274 VATTR_WANTED(vap, va_fsid);
7275 VATTR_WANTED(vap, va_fsid64);
7276 VATTR_WANTED(vap, va_fileid);
7277 VATTR_WANTED(vap, va_data_size);
7278 if ((error = vnode_getattr(vp, vap, imgp->ip_vfs_context)) != 0) {
7279 return error;
7280 }
7281
7282 /*
7283 * Ensure that at least one execute bit is on - otherwise root
7284 * will always succeed, and we don't want to happen unless the
7285 * file really is executable.
7286 */
7287 if (!vfs_authopaque(vnode_mount(vp)) && ((vap->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0)) {
7288 return EACCES;
7289 }
7290
7291 /* Disallow zero length files */
7292 if (vap->va_data_size == 0) {
7293 return ENOEXEC;
7294 }
7295
7296 imgp->ip_arch_offset = (user_size_t)0;
7297 #if __LP64__
7298 imgp->ip_arch_size = vap->va_data_size;
7299 #else
7300 if (vap->va_data_size > UINT32_MAX) {
7301 return ENOEXEC;
7302 }
7303 imgp->ip_arch_size = (user_size_t)vap->va_data_size;
7304 #endif
7305
7306 /* Disable setuid-ness for traced programs or if MNT_NOSUID */
7307 if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_lflag & P_LTRACED)) {
7308 vap->va_mode &= ~(VSUID | VSGID);
7309 }
7310
7311 /*
7312 * Disable _POSIX_SPAWN_ALLOW_DATA_EXEC and _POSIX_SPAWN_DISABLE_ASLR
7313 * flags for setuid/setgid binaries.
7314 */
7315 if (vap->va_mode & (VSUID | VSGID)) {
7316 imgp->ip_flags &= ~(IMGPF_ALLOW_DATA_EXEC | IMGPF_DISABLE_ASLR);
7317 }
7318
7319 #if CONFIG_MACF
7320 error = mac_vnode_check_exec(imgp->ip_vfs_context, vp, imgp);
7321 if (error) {
7322 return error;
7323 }
7324 #endif
7325
7326 /* Check for execute permission */
7327 action = KAUTH_VNODE_EXECUTE;
7328 /* Traced images must also be readable */
7329 if (p->p_lflag & P_LTRACED) {
7330 action |= KAUTH_VNODE_READ_DATA;
7331 }
7332 if ((error = vnode_authorize(vp, NULL, action, imgp->ip_vfs_context)) != 0) {
7333 return error;
7334 }
7335
7336 #if 0
7337 /* Don't let it run if anyone had it open for writing */
7338 vnode_lock(vp);
7339 if (vp->v_writecount) {
7340 panic("going to return ETXTBSY %x", vp);
7341 vnode_unlock(vp);
7342 return ETXTBSY;
7343 }
7344 vnode_unlock(vp);
7345 #endif
7346
7347 /* XXX May want to indicate to underlying FS that vnode is open */
7348
7349 return error;
7350 }
7351
7352
7353 /*
7354 * exec_handle_sugid
7355 *
7356 * Initially clear the P_SUGID in the process flags; if an SUGID process is
7357 * exec'ing a non-SUGID image, then this is the point of no return.
7358 *
7359 * If the image being activated is SUGID, then replace the credential with a
7360 * copy, disable tracing (unless the tracing process is root), reset the
7361 * mach task port to revoke it, set the P_SUGID bit,
7362 *
7363 * If the saved user and group ID will be changing, then make sure it happens
7364 * to a new credential, rather than a shared one.
7365 *
7366 * Set the security token (this is probably obsolete, given that the token
7367 * should not technically be separate from the credential itself).
7368 *
7369 * Parameters: struct image_params * the image parameter block
7370 *
7371 * Returns: void No failure indication
7372 *
7373 * Implicit returns:
7374 * <process credential> Potentially modified/replaced
7375 * <task port> Potentially revoked
7376 * <process flags> P_SUGID bit potentially modified
7377 * <security token> Potentially modified
7378 */
7379 __attribute__((noinline))
7380 static int
exec_handle_sugid(struct image_params * imgp)7381 exec_handle_sugid(struct image_params *imgp)
7382 {
7383 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
7384 kauth_cred_t cred = vfs_context_ucred(imgp->ip_vfs_context);
7385 int i;
7386 int leave_sugid_clear = 0;
7387 int mac_reset_ipc = 0;
7388 int error = 0;
7389 #if CONFIG_MACF
7390 int mac_transition, disjoint_cred = 0;
7391 int label_update_return = 0;
7392
7393 /*
7394 * Determine whether a call to update the MAC label will result in the
7395 * credential changing.
7396 *
7397 * Note: MAC policies which do not actually end up modifying
7398 * the label subsequently are strongly encouraged to
7399 * return 0 for this check, since a non-zero answer will
7400 * slow down the exec fast path for normal binaries.
7401 */
7402 mac_transition = mac_cred_check_label_update_execve(
7403 imgp->ip_vfs_context,
7404 imgp->ip_vp,
7405 imgp->ip_arch_offset,
7406 imgp->ip_scriptvp,
7407 imgp->ip_scriptlabelp,
7408 imgp->ip_execlabelp,
7409 p,
7410 &imgp->ip_px_smpx);
7411 #endif
7412
7413 OSBitAndAtomic(~((uint32_t)P_SUGID), &p->p_flag);
7414
7415 /*
7416 * Order of the following is important; group checks must go last,
7417 * as we use the success of the 'ismember' check combined with the
7418 * failure of the explicit match to indicate that we will be setting
7419 * the egid of the process even though the new process did not
7420 * require VSUID/VSGID bits in order for it to set the new group as
7421 * its egid.
7422 *
7423 * Note: Technically, by this we are implying a call to
7424 * setegid() in the new process, rather than implying
7425 * it used its VSGID bit to set the effective group,
7426 * even though there is no code in that process to make
7427 * such a call.
7428 */
7429 if (((imgp->ip_origvattr->va_mode & VSUID) != 0 &&
7430 kauth_cred_getuid(cred) != imgp->ip_origvattr->va_uid) ||
7431 ((imgp->ip_origvattr->va_mode & VSGID) != 0 &&
7432 ((kauth_cred_ismember_gid(cred, imgp->ip_origvattr->va_gid, &leave_sugid_clear) || !leave_sugid_clear) ||
7433 (kauth_cred_getgid(cred) != imgp->ip_origvattr->va_gid)))) {
7434 #if CONFIG_MACF
7435 /* label for MAC transition and neither VSUID nor VSGID */
7436 handle_mac_transition:
7437 #endif
7438
7439 #if CONFIG_SETUID
7440 /*
7441 * Replace the credential with a copy of itself if euid or
7442 * egid change.
7443 *
7444 * Note: setuid binaries will automatically opt out of
7445 * group resolver participation as a side effect
7446 * of this operation. This is an intentional
7447 * part of the security model, which requires a
7448 * participating credential be established by
7449 * escalating privilege, setting up all other
7450 * aspects of the credential including whether
7451 * or not to participate in external group
7452 * membership resolution, then dropping their
7453 * effective privilege to that of the desired
7454 * final credential state.
7455 *
7456 * Modifications to p_ucred must be guarded using the
7457 * proc's ucred lock. This prevents others from accessing
7458 * a garbage credential.
7459 */
7460
7461 if (imgp->ip_origvattr->va_mode & VSUID) {
7462 kauth_cred_proc_update(p, PROC_SETTOKEN_NONE,
7463 ^bool (kauth_cred_t parent __unused, kauth_cred_t model) {
7464 return kauth_cred_model_setresuid(model,
7465 KAUTH_UID_NONE,
7466 imgp->ip_origvattr->va_uid,
7467 imgp->ip_origvattr->va_uid,
7468 KAUTH_UID_NONE);
7469 });
7470 }
7471
7472 if (imgp->ip_origvattr->va_mode & VSGID) {
7473 kauth_cred_proc_update(p, PROC_SETTOKEN_NONE,
7474 ^bool (kauth_cred_t parent __unused, kauth_cred_t model) {
7475 return kauth_cred_model_setresgid(model,
7476 KAUTH_GID_NONE,
7477 imgp->ip_origvattr->va_gid,
7478 imgp->ip_origvattr->va_gid);
7479 });
7480 }
7481 #endif /* CONFIG_SETUID */
7482
7483 #if CONFIG_MACF
7484 /*
7485 * If a policy has indicated that it will transition the label,
7486 * before making the call into the MAC policies, get a new
7487 * duplicate credential, so they can modify it without
7488 * modifying any others sharing it.
7489 */
7490 if (mac_transition) {
7491 /*
7492 * This hook may generate upcalls that require
7493 * importance donation from the kernel.
7494 * (23925818)
7495 */
7496 thread_t thread = current_thread();
7497 thread_enable_send_importance(thread, TRUE);
7498 kauth_proc_label_update_execve(p,
7499 imgp->ip_vfs_context,
7500 imgp->ip_vp,
7501 imgp->ip_arch_offset,
7502 imgp->ip_scriptvp,
7503 imgp->ip_scriptlabelp,
7504 imgp->ip_execlabelp,
7505 &imgp->ip_csflags,
7506 &imgp->ip_px_smpx,
7507 &disjoint_cred, /* will be non zero if disjoint */
7508 &label_update_return);
7509 thread_enable_send_importance(thread, FALSE);
7510
7511 if (disjoint_cred) {
7512 /*
7513 * If updating the MAC label resulted in a
7514 * disjoint credential, flag that we need to
7515 * set the P_SUGID bit. This protects
7516 * against debuggers being attached by an
7517 * insufficiently privileged process onto the
7518 * result of a transition to a more privileged
7519 * credential.
7520 */
7521 leave_sugid_clear = 0;
7522 }
7523
7524 imgp->ip_mac_return = label_update_return;
7525 }
7526
7527 mac_reset_ipc = mac_proc_check_inherit_ipc_ports(p, p->p_textvp, p->p_textoff, imgp->ip_vp, imgp->ip_arch_offset, imgp->ip_scriptvp);
7528
7529 #endif /* CONFIG_MACF */
7530
7531 /*
7532 * If 'leave_sugid_clear' is non-zero, then we passed the
7533 * VSUID and MACF checks, and successfully determined that
7534 * the previous cred was a member of the VSGID group, but
7535 * that it was not the default at the time of the execve,
7536 * and that the post-labelling credential was not disjoint.
7537 * So we don't set the P_SUGID or reset mach ports and fds
7538 * on the basis of simply running this code.
7539 */
7540 if (mac_reset_ipc || !leave_sugid_clear) {
7541 /*
7542 * Have mach reset the task and thread ports.
7543 * We don't want anyone who had the ports before
7544 * a setuid exec to be able to access/control the
7545 * task/thread after.
7546 */
7547 ipc_task_reset((imgp->ip_new_thread != NULL) ?
7548 get_threadtask(imgp->ip_new_thread) : proc_task(p));
7549 ipc_thread_reset((imgp->ip_new_thread != NULL) ?
7550 imgp->ip_new_thread : current_thread());
7551 }
7552
7553 if (!leave_sugid_clear) {
7554 /*
7555 * Flag the process as setuid.
7556 */
7557 OSBitOrAtomic(P_SUGID, &p->p_flag);
7558
7559 /*
7560 * Radar 2261856; setuid security hole fix
7561 * XXX For setuid processes, attempt to ensure that
7562 * stdin, stdout, and stderr are already allocated.
7563 * We do not want userland to accidentally allocate
7564 * descriptors in this range which has implied meaning
7565 * to libc.
7566 */
7567 for (i = 0; i < 3; i++) {
7568 if (fp_get_noref_locked(p, i) != NULL) {
7569 continue;
7570 }
7571
7572 /*
7573 * Do the kernel equivalent of
7574 *
7575 * if i == 0
7576 * (void) open("/dev/null", O_RDONLY);
7577 * else
7578 * (void) open("/dev/null", O_WRONLY);
7579 */
7580
7581 struct fileproc *fp;
7582 int indx;
7583 int flag;
7584 struct nameidata *ndp = NULL;
7585
7586 if (i == 0) {
7587 flag = FREAD;
7588 } else {
7589 flag = FWRITE;
7590 }
7591
7592 if ((error = falloc_exec(p, imgp->ip_vfs_context,
7593 &fp, &indx)) != 0) {
7594 continue;
7595 }
7596
7597 ndp = kalloc_type(struct nameidata,
7598 Z_WAITOK | Z_ZERO | Z_NOFAIL);
7599
7600 NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW, UIO_SYSSPACE,
7601 CAST_USER_ADDR_T("/dev/null"),
7602 imgp->ip_vfs_context);
7603
7604 if ((error = vn_open(ndp, flag, 0)) != 0) {
7605 fp_free(p, indx, fp);
7606 kfree_type(struct nameidata, ndp);
7607 break;
7608 }
7609
7610 struct fileglob *fg = fp->fp_glob;
7611
7612 fg->fg_flag = flag;
7613 fg->fg_ops = &vnops;
7614 fp_set_data(fp, ndp->ni_vp);
7615
7616 vnode_put(ndp->ni_vp);
7617
7618 proc_fdlock(p);
7619 procfdtbl_releasefd(p, indx, NULL);
7620 fp_drop(p, indx, fp, 1);
7621 proc_fdunlock(p);
7622
7623 kfree_type(struct nameidata, ndp);
7624 }
7625 }
7626 }
7627 #if CONFIG_MACF
7628 else {
7629 /*
7630 * We are here because we were told that the MAC label will
7631 * be transitioned, and the binary is not VSUID or VSGID; to
7632 * deal with this case, we could either duplicate a lot of
7633 * code, or we can indicate we want to default the P_SUGID
7634 * bit clear and jump back up.
7635 */
7636 if (mac_transition) {
7637 leave_sugid_clear = 1;
7638 goto handle_mac_transition;
7639 }
7640 }
7641
7642 #endif /* CONFIG_MACF */
7643
7644 /* Update the process' identity version and set the security token.
7645 * Also, ensure we always see a modified identity version (rdar://129775819).
7646 */
7647 int previous_pid_version = proc_get_ro(p)->p_idversion;
7648 int new_pid_version;
7649 do {
7650 new_pid_version = OSIncrementAtomic(&nextpidversion);
7651 } while (new_pid_version == previous_pid_version);
7652 proc_setpidversion(p, new_pid_version);
7653 task_set_uniqueid(proc_task(p));
7654
7655 /*
7656 * Implement the semantic where the effective user and group become
7657 * the saved user and group in exec'ed programs.
7658 */
7659 kauth_cred_proc_update(p, PROC_SETTOKEN_ALWAYS,
7660 ^bool (kauth_cred_t parent __unused, kauth_cred_t model) {
7661 posix_cred_t pcred = posix_cred_get(model);
7662
7663 if (pcred->cr_svuid == pcred->cr_uid &&
7664 pcred->cr_svgid == pcred->cr_gid) {
7665 return false;
7666 }
7667
7668 pcred->cr_svuid = pcred->cr_uid;
7669 pcred->cr_svgid = pcred->cr_gid;
7670 return true;
7671 });
7672
7673 return error;
7674 }
7675
7676
7677 /*
7678 * create_unix_stack
7679 *
7680 * Description: Set the user stack address for the process to the provided
7681 * address. If a custom stack was not set as a result of the
7682 * load process (i.e. as specified by the image file for the
7683 * executable), then allocate the stack in the provided map and
7684 * set up appropriate guard pages for enforcing administrative
7685 * limits on stack growth, if they end up being needed.
7686 *
7687 * Parameters: p Process to set stack on
7688 * load_result Information from mach-o load commands
7689 * map Address map in which to allocate the new stack
7690 *
7691 * Returns: KERN_SUCCESS Stack successfully created
7692 * !KERN_SUCCESS Mach failure code
7693 */
7694 __attribute__((noinline))
7695 static kern_return_t
create_unix_stack(vm_map_t map,load_result_t * load_result,proc_t p)7696 create_unix_stack(vm_map_t map, load_result_t* load_result,
7697 proc_t p)
7698 {
7699 mach_vm_size_t size, prot_size;
7700 mach_vm_offset_t addr, prot_addr;
7701 kern_return_t kr;
7702
7703 mach_vm_address_t user_stack = load_result->user_stack;
7704
7705 proc_lock(p);
7706 p->user_stack = (uintptr_t)user_stack;
7707 if (load_result->custom_stack) {
7708 p->p_lflag |= P_LCUSTOM_STACK;
7709 }
7710 proc_unlock(p);
7711 if (vm_map_page_shift(map) < (int)PAGE_SHIFT) {
7712 DEBUG4K_LOAD("map %p user_stack 0x%llx custom %d user_stack_alloc_size 0x%llx\n", map, user_stack, load_result->custom_stack, load_result->user_stack_alloc_size);
7713 }
7714
7715 if (load_result->user_stack_alloc_size > 0) {
7716 /*
7717 * Allocate enough space for the maximum stack size we
7718 * will ever authorize and an extra page to act as
7719 * a guard page for stack overflows. For default stacks,
7720 * vm_initial_limit_stack takes care of the extra guard page.
7721 * Otherwise we must allocate it ourselves.
7722 */
7723 if (mach_vm_round_page_overflow(load_result->user_stack_alloc_size, &size)) {
7724 return KERN_INVALID_ARGUMENT;
7725 }
7726 addr = vm_map_trunc_page(load_result->user_stack - size,
7727 vm_map_page_mask(map));
7728 kr = mach_vm_allocate_kernel(map, &addr, size,
7729 VM_MAP_KERNEL_FLAGS_FIXED(.vm_tag = VM_MEMORY_STACK));
7730 if (kr != KERN_SUCCESS) {
7731 // Can't allocate at default location, try anywhere
7732 addr = 0;
7733 kr = mach_vm_allocate_kernel(map, &addr, size,
7734 VM_MAP_KERNEL_FLAGS_ANYWHERE(.vm_tag = VM_MEMORY_STACK));
7735 if (kr != KERN_SUCCESS) {
7736 return kr;
7737 }
7738
7739 user_stack = addr + size;
7740 load_result->user_stack = (user_addr_t)user_stack;
7741
7742 proc_lock(p);
7743 p->user_stack = (uintptr_t)user_stack;
7744 proc_unlock(p);
7745 }
7746
7747 load_result->user_stack_alloc = (user_addr_t)addr;
7748
7749 /*
7750 * And prevent access to what's above the current stack
7751 * size limit for this process.
7752 */
7753 if (load_result->user_stack_size == 0) {
7754 load_result->user_stack_size = proc_limitgetcur(p, RLIMIT_STACK);
7755 prot_size = vm_map_trunc_page(size - load_result->user_stack_size, vm_map_page_mask(map));
7756 } else {
7757 prot_size = PAGE_SIZE;
7758 }
7759
7760 prot_addr = addr;
7761 kr = mach_vm_protect(map,
7762 prot_addr,
7763 prot_size,
7764 FALSE,
7765 VM_PROT_NONE);
7766 if (kr != KERN_SUCCESS) {
7767 (void)mach_vm_deallocate(map, addr, size);
7768 return kr;
7769 }
7770 }
7771
7772 return KERN_SUCCESS;
7773 }
7774
7775 #include <sys/reboot.h>
7776
7777 /*
7778 * load_init_program_at_path
7779 *
7780 * Description: Load the "init" program; in most cases, this will be "launchd"
7781 *
7782 * Parameters: p Process to call execve() to create
7783 * the "init" program
7784 * scratch_addr Page in p, scratch space
7785 * path NULL terminated path
7786 *
7787 * Returns: KERN_SUCCESS Success
7788 * !KERN_SUCCESS See execve/mac_execve for error codes
7789 *
7790 * Notes: The process that is passed in is the first manufactured
7791 * process on the system, and gets here via bsd_ast() firing
7792 * for the first time. This is done to ensure that bsd_init()
7793 * has run to completion.
7794 *
7795 * The address map of the first manufactured process matches the
7796 * word width of the kernel. Once the self-exec completes, the
7797 * initproc might be different.
7798 */
7799 static int
load_init_program_at_path(proc_t p,user_addr_t scratch_addr,const char * path)7800 load_init_program_at_path(proc_t p, user_addr_t scratch_addr, const char* path)
7801 {
7802 int retval[2];
7803 int error;
7804 struct execve_args init_exec_args;
7805 user_addr_t argv0 = USER_ADDR_NULL, argv1 = USER_ADDR_NULL;
7806
7807 /*
7808 * Validate inputs and pre-conditions
7809 */
7810 assert(p);
7811 assert(scratch_addr);
7812 assert(path);
7813
7814 /*
7815 * Copy out program name.
7816 */
7817 size_t path_length = strlen(path) + 1;
7818 argv0 = scratch_addr;
7819 error = copyout(path, argv0, path_length);
7820 if (error) {
7821 return error;
7822 }
7823
7824 scratch_addr = USER_ADDR_ALIGN(scratch_addr + path_length, sizeof(user_addr_t));
7825
7826 /*
7827 * Put out first (and only) argument, similarly.
7828 * Assumes everything fits in a page as allocated above.
7829 */
7830 if (boothowto & RB_SINGLE) {
7831 const char *init_args = "-s";
7832 size_t init_args_length = strlen(init_args) + 1;
7833
7834 argv1 = scratch_addr;
7835 error = copyout(init_args, argv1, init_args_length);
7836 if (error) {
7837 return error;
7838 }
7839
7840 scratch_addr = USER_ADDR_ALIGN(scratch_addr + init_args_length, sizeof(user_addr_t));
7841 }
7842
7843 if (proc_is64bit(p)) {
7844 user64_addr_t argv64bit[3] = {};
7845
7846 argv64bit[0] = argv0;
7847 argv64bit[1] = argv1;
7848 argv64bit[2] = USER_ADDR_NULL;
7849
7850 error = copyout(argv64bit, scratch_addr, sizeof(argv64bit));
7851 if (error) {
7852 return error;
7853 }
7854 } else {
7855 user32_addr_t argv32bit[3] = {};
7856
7857 argv32bit[0] = (user32_addr_t)argv0;
7858 argv32bit[1] = (user32_addr_t)argv1;
7859 argv32bit[2] = USER_ADDR_NULL;
7860
7861 error = copyout(argv32bit, scratch_addr, sizeof(argv32bit));
7862 if (error) {
7863 return error;
7864 }
7865 }
7866
7867 /*
7868 * Set up argument block for fake call to execve.
7869 */
7870 init_exec_args.fname = argv0;
7871 init_exec_args.argp = scratch_addr;
7872 init_exec_args.envp = USER_ADDR_NULL;
7873
7874 /*
7875 * So that init task is set with uid,gid 0 token
7876 *
7877 * The access to the cred is safe:
7878 * the proc isn't running yet, it's stable.
7879 */
7880 set_security_token(p, proc_ucred_unsafe(p));
7881
7882 return execve(p, &init_exec_args, retval);
7883 }
7884
7885 static const char * init_programs[] = {
7886 #if DEBUG
7887 "/usr/appleinternal/sbin/launchd.debug",
7888 #endif
7889 #if DEVELOPMENT || DEBUG
7890 "/usr/appleinternal/sbin/launchd.development",
7891 #endif
7892 "/sbin/launchd",
7893 };
7894
7895 /*
7896 * load_init_program
7897 *
7898 * Description: Load the "init" program; in most cases, this will be "launchd"
7899 *
7900 * Parameters: p Process to call execve() to create
7901 * the "init" program
7902 *
7903 * Returns: (void)
7904 *
7905 * Notes: The process that is passed in is the first manufactured
7906 * process on the system, and gets here via bsd_ast() firing
7907 * for the first time. This is done to ensure that bsd_init()
7908 * has run to completion.
7909 *
7910 * In DEBUG & DEVELOPMENT builds, the launchdsuffix boot-arg
7911 * may be used to select a specific launchd executable. As with
7912 * the kcsuffix boot-arg, setting launchdsuffix to "" or "release"
7913 * will force /sbin/launchd to be selected.
7914 *
7915 * Search order by build:
7916 *
7917 * DEBUG DEVELOPMENT RELEASE PATH
7918 * ----------------------------------------------------------------------------------
7919 * 1 1 NA /usr/appleinternal/sbin/launchd.$LAUNCHDSUFFIX
7920 * 2 NA NA /usr/appleinternal/sbin/launchd.debug
7921 * 3 2 NA /usr/appleinternal/sbin/launchd.development
7922 * 4 3 1 /sbin/launchd
7923 */
7924 void
load_init_program(proc_t p)7925 load_init_program(proc_t p)
7926 {
7927 uint32_t i;
7928 int error;
7929 vm_map_t map = current_map();
7930 mach_vm_offset_t scratch_addr = 0;
7931 mach_vm_size_t map_page_size = vm_map_page_size(map);
7932
7933 #if DEVELOPMENT || DEBUG
7934 /* Use the opportunity to initialize exec's debug log stream */
7935 exec_log_handle = os_log_create("com.apple.xnu.bsd", "exec");
7936 #endif /* DEVELOPMENT || DEBUG */
7937
7938 (void) mach_vm_allocate_kernel(map, &scratch_addr, map_page_size,
7939 VM_MAP_KERNEL_FLAGS_ANYWHERE());
7940 #if CONFIG_MEMORYSTATUS
7941 (void) memorystatus_init_at_boot_snapshot();
7942 #endif /* CONFIG_MEMORYSTATUS */
7943
7944 #if DEBUG || DEVELOPMENT
7945 /* Check for boot-arg suffix first */
7946 char launchd_suffix[64];
7947 if (PE_parse_boot_argn("launchdsuffix", launchd_suffix, sizeof(launchd_suffix))) {
7948 char launchd_path[128];
7949 boolean_t is_release_suffix = ((launchd_suffix[0] == 0) ||
7950 (strcmp(launchd_suffix, "release") == 0));
7951
7952 if (is_release_suffix) {
7953 printf("load_init_program: attempting to load /sbin/launchd\n");
7954 error = load_init_program_at_path(p, (user_addr_t)scratch_addr, "/sbin/launchd");
7955 if (!error) {
7956 return;
7957 }
7958
7959 panic("Process 1 exec of launchd.release failed, errno %d", error);
7960 } else {
7961 strlcpy(launchd_path, "/usr/appleinternal/sbin/launchd.", sizeof(launchd_path));
7962 strlcat(launchd_path, launchd_suffix, sizeof(launchd_path));
7963
7964 printf("load_init_program: attempting to load %s\n", launchd_path);
7965 error = load_init_program_at_path(p, (user_addr_t)scratch_addr, launchd_path);
7966 if (!error) {
7967 return;
7968 } else if (error != ENOENT) {
7969 printf("load_init_program: failed loading %s: errno %d\n", launchd_path, error);
7970 }
7971 }
7972 }
7973 #endif
7974
7975 error = ENOENT;
7976 for (i = 0; i < sizeof(init_programs) / sizeof(init_programs[0]); i++) {
7977 printf("load_init_program: attempting to load %s\n", init_programs[i]);
7978 error = load_init_program_at_path(p, (user_addr_t)scratch_addr, init_programs[i]);
7979 if (!error) {
7980 return;
7981 } else if (error != ENOENT) {
7982 printf("load_init_program: failed loading %s: errno %d\n", init_programs[i], error);
7983 }
7984 }
7985
7986 panic("Process 1 exec of %s failed, errno %d", ((i == 0) ? "<null>" : init_programs[i - 1]), error);
7987 }
7988
7989 /*
7990 * load_return_to_errno
7991 *
7992 * Description: Convert a load_return_t (Mach error) to an errno (BSD error)
7993 *
7994 * Parameters: lrtn Mach error number
7995 *
7996 * Returns: (int) BSD error number
7997 * 0 Success
7998 * EBADARCH Bad architecture
7999 * EBADMACHO Bad Mach object file
8000 * ESHLIBVERS Bad shared library version
8001 * ENOMEM Out of memory/resource shortage
8002 * EACCES Access denied
8003 * ENOENT Entry not found (usually "file does
8004 * does not exist")
8005 * EIO An I/O error occurred
8006 * EBADEXEC The executable is corrupt/unknown
8007 */
8008 static int
load_return_to_errno(load_return_t lrtn)8009 load_return_to_errno(load_return_t lrtn)
8010 {
8011 switch (lrtn) {
8012 case LOAD_SUCCESS:
8013 return 0;
8014 case LOAD_BADARCH:
8015 return EBADARCH;
8016 case LOAD_BADMACHO:
8017 case LOAD_BADMACHO_UPX:
8018 return EBADMACHO;
8019 case LOAD_SHLIB:
8020 return ESHLIBVERS;
8021 case LOAD_NOSPACE:
8022 case LOAD_RESOURCE:
8023 return ENOMEM;
8024 case LOAD_PROTECT:
8025 return EACCES;
8026 case LOAD_ENOENT:
8027 return ENOENT;
8028 case LOAD_IOERROR:
8029 return EIO;
8030 case LOAD_DECRYPTFAIL:
8031 return EAUTH;
8032 case LOAD_FAILURE:
8033 default:
8034 return EBADEXEC;
8035 }
8036 }
8037
8038 #include <mach/mach_types.h>
8039 #include <mach/vm_prot.h>
8040 #include <mach/semaphore.h>
8041 #include <mach/sync_policy.h>
8042 #include <kern/clock.h>
8043 #include <mach/kern_return.h>
8044
8045 /*
8046 * execargs_alloc
8047 *
8048 * Description: Allocate the block of memory used by the execve arguments.
8049 * At the same time, we allocate a page so that we can read in
8050 * the first page of the image.
8051 *
8052 * Parameters: struct image_params * the image parameter block
8053 *
8054 * Returns: 0 Success
8055 * EINVAL Invalid argument
8056 * EACCES Permission denied
8057 * EINTR Interrupted function
8058 * ENOMEM Not enough space
8059 *
8060 * Notes: This is a temporary allocation into the kernel address space
8061 * to enable us to copy arguments in from user space. This is
8062 * necessitated by not mapping the process calling execve() into
8063 * the kernel address space during the execve() system call.
8064 *
8065 * We assemble the argument and environment, etc., into this
8066 * region before copying it as a single block into the child
8067 * process address space (at the top or bottom of the stack,
8068 * depending on which way the stack grows; see the function
8069 * exec_copyout_strings() for details).
8070 *
8071 * This ends up with a second (possibly unnecessary) copy compared
8072 * with assembing the data directly into the child address space,
8073 * instead, but since we cannot be guaranteed that the parent has
8074 * not modified its environment, we can't really know that it's
8075 * really a block there as well.
8076 */
8077
8078
8079 static int execargs_waiters = 0;
8080 static LCK_MTX_DECLARE_ATTR(execargs_cache_lock, &proc_lck_grp, &proc_lck_attr);
8081
8082 static void
execargs_lock_lock(void)8083 execargs_lock_lock(void)
8084 {
8085 lck_mtx_lock_spin(&execargs_cache_lock);
8086 }
8087
8088 static void
execargs_lock_unlock(void)8089 execargs_lock_unlock(void)
8090 {
8091 lck_mtx_unlock(&execargs_cache_lock);
8092 }
8093
8094 static wait_result_t
execargs_lock_sleep(void)8095 execargs_lock_sleep(void)
8096 {
8097 return lck_mtx_sleep(&execargs_cache_lock, LCK_SLEEP_DEFAULT, &execargs_free_count, THREAD_INTERRUPTIBLE);
8098 }
8099
8100 static kern_return_t
execargs_purgeable_allocate(char ** execarg_address)8101 execargs_purgeable_allocate(char **execarg_address)
8102 {
8103 mach_vm_offset_t addr = 0;
8104 kern_return_t kr = mach_vm_allocate_kernel(bsd_pageable_map, &addr,
8105 BSD_PAGEABLE_SIZE_PER_EXEC,
8106 VM_MAP_KERNEL_FLAGS_ANYWHERE(.vmf_purgeable = true));
8107 *execarg_address = (char *)addr;
8108 assert(kr == KERN_SUCCESS);
8109 return kr;
8110 }
8111
8112 static kern_return_t
execargs_purgeable_reference(void * execarg_address)8113 execargs_purgeable_reference(void *execarg_address)
8114 {
8115 int state = VM_PURGABLE_NONVOLATILE;
8116 kern_return_t kr = vm_map_purgable_control(bsd_pageable_map,
8117 (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state);
8118
8119 assert(kr == KERN_SUCCESS);
8120 return kr;
8121 }
8122
8123 static kern_return_t
execargs_purgeable_volatilize(void * execarg_address)8124 execargs_purgeable_volatilize(void *execarg_address)
8125 {
8126 int state = VM_PURGABLE_VOLATILE | VM_PURGABLE_ORDERING_OBSOLETE;
8127 kern_return_t kr;
8128 kr = vm_map_purgable_control(bsd_pageable_map,
8129 (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state);
8130
8131 assert(kr == KERN_SUCCESS);
8132
8133 return kr;
8134 }
8135
8136 static void
execargs_wakeup_waiters(void)8137 execargs_wakeup_waiters(void)
8138 {
8139 thread_wakeup(&execargs_free_count);
8140 }
8141
8142 static int
execargs_alloc(struct image_params * imgp)8143 execargs_alloc(struct image_params *imgp)
8144 {
8145 kern_return_t kret;
8146 wait_result_t res;
8147 int i, cache_index = -1;
8148
8149 execargs_lock_lock();
8150
8151 while (execargs_free_count == 0) {
8152 execargs_waiters++;
8153 res = execargs_lock_sleep();
8154 execargs_waiters--;
8155 if (res != THREAD_AWAKENED) {
8156 execargs_lock_unlock();
8157 return EINTR;
8158 }
8159 }
8160
8161 execargs_free_count--;
8162
8163 for (i = 0; i < execargs_cache_size; i++) {
8164 vm_offset_t element = execargs_cache[i];
8165 if (element) {
8166 cache_index = i;
8167 imgp->ip_strings = (char *)(execargs_cache[i]);
8168 execargs_cache[i] = 0;
8169 break;
8170 }
8171 }
8172
8173 assert(execargs_free_count >= 0);
8174
8175 execargs_lock_unlock();
8176
8177 if (cache_index == -1) {
8178 kret = execargs_purgeable_allocate(&imgp->ip_strings);
8179 } else {
8180 kret = execargs_purgeable_reference(imgp->ip_strings);
8181 }
8182
8183 assert(kret == KERN_SUCCESS);
8184 if (kret != KERN_SUCCESS) {
8185 return ENOMEM;
8186 }
8187
8188 /* last page used to read in file headers */
8189 imgp->ip_vdata = imgp->ip_strings + (NCARGS + PAGE_SIZE);
8190 imgp->ip_strendp = imgp->ip_strings;
8191 imgp->ip_argspace = NCARGS;
8192 imgp->ip_strspace = (NCARGS + PAGE_SIZE);
8193
8194 return 0;
8195 }
8196
8197 /*
8198 * execargs_free
8199 *
8200 * Description: Free the block of memory used by the execve arguments and the
8201 * first page of the executable by a previous call to the function
8202 * execargs_alloc().
8203 *
8204 * Parameters: struct image_params * the image parameter block
8205 *
8206 * Returns: 0 Success
8207 * EINVAL Invalid argument
8208 * EINTR Oeration interrupted
8209 */
8210 static int
execargs_free(struct image_params * imgp)8211 execargs_free(struct image_params *imgp)
8212 {
8213 kern_return_t kret;
8214 int i;
8215 boolean_t needs_wakeup = FALSE;
8216
8217 kret = execargs_purgeable_volatilize(imgp->ip_strings);
8218
8219 execargs_lock_lock();
8220 execargs_free_count++;
8221
8222 for (i = 0; i < execargs_cache_size; i++) {
8223 vm_offset_t element = execargs_cache[i];
8224 if (element == 0) {
8225 execargs_cache[i] = (vm_offset_t) imgp->ip_strings;
8226 imgp->ip_strings = NULL;
8227 break;
8228 }
8229 }
8230
8231 assert(imgp->ip_strings == NULL);
8232
8233 if (execargs_waiters > 0) {
8234 needs_wakeup = TRUE;
8235 }
8236
8237 execargs_lock_unlock();
8238
8239 if (needs_wakeup == TRUE) {
8240 execargs_wakeup_waiters();
8241 }
8242
8243 return kret == KERN_SUCCESS ? 0 : EINVAL;
8244 }
8245
8246 void
uthread_set_exec_data(struct uthread * uth,struct image_params * imgp)8247 uthread_set_exec_data(struct uthread *uth, struct image_params *imgp)
8248 {
8249 uth->uu_save.uus_exec_data.imgp = imgp;
8250 }
8251
8252 size_t
thread_get_current_exec_path(char * path,size_t size)8253 thread_get_current_exec_path(char *path, size_t size)
8254 {
8255 struct uthread *uth = current_uthread();
8256 struct image_params *imgp = uth->uu_save.uus_exec_data.imgp;
8257 size_t string_size = 0;
8258 char *exec_path;
8259
8260 if (path == NULL || imgp == NULL || imgp->ip_strings == NULL) {
8261 return 0;
8262 }
8263
8264 exec_path = imgp->ip_strings + strlen(EXECUTABLE_KEY);
8265 string_size = imgp->ip_strendp - exec_path;
8266 string_size = MIN(MAXPATHLEN, string_size);
8267 string_size = MIN(size, string_size);
8268
8269 string_size = strlcpy(path, exec_path, string_size);
8270 return string_size;
8271 }
8272 static void
exec_resettextvp(proc_t p,struct image_params * imgp)8273 exec_resettextvp(proc_t p, struct image_params *imgp)
8274 {
8275 vnode_t vp;
8276 off_t offset;
8277 vnode_t tvp = p->p_textvp;
8278 int ret;
8279
8280 vp = imgp->ip_vp;
8281 offset = imgp->ip_arch_offset;
8282
8283 if (vp == NULLVP) {
8284 panic("exec_resettextvp: expected valid vp");
8285 }
8286
8287 ret = vnode_ref(vp);
8288 proc_lock(p);
8289 if (ret == 0) {
8290 p->p_textvp = vp;
8291 p->p_textoff = offset;
8292 } else {
8293 p->p_textvp = NULLVP; /* this is paranoia */
8294 p->p_textoff = 0;
8295 }
8296 proc_unlock(p);
8297
8298 if (tvp != NULLVP) {
8299 if (vnode_getwithref(tvp) == 0) {
8300 vnode_rele(tvp);
8301 vnode_put(tvp);
8302 }
8303 }
8304 }
8305
8306 // Includes the 0-byte (therefore "SIZE" instead of "LEN").
8307 static const size_t CS_CDHASH_STRING_SIZE = CS_CDHASH_LEN * 2 + 1;
8308
8309 static void
cdhash_to_string(char str[CS_CDHASH_STRING_SIZE],uint8_t const * const cdhash)8310 cdhash_to_string(char str[CS_CDHASH_STRING_SIZE], uint8_t const * const cdhash)
8311 {
8312 static char const nibble[] = "0123456789abcdef";
8313
8314 /* Apparently still the safest way to get a hex representation
8315 * of binary data.
8316 * xnu's printf routines have %*D/%20D in theory, but "not really", see:
8317 * <rdar://problem/33328859> confusion around %*D/%nD in printf
8318 */
8319 for (int i = 0; i < CS_CDHASH_LEN; ++i) {
8320 str[i * 2] = nibble[(cdhash[i] & 0xf0) >> 4];
8321 str[i * 2 + 1] = nibble[cdhash[i] & 0x0f];
8322 }
8323 str[CS_CDHASH_STRING_SIZE - 1] = 0;
8324 }
8325
8326 /*
8327 * __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__
8328 *
8329 * Description: Waits for the userspace daemon to respond to the request
8330 * we made. Function declared non inline to be visible in
8331 * stackshots and spindumps as well as debugging.
8332 */
8333 __attribute__((noinline)) int
__EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port,int32_t new_pid)8334 __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port, int32_t new_pid)
8335 {
8336 return find_code_signature(task_access_port, new_pid);
8337 }
8338
8339 /*
8340 * Update signature dependent process state, called by
8341 * process_signature.
8342 */
8343 static int
proc_process_signature(proc_t p,os_reason_t * signature_failure_reason)8344 proc_process_signature(proc_t p, os_reason_t *signature_failure_reason)
8345 {
8346 int error = 0;
8347 char const *error_msg = NULL;
8348
8349 kern_return_t kr = machine_task_process_signature(proc_get_task_raw(p), proc_platform(p), proc_sdk(p), &error_msg);
8350
8351 if (kr != KERN_SUCCESS) {
8352 error = EINVAL;
8353
8354 if (error_msg != NULL) {
8355 uint32_t error_msg_len = (uint32_t)strlen(error_msg) + 1;
8356 mach_vm_address_t data_addr = 0;
8357 int reason_error = 0;
8358 int kcdata_error = 0;
8359
8360 os_reason_t reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY);
8361 reason->osr_flags = OS_REASON_FLAG_GENERATE_CRASH_REPORT | OS_REASON_FLAG_CONSISTENT_FAILURE;
8362
8363 if ((reason_error = os_reason_alloc_buffer_noblock(reason,
8364 kcdata_estimate_required_buffer_size(1, error_msg_len))) == 0 &&
8365 (kcdata_error = kcdata_get_memory_addr(&reason->osr_kcd_descriptor,
8366 EXIT_REASON_USER_DESC, error_msg_len,
8367 &data_addr)) == KERN_SUCCESS) {
8368 kern_return_t mc_error = kcdata_memcpy(&reason->osr_kcd_descriptor, (mach_vm_address_t)data_addr,
8369 error_msg, error_msg_len);
8370
8371 if (mc_error != KERN_SUCCESS) {
8372 printf("process_signature: failed to copy reason string (kcdata_memcpy error: %d)\n",
8373 mc_error);
8374 }
8375 } else {
8376 printf("failed to allocate space for reason string (os_reason_alloc_buffer error: %d, kcdata error: %d, length: %u)\n",
8377 reason_error, kcdata_error, error_msg_len);
8378 }
8379
8380 assert(*signature_failure_reason == NULL); // shouldn't have gotten so far
8381 *signature_failure_reason = reason;
8382 }
8383 }
8384 return error;
8385 }
8386
8387
8388 #define DT_UNRESTRICTED_SUBSYSTEM_ROOT "unrestricted-subsystem-root"
8389
8390 static bool
allow_unrestricted_subsystem_root(void)8391 allow_unrestricted_subsystem_root(void)
8392 {
8393 #if !(DEVELOPMENT || DEBUG)
8394 static bool allow_unrestricted_subsystem_root = false;
8395 static bool has_been_set = false;
8396
8397 if (!has_been_set) {
8398 DTEntry chosen;
8399 const uint32_t *value;
8400 unsigned size;
8401
8402 has_been_set = true;
8403 if (SecureDTLookupEntry(0, "/chosen", &chosen) == kSuccess &&
8404 SecureDTGetProperty(chosen, DT_UNRESTRICTED_SUBSYSTEM_ROOT, (const void**)&value, &size) == kSuccess &&
8405 value != NULL &&
8406 size == sizeof(uint32_t)) {
8407 allow_unrestricted_subsystem_root = (bool)*value;
8408 }
8409 }
8410
8411 return allow_unrestricted_subsystem_root;
8412 #else
8413 return true;
8414 #endif
8415 }
8416
8417 static int
process_signature(proc_t p,struct image_params * imgp)8418 process_signature(proc_t p, struct image_params *imgp)
8419 {
8420 mach_port_t port = IPC_PORT_NULL;
8421 kern_return_t kr = KERN_FAILURE;
8422 int error = EACCES;
8423 boolean_t unexpected_failure = FALSE;
8424 struct cs_blob *csb;
8425 boolean_t require_success = FALSE;
8426 int spawn = (imgp->ip_flags & IMGPF_SPAWN);
8427 const int vfexec = 0;
8428 os_reason_t signature_failure_reason = OS_REASON_NULL;
8429
8430 /*
8431 * Override inherited code signing flags with the
8432 * ones for the process that is being successfully
8433 * loaded
8434 */
8435 proc_lock(p);
8436 proc_csflags_update(p, imgp->ip_csflags);
8437 proc_unlock(p);
8438
8439 /* Set the switch_protect flag on the map */
8440 if (proc_getcsflags(p) & (CS_HARD | CS_KILL)) {
8441 vm_map_switch_protect(get_task_map(proc_task(p)), TRUE);
8442 }
8443 /* set the cs_enforced flags in the map */
8444 if (proc_getcsflags(p) & CS_ENFORCEMENT) {
8445 vm_map_cs_enforcement_set(get_task_map(proc_task(p)), TRUE);
8446 } else {
8447 vm_map_cs_enforcement_set(get_task_map(proc_task(p)), FALSE);
8448 }
8449
8450 /*
8451 * image activation may be failed due to policy
8452 * which is unexpected but security framework does not
8453 * approve of exec, kill and return immediately.
8454 */
8455 if (imgp->ip_mac_return != 0) {
8456 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
8457 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY, 0, 0);
8458 signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY);
8459 error = imgp->ip_mac_return;
8460 unexpected_failure = TRUE;
8461 goto done;
8462 }
8463
8464 if (imgp->ip_cs_error != OS_REASON_NULL) {
8465 signature_failure_reason = imgp->ip_cs_error;
8466 imgp->ip_cs_error = OS_REASON_NULL;
8467 error = EACCES;
8468 goto done;
8469 }
8470
8471 /* call the launch constraints hook */
8472 os_reason_t launch_constraint_reason;
8473 if ((error = mac_proc_check_launch_constraints(p, imgp, &launch_constraint_reason)) != 0) {
8474 signature_failure_reason = launch_constraint_reason;
8475 goto done;
8476 }
8477
8478 /*
8479 * Reject when there's subsystem root path set, but the image is restricted, and doesn't require
8480 * library validation. This is to avoid subsystem root being used to inject unsigned code
8481 */
8482 if (!allow_unrestricted_subsystem_root()) {
8483 if ((imgp->ip_csflags & CS_RESTRICT || proc_issetugid(p)) &&
8484 !(imgp->ip_csflags & CS_REQUIRE_LV) &&
8485 (imgp->ip_subsystem_root_path != NULL)) {
8486 signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY);
8487 error = EACCES;
8488 goto done;
8489 }
8490 }
8491
8492 #if XNU_TARGET_OS_OSX
8493 /* Check for platform passed in spawn attr if iOS binary is being spawned */
8494 if (proc_platform(p) == PLATFORM_IOS) {
8495 struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
8496 if (psa == NULL || psa->psa_platform == 0) {
8497 boolean_t no_sandbox_entitled = FALSE;
8498 #if DEBUG || DEVELOPMENT
8499 /*
8500 * Allow iOS binaries to spawn on internal systems
8501 * if no-sandbox entitlement is present of unentitled_ios_sim_launch
8502 * boot-arg set to true
8503 */
8504 if (unentitled_ios_sim_launch) {
8505 no_sandbox_entitled = TRUE;
8506 } else {
8507 no_sandbox_entitled = IOVnodeHasEntitlement(imgp->ip_vp,
8508 (int64_t)imgp->ip_arch_offset, "com.apple.private.security.no-sandbox");
8509 }
8510 #endif /* DEBUG || DEVELOPMENT */
8511 if (!no_sandbox_entitled) {
8512 signature_failure_reason = os_reason_create(OS_REASON_EXEC,
8513 EXEC_EXIT_REASON_WRONG_PLATFORM);
8514 error = EACCES;
8515 goto done;
8516 }
8517 printf("Allowing spawn of iOS binary %s since it has "
8518 "com.apple.private.security.no-sandbox entitlement or unentitled_ios_sim_launch "
8519 "boot-arg set to true\n", p->p_name);
8520 } else if (psa->psa_platform != PLATFORM_IOS) {
8521 /* Simulator binary spawned with wrong platform */
8522 signature_failure_reason = os_reason_create(OS_REASON_EXEC,
8523 EXEC_EXIT_REASON_WRONG_PLATFORM);
8524 error = EACCES;
8525 goto done;
8526 } else {
8527 printf("Allowing spawn of iOS binary %s since correct platform was passed in spawn\n",
8528 p->p_name);
8529 }
8530 }
8531 #endif /* XNU_TARGET_OS_OSX */
8532
8533 /* If the code signature came through the image activation path, we skip the
8534 * taskgated / externally attached path. */
8535 if (imgp->ip_csflags & CS_SIGNED) {
8536 error = 0;
8537 goto done;
8538 }
8539
8540 /* The rest of the code is for signatures that either already have been externally
8541 * attached (likely, but not necessarily by a previous run through the taskgated
8542 * path), or that will now be attached by taskgated. */
8543
8544 kr = task_get_task_access_port(proc_task(p), &port);
8545 if (KERN_SUCCESS != kr || !IPC_PORT_VALID(port)) {
8546 error = 0;
8547 if (require_success) {
8548 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
8549 proc_getpid(p), OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT, 0, 0);
8550 signature_failure_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT);
8551 error = EACCES;
8552 }
8553 goto done;
8554 }
8555
8556 /*
8557 * taskgated returns KERN_SUCCESS if it has completed its work
8558 * and the exec should continue, KERN_FAILURE if the exec should
8559 * fail, or it may error out with different error code in an
8560 * event of mig failure (e.g. process was signalled during the
8561 * rpc call, taskgated died, mig server died etc.).
8562 */
8563
8564 kr = __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(port, proc_getpid(p));
8565 switch (kr) {
8566 case KERN_SUCCESS:
8567 error = 0;
8568 break;
8569 case KERN_FAILURE:
8570 error = EACCES;
8571
8572 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
8573 proc_getpid(p), OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG, 0, 0);
8574 signature_failure_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG);
8575 goto done;
8576 default:
8577 error = EACCES;
8578
8579 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
8580 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_TASKGATED_OTHER, 0, 0);
8581 signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_TASKGATED_OTHER);
8582 unexpected_failure = TRUE;
8583 goto done;
8584 }
8585
8586 /* Only do this if exec_resettextvp() did not fail */
8587 if (p->p_textvp != NULLVP) {
8588 csb = ubc_cs_blob_get(p->p_textvp, -1, -1, p->p_textoff);
8589
8590 if (csb != NULL) {
8591 /* As the enforcement we can do here is very limited, we only allow things that
8592 * are the only reason why this code path still exists:
8593 * Adhoc signed non-platform binaries without special cs_flags and without any
8594 * entitlements (unrestricted ones still pass AMFI). */
8595 if (
8596 /* Revalidate the blob if necessary through bumped generation count. */
8597 (ubc_cs_generation_check(p->p_textvp) == 0 ||
8598 ubc_cs_blob_revalidate(p->p_textvp, csb, imgp, 0, proc_platform(p)) == 0) &&
8599 /* Only CS_ADHOC, no CS_KILL, CS_HARD etc. */
8600 (csb->csb_flags & CS_ALLOWED_MACHO) == CS_ADHOC &&
8601 /* If it has a CMS blob, it's not adhoc. The CS_ADHOC flag can lie. */
8602 csblob_find_blob_bytes((const uint8_t *)csb->csb_mem_kaddr, csb->csb_mem_size,
8603 CSSLOT_SIGNATURESLOT,
8604 CSMAGIC_BLOBWRAPPER) == NULL &&
8605 /* It could still be in a trust cache (unlikely with CS_ADHOC), or a magic path. */
8606 csb->csb_platform_binary == 0 &&
8607 /* No entitlements, not even unrestricted ones. */
8608 csb->csb_entitlements_blob == NULL &&
8609 csb->csb_der_entitlements_blob == NULL) {
8610 proc_lock(p);
8611 proc_csflags_set(p, CS_SIGNED | CS_VALID);
8612 proc_unlock(p);
8613 } else {
8614 uint8_t cdhash[CS_CDHASH_LEN];
8615 char cdhash_string[CS_CDHASH_STRING_SIZE];
8616 proc_getcdhash(p, cdhash);
8617 cdhash_to_string(cdhash_string, cdhash);
8618 printf("ignoring detached code signature on '%s' with cdhash '%s' "
8619 "because it is invalid, or not a simple adhoc signature.\n",
8620 p->p_name, cdhash_string);
8621 }
8622 }
8623 }
8624
8625 done:
8626 if (0 == error) {
8627 /*
8628 * Update the new process's signature-dependent process state.
8629 * state.
8630 */
8631
8632 error = proc_process_signature(p, &signature_failure_reason);
8633 }
8634
8635 if (0 == error) {
8636 /*
8637 * Update the new main thread's signature-dependent thread
8638 * state. This was also called when the thread was created,
8639 * but for the main thread the signature was not yet attached
8640 * at that time.
8641 */
8642 kr = thread_process_signature(imgp->ip_new_thread, proc_get_task_raw(p));
8643
8644 if (kr != KERN_SUCCESS) {
8645 error = EINVAL;
8646 signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_MACHINE_THREAD);
8647 }
8648 }
8649
8650 if (0 == error) {
8651 /* The process's code signature related properties are
8652 * fully set up, so this is an opportune moment to log
8653 * platform binary execution, if desired. */
8654 if (platform_exec_logging != 0 && csproc_get_platform_binary(p)) {
8655 uint8_t cdhash[CS_CDHASH_LEN];
8656 char cdhash_string[CS_CDHASH_STRING_SIZE];
8657 proc_getcdhash(p, cdhash);
8658 cdhash_to_string(cdhash_string, cdhash);
8659
8660 os_log(peLog, "CS Platform Exec Logging: Executing platform signed binary "
8661 "'%s' with cdhash %s\n", p->p_name, cdhash_string);
8662 }
8663 } else {
8664 if (!unexpected_failure) {
8665 proc_csflags_set(p, CS_KILLED);
8666 }
8667 /* make very sure execution fails */
8668 if (vfexec || spawn) {
8669 assert(signature_failure_reason != OS_REASON_NULL);
8670 psignal_vfork_with_reason(p, proc_task(p), imgp->ip_new_thread,
8671 SIGKILL, signature_failure_reason);
8672 signature_failure_reason = OS_REASON_NULL;
8673 error = 0;
8674 } else {
8675 assert(signature_failure_reason != OS_REASON_NULL);
8676 psignal_with_reason(p, SIGKILL, signature_failure_reason);
8677 signature_failure_reason = OS_REASON_NULL;
8678 }
8679 }
8680
8681 if (port != IPC_PORT_NULL) {
8682 ipc_port_release_send(port);
8683 }
8684
8685 /* If we hit this, we likely would have leaked an exit reason */
8686 assert(signature_failure_reason == OS_REASON_NULL);
8687 return error;
8688 }
8689
8690 /*
8691 * Typically as soon as we start executing this process, the
8692 * first instruction will trigger a VM fault to bring the text
8693 * pages (as executable) into the address space, followed soon
8694 * thereafter by dyld data structures (for dynamic executable).
8695 * To optimize this, as well as improve support for hardware
8696 * debuggers that can only access resident pages present
8697 * in the process' page tables, we prefault some pages if
8698 * possible. Errors are non-fatal.
8699 */
8700 #ifndef PREVENT_CALLER_STACK_USE
8701 #define PREVENT_CALLER_STACK_USE __attribute__((noinline))
8702 #endif
8703
8704 /*
8705 * Prefaulting dyld data does not work (rdar://76621401)
8706 */
8707 #define FIXED_76621401 0
8708 static void PREVENT_CALLER_STACK_USE
exec_prefault_data(__unused proc_t p,__unused struct image_params * imgp,__unused load_result_t * load_result)8709 exec_prefault_data(
8710 __unused proc_t p,
8711 __unused struct image_params *imgp,
8712 __unused load_result_t *load_result)
8713 {
8714 #if FIXED_76621401
8715 int ret;
8716 size_t expected_all_image_infos_size;
8717 #endif /* FIXED_76621401 */
8718 kern_return_t kr;
8719
8720 /*
8721 * Prefault executable or dyld entry point.
8722 */
8723 if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
8724 DEBUG4K_LOAD("entry_point 0x%llx\n", (uint64_t)load_result->entry_point);
8725 }
8726 kr = vm_fault(current_map(),
8727 vm_map_trunc_page(load_result->entry_point,
8728 vm_map_page_mask(current_map())),
8729 VM_PROT_READ | VM_PROT_EXECUTE,
8730 FALSE, VM_KERN_MEMORY_NONE,
8731 THREAD_UNINT, NULL, 0);
8732 if (kr != KERN_SUCCESS) {
8733 DEBUG4K_ERROR("map %p va 0x%llx -> 0x%x\n", current_map(), (uint64_t)vm_map_trunc_page(load_result->entry_point, vm_map_page_mask(current_map())), kr);
8734 }
8735
8736 #if FIXED_76621401
8737 if (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) {
8738 expected_all_image_infos_size = sizeof(struct user64_dyld_all_image_infos);
8739 } else {
8740 expected_all_image_infos_size = sizeof(struct user32_dyld_all_image_infos);
8741 }
8742
8743 /* Decode dyld anchor structure from <mach-o/dyld_images.h> */
8744 if (load_result->dynlinker &&
8745 load_result->all_image_info_addr &&
8746 load_result->all_image_info_size >= expected_all_image_infos_size) {
8747 union {
8748 struct user64_dyld_all_image_infos infos64;
8749 struct user32_dyld_all_image_infos infos32;
8750 } all_image_infos;
8751
8752 /*
8753 * Pre-fault to avoid copyin() going through the trap handler
8754 * and recovery path.
8755 */
8756 if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
8757 DEBUG4K_LOAD("all_image_info_addr 0x%llx\n", load_result->all_image_info_addr);
8758 }
8759 kr = vm_fault(current_map(),
8760 vm_map_trunc_page(load_result->all_image_info_addr,
8761 vm_map_page_mask(current_map())),
8762 VM_PROT_READ | VM_PROT_WRITE,
8763 FALSE, VM_KERN_MEMORY_NONE,
8764 THREAD_UNINT, NULL, 0);
8765 if (kr != KERN_SUCCESS) {
8766 // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(load_result->all_image_info_addr, vm_map_page_mask(current_map())), kr);
8767 }
8768 if ((load_result->all_image_info_addr & PAGE_MASK) + expected_all_image_infos_size > PAGE_SIZE) {
8769 /* all_image_infos straddles a page */
8770 kr = vm_fault(current_map(),
8771 vm_map_trunc_page(load_result->all_image_info_addr + expected_all_image_infos_size - 1,
8772 vm_map_page_mask(current_map())),
8773 VM_PROT_READ | VM_PROT_WRITE,
8774 FALSE, VM_KERN_MEMORY_NONE,
8775 THREAD_UNINT, NULL, 0);
8776 if (kr != KERN_SUCCESS) {
8777 // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(load_result->all_image_info_addr + expected_all_image_infos_size -1, vm_map_page_mask(current_map())), kr);
8778 }
8779 }
8780
8781 if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
8782 DEBUG4K_LOAD("copyin(0x%llx, 0x%lx)\n", load_result->all_image_info_addr, expected_all_image_infos_size);
8783 }
8784 ret = copyin((user_addr_t)load_result->all_image_info_addr,
8785 &all_image_infos,
8786 expected_all_image_infos_size);
8787 if (ret == 0 && all_image_infos.infos32.version >= DYLD_ALL_IMAGE_INFOS_ADDRESS_MINIMUM_VERSION) {
8788 user_addr_t notification_address;
8789 user_addr_t dyld_image_address;
8790 user_addr_t dyld_version_address;
8791 user_addr_t dyld_all_image_infos_address;
8792 user_addr_t dyld_slide_amount;
8793
8794 if (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) {
8795 notification_address = (user_addr_t)all_image_infos.infos64.notification;
8796 dyld_image_address = (user_addr_t)all_image_infos.infos64.dyldImageLoadAddress;
8797 dyld_version_address = (user_addr_t)all_image_infos.infos64.dyldVersion;
8798 dyld_all_image_infos_address = (user_addr_t)all_image_infos.infos64.dyldAllImageInfosAddress;
8799 } else {
8800 notification_address = all_image_infos.infos32.notification;
8801 dyld_image_address = all_image_infos.infos32.dyldImageLoadAddress;
8802 dyld_version_address = all_image_infos.infos32.dyldVersion;
8803 dyld_all_image_infos_address = all_image_infos.infos32.dyldAllImageInfosAddress;
8804 }
8805
8806 /*
8807 * dyld statically sets up the all_image_infos in its Mach-O
8808 * binary at static link time, with pointers relative to its default
8809 * load address. Since ASLR might slide dyld before its first
8810 * instruction is executed, "dyld_slide_amount" tells us how far
8811 * dyld was loaded compared to its default expected load address.
8812 * All other pointers into dyld's image should be adjusted by this
8813 * amount. At some point later, dyld will fix up pointers to take
8814 * into account the slide, at which point the all_image_infos_address
8815 * field in the structure will match the runtime load address, and
8816 * "dyld_slide_amount" will be 0, if we were to consult it again.
8817 */
8818
8819 dyld_slide_amount = (user_addr_t)load_result->all_image_info_addr - dyld_all_image_infos_address;
8820
8821 #if 0
8822 kprintf("exec_prefault: 0x%016llx 0x%08x 0x%016llx 0x%016llx 0x%016llx 0x%016llx\n",
8823 (uint64_t)load_result->all_image_info_addr,
8824 all_image_infos.infos32.version,
8825 (uint64_t)notification_address,
8826 (uint64_t)dyld_image_address,
8827 (uint64_t)dyld_version_address,
8828 (uint64_t)dyld_all_image_infos_address);
8829 #endif
8830
8831 if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
8832 DEBUG4K_LOAD("notification_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)notification_address, (uint64_t)dyld_slide_amount);
8833 }
8834 kr = vm_fault(current_map(),
8835 vm_map_trunc_page(notification_address + dyld_slide_amount,
8836 vm_map_page_mask(current_map())),
8837 VM_PROT_READ | VM_PROT_EXECUTE,
8838 FALSE, VM_KERN_MEMORY_NONE,
8839 THREAD_UNINT, NULL, 0);
8840 if (kr != KERN_SUCCESS) {
8841 // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(notification_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr);
8842 }
8843 if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
8844 DEBUG4K_LOAD("dyld_image_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)dyld_image_address, (uint64_t)dyld_slide_amount);
8845 }
8846 kr = vm_fault(current_map(),
8847 vm_map_trunc_page(dyld_image_address + dyld_slide_amount,
8848 vm_map_page_mask(current_map())),
8849 VM_PROT_READ | VM_PROT_EXECUTE,
8850 FALSE, VM_KERN_MEMORY_NONE,
8851 THREAD_UNINT, NULL, 0);
8852 if (kr != KERN_SUCCESS) {
8853 // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(dyld_image_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr);
8854 }
8855 if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
8856 DEBUG4K_LOAD("dyld_version_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)dyld_version_address, (uint64_t)dyld_slide_amount);
8857 }
8858 kr = vm_fault(current_map(),
8859 vm_map_trunc_page(dyld_version_address + dyld_slide_amount,
8860 vm_map_page_mask(current_map())),
8861 VM_PROT_READ,
8862 FALSE, VM_KERN_MEMORY_NONE,
8863 THREAD_UNINT, NULL, 0);
8864 if (kr != KERN_SUCCESS) {
8865 // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(dyld_version_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr);
8866 }
8867 if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
8868 DEBUG4K_LOAD("dyld_all_image_infos_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)dyld_version_address, (uint64_t)dyld_slide_amount);
8869 }
8870 kr = vm_fault(current_map(),
8871 vm_map_trunc_page(dyld_all_image_infos_address + dyld_slide_amount,
8872 vm_map_page_mask(current_map())),
8873 VM_PROT_READ | VM_PROT_WRITE,
8874 FALSE, VM_KERN_MEMORY_NONE,
8875 THREAD_UNINT, NULL, 0);
8876 if (kr != KERN_SUCCESS) {
8877 // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(dyld_all_image_infos_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr);
8878 }
8879 }
8880 }
8881 #endif /* FIXED_76621401 */
8882 }
8883
8884 static int
8885 sysctl_libmalloc_experiments SYSCTL_HANDLER_ARGS
8886 {
8887 #pragma unused(oidp, arg2, req)
8888 int changed;
8889 errno_t error;
8890 uint64_t value = os_atomic_load_wide(&libmalloc_experiment_factors, relaxed);
8891
8892 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
8893 if (error) {
8894 return error;
8895 }
8896
8897 if (changed) {
8898 os_atomic_store_wide(&libmalloc_experiment_factors, value, relaxed);
8899 }
8900
8901 return 0;
8902 }
8903
8904 EXPERIMENT_FACTOR_LEGACY_PROC(_kern, libmalloc_experiments, CTLTYPE_QUAD | CTLFLAG_RW, 0, 0, &sysctl_libmalloc_experiments, "A", "");
8905
8906 SYSCTL_NODE(_kern, OID_AUTO, sec_transition,
8907 CTLFLAG_RD | CTLFLAG_LOCKED, 0, "sec_transition");
8908
8909 #if DEBUG || DEVELOPMENT
8910 static int
sysctl_setup_ensure_pidversion_changes_on_exec(__unused int64_t in,int64_t * out)8911 sysctl_setup_ensure_pidversion_changes_on_exec(__unused int64_t in, int64_t *out)
8912 {
8913 // Tweak nextpidversion to try to trigger a reuse (unless the exec code is doing the right thing)
8914 int current_pid_version = proc_get_ro(current_proc())->p_idversion;
8915 nextpidversion = current_pid_version;
8916 *out = 0;
8917 return KERN_SUCCESS;
8918 }
8919
8920 SYSCTL_TEST_REGISTER(setup_ensure_pidversion_changes_on_exec, sysctl_setup_ensure_pidversion_changes_on_exec);
8921 #endif /* DEBUG || DEVELOPMENT */
8922