2 * Copyright (c) 2000-2011 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
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.
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.
45 * Redistribution and use in source and binary forms, with or without
46 * modification, are permitted provided that the following conditions
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.
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
73 * from: @(#)kern_exec.c 8.1 (Berkeley) 6/10/93
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,
81 #include <machine/reg.h>
82 #include <machine/cpu_capabilities.h>
84 #include <sys/param.h>
85 #include <sys/systm.h>
86 #include <sys/filedesc.h>
87 #include <sys/kernel.h>
88 #include <sys/proc_internal.h>
89 #include <sys/kauth.h>
91 #include <sys/socketvar.h>
92 #include <sys/malloc.h>
93 #include <sys/namei.h>
94 #include <sys/mount_internal.h>
95 #include <sys/vnode_internal.h>
96 #include <sys/file_internal.h>
98 #include <sys/uio_internal.h>
100 #include <sys/exec.h>
101 #include <sys/kdebug.h>
102 #include <sys/signal.h>
103 #include <sys/aio_kern.h>
104 #include <sys/sysproto.h>
106 #include <sys/shm_internal.h> /* shmexec() */
108 #include <sys/ubc_internal.h> /* ubc_map() */
109 #include <sys/spawn.h>
110 #include <sys/spawn_internal.h>
111 #include <sys/process_policy.h>
112 #include <sys/codesign.h>
113 #include <crypto/sha1.h>
115 #include <libkern/libkern.h>
117 #include <security/audit/audit.h>
119 #include <ipc/ipc_types.h>
121 #include <mach/mach_types.h>
122 #include <mach/port.h>
123 #include <mach/task.h>
124 #include <mach/task_access.h>
125 #include <mach/thread_act.h>
126 #include <mach/vm_map.h>
127 #include <mach/mach_vm.h>
128 #include <mach/vm_param.h>
130 #include <kern/sched_prim.h> /* thread_wakeup() */
131 #include <kern/affinity.h>
132 #include <kern/assert.h>
133 #include <kern/task.h>
134 #include <kern/coalition.h>
137 #include <security/mac.h>
138 #include <security/mac_mach_internal.h>
141 #include <vm/vm_map.h>
142 #include <vm/vm_kern.h>
143 #include <vm/vm_protos.h>
144 #include <vm/vm_kern.h>
145 #include <vm/vm_fault.h>
146 #include <vm/vm_pageout.h>
148 #include <kdp/kdp_dyld.h>
150 #include <machine/pal_routines.h>
152 #include <pexpert/pexpert.h>
154 #if CONFIG_MEMORYSTATUS
155 #include <sys/kern_memorystatus.h>
159 /* Do not include dtrace.h, it redefines kmem_[alloc/free] */
160 extern void (*dtrace_fasttrap_exec_ptr
)(proc_t
);
161 extern void (*dtrace_proc_waitfor_exec_ptr
)(proc_t
);
162 extern void (*dtrace_helpers_cleanup
)(proc_t
);
163 extern void dtrace_lazy_dofs_destroy(proc_t
);
166 * Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c,
167 * we will store its value before actually calling it.
169 static void (*dtrace_proc_waitfor_hook
)(proc_t
) = NULL
;
171 #include <sys/dtrace_ptss.h>
174 /* support for child creation in exec after vfork */
175 thread_t
fork_create_child(task_t parent_task
, coalition_t parent_coalition
, proc_t child_proc
, int inherit_memory
, int is64bit
);
176 void vfork_exit(proc_t p
, int rv
);
177 int setsigvec(proc_t
, thread_t
, int, struct __kern_sigaction
*, boolean_t in_sigstart
);
178 extern void proc_apply_task_networkbg_internal(proc_t
, thread_t
);
181 * Mach things for which prototypes are unavailable from Mach headers
185 void ipc_thread_reset(
187 kern_return_t
ipc_object_copyin(
189 mach_port_name_t name
,
190 mach_msg_type_name_t msgt_name
,
191 ipc_object_t
*objectp
);
192 void ipc_port_release_send(ipc_port_t
);
194 #if DEVELOPMENT || DEBUG
195 void task_importance_update_owner_info(task_t
);
198 extern struct savearea
*get_user_regs(thread_t
);
200 __attribute__((noinline
)) int __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port
, int32_t new_pid
);
202 #include <kern/thread.h>
203 #include <kern/task.h>
204 #include <kern/ast.h>
205 #include <kern/mach_loader.h>
206 #include <kern/mach_fat.h>
207 #include <mach-o/fat.h>
208 #include <mach-o/loader.h>
209 #include <machine/vmparam.h>
210 #include <sys/imgact.h>
216 * EAI_ITERLIMIT The maximum number of times to iterate an image
217 * activator in exec_activate_image() before treating
218 * it as malformed/corrupt.
220 #define EAI_ITERLIMIT 10
223 * For #! interpreter parsing
225 #define IS_WHITESPACE(ch) ((ch == ' ') || (ch == '\t'))
226 #define IS_EOL(ch) ((ch == '#') || (ch == '\n'))
228 extern vm_map_t bsd_pageable_map
;
229 extern const struct fileops vnops
;
231 #define ROUND_PTR(type, addr) \
232 (type *)( ( (uintptr_t)(addr) + 16 - 1) \
235 struct image_params
; /* Forward */
236 static int exec_activate_image(struct image_params
*imgp
);
237 static int exec_copyout_strings(struct image_params
*imgp
, user_addr_t
*stackp
);
238 static int load_return_to_errno(load_return_t lrtn
);
239 static int execargs_alloc(struct image_params
*imgp
);
240 static int execargs_free(struct image_params
*imgp
);
241 static int exec_check_permissions(struct image_params
*imgp
);
242 static int exec_extract_strings(struct image_params
*imgp
);
243 static int exec_add_apple_strings(struct image_params
*imgp
);
244 static int exec_handle_sugid(struct image_params
*imgp
);
245 static int sugid_scripts
= 0;
246 SYSCTL_INT (_kern
, OID_AUTO
, sugid_scripts
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &sugid_scripts
, 0, "");
247 static kern_return_t
create_unix_stack(vm_map_t map
, load_result_t
* load_result
, proc_t p
);
248 static int copyoutptr(user_addr_t ua
, user_addr_t ptr
, int ptr_size
);
249 static void exec_resettextvp(proc_t
, struct image_params
*);
250 static int check_for_signature(proc_t
, struct image_params
*);
251 static void exec_prefault_data(proc_t
, struct image_params
*, load_result_t
*);
252 static errno_t
exec_handle_port_actions(struct image_params
*imgp
, short psa_flags
, boolean_t
* portwatch_present
, ipc_port_t
* portwatch_ports
);
253 static errno_t
exec_handle_spawnattr_policy(proc_t p
, int psa_apptype
, uint64_t psa_qos_clamp
,
254 ipc_port_t
* portwatch_ports
, int portwatch_count
);
257 * exec_add_user_string
259 * Add the requested string to the string space area.
261 * Parameters; struct image_params * image parameter block
262 * user_addr_t string to add to strings area
263 * int segment from which string comes
264 * boolean_t TRUE if string contributes to NCARGS
267 * !0 Failure errno from copyinstr()
270 * (imgp->ip_strendp) updated location of next add, if any
271 * (imgp->ip_strspace) updated byte count of space remaining
272 * (imgp->ip_argspace) updated byte count of space in NCARGS
275 exec_add_user_string(struct image_params
*imgp
, user_addr_t str
, int seg
, boolean_t is_ncargs
)
284 space
= imgp
->ip_argspace
; /* by definition smaller than ip_strspace */
286 space
= imgp
->ip_strspace
;
293 if (!UIO_SEG_IS_USER_SPACE(seg
)) {
294 char *kstr
= CAST_DOWN(char *,str
); /* SAFE */
295 error
= copystr(kstr
, imgp
->ip_strendp
, space
, &len
);
297 error
= copyinstr(str
, imgp
->ip_strendp
, space
, &len
);
300 imgp
->ip_strendp
+= len
;
301 imgp
->ip_strspace
-= len
;
303 imgp
->ip_argspace
-= len
;
305 } while (error
== ENAMETOOLONG
);
313 * To support new app package launching for Mac OS X, the dyld needs the
314 * first argument to execve() stored on the user stack.
316 * Save the executable path name at the bottom of the strings area and set
317 * the argument vector pointer to the location following that to indicate
318 * the start of the argument and environment tuples, setting the remaining
319 * string space count to the size of the string area minus the path length.
321 * Parameters; struct image_params * image parameter block
322 * char * path used to invoke program
323 * int segment from which path comes
325 * Returns: int 0 Success
327 * copy[in]str:EFAULT Bad address
328 * copy[in]str:ENAMETOOLONG Filename too long
331 * (imgp->ip_strings) saved path
332 * (imgp->ip_strspace) space remaining in ip_strings
333 * (imgp->ip_strendp) start of remaining copy area
334 * (imgp->ip_argspace) space remaining of NCARGS
335 * (imgp->ip_applec) Initial applev[0]
337 * Note: We have to do this before the initial namei() since in the
338 * path contains symbolic links, namei() will overwrite the
339 * original path buffer contents. If the last symbolic link
340 * resolved was a relative pathname, we would lose the original
341 * "path", which could be an absolute pathname. This might be
342 * unacceptable for dyld.
345 exec_save_path(struct image_params
*imgp
, user_addr_t path
, int seg
)
351 len
= MIN(MAXPATHLEN
, imgp
->ip_strspace
);
354 case UIO_USERSPACE32
:
355 case UIO_USERSPACE64
: /* Same for copyin()... */
356 error
= copyinstr(path
, imgp
->ip_strings
, len
, &len
);
359 kpath
= CAST_DOWN(char *,path
); /* SAFE */
360 error
= copystr(kpath
, imgp
->ip_strings
, len
, &len
);
368 imgp
->ip_strendp
+= len
;
369 imgp
->ip_strspace
-= len
;
376 * exec_reset_save_path
378 * If we detect a shell script, we need to reset the string area
379 * state so that the interpreter can be saved onto the stack.
381 * Parameters; struct image_params * image parameter block
383 * Returns: int 0 Success
386 * (imgp->ip_strings) saved path
387 * (imgp->ip_strspace) space remaining in ip_strings
388 * (imgp->ip_strendp) start of remaining copy area
389 * (imgp->ip_argspace) space remaining of NCARGS
393 exec_reset_save_path(struct image_params
*imgp
)
395 imgp
->ip_strendp
= imgp
->ip_strings
;
396 imgp
->ip_argspace
= NCARGS
;
397 imgp
->ip_strspace
= ( NCARGS
+ PAGE_SIZE
);
405 * Image activator for interpreter scripts. If the image begins with the
406 * characters "#!", then it is an interpreter script. Verify that we are
407 * not already executing in PowerPC mode, and that the length of the script
408 * line indicating the interpreter is not in excess of the maximum allowed
409 * size. If this is the case, then break out the arguments, if any, which
410 * are separated by white space, and copy them into the argument save area
411 * as if they were provided on the command line before all other arguments.
412 * The line ends when we encounter a comment character ('#') or newline.
414 * Parameters; struct image_params * image parameter block
416 * Returns: -1 not an interpreter (keep looking)
417 * -3 Success: interpreter: relookup
418 * >0 Failure: interpreter: error number
420 * A return value other than -1 indicates subsequent image activators should
421 * not be given the opportunity to attempt to activate the image.
424 exec_shell_imgact(struct image_params
*imgp
)
426 char *vdata
= imgp
->ip_vdata
;
428 char *line_startp
, *line_endp
;
436 * Make sure it's a shell script. If we've already redirected
437 * from an interpreted file once, don't do it again.
439 * Note: We disallow PowerPC, since the expectation is that we
440 * may run a PowerPC interpreter, but not an interpret a PowerPC
441 * image. This is consistent with historical behaviour.
443 if (vdata
[0] != '#' ||
445 (imgp
->ip_flags
& IMGPF_INTERPRET
) != 0) {
449 imgp
->ip_flags
|= IMGPF_INTERPRET
;
450 imgp
->ip_interp_sugid_fd
= -1;
451 imgp
->ip_interp_buffer
[0] = '\0';
453 /* Check to see if SUGID scripts are permitted. If they aren't then
454 * clear the SUGID bits.
455 * imgp->ip_vattr is known to be valid.
457 if (sugid_scripts
== 0) {
458 imgp
->ip_origvattr
->va_mode
&= ~(VSUID
| VSGID
);
461 /* Try to find the first non-whitespace character */
462 for( ihp
= &vdata
[2]; ihp
< &vdata
[IMG_SHSIZE
]; ihp
++ ) {
464 /* Did not find interpreter, "#!\n" */
466 } else if (IS_WHITESPACE(*ihp
)) {
467 /* Whitespace, like "#! /bin/sh\n", keep going. */
469 /* Found start of interpreter */
474 if (ihp
== &vdata
[IMG_SHSIZE
]) {
475 /* All whitespace, like "#! " */
481 /* Try to find the end of the interpreter+args string */
482 for ( ; ihp
< &vdata
[IMG_SHSIZE
]; ihp
++ ) {
487 /* Still part of interpreter or args */
491 if (ihp
== &vdata
[IMG_SHSIZE
]) {
492 /* A long line, like "#! blah blah blah" without end */
496 /* Backtrack until we find the last non-whitespace */
497 while (IS_EOL(*ihp
) || IS_WHITESPACE(*ihp
)) {
501 /* The character after the last non-whitespace is our logical end of line */
505 * Now we have pointers to the usable part of:
507 * "#! /usr/bin/int first second third \n"
508 * ^ line_startp ^ line_endp
511 /* copy the interpreter name */
512 interp
= imgp
->ip_interp_buffer
;
513 for ( ihp
= line_startp
; (ihp
< line_endp
) && !IS_WHITESPACE(*ihp
); ihp
++)
517 exec_reset_save_path(imgp
);
518 exec_save_path(imgp
, CAST_USER_ADDR_T(imgp
->ip_interp_buffer
),
521 /* Copy the entire interpreter + args for later processing into argv[] */
522 interp
= imgp
->ip_interp_buffer
;
523 for ( ihp
= line_startp
; (ihp
< line_endp
); ihp
++)
528 * If we have a SUID oder SGID script, create a file descriptor
529 * from the vnode and pass /dev/fd/%d instead of the actual
530 * path name so that the script does not get opened twice
532 if (imgp
->ip_origvattr
->va_mode
& (VSUID
| VSGID
)) {
533 p
= vfs_context_proc(imgp
->ip_vfs_context
);
534 error
= falloc(p
, &fp
, &fd
, imgp
->ip_vfs_context
);
538 fp
->f_fglob
->fg_flag
= FREAD
;
539 fp
->f_fglob
->fg_ops
= &vnops
;
540 fp
->f_fglob
->fg_data
= (caddr_t
)imgp
->ip_vp
;
543 procfdtbl_releasefd(p
, fd
, NULL
);
544 fp_drop(p
, fd
, fp
, 1);
546 vnode_ref(imgp
->ip_vp
);
548 imgp
->ip_interp_sugid_fd
= fd
;
559 * Image activator for fat 1.0 binaries. If the binary is fat, then we
560 * need to select an image from it internally, and make that the image
561 * we are going to attempt to execute. At present, this consists of
562 * reloading the first page for the image with a first page from the
563 * offset location indicated by the fat header.
565 * Parameters; struct image_params * image parameter block
567 * Returns: -1 not a fat binary (keep looking)
568 * -2 Success: encapsulated binary: reread
569 * >0 Failure: error number
571 * Important: This image activator is byte order neutral.
573 * Note: A return value other than -1 indicates subsequent image
574 * activators should not be given the opportunity to attempt
575 * to activate the image.
577 * If we find an encapsulated binary, we make no assertions
578 * about its validity; instead, we leave that up to a rescan
579 * for an activator to claim it, and, if it is claimed by one,
580 * that activator is responsible for determining validity.
583 exec_fat_imgact(struct image_params
*imgp
)
585 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
586 kauth_cred_t cred
= kauth_cred_proc_ref(p
);
587 struct fat_header
*fat_header
= (struct fat_header
*)imgp
->ip_vdata
;
588 struct _posix_spawnattr
*psa
= NULL
;
589 struct fat_arch fat_arch
;
593 /* Make sure it's a fat binary */
594 if ((fat_header
->magic
!= FAT_MAGIC
) &&
595 (fat_header
->magic
!= FAT_CIGAM
)) {
600 #if DEVELOPMENT || DEBUG
601 if (cpu_type() == CPU_TYPE_ARM64
) {
602 uint32_t fat_nfat_arch
= OSSwapBigToHostInt32(fat_header
->nfat_arch
);
603 struct fat_arch
*archs
;
604 int vfexec
= (imgp
->ip_flags
& IMGPF_VFORK_EXEC
);
605 int spawn
= (imgp
->ip_flags
& IMGPF_SPAWN
);
607 archs
= (struct fat_arch
*)(imgp
->ip_vdata
+ sizeof(struct fat_header
));
609 /* ip_vdata always has PAGE_SIZE of data */
610 if (PAGE_SIZE
>= (sizeof(struct fat_header
) + (fat_nfat_arch
+ 1) * sizeof(struct fat_arch
))) {
611 if (fat_nfat_arch
> 0
612 && OSSwapBigToHostInt32(archs
[fat_nfat_arch
].cputype
) == CPU_TYPE_ARM64
) {
614 /* rdar://problem/15001727 */
615 printf("Attempt to execute malformed binary %s\n", imgp
->ip_strings
);
618 p
->p_csflags
|= CS_KILLED
;
622 * We can't stop the system call, so make sure the child never executes
623 * For vfork exec, the current implementation has not set up the thread in the
624 * child process, so we cannot signal it. Return an error code in that case.
626 if (!vfexec
&& !spawn
) {
638 /* If posix_spawn binprefs exist, respect those prefs. */
639 psa
= (struct _posix_spawnattr
*) imgp
->ip_px_sa
;
640 if (psa
!= NULL
&& psa
->psa_binprefs
[0] != 0) {
641 struct fat_arch
*arches
= (struct fat_arch
*) (fat_header
+ 1);
642 int nfat_arch
= 0, pr
= 0, f
= 0;
644 nfat_arch
= OSSwapBigToHostInt32(fat_header
->nfat_arch
);
645 /* Check each preference listed against all arches in header */
646 for (pr
= 0; pr
< NBINPREFS
; pr
++) {
647 cpu_type_t pref
= psa
->psa_binprefs
[pr
];
649 /* No suitable arch in the pref list */
654 if (pref
== CPU_TYPE_ANY
) {
655 /* Fall through to regular grading */
659 for (f
= 0; f
< nfat_arch
; f
++) {
660 cpu_type_t archtype
= OSSwapBigToHostInt32(
662 cpu_type_t archsubtype
= OSSwapBigToHostInt32(
663 arches
[f
].cpusubtype
) & ~CPU_SUBTYPE_MASK
;
664 if (pref
== archtype
&&
665 grade_binary(archtype
, archsubtype
)) {
666 /* We have a winner! */
667 fat_arch
.cputype
= archtype
;
668 fat_arch
.cpusubtype
= archsubtype
;
669 fat_arch
.offset
= OSSwapBigToHostInt32(
671 fat_arch
.size
= OSSwapBigToHostInt32(
673 fat_arch
.align
= OSSwapBigToHostInt32(
681 /* Look up our preferred architecture in the fat file. */
682 lret
= fatfile_getarch_affinity(imgp
->ip_vp
,
683 (vm_offset_t
)fat_header
,
685 (p
->p_flag
& P_AFFINITY
));
686 if (lret
!= LOAD_SUCCESS
) {
687 error
= load_return_to_errno(lret
);
692 /* Read the Mach-O header out of fat_arch */
693 error
= vn_rdwr(UIO_READ
, imgp
->ip_vp
, imgp
->ip_vdata
,
694 PAGE_SIZE
, fat_arch
.offset
,
695 UIO_SYSSPACE
, (IO_UNIT
|IO_NODELOCKED
),
701 /* Did we read a complete header? */
707 /* Success. Indicate we have identified an encapsulated binary */
709 imgp
->ip_arch_offset
= (user_size_t
)fat_arch
.offset
;
710 imgp
->ip_arch_size
= (user_size_t
)fat_arch
.size
;
713 kauth_cred_unref(&cred
);
720 * Image activator for mach-o 1.0 binaries.
722 * Parameters; struct image_params * image parameter block
724 * Returns: -1 not a fat binary (keep looking)
725 * -2 Success: encapsulated binary: reread
726 * >0 Failure: error number
727 * EBADARCH Mach-o binary, but with an unrecognized
729 * ENOMEM No memory for child process after -
730 * can only happen after vfork()
732 * Important: This image activator is NOT byte order neutral.
734 * Note: A return value other than -1 indicates subsequent image
735 * activators should not be given the opportunity to attempt
736 * to activate the image.
738 * TODO: More gracefully handle failures after vfork
741 exec_mach_imgact(struct image_params
*imgp
)
743 struct mach_header
*mach_header
= (struct mach_header
*)imgp
->ip_vdata
;
744 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
747 task_t new_task
= NULL
; /* protected by vfexec */
749 struct uthread
*uthread
;
750 vm_map_t old_map
= VM_MAP_NULL
;
753 load_result_t load_result
;
754 struct _posix_spawnattr
*psa
= NULL
;
755 int spawn
= (imgp
->ip_flags
& IMGPF_SPAWN
);
756 int vfexec
= (imgp
->ip_flags
& IMGPF_VFORK_EXEC
);
759 * make sure it's a Mach-O 1.0 or Mach-O 2.0 binary; the difference
760 * is a reserved field on the end, so for the most part, we can
761 * treat them as if they were identical. Reverse-endian Mach-O
762 * binaries are recognized but not compatible.
764 if ((mach_header
->magic
== MH_CIGAM
) ||
765 (mach_header
->magic
== MH_CIGAM_64
)) {
770 if ((mach_header
->magic
!= MH_MAGIC
) &&
771 (mach_header
->magic
!= MH_MAGIC_64
)) {
776 switch (mach_header
->filetype
) {
783 if (!imgp
->ip_origcputype
) {
784 imgp
->ip_origcputype
= mach_header
->cputype
;
785 imgp
->ip_origcpusubtype
= mach_header
->cpusubtype
;
788 task
= current_task();
789 thread
= current_thread();
790 uthread
= get_bsdthread_info(thread
);
792 if ((mach_header
->cputype
& CPU_ARCH_ABI64
) == CPU_ARCH_ABI64
)
793 imgp
->ip_flags
|= IMGPF_IS_64BIT
;
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) {
799 for (pr
= 0; pr
< NBINPREFS
; pr
++) {
800 cpu_type_t pref
= psa
->psa_binprefs
[pr
];
802 /* No suitable arch in the pref list */
807 if (pref
== CPU_TYPE_ANY
) {
808 /* Jump to regular grading */
812 if (pref
== imgp
->ip_origcputype
) {
813 /* We have a match! */
821 if (!grade_binary(imgp
->ip_origcputype
, imgp
->ip_origcpusubtype
& ~CPU_SUBTYPE_MASK
)) {
826 /* Copy in arguments/environment from the old process */
827 error
= exec_extract_strings(imgp
);
831 error
= exec_add_apple_strings(imgp
);
835 AUDIT_ARG(argv
, imgp
->ip_startargv
, imgp
->ip_argc
,
836 imgp
->ip_endargv
- imgp
->ip_startargv
);
837 AUDIT_ARG(envv
, imgp
->ip_endargv
, imgp
->ip_envc
,
838 imgp
->ip_endenvv
- imgp
->ip_endargv
);
841 * We are being called to activate an image subsequent to a vfork()
842 * operation; in this case, we know that our task, thread, and
843 * uthread are actually those of our parent, and our proc, which we
844 * obtained indirectly from the image_params vfs_context_t, is the
847 if (vfexec
|| spawn
) {
849 imgp
->ip_new_thread
= fork_create_child(task
, COALITION_NULL
, p
, FALSE
, (imgp
->ip_flags
& IMGPF_IS_64BIT
));
850 if (imgp
->ip_new_thread
== NULL
) {
856 /* reset local idea of thread, uthread, task */
857 thread
= imgp
->ip_new_thread
;
858 uthread
= get_bsdthread_info(thread
);
859 task
= new_task
= get_threadtask(thread
);
860 map
= get_task_map(task
);
866 * We set these flags here; this is OK, since if we fail after
867 * this point, we have already destroyed the parent process anyway.
869 task_set_dyld_info(task
, MACH_VM_MIN_ADDRESS
, 0);
870 if (imgp
->ip_flags
& IMGPF_IS_64BIT
) {
871 task_set_64bit(task
, TRUE
);
872 OSBitOrAtomic(P_LP64
, &p
->p_flag
);
874 task_set_64bit(task
, FALSE
);
875 OSBitAndAtomic(~((uint32_t)P_LP64
), &p
->p_flag
);
879 * Load the Mach-O file.
881 * NOTE: An error after this point indicates we have potentially
882 * destroyed or overwritten some process state while attempting an
883 * execve() following a vfork(), which is an unrecoverable condition.
884 * We send the new process an immediate SIGKILL to avoid it executing
885 * any instructions in the mutated address space. For true spawns,
886 * this is not the case, and "too late" is still not too late to
887 * return an error code to the parent process.
891 * Actually load the image file we previously decided to load.
893 lret
= load_machfile(imgp
, mach_header
, thread
, map
, &load_result
);
895 if (lret
!= LOAD_SUCCESS
) {
896 error
= load_return_to_errno(lret
);
901 p
->p_cputype
= imgp
->ip_origcputype
;
902 p
->p_cpusubtype
= imgp
->ip_origcpusubtype
;
905 vm_map_set_user_wire_limit(get_task_map(task
), p
->p_rlimit
[RLIMIT_MEMLOCK
].rlim_cur
);
908 * Set code-signing flags if this binary is signed, or if parent has
909 * requested them on exec.
911 if (load_result
.csflags
& CS_VALID
) {
912 imgp
->ip_csflags
|= load_result
.csflags
&
914 CS_HARD
|CS_KILL
|CS_ENFORCEMENT
|CS_REQUIRE_LV
|CS_DYLD_PLATFORM
|
915 CS_EXEC_SET_HARD
|CS_EXEC_SET_KILL
|CS_EXEC_SET_ENFORCEMENT
);
917 imgp
->ip_csflags
&= ~CS_VALID
;
920 if (p
->p_csflags
& CS_EXEC_SET_HARD
)
921 imgp
->ip_csflags
|= CS_HARD
;
922 if (p
->p_csflags
& CS_EXEC_SET_KILL
)
923 imgp
->ip_csflags
|= CS_KILL
;
924 if (p
->p_csflags
& CS_EXEC_SET_ENFORCEMENT
)
925 imgp
->ip_csflags
|= CS_ENFORCEMENT
;
926 if (p
->p_csflags
& CS_EXEC_SET_INSTALLER
)
927 imgp
->ip_csflags
|= CS_INSTALLER
;
931 * Set up the system reserved areas in the new address space.
933 vm_map_exec(get_task_map(task
),
935 (void *) p
->p_fd
->fd_rdir
,
939 * Close file descriptors which specify close-on-exec.
941 fdexec(p
, psa
!= NULL
? psa
->psa_flags
: 0);
944 * deal with set[ug]id.
946 error
= exec_handle_sugid(imgp
);
952 * deal with voucher on exec-calling thread.
954 if (imgp
->ip_new_thread
== NULL
)
955 thread_set_mach_voucher(current_thread(), IPC_VOUCHER_NULL
);
957 /* Make sure we won't interrupt ourself signalling a partial process */
958 if (!vfexec
&& !spawn
&& (p
->p_lflag
& P_LTRACED
))
961 if (load_result
.unixproc
&&
962 create_unix_stack(get_task_map(task
),
964 p
) != KERN_SUCCESS
) {
965 error
= load_return_to_errno(LOAD_NOSPACE
);
969 if (vfexec
|| spawn
) {
970 old_map
= vm_map_switch(get_task_map(task
));
973 if (load_result
.unixproc
) {
977 * Copy the strings area out into the new process address
981 error
= exec_copyout_strings(imgp
, &ap
);
984 vm_map_switch(old_map
);
988 thread_setuserstack(thread
, ap
);
991 if (load_result
.dynlinker
) {
993 int new_ptr_size
= (imgp
->ip_flags
& IMGPF_IS_64BIT
) ? 8 : 4;
995 /* Adjust the stack */
996 ap
= thread_adjuserstack(thread
, -new_ptr_size
);
997 error
= copyoutptr(load_result
.mach_header
, ap
, new_ptr_size
);
1000 if (vfexec
|| spawn
)
1001 vm_map_switch(old_map
);
1004 task_set_dyld_info(task
, load_result
.all_image_info_addr
,
1005 load_result
.all_image_info_size
);
1008 /* Avoid immediate VM faults back into kernel */
1009 exec_prefault_data(p
, imgp
, &load_result
);
1011 if (vfexec
|| spawn
) {
1012 vm_map_switch(old_map
);
1014 /* Set the entry point */
1015 thread_setentrypoint(thread
, load_result
.entry_point
);
1017 /* Stop profiling */
1021 * Reset signal state.
1023 execsigs(p
, thread
);
1026 * need to cancel async IO requests that can be cancelled and wait for those
1027 * already active. MAY BLOCK!
1032 /* FIXME: Till vmspace inherit is fixed: */
1033 if (!vfexec
&& p
->vm_shm
)
1037 /* Clean up the semaphores */
1042 * Remember file name for accounting.
1044 p
->p_acflag
&= ~AFORK
;
1045 /* If the translated name isn't NULL, then we want to use
1046 * that translated name as the name we show as the "real" name.
1047 * Otherwise, use the name passed into exec.
1049 if (0 != imgp
->ip_p_comm
[0]) {
1050 bcopy((caddr_t
)imgp
->ip_p_comm
, (caddr_t
)p
->p_comm
,
1053 if (imgp
->ip_ndp
->ni_cnd
.cn_namelen
> MAXCOMLEN
)
1054 imgp
->ip_ndp
->ni_cnd
.cn_namelen
= MAXCOMLEN
;
1055 bcopy((caddr_t
)imgp
->ip_ndp
->ni_cnd
.cn_nameptr
, (caddr_t
)p
->p_comm
,
1056 (unsigned)imgp
->ip_ndp
->ni_cnd
.cn_namelen
);
1057 p
->p_comm
[imgp
->ip_ndp
->ni_cnd
.cn_namelen
] = '\0';
1060 pal_dbg_set_task_name( p
->task
);
1062 #if DEVELOPMENT || DEBUG
1064 * Update the pid an proc name for importance base if any
1066 task_importance_update_owner_info(p
->task
);
1069 memcpy(&p
->p_uuid
[0], &load_result
.uuid
[0], sizeof(p
->p_uuid
));
1071 // <rdar://6598155> dtrace code cleanup needed
1074 * Invalidate any predicate evaluation already cached for this thread by DTrace.
1075 * That's because we've just stored to p_comm and DTrace refers to that when it
1076 * evaluates the "execname" special variable. uid and gid may have changed as well.
1078 dtrace_set_thread_predcache(current_thread(), 0);
1081 * Free any outstanding lazy dof entries. It is imperative we
1082 * always call dtrace_lazy_dofs_destroy, rather than null check
1083 * and call if !NULL. If we NULL test, during lazy dof faulting
1084 * we can race with the faulting code and proceed from here to
1085 * beyond the helpers cleanup. The lazy dof faulting will then
1086 * install new helpers which no longer belong to this process!
1088 dtrace_lazy_dofs_destroy(p
);
1092 * Clean up any DTrace helpers for the process.
1094 if (p
->p_dtrace_helpers
!= NULL
&& dtrace_helpers_cleanup
) {
1095 (*dtrace_helpers_cleanup
)(p
);
1099 * Cleanup the DTrace provider associated with this process.
1102 if (p
->p_dtrace_probes
&& dtrace_fasttrap_exec_ptr
) {
1103 (*dtrace_fasttrap_exec_ptr
)(p
);
1108 if (kdebug_enable
) {
1109 long dbg_arg1
, dbg_arg2
, dbg_arg3
, dbg_arg4
;
1112 * Collect the pathname for tracing
1114 kdbg_trace_string(p
, &dbg_arg1
, &dbg_arg2
, &dbg_arg3
, &dbg_arg4
);
1116 if (vfexec
|| spawn
) {
1117 KERNEL_DEBUG_CONSTANT1((TRACEDBG_CODE(DBG_TRACE_DATA
, 2)) | DBG_FUNC_NONE
,
1118 p
->p_pid
,0,0,0, (uintptr_t)thread_tid(thread
));
1119 KERNEL_DEBUG_CONSTANT1((TRACEDBG_CODE(DBG_TRACE_STRING
, 2)) | DBG_FUNC_NONE
,
1120 dbg_arg1
, dbg_arg2
, dbg_arg3
, dbg_arg4
, (uintptr_t)thread_tid(thread
));
1122 KERNEL_DEBUG_CONSTANT((TRACEDBG_CODE(DBG_TRACE_DATA
, 2)) | DBG_FUNC_NONE
,
1124 KERNEL_DEBUG_CONSTANT((TRACEDBG_CODE(DBG_TRACE_STRING
, 2)) | DBG_FUNC_NONE
,
1125 dbg_arg1
, dbg_arg2
, dbg_arg3
, dbg_arg4
, 0);
1130 * Ensure the 'translated' and 'affinity' flags are cleared, since we
1131 * no longer run PowerPC binaries.
1133 OSBitAndAtomic(~((uint32_t)(P_TRANSLATED
| P_AFFINITY
)), &p
->p_flag
);
1136 * If posix_spawned with the START_SUSPENDED flag, stop the
1137 * process before it runs.
1139 if (imgp
->ip_px_sa
!= NULL
) {
1140 psa
= (struct _posix_spawnattr
*) imgp
->ip_px_sa
;
1141 if (psa
->psa_flags
& POSIX_SPAWN_START_SUSPENDED
) {
1145 (void) task_suspend(p
->task
);
1150 * mark as execed, wakeup the process that vforked (if any) and tell
1151 * it that it now has its own resources back
1153 OSBitOrAtomic(P_EXEC
, &p
->p_flag
);
1154 proc_resetregister(p
);
1155 if (p
->p_pptr
&& (p
->p_lflag
& P_LPPWAIT
)) {
1157 p
->p_lflag
&= ~P_LPPWAIT
;
1159 wakeup((caddr_t
)p
->p_pptr
);
1163 * Pay for our earlier safety; deliver the delayed signals from
1164 * the incomplete vfexec process now that it's complete.
1166 if (vfexec
&& (p
->p_lflag
& P_LTRACED
)) {
1167 psignal_vfork(p
, new_task
, thread
, SIGTRAP
);
1173 /* Don't allow child process to execute any instructions */
1176 psignal_vfork(p
, new_task
, thread
, SIGKILL
);
1178 psignal(p
, SIGKILL
);
1181 /* We can't stop this system call at this point, so just pretend we succeeded */
1187 /* notify only if it has not failed due to FP Key error */
1188 if ((p
->p_lflag
& P_LTERM_DECRYPTFAIL
) == 0)
1189 proc_knote(p
, NOTE_EXEC
);
1192 /* Drop extra references for cases where we don't expect the caller to clean up */
1193 if (vfexec
|| (spawn
&& error
== 0)) {
1194 task_deallocate(new_task
);
1195 thread_deallocate(thread
);
1206 * Our image activator table; this is the table of the image types we are
1207 * capable of loading. We list them in order of preference to ensure the
1208 * fastest image load speed.
1210 * XXX hardcoded, for now; should use linker sets
1213 int (*ex_imgact
)(struct image_params
*);
1214 const char *ex_name
;
1216 { exec_mach_imgact
, "Mach-o Binary" },
1217 { exec_fat_imgact
, "Fat Binary" },
1218 { exec_shell_imgact
, "Interpreter Script" },
1224 * exec_activate_image
1226 * Description: Iterate through the available image activators, and activate
1227 * the image associated with the imgp structure. We start with
1230 * Parameters: struct image_params * Image parameter block
1232 * Returns: 0 Success
1233 * EBADEXEC The executable is corrupt/unknown
1234 * execargs_alloc:EINVAL Invalid argument
1235 * execargs_alloc:EACCES Permission denied
1236 * execargs_alloc:EINTR Interrupted function
1237 * execargs_alloc:ENOMEM Not enough space
1238 * exec_save_path:EFAULT Bad address
1239 * exec_save_path:ENAMETOOLONG Filename too long
1240 * exec_check_permissions:EACCES Permission denied
1241 * exec_check_permissions:ENOEXEC Executable file format error
1242 * exec_check_permissions:ETXTBSY Text file busy [misuse of error code]
1243 * exec_check_permissions:???
1245 * vn_rdwr:??? [anything vn_rdwr can return]
1246 * <ex_imgact>:??? [anything an imgact can return]
1249 exec_activate_image(struct image_params
*imgp
)
1251 struct nameidata
*ndp
= NULL
;
1254 int once
= 1; /* save SGUID-ness for interpreted files */
1256 int iterlimit
= EAI_ITERLIMIT
;
1257 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
1259 error
= execargs_alloc(imgp
);
1263 error
= exec_save_path(imgp
, imgp
->ip_user_fname
, imgp
->ip_seg
);
1268 /* Use imgp->ip_strings, which contains the copyin-ed exec path */
1269 DTRACE_PROC1(exec
, uintptr_t, imgp
->ip_strings
);
1271 MALLOC(ndp
, struct nameidata
*, sizeof(*ndp
), M_TEMP
, M_WAITOK
| M_ZERO
);
1277 NDINIT(ndp
, LOOKUP
, OP_LOOKUP
, FOLLOW
| LOCKLEAF
| AUDITVNPATH1
,
1278 UIO_SYSSPACE
, CAST_USER_ADDR_T(imgp
->ip_strings
), imgp
->ip_vfs_context
);
1284 imgp
->ip_ndp
= ndp
; /* successful namei(); call nameidone() later */
1285 imgp
->ip_vp
= ndp
->ni_vp
; /* if set, need to vnode_put() at some point */
1288 * Before we start the transition from binary A to binary B, make
1289 * sure another thread hasn't started exiting the process. We grab
1290 * the proc lock to check p_lflag initially, and the transition
1291 * mechanism ensures that the value doesn't change after we release
1295 if (p
->p_lflag
& P_LEXIT
) {
1299 error
= proc_transstart(p
, 1, 0);
1304 error
= exec_check_permissions(imgp
);
1308 /* Copy; avoid invocation of an interpreter overwriting the original */
1311 *imgp
->ip_origvattr
= *imgp
->ip_vattr
;
1314 error
= vn_rdwr(UIO_READ
, imgp
->ip_vp
, imgp
->ip_vdata
, PAGE_SIZE
, 0,
1315 UIO_SYSSPACE
, IO_NODELOCKED
,
1316 vfs_context_ucred(imgp
->ip_vfs_context
),
1317 &resid
, vfs_context_proc(imgp
->ip_vfs_context
));
1321 encapsulated_binary
:
1322 /* Limit the number of iterations we will attempt on each binary */
1323 if (--iterlimit
== 0) {
1328 for(i
= 0; error
== -1 && execsw
[i
].ex_imgact
!= NULL
; i
++) {
1330 error
= (*execsw
[i
].ex_imgact
)(imgp
);
1333 /* case -1: not claimed: continue */
1334 case -2: /* Encapsulated binary */
1335 goto encapsulated_binary
;
1337 case -3: /* Interpreter */
1340 * Copy the script label for later use. Note that
1341 * the label can be different when the script is
1342 * actually read by the interpreter.
1344 if (imgp
->ip_scriptlabelp
)
1345 mac_vnode_label_free(imgp
->ip_scriptlabelp
);
1346 imgp
->ip_scriptlabelp
= mac_vnode_label_alloc();
1347 if (imgp
->ip_scriptlabelp
== NULL
) {
1351 mac_vnode_label_copy(imgp
->ip_vp
->v_label
,
1352 imgp
->ip_scriptlabelp
);
1355 * Take a ref of the script vnode for later use.
1357 if (imgp
->ip_scriptvp
)
1358 vnode_put(imgp
->ip_scriptvp
);
1359 if (vnode_getwithref(imgp
->ip_vp
) == 0)
1360 imgp
->ip_scriptvp
= imgp
->ip_vp
;
1365 vnode_put(imgp
->ip_vp
);
1366 imgp
->ip_vp
= NULL
; /* already put */
1367 imgp
->ip_ndp
= NULL
; /* already nameidone */
1369 /* Use imgp->ip_strings, which exec_shell_imgact reset to the interpreter */
1370 NDINIT(ndp
, LOOKUP
, OP_LOOKUP
, FOLLOW
| LOCKLEAF
,
1371 UIO_SYSSPACE
, CAST_USER_ADDR_T(imgp
->ip_strings
), imgp
->ip_vfs_context
);
1373 proc_transend(p
, 0);
1382 * Call out to allow 3rd party notification of exec.
1383 * Ignore result of kauth_authorize_fileop call.
1385 if (error
== 0 && kauth_authorize_fileop_has_listeners()) {
1386 kauth_authorize_fileop(vfs_context_ucred(imgp
->ip_vfs_context
),
1388 (uintptr_t)ndp
->ni_vp
, 0);
1392 proc_transend(p
, 0);
1395 if (imgp
->ip_strings
)
1396 execargs_free(imgp
);
1398 nameidone(imgp
->ip_ndp
);
1407 * exec_handle_spawnattr_policy
1409 * Description: Decode and apply the posix_spawn apptype, qos clamp, and watchport ports to the task.
1411 * Parameters: proc_t p process to apply attributes to
1412 * int psa_apptype posix spawn attribute apptype
1414 * Returns: 0 Success
1417 exec_handle_spawnattr_policy(proc_t p
, int psa_apptype
, uint64_t psa_qos_clamp
,
1418 ipc_port_t
* portwatch_ports
, int portwatch_count
)
1420 int apptype
= TASK_APPTYPE_NONE
;
1421 int qos_clamp
= THREAD_QOS_UNSPECIFIED
;
1423 if ((psa_apptype
& POSIX_SPAWN_PROC_TYPE_MASK
) != 0) {
1424 int proctype
= psa_apptype
& POSIX_SPAWN_PROC_TYPE_MASK
;
1427 case POSIX_SPAWN_PROC_TYPE_DAEMON_INTERACTIVE
:
1428 apptype
= TASK_APPTYPE_DAEMON_INTERACTIVE
;
1430 case POSIX_SPAWN_PROC_TYPE_DAEMON_STANDARD
:
1431 apptype
= TASK_APPTYPE_DAEMON_STANDARD
;
1433 case POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE
:
1434 apptype
= TASK_APPTYPE_DAEMON_ADAPTIVE
;
1436 case POSIX_SPAWN_PROC_TYPE_DAEMON_BACKGROUND
:
1437 apptype
= TASK_APPTYPE_DAEMON_BACKGROUND
;
1439 case POSIX_SPAWN_PROC_TYPE_APP_DEFAULT
:
1440 apptype
= TASK_APPTYPE_APP_DEFAULT
;
1442 case POSIX_SPAWN_PROC_TYPE_APP_TAL
:
1443 apptype
= TASK_APPTYPE_APP_TAL
;
1446 apptype
= TASK_APPTYPE_NONE
;
1447 /* TODO: Should an invalid value here fail the spawn? */
1452 if (psa_qos_clamp
!= POSIX_SPAWN_PROC_CLAMP_NONE
) {
1453 switch (psa_qos_clamp
) {
1454 case POSIX_SPAWN_PROC_CLAMP_UTILITY
:
1455 qos_clamp
= THREAD_QOS_UTILITY
;
1457 case POSIX_SPAWN_PROC_CLAMP_BACKGROUND
:
1458 qos_clamp
= THREAD_QOS_BACKGROUND
;
1460 case POSIX_SPAWN_PROC_CLAMP_MAINTENANCE
:
1461 qos_clamp
= THREAD_QOS_MAINTENANCE
;
1464 qos_clamp
= THREAD_QOS_UNSPECIFIED
;
1465 /* TODO: Should an invalid value here fail the spawn? */
1470 if (psa_apptype
!= TASK_APPTYPE_NONE
|| qos_clamp
!= THREAD_QOS_UNSPECIFIED
) {
1471 proc_set_task_spawnpolicy(p
->task
, apptype
, qos_clamp
,
1472 portwatch_ports
, portwatch_count
);
1480 * exec_handle_port_actions
1482 * Description: Go through the _posix_port_actions_t contents,
1483 * calling task_set_special_port, task_set_exception_ports
1484 * and/or audit_session_spawnjoin for the current task.
1486 * Parameters: struct image_params * Image parameter block
1487 * short psa_flags posix spawn attribute flags
1489 * Returns: 0 Success
1491 * ENOTSUP Illegal posix_spawn attr flag was set
1494 exec_handle_port_actions(struct image_params
*imgp
, short psa_flags
, boolean_t
* portwatch_present
, ipc_port_t
* portwatch_ports
)
1496 _posix_spawn_port_actions_t pacts
= imgp
->ip_px_spa
;
1497 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
1498 _ps_port_action_t
*act
= NULL
;
1499 task_t task
= p
->task
;
1500 ipc_port_t port
= NULL
;
1504 *portwatch_present
= FALSE
;
1506 for (i
= 0; i
< pacts
->pspa_count
; i
++) {
1507 act
= &pacts
->pspa_actions
[i
];
1509 if (ipc_object_copyin(get_task_ipcspace(current_task()),
1510 act
->new_port
, MACH_MSG_TYPE_COPY_SEND
,
1511 (ipc_object_t
*) &port
) != KERN_SUCCESS
) {
1516 switch (act
->port_type
) {
1518 /* Only allowed when not under vfork */
1519 if (!(psa_flags
& POSIX_SPAWN_SETEXEC
))
1521 else if (task_set_special_port(task
,
1522 act
->which
, port
) != KERN_SUCCESS
)
1526 case PSPA_EXCEPTION
:
1527 /* Only allowed when not under vfork */
1528 if (!(psa_flags
& POSIX_SPAWN_SETEXEC
))
1530 else if (task_set_exception_ports(task
,
1531 act
->mask
, port
, act
->behavior
,
1532 act
->flavor
) != KERN_SUCCESS
)
1536 case PSPA_AU_SESSION
:
1537 ret
= audit_session_spawnjoin(p
, port
);
1540 case PSPA_IMP_WATCHPORTS
:
1541 if (portwatch_ports
!= NULL
) {
1542 *portwatch_present
= TRUE
;
1543 /* hold on to this till end of spawn */
1544 portwatch_ports
[i
] = port
;
1547 ipc_port_release_send(port
);
1554 /* action failed, so release port resources */
1557 ipc_port_release_send(port
);
1564 DTRACE_PROC1(spawn__port__failure
, mach_port_name_t
, act
->new_port
);
1569 * exec_handle_file_actions
1571 * Description: Go through the _posix_file_actions_t contents applying the
1572 * open, close, and dup2 operations to the open file table for
1573 * the current process.
1575 * Parameters: struct image_params * Image parameter block
1577 * Returns: 0 Success
1580 * Note: Actions are applied in the order specified, with the credential
1581 * of the parent process. This is done to permit the parent
1582 * process to utilize POSIX_SPAWN_RESETIDS to drop privilege in
1583 * the child following operations the child may in fact not be
1584 * normally permitted to perform.
1587 exec_handle_file_actions(struct image_params
*imgp
, short psa_flags
)
1591 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
1592 _posix_spawn_file_actions_t px_sfap
= imgp
->ip_px_sfa
;
1593 int ival
[2]; /* dummy retval for system calls) */
1595 for (action
= 0; action
< px_sfap
->psfa_act_count
; action
++) {
1596 _psfa_action_t
*psfa
= &px_sfap
->psfa_act_acts
[ action
];
1598 switch(psfa
->psfaa_type
) {
1601 * Open is different, in that it requires the use of
1602 * a path argument, which is normally copied in from
1603 * user space; because of this, we have to support an
1604 * open from kernel space that passes an address space
1605 * context of UIO_SYSSPACE, and casts the address
1606 * argument to a user_addr_t.
1609 struct vnode_attr
*vap
;
1610 struct nameidata
*ndp
;
1611 int mode
= psfa
->psfaa_openargs
.psfao_mode
;
1612 struct dup2_args dup2a
;
1613 struct close_nocancel_args ca
;
1616 MALLOC(bufp
, char *, sizeof(*vap
) + sizeof(*ndp
), M_TEMP
, M_WAITOK
| M_ZERO
);
1622 vap
= (struct vnode_attr
*) bufp
;
1623 ndp
= (struct nameidata
*) (bufp
+ sizeof(*vap
));
1626 /* Mask off all but regular access permissions */
1627 mode
= ((mode
&~ p
->p_fd
->fd_cmask
) & ALLPERMS
) & ~S_ISTXT
;
1628 VATTR_SET(vap
, va_mode
, mode
& ACCESSPERMS
);
1630 NDINIT(ndp
, LOOKUP
, OP_OPEN
, FOLLOW
| AUDITVNPATH1
, UIO_SYSSPACE
,
1631 CAST_USER_ADDR_T(psfa
->psfaa_openargs
.psfao_path
),
1632 imgp
->ip_vfs_context
);
1634 error
= open1(imgp
->ip_vfs_context
,
1636 psfa
->psfaa_openargs
.psfao_oflag
,
1638 fileproc_alloc_init
, NULL
,
1644 * If there's an error, or we get the right fd by
1645 * accident, then drop out here. This is easier than
1646 * reworking all the open code to preallocate fd
1647 * slots, and internally taking one as an argument.
1649 if (error
|| ival
[0] == psfa
->psfaa_filedes
)
1654 * If we didn't fall out from an error, we ended up
1655 * with the wrong fd; so now we've got to try to dup2
1656 * it to the right one.
1658 dup2a
.from
= origfd
;
1659 dup2a
.to
= psfa
->psfaa_filedes
;
1662 * The dup2() system call implementation sets
1663 * ival to newfd in the success case, but we
1664 * can ignore that, since if we didn't get the
1665 * fd we wanted, the error will stop us.
1667 error
= dup2(p
, &dup2a
, ival
);
1672 * Finally, close the original fd.
1676 error
= close_nocancel(p
, &ca
, ival
);
1681 struct dup2_args dup2a
;
1683 dup2a
.from
= psfa
->psfaa_filedes
;
1684 dup2a
.to
= psfa
->psfaa_openargs
.psfao_oflag
;
1687 * The dup2() system call implementation sets
1688 * ival to newfd in the success case, but we
1689 * can ignore that, since if we didn't get the
1690 * fd we wanted, the error will stop us.
1692 error
= dup2(p
, &dup2a
, ival
);
1697 struct close_nocancel_args ca
;
1699 ca
.fd
= psfa
->psfaa_filedes
;
1701 error
= close_nocancel(p
, &ca
, ival
);
1705 case PSFA_INHERIT
: {
1706 struct fcntl_nocancel_args fcntla
;
1709 * Check to see if the descriptor exists, and
1710 * ensure it's -not- marked as close-on-exec.
1712 * Attempting to "inherit" a guarded fd will
1713 * result in a error.
1715 fcntla
.fd
= psfa
->psfaa_filedes
;
1716 fcntla
.cmd
= F_GETFD
;
1717 if ((error
= fcntl_nocancel(p
, &fcntla
, ival
)) != 0)
1720 if ((ival
[0] & FD_CLOEXEC
) == FD_CLOEXEC
) {
1721 fcntla
.fd
= psfa
->psfaa_filedes
;
1722 fcntla
.cmd
= F_SETFD
;
1723 fcntla
.arg
= ival
[0] & ~FD_CLOEXEC
;
1724 error
= fcntl_nocancel(p
, &fcntla
, ival
);
1735 /* All file actions failures are considered fatal, per POSIX */
1738 if (PSFA_OPEN
== psfa
->psfaa_type
) {
1739 DTRACE_PROC1(spawn__open__failure
, uintptr_t,
1740 psfa
->psfaa_openargs
.psfao_path
);
1742 DTRACE_PROC1(spawn__fd__failure
, int, psfa
->psfaa_filedes
);
1748 if (error
!= 0 || (psa_flags
& POSIX_SPAWN_CLOEXEC_DEFAULT
) == 0)
1752 * If POSIX_SPAWN_CLOEXEC_DEFAULT is set, behave (during
1753 * this spawn only) as if "close on exec" is the default
1754 * disposition of all pre-existing file descriptors. In this case,
1755 * the list of file descriptors mentioned in the file actions
1756 * are the only ones that can be inherited, so mark them now.
1758 * The actual closing part comes later, in fdexec().
1761 for (action
= 0; action
< px_sfap
->psfa_act_count
; action
++) {
1762 _psfa_action_t
*psfa
= &px_sfap
->psfa_act_acts
[action
];
1763 int fd
= psfa
->psfaa_filedes
;
1765 switch (psfa
->psfaa_type
) {
1767 fd
= psfa
->psfaa_openargs
.psfao_oflag
;
1771 *fdflags(p
, fd
) |= UF_INHERIT
;
1785 * exec_spawnattr_getmacpolicyinfo
1788 exec_spawnattr_getmacpolicyinfo(const void *macextensions
, const char *policyname
, size_t *lenp
)
1790 const struct _posix_spawn_mac_policy_extensions
*psmx
= macextensions
;
1796 for (i
= 0; i
< psmx
->psmx_count
; i
++) {
1797 const _ps_mac_policy_extension_t
*extension
= &psmx
->psmx_extensions
[i
];
1798 if (strncmp(extension
->policyname
, policyname
, sizeof(extension
->policyname
)) == 0) {
1800 *lenp
= extension
->datalen
;
1801 return extension
->datap
;
1811 spawn_copyin_macpolicyinfo(const struct user__posix_spawn_args_desc
*px_args
, _posix_spawn_mac_policy_extensions_t
*psmxp
)
1813 _posix_spawn_mac_policy_extensions_t psmx
= NULL
;
1820 if (px_args
->mac_extensions_size
< PS_MAC_EXTENSIONS_SIZE(1) ||
1821 px_args
->mac_extensions_size
> PAGE_SIZE
) {
1826 MALLOC(psmx
, _posix_spawn_mac_policy_extensions_t
, px_args
->mac_extensions_size
, M_TEMP
, M_WAITOK
);
1827 if ((error
= copyin(px_args
->mac_extensions
, psmx
, px_args
->mac_extensions_size
)) != 0)
1830 if (PS_MAC_EXTENSIONS_SIZE(psmx
->psmx_count
) > px_args
->mac_extensions_size
) {
1835 for (i
= 0; i
< psmx
->psmx_count
; i
++) {
1836 _ps_mac_policy_extension_t
*extension
= &psmx
->psmx_extensions
[i
];
1837 if (extension
->datalen
== 0 || extension
->datalen
> PAGE_SIZE
) {
1843 for (copycnt
= 0; copycnt
< psmx
->psmx_count
; copycnt
++) {
1844 _ps_mac_policy_extension_t
*extension
= &psmx
->psmx_extensions
[copycnt
];
1847 MALLOC(data
, void *, extension
->datalen
, M_TEMP
, M_WAITOK
);
1848 if ((error
= copyin(extension
->data
, data
, extension
->datalen
)) != 0) {
1852 extension
->datap
= data
;
1860 for (i
= 0; i
< copycnt
; i
++)
1861 FREE(psmx
->psmx_extensions
[i
].datap
, M_TEMP
);
1868 spawn_free_macpolicyinfo(_posix_spawn_mac_policy_extensions_t psmx
)
1874 for (i
= 0; i
< psmx
->psmx_count
; i
++)
1875 FREE(psmx
->psmx_extensions
[i
].datap
, M_TEMP
);
1878 #endif /* CONFIG_MACF */
1883 * Parameters: uap->pid Pointer to pid return area
1884 * uap->fname File name to exec
1885 * uap->argp Argument list
1886 * uap->envp Environment list
1888 * Returns: 0 Success
1889 * EINVAL Invalid argument
1890 * ENOTSUP Not supported
1891 * ENOEXEC Executable file format error
1892 * exec_activate_image:EINVAL Invalid argument
1893 * exec_activate_image:EACCES Permission denied
1894 * exec_activate_image:EINTR Interrupted function
1895 * exec_activate_image:ENOMEM Not enough space
1896 * exec_activate_image:EFAULT Bad address
1897 * exec_activate_image:ENAMETOOLONG Filename too long
1898 * exec_activate_image:ENOEXEC Executable file format error
1899 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
1900 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
1901 * exec_activate_image:???
1902 * mac_execve_enter:???
1904 * TODO: Expect to need __mac_posix_spawn() at some point...
1905 * Handle posix_spawnattr_t
1906 * Handle posix_spawn_file_actions_t
1909 posix_spawn(proc_t ap
, struct posix_spawn_args
*uap
, int32_t *retval
)
1911 proc_t p
= ap
; /* quiet bogus GCC vfork() warning */
1912 user_addr_t pid
= uap
->pid
;
1913 int ival
[2]; /* dummy retval for setpgid() */
1915 struct image_params
*imgp
;
1916 struct vnode_attr
*vap
;
1917 struct vnode_attr
*origvap
;
1918 struct uthread
*uthread
= 0; /* compiler complains if not set to 0*/
1920 char alt_p_comm
[sizeof(p
->p_comm
)] = {0}; /* for PowerPC */
1921 int is_64
= IS_64BIT_PROCESS(p
);
1922 struct vfs_context context
;
1923 struct user__posix_spawn_args_desc px_args
;
1924 struct _posix_spawnattr px_sa
;
1925 _posix_spawn_file_actions_t px_sfap
= NULL
;
1926 _posix_spawn_port_actions_t px_spap
= NULL
;
1927 struct __kern_sigaction vec
;
1928 boolean_t spawn_no_exec
= FALSE
;
1929 boolean_t proc_transit_set
= TRUE
;
1930 boolean_t exec_done
= FALSE
;
1931 int portwatch_count
= 0;
1932 ipc_port_t
* portwatch_ports
= NULL
;
1933 vm_size_t px_sa_offset
= offsetof(struct _posix_spawnattr
, psa_ports
);
1936 * Allocate a big chunk for locals instead of using stack since these
1937 * structures are pretty big.
1939 MALLOC(bufp
, char *, (sizeof(*imgp
) + sizeof(*vap
) + sizeof(*origvap
)), M_TEMP
, M_WAITOK
| M_ZERO
);
1940 imgp
= (struct image_params
*) bufp
;
1945 vap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
));
1946 origvap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
) + sizeof(*vap
));
1948 /* Initialize the common data in the image_params structure */
1949 imgp
->ip_user_fname
= uap
->path
;
1950 imgp
->ip_user_argv
= uap
->argv
;
1951 imgp
->ip_user_envv
= uap
->envp
;
1952 imgp
->ip_vattr
= vap
;
1953 imgp
->ip_origvattr
= origvap
;
1954 imgp
->ip_vfs_context
= &context
;
1955 imgp
->ip_flags
= (is_64
? IMGPF_WAS_64BIT
: IMGPF_NONE
);
1956 imgp
->ip_p_comm
= alt_p_comm
; /* for PowerPC */
1957 imgp
->ip_seg
= (is_64
? UIO_USERSPACE64
: UIO_USERSPACE32
);
1958 imgp
->ip_mac_return
= 0;
1960 if (uap
->adesc
!= USER_ADDR_NULL
) {
1962 error
= copyin(uap
->adesc
, &px_args
, sizeof(px_args
));
1964 struct user32__posix_spawn_args_desc px_args32
;
1966 error
= copyin(uap
->adesc
, &px_args32
, sizeof(px_args32
));
1969 * Convert arguments descriptor from external 32 bit
1970 * representation to internal 64 bit representation
1972 px_args
.attr_size
= px_args32
.attr_size
;
1973 px_args
.attrp
= CAST_USER_ADDR_T(px_args32
.attrp
);
1974 px_args
.file_actions_size
= px_args32
.file_actions_size
;
1975 px_args
.file_actions
= CAST_USER_ADDR_T(px_args32
.file_actions
);
1976 px_args
.port_actions_size
= px_args32
.port_actions_size
;
1977 px_args
.port_actions
= CAST_USER_ADDR_T(px_args32
.port_actions
);
1978 px_args
.mac_extensions_size
= px_args32
.mac_extensions_size
;
1979 px_args
.mac_extensions
= CAST_USER_ADDR_T(px_args32
.mac_extensions
);
1984 if (px_args
.attr_size
!= 0) {
1986 * We are not copying the port_actions pointer,
1987 * because we already have it from px_args.
1988 * This is a bit fragile: <rdar://problem/16427422>
1991 if ((error
= copyin(px_args
.attrp
, &px_sa
, px_sa_offset
) != 0))
1994 bzero( (void *)( (unsigned long) &px_sa
+ px_sa_offset
), sizeof(px_sa
) - px_sa_offset
);
1996 imgp
->ip_px_sa
= &px_sa
;
1998 if (px_args
.file_actions_size
!= 0) {
1999 /* Limit file_actions to allowed number of open files */
2000 int maxfa
= (p
->p_limit
? p
->p_rlimit
[RLIMIT_NOFILE
].rlim_cur
: NOFILE
);
2001 if (px_args
.file_actions_size
< PSF_ACTIONS_SIZE(1) ||
2002 px_args
.file_actions_size
> PSF_ACTIONS_SIZE(maxfa
)) {
2006 MALLOC(px_sfap
, _posix_spawn_file_actions_t
, px_args
.file_actions_size
, M_TEMP
, M_WAITOK
);
2007 if (px_sfap
== NULL
) {
2011 imgp
->ip_px_sfa
= px_sfap
;
2013 if ((error
= copyin(px_args
.file_actions
, px_sfap
,
2014 px_args
.file_actions_size
)) != 0)
2017 /* Verify that the action count matches the struct size */
2018 if (PSF_ACTIONS_SIZE(px_sfap
->psfa_act_count
) != px_args
.file_actions_size
) {
2023 if (px_args
.port_actions_size
!= 0) {
2024 /* Limit port_actions to one page of data */
2025 if (px_args
.port_actions_size
< PS_PORT_ACTIONS_SIZE(1) ||
2026 px_args
.port_actions_size
> PAGE_SIZE
) {
2031 MALLOC(px_spap
, _posix_spawn_port_actions_t
,
2032 px_args
.port_actions_size
, M_TEMP
, M_WAITOK
);
2033 if (px_spap
== NULL
) {
2037 imgp
->ip_px_spa
= px_spap
;
2039 if ((error
= copyin(px_args
.port_actions
, px_spap
,
2040 px_args
.port_actions_size
)) != 0)
2043 /* Verify that the action count matches the struct size */
2044 if (PS_PORT_ACTIONS_SIZE(px_spap
->pspa_count
) != px_args
.port_actions_size
) {
2050 if (px_args
.mac_extensions_size
!= 0) {
2051 if ((error
= spawn_copyin_macpolicyinfo(&px_args
, (_posix_spawn_mac_policy_extensions_t
*)&imgp
->ip_px_smpx
)) != 0)
2054 #endif /* CONFIG_MACF */
2057 /* set uthread to parent */
2058 uthread
= get_bsdthread_info(current_thread());
2061 * <rdar://6640530>; this does not result in a behaviour change
2062 * relative to Leopard, so there should not be any existing code
2063 * which depends on it.
2065 if (uthread
->uu_flag
& UT_VFORK
) {
2071 * If we don't have the extension flag that turns "posix_spawn()"
2072 * into "execve() with options", then we will be creating a new
2073 * process which does not inherit memory from the parent process,
2074 * which is one of the most expensive things about using fork()
2077 if (imgp
->ip_px_sa
== NULL
|| !(px_sa
.psa_flags
& POSIX_SPAWN_SETEXEC
)){
2080 * Set the new task's coalition, if it is requested.
2081 * TODO: privilege check - 15365900
2083 coalition_t coal
= COALITION_NULL
;
2084 #if CONFIG_COALITIONS
2085 if (imgp
->ip_px_sa
) {
2086 uint64_t cid
= px_sa
.psa_coalitionid
;
2089 printf("%s: searching for coalition ID %llu\n", __func__
, cid
);
2091 coal
= coalition_find_and_activate_by_id(cid
);
2092 if (coal
== COALITION_NULL
) {
2094 printf("%s: could not find coalition ID %llu (perhaps it has been terminated or reaped)\n", __func__
, cid
);
2101 #endif /* CONFIG_COALITIONS */
2103 error
= fork1(p
, &imgp
->ip_new_thread
, PROC_CREATE_SPAWN
, coal
);
2106 if (coal
!= COALITION_NULL
) {
2107 #if CONFIG_COALITIONS
2108 coalition_remove_active(coal
);
2109 coalition_release(coal
);
2110 #endif /* CONFIG_COALITIONS */
2114 imgp
->ip_flags
|= IMGPF_SPAWN
; /* spawn w/o exec */
2115 spawn_no_exec
= TRUE
; /* used in later tests */
2117 if (coal
!= COALITION_NULL
) {
2118 #if CONFIG_COALITIONS
2119 coalition_remove_active(coal
);
2120 coalition_release(coal
);
2121 #endif /* CONFIG_COALITIONS */
2125 if (spawn_no_exec
) {
2126 p
= (proc_t
)get_bsdthreadtask_info(imgp
->ip_new_thread
);
2129 * We had to wait until this point before firing the
2130 * proc:::create probe, otherwise p would not point to the
2133 DTRACE_PROC1(create
, proc_t
, p
);
2137 /* By default, the thread everyone plays with is the parent */
2138 context
.vc_thread
= current_thread();
2139 context
.vc_ucred
= p
->p_ucred
; /* XXX must NOT be kauth_cred_get() */
2142 * However, if we're not in the setexec case, redirect the context
2143 * to the newly created process instead
2146 context
.vc_thread
= imgp
->ip_new_thread
;
2149 * Post fdcopy(), pre exec_handle_sugid() - this is where we want
2150 * to handle the file_actions. Since vfork() also ends up setting
2151 * us into the parent process group, and saved off the signal flags,
2152 * this is also where we want to handle the spawn flags.
2155 /* Has spawn file actions? */
2156 if (imgp
->ip_px_sfa
!= NULL
) {
2158 * The POSIX_SPAWN_CLOEXEC_DEFAULT flag
2159 * is handled in exec_handle_file_actions().
2161 if ((error
= exec_handle_file_actions(imgp
,
2162 imgp
->ip_px_sa
!= NULL
? px_sa
.psa_flags
: 0)) != 0)
2166 /* Has spawn port actions? */
2167 if (imgp
->ip_px_spa
!= NULL
) {
2168 boolean_t is_adaptive
= FALSE
;
2169 boolean_t portwatch_present
= FALSE
;
2171 /* Will this process become adaptive? The apptype isn't ready yet, so we can't look there. */
2172 if (imgp
->ip_px_sa
!= NULL
&& px_sa
.psa_apptype
== POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE
)
2177 * Allocate a place to store the ports we want to bind to the new task
2178 * We can't bind them until after the apptype is set.
2180 if (px_spap
->pspa_count
!= 0 && is_adaptive
) {
2181 portwatch_count
= px_spap
->pspa_count
;
2182 MALLOC(portwatch_ports
, ipc_port_t
*, (sizeof(ipc_port_t
) * portwatch_count
), M_TEMP
, M_WAITOK
| M_ZERO
);
2184 portwatch_ports
= NULL
;
2187 if ((error
= exec_handle_port_actions(imgp
,
2188 imgp
->ip_px_sa
!= NULL
? px_sa
.psa_flags
: 0, &portwatch_present
, portwatch_ports
)) != 0)
2191 if (portwatch_present
== FALSE
&& portwatch_ports
!= NULL
) {
2192 FREE(portwatch_ports
, M_TEMP
);
2193 portwatch_ports
= NULL
;
2194 portwatch_count
= 0;
2198 /* Has spawn attr? */
2199 if (imgp
->ip_px_sa
!= NULL
) {
2201 * Set the process group ID of the child process; this has
2202 * to happen before the image activation.
2204 if (px_sa
.psa_flags
& POSIX_SPAWN_SETPGROUP
) {
2205 struct setpgid_args spga
;
2206 spga
.pid
= p
->p_pid
;
2207 spga
.pgid
= px_sa
.psa_pgroup
;
2209 * Effectively, call setpgid() system call; works
2210 * because there are no pointer arguments.
2212 if((error
= setpgid(p
, &spga
, ival
)) != 0)
2217 * Reset UID/GID to parent's RUID/RGID; This works only
2218 * because the operation occurs *after* the vfork() and
2219 * before the call to exec_handle_sugid() by the image
2220 * activator called from exec_activate_image(). POSIX
2221 * requires that any setuid/setgid bits on the process
2222 * image will take precedence over the spawn attributes
2225 * The use of p_ucred is safe, since we are acting on the
2226 * new process, and it has no threads other than the one
2227 * we are creating for it.
2229 if (px_sa
.psa_flags
& POSIX_SPAWN_RESETIDS
) {
2230 kauth_cred_t my_cred
= p
->p_ucred
;
2231 kauth_cred_t my_new_cred
= kauth_cred_setuidgid(my_cred
, kauth_cred_getruid(my_cred
), kauth_cred_getrgid(my_cred
));
2232 if (my_new_cred
!= my_cred
) {
2233 p
->p_ucred
= my_new_cred
;
2234 /* update cred on proc */
2235 PROC_UPDATE_CREDS_ONPROC(p
);
2240 * Disable ASLR for the spawned process.
2243 * But only do so if we are not embedded; embedded allows for a
2244 * boot-arg (-disable_aslr) to deal with this (which itself is
2245 * only honored on DEVELOPMENT or DEBUG builds of xnu).
2247 if (px_sa
.psa_flags
& _POSIX_SPAWN_DISABLE_ASLR
)
2248 OSBitOrAtomic(P_DISABLE_ASLR
, &p
->p_flag
);
2251 * Forcibly disallow execution from data pages for the spawned process
2252 * even if it would otherwise be permitted by the architecture default.
2254 if (px_sa
.psa_flags
& _POSIX_SPAWN_ALLOW_DATA_EXEC
)
2255 imgp
->ip_flags
|= IMGPF_ALLOW_DATA_EXEC
;
2259 * Disable ASLR during image activation. This occurs either if the
2260 * _POSIX_SPAWN_DISABLE_ASLR attribute was found above or if
2261 * P_DISABLE_ASLR was inherited from the parent process.
2263 if (p
->p_flag
& P_DISABLE_ASLR
)
2264 imgp
->ip_flags
|= IMGPF_DISABLE_ASLR
;
2267 * Clear transition flag so we won't hang if exec_activate_image() causes
2268 * an automount (and launchd does a proc sysctl to service it).
2270 * <rdar://problem/6848672>, <rdar://problem/5959568>.
2272 if (spawn_no_exec
) {
2273 proc_transend(p
, 0);
2274 proc_transit_set
= 0;
2277 #if MAC_SPAWN /* XXX */
2278 if (uap
->mac_p
!= USER_ADDR_NULL
) {
2279 error
= mac_execve_enter(uap
->mac_p
, imgp
);
2286 * Activate the image
2288 error
= exec_activate_image(imgp
);
2291 /* process completed the exec */
2293 } else if (error
== -1) {
2294 /* Image not claimed by any activator? */
2299 * If we have a spawn attr, and it contains signal related flags,
2300 * the we need to process them in the "context" of the new child
2301 * process, so we have to process it following image activation,
2302 * prior to making the thread runnable in user space. This is
2303 * necessitated by some signal information being per-thread rather
2304 * than per-process, and we don't have the new allocation in hand
2305 * until after the image is activated.
2307 if (!error
&& imgp
->ip_px_sa
!= NULL
) {
2308 thread_t child_thread
= current_thread();
2309 uthread_t child_uthread
= uthread
;
2312 * If we created a new child thread, then the thread and
2313 * uthread are different than the current ones; otherwise,
2314 * we leave them, since we are in the exec case instead.
2316 if (spawn_no_exec
) {
2317 child_thread
= imgp
->ip_new_thread
;
2318 child_uthread
= get_bsdthread_info(child_thread
);
2322 * Mask a list of signals, instead of them being unmasked, if
2323 * they were unmasked in the parent; note that some signals
2326 if (px_sa
.psa_flags
& POSIX_SPAWN_SETSIGMASK
)
2327 child_uthread
->uu_sigmask
= (px_sa
.psa_sigmask
& ~sigcantmask
);
2329 * Default a list of signals instead of ignoring them, if
2330 * they were ignored in the parent. Note that we pass
2331 * spawn_no_exec to setsigvec() to indicate that we called
2332 * fork1() and therefore do not need to call proc_signalstart()
2335 if (px_sa
.psa_flags
& POSIX_SPAWN_SETSIGDEF
) {
2336 vec
.sa_handler
= SIG_DFL
;
2340 for (sig
= 0; sig
< NSIG
; sig
++)
2341 if (px_sa
.psa_sigdefault
& (1 << sig
)) {
2342 error
= setsigvec(p
, child_thread
, sig
+ 1, &vec
, spawn_no_exec
);
2347 * Activate the CPU usage monitor, if requested. This is done via a task-wide, per-thread CPU
2348 * usage limit, which will generate a resource exceeded exception if any one thread exceeds the
2351 * Userland gives us interval in seconds, and the kernel SPI expects nanoseconds.
2353 if (px_sa
.psa_cpumonitor_percent
!= 0) {
2355 * Always treat a CPU monitor activation coming from spawn as entitled. Requiring
2356 * an entitlement to configure the monitor a certain way seems silly, since
2357 * whomever is turning it on could just as easily choose not to do so.
2359 * XXX - Ignore the parameters that we get from userland. The spawnattr method of
2360 * activating the monitor always gets the system default parameters. Once we have
2361 * an explicit spawn SPI for configuring the defaults, we can revert this to
2362 * respect the params passed in from userland.
2364 error
= proc_set_task_ruse_cpu(p
->task
,
2365 TASK_POLICY_RESOURCE_ATTRIBUTE_NOTIFY_EXC
,
2366 PROC_POLICY_CPUMON_DEFAULTS
, 0,
2374 /* reset delay idle sleep status if set */
2375 if ((p
->p_flag
& P_DELAYIDLESLEEP
) == P_DELAYIDLESLEEP
)
2376 OSBitAndAtomic(~((uint32_t)P_DELAYIDLESLEEP
), &p
->p_flag
);
2377 /* upon successful spawn, re/set the proc control state */
2378 if (imgp
->ip_px_sa
!= NULL
) {
2379 switch (px_sa
.psa_pcontrol
) {
2380 case POSIX_SPAWN_PCONTROL_THROTTLE
:
2381 p
->p_pcaction
= P_PCTHROTTLE
;
2383 case POSIX_SPAWN_PCONTROL_SUSPEND
:
2384 p
->p_pcaction
= P_PCSUSP
;
2386 case POSIX_SPAWN_PCONTROL_KILL
:
2387 p
->p_pcaction
= P_PCKILL
;
2389 case POSIX_SPAWN_PCONTROL_NONE
:
2395 exec_resettextvp(p
, imgp
);
2397 #if CONFIG_MEMORYSTATUS && CONFIG_JETSAM
2398 /* Has jetsam attributes? */
2399 if (imgp
->ip_px_sa
!= NULL
&& (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_SET
)) {
2400 memorystatus_update(p
, px_sa
.psa_priority
, 0, (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY
),
2401 TRUE
, px_sa
.psa_high_water_mark
, (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND
),
2402 (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_MEMLIMIT_FATAL
));
2408 * If we successfully called fork1(), we always need to do this;
2409 * we identify this case by noting the IMGPF_SPAWN flag. This is
2410 * because we come back from that call with signals blocked in the
2411 * child, and we have to unblock them, but we want to wait until
2412 * after we've performed any spawn actions. This has to happen
2413 * before check_for_signature(), which uses psignal.
2415 if (spawn_no_exec
) {
2416 if (proc_transit_set
)
2417 proc_transend(p
, 0);
2420 * Drop the signal lock on the child which was taken on our
2421 * behalf by forkproc()/cloneproc() to prevent signals being
2422 * received by the child in a partially constructed state.
2424 proc_signalend(p
, 0);
2426 /* flag the 'fork' has occurred */
2427 proc_knote(p
->p_pptr
, NOTE_FORK
| p
->p_pid
);
2428 /* then flag exec has occurred */
2429 /* notify only if it has not failed due to FP Key error */
2430 if ((p
->p_lflag
& P_LTERM_DECRYPTFAIL
) == 0)
2431 proc_knote(p
, NOTE_EXEC
);
2433 /* reset the importance attribute from our previous life */
2434 task_importance_reset(p
->task
);
2436 /* reset atm context from task */
2437 task_atm_reset(p
->task
);
2441 * Apply the spawnattr policy, apptype (which primes the task for importance donation),
2442 * and bind any portwatch ports to the new task.
2443 * This must be done after the exec so that the child's thread is ready,
2444 * and after the in transit state has been released, because priority is
2445 * dropped here so we need to be prepared for a potentially long preemption interval
2447 * TODO: Consider splitting this up into separate phases
2449 if (error
== 0 && imgp
->ip_px_sa
!= NULL
) {
2450 struct _posix_spawnattr
*psa
= (struct _posix_spawnattr
*) imgp
->ip_px_sa
;
2452 exec_handle_spawnattr_policy(p
, psa
->psa_apptype
, psa
->psa_qos_clamp
,
2453 portwatch_ports
, portwatch_count
);
2456 /* Apply the main thread qos */
2458 thread_t main_thread
= (imgp
->ip_new_thread
!= NULL
) ? imgp
->ip_new_thread
: current_thread();
2460 task_set_main_thread_qos(p
->task
, main_thread
);
2464 * Release any ports we kept around for binding to the new task
2465 * We need to release the rights even if the posix_spawn has failed.
2467 if (portwatch_ports
!= NULL
) {
2468 for (int i
= 0; i
< portwatch_count
; i
++) {
2469 ipc_port_t port
= NULL
;
2470 if ((port
= portwatch_ports
[i
]) != NULL
) {
2471 ipc_port_release_send(port
);
2474 FREE(portwatch_ports
, M_TEMP
);
2475 portwatch_ports
= NULL
;
2476 portwatch_count
= 0;
2480 * We have to delay operations which might throw a signal until after
2481 * the signals have been unblocked; however, we want that to happen
2482 * after exec_resettextvp() so that the textvp is correct when they
2486 error
= check_for_signature(p
, imgp
);
2489 * Pay for our earlier safety; deliver the delayed signals from
2490 * the incomplete spawn process now that it's complete.
2492 if (imgp
!= NULL
&& spawn_no_exec
&& (p
->p_lflag
& P_LTRACED
)) {
2493 psignal_vfork(p
, p
->task
, imgp
->ip_new_thread
, SIGTRAP
);
2500 vnode_put(imgp
->ip_vp
);
2501 if (imgp
->ip_scriptvp
)
2502 vnode_put(imgp
->ip_scriptvp
);
2503 if (imgp
->ip_strings
)
2504 execargs_free(imgp
);
2505 if (imgp
->ip_px_sfa
!= NULL
)
2506 FREE(imgp
->ip_px_sfa
, M_TEMP
);
2507 if (imgp
->ip_px_spa
!= NULL
)
2508 FREE(imgp
->ip_px_spa
, M_TEMP
);
2511 if (imgp
->ip_px_smpx
!= NULL
)
2512 spawn_free_macpolicyinfo(imgp
->ip_px_smpx
);
2513 if (imgp
->ip_execlabelp
)
2514 mac_cred_label_free(imgp
->ip_execlabelp
);
2515 if (imgp
->ip_scriptlabelp
)
2516 mac_vnode_label_free(imgp
->ip_scriptlabelp
);
2521 if (spawn_no_exec
) {
2523 * In the original DTrace reference implementation,
2524 * posix_spawn() was a libc routine that just
2525 * did vfork(2) then exec(2). Thus the proc::: probes
2526 * are very fork/exec oriented. The details of this
2527 * in-kernel implementation of posix_spawn() is different
2528 * (while producing the same process-observable effects)
2529 * particularly w.r.t. errors, and which thread/process
2530 * is constructing what on behalf of whom.
2533 DTRACE_PROC1(spawn__failure
, int, error
);
2535 DTRACE_PROC(spawn__success
);
2537 * Some DTrace scripts, e.g. newproc.d in
2538 * /usr/bin, rely on the the 'exec-success'
2539 * probe being fired in the child after the
2540 * new process image has been constructed
2541 * in order to determine the associated pid.
2543 * So, even though the parent built the image
2544 * here, for compatibility, mark the new thread
2545 * so 'exec-success' fires on it as it leaves
2548 dtrace_thread_didexec(imgp
->ip_new_thread
);
2552 DTRACE_PROC1(exec__failure
, int, error
);
2554 DTRACE_PROC(exec__success
);
2558 if ((dtrace_proc_waitfor_hook
= dtrace_proc_waitfor_exec_ptr
) != NULL
)
2559 (*dtrace_proc_waitfor_hook
)(p
);
2562 /* Return to both the parent and the child? */
2563 if (imgp
!= NULL
&& spawn_no_exec
) {
2565 * If the parent wants the pid, copy it out
2567 if (pid
!= USER_ADDR_NULL
)
2568 (void)suword(pid
, p
->p_pid
);
2572 * If we had an error, perform an internal reap ; this is
2573 * entirely safe, as we have a real process backing us.
2577 p
->p_listflag
|= P_LIST_DEADPARENT
;
2580 /* make sure no one else has killed it off... */
2581 if (p
->p_stat
!= SZOMB
&& p
->exit_thread
== NULL
) {
2582 p
->exit_thread
= current_thread();
2584 exit1(p
, 1, (int *)NULL
);
2585 if (exec_done
== FALSE
) {
2586 task_deallocate(get_threadtask(imgp
->ip_new_thread
));
2587 thread_deallocate(imgp
->ip_new_thread
);
2590 /* someone is doing it for us; just skip it */
2596 * Return to the child
2598 * Note: the image activator earlier dropped the
2599 * task/thread references to the newly spawned
2600 * process; this is OK, since we still have suspended
2601 * queue references on them, so we should be fine
2602 * with the delayed resume of the thread here.
2604 (void)thread_resume(imgp
->ip_new_thread
);
2618 * Parameters: uap->fname File name to exec
2619 * uap->argp Argument list
2620 * uap->envp Environment list
2622 * Returns: 0 Success
2623 * __mac_execve:EINVAL Invalid argument
2624 * __mac_execve:ENOTSUP Invalid argument
2625 * __mac_execve:EACCES Permission denied
2626 * __mac_execve:EINTR Interrupted function
2627 * __mac_execve:ENOMEM Not enough space
2628 * __mac_execve:EFAULT Bad address
2629 * __mac_execve:ENAMETOOLONG Filename too long
2630 * __mac_execve:ENOEXEC Executable file format error
2631 * __mac_execve:ETXTBSY Text file busy [misuse of error code]
2634 * TODO: Dynamic linker header address on stack is copied via suword()
2638 execve(proc_t p
, struct execve_args
*uap
, int32_t *retval
)
2640 struct __mac_execve_args muap
;
2643 memoryshot(VM_EXECVE
, DBG_FUNC_NONE
);
2645 muap
.fname
= uap
->fname
;
2646 muap
.argp
= uap
->argp
;
2647 muap
.envp
= uap
->envp
;
2648 muap
.mac_p
= USER_ADDR_NULL
;
2649 err
= __mac_execve(p
, &muap
, retval
);
2657 * Parameters: uap->fname File name to exec
2658 * uap->argp Argument list
2659 * uap->envp Environment list
2660 * uap->mac_p MAC label supplied by caller
2662 * Returns: 0 Success
2663 * EINVAL Invalid argument
2664 * ENOTSUP Not supported
2665 * ENOEXEC Executable file format error
2666 * exec_activate_image:EINVAL Invalid argument
2667 * exec_activate_image:EACCES Permission denied
2668 * exec_activate_image:EINTR Interrupted function
2669 * exec_activate_image:ENOMEM Not enough space
2670 * exec_activate_image:EFAULT Bad address
2671 * exec_activate_image:ENAMETOOLONG Filename too long
2672 * exec_activate_image:ENOEXEC Executable file format error
2673 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
2674 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
2675 * exec_activate_image:???
2676 * mac_execve_enter:???
2678 * TODO: Dynamic linker header address on stack is copied via suword()
2681 __mac_execve(proc_t p
, struct __mac_execve_args
*uap
, int32_t *retval
)
2684 struct image_params
*imgp
;
2685 struct vnode_attr
*vap
;
2686 struct vnode_attr
*origvap
;
2688 char alt_p_comm
[sizeof(p
->p_comm
)] = {0}; /* for PowerPC */
2689 int is_64
= IS_64BIT_PROCESS(p
);
2690 struct vfs_context context
;
2691 struct uthread
*uthread
;
2693 context
.vc_thread
= current_thread();
2694 context
.vc_ucred
= kauth_cred_proc_ref(p
); /* XXX must NOT be kauth_cred_get() */
2696 /* Allocate a big chunk for locals instead of using stack since these
2697 * structures a pretty big.
2699 MALLOC(bufp
, char *, (sizeof(*imgp
) + sizeof(*vap
) + sizeof(*origvap
)), M_TEMP
, M_WAITOK
| M_ZERO
);
2700 imgp
= (struct image_params
*) bufp
;
2703 goto exit_with_error
;
2705 vap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
));
2706 origvap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
) + sizeof(*vap
));
2708 /* Initialize the common data in the image_params structure */
2709 imgp
->ip_user_fname
= uap
->fname
;
2710 imgp
->ip_user_argv
= uap
->argp
;
2711 imgp
->ip_user_envv
= uap
->envp
;
2712 imgp
->ip_vattr
= vap
;
2713 imgp
->ip_origvattr
= origvap
;
2714 imgp
->ip_vfs_context
= &context
;
2715 imgp
->ip_flags
= (is_64
? IMGPF_WAS_64BIT
: IMGPF_NONE
) | ((p
->p_flag
& P_DISABLE_ASLR
) ? IMGPF_DISABLE_ASLR
: IMGPF_NONE
);
2716 imgp
->ip_p_comm
= alt_p_comm
; /* for PowerPC */
2717 imgp
->ip_seg
= (is_64
? UIO_USERSPACE64
: UIO_USERSPACE32
);
2718 imgp
->ip_mac_return
= 0;
2720 uthread
= get_bsdthread_info(current_thread());
2721 if (uthread
->uu_flag
& UT_VFORK
) {
2722 imgp
->ip_flags
|= IMGPF_VFORK_EXEC
;
2726 if (uap
->mac_p
!= USER_ADDR_NULL
) {
2727 error
= mac_execve_enter(uap
->mac_p
, imgp
);
2729 kauth_cred_unref(&context
.vc_ucred
);
2730 goto exit_with_error
;
2735 error
= exec_activate_image(imgp
);
2737 kauth_cred_unref(&context
.vc_ucred
);
2739 /* Image not claimed by any activator? */
2744 exec_resettextvp(p
, imgp
);
2745 error
= check_for_signature(p
, imgp
);
2747 if (imgp
->ip_vp
!= NULLVP
)
2748 vnode_put(imgp
->ip_vp
);
2749 if (imgp
->ip_scriptvp
!= NULLVP
)
2750 vnode_put(imgp
->ip_scriptvp
);
2751 if (imgp
->ip_strings
)
2752 execargs_free(imgp
);
2754 if (imgp
->ip_execlabelp
)
2755 mac_cred_label_free(imgp
->ip_execlabelp
);
2756 if (imgp
->ip_scriptlabelp
)
2757 mac_vnode_label_free(imgp
->ip_scriptlabelp
);
2760 /* Sever any extant thread affinity */
2761 thread_affinity_exec(current_thread());
2763 thread_t main_thread
= (imgp
->ip_new_thread
!= NULL
) ? imgp
->ip_new_thread
: current_thread();
2765 task_set_main_thread_qos(p
->task
, main_thread
);
2767 /* reset task importance */
2768 task_importance_reset(p
->task
);
2770 /* reset atm context from task */
2771 task_atm_reset(p
->task
);
2773 DTRACE_PROC(exec__success
);
2776 if ((dtrace_proc_waitfor_hook
= dtrace_proc_waitfor_exec_ptr
) != NULL
)
2777 (*dtrace_proc_waitfor_hook
)(p
);
2780 if (imgp
->ip_flags
& IMGPF_VFORK_EXEC
) {
2781 vfork_return(p
, retval
, p
->p_pid
);
2782 (void)thread_resume(imgp
->ip_new_thread
);
2785 DTRACE_PROC1(exec__failure
, int, error
);
2800 * Description: Copy a pointer in from user space to a user_addr_t in kernel
2801 * space, based on 32/64 bitness of the user space
2803 * Parameters: froma User space address
2804 * toptr Address of kernel space user_addr_t
2805 * ptr_size 4/8, based on 'froma' address space
2807 * Returns: 0 Success
2808 * EFAULT Bad 'froma'
2811 * *ptr_size Modified
2814 copyinptr(user_addr_t froma
, user_addr_t
*toptr
, int ptr_size
)
2818 if (ptr_size
== 4) {
2819 /* 64 bit value containing 32 bit address */
2822 error
= copyin(froma
, &i
, 4);
2823 *toptr
= CAST_USER_ADDR_T(i
); /* SAFE */
2825 error
= copyin(froma
, toptr
, 8);
2834 * Description: Copy a pointer out from a user_addr_t in kernel space to
2835 * user space, based on 32/64 bitness of the user space
2837 * Parameters: ua User space address to copy to
2838 * ptr Address of kernel space user_addr_t
2839 * ptr_size 4/8, based on 'ua' address space
2841 * Returns: 0 Success
2846 copyoutptr(user_addr_t ua
, user_addr_t ptr
, int ptr_size
)
2850 if (ptr_size
== 4) {
2851 /* 64 bit value containing 32 bit address */
2852 unsigned int i
= CAST_DOWN_EXPLICIT(unsigned int,ua
); /* SAFE */
2854 error
= copyout(&i
, ptr
, 4);
2856 error
= copyout(&ua
, ptr
, 8);
2863 * exec_copyout_strings
2865 * Copy out the strings segment to user space. The strings segment is put
2866 * on a preinitialized stack frame.
2868 * Parameters: struct image_params * the image parameter block
2869 * int * a pointer to the stack offset variable
2871 * Returns: 0 Success
2875 * (*stackp) The stack offset, modified
2877 * Note: The strings segment layout is backward, from the beginning
2878 * of the top of the stack to consume the minimal amount of
2879 * space possible; the returned stack pointer points to the
2880 * end of the area consumed (stacks grow downward).
2882 * argc is an int; arg[i] are pointers; env[i] are pointers;
2883 * the 0's are (void *)NULL's
2885 * The stack frame layout is:
2887 * +-------------+ <- p->user_stack
2928 * sp-> +-------------+
2930 * Although technically a part of the STRING AREA, we treat the PATH AREA as
2931 * a separate entity. This allows us to align the beginning of the PATH AREA
2932 * to a pointer boundary so that the exec_path, env[i], and argv[i] pointers
2933 * which preceed it on the stack are properly aligned.
2937 exec_copyout_strings(struct image_params
*imgp
, user_addr_t
*stackp
)
2939 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
2940 int ptr_size
= (imgp
->ip_flags
& IMGPF_IS_64BIT
) ? 8 : 4;
2942 void *ptr_buffer_start
, *ptr_buffer
;
2945 user_addr_t string_area
; /* *argv[], *env[] */
2946 user_addr_t ptr_area
; /* argv[], env[], applev[] */
2947 user_addr_t argc_area
; /* argc */
2952 struct copyout_desc
{
2956 user_addr_t
*dtrace_cookie
;
2958 boolean_t null_term
;
2961 .start_string
= imgp
->ip_startargv
,
2962 .count
= imgp
->ip_argc
,
2964 .dtrace_cookie
= &p
->p_dtrace_argv
,
2969 .start_string
= imgp
->ip_endargv
,
2970 .count
= imgp
->ip_envc
,
2972 .dtrace_cookie
= &p
->p_dtrace_envp
,
2977 .start_string
= imgp
->ip_strings
,
2980 .dtrace_cookie
= NULL
,
2985 .start_string
= imgp
->ip_endenvv
,
2986 .count
= imgp
->ip_applec
- 1, /* exec_path handled above */
2988 .dtrace_cookie
= NULL
,
2997 * All previous contributors to the string area
2998 * should have aligned their sub-area
3000 if (imgp
->ip_strspace
% ptr_size
!= 0) {
3005 /* Grow the stack down for the strings we've been building up */
3006 string_size
= imgp
->ip_strendp
- imgp
->ip_strings
;
3007 stack
-= string_size
;
3008 string_area
= stack
;
3011 * Need room for one pointer for each string, plus
3012 * one for the NULLs terminating the argv, envv, and apple areas.
3014 ptr_area_size
= (imgp
->ip_argc
+ imgp
->ip_envc
+ imgp
->ip_applec
+ 3) *
3016 stack
-= ptr_area_size
;
3019 /* We'll construct all the pointer arrays in our string buffer,
3020 * which we already know is aligned properly, and ip_argspace
3021 * was used to verify we have enough space.
3023 ptr_buffer_start
= ptr_buffer
= (void *)imgp
->ip_strendp
;
3026 * Need room for pointer-aligned argc slot.
3032 * Record the size of the arguments area so that sysctl_procargs()
3033 * can return the argument area without having to parse the arguments.
3036 p
->p_argc
= imgp
->ip_argc
;
3037 p
->p_argslen
= (int)(*stackp
- string_area
);
3040 /* Return the initial stack address: the location of argc */
3044 * Copy out the entire strings area.
3046 error
= copyout(imgp
->ip_strings
, string_area
,
3051 for (i
= 0; i
< sizeof(descriptors
)/sizeof(descriptors
[0]); i
++) {
3052 char *cur_string
= descriptors
[i
].start_string
;
3056 if (descriptors
[i
].dtrace_cookie
) {
3058 *descriptors
[i
].dtrace_cookie
= ptr_area
+ ((uintptr_t)ptr_buffer
- (uintptr_t)ptr_buffer_start
); /* dtrace convenience */
3061 #endif /* CONFIG_DTRACE */
3064 * For each segment (argv, envv, applev), copy as many pointers as requested
3065 * to our pointer buffer.
3067 for (j
= 0; j
< descriptors
[i
].count
; j
++) {
3068 user_addr_t cur_address
= string_area
+ (cur_string
- imgp
->ip_strings
);
3070 /* Copy out the pointer to the current string. Alignment has been verified */
3071 if (ptr_size
== 8) {
3072 *(uint64_t *)ptr_buffer
= (uint64_t)cur_address
;
3074 *(uint32_t *)ptr_buffer
= (uint32_t)cur_address
;
3077 ptr_buffer
= (void *)((uintptr_t)ptr_buffer
+ ptr_size
);
3078 cur_string
+= strlen(cur_string
) + 1; /* Only a NUL between strings in the same area */
3081 if (descriptors
[i
].null_term
) {
3082 if (ptr_size
== 8) {
3083 *(uint64_t *)ptr_buffer
= 0ULL;
3085 *(uint32_t *)ptr_buffer
= 0;
3088 ptr_buffer
= (void *)((uintptr_t)ptr_buffer
+ ptr_size
);
3093 * Copy out all our pointer arrays in bulk.
3095 error
= copyout(ptr_buffer_start
, ptr_area
,
3100 /* argc (int32, stored in a ptr_size area) */
3101 error
= copyoutptr((user_addr_t
)imgp
->ip_argc
, argc_area
, ptr_size
);
3111 * exec_extract_strings
3113 * Copy arguments and environment from user space into work area; we may
3114 * have already copied some early arguments into the work area, and if
3115 * so, any arguments opied in are appended to those already there.
3116 * This function is the primary manipulator of ip_argspace, since
3117 * these are the arguments the client of execve(2) knows about. After
3118 * each argv[]/envv[] string is copied, we charge the string length
3119 * and argv[]/envv[] pointer slot to ip_argspace, so that we can
3120 * full preflight the arg list size.
3122 * Parameters: struct image_params * the image parameter block
3124 * Returns: 0 Success
3128 * (imgp->ip_argc) Count of arguments, updated
3129 * (imgp->ip_envc) Count of environment strings, updated
3130 * (imgp->ip_argspace) Count of remaining of NCARGS
3131 * (imgp->ip_interp_buffer) Interpreter and args (mutated in place)
3134 * Note: The argument and environment vectors are user space pointers
3135 * to arrays of user space pointers.
3138 exec_extract_strings(struct image_params
*imgp
)
3141 int ptr_size
= (imgp
->ip_flags
& IMGPF_WAS_64BIT
) ? 8 : 4;
3142 int new_ptr_size
= (imgp
->ip_flags
& IMGPF_IS_64BIT
) ? 8 : 4;
3143 user_addr_t argv
= imgp
->ip_user_argv
;
3144 user_addr_t envv
= imgp
->ip_user_envv
;
3147 * Adjust space reserved for the path name by however much padding it
3148 * needs. Doing this here since we didn't know if this would be a 32-
3149 * or 64-bit process back in exec_save_path.
3151 while (imgp
->ip_strspace
% new_ptr_size
!= 0) {
3152 *imgp
->ip_strendp
++ = '\0';
3153 imgp
->ip_strspace
--;
3154 /* imgp->ip_argspace--; not counted towards exec args total */
3158 * From now on, we start attributing string space to ip_argspace
3160 imgp
->ip_startargv
= imgp
->ip_strendp
;
3163 if((imgp
->ip_flags
& IMGPF_INTERPRET
) != 0) {
3165 char *argstart
, *ch
;
3167 /* First, the arguments in the "#!" string are tokenized and extracted. */
3168 argstart
= imgp
->ip_interp_buffer
;
3171 while (*ch
&& !IS_WHITESPACE(*ch
)) {
3176 /* last argument, no need to NUL-terminate */
3177 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(argstart
), UIO_SYSSPACE
, TRUE
);
3182 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(argstart
), UIO_SYSSPACE
, TRUE
);
3185 * Find the next string. We know spaces at the end of the string have already
3189 while (IS_WHITESPACE(*argstart
)) {
3194 /* Error-check, regardless of whether this is the last interpreter arg or not */
3197 if (imgp
->ip_argspace
< new_ptr_size
) {
3201 imgp
->ip_argspace
-= new_ptr_size
; /* to hold argv[] entry */
3207 * If we are running an interpreter, replace the av[0] that was
3208 * passed to execve() with the path name that was
3209 * passed to execve() for interpreters which do not use the PATH
3210 * to locate their script arguments.
3212 error
= copyinptr(argv
, &arg
, ptr_size
);
3216 argv
+= ptr_size
; /* consume without using */
3220 if (imgp
->ip_interp_sugid_fd
!= -1) {
3221 char temp
[19]; /* "/dev/fd/" + 10 digits + NUL */
3222 snprintf(temp
, sizeof(temp
), "/dev/fd/%d", imgp
->ip_interp_sugid_fd
);
3223 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(temp
), UIO_SYSSPACE
, TRUE
);
3225 error
= exec_add_user_string(imgp
, imgp
->ip_user_fname
, imgp
->ip_seg
, TRUE
);
3230 if (imgp
->ip_argspace
< new_ptr_size
) {
3234 imgp
->ip_argspace
-= new_ptr_size
; /* to hold argv[] entry */
3238 while (argv
!= 0LL) {
3241 error
= copyinptr(argv
, &arg
, ptr_size
);
3254 error
= exec_add_user_string(imgp
, arg
, imgp
->ip_seg
, TRUE
);
3257 if (imgp
->ip_argspace
< new_ptr_size
) {
3261 imgp
->ip_argspace
-= new_ptr_size
; /* to hold argv[] entry */
3265 /* Save space for argv[] NULL terminator */
3266 if (imgp
->ip_argspace
< new_ptr_size
) {
3270 imgp
->ip_argspace
-= new_ptr_size
;
3272 /* Note where the args ends and env begins. */
3273 imgp
->ip_endargv
= imgp
->ip_strendp
;
3276 /* Now, get the environment */
3277 while (envv
!= 0LL) {
3280 error
= copyinptr(envv
, &env
, ptr_size
);
3291 error
= exec_add_user_string(imgp
, env
, imgp
->ip_seg
, TRUE
);
3294 if (imgp
->ip_argspace
< new_ptr_size
) {
3298 imgp
->ip_argspace
-= new_ptr_size
; /* to hold envv[] entry */
3302 /* Save space for envv[] NULL terminator */
3303 if (imgp
->ip_argspace
< new_ptr_size
) {
3307 imgp
->ip_argspace
-= new_ptr_size
;
3309 /* Align the tail of the combined argv+envv area */
3310 while (imgp
->ip_strspace
% new_ptr_size
!= 0) {
3311 if (imgp
->ip_argspace
< 1) {
3315 *imgp
->ip_strendp
++ = '\0';
3316 imgp
->ip_strspace
--;
3317 imgp
->ip_argspace
--;
3320 /* Note where the envv ends and applev begins. */
3321 imgp
->ip_endenvv
= imgp
->ip_strendp
;
3324 * From now on, we are no longer charging argument
3325 * space to ip_argspace.
3333 random_hex_str(char *str
, int len
, boolean_t embedNUL
)
3335 uint64_t low
, high
, value
;
3339 /* A 64-bit value will only take 16 characters, plus '0x' and NULL. */
3343 /* We need enough room for at least 1 digit */
3349 value
= high
<< 32 | low
;
3353 * Zero a byte to protect against C string vulnerabilities
3354 * e.g. for userland __stack_chk_guard.
3356 value
&= ~(0xffull
<< 8);
3361 for (idx
= 2; idx
< len
- 1; idx
++) {
3362 digit
= value
& 0xf;
3365 str
[idx
] = '0' + digit
;
3367 str
[idx
] = 'a' + (digit
- 10);
3374 * Libc has an 8-element array set up for stack guard values. It only fills
3375 * in one of those entries, and both gcc and llvm seem to use only a single
3376 * 8-byte guard. Until somebody needs more than an 8-byte guard value, don't
3377 * do the work to construct them.
3379 #define GUARD_VALUES 1
3380 #define GUARD_KEY "stack_guard="
3383 * System malloc needs some entropy when it is initialized.
3385 #define ENTROPY_VALUES 2
3386 #define ENTROPY_KEY "malloc_entropy="
3389 * System malloc engages nanozone for UIAPP.
3391 #define NANO_ENGAGE_KEY "MallocNanoZone=1"
3393 #define PFZ_KEY "pfz="
3394 extern user32_addr_t commpage_text32_location
;
3395 extern user64_addr_t commpage_text64_location
;
3397 * Build up the contents of the apple[] string vector
3400 exec_add_apple_strings(struct image_params
*imgp
)
3405 char guard_vec
[strlen(GUARD_KEY
) + 19 * GUARD_VALUES
+ 1];
3408 char entropy_vec
[strlen(ENTROPY_KEY
) + 19 * ENTROPY_VALUES
+ 1];
3410 char pfz_string
[strlen(PFZ_KEY
) + 16 + 4 +1];
3412 if( imgp
->ip_flags
& IMGPF_IS_64BIT
) {
3414 snprintf(pfz_string
, sizeof(pfz_string
),PFZ_KEY
"0x%llx",commpage_text64_location
);
3416 snprintf(pfz_string
, sizeof(pfz_string
),PFZ_KEY
"0x%x",commpage_text32_location
);
3419 /* exec_save_path stored the first string */
3420 imgp
->ip_applec
= 1;
3422 /* adding the pfz string */
3423 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(pfz_string
),UIO_SYSSPACE
,FALSE
);
3428 /* adding the NANO_ENGAGE_KEY key */
3429 if (imgp
->ip_px_sa
) {
3430 int proc_flags
= (((struct _posix_spawnattr
*) imgp
->ip_px_sa
)->psa_flags
);
3432 if ((proc_flags
& _POSIX_SPAWN_NANO_ALLOCATOR
) == _POSIX_SPAWN_NANO_ALLOCATOR
) {
3433 char uiapp_string
[strlen(NANO_ENGAGE_KEY
) + 1];
3435 snprintf(uiapp_string
, sizeof(uiapp_string
), NANO_ENGAGE_KEY
);
3436 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(uiapp_string
),UIO_SYSSPACE
,FALSE
);
3444 * Supply libc with a collection of random values to use when
3445 * implementing -fstack-protector.
3447 * (The first random string always contains an embedded NUL so that
3448 * __stack_chk_guard also protects against C string vulnerabilities)
3450 (void)strlcpy(guard_vec
, GUARD_KEY
, sizeof (guard_vec
));
3451 for (i
= 0; i
< GUARD_VALUES
; i
++) {
3452 random_hex_str(guard
, sizeof (guard
), i
== 0);
3454 (void)strlcat(guard_vec
, ",", sizeof (guard_vec
));
3455 (void)strlcat(guard_vec
, guard
, sizeof (guard_vec
));
3458 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(guard_vec
), UIO_SYSSPACE
, FALSE
);
3464 * Supply libc with entropy for system malloc.
3466 (void)strlcpy(entropy_vec
, ENTROPY_KEY
, sizeof(entropy_vec
));
3467 for (i
= 0; i
< ENTROPY_VALUES
; i
++) {
3468 random_hex_str(entropy
, sizeof (entropy
), FALSE
);
3470 (void)strlcat(entropy_vec
, ",", sizeof (entropy_vec
));
3471 (void)strlcat(entropy_vec
, entropy
, sizeof (entropy_vec
));
3474 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(entropy_vec
), UIO_SYSSPACE
, FALSE
);
3479 /* Align the tail of the combined applev area */
3480 while (imgp
->ip_strspace
% new_ptr_size
!= 0) {
3481 *imgp
->ip_strendp
++ = '\0';
3482 imgp
->ip_strspace
--;
3489 #define unix_stack_size(p) (p->p_rlimit[RLIMIT_STACK].rlim_cur)
3492 * exec_check_permissions
3494 * Description: Verify that the file that is being attempted to be executed
3495 * is in fact allowed to be executed based on it POSIX file
3496 * permissions and other access control criteria
3498 * Parameters: struct image_params * the image parameter block
3500 * Returns: 0 Success
3501 * EACCES Permission denied
3502 * ENOEXEC Executable file format error
3503 * ETXTBSY Text file busy [misuse of error code]
3505 * vnode_authorize:???
3508 exec_check_permissions(struct image_params
*imgp
)
3510 struct vnode
*vp
= imgp
->ip_vp
;
3511 struct vnode_attr
*vap
= imgp
->ip_vattr
;
3512 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
3514 kauth_action_t action
;
3516 /* Only allow execution of regular files */
3517 if (!vnode_isreg(vp
))
3520 /* Get the file attributes that we will be using here and elsewhere */
3522 VATTR_WANTED(vap
, va_uid
);
3523 VATTR_WANTED(vap
, va_gid
);
3524 VATTR_WANTED(vap
, va_mode
);
3525 VATTR_WANTED(vap
, va_fsid
);
3526 VATTR_WANTED(vap
, va_fileid
);
3527 VATTR_WANTED(vap
, va_data_size
);
3528 if ((error
= vnode_getattr(vp
, vap
, imgp
->ip_vfs_context
)) != 0)
3532 * Ensure that at least one execute bit is on - otherwise root
3533 * will always succeed, and we don't want to happen unless the
3534 * file really is executable.
3536 if (!vfs_authopaque(vnode_mount(vp
)) && ((vap
->va_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)) == 0))
3539 /* Disallow zero length files */
3540 if (vap
->va_data_size
== 0)
3543 imgp
->ip_arch_offset
= (user_size_t
)0;
3544 imgp
->ip_arch_size
= vap
->va_data_size
;
3546 /* Disable setuid-ness for traced programs or if MNT_NOSUID */
3547 if ((vp
->v_mount
->mnt_flag
& MNT_NOSUID
) || (p
->p_lflag
& P_LTRACED
))
3548 vap
->va_mode
&= ~(VSUID
| VSGID
);
3551 * Disable _POSIX_SPAWN_ALLOW_DATA_EXEC and _POSIX_SPAWN_DISABLE_ASLR
3552 * flags for setuid/setgid binaries.
3554 if (vap
->va_mode
& (VSUID
| VSGID
))
3555 imgp
->ip_flags
&= ~(IMGPF_ALLOW_DATA_EXEC
| IMGPF_DISABLE_ASLR
);
3558 error
= mac_vnode_check_exec(imgp
->ip_vfs_context
, vp
, imgp
);
3563 /* Check for execute permission */
3564 action
= KAUTH_VNODE_EXECUTE
;
3565 /* Traced images must also be readable */
3566 if (p
->p_lflag
& P_LTRACED
)
3567 action
|= KAUTH_VNODE_READ_DATA
;
3568 if ((error
= vnode_authorize(vp
, NULL
, action
, imgp
->ip_vfs_context
)) != 0)
3572 /* Don't let it run if anyone had it open for writing */
3574 if (vp
->v_writecount
) {
3575 panic("going to return ETXTBSY %x", vp
);
3583 /* XXX May want to indicate to underlying FS that vnode is open */
3592 * Initially clear the P_SUGID in the process flags; if an SUGID process is
3593 * exec'ing a non-SUGID image, then this is the point of no return.
3595 * If the image being activated is SUGID, then replace the credential with a
3596 * copy, disable tracing (unless the tracing process is root), reset the
3597 * mach task port to revoke it, set the P_SUGID bit,
3599 * If the saved user and group ID will be changing, then make sure it happens
3600 * to a new credential, rather than a shared one.
3602 * Set the security token (this is probably obsolete, given that the token
3603 * should not technically be separate from the credential itself).
3605 * Parameters: struct image_params * the image parameter block
3607 * Returns: void No failure indication
3610 * <process credential> Potentially modified/replaced
3611 * <task port> Potentially revoked
3612 * <process flags> P_SUGID bit potentially modified
3613 * <security token> Potentially modified
3616 exec_handle_sugid(struct image_params
*imgp
)
3618 kauth_cred_t cred
= vfs_context_ucred(imgp
->ip_vfs_context
);
3619 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
3621 int leave_sugid_clear
= 0;
3622 int mac_reset_ipc
= 0;
3625 int mac_transition
, disjoint_cred
= 0;
3626 int label_update_return
= 0;
3629 * Determine whether a call to update the MAC label will result in the
3630 * credential changing.
3632 * Note: MAC policies which do not actually end up modifying
3633 * the label subsequently are strongly encouraged to
3634 * return 0 for this check, since a non-zero answer will
3635 * slow down the exec fast path for normal binaries.
3637 mac_transition
= mac_cred_check_label_update_execve(
3638 imgp
->ip_vfs_context
,
3640 imgp
->ip_arch_offset
,
3642 imgp
->ip_scriptlabelp
,
3643 imgp
->ip_execlabelp
,
3648 OSBitAndAtomic(~((uint32_t)P_SUGID
), &p
->p_flag
);
3651 * Order of the following is important; group checks must go last,
3652 * as we use the success of the 'ismember' check combined with the
3653 * failure of the explicit match to indicate that we will be setting
3654 * the egid of the process even though the new process did not
3655 * require VSUID/VSGID bits in order for it to set the new group as
3658 * Note: Technically, by this we are implying a call to
3659 * setegid() in the new process, rather than implying
3660 * it used its VSGID bit to set the effective group,
3661 * even though there is no code in that process to make
3664 if (((imgp
->ip_origvattr
->va_mode
& VSUID
) != 0 &&
3665 kauth_cred_getuid(cred
) != imgp
->ip_origvattr
->va_uid
) ||
3666 ((imgp
->ip_origvattr
->va_mode
& VSGID
) != 0 &&
3667 ((kauth_cred_ismember_gid(cred
, imgp
->ip_origvattr
->va_gid
, &leave_sugid_clear
) || !leave_sugid_clear
) ||
3668 (kauth_cred_getgid(cred
) != imgp
->ip_origvattr
->va_gid
)))) {
3671 /* label for MAC transition and neither VSUID nor VSGID */
3672 handle_mac_transition
:
3676 * Replace the credential with a copy of itself if euid or
3679 * Note: setuid binaries will automatically opt out of
3680 * group resolver participation as a side effect
3681 * of this operation. This is an intentional
3682 * part of the security model, which requires a
3683 * participating credential be established by
3684 * escalating privilege, setting up all other
3685 * aspects of the credential including whether
3686 * or not to participate in external group
3687 * membership resolution, then dropping their
3688 * effective privilege to that of the desired
3689 * final credential state.
3691 if (imgp
->ip_origvattr
->va_mode
& VSUID
) {
3692 p
->p_ucred
= kauth_cred_setresuid(p
->p_ucred
, KAUTH_UID_NONE
, imgp
->ip_origvattr
->va_uid
, imgp
->ip_origvattr
->va_uid
, KAUTH_UID_NONE
);
3693 /* update cred on proc */
3694 PROC_UPDATE_CREDS_ONPROC(p
);
3696 if (imgp
->ip_origvattr
->va_mode
& VSGID
) {
3697 p
->p_ucred
= kauth_cred_setresgid(p
->p_ucred
, KAUTH_GID_NONE
, imgp
->ip_origvattr
->va_gid
, imgp
->ip_origvattr
->va_gid
);
3698 /* update cred on proc */
3699 PROC_UPDATE_CREDS_ONPROC(p
);
3704 * If a policy has indicated that it will transition the label,
3705 * before making the call into the MAC policies, get a new
3706 * duplicate credential, so they can modify it without
3707 * modifying any others sharing it.
3709 if (mac_transition
) {
3710 kauth_proc_label_update_execve(p
,
3711 imgp
->ip_vfs_context
,
3713 imgp
->ip_arch_offset
,
3715 imgp
->ip_scriptlabelp
,
3716 imgp
->ip_execlabelp
,
3719 &disjoint_cred
, /* will be non zero if disjoint */
3720 &label_update_return
);
3722 if (disjoint_cred
) {
3724 * If updating the MAC label resulted in a
3725 * disjoint credential, flag that we need to
3726 * set the P_SUGID bit. This protects
3727 * against debuggers being attached by an
3728 * insufficiently privileged process onto the
3729 * result of a transition to a more privileged
3732 leave_sugid_clear
= 0;
3735 imgp
->ip_mac_return
= label_update_return
;
3738 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
);
3740 #endif /* CONFIG_MACF */
3743 * If 'leave_sugid_clear' is non-zero, then we passed the
3744 * VSUID and MACF checks, and successfully determined that
3745 * the previous cred was a member of the VSGID group, but
3746 * that it was not the default at the time of the execve,
3747 * and that the post-labelling credential was not disjoint.
3748 * So we don't set the P_SUGID or reset mach ports and fds
3749 * on the basis of simply running this code.
3751 if (mac_reset_ipc
|| !leave_sugid_clear
) {
3753 * Have mach reset the task and thread ports.
3754 * We don't want anyone who had the ports before
3755 * a setuid exec to be able to access/control the
3756 * task/thread after.
3758 ipc_task_reset(p
->task
);
3759 ipc_thread_reset((imgp
->ip_new_thread
!= NULL
) ?
3760 imgp
->ip_new_thread
: current_thread());
3763 if (!leave_sugid_clear
) {
3765 * Flag the process as setuid.
3767 OSBitOrAtomic(P_SUGID
, &p
->p_flag
);
3770 * Radar 2261856; setuid security hole fix
3771 * XXX For setuid processes, attempt to ensure that
3772 * stdin, stdout, and stderr are already allocated.
3773 * We do not want userland to accidentally allocate
3774 * descriptors in this range which has implied meaning
3777 for (i
= 0; i
< 3; i
++) {
3779 if (p
->p_fd
->fd_ofiles
[i
] != NULL
)
3783 * Do the kernel equivalent of
3786 * (void) open("/dev/null", O_RDONLY);
3788 * (void) open("/dev/null", O_WRONLY);
3791 struct fileproc
*fp
;
3794 struct nameidata
*ndp
= NULL
;
3801 if ((error
= falloc(p
,
3802 &fp
, &indx
, imgp
->ip_vfs_context
)) != 0)
3805 MALLOC(ndp
, struct nameidata
*, sizeof(*ndp
), M_TEMP
, M_WAITOK
| M_ZERO
);
3811 NDINIT(ndp
, LOOKUP
, OP_OPEN
, FOLLOW
, UIO_SYSSPACE
,
3812 CAST_USER_ADDR_T("/dev/null"),
3813 imgp
->ip_vfs_context
);
3815 if ((error
= vn_open(ndp
, flag
, 0)) != 0) {
3816 fp_free(p
, indx
, fp
);
3820 struct fileglob
*fg
= fp
->f_fglob
;
3823 fg
->fg_ops
= &vnops
;
3824 fg
->fg_data
= ndp
->ni_vp
;
3826 vnode_put(ndp
->ni_vp
);
3829 procfdtbl_releasefd(p
, indx
, NULL
);
3830 fp_drop(p
, indx
, fp
, 1);
3840 * We are here because we were told that the MAC label will
3841 * be transitioned, and the binary is not VSUID or VSGID; to
3842 * deal with this case, we could either duplicate a lot of
3843 * code, or we can indicate we want to default the P_SUGID
3844 * bit clear and jump back up.
3846 if (mac_transition
) {
3847 leave_sugid_clear
= 1;
3848 goto handle_mac_transition
;
3852 #endif /* CONFIG_MACF */
3855 * Implement the semantic where the effective user and group become
3856 * the saved user and group in exec'ed programs.
3858 p
->p_ucred
= kauth_cred_setsvuidgid(p
->p_ucred
, kauth_cred_getuid(p
->p_ucred
), kauth_cred_getgid(p
->p_ucred
));
3859 /* update cred on proc */
3860 PROC_UPDATE_CREDS_ONPROC(p
);
3862 /* Update the process' identity version and set the security token */
3864 set_security_token(p
);
3873 * Description: Set the user stack address for the process to the provided
3874 * address. If a custom stack was not set as a result of the
3875 * load process (i.e. as specified by the image file for the
3876 * executable), then allocate the stack in the provided map and
3877 * set up appropriate guard pages for enforcing administrative
3878 * limits on stack growth, if they end up being needed.
3880 * Parameters: p Process to set stack on
3881 * load_result Information from mach-o load commands
3882 * map Address map in which to allocate the new stack
3884 * Returns: KERN_SUCCESS Stack successfully created
3885 * !KERN_SUCCESS Mach failure code
3887 static kern_return_t
3888 create_unix_stack(vm_map_t map
, load_result_t
* load_result
,
3891 mach_vm_size_t size
, prot_size
;
3892 mach_vm_offset_t addr
, prot_addr
;
3895 mach_vm_address_t user_stack
= load_result
->user_stack
;
3898 p
->user_stack
= user_stack
;
3901 if (!load_result
->prog_allocated_stack
) {
3903 * Allocate enough space for the maximum stack size we
3904 * will ever authorize and an extra page to act as
3905 * a guard page for stack overflows. For default stacks,
3906 * vm_initial_limit_stack takes care of the extra guard page.
3907 * Otherwise we must allocate it ourselves.
3910 size
= mach_vm_round_page(load_result
->user_stack_size
);
3911 if (load_result
->prog_stack_size
)
3913 addr
= mach_vm_trunc_page(load_result
->user_stack
- size
);
3914 kr
= mach_vm_allocate(map
, &addr
, size
,
3915 VM_MAKE_TAG(VM_MEMORY_STACK
) |
3917 if (kr
!= KERN_SUCCESS
) {
3918 /* If can't allocate at default location, try anywhere */
3920 kr
= mach_vm_allocate(map
, &addr
, size
,
3921 VM_MAKE_TAG(VM_MEMORY_STACK
) |
3923 if (kr
!= KERN_SUCCESS
)
3926 user_stack
= addr
+ size
;
3927 load_result
->user_stack
= user_stack
;
3930 p
->user_stack
= user_stack
;
3935 * And prevent access to what's above the current stack
3936 * size limit for this process.
3939 if (load_result
->prog_stack_size
)
3940 prot_size
= PAGE_SIZE
;
3942 prot_size
= mach_vm_trunc_page(size
- unix_stack_size(p
));
3943 kr
= mach_vm_protect(map
,
3948 if (kr
!= KERN_SUCCESS
) {
3949 (void) mach_vm_deallocate(map
, addr
, size
);
3954 return KERN_SUCCESS
;
3957 #include <sys/reboot.h>
3959 static const char * init_programs
[] = {
3960 #if DEVELOPMENT || DEBUG
3961 "/usr/local/sbin/launchd.development",
3969 * Description: Load the "init" program; in most cases, this will be "launchd"
3971 * Parameters: p Process to call execve() to create
3972 * the "init" program
3976 * Notes: The process that is passed in is the first manufactured
3977 * process on the system, and gets here via bsd_ast() firing
3978 * for the first time. This is done to ensure that bsd_init()
3979 * has run to completion.
3982 load_init_program(proc_t p
)
3984 vm_offset_t init_addr
, addr
;
3990 const char *init_program_name
;
3991 struct execve_args init_exec_args
;
3993 init_addr
= VM_MIN_ADDRESS
;
3994 (void) vm_allocate(current_map(), &init_addr
, PAGE_SIZE
, VM_FLAGS_ANYWHERE
);
3998 for (i
= 0; i
< sizeof(init_programs
)/sizeof(init_programs
[0]); i
++) {
4000 init_program_name
= init_programs
[i
];
4005 * Copy out program name.
4007 (void) copyout(init_program_name
, CAST_USER_ADDR_T(addr
), strlen(init_program_name
)+1);
4009 argv
[argc
++] = (uint32_t)addr
;
4010 addr
+= strlen(init_program_name
)+1;
4011 addr
= (vm_offset_t
)ROUND_PTR(char, addr
);
4014 * Put out first (and only) argument, similarly.
4015 * Assumes everything fits in a page as allocated above.
4017 if (boothowto
& RB_SINGLE
) {
4018 const char *init_args
= "-s";
4020 copyout(init_args
, CAST_USER_ADDR_T(addr
), strlen(init_args
)+1);
4022 argv
[argc
++] = (uint32_t)addr
;
4023 addr
+= strlen(init_args
)+1;
4024 addr
= (vm_offset_t
)ROUND_PTR(char, addr
);
4028 * Null-end the argument list
4033 * Copy out the argument list.
4035 (void) copyout(argv
, CAST_USER_ADDR_T(addr
), sizeof(argv
));
4038 * Set up argument block for fake call to execve.
4040 init_exec_args
.fname
= CAST_USER_ADDR_T(argv
[0]);
4041 init_exec_args
.argp
= CAST_USER_ADDR_T((char **)addr
);
4042 init_exec_args
.envp
= CAST_USER_ADDR_T(0);
4045 * So that init task is set with uid,gid 0 token
4047 set_security_token(p
);
4049 error
= execve(p
, &init_exec_args
, retval
);
4054 panic("Process 1 exec of %s failed, errno %d", init_program_name
, error
);
4058 * load_return_to_errno
4060 * Description: Convert a load_return_t (Mach error) to an errno (BSD error)
4062 * Parameters: lrtn Mach error number
4064 * Returns: (int) BSD error number
4066 * EBADARCH Bad architecture
4067 * EBADMACHO Bad Mach object file
4068 * ESHLIBVERS Bad shared library version
4069 * ENOMEM Out of memory/resource shortage
4070 * EACCES Access denied
4071 * ENOENT Entry not found (usually "file does
4073 * EIO An I/O error occurred
4074 * EBADEXEC The executable is corrupt/unknown
4077 load_return_to_errno(load_return_t lrtn
)
4098 case LOAD_DECRYPTFAIL
:
4104 #include <mach/mach_types.h>
4105 #include <mach/vm_prot.h>
4106 #include <mach/semaphore.h>
4107 #include <mach/sync_policy.h>
4108 #include <kern/clock.h>
4109 #include <mach/kern_return.h>
4114 * Description: Allocate the block of memory used by the execve arguments.
4115 * At the same time, we allocate a page so that we can read in
4116 * the first page of the image.
4118 * Parameters: struct image_params * the image parameter block
4120 * Returns: 0 Success
4121 * EINVAL Invalid argument
4122 * EACCES Permission denied
4123 * EINTR Interrupted function
4124 * ENOMEM Not enough space
4126 * Notes: This is a temporary allocation into the kernel address space
4127 * to enable us to copy arguments in from user space. This is
4128 * necessitated by not mapping the process calling execve() into
4129 * the kernel address space during the execve() system call.
4131 * We assemble the argument and environment, etc., into this
4132 * region before copying it as a single block into the child
4133 * process address space (at the top or bottom of the stack,
4134 * depending on which way the stack grows; see the function
4135 * exec_copyout_strings() for details).
4137 * This ends up with a second (possibly unnecessary) copy compared
4138 * with assembing the data directly into the child address space,
4139 * instead, but since we cannot be guaranteed that the parent has
4140 * not modified its environment, we can't really know that it's
4141 * really a block there as well.
4145 static int execargs_waiters
= 0;
4146 lck_mtx_t
*execargs_cache_lock
;
4149 execargs_lock_lock(void) {
4150 lck_mtx_lock_spin(execargs_cache_lock
);
4154 execargs_lock_unlock(void) {
4155 lck_mtx_unlock(execargs_cache_lock
);
4158 static wait_result_t
4159 execargs_lock_sleep(void) {
4160 return(lck_mtx_sleep(execargs_cache_lock
, LCK_SLEEP_DEFAULT
, &execargs_free_count
, THREAD_INTERRUPTIBLE
));
4163 static kern_return_t
4164 execargs_purgeable_allocate(char **execarg_address
) {
4165 kern_return_t kr
= vm_allocate(bsd_pageable_map
, (vm_offset_t
*)execarg_address
, BSD_PAGEABLE_SIZE_PER_EXEC
, VM_FLAGS_ANYWHERE
| VM_FLAGS_PURGABLE
);
4166 assert(kr
== KERN_SUCCESS
);
4170 static kern_return_t
4171 execargs_purgeable_reference(void *execarg_address
) {
4172 int state
= VM_PURGABLE_NONVOLATILE
;
4173 kern_return_t kr
= vm_purgable_control(bsd_pageable_map
, (vm_offset_t
) execarg_address
, VM_PURGABLE_SET_STATE
, &state
);
4175 assert(kr
== KERN_SUCCESS
);
4179 static kern_return_t
4180 execargs_purgeable_volatilize(void *execarg_address
) {
4181 int state
= VM_PURGABLE_VOLATILE
| VM_PURGABLE_ORDERING_OBSOLETE
;
4183 kr
= vm_purgable_control(bsd_pageable_map
, (vm_offset_t
) execarg_address
, VM_PURGABLE_SET_STATE
, &state
);
4185 assert(kr
== KERN_SUCCESS
);
4191 execargs_wakeup_waiters(void) {
4192 thread_wakeup(&execargs_free_count
);
4196 execargs_alloc(struct image_params
*imgp
)
4200 int i
, cache_index
= -1;
4202 execargs_lock_lock();
4204 while (execargs_free_count
== 0) {
4206 res
= execargs_lock_sleep();
4208 if (res
!= THREAD_AWAKENED
) {
4209 execargs_lock_unlock();
4214 execargs_free_count
--;
4216 for (i
= 0; i
< execargs_cache_size
; i
++) {
4217 vm_offset_t element
= execargs_cache
[i
];
4220 imgp
->ip_strings
= (char *)(execargs_cache
[i
]);
4221 execargs_cache
[i
] = 0;
4226 assert(execargs_free_count
>= 0);
4228 execargs_lock_unlock();
4230 if (cache_index
== -1) {
4231 kret
= execargs_purgeable_allocate(&imgp
->ip_strings
);
4234 kret
= execargs_purgeable_reference(imgp
->ip_strings
);
4236 assert(kret
== KERN_SUCCESS
);
4237 if (kret
!= KERN_SUCCESS
) {
4241 /* last page used to read in file headers */
4242 imgp
->ip_vdata
= imgp
->ip_strings
+ ( NCARGS
+ PAGE_SIZE
);
4243 imgp
->ip_strendp
= imgp
->ip_strings
;
4244 imgp
->ip_argspace
= NCARGS
;
4245 imgp
->ip_strspace
= ( NCARGS
+ PAGE_SIZE
);
4253 * Description: Free the block of memory used by the execve arguments and the
4254 * first page of the executable by a previous call to the function
4257 * Parameters: struct image_params * the image parameter block
4259 * Returns: 0 Success
4260 * EINVAL Invalid argument
4261 * EINTR Oeration interrupted
4264 execargs_free(struct image_params
*imgp
)
4268 boolean_t needs_wakeup
= FALSE
;
4270 kret
= execargs_purgeable_volatilize(imgp
->ip_strings
);
4272 execargs_lock_lock();
4273 execargs_free_count
++;
4275 for (i
= 0; i
< execargs_cache_size
; i
++) {
4276 vm_offset_t element
= execargs_cache
[i
];
4278 execargs_cache
[i
] = (vm_offset_t
) imgp
->ip_strings
;
4279 imgp
->ip_strings
= NULL
;
4284 assert(imgp
->ip_strings
== NULL
);
4286 if (execargs_waiters
> 0)
4287 needs_wakeup
= TRUE
;
4289 execargs_lock_unlock();
4291 if (needs_wakeup
== TRUE
)
4292 execargs_wakeup_waiters();
4294 return ((kret
== KERN_SUCCESS
? 0 : EINVAL
));
4298 exec_resettextvp(proc_t p
, struct image_params
*imgp
)
4302 vnode_t tvp
= p
->p_textvp
;
4306 offset
= imgp
->ip_arch_offset
;
4309 panic("exec_resettextvp: expected valid vp");
4311 ret
= vnode_ref(vp
);
4315 p
->p_textoff
= offset
;
4317 p
->p_textvp
= NULLVP
; /* this is paranoia */
4322 if ( tvp
!= NULLVP
) {
4323 if (vnode_getwithref(tvp
) == 0) {
4332 * If the process is not signed or if it contains entitlements, we
4333 * need to communicate through the task_access_port to taskgated.
4335 * taskgated will provide a detached code signature if present, and
4336 * will enforce any restrictions on entitlements.
4340 taskgated_required(proc_t p
, boolean_t
*require_success
)
4346 if ((p
->p_csflags
& CS_VALID
) == 0) {
4347 *require_success
= FALSE
;
4351 error
= cs_entitlements_blob_get(p
, &blob
, &length
);
4352 if (error
== 0 && blob
!= NULL
) {
4354 * fatal on the desktop when entitlements are present,
4355 * unless we started in single-user mode
4357 if ((boothowto
& RB_SINGLE
) == 0)
4358 *require_success
= TRUE
;
4360 * Allow initproc to run without causing taskgated to launch
4362 if (p
== initproc
) {
4363 *require_success
= FALSE
;
4370 *require_success
= FALSE
;
4375 * __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__
4377 * Description: Waits for the userspace daemon to respond to the request
4378 * we made. Function declared non inline to be visible in
4379 * stackshots and spindumps as well as debugging.
4381 __attribute__((noinline
)) int
4382 __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port
, int32_t new_pid
)
4384 return find_code_signature(task_access_port
, new_pid
);
4388 check_for_signature(proc_t p
, struct image_params
*imgp
)
4390 mach_port_t port
= NULL
;
4391 kern_return_t kr
= KERN_FAILURE
;
4393 boolean_t unexpected_failure
= FALSE
;
4394 unsigned char hash
[SHA1_RESULTLEN
];
4395 boolean_t require_success
= FALSE
;
4396 int spawn
= (imgp
->ip_flags
& IMGPF_SPAWN
);
4397 int vfexec
= (imgp
->ip_flags
& IMGPF_VFORK_EXEC
);
4400 * Override inherited code signing flags with the
4401 * ones for the process that is being successfully
4405 p
->p_csflags
= imgp
->ip_csflags
;
4408 /* Set the switch_protect flag on the map */
4409 if(p
->p_csflags
& (CS_HARD
|CS_KILL
)) {
4410 vm_map_switch_protect(get_task_map(p
->task
), TRUE
);
4414 * image activation may be failed due to policy
4415 * which is unexpected but security framework does not
4416 * approve of exec, kill and return immediately.
4418 if (imgp
->ip_mac_return
!= 0) {
4419 error
= imgp
->ip_mac_return
;
4420 unexpected_failure
= TRUE
;
4424 /* check if callout to taskgated is needed */
4425 if (!taskgated_required(p
, &require_success
)) {
4430 kr
= task_get_task_access_port(p
->task
, &port
);
4431 if (KERN_SUCCESS
!= kr
|| !IPC_PORT_VALID(port
)) {
4433 if (require_success
)
4439 * taskgated returns KERN_SUCCESS if it has completed its work
4440 * and the exec should continue, KERN_FAILURE if the exec should
4441 * fail, or it may error out with different error code in an
4442 * event of mig failure (e.g. process was signalled during the
4443 * rpc call, taskgated died, mig server died etc.).
4446 kr
= __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(port
, p
->p_pid
);
4456 unexpected_failure
= TRUE
;
4460 /* Only do this if exec_resettextvp() did not fail */
4461 if (p
->p_textvp
!= NULLVP
) {
4463 * If there's a new code directory, mark this process
4466 if (0 == ubc_cs_getcdhash(p
->p_textvp
, p
->p_textoff
, hash
)) {
4468 p
->p_csflags
|= CS_VALID
;
4475 if (!unexpected_failure
)
4476 p
->p_csflags
|= CS_KILLED
;
4477 /* make very sure execution fails */
4478 if (vfexec
|| spawn
) {
4479 psignal_vfork(p
, p
->task
, imgp
->ip_new_thread
, SIGKILL
);
4482 psignal(p
, SIGKILL
);
4489 * Typically as soon as we start executing this process, the
4490 * first instruction will trigger a VM fault to bring the text
4491 * pages (as executable) into the address space, followed soon
4492 * thereafter by dyld data structures (for dynamic executable).
4493 * To optimize this, as well as improve support for hardware
4494 * debuggers that can only access resident pages present
4495 * in the process' page tables, we prefault some pages if
4496 * possible. Errors are non-fatal.
4498 static void exec_prefault_data(proc_t p __unused
, struct image_params
*imgp
, load_result_t
*load_result
)
4501 size_t expected_all_image_infos_size
;
4504 * Prefault executable or dyld entry point.
4506 vm_fault(current_map(),
4507 vm_map_trunc_page(load_result
->entry_point
,
4508 vm_map_page_mask(current_map())),
4509 VM_PROT_READ
| VM_PROT_EXECUTE
,
4511 THREAD_UNINT
, NULL
, 0);
4513 if (imgp
->ip_flags
& IMGPF_IS_64BIT
) {
4514 expected_all_image_infos_size
= sizeof(struct user64_dyld_all_image_infos
);
4516 expected_all_image_infos_size
= sizeof(struct user32_dyld_all_image_infos
);
4519 /* Decode dyld anchor structure from <mach-o/dyld_images.h> */
4520 if (load_result
->dynlinker
&&
4521 load_result
->all_image_info_addr
&&
4522 load_result
->all_image_info_size
>= expected_all_image_infos_size
) {
4524 struct user64_dyld_all_image_infos infos64
;
4525 struct user32_dyld_all_image_infos infos32
;
4529 * Pre-fault to avoid copyin() going through the trap handler
4530 * and recovery path.
4532 vm_fault(current_map(),
4533 vm_map_trunc_page(load_result
->all_image_info_addr
,
4534 vm_map_page_mask(current_map())),
4535 VM_PROT_READ
| VM_PROT_WRITE
,
4537 THREAD_UNINT
, NULL
, 0);
4538 if ((load_result
->all_image_info_addr
& PAGE_MASK
) + expected_all_image_infos_size
> PAGE_SIZE
) {
4539 /* all_image_infos straddles a page */
4540 vm_fault(current_map(),
4541 vm_map_trunc_page(load_result
->all_image_info_addr
+ expected_all_image_infos_size
- 1,
4542 vm_map_page_mask(current_map())),
4543 VM_PROT_READ
| VM_PROT_WRITE
,
4545 THREAD_UNINT
, NULL
, 0);
4548 ret
= copyin(load_result
->all_image_info_addr
,
4550 expected_all_image_infos_size
);
4551 if (ret
== 0 && all_image_infos
.infos32
.version
>= 9) {
4553 user_addr_t notification_address
;
4554 user_addr_t dyld_image_address
;
4555 user_addr_t dyld_version_address
;
4556 user_addr_t dyld_all_image_infos_address
;
4557 user_addr_t dyld_slide_amount
;
4559 if (imgp
->ip_flags
& IMGPF_IS_64BIT
) {
4560 notification_address
= all_image_infos
.infos64
.notification
;
4561 dyld_image_address
= all_image_infos
.infos64
.dyldImageLoadAddress
;
4562 dyld_version_address
= all_image_infos
.infos64
.dyldVersion
;
4563 dyld_all_image_infos_address
= all_image_infos
.infos64
.dyldAllImageInfosAddress
;
4565 notification_address
= all_image_infos
.infos32
.notification
;
4566 dyld_image_address
= all_image_infos
.infos32
.dyldImageLoadAddress
;
4567 dyld_version_address
= all_image_infos
.infos32
.dyldVersion
;
4568 dyld_all_image_infos_address
= all_image_infos
.infos32
.dyldAllImageInfosAddress
;
4572 * dyld statically sets up the all_image_infos in its Mach-O
4573 * binary at static link time, with pointers relative to its default
4574 * load address. Since ASLR might slide dyld before its first
4575 * instruction is executed, "dyld_slide_amount" tells us how far
4576 * dyld was loaded compared to its default expected load address.
4577 * All other pointers into dyld's image should be adjusted by this
4578 * amount. At some point later, dyld will fix up pointers to take
4579 * into account the slide, at which point the all_image_infos_address
4580 * field in the structure will match the runtime load address, and
4581 * "dyld_slide_amount" will be 0, if we were to consult it again.
4584 dyld_slide_amount
= load_result
->all_image_info_addr
- dyld_all_image_infos_address
;
4587 kprintf("exec_prefault: 0x%016llx 0x%08x 0x%016llx 0x%016llx 0x%016llx 0x%016llx\n",
4588 (uint64_t)load_result
->all_image_info_addr
,
4589 all_image_infos
.infos32
.version
,
4590 (uint64_t)notification_address
,
4591 (uint64_t)dyld_image_address
,
4592 (uint64_t)dyld_version_address
,
4593 (uint64_t)dyld_all_image_infos_address
);
4596 vm_fault(current_map(),
4597 vm_map_trunc_page(notification_address
+ dyld_slide_amount
,
4598 vm_map_page_mask(current_map())),
4599 VM_PROT_READ
| VM_PROT_EXECUTE
,
4601 THREAD_UNINT
, NULL
, 0);
4602 vm_fault(current_map(),
4603 vm_map_trunc_page(dyld_image_address
+ dyld_slide_amount
,
4604 vm_map_page_mask(current_map())),
4605 VM_PROT_READ
| VM_PROT_EXECUTE
,
4607 THREAD_UNINT
, NULL
, 0);
4608 vm_fault(current_map(),
4609 vm_map_trunc_page(dyld_version_address
+ dyld_slide_amount
,
4610 vm_map_page_mask(current_map())),
4613 THREAD_UNINT
, NULL
, 0);
4614 vm_fault(current_map(),
4615 vm_map_trunc_page(dyld_all_image_infos_address
+ dyld_slide_amount
,
4616 vm_map_page_mask(current_map())),
4617 VM_PROT_READ
| VM_PROT_WRITE
,
4619 THREAD_UNINT
, NULL
, 0);