]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/mach_loader.c
81419cb5fd88f93f29a8f64aee91859ff4028569
[apple/xnu.git] / bsd / kern / mach_loader.c
1 /*
2 * Copyright (c) 2000-2010 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * Copyright (C) 1988, 1989, NeXT, Inc.
30 *
31 * File: kern/mach_loader.c
32 * Author: Avadis Tevanian, Jr.
33 *
34 * Mach object file loader (kernel version, for now).
35 *
36 * 21-Jul-88 Avadis Tevanian, Jr. (avie) at NeXT
37 * Started.
38 */
39
40 #include <sys/param.h>
41 #include <sys/vnode_internal.h>
42 #include <sys/uio.h>
43 #include <sys/namei.h>
44 #include <sys/proc_internal.h>
45 #include <sys/kauth.h>
46 #include <sys/stat.h>
47 #include <sys/malloc.h>
48 #include <sys/mount_internal.h>
49 #include <sys/fcntl.h>
50 #include <sys/ubc_internal.h>
51 #include <sys/imgact.h>
52 #include <sys/codesign.h>
53
54 #include <mach/mach_types.h>
55 #include <mach/vm_map.h> /* vm_allocate() */
56 #include <mach/mach_vm.h> /* mach_vm_allocate() */
57 #include <mach/vm_statistics.h>
58 #include <mach/task.h>
59 #include <mach/thread_act.h>
60
61 #include <machine/vmparam.h>
62 #include <machine/exec.h>
63 #include <machine/pal_routines.h>
64
65 #include <kern/kern_types.h>
66 #include <kern/cpu_number.h>
67 #include <kern/mach_loader.h>
68 #include <kern/mach_fat.h>
69 #include <kern/kalloc.h>
70 #include <kern/task.h>
71 #include <kern/thread.h>
72 #include <kern/page_decrypt.h>
73
74 #include <mach-o/fat.h>
75 #include <mach-o/loader.h>
76
77 #include <vm/pmap.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_kern.h>
80 #include <vm/vm_pager.h>
81 #include <vm/vnode_pager.h>
82 #include <vm/vm_protos.h>
83 #include <IOKit/IOReturn.h> /* for kIOReturnNotPrivileged */
84
85 /*
86 * XXX vm/pmap.h should not treat these prototypes as MACH_KERNEL_PRIVATE
87 * when KERNEL is defined.
88 */
89 extern pmap_t pmap_create(ledger_t ledger, vm_map_size_t size,
90 boolean_t is_64bit);
91
92 /* XXX should have prototypes in a shared header file */
93 extern int get_map_nentries(vm_map_t);
94
95 extern kern_return_t memory_object_signed(memory_object_control_t control,
96 boolean_t is_signed);
97
98 /* An empty load_result_t */
99 static load_result_t load_result_null = {
100 .mach_header = MACH_VM_MIN_ADDRESS,
101 .entry_point = MACH_VM_MIN_ADDRESS,
102 .user_stack = MACH_VM_MIN_ADDRESS,
103 .user_stack_size = 0,
104 .all_image_info_addr = MACH_VM_MIN_ADDRESS,
105 .all_image_info_size = 0,
106 .thread_count = 0,
107 .unixproc = 0,
108 .dynlinker = 0,
109 .needs_dynlinker = 0,
110 .prog_allocated_stack = 0,
111 .prog_stack_size = 0,
112 .validentry = 0,
113 .using_lcmain = 0,
114 .csflags = 0,
115 .uuid = { 0 },
116 .min_vm_addr = MACH_VM_MAX_ADDRESS,
117 .max_vm_addr = MACH_VM_MIN_ADDRESS,
118 .cs_end_offset = 0
119 };
120
121 /*
122 * Prototypes of static functions.
123 */
124 static load_return_t
125 parse_machfile(
126 struct vnode *vp,
127 vm_map_t map,
128 thread_t thread,
129 struct mach_header *header,
130 off_t file_offset,
131 off_t macho_size,
132 int depth,
133 int64_t slide,
134 int64_t dyld_slide,
135 load_result_t *result
136 );
137
138 static load_return_t
139 load_segment(
140 struct load_command *lcp,
141 uint32_t filetype,
142 void *control,
143 off_t pager_offset,
144 off_t macho_size,
145 struct vnode *vp,
146 vm_map_t map,
147 int64_t slide,
148 load_result_t *result
149 );
150
151 static load_return_t
152 load_uuid(
153 struct uuid_command *uulp,
154 char *command_end,
155 load_result_t *result
156 );
157
158 static load_return_t
159 load_code_signature(
160 struct linkedit_data_command *lcp,
161 struct vnode *vp,
162 off_t macho_offset,
163 off_t macho_size,
164 cpu_type_t cputype,
165 load_result_t *result);
166
167 #if CONFIG_CODE_DECRYPTION
168 static load_return_t
169 set_code_unprotect(
170 struct encryption_info_command *lcp,
171 caddr_t addr,
172 vm_map_t map,
173 int64_t slide,
174 struct vnode *vp,
175 cpu_type_t cputype,
176 cpu_subtype_t cpusubtype);
177 #endif
178
179 static
180 load_return_t
181 load_main(
182 struct entry_point_command *epc,
183 thread_t thread,
184 int64_t slide,
185 load_result_t *result
186 );
187
188 static load_return_t
189 load_unixthread(
190 struct thread_command *tcp,
191 thread_t thread,
192 int64_t slide,
193 load_result_t *result
194 );
195
196 static load_return_t
197 load_threadstate(
198 thread_t thread,
199 uint32_t *ts,
200 uint32_t total_size
201 );
202
203 static load_return_t
204 load_threadstack(
205 thread_t thread,
206 uint32_t *ts,
207 uint32_t total_size,
208 mach_vm_offset_t *user_stack,
209 int *customstack
210 );
211
212 static load_return_t
213 load_threadentry(
214 thread_t thread,
215 uint32_t *ts,
216 uint32_t total_size,
217 mach_vm_offset_t *entry_point
218 );
219
220 static load_return_t
221 load_dylinker(
222 struct dylinker_command *lcp,
223 integer_t archbits,
224 vm_map_t map,
225 thread_t thread,
226 int depth,
227 int64_t slide,
228 load_result_t *result
229 );
230
231 struct macho_data;
232
233 static load_return_t
234 get_macho_vnode(
235 char *path,
236 integer_t archbits,
237 struct mach_header *mach_header,
238 off_t *file_offset,
239 off_t *macho_size,
240 struct macho_data *macho_data,
241 struct vnode **vpp
242 );
243
244 static inline void
245 widen_segment_command(const struct segment_command *scp32,
246 struct segment_command_64 *scp)
247 {
248 scp->cmd = scp32->cmd;
249 scp->cmdsize = scp32->cmdsize;
250 bcopy(scp32->segname, scp->segname, sizeof(scp->segname));
251 scp->vmaddr = scp32->vmaddr;
252 scp->vmsize = scp32->vmsize;
253 scp->fileoff = scp32->fileoff;
254 scp->filesize = scp32->filesize;
255 scp->maxprot = scp32->maxprot;
256 scp->initprot = scp32->initprot;
257 scp->nsects = scp32->nsects;
258 scp->flags = scp32->flags;
259 }
260
261 static void
262 note_all_image_info_section(const struct segment_command_64 *scp,
263 boolean_t is64, size_t section_size, const void *sections,
264 int64_t slide, load_result_t *result)
265 {
266 const union {
267 struct section s32;
268 struct section_64 s64;
269 } *sectionp;
270 unsigned int i;
271
272 if (strncmp(scp->segname, "__DATA", sizeof(scp->segname)) != 0)
273 return;
274 for (i = 0; i < scp->nsects; ++i) {
275 sectionp = (const void *)
276 ((const char *)sections + section_size * i);
277 if (0 == strncmp(sectionp->s64.sectname, "__all_image_info",
278 sizeof(sectionp->s64.sectname))) {
279 result->all_image_info_addr =
280 is64 ? sectionp->s64.addr : sectionp->s32.addr;
281 result->all_image_info_addr += slide;
282 result->all_image_info_size =
283 is64 ? sectionp->s64.size : sectionp->s32.size;
284 return;
285 }
286 }
287 }
288
289 load_return_t
290 load_machfile(
291 struct image_params *imgp,
292 struct mach_header *header,
293 thread_t thread,
294 vm_map_t new_map,
295 load_result_t *result
296 )
297 {
298 struct vnode *vp = imgp->ip_vp;
299 off_t file_offset = imgp->ip_arch_offset;
300 off_t macho_size = imgp->ip_arch_size;
301 off_t file_size = imgp->ip_vattr->va_data_size;
302
303 pmap_t pmap = 0; /* protected by create_map */
304 vm_map_t map;
305 vm_map_t old_map;
306 task_t old_task = TASK_NULL; /* protected by create_map */
307 load_result_t myresult;
308 load_return_t lret;
309 boolean_t create_map = FALSE;
310 boolean_t enforce_hard_pagezero = TRUE;
311 int spawn = (imgp->ip_flags & IMGPF_SPAWN);
312 task_t task = current_task();
313 proc_t p = current_proc();
314 mach_vm_offset_t aslr_offset = 0;
315 mach_vm_offset_t dyld_aslr_offset = 0;
316 kern_return_t kret;
317
318 if (macho_size > file_size) {
319 return(LOAD_BADMACHO);
320 }
321
322 if (new_map == VM_MAP_NULL) {
323 create_map = TRUE;
324 old_task = current_task();
325 }
326
327 /*
328 * If we are spawning, we have created backing objects for the process
329 * already, which include non-lazily creating the task map. So we
330 * are going to switch out the task map with one appropriate for the
331 * bitness of the image being loaded.
332 */
333 if (spawn) {
334 create_map = TRUE;
335 old_task = get_threadtask(thread);
336 }
337
338 if (create_map) {
339 task_t ledger_task;
340 if (imgp->ip_new_thread) {
341 ledger_task = get_threadtask(imgp->ip_new_thread);
342 } else {
343 ledger_task = task;
344 }
345 pmap = pmap_create(get_task_ledger(ledger_task),
346 (vm_map_size_t) 0,
347 (imgp->ip_flags & IMGPF_IS_64BIT));
348 pal_switch_pmap(thread, pmap, imgp->ip_flags & IMGPF_IS_64BIT);
349 map = vm_map_create(pmap,
350 0,
351 vm_compute_max_offset((imgp->ip_flags & IMGPF_IS_64BIT)),
352 TRUE);
353 } else
354 map = new_map;
355
356
357 #ifndef CONFIG_ENFORCE_SIGNED_CODE
358 /* This turns off faulting for executable pages, which allows
359 * to circumvent Code Signing Enforcement. The per process
360 * flag (CS_ENFORCEMENT) is not set yet, but we can use the
361 * global flag.
362 */
363 if ( !cs_enforcement(NULL) && (header->flags & MH_ALLOW_STACK_EXECUTION) )
364 vm_map_disable_NX(map);
365 #endif
366
367 /* Forcibly disallow execution from data pages on even if the arch
368 * normally permits it. */
369 if ((header->flags & MH_NO_HEAP_EXECUTION) && !(imgp->ip_flags & IMGPF_ALLOW_DATA_EXEC))
370 vm_map_disallow_data_exec(map);
371
372 /*
373 * Compute a random offset for ASLR, and an independent random offset for dyld.
374 */
375 if (!(imgp->ip_flags & IMGPF_DISABLE_ASLR)) {
376 uint64_t max_slide_pages;
377
378 max_slide_pages = vm_map_get_max_aslr_slide_pages(map);
379
380 aslr_offset = random();
381 aslr_offset %= max_slide_pages;
382 aslr_offset <<= vm_map_page_shift(map);
383
384 dyld_aslr_offset = random();
385 dyld_aslr_offset %= max_slide_pages;
386 dyld_aslr_offset <<= vm_map_page_shift(map);
387 }
388
389 if (!result)
390 result = &myresult;
391
392 *result = load_result_null;
393
394 lret = parse_machfile(vp, map, thread, header, file_offset, macho_size,
395 0, (int64_t)aslr_offset, (int64_t)dyld_aslr_offset, result);
396
397 if (lret != LOAD_SUCCESS) {
398 if (create_map) {
399 vm_map_deallocate(map); /* will lose pmap reference too */
400 }
401 return(lret);
402 }
403
404 #if __x86_64__
405 /*
406 * On x86, for compatibility, don't enforce the hard page-zero restriction for 32-bit binaries.
407 */
408 if ((imgp->ip_flags & IMGPF_IS_64BIT) == 0) {
409 enforce_hard_pagezero = FALSE;
410 }
411 #endif
412 /*
413 * Check to see if the page zero is enforced by the map->min_offset.
414 */
415 if (enforce_hard_pagezero && (vm_map_has_hard_pagezero(map, 0x1000) == FALSE)) {
416 if (create_map) {
417 vm_map_deallocate(map); /* will lose pmap reference too */
418 }
419 printf("Cannot enforce a hard page-zero for %s\n", imgp->ip_strings);
420 return (LOAD_BADMACHO);
421 }
422
423 /*
424 * Commit to new map.
425 *
426 * Swap the new map for the old, which consumes our new map
427 * reference but each leaves us responsible for the old_map reference.
428 * That lets us get off the pmap associated with it, and
429 * then we can release it.
430 */
431
432 if (create_map) {
433 /*
434 * If this is an exec, then we are going to destroy the old
435 * task, and it's correct to halt it; if it's spawn, the
436 * task is not yet running, and it makes no sense.
437 */
438 if (!spawn) {
439 /*
440 * Mark the task as halting and start the other
441 * threads towards terminating themselves. Then
442 * make sure any threads waiting for a process
443 * transition get informed that we are committed to
444 * this transition, and then finally complete the
445 * task halting (wait for threads and then cleanup
446 * task resources).
447 *
448 * NOTE: task_start_halt() makes sure that no new
449 * threads are created in the task during the transition.
450 * We need to mark the workqueue as exiting before we
451 * wait for threads to terminate (at the end of which
452 * we no longer have a prohibition on thread creation).
453 *
454 * Finally, clean up any lingering workqueue data structures
455 * that may have been left behind by the workqueue threads
456 * as they exited (and then clean up the work queue itself).
457 */
458 kret = task_start_halt(task);
459 if (kret != KERN_SUCCESS) {
460 vm_map_deallocate(map); /* will lose pmap reference too */
461 return (LOAD_FAILURE);
462 }
463 proc_transcommit(p, 0);
464 workqueue_mark_exiting(p);
465 task_complete_halt(task);
466 workqueue_exit(p);
467 }
468 old_map = swap_task_map(old_task, thread, map, !spawn);
469 vm_map_deallocate(old_map);
470 }
471 return(LOAD_SUCCESS);
472 }
473
474 /*
475 * The file size of a mach-o file is limited to 32 bits; this is because
476 * this is the limit on the kalloc() of enough bytes for a mach_header and
477 * the contents of its sizeofcmds, which is currently constrained to 32
478 * bits in the file format itself. We read into the kernel buffer the
479 * commands section, and then parse it in order to parse the mach-o file
480 * format load_command segment(s). We are only interested in a subset of
481 * the total set of possible commands. If "map"==VM_MAP_NULL or
482 * "thread"==THREAD_NULL, do not make permament VM modifications,
483 * just preflight the parse.
484 */
485 static
486 load_return_t
487 parse_machfile(
488 struct vnode *vp,
489 vm_map_t map,
490 thread_t thread,
491 struct mach_header *header,
492 off_t file_offset,
493 off_t macho_size,
494 int depth,
495 int64_t aslr_offset,
496 int64_t dyld_aslr_offset,
497 load_result_t *result
498 )
499 {
500 uint32_t ncmds;
501 struct load_command *lcp;
502 struct dylinker_command *dlp = 0;
503 integer_t dlarchbits = 0;
504 void * control;
505 load_return_t ret = LOAD_SUCCESS;
506 caddr_t addr;
507 void * kl_addr;
508 vm_size_t size,kl_size;
509 size_t offset;
510 size_t oldoffset; /* for overflow check */
511 int pass;
512 proc_t p = current_proc(); /* XXXX */
513 int error;
514 int resid=0;
515 size_t mach_header_sz = sizeof(struct mach_header);
516 boolean_t abi64;
517 boolean_t got_code_signatures = FALSE;
518 int64_t slide = 0;
519
520 if (header->magic == MH_MAGIC_64 ||
521 header->magic == MH_CIGAM_64) {
522 mach_header_sz = sizeof(struct mach_header_64);
523 }
524
525 /*
526 * Break infinite recursion
527 */
528 if (depth > 1) {
529 return(LOAD_FAILURE);
530 }
531
532 depth++;
533
534 /*
535 * Check to see if right machine type.
536 */
537 if (((cpu_type_t)(header->cputype & ~CPU_ARCH_MASK) != (cpu_type() & ~CPU_ARCH_MASK)) ||
538 !grade_binary(header->cputype,
539 header->cpusubtype & ~CPU_SUBTYPE_MASK))
540 return(LOAD_BADARCH);
541
542 abi64 = ((header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64);
543
544 switch (header->filetype) {
545
546 case MH_EXECUTE:
547 if (depth != 1) {
548 return (LOAD_FAILURE);
549 }
550
551 break;
552 case MH_DYLINKER:
553 if (depth != 2) {
554 return (LOAD_FAILURE);
555 }
556 break;
557
558 default:
559 return (LOAD_FAILURE);
560 }
561
562 /*
563 * Get the pager for the file.
564 */
565 control = ubc_getobject(vp, UBC_FLAGS_NONE);
566
567 /*
568 * Map portion that must be accessible directly into
569 * kernel's map.
570 */
571 if ((off_t)(mach_header_sz + header->sizeofcmds) > macho_size)
572 return(LOAD_BADMACHO);
573
574 /*
575 * Round size of Mach-O commands up to page boundry.
576 */
577 size = round_page(mach_header_sz + header->sizeofcmds);
578 if (size <= 0)
579 return(LOAD_BADMACHO);
580
581 /*
582 * Map the load commands into kernel memory.
583 */
584 addr = 0;
585 kl_size = size;
586 kl_addr = kalloc(size);
587 addr = (caddr_t)kl_addr;
588 if (addr == NULL)
589 return(LOAD_NOSPACE);
590
591 error = vn_rdwr(UIO_READ, vp, addr, size, file_offset,
592 UIO_SYSSPACE, 0, kauth_cred_get(), &resid, p);
593 if (error) {
594 if (kl_addr)
595 kfree(kl_addr, kl_size);
596 return(LOAD_IOERROR);
597 }
598
599 if (resid) {
600 /* We must be able to read in as much as the mach_header indicated */
601 if (kl_addr)
602 kfree(kl_addr, kl_size);
603 return(LOAD_BADMACHO);
604 }
605
606 /*
607 * For PIE and dyld, slide everything by the ASLR offset.
608 */
609 if ((header->flags & MH_PIE) || (header->filetype == MH_DYLINKER)) {
610 slide = aslr_offset;
611 }
612
613 /*
614 * Scan through the commands, processing each one as necessary.
615 * We parse in three passes through the headers:
616 * 1: thread state, uuid, code signature
617 * 2: segments
618 * 3: dyld, encryption, check entry point
619 */
620
621 for (pass = 1; pass <= 3; pass++) {
622
623 /*
624 * Check that the entry point is contained in an executable segments
625 */
626 if ((pass == 3) && (!result->using_lcmain && result->validentry == 0)) {
627 thread_state_initialize(thread);
628 ret = LOAD_FAILURE;
629 break;
630 }
631
632 /*
633 * Loop through each of the load_commands indicated by the
634 * Mach-O header; if an absurd value is provided, we just
635 * run off the end of the reserved section by incrementing
636 * the offset too far, so we are implicitly fail-safe.
637 */
638 offset = mach_header_sz;
639 ncmds = header->ncmds;
640
641 while (ncmds--) {
642 /*
643 * Get a pointer to the command.
644 */
645 lcp = (struct load_command *)(addr + offset);
646 oldoffset = offset;
647 offset += lcp->cmdsize;
648
649 /*
650 * Perform prevalidation of the struct load_command
651 * before we attempt to use its contents. Invalid
652 * values are ones which result in an overflow, or
653 * which can not possibly be valid commands, or which
654 * straddle or exist past the reserved section at the
655 * start of the image.
656 */
657 if (oldoffset > offset ||
658 lcp->cmdsize < sizeof(struct load_command) ||
659 offset > header->sizeofcmds + mach_header_sz) {
660 ret = LOAD_BADMACHO;
661 break;
662 }
663
664 /*
665 * Act on struct load_command's for which kernel
666 * intervention is required.
667 */
668 switch(lcp->cmd) {
669 case LC_SEGMENT:
670 if (pass != 2)
671 break;
672
673 if (abi64) {
674 /*
675 * Having an LC_SEGMENT command for the
676 * wrong ABI is invalid <rdar://problem/11021230>
677 */
678 ret = LOAD_BADMACHO;
679 break;
680 }
681
682 ret = load_segment(lcp,
683 header->filetype,
684 control,
685 file_offset,
686 macho_size,
687 vp,
688 map,
689 slide,
690 result);
691 break;
692 case LC_SEGMENT_64:
693 if (pass != 2)
694 break;
695
696 if (!abi64) {
697 /*
698 * Having an LC_SEGMENT_64 command for the
699 * wrong ABI is invalid <rdar://problem/11021230>
700 */
701 ret = LOAD_BADMACHO;
702 break;
703 }
704
705 ret = load_segment(lcp,
706 header->filetype,
707 control,
708 file_offset,
709 macho_size,
710 vp,
711 map,
712 slide,
713 result);
714 break;
715 case LC_UNIXTHREAD:
716 if (pass != 1)
717 break;
718 ret = load_unixthread(
719 (struct thread_command *) lcp,
720 thread,
721 slide,
722 result);
723 break;
724 case LC_MAIN:
725 if (pass != 1)
726 break;
727 if (depth != 1)
728 break;
729 ret = load_main(
730 (struct entry_point_command *) lcp,
731 thread,
732 slide,
733 result);
734 break;
735 case LC_LOAD_DYLINKER:
736 if (pass != 3)
737 break;
738 if ((depth == 1) && (dlp == 0)) {
739 dlp = (struct dylinker_command *)lcp;
740 dlarchbits = (header->cputype & CPU_ARCH_MASK);
741 } else {
742 ret = LOAD_FAILURE;
743 }
744 break;
745 case LC_UUID:
746 if (pass == 1 && depth == 1) {
747 ret = load_uuid((struct uuid_command *) lcp,
748 (char *)addr + mach_header_sz + header->sizeofcmds,
749 result);
750 }
751 break;
752 case LC_CODE_SIGNATURE:
753 /* CODE SIGNING */
754 if (pass != 1)
755 break;
756 /* pager -> uip ->
757 load signatures & store in uip
758 set VM object "signed_pages"
759 */
760 ret = load_code_signature(
761 (struct linkedit_data_command *) lcp,
762 vp,
763 file_offset,
764 macho_size,
765 header->cputype,
766 result);
767 if (ret != LOAD_SUCCESS) {
768 printf("proc %d: load code signature error %d "
769 "for file \"%s\"\n",
770 p->p_pid, ret, vp->v_name);
771 /*
772 * Allow injections to be ignored on devices w/o enforcement enabled
773 */
774 if (!cs_enforcement(NULL))
775 ret = LOAD_SUCCESS; /* ignore error */
776
777 } else {
778 got_code_signatures = TRUE;
779 }
780
781 if (got_code_signatures) {
782 unsigned tainted = CS_VALIDATE_TAINTED;
783 boolean_t valid = FALSE;
784 struct cs_blob *blobs;
785 vm_size_t off = 0;
786
787
788 if (cs_debug > 10)
789 printf("validating initial pages of %s\n", vp->v_name);
790 blobs = ubc_get_cs_blobs(vp);
791
792 while (off < size && ret == LOAD_SUCCESS) {
793 tainted = CS_VALIDATE_TAINTED;
794
795 valid = cs_validate_page(blobs,
796 NULL,
797 file_offset + off,
798 addr + off,
799 &tainted);
800 if (!valid || (tainted & CS_VALIDATE_TAINTED)) {
801 if (cs_debug)
802 printf("CODE SIGNING: %s[%d]: invalid initial page at offset %lld validated:%d tainted:%d csflags:0x%x\n",
803 vp->v_name, p->p_pid, (long long)(file_offset + off), valid, tainted, result->csflags);
804 if (cs_enforcement(NULL) ||
805 (result->csflags & (CS_HARD|CS_KILL|CS_ENFORCEMENT))) {
806 ret = LOAD_FAILURE;
807 }
808 result->csflags &= ~CS_VALID;
809 }
810 off += PAGE_SIZE;
811 }
812 }
813
814 break;
815 #if CONFIG_CODE_DECRYPTION
816 case LC_ENCRYPTION_INFO:
817 case LC_ENCRYPTION_INFO_64:
818 if (pass != 3)
819 break;
820 ret = set_code_unprotect(
821 (struct encryption_info_command *) lcp,
822 addr, map, slide, vp,
823 header->cputype, header->cpusubtype);
824 if (ret != LOAD_SUCCESS) {
825 printf("proc %d: set_code_unprotect() error %d "
826 "for file \"%s\"\n",
827 p->p_pid, ret, vp->v_name);
828 /*
829 * Don't let the app run if it's
830 * encrypted but we failed to set up the
831 * decrypter. If the keys are missing it will
832 * return LOAD_DECRYPTFAIL.
833 */
834 if (ret == LOAD_DECRYPTFAIL) {
835 /* failed to load due to missing FP keys */
836 proc_lock(p);
837 p->p_lflag |= P_LTERM_DECRYPTFAIL;
838 proc_unlock(p);
839 }
840 psignal(p, SIGKILL);
841 }
842 break;
843 #endif
844 default:
845 /* Other commands are ignored by the kernel */
846 ret = LOAD_SUCCESS;
847 break;
848 }
849 if (ret != LOAD_SUCCESS)
850 break;
851 }
852 if (ret != LOAD_SUCCESS)
853 break;
854 }
855
856 if (ret == LOAD_SUCCESS) {
857 if (! got_code_signatures) {
858 if (cs_enforcement(NULL)) {
859 ret = LOAD_FAILURE;
860 } else {
861 /*
862 * No embedded signatures: look for detached by taskgated,
863 * this is only done on OSX, on embedded platforms we expect everything
864 * to be have embedded signatures.
865 */
866 struct cs_blob *blob;
867
868 blob = ubc_cs_blob_get(vp, -1, file_offset);
869 if (blob != NULL) {
870 unsigned int cs_flag_data = blob->csb_flags;
871 if(0 != ubc_cs_generation_check(vp)) {
872 if (0 != ubc_cs_blob_revalidate(vp, blob, 0)) {
873 /* clear out the flag data if revalidation fails */
874 cs_flag_data = 0;
875 result->csflags &= ~CS_VALID;
876 }
877 }
878 /* get flags to be applied to the process */
879 result->csflags |= cs_flag_data;
880 }
881 }
882 }
883
884 /* Make sure if we need dyld, we got it */
885 if ((ret == LOAD_SUCCESS) && result->needs_dynlinker && !dlp) {
886 ret = LOAD_FAILURE;
887 }
888
889 if ((ret == LOAD_SUCCESS) && (dlp != 0)) {
890 /*
891 * load the dylinker, and slide it by the independent DYLD ASLR
892 * offset regardless of the PIE-ness of the main binary.
893 */
894 ret = load_dylinker(dlp, dlarchbits, map, thread, depth,
895 dyld_aslr_offset, result);
896 }
897
898 if((ret == LOAD_SUCCESS) && (depth == 1)) {
899 if (result->thread_count == 0) {
900 ret = LOAD_FAILURE;
901 }
902 }
903 }
904
905 if (kl_addr )
906 kfree(kl_addr, kl_size);
907
908 return(ret);
909 }
910
911 #if CONFIG_CODE_DECRYPTION
912
913 #define APPLE_UNPROTECTED_HEADER_SIZE (3 * PAGE_SIZE_64)
914
915 static load_return_t
916 unprotect_dsmos_segment(
917 uint64_t file_off,
918 uint64_t file_size,
919 struct vnode *vp,
920 off_t macho_offset,
921 vm_map_t map,
922 vm_map_offset_t map_addr,
923 vm_map_size_t map_size)
924 {
925 kern_return_t kr;
926
927 /*
928 * The first APPLE_UNPROTECTED_HEADER_SIZE bytes (from offset 0 of
929 * this part of a Universal binary) are not protected...
930 * The rest needs to be "transformed".
931 */
932 if (file_off <= APPLE_UNPROTECTED_HEADER_SIZE &&
933 file_off + file_size <= APPLE_UNPROTECTED_HEADER_SIZE) {
934 /* it's all unprotected, nothing to do... */
935 kr = KERN_SUCCESS;
936 } else {
937 if (file_off <= APPLE_UNPROTECTED_HEADER_SIZE) {
938 /*
939 * We start mapping in the unprotected area.
940 * Skip the unprotected part...
941 */
942 vm_map_offset_t delta;
943
944 delta = APPLE_UNPROTECTED_HEADER_SIZE;
945 delta -= file_off;
946 map_addr += delta;
947 map_size -= delta;
948 }
949 /* ... transform the rest of the mapping. */
950 struct pager_crypt_info crypt_info;
951 crypt_info.page_decrypt = dsmos_page_transform;
952 crypt_info.crypt_ops = NULL;
953 crypt_info.crypt_end = NULL;
954 #pragma unused(vp, macho_offset)
955 crypt_info.crypt_ops = (void *)0x2e69cf40;
956 kr = vm_map_apple_protected(map,
957 map_addr,
958 map_addr + map_size,
959 &crypt_info);
960 }
961
962 if (kr != KERN_SUCCESS) {
963 return LOAD_FAILURE;
964 }
965 return LOAD_SUCCESS;
966 }
967 #else /* CONFIG_CODE_DECRYPTION */
968 static load_return_t
969 unprotect_dsmos_segment(
970 __unused uint64_t file_off,
971 __unused uint64_t file_size,
972 __unused struct vnode *vp,
973 __unused off_t macho_offset,
974 __unused vm_map_t map,
975 __unused vm_map_offset_t map_addr,
976 __unused vm_map_size_t map_size)
977 {
978 return LOAD_SUCCESS;
979 }
980 #endif /* CONFIG_CODE_DECRYPTION */
981
982 static
983 load_return_t
984 load_segment(
985 struct load_command *lcp,
986 uint32_t filetype,
987 void * control,
988 off_t pager_offset,
989 off_t macho_size,
990 struct vnode *vp,
991 vm_map_t map,
992 int64_t slide,
993 load_result_t *result
994 )
995 {
996 struct segment_command_64 segment_command, *scp;
997 kern_return_t ret;
998 vm_map_offset_t map_addr, map_offset;
999 vm_map_size_t map_size, seg_size, delta_size;
1000 vm_prot_t initprot;
1001 vm_prot_t maxprot;
1002 size_t segment_command_size, total_section_size,
1003 single_section_size;
1004
1005 if (LC_SEGMENT_64 == lcp->cmd) {
1006 segment_command_size = sizeof(struct segment_command_64);
1007 single_section_size = sizeof(struct section_64);
1008 } else {
1009 segment_command_size = sizeof(struct segment_command);
1010 single_section_size = sizeof(struct section);
1011 }
1012 if (lcp->cmdsize < segment_command_size)
1013 return (LOAD_BADMACHO);
1014 total_section_size = lcp->cmdsize - segment_command_size;
1015
1016 if (LC_SEGMENT_64 == lcp->cmd)
1017 scp = (struct segment_command_64 *)lcp;
1018 else {
1019 scp = &segment_command;
1020 widen_segment_command((struct segment_command *)lcp, scp);
1021 }
1022
1023 /*
1024 * Make sure what we get from the file is really ours (as specified
1025 * by macho_size).
1026 */
1027 if (scp->fileoff + scp->filesize < scp->fileoff ||
1028 scp->fileoff + scp->filesize > (uint64_t)macho_size)
1029 return (LOAD_BADMACHO);
1030 /*
1031 * Ensure that the number of sections specified would fit
1032 * within the load command size.
1033 */
1034 if (total_section_size / single_section_size < scp->nsects)
1035 return (LOAD_BADMACHO);
1036 /*
1037 * Make sure the segment is page-aligned in the file.
1038 */
1039 if ((scp->fileoff & PAGE_MASK_64) != 0)
1040 return (LOAD_BADMACHO);
1041
1042 /*
1043 * If we have a code signature attached for this slice
1044 * require that the segments are within the signed part
1045 * of the file.
1046 */
1047 if (result->cs_end_offset &&
1048 result->cs_end_offset < (off_t)scp->fileoff &&
1049 result->cs_end_offset - scp->fileoff < scp->filesize)
1050 {
1051 if (cs_debug)
1052 printf("section outside code signature\n");
1053 return LOAD_BADMACHO;
1054 }
1055
1056 /*
1057 * Round sizes to page size.
1058 */
1059 seg_size = round_page_64(scp->vmsize);
1060 map_size = round_page_64(scp->filesize);
1061 map_addr = trunc_page_64(scp->vmaddr); /* JVXXX note that in XNU TOT this is round instead of trunc for 64 bits */
1062
1063 seg_size = vm_map_round_page(seg_size, vm_map_page_mask(map));
1064 map_size = vm_map_round_page(map_size, vm_map_page_mask(map));
1065
1066 if (seg_size == 0)
1067 return (KERN_SUCCESS);
1068 if (map_addr == 0 &&
1069 map_size == 0 &&
1070 seg_size != 0 &&
1071 (scp->initprot & VM_PROT_ALL) == VM_PROT_NONE &&
1072 (scp->maxprot & VM_PROT_ALL) == VM_PROT_NONE) {
1073 /*
1074 * For PIE, extend page zero rather than moving it. Extending
1075 * page zero keeps early allocations from falling predictably
1076 * between the end of page zero and the beginning of the first
1077 * slid segment.
1078 */
1079 seg_size += slide;
1080 slide = 0;
1081
1082 /*
1083 * This is a "page zero" segment: it starts at address 0,
1084 * is not mapped from the binary file and is not accessible.
1085 * User-space should never be able to access that memory, so
1086 * make it completely off limits by raising the VM map's
1087 * minimum offset.
1088 */
1089 ret = vm_map_raise_min_offset(map, seg_size);
1090 if (ret != KERN_SUCCESS) {
1091 return (LOAD_FAILURE);
1092 }
1093 return (LOAD_SUCCESS);
1094 }
1095
1096 /* If a non-zero slide was specified by the caller, apply now */
1097 map_addr += slide;
1098
1099 if (map_addr < result->min_vm_addr)
1100 result->min_vm_addr = map_addr;
1101 if (map_addr+seg_size > result->max_vm_addr)
1102 result->max_vm_addr = map_addr+seg_size;
1103
1104 if (map == VM_MAP_NULL)
1105 return (LOAD_SUCCESS);
1106
1107 map_offset = pager_offset + scp->fileoff; /* limited to 32 bits */
1108
1109 if (map_size > 0) {
1110 initprot = (scp->initprot) & VM_PROT_ALL;
1111 maxprot = (scp->maxprot) & VM_PROT_ALL;
1112 /*
1113 * Map a copy of the file into the address space.
1114 */
1115 ret = vm_map_enter_mem_object_control(map,
1116 &map_addr, map_size, (mach_vm_offset_t)0,
1117 VM_FLAGS_FIXED, control, map_offset, TRUE,
1118 initprot, maxprot,
1119 VM_INHERIT_DEFAULT);
1120 if (ret != KERN_SUCCESS) {
1121 return (LOAD_NOSPACE);
1122 }
1123
1124 /*
1125 * If the file didn't end on a page boundary,
1126 * we need to zero the leftover.
1127 */
1128 delta_size = map_size - scp->filesize;
1129 #if FIXME
1130 if (delta_size > 0) {
1131 mach_vm_offset_t tmp;
1132
1133 ret = mach_vm_allocate(kernel_map, &tmp, delta_size, VM_FLAGS_ANYWHERE);
1134 if (ret != KERN_SUCCESS)
1135 return(LOAD_RESOURCE);
1136
1137 if (copyout(tmp, map_addr + scp->filesize,
1138 delta_size)) {
1139 (void) mach_vm_deallocate(
1140 kernel_map, tmp, delta_size);
1141 return (LOAD_FAILURE);
1142 }
1143
1144 (void) mach_vm_deallocate(kernel_map, tmp, delta_size);
1145 }
1146 #endif /* FIXME */
1147 }
1148
1149 /*
1150 * If the virtual size of the segment is greater
1151 * than the size from the file, we need to allocate
1152 * zero fill memory for the rest.
1153 */
1154 delta_size = seg_size - map_size;
1155 if (delta_size > 0) {
1156 mach_vm_offset_t tmp = map_addr + map_size;
1157
1158 ret = mach_vm_map(map, &tmp, delta_size, 0, VM_FLAGS_FIXED,
1159 NULL, 0, FALSE,
1160 scp->initprot, scp->maxprot,
1161 VM_INHERIT_DEFAULT);
1162 if (ret != KERN_SUCCESS)
1163 return(LOAD_NOSPACE);
1164 }
1165
1166 if ( (scp->fileoff == 0) && (scp->filesize != 0) )
1167 result->mach_header = map_addr;
1168
1169 if (scp->flags & SG_PROTECTED_VERSION_1) {
1170 ret = unprotect_dsmos_segment(scp->fileoff,
1171 scp->filesize,
1172 vp,
1173 pager_offset,
1174 map,
1175 map_addr,
1176 map_size);
1177 } else {
1178 ret = LOAD_SUCCESS;
1179 }
1180 if (LOAD_SUCCESS == ret && filetype == MH_DYLINKER &&
1181 result->all_image_info_addr == MACH_VM_MIN_ADDRESS)
1182 note_all_image_info_section(scp,
1183 LC_SEGMENT_64 == lcp->cmd, single_section_size,
1184 (const char *)lcp + segment_command_size, slide, result);
1185
1186 if (result->entry_point != MACH_VM_MIN_ADDRESS) {
1187 if ((result->entry_point >= map_addr) && (result->entry_point < (map_addr + map_size))) {
1188 if ((scp->initprot & (VM_PROT_READ|VM_PROT_EXECUTE)) == (VM_PROT_READ|VM_PROT_EXECUTE)) {
1189 result->validentry = 1;
1190 } else {
1191 /* right range but wrong protections, unset if previously validated */
1192 result->validentry = 0;
1193 }
1194 }
1195 }
1196
1197 return ret;
1198 }
1199
1200 static
1201 load_return_t
1202 load_uuid(
1203 struct uuid_command *uulp,
1204 char *command_end,
1205 load_result_t *result
1206 )
1207 {
1208 /*
1209 * We need to check the following for this command:
1210 * - The command size should be atleast the size of struct uuid_command
1211 * - The UUID part of the command should be completely within the mach-o header
1212 */
1213
1214 if ((uulp->cmdsize < sizeof(struct uuid_command)) ||
1215 (((char *)uulp + sizeof(struct uuid_command)) > command_end)) {
1216 return (LOAD_BADMACHO);
1217 }
1218
1219 memcpy(&result->uuid[0], &uulp->uuid[0], sizeof(result->uuid));
1220 return (LOAD_SUCCESS);
1221 }
1222
1223 static
1224 load_return_t
1225 load_main(
1226 struct entry_point_command *epc,
1227 thread_t thread,
1228 int64_t slide,
1229 load_result_t *result
1230 )
1231 {
1232 mach_vm_offset_t addr;
1233 kern_return_t ret;
1234
1235 if (epc->cmdsize < sizeof(*epc))
1236 return (LOAD_BADMACHO);
1237 if (result->thread_count != 0) {
1238 return (LOAD_FAILURE);
1239 }
1240
1241 if (thread == THREAD_NULL)
1242 return (LOAD_SUCCESS);
1243
1244 /* LC_MAIN specifies stack size but not location */
1245 if (epc->stacksize) {
1246 result->prog_stack_size = 1;
1247 result->user_stack_size = epc->stacksize;
1248 } else {
1249 result->prog_stack_size = 0;
1250 result->user_stack_size = MAXSSIZ;
1251 }
1252 result->prog_allocated_stack = 0;
1253
1254 /* use default location for stack */
1255 ret = thread_userstackdefault(thread, &addr);
1256 if (ret != KERN_SUCCESS)
1257 return(LOAD_FAILURE);
1258
1259 /* The stack slides down from the default location */
1260 result->user_stack = addr;
1261 result->user_stack -= slide;
1262
1263 if (result->using_lcmain || result->entry_point != MACH_VM_MIN_ADDRESS) {
1264 /* Already processed LC_MAIN or LC_UNIXTHREAD */
1265 return (LOAD_FAILURE);
1266 }
1267
1268 /* kernel does *not* use entryoff from LC_MAIN. Dyld uses it. */
1269 result->needs_dynlinker = TRUE;
1270 result->using_lcmain = TRUE;
1271
1272 ret = thread_state_initialize( thread );
1273 if (ret != KERN_SUCCESS) {
1274 return(LOAD_FAILURE);
1275 }
1276
1277 result->unixproc = TRUE;
1278 result->thread_count++;
1279
1280 return(LOAD_SUCCESS);
1281 }
1282
1283
1284 static
1285 load_return_t
1286 load_unixthread(
1287 struct thread_command *tcp,
1288 thread_t thread,
1289 int64_t slide,
1290 load_result_t *result
1291 )
1292 {
1293 load_return_t ret;
1294 int customstack =0;
1295 mach_vm_offset_t addr;
1296
1297 if (tcp->cmdsize < sizeof(*tcp))
1298 return (LOAD_BADMACHO);
1299 if (result->thread_count != 0) {
1300 return (LOAD_FAILURE);
1301 }
1302
1303 if (thread == THREAD_NULL)
1304 return (LOAD_SUCCESS);
1305
1306 ret = load_threadstack(thread,
1307 (uint32_t *)(((vm_offset_t)tcp) +
1308 sizeof(struct thread_command)),
1309 tcp->cmdsize - sizeof(struct thread_command),
1310 &addr,
1311 &customstack);
1312 if (ret != LOAD_SUCCESS)
1313 return(ret);
1314
1315 /* LC_UNIXTHREAD optionally specifies stack size and location */
1316
1317 if (customstack) {
1318 result->prog_stack_size = 0; /* unknown */
1319 result->prog_allocated_stack = 1;
1320 } else {
1321 result->prog_allocated_stack = 0;
1322 result->prog_stack_size = 0;
1323 result->user_stack_size = MAXSSIZ;
1324 }
1325
1326 /* The stack slides down from the default location */
1327 result->user_stack = addr;
1328 result->user_stack -= slide;
1329
1330 ret = load_threadentry(thread,
1331 (uint32_t *)(((vm_offset_t)tcp) +
1332 sizeof(struct thread_command)),
1333 tcp->cmdsize - sizeof(struct thread_command),
1334 &addr);
1335 if (ret != LOAD_SUCCESS)
1336 return(ret);
1337
1338 if (result->using_lcmain || result->entry_point != MACH_VM_MIN_ADDRESS) {
1339 /* Already processed LC_MAIN or LC_UNIXTHREAD */
1340 return (LOAD_FAILURE);
1341 }
1342
1343 result->entry_point = addr;
1344 result->entry_point += slide;
1345
1346 ret = load_threadstate(thread,
1347 (uint32_t *)(((vm_offset_t)tcp) +
1348 sizeof(struct thread_command)),
1349 tcp->cmdsize - sizeof(struct thread_command));
1350 if (ret != LOAD_SUCCESS)
1351 return (ret);
1352
1353 result->unixproc = TRUE;
1354 result->thread_count++;
1355
1356 return(LOAD_SUCCESS);
1357 }
1358
1359 static
1360 load_return_t
1361 load_threadstate(
1362 thread_t thread,
1363 uint32_t *ts,
1364 uint32_t total_size
1365 )
1366 {
1367 kern_return_t ret;
1368 uint32_t size;
1369 int flavor;
1370 uint32_t thread_size;
1371 uint32_t *local_ts;
1372 uint32_t local_ts_size;
1373
1374 local_ts = NULL;
1375 local_ts_size = 0;
1376
1377 ret = thread_state_initialize( thread );
1378 if (ret != KERN_SUCCESS) {
1379 ret = LOAD_FAILURE;
1380 goto done;
1381 }
1382
1383 if (total_size > 0) {
1384 local_ts_size = total_size;
1385 local_ts = kalloc(local_ts_size);
1386 if (local_ts == NULL) {
1387 ret = LOAD_FAILURE;
1388 goto done;
1389 }
1390 memcpy(local_ts, ts, local_ts_size);
1391 ts = local_ts;
1392 }
1393
1394 /*
1395 * Set the new thread state; iterate through the state flavors in
1396 * the mach-o file.
1397 */
1398 while (total_size > 0) {
1399 flavor = *ts++;
1400 size = *ts++;
1401 if (UINT32_MAX-2 < size ||
1402 UINT32_MAX/sizeof(uint32_t) < size+2) {
1403 ret = LOAD_BADMACHO;
1404 goto done;
1405 }
1406 thread_size = (size+2)*sizeof(uint32_t);
1407 if (thread_size > total_size) {
1408 ret = LOAD_BADMACHO;
1409 goto done;
1410 }
1411 total_size -= thread_size;
1412 /*
1413 * Third argument is a kernel space pointer; it gets cast
1414 * to the appropriate type in machine_thread_set_state()
1415 * based on the value of flavor.
1416 */
1417 ret = thread_setstatus(thread, flavor, (thread_state_t)ts, size);
1418 if (ret != KERN_SUCCESS) {
1419 ret = LOAD_FAILURE;
1420 goto done;
1421 }
1422 ts += size; /* ts is a (uint32_t *) */
1423 }
1424 ret = LOAD_SUCCESS;
1425
1426 done:
1427 if (local_ts != NULL) {
1428 kfree(local_ts, local_ts_size);
1429 local_ts = NULL;
1430 }
1431 return ret;
1432 }
1433
1434 static
1435 load_return_t
1436 load_threadstack(
1437 thread_t thread,
1438 uint32_t *ts,
1439 uint32_t total_size,
1440 mach_vm_offset_t *user_stack,
1441 int *customstack
1442 )
1443 {
1444 kern_return_t ret;
1445 uint32_t size;
1446 int flavor;
1447 uint32_t stack_size;
1448
1449 while (total_size > 0) {
1450 flavor = *ts++;
1451 size = *ts++;
1452 if (UINT32_MAX-2 < size ||
1453 UINT32_MAX/sizeof(uint32_t) < size+2)
1454 return (LOAD_BADMACHO);
1455 stack_size = (size+2)*sizeof(uint32_t);
1456 if (stack_size > total_size)
1457 return(LOAD_BADMACHO);
1458 total_size -= stack_size;
1459
1460 /*
1461 * Third argument is a kernel space pointer; it gets cast
1462 * to the appropriate type in thread_userstack() based on
1463 * the value of flavor.
1464 */
1465 ret = thread_userstack(thread, flavor, (thread_state_t)ts, size, user_stack, customstack);
1466 if (ret != KERN_SUCCESS) {
1467 return(LOAD_FAILURE);
1468 }
1469 ts += size; /* ts is a (uint32_t *) */
1470 }
1471 return(LOAD_SUCCESS);
1472 }
1473
1474 static
1475 load_return_t
1476 load_threadentry(
1477 thread_t thread,
1478 uint32_t *ts,
1479 uint32_t total_size,
1480 mach_vm_offset_t *entry_point
1481 )
1482 {
1483 kern_return_t ret;
1484 uint32_t size;
1485 int flavor;
1486 uint32_t entry_size;
1487
1488 /*
1489 * Set the thread state.
1490 */
1491 *entry_point = MACH_VM_MIN_ADDRESS;
1492 while (total_size > 0) {
1493 flavor = *ts++;
1494 size = *ts++;
1495 if (UINT32_MAX-2 < size ||
1496 UINT32_MAX/sizeof(uint32_t) < size+2)
1497 return (LOAD_BADMACHO);
1498 entry_size = (size+2)*sizeof(uint32_t);
1499 if (entry_size > total_size)
1500 return(LOAD_BADMACHO);
1501 total_size -= entry_size;
1502 /*
1503 * Third argument is a kernel space pointer; it gets cast
1504 * to the appropriate type in thread_entrypoint() based on
1505 * the value of flavor.
1506 */
1507 ret = thread_entrypoint(thread, flavor, (thread_state_t)ts, size, entry_point);
1508 if (ret != KERN_SUCCESS) {
1509 return(LOAD_FAILURE);
1510 }
1511 ts += size; /* ts is a (uint32_t *) */
1512 }
1513 return(LOAD_SUCCESS);
1514 }
1515
1516 struct macho_data {
1517 struct nameidata __nid;
1518 union macho_vnode_header {
1519 struct mach_header mach_header;
1520 struct fat_header fat_header;
1521 char __pad[512];
1522 } __header;
1523 };
1524
1525 #define DEFAULT_DYLD_PATH "/usr/lib/dyld"
1526
1527 static load_return_t
1528 load_dylinker(
1529 struct dylinker_command *lcp,
1530 integer_t archbits,
1531 vm_map_t map,
1532 thread_t thread,
1533 int depth,
1534 int64_t slide,
1535 load_result_t *result
1536 )
1537 {
1538 char *name;
1539 char *p;
1540 struct vnode *vp = NULLVP; /* set by get_macho_vnode() */
1541 struct mach_header *header;
1542 off_t file_offset = 0; /* set by get_macho_vnode() */
1543 off_t macho_size = 0; /* set by get_macho_vnode() */
1544 load_result_t *myresult;
1545 kern_return_t ret;
1546 struct macho_data *macho_data;
1547 struct {
1548 struct mach_header __header;
1549 load_result_t __myresult;
1550 struct macho_data __macho_data;
1551 } *dyld_data;
1552
1553 if (lcp->cmdsize < sizeof(*lcp))
1554 return (LOAD_BADMACHO);
1555
1556 name = (char *)lcp + lcp->name.offset;
1557 /*
1558 * Check for a proper null terminated string.
1559 */
1560 p = name;
1561 do {
1562 if (p >= (char *)lcp + lcp->cmdsize)
1563 return(LOAD_BADMACHO);
1564 } while (*p++);
1565
1566 #if !(DEVELOPMENT || DEBUG)
1567 if (0 != strcmp(name, DEFAULT_DYLD_PATH)) {
1568 return (LOAD_BADMACHO);
1569 }
1570 #endif
1571
1572 /* Allocate wad-of-data from heap to reduce excessively deep stacks */
1573
1574 MALLOC(dyld_data, void *, sizeof (*dyld_data), M_TEMP, M_WAITOK);
1575 header = &dyld_data->__header;
1576 myresult = &dyld_data->__myresult;
1577 macho_data = &dyld_data->__macho_data;
1578
1579 ret = get_macho_vnode(name, archbits, header,
1580 &file_offset, &macho_size, macho_data, &vp);
1581 if (ret)
1582 goto novp_out;
1583
1584 *myresult = load_result_null;
1585
1586 /*
1587 * First try to map dyld in directly. This should work most of
1588 * the time since there shouldn't normally be something already
1589 * mapped to its address.
1590 */
1591
1592 ret = parse_machfile(vp, map, thread, header, file_offset,
1593 macho_size, depth, slide, 0, myresult);
1594
1595 /*
1596 * If it turned out something was in the way, then we'll take
1597 * take this longer path to preflight dyld's vm ranges, then
1598 * map it at a free location in the address space.
1599 */
1600
1601 if (ret == LOAD_NOSPACE) {
1602 mach_vm_offset_t dyl_start, map_addr;
1603 mach_vm_size_t dyl_length;
1604 int64_t slide_amount;
1605
1606 *myresult = load_result_null;
1607
1608 /*
1609 * Preflight parsing the Mach-O file with a NULL
1610 * map, which will return the ranges needed for a
1611 * subsequent map attempt (with a slide) in "myresult"
1612 */
1613 ret = parse_machfile(vp, VM_MAP_NULL, THREAD_NULL, header,
1614 file_offset, macho_size, depth,
1615 0 /* slide */, 0, myresult);
1616
1617 if (ret != LOAD_SUCCESS) {
1618 goto out;
1619 }
1620
1621 dyl_start = myresult->min_vm_addr;
1622 dyl_length = myresult->max_vm_addr - myresult->min_vm_addr;
1623
1624 dyl_length += slide;
1625
1626 /* To find an appropriate load address, do a quick allocation */
1627 map_addr = dyl_start;
1628 ret = mach_vm_allocate(map, &map_addr, dyl_length, VM_FLAGS_ANYWHERE);
1629 if (ret != KERN_SUCCESS) {
1630 ret = LOAD_NOSPACE;
1631 goto out;
1632 }
1633
1634 ret = mach_vm_deallocate(map, map_addr, dyl_length);
1635 if (ret != KERN_SUCCESS) {
1636 ret = LOAD_NOSPACE;
1637 goto out;
1638 }
1639
1640 if (map_addr < dyl_start)
1641 slide_amount = -(int64_t)(dyl_start - map_addr);
1642 else
1643 slide_amount = (int64_t)(map_addr - dyl_start);
1644
1645 slide_amount += slide;
1646
1647 *myresult = load_result_null;
1648
1649 ret = parse_machfile(vp, map, thread, header,
1650 file_offset, macho_size, depth,
1651 slide_amount, 0, myresult);
1652
1653 if (ret) {
1654 goto out;
1655 }
1656 }
1657
1658 if (ret == LOAD_SUCCESS) {
1659 result->dynlinker = TRUE;
1660 result->entry_point = myresult->entry_point;
1661 result->validentry = myresult->validentry;
1662 result->all_image_info_addr = myresult->all_image_info_addr;
1663 result->all_image_info_size = myresult->all_image_info_size;
1664 if (myresult->platform_binary) {
1665 result->csflags |= CS_DYLD_PLATFORM;
1666 }
1667 }
1668 out:
1669 vnode_put(vp);
1670 novp_out:
1671 FREE(dyld_data, M_TEMP);
1672 return (ret);
1673
1674 }
1675
1676 static load_return_t
1677 load_code_signature(
1678 struct linkedit_data_command *lcp,
1679 struct vnode *vp,
1680 off_t macho_offset,
1681 off_t macho_size,
1682 cpu_type_t cputype,
1683 load_result_t *result)
1684 {
1685 int ret;
1686 kern_return_t kr;
1687 vm_offset_t addr;
1688 int resid;
1689 struct cs_blob *blob;
1690 int error;
1691 vm_size_t blob_size;
1692
1693 addr = 0;
1694 blob = NULL;
1695
1696 if (lcp->cmdsize != sizeof (struct linkedit_data_command) ||
1697 lcp->dataoff + lcp->datasize > macho_size) {
1698 ret = LOAD_BADMACHO;
1699 goto out;
1700 }
1701
1702 blob = ubc_cs_blob_get(vp, cputype, macho_offset);
1703 if (blob != NULL) {
1704 /* we already have a blob for this vnode and cputype */
1705 if (blob->csb_cpu_type == cputype &&
1706 blob->csb_base_offset == macho_offset &&
1707 blob->csb_mem_size == lcp->datasize) {
1708 /* it matches the blob we want here, lets verify the version */
1709 if(0 != ubc_cs_generation_check(vp)) {
1710 if (0 != ubc_cs_blob_revalidate(vp, blob, 0)) {
1711 ret = LOAD_FAILURE; /* set error same as from ubc_cs_blob_add */
1712 goto out;
1713 }
1714 }
1715 ret = LOAD_SUCCESS;
1716 } else {
1717 /* the blob has changed for this vnode: fail ! */
1718 ret = LOAD_BADMACHO;
1719 }
1720 goto out;
1721 }
1722
1723 blob_size = lcp->datasize;
1724 kr = ubc_cs_blob_allocate(&addr, &blob_size);
1725 if (kr != KERN_SUCCESS) {
1726 ret = LOAD_NOSPACE;
1727 goto out;
1728 }
1729
1730 resid = 0;
1731 error = vn_rdwr(UIO_READ,
1732 vp,
1733 (caddr_t) addr,
1734 lcp->datasize,
1735 macho_offset + lcp->dataoff,
1736 UIO_SYSSPACE,
1737 0,
1738 kauth_cred_get(),
1739 &resid,
1740 current_proc());
1741 if (error || resid != 0) {
1742 ret = LOAD_IOERROR;
1743 goto out;
1744 }
1745
1746 if (ubc_cs_blob_add(vp,
1747 cputype,
1748 macho_offset,
1749 addr,
1750 lcp->datasize,
1751 0)) {
1752 ret = LOAD_FAILURE;
1753 goto out;
1754 } else {
1755 /* ubc_cs_blob_add() has consumed "addr" */
1756 addr = 0;
1757 }
1758
1759 #if CHECK_CS_VALIDATION_BITMAP
1760 ubc_cs_validation_bitmap_allocate( vp );
1761 #endif
1762
1763 blob = ubc_cs_blob_get(vp, cputype, macho_offset);
1764
1765 ret = LOAD_SUCCESS;
1766 out:
1767 if (ret == LOAD_SUCCESS) {
1768 result->csflags |= blob->csb_flags;
1769 result->platform_binary = blob->csb_platform_binary;
1770 result->cs_end_offset = blob->csb_end_offset;
1771 }
1772 if (addr != 0) {
1773 ubc_cs_blob_deallocate(addr, blob_size);
1774 addr = 0;
1775 }
1776
1777 return ret;
1778 }
1779
1780
1781 #if CONFIG_CODE_DECRYPTION
1782
1783 static load_return_t
1784 set_code_unprotect(
1785 struct encryption_info_command *eip,
1786 caddr_t addr,
1787 vm_map_t map,
1788 int64_t slide,
1789 struct vnode *vp,
1790 cpu_type_t cputype,
1791 cpu_subtype_t cpusubtype)
1792 {
1793 int result, len;
1794 pager_crypt_info_t crypt_info;
1795 const char * cryptname = 0;
1796 char *vpath;
1797
1798 size_t offset;
1799 struct segment_command_64 *seg64;
1800 struct segment_command *seg32;
1801 vm_map_offset_t map_offset, map_size;
1802 kern_return_t kr;
1803
1804 if (eip->cmdsize < sizeof(*eip)) return LOAD_BADMACHO;
1805
1806 switch(eip->cryptid) {
1807 case 0:
1808 /* not encrypted, just an empty load command */
1809 return LOAD_SUCCESS;
1810 case 1:
1811 cryptname="com.apple.unfree";
1812 break;
1813 case 0x10:
1814 /* some random cryptid that you could manually put into
1815 * your binary if you want NULL */
1816 cryptname="com.apple.null";
1817 break;
1818 default:
1819 return LOAD_BADMACHO;
1820 }
1821
1822 if (map == VM_MAP_NULL) return (LOAD_SUCCESS);
1823 if (NULL == text_crypter_create) return LOAD_FAILURE;
1824
1825 MALLOC_ZONE(vpath, char *, MAXPATHLEN, M_NAMEI, M_WAITOK);
1826 if(vpath == NULL) return LOAD_FAILURE;
1827
1828 len = MAXPATHLEN;
1829 result = vn_getpath(vp, vpath, &len);
1830 if(result) {
1831 FREE_ZONE(vpath, MAXPATHLEN, M_NAMEI);
1832 return LOAD_FAILURE;
1833 }
1834
1835 /* set up decrypter first */
1836 crypt_file_data_t crypt_data = {
1837 .filename = vpath,
1838 .cputype = cputype,
1839 .cpusubtype = cpusubtype};
1840 kr=text_crypter_create(&crypt_info, cryptname, (void*)&crypt_data);
1841 FREE_ZONE(vpath, MAXPATHLEN, M_NAMEI);
1842
1843 if(kr) {
1844 printf("set_code_unprotect: unable to create decrypter %s, kr=%d\n",
1845 cryptname, kr);
1846 if (kr == kIOReturnNotPrivileged) {
1847 /* text encryption returned decryption failure */
1848 return(LOAD_DECRYPTFAIL);
1849 }else
1850 return LOAD_RESOURCE;
1851 }
1852
1853 /* this is terrible, but we have to rescan the load commands to find the
1854 * virtual address of this encrypted stuff. This code is gonna look like
1855 * the dyld source one day... */
1856 struct mach_header *header = (struct mach_header *)addr;
1857 size_t mach_header_sz = sizeof(struct mach_header);
1858 if (header->magic == MH_MAGIC_64 ||
1859 header->magic == MH_CIGAM_64) {
1860 mach_header_sz = sizeof(struct mach_header_64);
1861 }
1862 offset = mach_header_sz;
1863 uint32_t ncmds = header->ncmds;
1864 while (ncmds--) {
1865 /*
1866 * Get a pointer to the command.
1867 */
1868 struct load_command *lcp = (struct load_command *)(addr + offset);
1869 offset += lcp->cmdsize;
1870
1871 switch(lcp->cmd) {
1872 case LC_SEGMENT_64:
1873 seg64 = (struct segment_command_64 *)lcp;
1874 if ((seg64->fileoff <= eip->cryptoff) &&
1875 (seg64->fileoff+seg64->filesize >=
1876 eip->cryptoff+eip->cryptsize)) {
1877 map_offset = seg64->vmaddr + eip->cryptoff - seg64->fileoff + slide;
1878 map_size = eip->cryptsize;
1879 goto remap_now;
1880 }
1881 case LC_SEGMENT:
1882 seg32 = (struct segment_command *)lcp;
1883 if ((seg32->fileoff <= eip->cryptoff) &&
1884 (seg32->fileoff+seg32->filesize >=
1885 eip->cryptoff+eip->cryptsize)) {
1886 map_offset = seg32->vmaddr + eip->cryptoff - seg32->fileoff + slide;
1887 map_size = eip->cryptsize;
1888 goto remap_now;
1889 }
1890 }
1891 }
1892
1893 /* if we get here, did not find anything */
1894 return LOAD_BADMACHO;
1895
1896 remap_now:
1897 /* now remap using the decrypter */
1898 kr = vm_map_apple_protected(map, map_offset, map_offset+map_size, &crypt_info);
1899 if(kr) {
1900 printf("set_code_unprotect(): mapping failed with %x\n", kr);
1901 crypt_info.crypt_end(crypt_info.crypt_ops);
1902 return LOAD_PROTECT;
1903 }
1904
1905 return LOAD_SUCCESS;
1906 }
1907
1908 #endif
1909
1910 /*
1911 * This routine exists to support the load_dylinker().
1912 *
1913 * This routine has its own, separate, understanding of the FAT file format,
1914 * which is terrifically unfortunate.
1915 */
1916 static
1917 load_return_t
1918 get_macho_vnode(
1919 char *path,
1920 integer_t archbits,
1921 struct mach_header *mach_header,
1922 off_t *file_offset,
1923 off_t *macho_size,
1924 struct macho_data *data,
1925 struct vnode **vpp
1926 )
1927 {
1928 struct vnode *vp;
1929 vfs_context_t ctx = vfs_context_current();
1930 proc_t p = vfs_context_proc(ctx);
1931 kauth_cred_t kerncred;
1932 struct nameidata *ndp = &data->__nid;
1933 boolean_t is_fat;
1934 struct fat_arch fat_arch;
1935 int error;
1936 int resid;
1937 union macho_vnode_header *header = &data->__header;
1938 off_t fsize = (off_t)0;
1939
1940 /*
1941 * Capture the kernel credential for use in the actual read of the
1942 * file, since the user doing the execution may have execute rights
1943 * but not read rights, but to exec something, we have to either map
1944 * or read it into the new process address space, which requires
1945 * read rights. This is to deal with lack of common credential
1946 * serialization code which would treat NOCRED as "serialize 'root'".
1947 */
1948 kerncred = vfs_context_ucred(vfs_context_kernel());
1949
1950 /* init the namei data to point the file user's program name */
1951 NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW | LOCKLEAF, UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
1952
1953 if ((error = namei(ndp)) != 0) {
1954 if (error == ENOENT) {
1955 error = LOAD_ENOENT;
1956 } else {
1957 error = LOAD_FAILURE;
1958 }
1959 return(error);
1960 }
1961 nameidone(ndp);
1962 vp = ndp->ni_vp;
1963
1964 /* check for regular file */
1965 if (vp->v_type != VREG) {
1966 error = LOAD_PROTECT;
1967 goto bad1;
1968 }
1969
1970 /* get size */
1971 if ((error = vnode_size(vp, &fsize, ctx)) != 0) {
1972 error = LOAD_FAILURE;
1973 goto bad1;
1974 }
1975
1976 /* Check mount point */
1977 if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
1978 error = LOAD_PROTECT;
1979 goto bad1;
1980 }
1981
1982 /* check access */
1983 if ((error = vnode_authorize(vp, NULL, KAUTH_VNODE_EXECUTE | KAUTH_VNODE_READ_DATA, ctx)) != 0) {
1984 error = LOAD_PROTECT;
1985 goto bad1;
1986 }
1987
1988 /* try to open it */
1989 if ((error = VNOP_OPEN(vp, FREAD, ctx)) != 0) {
1990 error = LOAD_PROTECT;
1991 goto bad1;
1992 }
1993
1994 if ((error = vn_rdwr(UIO_READ, vp, (caddr_t)header, sizeof (*header), 0,
1995 UIO_SYSSPACE, IO_NODELOCKED, kerncred, &resid, p)) != 0) {
1996 error = LOAD_IOERROR;
1997 goto bad2;
1998 }
1999
2000 if (resid) {
2001 error = LOAD_BADMACHO;
2002 goto bad2;
2003 }
2004
2005 if (header->mach_header.magic == MH_MAGIC ||
2006 header->mach_header.magic == MH_MAGIC_64) {
2007 is_fat = FALSE;
2008 } else if (OSSwapBigToHostInt32(header->fat_header.magic) == FAT_MAGIC) {
2009 is_fat = TRUE;
2010 } else {
2011 error = LOAD_BADMACHO;
2012 goto bad2;
2013 }
2014
2015 if (is_fat) {
2016
2017 error = fatfile_validate_fatarches((vm_offset_t)(&header->fat_header),
2018 sizeof(*header));
2019 if (error != LOAD_SUCCESS) {
2020 goto bad2;
2021 }
2022
2023 /* Look up our architecture in the fat file. */
2024 error = fatfile_getarch_with_bits(archbits,
2025 (vm_offset_t)(&header->fat_header), sizeof(*header), &fat_arch);
2026 if (error != LOAD_SUCCESS)
2027 goto bad2;
2028
2029 /* Read the Mach-O header out of it */
2030 error = vn_rdwr(UIO_READ, vp, (caddr_t)&header->mach_header,
2031 sizeof (header->mach_header), fat_arch.offset,
2032 UIO_SYSSPACE, IO_NODELOCKED, kerncred, &resid, p);
2033 if (error) {
2034 error = LOAD_IOERROR;
2035 goto bad2;
2036 }
2037
2038 if (resid) {
2039 error = LOAD_BADMACHO;
2040 goto bad2;
2041 }
2042
2043 /* Is this really a Mach-O? */
2044 if (header->mach_header.magic != MH_MAGIC &&
2045 header->mach_header.magic != MH_MAGIC_64) {
2046 error = LOAD_BADMACHO;
2047 goto bad2;
2048 }
2049
2050 *file_offset = fat_arch.offset;
2051 *macho_size = fat_arch.size;
2052 } else {
2053 /*
2054 * Force get_macho_vnode() to fail if the architecture bits
2055 * do not match the expected architecture bits. This in
2056 * turn causes load_dylinker() to fail for the same reason,
2057 * so it ensures the dynamic linker and the binary are in
2058 * lock-step. This is potentially bad, if we ever add to
2059 * the CPU_ARCH_* bits any bits that are desirable but not
2060 * required, since the dynamic linker might work, but we will
2061 * refuse to load it because of this check.
2062 */
2063 if ((cpu_type_t)(header->mach_header.cputype & CPU_ARCH_MASK) != archbits) {
2064 error = LOAD_BADARCH;
2065 goto bad2;
2066 }
2067
2068 *file_offset = 0;
2069 *macho_size = fsize;
2070 }
2071
2072 *mach_header = header->mach_header;
2073 *vpp = vp;
2074
2075 ubc_setsize(vp, fsize);
2076 return (error);
2077
2078 bad2:
2079 (void) VNOP_CLOSE(vp, FREAD, ctx);
2080 bad1:
2081 vnode_put(vp);
2082 return(error);
2083 }