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