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