]> git.saurik.com Git - apple/xnu.git/blame - bsd/kern/kern_exec.c
xnu-1699.32.7.tar.gz
[apple/xnu.git] / bsd / kern / kern_exec.c
CommitLineData
1c79356b 1/*
6d2010ae 2 * Copyright (c) 2000-2011 Apple Inc. All rights reserved.
5d5c5d0d 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
1c79356b 5 *
2d21ac55
A
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.
8f6c56a5 14 *
2d21ac55
A
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
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
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.
8f6c56a5 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b
A
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#include <cputypes.h>
37
38/*-
39 * Copyright (c) 1982, 1986, 1991, 1993
40 * The Regents of the University of California. All rights reserved.
41 * (c) UNIX System Laboratories, Inc.
42 * All or some portions of this file are derived from material licensed
43 * to the University of California by American Telephone and Telegraph
44 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
45 * the permission of UNIX System Laboratories, Inc.
46 *
47 * Redistribution and use in source and binary forms, with or without
48 * modification, are permitted provided that the following conditions
49 * are met:
50 * 1. Redistributions of source code must retain the above copyright
51 * notice, this list of conditions and the following disclaimer.
52 * 2. Redistributions in binary form must reproduce the above copyright
53 * notice, this list of conditions and the following disclaimer in the
54 * documentation and/or other materials provided with the distribution.
55 * 3. All advertising materials mentioning features or use of this software
56 * must display the following acknowledgement:
57 * This product includes software developed by the University of
58 * California, Berkeley and its contributors.
59 * 4. Neither the name of the University nor the names of its contributors
60 * may be used to endorse or promote products derived from this software
61 * without specific prior written permission.
62 *
63 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
64 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
67 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
68 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
69 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
70 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
71 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
72 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73 * SUCH DAMAGE.
74 *
75 * from: @(#)kern_exec.c 8.1 (Berkeley) 6/10/93
76 */
2d21ac55
A
77/*
78 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
79 * support for mandatory and extensible security protections. This notice
80 * is included in support of clause 2.2 (b) of the Apple Public License,
81 * Version 2.0.
82 */
1c79356b
A
83#include <machine/reg.h>
84
85#include <sys/param.h>
86#include <sys/systm.h>
87#include <sys/filedesc.h>
88#include <sys/kernel.h>
91447636
A
89#include <sys/proc_internal.h>
90#include <sys/kauth.h>
1c79356b 91#include <sys/user.h>
1c79356b
A
92#include <sys/socketvar.h>
93#include <sys/malloc.h>
94#include <sys/namei.h>
91447636
A
95#include <sys/mount_internal.h>
96#include <sys/vnode_internal.h>
97#include <sys/file_internal.h>
1c79356b 98#include <sys/stat.h>
91447636 99#include <sys/uio_internal.h>
1c79356b
A
100#include <sys/acct.h>
101#include <sys/exec.h>
102#include <sys/kdebug.h>
103#include <sys/signal.h>
55e303ae 104#include <sys/aio_kern.h>
91447636 105#include <sys/sysproto.h>
2d21ac55 106#if SYSV_SHM
91447636 107#include <sys/shm_internal.h> /* shmexec() */
2d21ac55 108#endif
91447636 109#include <sys/ubc_internal.h> /* ubc_map() */
2d21ac55
A
110#include <sys/spawn.h>
111#include <sys/spawn_internal.h>
112#include <sys/codesign.h>
b0d623f7 113#include <crypto/sha1.h>
1c79356b 114
b0d623f7 115#include <security/audit/audit.h>
e5568f75 116
2d21ac55
A
117#include <ipc/ipc_types.h>
118
91447636 119#include <mach/mach_types.h>
b0d623f7 120#include <mach/port.h>
91447636 121#include <mach/task.h>
b0d623f7 122#include <mach/task_access.h>
91447636
A
123#include <mach/thread_act.h>
124#include <mach/vm_map.h>
125#include <mach/mach_vm.h>
1c79356b
A
126#include <mach/vm_param.h>
127
b0d623f7
A
128#include <kern/sched_prim.h> /* thread_wakeup() */
129#include <kern/affinity.h>
130#include <kern/assert.h>
131
2d21ac55
A
132#if CONFIG_MACF
133#include <security/mac.h>
134#include <security/mac_mach_internal.h>
135#endif
136
1c79356b
A
137#include <vm/vm_map.h>
138#include <vm/vm_kern.h>
2d21ac55 139#include <vm/vm_protos.h>
91447636 140#include <vm/vm_kern.h>
2d21ac55 141
6d2010ae 142#include <machine/pal_routines.h>
b0d623f7 143
2d21ac55
A
144#if CONFIG_DTRACE
145/* Do not include dtrace.h, it redefines kmem_[alloc/free] */
146extern void (*dtrace_fasttrap_exec_ptr)(proc_t);
147extern void (*dtrace_helpers_cleanup)(proc_t);
148extern void dtrace_lazy_dofs_destroy(proc_t);
149
150#include <sys/dtrace_ptss.h>
151#endif
152
153/* support for child creation in exec after vfork */
154thread_t fork_create_child(task_t parent_task, proc_t child_proc, int inherit_memory, int is64bit);
155void vfork_exit(proc_t p, int rv);
b0d623f7 156int setsigvec(proc_t, thread_t, int, struct __kern_sigaction *, boolean_t in_sigstart);
6d2010ae 157extern void proc_apply_task_networkbg_internal(proc_t);
1c79356b 158
91447636
A
159/*
160 * Mach things for which prototypes are unavailable from Mach headers
161 */
162void ipc_task_reset(
163 task_t task);
6601e61a
A
164void ipc_thread_reset(
165 thread_t thread);
2d21ac55
A
166kern_return_t ipc_object_copyin(
167 ipc_space_t space,
168 mach_port_name_t name,
169 mach_msg_type_name_t msgt_name,
170 ipc_object_t *objectp);
171void ipc_port_release_send(ipc_port_t);
91447636
A
172
173extern struct savearea *get_user_regs(thread_t);
174
175
1c79356b
A
176#include <kern/thread.h>
177#include <kern/task.h>
1c79356b
A
178#include <kern/ast.h>
179#include <kern/mach_loader.h>
b0d623f7 180#include <kern/mach_fat.h>
1c79356b
A
181#include <mach-o/fat.h>
182#include <mach-o/loader.h>
183#include <machine/vmparam.h>
91447636
A
184#include <sys/imgact.h>
185
2d21ac55
A
186#include <sys/sdt.h>
187
91447636 188
2d21ac55
A
189/*
190 * EAI_ITERLIMIT The maximum number of times to iterate an image
191 * activator in exec_activate_image() before treating
192 * it as malformed/corrupt.
193 */
194#define EAI_ITERLIMIT 10
1c79356b 195
6d2010ae
A
196/*
197 * For #! interpreter parsing
198 */
199#define IS_WHITESPACE(ch) ((ch == ' ') || (ch == '\t'))
200#define IS_EOL(ch) ((ch == '#') || (ch == '\n'))
201
1c79356b 202extern vm_map_t bsd_pageable_map;
91447636 203extern struct fileops vnops;
1c79356b
A
204
205#define ROUND_PTR(type, addr) \
b0d623f7 206 (type *)( ( (uintptr_t)(addr) + 16 - 1) \
1c79356b
A
207 & ~(16 - 1) )
208
91447636 209struct image_params; /* Forward */
2d21ac55 210static int exec_activate_image(struct image_params *imgp);
91447636 211static int exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp);
1c79356b 212static int load_return_to_errno(load_return_t lrtn);
91447636
A
213static int execargs_alloc(struct image_params *imgp);
214static int execargs_free(struct image_params *imgp);
215static int exec_check_permissions(struct image_params *imgp);
216static int exec_extract_strings(struct image_params *imgp);
6d2010ae 217static int exec_add_apple_strings(struct image_params *imgp);
91447636 218static int exec_handle_sugid(struct image_params *imgp);
a3d08fcd 219static int sugid_scripts = 0;
6d2010ae 220SYSCTL_INT (_kern, OID_AUTO, sugid_scripts, CTLFLAG_RW | CTLFLAG_LOCKED, &sugid_scripts, 0, "");
91447636 221static kern_return_t create_unix_stack(vm_map_t map, user_addr_t user_stack,
2d21ac55 222 int customstack, proc_t p);
91447636 223static int copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size);
2d21ac55 224static void exec_resettextvp(proc_t, struct image_params *);
b0d623f7 225static int check_for_signature(proc_t, struct image_params *);
91447636 226
2d21ac55
A
227/* We don't want this one exported */
228__private_extern__
b0d623f7 229int open1(vfs_context_t, struct nameidata *, int, struct vnode_attr *, int32_t *);
1c79356b 230
55e303ae 231/*
6d2010ae 232 * exec_add_user_string
91447636
A
233 *
234 * Add the requested string to the string space area.
235 *
236 * Parameters; struct image_params * image parameter block
237 * user_addr_t string to add to strings area
6d2010ae
A
238 * int segment from which string comes
239 * boolean_t TRUE if string contributes to NCARGS
91447636
A
240 *
241 * Returns: 0 Success
242 * !0 Failure errno from copyinstr()
243 *
244 * Implicit returns:
245 * (imgp->ip_strendp) updated location of next add, if any
246 * (imgp->ip_strspace) updated byte count of space remaining
6d2010ae 247 * (imgp->ip_argspace) updated byte count of space in NCARGS
55e303ae 248 */
91447636 249static int
6d2010ae 250exec_add_user_string(struct image_params *imgp, user_addr_t str, int seg, boolean_t is_ncargs)
91447636 251{
6d2010ae
A
252 int error = 0;
253
254 do {
255 size_t len = 0;
256 int space;
257
258 if (is_ncargs)
259 space = imgp->ip_argspace; /* by definition smaller than ip_strspace */
260 else
261 space = imgp->ip_strspace;
262
263 if (space <= 0) {
55e303ae
A
264 error = E2BIG;
265 break;
266 }
6d2010ae
A
267
268 if (!UIO_SEG_IS_USER_SPACE(seg)) {
91447636 269 char *kstr = CAST_DOWN(char *,str); /* SAFE */
6d2010ae 270 error = copystr(kstr, imgp->ip_strendp, space, &len);
55e303ae 271 } else {
6d2010ae 272 error = copyinstr(str, imgp->ip_strendp, space, &len);
55e303ae 273 }
6d2010ae 274
91447636
A
275 imgp->ip_strendp += len;
276 imgp->ip_strspace -= len;
6d2010ae
A
277 if (is_ncargs)
278 imgp->ip_argspace -= len;
279
55e303ae 280 } while (error == ENAMETOOLONG);
6d2010ae 281
55e303ae
A
282 return error;
283}
284
91447636
A
285/*
286 * exec_save_path
287 *
288 * To support new app package launching for Mac OS X, the dyld needs the
289 * first argument to execve() stored on the user stack.
290 *
6d2010ae 291 * Save the executable path name at the bottom of the strings area and set
91447636
A
292 * the argument vector pointer to the location following that to indicate
293 * the start of the argument and environment tuples, setting the remaining
6d2010ae 294 * string space count to the size of the string area minus the path length.
91447636
A
295 *
296 * Parameters; struct image_params * image parameter block
297 * char * path used to invoke program
2d21ac55 298 * int segment from which path comes
91447636
A
299 *
300 * Returns: int 0 Success
2d21ac55
A
301 * EFAULT Bad address
302 * copy[in]str:EFAULT Bad address
303 * copy[in]str:ENAMETOOLONG Filename too long
304 *
91447636
A
305 * Implicit returns:
306 * (imgp->ip_strings) saved path
307 * (imgp->ip_strspace) space remaining in ip_strings
91447636 308 * (imgp->ip_strendp) start of remaining copy area
6d2010ae
A
309 * (imgp->ip_argspace) space remaining of NCARGS
310 * (imgp->ip_applec) Initial applev[0]
91447636
A
311 *
312 * Note: We have to do this before the initial namei() since in the
313 * path contains symbolic links, namei() will overwrite the
314 * original path buffer contents. If the last symbolic link
315 * resolved was a relative pathname, we would lose the original
316 * "path", which could be an absolute pathname. This might be
317 * unacceptable for dyld.
318 */
319static int
2d21ac55 320exec_save_path(struct image_params *imgp, user_addr_t path, int seg)
1c79356b 321{
91447636
A
322 int error;
323 size_t len;
6d2010ae 324 char *kpath;
91447636
A
325
326 len = MIN(MAXPATHLEN, imgp->ip_strspace);
327
2d21ac55 328 switch(seg) {
91447636
A
329 case UIO_USERSPACE32:
330 case UIO_USERSPACE64: /* Same for copyin()... */
331 error = copyinstr(path, imgp->ip_strings, len, &len);
332 break;
b0d623f7 333 case UIO_SYSSPACE:
6d2010ae 334 kpath = CAST_DOWN(char *,path); /* SAFE */
91447636
A
335 error = copystr(kpath, imgp->ip_strings, len, &len);
336 break;
337 default:
338 error = EFAULT;
339 break;
340 }
341
342 if (!error) {
343 imgp->ip_strendp += len;
344 imgp->ip_strspace -= len;
91447636
A
345 }
346
347 return(error);
348}
349
6d2010ae
A
350/*
351 * exec_reset_save_path
352 *
353 * If we detect a shell script, we need to reset the string area
354 * state so that the interpreter can be saved onto the stack.
355
356 * Parameters; struct image_params * image parameter block
357 *
358 * Returns: int 0 Success
359 *
360 * Implicit returns:
361 * (imgp->ip_strings) saved path
362 * (imgp->ip_strspace) space remaining in ip_strings
363 * (imgp->ip_strendp) start of remaining copy area
364 * (imgp->ip_argspace) space remaining of NCARGS
365 *
366 */
367static int
368exec_reset_save_path(struct image_params *imgp)
369{
370 imgp->ip_strendp = imgp->ip_strings;
371 imgp->ip_argspace = NCARGS;
372 imgp->ip_strspace = ( NCARGS + PAGE_SIZE );
373
374 return (0);
375}
376
0c530ab8
A
377#ifdef IMGPF_POWERPC
378/*
379 * exec_powerpc32_imgact
380 *
381 * Implicitly invoke the PowerPC handler for a byte-swapped image magic
382 * number. This may happen either as a result of an attempt to invoke a
383 * PowerPC image directly, or indirectly as the interpreter used in an
384 * interpreter script.
385 *
386 * Parameters; struct image_params * image parameter block
387 *
388 * Returns: -1 not an PowerPC image (keep looking)
389 * -3 Success: exec_archhandler_ppc: relookup
390 * >0 Failure: exec_archhandler_ppc: error number
391 *
392 * Note: This image activator does not handle the case of a direct
393 * invocation of the exec_archhandler_ppc, since in that case, the
394 * exec_archhandler_ppc itself is not a PowerPC binary; instead,
395 * binary image activators must recognize the exec_archhandler_ppc;
396 * This is managed in exec_check_permissions().
397 *
398 * Note: This image activator is limited to 32 bit powerpc images;
399 * if support for 64 bit powerpc images is desired, it would
400 * be more in line with this design to write a separate 64 bit
401 * image activator.
402 */
403static int
404exec_powerpc32_imgact(struct image_params *imgp)
405{
406 struct mach_header *mach_header = (struct mach_header *)imgp->ip_vdata;
407 int error;
408 size_t len = 0;
409
410 /*
411 * Make sure it's a PowerPC binary. If we've already redirected
412 * from an interpreted file once, don't do it again.
413 */
2d21ac55
A
414 if (mach_header->magic != MH_CIGAM) {
415 /*
416 * If it's a cross-architecture 64 bit binary, then claim
417 * it, but refuse to run it.
418 */
419 if (mach_header->magic == MH_CIGAM_64)
420 return (EBADARCH);
0c530ab8 421 return (-1);
2d21ac55 422 }
0c530ab8
A
423
424 /* If there is no exec_archhandler_ppc, we can't run it */
425 if (exec_archhandler_ppc.path[0] == 0)
426 return (EBADARCH);
427
2d21ac55
A
428 /* Remember the type of the original file for later grading */
429 if (!imgp->ip_origcputype) {
430 imgp->ip_origcputype =
431 OSSwapBigToHostInt32(mach_header->cputype);
432 imgp->ip_origcpusubtype =
433 OSSwapBigToHostInt32(mach_header->cpusubtype);
434 }
435
0c530ab8
A
436 /*
437 * The PowerPC flag will be set by the exec_check_permissions()
438 * call anyway; however, we set this flag here so that the relookup
439 * in execve() does not follow symbolic links, as a side effect.
440 */
441 imgp->ip_flags |= IMGPF_POWERPC;
442
443 /* impute an interpreter */
6d2010ae 444 error = copystr(exec_archhandler_ppc.path, imgp->ip_interp_buffer,
0c530ab8
A
445 IMG_SHSIZE, &len);
446 if (error)
447 return (error);
448
6d2010ae
A
449 exec_reset_save_path(imgp);
450 exec_save_path(imgp, CAST_USER_ADDR_T(imgp->ip_interp_buffer),
451 UIO_SYSSPACE);
452
0c530ab8
A
453 /*
454 * provide a replacement string for p->p_comm; we have to use an
b0d623f7 455 * alternate buffer for this, rather than replacing it directly,
0c530ab8
A
456 * since the exec may fail and return to the parent. In that case,
457 * we would have erroneously changed the parent p->p_comm instead.
458 */
b0d623f7
A
459 strlcpy(imgp->ip_p_comm, imgp->ip_ndp->ni_cnd.cn_nameptr, MAXCOMLEN+1);
460 /* +1 to allow MAXCOMLEN characters to be copied */
0c530ab8
A
461
462 return (-3);
463}
464#endif /* IMGPF_POWERPC */
91447636
A
465
466
467/*
468 * exec_shell_imgact
469 *
470 * Image activator for interpreter scripts. If the image begins with the
471 * characters "#!", then it is an interpreter script. Verify that we are
0c530ab8 472 * not already executing in PowerPC mode, and that the length of the script
91447636
A
473 * line indicating the interpreter is not in excess of the maximum allowed
474 * size. If this is the case, then break out the arguments, if any, which
475 * are separated by white space, and copy them into the argument save area
476 * as if they were provided on the command line before all other arguments.
477 * The line ends when we encounter a comment character ('#') or newline.
478 *
479 * Parameters; struct image_params * image parameter block
480 *
481 * Returns: -1 not an interpreter (keep looking)
482 * -3 Success: interpreter: relookup
483 * >0 Failure: interpreter: error number
484 *
485 * A return value other than -1 indicates subsequent image activators should
486 * not be given the opportunity to attempt to activate the image.
487 */
488static int
489exec_shell_imgact(struct image_params *imgp)
490{
491 char *vdata = imgp->ip_vdata;
492 char *ihp;
6d2010ae 493 char *line_startp, *line_endp;
91447636 494 char *interp;
2d21ac55
A
495 proc_t p;
496 struct fileproc *fp;
497 int fd;
498 int error;
91447636
A
499
500 /*
501 * Make sure it's a shell script. If we've already redirected
502 * from an interpreted file once, don't do it again.
503 *
0c530ab8
A
504 * Note: We disallow PowerPC, since the expectation is that we
505 * may run a PowerPC interpreter, but not an interpret a PowerPC
91447636 506 * image. This is consistent with historical behaviour.
55e303ae 507 */
91447636
A
508 if (vdata[0] != '#' ||
509 vdata[1] != '!' ||
510 (imgp->ip_flags & IMGPF_INTERPRET) != 0) {
511 return (-1);
512 }
513
0c530ab8
A
514#ifdef IMGPF_POWERPC
515 if ((imgp->ip_flags & IMGPF_POWERPC) != 0)
516 return (EBADARCH);
517#endif /* IMGPF_POWERPC */
91447636
A
518
519 imgp->ip_flags |= IMGPF_INTERPRET;
6d2010ae
A
520 imgp->ip_interp_sugid_fd = -1;
521 imgp->ip_interp_buffer[0] = '\0';
91447636 522
6d2010ae 523 /* Check to see if SUGID scripts are permitted. If they aren't then
91447636
A
524 * clear the SUGID bits.
525 * imgp->ip_vattr is known to be valid.
6d2010ae
A
526 */
527 if (sugid_scripts == 0) {
528 imgp->ip_origvattr->va_mode &= ~(VSUID | VSGID);
91447636
A
529 }
530
6d2010ae
A
531 /* Try to find the first non-whitespace character */
532 for( ihp = &vdata[2]; ihp < &vdata[IMG_SHSIZE]; ihp++ ) {
533 if (IS_EOL(*ihp)) {
534 /* Did not find interpreter, "#!\n" */
91447636 535 return (ENOEXEC);
6d2010ae
A
536 } else if (IS_WHITESPACE(*ihp)) {
537 /* Whitespace, like "#! /bin/sh\n", keep going. */
538 } else {
539 /* Found start of interpreter */
540 break;
541 }
91447636
A
542 }
543
6d2010ae
A
544 if (ihp == &vdata[IMG_SHSIZE]) {
545 /* All whitespace, like "#! " */
546 return (ENOEXEC);
547 }
91447636 548
6d2010ae
A
549 line_startp = ihp;
550
551 /* Try to find the end of the interpreter+args string */
552 for ( ; ihp < &vdata[IMG_SHSIZE]; ihp++ ) {
553 if (IS_EOL(*ihp)) {
554 /* Got it */
555 break;
556 } else {
557 /* Still part of interpreter or args */
558 }
559 }
91447636 560
6d2010ae
A
561 if (ihp == &vdata[IMG_SHSIZE]) {
562 /* A long line, like "#! blah blah blah" without end */
91447636 563 return (ENOEXEC);
6d2010ae
A
564 }
565
566 /* Backtrack until we find the last non-whitespace */
567 while (IS_EOL(*ihp) || IS_WHITESPACE(*ihp)) {
568 ihp--;
569 }
570
571 /* The character after the last non-whitespace is our logical end of line */
572 line_endp = ihp + 1;
573
574 /*
575 * Now we have pointers to the usable part of:
576 *
577 * "#! /usr/bin/int first second third \n"
578 * ^ line_startp ^ line_endp
579 */
91447636
A
580
581 /* copy the interpreter name */
6d2010ae
A
582 interp = imgp->ip_interp_buffer;
583 for ( ihp = line_startp; (ihp < line_endp) && !IS_WHITESPACE(*ihp); ihp++)
584 *interp++ = *ihp;
91447636
A
585 *interp = '\0';
586
6d2010ae
A
587 exec_reset_save_path(imgp);
588 exec_save_path(imgp, CAST_USER_ADDR_T(imgp->ip_interp_buffer),
b0d623f7 589 UIO_SYSSPACE);
91447636 590
6d2010ae
A
591 /* Copy the entire interpreter + args for later processing into argv[] */
592 interp = imgp->ip_interp_buffer;
593 for ( ihp = line_startp; (ihp < line_endp); ihp++)
594 *interp++ = *ihp;
595 *interp = '\0';
91447636 596
2d21ac55
A
597 /*
598 * If we have a SUID oder SGID script, create a file descriptor
599 * from the vnode and pass /dev/fd/%d instead of the actual
600 * path name so that the script does not get opened twice
601 */
602 if (imgp->ip_origvattr->va_mode & (VSUID | VSGID)) {
603 p = vfs_context_proc(imgp->ip_vfs_context);
604 error = falloc(p, &fp, &fd, imgp->ip_vfs_context);
605 if (error)
606 return(error);
607
608 fp->f_fglob->fg_flag = FREAD;
609 fp->f_fglob->fg_type = DTYPE_VNODE;
610 fp->f_fglob->fg_ops = &vnops;
611 fp->f_fglob->fg_data = (caddr_t)imgp->ip_vp;
612
613 proc_fdlock(p);
614 procfdtbl_releasefd(p, fd, NULL);
615 fp_drop(p, fd, fp, 1);
616 proc_fdunlock(p);
617 vnode_ref(imgp->ip_vp);
618
6d2010ae 619 imgp->ip_interp_sugid_fd = fd;
2d21ac55
A
620 }
621
91447636
A
622 return (-3);
623}
624
625
626
627/*
628 * exec_fat_imgact
629 *
630 * Image activator for fat 1.0 binaries. If the binary is fat, then we
631 * need to select an image from it internally, and make that the image
632 * we are going to attempt to execute. At present, this consists of
633 * reloading the first page for the image with a first page from the
634 * offset location indicated by the fat header.
635 *
2d21ac55
A
636 * Parameters; struct image_params * image parameter block
637 *
638 * Returns: -1 not a fat binary (keep looking)
639 * -2 Success: encapsulated binary: reread
640 * >0 Failure: error number
641 *
91447636
A
642 * Important: This image activator is byte order neutral.
643 *
2d21ac55
A
644 * Note: A return value other than -1 indicates subsequent image
645 * activators should not be given the opportunity to attempt
646 * to activate the image.
647 *
648 * If we find an encapsulated binary, we make no assertions
91447636
A
649 * about its validity; instead, we leave that up to a rescan
650 * for an activator to claim it, and, if it is claimed by one,
651 * that activator is responsible for determining validity.
652 */
653static int
654exec_fat_imgact(struct image_params *imgp)
655{
2d21ac55 656 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
0c530ab8 657 kauth_cred_t cred = kauth_cred_proc_ref(p);
91447636 658 struct fat_header *fat_header = (struct fat_header *)imgp->ip_vdata;
2d21ac55 659 struct _posix_spawnattr *psa = NULL;
91447636
A
660 struct fat_arch fat_arch;
661 int resid, error;
662 load_return_t lret;
663
664 /* Make sure it's a fat binary */
665 if ((fat_header->magic != FAT_MAGIC) &&
666 (fat_header->magic != FAT_CIGAM)) {
667 error = -1;
668 goto bad;
669 }
670
2d21ac55
A
671 /* If posix_spawn binprefs exist, respect those prefs. */
672 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
673 if (psa != NULL && psa->psa_binprefs[0] != 0) {
674 struct fat_arch *arches = (struct fat_arch *) (fat_header + 1);
675 int nfat_arch = 0, pr = 0, f = 0;
676
677 nfat_arch = OSSwapBigToHostInt32(fat_header->nfat_arch);
678 /* Check each preference listed against all arches in header */
679 for (pr = 0; pr < NBINPREFS; pr++) {
680 cpu_type_t pref = psa->psa_binprefs[pr];
681 if (pref == 0) {
682 /* No suitable arch in the pref list */
683 error = EBADARCH;
684 goto bad;
685 }
686
687 if (pref == CPU_TYPE_ANY) {
688 /* Fall through to regular grading */
689 break;
690 }
691
692 for (f = 0; f < nfat_arch; f++) {
693 cpu_type_t archtype = OSSwapBigToHostInt32(
694 arches[f].cputype);
695 cpu_type_t archsubtype = OSSwapBigToHostInt32(
696 arches[f].cpusubtype) & ~CPU_SUBTYPE_MASK;
697 if (pref == archtype &&
698 grade_binary(archtype, archsubtype)) {
699 /* We have a winner! */
700 fat_arch.cputype = archtype;
701 fat_arch.cpusubtype = archsubtype;
702 fat_arch.offset = OSSwapBigToHostInt32(
703 arches[f].offset);
704 fat_arch.size = OSSwapBigToHostInt32(
705 arches[f].size);
706 fat_arch.align = OSSwapBigToHostInt32(
707 arches[f].align);
708 goto use_arch;
709 }
710 }
711 }
712 }
713
91447636
A
714 /* Look up our preferred architecture in the fat file. */
715 lret = fatfile_getarch_affinity(imgp->ip_vp,
716 (vm_offset_t)fat_header,
717 &fat_arch,
718 (p->p_flag & P_AFFINITY));
719 if (lret != LOAD_SUCCESS) {
720 error = load_return_to_errno(lret);
721 goto bad;
722 }
723
2d21ac55
A
724use_arch:
725 /* Read the Mach-O header out of fat_arch */
91447636
A
726 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata,
727 PAGE_SIZE, fat_arch.offset,
b0d623f7 728 UIO_SYSSPACE, (IO_UNIT|IO_NODELOCKED),
91447636
A
729 cred, &resid, p);
730 if (error) {
731 goto bad;
732 }
733
734 /* Did we read a complete header? */
735 if (resid) {
736 error = EBADEXEC;
737 goto bad;
738 }
739
740 /* Success. Indicate we have identified an encapsulated binary */
741 error = -2;
742 imgp->ip_arch_offset = (user_size_t)fat_arch.offset;
743 imgp->ip_arch_size = (user_size_t)fat_arch.size;
744
745bad:
0c530ab8 746 kauth_cred_unref(&cred);
91447636
A
747 return (error);
748}
749
750/*
751 * exec_mach_imgact
752 *
753 * Image activator for mach-o 1.0 binaries.
754 *
2d21ac55
A
755 * Parameters; struct image_params * image parameter block
756 *
757 * Returns: -1 not a fat binary (keep looking)
758 * -2 Success: encapsulated binary: reread
759 * >0 Failure: error number
760 * EBADARCH Mach-o binary, but with an unrecognized
761 * architecture
762 * ENOMEM No memory for child process after -
763 * can only happen after vfork()
764 *
91447636 765 * Important: This image activator is NOT byte order neutral.
2d21ac55
A
766 *
767 * Note: A return value other than -1 indicates subsequent image
768 * activators should not be given the opportunity to attempt
769 * to activate the image.
770 *
771 * TODO: More gracefully handle failures after vfork
91447636
A
772 */
773static int
774exec_mach_imgact(struct image_params *imgp)
775{
776 struct mach_header *mach_header = (struct mach_header *)imgp->ip_vdata;
2d21ac55 777 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
91447636
A
778 int error = 0;
779 int vfexec = 0;
780 task_t task;
2d21ac55 781 task_t new_task = NULL; /* protected by vfexec */
91447636 782 thread_t thread;
1c79356b 783 struct uthread *uthread;
91447636 784 vm_map_t old_map = VM_MAP_NULL;
0b4e3aa0 785 vm_map_t map;
91447636
A
786 load_return_t lret;
787 load_result_t load_result;
2d21ac55 788 struct _posix_spawnattr *psa = NULL;
b0d623f7 789 int spawn = (imgp->ip_flags & IMGPF_SPAWN);
6d2010ae 790 int apptype = 0;
2d21ac55 791
91447636
A
792 /*
793 * make sure it's a Mach-O 1.0 or Mach-O 2.0 binary; the difference
794 * is a reserved field on the end, so for the most part, we can
795 * treat them as if they were identical.
796 */
797 if ((mach_header->magic != MH_MAGIC) &&
798 (mach_header->magic != MH_MAGIC_64)) {
2d21ac55
A
799 error = -1;
800 goto bad;
801 }
802
803 switch (mach_header->filetype) {
804 case MH_DYLIB:
805 case MH_BUNDLE:
806 error = -1;
91447636
A
807 goto bad;
808 }
809
2d21ac55
A
810 if (!imgp->ip_origcputype) {
811 imgp->ip_origcputype = mach_header->cputype;
812 imgp->ip_origcpusubtype = mach_header->cpusubtype;
813 }
814
91447636
A
815 task = current_task();
816 thread = current_thread();
817 uthread = get_bsdthread_info(thread);
818
b0d623f7
A
819 /*
820 * Save off the vfexec state up front; we have to do this, because
6d2010ae 821 * we need to know if we were in this state initially subsequent to
b0d623f7
A
822 * creating the backing task, thread, and uthread for the child
823 * process (from the vfs_context_t from in img_parms).
824 */
91447636
A
825 if (uthread->uu_flag & UT_VFORK)
826 vfexec = 1; /* Mark in exec */
827
828 if ((mach_header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64)
829 imgp->ip_flags |= IMGPF_IS_64BIT;
830
2d21ac55
A
831 /* If posix_spawn binprefs exist, respect those prefs. */
832 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
833 if (psa != NULL && psa->psa_binprefs[0] != 0) {
834 int pr = 0;
835 for (pr = 0; pr < NBINPREFS; pr++) {
836 cpu_type_t pref = psa->psa_binprefs[pr];
837 if (pref == 0) {
838 /* No suitable arch in the pref list */
839 error = EBADARCH;
840 goto bad;
841 }
842
843 if (pref == CPU_TYPE_ANY) {
844 /* Jump to regular grading */
845 goto grade;
846 }
847
848 if (pref == imgp->ip_origcputype) {
849 /* We have a match! */
850 goto grade;
851 }
852 }
91447636
A
853 error = EBADARCH;
854 goto bad;
855 }
2d21ac55
A
856grade:
857 if (!grade_binary(imgp->ip_origcputype & ~CPU_SUBTYPE_LIB64,
858 imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK)) {
859 error = EBADARCH;
860 goto bad;
91447636
A
861 }
862
2d21ac55
A
863 /* Copy in arguments/environment from the old process */
864 error = exec_extract_strings(imgp);
865 if (error)
866 goto bad;
867
6d2010ae
A
868 error = exec_add_apple_strings(imgp);
869 if (error)
870 goto bad;
b0d623f7 871
6d2010ae
A
872 AUDIT_ARG(argv, imgp->ip_startargv, imgp->ip_argc,
873 imgp->ip_endargv - imgp->ip_startargv);
874 AUDIT_ARG(envv, imgp->ip_endargv, imgp->ip_envc,
875 imgp->ip_endenvv - imgp->ip_endargv);
91447636 876
0c530ab8
A
877#ifdef IMGPF_POWERPC
878 /*
879 * XXX
880 *
881 * Should be factored out; this is here because we might be getting
882 * invoked this way as the result of a shell script, and the check
883 * in exec_check_permissions() is not interior to the jump back up
2d21ac55 884 * to the "encapsulated_binary:" label in exec_activate_image().
0c530ab8
A
885 */
886 if (imgp->ip_vattr->va_fsid == exec_archhandler_ppc.fsid &&
6d2010ae 887 imgp->ip_vattr->va_fileid == exec_archhandler_ppc.fileid) {
0c530ab8
A
888 imgp->ip_flags |= IMGPF_POWERPC;
889 }
890#endif /* IMGPF_POWERPC */
91447636 891
b0d623f7
A
892 /*
893 * We are being called to activate an image subsequent to a vfork()
894 * operation; in this case, we know that our task, thread, and
6d2010ae 895 * uthread are actually those of our parent, and our proc, which we
b0d623f7
A
896 * obtained indirectly from the image_params vfs_context_t, is the
897 * new child process.
898 */
899 if (vfexec || spawn) {
900 if (vfexec) {
901 imgp->ip_new_thread = fork_create_child(task, p, FALSE, (imgp->ip_flags & IMGPF_IS_64BIT));
902 if (imgp->ip_new_thread == NULL) {
903 error = ENOMEM;
904 goto bad;
905 }
2d21ac55 906 }
b0d623f7 907
2d21ac55 908 /* reset local idea of thread, uthread, task */
b0d623f7 909 thread = imgp->ip_new_thread;
91447636 910 uthread = get_bsdthread_info(thread);
2d21ac55
A
911 task = new_task = get_threadtask(thread);
912 map = get_task_map(task);
91447636
A
913 } else {
914 map = VM_MAP_NULL;
915 }
916
917 /*
918 * We set these flags here; this is OK, since if we fail after
919 * this point, we have already destroyed the parent process anyway.
920 */
b0d623f7 921 task_set_dyld_info(task, MACH_VM_MIN_ADDRESS, 0);
91447636
A
922 if (imgp->ip_flags & IMGPF_IS_64BIT) {
923 task_set_64bit(task, TRUE);
b0d623f7 924 OSBitOrAtomic(P_LP64, &p->p_flag);
91447636
A
925 } else {
926 task_set_64bit(task, FALSE);
b0d623f7 927 OSBitAndAtomic(~((uint32_t)P_LP64), &p->p_flag);
91447636
A
928 }
929
930 /*
931 * Load the Mach-O file.
b0d623f7 932 *
91447636 933 * NOTE: An error after this point indicates we have potentially
6d2010ae 934 * destroyed or overwritten some process state while attempting an
91447636
A
935 * execve() following a vfork(), which is an unrecoverable condition.
936 */
937
91447636
A
938 /*
939 * Actually load the image file we previously decided to load.
940 */
2d21ac55 941 lret = load_machfile(imgp, mach_header, thread, map, &load_result);
91447636
A
942
943 if (lret != LOAD_SUCCESS) {
944 error = load_return_to_errno(lret);
945 goto badtoolate;
946 }
947
2d21ac55
A
948 vm_map_set_user_wire_limit(get_task_map(task), p->p_rlimit[RLIMIT_MEMLOCK].rlim_cur);
949
950 /*
951 * Set code-signing flags if this binary is signed, or if parent has
952 * requested them on exec.
953 */
954 if (load_result.csflags & CS_VALID) {
955 imgp->ip_csflags |= load_result.csflags &
956 (CS_VALID|
957 CS_HARD|CS_KILL|CS_EXEC_SET_HARD|CS_EXEC_SET_KILL);
958 } else {
959 imgp->ip_csflags &= ~CS_VALID;
960 }
961
962 if (p->p_csflags & CS_EXEC_SET_HARD)
963 imgp->ip_csflags |= CS_HARD;
964 if (p->p_csflags & CS_EXEC_SET_KILL)
965 imgp->ip_csflags |= CS_KILL;
966
967
2d21ac55
A
968 /*
969 * Set up the system reserved areas in the new address space.
970 */
971 vm_map_exec(get_task_map(task),
972 task,
973 (void *) p->p_fd->fd_rdir,
974#ifdef IMGPF_POWERPC
975 imgp->ip_flags & IMGPF_POWERPC ?
976 CPU_TYPE_POWERPC :
977#endif
978 cpu_type());
979
0c530ab8 980 /*
6d2010ae 981 * Close file descriptors which specify close-on-exec.
6601e61a 982 */
6d2010ae 983 fdexec(p, psa != NULL ? psa->psa_flags : 0);
91447636
A
984
985 /*
986 * deal with set[ug]id.
987 */
988 error = exec_handle_sugid(imgp);
989
b0d623f7
A
990 /* Make sure we won't interrupt ourself signalling a partial process */
991 if (!vfexec && !spawn && (p->p_lflag & P_LTRACED))
91447636
A
992 psignal(p, SIGTRAP);
993
994 if (error) {
995 goto badtoolate;
996 }
91447636
A
997
998 if (load_result.unixproc &&
999 create_unix_stack(get_task_map(task),
2d21ac55
A
1000 load_result.user_stack,
1001 load_result.customstack,
1002 p) != KERN_SUCCESS) {
91447636
A
1003 error = load_return_to_errno(LOAD_NOSPACE);
1004 goto badtoolate;
1005 }
1006
b0d623f7 1007 if (vfexec || spawn) {
91447636
A
1008 old_map = vm_map_switch(get_task_map(task));
1009 }
1010
1011 if (load_result.unixproc) {
1012 user_addr_t ap;
1013
1014 /*
1015 * Copy the strings area out into the new process address
1016 * space.
1017 */
1018 ap = p->user_stack;
1019 error = exec_copyout_strings(imgp, &ap);
1020 if (error) {
b0d623f7 1021 if (vfexec || spawn)
91447636
A
1022 vm_map_switch(old_map);
1023 goto badtoolate;
1024 }
1025 /* Set the stack */
1026 thread_setuserstack(thread, ap);
1027 }
1028
1029 if (load_result.dynlinker) {
1030 uint64_t ap;
6d2010ae 1031 int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
91447636
A
1032
1033 /* Adjust the stack */
6d2010ae
A
1034 ap = thread_adjuserstack(thread, -new_ptr_size);
1035 error = copyoutptr(load_result.mach_header, ap, new_ptr_size);
1036
0c530ab8 1037 if (error) {
b0d623f7 1038 if (vfexec || spawn)
2d21ac55 1039 vm_map_switch(old_map);
0c530ab8 1040 goto badtoolate;
91447636 1041 }
b0d623f7
A
1042 task_set_dyld_info(task, load_result.all_image_info_addr,
1043 load_result.all_image_info_size);
91447636
A
1044 }
1045
b0d623f7 1046 if (vfexec || spawn) {
91447636
A
1047 vm_map_switch(old_map);
1048 }
1049 /* Set the entry point */
1050 thread_setentrypoint(thread, load_result.entry_point);
1051
1052 /* Stop profiling */
1053 stopprofclock(p);
1054
1055 /*
1056 * Reset signal state.
1057 */
1058 execsigs(p, thread);
1059
91447636
A
1060 /*
1061 * need to cancel async IO requests that can be cancelled and wait for those
1062 * already active. MAY BLOCK!
1063 */
1064 _aio_exec( p );
1065
2d21ac55 1066#if SYSV_SHM
91447636
A
1067 /* FIXME: Till vmspace inherit is fixed: */
1068 if (!vfexec && p->vm_shm)
1069 shmexec(p);
2d21ac55
A
1070#endif
1071#if SYSV_SEM
91447636
A
1072 /* Clean up the semaphores */
1073 semexit(p);
2d21ac55 1074#endif
91447636
A
1075
1076 /*
1077 * Remember file name for accounting.
1078 */
1079 p->p_acflag &= ~AFORK;
1080 /* If the translated name isn't NULL, then we want to use
1081 * that translated name as the name we show as the "real" name.
1082 * Otherwise, use the name passed into exec.
1083 */
1084 if (0 != imgp->ip_p_comm[0]) {
1085 bcopy((caddr_t)imgp->ip_p_comm, (caddr_t)p->p_comm,
1086 sizeof(p->p_comm));
1087 } else {
1088 if (imgp->ip_ndp->ni_cnd.cn_namelen > MAXCOMLEN)
1089 imgp->ip_ndp->ni_cnd.cn_namelen = MAXCOMLEN;
1090 bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_comm,
1091 (unsigned)imgp->ip_ndp->ni_cnd.cn_namelen);
1092 p->p_comm[imgp->ip_ndp->ni_cnd.cn_namelen] = '\0';
1093 }
55e303ae 1094
6d2010ae
A
1095 pal_dbg_set_task_name( p->task );
1096
b0d623f7
A
1097 memcpy(&p->p_uuid[0], &load_result.uuid[0], sizeof(p->p_uuid));
1098
1099// <rdar://6598155> dtrace code cleanup needed
2d21ac55
A
1100#if CONFIG_DTRACE
1101 /*
1102 * Invalidate any predicate evaluation already cached for this thread by DTrace.
1103 * That's because we've just stored to p_comm and DTrace refers to that when it
1104 * evaluates the "execname" special variable. uid and gid may have changed as well.
1105 */
1106 dtrace_set_thread_predcache(current_thread(), 0);
1107
1108 /*
1109 * Free any outstanding lazy dof entries. It is imperative we
1110 * always call dtrace_lazy_dofs_destroy, rather than null check
1111 * and call if !NULL. If we NULL test, during lazy dof faulting
1112 * we can race with the faulting code and proceed from here to
1113 * beyond the helpers cleanup. The lazy dof faulting will then
1114 * install new helpers which no longer belong to this process!
1115 */
1116 dtrace_lazy_dofs_destroy(p);
1117
1118
1119 /*
1120 * Clean up any DTrace helpers for the process.
1121 */
1122 if (p->p_dtrace_helpers != NULL && dtrace_helpers_cleanup) {
1123 (*dtrace_helpers_cleanup)(p);
1124 }
1125
1126 /*
1127 * Cleanup the DTrace provider associated with this process.
1128 */
1129 proc_lock(p);
1130 if (p->p_dtrace_probes && dtrace_fasttrap_exec_ptr) {
1131 (*dtrace_fasttrap_exec_ptr)(p);
1132 }
1133 proc_unlock(p);
1134#endif
1135
0c530ab8 1136 if (kdebug_enable) {
2d21ac55
A
1137 long dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4;
1138
1139 /*
1140 * Collect the pathname for tracing
1141 */
1142 kdbg_trace_string(p, &dbg_arg1, &dbg_arg2, &dbg_arg3, &dbg_arg4);
1143
b0d623f7 1144 if (vfexec || spawn) {
2d21ac55 1145 KERNEL_DEBUG_CONSTANT1((TRACEDBG_CODE(DBG_TRACE_DATA, 2)) | DBG_FUNC_NONE,
b0d623f7 1146 p->p_pid ,0,0,0, (uintptr_t)thread_tid(thread));
2d21ac55 1147 KERNEL_DEBUG_CONSTANT1((TRACEDBG_CODE(DBG_TRACE_STRING, 2)) | DBG_FUNC_NONE,
b0d623f7 1148 dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4, (uintptr_t)thread_tid(thread));
2d21ac55
A
1149 } else {
1150 KERNEL_DEBUG_CONSTANT((TRACEDBG_CODE(DBG_TRACE_DATA, 2)) | DBG_FUNC_NONE,
1151 p->p_pid ,0,0,0,0);
1152 KERNEL_DEBUG_CONSTANT((TRACEDBG_CODE(DBG_TRACE_STRING, 2)) | DBG_FUNC_NONE,
1153 dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4, 0);
1154 }
91447636
A
1155 }
1156
0c530ab8
A
1157#ifdef IMGPF_POWERPC
1158 /*
1159 * Mark the process as powerpc or not. If powerpc, set the affinity
1160 * flag, which will be used for grading binaries in future exec's
1161 * from the process.
1162 */
1163 if (((imgp->ip_flags & IMGPF_POWERPC) != 0))
b0d623f7 1164 OSBitOrAtomic(P_TRANSLATED, &p->p_flag);
0c530ab8
A
1165 else
1166#endif /* IMGPF_POWERPC */
b0d623f7
A
1167 OSBitAndAtomic(~((uint32_t)P_TRANSLATED), &p->p_flag);
1168 OSBitAndAtomic(~((uint32_t)P_AFFINITY), &p->p_flag);
2d21ac55
A
1169
1170 /*
1171 * If posix_spawned with the START_SUSPENDED flag, stop the
1172 * process before it runs.
1173 */
1174 if (imgp->ip_px_sa != NULL) {
1175 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
1176 if (psa->psa_flags & POSIX_SPAWN_START_SUSPENDED) {
1177 proc_lock(p);
1178 p->p_stat = SSTOP;
1179 proc_unlock(p);
1180 (void) task_suspend(p->task);
1181 }
6d2010ae
A
1182 if ((psa->psa_flags & POSIX_SPAWN_OSX_TALAPP_START) || (psa->psa_flags & POSIX_SPAWN_OSX_DBCLIENT_START) || (psa->psa_flags & POSIX_SPAWN_IOS_APP_START)) {
1183 if ((psa->psa_flags & POSIX_SPAWN_OSX_TALAPP_START))
1184 apptype = PROC_POLICY_OSX_APPTYPE_TAL;
1185 else if (psa->psa_flags & POSIX_SPAWN_OSX_DBCLIENT_START)
1186 apptype = PROC_POLICY_OSX_APPTYPE_DBCLIENT;
1187 else if (psa->psa_flags & POSIX_SPAWN_IOS_APP_START)
1188 apptype = PROC_POLICY_IOS_APPTYPE;
1189 else
1190 apptype = 0;
1191 proc_set_task_apptype(p->task, apptype);
1192 if ((apptype == PROC_POLICY_OSX_APPTYPE_TAL) ||
1193 (apptype == PROC_POLICY_OSX_APPTYPE_DBCLIENT)) {
1194
1195 proc_apply_task_networkbg_internal(p);
1196 }
1197 }
2d21ac55 1198 }
91447636
A
1199
1200 /*
1201 * mark as execed, wakeup the process that vforked (if any) and tell
b0d623f7 1202 * it that it now has its own resources back
91447636 1203 */
b0d623f7
A
1204 OSBitOrAtomic(P_EXEC, &p->p_flag);
1205 proc_resetregister(p);
2d21ac55
A
1206 if (p->p_pptr && (p->p_lflag & P_LPPWAIT)) {
1207 proc_lock(p);
1208 p->p_lflag &= ~P_LPPWAIT;
1209 proc_unlock(p);
91447636
A
1210 wakeup((caddr_t)p->p_pptr);
1211 }
1212
b0d623f7
A
1213 /*
1214 * Pay for our earlier safety; deliver the delayed signals from
1215 * the incomplete vfexec process now that it's complete.
1216 */
2d21ac55 1217 if (vfexec && (p->p_lflag & P_LTRACED)) {
91447636
A
1218 psignal_vfork(p, new_task, thread, SIGTRAP);
1219 }
1220
1221badtoolate:
b0d623f7 1222if (!spawn)
593a1d5f
A
1223 proc_knote(p, NOTE_EXEC);
1224
b0d623f7 1225 if (vfexec || spawn) {
91447636
A
1226 task_deallocate(new_task);
1227 thread_deallocate(thread);
1228 if (error)
1229 error = 0;
1230 }
1231
1232bad:
1233 return(error);
1234}
1235
1236
1237
1238
1239/*
1240 * Our image activator table; this is the table of the image types we are
1241 * capable of loading. We list them in order of preference to ensure the
1242 * fastest image load speed.
1243 *
1244 * XXX hardcoded, for now; should use linker sets
1245 */
1246struct execsw {
1247 int (*ex_imgact)(struct image_params *);
1248 const char *ex_name;
1249} execsw[] = {
1250 { exec_mach_imgact, "Mach-o Binary" },
1251 { exec_fat_imgact, "Fat Binary" },
0c530ab8
A
1252#ifdef IMGPF_POWERPC
1253 { exec_powerpc32_imgact, "PowerPC binary" },
1254#endif /* IMGPF_POWERPC */
91447636
A
1255 { exec_shell_imgact, "Interpreter Script" },
1256 { NULL, NULL}
1257};
1258
1259
1260/*
2d21ac55
A
1261 * exec_activate_image
1262 *
1263 * Description: Iterate through the available image activators, and activate
1264 * the image associated with the imgp structure. We start with
1265 * the
1266 *
1267 * Parameters: struct image_params * Image parameter block
1268 *
1269 * Returns: 0 Success
1270 * EBADEXEC The executable is corrupt/unknown
1271 * execargs_alloc:EINVAL Invalid argument
1272 * execargs_alloc:EACCES Permission denied
1273 * execargs_alloc:EINTR Interrupted function
1274 * execargs_alloc:ENOMEM Not enough space
1275 * exec_save_path:EFAULT Bad address
1276 * exec_save_path:ENAMETOOLONG Filename too long
1277 * exec_check_permissions:EACCES Permission denied
1278 * exec_check_permissions:ENOEXEC Executable file format error
1279 * exec_check_permissions:ETXTBSY Text file busy [misuse of error code]
1280 * exec_check_permissions:???
1281 * namei:???
1282 * vn_rdwr:??? [anything vn_rdwr can return]
1283 * <ex_imgact>:??? [anything an imgact can return]
91447636 1284 */
2d21ac55
A
1285static int
1286exec_activate_image(struct image_params *imgp)
91447636 1287{
91447636 1288 struct nameidata nd;
2d21ac55
A
1289 int error;
1290 int resid;
91447636 1291 int once = 1; /* save SGUID-ness for interpreted files */
2d21ac55
A
1292 int i;
1293 int iterlimit = EAI_ITERLIMIT;
593a1d5f 1294 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
1c79356b 1295
91447636 1296 error = execargs_alloc(imgp);
2d21ac55
A
1297 if (error)
1298 goto bad;
1299
2d21ac55 1300 error = exec_save_path(imgp, imgp->ip_user_fname, imgp->ip_seg);
55e303ae 1301 if (error) {
593a1d5f 1302 goto bad_notrans;
55e303ae 1303 }
91447636 1304
6d2010ae 1305 /* Use imgp->ip_strings, which contains the copyin-ed exec path */
2d21ac55
A
1306 DTRACE_PROC1(exec, uintptr_t, imgp->ip_strings);
1307
6d2010ae
A
1308 NDINIT(&nd, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF | AUDITVNPATH1,
1309 UIO_SYSSPACE, CAST_USER_ADDR_T(imgp->ip_strings), imgp->ip_vfs_context);
55e303ae 1310
91447636 1311again:
55e303ae
A
1312 error = namei(&nd);
1313 if (error)
593a1d5f 1314 goto bad_notrans;
91447636
A
1315 imgp->ip_ndp = &nd; /* successful namei(); call nameidone() later */
1316 imgp->ip_vp = nd.ni_vp; /* if set, need to vnode_put() at some point */
1c79356b 1317
6d2010ae
A
1318 /*
1319 * Before we start the transition from binary A to binary B, make
1320 * sure another thread hasn't started exiting the process. We grab
1321 * the proc lock to check p_lflag initially, and the transition
1322 * mechanism ensures that the value doesn't change after we release
1323 * the lock.
1324 */
1325 proc_lock(p);
1326 if (p->p_lflag & P_LEXIT) {
1327 proc_unlock(p);
1328 goto bad_notrans;
1329 }
1330 error = proc_transstart(p, 1);
1331 proc_unlock(p);
b0d623f7
A
1332 if (error)
1333 goto bad_notrans;
593a1d5f 1334
91447636
A
1335 error = exec_check_permissions(imgp);
1336 if (error)
1c79356b 1337 goto bad;
1c79356b 1338
91447636
A
1339 /* Copy; avoid invocation of an interpreter overwriting the original */
1340 if (once) {
1341 once = 0;
2d21ac55 1342 *imgp->ip_origvattr = *imgp->ip_vattr;
91447636 1343 }
1c79356b 1344
91447636 1345 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata, PAGE_SIZE, 0,
b0d623f7 1346 UIO_SYSSPACE, IO_NODELOCKED,
2d21ac55
A
1347 vfs_context_ucred(imgp->ip_vfs_context),
1348 &resid, vfs_context_proc(imgp->ip_vfs_context));
1c79356b
A
1349 if (error)
1350 goto bad;
91447636
A
1351
1352encapsulated_binary:
2d21ac55
A
1353 /* Limit the number of iterations we will attempt on each binary */
1354 if (--iterlimit == 0) {
1355 error = EBADEXEC;
1356 goto bad;
1357 }
91447636
A
1358 error = -1;
1359 for(i = 0; error == -1 && execsw[i].ex_imgact != NULL; i++) {
1c79356b 1360
91447636 1361 error = (*execsw[i].ex_imgact)(imgp);
1c79356b 1362
91447636
A
1363 switch (error) {
1364 /* case -1: not claimed: continue */
1365 case -2: /* Encapsulated binary */
1366 goto encapsulated_binary;
1c79356b 1367
91447636 1368 case -3: /* Interpreter */
2d21ac55
A
1369#if CONFIG_MACF
1370 /*
1371 * Copy the script label for later use. Note that
1372 * the label can be different when the script is
1373 * actually read by the interpreter.
1374 */
1375 if (imgp->ip_scriptlabelp)
1376 mac_vnode_label_free(imgp->ip_scriptlabelp);
1377 imgp->ip_scriptlabelp = mac_vnode_label_alloc();
1378 if (imgp->ip_scriptlabelp == NULL) {
1379 error = ENOMEM;
1380 break;
1381 }
1382 mac_vnode_label_copy(imgp->ip_vp->v_label,
b0d623f7 1383 imgp->ip_scriptlabelp);
2d21ac55 1384#endif
6d2010ae
A
1385
1386 nameidone(&nd);
1387
91447636
A
1388 vnode_put(imgp->ip_vp);
1389 imgp->ip_vp = NULL; /* already put */
6d2010ae
A
1390 imgp->ip_ndp = NULL; /* already nameidone */
1391
1392 /* Use imgp->ip_strings, which exec_shell_imgact reset to the interpreter */
1393 NDINIT(&nd, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF,
1394 UIO_SYSSPACE, CAST_USER_ADDR_T(imgp->ip_strings), imgp->ip_vfs_context);
1c79356b 1395
0c530ab8
A
1396#ifdef IMGPF_POWERPC
1397 /*
1398 * PowerPC does not follow symlinks because the
1399 * code which sets exec_archhandler_ppc.fsid and
1400 * exec_archhandler_ppc.fileid doesn't follow them.
1401 */
1402 if (imgp->ip_flags & IMGPF_POWERPC)
1403 nd.ni_cnd.cn_flags &= ~FOLLOW;
1404#endif /* IMGPF_POWERPC */
1c79356b 1405
593a1d5f 1406 proc_transend(p, 0);
91447636
A
1407 goto again;
1408
1409 default:
1410 break;
1411 }
1412 }
2d21ac55
A
1413
1414 /*
1415 * Call out to allow 3rd party notification of exec.
91447636
A
1416 * Ignore result of kauth_authorize_fileop call.
1417 */
1418 if (error == 0 && kauth_authorize_fileop_has_listeners()) {
2d21ac55
A
1419 kauth_authorize_fileop(vfs_context_ucred(imgp->ip_vfs_context),
1420 KAUTH_FILEOP_EXEC,
1421 (uintptr_t)nd.ni_vp, 0);
91447636 1422 }
91447636
A
1423
1424bad:
593a1d5f
A
1425 proc_transend(p, 0);
1426
1427bad_notrans:
91447636
A
1428 if (imgp->ip_strings)
1429 execargs_free(imgp);
2d21ac55
A
1430 if (imgp->ip_ndp)
1431 nameidone(imgp->ip_ndp);
91447636 1432
2d21ac55
A
1433 return (error);
1434}
91447636 1435
2d21ac55
A
1436/*
1437 * exec_handle_port_actions
1438 *
1439 * Description: Go through the _posix_port_actions_t contents,
b0d623f7
A
1440 * calling task_set_special_port, task_set_exception_ports
1441 * and/or audit_session_spawnjoin for the current task.
2d21ac55
A
1442 *
1443 * Parameters: struct image_params * Image parameter block
b0d623f7 1444 * short psa_flags posix spawn attribute flags
2d21ac55
A
1445 *
1446 * Returns: 0 Success
6d2010ae 1447 * EINVAL Failure
b0d623f7 1448 * ENOTSUP Illegal posix_spawn attr flag was set
2d21ac55 1449 */
6d2010ae 1450static errno_t
b0d623f7 1451exec_handle_port_actions(struct image_params *imgp, short psa_flags)
91447636 1452{
2d21ac55
A
1453 _posix_spawn_port_actions_t pacts = imgp->ip_px_spa;
1454 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
1455 _ps_port_action_t *act = NULL;
1456 task_t task = p->task;
1457 ipc_port_t port = NULL;
6d2010ae 1458 errno_t ret = KERN_SUCCESS;
2d21ac55 1459 int i;
91447636 1460
2d21ac55
A
1461 for (i = 0; i < pacts->pspa_count; i++) {
1462 act = &pacts->pspa_actions[i];
91447636 1463
6d2010ae 1464 if (ipc_object_copyin(get_task_ipcspace(current_task()),
b0d623f7 1465 CAST_MACH_PORT_TO_NAME(act->new_port),
2d21ac55 1466 MACH_MSG_TYPE_COPY_SEND,
6d2010ae
A
1467 (ipc_object_t *) &port) != KERN_SUCCESS)
1468 return EINVAL;
a3d08fcd 1469
2d21ac55
A
1470 if (ret)
1471 return ret;
1c79356b 1472
2d21ac55
A
1473 switch (act->port_type) {
1474 case PSPA_SPECIAL:
b0d623f7
A
1475 /* Only allowed when not under vfork */
1476 if (!(psa_flags & POSIX_SPAWN_SETEXEC))
1477 return ENOTSUP;
6d2010ae 1478 ret = (task_set_special_port(task,
2d21ac55 1479 act->which,
6d2010ae 1480 port) == KERN_SUCCESS) ? 0 : EINVAL;
2d21ac55
A
1481 break;
1482 case PSPA_EXCEPTION:
b0d623f7
A
1483 /* Only allowed when not under vfork */
1484 if (!(psa_flags & POSIX_SPAWN_SETEXEC))
1485 return ENOTSUP;
6d2010ae 1486 ret = (task_set_exception_ports(task,
2d21ac55
A
1487 act->mask,
1488 port,
1489 act->behavior,
6d2010ae 1490 act->flavor) == KERN_SUCCESS) ? 0 : EINVAL;
2d21ac55 1491 break;
b0d623f7
A
1492#if CONFIG_AUDIT
1493 case PSPA_AU_SESSION:
1494 ret = audit_session_spawnjoin(p,
1495 port);
1496 break;
1497#endif
2d21ac55 1498 default:
6d2010ae 1499 ret = EINVAL;
2d21ac55
A
1500 }
1501 /* action failed, so release port resources */
1502 if (ret) {
1503 ipc_port_release_send(port);
1504 return ret;
1505 }
1506 }
1507
1508 return ret;
1509}
1510
1511/*
1512 * exec_handle_file_actions
1513 *
1514 * Description: Go through the _posix_file_actions_t contents applying the
1515 * open, close, and dup2 operations to the open file table for
1516 * the current process.
1517 *
1518 * Parameters: struct image_params * Image parameter block
1519 *
1520 * Returns: 0 Success
1521 * ???
1522 *
1523 * Note: Actions are applied in the order specified, with the credential
1524 * of the parent process. This is done to permit the parent
1525 * process to utilize POSIX_SPAWN_RESETIDS to drop privilege in
1526 * the child following operations the child may in fact not be
1527 * normally permitted to perform.
1528 */
1529static int
6d2010ae 1530exec_handle_file_actions(struct image_params *imgp, short psa_flags)
2d21ac55
A
1531{
1532 int error = 0;
1533 int action;
1534 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
1535 _posix_spawn_file_actions_t px_sfap = imgp->ip_px_sfa;
b0d623f7 1536 int ival[2]; /* dummy retval for system calls) */
2d21ac55
A
1537
1538 for (action = 0; action < px_sfap->psfa_act_count; action++) {
1539 _psfa_action_t *psfa = &px_sfap->psfa_act_acts[ action];
1540
1541 switch(psfa->psfaa_type) {
1542 case PSFA_OPEN: {
1543 /*
1544 * Open is different, in that it requires the use of
1545 * a path argument, which is normally copied in from
1546 * user space; because of this, we have to support an
1547 * open from kernel space that passes an address space
6d2010ae 1548 * context of UIO_SYSSPACE, and casts the address
2d21ac55
A
1549 * argument to a user_addr_t.
1550 */
1551 struct vnode_attr va;
1552 struct nameidata nd;
1553 int mode = psfa->psfaa_openargs.psfao_mode;
1554 struct dup2_args dup2a;
1555 struct close_nocancel_args ca;
1556 int origfd;
1557
1558 VATTR_INIT(&va);
1559 /* Mask off all but regular access permissions */
1560 mode = ((mode &~ p->p_fd->fd_cmask) & ALLPERMS) & ~S_ISTXT;
1561 VATTR_SET(&va, va_mode, mode & ACCESSPERMS);
1562
6d2010ae 1563 NDINIT(&nd, LOOKUP, OP_OPEN, FOLLOW | AUDITVNPATH1, UIO_SYSSPACE,
2d21ac55
A
1564 CAST_USER_ADDR_T(psfa->psfaa_openargs.psfao_path),
1565 imgp->ip_vfs_context);
1566
1567 error = open1(imgp->ip_vfs_context,
1568 &nd,
1569 psfa->psfaa_openargs.psfao_oflag,
1570 &va,
1571 ival);
1572
1573 /*
1574 * If there's an error, or we get the right fd by
6d2010ae
A
1575 * accident, then drop out here. This is easier than
1576 * reworking all the open code to preallocate fd
2d21ac55
A
1577 * slots, and internally taking one as an argument.
1578 */
1579 if (error || ival[0] == psfa->psfaa_filedes)
1580 break;
1581
1582 origfd = ival[0];
1583 /*
1584 * If we didn't fall out from an error, we ended up
1585 * with the wrong fd; so now we've got to try to dup2
1586 * it to the right one.
1587 */
1588 dup2a.from = origfd;
1589 dup2a.to = psfa->psfaa_filedes;
1590
1591 /*
1592 * The dup2() system call implementation sets
1593 * ival to newfd in the success case, but we
1594 * can ignore that, since if we didn't get the
1595 * fd we wanted, the error will stop us.
1596 */
1597 error = dup2(p, &dup2a, ival);
1598 if (error)
1599 break;
1600
1601 /*
1602 * Finally, close the original fd.
1603 */
1604 ca.fd = origfd;
1605
1606 error = close_nocancel(p, &ca, ival);
1607 }
1608 break;
1609
1610 case PSFA_DUP2: {
1611 struct dup2_args dup2a;
1612
1613 dup2a.from = psfa->psfaa_filedes;
1614 dup2a.to = psfa->psfaa_openargs.psfao_oflag;
1615
1616 /*
1617 * The dup2() system call implementation sets
1618 * ival to newfd in the success case, but we
1619 * can ignore that, since if we didn't get the
1620 * fd we wanted, the error will stop us.
1621 */
1622 error = dup2(p, &dup2a, ival);
1623 }
1624 break;
1625
1626 case PSFA_CLOSE: {
1627 struct close_nocancel_args ca;
1628
1629 ca.fd = psfa->psfaa_filedes;
1630
1631 error = close_nocancel(p, &ca, ival);
1632 }
1633 break;
1634
6d2010ae
A
1635 case PSFA_INHERIT: {
1636 struct fileproc *fp;
1637 int fd = psfa->psfaa_filedes;
1638
1639 /*
1640 * Check to see if the descriptor exists, and
1641 * ensure it's -not- marked as close-on-exec.
1642 * [Less code than the equivalent F_GETFD/F_SETFD.]
1643 */
1644 proc_fdlock(p);
1645 if ((error = fp_lookup(p, fd, &fp, 1)) == 0) {
1646 *fdflags(p, fd) &= ~UF_EXCLOSE;
1647 (void) fp_drop(p, fd, fp, 1);
1648 }
1649 proc_fdunlock(p);
1650 }
1651 break;
1652
2d21ac55
A
1653 default:
1654 error = EINVAL;
1655 break;
1656 }
6d2010ae 1657
2d21ac55 1658 /* All file actions failures are considered fatal, per POSIX */
6d2010ae 1659
2d21ac55
A
1660 if (error)
1661 break;
1662 }
1663
6d2010ae
A
1664 if (error != 0 || (psa_flags & POSIX_SPAWN_CLOEXEC_DEFAULT) == 0)
1665 return (error);
1666
1667 /*
1668 * If POSIX_SPAWN_CLOEXEC_DEFAULT is set, behave (during
1669 * this spawn only) as if "close on exec" is the default
1670 * disposition of all pre-existing file descriptors. In this case,
1671 * the list of file descriptors mentioned in the file actions
1672 * are the only ones that can be inherited, so mark them now.
1673 *
1674 * The actual closing part comes later, in fdexec().
1675 */
1676 proc_fdlock(p);
1677 for (action = 0; action < px_sfap->psfa_act_count; action++) {
1678 _psfa_action_t *psfa = &px_sfap->psfa_act_acts[action];
1679 int fd = psfa->psfaa_filedes;
1680
1681 switch (psfa->psfaa_type) {
1682 case PSFA_DUP2:
1683 fd = psfa->psfaa_openargs.psfao_oflag;
1684 /*FALLTHROUGH*/
1685 case PSFA_OPEN:
1686 case PSFA_INHERIT:
1687 *fdflags(p, fd) |= UF_INHERIT;
1688 break;
1689
1690 case PSFA_CLOSE:
1691 break;
1692 }
1693 }
1694 proc_fdunlock(p);
1695
1696 return (0);
2d21ac55
A
1697}
1698
1699
1700/*
1701 * posix_spawn
1702 *
1703 * Parameters: uap->pid Pointer to pid return area
1704 * uap->fname File name to exec
1705 * uap->argp Argument list
1706 * uap->envp Environment list
1707 *
1708 * Returns: 0 Success
1709 * EINVAL Invalid argument
1710 * ENOTSUP Not supported
1711 * ENOEXEC Executable file format error
1712 * exec_activate_image:EINVAL Invalid argument
1713 * exec_activate_image:EACCES Permission denied
1714 * exec_activate_image:EINTR Interrupted function
1715 * exec_activate_image:ENOMEM Not enough space
1716 * exec_activate_image:EFAULT Bad address
1717 * exec_activate_image:ENAMETOOLONG Filename too long
1718 * exec_activate_image:ENOEXEC Executable file format error
1719 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
1720 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
1721 * exec_activate_image:???
1722 * mac_execve_enter:???
1723 *
b0d623f7 1724 * TODO: Expect to need __mac_posix_spawn() at some point...
2d21ac55
A
1725 * Handle posix_spawnattr_t
1726 * Handle posix_spawn_file_actions_t
1727 */
1728int
b0d623f7 1729posix_spawn(proc_t ap, struct posix_spawn_args *uap, int32_t *retval)
2d21ac55
A
1730{
1731 proc_t p = ap; /* quiet bogus GCC vfork() warning */
4a3eedf9 1732 user_addr_t pid = uap->pid;
b0d623f7
A
1733 int ival[2]; /* dummy retval for setpgid() */
1734 char *bufp = NULL;
1735 struct image_params *imgp;
1736 struct vnode_attr *vap;
1737 struct vnode_attr *origvap;
2d21ac55
A
1738 struct uthread *uthread = 0; /* compiler complains if not set to 0*/
1739 int error, sig;
2d21ac55
A
1740 char alt_p_comm[sizeof(p->p_comm)] = {0}; /* for PowerPC */
1741 int is_64 = IS_64BIT_PROCESS(p);
2d21ac55
A
1742 struct vfs_context context;
1743 struct user__posix_spawn_args_desc px_args;
1744 struct _posix_spawnattr px_sa;
1745 _posix_spawn_file_actions_t px_sfap = NULL;
1746 _posix_spawn_port_actions_t px_spap = NULL;
b0d623f7
A
1747 struct __kern_sigaction vec;
1748 boolean_t spawn_no_exec = FALSE;
6d2010ae
A
1749 boolean_t proc_transit_set = TRUE;
1750 boolean_t exec_done = FALSE;
2d21ac55 1751
b0d623f7
A
1752 /*
1753 * Allocate a big chunk for locals instead of using stack since these
6d2010ae 1754 * structures are pretty big.
b0d623f7
A
1755 */
1756 MALLOC(bufp, char *, (sizeof(*imgp) + sizeof(*vap) + sizeof(*origvap)), M_TEMP, M_WAITOK | M_ZERO);
1757 imgp = (struct image_params *) bufp;
1758 if (bufp == NULL) {
1759 error = ENOMEM;
1760 goto bad;
1761 }
1762 vap = (struct vnode_attr *) (bufp + sizeof(*imgp));
1763 origvap = (struct vnode_attr *) (bufp + sizeof(*imgp) + sizeof(*vap));
2d21ac55
A
1764
1765 /* Initialize the common data in the image_params structure */
2d21ac55
A
1766 imgp->ip_user_fname = uap->path;
1767 imgp->ip_user_argv = uap->argv;
1768 imgp->ip_user_envv = uap->envp;
b0d623f7
A
1769 imgp->ip_vattr = vap;
1770 imgp->ip_origvattr = origvap;
2d21ac55
A
1771 imgp->ip_vfs_context = &context;
1772 imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT : IMGPF_NONE);
1773 imgp->ip_p_comm = alt_p_comm; /* for PowerPC */
1774 imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
1775
1776 if (uap->adesc != USER_ADDR_NULL) {
1777 if(is_64) {
1778 error = copyin(uap->adesc, &px_args, sizeof(px_args));
1779 } else {
b0d623f7 1780 struct user32__posix_spawn_args_desc px_args32;
2d21ac55
A
1781
1782 error = copyin(uap->adesc, &px_args32, sizeof(px_args32));
1783
1784 /*
1785 * Convert arguments descriptor from external 32 bit
1786 * representation to internal 64 bit representation
1787 */
1788 px_args.attr_size = px_args32.attr_size;
1789 px_args.attrp = CAST_USER_ADDR_T(px_args32.attrp);
1790 px_args.file_actions_size = px_args32.file_actions_size;
1791 px_args.file_actions = CAST_USER_ADDR_T(px_args32.file_actions);
1792 px_args.port_actions_size = px_args32.port_actions_size;
1793 px_args.port_actions = CAST_USER_ADDR_T(px_args32.port_actions);
1794 }
1795 if (error)
1796 goto bad;
1797
1798 if (px_args.attr_size != 0) {
1799 /*
1800 * This could lose some of the port_actions pointer,
1801 * but we already have it from px_args.
1802 */
1803 if ((error = copyin(px_args.attrp, &px_sa, sizeof(px_sa))) != 0)
1804 goto bad;
1805
1806 imgp->ip_px_sa = &px_sa;
1807 }
1808 if (px_args.file_actions_size != 0) {
1809 /* Limit file_actions to allowed number of open files */
1810 int maxfa = (p->p_limit ? p->p_rlimit[RLIMIT_NOFILE].rlim_cur : NOFILE);
1811 if (px_args.file_actions_size < PSF_ACTIONS_SIZE(1) ||
1812 px_args.file_actions_size > PSF_ACTIONS_SIZE(maxfa)) {
1813 error = EINVAL;
1814 goto bad;
1815 }
1816 MALLOC(px_sfap, _posix_spawn_file_actions_t, px_args.file_actions_size, M_TEMP, M_WAITOK);
1817 if (px_sfap == NULL) {
1818 error = ENOMEM;
1819 goto bad;
1820 }
1821 imgp->ip_px_sfa = px_sfap;
1822
1823 if ((error = copyin(px_args.file_actions, px_sfap,
1824 px_args.file_actions_size)) != 0)
1825 goto bad;
1826 }
1827 if (px_args.port_actions_size != 0) {
1828 /* Limit port_actions to one page of data */
1829 if (px_args.port_actions_size < PS_PORT_ACTIONS_SIZE(1) ||
1830 px_args.port_actions_size > PAGE_SIZE) {
1831 error = EINVAL;
1832 goto bad;
1833 }
1834
1835 MALLOC(px_spap, _posix_spawn_port_actions_t,
1836 px_args.port_actions_size, M_TEMP, M_WAITOK);
1837 if (px_spap == NULL) {
1838 error = ENOMEM;
1839 goto bad;
1840 }
1841 imgp->ip_px_spa = px_spap;
1842
1843 if ((error = copyin(px_args.port_actions, px_spap,
1844 px_args.port_actions_size)) != 0)
1845 goto bad;
1846 }
1847 }
1848
b0d623f7
A
1849 /* set uthread to parent */
1850 uthread = get_bsdthread_info(current_thread());
1851
1852 /*
1853 * <rdar://6640530>; this does not result in a behaviour change
1854 * relative to Leopard, so there should not be any existing code
1855 * which depends on it.
1856 */
1857 if (uthread->uu_flag & UT_VFORK) {
1858 error = EINVAL;
1859 goto bad;
1860 }
1861
1862 /*
6d2010ae 1863 * If we don't have the extension flag that turns "posix_spawn()"
b0d623f7
A
1864 * into "execve() with options", then we will be creating a new
1865 * process which does not inherit memory from the parent process,
1866 * which is one of the most expensive things about using fork()
1867 * and execve().
1868 */
2d21ac55 1869 if (imgp->ip_px_sa == NULL || !(px_sa.psa_flags & POSIX_SPAWN_SETEXEC)){
b0d623f7 1870 if ((error = fork1(p, &imgp->ip_new_thread, PROC_CREATE_SPAWN)) != 0)
2d21ac55 1871 goto bad;
b0d623f7
A
1872 imgp->ip_flags |= IMGPF_SPAWN; /* spawn w/o exec */
1873 spawn_no_exec = TRUE; /* used in later tests */
2d21ac55
A
1874 }
1875
b0d623f7
A
1876 if (spawn_no_exec)
1877 p = (proc_t)get_bsdthreadtask_info(imgp->ip_new_thread);
6d2010ae 1878 assert(p != NULL);
2d21ac55 1879
b0d623f7 1880 /* By default, the thread everyone plays with is the parent */
2d21ac55
A
1881 context.vc_thread = current_thread();
1882 context.vc_ucred = p->p_ucred; /* XXX must NOT be kauth_cred_get() */
1883
b0d623f7
A
1884 /*
1885 * However, if we're not in the setexec case, redirect the context
1886 * to the newly created process instead
1887 */
1888 if (spawn_no_exec)
1889 context.vc_thread = imgp->ip_new_thread;
1890
2d21ac55
A
1891 /*
1892 * Post fdcopy(), pre exec_handle_sugid() - this is where we want
1893 * to handle the file_actions. Since vfork() also ends up setting
1894 * us into the parent process group, and saved off the signal flags,
1895 * this is also where we want to handle the spawn flags.
1896 */
6d2010ae 1897
2d21ac55 1898 /* Has spawn file actions? */
6d2010ae
A
1899 if (imgp->ip_px_sfa != NULL) {
1900 /*
1901 * The POSIX_SPAWN_CLOEXEC_DEFAULT flag
1902 * is handled in exec_handle_file_actions().
1903 */
1904 if ((error = exec_handle_file_actions(imgp,
1905 imgp->ip_px_sa != NULL ? px_sa.psa_flags : 0)) != 0)
1906 goto bad;
2d21ac55
A
1907 }
1908
1909 /* Has spawn port actions? */
1910 if (imgp->ip_px_spa != NULL) {
b0d623f7
A
1911 /*
1912 * The check for the POSIX_SPAWN_SETEXEC flag is done in
1913 * exec_handle_port_actions().
1914 */
6d2010ae
A
1915 if ((error = exec_handle_port_actions(imgp,
1916 imgp->ip_px_sa != NULL ? px_sa.psa_flags : 0)) != 0)
2d21ac55
A
1917 goto bad;
1918 }
1919
1920 /* Has spawn attr? */
1921 if (imgp->ip_px_sa != NULL) {
b0d623f7
A
1922 /*
1923 * Set the process group ID of the child process; this has
1924 * to happen before the image activation.
1925 */
2d21ac55
A
1926 if (px_sa.psa_flags & POSIX_SPAWN_SETPGROUP) {
1927 struct setpgid_args spga;
1928 spga.pid = p->p_pid;
1929 spga.pgid = px_sa.psa_pgroup;
1930 /*
1931 * Effectively, call setpgid() system call; works
1932 * because there are no pointer arguments.
1933 */
1934 if((error = setpgid(p, &spga, ival)) != 0)
1935 goto bad;
1936 }
b0d623f7 1937
2d21ac55
A
1938 /*
1939 * Reset UID/GID to parent's RUID/RGID; This works only
1940 * because the operation occurs *after* the vfork() and
1941 * before the call to exec_handle_sugid() by the image
b0d623f7
A
1942 * activator called from exec_activate_image(). POSIX
1943 * requires that any setuid/setgid bits on the process
1944 * image will take precedence over the spawn attributes
1945 * (re)setting them.
2d21ac55
A
1946 *
1947 * The use of p_ucred is safe, since we are acting on the
1948 * new process, and it has no threads other than the one
1949 * we are creating for it.
1950 */
1951 if (px_sa.psa_flags & POSIX_SPAWN_RESETIDS) {
1952 kauth_cred_t my_cred = p->p_ucred;
6d2010ae
A
1953 kauth_cred_t my_new_cred = kauth_cred_setuidgid(my_cred, kauth_cred_getruid(my_cred), kauth_cred_getrgid(my_cred));
1954 if (my_new_cred != my_cred) {
2d21ac55 1955 p->p_ucred = my_new_cred;
6d2010ae
A
1956 /* update cred on proc */
1957 PROC_UPDATE_CREDS_ONPROC(p);
1958 }
2d21ac55 1959 }
6d2010ae
A
1960
1961 /*
1962 * Disable ASLR for the spawned process.
1963 */
1964 if (px_sa.psa_flags & _POSIX_SPAWN_DISABLE_ASLR)
1965 OSBitOrAtomic(P_DISABLE_ASLR, &p->p_flag);
1966
1967 /*
1968 * Forcibly disallow execution from data pages for the spawned process
1969 * even if it would otherwise be permitted by the architecture default.
1970 */
1971 if (px_sa.psa_flags & _POSIX_SPAWN_ALLOW_DATA_EXEC)
1972 imgp->ip_flags |= IMGPF_ALLOW_DATA_EXEC;
b0d623f7
A
1973 }
1974
6d2010ae
A
1975 /*
1976 * Disable ASLR during image activation. This occurs either if the
1977 * _POSIX_SPAWN_DISABLE_ASLR attribute was found above or if
1978 * P_DISABLE_ASLR was inherited from the parent process.
1979 */
1980 if (p->p_flag & P_DISABLE_ASLR)
1981 imgp->ip_flags |= IMGPF_DISABLE_ASLR;
1982
b0d623f7
A
1983 /*
1984 * Clear transition flag so we won't hang if exec_activate_image() causes
1985 * an automount (and launchd does a proc sysctl to service it).
1986 *
1987 * <rdar://problem/6848672>, <rdar://problem/5959568>.
1988 */
1989 if (spawn_no_exec) {
1990 proc_transend(p, 0);
6d2010ae 1991 proc_transit_set = 0;
b0d623f7
A
1992 }
1993
1994#if MAC_SPAWN /* XXX */
1995 if (uap->mac_p != USER_ADDR_NULL) {
1996 error = mac_execve_enter(uap->mac_p, imgp);
1997 if (error)
1998 goto bad;
1999 }
2000#endif
2001
2002 /*
2003 * Activate the image
2004 */
2005 error = exec_activate_image(imgp);
2006
6d2010ae
A
2007 if (error == 0) {
2008 /* process completed the exec */
2009 exec_done = TRUE;
2010 } else if (error == -1) {
2011 /* Image not claimed by any activator? */
b0d623f7 2012 error = ENOEXEC;
6d2010ae 2013 }
b0d623f7
A
2014
2015 /*
2016 * If we have a spawn attr, and it contains signal related flags,
2017 * the we need to process them in the "context" of the new child
2018 * process, so we have to process it following image activation,
2019 * prior to making the thread runnable in user space. This is
2020 * necessitated by some signal information being per-thread rather
2021 * than per-process, and we don't have the new allocation in hand
2022 * until after the image is activated.
2023 */
2024 if (!error && imgp->ip_px_sa != NULL) {
2025 thread_t child_thread = current_thread();
2026 uthread_t child_uthread = uthread;
2027
2028 /*
2029 * If we created a new child thread, then the thread and
2030 * uthread are different than the current ones; otherwise,
2031 * we leave them, since we are in the exec case instead.
2032 */
2033 if (spawn_no_exec) {
2034 child_thread = imgp->ip_new_thread;
2035 child_uthread = get_bsdthread_info(child_thread);
2036 }
2037
2d21ac55
A
2038 /*
2039 * Mask a list of signals, instead of them being unmasked, if
2040 * they were unmasked in the parent; note that some signals
2041 * are not maskable.
2042 */
2043 if (px_sa.psa_flags & POSIX_SPAWN_SETSIGMASK)
b0d623f7 2044 child_uthread->uu_sigmask = (px_sa.psa_sigmask & ~sigcantmask);
2d21ac55
A
2045 /*
2046 * Default a list of signals instead of ignoring them, if
b0d623f7
A
2047 * they were ignored in the parent. Note that we pass
2048 * spawn_no_exec to setsigvec() to indicate that we called
2049 * fork1() and therefore do not need to call proc_signalstart()
2050 * internally.
2d21ac55
A
2051 */
2052 if (px_sa.psa_flags & POSIX_SPAWN_SETSIGDEF) {
2053 vec.sa_handler = SIG_DFL;
2054 vec.sa_tramp = 0;
2055 vec.sa_mask = 0;
2056 vec.sa_flags = 0;
2057 for (sig = 0; sig < NSIG; sig++)
b0d623f7
A
2058 if (px_sa.psa_sigdefault & (1 << sig)) {
2059 error = setsigvec(p, child_thread, sig + 1, &vec, spawn_no_exec);
2d21ac55
A
2060 }
2061 }
2062 }
2063
b0d623f7
A
2064bad:
2065 if (error == 0) {
2066 /* upon successful spawn, re/set the proc control state */
2067 if (imgp->ip_px_sa != NULL) {
2068 switch (px_sa.psa_pcontrol) {
2069 case POSIX_SPAWN_PCONTROL_THROTTLE:
2070 p->p_pcaction = P_PCTHROTTLE;
2071 break;
2072 case POSIX_SPAWN_PCONTROL_SUSPEND:
2073 p->p_pcaction = P_PCSUSP;
2074 break;
2075 case POSIX_SPAWN_PCONTROL_KILL:
2076 p->p_pcaction = P_PCKILL;
2077 break;
2078 case POSIX_SPAWN_PCONTROL_NONE:
2079 default:
2080 p->p_pcaction = 0;
2081 break;
2082 };
2d21ac55 2083 }
b0d623f7 2084 exec_resettextvp(p, imgp);
2d21ac55
A
2085 }
2086
b0d623f7
A
2087 /*
2088 * If we successfully called fork1(), we always need to do this;
2089 * we identify this case by noting the IMGPF_SPAWN flag. This is
2090 * because we come back from that call with signals blocked in the
2091 * child, and we have to unblock them, but we want to wait until
2092 * after we've performed any spawn actions. This has to happen
2093 * before check_for_signature(), which uses psignal.
2094 */
2095 if (spawn_no_exec) {
6d2010ae
A
2096 if (proc_transit_set)
2097 proc_transend(p, 0);
2098
b0d623f7
A
2099 /*
2100 * Drop the signal lock on the child which was taken on our
2101 * behalf by forkproc()/cloneproc() to prevent signals being
2102 * received by the child in a partially constructed state.
2103 */
2104 proc_signalend(p, 0);
2105
2106 /* flag the 'fork' has occurred */
2107 proc_knote(p->p_pptr, NOTE_FORK | p->p_pid);
2108 /* then flag exec has occurred */
2109 proc_knote(p, NOTE_EXEC);
2110 DTRACE_PROC1(create, proc_t, p);
2d21ac55 2111 }
2d21ac55 2112
b0d623f7
A
2113 /*
2114 * We have to delay operations which might throw a signal until after
2115 * the signals have been unblocked; however, we want that to happen
2116 * after exec_resettextvp() so that the textvp is correct when they
2117 * fire.
2118 */
2d21ac55 2119 if (error == 0) {
b0d623f7
A
2120 error = check_for_signature(p, imgp);
2121
2122 /*
2123 * Pay for our earlier safety; deliver the delayed signals from
2124 * the incomplete spawn process now that it's complete.
2125 */
2126 if (imgp != NULL && spawn_no_exec && (p->p_lflag & P_LTRACED)) {
2127 psignal_vfork(p, p->task, imgp->ip_new_thread, SIGTRAP);
2128 }
2129 }
2130
2d21ac55 2131
b0d623f7
A
2132 if (imgp != NULL) {
2133 if (imgp->ip_vp)
2134 vnode_put(imgp->ip_vp);
2135 if (imgp->ip_strings)
2136 execargs_free(imgp);
2137 if (imgp->ip_px_sfa != NULL)
2138 FREE(imgp->ip_px_sfa, M_TEMP);
2139 if (imgp->ip_px_spa != NULL)
2140 FREE(imgp->ip_px_spa, M_TEMP);
2141
2d21ac55 2142#if CONFIG_MACF
b0d623f7
A
2143 if (imgp->ip_execlabelp)
2144 mac_cred_label_free(imgp->ip_execlabelp);
2145 if (imgp->ip_scriptlabelp)
2146 mac_vnode_label_free(imgp->ip_scriptlabelp);
2d21ac55 2147#endif
b0d623f7
A
2148 }
2149
2150 if (error) {
2151 DTRACE_PROC1(exec__failure, int, error);
2152 } else {
2153 /*
2154 * <rdar://6609474> temporary - so dtrace call to current_proc()
2155 * returns the child process instead of the parent.
2156 */
2157 if (imgp != NULL && imgp->ip_flags & IMGPF_SPAWN) {
2158 p->p_lflag |= P_LINVFORK;
2159 p->p_vforkact = current_thread();
2160 uthread->uu_proc = p;
2161 uthread->uu_flag |= UT_VFORK;
2162 }
2163
2164 DTRACE_PROC(exec__success);
2165
2166 /*
2167 * <rdar://6609474> temporary - so dtrace call to current_proc()
2168 * returns the child process instead of the parent.
2169 */
2170 if (imgp != NULL && imgp->ip_flags & IMGPF_SPAWN) {
2171 p->p_lflag &= ~P_LINVFORK;
2172 p->p_vforkact = NULL;
2173 uthread->uu_proc = PROC_NULL;
2174 uthread->uu_flag &= ~UT_VFORK;
2175 }
2176 }
2177
2178 /* Return to both the parent and the child? */
2179 if (imgp != NULL && spawn_no_exec) {
2d21ac55 2180 /*
2d21ac55
A
2181 * If the parent wants the pid, copy it out
2182 */
4a3eedf9
A
2183 if (pid != USER_ADDR_NULL)
2184 (void)suword(pid, p->p_pid);
2d21ac55 2185 retval[0] = error;
2d21ac55 2186
2d21ac55 2187 /*
b0d623f7
A
2188 * If we had an error, perform an internal reap ; this is
2189 * entirely safe, as we have a real process backing us.
2d21ac55 2190 */
b0d623f7
A
2191 if (error) {
2192 proc_list_lock();
2193 p->p_listflag |= P_LIST_DEADPARENT;
2194 proc_list_unlock();
2195 proc_lock(p);
2196 /* make sure no one else has killed it off... */
2197 if (p->p_stat != SZOMB && p->exit_thread == NULL) {
2198 p->exit_thread = current_thread();
2199 proc_unlock(p);
2200 exit1(p, 1, (int *)NULL);
6d2010ae
A
2201 if (exec_done == FALSE) {
2202 task_deallocate(get_threadtask(imgp->ip_new_thread));
2203 thread_deallocate(imgp->ip_new_thread);
2204 }
b0d623f7
A
2205 } else {
2206 /* someone is doing it for us; just skip it */
2207 proc_unlock(p);
2208 }
2209 } else {
2d21ac55 2210
b0d623f7
A
2211 /*
2212 * Return" to the child
2213 *
2214 * Note: the image activator earlier dropped the
2215 * task/thread references to the newly spawned
2216 * process; this is OK, since we still have suspended
2217 * queue references on them, so we should be fine
2218 * with the delayed resume of the thread here.
2219 */
2220 (void)thread_resume(imgp->ip_new_thread);
2221 }
2222 }
2223 if (bufp != NULL) {
2224 FREE(bufp, M_TEMP);
2225 }
2226
2d21ac55
A
2227 return(error);
2228}
2229
2230
2231/*
2232 * execve
2233 *
2234 * Parameters: uap->fname File name to exec
2235 * uap->argp Argument list
2236 * uap->envp Environment list
2237 *
2238 * Returns: 0 Success
2239 * __mac_execve:EINVAL Invalid argument
2240 * __mac_execve:ENOTSUP Invalid argument
2241 * __mac_execve:EACCES Permission denied
2242 * __mac_execve:EINTR Interrupted function
2243 * __mac_execve:ENOMEM Not enough space
2244 * __mac_execve:EFAULT Bad address
2245 * __mac_execve:ENAMETOOLONG Filename too long
2246 * __mac_execve:ENOEXEC Executable file format error
2247 * __mac_execve:ETXTBSY Text file busy [misuse of error code]
2248 * __mac_execve:???
2249 *
2250 * TODO: Dynamic linker header address on stack is copied via suword()
2251 */
2252/* ARGSUSED */
2253int
b0d623f7 2254execve(proc_t p, struct execve_args *uap, int32_t *retval)
2d21ac55
A
2255{
2256 struct __mac_execve_args muap;
2257 int err;
2258
2259 muap.fname = uap->fname;
2260 muap.argp = uap->argp;
2261 muap.envp = uap->envp;
2262 muap.mac_p = USER_ADDR_NULL;
2263 err = __mac_execve(p, &muap, retval);
2264
2265 return(err);
2266}
2267
2268/*
2269 * __mac_execve
2270 *
2271 * Parameters: uap->fname File name to exec
2272 * uap->argp Argument list
2273 * uap->envp Environment list
2274 * uap->mac_p MAC label supplied by caller
2275 *
2276 * Returns: 0 Success
2277 * EINVAL Invalid argument
2278 * ENOTSUP Not supported
2279 * ENOEXEC Executable file format error
2280 * exec_activate_image:EINVAL Invalid argument
2281 * exec_activate_image:EACCES Permission denied
2282 * exec_activate_image:EINTR Interrupted function
2283 * exec_activate_image:ENOMEM Not enough space
2284 * exec_activate_image:EFAULT Bad address
2285 * exec_activate_image:ENAMETOOLONG Filename too long
2286 * exec_activate_image:ENOEXEC Executable file format error
2287 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
2288 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
2289 * exec_activate_image:???
2290 * mac_execve_enter:???
2291 *
2292 * TODO: Dynamic linker header address on stack is copied via suword()
2293 */
2294int
b0d623f7 2295__mac_execve(proc_t p, struct __mac_execve_args *uap, int32_t *retval)
2d21ac55 2296{
b0d623f7
A
2297 char *bufp = NULL;
2298 struct image_params *imgp;
2299 struct vnode_attr *vap;
2300 struct vnode_attr *origvap;
2d21ac55 2301 int error;
2d21ac55
A
2302 char alt_p_comm[sizeof(p->p_comm)] = {0}; /* for PowerPC */
2303 int is_64 = IS_64BIT_PROCESS(p);
2304 struct vfs_context context;
2305
2306 context.vc_thread = current_thread();
2307 context.vc_ucred = kauth_cred_proc_ref(p); /* XXX must NOT be kauth_cred_get() */
2308
b0d623f7
A
2309 /* Allocate a big chunk for locals instead of using stack since these
2310 * structures a pretty big.
2311 */
2312 MALLOC(bufp, char *, (sizeof(*imgp) + sizeof(*vap) + sizeof(*origvap)), M_TEMP, M_WAITOK | M_ZERO);
2313 imgp = (struct image_params *) bufp;
2314 if (bufp == NULL) {
2315 error = ENOMEM;
2316 goto exit_with_error;
2317 }
2318 vap = (struct vnode_attr *) (bufp + sizeof(*imgp));
2319 origvap = (struct vnode_attr *) (bufp + sizeof(*imgp) + sizeof(*vap));
2320
2d21ac55 2321 /* Initialize the common data in the image_params structure */
2d21ac55
A
2322 imgp->ip_user_fname = uap->fname;
2323 imgp->ip_user_argv = uap->argp;
2324 imgp->ip_user_envv = uap->envp;
b0d623f7
A
2325 imgp->ip_vattr = vap;
2326 imgp->ip_origvattr = origvap;
2d21ac55 2327 imgp->ip_vfs_context = &context;
6d2010ae 2328 imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT : IMGPF_NONE) | ((p->p_flag & P_DISABLE_ASLR) ? IMGPF_DISABLE_ASLR : IMGPF_NONE);
2d21ac55
A
2329 imgp->ip_p_comm = alt_p_comm; /* for PowerPC */
2330 imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
2331
2d21ac55
A
2332#if CONFIG_MACF
2333 if (uap->mac_p != USER_ADDR_NULL) {
2334 error = mac_execve_enter(uap->mac_p, imgp);
2335 if (error) {
2336 kauth_cred_unref(&context.vc_ucred);
b0d623f7 2337 goto exit_with_error;
2d21ac55
A
2338 }
2339 }
2340#endif
2341
2d21ac55 2342 error = exec_activate_image(imgp);
2d21ac55
A
2343
2344 kauth_cred_unref(&context.vc_ucred);
2345
2346 /* Image not claimed by any activator? */
2347 if (error == -1)
2348 error = ENOEXEC;
2349
2350 if (error == 0) {
2351 exec_resettextvp(p, imgp);
b0d623f7 2352 error = check_for_signature(p, imgp);
2d21ac55
A
2353 }
2354 if (imgp->ip_vp != NULLVP)
2355 vnode_put(imgp->ip_vp);
2356 if (imgp->ip_strings)
2357 execargs_free(imgp);
2358#if CONFIG_MACF
2359 if (imgp->ip_execlabelp)
2360 mac_cred_label_free(imgp->ip_execlabelp);
2361 if (imgp->ip_scriptlabelp)
2362 mac_vnode_label_free(imgp->ip_scriptlabelp);
2363#endif
2364 if (!error) {
b0d623f7 2365 struct uthread *uthread;
2d21ac55 2366
b0d623f7
A
2367 /* Sever any extant thread affinity */
2368 thread_affinity_exec(current_thread());
2369
2370 DTRACE_PROC(exec__success);
2371 uthread = get_bsdthread_info(current_thread());
2d21ac55
A
2372 if (uthread->uu_flag & UT_VFORK) {
2373 vfork_return(p, retval, p->p_pid);
b0d623f7 2374 (void)thread_resume(imgp->ip_new_thread);
2d21ac55
A
2375 }
2376 } else {
2377 DTRACE_PROC1(exec__failure, int, error);
2378 }
b0d623f7
A
2379
2380exit_with_error:
2381 if (bufp != NULL) {
2382 FREE(bufp, M_TEMP);
2383 }
2d21ac55
A
2384
2385 return(error);
2386}
2387
2388
2389/*
2390 * copyinptr
2391 *
2392 * Description: Copy a pointer in from user space to a user_addr_t in kernel
2393 * space, based on 32/64 bitness of the user space
2394 *
2395 * Parameters: froma User space address
2396 * toptr Address of kernel space user_addr_t
2397 * ptr_size 4/8, based on 'froma' address space
2398 *
2399 * Returns: 0 Success
2400 * EFAULT Bad 'froma'
2401 *
2402 * Implicit returns:
2403 * *ptr_size Modified
2404 */
2405static int
2406copyinptr(user_addr_t froma, user_addr_t *toptr, int ptr_size)
2407{
2408 int error;
2409
2410 if (ptr_size == 4) {
2411 /* 64 bit value containing 32 bit address */
2412 unsigned int i;
2413
2414 error = copyin(froma, &i, 4);
2415 *toptr = CAST_USER_ADDR_T(i); /* SAFE */
2416 } else {
2417 error = copyin(froma, toptr, 8);
2418 }
2419 return (error);
2420}
2421
2422
2423/*
2424 * copyoutptr
2425 *
2426 * Description: Copy a pointer out from a user_addr_t in kernel space to
2427 * user space, based on 32/64 bitness of the user space
2428 *
2429 * Parameters: ua User space address to copy to
2430 * ptr Address of kernel space user_addr_t
2431 * ptr_size 4/8, based on 'ua' address space
2432 *
2433 * Returns: 0 Success
2434 * EFAULT Bad 'ua'
2435 *
2d21ac55
A
2436 */
2437static int
2438copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size)
2439{
91447636 2440 int error;
1c79356b 2441
91447636
A
2442 if (ptr_size == 4) {
2443 /* 64 bit value containing 32 bit address */
b0d623f7 2444 unsigned int i = CAST_DOWN_EXPLICIT(unsigned int,ua); /* SAFE */
91447636
A
2445
2446 error = copyout(&i, ptr, 4);
2447 } else {
2448 error = copyout(&ua, ptr, 8);
1c79356b 2449 }
91447636
A
2450 return (error);
2451}
2452
2453
2454/*
2455 * exec_copyout_strings
2456 *
2457 * Copy out the strings segment to user space. The strings segment is put
2458 * on a preinitialized stack frame.
2459 *
2460 * Parameters: struct image_params * the image parameter block
2461 * int * a pointer to the stack offset variable
2462 *
2463 * Returns: 0 Success
2464 * !0 Faiure: errno
2465 *
2466 * Implicit returns:
2467 * (*stackp) The stack offset, modified
2468 *
2469 * Note: The strings segment layout is backward, from the beginning
2470 * of the top of the stack to consume the minimal amount of
2471 * space possible; the returned stack pointer points to the
6d2010ae 2472 * end of the area consumed (stacks grow downward).
91447636
A
2473 *
2474 * argc is an int; arg[i] are pointers; env[i] are pointers;
6d2010ae 2475 * the 0's are (void *)NULL's
91447636
A
2476 *
2477 * The stack frame layout is:
2478 *
6d2010ae
A
2479 * +-------------+ <- p->user_stack
2480 * | 16b |
2481 * +-------------+
2482 * | STRING AREA |
2483 * | : |
2484 * | : |
2485 * | : |
2486 * +- -- -- -- --+
2487 * | PATH AREA |
2488 * +-------------+
2489 * | 0 |
2490 * +-------------+
2491 * | applev[n] |
2492 * +-------------+
2493 * :
2494 * :
2495 * +-------------+
2496 * | applev[1] |
2497 * +-------------+
2498 * | exec_path / |
2499 * | applev[0] |
2500 * +-------------+
2501 * | 0 |
2502 * +-------------+
2503 * | env[n] |
2504 * +-------------+
2505 * :
2506 * :
2507 * +-------------+
2508 * | env[0] |
2509 * +-------------+
2510 * | 0 |
2511 * +-------------+
2512 * | arg[argc-1] |
2513 * +-------------+
2514 * :
2515 * :
2516 * +-------------+
2517 * | arg[0] |
2518 * +-------------+
2519 * | argc |
2520 * sp-> +-------------+
91447636
A
2521 *
2522 * Although technically a part of the STRING AREA, we treat the PATH AREA as
2523 * a separate entity. This allows us to align the beginning of the PATH AREA
2524 * to a pointer boundary so that the exec_path, env[i], and argv[i] pointers
2525 * which preceed it on the stack are properly aligned.
91447636 2526 */
6d2010ae 2527
91447636
A
2528static int
2529exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp)
2530{
2d21ac55 2531 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
91447636 2532 int ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
6d2010ae
A
2533 int ptr_area_size;
2534 void *ptr_buffer_start, *ptr_buffer;
2535 int string_size;
2536
91447636 2537 user_addr_t string_area; /* *argv[], *env[] */
6d2010ae
A
2538 user_addr_t ptr_area; /* argv[], env[], applev[] */
2539 user_addr_t argc_area; /* argc */
91447636 2540 user_addr_t stack;
91447636 2541 int error;
6d2010ae
A
2542
2543 unsigned i;
2544 struct copyout_desc {
2545 char *start_string;
2546 int count;
2547#if CONFIG_DTRACE
2548 user_addr_t *dtrace_cookie;
2549#endif
2550 boolean_t null_term;
2551 } descriptors[] = {
2552 {
2553 .start_string = imgp->ip_startargv,
2554 .count = imgp->ip_argc,
2555#if CONFIG_DTRACE
2556 .dtrace_cookie = &p->p_dtrace_argv,
2557#endif
2558 .null_term = TRUE
2559 },
2560 {
2561 .start_string = imgp->ip_endargv,
2562 .count = imgp->ip_envc,
2563#if CONFIG_DTRACE
2564 .dtrace_cookie = &p->p_dtrace_envp,
2565#endif
2566 .null_term = TRUE
2567 },
2568 {
2569 .start_string = imgp->ip_strings,
2570 .count = 1,
2571#if CONFIG_DTRACE
2572 .dtrace_cookie = NULL,
2573#endif
2574 .null_term = FALSE
2575 },
2576 {
2577 .start_string = imgp->ip_endenvv,
2578 .count = imgp->ip_applec - 1, /* exec_path handled above */
2579#if CONFIG_DTRACE
2580 .dtrace_cookie = NULL,
2581#endif
2582 .null_term = TRUE
2583 }
2584 };
91447636
A
2585
2586 stack = *stackp;
2587
2588 /*
6d2010ae
A
2589 * All previous contributors to the string area
2590 * should have aligned their sub-area
91447636 2591 */
6d2010ae
A
2592 if (imgp->ip_strspace % ptr_size != 0) {
2593 error = EINVAL;
2594 goto bad;
2595 }
91447636 2596
6d2010ae
A
2597 /* Grow the stack down for the strings we've been building up */
2598 string_size = imgp->ip_strendp - imgp->ip_strings;
2599 stack -= string_size;
2600 string_area = stack;
2601
2602 /*
2603 * Need room for one pointer for each string, plus
2604 * one for the NULLs terminating the argv, envv, and apple areas.
2605 */
2606 ptr_area_size = (imgp->ip_argc + imgp->ip_envc + imgp->ip_applec + 3) *
2607 ptr_size;
2608 stack -= ptr_area_size;
2609 ptr_area = stack;
2610
2611 /* We'll construct all the pointer arrays in our string buffer,
2612 * which we already know is aligned properly, and ip_argspace
2613 * was used to verify we have enough space.
2614 */
2615 ptr_buffer_start = ptr_buffer = (void *)imgp->ip_strendp;
2616
2617 /*
2618 * Need room for pointer-aligned argc slot.
2619 */
2620 stack -= ptr_size;
2621 argc_area = stack;
1c79356b
A
2622
2623 /*
91447636
A
2624 * Record the size of the arguments area so that sysctl_procargs()
2625 * can return the argument area without having to parse the arguments.
1c79356b 2626 */
2d21ac55 2627 proc_lock(p);
91447636 2628 p->p_argc = imgp->ip_argc;
6d2010ae 2629 p->p_argslen = (int)(*stackp - string_area);
2d21ac55 2630 proc_unlock(p);
91447636 2631
6d2010ae
A
2632 /* Return the initial stack address: the location of argc */
2633 *stackp = stack;
91447636 2634
1c79356b 2635 /*
6d2010ae
A
2636 * Copy out the entire strings area.
2637 */
2638 error = copyout(imgp->ip_strings, string_area,
2639 string_size);
91447636
A
2640 if (error)
2641 goto bad;
2642
6d2010ae
A
2643 for (i = 0; i < sizeof(descriptors)/sizeof(descriptors[0]); i++) {
2644 char *cur_string = descriptors[i].start_string;
2645 int j;
91447636 2646
2d21ac55 2647#if CONFIG_DTRACE
6d2010ae
A
2648 if (descriptors[i].dtrace_cookie) {
2649 proc_lock(p);
2650 *descriptors[i].dtrace_cookie = ptr_area + ((uintptr_t)ptr_buffer - (uintptr_t)ptr_buffer_start); /* dtrace convenience */
2651 proc_unlock(p);
2652 }
2d21ac55 2653#endif /* CONFIG_DTRACE */
91447636 2654
6d2010ae
A
2655 /*
2656 * For each segment (argv, envv, applev), copy as many pointers as requested
2657 * to our pointer buffer.
2658 */
2659 for (j = 0; j < descriptors[i].count; j++) {
2660 user_addr_t cur_address = string_area + (cur_string - imgp->ip_strings);
2661
2662 /* Copy out the pointer to the current string. Alignment has been verified */
2663 if (ptr_size == 8) {
2664 *(uint64_t *)ptr_buffer = (uint64_t)cur_address;
2665 } else {
2666 *(uint32_t *)ptr_buffer = (uint32_t)cur_address;
2667 }
2668
2669 ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size);
2670 cur_string += strlen(cur_string) + 1; /* Only a NUL between strings in the same area */
91447636 2671 }
91447636 2672
6d2010ae
A
2673 if (descriptors[i].null_term) {
2674 if (ptr_size == 8) {
2675 *(uint64_t *)ptr_buffer = 0ULL;
2676 } else {
2677 *(uint32_t *)ptr_buffer = 0;
91447636 2678 }
6d2010ae
A
2679
2680 ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size);
2681 }
2682 }
2683
2684 /*
2685 * Copy out all our pointer arrays in bulk.
2686 */
2687 error = copyout(ptr_buffer_start, ptr_area,
2688 ptr_area_size);
2689 if (error)
2690 goto bad;
2691
2692 /* argc (int32, stored in a ptr_size area) */
2693 error = copyoutptr((user_addr_t)imgp->ip_argc, argc_area, ptr_size);
2694 if (error)
2695 goto bad;
91447636
A
2696
2697bad:
2698 return(error);
2699}
2700
2701
2702/*
2703 * exec_extract_strings
2704 *
2705 * Copy arguments and environment from user space into work area; we may
2706 * have already copied some early arguments into the work area, and if
2707 * so, any arguments opied in are appended to those already there.
6d2010ae
A
2708 * This function is the primary manipulator of ip_argspace, since
2709 * these are the arguments the client of execve(2) knows about. After
2710 * each argv[]/envv[] string is copied, we charge the string length
2711 * and argv[]/envv[] pointer slot to ip_argspace, so that we can
2712 * full preflight the arg list size.
91447636
A
2713 *
2714 * Parameters: struct image_params * the image parameter block
2715 *
2716 * Returns: 0 Success
2717 * !0 Failure: errno
2718 *
2719 * Implicit returns;
2720 * (imgp->ip_argc) Count of arguments, updated
2721 * (imgp->ip_envc) Count of environment strings, updated
6d2010ae
A
2722 * (imgp->ip_argspace) Count of remaining of NCARGS
2723 * (imgp->ip_interp_buffer) Interpreter and args (mutated in place)
91447636
A
2724 *
2725 *
2d21ac55 2726 * Note: The argument and environment vectors are user space pointers
91447636
A
2727 * to arrays of user space pointers.
2728 */
2729static int
2730exec_extract_strings(struct image_params *imgp)
2731{
2732 int error = 0;
91447636 2733 int ptr_size = (imgp->ip_flags & IMGPF_WAS_64BIT) ? 8 : 4;
6d2010ae 2734 int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
91447636
A
2735 user_addr_t argv = imgp->ip_user_argv;
2736 user_addr_t envv = imgp->ip_user_envv;
2737
b0d623f7
A
2738 /*
2739 * Adjust space reserved for the path name by however much padding it
2740 * needs. Doing this here since we didn't know if this would be a 32-
2741 * or 64-bit process back in exec_save_path.
2742 */
6d2010ae
A
2743 while (imgp->ip_strspace % new_ptr_size != 0) {
2744 *imgp->ip_strendp++ = '\0';
2745 imgp->ip_strspace--;
2746 /* imgp->ip_argspace--; not counted towards exec args total */
2747 }
b0d623f7 2748
1c79356b 2749 /*
6d2010ae 2750 * From now on, we start attributing string space to ip_argspace
1c79356b 2751 */
6d2010ae
A
2752 imgp->ip_startargv = imgp->ip_strendp;
2753 imgp->ip_argc = 0;
2754
2755 if((imgp->ip_flags & IMGPF_INTERPRET) != 0) {
91447636 2756 user_addr_t arg;
6d2010ae
A
2757 char *argstart, *ch;
2758
2759 /* First, the arguments in the "#!" string are tokenized and extracted. */
2760 argstart = imgp->ip_interp_buffer;
2761 while (argstart) {
2762 ch = argstart;
2763 while (*ch && !IS_WHITESPACE(*ch)) {
2764 ch++;
2765 }
91447636 2766
6d2010ae
A
2767 if (*ch == '\0') {
2768 /* last argument, no need to NUL-terminate */
2769 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE);
2770 argstart = NULL;
2771 } else {
2772 /* NUL-terminate */
2773 *ch = '\0';
2774 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE);
2775
2776 /*
2777 * Find the next string. We know spaces at the end of the string have already
2778 * been stripped.
2779 */
2780 argstart = ch + 1;
2781 while (IS_WHITESPACE(*argstart)) {
2782 argstart++;
2783 }
2784 }
2785
2786 /* Error-check, regardless of whether this is the last interpreter arg or not */
91447636
A
2787 if (error)
2788 goto bad;
6d2010ae
A
2789 if (imgp->ip_argspace < new_ptr_size) {
2790 error = E2BIG;
2791 goto bad;
2792 }
2793 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
91447636 2794 imgp->ip_argc++;
1c79356b 2795 }
6d2010ae
A
2796
2797 if (argv != 0LL) {
2798 /*
2799 * If we are running an interpreter, replace the av[0] that was
2800 * passed to execve() with the path name that was
2801 * passed to execve() for interpreters which do not use the PATH
2802 * to locate their script arguments.
2803 */
2804 error = copyinptr(argv, &arg, ptr_size);
2805 if (error)
2806 goto bad;
2807 if (arg != 0LL) {
2808 argv += ptr_size; /* consume without using */
2809 }
2810 }
2811
2812 if (imgp->ip_interp_sugid_fd != -1) {
2813 char temp[19]; /* "/dev/fd/" + 10 digits + NUL */
2814 snprintf(temp, sizeof(temp), "/dev/fd/%d", imgp->ip_interp_sugid_fd);
2815 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(temp), UIO_SYSSPACE, TRUE);
2816 } else {
2817 error = exec_add_user_string(imgp, imgp->ip_user_fname, imgp->ip_seg, TRUE);
2818 }
2819
2820 if (error)
2821 goto bad;
2822 if (imgp->ip_argspace < new_ptr_size) {
2823 error = E2BIG;
2824 goto bad;
2825 }
2826 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
2827 imgp->ip_argc++;
91447636 2828 }
1c79356b 2829
91447636
A
2830 while (argv != 0LL) {
2831 user_addr_t arg;
2832
2833 error = copyinptr(argv, &arg, ptr_size);
2834 if (error)
1c79356b 2835 goto bad;
1c79356b 2836
91447636
A
2837 if (arg == 0LL) {
2838 break;
1c79356b 2839 }
6d2010ae
A
2840
2841 argv += ptr_size;
2842
91447636
A
2843 /*
2844 * av[n...] = arg[n]
2845 */
6d2010ae 2846 error = exec_add_user_string(imgp, arg, imgp->ip_seg, TRUE);
91447636
A
2847 if (error)
2848 goto bad;
6d2010ae
A
2849 if (imgp->ip_argspace < new_ptr_size) {
2850 error = E2BIG;
2851 goto bad;
2852 }
2853 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
91447636
A
2854 imgp->ip_argc++;
2855 }
6d2010ae
A
2856
2857 /* Save space for argv[] NULL terminator */
2858 if (imgp->ip_argspace < new_ptr_size) {
2859 error = E2BIG;
2860 goto bad;
2861 }
2862 imgp->ip_argspace -= new_ptr_size;
b0d623f7 2863
6d2010ae
A
2864 /* Note where the args ends and env begins. */
2865 imgp->ip_endargv = imgp->ip_strendp;
2866 imgp->ip_envc = 0;
91447636
A
2867
2868 /* Now, get the environment */
2869 while (envv != 0LL) {
2870 user_addr_t env;
2871
2872 error = copyinptr(envv, &env, ptr_size);
2873 if (error)
2874 goto bad;
1c79356b 2875
91447636
A
2876 envv += ptr_size;
2877 if (env == 0LL) {
2878 break;
1c79356b 2879 }
1c79356b 2880 /*
91447636
A
2881 * av[n...] = env[n]
2882 */
6d2010ae 2883 error = exec_add_user_string(imgp, env, imgp->ip_seg, TRUE);
91447636 2884 if (error)
55e303ae 2885 goto bad;
6d2010ae
A
2886 if (imgp->ip_argspace < new_ptr_size) {
2887 error = E2BIG;
2888 goto bad;
2889 }
2890 imgp->ip_argspace -= new_ptr_size; /* to hold envv[] entry */
91447636 2891 imgp->ip_envc++;
55e303ae 2892 }
6d2010ae
A
2893
2894 /* Save space for envv[] NULL terminator */
2895 if (imgp->ip_argspace < new_ptr_size) {
2896 error = E2BIG;
2897 goto bad;
2898 }
2899 imgp->ip_argspace -= new_ptr_size;
2900
2901 /* Align the tail of the combined argv+envv area */
2902 while (imgp->ip_strspace % new_ptr_size != 0) {
2903 if (imgp->ip_argspace < 1) {
2904 error = E2BIG;
2905 goto bad;
2906 }
2907 *imgp->ip_strendp++ = '\0';
2908 imgp->ip_strspace--;
2909 imgp->ip_argspace--;
2910 }
2911
2912 /* Note where the envv ends and applev begins. */
2913 imgp->ip_endenvv = imgp->ip_strendp;
2914
2915 /*
2916 * From now on, we are no longer charging argument
2917 * space to ip_argspace.
2918 */
2919
91447636
A
2920bad:
2921 return error;
2922}
55e303ae 2923
6d2010ae
A
2924static char *
2925random_hex_str(char *str, int len)
2926{
2927 uint64_t low, high, value;
2928 int idx;
2929 char digit;
2930
2931 /* A 64-bit value will only take 16 characters, plus '0x' and NULL. */
2932 if (len > 19)
2933 len = 19;
2934
2935 /* We need enough room for at least 1 digit */
2936 if (len < 4)
2937 return (NULL);
2938
2939 low = random();
2940 high = random();
2941 value = high << 32 | low;
2942
2943 str[0] = '0';
2944 str[1] = 'x';
2945 for (idx = 2; idx < len - 1; idx++) {
2946 digit = value & 0xf;
2947 value = value >> 4;
2948 if (digit < 10)
2949 str[idx] = '0' + digit;
2950 else
2951 str[idx] = 'a' + (digit - 10);
2952 }
2953 str[idx] = '\0';
2954 return (str);
2955}
2956
2957/*
2958 * Libc has an 8-element array set up for stack guard values. It only fills
2959 * in one of those entries, and both gcc and llvm seem to use only a single
2960 * 8-byte guard. Until somebody needs more than an 8-byte guard value, don't
2961 * do the work to construct them.
2962 */
2963#define GUARD_VALUES 1
2964#define GUARD_KEY "stack_guard="
2965
2966/*
2967 * System malloc needs some entropy when it is initialized.
2968 */
2969#define ENTROPY_VALUES 2
2970#define ENTROPY_KEY "malloc_entropy="
2971
2972/*
2973 * Build up the contents of the apple[] string vector
2974 */
2975static int
2976exec_add_apple_strings(struct image_params *imgp)
2977{
2978 int i, error;
2979 int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
2980 char guard[19];
2981 char guard_vec[strlen(GUARD_KEY) + 19 * GUARD_VALUES + 1];
2982
2983 char entropy[19];
2984 char entropy_vec[strlen(ENTROPY_KEY) + 19 * ENTROPY_VALUES + 1];
2985
2986 /* exec_save_path stored the first string */
2987 imgp->ip_applec = 1;
2988
2989 /*
2990 * Supply libc with a collection of random values to use when
2991 * implementing -fstack-protector.
2992 */
2993 (void)strlcpy(guard_vec, GUARD_KEY, sizeof (guard_vec));
2994 for (i = 0; i < GUARD_VALUES; i++) {
2995 random_hex_str(guard, sizeof (guard));
2996 if (i)
2997 (void)strlcat(guard_vec, ",", sizeof (guard_vec));
2998 (void)strlcat(guard_vec, guard, sizeof (guard_vec));
2999 }
3000
3001 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(guard_vec), UIO_SYSSPACE, FALSE);
3002 if (error)
3003 goto bad;
3004 imgp->ip_applec++;
3005
3006 /*
3007 * Supply libc with entropy for system malloc.
3008 */
3009 (void)strlcpy(entropy_vec, ENTROPY_KEY, sizeof(entropy_vec));
3010 for (i = 0; i < ENTROPY_VALUES; i++) {
3011 random_hex_str(entropy, sizeof (entropy));
3012 if (i)
3013 (void)strlcat(entropy_vec, ",", sizeof (entropy_vec));
3014 (void)strlcat(entropy_vec, entropy, sizeof (entropy_vec));
3015 }
3016
3017 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(entropy_vec), UIO_SYSSPACE, FALSE);
3018 if (error)
3019 goto bad;
3020 imgp->ip_applec++;
3021
3022 /* Align the tail of the combined applev area */
3023 while (imgp->ip_strspace % new_ptr_size != 0) {
3024 *imgp->ip_strendp++ = '\0';
3025 imgp->ip_strspace--;
3026 }
3027
3028bad:
3029 return error;
3030}
55e303ae 3031
91447636 3032#define unix_stack_size(p) (p->p_rlimit[RLIMIT_STACK].rlim_cur)
55e303ae 3033
2d21ac55
A
3034/*
3035 * exec_check_permissions
3036 *
6d2010ae 3037 * Description: Verify that the file that is being attempted to be executed
2d21ac55
A
3038 * is in fact allowed to be executed based on it POSIX file
3039 * permissions and other access control criteria
3040 *
3041 * Parameters: struct image_params * the image parameter block
3042 *
3043 * Returns: 0 Success
3044 * EACCES Permission denied
3045 * ENOEXEC Executable file format error
3046 * ETXTBSY Text file busy [misuse of error code]
3047 * vnode_getattr:???
3048 * vnode_authorize:???
3049 */
91447636
A
3050static int
3051exec_check_permissions(struct image_params *imgp)
3052{
3053 struct vnode *vp = imgp->ip_vp;
3054 struct vnode_attr *vap = imgp->ip_vattr;
2d21ac55 3055 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
91447636
A
3056 int error;
3057 kauth_action_t action;
55e303ae 3058
91447636
A
3059 /* Only allow execution of regular files */
3060 if (!vnode_isreg(vp))
3061 return (EACCES);
3062
3063 /* Get the file attributes that we will be using here and elsewhere */
3064 VATTR_INIT(vap);
3065 VATTR_WANTED(vap, va_uid);
3066 VATTR_WANTED(vap, va_gid);
3067 VATTR_WANTED(vap, va_mode);
3068 VATTR_WANTED(vap, va_fsid);
3069 VATTR_WANTED(vap, va_fileid);
3070 VATTR_WANTED(vap, va_data_size);
3071 if ((error = vnode_getattr(vp, vap, imgp->ip_vfs_context)) != 0)
3072 return (error);
55e303ae 3073
91447636
A
3074 /*
3075 * Ensure that at least one execute bit is on - otherwise root
3076 * will always succeed, and we don't want to happen unless the
3077 * file really is executable.
3078 */
6d2010ae 3079 if (!vfs_authopaque(vnode_mount(vp)) && ((vap->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0))
91447636 3080 return (EACCES);
55e303ae 3081
91447636
A
3082 /* Disallow zero length files */
3083 if (vap->va_data_size == 0)
3084 return (ENOEXEC);
55e303ae 3085
91447636
A
3086 imgp->ip_arch_offset = (user_size_t)0;
3087 imgp->ip_arch_size = vap->va_data_size;
0b4e3aa0 3088
91447636 3089 /* Disable setuid-ness for traced programs or if MNT_NOSUID */
b0d623f7 3090 if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_lflag & P_LTRACED))
91447636 3091 vap->va_mode &= ~(VSUID | VSGID);
2d21ac55
A
3092
3093#if CONFIG_MACF
3094 error = mac_vnode_check_exec(imgp->ip_vfs_context, vp, imgp);
3095 if (error)
3096 return (error);
3097#endif
91447636
A
3098
3099 /* Check for execute permission */
3100 action = KAUTH_VNODE_EXECUTE;
3101 /* Traced images must also be readable */
2d21ac55 3102 if (p->p_lflag & P_LTRACED)
91447636
A
3103 action |= KAUTH_VNODE_READ_DATA;
3104 if ((error = vnode_authorize(vp, NULL, action, imgp->ip_vfs_context)) != 0)
3105 return (error);
1c79356b 3106
2d21ac55 3107#if 0
91447636 3108 /* Don't let it run if anyone had it open for writing */
2d21ac55
A
3109 vnode_lock(vp);
3110 if (vp->v_writecount) {
3111 panic("going to return ETXTBSY %x", vp);
3112 vnode_unlock(vp);
91447636 3113 return (ETXTBSY);
2d21ac55
A
3114 }
3115 vnode_unlock(vp);
3116#endif
3117
de355530 3118
0c530ab8
A
3119#ifdef IMGPF_POWERPC
3120 /*
3121 * If the file we are about to attempt to load is the exec_handler_ppc,
3122 * which is determined by matching the vattr fields against previously
3123 * cached values, then we set the PowerPC environment flag.
3124 */
3125 if (vap->va_fsid == exec_archhandler_ppc.fsid &&
6d2010ae 3126 vap->va_fileid == exec_archhandler_ppc.fileid) {
0c530ab8
A
3127 imgp->ip_flags |= IMGPF_POWERPC;
3128 }
3129#endif /* IMGPF_POWERPC */
0b4e3aa0 3130
91447636 3131 /* XXX May want to indicate to underlying FS that vnode is open */
1c79356b 3132
91447636
A
3133 return (error);
3134}
3135
2d21ac55 3136
91447636
A
3137/*
3138 * exec_handle_sugid
3139 *
3140 * Initially clear the P_SUGID in the process flags; if an SUGID process is
3141 * exec'ing a non-SUGID image, then this is the point of no return.
3142 *
2d21ac55 3143 * If the image being activated is SUGID, then replace the credential with a
91447636
A
3144 * copy, disable tracing (unless the tracing process is root), reset the
3145 * mach task port to revoke it, set the P_SUGID bit,
3146 *
3147 * If the saved user and group ID will be changing, then make sure it happens
3148 * to a new credential, rather than a shared one.
3149 *
3150 * Set the security token (this is probably obsolete, given that the token
3151 * should not technically be separate from the credential itself).
3152 *
3153 * Parameters: struct image_params * the image parameter block
3154 *
3155 * Returns: void No failure indication
3156 *
3157 * Implicit returns:
3158 * <process credential> Potentially modified/replaced
3159 * <task port> Potentially revoked
3160 * <process flags> P_SUGID bit potentially modified
3161 * <security token> Potentially modified
3162 */
3163static int
3164exec_handle_sugid(struct image_params *imgp)
3165{
3166 kauth_cred_t cred = vfs_context_ucred(imgp->ip_vfs_context);
2d21ac55 3167 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
91447636 3168 int i;
c910b4d9 3169 int leave_sugid_clear = 0;
91447636 3170 int error = 0;
2d21ac55
A
3171#if CONFIG_MACF
3172 int mac_transition;
c910b4d9
A
3173
3174 /*
3175 * Determine whether a call to update the MAC label will result in the
3176 * credential changing.
3177 *
3178 * Note: MAC policies which do not actually end up modifying
3179 * the label subsequently are strongly encouraged to
3180 * return 0 for this check, since a non-zero answer will
3181 * slow down the exec fast path for normal binaries.
3182 */
3183 mac_transition = mac_cred_check_label_update_execve(
3184 imgp->ip_vfs_context,
3185 imgp->ip_vp,
3186 imgp->ip_scriptlabelp,
3187 imgp->ip_execlabelp, p);
2d21ac55 3188#endif
1c79356b 3189
b0d623f7 3190 OSBitAndAtomic(~((uint32_t)P_SUGID), &p->p_flag);
91447636 3191
2d21ac55
A
3192 /*
3193 * Order of the following is important; group checks must go last,
c910b4d9 3194 * as we use the success of the 'ismember' check combined with the
2d21ac55
A
3195 * failure of the explicit match to indicate that we will be setting
3196 * the egid of the process even though the new process did not
3197 * require VSUID/VSGID bits in order for it to set the new group as
3198 * its egid.
3199 *
3200 * Note: Technically, by this we are implying a call to
3201 * setegid() in the new process, rather than implying
3202 * it used its VSGID bit to set the effective group,
3203 * even though there is no code in that process to make
3204 * such a call.
3205 */
91447636
A
3206 if (((imgp->ip_origvattr->va_mode & VSUID) != 0 &&
3207 kauth_cred_getuid(cred) != imgp->ip_origvattr->va_uid) ||
3208 ((imgp->ip_origvattr->va_mode & VSGID) != 0 &&
c910b4d9 3209 ((kauth_cred_ismember_gid(cred, imgp->ip_origvattr->va_gid, &leave_sugid_clear) || !leave_sugid_clear) ||
6d2010ae 3210 (kauth_cred_getgid(cred) != imgp->ip_origvattr->va_gid)))) {
2d21ac55 3211
c910b4d9
A
3212#if CONFIG_MACF
3213/* label for MAC transition and neither VSUID nor VSGID */
3214handle_mac_transition:
3215#endif
3216
1c79356b 3217 /*
2d21ac55
A
3218 * Replace the credential with a copy of itself if euid or
3219 * egid change.
3220 *
3221 * Note: setuid binaries will automatically opt out of
3222 * group resolver participation as a side effect
3223 * of this operation. This is an intentional
3224 * part of the security model, which requires a
3225 * participating credential be established by
3226 * escalating privilege, setting up all other
3227 * aspects of the credential including whether
3228 * or not to participate in external group
3229 * membership resolution, then dropping their
3230 * effective privilege to that of the desired
3231 * final credential state.
91447636
A
3232 */
3233 if (imgp->ip_origvattr->va_mode & VSUID) {
2d21ac55 3234 p->p_ucred = kauth_cred_setresuid(p->p_ucred, KAUTH_UID_NONE, imgp->ip_origvattr->va_uid, imgp->ip_origvattr->va_uid, KAUTH_UID_NONE);
6d2010ae
A
3235 /* update cred on proc */
3236 PROC_UPDATE_CREDS_ONPROC(p);
91447636
A
3237 }
3238 if (imgp->ip_origvattr->va_mode & VSGID) {
2d21ac55 3239 p->p_ucred = kauth_cred_setresgid(p->p_ucred, KAUTH_GID_NONE, imgp->ip_origvattr->va_gid, imgp->ip_origvattr->va_gid);
6d2010ae
A
3240 /* update cred on proc */
3241 PROC_UPDATE_CREDS_ONPROC(p);
91447636 3242 }
1c79356b 3243
2d21ac55
A
3244#if CONFIG_MACF
3245 /*
c910b4d9
A
3246 * If a policy has indicated that it will transition the label,
3247 * before making the call into the MAC policies, get a new
2d21ac55
A
3248 * duplicate credential, so they can modify it without
3249 * modifying any others sharing it.
3250 */
c910b4d9
A
3251 if (mac_transition) {
3252 kauth_cred_t my_cred;
3253 if (kauth_proc_label_update_execve(p,
3254 imgp->ip_vfs_context,
3255 imgp->ip_vp,
3256 imgp->ip_scriptlabelp,
3257 imgp->ip_execlabelp)) {
3258 /*
3259 * If updating the MAC label resulted in a
3260 * disjoint credential, flag that we need to
3261 * set the P_SUGID bit. This protects
3262 * against debuggers being attached by an
3263 * insufficiently privileged process onto the
3264 * result of a transition to a more privileged
3265 * credential.
3266 */
3267 leave_sugid_clear = 0;
3268 }
2d21ac55
A
3269
3270 my_cred = kauth_cred_proc_ref(p);
3271 mac_task_label_update_cred(my_cred, p->task);
3272 kauth_cred_unref(&my_cred);
3273 }
c910b4d9
A
3274#endif /* CONFIG_MACF */
3275
55e303ae 3276 /*
6601e61a
A
3277 * Have mach reset the task and thread ports.
3278 * We don't want anyone who had the ports before
3279 * a setuid exec to be able to access/control the
3280 * task/thread after.
55e303ae 3281 */
d1ecb069
A
3282 ipc_task_reset(p->task);
3283 ipc_thread_reset((imgp->ip_new_thread != NULL) ?
3284 imgp->ip_new_thread : current_thread());
55e303ae 3285
2d21ac55 3286 /*
c910b4d9
A
3287 * If 'leave_sugid_clear' is non-zero, then we passed the
3288 * VSUID and MACF checks, and successfully determined that
3289 * the previous cred was a member of the VSGID group, but
3290 * that it was not the default at the time of the execve,
3291 * and that the post-labelling credential was not disjoint.
3292 * So we don't set the P_SUGID on the basis of simply
3293 * running this code.
2d21ac55 3294 */
c910b4d9 3295 if (!leave_sugid_clear)
b0d623f7 3296 OSBitOrAtomic(P_SUGID, &p->p_flag);
1c79356b 3297
1c79356b 3298 /*
6d2010ae 3299 * Radar 2261856; setuid security hole fix
1c79356b
A
3300 * XXX For setuid processes, attempt to ensure that
3301 * stdin, stdout, and stderr are already allocated.
3302 * We do not want userland to accidentally allocate
3303 * descriptors in this range which has implied meaning
3304 * to libc.
3305 */
ebb1b9f4 3306 for (i = 0; i < 3; i++) {
91447636 3307
ebb1b9f4
A
3308 if (p->p_fd->fd_ofiles[i] != NULL)
3309 continue;
1c79356b 3310
ebb1b9f4
A
3311 /*
3312 * Do the kernel equivalent of
3313 *
3314 * (void) open("/dev/null", O_RDONLY);
3315 */
91447636 3316
ebb1b9f4
A
3317 struct fileproc *fp;
3318 int indx;
1c79356b 3319
ebb1b9f4
A
3320 if ((error = falloc(p,
3321 &fp, &indx, imgp->ip_vfs_context)) != 0)
3322 continue;
3323
3324 struct nameidata nd1;
3325
3326 NDINIT(&nd1, LOOKUP, OP_OPEN, FOLLOW, UIO_SYSSPACE,
3327 CAST_USER_ADDR_T("/dev/null"),
3328 imgp->ip_vfs_context);
3329
3330 if ((error = vn_open(&nd1, FREAD, 0)) != 0) {
3331 fp_free(p, indx, fp);
3332 break;
1c79356b 3333 }
ebb1b9f4
A
3334
3335 struct fileglob *fg = fp->f_fglob;
3336
3337 fg->fg_flag = FREAD;
3338 fg->fg_type = DTYPE_VNODE;
3339 fg->fg_ops = &vnops;
3340 fg->fg_data = nd1.ni_vp;
3341
3342 vnode_put(nd1.ni_vp);
3343
3344 proc_fdlock(p);
3345 procfdtbl_releasefd(p, indx, NULL);
3346 fp_drop(p, indx, fp, 1);
3347 proc_fdunlock(p);
1c79356b 3348 }
1c79356b 3349 }
c910b4d9
A
3350#if CONFIG_MACF
3351 else {
3352 /*
3353 * We are here because we were told that the MAC label will
3354 * be transitioned, and the binary is not VSUID or VSGID; to
3355 * deal with this case, we could either duplicate a lot of
3356 * code, or we can indicate we want to default the P_SUGID
3357 * bit clear and jump back up.
3358 */
3359 if (mac_transition) {
3360 leave_sugid_clear = 1;
3361 goto handle_mac_transition;
3362 }
3363 }
3364#endif /* CONFIG_MACF */
1c79356b
A
3365
3366 /*
91447636
A
3367 * Implement the semantic where the effective user and group become
3368 * the saved user and group in exec'ed programs.
1c79356b 3369 */
6d2010ae
A
3370 p->p_ucred = kauth_cred_setsvuidgid(p->p_ucred, kauth_cred_getuid(p->p_ucred), kauth_cred_getgid(p->p_ucred));
3371 /* update cred on proc */
3372 PROC_UPDATE_CREDS_ONPROC(p);
91447636 3373
593a1d5f
A
3374 /* Update the process' identity version and set the security token */
3375 p->p_idversion++;
91447636 3376 set_security_token(p);
0b4e3aa0 3377
1c79356b
A
3378 return(error);
3379}
3380
2d21ac55
A
3381
3382/*
3383 * create_unix_stack
3384 *
3385 * Description: Set the user stack address for the process to the provided
3386 * address. If a custom stack was not set as a result of the
3387 * load process (i.e. as specified by the image file for the
3388 * executable), then allocate the stack in the provided map and
3389 * set up appropriate guard pages for enforcing administrative
3390 * limits on stack growth, if they end up being needed.
3391 *
3392 * Parameters: p Process to set stack on
3393 * user_stack Address to set stack for process to
3394 * customstack FALSE if no custom stack in binary
3395 * map Address map in which to allocate the
3396 * new stack, if 'customstack' is FALSE
3397 *
3398 * Returns: KERN_SUCCESS Stack successfully created
3399 * !KERN_SUCCESS Mach failure code
3400 */
91447636
A
3401static kern_return_t
3402create_unix_stack(vm_map_t map, user_addr_t user_stack, int customstack,
2d21ac55 3403 proc_t p)
1c79356b 3404{
2d21ac55
A
3405 mach_vm_size_t size, prot_size;
3406 mach_vm_offset_t addr, prot_addr;
3407 kern_return_t kr;
1c79356b 3408
2d21ac55 3409 proc_lock(p);
91447636 3410 p->user_stack = user_stack;
2d21ac55
A
3411 proc_unlock(p);
3412
0b4e3aa0 3413 if (!customstack) {
2d21ac55
A
3414 /*
3415 * Allocate enough space for the maximum stack size we
3416 * will ever authorize and an extra page to act as
3417 * a guard page for stack overflows.
3418 */
3419 size = mach_vm_round_page(MAXSSIZ);
3420#if STACK_GROWTH_UP
3421 addr = mach_vm_trunc_page(user_stack);
3422#else /* STACK_GROWTH_UP */
91447636 3423 addr = mach_vm_trunc_page(user_stack - size);
2d21ac55
A
3424#endif /* STACK_GROWTH_UP */
3425 kr = mach_vm_allocate(map, &addr, size,
91447636 3426 VM_MAKE_TAG(VM_MEMORY_STACK) |
2d21ac55
A
3427 VM_FLAGS_FIXED);
3428 if (kr != KERN_SUCCESS) {
3429 return kr;
3430 }
3431 /*
3432 * And prevent access to what's above the current stack
3433 * size limit for this process.
3434 */
3435 prot_addr = addr;
3436#if STACK_GROWTH_UP
3437 prot_addr += unix_stack_size(p);
3438#endif /* STACK_GROWTH_UP */
3439 prot_addr = mach_vm_round_page(prot_addr);
3440 prot_size = mach_vm_trunc_page(size - unix_stack_size(p));
3441 kr = mach_vm_protect(map,
3442 prot_addr,
3443 prot_size,
3444 FALSE,
3445 VM_PROT_NONE);
3446 if (kr != KERN_SUCCESS) {
3447 (void) mach_vm_deallocate(map, addr, size);
3448 return kr;
3449 }
3450 }
3451 return KERN_SUCCESS;
1c79356b
A
3452}
3453
3454#include <sys/reboot.h>
3455
91447636 3456static char init_program_name[128] = "/sbin/launchd";
1c79356b
A
3457
3458struct execve_args init_exec_args;
1c79356b 3459
2d21ac55
A
3460/*
3461 * load_init_program
3462 *
3463 * Description: Load the "init" program; in most cases, this will be "launchd"
3464 *
3465 * Parameters: p Process to call execve() to create
3466 * the "init" program
3467 *
3468 * Returns: (void)
3469 *
3470 * Notes: The process that is passed in is the first manufactured
3471 * process on the system, and gets here via bsd_ast() firing
3472 * for the first time. This is done to ensure that bsd_init()
3473 * has run to completion.
3474 */
1c79356b 3475void
2d21ac55 3476load_init_program(proc_t p)
1c79356b
A
3477{
3478 vm_offset_t init_addr;
2d21ac55 3479 int argc = 0;
b0d623f7 3480 uint32_t argv[3];
91447636 3481 int error;
b0d623f7 3482 int retval[2];
1c79356b 3483
2d21ac55
A
3484 /*
3485 * Copy out program name.
3486 */
1c79356b 3487
2d21ac55
A
3488 init_addr = VM_MIN_ADDRESS;
3489 (void) vm_allocate(current_map(), &init_addr, PAGE_SIZE,
3490 VM_FLAGS_ANYWHERE);
3491 if (init_addr == 0)
3492 init_addr++;
91447636 3493
2d21ac55
A
3494 (void) copyout((caddr_t) init_program_name, CAST_USER_ADDR_T(init_addr),
3495 (unsigned) sizeof(init_program_name)+1);
1c79356b 3496
b0d623f7 3497 argv[argc++] = (uint32_t)init_addr;
2d21ac55
A
3498 init_addr += sizeof(init_program_name);
3499 init_addr = (vm_offset_t)ROUND_PTR(char, init_addr);
1c79356b 3500
2d21ac55
A
3501 /*
3502 * Put out first (and only) argument, similarly.
3503 * Assumes everything fits in a page as allocated
3504 * above.
3505 */
3506 if (boothowto & RB_SINGLE) {
3507 const char *init_args = "-s";
1c79356b 3508
2d21ac55
A
3509 copyout(init_args, CAST_USER_ADDR_T(init_addr),
3510 strlen(init_args));
1c79356b 3511
b0d623f7 3512 argv[argc++] = (uint32_t)init_addr;
2d21ac55 3513 init_addr += strlen(init_args);
1c79356b
A
3514 init_addr = (vm_offset_t)ROUND_PTR(char, init_addr);
3515
2d21ac55 3516 }
1c79356b 3517
2d21ac55
A
3518 /*
3519 * Null-end the argument list
3520 */
b0d623f7 3521 argv[argc] = 0;
2d21ac55
A
3522
3523 /*
3524 * Copy out the argument list.
3525 */
3526
3527 (void) copyout((caddr_t) argv, CAST_USER_ADDR_T(init_addr),
3528 (unsigned) sizeof(argv));
1c79356b 3529
2d21ac55
A
3530 /*
3531 * Set up argument block for fake call to execve.
3532 */
1c79356b 3533
2d21ac55
A
3534 init_exec_args.fname = CAST_USER_ADDR_T(argv[0]);
3535 init_exec_args.argp = CAST_USER_ADDR_T((char **)init_addr);
3536 init_exec_args.envp = CAST_USER_ADDR_T(0);
3537
3538 /*
3539 * So that mach_init task is set with uid,gid 0 token
3540 */
3541 set_security_token(p);
1c79356b 3542
2d21ac55
A
3543 error = execve(p,&init_exec_args,retval);
3544 if (error)
6d2010ae 3545 panic("Process 1 exec of %s failed, errno %d",
2d21ac55 3546 init_program_name, error);
1c79356b
A
3547}
3548
3549/*
2d21ac55
A
3550 * load_return_to_errno
3551 *
3552 * Description: Convert a load_return_t (Mach error) to an errno (BSD error)
3553 *
3554 * Parameters: lrtn Mach error number
3555 *
3556 * Returns: (int) BSD error number
3557 * 0 Success
3558 * EBADARCH Bad architecture
3559 * EBADMACHO Bad Mach object file
3560 * ESHLIBVERS Bad shared library version
3561 * ENOMEM Out of memory/resource shortage
3562 * EACCES Access denied
3563 * ENOENT Entry not found (usually "file does
3564 * does not exist")
3565 * EIO An I/O error occurred
3566 * EBADEXEC The executable is corrupt/unknown
1c79356b
A
3567 */
3568static int
3569load_return_to_errno(load_return_t lrtn)
3570{
3571 switch (lrtn) {
2d21ac55
A
3572 case LOAD_SUCCESS:
3573 return 0;
3574 case LOAD_BADARCH:
3575 return EBADARCH;
3576 case LOAD_BADMACHO:
3577 return EBADMACHO;
3578 case LOAD_SHLIB:
3579 return ESHLIBVERS;
3580 case LOAD_NOSPACE:
3581 case LOAD_RESOURCE:
3582 return ENOMEM;
3583 case LOAD_PROTECT:
3584 return EACCES;
3585 case LOAD_ENOENT:
3586 return ENOENT;
3587 case LOAD_IOERROR:
3588 return EIO;
3589 case LOAD_FAILURE:
3590 default:
3591 return EBADEXEC;
1c79356b
A
3592 }
3593}
3594
765c9de3
A
3595#include <mach/mach_types.h>
3596#include <mach/vm_prot.h>
3597#include <mach/semaphore.h>
3598#include <mach/sync_policy.h>
3599#include <kern/clock.h>
3600#include <mach/kern_return.h>
3601
91447636 3602/*
2d21ac55
A
3603 * execargs_alloc
3604 *
3605 * Description: Allocate the block of memory used by the execve arguments.
3606 * At the same time, we allocate a page so that we can read in
3607 * the first page of the image.
3608 *
3609 * Parameters: struct image_params * the image parameter block
3610 *
3611 * Returns: 0 Success
3612 * EINVAL Invalid argument
3613 * EACCES Permission denied
3614 * EINTR Interrupted function
3615 * ENOMEM Not enough space
3616 *
3617 * Notes: This is a temporary allocation into the kernel address space
3618 * to enable us to copy arguments in from user space. This is
3619 * necessitated by not mapping the process calling execve() into
3620 * the kernel address space during the execve() system call.
3621 *
3622 * We assemble the argument and environment, etc., into this
3623 * region before copying it as a single block into the child
3624 * process address space (at the top or bottom of the stack,
3625 * depending on which way the stack grows; see the function
3626 * exec_copyout_strings() for details).
3627 *
3628 * This ends up with a second (possibly unnecessary) copy compared
3629 * with assembing the data directly into the child address space,
3630 * instead, but since we cannot be guaranteed that the parent has
3631 * not modified its environment, we can't really know that it's
3632 * really a block there as well.
91447636 3633 */
b0d623f7
A
3634
3635
3636static int execargs_waiters = 0;
3637lck_mtx_t *execargs_cache_lock;
3638
3639static void
3640execargs_lock_lock(void) {
3641 lck_mtx_lock_spin(execargs_cache_lock);
3642}
3643
3644static void
3645execargs_lock_unlock(void) {
3646 lck_mtx_unlock(execargs_cache_lock);
3647}
3648
3649static void
3650execargs_lock_sleep(void) {
3651 lck_mtx_sleep(execargs_cache_lock, LCK_SLEEP_DEFAULT, &execargs_free_count, THREAD_UNINT);
3652}
3653
3654static kern_return_t
3655execargs_purgeable_allocate(char **execarg_address) {
6d2010ae 3656 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);
b0d623f7
A
3657 assert(kr == KERN_SUCCESS);
3658 return kr;
3659}
3660
3661static kern_return_t
3662execargs_purgeable_reference(void *execarg_address) {
3663 int state = VM_PURGABLE_NONVOLATILE;
3664 kern_return_t kr = vm_purgable_control(bsd_pageable_map, (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state);
3665
3666 assert(kr == KERN_SUCCESS);
3667 return kr;
3668}
3669
3670static kern_return_t
3671execargs_purgeable_volatilize(void *execarg_address) {
3672 int state = VM_PURGABLE_VOLATILE | VM_PURGABLE_ORDERING_OBSOLETE;
3673 kern_return_t kr;
3674 kr = vm_purgable_control(bsd_pageable_map, (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state);
3675
3676 assert(kr == KERN_SUCCESS);
3677
3678 return kr;
3679}
3680
3681static void
3682execargs_wakeup_waiters(void) {
3683 thread_wakeup(&execargs_free_count);
3684}
3685
765c9de3 3686static int
91447636 3687execargs_alloc(struct image_params *imgp)
765c9de3
A
3688{
3689 kern_return_t kret;
b0d623f7 3690 int i, cache_index = -1;
765c9de3 3691
b0d623f7
A
3692 execargs_lock_lock();
3693
3694 while (execargs_free_count == 0) {
3695 execargs_waiters++;
3696 execargs_lock_sleep();
3697 execargs_waiters--;
3698 }
3699
3700 execargs_free_count--;
3701
3702 for (i = 0; i < execargs_cache_size; i++) {
3703 vm_offset_t element = execargs_cache[i];
3704 if (element) {
3705 cache_index = i;
3706 imgp->ip_strings = (char *)(execargs_cache[i]);
3707 execargs_cache[i] = 0;
3708 break;
765c9de3 3709 }
b0d623f7 3710 }
765c9de3 3711
b0d623f7
A
3712 assert(execargs_free_count >= 0);
3713
3714 execargs_lock_unlock();
3715
3716 if (cache_index == -1) {
3717 kret = execargs_purgeable_allocate(&imgp->ip_strings);
3718 }
3719 else
3720 kret = execargs_purgeable_reference(imgp->ip_strings);
3721
3722 assert(kret == KERN_SUCCESS);
55e303ae 3723 if (kret != KERN_SUCCESS) {
765c9de3 3724 return (ENOMEM);
55e303ae 3725 }
b0d623f7 3726
6d2010ae
A
3727 /* last page used to read in file headers */
3728 imgp->ip_vdata = imgp->ip_strings + ( NCARGS + PAGE_SIZE );
3729 imgp->ip_strendp = imgp->ip_strings;
3730 imgp->ip_argspace = NCARGS;
3731 imgp->ip_strspace = ( NCARGS + PAGE_SIZE );
b0d623f7 3732
765c9de3
A
3733 return (0);
3734}
3735
2d21ac55
A
3736/*
3737 * execargs_free
3738 *
3739 * Description: Free the block of memory used by the execve arguments and the
3740 * first page of the executable by a previous call to the function
3741 * execargs_alloc().
3742 *
3743 * Parameters: struct image_params * the image parameter block
3744 *
3745 * Returns: 0 Success
3746 * EINVAL Invalid argument
3747 * EINTR Oeration interrupted
3748 */
765c9de3 3749static int
91447636 3750execargs_free(struct image_params *imgp)
765c9de3
A
3751{
3752 kern_return_t kret;
b0d623f7
A
3753 int i;
3754 boolean_t needs_wakeup = FALSE;
3755
3756 kret = execargs_purgeable_volatilize(imgp->ip_strings);
765c9de3 3757
b0d623f7
A
3758 execargs_lock_lock();
3759 execargs_free_count++;
3760
3761 for (i = 0; i < execargs_cache_size; i++) {
3762 vm_offset_t element = execargs_cache[i];
3763 if (element == 0) {
3764 execargs_cache[i] = (vm_offset_t) imgp->ip_strings;
3765 imgp->ip_strings = NULL;
3766 break;
3767 }
765c9de3 3768 }
b0d623f7
A
3769
3770 assert(imgp->ip_strings == NULL);
3771
3772 if (execargs_waiters > 0)
3773 needs_wakeup = TRUE;
3774
3775 execargs_lock_unlock();
3776
3777 if (needs_wakeup == TRUE)
3778 execargs_wakeup_waiters();
3779
3780 return ((kret == KERN_SUCCESS ? 0 : EINVAL));
765c9de3 3781}
2d21ac55
A
3782
3783static void
3784exec_resettextvp(proc_t p, struct image_params *imgp)
3785{
3786 vnode_t vp;
3787 off_t offset;
3788 vnode_t tvp = p->p_textvp;
3789 int ret;
3790
3791 vp = imgp->ip_vp;
3792 offset = imgp->ip_arch_offset;
3793
3794 if (vp == NULLVP)
3795 panic("exec_resettextvp: expected valid vp");
3796
3797 ret = vnode_ref(vp);
3798 proc_lock(p);
3799 if (ret == 0) {
3800 p->p_textvp = vp;
3801 p->p_textoff = offset;
3802 } else {
3803 p->p_textvp = NULLVP; /* this is paranoia */
3804 p->p_textoff = 0;
3805 }
3806 proc_unlock(p);
3807
3808 if ( tvp != NULLVP) {
3809 if (vnode_getwithref(tvp) == 0) {
3810 vnode_rele(tvp);
3811 vnode_put(tvp);
3812 }
3813 }
3814
3815}
3816
b0d623f7
A
3817static int
3818check_for_signature(proc_t p, struct image_params *imgp)
3819{
6d2010ae
A
3820 void *blob = NULL;
3821 size_t length = 0;
b0d623f7 3822 mach_port_t port = NULL;
6d2010ae
A
3823 kern_return_t kr = KERN_FAILURE;
3824 int error = EACCES;
b0d623f7
A
3825 unsigned char hash[SHA1_RESULTLEN];
3826
3827 /*
3828 * Override inherited code signing flags with the
3829 * ones for the process that is being successfully
3830 * loaded
3831 */
3832 proc_lock(p);
3833 p->p_csflags = imgp->ip_csflags;
3834 proc_unlock(p);
3835
3836 /* Set the switch_protect flag on the map */
3837 if(p->p_csflags & (CS_HARD|CS_KILL)) {
3838 vm_map_switch_protect(get_task_map(p->task), TRUE);
3839 }
3840
6d2010ae
A
3841 /* If the process is not signed or if it contains
3842 * entitlements, we need to communicate through the
3843 * task_access_port to taskgated. taskgated will provide a
3844 * detached code signature if present, and will enforce any
3845 * restrictions on entitlements. taskgated returns
3846 * KERN_SUCCESS if it has completed its work and the exec
3847 * should continue, or KERN_FAILURE if the exec should fail.
3848 */
3849 error = cs_entitlements_blob_get(p, &blob, &length);
b0d623f7 3850
6d2010ae
A
3851 /* if signed and no entitlements, then we're done here */
3852 if ((p->p_csflags & CS_VALID) && NULL == blob) {
3853 error = 0;
3854 goto done;
3855 }
3856
3857 kr = task_get_task_access_port(p->task, &port);
3858 if (KERN_SUCCESS != kr || !IPC_PORT_VALID(port)) {
3859 error = 0;
3860#if !CONFIG_EMBEDDED
3861 /* fatal on the desktop when entitlements are present */
3862 if (NULL != blob)
3863 error = EACCES;
3864#endif
3865 goto done;
3866 }
3867
3868 kr = find_code_signature(port, p->p_pid);
3869 if (KERN_SUCCESS != kr) {
3870 error = EACCES;
3871 goto done;
3872 }
3873
3874 /* Only do this if exec_resettextvp() did not fail */
3875 if (p->p_textvp != NULLVP) {
3876 /*
3877 * If there's a new code directory, mark this process
3878 * as signed.
3879 */
3880 if (0 == ubc_cs_getcdhash(p->p_textvp, p->p_textoff, hash)) {
3881 proc_lock(p);
3882 p->p_csflags |= CS_VALID;
3883 proc_unlock(p);
b0d623f7
A
3884 }
3885 }
3886
6d2010ae
A
3887done:
3888 if (0 != error)
3889 /* make very sure execution fails */
3890 psignal(p, SIGKILL);
3891 return error;
b0d623f7
A
3892}
3893