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