]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kern_exec.c
e0dc45aa7dad616af6de755477a2cc8e41d05b78
[apple/xnu.git] / bsd / kern / kern_exec.c
1 /*
2 * Copyright (c) 2000-2004 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
24 /*
25 * Mach Operating System
26 * Copyright (c) 1987 Carnegie-Mellon University
27 * All rights reserved. The CMU software License Agreement specifies
28 * the terms and conditions for use and redistribution.
29 */
30
31 #include <cputypes.h>
32
33 /*-
34 * Copyright (c) 1982, 1986, 1991, 1993
35 * The Regents of the University of California. All rights reserved.
36 * (c) UNIX System Laboratories, Inc.
37 * All or some portions of this file are derived from material licensed
38 * to the University of California by American Telephone and Telegraph
39 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
40 * the permission of UNIX System Laboratories, Inc.
41 *
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement:
52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission.
57 *
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
69 *
70 * from: @(#)kern_exec.c 8.1 (Berkeley) 6/10/93
71 */
72 #include <machine/reg.h>
73
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/filedesc.h>
77 #include <sys/kernel.h>
78 #include <sys/proc_internal.h>
79 #include <sys/kauth.h>
80 #include <sys/user.h>
81 #include <sys/socketvar.h>
82 #include <sys/malloc.h>
83 #include <sys/namei.h>
84 #include <sys/mount_internal.h>
85 #include <sys/vnode_internal.h>
86 #include <sys/file_internal.h>
87 #include <sys/stat.h>
88 #include <sys/uio_internal.h>
89 #include <sys/acct.h>
90 #include <sys/exec.h>
91 #include <sys/kdebug.h>
92 #include <sys/signal.h>
93 #include <sys/aio_kern.h>
94 #include <sys/sysproto.h>
95 #include <sys/shm_internal.h> /* shmexec() */
96 #include <sys/ubc_internal.h> /* ubc_map() */
97
98 #include <bsm/audit_kernel.h>
99
100 #include <mach/mach_types.h>
101 #include <mach/task.h>
102 #include <mach/thread_act.h>
103 #include <mach/vm_map.h>
104 #include <mach/mach_vm.h>
105 #include <mach/vm_param.h>
106
107 #include <vm/vm_map.h>
108 #include <vm/vm_kern.h>
109 #include <vm/vm_pager.h>
110 #include <vm/vm_kern.h>
111 #include <vm/task_working_set.h>
112 #include <vm/vm_shared_memory_server.h>
113
114 /*
115 * Mach things for which prototypes are unavailable from Mach headers
116 */
117 void ipc_task_reset(
118 task_t task);
119
120 extern struct savearea *get_user_regs(thread_t);
121
122
123 #include <kern/thread.h>
124 #include <kern/task.h>
125 #include <kern/ast.h>
126 #include <kern/mach_loader.h>
127 #include <mach-o/fat.h>
128 #include <mach-o/loader.h>
129 #include <machine/vmparam.h>
130 #if KTRACE
131 #include <sys/ktrace.h>
132 #endif
133 #include <sys/imgact.h>
134
135
136 /*
137 * SIZE_MAXPTR The maximum size of a user space pointer, in bytes
138 * SIZE_IMG_STRSPACE The available string space, minus two pointers; we
139 * define it interms of the maximum, since we don't
140 * know the pointer size going in, until after we've
141 * parsed the executable image.
142 */
143 #define SIZE_MAXPTR 8 /* 64 bits */
144 #define SIZE_IMG_STRSPACE (NCARGS - 2 * SIZE_MAXPTR)
145
146 int app_profile = 0;
147
148 extern vm_map_t bsd_pageable_map;
149 extern struct fileops vnops;
150
151 #define ROUND_PTR(type, addr) \
152 (type *)( ( (unsigned)(addr) + 16 - 1) \
153 & ~(16 - 1) )
154
155 struct image_params; /* Forward */
156 static int exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp);
157 static int load_return_to_errno(load_return_t lrtn);
158 static int execargs_alloc(struct image_params *imgp);
159 static int execargs_free(struct image_params *imgp);
160 static int exec_check_permissions(struct image_params *imgp);
161 static int exec_extract_strings(struct image_params *imgp);
162 static int exec_handle_sugid(struct image_params *imgp);
163 static int sugid_scripts = 0;
164 SYSCTL_INT (_kern, OID_AUTO, sugid_scripts, CTLFLAG_RW, &sugid_scripts, 0, "");
165 static kern_return_t create_unix_stack(vm_map_t map, user_addr_t user_stack,
166 int customstack, struct proc *p);
167 static int copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size);
168
169 /* XXX forward; should be in headers, but can't be for one reason or another */
170 extern int grade_binary(cpu_type_t exectype, cpu_subtype_t execsubtype);
171 extern void vfork_return(thread_t th_act,
172 struct proc * p,
173 struct proc *p2,
174 register_t *retval);
175
176
177 extern char classichandler[32];
178 extern uint32_t classichandler_fsid;
179 extern long classichandler_fileid;
180
181
182 /*
183 * exec_add_string
184 *
185 * Add the requested string to the string space area.
186 *
187 * Parameters; struct image_params * image parameter block
188 * user_addr_t string to add to strings area
189 * uio_seg segment where string is located
190 *
191 * Returns: 0 Success
192 * !0 Failure errno from copyinstr()
193 *
194 * Implicit returns:
195 * (imgp->ip_strendp) updated location of next add, if any
196 * (imgp->ip_strspace) updated byte count of space remaining
197 */
198 static int
199 exec_add_string(struct image_params *imgp, user_addr_t str, /*uio_seg*/int seg)
200 {
201 int error = 0;
202
203 do {
204 size_t len = 0;
205 if (imgp->ip_strspace <= 0) {
206 error = E2BIG;
207 break;
208 }
209 if (IS_UIO_SYS_SPACE(seg)) {
210 char *kstr = CAST_DOWN(char *,str); /* SAFE */
211 error = copystr(kstr, imgp->ip_strendp, imgp->ip_strspace, &len);
212 } else {
213 error = copyinstr(str, imgp->ip_strendp, imgp->ip_strspace,
214 &len);
215 }
216 imgp->ip_strendp += len;
217 imgp->ip_strspace -= len;
218 } while (error == ENAMETOOLONG);
219
220 return error;
221 }
222
223 /*
224 * exec_save_path
225 *
226 * To support new app package launching for Mac OS X, the dyld needs the
227 * first argument to execve() stored on the user stack.
228 *
229 * Save the executable path name at the top of the strings area and set
230 * the argument vector pointer to the location following that to indicate
231 * the start of the argument and environment tuples, setting the remaining
232 * string space count to the size of the string area minus the path length
233 * and a reserve for two pointers.
234 *
235 * Parameters; struct image_params * image parameter block
236 * char * path used to invoke program
237 * uio_seg segment where path is located
238 *
239 * Returns: int 0 Success
240 * !0 Failure: error number
241 * Implicit returns:
242 * (imgp->ip_strings) saved path
243 * (imgp->ip_strspace) space remaining in ip_strings
244 * (imgp->ip_argv) beginning of argument list
245 * (imgp->ip_strendp) start of remaining copy area
246 *
247 * Note: We have to do this before the initial namei() since in the
248 * path contains symbolic links, namei() will overwrite the
249 * original path buffer contents. If the last symbolic link
250 * resolved was a relative pathname, we would lose the original
251 * "path", which could be an absolute pathname. This might be
252 * unacceptable for dyld.
253 */
254 static int
255 exec_save_path(struct image_params *imgp, user_addr_t path, /*uio_seg*/int seg)
256 {
257 int error;
258 size_t len;
259 char *kpath = CAST_DOWN(char *,path); /* SAFE */
260
261 imgp->ip_strendp = imgp->ip_strings;
262 imgp->ip_strspace = SIZE_IMG_STRSPACE;
263
264 len = MIN(MAXPATHLEN, imgp->ip_strspace);
265
266 switch( seg) {
267 case UIO_USERSPACE32:
268 case UIO_USERSPACE64: /* Same for copyin()... */
269 error = copyinstr(path, imgp->ip_strings, len, &len);
270 break;
271 case UIO_SYSSPACE32:
272 error = copystr(kpath, imgp->ip_strings, len, &len);
273 break;
274 default:
275 error = EFAULT;
276 break;
277 }
278
279 if (!error) {
280 imgp->ip_strendp += len;
281 imgp->ip_strspace -= len;
282 imgp->ip_argv = imgp->ip_strendp;
283 }
284
285 return(error);
286 }
287
288
289
290 /*
291 * exec_shell_imgact
292 *
293 * Image activator for interpreter scripts. If the image begins with the
294 * characters "#!", then it is an interpreter script. Verify that we are
295 * not already executing in Classic mode, and that the length of the script
296 * line indicating the interpreter is not in excess of the maximum allowed
297 * size. If this is the case, then break out the arguments, if any, which
298 * are separated by white space, and copy them into the argument save area
299 * as if they were provided on the command line before all other arguments.
300 * The line ends when we encounter a comment character ('#') or newline.
301 *
302 * Parameters; struct image_params * image parameter block
303 *
304 * Returns: -1 not an interpreter (keep looking)
305 * -3 Success: interpreter: relookup
306 * >0 Failure: interpreter: error number
307 *
308 * A return value other than -1 indicates subsequent image activators should
309 * not be given the opportunity to attempt to activate the image.
310 */
311 static int
312 exec_shell_imgact(struct image_params *imgp)
313 {
314 char *vdata = imgp->ip_vdata;
315 char *ihp;
316 char *line_endp;
317 char *interp;
318
319 /*
320 * Make sure it's a shell script. If we've already redirected
321 * from an interpreted file once, don't do it again.
322 *
323 * Note: We disallow Classic, since the expectation is that we
324 * may run a Classic interpreter, but not an interpret a Classic
325 * image. This is consistent with historical behaviour.
326 */
327 if (vdata[0] != '#' ||
328 vdata[1] != '!' ||
329 (imgp->ip_flags & IMGPF_INTERPRET) != 0) {
330 return (-1);
331 }
332
333
334 imgp->ip_flags |= IMGPF_INTERPRET;
335
336 /* Check to see if SUGID scripts are permitted. If they aren't then
337 * clear the SUGID bits.
338 * imgp->ip_vattr is known to be valid.
339 */
340 if (sugid_scripts == 0) {
341 imgp->ip_origvattr->va_mode &= ~(VSUID | VSGID);
342 }
343
344 /* Find the nominal end of the interpreter line */
345 for( ihp = &vdata[2]; *ihp != '\n' && *ihp != '#'; ihp++) {
346 if (ihp >= &vdata[IMG_SHSIZE])
347 return (ENOEXEC);
348 }
349
350 line_endp = ihp;
351 ihp = &vdata[2];
352 /* Skip over leading spaces - until the interpreter name */
353 while ( ihp < line_endp && ((*ihp == ' ') || (*ihp == '\t')))
354 ihp++;
355
356 /*
357 * Find the last non-whitespace character before the end of line or
358 * the beginning of a comment; this is our new end of line.
359 */
360 for (;line_endp > ihp && ((*line_endp == ' ') || (*line_endp == '\t')); line_endp--)
361 continue;
362
363 /* Empty? */
364 if (line_endp == ihp)
365 return (ENOEXEC);
366
367 /* copy the interpreter name */
368 interp = imgp->ip_interp_name;
369 while ((ihp < line_endp) && (*ihp != ' ') && (*ihp != '\t'))
370 *interp++ = *ihp++;
371 *interp = '\0';
372
373 exec_save_path(imgp, CAST_USER_ADDR_T(imgp->ip_interp_name),
374 UIO_SYSSPACE32);
375
376 ihp = &vdata[2];
377 while (ihp < line_endp) {
378 /* Skip leading whitespace before each argument */
379 while ((*ihp == ' ') || (*ihp == '\t'))
380 ihp++;
381
382 if (ihp >= line_endp)
383 break;
384
385 /* We have an argument; copy it */
386 while ((ihp < line_endp) && (*ihp != ' ') && (*ihp != '\t')) {
387 *imgp->ip_strendp++ = *ihp++;
388 imgp->ip_strspace--;
389 }
390 *imgp->ip_strendp++ = 0;
391 imgp->ip_strspace--;
392 imgp->ip_argc++;
393 }
394
395 return (-3);
396 }
397
398
399
400 /*
401 * exec_fat_imgact
402 *
403 * Image activator for fat 1.0 binaries. If the binary is fat, then we
404 * need to select an image from it internally, and make that the image
405 * we are going to attempt to execute. At present, this consists of
406 * reloading the first page for the image with a first page from the
407 * offset location indicated by the fat header.
408 *
409 * Important: This image activator is byte order neutral.
410 *
411 * Note: If we find an encapsulated binary, we make no assertions
412 * about its validity; instead, we leave that up to a rescan
413 * for an activator to claim it, and, if it is claimed by one,
414 * that activator is responsible for determining validity.
415 */
416 static int
417 exec_fat_imgact(struct image_params *imgp)
418 {
419 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
420 kauth_cred_t cred = p->p_ucred;
421 struct fat_header *fat_header = (struct fat_header *)imgp->ip_vdata;
422 struct fat_arch fat_arch;
423 int resid, error;
424 load_return_t lret;
425
426 /* Make sure it's a fat binary */
427 if ((fat_header->magic != FAT_MAGIC) &&
428 (fat_header->magic != FAT_CIGAM)) {
429 error = -1;
430 goto bad;
431 }
432
433 /* Look up our preferred architecture in the fat file. */
434 lret = fatfile_getarch_affinity(imgp->ip_vp,
435 (vm_offset_t)fat_header,
436 &fat_arch,
437 (p->p_flag & P_AFFINITY));
438 if (lret != LOAD_SUCCESS) {
439 error = load_return_to_errno(lret);
440 goto bad;
441 }
442
443 /* Read the Mach-O header out of it */
444 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata,
445 PAGE_SIZE, fat_arch.offset,
446 UIO_SYSSPACE32, (IO_UNIT|IO_NODELOCKED),
447 cred, &resid, p);
448 if (error) {
449 goto bad;
450 }
451
452 /* Did we read a complete header? */
453 if (resid) {
454 error = EBADEXEC;
455 goto bad;
456 }
457
458 /* Success. Indicate we have identified an encapsulated binary */
459 error = -2;
460 imgp->ip_arch_offset = (user_size_t)fat_arch.offset;
461 imgp->ip_arch_size = (user_size_t)fat_arch.size;
462
463 bad:
464 return (error);
465 }
466
467 /*
468 * exec_mach_imgact
469 *
470 * Image activator for mach-o 1.0 binaries.
471 *
472 * Important: This image activator is NOT byte order neutral.
473 */
474 static int
475 exec_mach_imgact(struct image_params *imgp)
476 {
477 struct mach_header *mach_header = (struct mach_header *)imgp->ip_vdata;
478 kauth_cred_t cred = vfs_context_ucred(imgp->ip_vfs_context);
479 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
480 int error = 0;
481 int vfexec = 0;
482 task_t task;
483 task_t new_task;
484 thread_t thread;
485 struct uthread *uthread;
486 vm_map_t old_map = VM_MAP_NULL;
487 vm_map_t map;
488 boolean_t clean_regions = FALSE;
489 shared_region_mapping_t initial_region = NULL;
490 load_return_t lret;
491 load_result_t load_result;
492
493 /*
494 * make sure it's a Mach-O 1.0 or Mach-O 2.0 binary; the difference
495 * is a reserved field on the end, so for the most part, we can
496 * treat them as if they were identical.
497 */
498 if ((mach_header->magic != MH_MAGIC) &&
499 (mach_header->magic != MH_MAGIC_64)) {
500 error = -1;
501 goto bad;
502 }
503
504 task = current_task();
505 thread = current_thread();
506 uthread = get_bsdthread_info(thread);
507
508 if (uthread->uu_flag & UT_VFORK)
509 vfexec = 1; /* Mark in exec */
510
511 if ((mach_header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64)
512 imgp->ip_flags |= IMGPF_IS_64BIT;
513
514 if (!grade_binary(mach_header->cputype, mach_header->cpusubtype)) {
515 error = EBADARCH;
516 goto bad;
517 }
518
519 /*
520 * Copy in arguments/environment from the old process, if the
521 * vector is non-NULL (i.e. exec is not being called from
522 * load_init_program(), as a special case, at system startup).
523 */
524 if (imgp->ip_user_argv != 0LL) {
525 error = exec_extract_strings(imgp);
526 if (error)
527 goto bad;
528 }
529
530 /*
531 * Hack for binary compatability; put three NULs on the end of the
532 * string area, and round it up to the next word boundary. This
533 * ensures padding with NULs to the boundary.
534 */
535 imgp->ip_strendp[0] = 0;
536 imgp->ip_strendp[1] = 0;
537 imgp->ip_strendp[2] = 0;
538 imgp->ip_strendp += (((imgp->ip_strendp - imgp->ip_strings) + NBPW-1) & ~(NBPW-1));
539
540
541 if (vfexec) {
542 kern_return_t result;
543
544 result = task_create_internal(task, FALSE, &new_task);
545 if (result != KERN_SUCCESS)
546 printf("execve: task_create failed. Code: 0x%x\n", result);
547 p->task = new_task;
548 set_bsdtask_info(new_task, p);
549 if (p->p_nice != 0)
550 resetpriority(p);
551 map = get_task_map(new_task);
552 result = thread_create(new_task, &imgp->ip_vfork_thread);
553 if (result != KERN_SUCCESS)
554 printf("execve: thread_create failed. Code: 0x%x\n", result);
555 /* reset local idea of task, thread, uthread */
556 task = new_task;
557 thread = imgp->ip_vfork_thread;
558 uthread = get_bsdthread_info(thread);
559 } else {
560 map = VM_MAP_NULL;
561 }
562
563 /*
564 * We set these flags here; this is OK, since if we fail after
565 * this point, we have already destroyed the parent process anyway.
566 */
567 if (imgp->ip_flags & IMGPF_IS_64BIT) {
568 task_set_64bit(task, TRUE);
569 p->p_flag |= P_LP64;
570 } else {
571 task_set_64bit(task, FALSE);
572 p->p_flag &= ~P_LP64;
573 }
574
575 /*
576 * Load the Mach-O file.
577 */
578 /* LP64 - remove following "if" statement after osfmk/vm/task_working_set.c */
579 if((imgp->ip_flags & IMGPF_IS_64BIT) == 0)
580 if(imgp->ip_tws_cache_name) {
581 tws_handle_startup_file(task, kauth_cred_getuid(cred),
582 imgp->ip_tws_cache_name, imgp->ip_vp, &clean_regions);
583 }
584
585 vm_get_shared_region(task, &initial_region);
586
587
588 /*
589 * NOTE: An error after this point indicates we have potentially
590 * destroyed or overwrote some process state while attempting an
591 * execve() following a vfork(), which is an unrecoverable condition.
592 */
593
594 /*
595 * We reset the task to 64-bit (or not) here. It may have picked up
596 * a new map, and we need that to reflect its true 64-bit nature.
597 */
598 task_set_64bit(task,
599 ((imgp->ip_flags & IMGPF_IS_64BIT) == IMGPF_IS_64BIT));
600
601 /*
602 * Actually load the image file we previously decided to load.
603 */
604 lret = load_machfile(imgp, mach_header, thread, map, clean_regions, &load_result);
605
606 if (lret != LOAD_SUCCESS) {
607 error = load_return_to_errno(lret);
608 goto badtoolate;
609 }
610
611 /* load_machfile() maps the vnode */
612 (void)ubc_map(imgp->ip_vp, PROT_EXEC);
613
614 /*
615 * deal with set[ug]id.
616 */
617 error = exec_handle_sugid(imgp);
618
619 KNOTE(&p->p_klist, NOTE_EXEC);
620
621 if (!vfexec && (p->p_flag & P_TRACED))
622 psignal(p, SIGTRAP);
623
624 if (error) {
625 goto badtoolate;
626 }
627 vnode_put(imgp->ip_vp);
628 imgp->ip_vp = NULL;
629
630 if (load_result.unixproc &&
631 create_unix_stack(get_task_map(task),
632 load_result.user_stack, load_result.customstack, p)) {
633 error = load_return_to_errno(LOAD_NOSPACE);
634 goto badtoolate;
635 }
636
637 if (vfexec) {
638 uthread->uu_ar0 = (void *)get_user_regs(thread);
639 old_map = vm_map_switch(get_task_map(task));
640 }
641
642 if (load_result.unixproc) {
643 user_addr_t ap;
644
645 /*
646 * Copy the strings area out into the new process address
647 * space.
648 */
649 ap = p->user_stack;
650 error = exec_copyout_strings(imgp, &ap);
651 if (error) {
652 if (vfexec)
653 vm_map_switch(old_map);
654 goto badtoolate;
655 }
656 /* Set the stack */
657 thread_setuserstack(thread, ap);
658 }
659
660 if (load_result.dynlinker) {
661 uint64_t ap;
662
663 /* Adjust the stack */
664 if (imgp->ip_flags & IMGPF_IS_64BIT) {
665 ap = thread_adjuserstack(thread, -8);
666 (void)copyoutptr(load_result.mach_header, ap, 8);
667 } else {
668 ap = thread_adjuserstack(thread, -4);
669 (void)suword(ap, load_result.mach_header);
670 }
671 }
672
673 if (vfexec) {
674 vm_map_switch(old_map);
675 }
676 /* Set the entry point */
677 thread_setentrypoint(thread, load_result.entry_point);
678
679 /* Stop profiling */
680 stopprofclock(p);
681
682 /*
683 * Reset signal state.
684 */
685 execsigs(p, thread);
686
687 /*
688 * Close file descriptors
689 * which specify close-on-exec.
690 */
691 fdexec(p);
692
693 /*
694 * need to cancel async IO requests that can be cancelled and wait for those
695 * already active. MAY BLOCK!
696 */
697 _aio_exec( p );
698
699 /* FIXME: Till vmspace inherit is fixed: */
700 if (!vfexec && p->vm_shm)
701 shmexec(p);
702 /* Clean up the semaphores */
703 semexit(p);
704
705 /*
706 * Remember file name for accounting.
707 */
708 p->p_acflag &= ~AFORK;
709 /* If the translated name isn't NULL, then we want to use
710 * that translated name as the name we show as the "real" name.
711 * Otherwise, use the name passed into exec.
712 */
713 if (0 != imgp->ip_p_comm[0]) {
714 bcopy((caddr_t)imgp->ip_p_comm, (caddr_t)p->p_comm,
715 sizeof(p->p_comm));
716 } else {
717 if (imgp->ip_ndp->ni_cnd.cn_namelen > MAXCOMLEN)
718 imgp->ip_ndp->ni_cnd.cn_namelen = MAXCOMLEN;
719 bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_comm,
720 (unsigned)imgp->ip_ndp->ni_cnd.cn_namelen);
721 p->p_comm[imgp->ip_ndp->ni_cnd.cn_namelen] = '\0';
722 }
723
724 {
725 /* This is for kdebug */
726 long dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4;
727
728 /* Collect the pathname for tracing */
729 kdbg_trace_string(p, &dbg_arg1, &dbg_arg2, &dbg_arg3, &dbg_arg4);
730
731
732
733 if (vfexec)
734 {
735 KERNEL_DEBUG_CONSTANT1((TRACEDBG_CODE(DBG_TRACE_DATA, 2)) | DBG_FUNC_NONE,
736 p->p_pid ,0,0,0, (unsigned int)thread);
737 KERNEL_DEBUG_CONSTANT1((TRACEDBG_CODE(DBG_TRACE_STRING, 2)) | DBG_FUNC_NONE,
738 dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4, (unsigned int)thread);
739 }
740 else
741 {
742 KERNEL_DEBUG_CONSTANT((TRACEDBG_CODE(DBG_TRACE_DATA, 2)) | DBG_FUNC_NONE,
743 p->p_pid ,0,0,0,0);
744 KERNEL_DEBUG_CONSTANT((TRACEDBG_CODE(DBG_TRACE_STRING, 2)) | DBG_FUNC_NONE,
745 dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4, 0);
746 }
747 }
748
749 p->p_flag &= ~P_CLASSIC;
750
751 /*
752 * mark as execed, wakeup the process that vforked (if any) and tell
753 * it that it now has it's own resources back
754 */
755 p->p_flag |= P_EXEC;
756 if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
757 p->p_flag &= ~P_PPWAIT;
758 wakeup((caddr_t)p->p_pptr);
759 }
760
761 if (vfexec && (p->p_flag & P_TRACED)) {
762 psignal_vfork(p, new_task, thread, SIGTRAP);
763 }
764
765 badtoolate:
766 if (vfexec) {
767 task_deallocate(new_task);
768 thread_deallocate(thread);
769 if (error)
770 error = 0;
771 }
772
773 bad:
774 return(error);
775 }
776
777
778
779
780 /*
781 * Our image activator table; this is the table of the image types we are
782 * capable of loading. We list them in order of preference to ensure the
783 * fastest image load speed.
784 *
785 * XXX hardcoded, for now; should use linker sets
786 */
787 struct execsw {
788 int (*ex_imgact)(struct image_params *);
789 const char *ex_name;
790 } execsw[] = {
791 { exec_mach_imgact, "Mach-o Binary" },
792 { exec_fat_imgact, "Fat Binary" },
793 { exec_shell_imgact, "Interpreter Script" },
794 { NULL, NULL}
795 };
796
797
798 /*
799 * TODO: Dynamic linker header address on stack is copied via suword()
800 */
801 /* ARGSUSED */
802 int
803 execve(struct proc *p, struct execve_args *uap, register_t *retval)
804 {
805 kauth_cred_t cred = p->p_ucred;
806 struct image_params image_params, *imgp;
807 struct vnode_attr va;
808 struct vnode_attr origva;
809 struct nameidata nd;
810 struct uthread *uthread;
811 int i;
812 int resid, error;
813 task_t task;
814 int numthreads;
815 int vfexec=0;
816 int once = 1; /* save SGUID-ness for interpreted files */
817 char alt_p_comm[sizeof(p->p_comm)] = {0}; /* for Classic */
818 int is_64 = IS_64BIT_PROCESS(p);
819 int seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
820 struct vfs_context context;
821
822 context.vc_proc = p;
823 context.vc_ucred = p->p_ucred; /* XXX must NOT be kauth_cred_get() */
824
825
826 imgp = &image_params;
827
828 /* Initialize the common data in the image_params structure */
829 bzero(imgp, sizeof(*imgp));
830 imgp->ip_user_fname = uap->fname;
831 imgp->ip_user_argv = uap->argp;
832 imgp->ip_user_envv = uap->envp;
833 imgp->ip_vattr = &va;
834 imgp->ip_origvattr = &origva;
835 imgp->ip_vfs_context = &context;
836 imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT : IMGPF_NONE);
837 imgp->ip_tws_cache_name = NULL;
838 imgp->ip_p_comm = alt_p_comm; /* for Classic */
839
840 /*
841 * XXXAUDIT: Currently, we only audit the pathname of the binary.
842 * There may also be poor interaction with dyld.
843 */
844
845 task = current_task();
846 uthread = get_bsdthread_info(current_thread());
847
848 if (uthread->uu_flag & UT_VFORK) {
849 vfexec = 1; /* Mark in exec */
850 } else {
851 if (task != kernel_task) {
852 numthreads = get_task_numacts(task);
853 if (numthreads <= 0 )
854 return(EINVAL);
855 if (numthreads > 1) {
856 return(ENOTSUP);
857 }
858 }
859 }
860
861 error = execargs_alloc(imgp);
862 if (error)
863 return(error);
864
865 /*
866 * XXXAUDIT: Note: the double copyin introduces an audit
867 * race. To correct this race, we must use a single
868 * copyin(), e.g. by passing a flag to namei to indicate an
869 * external path buffer is being used.
870 */
871 error = exec_save_path(imgp, uap->fname, seg);
872 if (error) {
873 execargs_free(imgp);
874 return(error);
875 }
876
877 /*
878 * No app profiles under chroot
879 */
880 if((p->p_fd->fd_rdir == NULLVP) && (app_profile != 0)) {
881
882 /* grab the name of the file out of its path */
883 /* we will need this for lookup within the */
884 /* name file */
885 /* Scan backwards for the first '/' or start of string */
886 imgp->ip_tws_cache_name = imgp->ip_strendp;
887 while (imgp->ip_tws_cache_name[0] != '/') {
888 if(imgp->ip_tws_cache_name == imgp->ip_strings) {
889 imgp->ip_tws_cache_name--;
890 break;
891 }
892 imgp->ip_tws_cache_name--;
893 }
894 imgp->ip_tws_cache_name++;
895 }
896 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNPATH1,
897 seg, uap->fname, imgp->ip_vfs_context);
898
899 again:
900 error = namei(&nd);
901 if (error)
902 goto bad;
903 imgp->ip_ndp = &nd; /* successful namei(); call nameidone() later */
904 imgp->ip_vp = nd.ni_vp; /* if set, need to vnode_put() at some point */
905
906 error = exec_check_permissions(imgp);
907 if (error)
908 goto bad;
909
910 /* Copy; avoid invocation of an interpreter overwriting the original */
911 if (once) {
912 once = 0;
913 origva = va;
914 }
915
916 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata, PAGE_SIZE, 0,
917 UIO_SYSSPACE32, IO_NODELOCKED, cred, &resid, p);
918 if (error)
919 goto bad;
920
921 encapsulated_binary:
922 error = -1;
923 for(i = 0; error == -1 && execsw[i].ex_imgact != NULL; i++) {
924
925 error = (*execsw[i].ex_imgact)(imgp);
926
927 switch (error) {
928 /* case -1: not claimed: continue */
929 case -2: /* Encapsulated binary */
930 goto encapsulated_binary;
931
932 case -3: /* Interpreter */
933 vnode_put(imgp->ip_vp);
934 imgp->ip_vp = NULL; /* already put */
935 nd.ni_cnd.cn_nameiop = LOOKUP;
936 nd.ni_cnd.cn_flags = (nd.ni_cnd.cn_flags & HASBUF) |
937 (FOLLOW | LOCKLEAF);
938
939
940 nd.ni_segflg = UIO_SYSSPACE32;
941 nd.ni_dirp = CAST_USER_ADDR_T(imgp->ip_interp_name);
942 goto again;
943
944 default:
945 break;
946 }
947 }
948
949 /* call out to allow 3rd party notification of exec.
950 * Ignore result of kauth_authorize_fileop call.
951 */
952 if (error == 0 && kauth_authorize_fileop_has_listeners()) {
953 kauth_authorize_fileop(vfs_context_ucred(&context), KAUTH_FILEOP_EXEC,
954 (uintptr_t)nd.ni_vp, 0);
955 }
956
957 /* Image not claimed by any activator? */
958 if (error == -1)
959 error = ENOEXEC;
960
961 bad:
962 if (imgp->ip_ndp)
963 nameidone(imgp->ip_ndp);
964 if (imgp->ip_vp)
965 vnode_put(imgp->ip_vp);
966 if (imgp->ip_strings)
967 execargs_free(imgp);
968 if (!error && vfexec) {
969 vfork_return(current_thread(), p->p_pptr, p, retval);
970 (void)thread_resume(imgp->ip_vfork_thread);
971 return(0);
972 }
973 return(error);
974 }
975
976
977 static int
978 copyinptr(user_addr_t froma, user_addr_t *toptr, int ptr_size)
979 {
980 int error;
981
982 if (ptr_size == 4) {
983 /* 64 bit value containing 32 bit address */
984 unsigned int i;
985
986 error = copyin(froma, &i, 4);
987 *toptr = CAST_USER_ADDR_T(i); /* SAFE */
988 } else {
989 error = copyin(froma, toptr, 8);
990 }
991 return (error);
992 }
993
994
995 static int
996 copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size)
997 {
998 int error;
999
1000 if (ptr_size == 4) {
1001 /* 64 bit value containing 32 bit address */
1002 unsigned int i = CAST_DOWN(unsigned int,ua); /* SAFE */
1003
1004 error = copyout(&i, ptr, 4);
1005 } else {
1006 error = copyout(&ua, ptr, 8);
1007 }
1008 return (error);
1009 }
1010
1011
1012 /*
1013 * exec_copyout_strings
1014 *
1015 * Copy out the strings segment to user space. The strings segment is put
1016 * on a preinitialized stack frame.
1017 *
1018 * Parameters: struct image_params * the image parameter block
1019 * int * a pointer to the stack offset variable
1020 *
1021 * Returns: 0 Success
1022 * !0 Faiure: errno
1023 *
1024 * Implicit returns:
1025 * (*stackp) The stack offset, modified
1026 *
1027 * Note: The strings segment layout is backward, from the beginning
1028 * of the top of the stack to consume the minimal amount of
1029 * space possible; the returned stack pointer points to the
1030 * end of the area consumed (stacks grow upward).
1031 *
1032 * argc is an int; arg[i] are pointers; env[i] are pointers;
1033 * exec_path is a pointer; the 0's are (void *)NULL's
1034 *
1035 * The stack frame layout is:
1036 *
1037 * +-------------+
1038 * sp-> | argc |
1039 * +-------------+
1040 * | arg[0] |
1041 * +-------------+
1042 * :
1043 * :
1044 * +-------------+
1045 * | arg[argc-1] |
1046 * +-------------+
1047 * | 0 |
1048 * +-------------+
1049 * | env[0] |
1050 * +-------------+
1051 * :
1052 * :
1053 * +-------------+
1054 * | env[n] |
1055 * +-------------+
1056 * | 0 |
1057 * +-------------+
1058 * | exec_path | In MacOS X PR2 Beaker2E the path passed to exec() is
1059 * +-------------+ passed on the stack just after the trailing 0 of the
1060 * | 0 | the envp[] array as a pointer to a string.
1061 * +-------------+
1062 * | PATH AREA |
1063 * +-------------+
1064 * | STRING AREA |
1065 * :
1066 * :
1067 * | | <- p->user_stack
1068 * +-------------+
1069 *
1070 * Although technically a part of the STRING AREA, we treat the PATH AREA as
1071 * a separate entity. This allows us to align the beginning of the PATH AREA
1072 * to a pointer boundary so that the exec_path, env[i], and argv[i] pointers
1073 * which preceed it on the stack are properly aligned.
1074 *
1075 * TODO: argc copied with suword(), which takes a 64 bit address
1076 */
1077 static int
1078 exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp)
1079 {
1080 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
1081 int ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
1082 char *argv = imgp->ip_argv; /* modifiable copy of argv */
1083 user_addr_t string_area; /* *argv[], *env[] */
1084 user_addr_t path_area; /* package launch path */
1085 user_addr_t ptr_area; /* argv[], env[], exec_path */
1086 user_addr_t stack;
1087 int stringc = imgp->ip_argc + imgp->ip_envc;
1088 int len;
1089 int error;
1090 int strspace;
1091
1092 stack = *stackp;
1093
1094 /*
1095 * Set up pointers to the beginning of the string area, the beginning
1096 * of the path area, and the beginning of the pointer area (actually,
1097 * the location of argc, an int, which may be smaller than a pointer,
1098 * but we use ptr_size worth of space for it, for alignment).
1099 */
1100 string_area = stack - (((imgp->ip_strendp - imgp->ip_strings) + ptr_size-1) & ~(ptr_size-1)) - ptr_size;
1101 path_area = string_area - (((imgp->ip_argv - imgp->ip_strings) + ptr_size-1) & ~(ptr_size-1));
1102 ptr_area = path_area - ((imgp->ip_argc + imgp->ip_envc + 4) * ptr_size) - ptr_size /*argc*/;
1103
1104 /* Return the initial stack address: the location of argc */
1105 *stackp = ptr_area;
1106
1107 /*
1108 * Record the size of the arguments area so that sysctl_procargs()
1109 * can return the argument area without having to parse the arguments.
1110 */
1111 p->p_argc = imgp->ip_argc;
1112 p->p_argslen = (int)(stack - path_area);
1113
1114
1115 /*
1116 * Support for new app package launching for Mac OS X allocates
1117 * the "path" at the begining of the imgp->ip_strings buffer.
1118 * copy it just before the string area.
1119 */
1120 len = 0;
1121 error = copyoutstr(imgp->ip_strings, path_area,
1122 (unsigned)(imgp->ip_argv - imgp->ip_strings),
1123 (size_t *)&len);
1124 if (error)
1125 goto bad;
1126
1127
1128 /* Save a NULL pointer below it */
1129 (void)copyoutptr(0LL, path_area - ptr_size, ptr_size);
1130
1131 /* Save the pointer to "path" just below it */
1132 (void)copyoutptr(path_area, path_area - 2*ptr_size, ptr_size);
1133
1134 /*
1135 * ptr_size for 2 NULL one each ofter arg[argc -1] and env[n]
1136 * ptr_size for argc
1137 * skip over saved path, ptr_size for pointer to path,
1138 * and ptr_size for the NULL after pointer to path.
1139 */
1140
1141 /* argc (int32, stored in a ptr_size area) */
1142 (void)suword(ptr_area, imgp->ip_argc);
1143 ptr_area += sizeof(int);
1144 /* pad to ptr_size, if 64 bit image, to ensure user stack alignment */
1145 if (imgp->ip_flags & IMGPF_IS_64BIT) {
1146 (void)suword(ptr_area, 0); /* int, not long: ignored */
1147 ptr_area += sizeof(int);
1148 }
1149
1150
1151 /*
1152 * We use (string_area - path_area) here rather than the more
1153 * intuitive (imgp->ip_argv - imgp->ip_strings) because we are
1154 * interested in the length of the PATH_AREA in user space,
1155 * rather than the actual length of the execution path, since
1156 * it includes alignment padding of the PATH_AREA + STRING_AREA
1157 * to a ptr_size boundary.
1158 */
1159 strspace = SIZE_IMG_STRSPACE - (string_area - path_area);
1160 for (;;) {
1161 if (stringc == imgp->ip_envc) {
1162 /* argv[n] = NULL */
1163 (void)copyoutptr(0LL, ptr_area, ptr_size);
1164 ptr_area += ptr_size;
1165 }
1166 if (--stringc < 0)
1167 break;
1168
1169 /* pointer: argv[n]/env[n] */
1170 (void)copyoutptr(string_area, ptr_area, ptr_size);
1171
1172 /* string : argv[n][]/env[n][] */
1173 do {
1174 if (strspace <= 0) {
1175 error = E2BIG;
1176 break;
1177 }
1178 error = copyoutstr(argv, string_area,
1179 (unsigned)strspace,
1180 (size_t *)&len);
1181 string_area += len;
1182 argv += len;
1183 strspace -= len;
1184 } while (error == ENAMETOOLONG);
1185 if (error == EFAULT || error == E2BIG)
1186 break; /* bad stack - user's problem */
1187 ptr_area += ptr_size;
1188 }
1189 /* env[n] = NULL */
1190 (void)copyoutptr(0LL, ptr_area, ptr_size);
1191
1192 bad:
1193 return(error);
1194 }
1195
1196
1197 /*
1198 * exec_extract_strings
1199 *
1200 * Copy arguments and environment from user space into work area; we may
1201 * have already copied some early arguments into the work area, and if
1202 * so, any arguments opied in are appended to those already there.
1203 *
1204 * Parameters: struct image_params * the image parameter block
1205 *
1206 * Returns: 0 Success
1207 * !0 Failure: errno
1208 *
1209 * Implicit returns;
1210 * (imgp->ip_argc) Count of arguments, updated
1211 * (imgp->ip_envc) Count of environment strings, updated
1212 *
1213 *
1214 * Notes: The argument and environment vectors are user space pointers
1215 * to arrays of user space pointers.
1216 */
1217 static int
1218 exec_extract_strings(struct image_params *imgp)
1219 {
1220 int error = 0;
1221 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
1222 int seg = (IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32);
1223 int ptr_size = (imgp->ip_flags & IMGPF_WAS_64BIT) ? 8 : 4;
1224 user_addr_t argv = imgp->ip_user_argv;
1225 user_addr_t envv = imgp->ip_user_envv;
1226
1227 /* Now, get rest of arguments */
1228
1229 /*
1230 * If we are running an interpreter, replace the av[0] that was
1231 * passed to execve() with the fully qualified path name that was
1232 * passed to execve() for interpreters which do not use the PATH
1233 * to locate their script arguments.
1234 */
1235 if((imgp->ip_flags & IMGPF_INTERPRET) != 0 && argv != 0LL) {
1236 user_addr_t arg;
1237
1238 error = copyinptr(argv, &arg, ptr_size);
1239 if (error)
1240 goto bad;
1241 if (arg != 0LL && arg != (user_addr_t)-1) {
1242 argv += ptr_size;
1243 error = exec_add_string(imgp, imgp->ip_user_fname, seg);
1244 if (error)
1245 goto bad;
1246 imgp->ip_argc++;
1247 }
1248 }
1249
1250 while (argv != 0LL) {
1251 user_addr_t arg;
1252
1253 error = copyinptr(argv, &arg, ptr_size);
1254 if (error)
1255 goto bad;
1256
1257 argv += ptr_size;
1258 if (arg == 0LL) {
1259 break;
1260 } else if (arg == (user_addr_t)-1) {
1261 /* Um... why would it be -1? */
1262 error = EFAULT;
1263 goto bad;
1264 }
1265 /*
1266 * av[n...] = arg[n]
1267 */
1268 error = exec_add_string(imgp, arg, seg);
1269 if (error)
1270 goto bad;
1271 imgp->ip_argc++;
1272 }
1273
1274 /* Now, get the environment */
1275 while (envv != 0LL) {
1276 user_addr_t env;
1277
1278 error = copyinptr(envv, &env, ptr_size);
1279 if (error)
1280 goto bad;
1281
1282 envv += ptr_size;
1283 if (env == 0LL) {
1284 break;
1285 } else if (env == (user_addr_t)-1) {
1286 error = EFAULT;
1287 goto bad;
1288 }
1289 /*
1290 * av[n...] = env[n]
1291 */
1292 error = exec_add_string(imgp, env, seg);
1293 if (error)
1294 goto bad;
1295 imgp->ip_envc++;
1296 }
1297 bad:
1298 return error;
1299 }
1300
1301
1302 #define unix_stack_size(p) (p->p_rlimit[RLIMIT_STACK].rlim_cur)
1303
1304 static int
1305 exec_check_permissions(struct image_params *imgp)
1306 {
1307 struct vnode *vp = imgp->ip_vp;
1308 struct vnode_attr *vap = imgp->ip_vattr;
1309 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
1310 int error;
1311 kauth_action_t action;
1312
1313 /* Only allow execution of regular files */
1314 if (!vnode_isreg(vp))
1315 return (EACCES);
1316
1317 /* Get the file attributes that we will be using here and elsewhere */
1318 VATTR_INIT(vap);
1319 VATTR_WANTED(vap, va_uid);
1320 VATTR_WANTED(vap, va_gid);
1321 VATTR_WANTED(vap, va_mode);
1322 VATTR_WANTED(vap, va_fsid);
1323 VATTR_WANTED(vap, va_fileid);
1324 VATTR_WANTED(vap, va_data_size);
1325 if ((error = vnode_getattr(vp, vap, imgp->ip_vfs_context)) != 0)
1326 return (error);
1327
1328 /*
1329 * Ensure that at least one execute bit is on - otherwise root
1330 * will always succeed, and we don't want to happen unless the
1331 * file really is executable.
1332 */
1333 if ((vap->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0)
1334 return (EACCES);
1335
1336 /* Disallow zero length files */
1337 if (vap->va_data_size == 0)
1338 return (ENOEXEC);
1339
1340 imgp->ip_arch_offset = (user_size_t)0;
1341 imgp->ip_arch_size = vap->va_data_size;
1342
1343 /* Disable setuid-ness for traced programs or if MNT_NOSUID */
1344 if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_flag & P_TRACED))
1345 vap->va_mode &= ~(VSUID | VSGID);
1346
1347 /* Check for execute permission */
1348 action = KAUTH_VNODE_EXECUTE;
1349 /* Traced images must also be readable */
1350 if (p->p_flag & P_TRACED)
1351 action |= KAUTH_VNODE_READ_DATA;
1352 if ((error = vnode_authorize(vp, NULL, action, imgp->ip_vfs_context)) != 0)
1353 return (error);
1354
1355 /* Don't let it run if anyone had it open for writing */
1356 if (vp->v_writecount)
1357 return (ETXTBSY);
1358
1359
1360 /* XXX May want to indicate to underlying FS that vnode is open */
1361
1362 return (error);
1363 }
1364
1365 /*
1366 * exec_handle_sugid
1367 *
1368 * Initially clear the P_SUGID in the process flags; if an SUGID process is
1369 * exec'ing a non-SUGID image, then this is the point of no return.
1370 *
1371 * If the image being activated is SUGI, then replace the credential with a
1372 * copy, disable tracing (unless the tracing process is root), reset the
1373 * mach task port to revoke it, set the P_SUGID bit,
1374 *
1375 * If the saved user and group ID will be changing, then make sure it happens
1376 * to a new credential, rather than a shared one.
1377 *
1378 * Set the security token (this is probably obsolete, given that the token
1379 * should not technically be separate from the credential itself).
1380 *
1381 * Parameters: struct image_params * the image parameter block
1382 *
1383 * Returns: void No failure indication
1384 *
1385 * Implicit returns:
1386 * <process credential> Potentially modified/replaced
1387 * <task port> Potentially revoked
1388 * <process flags> P_SUGID bit potentially modified
1389 * <security token> Potentially modified
1390 */
1391 static int
1392 exec_handle_sugid(struct image_params *imgp)
1393 {
1394 kauth_cred_t cred = vfs_context_ucred(imgp->ip_vfs_context);
1395 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
1396 int i;
1397 int error = 0;
1398 static struct vnode *dev_null = NULLVP;
1399
1400 p->p_flag &= ~P_SUGID;
1401
1402 if (((imgp->ip_origvattr->va_mode & VSUID) != 0 &&
1403 kauth_cred_getuid(cred) != imgp->ip_origvattr->va_uid) ||
1404 ((imgp->ip_origvattr->va_mode & VSGID) != 0 &&
1405 cred->cr_gid != imgp->ip_origvattr->va_gid)) {
1406 #if KTRACE
1407 /*
1408 * If process is being ktraced, turn off - unless
1409 * root set it.
1410 */
1411 if (p->p_tracep && !(p->p_traceflag & KTRFAC_ROOT)) {
1412 struct vnode *tvp = p->p_tracep;
1413 p->p_tracep = NULL;
1414 p->p_traceflag = 0;
1415 vnode_rele(tvp);
1416 }
1417 #endif
1418 /*
1419 * Replace the credential with a copy of itself if euid or egid change.
1420 */
1421 if (imgp->ip_origvattr->va_mode & VSUID) {
1422 p->p_ucred = kauth_cred_seteuid(p->p_ucred, imgp->ip_origvattr->va_uid);
1423 }
1424 if (imgp->ip_origvattr->va_mode & VSGID) {
1425 p->p_ucred = kauth_cred_setegid(p->p_ucred, imgp->ip_origvattr->va_gid);
1426 }
1427
1428 /*
1429 * Have mach reset the task port. We don't want
1430 * anyone who had the task port before a setuid
1431 * exec to be able to access/control the task
1432 * after.
1433 */
1434 if (current_task() == p->task)
1435 ipc_task_reset(p->task);
1436
1437 p->p_flag |= P_SUGID;
1438
1439 /* Cache the vnode for /dev/null the first time around */
1440 if (dev_null == NULLVP) {
1441 struct nameidata nd1;
1442
1443 NDINIT(&nd1, LOOKUP, FOLLOW, UIO_SYSSPACE32,
1444 CAST_USER_ADDR_T("/dev/null"),
1445 imgp->ip_vfs_context);
1446
1447 if ((error = vn_open(&nd1, FREAD, 0)) == 0) {
1448 dev_null = nd1.ni_vp;
1449 /*
1450 * vn_open returns with both a use_count
1451 * and an io_count on the found vnode
1452 * drop the io_count, but keep the use_count
1453 */
1454 vnode_put(nd1.ni_vp);
1455 }
1456 }
1457
1458 /* Radar 2261856; setuid security hole fix */
1459 /* Patch from OpenBSD: A. Ramesh */
1460 /*
1461 * XXX For setuid processes, attempt to ensure that
1462 * stdin, stdout, and stderr are already allocated.
1463 * We do not want userland to accidentally allocate
1464 * descriptors in this range which has implied meaning
1465 * to libc.
1466 */
1467 if (dev_null != NULLVP) {
1468 for (i = 0; i < 3; i++) {
1469 struct fileproc *fp;
1470 int indx;
1471
1472 if (p->p_fd->fd_ofiles[i] != NULL)
1473 continue;
1474
1475 if ((error = falloc(p, &fp, &indx)) != 0)
1476 continue;
1477
1478 if ((error = vnode_ref_ext(dev_null, FREAD)) != 0) {
1479 fp_free(p, indx, fp);
1480 break;
1481 }
1482
1483 fp->f_fglob->fg_flag = FREAD;
1484 fp->f_fglob->fg_type = DTYPE_VNODE;
1485 fp->f_fglob->fg_ops = &vnops;
1486 fp->f_fglob->fg_data = (caddr_t)dev_null;
1487
1488 proc_fdlock(p);
1489 *fdflags(p, indx) &= ~UF_RESERVED;
1490 fp_drop(p, indx, fp, 1);
1491 proc_fdunlock(p);
1492 }
1493 /*
1494 * for now we need to drop the reference immediately
1495 * since we don't have any mechanism in place to
1496 * release it before starting to unmount "/dev"
1497 * during a reboot/shutdown
1498 */
1499 vnode_rele(dev_null);
1500 dev_null = NULLVP;
1501 }
1502 }
1503
1504 /*
1505 * Implement the semantic where the effective user and group become
1506 * the saved user and group in exec'ed programs.
1507 */
1508 p->p_ucred = kauth_cred_setsvuidgid(p->p_ucred, kauth_cred_getuid(p->p_ucred), p->p_ucred->cr_gid);
1509
1510 /* XXX Obsolete; security token should not be separate from cred */
1511 set_security_token(p);
1512
1513 return(error);
1514 }
1515
1516 static kern_return_t
1517 create_unix_stack(vm_map_t map, user_addr_t user_stack, int customstack,
1518 struct proc *p)
1519 {
1520 mach_vm_size_t size;
1521 mach_vm_offset_t addr;
1522
1523 p->user_stack = user_stack;
1524 if (!customstack) {
1525 size = mach_vm_round_page(unix_stack_size(p));
1526 addr = mach_vm_trunc_page(user_stack - size);
1527 return (mach_vm_allocate(map, &addr, size,
1528 VM_MAKE_TAG(VM_MEMORY_STACK) |
1529 VM_FLAGS_FIXED));
1530 } else
1531 return(KERN_SUCCESS);
1532 }
1533
1534 #include <sys/reboot.h>
1535
1536 static char init_program_name[128] = "/sbin/launchd";
1537 static const char * other_init = "/sbin/mach_init";
1538
1539 char init_args[128] = "";
1540
1541 struct execve_args init_exec_args;
1542 int init_attempts = 0;
1543
1544
1545 void
1546 load_init_program(struct proc *p)
1547 {
1548 vm_offset_t init_addr;
1549 char *argv[3];
1550 int error;
1551 register_t retval[2];
1552
1553 error = 0;
1554
1555 /* init_args are copied in string form directly from bootstrap */
1556
1557 do {
1558 if (boothowto & RB_INITNAME) {
1559 printf("init program? ");
1560 #if FIXME /* [ */
1561 gets(init_program_name, init_program_name);
1562 #endif /* FIXME ] */
1563 }
1564
1565 if (error && ((boothowto & RB_INITNAME) == 0) &&
1566 (init_attempts == 1)) {
1567 printf("Load of %s, errno %d, trying %s\n",
1568 init_program_name, error, other_init);
1569 error = 0;
1570 bcopy(other_init, init_program_name,
1571 sizeof(other_init));
1572 }
1573
1574 init_attempts++;
1575
1576 if (error) {
1577 printf("Load of %s failed, errno %d\n",
1578 init_program_name, error);
1579 error = 0;
1580 boothowto |= RB_INITNAME;
1581 continue;
1582 }
1583
1584 /*
1585 * Copy out program name.
1586 */
1587
1588 init_addr = VM_MIN_ADDRESS;
1589 (void) vm_allocate(current_map(), &init_addr,
1590 PAGE_SIZE, VM_FLAGS_ANYWHERE);
1591 if (init_addr == 0)
1592 init_addr++;
1593
1594 (void) copyout((caddr_t) init_program_name,
1595 CAST_USER_ADDR_T(init_addr),
1596 (unsigned) sizeof(init_program_name)+1);
1597
1598 argv[0] = (char *) init_addr;
1599 init_addr += sizeof(init_program_name);
1600 init_addr = (vm_offset_t)ROUND_PTR(char, init_addr);
1601
1602 /*
1603 * Put out first (and only) argument, similarly.
1604 * Assumes everything fits in a page as allocated
1605 * above.
1606 */
1607
1608 (void) copyout((caddr_t) init_args,
1609 CAST_USER_ADDR_T(init_addr),
1610 (unsigned) sizeof(init_args));
1611
1612 argv[1] = (char *) init_addr;
1613 init_addr += sizeof(init_args);
1614 init_addr = (vm_offset_t)ROUND_PTR(char, init_addr);
1615
1616 /*
1617 * Null-end the argument list
1618 */
1619
1620 argv[2] = (char *) 0;
1621
1622 /*
1623 * Copy out the argument list.
1624 */
1625
1626 (void) copyout((caddr_t) argv,
1627 CAST_USER_ADDR_T(init_addr),
1628 (unsigned) sizeof(argv));
1629
1630 /*
1631 * Set up argument block for fake call to execve.
1632 */
1633
1634 init_exec_args.fname = CAST_USER_ADDR_T(argv[0]);
1635 init_exec_args.argp = CAST_USER_ADDR_T((char **)init_addr);
1636 init_exec_args.envp = CAST_USER_ADDR_T(0);
1637
1638 /* So that mach_init task
1639 * is set with uid,gid 0 token
1640 */
1641 set_security_token(p);
1642
1643 error = execve(p,&init_exec_args,retval);
1644 } while (error);
1645 }
1646
1647 /*
1648 * Convert a load_return_t to an errno.
1649 */
1650 static int
1651 load_return_to_errno(load_return_t lrtn)
1652 {
1653 switch (lrtn) {
1654 case LOAD_SUCCESS:
1655 return 0;
1656 case LOAD_BADARCH:
1657 return EBADARCH;
1658 case LOAD_BADMACHO:
1659 return EBADMACHO;
1660 case LOAD_SHLIB:
1661 return ESHLIBVERS;
1662 case LOAD_NOSPACE:
1663 case LOAD_RESOURCE:
1664 return ENOMEM;
1665 case LOAD_PROTECT:
1666 return EACCES;
1667 case LOAD_ENOENT:
1668 return ENOENT;
1669 case LOAD_IOERROR:
1670 return EIO;
1671 case LOAD_FAILURE:
1672 default:
1673 return EBADEXEC;
1674 }
1675 }
1676
1677 #include <mach/mach_types.h>
1678 #include <mach/vm_prot.h>
1679 #include <mach/semaphore.h>
1680 #include <mach/sync_policy.h>
1681 #include <kern/clock.h>
1682 #include <mach/kern_return.h>
1683
1684 extern semaphore_t execve_semaphore;
1685
1686 /*
1687 * The block of memory used by the execve arguments. At the same time,
1688 * we allocate a page so that we can read in the first page of the image.
1689 */
1690 static int
1691 execargs_alloc(struct image_params *imgp)
1692 {
1693 kern_return_t kret;
1694
1695 kret = semaphore_wait(execve_semaphore);
1696 if (kret != KERN_SUCCESS)
1697 switch (kret) {
1698 default:
1699 return (EINVAL);
1700 case KERN_INVALID_ADDRESS:
1701 case KERN_PROTECTION_FAILURE:
1702 return (EACCES);
1703 case KERN_ABORTED:
1704 case KERN_OPERATION_TIMED_OUT:
1705 return (EINTR);
1706 }
1707
1708 kret = kmem_alloc_pageable(bsd_pageable_map, (vm_offset_t *)&imgp->ip_strings, NCARGS + PAGE_SIZE);
1709 imgp->ip_vdata = imgp->ip_strings + NCARGS;
1710 if (kret != KERN_SUCCESS) {
1711 semaphore_signal(execve_semaphore);
1712 return (ENOMEM);
1713 }
1714 return (0);
1715 }
1716
1717 static int
1718 execargs_free(struct image_params *imgp)
1719 {
1720 kern_return_t kret;
1721
1722 kmem_free(bsd_pageable_map, (vm_offset_t)imgp->ip_strings, NCARGS + PAGE_SIZE);
1723 imgp->ip_strings = NULL;
1724
1725 kret = semaphore_signal(execve_semaphore);
1726 switch (kret) {
1727 case KERN_INVALID_ADDRESS:
1728 case KERN_PROTECTION_FAILURE:
1729 return (EINVAL);
1730 case KERN_ABORTED:
1731 case KERN_OPERATION_TIMED_OUT:
1732 return (EINTR);
1733 case KERN_SUCCESS:
1734 return(0);
1735 default:
1736 return (EINVAL);
1737 }
1738 }