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