]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kern_exec.c
df43f2013bec20407bf001cf4a9db579281c632a
[apple/xnu.git] / bsd / kern / kern_exec.c
1 /*
2 * Copyright (c) 2000-2013 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29 /*
30 * Mach Operating System
31 * Copyright (c) 1987 Carnegie-Mellon University
32 * All rights reserved. The CMU software License Agreement specifies
33 * the terms and conditions for use and redistribution.
34 */
35
36 /*-
37 * Copyright (c) 1982, 1986, 1991, 1993
38 * The Regents of the University of California. All rights reserved.
39 * (c) UNIX System Laboratories, Inc.
40 * All or some portions of this file are derived from material licensed
41 * to the University of California by American Telephone and Telegraph
42 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
43 * the permission of UNIX System Laboratories, Inc.
44 *
45 * Redistribution and use in source and binary forms, with or without
46 * modification, are permitted provided that the following conditions
47 * are met:
48 * 1. Redistributions of source code must retain the above copyright
49 * notice, this list of conditions and the following disclaimer.
50 * 2. Redistributions in binary form must reproduce the above copyright
51 * notice, this list of conditions and the following disclaimer in the
52 * documentation and/or other materials provided with the distribution.
53 * 3. All advertising materials mentioning features or use of this software
54 * must display the following acknowledgement:
55 * This product includes software developed by the University of
56 * California, Berkeley and its contributors.
57 * 4. Neither the name of the University nor the names of its contributors
58 * may be used to endorse or promote products derived from this software
59 * without specific prior written permission.
60 *
61 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
62 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
63 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
65 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
66 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
67 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
68 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
69 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
70 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
71 * SUCH DAMAGE.
72 *
73 * from: @(#)kern_exec.c 8.1 (Berkeley) 6/10/93
74 */
75 /*
76 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
77 * support for mandatory and extensible security protections. This notice
78 * is included in support of clause 2.2 (b) of the Apple Public License,
79 * Version 2.0.
80 */
81 #include <machine/reg.h>
82 #include <machine/cpu_capabilities.h>
83
84 #include <sys/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>
90 #include <sys/user.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>
97 #include <sys/stat.h>
98 #include <sys/uio_internal.h>
99 #include <sys/acct.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>
105 #include <sys/persona.h>
106 #include <sys/reason.h>
107 #if SYSV_SHM
108 #include <sys/shm_internal.h> /* shmexec() */
109 #endif
110 #include <sys/ubc_internal.h> /* ubc_map() */
111 #include <sys/spawn.h>
112 #include <sys/spawn_internal.h>
113 #include <sys/process_policy.h>
114 #include <sys/codesign.h>
115 #include <sys/random.h>
116 #include <crypto/sha1.h>
117
118 #include <libkern/libkern.h>
119
120 #include <security/audit/audit.h>
121
122 #include <ipc/ipc_types.h>
123
124 #include <mach/mach_types.h>
125 #include <mach/port.h>
126 #include <mach/task.h>
127 #include <mach/task_access.h>
128 #include <mach/thread_act.h>
129 #include <mach/vm_map.h>
130 #include <mach/mach_vm.h>
131 #include <mach/vm_param.h>
132
133 #include <kern/sched_prim.h> /* thread_wakeup() */
134 #include <kern/affinity.h>
135 #include <kern/assert.h>
136 #include <kern/task.h>
137 #include <kern/coalition.h>
138 #include <kern/policy_internal.h>
139 #include <kern/kalloc.h>
140
141 #include <os/log.h>
142
143 #if CONFIG_MACF
144 #include <security/mac_framework.h>
145 #include <security/mac_mach_internal.h>
146 #endif
147
148 #include <vm/vm_map.h>
149 #include <vm/vm_kern.h>
150 #include <vm/vm_protos.h>
151 #include <vm/vm_kern.h>
152 #include <vm/vm_fault.h>
153 #include <vm/vm_pageout.h>
154
155 #include <kdp/kdp_dyld.h>
156
157 #include <machine/pal_routines.h>
158
159 #include <pexpert/pexpert.h>
160
161 #if CONFIG_MEMORYSTATUS
162 #include <sys/kern_memorystatus.h>
163 #endif
164
165 #if CONFIG_DTRACE
166 /* Do not include dtrace.h, it redefines kmem_[alloc/free] */
167 extern void dtrace_proc_exec(proc_t);
168 extern void (*dtrace_proc_waitfor_exec_ptr)(proc_t);
169
170 /*
171 * Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c,
172 * we will store its value before actually calling it.
173 */
174 static void (*dtrace_proc_waitfor_hook)(proc_t) = NULL;
175
176 #include <sys/dtrace_ptss.h>
177 #endif
178
179 /* support for child creation in exec after vfork */
180 thread_t fork_create_child(task_t parent_task, coalition_t *parent_coalition, proc_t child_proc, int inherit_memory, int is64bit, int in_exec);
181 void vfork_exit(proc_t p, int rv);
182 extern void proc_apply_task_networkbg_internal(proc_t, thread_t);
183 extern void task_set_did_exec_flag(task_t task);
184 extern void task_clear_exec_copy_flag(task_t task);
185 proc_t proc_exec_switch_task(proc_t p, task_t old_task, task_t new_task, thread_t new_thread);
186 boolean_t task_is_active(task_t);
187 boolean_t thread_is_active(thread_t thread);
188 void thread_copy_resource_info(thread_t dst_thread, thread_t src_thread);
189 void *ipc_importance_exec_switch_task(task_t old_task, task_t new_task);
190 extern void ipc_importance_release(void *elem);
191
192 /*
193 * Mach things for which prototypes are unavailable from Mach headers
194 */
195 void ipc_task_reset(
196 task_t task);
197 void ipc_thread_reset(
198 thread_t thread);
199 kern_return_t ipc_object_copyin(
200 ipc_space_t space,
201 mach_port_name_t name,
202 mach_msg_type_name_t msgt_name,
203 ipc_object_t *objectp);
204 void ipc_port_release_send(ipc_port_t);
205
206 #if DEVELOPMENT || DEBUG
207 void task_importance_update_owner_info(task_t);
208 #endif
209
210 extern struct savearea *get_user_regs(thread_t);
211
212 __attribute__((noinline)) int __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port, int32_t new_pid);
213
214 #include <kern/thread.h>
215 #include <kern/task.h>
216 #include <kern/ast.h>
217 #include <kern/mach_loader.h>
218 #include <kern/mach_fat.h>
219 #include <mach-o/fat.h>
220 #include <mach-o/loader.h>
221 #include <machine/vmparam.h>
222 #include <sys/imgact.h>
223
224 #include <sys/sdt.h>
225
226
227 /*
228 * EAI_ITERLIMIT The maximum number of times to iterate an image
229 * activator in exec_activate_image() before treating
230 * it as malformed/corrupt.
231 */
232 #define EAI_ITERLIMIT 3
233
234 /*
235 * For #! interpreter parsing
236 */
237 #define IS_WHITESPACE(ch) ((ch == ' ') || (ch == '\t'))
238 #define IS_EOL(ch) ((ch == '#') || (ch == '\n'))
239
240 extern vm_map_t bsd_pageable_map;
241 extern const struct fileops vnops;
242
243 #define USER_ADDR_ALIGN(addr, val) \
244 ( ( (user_addr_t)(addr) + (val) - 1) \
245 & ~((val) - 1) )
246
247 /* Platform Code Exec Logging */
248 static int platform_exec_logging = 0;
249
250 SYSCTL_DECL(_security_mac);
251
252 SYSCTL_INT(_security_mac, OID_AUTO, platform_exec_logging, CTLFLAG_RW, &platform_exec_logging, 0,
253 "log cdhashes for all platform binary executions");
254
255 static os_log_t peLog = OS_LOG_DEFAULT;
256
257 struct image_params; /* Forward */
258 static int exec_activate_image(struct image_params *imgp);
259 static int exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp);
260 static int load_return_to_errno(load_return_t lrtn);
261 static int execargs_alloc(struct image_params *imgp);
262 static int execargs_free(struct image_params *imgp);
263 static int exec_check_permissions(struct image_params *imgp);
264 static int exec_extract_strings(struct image_params *imgp);
265 static int exec_add_apple_strings(struct image_params *imgp, const load_result_t *load_result);
266 static int exec_handle_sugid(struct image_params *imgp);
267 static int sugid_scripts = 0;
268 SYSCTL_INT (_kern, OID_AUTO, sugid_scripts, CTLFLAG_RW | CTLFLAG_LOCKED, &sugid_scripts, 0, "");
269 static kern_return_t create_unix_stack(vm_map_t map, load_result_t* load_result, proc_t p);
270 static int copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size);
271 static void exec_resettextvp(proc_t, struct image_params *);
272 static int check_for_signature(proc_t, struct image_params *);
273 static void exec_prefault_data(proc_t, struct image_params *, load_result_t *);
274 static errno_t exec_handle_port_actions(struct image_params *imgp, boolean_t * portwatch_present, ipc_port_t * portwatch_ports);
275 static errno_t exec_handle_spawnattr_policy(proc_t p, int psa_apptype, uint64_t psa_qos_clamp, uint64_t psa_darwin_role,
276 ipc_port_t * portwatch_ports, int portwatch_count);
277
278 /*
279 * exec_add_user_string
280 *
281 * Add the requested string to the string space area.
282 *
283 * Parameters; struct image_params * image parameter block
284 * user_addr_t string to add to strings area
285 * int segment from which string comes
286 * boolean_t TRUE if string contributes to NCARGS
287 *
288 * Returns: 0 Success
289 * !0 Failure errno from copyinstr()
290 *
291 * Implicit returns:
292 * (imgp->ip_strendp) updated location of next add, if any
293 * (imgp->ip_strspace) updated byte count of space remaining
294 * (imgp->ip_argspace) updated byte count of space in NCARGS
295 */
296 static int
297 exec_add_user_string(struct image_params *imgp, user_addr_t str, int seg, boolean_t is_ncargs)
298 {
299 int error = 0;
300
301 do {
302 size_t len = 0;
303 int space;
304
305 if (is_ncargs)
306 space = imgp->ip_argspace; /* by definition smaller than ip_strspace */
307 else
308 space = imgp->ip_strspace;
309
310 if (space <= 0) {
311 error = E2BIG;
312 break;
313 }
314
315 if (!UIO_SEG_IS_USER_SPACE(seg)) {
316 char *kstr = CAST_DOWN(char *,str); /* SAFE */
317 error = copystr(kstr, imgp->ip_strendp, space, &len);
318 } else {
319 error = copyinstr(str, imgp->ip_strendp, space, &len);
320 }
321
322 imgp->ip_strendp += len;
323 imgp->ip_strspace -= len;
324 if (is_ncargs)
325 imgp->ip_argspace -= len;
326
327 } while (error == ENAMETOOLONG);
328
329 return error;
330 }
331
332 /*
333 * dyld is now passed the executable path as a getenv-like variable
334 * in the same fashion as the stack_guard and malloc_entropy keys.
335 */
336 #define EXECUTABLE_KEY "executable_path="
337
338 /*
339 * exec_save_path
340 *
341 * To support new app package launching for Mac OS X, the dyld needs the
342 * first argument to execve() stored on the user stack.
343 *
344 * Save the executable path name at the bottom of the strings area and set
345 * the argument vector pointer to the location following that to indicate
346 * the start of the argument and environment tuples, setting the remaining
347 * string space count to the size of the string area minus the path length.
348 *
349 * Parameters; struct image_params * image parameter block
350 * char * path used to invoke program
351 * int segment from which path comes
352 *
353 * Returns: int 0 Success
354 * EFAULT Bad address
355 * copy[in]str:EFAULT Bad address
356 * copy[in]str:ENAMETOOLONG Filename too long
357 *
358 * Implicit returns:
359 * (imgp->ip_strings) saved path
360 * (imgp->ip_strspace) space remaining in ip_strings
361 * (imgp->ip_strendp) start of remaining copy area
362 * (imgp->ip_argspace) space remaining of NCARGS
363 * (imgp->ip_applec) Initial applev[0]
364 *
365 * Note: We have to do this before the initial namei() since in the
366 * path contains symbolic links, namei() will overwrite the
367 * original path buffer contents. If the last symbolic link
368 * resolved was a relative pathname, we would lose the original
369 * "path", which could be an absolute pathname. This might be
370 * unacceptable for dyld.
371 */
372 static int
373 exec_save_path(struct image_params *imgp, user_addr_t path, int seg, const char **excpath)
374 {
375 int error;
376 size_t len;
377 char *kpath;
378
379 // imgp->ip_strings can come out of a cache, so we need to obliterate the
380 // old path.
381 memset(imgp->ip_strings, '\0', strlen(EXECUTABLE_KEY) + MAXPATHLEN);
382
383 len = MIN(MAXPATHLEN, imgp->ip_strspace);
384
385 switch(seg) {
386 case UIO_USERSPACE32:
387 case UIO_USERSPACE64: /* Same for copyin()... */
388 error = copyinstr(path, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len);
389 break;
390 case UIO_SYSSPACE:
391 kpath = CAST_DOWN(char *,path); /* SAFE */
392 error = copystr(kpath, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len);
393 break;
394 default:
395 error = EFAULT;
396 break;
397 }
398
399 if (!error) {
400 bcopy(EXECUTABLE_KEY, imgp->ip_strings, strlen(EXECUTABLE_KEY));
401 len += strlen(EXECUTABLE_KEY);
402
403 imgp->ip_strendp += len;
404 imgp->ip_strspace -= len;
405
406 if (excpath) {
407 *excpath = imgp->ip_strings + strlen(EXECUTABLE_KEY);
408 }
409 }
410
411 return(error);
412 }
413
414 /*
415 * exec_reset_save_path
416 *
417 * If we detect a shell script, we need to reset the string area
418 * state so that the interpreter can be saved onto the stack.
419
420 * Parameters; struct image_params * image parameter block
421 *
422 * Returns: int 0 Success
423 *
424 * Implicit returns:
425 * (imgp->ip_strings) saved path
426 * (imgp->ip_strspace) space remaining in ip_strings
427 * (imgp->ip_strendp) start of remaining copy area
428 * (imgp->ip_argspace) space remaining of NCARGS
429 *
430 */
431 static int
432 exec_reset_save_path(struct image_params *imgp)
433 {
434 imgp->ip_strendp = imgp->ip_strings;
435 imgp->ip_argspace = NCARGS;
436 imgp->ip_strspace = ( NCARGS + PAGE_SIZE );
437
438 return (0);
439 }
440
441 /*
442 * exec_shell_imgact
443 *
444 * Image activator for interpreter scripts. If the image begins with
445 * the characters "#!", then it is an interpreter script. Verify the
446 * length of the script line indicating the interpreter is not in
447 * excess of the maximum allowed size. If this is the case, then
448 * break out the arguments, if any, which are separated by white
449 * space, and copy them into the argument save area as if they were
450 * provided on the command line before all other arguments. The line
451 * ends when we encounter a comment character ('#') or newline.
452 *
453 * Parameters; struct image_params * image parameter block
454 *
455 * Returns: -1 not an interpreter (keep looking)
456 * -3 Success: interpreter: relookup
457 * >0 Failure: interpreter: error number
458 *
459 * A return value other than -1 indicates subsequent image activators should
460 * not be given the opportunity to attempt to activate the image.
461 */
462 static int
463 exec_shell_imgact(struct image_params *imgp)
464 {
465 char *vdata = imgp->ip_vdata;
466 char *ihp;
467 char *line_startp, *line_endp;
468 char *interp;
469
470 /*
471 * Make sure it's a shell script. If we've already redirected
472 * from an interpreted file once, don't do it again.
473 */
474 if (vdata[0] != '#' ||
475 vdata[1] != '!' ||
476 (imgp->ip_flags & IMGPF_INTERPRET) != 0) {
477 return (-1);
478 }
479
480 if (imgp->ip_origcputype != 0) {
481 /* Fat header previously matched, don't allow shell script inside */
482 return (-1);
483 }
484
485 imgp->ip_flags |= IMGPF_INTERPRET;
486 imgp->ip_interp_sugid_fd = -1;
487 imgp->ip_interp_buffer[0] = '\0';
488
489 /* Check to see if SUGID scripts are permitted. If they aren't then
490 * clear the SUGID bits.
491 * imgp->ip_vattr is known to be valid.
492 */
493 if (sugid_scripts == 0) {
494 imgp->ip_origvattr->va_mode &= ~(VSUID | VSGID);
495 }
496
497 /* Try to find the first non-whitespace character */
498 for( ihp = &vdata[2]; ihp < &vdata[IMG_SHSIZE]; ihp++ ) {
499 if (IS_EOL(*ihp)) {
500 /* Did not find interpreter, "#!\n" */
501 return (ENOEXEC);
502 } else if (IS_WHITESPACE(*ihp)) {
503 /* Whitespace, like "#! /bin/sh\n", keep going. */
504 } else {
505 /* Found start of interpreter */
506 break;
507 }
508 }
509
510 if (ihp == &vdata[IMG_SHSIZE]) {
511 /* All whitespace, like "#! " */
512 return (ENOEXEC);
513 }
514
515 line_startp = ihp;
516
517 /* Try to find the end of the interpreter+args string */
518 for ( ; ihp < &vdata[IMG_SHSIZE]; ihp++ ) {
519 if (IS_EOL(*ihp)) {
520 /* Got it */
521 break;
522 } else {
523 /* Still part of interpreter or args */
524 }
525 }
526
527 if (ihp == &vdata[IMG_SHSIZE]) {
528 /* A long line, like "#! blah blah blah" without end */
529 return (ENOEXEC);
530 }
531
532 /* Backtrack until we find the last non-whitespace */
533 while (IS_EOL(*ihp) || IS_WHITESPACE(*ihp)) {
534 ihp--;
535 }
536
537 /* The character after the last non-whitespace is our logical end of line */
538 line_endp = ihp + 1;
539
540 /*
541 * Now we have pointers to the usable part of:
542 *
543 * "#! /usr/bin/int first second third \n"
544 * ^ line_startp ^ line_endp
545 */
546
547 /* copy the interpreter name */
548 interp = imgp->ip_interp_buffer;
549 for ( ihp = line_startp; (ihp < line_endp) && !IS_WHITESPACE(*ihp); ihp++)
550 *interp++ = *ihp;
551 *interp = '\0';
552
553 exec_reset_save_path(imgp);
554 exec_save_path(imgp, CAST_USER_ADDR_T(imgp->ip_interp_buffer),
555 UIO_SYSSPACE, NULL);
556
557 /* Copy the entire interpreter + args for later processing into argv[] */
558 interp = imgp->ip_interp_buffer;
559 for ( ihp = line_startp; (ihp < line_endp); ihp++)
560 *interp++ = *ihp;
561 *interp = '\0';
562
563 #if !SECURE_KERNEL
564 /*
565 * If we have an SUID or SGID script, create a file descriptor
566 * from the vnode and pass /dev/fd/%d instead of the actual
567 * path name so that the script does not get opened twice
568 */
569 if (imgp->ip_origvattr->va_mode & (VSUID | VSGID)) {
570 proc_t p;
571 struct fileproc *fp;
572 int fd;
573 int error;
574
575 p = vfs_context_proc(imgp->ip_vfs_context);
576 error = falloc(p, &fp, &fd, imgp->ip_vfs_context);
577 if (error)
578 return(error);
579
580 fp->f_fglob->fg_flag = FREAD;
581 fp->f_fglob->fg_ops = &vnops;
582 fp->f_fglob->fg_data = (caddr_t)imgp->ip_vp;
583
584 proc_fdlock(p);
585 procfdtbl_releasefd(p, fd, NULL);
586 fp_drop(p, fd, fp, 1);
587 proc_fdunlock(p);
588 vnode_ref(imgp->ip_vp);
589
590 imgp->ip_interp_sugid_fd = fd;
591 }
592 #endif
593
594 return (-3);
595 }
596
597
598
599 /*
600 * exec_fat_imgact
601 *
602 * Image activator for fat 1.0 binaries. If the binary is fat, then we
603 * need to select an image from it internally, and make that the image
604 * we are going to attempt to execute. At present, this consists of
605 * reloading the first page for the image with a first page from the
606 * offset location indicated by the fat header.
607 *
608 * Parameters; struct image_params * image parameter block
609 *
610 * Returns: -1 not a fat binary (keep looking)
611 * -2 Success: encapsulated binary: reread
612 * >0 Failure: error number
613 *
614 * Important: This image activator is byte order neutral.
615 *
616 * Note: A return value other than -1 indicates subsequent image
617 * activators should not be given the opportunity to attempt
618 * to activate the image.
619 *
620 * If we find an encapsulated binary, we make no assertions
621 * about its validity; instead, we leave that up to a rescan
622 * for an activator to claim it, and, if it is claimed by one,
623 * that activator is responsible for determining validity.
624 */
625 static int
626 exec_fat_imgact(struct image_params *imgp)
627 {
628 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
629 kauth_cred_t cred = kauth_cred_proc_ref(p);
630 struct fat_header *fat_header = (struct fat_header *)imgp->ip_vdata;
631 struct _posix_spawnattr *psa = NULL;
632 struct fat_arch fat_arch;
633 int resid, error;
634 load_return_t lret;
635
636 if (imgp->ip_origcputype != 0) {
637 /* Fat header previously matched, don't allow another fat file inside */
638 error = -1; /* not claimed */
639 goto bad;
640 }
641
642 /* Make sure it's a fat binary */
643 if (OSSwapBigToHostInt32(fat_header->magic) != FAT_MAGIC) {
644 error = -1; /* not claimed */
645 goto bad;
646 }
647
648 /* imgp->ip_vdata has PAGE_SIZE, zerofilled if the file is smaller */
649 lret = fatfile_validate_fatarches((vm_offset_t)fat_header, PAGE_SIZE);
650 if (lret != LOAD_SUCCESS) {
651 error = load_return_to_errno(lret);
652 goto bad;
653 }
654
655 /* If posix_spawn binprefs exist, respect those prefs. */
656 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
657 if (psa != NULL && psa->psa_binprefs[0] != 0) {
658 uint32_t pr = 0;
659
660 /* Check each preference listed against all arches in header */
661 for (pr = 0; pr < NBINPREFS; pr++) {
662 cpu_type_t pref = psa->psa_binprefs[pr];
663 if (pref == 0) {
664 /* No suitable arch in the pref list */
665 error = EBADARCH;
666 goto bad;
667 }
668
669 if (pref == CPU_TYPE_ANY) {
670 /* Fall through to regular grading */
671 goto regular_grading;
672 }
673
674 lret = fatfile_getbestarch_for_cputype(pref,
675 (vm_offset_t)fat_header,
676 PAGE_SIZE,
677 &fat_arch);
678 if (lret == LOAD_SUCCESS) {
679 goto use_arch;
680 }
681 }
682
683 /* Requested binary preference was not honored */
684 error = EBADEXEC;
685 goto bad;
686 }
687
688 regular_grading:
689 /* Look up our preferred architecture in the fat file. */
690 lret = fatfile_getbestarch((vm_offset_t)fat_header,
691 PAGE_SIZE,
692 &fat_arch);
693 if (lret != LOAD_SUCCESS) {
694 error = load_return_to_errno(lret);
695 goto bad;
696 }
697
698 use_arch:
699 /* Read the Mach-O header out of fat_arch */
700 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata,
701 PAGE_SIZE, fat_arch.offset,
702 UIO_SYSSPACE, (IO_UNIT|IO_NODELOCKED),
703 cred, &resid, p);
704 if (error) {
705 goto bad;
706 }
707
708 if (resid) {
709 memset(imgp->ip_vdata + (PAGE_SIZE - resid), 0x0, resid);
710 }
711
712 /* Success. Indicate we have identified an encapsulated binary */
713 error = -2;
714 imgp->ip_arch_offset = (user_size_t)fat_arch.offset;
715 imgp->ip_arch_size = (user_size_t)fat_arch.size;
716 imgp->ip_origcputype = fat_arch.cputype;
717 imgp->ip_origcpusubtype = fat_arch.cpusubtype;
718
719 bad:
720 kauth_cred_unref(&cred);
721 return (error);
722 }
723
724 static int
725 activate_exec_state(task_t task, proc_t p, thread_t thread, load_result_t *result)
726 {
727 int ret;
728
729 task_set_dyld_info(task, MACH_VM_MIN_ADDRESS, 0);
730 if (result->is64bit) {
731 task_set_64bit(task, TRUE);
732 OSBitOrAtomic(P_LP64, &p->p_flag);
733 } else {
734 task_set_64bit(task, FALSE);
735 OSBitAndAtomic(~((uint32_t)P_LP64), &p->p_flag);
736 }
737
738 ret = thread_state_initialize(thread);
739 if (ret != KERN_SUCCESS) {
740 return ret;
741 }
742
743 if (result->threadstate) {
744 uint32_t *ts = result->threadstate;
745 uint32_t total_size = result->threadstate_sz;
746
747 while (total_size > 0) {
748 uint32_t flavor = *ts++;
749 uint32_t size = *ts++;
750
751 ret = thread_setstatus(thread, flavor, (thread_state_t)ts, size);
752 if (ret) {
753 return ret;
754 }
755 ts += size;
756 total_size -= (size + 2) * sizeof(uint32_t);
757 }
758 }
759
760 thread_setentrypoint(thread, result->entry_point);
761
762 return KERN_SUCCESS;
763 }
764
765
766 /*
767 * Set p->p_comm and p->p_name to the name passed to exec
768 */
769 static void
770 set_proc_name(struct image_params *imgp, proc_t p)
771 {
772 int p_name_len = sizeof(p->p_name) - 1;
773
774 if (imgp->ip_ndp->ni_cnd.cn_namelen > p_name_len) {
775 imgp->ip_ndp->ni_cnd.cn_namelen = p_name_len;
776 }
777
778 bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_name,
779 (unsigned)imgp->ip_ndp->ni_cnd.cn_namelen);
780 p->p_name[imgp->ip_ndp->ni_cnd.cn_namelen] = '\0';
781
782 if (imgp->ip_ndp->ni_cnd.cn_namelen > MAXCOMLEN) {
783 imgp->ip_ndp->ni_cnd.cn_namelen = MAXCOMLEN;
784 }
785
786 bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_comm,
787 (unsigned)imgp->ip_ndp->ni_cnd.cn_namelen);
788 p->p_comm[imgp->ip_ndp->ni_cnd.cn_namelen] = '\0';
789 }
790
791 static uint64_t get_va_fsid(struct vnode_attr *vap)
792 {
793 if (VATTR_IS_SUPPORTED(vap, va_fsid64)) {
794 return *(uint64_t *)&vap->va_fsid64;
795 } else {
796 return vap->va_fsid;
797 }
798 }
799
800 /*
801 * exec_mach_imgact
802 *
803 * Image activator for mach-o 1.0 binaries.
804 *
805 * Parameters; struct image_params * image parameter block
806 *
807 * Returns: -1 not a fat binary (keep looking)
808 * -2 Success: encapsulated binary: reread
809 * >0 Failure: error number
810 * EBADARCH Mach-o binary, but with an unrecognized
811 * architecture
812 * ENOMEM No memory for child process after -
813 * can only happen after vfork()
814 *
815 * Important: This image activator is NOT byte order neutral.
816 *
817 * Note: A return value other than -1 indicates subsequent image
818 * activators should not be given the opportunity to attempt
819 * to activate the image.
820 *
821 * TODO: More gracefully handle failures after vfork
822 */
823 static int
824 exec_mach_imgact(struct image_params *imgp)
825 {
826 struct mach_header *mach_header = (struct mach_header *)imgp->ip_vdata;
827 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
828 int error = 0;
829 task_t task;
830 task_t new_task = NULL; /* protected by vfexec */
831 thread_t thread;
832 struct uthread *uthread;
833 vm_map_t old_map = VM_MAP_NULL;
834 vm_map_t map = VM_MAP_NULL;
835 load_return_t lret;
836 load_result_t load_result;
837 struct _posix_spawnattr *psa = NULL;
838 int spawn = (imgp->ip_flags & IMGPF_SPAWN);
839 int vfexec = (imgp->ip_flags & IMGPF_VFORK_EXEC);
840 int exec = (imgp->ip_flags & IMGPF_EXEC);
841 os_reason_t exec_failure_reason = OS_REASON_NULL;
842
843 /*
844 * make sure it's a Mach-O 1.0 or Mach-O 2.0 binary; the difference
845 * is a reserved field on the end, so for the most part, we can
846 * treat them as if they were identical. Reverse-endian Mach-O
847 * binaries are recognized but not compatible.
848 */
849 if ((mach_header->magic == MH_CIGAM) ||
850 (mach_header->magic == MH_CIGAM_64)) {
851 error = EBADARCH;
852 goto bad;
853 }
854
855 if ((mach_header->magic != MH_MAGIC) &&
856 (mach_header->magic != MH_MAGIC_64)) {
857 error = -1;
858 goto bad;
859 }
860
861 if (mach_header->filetype != MH_EXECUTE) {
862 error = -1;
863 goto bad;
864 }
865
866 if (imgp->ip_origcputype != 0) {
867 /* Fat header previously had an idea about this thin file */
868 if (imgp->ip_origcputype != mach_header->cputype ||
869 imgp->ip_origcpusubtype != mach_header->cpusubtype) {
870 error = EBADARCH;
871 goto bad;
872 }
873 } else {
874 imgp->ip_origcputype = mach_header->cputype;
875 imgp->ip_origcpusubtype = mach_header->cpusubtype;
876 }
877
878 task = current_task();
879 thread = current_thread();
880 uthread = get_bsdthread_info(thread);
881
882 if ((mach_header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64)
883 imgp->ip_flags |= IMGPF_IS_64BIT;
884
885 /* If posix_spawn binprefs exist, respect those prefs. */
886 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
887 if (psa != NULL && psa->psa_binprefs[0] != 0) {
888 int pr = 0;
889 for (pr = 0; pr < NBINPREFS; pr++) {
890 cpu_type_t pref = psa->psa_binprefs[pr];
891 if (pref == 0) {
892 /* No suitable arch in the pref list */
893 error = EBADARCH;
894 goto bad;
895 }
896
897 if (pref == CPU_TYPE_ANY) {
898 /* Jump to regular grading */
899 goto grade;
900 }
901
902 if (pref == imgp->ip_origcputype) {
903 /* We have a match! */
904 goto grade;
905 }
906 }
907 error = EBADARCH;
908 goto bad;
909 }
910 grade:
911 if (!grade_binary(imgp->ip_origcputype, imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK)) {
912 error = EBADARCH;
913 goto bad;
914 }
915
916 /* Copy in arguments/environment from the old process */
917 error = exec_extract_strings(imgp);
918 if (error)
919 goto bad;
920
921 AUDIT_ARG(argv, imgp->ip_startargv, imgp->ip_argc,
922 imgp->ip_endargv - imgp->ip_startargv);
923 AUDIT_ARG(envv, imgp->ip_endargv, imgp->ip_envc,
924 imgp->ip_endenvv - imgp->ip_endargv);
925
926 /*
927 * We are being called to activate an image subsequent to a vfork()
928 * operation; in this case, we know that our task, thread, and
929 * uthread are actually those of our parent, and our proc, which we
930 * obtained indirectly from the image_params vfs_context_t, is the
931 * new child process.
932 */
933 if (vfexec) {
934 imgp->ip_new_thread = fork_create_child(task, NULL, p, FALSE, (imgp->ip_flags & IMGPF_IS_64BIT), FALSE);
935 /* task and thread ref returned, will be released in __mac_execve */
936 if (imgp->ip_new_thread == NULL) {
937 error = ENOMEM;
938 goto bad;
939 }
940 }
941
942
943 /* reset local idea of thread, uthread, task */
944 thread = imgp->ip_new_thread;
945 uthread = get_bsdthread_info(thread);
946 task = new_task = get_threadtask(thread);
947
948 /*
949 * Load the Mach-O file.
950 *
951 * NOTE: An error after this point indicates we have potentially
952 * destroyed or overwritten some process state while attempting an
953 * execve() following a vfork(), which is an unrecoverable condition.
954 * We send the new process an immediate SIGKILL to avoid it executing
955 * any instructions in the mutated address space. For true spawns,
956 * this is not the case, and "too late" is still not too late to
957 * return an error code to the parent process.
958 */
959
960 /*
961 * Actually load the image file we previously decided to load.
962 */
963 lret = load_machfile(imgp, mach_header, thread, &map, &load_result);
964 if (lret != LOAD_SUCCESS) {
965 error = load_return_to_errno(lret);
966
967 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
968 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO, 0, 0);
969 if (lret == LOAD_BADMACHO_UPX) {
970 /* set anything that might be useful in the crash report */
971 set_proc_name(imgp, p);
972
973 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_UPX);
974 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
975 exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE;
976 } else {
977 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO);
978 }
979
980 goto badtoolate;
981 }
982
983 proc_lock(p);
984 p->p_cputype = imgp->ip_origcputype;
985 p->p_cpusubtype = imgp->ip_origcpusubtype;
986 proc_unlock(p);
987
988 vm_map_set_user_wire_limit(map, p->p_rlimit[RLIMIT_MEMLOCK].rlim_cur);
989
990 /*
991 * Set code-signing flags if this binary is signed, or if parent has
992 * requested them on exec.
993 */
994 if (load_result.csflags & CS_VALID) {
995 imgp->ip_csflags |= load_result.csflags &
996 (CS_VALID|CS_SIGNED|CS_DEV_CODE|
997 CS_HARD|CS_KILL|CS_RESTRICT|CS_ENFORCEMENT|CS_REQUIRE_LV|
998 CS_ENTITLEMENTS_VALIDATED|CS_DYLD_PLATFORM|
999 CS_ENTITLEMENT_FLAGS|
1000 CS_EXEC_SET_HARD|CS_EXEC_SET_KILL|CS_EXEC_SET_ENFORCEMENT);
1001 } else {
1002 imgp->ip_csflags &= ~CS_VALID;
1003 }
1004
1005 if (p->p_csflags & CS_EXEC_SET_HARD)
1006 imgp->ip_csflags |= CS_HARD;
1007 if (p->p_csflags & CS_EXEC_SET_KILL)
1008 imgp->ip_csflags |= CS_KILL;
1009 if (p->p_csflags & CS_EXEC_SET_ENFORCEMENT)
1010 imgp->ip_csflags |= CS_ENFORCEMENT;
1011 if (p->p_csflags & CS_EXEC_INHERIT_SIP) {
1012 if (p->p_csflags & CS_INSTALLER)
1013 imgp->ip_csflags |= CS_INSTALLER;
1014 if (p->p_csflags & CS_DATAVAULT_CONTROLLER)
1015 imgp->ip_csflags |= CS_DATAVAULT_CONTROLLER;
1016 if (p->p_csflags & CS_NVRAM_UNRESTRICTED)
1017 imgp->ip_csflags |= CS_NVRAM_UNRESTRICTED;
1018 }
1019
1020 /*
1021 * Set up the system reserved areas in the new address space.
1022 */
1023 vm_map_exec(map, task, load_result.is64bit, (void *)p->p_fd->fd_rdir, cpu_type());
1024
1025 /*
1026 * Close file descriptors which specify close-on-exec.
1027 */
1028 fdexec(p, psa != NULL ? psa->psa_flags : 0, exec);
1029
1030 /*
1031 * deal with set[ug]id.
1032 */
1033 error = exec_handle_sugid(imgp);
1034 if (error) {
1035 vm_map_deallocate(map);
1036
1037 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1038 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_SUGID_FAILURE, 0, 0);
1039 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SUGID_FAILURE);
1040 goto badtoolate;
1041 }
1042
1043 /*
1044 * Commit to new map.
1045 *
1046 * Swap the new map for the old for target task, which consumes
1047 * our new map reference but each leaves us responsible for the
1048 * old_map reference. That lets us get off the pmap associated
1049 * with it, and then we can release it.
1050 *
1051 * The map needs to be set on the target task which is different
1052 * than current task, thus swap_task_map is used instead of
1053 * vm_map_switch.
1054 */
1055 old_map = swap_task_map(task, thread, map);
1056 vm_map_deallocate(old_map);
1057 old_map = NULL;
1058
1059 lret = activate_exec_state(task, p, thread, &load_result);
1060 if (lret != KERN_SUCCESS) {
1061
1062 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1063 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_ACTV_THREADSTATE, 0, 0);
1064 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_ACTV_THREADSTATE);
1065 goto badtoolate;
1066 }
1067
1068 /*
1069 * deal with voucher on exec-calling thread.
1070 */
1071 if (imgp->ip_new_thread == NULL)
1072 thread_set_mach_voucher(current_thread(), IPC_VOUCHER_NULL);
1073
1074 /* Make sure we won't interrupt ourself signalling a partial process */
1075 if (!vfexec && !spawn && (p->p_lflag & P_LTRACED))
1076 psignal(p, SIGTRAP);
1077
1078 if (load_result.unixproc &&
1079 create_unix_stack(get_task_map(task),
1080 &load_result,
1081 p) != KERN_SUCCESS) {
1082 error = load_return_to_errno(LOAD_NOSPACE);
1083
1084 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1085 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_STACK_ALLOC, 0, 0);
1086 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_STACK_ALLOC);
1087 goto badtoolate;
1088 }
1089
1090 error = exec_add_apple_strings(imgp, &load_result);
1091 if (error) {
1092
1093 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1094 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_APPLE_STRING_INIT, 0, 0);
1095 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_APPLE_STRING_INIT);
1096 goto badtoolate;
1097 }
1098
1099 /* Switch to target task's map to copy out strings */
1100 old_map = vm_map_switch(get_task_map(task));
1101
1102 if (load_result.unixproc) {
1103 user_addr_t ap;
1104
1105 /*
1106 * Copy the strings area out into the new process address
1107 * space.
1108 */
1109 ap = p->user_stack;
1110 error = exec_copyout_strings(imgp, &ap);
1111 if (error) {
1112 vm_map_switch(old_map);
1113
1114 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1115 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_STRINGS, 0, 0);
1116 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_STRINGS);
1117 goto badtoolate;
1118 }
1119 /* Set the stack */
1120 thread_setuserstack(thread, ap);
1121 }
1122
1123 if (load_result.dynlinker) {
1124 uint64_t ap;
1125 int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
1126
1127 /* Adjust the stack */
1128 ap = thread_adjuserstack(thread, -new_ptr_size);
1129 error = copyoutptr(load_result.mach_header, ap, new_ptr_size);
1130
1131 if (error) {
1132 vm_map_switch(old_map);
1133
1134 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1135 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_DYNLINKER, 0, 0);
1136 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_DYNLINKER);
1137 goto badtoolate;
1138 }
1139 task_set_dyld_info(task, load_result.all_image_info_addr,
1140 load_result.all_image_info_size);
1141 }
1142
1143 /* Avoid immediate VM faults back into kernel */
1144 exec_prefault_data(p, imgp, &load_result);
1145
1146 vm_map_switch(old_map);
1147
1148 /* Stop profiling */
1149 stopprofclock(p);
1150
1151 /*
1152 * Reset signal state.
1153 */
1154 execsigs(p, thread);
1155
1156 /*
1157 * need to cancel async IO requests that can be cancelled and wait for those
1158 * already active. MAY BLOCK!
1159 */
1160 _aio_exec( p );
1161
1162 #if SYSV_SHM
1163 /* FIXME: Till vmspace inherit is fixed: */
1164 if (!vfexec && p->vm_shm)
1165 shmexec(p);
1166 #endif
1167 #if SYSV_SEM
1168 /* Clean up the semaphores */
1169 semexit(p);
1170 #endif
1171
1172 /*
1173 * Remember file name for accounting.
1174 */
1175 p->p_acflag &= ~AFORK;
1176
1177 set_proc_name(imgp, p);
1178
1179 #if CONFIG_SECLUDED_MEMORY
1180 if (secluded_for_apps &&
1181 load_result.platform_binary) {
1182 if (strncmp(p->p_name,
1183 "Camera",
1184 sizeof (p->p_name)) == 0) {
1185 task_set_could_use_secluded_mem(task, TRUE);
1186 } else {
1187 task_set_could_use_secluded_mem(task, FALSE);
1188 }
1189 if (strncmp(p->p_name,
1190 "mediaserverd",
1191 sizeof (p->p_name)) == 0) {
1192 task_set_could_also_use_secluded_mem(task, TRUE);
1193 }
1194 }
1195 #endif /* CONFIG_SECLUDED_MEMORY */
1196
1197 pal_dbg_set_task_name(task);
1198
1199 /*
1200 * The load result will have already been munged by AMFI to include the
1201 * platform binary flag if boot-args dictated it (AMFI will mark anything
1202 * that doesn't go through the upcall path as a platform binary if its
1203 * enforcement is disabled).
1204 */
1205 if (load_result.platform_binary) {
1206 if (cs_debug) {
1207 printf("setting platform binary on task: pid = %d\n", p->p_pid);
1208 }
1209
1210 /*
1211 * We must use 'task' here because the proc's task has not yet been
1212 * switched to the new one.
1213 */
1214 task_set_platform_binary(task, TRUE);
1215 } else {
1216 if (cs_debug) {
1217 printf("clearing platform binary on task: pid = %d\n", p->p_pid);
1218 }
1219
1220 task_set_platform_binary(task, FALSE);
1221 }
1222
1223 #if DEVELOPMENT || DEBUG
1224 /*
1225 * Update the pid an proc name for importance base if any
1226 */
1227 task_importance_update_owner_info(task);
1228 #endif
1229
1230 memcpy(&p->p_uuid[0], &load_result.uuid[0], sizeof(p->p_uuid));
1231
1232 #if CONFIG_DTRACE
1233 dtrace_proc_exec(p);
1234 #endif
1235
1236 if (kdebug_enable) {
1237 long dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4;
1238
1239 /*
1240 * Collect the pathname for tracing
1241 */
1242 kdbg_trace_string(p, &dbg_arg1, &dbg_arg2, &dbg_arg3, &dbg_arg4);
1243
1244 uintptr_t fsid = 0, fileid = 0;
1245 if (imgp->ip_vattr) {
1246 uint64_t fsid64 = get_va_fsid(imgp->ip_vattr);
1247 fsid = fsid64;
1248 fileid = imgp->ip_vattr->va_fileid;
1249 // check for (unexpected) overflow and trace zero in that case
1250 if (fsid != fsid64 || fileid != imgp->ip_vattr->va_fileid) {
1251 fsid = fileid = 0;
1252 }
1253 }
1254 KERNEL_DEBUG_CONSTANT1(TRACE_DATA_EXEC | DBG_FUNC_NONE,
1255 p->p_pid , fsid, fileid, 0, (uintptr_t)thread_tid(thread));
1256 KERNEL_DEBUG_CONSTANT1(TRACE_STRING_EXEC | DBG_FUNC_NONE,
1257 dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4, (uintptr_t)thread_tid(thread));
1258 }
1259
1260 /*
1261 * If posix_spawned with the START_SUSPENDED flag, stop the
1262 * process before it runs.
1263 */
1264 if (imgp->ip_px_sa != NULL) {
1265 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
1266 if (psa->psa_flags & POSIX_SPAWN_START_SUSPENDED) {
1267 proc_lock(p);
1268 p->p_stat = SSTOP;
1269 proc_unlock(p);
1270 (void) task_suspend_internal(task);
1271 }
1272 }
1273
1274 /*
1275 * mark as execed, wakeup the process that vforked (if any) and tell
1276 * it that it now has its own resources back
1277 */
1278 OSBitOrAtomic(P_EXEC, &p->p_flag);
1279 proc_resetregister(p);
1280 if (p->p_pptr && (p->p_lflag & P_LPPWAIT)) {
1281 proc_lock(p);
1282 p->p_lflag &= ~P_LPPWAIT;
1283 proc_unlock(p);
1284 wakeup((caddr_t)p->p_pptr);
1285 }
1286
1287 /*
1288 * Pay for our earlier safety; deliver the delayed signals from
1289 * the incomplete vfexec process now that it's complete.
1290 */
1291 if (vfexec && (p->p_lflag & P_LTRACED)) {
1292 psignal_vfork(p, new_task, thread, SIGTRAP);
1293 }
1294
1295 goto done;
1296
1297 badtoolate:
1298 /* Don't allow child process to execute any instructions */
1299 if (!spawn) {
1300 if (vfexec) {
1301 assert(exec_failure_reason != OS_REASON_NULL);
1302 psignal_vfork_with_reason(p, new_task, thread, SIGKILL, exec_failure_reason);
1303 exec_failure_reason = OS_REASON_NULL;
1304 } else {
1305 assert(exec_failure_reason != OS_REASON_NULL);
1306 psignal_with_reason(p, SIGKILL, exec_failure_reason);
1307 exec_failure_reason = OS_REASON_NULL;
1308
1309 if (exec) {
1310 /* Terminate the exec copy task */
1311 task_terminate_internal(task);
1312 }
1313 }
1314
1315 /* We can't stop this system call at this point, so just pretend we succeeded */
1316 error = 0;
1317 } else {
1318 os_reason_free(exec_failure_reason);
1319 exec_failure_reason = OS_REASON_NULL;
1320 }
1321
1322 done:
1323 if (!spawn) {
1324 /* notify only if it has not failed due to FP Key error */
1325 if ((p->p_lflag & P_LTERM_DECRYPTFAIL) == 0)
1326 proc_knote(p, NOTE_EXEC);
1327 }
1328
1329 if (load_result.threadstate) {
1330 kfree(load_result.threadstate, load_result.threadstate_sz);
1331 load_result.threadstate = NULL;
1332 }
1333
1334 bad:
1335 /* If we hit this, we likely would have leaked an exit reason */
1336 assert(exec_failure_reason == OS_REASON_NULL);
1337 return(error);
1338 }
1339
1340
1341
1342
1343 /*
1344 * Our image activator table; this is the table of the image types we are
1345 * capable of loading. We list them in order of preference to ensure the
1346 * fastest image load speed.
1347 *
1348 * XXX hardcoded, for now; should use linker sets
1349 */
1350 struct execsw {
1351 int (*ex_imgact)(struct image_params *);
1352 const char *ex_name;
1353 } execsw[] = {
1354 { exec_mach_imgact, "Mach-o Binary" },
1355 { exec_fat_imgact, "Fat Binary" },
1356 { exec_shell_imgact, "Interpreter Script" },
1357 { NULL, NULL}
1358 };
1359
1360
1361 /*
1362 * exec_activate_image
1363 *
1364 * Description: Iterate through the available image activators, and activate
1365 * the image associated with the imgp structure. We start with
1366 * the activator for Mach-o binaries followed by that for Fat binaries
1367 * for Interpreter scripts.
1368 *
1369 * Parameters: struct image_params * Image parameter block
1370 *
1371 * Returns: 0 Success
1372 * EBADEXEC The executable is corrupt/unknown
1373 * execargs_alloc:EINVAL Invalid argument
1374 * execargs_alloc:EACCES Permission denied
1375 * execargs_alloc:EINTR Interrupted function
1376 * execargs_alloc:ENOMEM Not enough space
1377 * exec_save_path:EFAULT Bad address
1378 * exec_save_path:ENAMETOOLONG Filename too long
1379 * exec_check_permissions:EACCES Permission denied
1380 * exec_check_permissions:ENOEXEC Executable file format error
1381 * exec_check_permissions:ETXTBSY Text file busy [misuse of error code]
1382 * exec_check_permissions:???
1383 * namei:???
1384 * vn_rdwr:??? [anything vn_rdwr can return]
1385 * <ex_imgact>:??? [anything an imgact can return]
1386 * EDEADLK Process is being terminated
1387 */
1388 static int
1389 exec_activate_image(struct image_params *imgp)
1390 {
1391 struct nameidata *ndp = NULL;
1392 const char *excpath;
1393 int error;
1394 int resid;
1395 int once = 1; /* save SGUID-ness for interpreted files */
1396 int i;
1397 int itercount = 0;
1398 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
1399
1400 error = execargs_alloc(imgp);
1401 if (error)
1402 goto bad_notrans;
1403
1404 error = exec_save_path(imgp, imgp->ip_user_fname, imgp->ip_seg, &excpath);
1405 if (error) {
1406 goto bad_notrans;
1407 }
1408
1409 /* Use excpath, which contains the copyin-ed exec path */
1410 DTRACE_PROC1(exec, uintptr_t, excpath);
1411
1412 MALLOC(ndp, struct nameidata *, sizeof(*ndp), M_TEMP, M_WAITOK | M_ZERO);
1413 if (ndp == NULL) {
1414 error = ENOMEM;
1415 goto bad_notrans;
1416 }
1417
1418 NDINIT(ndp, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF | AUDITVNPATH1,
1419 UIO_SYSSPACE, CAST_USER_ADDR_T(excpath), imgp->ip_vfs_context);
1420
1421 again:
1422 error = namei(ndp);
1423 if (error)
1424 goto bad_notrans;
1425 imgp->ip_ndp = ndp; /* successful namei(); call nameidone() later */
1426 imgp->ip_vp = ndp->ni_vp; /* if set, need to vnode_put() at some point */
1427
1428 /*
1429 * Before we start the transition from binary A to binary B, make
1430 * sure another thread hasn't started exiting the process. We grab
1431 * the proc lock to check p_lflag initially, and the transition
1432 * mechanism ensures that the value doesn't change after we release
1433 * the lock.
1434 */
1435 proc_lock(p);
1436 if (p->p_lflag & P_LEXIT) {
1437 error = EDEADLK;
1438 proc_unlock(p);
1439 goto bad_notrans;
1440 }
1441 error = proc_transstart(p, 1, 0);
1442 proc_unlock(p);
1443 if (error)
1444 goto bad_notrans;
1445
1446 error = exec_check_permissions(imgp);
1447 if (error)
1448 goto bad;
1449
1450 /* Copy; avoid invocation of an interpreter overwriting the original */
1451 if (once) {
1452 once = 0;
1453 *imgp->ip_origvattr = *imgp->ip_vattr;
1454 }
1455
1456 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata, PAGE_SIZE, 0,
1457 UIO_SYSSPACE, IO_NODELOCKED,
1458 vfs_context_ucred(imgp->ip_vfs_context),
1459 &resid, vfs_context_proc(imgp->ip_vfs_context));
1460 if (error)
1461 goto bad;
1462
1463 if (resid) {
1464 memset(imgp->ip_vdata + (PAGE_SIZE - resid), 0x0, resid);
1465 }
1466
1467 encapsulated_binary:
1468 /* Limit the number of iterations we will attempt on each binary */
1469 if (++itercount > EAI_ITERLIMIT) {
1470 error = EBADEXEC;
1471 goto bad;
1472 }
1473 error = -1;
1474 for(i = 0; error == -1 && execsw[i].ex_imgact != NULL; i++) {
1475
1476 error = (*execsw[i].ex_imgact)(imgp);
1477
1478 switch (error) {
1479 /* case -1: not claimed: continue */
1480 case -2: /* Encapsulated binary, imgp->ip_XXX set for next iteration */
1481 goto encapsulated_binary;
1482
1483 case -3: /* Interpreter */
1484 #if CONFIG_MACF
1485 /*
1486 * Copy the script label for later use. Note that
1487 * the label can be different when the script is
1488 * actually read by the interpreter.
1489 */
1490 if (imgp->ip_scriptlabelp)
1491 mac_vnode_label_free(imgp->ip_scriptlabelp);
1492 imgp->ip_scriptlabelp = mac_vnode_label_alloc();
1493 if (imgp->ip_scriptlabelp == NULL) {
1494 error = ENOMEM;
1495 break;
1496 }
1497 mac_vnode_label_copy(imgp->ip_vp->v_label,
1498 imgp->ip_scriptlabelp);
1499
1500 /*
1501 * Take a ref of the script vnode for later use.
1502 */
1503 if (imgp->ip_scriptvp)
1504 vnode_put(imgp->ip_scriptvp);
1505 if (vnode_getwithref(imgp->ip_vp) == 0)
1506 imgp->ip_scriptvp = imgp->ip_vp;
1507 #endif
1508
1509 nameidone(ndp);
1510
1511 vnode_put(imgp->ip_vp);
1512 imgp->ip_vp = NULL; /* already put */
1513 imgp->ip_ndp = NULL; /* already nameidone */
1514
1515 /* Use excpath, which exec_shell_imgact reset to the interpreter */
1516 NDINIT(ndp, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF,
1517 UIO_SYSSPACE, CAST_USER_ADDR_T(excpath), imgp->ip_vfs_context);
1518
1519 proc_transend(p, 0);
1520 goto again;
1521
1522 default:
1523 break;
1524 }
1525 }
1526
1527 /*
1528 * Call out to allow 3rd party notification of exec.
1529 * Ignore result of kauth_authorize_fileop call.
1530 */
1531 if (error == 0 && kauth_authorize_fileop_has_listeners()) {
1532 kauth_authorize_fileop(vfs_context_ucred(imgp->ip_vfs_context),
1533 KAUTH_FILEOP_EXEC,
1534 (uintptr_t)ndp->ni_vp, 0);
1535 }
1536 bad:
1537 proc_transend(p, 0);
1538
1539 bad_notrans:
1540 if (imgp->ip_strings)
1541 execargs_free(imgp);
1542 if (imgp->ip_ndp)
1543 nameidone(imgp->ip_ndp);
1544 if (ndp)
1545 FREE(ndp, M_TEMP);
1546
1547 return (error);
1548 }
1549
1550
1551 /*
1552 * exec_handle_spawnattr_policy
1553 *
1554 * Description: Decode and apply the posix_spawn apptype, qos clamp, and watchport ports to the task.
1555 *
1556 * Parameters: proc_t p process to apply attributes to
1557 * int psa_apptype posix spawn attribute apptype
1558 *
1559 * Returns: 0 Success
1560 */
1561 static errno_t
1562 exec_handle_spawnattr_policy(proc_t p, int psa_apptype, uint64_t psa_qos_clamp, uint64_t psa_darwin_role,
1563 ipc_port_t * portwatch_ports, int portwatch_count)
1564 {
1565 int apptype = TASK_APPTYPE_NONE;
1566 int qos_clamp = THREAD_QOS_UNSPECIFIED;
1567 int role = TASK_UNSPECIFIED;
1568
1569 if ((psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) != 0) {
1570 int proctype = psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK;
1571
1572 switch(proctype) {
1573 case POSIX_SPAWN_PROC_TYPE_DAEMON_INTERACTIVE:
1574 apptype = TASK_APPTYPE_DAEMON_INTERACTIVE;
1575 break;
1576 case POSIX_SPAWN_PROC_TYPE_DAEMON_STANDARD:
1577 apptype = TASK_APPTYPE_DAEMON_STANDARD;
1578 break;
1579 case POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE:
1580 apptype = TASK_APPTYPE_DAEMON_ADAPTIVE;
1581 break;
1582 case POSIX_SPAWN_PROC_TYPE_DAEMON_BACKGROUND:
1583 apptype = TASK_APPTYPE_DAEMON_BACKGROUND;
1584 break;
1585 case POSIX_SPAWN_PROC_TYPE_APP_DEFAULT:
1586 apptype = TASK_APPTYPE_APP_DEFAULT;
1587 break;
1588 #if !CONFIG_EMBEDDED
1589 case POSIX_SPAWN_PROC_TYPE_APP_TAL:
1590 apptype = TASK_APPTYPE_APP_TAL;
1591 break;
1592 #endif /* !CONFIG_EMBEDDED */
1593 default:
1594 apptype = TASK_APPTYPE_NONE;
1595 /* TODO: Should an invalid value here fail the spawn? */
1596 break;
1597 }
1598 }
1599
1600 if (psa_qos_clamp != POSIX_SPAWN_PROC_CLAMP_NONE) {
1601 switch (psa_qos_clamp) {
1602 case POSIX_SPAWN_PROC_CLAMP_UTILITY:
1603 qos_clamp = THREAD_QOS_UTILITY;
1604 break;
1605 case POSIX_SPAWN_PROC_CLAMP_BACKGROUND:
1606 qos_clamp = THREAD_QOS_BACKGROUND;
1607 break;
1608 case POSIX_SPAWN_PROC_CLAMP_MAINTENANCE:
1609 qos_clamp = THREAD_QOS_MAINTENANCE;
1610 break;
1611 default:
1612 qos_clamp = THREAD_QOS_UNSPECIFIED;
1613 /* TODO: Should an invalid value here fail the spawn? */
1614 break;
1615 }
1616 }
1617
1618 if (psa_darwin_role != PRIO_DARWIN_ROLE_DEFAULT) {
1619 proc_darwin_role_to_task_role(psa_darwin_role, &role);
1620 }
1621
1622 if (apptype != TASK_APPTYPE_NONE ||
1623 qos_clamp != THREAD_QOS_UNSPECIFIED ||
1624 role != TASK_UNSPECIFIED) {
1625 proc_set_task_spawnpolicy(p->task, apptype, qos_clamp, role,
1626 portwatch_ports, portwatch_count);
1627 }
1628
1629 return (0);
1630 }
1631
1632
1633 /*
1634 * exec_handle_port_actions
1635 *
1636 * Description: Go through the _posix_port_actions_t contents,
1637 * calling task_set_special_port, task_set_exception_ports
1638 * and/or audit_session_spawnjoin for the current task.
1639 *
1640 * Parameters: struct image_params * Image parameter block
1641 *
1642 * Returns: 0 Success
1643 * EINVAL Failure
1644 * ENOTSUP Illegal posix_spawn attr flag was set
1645 */
1646 static errno_t
1647 exec_handle_port_actions(struct image_params *imgp, boolean_t * portwatch_present,
1648 ipc_port_t * portwatch_ports)
1649 {
1650 _posix_spawn_port_actions_t pacts = imgp->ip_px_spa;
1651 #if CONFIG_AUDIT
1652 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
1653 #endif
1654 _ps_port_action_t *act = NULL;
1655 task_t task = get_threadtask(imgp->ip_new_thread);
1656 ipc_port_t port = NULL;
1657 errno_t ret = 0;
1658 int i;
1659 kern_return_t kr;
1660
1661 *portwatch_present = FALSE;
1662
1663 for (i = 0; i < pacts->pspa_count; i++) {
1664 act = &pacts->pspa_actions[i];
1665
1666 if (MACH_PORT_VALID(act->new_port)) {
1667 kr = ipc_object_copyin(get_task_ipcspace(current_task()),
1668 act->new_port, MACH_MSG_TYPE_COPY_SEND,
1669 (ipc_object_t *) &port);
1670
1671 if (kr != KERN_SUCCESS) {
1672 ret = EINVAL;
1673 goto done;
1674 }
1675 } else {
1676 /* it's NULL or DEAD */
1677 port = CAST_MACH_NAME_TO_PORT(act->new_port);
1678 }
1679
1680 switch (act->port_type) {
1681 case PSPA_SPECIAL:
1682 kr = task_set_special_port(task, act->which, port);
1683
1684 if (kr != KERN_SUCCESS)
1685 ret = EINVAL;
1686 break;
1687
1688 case PSPA_EXCEPTION:
1689 kr = task_set_exception_ports(task, act->mask, port,
1690 act->behavior, act->flavor);
1691 if (kr != KERN_SUCCESS)
1692 ret = EINVAL;
1693 break;
1694 #if CONFIG_AUDIT
1695 case PSPA_AU_SESSION:
1696 ret = audit_session_spawnjoin(p, task, port);
1697 if (ret) {
1698 /* audit_session_spawnjoin() has already dropped the reference in case of error. */
1699 goto done;
1700 }
1701
1702 break;
1703 #endif
1704 case PSPA_IMP_WATCHPORTS:
1705 if (portwatch_ports != NULL && IPC_PORT_VALID(port)) {
1706 *portwatch_present = TRUE;
1707 /* hold on to this till end of spawn */
1708 portwatch_ports[i] = port;
1709 } else {
1710 ipc_port_release_send(port);
1711 }
1712
1713 break;
1714 default:
1715 ret = EINVAL;
1716 break;
1717 }
1718
1719 if (ret) {
1720 /* action failed, so release port resources */
1721 ipc_port_release_send(port);
1722 break;
1723 }
1724 }
1725
1726 done:
1727 if (0 != ret)
1728 DTRACE_PROC1(spawn__port__failure, mach_port_name_t, act->new_port);
1729 return (ret);
1730 }
1731
1732 /*
1733 * exec_handle_file_actions
1734 *
1735 * Description: Go through the _posix_file_actions_t contents applying the
1736 * open, close, and dup2 operations to the open file table for
1737 * the current process.
1738 *
1739 * Parameters: struct image_params * Image parameter block
1740 *
1741 * Returns: 0 Success
1742 * ???
1743 *
1744 * Note: Actions are applied in the order specified, with the credential
1745 * of the parent process. This is done to permit the parent
1746 * process to utilize POSIX_SPAWN_RESETIDS to drop privilege in
1747 * the child following operations the child may in fact not be
1748 * normally permitted to perform.
1749 */
1750 static int
1751 exec_handle_file_actions(struct image_params *imgp, short psa_flags)
1752 {
1753 int error = 0;
1754 int action;
1755 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
1756 _posix_spawn_file_actions_t px_sfap = imgp->ip_px_sfa;
1757 int ival[2]; /* dummy retval for system calls) */
1758
1759 for (action = 0; action < px_sfap->psfa_act_count; action++) {
1760 _psfa_action_t *psfa = &px_sfap->psfa_act_acts[ action];
1761
1762 switch(psfa->psfaa_type) {
1763 case PSFA_OPEN: {
1764 /*
1765 * Open is different, in that it requires the use of
1766 * a path argument, which is normally copied in from
1767 * user space; because of this, we have to support an
1768 * open from kernel space that passes an address space
1769 * context of UIO_SYSSPACE, and casts the address
1770 * argument to a user_addr_t.
1771 */
1772 char *bufp = NULL;
1773 struct vnode_attr *vap;
1774 struct nameidata *ndp;
1775 int mode = psfa->psfaa_openargs.psfao_mode;
1776 struct dup2_args dup2a;
1777 struct close_nocancel_args ca;
1778 int origfd;
1779
1780 MALLOC(bufp, char *, sizeof(*vap) + sizeof(*ndp), M_TEMP, M_WAITOK | M_ZERO);
1781 if (bufp == NULL) {
1782 error = ENOMEM;
1783 break;
1784 }
1785
1786 vap = (struct vnode_attr *) bufp;
1787 ndp = (struct nameidata *) (bufp + sizeof(*vap));
1788
1789 VATTR_INIT(vap);
1790 /* Mask off all but regular access permissions */
1791 mode = ((mode &~ p->p_fd->fd_cmask) & ALLPERMS) & ~S_ISTXT;
1792 VATTR_SET(vap, va_mode, mode & ACCESSPERMS);
1793
1794 NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW | AUDITVNPATH1, UIO_SYSSPACE,
1795 CAST_USER_ADDR_T(psfa->psfaa_openargs.psfao_path),
1796 imgp->ip_vfs_context);
1797
1798 error = open1(imgp->ip_vfs_context,
1799 ndp,
1800 psfa->psfaa_openargs.psfao_oflag,
1801 vap,
1802 fileproc_alloc_init, NULL,
1803 ival);
1804
1805 FREE(bufp, M_TEMP);
1806
1807 /*
1808 * If there's an error, or we get the right fd by
1809 * accident, then drop out here. This is easier than
1810 * reworking all the open code to preallocate fd
1811 * slots, and internally taking one as an argument.
1812 */
1813 if (error || ival[0] == psfa->psfaa_filedes)
1814 break;
1815
1816 origfd = ival[0];
1817 /*
1818 * If we didn't fall out from an error, we ended up
1819 * with the wrong fd; so now we've got to try to dup2
1820 * it to the right one.
1821 */
1822 dup2a.from = origfd;
1823 dup2a.to = psfa->psfaa_filedes;
1824
1825 /*
1826 * The dup2() system call implementation sets
1827 * ival to newfd in the success case, but we
1828 * can ignore that, since if we didn't get the
1829 * fd we wanted, the error will stop us.
1830 */
1831 error = dup2(p, &dup2a, ival);
1832 if (error)
1833 break;
1834
1835 /*
1836 * Finally, close the original fd.
1837 */
1838 ca.fd = origfd;
1839
1840 error = close_nocancel(p, &ca, ival);
1841 }
1842 break;
1843
1844 case PSFA_DUP2: {
1845 struct dup2_args dup2a;
1846
1847 dup2a.from = psfa->psfaa_filedes;
1848 dup2a.to = psfa->psfaa_openargs.psfao_oflag;
1849
1850 /*
1851 * The dup2() system call implementation sets
1852 * ival to newfd in the success case, but we
1853 * can ignore that, since if we didn't get the
1854 * fd we wanted, the error will stop us.
1855 */
1856 error = dup2(p, &dup2a, ival);
1857 }
1858 break;
1859
1860 case PSFA_CLOSE: {
1861 struct close_nocancel_args ca;
1862
1863 ca.fd = psfa->psfaa_filedes;
1864
1865 error = close_nocancel(p, &ca, ival);
1866 }
1867 break;
1868
1869 case PSFA_INHERIT: {
1870 struct fcntl_nocancel_args fcntla;
1871
1872 /*
1873 * Check to see if the descriptor exists, and
1874 * ensure it's -not- marked as close-on-exec.
1875 *
1876 * Attempting to "inherit" a guarded fd will
1877 * result in a error.
1878 */
1879 fcntla.fd = psfa->psfaa_filedes;
1880 fcntla.cmd = F_GETFD;
1881 if ((error = fcntl_nocancel(p, &fcntla, ival)) != 0)
1882 break;
1883
1884 if ((ival[0] & FD_CLOEXEC) == FD_CLOEXEC) {
1885 fcntla.fd = psfa->psfaa_filedes;
1886 fcntla.cmd = F_SETFD;
1887 fcntla.arg = ival[0] & ~FD_CLOEXEC;
1888 error = fcntl_nocancel(p, &fcntla, ival);
1889 }
1890
1891 }
1892 break;
1893
1894 default:
1895 error = EINVAL;
1896 break;
1897 }
1898
1899 /* All file actions failures are considered fatal, per POSIX */
1900
1901 if (error) {
1902 if (PSFA_OPEN == psfa->psfaa_type) {
1903 DTRACE_PROC1(spawn__open__failure, uintptr_t,
1904 psfa->psfaa_openargs.psfao_path);
1905 } else {
1906 DTRACE_PROC1(spawn__fd__failure, int, psfa->psfaa_filedes);
1907 }
1908 break;
1909 }
1910 }
1911
1912 if (error != 0 || (psa_flags & POSIX_SPAWN_CLOEXEC_DEFAULT) == 0)
1913 return (error);
1914
1915 /*
1916 * If POSIX_SPAWN_CLOEXEC_DEFAULT is set, behave (during
1917 * this spawn only) as if "close on exec" is the default
1918 * disposition of all pre-existing file descriptors. In this case,
1919 * the list of file descriptors mentioned in the file actions
1920 * are the only ones that can be inherited, so mark them now.
1921 *
1922 * The actual closing part comes later, in fdexec().
1923 */
1924 proc_fdlock(p);
1925 for (action = 0; action < px_sfap->psfa_act_count; action++) {
1926 _psfa_action_t *psfa = &px_sfap->psfa_act_acts[action];
1927 int fd = psfa->psfaa_filedes;
1928
1929 switch (psfa->psfaa_type) {
1930 case PSFA_DUP2:
1931 fd = psfa->psfaa_openargs.psfao_oflag;
1932 /*FALLTHROUGH*/
1933 case PSFA_OPEN:
1934 case PSFA_INHERIT:
1935 *fdflags(p, fd) |= UF_INHERIT;
1936 break;
1937
1938 case PSFA_CLOSE:
1939 break;
1940 }
1941 }
1942 proc_fdunlock(p);
1943
1944 return (0);
1945 }
1946
1947 #if CONFIG_MACF
1948 /*
1949 * exec_spawnattr_getmacpolicyinfo
1950 */
1951 void *
1952 exec_spawnattr_getmacpolicyinfo(const void *macextensions, const char *policyname, size_t *lenp)
1953 {
1954 const struct _posix_spawn_mac_policy_extensions *psmx = macextensions;
1955 int i;
1956
1957 if (psmx == NULL)
1958 return NULL;
1959
1960 for (i = 0; i < psmx->psmx_count; i++) {
1961 const _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i];
1962 if (strncmp(extension->policyname, policyname, sizeof(extension->policyname)) == 0) {
1963 if (lenp != NULL)
1964 *lenp = extension->datalen;
1965 return extension->datap;
1966 }
1967 }
1968
1969 if (lenp != NULL)
1970 *lenp = 0;
1971 return NULL;
1972 }
1973
1974 static int
1975 spawn_copyin_macpolicyinfo(const struct user__posix_spawn_args_desc *px_args, _posix_spawn_mac_policy_extensions_t *psmxp)
1976 {
1977 _posix_spawn_mac_policy_extensions_t psmx = NULL;
1978 int error = 0;
1979 int copycnt = 0;
1980 int i = 0;
1981
1982 *psmxp = NULL;
1983
1984 if (px_args->mac_extensions_size < PS_MAC_EXTENSIONS_SIZE(1) ||
1985 px_args->mac_extensions_size > PAGE_SIZE) {
1986 error = EINVAL;
1987 goto bad;
1988 }
1989
1990 MALLOC(psmx, _posix_spawn_mac_policy_extensions_t, px_args->mac_extensions_size, M_TEMP, M_WAITOK);
1991 if ((error = copyin(px_args->mac_extensions, psmx, px_args->mac_extensions_size)) != 0)
1992 goto bad;
1993
1994 if (PS_MAC_EXTENSIONS_SIZE(psmx->psmx_count) > px_args->mac_extensions_size) {
1995 error = EINVAL;
1996 goto bad;
1997 }
1998
1999 for (i = 0; i < psmx->psmx_count; i++) {
2000 _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i];
2001 if (extension->datalen == 0 || extension->datalen > PAGE_SIZE) {
2002 error = EINVAL;
2003 goto bad;
2004 }
2005 }
2006
2007 for (copycnt = 0; copycnt < psmx->psmx_count; copycnt++) {
2008 _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[copycnt];
2009 void *data = NULL;
2010
2011 MALLOC(data, void *, extension->datalen, M_TEMP, M_WAITOK);
2012 if ((error = copyin(extension->data, data, extension->datalen)) != 0) {
2013 FREE(data, M_TEMP);
2014 goto bad;
2015 }
2016 extension->datap = data;
2017 }
2018
2019 *psmxp = psmx;
2020 return 0;
2021
2022 bad:
2023 if (psmx != NULL) {
2024 for (i = 0; i < copycnt; i++)
2025 FREE(psmx->psmx_extensions[i].datap, M_TEMP);
2026 FREE(psmx, M_TEMP);
2027 }
2028 return error;
2029 }
2030
2031 static void
2032 spawn_free_macpolicyinfo(_posix_spawn_mac_policy_extensions_t psmx)
2033 {
2034 int i;
2035
2036 if (psmx == NULL)
2037 return;
2038 for (i = 0; i < psmx->psmx_count; i++)
2039 FREE(psmx->psmx_extensions[i].datap, M_TEMP);
2040 FREE(psmx, M_TEMP);
2041 }
2042 #endif /* CONFIG_MACF */
2043
2044 #if CONFIG_COALITIONS
2045 static inline void spawn_coalitions_release_all(coalition_t coal[COALITION_NUM_TYPES])
2046 {
2047 for (int c = 0; c < COALITION_NUM_TYPES; c++) {
2048 if (coal[c]) {
2049 coalition_remove_active(coal[c]);
2050 coalition_release(coal[c]);
2051 }
2052 }
2053 }
2054 #endif
2055
2056 #if CONFIG_PERSONAS
2057 static int spawn_validate_persona(struct _posix_spawn_persona_info *px_persona)
2058 {
2059 int error = 0;
2060 struct persona *persona = NULL;
2061 int verify = px_persona->pspi_flags & POSIX_SPAWN_PERSONA_FLAGS_VERIFY;
2062
2063 /*
2064 * TODO: rdar://problem/19981151
2065 * Add entitlement check!
2066 */
2067 if (!kauth_cred_issuser(kauth_cred_get()))
2068 return EPERM;
2069
2070 persona = persona_lookup(px_persona->pspi_id);
2071 if (!persona) {
2072 error = ESRCH;
2073 goto out;
2074 }
2075
2076 if (verify) {
2077 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_UID) {
2078 if (px_persona->pspi_uid != persona_get_uid(persona)) {
2079 error = EINVAL;
2080 goto out;
2081 }
2082 }
2083 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GID) {
2084 if (px_persona->pspi_gid != persona_get_gid(persona)) {
2085 error = EINVAL;
2086 goto out;
2087 }
2088 }
2089 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) {
2090 int ngroups = 0;
2091 gid_t groups[NGROUPS_MAX];
2092
2093 if (persona_get_groups(persona, &ngroups, groups,
2094 px_persona->pspi_ngroups) != 0) {
2095 error = EINVAL;
2096 goto out;
2097 }
2098 if (ngroups != (int)px_persona->pspi_ngroups) {
2099 error = EINVAL;
2100 goto out;
2101 }
2102 while (ngroups--) {
2103 if (px_persona->pspi_groups[ngroups] != groups[ngroups]) {
2104 error = EINVAL;
2105 goto out;
2106 }
2107 }
2108 if (px_persona->pspi_gmuid != persona_get_gmuid(persona)) {
2109 error = EINVAL;
2110 goto out;
2111 }
2112 }
2113 }
2114
2115 out:
2116 if (persona)
2117 persona_put(persona);
2118
2119 return error;
2120 }
2121
2122 static int spawn_persona_adopt(proc_t p, struct _posix_spawn_persona_info *px_persona)
2123 {
2124 int ret;
2125 kauth_cred_t cred;
2126 struct persona *persona = NULL;
2127 int override = !!(px_persona->pspi_flags & POSIX_SPAWN_PERSONA_FLAGS_OVERRIDE);
2128
2129 if (!override)
2130 return persona_proc_adopt_id(p, px_persona->pspi_id, NULL);
2131
2132 /*
2133 * we want to spawn into the given persona, but we want to override
2134 * the kauth with a different UID/GID combo
2135 */
2136 persona = persona_lookup(px_persona->pspi_id);
2137 if (!persona)
2138 return ESRCH;
2139
2140 cred = persona_get_cred(persona);
2141 if (!cred) {
2142 ret = EINVAL;
2143 goto out;
2144 }
2145
2146 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_UID) {
2147 cred = kauth_cred_setresuid(cred,
2148 px_persona->pspi_uid,
2149 px_persona->pspi_uid,
2150 px_persona->pspi_uid,
2151 KAUTH_UID_NONE);
2152 }
2153
2154 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GID) {
2155 cred = kauth_cred_setresgid(cred,
2156 px_persona->pspi_gid,
2157 px_persona->pspi_gid,
2158 px_persona->pspi_gid);
2159 }
2160
2161 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) {
2162 cred = kauth_cred_setgroups(cred,
2163 px_persona->pspi_groups,
2164 px_persona->pspi_ngroups,
2165 px_persona->pspi_gmuid);
2166 }
2167
2168 ret = persona_proc_adopt(p, persona, cred);
2169
2170 out:
2171 persona_put(persona);
2172 return ret;
2173 }
2174 #endif
2175
2176 /*
2177 * posix_spawn
2178 *
2179 * Parameters: uap->pid Pointer to pid return area
2180 * uap->fname File name to exec
2181 * uap->argp Argument list
2182 * uap->envp Environment list
2183 *
2184 * Returns: 0 Success
2185 * EINVAL Invalid argument
2186 * ENOTSUP Not supported
2187 * ENOEXEC Executable file format error
2188 * exec_activate_image:EINVAL Invalid argument
2189 * exec_activate_image:EACCES Permission denied
2190 * exec_activate_image:EINTR Interrupted function
2191 * exec_activate_image:ENOMEM Not enough space
2192 * exec_activate_image:EFAULT Bad address
2193 * exec_activate_image:ENAMETOOLONG Filename too long
2194 * exec_activate_image:ENOEXEC Executable file format error
2195 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
2196 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
2197 * exec_activate_image:???
2198 * mac_execve_enter:???
2199 *
2200 * TODO: Expect to need __mac_posix_spawn() at some point...
2201 * Handle posix_spawnattr_t
2202 * Handle posix_spawn_file_actions_t
2203 */
2204 int
2205 posix_spawn(proc_t ap, struct posix_spawn_args *uap, int32_t *retval)
2206 {
2207 proc_t p = ap; /* quiet bogus GCC vfork() warning */
2208 user_addr_t pid = uap->pid;
2209 int ival[2]; /* dummy retval for setpgid() */
2210 char *bufp = NULL;
2211 struct image_params *imgp;
2212 struct vnode_attr *vap;
2213 struct vnode_attr *origvap;
2214 struct uthread *uthread = 0; /* compiler complains if not set to 0*/
2215 int error, sig;
2216 int is_64 = IS_64BIT_PROCESS(p);
2217 struct vfs_context context;
2218 struct user__posix_spawn_args_desc px_args;
2219 struct _posix_spawnattr px_sa;
2220 _posix_spawn_file_actions_t px_sfap = NULL;
2221 _posix_spawn_port_actions_t px_spap = NULL;
2222 struct __kern_sigaction vec;
2223 boolean_t spawn_no_exec = FALSE;
2224 boolean_t proc_transit_set = TRUE;
2225 boolean_t exec_done = FALSE;
2226 int portwatch_count = 0;
2227 ipc_port_t * portwatch_ports = NULL;
2228 vm_size_t px_sa_offset = offsetof(struct _posix_spawnattr, psa_ports);
2229 task_t new_task = NULL;
2230 boolean_t should_release_proc_ref = FALSE;
2231 void *inherit = NULL;
2232 #if CONFIG_PERSONAS
2233 struct _posix_spawn_persona_info *px_persona = NULL;
2234 #endif
2235
2236 /*
2237 * Allocate a big chunk for locals instead of using stack since these
2238 * structures are pretty big.
2239 */
2240 MALLOC(bufp, char *, (sizeof(*imgp) + sizeof(*vap) + sizeof(*origvap)), M_TEMP, M_WAITOK | M_ZERO);
2241 imgp = (struct image_params *) bufp;
2242 if (bufp == NULL) {
2243 error = ENOMEM;
2244 goto bad;
2245 }
2246 vap = (struct vnode_attr *) (bufp + sizeof(*imgp));
2247 origvap = (struct vnode_attr *) (bufp + sizeof(*imgp) + sizeof(*vap));
2248
2249 /* Initialize the common data in the image_params structure */
2250 imgp->ip_user_fname = uap->path;
2251 imgp->ip_user_argv = uap->argv;
2252 imgp->ip_user_envv = uap->envp;
2253 imgp->ip_vattr = vap;
2254 imgp->ip_origvattr = origvap;
2255 imgp->ip_vfs_context = &context;
2256 imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT : IMGPF_NONE);
2257 imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
2258 imgp->ip_mac_return = 0;
2259 imgp->ip_px_persona = NULL;
2260 imgp->ip_cs_error = OS_REASON_NULL;
2261
2262 if (uap->adesc != USER_ADDR_NULL) {
2263 if(is_64) {
2264 error = copyin(uap->adesc, &px_args, sizeof(px_args));
2265 } else {
2266 struct user32__posix_spawn_args_desc px_args32;
2267
2268 error = copyin(uap->adesc, &px_args32, sizeof(px_args32));
2269
2270 /*
2271 * Convert arguments descriptor from external 32 bit
2272 * representation to internal 64 bit representation
2273 */
2274 px_args.attr_size = px_args32.attr_size;
2275 px_args.attrp = CAST_USER_ADDR_T(px_args32.attrp);
2276 px_args.file_actions_size = px_args32.file_actions_size;
2277 px_args.file_actions = CAST_USER_ADDR_T(px_args32.file_actions);
2278 px_args.port_actions_size = px_args32.port_actions_size;
2279 px_args.port_actions = CAST_USER_ADDR_T(px_args32.port_actions);
2280 px_args.mac_extensions_size = px_args32.mac_extensions_size;
2281 px_args.mac_extensions = CAST_USER_ADDR_T(px_args32.mac_extensions);
2282 px_args.coal_info_size = px_args32.coal_info_size;
2283 px_args.coal_info = CAST_USER_ADDR_T(px_args32.coal_info);
2284 px_args.persona_info_size = px_args32.persona_info_size;
2285 px_args.persona_info = CAST_USER_ADDR_T(px_args32.persona_info);
2286 }
2287 if (error)
2288 goto bad;
2289
2290 if (px_args.attr_size != 0) {
2291 /*
2292 * We are not copying the port_actions pointer,
2293 * because we already have it from px_args.
2294 * This is a bit fragile: <rdar://problem/16427422>
2295 */
2296
2297 if ((error = copyin(px_args.attrp, &px_sa, px_sa_offset) != 0))
2298 goto bad;
2299
2300 bzero( (void *)( (unsigned long) &px_sa + px_sa_offset), sizeof(px_sa) - px_sa_offset );
2301
2302 imgp->ip_px_sa = &px_sa;
2303 }
2304 if (px_args.file_actions_size != 0) {
2305 /* Limit file_actions to allowed number of open files */
2306 int maxfa = (p->p_limit ? p->p_rlimit[RLIMIT_NOFILE].rlim_cur : NOFILE);
2307 if (px_args.file_actions_size < PSF_ACTIONS_SIZE(1) ||
2308 px_args.file_actions_size > PSF_ACTIONS_SIZE(maxfa)) {
2309 error = EINVAL;
2310 goto bad;
2311 }
2312 MALLOC(px_sfap, _posix_spawn_file_actions_t, px_args.file_actions_size, M_TEMP, M_WAITOK);
2313 if (px_sfap == NULL) {
2314 error = ENOMEM;
2315 goto bad;
2316 }
2317 imgp->ip_px_sfa = px_sfap;
2318
2319 if ((error = copyin(px_args.file_actions, px_sfap,
2320 px_args.file_actions_size)) != 0)
2321 goto bad;
2322
2323 /* Verify that the action count matches the struct size */
2324 if (PSF_ACTIONS_SIZE(px_sfap->psfa_act_count) != px_args.file_actions_size) {
2325 error = EINVAL;
2326 goto bad;
2327 }
2328 }
2329 if (px_args.port_actions_size != 0) {
2330 /* Limit port_actions to one page of data */
2331 if (px_args.port_actions_size < PS_PORT_ACTIONS_SIZE(1) ||
2332 px_args.port_actions_size > PAGE_SIZE) {
2333 error = EINVAL;
2334 goto bad;
2335 }
2336
2337 MALLOC(px_spap, _posix_spawn_port_actions_t,
2338 px_args.port_actions_size, M_TEMP, M_WAITOK);
2339 if (px_spap == NULL) {
2340 error = ENOMEM;
2341 goto bad;
2342 }
2343 imgp->ip_px_spa = px_spap;
2344
2345 if ((error = copyin(px_args.port_actions, px_spap,
2346 px_args.port_actions_size)) != 0)
2347 goto bad;
2348
2349 /* Verify that the action count matches the struct size */
2350 if (PS_PORT_ACTIONS_SIZE(px_spap->pspa_count) != px_args.port_actions_size) {
2351 error = EINVAL;
2352 goto bad;
2353 }
2354 }
2355 #if CONFIG_PERSONAS
2356 /* copy in the persona info */
2357 if (px_args.persona_info_size != 0 && px_args.persona_info != 0) {
2358 /* for now, we need the exact same struct in user space */
2359 if (px_args.persona_info_size != sizeof(*px_persona)) {
2360 error = ERANGE;
2361 goto bad;
2362 }
2363
2364 MALLOC(px_persona, struct _posix_spawn_persona_info *, px_args.persona_info_size, M_TEMP, M_WAITOK|M_ZERO);
2365 if (px_persona == NULL) {
2366 error = ENOMEM;
2367 goto bad;
2368 }
2369 imgp->ip_px_persona = px_persona;
2370
2371 if ((error = copyin(px_args.persona_info, px_persona,
2372 px_args.persona_info_size)) != 0)
2373 goto bad;
2374 if ((error = spawn_validate_persona(px_persona)) != 0)
2375 goto bad;
2376 }
2377 #endif
2378 #if CONFIG_MACF
2379 if (px_args.mac_extensions_size != 0) {
2380 if ((error = spawn_copyin_macpolicyinfo(&px_args, (_posix_spawn_mac_policy_extensions_t *)&imgp->ip_px_smpx)) != 0)
2381 goto bad;
2382 }
2383 #endif /* CONFIG_MACF */
2384 }
2385
2386 /* set uthread to parent */
2387 uthread = get_bsdthread_info(current_thread());
2388
2389 /*
2390 * <rdar://6640530>; this does not result in a behaviour change
2391 * relative to Leopard, so there should not be any existing code
2392 * which depends on it.
2393 */
2394 if (uthread->uu_flag & UT_VFORK) {
2395 error = EINVAL;
2396 goto bad;
2397 }
2398
2399 /*
2400 * If we don't have the extension flag that turns "posix_spawn()"
2401 * into "execve() with options", then we will be creating a new
2402 * process which does not inherit memory from the parent process,
2403 * which is one of the most expensive things about using fork()
2404 * and execve().
2405 */
2406 if (imgp->ip_px_sa == NULL || !(px_sa.psa_flags & POSIX_SPAWN_SETEXEC)){
2407
2408 /* Set the new task's coalition, if it is requested. */
2409 coalition_t coal[COALITION_NUM_TYPES] = { COALITION_NULL };
2410 #if CONFIG_COALITIONS
2411 int i, ncoals;
2412 kern_return_t kr = KERN_SUCCESS;
2413 struct _posix_spawn_coalition_info coal_info;
2414 int coal_role[COALITION_NUM_TYPES];
2415
2416 if (imgp->ip_px_sa == NULL || !px_args.coal_info)
2417 goto do_fork1;
2418
2419 memset(&coal_info, 0, sizeof(coal_info));
2420
2421 if (px_args.coal_info_size > sizeof(coal_info))
2422 px_args.coal_info_size = sizeof(coal_info);
2423 error = copyin(px_args.coal_info,
2424 &coal_info, px_args.coal_info_size);
2425 if (error != 0)
2426 goto bad;
2427
2428 ncoals = 0;
2429 for (i = 0; i < COALITION_NUM_TYPES; i++) {
2430 uint64_t cid = coal_info.psci_info[i].psci_id;
2431 if (cid != 0) {
2432 /*
2433 * don't allow tasks which are not in a
2434 * privileged coalition to spawn processes
2435 * into coalitions other than their own
2436 */
2437 if (!task_is_in_privileged_coalition(p->task, i)) {
2438 coal_dbg("ERROR: %d not in privilegd "
2439 "coalition of type %d",
2440 p->p_pid, i);
2441 spawn_coalitions_release_all(coal);
2442 error = EPERM;
2443 goto bad;
2444 }
2445
2446 coal_dbg("searching for coalition id:%llu", cid);
2447 /*
2448 * take a reference and activation on the
2449 * coalition to guard against free-while-spawn
2450 * races
2451 */
2452 coal[i] = coalition_find_and_activate_by_id(cid);
2453 if (coal[i] == COALITION_NULL) {
2454 coal_dbg("could not find coalition id:%llu "
2455 "(perhaps it has been terminated or reaped)", cid);
2456 /*
2457 * release any other coalition's we
2458 * may have a reference to
2459 */
2460 spawn_coalitions_release_all(coal);
2461 error = ESRCH;
2462 goto bad;
2463 }
2464 if (coalition_type(coal[i]) != i) {
2465 coal_dbg("coalition with id:%lld is not of type:%d"
2466 " (it's type:%d)", cid, i, coalition_type(coal[i]));
2467 error = ESRCH;
2468 goto bad;
2469 }
2470 coal_role[i] = coal_info.psci_info[i].psci_role;
2471 ncoals++;
2472 }
2473 }
2474 if (ncoals < COALITION_NUM_TYPES) {
2475 /*
2476 * If the user is attempting to spawn into a subset of
2477 * the known coalition types, then make sure they have
2478 * _at_least_ specified a resource coalition. If not,
2479 * the following fork1() call will implicitly force an
2480 * inheritance from 'p' and won't actually spawn the
2481 * new task into the coalitions the user specified.
2482 * (also the call to coalitions_set_roles will panic)
2483 */
2484 if (coal[COALITION_TYPE_RESOURCE] == COALITION_NULL) {
2485 spawn_coalitions_release_all(coal);
2486 error = EINVAL;
2487 goto bad;
2488 }
2489 }
2490 do_fork1:
2491 #endif /* CONFIG_COALITIONS */
2492
2493 /*
2494 * note that this will implicitly inherit the
2495 * caller's persona (if it exists)
2496 */
2497 error = fork1(p, &imgp->ip_new_thread, PROC_CREATE_SPAWN, coal);
2498 /* returns a thread and task reference */
2499
2500 if (error == 0) {
2501 new_task = get_threadtask(imgp->ip_new_thread);
2502 }
2503 #if CONFIG_COALITIONS
2504 /* set the roles of this task within each given coalition */
2505 if (error == 0) {
2506 kr = coalitions_set_roles(coal, new_task, coal_role);
2507 if (kr != KERN_SUCCESS)
2508 error = EINVAL;
2509 if (kdebug_debugid_enabled(MACHDBG_CODE(DBG_MACH_COALITION,
2510 MACH_COALITION_ADOPT))) {
2511 for (i = 0; i < COALITION_NUM_TYPES; i++) {
2512 if (coal[i] != COALITION_NULL) {
2513 /*
2514 * On 32-bit targets, uniqueid
2515 * will get truncated to 32 bits
2516 */
2517 KDBG_RELEASE(MACHDBG_CODE(
2518 DBG_MACH_COALITION,
2519 MACH_COALITION_ADOPT),
2520 coalition_id(coal[i]),
2521 get_task_uniqueid(new_task));
2522 }
2523 }
2524 }
2525 }
2526
2527 /* drop our references and activations - fork1() now holds them */
2528 spawn_coalitions_release_all(coal);
2529 #endif /* CONFIG_COALITIONS */
2530 if (error != 0) {
2531 goto bad;
2532 }
2533 imgp->ip_flags |= IMGPF_SPAWN; /* spawn w/o exec */
2534 spawn_no_exec = TRUE; /* used in later tests */
2535
2536 #if CONFIG_PERSONAS
2537 /*
2538 * If the parent isn't in a persona (launchd), and
2539 * hasn't specified a new persona for the process,
2540 * then we'll put the process into the system persona
2541 *
2542 * TODO: this will have to be re-worked because as of
2543 * now, without any launchd adoption, the resulting
2544 * xpcproxy process will not have sufficient
2545 * privileges to setuid/gid.
2546 */
2547 #if 0
2548 if (!proc_has_persona(p) && imgp->ip_px_persona == NULL) {
2549 MALLOC(px_persona, struct _posix_spawn_persona_info *,
2550 sizeof(*px_persona), M_TEMP, M_WAITOK|M_ZERO);
2551 if (px_persona == NULL) {
2552 error = ENOMEM;
2553 goto bad;
2554 }
2555 px_persona->pspi_id = persona_get_id(g_system_persona);
2556 imgp->ip_px_persona = px_persona;
2557 }
2558 #endif /* 0 */
2559 #endif /* CONFIG_PERSONAS */
2560 } else {
2561 /*
2562 * For execve case, create a new task and thread
2563 * which points to current_proc. The current_proc will point
2564 * to the new task after image activation and proc ref drain.
2565 *
2566 * proc (current_proc) <----- old_task (current_task)
2567 * ^ | ^
2568 * | | |
2569 * | ----------------------------------
2570 * |
2571 * --------- new_task (task marked as TF_EXEC_COPY)
2572 *
2573 * After image activation, the proc will point to the new task
2574 * and would look like following.
2575 *
2576 * proc (current_proc) <----- old_task (current_task, marked as TPF_DID_EXEC)
2577 * ^ |
2578 * | |
2579 * | ----------> new_task
2580 * | |
2581 * -----------------
2582 *
2583 * During exec any transition from new_task -> proc is fine, but don't allow
2584 * transition from proc->task, since it will modify old_task.
2585 */
2586 imgp->ip_new_thread = fork_create_child(current_task(),
2587 NULL, p, FALSE, p->p_flag & P_LP64, TRUE);
2588 /* task and thread ref returned by fork_create_child */
2589 if (imgp->ip_new_thread == NULL) {
2590 error = ENOMEM;
2591 goto bad;
2592 }
2593
2594 new_task = get_threadtask(imgp->ip_new_thread);
2595 imgp->ip_flags |= IMGPF_EXEC;
2596 }
2597
2598 if (spawn_no_exec) {
2599 p = (proc_t)get_bsdthreadtask_info(imgp->ip_new_thread);
2600
2601 /*
2602 * We had to wait until this point before firing the
2603 * proc:::create probe, otherwise p would not point to the
2604 * child process.
2605 */
2606 DTRACE_PROC1(create, proc_t, p);
2607 }
2608 assert(p != NULL);
2609
2610 context.vc_thread = imgp->ip_new_thread;
2611 context.vc_ucred = p->p_ucred; /* XXX must NOT be kauth_cred_get() */
2612
2613 /*
2614 * Post fdcopy(), pre exec_handle_sugid() - this is where we want
2615 * to handle the file_actions. Since vfork() also ends up setting
2616 * us into the parent process group, and saved off the signal flags,
2617 * this is also where we want to handle the spawn flags.
2618 */
2619
2620 /* Has spawn file actions? */
2621 if (imgp->ip_px_sfa != NULL) {
2622 /*
2623 * The POSIX_SPAWN_CLOEXEC_DEFAULT flag
2624 * is handled in exec_handle_file_actions().
2625 */
2626 if ((error = exec_handle_file_actions(imgp,
2627 imgp->ip_px_sa != NULL ? px_sa.psa_flags : 0)) != 0)
2628 goto bad;
2629 }
2630
2631 /* Has spawn port actions? */
2632 if (imgp->ip_px_spa != NULL) {
2633 boolean_t is_adaptive = FALSE;
2634 boolean_t portwatch_present = FALSE;
2635
2636 /* Will this process become adaptive? The apptype isn't ready yet, so we can't look there. */
2637 if (imgp->ip_px_sa != NULL && px_sa.psa_apptype == POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE)
2638 is_adaptive = TRUE;
2639
2640 /*
2641 * portwatch only:
2642 * Allocate a place to store the ports we want to bind to the new task
2643 * We can't bind them until after the apptype is set.
2644 */
2645 if (px_spap->pspa_count != 0 && is_adaptive) {
2646 portwatch_count = px_spap->pspa_count;
2647 MALLOC(portwatch_ports, ipc_port_t *, (sizeof(ipc_port_t) * portwatch_count), M_TEMP, M_WAITOK | M_ZERO);
2648 } else {
2649 portwatch_ports = NULL;
2650 }
2651
2652 if ((error = exec_handle_port_actions(imgp, &portwatch_present, portwatch_ports)) != 0)
2653 goto bad;
2654
2655 if (portwatch_present == FALSE && portwatch_ports != NULL) {
2656 FREE(portwatch_ports, M_TEMP);
2657 portwatch_ports = NULL;
2658 portwatch_count = 0;
2659 }
2660 }
2661
2662 /* Has spawn attr? */
2663 if (imgp->ip_px_sa != NULL) {
2664 /*
2665 * Set the process group ID of the child process; this has
2666 * to happen before the image activation.
2667 */
2668 if (px_sa.psa_flags & POSIX_SPAWN_SETPGROUP) {
2669 struct setpgid_args spga;
2670 spga.pid = p->p_pid;
2671 spga.pgid = px_sa.psa_pgroup;
2672 /*
2673 * Effectively, call setpgid() system call; works
2674 * because there are no pointer arguments.
2675 */
2676 if((error = setpgid(p, &spga, ival)) != 0)
2677 goto bad;
2678 }
2679
2680 /*
2681 * Reset UID/GID to parent's RUID/RGID; This works only
2682 * because the operation occurs *after* the vfork() and
2683 * before the call to exec_handle_sugid() by the image
2684 * activator called from exec_activate_image(). POSIX
2685 * requires that any setuid/setgid bits on the process
2686 * image will take precedence over the spawn attributes
2687 * (re)setting them.
2688 *
2689 * Modifications to p_ucred must be guarded using the
2690 * proc's ucred lock. This prevents others from accessing
2691 * a garbage credential.
2692 */
2693 while (px_sa.psa_flags & POSIX_SPAWN_RESETIDS) {
2694 kauth_cred_t my_cred = kauth_cred_proc_ref(p);
2695 kauth_cred_t my_new_cred = kauth_cred_setuidgid(my_cred, kauth_cred_getruid(my_cred), kauth_cred_getrgid(my_cred));
2696
2697 if (my_cred == my_new_cred) {
2698 kauth_cred_unref(&my_cred);
2699 break;
2700 }
2701
2702 /* update cred on proc */
2703 proc_ucred_lock(p);
2704
2705 if (p->p_ucred != my_cred) {
2706 proc_ucred_unlock(p);
2707 kauth_cred_unref(&my_new_cred);
2708 continue;
2709 }
2710
2711 /* donate cred reference on my_new_cred to p->p_ucred */
2712 p->p_ucred = my_new_cred;
2713 PROC_UPDATE_CREDS_ONPROC(p);
2714 proc_ucred_unlock(p);
2715
2716 /* drop additional reference that was taken on the previous cred */
2717 kauth_cred_unref(&my_cred);
2718 }
2719
2720 #if CONFIG_PERSONAS
2721 if (spawn_no_exec && imgp->ip_px_persona != NULL) {
2722 /*
2723 * If we were asked to spawn a process into a new persona,
2724 * do the credential switch now (which may override the UID/GID
2725 * inherit done just above). It's important to do this switch
2726 * before image activation both for reasons stated above, and
2727 * to ensure that the new persona has access to the image/file
2728 * being executed.
2729 */
2730 error = spawn_persona_adopt(p, imgp->ip_px_persona);
2731 if (error != 0)
2732 goto bad;
2733 }
2734 #endif /* CONFIG_PERSONAS */
2735 #if !SECURE_KERNEL
2736 /*
2737 * Disable ASLR for the spawned process.
2738 *
2739 * But only do so if we are not embedded + RELEASE.
2740 * While embedded allows for a boot-arg (-disable_aslr)
2741 * to deal with this (which itself is only honored on
2742 * DEVELOPMENT or DEBUG builds of xnu), it is often
2743 * useful or necessary to disable ASLR on a per-process
2744 * basis for unit testing and debugging.
2745 */
2746 if (px_sa.psa_flags & _POSIX_SPAWN_DISABLE_ASLR)
2747 OSBitOrAtomic(P_DISABLE_ASLR, &p->p_flag);
2748 #endif /* !SECURE_KERNEL */
2749
2750 /* Randomize high bits of ASLR slide */
2751 if (px_sa.psa_flags & _POSIX_SPAWN_HIGH_BITS_ASLR)
2752 imgp->ip_flags |= IMGPF_HIGH_BITS_ASLR;
2753
2754 /*
2755 * Forcibly disallow execution from data pages for the spawned process
2756 * even if it would otherwise be permitted by the architecture default.
2757 */
2758 if (px_sa.psa_flags & _POSIX_SPAWN_ALLOW_DATA_EXEC)
2759 imgp->ip_flags |= IMGPF_ALLOW_DATA_EXEC;
2760 }
2761
2762 /*
2763 * Disable ASLR during image activation. This occurs either if the
2764 * _POSIX_SPAWN_DISABLE_ASLR attribute was found above or if
2765 * P_DISABLE_ASLR was inherited from the parent process.
2766 */
2767 if (p->p_flag & P_DISABLE_ASLR)
2768 imgp->ip_flags |= IMGPF_DISABLE_ASLR;
2769
2770 /*
2771 * Clear transition flag so we won't hang if exec_activate_image() causes
2772 * an automount (and launchd does a proc sysctl to service it).
2773 *
2774 * <rdar://problem/6848672>, <rdar://problem/5959568>.
2775 */
2776 if (spawn_no_exec) {
2777 proc_transend(p, 0);
2778 proc_transit_set = 0;
2779 }
2780
2781 #if MAC_SPAWN /* XXX */
2782 if (uap->mac_p != USER_ADDR_NULL) {
2783 error = mac_execve_enter(uap->mac_p, imgp);
2784 if (error)
2785 goto bad;
2786 }
2787 #endif
2788
2789 /*
2790 * Activate the image
2791 */
2792 error = exec_activate_image(imgp);
2793
2794 if (error == 0 && !spawn_no_exec) {
2795 p = proc_exec_switch_task(p, current_task(), new_task, imgp->ip_new_thread);
2796 /* proc ref returned */
2797 should_release_proc_ref = TRUE;
2798 }
2799
2800 if (error == 0) {
2801 /* process completed the exec */
2802 exec_done = TRUE;
2803 } else if (error == -1) {
2804 /* Image not claimed by any activator? */
2805 error = ENOEXEC;
2806 }
2807
2808 /*
2809 * If we have a spawn attr, and it contains signal related flags,
2810 * the we need to process them in the "context" of the new child
2811 * process, so we have to process it following image activation,
2812 * prior to making the thread runnable in user space. This is
2813 * necessitated by some signal information being per-thread rather
2814 * than per-process, and we don't have the new allocation in hand
2815 * until after the image is activated.
2816 */
2817 if (!error && imgp->ip_px_sa != NULL) {
2818 thread_t child_thread = imgp->ip_new_thread;
2819 uthread_t child_uthread = get_bsdthread_info(child_thread);
2820
2821 /*
2822 * Mask a list of signals, instead of them being unmasked, if
2823 * they were unmasked in the parent; note that some signals
2824 * are not maskable.
2825 */
2826 if (px_sa.psa_flags & POSIX_SPAWN_SETSIGMASK)
2827 child_uthread->uu_sigmask = (px_sa.psa_sigmask & ~sigcantmask);
2828 /*
2829 * Default a list of signals instead of ignoring them, if
2830 * they were ignored in the parent. Note that we pass
2831 * spawn_no_exec to setsigvec() to indicate that we called
2832 * fork1() and therefore do not need to call proc_signalstart()
2833 * internally.
2834 */
2835 if (px_sa.psa_flags & POSIX_SPAWN_SETSIGDEF) {
2836 vec.sa_handler = SIG_DFL;
2837 vec.sa_tramp = 0;
2838 vec.sa_mask = 0;
2839 vec.sa_flags = 0;
2840 for (sig = 1; sig < NSIG; sig++)
2841 if (px_sa.psa_sigdefault & (1 << (sig-1))) {
2842 error = setsigvec(p, child_thread, sig, &vec, spawn_no_exec);
2843 }
2844 }
2845
2846 /*
2847 * Activate the CPU usage monitor, if requested. This is done via a task-wide, per-thread CPU
2848 * usage limit, which will generate a resource exceeded exception if any one thread exceeds the
2849 * limit.
2850 *
2851 * Userland gives us interval in seconds, and the kernel SPI expects nanoseconds.
2852 */
2853 if (px_sa.psa_cpumonitor_percent != 0) {
2854 /*
2855 * Always treat a CPU monitor activation coming from spawn as entitled. Requiring
2856 * an entitlement to configure the monitor a certain way seems silly, since
2857 * whomever is turning it on could just as easily choose not to do so.
2858 */
2859 error = proc_set_task_ruse_cpu(p->task,
2860 TASK_POLICY_RESOURCE_ATTRIBUTE_NOTIFY_EXC,
2861 px_sa.psa_cpumonitor_percent,
2862 px_sa.psa_cpumonitor_interval * NSEC_PER_SEC,
2863 0, TRUE);
2864 }
2865 }
2866
2867 bad:
2868
2869 if (error == 0) {
2870 /* reset delay idle sleep status if set */
2871 #if !CONFIG_EMBEDDED
2872 if ((p->p_flag & P_DELAYIDLESLEEP) == P_DELAYIDLESLEEP)
2873 OSBitAndAtomic(~((uint32_t)P_DELAYIDLESLEEP), &p->p_flag);
2874 #endif /* !CONFIG_EMBEDDED */
2875 /* upon successful spawn, re/set the proc control state */
2876 if (imgp->ip_px_sa != NULL) {
2877 switch (px_sa.psa_pcontrol) {
2878 case POSIX_SPAWN_PCONTROL_THROTTLE:
2879 p->p_pcaction = P_PCTHROTTLE;
2880 break;
2881 case POSIX_SPAWN_PCONTROL_SUSPEND:
2882 p->p_pcaction = P_PCSUSP;
2883 break;
2884 case POSIX_SPAWN_PCONTROL_KILL:
2885 p->p_pcaction = P_PCKILL;
2886 break;
2887 case POSIX_SPAWN_PCONTROL_NONE:
2888 default:
2889 p->p_pcaction = 0;
2890 break;
2891 };
2892 }
2893 exec_resettextvp(p, imgp);
2894
2895 #if CONFIG_MEMORYSTATUS
2896 /* Has jetsam attributes? */
2897 if (imgp->ip_px_sa != NULL && (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_SET)) {
2898 /*
2899 * With 2-level high-water-mark support, POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is no
2900 * longer relevant, as background limits are described via the inactive limit slots.
2901 *
2902 * That said, however, if the POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is passed in,
2903 * we attempt to mimic previous behavior by forcing the BG limit data into the
2904 * inactive/non-fatal mode and force the active slots to hold system_wide/fatal mode.
2905 */
2906 if (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND) {
2907 memorystatus_update(p, px_sa.psa_priority, 0,
2908 (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY),
2909 TRUE,
2910 -1, TRUE,
2911 px_sa.psa_memlimit_inactive, FALSE);
2912 } else {
2913 memorystatus_update(p, px_sa.psa_priority, 0,
2914 (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY),
2915 TRUE,
2916 px_sa.psa_memlimit_active,
2917 (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_MEMLIMIT_ACTIVE_FATAL),
2918 px_sa.psa_memlimit_inactive,
2919 (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_MEMLIMIT_INACTIVE_FATAL));
2920 }
2921
2922 }
2923 #endif /* CONFIG_MEMORYSTATUS */
2924 }
2925
2926 /*
2927 * If we successfully called fork1(), we always need to do this;
2928 * we identify this case by noting the IMGPF_SPAWN flag. This is
2929 * because we come back from that call with signals blocked in the
2930 * child, and we have to unblock them, but we want to wait until
2931 * after we've performed any spawn actions. This has to happen
2932 * before check_for_signature(), which uses psignal.
2933 */
2934 if (spawn_no_exec) {
2935 if (proc_transit_set)
2936 proc_transend(p, 0);
2937
2938 /*
2939 * Drop the signal lock on the child which was taken on our
2940 * behalf by forkproc()/cloneproc() to prevent signals being
2941 * received by the child in a partially constructed state.
2942 */
2943 proc_signalend(p, 0);
2944
2945 /* flag the 'fork' has occurred */
2946 proc_knote(p->p_pptr, NOTE_FORK | p->p_pid);
2947 /* then flag exec has occurred */
2948 /* notify only if it has not failed due to FP Key error */
2949 if ((p->p_lflag & P_LTERM_DECRYPTFAIL) == 0)
2950 proc_knote(p, NOTE_EXEC);
2951 }
2952
2953 if (error == 0) {
2954 /*
2955 * We need to initialize the bank context behind the protection of
2956 * the proc_trans lock to prevent a race with exit. We can't do this during
2957 * exec_activate_image because task_bank_init checks entitlements that
2958 * aren't loaded until subsequent calls (including exec_resettextvp).
2959 */
2960 error = proc_transstart(p, 0, 0);
2961
2962 if (error == 0) {
2963 task_bank_init(get_threadtask(imgp->ip_new_thread));
2964 proc_transend(p, 0);
2965 }
2966 }
2967
2968 /* Inherit task role from old task to new task for exec */
2969 if (error == 0 && !spawn_no_exec) {
2970 proc_inherit_task_role(get_threadtask(imgp->ip_new_thread), current_task());
2971 }
2972
2973 /*
2974 * Apply the spawnattr policy, apptype (which primes the task for importance donation),
2975 * and bind any portwatch ports to the new task.
2976 * This must be done after the exec so that the child's thread is ready,
2977 * and after the in transit state has been released, because priority is
2978 * dropped here so we need to be prepared for a potentially long preemption interval
2979 *
2980 * TODO: Consider splitting this up into separate phases
2981 */
2982 if (error == 0 && imgp->ip_px_sa != NULL) {
2983 struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
2984
2985 exec_handle_spawnattr_policy(p, psa->psa_apptype, psa->psa_qos_clamp, psa->psa_darwin_role,
2986 portwatch_ports, portwatch_count);
2987 }
2988
2989 /*
2990 * Need to transfer pending watch port boosts to the new task while still making
2991 * sure that the old task remains in the importance linkage. Create an importance
2992 * linkage from old task to new task, then switch the task importance base
2993 * of old task and new task. After the switch the port watch boost will be
2994 * boosting the new task and new task will be donating importance to old task.
2995 */
2996 if (error == 0 && task_did_exec(current_task())) {
2997 inherit = ipc_importance_exec_switch_task(current_task(), get_threadtask(imgp->ip_new_thread));
2998 }
2999
3000 if (error == 0) {
3001 /* Apply the main thread qos */
3002 thread_t main_thread = imgp->ip_new_thread;
3003 task_set_main_thread_qos(get_threadtask(imgp->ip_new_thread), main_thread);
3004
3005 #if CONFIG_MACF
3006 /*
3007 * Processes with the MAP_JIT entitlement are permitted to have
3008 * a jumbo-size map.
3009 */
3010 if (mac_proc_check_map_anon(p, 0, 0, 0, MAP_JIT, NULL) == 0) {
3011 vm_map_set_jumbo(get_task_map(p->task));
3012 }
3013 #endif /* CONFIG_MACF */
3014 }
3015
3016 /*
3017 * Release any ports we kept around for binding to the new task
3018 * We need to release the rights even if the posix_spawn has failed.
3019 */
3020 if (portwatch_ports != NULL) {
3021 for (int i = 0; i < portwatch_count; i++) {
3022 ipc_port_t port = NULL;
3023 if ((port = portwatch_ports[i]) != NULL) {
3024 ipc_port_release_send(port);
3025 }
3026 }
3027 FREE(portwatch_ports, M_TEMP);
3028 portwatch_ports = NULL;
3029 portwatch_count = 0;
3030 }
3031
3032 /*
3033 * We have to delay operations which might throw a signal until after
3034 * the signals have been unblocked; however, we want that to happen
3035 * after exec_resettextvp() so that the textvp is correct when they
3036 * fire.
3037 */
3038 if (error == 0) {
3039 error = check_for_signature(p, imgp);
3040
3041 /*
3042 * Pay for our earlier safety; deliver the delayed signals from
3043 * the incomplete spawn process now that it's complete.
3044 */
3045 if (imgp != NULL && spawn_no_exec && (p->p_lflag & P_LTRACED)) {
3046 psignal_vfork(p, p->task, imgp->ip_new_thread, SIGTRAP);
3047 }
3048
3049 if (error == 0 && !spawn_no_exec)
3050 KDBG(BSDDBG_CODE(DBG_BSD_PROC,BSD_PROC_EXEC),
3051 p->p_pid);
3052 }
3053
3054
3055 if (imgp != NULL) {
3056 if (imgp->ip_vp)
3057 vnode_put(imgp->ip_vp);
3058 if (imgp->ip_scriptvp)
3059 vnode_put(imgp->ip_scriptvp);
3060 if (imgp->ip_strings)
3061 execargs_free(imgp);
3062 if (imgp->ip_px_sfa != NULL)
3063 FREE(imgp->ip_px_sfa, M_TEMP);
3064 if (imgp->ip_px_spa != NULL)
3065 FREE(imgp->ip_px_spa, M_TEMP);
3066 #if CONFIG_PERSONAS
3067 if (imgp->ip_px_persona != NULL)
3068 FREE(imgp->ip_px_persona, M_TEMP);
3069 #endif
3070 #if CONFIG_MACF
3071 if (imgp->ip_px_smpx != NULL)
3072 spawn_free_macpolicyinfo(imgp->ip_px_smpx);
3073 if (imgp->ip_execlabelp)
3074 mac_cred_label_free(imgp->ip_execlabelp);
3075 if (imgp->ip_scriptlabelp)
3076 mac_vnode_label_free(imgp->ip_scriptlabelp);
3077 if (imgp->ip_cs_error != OS_REASON_NULL) {
3078 os_reason_free(imgp->ip_cs_error);
3079 imgp->ip_cs_error = OS_REASON_NULL;
3080 }
3081 #endif
3082 }
3083
3084 #if CONFIG_DTRACE
3085 if (spawn_no_exec) {
3086 /*
3087 * In the original DTrace reference implementation,
3088 * posix_spawn() was a libc routine that just
3089 * did vfork(2) then exec(2). Thus the proc::: probes
3090 * are very fork/exec oriented. The details of this
3091 * in-kernel implementation of posix_spawn() is different
3092 * (while producing the same process-observable effects)
3093 * particularly w.r.t. errors, and which thread/process
3094 * is constructing what on behalf of whom.
3095 */
3096 if (error) {
3097 DTRACE_PROC1(spawn__failure, int, error);
3098 } else {
3099 DTRACE_PROC(spawn__success);
3100 /*
3101 * Some DTrace scripts, e.g. newproc.d in
3102 * /usr/bin, rely on the the 'exec-success'
3103 * probe being fired in the child after the
3104 * new process image has been constructed
3105 * in order to determine the associated pid.
3106 *
3107 * So, even though the parent built the image
3108 * here, for compatibility, mark the new thread
3109 * so 'exec-success' fires on it as it leaves
3110 * the kernel.
3111 */
3112 dtrace_thread_didexec(imgp->ip_new_thread);
3113 }
3114 } else {
3115 if (error) {
3116 DTRACE_PROC1(exec__failure, int, error);
3117 } else {
3118 dtrace_thread_didexec(imgp->ip_new_thread);
3119 }
3120 }
3121
3122 if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL) {
3123 (*dtrace_proc_waitfor_hook)(p);
3124 }
3125 #endif
3126 /*
3127 * clear bsd_info from old task if it did exec.
3128 */
3129 if (task_did_exec(current_task())) {
3130 set_bsdtask_info(current_task(), NULL);
3131 }
3132
3133 /* clear bsd_info from new task and terminate it if exec failed */
3134 if (new_task != NULL && task_is_exec_copy(new_task)) {
3135 set_bsdtask_info(new_task, NULL);
3136 task_terminate_internal(new_task);
3137 }
3138
3139 /* Return to both the parent and the child? */
3140 if (imgp != NULL && spawn_no_exec) {
3141 /*
3142 * If the parent wants the pid, copy it out
3143 */
3144 if (pid != USER_ADDR_NULL)
3145 (void)suword(pid, p->p_pid);
3146 retval[0] = error;
3147
3148 /*
3149 * If we had an error, perform an internal reap ; this is
3150 * entirely safe, as we have a real process backing us.
3151 */
3152 if (error) {
3153 proc_list_lock();
3154 p->p_listflag |= P_LIST_DEADPARENT;
3155 proc_list_unlock();
3156 proc_lock(p);
3157 /* make sure no one else has killed it off... */
3158 if (p->p_stat != SZOMB && p->exit_thread == NULL) {
3159 p->exit_thread = current_thread();
3160 proc_unlock(p);
3161 exit1(p, 1, (int *)NULL);
3162 } else {
3163 /* someone is doing it for us; just skip it */
3164 proc_unlock(p);
3165 }
3166 }
3167 }
3168
3169 /*
3170 * Do not terminate the current task, if proc_exec_switch_task did not
3171 * switch the tasks, terminating the current task without the switch would
3172 * result in loosing the SIGKILL status.
3173 */
3174 if (task_did_exec(current_task())) {
3175 /* Terminate the current task, since exec will start in new task */
3176 task_terminate_internal(current_task());
3177 }
3178
3179 /* Release the thread ref returned by fork_create_child/fork1 */
3180 if (imgp != NULL && imgp->ip_new_thread) {
3181 /* wake up the new thread */
3182 task_clear_return_wait(get_threadtask(imgp->ip_new_thread));
3183 thread_deallocate(imgp->ip_new_thread);
3184 imgp->ip_new_thread = NULL;
3185 }
3186
3187 /* Release the ref returned by fork_create_child/fork1 */
3188 if (new_task) {
3189 task_deallocate(new_task);
3190 new_task = NULL;
3191 }
3192
3193 if (should_release_proc_ref) {
3194 proc_rele(p);
3195 }
3196
3197 if (bufp != NULL) {
3198 FREE(bufp, M_TEMP);
3199 }
3200
3201 if (inherit != NULL) {
3202 ipc_importance_release(inherit);
3203 }
3204
3205 return(error);
3206 }
3207
3208 /*
3209 * proc_exec_switch_task
3210 *
3211 * Parameters: p proc
3212 * old_task task before exec
3213 * new_task task after exec
3214 * new_thread thread in new task
3215 *
3216 * Returns: proc.
3217 *
3218 * Note: The function will switch the task pointer of proc
3219 * from old task to new task. The switch needs to happen
3220 * after draining all proc refs and inside a proc translock.
3221 * In the case of failure to switch the task, which might happen
3222 * if the process received a SIGKILL or jetsam killed it, it will make
3223 * sure that the new tasks terminates. User proc ref returned
3224 * to caller.
3225 *
3226 * This function is called after point of no return, in the case
3227 * failure to switch, it will terminate the new task and swallow the
3228 * error and let the terminated process complete exec and die.
3229 */
3230 proc_t
3231 proc_exec_switch_task(proc_t p, task_t old_task, task_t new_task, thread_t new_thread)
3232 {
3233 int error = 0;
3234 boolean_t task_active;
3235 boolean_t proc_active;
3236 boolean_t thread_active;
3237 thread_t old_thread = current_thread();
3238
3239 /*
3240 * Switch the task pointer of proc to new task.
3241 * Before switching the task, wait for proc_refdrain.
3242 * After the switch happens, the proc can disappear,
3243 * take a ref before it disappears. Waiting for
3244 * proc_refdrain in exec will block all other threads
3245 * trying to take a proc ref, boost the current thread
3246 * to avoid priority inversion.
3247 */
3248 thread_set_exec_promotion(old_thread);
3249 p = proc_refdrain_with_refwait(p, TRUE);
3250 /* extra proc ref returned to the caller */
3251
3252 assert(get_threadtask(new_thread) == new_task);
3253 task_active = task_is_active(new_task);
3254
3255 /* Take the proc_translock to change the task ptr */
3256 proc_lock(p);
3257 proc_active = !(p->p_lflag & P_LEXIT);
3258
3259 /* Check if the current thread is not aborted due to SIGKILL */
3260 thread_active = thread_is_active(old_thread);
3261
3262 /*
3263 * Do not switch the task if the new task or proc is already terminated
3264 * as a result of error in exec past point of no return
3265 */
3266 if (proc_active && task_active && thread_active) {
3267 error = proc_transstart(p, 1, 0);
3268 if (error == 0) {
3269 uthread_t new_uthread = get_bsdthread_info(new_thread);
3270 uthread_t old_uthread = get_bsdthread_info(current_thread());
3271
3272 /*
3273 * bsd_info of old_task will get cleared in execve and posix_spawn
3274 * after firing exec-success/error dtrace probe.
3275 */
3276 p->task = new_task;
3277
3278 /* Clear dispatchqueue and workloop ast offset */
3279 p->p_dispatchqueue_offset = 0;
3280 p->p_dispatchqueue_serialno_offset = 0;
3281 p->p_return_to_kernel_offset = 0;
3282
3283 /* Copy the signal state, dtrace state and set bsd ast on new thread */
3284 act_set_astbsd(new_thread);
3285 new_uthread->uu_siglist = old_uthread->uu_siglist;
3286 new_uthread->uu_sigwait = old_uthread->uu_sigwait;
3287 new_uthread->uu_sigmask = old_uthread->uu_sigmask;
3288 new_uthread->uu_oldmask = old_uthread->uu_oldmask;
3289 new_uthread->uu_vforkmask = old_uthread->uu_vforkmask;
3290 new_uthread->uu_exit_reason = old_uthread->uu_exit_reason;
3291 #if CONFIG_DTRACE
3292 new_uthread->t_dtrace_sig = old_uthread->t_dtrace_sig;
3293 new_uthread->t_dtrace_stop = old_uthread->t_dtrace_stop;
3294 new_uthread->t_dtrace_resumepid = old_uthread->t_dtrace_resumepid;
3295 assert(new_uthread->t_dtrace_scratch == NULL);
3296 new_uthread->t_dtrace_scratch = old_uthread->t_dtrace_scratch;
3297
3298 old_uthread->t_dtrace_sig = 0;
3299 old_uthread->t_dtrace_stop = 0;
3300 old_uthread->t_dtrace_resumepid = 0;
3301 old_uthread->t_dtrace_scratch = NULL;
3302 #endif
3303 /* Copy the resource accounting info */
3304 thread_copy_resource_info(new_thread, current_thread());
3305
3306 /* Clear the exit reason and signal state on old thread */
3307 old_uthread->uu_exit_reason = NULL;
3308 old_uthread->uu_siglist = 0;
3309
3310 /* Add the new uthread to proc uthlist and remove the old one */
3311 TAILQ_INSERT_TAIL(&p->p_uthlist, new_uthread, uu_list);
3312 TAILQ_REMOVE(&p->p_uthlist, old_uthread, uu_list);
3313
3314 task_set_did_exec_flag(old_task);
3315 task_clear_exec_copy_flag(new_task);
3316
3317 task_copy_fields_for_exec(new_task, old_task);
3318
3319 proc_transend(p, 1);
3320 }
3321 }
3322
3323 proc_unlock(p);
3324 proc_refwake(p);
3325 thread_clear_exec_promotion(old_thread);
3326
3327 if (error != 0 || !task_active || !proc_active || !thread_active) {
3328 task_terminate_internal(new_task);
3329 }
3330
3331 return p;
3332 }
3333
3334 /*
3335 * execve
3336 *
3337 * Parameters: uap->fname File name to exec
3338 * uap->argp Argument list
3339 * uap->envp Environment list
3340 *
3341 * Returns: 0 Success
3342 * __mac_execve:EINVAL Invalid argument
3343 * __mac_execve:ENOTSUP Invalid argument
3344 * __mac_execve:EACCES Permission denied
3345 * __mac_execve:EINTR Interrupted function
3346 * __mac_execve:ENOMEM Not enough space
3347 * __mac_execve:EFAULT Bad address
3348 * __mac_execve:ENAMETOOLONG Filename too long
3349 * __mac_execve:ENOEXEC Executable file format error
3350 * __mac_execve:ETXTBSY Text file busy [misuse of error code]
3351 * __mac_execve:???
3352 *
3353 * TODO: Dynamic linker header address on stack is copied via suword()
3354 */
3355 /* ARGSUSED */
3356 int
3357 execve(proc_t p, struct execve_args *uap, int32_t *retval)
3358 {
3359 struct __mac_execve_args muap;
3360 int err;
3361
3362 memoryshot(VM_EXECVE, DBG_FUNC_NONE);
3363
3364 muap.fname = uap->fname;
3365 muap.argp = uap->argp;
3366 muap.envp = uap->envp;
3367 muap.mac_p = USER_ADDR_NULL;
3368 err = __mac_execve(p, &muap, retval);
3369
3370 return(err);
3371 }
3372
3373 /*
3374 * __mac_execve
3375 *
3376 * Parameters: uap->fname File name to exec
3377 * uap->argp Argument list
3378 * uap->envp Environment list
3379 * uap->mac_p MAC label supplied by caller
3380 *
3381 * Returns: 0 Success
3382 * EINVAL Invalid argument
3383 * ENOTSUP Not supported
3384 * ENOEXEC Executable file format error
3385 * exec_activate_image:EINVAL Invalid argument
3386 * exec_activate_image:EACCES Permission denied
3387 * exec_activate_image:EINTR Interrupted function
3388 * exec_activate_image:ENOMEM Not enough space
3389 * exec_activate_image:EFAULT Bad address
3390 * exec_activate_image:ENAMETOOLONG Filename too long
3391 * exec_activate_image:ENOEXEC Executable file format error
3392 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
3393 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
3394 * exec_activate_image:???
3395 * mac_execve_enter:???
3396 *
3397 * TODO: Dynamic linker header address on stack is copied via suword()
3398 */
3399 int
3400 __mac_execve(proc_t p, struct __mac_execve_args *uap, int32_t *retval)
3401 {
3402 char *bufp = NULL;
3403 struct image_params *imgp;
3404 struct vnode_attr *vap;
3405 struct vnode_attr *origvap;
3406 int error;
3407 int is_64 = IS_64BIT_PROCESS(p);
3408 struct vfs_context context;
3409 struct uthread *uthread;
3410 task_t new_task = NULL;
3411 boolean_t should_release_proc_ref = FALSE;
3412 boolean_t exec_done = FALSE;
3413 boolean_t in_vfexec = FALSE;
3414 void *inherit = NULL;
3415
3416 context.vc_thread = current_thread();
3417 context.vc_ucred = kauth_cred_proc_ref(p); /* XXX must NOT be kauth_cred_get() */
3418
3419 /* Allocate a big chunk for locals instead of using stack since these
3420 * structures a pretty big.
3421 */
3422 MALLOC(bufp, char *, (sizeof(*imgp) + sizeof(*vap) + sizeof(*origvap)), M_TEMP, M_WAITOK | M_ZERO);
3423 imgp = (struct image_params *) bufp;
3424 if (bufp == NULL) {
3425 error = ENOMEM;
3426 goto exit_with_error;
3427 }
3428 vap = (struct vnode_attr *) (bufp + sizeof(*imgp));
3429 origvap = (struct vnode_attr *) (bufp + sizeof(*imgp) + sizeof(*vap));
3430
3431 /* Initialize the common data in the image_params structure */
3432 imgp->ip_user_fname = uap->fname;
3433 imgp->ip_user_argv = uap->argp;
3434 imgp->ip_user_envv = uap->envp;
3435 imgp->ip_vattr = vap;
3436 imgp->ip_origvattr = origvap;
3437 imgp->ip_vfs_context = &context;
3438 imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT : IMGPF_NONE) | ((p->p_flag & P_DISABLE_ASLR) ? IMGPF_DISABLE_ASLR : IMGPF_NONE);
3439 imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
3440 imgp->ip_mac_return = 0;
3441 imgp->ip_cs_error = OS_REASON_NULL;
3442
3443 #if CONFIG_MACF
3444 if (uap->mac_p != USER_ADDR_NULL) {
3445 error = mac_execve_enter(uap->mac_p, imgp);
3446 if (error) {
3447 kauth_cred_unref(&context.vc_ucred);
3448 goto exit_with_error;
3449 }
3450 }
3451 #endif
3452 uthread = get_bsdthread_info(current_thread());
3453 if (uthread->uu_flag & UT_VFORK) {
3454 imgp->ip_flags |= IMGPF_VFORK_EXEC;
3455 in_vfexec = TRUE;
3456 } else {
3457 imgp->ip_flags |= IMGPF_EXEC;
3458
3459 /*
3460 * For execve case, create a new task and thread
3461 * which points to current_proc. The current_proc will point
3462 * to the new task after image activation and proc ref drain.
3463 *
3464 * proc (current_proc) <----- old_task (current_task)
3465 * ^ | ^
3466 * | | |
3467 * | ----------------------------------
3468 * |
3469 * --------- new_task (task marked as TF_EXEC_COPY)
3470 *
3471 * After image activation, the proc will point to the new task
3472 * and would look like following.
3473 *
3474 * proc (current_proc) <----- old_task (current_task, marked as TPF_DID_EXEC)
3475 * ^ |
3476 * | |
3477 * | ----------> new_task
3478 * | |
3479 * -----------------
3480 *
3481 * During exec any transition from new_task -> proc is fine, but don't allow
3482 * transition from proc->task, since it will modify old_task.
3483 */
3484 imgp->ip_new_thread = fork_create_child(current_task(),
3485 NULL, p, FALSE, p->p_flag & P_LP64, TRUE);
3486 /* task and thread ref returned by fork_create_child */
3487 if (imgp->ip_new_thread == NULL) {
3488 error = ENOMEM;
3489 goto exit_with_error;
3490 }
3491
3492 new_task = get_threadtask(imgp->ip_new_thread);
3493 context.vc_thread = imgp->ip_new_thread;
3494 }
3495
3496 error = exec_activate_image(imgp);
3497 /* thread and task ref returned for vfexec case */
3498
3499 if (imgp->ip_new_thread != NULL) {
3500 /*
3501 * task reference might be returned by exec_activate_image
3502 * for vfexec.
3503 */
3504 new_task = get_threadtask(imgp->ip_new_thread);
3505 }
3506
3507 if (!error && !in_vfexec) {
3508 p = proc_exec_switch_task(p, current_task(), new_task, imgp->ip_new_thread);
3509 /* proc ref returned */
3510 should_release_proc_ref = TRUE;
3511 }
3512
3513 kauth_cred_unref(&context.vc_ucred);
3514
3515 /* Image not claimed by any activator? */
3516 if (error == -1)
3517 error = ENOEXEC;
3518
3519 if (!error) {
3520 exec_done = TRUE;
3521 assert(imgp->ip_new_thread != NULL);
3522
3523 exec_resettextvp(p, imgp);
3524 error = check_for_signature(p, imgp);
3525 }
3526 if (imgp->ip_vp != NULLVP)
3527 vnode_put(imgp->ip_vp);
3528 if (imgp->ip_scriptvp != NULLVP)
3529 vnode_put(imgp->ip_scriptvp);
3530 if (imgp->ip_strings)
3531 execargs_free(imgp);
3532 #if CONFIG_MACF
3533 if (imgp->ip_execlabelp)
3534 mac_cred_label_free(imgp->ip_execlabelp);
3535 if (imgp->ip_scriptlabelp)
3536 mac_vnode_label_free(imgp->ip_scriptlabelp);
3537 #endif
3538 if (imgp->ip_cs_error != OS_REASON_NULL) {
3539 os_reason_free(imgp->ip_cs_error);
3540 imgp->ip_cs_error = OS_REASON_NULL;
3541 }
3542
3543 if (!error) {
3544 /*
3545 * We need to initialize the bank context behind the protection of
3546 * the proc_trans lock to prevent a race with exit. We can't do this during
3547 * exec_activate_image because task_bank_init checks entitlements that
3548 * aren't loaded until subsequent calls (including exec_resettextvp).
3549 */
3550 error = proc_transstart(p, 0, 0);
3551 }
3552
3553 if (!error) {
3554 task_bank_init(get_threadtask(imgp->ip_new_thread));
3555 proc_transend(p, 0);
3556
3557 /* Sever any extant thread affinity */
3558 thread_affinity_exec(current_thread());
3559
3560 /* Inherit task role from old task to new task for exec */
3561 if (!in_vfexec) {
3562 proc_inherit_task_role(get_threadtask(imgp->ip_new_thread), current_task());
3563 }
3564
3565 thread_t main_thread = imgp->ip_new_thread;
3566
3567 task_set_main_thread_qos(new_task, main_thread);
3568
3569 #if CONFIG_MACF
3570 /*
3571 * Processes with the MAP_JIT entitlement are permitted to have
3572 * a jumbo-size map.
3573 */
3574 if (mac_proc_check_map_anon(p, 0, 0, 0, MAP_JIT, NULL) == 0) {
3575 vm_map_set_jumbo(get_task_map(new_task));
3576 }
3577 #endif /* CONFIG_MACF */
3578
3579
3580 #if CONFIG_DTRACE
3581 dtrace_thread_didexec(imgp->ip_new_thread);
3582
3583 if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL)
3584 (*dtrace_proc_waitfor_hook)(p);
3585 #endif
3586
3587 if (in_vfexec) {
3588 vfork_return(p, retval, p->p_pid);
3589 }
3590 } else {
3591 DTRACE_PROC1(exec__failure, int, error);
3592 }
3593
3594 exit_with_error:
3595
3596 /*
3597 * clear bsd_info from old task if it did exec.
3598 */
3599 if (task_did_exec(current_task())) {
3600 set_bsdtask_info(current_task(), NULL);
3601 }
3602
3603 /* clear bsd_info from new task and terminate it if exec failed */
3604 if (new_task != NULL && task_is_exec_copy(new_task)) {
3605 set_bsdtask_info(new_task, NULL);
3606 task_terminate_internal(new_task);
3607 }
3608
3609 /*
3610 * Need to transfer pending watch port boosts to the new task while still making
3611 * sure that the old task remains in the importance linkage. Create an importance
3612 * linkage from old task to new task, then switch the task importance base
3613 * of old task and new task. After the switch the port watch boost will be
3614 * boosting the new task and new task will be donating importance to old task.
3615 */
3616 if (error == 0 && task_did_exec(current_task())) {
3617 inherit = ipc_importance_exec_switch_task(current_task(), get_threadtask(imgp->ip_new_thread));
3618 }
3619
3620 if (imgp != NULL) {
3621 /*
3622 * Do not terminate the current task, if proc_exec_switch_task did not
3623 * switch the tasks, terminating the current task without the switch would
3624 * result in loosing the SIGKILL status.
3625 */
3626 if (task_did_exec(current_task())) {
3627 /* Terminate the current task, since exec will start in new task */
3628 task_terminate_internal(current_task());
3629 }
3630
3631 /* Release the thread ref returned by fork_create_child */
3632 if (imgp->ip_new_thread) {
3633 /* wake up the new exec thread */
3634 task_clear_return_wait(get_threadtask(imgp->ip_new_thread));
3635 thread_deallocate(imgp->ip_new_thread);
3636 imgp->ip_new_thread = NULL;
3637 }
3638 }
3639
3640 /* Release the ref returned by fork_create_child */
3641 if (new_task) {
3642 task_deallocate(new_task);
3643 new_task = NULL;
3644 }
3645
3646 if (should_release_proc_ref) {
3647 proc_rele(p);
3648 }
3649
3650 if (bufp != NULL) {
3651 FREE(bufp, M_TEMP);
3652 }
3653
3654 if (inherit != NULL) {
3655 ipc_importance_release(inherit);
3656 }
3657
3658 return(error);
3659 }
3660
3661
3662 /*
3663 * copyinptr
3664 *
3665 * Description: Copy a pointer in from user space to a user_addr_t in kernel
3666 * space, based on 32/64 bitness of the user space
3667 *
3668 * Parameters: froma User space address
3669 * toptr Address of kernel space user_addr_t
3670 * ptr_size 4/8, based on 'froma' address space
3671 *
3672 * Returns: 0 Success
3673 * EFAULT Bad 'froma'
3674 *
3675 * Implicit returns:
3676 * *ptr_size Modified
3677 */
3678 static int
3679 copyinptr(user_addr_t froma, user_addr_t *toptr, int ptr_size)
3680 {
3681 int error;
3682
3683 if (ptr_size == 4) {
3684 /* 64 bit value containing 32 bit address */
3685 unsigned int i;
3686
3687 error = copyin(froma, &i, 4);
3688 *toptr = CAST_USER_ADDR_T(i); /* SAFE */
3689 } else {
3690 error = copyin(froma, toptr, 8);
3691 }
3692 return (error);
3693 }
3694
3695
3696 /*
3697 * copyoutptr
3698 *
3699 * Description: Copy a pointer out from a user_addr_t in kernel space to
3700 * user space, based on 32/64 bitness of the user space
3701 *
3702 * Parameters: ua User space address to copy to
3703 * ptr Address of kernel space user_addr_t
3704 * ptr_size 4/8, based on 'ua' address space
3705 *
3706 * Returns: 0 Success
3707 * EFAULT Bad 'ua'
3708 *
3709 */
3710 static int
3711 copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size)
3712 {
3713 int error;
3714
3715 if (ptr_size == 4) {
3716 /* 64 bit value containing 32 bit address */
3717 unsigned int i = CAST_DOWN_EXPLICIT(unsigned int,ua); /* SAFE */
3718
3719 error = copyout(&i, ptr, 4);
3720 } else {
3721 error = copyout(&ua, ptr, 8);
3722 }
3723 return (error);
3724 }
3725
3726
3727 /*
3728 * exec_copyout_strings
3729 *
3730 * Copy out the strings segment to user space. The strings segment is put
3731 * on a preinitialized stack frame.
3732 *
3733 * Parameters: struct image_params * the image parameter block
3734 * int * a pointer to the stack offset variable
3735 *
3736 * Returns: 0 Success
3737 * !0 Faiure: errno
3738 *
3739 * Implicit returns:
3740 * (*stackp) The stack offset, modified
3741 *
3742 * Note: The strings segment layout is backward, from the beginning
3743 * of the top of the stack to consume the minimal amount of
3744 * space possible; the returned stack pointer points to the
3745 * end of the area consumed (stacks grow downward).
3746 *
3747 * argc is an int; arg[i] are pointers; env[i] are pointers;
3748 * the 0's are (void *)NULL's
3749 *
3750 * The stack frame layout is:
3751 *
3752 * +-------------+ <- p->user_stack
3753 * | 16b |
3754 * +-------------+
3755 * | STRING AREA |
3756 * | : |
3757 * | : |
3758 * | : |
3759 * +- -- -- -- --+
3760 * | PATH AREA |
3761 * +-------------+
3762 * | 0 |
3763 * +-------------+
3764 * | applev[n] |
3765 * +-------------+
3766 * :
3767 * :
3768 * +-------------+
3769 * | applev[1] |
3770 * +-------------+
3771 * | exec_path / |
3772 * | applev[0] |
3773 * +-------------+
3774 * | 0 |
3775 * +-------------+
3776 * | env[n] |
3777 * +-------------+
3778 * :
3779 * :
3780 * +-------------+
3781 * | env[0] |
3782 * +-------------+
3783 * | 0 |
3784 * +-------------+
3785 * | arg[argc-1] |
3786 * +-------------+
3787 * :
3788 * :
3789 * +-------------+
3790 * | arg[0] |
3791 * +-------------+
3792 * | argc |
3793 * sp-> +-------------+
3794 *
3795 * Although technically a part of the STRING AREA, we treat the PATH AREA as
3796 * a separate entity. This allows us to align the beginning of the PATH AREA
3797 * to a pointer boundary so that the exec_path, env[i], and argv[i] pointers
3798 * which preceed it on the stack are properly aligned.
3799 */
3800
3801 static int
3802 exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp)
3803 {
3804 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
3805 int ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
3806 int ptr_area_size;
3807 void *ptr_buffer_start, *ptr_buffer;
3808 int string_size;
3809
3810 user_addr_t string_area; /* *argv[], *env[] */
3811 user_addr_t ptr_area; /* argv[], env[], applev[] */
3812 user_addr_t argc_area; /* argc */
3813 user_addr_t stack;
3814 int error;
3815
3816 unsigned i;
3817 struct copyout_desc {
3818 char *start_string;
3819 int count;
3820 #if CONFIG_DTRACE
3821 user_addr_t *dtrace_cookie;
3822 #endif
3823 boolean_t null_term;
3824 } descriptors[] = {
3825 {
3826 .start_string = imgp->ip_startargv,
3827 .count = imgp->ip_argc,
3828 #if CONFIG_DTRACE
3829 .dtrace_cookie = &p->p_dtrace_argv,
3830 #endif
3831 .null_term = TRUE
3832 },
3833 {
3834 .start_string = imgp->ip_endargv,
3835 .count = imgp->ip_envc,
3836 #if CONFIG_DTRACE
3837 .dtrace_cookie = &p->p_dtrace_envp,
3838 #endif
3839 .null_term = TRUE
3840 },
3841 {
3842 .start_string = imgp->ip_strings,
3843 .count = 1,
3844 #if CONFIG_DTRACE
3845 .dtrace_cookie = NULL,
3846 #endif
3847 .null_term = FALSE
3848 },
3849 {
3850 .start_string = imgp->ip_endenvv,
3851 .count = imgp->ip_applec - 1, /* exec_path handled above */
3852 #if CONFIG_DTRACE
3853 .dtrace_cookie = NULL,
3854 #endif
3855 .null_term = TRUE
3856 }
3857 };
3858
3859 stack = *stackp;
3860
3861 /*
3862 * All previous contributors to the string area
3863 * should have aligned their sub-area
3864 */
3865 if (imgp->ip_strspace % ptr_size != 0) {
3866 error = EINVAL;
3867 goto bad;
3868 }
3869
3870 /* Grow the stack down for the strings we've been building up */
3871 string_size = imgp->ip_strendp - imgp->ip_strings;
3872 stack -= string_size;
3873 string_area = stack;
3874
3875 /*
3876 * Need room for one pointer for each string, plus
3877 * one for the NULLs terminating the argv, envv, and apple areas.
3878 */
3879 ptr_area_size = (imgp->ip_argc + imgp->ip_envc + imgp->ip_applec + 3) *
3880 ptr_size;
3881 stack -= ptr_area_size;
3882 ptr_area = stack;
3883
3884 /* We'll construct all the pointer arrays in our string buffer,
3885 * which we already know is aligned properly, and ip_argspace
3886 * was used to verify we have enough space.
3887 */
3888 ptr_buffer_start = ptr_buffer = (void *)imgp->ip_strendp;
3889
3890 /*
3891 * Need room for pointer-aligned argc slot.
3892 */
3893 stack -= ptr_size;
3894 argc_area = stack;
3895
3896 /*
3897 * Record the size of the arguments area so that sysctl_procargs()
3898 * can return the argument area without having to parse the arguments.
3899 */
3900 proc_lock(p);
3901 p->p_argc = imgp->ip_argc;
3902 p->p_argslen = (int)(*stackp - string_area);
3903 proc_unlock(p);
3904
3905 /* Return the initial stack address: the location of argc */
3906 *stackp = stack;
3907
3908 /*
3909 * Copy out the entire strings area.
3910 */
3911 error = copyout(imgp->ip_strings, string_area,
3912 string_size);
3913 if (error)
3914 goto bad;
3915
3916 for (i = 0; i < sizeof(descriptors)/sizeof(descriptors[0]); i++) {
3917 char *cur_string = descriptors[i].start_string;
3918 int j;
3919
3920 #if CONFIG_DTRACE
3921 if (descriptors[i].dtrace_cookie) {
3922 proc_lock(p);
3923 *descriptors[i].dtrace_cookie = ptr_area + ((uintptr_t)ptr_buffer - (uintptr_t)ptr_buffer_start); /* dtrace convenience */
3924 proc_unlock(p);
3925 }
3926 #endif /* CONFIG_DTRACE */
3927
3928 /*
3929 * For each segment (argv, envv, applev), copy as many pointers as requested
3930 * to our pointer buffer.
3931 */
3932 for (j = 0; j < descriptors[i].count; j++) {
3933 user_addr_t cur_address = string_area + (cur_string - imgp->ip_strings);
3934
3935 /* Copy out the pointer to the current string. Alignment has been verified */
3936 if (ptr_size == 8) {
3937 *(uint64_t *)ptr_buffer = (uint64_t)cur_address;
3938 } else {
3939 *(uint32_t *)ptr_buffer = (uint32_t)cur_address;
3940 }
3941
3942 ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size);
3943 cur_string += strlen(cur_string) + 1; /* Only a NUL between strings in the same area */
3944 }
3945
3946 if (descriptors[i].null_term) {
3947 if (ptr_size == 8) {
3948 *(uint64_t *)ptr_buffer = 0ULL;
3949 } else {
3950 *(uint32_t *)ptr_buffer = 0;
3951 }
3952
3953 ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size);
3954 }
3955 }
3956
3957 /*
3958 * Copy out all our pointer arrays in bulk.
3959 */
3960 error = copyout(ptr_buffer_start, ptr_area,
3961 ptr_area_size);
3962 if (error)
3963 goto bad;
3964
3965 /* argc (int32, stored in a ptr_size area) */
3966 error = copyoutptr((user_addr_t)imgp->ip_argc, argc_area, ptr_size);
3967 if (error)
3968 goto bad;
3969
3970 bad:
3971 return(error);
3972 }
3973
3974
3975 /*
3976 * exec_extract_strings
3977 *
3978 * Copy arguments and environment from user space into work area; we may
3979 * have already copied some early arguments into the work area, and if
3980 * so, any arguments opied in are appended to those already there.
3981 * This function is the primary manipulator of ip_argspace, since
3982 * these are the arguments the client of execve(2) knows about. After
3983 * each argv[]/envv[] string is copied, we charge the string length
3984 * and argv[]/envv[] pointer slot to ip_argspace, so that we can
3985 * full preflight the arg list size.
3986 *
3987 * Parameters: struct image_params * the image parameter block
3988 *
3989 * Returns: 0 Success
3990 * !0 Failure: errno
3991 *
3992 * Implicit returns;
3993 * (imgp->ip_argc) Count of arguments, updated
3994 * (imgp->ip_envc) Count of environment strings, updated
3995 * (imgp->ip_argspace) Count of remaining of NCARGS
3996 * (imgp->ip_interp_buffer) Interpreter and args (mutated in place)
3997 *
3998 *
3999 * Note: The argument and environment vectors are user space pointers
4000 * to arrays of user space pointers.
4001 */
4002 static int
4003 exec_extract_strings(struct image_params *imgp)
4004 {
4005 int error = 0;
4006 int ptr_size = (imgp->ip_flags & IMGPF_WAS_64BIT) ? 8 : 4;
4007 int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
4008 user_addr_t argv = imgp->ip_user_argv;
4009 user_addr_t envv = imgp->ip_user_envv;
4010
4011 /*
4012 * Adjust space reserved for the path name by however much padding it
4013 * needs. Doing this here since we didn't know if this would be a 32-
4014 * or 64-bit process back in exec_save_path.
4015 */
4016 while (imgp->ip_strspace % new_ptr_size != 0) {
4017 *imgp->ip_strendp++ = '\0';
4018 imgp->ip_strspace--;
4019 /* imgp->ip_argspace--; not counted towards exec args total */
4020 }
4021
4022 /*
4023 * From now on, we start attributing string space to ip_argspace
4024 */
4025 imgp->ip_startargv = imgp->ip_strendp;
4026 imgp->ip_argc = 0;
4027
4028 if((imgp->ip_flags & IMGPF_INTERPRET) != 0) {
4029 user_addr_t arg;
4030 char *argstart, *ch;
4031
4032 /* First, the arguments in the "#!" string are tokenized and extracted. */
4033 argstart = imgp->ip_interp_buffer;
4034 while (argstart) {
4035 ch = argstart;
4036 while (*ch && !IS_WHITESPACE(*ch)) {
4037 ch++;
4038 }
4039
4040 if (*ch == '\0') {
4041 /* last argument, no need to NUL-terminate */
4042 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE);
4043 argstart = NULL;
4044 } else {
4045 /* NUL-terminate */
4046 *ch = '\0';
4047 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE);
4048
4049 /*
4050 * Find the next string. We know spaces at the end of the string have already
4051 * been stripped.
4052 */
4053 argstart = ch + 1;
4054 while (IS_WHITESPACE(*argstart)) {
4055 argstart++;
4056 }
4057 }
4058
4059 /* Error-check, regardless of whether this is the last interpreter arg or not */
4060 if (error)
4061 goto bad;
4062 if (imgp->ip_argspace < new_ptr_size) {
4063 error = E2BIG;
4064 goto bad;
4065 }
4066 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
4067 imgp->ip_argc++;
4068 }
4069
4070 if (argv != 0LL) {
4071 /*
4072 * If we are running an interpreter, replace the av[0] that was
4073 * passed to execve() with the path name that was
4074 * passed to execve() for interpreters which do not use the PATH
4075 * to locate their script arguments.
4076 */
4077 error = copyinptr(argv, &arg, ptr_size);
4078 if (error)
4079 goto bad;
4080 if (arg != 0LL) {
4081 argv += ptr_size; /* consume without using */
4082 }
4083 }
4084
4085 if (imgp->ip_interp_sugid_fd != -1) {
4086 char temp[19]; /* "/dev/fd/" + 10 digits + NUL */
4087 snprintf(temp, sizeof(temp), "/dev/fd/%d", imgp->ip_interp_sugid_fd);
4088 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(temp), UIO_SYSSPACE, TRUE);
4089 } else {
4090 error = exec_add_user_string(imgp, imgp->ip_user_fname, imgp->ip_seg, TRUE);
4091 }
4092
4093 if (error)
4094 goto bad;
4095 if (imgp->ip_argspace < new_ptr_size) {
4096 error = E2BIG;
4097 goto bad;
4098 }
4099 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
4100 imgp->ip_argc++;
4101 }
4102
4103 while (argv != 0LL) {
4104 user_addr_t arg;
4105
4106 error = copyinptr(argv, &arg, ptr_size);
4107 if (error)
4108 goto bad;
4109
4110 if (arg == 0LL) {
4111 break;
4112 }
4113
4114 argv += ptr_size;
4115
4116 /*
4117 * av[n...] = arg[n]
4118 */
4119 error = exec_add_user_string(imgp, arg, imgp->ip_seg, TRUE);
4120 if (error)
4121 goto bad;
4122 if (imgp->ip_argspace < new_ptr_size) {
4123 error = E2BIG;
4124 goto bad;
4125 }
4126 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
4127 imgp->ip_argc++;
4128 }
4129
4130 /* Save space for argv[] NULL terminator */
4131 if (imgp->ip_argspace < new_ptr_size) {
4132 error = E2BIG;
4133 goto bad;
4134 }
4135 imgp->ip_argspace -= new_ptr_size;
4136
4137 /* Note where the args ends and env begins. */
4138 imgp->ip_endargv = imgp->ip_strendp;
4139 imgp->ip_envc = 0;
4140
4141 /* Now, get the environment */
4142 while (envv != 0LL) {
4143 user_addr_t env;
4144
4145 error = copyinptr(envv, &env, ptr_size);
4146 if (error)
4147 goto bad;
4148
4149 envv += ptr_size;
4150 if (env == 0LL) {
4151 break;
4152 }
4153 /*
4154 * av[n...] = env[n]
4155 */
4156 error = exec_add_user_string(imgp, env, imgp->ip_seg, TRUE);
4157 if (error)
4158 goto bad;
4159 if (imgp->ip_argspace < new_ptr_size) {
4160 error = E2BIG;
4161 goto bad;
4162 }
4163 imgp->ip_argspace -= new_ptr_size; /* to hold envv[] entry */
4164 imgp->ip_envc++;
4165 }
4166
4167 /* Save space for envv[] NULL terminator */
4168 if (imgp->ip_argspace < new_ptr_size) {
4169 error = E2BIG;
4170 goto bad;
4171 }
4172 imgp->ip_argspace -= new_ptr_size;
4173
4174 /* Align the tail of the combined argv+envv area */
4175 while (imgp->ip_strspace % new_ptr_size != 0) {
4176 if (imgp->ip_argspace < 1) {
4177 error = E2BIG;
4178 goto bad;
4179 }
4180 *imgp->ip_strendp++ = '\0';
4181 imgp->ip_strspace--;
4182 imgp->ip_argspace--;
4183 }
4184
4185 /* Note where the envv ends and applev begins. */
4186 imgp->ip_endenvv = imgp->ip_strendp;
4187
4188 /*
4189 * From now on, we are no longer charging argument
4190 * space to ip_argspace.
4191 */
4192
4193 bad:
4194 return error;
4195 }
4196
4197 /*
4198 * Libc has an 8-element array set up for stack guard values. It only fills
4199 * in one of those entries, and both gcc and llvm seem to use only a single
4200 * 8-byte guard. Until somebody needs more than an 8-byte guard value, don't
4201 * do the work to construct them.
4202 */
4203 #define GUARD_VALUES 1
4204 #define GUARD_KEY "stack_guard="
4205
4206 /*
4207 * System malloc needs some entropy when it is initialized.
4208 */
4209 #define ENTROPY_VALUES 2
4210 #define ENTROPY_KEY "malloc_entropy="
4211
4212 /*
4213 * System malloc engages nanozone for UIAPP.
4214 */
4215 #define NANO_ENGAGE_KEY "MallocNanoZone=1"
4216
4217 #define PFZ_KEY "pfz="
4218 extern user32_addr_t commpage_text32_location;
4219 extern user64_addr_t commpage_text64_location;
4220
4221 #define MAIN_STACK_VALUES 4
4222 #define MAIN_STACK_KEY "main_stack="
4223
4224 #define FSID_KEY "executable_file="
4225 #define DYLD_FSID_KEY "dyld_file="
4226 #define CDHASH_KEY "executable_cdhash="
4227
4228 #define FSID_MAX_STRING "0x1234567890abcdef,0x1234567890abcdef"
4229
4230 #define HEX_STR_LEN 18 // 64-bit hex value "0x0123456701234567"
4231
4232 static int
4233 exec_add_entropy_key(struct image_params *imgp,
4234 const char *key,
4235 int values,
4236 boolean_t embedNUL)
4237 {
4238 const int limit = 8;
4239 uint64_t entropy[limit];
4240 char str[strlen(key) + (HEX_STR_LEN + 1) * limit + 1];
4241 if (values > limit) {
4242 values = limit;
4243 }
4244
4245 read_random(entropy, sizeof(entropy[0]) * values);
4246
4247 if (embedNUL) {
4248 entropy[0] &= ~(0xffull << 8);
4249 }
4250
4251 int len = snprintf(str, sizeof(str), "%s0x%llx", key, entropy[0]);
4252 int remaining = sizeof(str) - len;
4253 for (int i = 1; i < values && remaining > 0; ++i) {
4254 int start = sizeof(str) - remaining;
4255 len = snprintf(&str[start], remaining, ",0x%llx", entropy[i]);
4256 remaining -= len;
4257 }
4258
4259 return exec_add_user_string(imgp, CAST_USER_ADDR_T(str), UIO_SYSSPACE, FALSE);
4260 }
4261
4262 /*
4263 * Build up the contents of the apple[] string vector
4264 */
4265 static int
4266 exec_add_apple_strings(struct image_params *imgp,
4267 const load_result_t *load_result)
4268 {
4269 int error;
4270 int img_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
4271
4272 /* exec_save_path stored the first string */
4273 imgp->ip_applec = 1;
4274
4275 /* adding the pfz string */
4276 {
4277 char pfz_string[strlen(PFZ_KEY) + HEX_STR_LEN + 1];
4278
4279 if (img_ptr_size == 8) {
4280 snprintf(pfz_string, sizeof(pfz_string), PFZ_KEY "0x%llx", commpage_text64_location);
4281 } else {
4282 snprintf(pfz_string, sizeof(pfz_string), PFZ_KEY "0x%x", commpage_text32_location);
4283 }
4284 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(pfz_string), UIO_SYSSPACE, FALSE);
4285 if (error) {
4286 goto bad;
4287 }
4288 imgp->ip_applec++;
4289 }
4290
4291 /* adding the NANO_ENGAGE_KEY key */
4292 if (imgp->ip_px_sa) {
4293 int proc_flags = (((struct _posix_spawnattr *) imgp->ip_px_sa)->psa_flags);
4294
4295 if ((proc_flags & _POSIX_SPAWN_NANO_ALLOCATOR) == _POSIX_SPAWN_NANO_ALLOCATOR) {
4296 const char *nano_string = NANO_ENGAGE_KEY;
4297 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(nano_string), UIO_SYSSPACE, FALSE);
4298 if (error){
4299 goto bad;
4300 }
4301 imgp->ip_applec++;
4302 }
4303 }
4304
4305 /*
4306 * Supply libc with a collection of random values to use when
4307 * implementing -fstack-protector.
4308 *
4309 * (The first random string always contains an embedded NUL so that
4310 * __stack_chk_guard also protects against C string vulnerabilities)
4311 */
4312 error = exec_add_entropy_key(imgp, GUARD_KEY, GUARD_VALUES, TRUE);
4313 if (error) {
4314 goto bad;
4315 }
4316 imgp->ip_applec++;
4317
4318 /*
4319 * Supply libc with entropy for system malloc.
4320 */
4321 error = exec_add_entropy_key(imgp, ENTROPY_KEY, ENTROPY_VALUES, FALSE);
4322 if (error) {
4323 goto bad;
4324 }
4325 imgp->ip_applec++;
4326
4327 /*
4328 * Add MAIN_STACK_KEY: Supplies the address and size of the main thread's
4329 * stack if it was allocated by the kernel.
4330 *
4331 * The guard page is not included in this stack size as libpthread
4332 * expects to add it back in after receiving this value.
4333 */
4334 if (load_result->unixproc) {
4335 char stack_string[strlen(MAIN_STACK_KEY) + (HEX_STR_LEN + 1) * MAIN_STACK_VALUES + 1];
4336 snprintf(stack_string, sizeof(stack_string),
4337 MAIN_STACK_KEY "0x%llx,0x%llx,0x%llx,0x%llx",
4338 (uint64_t)load_result->user_stack,
4339 (uint64_t)load_result->user_stack_size,
4340 (uint64_t)load_result->user_stack_alloc,
4341 (uint64_t)load_result->user_stack_alloc_size);
4342 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(stack_string), UIO_SYSSPACE, FALSE);
4343 if (error) {
4344 goto bad;
4345 }
4346 imgp->ip_applec++;
4347 }
4348
4349 if (imgp->ip_vattr) {
4350 uint64_t fsid = get_va_fsid(imgp->ip_vattr);
4351 uint64_t fsobjid = imgp->ip_vattr->va_fileid;
4352
4353 char fsid_string[strlen(FSID_KEY) + strlen(FSID_MAX_STRING) + 1];
4354 snprintf(fsid_string, sizeof(fsid_string),
4355 FSID_KEY "0x%llx,0x%llx", fsid, fsobjid);
4356 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(fsid_string), UIO_SYSSPACE, FALSE);
4357 if (error) {
4358 goto bad;
4359 }
4360 imgp->ip_applec++;
4361 }
4362
4363 if (imgp->ip_dyld_fsid || imgp->ip_dyld_fsobjid ) {
4364 char fsid_string[strlen(DYLD_FSID_KEY) + strlen(FSID_MAX_STRING) + 1];
4365 snprintf(fsid_string, sizeof(fsid_string),
4366 DYLD_FSID_KEY "0x%llx,0x%llx", imgp->ip_dyld_fsid, imgp->ip_dyld_fsobjid);
4367 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(fsid_string), UIO_SYSSPACE, FALSE);
4368 if (error) {
4369 goto bad;
4370 }
4371 imgp->ip_applec++;
4372 }
4373
4374 uint8_t cdhash[SHA1_RESULTLEN];
4375 int cdhash_errror = ubc_cs_getcdhash(imgp->ip_vp, imgp->ip_arch_offset, cdhash);
4376 if (cdhash_errror == 0) {
4377 char hash_string[strlen(CDHASH_KEY) + 2*SHA1_RESULTLEN + 1];
4378 strncpy(hash_string, CDHASH_KEY, sizeof(hash_string));
4379 char *p = hash_string + sizeof(CDHASH_KEY) - 1;
4380 for (int i = 0; i < SHA1_RESULTLEN; i++) {
4381 snprintf(p, 3, "%02x", (int) cdhash[i]);
4382 p += 2;
4383 }
4384 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(hash_string), UIO_SYSSPACE, FALSE);
4385 if (error) {
4386 goto bad;
4387 }
4388 imgp->ip_applec++;
4389 }
4390
4391 /* Align the tail of the combined applev area */
4392 while (imgp->ip_strspace % img_ptr_size != 0) {
4393 *imgp->ip_strendp++ = '\0';
4394 imgp->ip_strspace--;
4395 }
4396
4397 bad:
4398 return error;
4399 }
4400
4401 #define unix_stack_size(p) (p->p_rlimit[RLIMIT_STACK].rlim_cur)
4402
4403 /*
4404 * exec_check_permissions
4405 *
4406 * Description: Verify that the file that is being attempted to be executed
4407 * is in fact allowed to be executed based on it POSIX file
4408 * permissions and other access control criteria
4409 *
4410 * Parameters: struct image_params * the image parameter block
4411 *
4412 * Returns: 0 Success
4413 * EACCES Permission denied
4414 * ENOEXEC Executable file format error
4415 * ETXTBSY Text file busy [misuse of error code]
4416 * vnode_getattr:???
4417 * vnode_authorize:???
4418 */
4419 static int
4420 exec_check_permissions(struct image_params *imgp)
4421 {
4422 struct vnode *vp = imgp->ip_vp;
4423 struct vnode_attr *vap = imgp->ip_vattr;
4424 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
4425 int error;
4426 kauth_action_t action;
4427
4428 /* Only allow execution of regular files */
4429 if (!vnode_isreg(vp))
4430 return (EACCES);
4431
4432 /* Get the file attributes that we will be using here and elsewhere */
4433 VATTR_INIT(vap);
4434 VATTR_WANTED(vap, va_uid);
4435 VATTR_WANTED(vap, va_gid);
4436 VATTR_WANTED(vap, va_mode);
4437 VATTR_WANTED(vap, va_fsid);
4438 VATTR_WANTED(vap, va_fsid64);
4439 VATTR_WANTED(vap, va_fileid);
4440 VATTR_WANTED(vap, va_data_size);
4441 if ((error = vnode_getattr(vp, vap, imgp->ip_vfs_context)) != 0)
4442 return (error);
4443
4444 /*
4445 * Ensure that at least one execute bit is on - otherwise root
4446 * will always succeed, and we don't want to happen unless the
4447 * file really is executable.
4448 */
4449 if (!vfs_authopaque(vnode_mount(vp)) && ((vap->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0))
4450 return (EACCES);
4451
4452 /* Disallow zero length files */
4453 if (vap->va_data_size == 0)
4454 return (ENOEXEC);
4455
4456 imgp->ip_arch_offset = (user_size_t)0;
4457 imgp->ip_arch_size = vap->va_data_size;
4458
4459 /* Disable setuid-ness for traced programs or if MNT_NOSUID */
4460 if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_lflag & P_LTRACED))
4461 vap->va_mode &= ~(VSUID | VSGID);
4462
4463 /*
4464 * Disable _POSIX_SPAWN_ALLOW_DATA_EXEC and _POSIX_SPAWN_DISABLE_ASLR
4465 * flags for setuid/setgid binaries.
4466 */
4467 if (vap->va_mode & (VSUID | VSGID))
4468 imgp->ip_flags &= ~(IMGPF_ALLOW_DATA_EXEC | IMGPF_DISABLE_ASLR);
4469
4470 #if CONFIG_MACF
4471 error = mac_vnode_check_exec(imgp->ip_vfs_context, vp, imgp);
4472 if (error)
4473 return (error);
4474 #endif
4475
4476 /* Check for execute permission */
4477 action = KAUTH_VNODE_EXECUTE;
4478 /* Traced images must also be readable */
4479 if (p->p_lflag & P_LTRACED)
4480 action |= KAUTH_VNODE_READ_DATA;
4481 if ((error = vnode_authorize(vp, NULL, action, imgp->ip_vfs_context)) != 0)
4482 return (error);
4483
4484 #if 0
4485 /* Don't let it run if anyone had it open for writing */
4486 vnode_lock(vp);
4487 if (vp->v_writecount) {
4488 panic("going to return ETXTBSY %x", vp);
4489 vnode_unlock(vp);
4490 return (ETXTBSY);
4491 }
4492 vnode_unlock(vp);
4493 #endif
4494
4495
4496 /* XXX May want to indicate to underlying FS that vnode is open */
4497
4498 return (error);
4499 }
4500
4501
4502 /*
4503 * exec_handle_sugid
4504 *
4505 * Initially clear the P_SUGID in the process flags; if an SUGID process is
4506 * exec'ing a non-SUGID image, then this is the point of no return.
4507 *
4508 * If the image being activated is SUGID, then replace the credential with a
4509 * copy, disable tracing (unless the tracing process is root), reset the
4510 * mach task port to revoke it, set the P_SUGID bit,
4511 *
4512 * If the saved user and group ID will be changing, then make sure it happens
4513 * to a new credential, rather than a shared one.
4514 *
4515 * Set the security token (this is probably obsolete, given that the token
4516 * should not technically be separate from the credential itself).
4517 *
4518 * Parameters: struct image_params * the image parameter block
4519 *
4520 * Returns: void No failure indication
4521 *
4522 * Implicit returns:
4523 * <process credential> Potentially modified/replaced
4524 * <task port> Potentially revoked
4525 * <process flags> P_SUGID bit potentially modified
4526 * <security token> Potentially modified
4527 */
4528 static int
4529 exec_handle_sugid(struct image_params *imgp)
4530 {
4531 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
4532 kauth_cred_t cred = vfs_context_ucred(imgp->ip_vfs_context);
4533 kauth_cred_t my_cred, my_new_cred;
4534 int i;
4535 int leave_sugid_clear = 0;
4536 int mac_reset_ipc = 0;
4537 int error = 0;
4538 task_t task = NULL;
4539 #if CONFIG_MACF
4540 int mac_transition, disjoint_cred = 0;
4541 int label_update_return = 0;
4542
4543 /*
4544 * Determine whether a call to update the MAC label will result in the
4545 * credential changing.
4546 *
4547 * Note: MAC policies which do not actually end up modifying
4548 * the label subsequently are strongly encouraged to
4549 * return 0 for this check, since a non-zero answer will
4550 * slow down the exec fast path for normal binaries.
4551 */
4552 mac_transition = mac_cred_check_label_update_execve(
4553 imgp->ip_vfs_context,
4554 imgp->ip_vp,
4555 imgp->ip_arch_offset,
4556 imgp->ip_scriptvp,
4557 imgp->ip_scriptlabelp,
4558 imgp->ip_execlabelp,
4559 p,
4560 imgp->ip_px_smpx);
4561 #endif
4562
4563 OSBitAndAtomic(~((uint32_t)P_SUGID), &p->p_flag);
4564
4565 /*
4566 * Order of the following is important; group checks must go last,
4567 * as we use the success of the 'ismember' check combined with the
4568 * failure of the explicit match to indicate that we will be setting
4569 * the egid of the process even though the new process did not
4570 * require VSUID/VSGID bits in order for it to set the new group as
4571 * its egid.
4572 *
4573 * Note: Technically, by this we are implying a call to
4574 * setegid() in the new process, rather than implying
4575 * it used its VSGID bit to set the effective group,
4576 * even though there is no code in that process to make
4577 * such a call.
4578 */
4579 if (((imgp->ip_origvattr->va_mode & VSUID) != 0 &&
4580 kauth_cred_getuid(cred) != imgp->ip_origvattr->va_uid) ||
4581 ((imgp->ip_origvattr->va_mode & VSGID) != 0 &&
4582 ((kauth_cred_ismember_gid(cred, imgp->ip_origvattr->va_gid, &leave_sugid_clear) || !leave_sugid_clear) ||
4583 (kauth_cred_getgid(cred) != imgp->ip_origvattr->va_gid)))) {
4584
4585 #if CONFIG_MACF
4586 /* label for MAC transition and neither VSUID nor VSGID */
4587 handle_mac_transition:
4588 #endif
4589
4590 #if !SECURE_KERNEL
4591 /*
4592 * Replace the credential with a copy of itself if euid or
4593 * egid change.
4594 *
4595 * Note: setuid binaries will automatically opt out of
4596 * group resolver participation as a side effect
4597 * of this operation. This is an intentional
4598 * part of the security model, which requires a
4599 * participating credential be established by
4600 * escalating privilege, setting up all other
4601 * aspects of the credential including whether
4602 * or not to participate in external group
4603 * membership resolution, then dropping their
4604 * effective privilege to that of the desired
4605 * final credential state.
4606 *
4607 * Modifications to p_ucred must be guarded using the
4608 * proc's ucred lock. This prevents others from accessing
4609 * a garbage credential.
4610 */
4611 while (imgp->ip_origvattr->va_mode & VSUID) {
4612 my_cred = kauth_cred_proc_ref(p);
4613 my_new_cred = kauth_cred_setresuid(my_cred, KAUTH_UID_NONE, imgp->ip_origvattr->va_uid, imgp->ip_origvattr->va_uid, KAUTH_UID_NONE);
4614
4615 if (my_new_cred == my_cred) {
4616 kauth_cred_unref(&my_cred);
4617 break;
4618 }
4619
4620 /* update cred on proc */
4621 proc_ucred_lock(p);
4622
4623 if (p->p_ucred != my_cred) {
4624 proc_ucred_unlock(p);
4625 kauth_cred_unref(&my_new_cred);
4626 continue;
4627 }
4628
4629 /* donate cred reference on my_new_cred to p->p_ucred */
4630 p->p_ucred = my_new_cred;
4631 PROC_UPDATE_CREDS_ONPROC(p);
4632 proc_ucred_unlock(p);
4633
4634 /* drop additional reference that was taken on the previous cred */
4635 kauth_cred_unref(&my_cred);
4636
4637 break;
4638 }
4639
4640 while (imgp->ip_origvattr->va_mode & VSGID) {
4641 my_cred = kauth_cred_proc_ref(p);
4642 my_new_cred = kauth_cred_setresgid(my_cred, KAUTH_GID_NONE, imgp->ip_origvattr->va_gid, imgp->ip_origvattr->va_gid);
4643
4644 if (my_new_cred == my_cred) {
4645 kauth_cred_unref(&my_cred);
4646 break;
4647 }
4648
4649 /* update cred on proc */
4650 proc_ucred_lock(p);
4651
4652 if (p->p_ucred != my_cred) {
4653 proc_ucred_unlock(p);
4654 kauth_cred_unref(&my_new_cred);
4655 continue;
4656 }
4657
4658 /* donate cred reference on my_new_cred to p->p_ucred */
4659 p->p_ucred = my_new_cred;
4660 PROC_UPDATE_CREDS_ONPROC(p);
4661 proc_ucred_unlock(p);
4662
4663 /* drop additional reference that was taken on the previous cred */
4664 kauth_cred_unref(&my_cred);
4665
4666 break;
4667 }
4668 #endif /* !SECURE_KERNEL */
4669
4670 #if CONFIG_MACF
4671 /*
4672 * If a policy has indicated that it will transition the label,
4673 * before making the call into the MAC policies, get a new
4674 * duplicate credential, so they can modify it without
4675 * modifying any others sharing it.
4676 */
4677 if (mac_transition) {
4678 /*
4679 * This hook may generate upcalls that require
4680 * importance donation from the kernel.
4681 * (23925818)
4682 */
4683 thread_t thread = current_thread();
4684 thread_enable_send_importance(thread, TRUE);
4685 kauth_proc_label_update_execve(p,
4686 imgp->ip_vfs_context,
4687 imgp->ip_vp,
4688 imgp->ip_arch_offset,
4689 imgp->ip_scriptvp,
4690 imgp->ip_scriptlabelp,
4691 imgp->ip_execlabelp,
4692 &imgp->ip_csflags,
4693 imgp->ip_px_smpx,
4694 &disjoint_cred, /* will be non zero if disjoint */
4695 &label_update_return);
4696 thread_enable_send_importance(thread, FALSE);
4697
4698 if (disjoint_cred) {
4699 /*
4700 * If updating the MAC label resulted in a
4701 * disjoint credential, flag that we need to
4702 * set the P_SUGID bit. This protects
4703 * against debuggers being attached by an
4704 * insufficiently privileged process onto the
4705 * result of a transition to a more privileged
4706 * credential.
4707 */
4708 leave_sugid_clear = 0;
4709 }
4710
4711 imgp->ip_mac_return = label_update_return;
4712 }
4713
4714 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);
4715
4716 #endif /* CONFIG_MACF */
4717
4718 /*
4719 * If 'leave_sugid_clear' is non-zero, then we passed the
4720 * VSUID and MACF checks, and successfully determined that
4721 * the previous cred was a member of the VSGID group, but
4722 * that it was not the default at the time of the execve,
4723 * and that the post-labelling credential was not disjoint.
4724 * So we don't set the P_SUGID or reset mach ports and fds
4725 * on the basis of simply running this code.
4726 */
4727 if (mac_reset_ipc || !leave_sugid_clear) {
4728 /*
4729 * Have mach reset the task and thread ports.
4730 * We don't want anyone who had the ports before
4731 * a setuid exec to be able to access/control the
4732 * task/thread after.
4733 */
4734 ipc_task_reset((imgp->ip_new_thread != NULL) ?
4735 get_threadtask(imgp->ip_new_thread) : p->task);
4736 ipc_thread_reset((imgp->ip_new_thread != NULL) ?
4737 imgp->ip_new_thread : current_thread());
4738 }
4739
4740 if (!leave_sugid_clear) {
4741 /*
4742 * Flag the process as setuid.
4743 */
4744 OSBitOrAtomic(P_SUGID, &p->p_flag);
4745
4746 /*
4747 * Radar 2261856; setuid security hole fix
4748 * XXX For setuid processes, attempt to ensure that
4749 * stdin, stdout, and stderr are already allocated.
4750 * We do not want userland to accidentally allocate
4751 * descriptors in this range which has implied meaning
4752 * to libc.
4753 */
4754 for (i = 0; i < 3; i++) {
4755
4756 if (p->p_fd->fd_ofiles[i] != NULL)
4757 continue;
4758
4759 /*
4760 * Do the kernel equivalent of
4761 *
4762 * if i == 0
4763 * (void) open("/dev/null", O_RDONLY);
4764 * else
4765 * (void) open("/dev/null", O_WRONLY);
4766 */
4767
4768 struct fileproc *fp;
4769 int indx;
4770 int flag;
4771 struct nameidata *ndp = NULL;
4772
4773 if (i == 0)
4774 flag = FREAD;
4775 else
4776 flag = FWRITE;
4777
4778 if ((error = falloc(p,
4779 &fp, &indx, imgp->ip_vfs_context)) != 0)
4780 continue;
4781
4782 MALLOC(ndp, struct nameidata *, sizeof(*ndp), M_TEMP, M_WAITOK | M_ZERO);
4783 if (ndp == NULL) {
4784 fp_free(p, indx, fp);
4785 error = ENOMEM;
4786 break;
4787 }
4788
4789 NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW, UIO_SYSSPACE,
4790 CAST_USER_ADDR_T("/dev/null"),
4791 imgp->ip_vfs_context);
4792
4793 if ((error = vn_open(ndp, flag, 0)) != 0) {
4794 fp_free(p, indx, fp);
4795 FREE(ndp, M_TEMP);
4796 break;
4797 }
4798
4799 struct fileglob *fg = fp->f_fglob;
4800
4801 fg->fg_flag = flag;
4802 fg->fg_ops = &vnops;
4803 fg->fg_data = ndp->ni_vp;
4804
4805 vnode_put(ndp->ni_vp);
4806
4807 proc_fdlock(p);
4808 procfdtbl_releasefd(p, indx, NULL);
4809 fp_drop(p, indx, fp, 1);
4810 proc_fdunlock(p);
4811
4812 FREE(ndp, M_TEMP);
4813 }
4814 }
4815 }
4816 #if CONFIG_MACF
4817 else {
4818 /*
4819 * We are here because we were told that the MAC label will
4820 * be transitioned, and the binary is not VSUID or VSGID; to
4821 * deal with this case, we could either duplicate a lot of
4822 * code, or we can indicate we want to default the P_SUGID
4823 * bit clear and jump back up.
4824 */
4825 if (mac_transition) {
4826 leave_sugid_clear = 1;
4827 goto handle_mac_transition;
4828 }
4829 }
4830
4831 #endif /* CONFIG_MACF */
4832
4833 /*
4834 * Implement the semantic where the effective user and group become
4835 * the saved user and group in exec'ed programs.
4836 *
4837 * Modifications to p_ucred must be guarded using the
4838 * proc's ucred lock. This prevents others from accessing
4839 * a garbage credential.
4840 */
4841 for (;;) {
4842 my_cred = kauth_cred_proc_ref(p);
4843 my_new_cred = kauth_cred_setsvuidgid(my_cred, kauth_cred_getuid(my_cred), kauth_cred_getgid(my_cred));
4844
4845 if (my_new_cred == my_cred) {
4846 kauth_cred_unref(&my_cred);
4847 break;
4848 }
4849
4850 /* update cred on proc */
4851 proc_ucred_lock(p);
4852
4853 if (p->p_ucred != my_cred) {
4854 proc_ucred_unlock(p);
4855 kauth_cred_unref(&my_new_cred);
4856 continue;
4857 }
4858
4859 /* donate cred reference on my_new_cred to p->p_ucred */
4860 p->p_ucred = my_new_cred;
4861 PROC_UPDATE_CREDS_ONPROC(p);
4862 proc_ucred_unlock(p);
4863
4864 /* drop additional reference that was taken on the previous cred */
4865 kauth_cred_unref(&my_cred);
4866
4867 break;
4868 }
4869
4870
4871 /* Update the process' identity version and set the security token */
4872 p->p_idversion++;
4873
4874 if (imgp->ip_new_thread != NULL) {
4875 task = get_threadtask(imgp->ip_new_thread);
4876 } else {
4877 task = p->task;
4878 }
4879 set_security_token_task_internal(p, task);
4880
4881 return(error);
4882 }
4883
4884
4885 /*
4886 * create_unix_stack
4887 *
4888 * Description: Set the user stack address for the process to the provided
4889 * address. If a custom stack was not set as a result of the
4890 * load process (i.e. as specified by the image file for the
4891 * executable), then allocate the stack in the provided map and
4892 * set up appropriate guard pages for enforcing administrative
4893 * limits on stack growth, if they end up being needed.
4894 *
4895 * Parameters: p Process to set stack on
4896 * load_result Information from mach-o load commands
4897 * map Address map in which to allocate the new stack
4898 *
4899 * Returns: KERN_SUCCESS Stack successfully created
4900 * !KERN_SUCCESS Mach failure code
4901 */
4902 static kern_return_t
4903 create_unix_stack(vm_map_t map, load_result_t* load_result,
4904 proc_t p)
4905 {
4906 mach_vm_size_t size, prot_size;
4907 mach_vm_offset_t addr, prot_addr;
4908 kern_return_t kr;
4909
4910 mach_vm_address_t user_stack = load_result->user_stack;
4911
4912 proc_lock(p);
4913 p->user_stack = user_stack;
4914 proc_unlock(p);
4915
4916 if (load_result->user_stack_alloc_size > 0) {
4917 /*
4918 * Allocate enough space for the maximum stack size we
4919 * will ever authorize and an extra page to act as
4920 * a guard page for stack overflows. For default stacks,
4921 * vm_initial_limit_stack takes care of the extra guard page.
4922 * Otherwise we must allocate it ourselves.
4923 */
4924 if (mach_vm_round_page_overflow(load_result->user_stack_alloc_size, &size)) {
4925 return KERN_INVALID_ARGUMENT;
4926 }
4927 addr = mach_vm_trunc_page(load_result->user_stack - size);
4928 kr = mach_vm_allocate_kernel(map, &addr, size,
4929 VM_FLAGS_FIXED, VM_MEMORY_STACK);
4930 if (kr != KERN_SUCCESS) {
4931 // Can't allocate at default location, try anywhere
4932 addr = 0;
4933 kr = mach_vm_allocate_kernel(map, &addr, size,
4934 VM_FLAGS_ANYWHERE, VM_MEMORY_STACK);
4935 if (kr != KERN_SUCCESS) {
4936 return kr;
4937 }
4938
4939 user_stack = addr + size;
4940 load_result->user_stack = user_stack;
4941
4942 proc_lock(p);
4943 p->user_stack = user_stack;
4944 proc_unlock(p);
4945 }
4946
4947 load_result->user_stack_alloc = addr;
4948
4949 /*
4950 * And prevent access to what's above the current stack
4951 * size limit for this process.
4952 */
4953 if (load_result->user_stack_size == 0) {
4954 load_result->user_stack_size = unix_stack_size(p);
4955 prot_size = mach_vm_trunc_page(size - load_result->user_stack_size);
4956 } else {
4957 prot_size = PAGE_SIZE;
4958 }
4959
4960 prot_addr = addr;
4961 kr = mach_vm_protect(map,
4962 prot_addr,
4963 prot_size,
4964 FALSE,
4965 VM_PROT_NONE);
4966 if (kr != KERN_SUCCESS) {
4967 (void)mach_vm_deallocate(map, addr, size);
4968 return kr;
4969 }
4970 }
4971
4972 return KERN_SUCCESS;
4973 }
4974
4975 #include <sys/reboot.h>
4976
4977 /*
4978 * load_init_program_at_path
4979 *
4980 * Description: Load the "init" program; in most cases, this will be "launchd"
4981 *
4982 * Parameters: p Process to call execve() to create
4983 * the "init" program
4984 * scratch_addr Page in p, scratch space
4985 * path NULL terminated path
4986 *
4987 * Returns: KERN_SUCCESS Success
4988 * !KERN_SUCCESS See execve/mac_execve for error codes
4989 *
4990 * Notes: The process that is passed in is the first manufactured
4991 * process on the system, and gets here via bsd_ast() firing
4992 * for the first time. This is done to ensure that bsd_init()
4993 * has run to completion.
4994 *
4995 * The address map of the first manufactured process matches the
4996 * word width of the kernel. Once the self-exec completes, the
4997 * initproc might be different.
4998 */
4999 static int
5000 load_init_program_at_path(proc_t p, user_addr_t scratch_addr, const char* path)
5001 {
5002 int retval[2];
5003 int error;
5004 struct execve_args init_exec_args;
5005 user_addr_t argv0 = USER_ADDR_NULL, argv1 = USER_ADDR_NULL;
5006
5007 /*
5008 * Validate inputs and pre-conditions
5009 */
5010 assert(p);
5011 assert(scratch_addr);
5012 assert(path);
5013
5014 /*
5015 * Copy out program name.
5016 */
5017 size_t path_length = strlen(path) + 1;
5018 argv0 = scratch_addr;
5019 error = copyout(path, argv0, path_length);
5020 if (error)
5021 return error;
5022
5023 scratch_addr = USER_ADDR_ALIGN(scratch_addr + path_length, sizeof(user_addr_t));
5024
5025 /*
5026 * Put out first (and only) argument, similarly.
5027 * Assumes everything fits in a page as allocated above.
5028 */
5029 if (boothowto & RB_SINGLE) {
5030 const char *init_args = "-s";
5031 size_t init_args_length = strlen(init_args)+1;
5032
5033 argv1 = scratch_addr;
5034 error = copyout(init_args, argv1, init_args_length);
5035 if (error)
5036 return error;
5037
5038 scratch_addr = USER_ADDR_ALIGN(scratch_addr + init_args_length, sizeof(user_addr_t));
5039 }
5040
5041 if (proc_is64bit(p)) {
5042 user64_addr_t argv64bit[3];
5043
5044 argv64bit[0] = argv0;
5045 argv64bit[1] = argv1;
5046 argv64bit[2] = USER_ADDR_NULL;
5047
5048 error = copyout(argv64bit, scratch_addr, sizeof(argv64bit));
5049 if (error)
5050 return error;
5051 } else {
5052 user32_addr_t argv32bit[3];
5053
5054 argv32bit[0] = (user32_addr_t)argv0;
5055 argv32bit[1] = (user32_addr_t)argv1;
5056 argv32bit[2] = USER_ADDR_NULL;
5057
5058 error = copyout(argv32bit, scratch_addr, sizeof(argv32bit));
5059 if (error)
5060 return error;
5061 }
5062
5063 /*
5064 * Set up argument block for fake call to execve.
5065 */
5066 init_exec_args.fname = argv0;
5067 init_exec_args.argp = scratch_addr;
5068 init_exec_args.envp = USER_ADDR_NULL;
5069
5070 /*
5071 * So that init task is set with uid,gid 0 token
5072 */
5073 set_security_token(p);
5074
5075 return execve(p, &init_exec_args, retval);
5076 }
5077
5078 static const char * init_programs[] = {
5079 #if DEBUG
5080 "/usr/local/sbin/launchd.debug",
5081 #endif
5082 #if DEVELOPMENT || DEBUG
5083 "/usr/local/sbin/launchd.development",
5084 #endif
5085 "/sbin/launchd",
5086 };
5087
5088 /*
5089 * load_init_program
5090 *
5091 * Description: Load the "init" program; in most cases, this will be "launchd"
5092 *
5093 * Parameters: p Process to call execve() to create
5094 * the "init" program
5095 *
5096 * Returns: (void)
5097 *
5098 * Notes: The process that is passed in is the first manufactured
5099 * process on the system, and gets here via bsd_ast() firing
5100 * for the first time. This is done to ensure that bsd_init()
5101 * has run to completion.
5102 *
5103 * In DEBUG & DEVELOPMENT builds, the launchdsuffix boot-arg
5104 * may be used to select a specific launchd executable. As with
5105 * the kcsuffix boot-arg, setting launchdsuffix to "" or "release"
5106 * will force /sbin/launchd to be selected.
5107 *
5108 * Search order by build:
5109 *
5110 * DEBUG DEVELOPMENT RELEASE PATH
5111 * ----------------------------------------------------------------------------------
5112 * 1 1 NA /usr/local/sbin/launchd.$LAUNCHDSUFFIX
5113 * 2 NA NA /usr/local/sbin/launchd.debug
5114 * 3 2 NA /usr/local/sbin/launchd.development
5115 * 4 3 1 /sbin/launchd
5116 */
5117 void
5118 load_init_program(proc_t p)
5119 {
5120 uint32_t i;
5121 int error;
5122 vm_map_t map = current_map();
5123 mach_vm_offset_t scratch_addr = 0;
5124 mach_vm_size_t map_page_size = vm_map_page_size(map);
5125
5126 (void) mach_vm_allocate_kernel(map, &scratch_addr, map_page_size, VM_FLAGS_ANYWHERE, VM_KERN_MEMORY_NONE);
5127 #if CONFIG_MEMORYSTATUS
5128 (void) memorystatus_init_at_boot_snapshot();
5129 #endif /* CONFIG_MEMORYSTATUS */
5130
5131 #if DEBUG || DEVELOPMENT
5132 /* Check for boot-arg suffix first */
5133 char launchd_suffix[64];
5134 if (PE_parse_boot_argn("launchdsuffix", launchd_suffix, sizeof(launchd_suffix))) {
5135 char launchd_path[128];
5136 boolean_t is_release_suffix = ((launchd_suffix[0] == 0) ||
5137 (strcmp(launchd_suffix, "release") == 0));
5138
5139 if (is_release_suffix) {
5140 printf("load_init_program: attempting to load /sbin/launchd\n");
5141 error = load_init_program_at_path(p, (user_addr_t)scratch_addr, "/sbin/launchd");
5142 if (!error)
5143 return;
5144
5145 panic("Process 1 exec of launchd.release failed, errno %d", error);
5146 } else {
5147 strlcpy(launchd_path, "/usr/local/sbin/launchd.", sizeof(launchd_path));
5148 strlcat(launchd_path, launchd_suffix, sizeof(launchd_path));
5149
5150 printf("load_init_program: attempting to load %s\n", launchd_path);
5151 error = load_init_program_at_path(p, (user_addr_t)scratch_addr, launchd_path);
5152 if (!error) {
5153 return;
5154 } else {
5155 printf("load_init_program: failed loading %s: errno %d\n", launchd_path, error);
5156 }
5157 }
5158 }
5159 #endif
5160
5161 error = ENOENT;
5162 for (i = 0; i < sizeof(init_programs)/sizeof(init_programs[0]); i++) {
5163 printf("load_init_program: attempting to load %s\n", init_programs[i]);
5164 error = load_init_program_at_path(p, (user_addr_t)scratch_addr, init_programs[i]);
5165 if (!error) {
5166 return;
5167 } else {
5168 printf("load_init_program: failed loading %s: errno %d\n", init_programs[i], error);
5169 }
5170 }
5171
5172 panic("Process 1 exec of %s failed, errno %d", ((i == 0) ? "<null>" : init_programs[i-1]), error);
5173 }
5174
5175 /*
5176 * load_return_to_errno
5177 *
5178 * Description: Convert a load_return_t (Mach error) to an errno (BSD error)
5179 *
5180 * Parameters: lrtn Mach error number
5181 *
5182 * Returns: (int) BSD error number
5183 * 0 Success
5184 * EBADARCH Bad architecture
5185 * EBADMACHO Bad Mach object file
5186 * ESHLIBVERS Bad shared library version
5187 * ENOMEM Out of memory/resource shortage
5188 * EACCES Access denied
5189 * ENOENT Entry not found (usually "file does
5190 * does not exist")
5191 * EIO An I/O error occurred
5192 * EBADEXEC The executable is corrupt/unknown
5193 */
5194 static int
5195 load_return_to_errno(load_return_t lrtn)
5196 {
5197 switch (lrtn) {
5198 case LOAD_SUCCESS:
5199 return 0;
5200 case LOAD_BADARCH:
5201 return EBADARCH;
5202 case LOAD_BADMACHO:
5203 case LOAD_BADMACHO_UPX:
5204 return EBADMACHO;
5205 case LOAD_SHLIB:
5206 return ESHLIBVERS;
5207 case LOAD_NOSPACE:
5208 case LOAD_RESOURCE:
5209 return ENOMEM;
5210 case LOAD_PROTECT:
5211 return EACCES;
5212 case LOAD_ENOENT:
5213 return ENOENT;
5214 case LOAD_IOERROR:
5215 return EIO;
5216 case LOAD_FAILURE:
5217 case LOAD_DECRYPTFAIL:
5218 default:
5219 return EBADEXEC;
5220 }
5221 }
5222
5223 #include <mach/mach_types.h>
5224 #include <mach/vm_prot.h>
5225 #include <mach/semaphore.h>
5226 #include <mach/sync_policy.h>
5227 #include <kern/clock.h>
5228 #include <mach/kern_return.h>
5229
5230 /*
5231 * execargs_alloc
5232 *
5233 * Description: Allocate the block of memory used by the execve arguments.
5234 * At the same time, we allocate a page so that we can read in
5235 * the first page of the image.
5236 *
5237 * Parameters: struct image_params * the image parameter block
5238 *
5239 * Returns: 0 Success
5240 * EINVAL Invalid argument
5241 * EACCES Permission denied
5242 * EINTR Interrupted function
5243 * ENOMEM Not enough space
5244 *
5245 * Notes: This is a temporary allocation into the kernel address space
5246 * to enable us to copy arguments in from user space. This is
5247 * necessitated by not mapping the process calling execve() into
5248 * the kernel address space during the execve() system call.
5249 *
5250 * We assemble the argument and environment, etc., into this
5251 * region before copying it as a single block into the child
5252 * process address space (at the top or bottom of the stack,
5253 * depending on which way the stack grows; see the function
5254 * exec_copyout_strings() for details).
5255 *
5256 * This ends up with a second (possibly unnecessary) copy compared
5257 * with assembing the data directly into the child address space,
5258 * instead, but since we cannot be guaranteed that the parent has
5259 * not modified its environment, we can't really know that it's
5260 * really a block there as well.
5261 */
5262
5263
5264 static int execargs_waiters = 0;
5265 lck_mtx_t *execargs_cache_lock;
5266
5267 static void
5268 execargs_lock_lock(void) {
5269 lck_mtx_lock_spin(execargs_cache_lock);
5270 }
5271
5272 static void
5273 execargs_lock_unlock(void) {
5274 lck_mtx_unlock(execargs_cache_lock);
5275 }
5276
5277 static wait_result_t
5278 execargs_lock_sleep(void) {
5279 return(lck_mtx_sleep(execargs_cache_lock, LCK_SLEEP_DEFAULT, &execargs_free_count, THREAD_INTERRUPTIBLE));
5280 }
5281
5282 static kern_return_t
5283 execargs_purgeable_allocate(char **execarg_address) {
5284 kern_return_t kr = vm_allocate_kernel(bsd_pageable_map, (vm_offset_t *)execarg_address, BSD_PAGEABLE_SIZE_PER_EXEC, VM_FLAGS_ANYWHERE | VM_FLAGS_PURGABLE, VM_KERN_MEMORY_NONE);
5285 assert(kr == KERN_SUCCESS);
5286 return kr;
5287 }
5288
5289 static kern_return_t
5290 execargs_purgeable_reference(void *execarg_address) {
5291 int state = VM_PURGABLE_NONVOLATILE;
5292 kern_return_t kr = vm_purgable_control(bsd_pageable_map, (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state);
5293
5294 assert(kr == KERN_SUCCESS);
5295 return kr;
5296 }
5297
5298 static kern_return_t
5299 execargs_purgeable_volatilize(void *execarg_address) {
5300 int state = VM_PURGABLE_VOLATILE | VM_PURGABLE_ORDERING_OBSOLETE;
5301 kern_return_t kr;
5302 kr = vm_purgable_control(bsd_pageable_map, (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state);
5303
5304 assert(kr == KERN_SUCCESS);
5305
5306 return kr;
5307 }
5308
5309 static void
5310 execargs_wakeup_waiters(void) {
5311 thread_wakeup(&execargs_free_count);
5312 }
5313
5314 static int
5315 execargs_alloc(struct image_params *imgp)
5316 {
5317 kern_return_t kret;
5318 wait_result_t res;
5319 int i, cache_index = -1;
5320
5321 execargs_lock_lock();
5322
5323 while (execargs_free_count == 0) {
5324 execargs_waiters++;
5325 res = execargs_lock_sleep();
5326 execargs_waiters--;
5327 if (res != THREAD_AWAKENED) {
5328 execargs_lock_unlock();
5329 return (EINTR);
5330 }
5331 }
5332
5333 execargs_free_count--;
5334
5335 for (i = 0; i < execargs_cache_size; i++) {
5336 vm_offset_t element = execargs_cache[i];
5337 if (element) {
5338 cache_index = i;
5339 imgp->ip_strings = (char *)(execargs_cache[i]);
5340 execargs_cache[i] = 0;
5341 break;
5342 }
5343 }
5344
5345 assert(execargs_free_count >= 0);
5346
5347 execargs_lock_unlock();
5348
5349 if (cache_index == -1) {
5350 kret = execargs_purgeable_allocate(&imgp->ip_strings);
5351 }
5352 else
5353 kret = execargs_purgeable_reference(imgp->ip_strings);
5354
5355 assert(kret == KERN_SUCCESS);
5356 if (kret != KERN_SUCCESS) {
5357 return (ENOMEM);
5358 }
5359
5360 /* last page used to read in file headers */
5361 imgp->ip_vdata = imgp->ip_strings + ( NCARGS + PAGE_SIZE );
5362 imgp->ip_strendp = imgp->ip_strings;
5363 imgp->ip_argspace = NCARGS;
5364 imgp->ip_strspace = ( NCARGS + PAGE_SIZE );
5365
5366 return (0);
5367 }
5368
5369 /*
5370 * execargs_free
5371 *
5372 * Description: Free the block of memory used by the execve arguments and the
5373 * first page of the executable by a previous call to the function
5374 * execargs_alloc().
5375 *
5376 * Parameters: struct image_params * the image parameter block
5377 *
5378 * Returns: 0 Success
5379 * EINVAL Invalid argument
5380 * EINTR Oeration interrupted
5381 */
5382 static int
5383 execargs_free(struct image_params *imgp)
5384 {
5385 kern_return_t kret;
5386 int i;
5387 boolean_t needs_wakeup = FALSE;
5388
5389 kret = execargs_purgeable_volatilize(imgp->ip_strings);
5390
5391 execargs_lock_lock();
5392 execargs_free_count++;
5393
5394 for (i = 0; i < execargs_cache_size; i++) {
5395 vm_offset_t element = execargs_cache[i];
5396 if (element == 0) {
5397 execargs_cache[i] = (vm_offset_t) imgp->ip_strings;
5398 imgp->ip_strings = NULL;
5399 break;
5400 }
5401 }
5402
5403 assert(imgp->ip_strings == NULL);
5404
5405 if (execargs_waiters > 0)
5406 needs_wakeup = TRUE;
5407
5408 execargs_lock_unlock();
5409
5410 if (needs_wakeup == TRUE)
5411 execargs_wakeup_waiters();
5412
5413 return ((kret == KERN_SUCCESS ? 0 : EINVAL));
5414 }
5415
5416 static void
5417 exec_resettextvp(proc_t p, struct image_params *imgp)
5418 {
5419 vnode_t vp;
5420 off_t offset;
5421 vnode_t tvp = p->p_textvp;
5422 int ret;
5423
5424 vp = imgp->ip_vp;
5425 offset = imgp->ip_arch_offset;
5426
5427 if (vp == NULLVP)
5428 panic("exec_resettextvp: expected valid vp");
5429
5430 ret = vnode_ref(vp);
5431 proc_lock(p);
5432 if (ret == 0) {
5433 p->p_textvp = vp;
5434 p->p_textoff = offset;
5435 } else {
5436 p->p_textvp = NULLVP; /* this is paranoia */
5437 p->p_textoff = 0;
5438 }
5439 proc_unlock(p);
5440
5441 if ( tvp != NULLVP) {
5442 if (vnode_getwithref(tvp) == 0) {
5443 vnode_rele(tvp);
5444 vnode_put(tvp);
5445 }
5446 }
5447
5448 }
5449
5450 // Includes the 0-byte (therefore "SIZE" instead of "LEN").
5451 static const size_t CS_CDHASH_STRING_SIZE = CS_CDHASH_LEN * 2 + 1;
5452
5453 static void cdhash_to_string(char str[CS_CDHASH_STRING_SIZE], uint8_t const * const cdhash) {
5454 static char const nibble[] = "0123456789abcdef";
5455
5456 /* Apparently still the safest way to get a hex representation
5457 * of binary data.
5458 * xnu's printf routines have %*D/%20D in theory, but "not really", see:
5459 * <rdar://problem/33328859> confusion around %*D/%nD in printf
5460 */
5461 for (int i = 0; i < CS_CDHASH_LEN; ++i) {
5462 str[i*2] = nibble[(cdhash[i] & 0xf0) >> 4];
5463 str[i*2+1] = nibble[cdhash[i] & 0x0f];
5464 }
5465 str[CS_CDHASH_STRING_SIZE - 1] = 0;
5466 }
5467
5468 /*
5469 * If the process is not signed or if it contains entitlements, we
5470 * need to communicate through the task_access_port to taskgated.
5471 *
5472 * taskgated will provide a detached code signature if present, and
5473 * will enforce any restrictions on entitlements.
5474 */
5475
5476 static boolean_t
5477 taskgated_required(proc_t p, boolean_t *require_success)
5478 {
5479 size_t length;
5480 void *blob;
5481 int error;
5482
5483 if (cs_debug > 2)
5484 csvnode_print_debug(p->p_textvp);
5485
5486 #if !CONFIG_EMBEDDED
5487 const int can_skip_taskgated = csproc_get_platform_binary(p) && !csproc_get_platform_path(p);
5488 #else
5489 const int can_skip_taskgated = csproc_get_platform_binary(p);
5490 #endif
5491 if (can_skip_taskgated) {
5492 if (cs_debug) printf("taskgated not required for: %s\n", p->p_name);
5493 *require_success = FALSE;
5494 return FALSE;
5495 }
5496
5497 if ((p->p_csflags & CS_VALID) == 0) {
5498 *require_success = FALSE;
5499 return TRUE;
5500 }
5501
5502 error = cs_entitlements_blob_get(p, &blob, &length);
5503 if (error == 0 && blob != NULL) {
5504 #if !CONFIG_EMBEDDED
5505 /*
5506 * fatal on the desktop when entitlements are present,
5507 * unless we started in single-user mode
5508 */
5509 if ((boothowto & RB_SINGLE) == 0)
5510 *require_success = TRUE;
5511 /*
5512 * Allow initproc to run without causing taskgated to launch
5513 */
5514 if (p == initproc) {
5515 *require_success = FALSE;
5516 return FALSE;
5517 }
5518
5519 #endif
5520 if (cs_debug) printf("taskgated required for: %s\n", p->p_name);
5521
5522 return TRUE;
5523 }
5524
5525 *require_success = FALSE;
5526 return FALSE;
5527 }
5528
5529 /*
5530 * __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__
5531 *
5532 * Description: Waits for the userspace daemon to respond to the request
5533 * we made. Function declared non inline to be visible in
5534 * stackshots and spindumps as well as debugging.
5535 */
5536 __attribute__((noinline)) int
5537 __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port, int32_t new_pid)
5538 {
5539 return find_code_signature(task_access_port, new_pid);
5540 }
5541
5542 static int
5543 check_for_signature(proc_t p, struct image_params *imgp)
5544 {
5545 mach_port_t port = NULL;
5546 kern_return_t kr = KERN_FAILURE;
5547 int error = EACCES;
5548 boolean_t unexpected_failure = FALSE;
5549 unsigned char hash[CS_CDHASH_LEN];
5550 boolean_t require_success = FALSE;
5551 int spawn = (imgp->ip_flags & IMGPF_SPAWN);
5552 int vfexec = (imgp->ip_flags & IMGPF_VFORK_EXEC);
5553 os_reason_t signature_failure_reason = OS_REASON_NULL;
5554
5555 /*
5556 * Override inherited code signing flags with the
5557 * ones for the process that is being successfully
5558 * loaded
5559 */
5560 proc_lock(p);
5561 p->p_csflags = imgp->ip_csflags;
5562 proc_unlock(p);
5563
5564 /* Set the switch_protect flag on the map */
5565 if(p->p_csflags & (CS_HARD|CS_KILL)) {
5566 vm_map_switch_protect(get_task_map(p->task), TRUE);
5567 }
5568
5569 /*
5570 * image activation may be failed due to policy
5571 * which is unexpected but security framework does not
5572 * approve of exec, kill and return immediately.
5573 */
5574 if (imgp->ip_mac_return != 0) {
5575
5576 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
5577 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY, 0, 0);
5578 signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY);
5579 error = imgp->ip_mac_return;
5580 unexpected_failure = TRUE;
5581 goto done;
5582 }
5583
5584 if (imgp->ip_cs_error != OS_REASON_NULL) {
5585 signature_failure_reason = imgp->ip_cs_error;
5586 imgp->ip_cs_error = OS_REASON_NULL;
5587 error = EACCES;
5588 goto done;
5589 }
5590
5591 /* check if callout to taskgated is needed */
5592 if (!taskgated_required(p, &require_success)) {
5593 error = 0;
5594 goto done;
5595 }
5596
5597 kr = task_get_task_access_port(p->task, &port);
5598 if (KERN_SUCCESS != kr || !IPC_PORT_VALID(port)) {
5599 error = 0;
5600 if (require_success) {
5601 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
5602 p->p_pid, OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT, 0, 0);
5603 signature_failure_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT);
5604 error = EACCES;
5605 }
5606 goto done;
5607 }
5608
5609 /*
5610 * taskgated returns KERN_SUCCESS if it has completed its work
5611 * and the exec should continue, KERN_FAILURE if the exec should
5612 * fail, or it may error out with different error code in an
5613 * event of mig failure (e.g. process was signalled during the
5614 * rpc call, taskgated died, mig server died etc.).
5615 */
5616
5617 kr = __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(port, p->p_pid);
5618 switch (kr) {
5619 case KERN_SUCCESS:
5620 error = 0;
5621 break;
5622 case KERN_FAILURE:
5623 error = EACCES;
5624
5625 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
5626 p->p_pid, OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG, 0, 0);
5627 signature_failure_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG);
5628 goto done;
5629 default:
5630 error = EACCES;
5631
5632 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
5633 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_TASKGATED_OTHER, 0, 0);
5634 signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_TASKGATED_OTHER);
5635 unexpected_failure = TRUE;
5636 goto done;
5637 }
5638
5639 /* Only do this if exec_resettextvp() did not fail */
5640 if (p->p_textvp != NULLVP) {
5641 /*
5642 * If there's a new code directory, mark this process
5643 * as signed.
5644 */
5645 if (0 == ubc_cs_getcdhash(p->p_textvp, p->p_textoff, hash)) {
5646 proc_lock(p);
5647 p->p_csflags |= CS_VALID;
5648 proc_unlock(p);
5649 }
5650 }
5651
5652 done:
5653 if (0 == error) {
5654 /* The process's code signature related properties are
5655 * fully set up, so this is an opportune moment to log
5656 * platform binary execution, if desired. */
5657 if (platform_exec_logging != 0 && csproc_get_platform_binary(p)) {
5658 uint8_t cdhash[CS_CDHASH_LEN];
5659 char cdhash_string[CS_CDHASH_STRING_SIZE];
5660 proc_getcdhash(p, cdhash);
5661 cdhash_to_string(cdhash_string, cdhash);
5662
5663 os_log(peLog, "CS Platform Exec Logging: Executing platform signed binary "
5664 "'%s' with cdhash %s\n", p->p_name, cdhash_string);
5665 }
5666 } else {
5667 if (!unexpected_failure)
5668 p->p_csflags |= CS_KILLED;
5669 /* make very sure execution fails */
5670 if (vfexec || spawn) {
5671 assert(signature_failure_reason != OS_REASON_NULL);
5672 psignal_vfork_with_reason(p, p->task, imgp->ip_new_thread,
5673 SIGKILL, signature_failure_reason);
5674 signature_failure_reason = OS_REASON_NULL;
5675 error = 0;
5676 } else {
5677 assert(signature_failure_reason != OS_REASON_NULL);
5678 psignal_with_reason(p, SIGKILL, signature_failure_reason);
5679 signature_failure_reason = OS_REASON_NULL;
5680 }
5681 }
5682
5683 /* If we hit this, we likely would have leaked an exit reason */
5684 assert(signature_failure_reason == OS_REASON_NULL);
5685 return error;
5686 }
5687
5688 /*
5689 * Typically as soon as we start executing this process, the
5690 * first instruction will trigger a VM fault to bring the text
5691 * pages (as executable) into the address space, followed soon
5692 * thereafter by dyld data structures (for dynamic executable).
5693 * To optimize this, as well as improve support for hardware
5694 * debuggers that can only access resident pages present
5695 * in the process' page tables, we prefault some pages if
5696 * possible. Errors are non-fatal.
5697 */
5698 static void exec_prefault_data(proc_t p __unused, struct image_params *imgp, load_result_t *load_result)
5699 {
5700 int ret;
5701 size_t expected_all_image_infos_size;
5702
5703 /*
5704 * Prefault executable or dyld entry point.
5705 */
5706 vm_fault(current_map(),
5707 vm_map_trunc_page(load_result->entry_point,
5708 vm_map_page_mask(current_map())),
5709 VM_PROT_READ | VM_PROT_EXECUTE,
5710 FALSE, VM_KERN_MEMORY_NONE,
5711 THREAD_UNINT, NULL, 0);
5712
5713 if (imgp->ip_flags & IMGPF_IS_64BIT) {
5714 expected_all_image_infos_size = sizeof(struct user64_dyld_all_image_infos);
5715 } else {
5716 expected_all_image_infos_size = sizeof(struct user32_dyld_all_image_infos);
5717 }
5718
5719 /* Decode dyld anchor structure from <mach-o/dyld_images.h> */
5720 if (load_result->dynlinker &&
5721 load_result->all_image_info_addr &&
5722 load_result->all_image_info_size >= expected_all_image_infos_size) {
5723 union {
5724 struct user64_dyld_all_image_infos infos64;
5725 struct user32_dyld_all_image_infos infos32;
5726 } all_image_infos;
5727
5728 /*
5729 * Pre-fault to avoid copyin() going through the trap handler
5730 * and recovery path.
5731 */
5732 vm_fault(current_map(),
5733 vm_map_trunc_page(load_result->all_image_info_addr,
5734 vm_map_page_mask(current_map())),
5735 VM_PROT_READ | VM_PROT_WRITE,
5736 FALSE, VM_KERN_MEMORY_NONE,
5737 THREAD_UNINT, NULL, 0);
5738 if ((load_result->all_image_info_addr & PAGE_MASK) + expected_all_image_infos_size > PAGE_SIZE) {
5739 /* all_image_infos straddles a page */
5740 vm_fault(current_map(),
5741 vm_map_trunc_page(load_result->all_image_info_addr + expected_all_image_infos_size - 1,
5742 vm_map_page_mask(current_map())),
5743 VM_PROT_READ | VM_PROT_WRITE,
5744 FALSE, VM_KERN_MEMORY_NONE,
5745 THREAD_UNINT, NULL, 0);
5746 }
5747
5748 ret = copyin(load_result->all_image_info_addr,
5749 &all_image_infos,
5750 expected_all_image_infos_size);
5751 if (ret == 0 && all_image_infos.infos32.version >= DYLD_ALL_IMAGE_INFOS_ADDRESS_MINIMUM_VERSION) {
5752
5753 user_addr_t notification_address;
5754 user_addr_t dyld_image_address;
5755 user_addr_t dyld_version_address;
5756 user_addr_t dyld_all_image_infos_address;
5757 user_addr_t dyld_slide_amount;
5758
5759 if (imgp->ip_flags & IMGPF_IS_64BIT) {
5760 notification_address = all_image_infos.infos64.notification;
5761 dyld_image_address = all_image_infos.infos64.dyldImageLoadAddress;
5762 dyld_version_address = all_image_infos.infos64.dyldVersion;
5763 dyld_all_image_infos_address = all_image_infos.infos64.dyldAllImageInfosAddress;
5764 } else {
5765 notification_address = all_image_infos.infos32.notification;
5766 dyld_image_address = all_image_infos.infos32.dyldImageLoadAddress;
5767 dyld_version_address = all_image_infos.infos32.dyldVersion;
5768 dyld_all_image_infos_address = all_image_infos.infos32.dyldAllImageInfosAddress;
5769 }
5770
5771 /*
5772 * dyld statically sets up the all_image_infos in its Mach-O
5773 * binary at static link time, with pointers relative to its default
5774 * load address. Since ASLR might slide dyld before its first
5775 * instruction is executed, "dyld_slide_amount" tells us how far
5776 * dyld was loaded compared to its default expected load address.
5777 * All other pointers into dyld's image should be adjusted by this
5778 * amount. At some point later, dyld will fix up pointers to take
5779 * into account the slide, at which point the all_image_infos_address
5780 * field in the structure will match the runtime load address, and
5781 * "dyld_slide_amount" will be 0, if we were to consult it again.
5782 */
5783
5784 dyld_slide_amount = load_result->all_image_info_addr - dyld_all_image_infos_address;
5785
5786 #if 0
5787 kprintf("exec_prefault: 0x%016llx 0x%08x 0x%016llx 0x%016llx 0x%016llx 0x%016llx\n",
5788 (uint64_t)load_result->all_image_info_addr,
5789 all_image_infos.infos32.version,
5790 (uint64_t)notification_address,
5791 (uint64_t)dyld_image_address,
5792 (uint64_t)dyld_version_address,
5793 (uint64_t)dyld_all_image_infos_address);
5794 #endif
5795
5796 vm_fault(current_map(),
5797 vm_map_trunc_page(notification_address + dyld_slide_amount,
5798 vm_map_page_mask(current_map())),
5799 VM_PROT_READ | VM_PROT_EXECUTE,
5800 FALSE, VM_KERN_MEMORY_NONE,
5801 THREAD_UNINT, NULL, 0);
5802 vm_fault(current_map(),
5803 vm_map_trunc_page(dyld_image_address + dyld_slide_amount,
5804 vm_map_page_mask(current_map())),
5805 VM_PROT_READ | VM_PROT_EXECUTE,
5806 FALSE, VM_KERN_MEMORY_NONE,
5807 THREAD_UNINT, NULL, 0);
5808 vm_fault(current_map(),
5809 vm_map_trunc_page(dyld_version_address + dyld_slide_amount,
5810 vm_map_page_mask(current_map())),
5811 VM_PROT_READ,
5812 FALSE, VM_KERN_MEMORY_NONE,
5813 THREAD_UNINT, NULL, 0);
5814 vm_fault(current_map(),
5815 vm_map_trunc_page(dyld_all_image_infos_address + dyld_slide_amount,
5816 vm_map_page_mask(current_map())),
5817 VM_PROT_READ | VM_PROT_WRITE,
5818 FALSE, VM_KERN_MEMORY_NONE,
5819 THREAD_UNINT, NULL, 0);
5820 }
5821 }
5822 }