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