1 /*
2 * Copyright (c) 2000-2024 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/file_internal.h>
51 #include <sys/ubc_internal.h>
52 #include <sys/imgact.h>
53 #include <sys/codesign.h>
54 #include <sys/proc_uuid_policy.h>
55 #include <sys/reason.h>
56 #include <sys/kdebug.h>
57 #include <sys/spawn_internal.h>
58
59 #include <mach/mach_types.h>
60 #include <mach/vm_map.h> /* vm_allocate() */
61 #include <mach/mach_vm.h> /* mach_vm_allocate() */
62 #include <mach/vm_statistics.h>
63 #include <mach/task.h>
64 #include <mach/thread_act.h>
65
66 #include <machine/vmparam.h>
67 #include <machine/exec.h>
68 #include <machine/pal_routines.h>
69
70 #include <kern/ast.h>
71 #include <kern/kern_types.h>
72 #include <kern/cpu_number.h>
73 #include <kern/mach_loader.h>
74 #include <kern/mach_fat.h>
75 #include <kern/kalloc.h>
76 #include <kern/task.h>
77 #include <kern/thread.h>
78 #include <kern/page_decrypt.h>
79
80 #include <mach-o/fat.h>
81 #include <mach-o/loader.h>
82
83 #include <vm/pmap.h>
84 #include <vm/vm_map_xnu.h>
85 #include <vm/vm_kern_xnu.h>
86 #include <vm/vm_pager_xnu.h>
87 #include <vm/vnode_pager.h>
88 #include <vm/vm_protos.h>
89 #include <vm/vm_shared_region.h>
90 #include <IOKit/IOReturn.h> /* for kIOReturnNotPrivileged */
91 #include <IOKit/IOBSD.h> /* for IOVnodeHasEntitlement */
92
93 #include <os/log.h>
94 #include <os/overflow.h>
95
96 #include <pexpert/pexpert.h>
97 #include <libkern/libkern.h>
98
99 #include "kern_exec_internal.h"
100
101 #if APPLEVIRTUALPLATFORM
102 #define ALLOW_FORCING_ARM64_32 1
103 #endif /* APPLEVIRTUALPLATFORM */
104
105 #if ALLOW_FORCING_ARM64_32
106 #if DEVELOPMENT || DEBUG
107 TUNABLE_DT(uint32_t, force_arm64_32, "/defaults", "force-arm64-32", "force-arm64-32", 0, TUNABLE_DT_NONE);
108 #else
109 TUNABLE_DT(uint32_t, force_arm64_32, "/defaults", "force-arm64-32", "force-arm64-32", 0, TUNABLE_DT_NO_BOOTARG);
110 #endif
111 #endif /* ALLOW_FORCING_ARM64_32 */
112
113 #if ALLOW_FORCING_ARM64_32 || DEVELOPMENT || DEBUG
114 /*
115 * The binary grading priority for the highest priority override. Each progressive override
116 * receives a priority 1 less than its neighbor.
117 */
118 #define BINGRADE_OVERRIDE_MAX 200
119 #endif /* ALLOW_FORCING_ARM64_32 || DEVELOPMENT || DEBUG */
120
121 #if DEVELOPMENT || DEBUG
122 /*
123 * Maxmum number of overrides that can be passed via the bingrade boot-arg property.
124 */
125 #define MAX_BINGRADE_OVERRIDES 4
126 /*
127 * Max size of one bingrade override + 1 comma
128 * (technically, sizeof will also include the terminating NUL here, but an overestimation of
129 * buffer space is fine).
130 */
131 #define BINGRADE_MAXSTRINGLEN sizeof("0x12345678:0x12345678:0x12345678,")
132
133 /*
134 * Each binary grading override has a cpu type and cpu subtype to match against the values in
135 * the Mach-o header.
136 */
137 typedef struct bingrade {
138 uint32_t cputype;
139 uint32_t cpusubtype;
140 uint32_t execfeatures;
141 #define EXECFEATURES_OVERRIDE_WILDCARD (~(uint32_t)0)
142 } bingrade_t;
143
144 /* The number of binary grading overrides that are active */
145 static int num_bingrade_overrides = -1;
146
147 /*
148 * The bingrade_overrides array is an ordered list of binary grading overrides. The first element in the array
149 * has the highest priority. When parsing the `bingrade' boot-arg, elements are added to this array in order.
150 */
151 static bingrade_t bingrade_overrides[MAX_BINGRADE_OVERRIDES] = { 0 };
152 #endif /* DEVELOPMENT || DEBUG */
153
154
155 /* An empty load_result_t */
156 static const load_result_t load_result_null = {
157 .mach_header = MACH_VM_MIN_ADDRESS,
158 .entry_point = MACH_VM_MIN_ADDRESS,
159 .user_stack = MACH_VM_MIN_ADDRESS,
160 .user_stack_size = 0,
161 .user_stack_alloc = MACH_VM_MIN_ADDRESS,
162 .user_stack_alloc_size = 0,
163 .all_image_info_addr = MACH_VM_MIN_ADDRESS,
164 .all_image_info_size = 0,
165 .thread_count = 0,
166 .unixproc = 0,
167 .dynlinker = 0,
168 .needs_dynlinker = 0,
169 .validentry = 0,
170 .using_lcmain = 0,
171 .is_64bit_addr = 0,
172 .is_64bit_data = 0,
173 .custom_stack = 0,
174 .csflags = 0,
175 .has_pagezero = 0,
176 .uuid = { 0 },
177 .min_vm_addr = MACH_VM_MAX_ADDRESS,
178 .max_vm_addr = MACH_VM_MIN_ADDRESS,
179 .ro_vm_start = MACH_VM_MIN_ADDRESS,
180 .ro_vm_end = MACH_VM_MIN_ADDRESS,
181 .cs_end_offset = 0,
182 .threadstate = NULL,
183 .threadstate_sz = 0,
184 .is_rosetta = 0,
185 .dynlinker_ro_vm_start = 0,
186 .dynlinker_ro_vm_end = 0,
187 .dynlinker_mach_header = MACH_VM_MIN_ADDRESS,
188 .dynlinker_fd = -1,
189 };
190
191 /*
192 * Prototypes of static functions.
193 */
194 static load_return_t
195 parse_machfile(
196 struct vnode *vp,
197 vm_map_t map,
198 thread_t thread,
199 struct mach_header *header,
200 off_t file_offset,
201 off_t macho_size,
202 int depth,
203 int64_t slide,
204 int64_t dyld_slide,
205 load_result_t *result,
206 load_result_t *binresult,
207 struct image_params *imgp
208 );
209
210 static load_return_t
211 load_segment(
212 struct load_command *lcp,
213 uint32_t filetype,
214 void *control,
215 off_t pager_offset,
216 off_t macho_size,
217 struct vnode *vp,
218 vm_map_t map,
219 int64_t slide,
220 load_result_t *result,
221 struct image_params *imgp
222 );
223
224 static load_return_t
225 load_uuid(
226 struct uuid_command *uulp,
227 char *command_end,
228 load_result_t *result
229 );
230
231 static load_return_t
232 load_version(
233 struct version_min_command *vmc,
234 boolean_t *found_version_cmd,
235 struct image_params *imgp,
236 load_result_t *result
237 );
238
239 static load_return_t
240 load_code_signature(
241 struct linkedit_data_command *lcp,
242 struct vnode *vp,
243 off_t macho_offset,
244 off_t macho_size,
245 cpu_type_t cputype,
246 cpu_subtype_t cpusubtype,
247 load_result_t *result,
248 struct image_params *imgp);
249
250 #if CONFIG_CODE_DECRYPTION
251 static load_return_t
252 set_code_unprotect(
253 struct encryption_info_command *lcp,
254 caddr_t addr,
255 vm_map_t map,
256 int64_t slide,
257 struct vnode *vp,
258 off_t macho_offset,
259 cpu_type_t cputype,
260 cpu_subtype_t cpusubtype);
261 #endif
262
263 static
264 load_return_t
265 load_main(
266 struct entry_point_command *epc,
267 thread_t thread,
268 int64_t slide,
269 load_result_t *result
270 );
271
272 static
273 load_return_t
274 setup_driver_main(
275 thread_t thread,
276 int64_t slide,
277 load_result_t *result
278 );
279
280 static load_return_t
281 load_unixthread(
282 struct thread_command *tcp,
283 thread_t thread,
284 int64_t slide,
285 boolean_t is_x86_64_compat_binary,
286 load_result_t *result
287 );
288
289 static load_return_t
290 load_threadstate(
291 thread_t thread,
292 uint32_t *ts,
293 uint32_t total_size,
294 load_result_t *
295 );
296
297 static load_return_t
298 load_threadstack(
299 thread_t thread,
300 uint32_t *ts,
301 uint32_t total_size,
302 mach_vm_offset_t *user_stack,
303 int *customstack,
304 boolean_t is_x86_64_compat_binary,
305 load_result_t *result
306 );
307
308 static load_return_t
309 load_threadentry(
310 thread_t thread,
311 uint32_t *ts,
312 uint32_t total_size,
313 mach_vm_offset_t *entry_point
314 );
315
316 static load_return_t
317 load_dylinker(
318 struct dylinker_command *lcp,
319 integer_t archbits,
320 vm_map_t map,
321 thread_t thread,
322 int depth,
323 int64_t slide,
324 load_result_t *result,
325 struct image_params *imgp
326 );
327
328
329 #if CONFIG_ROSETTA
330 static load_return_t
331 load_rosetta(
332 vm_map_t map,
333 thread_t thread,
334 load_result_t *result,
335 struct image_params *imgp
336 );
337 #endif
338
339 #if __x86_64__
340 extern int bootarg_no32exec;
341 static boolean_t
342 check_if_simulator_binary(
343 struct image_params *imgp,
344 off_t file_offset,
345 off_t macho_size);
346 #endif
347
348 struct macho_data;
349
350 static load_return_t
351 get_macho_vnode(
352 const char *path,
353 integer_t archbits,
354 struct mach_header *mach_header,
355 off_t *file_offset,
356 off_t *macho_size,
357 struct macho_data *macho_data,
358 struct vnode **vpp,
359 struct image_params *imgp
360 );
361
362 #if DEVELOPMENT || DEBUG
363 /*
364 * Parse the bingrade boot-arg, adding cputype/cpusubtype/execfeatures tuples to the global binary grading
365 * override array. The bingrade boot-arg must be of the form:
366 *
367 * NUM := '0x' <HEXDIGITS> | '0' <OCTALDIGITS> | <DECIMALDIGITS>
368 * OVERRIDESPEC := <NUM> | <NUM> ':' <NUM> | <NUM> ':' <NUM> ':' <NUM>
369 * BINSPEC_BOOTARG := <OVERRIDESPEC> ',' <BINSPEC_BOOTARG> | <OVERRIDESPEC>
370 *
371 * Returns the number of overrides specified in the boot-arg, or 0 if there were no overrides or the
372 * syntax of the overrides was found to be invalid.
373 */
374 static int
parse_bingrade_override_bootarg(bingrade_t * overrides,int max_overrides,char * overrides_arg_string)375 parse_bingrade_override_bootarg(bingrade_t *overrides, int max_overrides, char *overrides_arg_string)
376 {
377 char bingrade_arg[BINGRADE_MAXSTRINGLEN * MAX_BINGRADE_OVERRIDES + 1];
378 int cputypespec_count = 0;
379
380 /* Look for the bingrade boot-arg */
381 if (overrides_arg_string != NULL || PE_parse_boot_arg_str("bingrade", bingrade_arg, sizeof(bingrade_arg))) {
382 char *bingrade_str = (overrides_arg_string != NULL) ? overrides_arg_string : &bingrade_arg[0];
383 char *cputypespec;
384
385 /* Skip leading whitespace */
386 while (*bingrade_str == ' ' || *bingrade_str == '\t') {
387 bingrade_str++;
388 }
389
390 if (*bingrade_str == 0) {
391 /* empty string, so just return 0 */
392 return 0;
393 }
394
395 /* If we found the boot-arg, iterate on each OVERRIDESPEC in the BOOTSPEC_BOOTARG */
396 while ((cputypespec_count < max_overrides) && ((cputypespec = strsep(&bingrade_str, ",")) != NULL)) {
397 char *colon = strchr(cputypespec, ':');
398 char *end;
399 char *cputypeptr;
400 char cputypestr[16] = { 0 };
401 unsigned long cputype, cpusubtype, execfeatures;
402
403 /* If there's a colon present, process the cpu subtype and possibly the execfeatures */
404 if (colon != NULL) {
405 colon++; /* Move past the colon before parsing */
406
407 char execfeat_buf[16] = { 0 }; /* This *MUST* be preinitialized to zeroes */
408 char *second_colon = strchr(colon, ':');
409 ptrdiff_t amt_to_copy = 0;
410
411 if (second_colon != NULL) {
412 strlcpy(execfeat_buf, second_colon + 1, MIN(strlen(second_colon + 1) + 1, sizeof(execfeat_buf)));
413
414 execfeatures = strtoul(execfeat_buf, &end, 0);
415 if (execfeat_buf == end || execfeatures > UINT_MAX) {
416 printf("Invalid bingrade boot-arg (`%s').\n", cputypespec);
417 return 0;
418 }
419
420 overrides[cputypespec_count].execfeatures = (uint32_t)execfeatures;
421
422 /*
423 * Note there is no "+ 1" here because we are only copying up to but not
424 * including the second colon. Since cputypestr was initialized to all 0s
425 * above, the terminating NUL will already be there.
426 */
427 amt_to_copy = second_colon - colon;
428 } else {
429 /* No second colon, so use the wildcard for execfeatures */
430 overrides[cputypespec_count].execfeatures = EXECFEATURES_OVERRIDE_WILDCARD;
431 /*
432 * There is no "+ 1" here because colon was already moved forward by 1 (above).
433 * which allows this computation to include the terminating NUL in the length
434 * computed.
435 */
436 amt_to_copy = colon - cputypespec;
437 }
438
439 /* Now determine the cpu subtype */
440 cpusubtype = strtoul(colon, &end, 0);
441 if (colon == end || cpusubtype > UINT_MAX) {
442 printf("Invalid bingrade boot-arg (`%s').\n", cputypespec);
443 return 0;
444 }
445 overrides[cputypespec_count].cpusubtype = (uint32_t)cpusubtype;
446
447 /* Copy the cputype string into a temp buffer */
448 strlcpy(cputypestr, cputypespec, MIN(sizeof(cputypestr), amt_to_copy));
449
450 cputypeptr = &cputypestr[0];
451 } else {
452 /*
453 * No colon present, set the cpu subtype to 0, the execfeatures to EXECFEATURES_OVERRIDE_WILDCARD
454 * and use the whole string as the cpu type
455 */
456 overrides[cputypespec_count].cpusubtype = 0;
457 overrides[cputypespec_count].execfeatures = EXECFEATURES_OVERRIDE_WILDCARD;
458 cputypeptr = cputypespec;
459 }
460
461 cputype = strtoul(cputypeptr, &end, 0);
462 if (cputypeptr == end || cputype > UINT_MAX) {
463 printf("Invalid bingrade boot-arg (`%s').\n", cputypespec);
464 return 0;
465 }
466 overrides[cputypespec_count].cputype = (uint32_t)cputype;
467
468 cputypespec_count++;
469 }
470 } else {
471 /* No bingrade boot-arg; return 0 overrides */
472 return 0;
473 }
474
475 return cputypespec_count;
476 }
477
478 size_t
bingrade_get_override_string(char * existing_overrides,size_t existing_overrides_bufsize)479 bingrade_get_override_string(char *existing_overrides, size_t existing_overrides_bufsize)
480 {
481 if (num_bingrade_overrides <= 0) {
482 return 0; /* No overrides set */
483 }
484
485 /* Init the empty string for strlcat */
486 existing_overrides[0] = 0;
487
488 for (int i = 0; i < num_bingrade_overrides; i++) {
489 char next_override[33]; /* 10char + ':' + 10char + ([future] ':' + 10char) */
490 snprintf(next_override, sizeof(next_override), "0x%x:0x%x", bingrade_overrides[i].cputype, bingrade_overrides[i].cpusubtype);
491 if (i > 0) {
492 strlcat(existing_overrides, ",", existing_overrides_bufsize);
493 }
494 strlcat(existing_overrides, next_override, existing_overrides_bufsize);
495 }
496
497 return strlen(existing_overrides);
498 }
499
500 int
binary_grade_overrides_update(char * overrides_arg)501 binary_grade_overrides_update(char *overrides_arg)
502 {
503 #if ALLOW_FORCING_ARM64_32
504 if (force_arm64_32) {
505 /* If forcing arm64_32, don't allow bingrade override. */
506 return 0;
507 }
508 #endif /* ALLOW_FORCING_ARM64_32 */
509 num_bingrade_overrides = parse_bingrade_override_bootarg(bingrade_overrides, MAX_BINGRADE_OVERRIDES, overrides_arg);
510 return num_bingrade_overrides;
511 }
512 #endif /* DEVELOPMENT || DEBUG */
513
514 static inline void
widen_segment_command(const struct segment_command * scp32,struct segment_command_64 * scp)515 widen_segment_command(const struct segment_command *scp32,
516 struct segment_command_64 *scp)
517 {
518 scp->cmd = scp32->cmd;
519 scp->cmdsize = scp32->cmdsize;
520 bcopy(scp32->segname, scp->segname, sizeof(scp->segname));
521 scp->vmaddr = scp32->vmaddr;
522 scp->vmsize = scp32->vmsize;
523 scp->fileoff = scp32->fileoff;
524 scp->filesize = scp32->filesize;
525 scp->maxprot = scp32->maxprot;
526 scp->initprot = scp32->initprot;
527 scp->nsects = scp32->nsects;
528 scp->flags = scp32->flags;
529 }
530
531 static void
note_all_image_info_section(const struct segment_command_64 * scp,boolean_t is64,size_t section_size,const void * sections,int64_t slide,load_result_t * result)532 note_all_image_info_section(const struct segment_command_64 *scp,
533 boolean_t is64, size_t section_size, const void *sections,
534 int64_t slide, load_result_t *result)
535 {
536 const union {
537 struct section s32;
538 struct section_64 s64;
539 } *sectionp;
540 unsigned int i;
541
542
543 if (strncmp(scp->segname, "__DATA_DIRTY", sizeof(scp->segname)) != 0 &&
544 strncmp(scp->segname, "__DATA", sizeof(scp->segname)) != 0) {
545 return;
546 }
547 for (i = 0; i < scp->nsects; ++i) {
548 sectionp = (const void *)
549 ((const char *)sections + section_size * i);
550 if (0 == strncmp(sectionp->s64.sectname, "__all_image_info",
551 sizeof(sectionp->s64.sectname))) {
552 result->all_image_info_addr =
553 is64 ? sectionp->s64.addr : sectionp->s32.addr;
554 result->all_image_info_addr += slide;
555 result->all_image_info_size =
556 is64 ? sectionp->s64.size : sectionp->s32.size;
557 return;
558 }
559 }
560 }
561
562 #if __arm64__
563 /*
564 * Allow bypassing some security rules (hard pagezero, no write+execute)
565 * in exchange for better binary compatibility for legacy apps built
566 * before 16KB-alignment was enforced.
567 */
568 const int fourk_binary_compatibility_unsafe = TRUE;
569 #endif /* __arm64__ */
570
571 #if XNU_TARGET_OS_OSX
572
573 /* Determines whether this process may host/run third party plugins. */
574 static inline bool
process_is_plugin_host(struct image_params * imgp,load_result_t * result)575 process_is_plugin_host(struct image_params *imgp, load_result_t *result)
576 {
577 if (imgp->ip_flags & IMGPF_NOJOP) {
578 return false;
579 }
580
581 if (!result->platform_binary) {
582 return false;
583 }
584
585 struct cs_blob *csblob = csvnode_get_blob(imgp->ip_vp, imgp->ip_arch_offset);
586 const char *identity = csblob_get_identity(csblob);
587 if (!identity) {
588 return false;
589 }
590
591 /* Check if override host plugin entitlement is present and posix spawn attribute to disable A keys is passed */
592 if (IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, OVERRIDE_PLUGIN_HOST_ENTITLEMENT)) {
593 bool ret = imgp->ip_flags & IMGPF_PLUGIN_HOST_DISABLE_A_KEYS;
594 if (ret) {
595 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
596 set_proc_name(imgp, p);
597 os_log(OS_LOG_DEFAULT, "%s: running binary \"%s\" in keys-off mode due to posix_spawnattr_disable_ptr_auth_a_keys_np", __func__, p->p_name);
598 }
599 return ret;
600 }
601
602 /* Disabling library validation is a good signal that this process plans to host plugins */
603 const char *const disable_lv_entitlements[] = {
604 "com.apple.security.cs.disable-library-validation",
605 "com.apple.private.cs.automator-plugins",
606 CLEAR_LV_ENTITLEMENT,
607 };
608 for (size_t i = 0; i < ARRAY_COUNT(disable_lv_entitlements); i++) {
609 const char *entitlement = disable_lv_entitlements[i];
610 if (IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, entitlement)) {
611 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
612 set_proc_name(imgp, p);
613 os_log(OS_LOG_DEFAULT, "%s: running binary \"%s\" in keys-off mode due to entitlement: %s", __func__, p->p_name, entitlement);
614 return true;
615 }
616 }
617
618 /* From /System/Library/Security/HardeningExceptions.plist */
619 const char *const hardening_exceptions[] = {
620 "com.apple.perl5", /* Scripting engines may load third party code and jit*/
621 "com.apple.perl", /* Scripting engines may load third party code and jit*/
622 "org.python.python", /* Scripting engines may load third party code and jit*/
623 "com.apple.expect", /* Scripting engines may load third party code and jit*/
624 "com.tcltk.wish", /* Scripting engines may load third party code and jit*/
625 "com.tcltk.tclsh", /* Scripting engines may load third party code and jit*/
626 "com.apple.ruby", /* Scripting engines may load third party code and jit*/
627 "com.apple.bash", /* Required for the 'enable' command */
628 "com.apple.zsh", /* Required for the 'zmodload' command */
629 "com.apple.ksh", /* Required for 'builtin' command */
630 "com.apple.sh", /* rdar://138353488: sh re-execs into zsh or bash, which are exempted */
631 };
632 for (size_t i = 0; i < ARRAY_COUNT(hardening_exceptions); i++) {
633 if (strncmp(hardening_exceptions[i], identity, strlen(hardening_exceptions[i])) == 0) {
634 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
635 set_proc_name(imgp, p);
636 os_log(OS_LOG_DEFAULT, "%s: running binary \"%s\" in keys-off mode due to identity: %s", __func__, p->p_name, identity);
637 return true;
638 }
639 }
640
641 return false;
642 }
643 #endif /* XNU_TARGET_OS_OSX */
644
645 static int
grade_binary_override(cpu_type_t __unused exectype,cpu_subtype_t __unused execsubtype,cpu_subtype_t execfeatures __unused,bool allow_simulator_binary __unused)646 grade_binary_override(cpu_type_t __unused exectype, cpu_subtype_t __unused execsubtype, cpu_subtype_t execfeatures __unused,
647 bool allow_simulator_binary __unused)
648 {
649 #if ALLOW_FORCING_ARM64_32
650 if (force_arm64_32) {
651 /* Forcing ARM64_32 takes precedence over 'bingrade' boot-arg. */
652 if (exectype == CPU_TYPE_ARM64_32 && execsubtype == CPU_SUBTYPE_ARM64_32_V8) {
653 return BINGRADE_OVERRIDE_MAX;
654 } else {
655 /* Stop trying to match. */
656 return 0;
657 }
658 }
659 #endif /* ALLOW_FORCING_ARM64_32 */
660
661 #if DEVELOPMENT || DEBUG
662 if (num_bingrade_overrides == -1) {
663 num_bingrade_overrides = parse_bingrade_override_bootarg(bingrade_overrides, MAX_BINGRADE_OVERRIDES, NULL);
664 }
665
666 if (num_bingrade_overrides == 0) {
667 return -1;
668 }
669
670 for (int i = 0; i < num_bingrade_overrides; i++) {
671 if (bingrade_overrides[i].cputype == exectype && bingrade_overrides[i].cpusubtype == execsubtype &&
672 (bingrade_overrides[i].execfeatures == EXECFEATURES_OVERRIDE_WILDCARD ||
673 bingrade_overrides[i].execfeatures == execfeatures)) {
674 return BINGRADE_OVERRIDE_MAX - i;
675 }
676 }
677 #endif /* DEVELOPMENT || DEBUG */
678 /* exectype/execsubtype Not found in override list */
679 return -1;
680 }
681
682 load_return_t
load_machfile(struct image_params * imgp,struct mach_header * header,thread_t thread,vm_map_t * mapp,load_result_t * result)683 load_machfile(
684 struct image_params *imgp,
685 struct mach_header *header,
686 thread_t thread,
687 vm_map_t *mapp,
688 load_result_t *result
689 )
690 {
691 struct vnode *vp = imgp->ip_vp;
692 off_t file_offset = imgp->ip_arch_offset;
693 off_t macho_size = imgp->ip_arch_size;
694 off_t total_size = 0;
695 off_t file_size = imgp->ip_vattr->va_data_size;
696 pmap_t pmap = 0; /* protected by create_map */
697 vm_map_t map;
698 load_result_t myresult;
699 load_return_t lret;
700 boolean_t enforce_hard_pagezero = TRUE;
701 int in_exec = (imgp->ip_flags & IMGPF_EXEC);
702 task_t task = current_task();
703 int64_t aslr_page_offset = 0;
704 int64_t dyld_aslr_page_offset = 0;
705 int64_t aslr_section_size = 0;
706 int64_t aslr_section_offset = 0;
707 kern_return_t kret;
708 unsigned int pmap_flags = 0;
709
710 if (os_add_overflow(file_offset, macho_size, &total_size) ||
711 total_size > file_size) {
712 return LOAD_BADMACHO;
713 }
714
715 result->is_64bit_addr = ((imgp->ip_flags & IMGPF_IS_64BIT_ADDR) == IMGPF_IS_64BIT_ADDR);
716 result->is_64bit_data = ((imgp->ip_flags & IMGPF_IS_64BIT_DATA) == IMGPF_IS_64BIT_DATA);
717 #if defined(HAS_APPLE_PAC)
718 pmap_flags |= (imgp->ip_flags & IMGPF_NOJOP) ? PMAP_CREATE_DISABLE_JOP : 0;
719 #endif /* defined(HAS_APPLE_PAC) */
720 #if CONFIG_ROSETTA
721 pmap_flags |= (imgp->ip_flags & IMGPF_ROSETTA) ? PMAP_CREATE_ROSETTA : 0;
722 #endif
723 pmap_flags |= result->is_64bit_addr ? PMAP_CREATE_64BIT : 0;
724
725 task_t ledger_task;
726 if (imgp->ip_new_thread) {
727 ledger_task = get_threadtask(imgp->ip_new_thread);
728 } else {
729 ledger_task = task;
730 }
731
732 #if XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES
733 if (imgp->ip_px_sa != NULL) {
734 struct _posix_spawnattr* psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
735 if (psa->psa_flags & _POSIX_SPAWN_FORCE_4K_PAGES) {
736 pmap_flags |= PMAP_CREATE_FORCE_4K_PAGES;
737 }
738 }
739 #endif /* XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGE */
740
741 pmap = pmap_create_options(get_task_ledger(ledger_task),
742 (vm_map_size_t) 0,
743 pmap_flags);
744 if (pmap == NULL) {
745 return LOAD_RESOURCE;
746 }
747 map = vm_map_create_options(pmap, 0,
748 vm_compute_max_offset(result->is_64bit_addr),
749 VM_MAP_CREATE_PAGEABLE);
750
751 #if defined(__arm64__)
752 if (result->is_64bit_addr) {
753 /* enforce 16KB alignment of VM map entries */
754 vm_map_set_page_shift(map, SIXTEENK_PAGE_SHIFT);
755 } else {
756 vm_map_set_page_shift(map, page_shift_user32);
757 }
758 #endif /* __arm64__ */
759
760 #if PMAP_CREATE_FORCE_4K_PAGES
761 if (pmap_flags & PMAP_CREATE_FORCE_4K_PAGES) {
762 DEBUG4K_LIFE("***** launching '%s' as 4k *****\n", vp->v_name);
763 vm_map_set_page_shift(map, FOURK_PAGE_SHIFT);
764 }
765 #endif /* PMAP_CREATE_FORCE_4K_PAGES */
766
767 #ifndef CONFIG_ENFORCE_SIGNED_CODE
768 /* This turns off faulting for executable pages, which allows
769 * to circumvent Code Signing Enforcement. The per process
770 * flag (CS_ENFORCEMENT) is not set yet, but we can use the
771 * global flag.
772 */
773 if (!cs_process_global_enforcement() && (header->flags & MH_ALLOW_STACK_EXECUTION)) {
774 vm_map_disable_NX(map);
775 // TODO: Message Trace or log that this is happening
776 }
777 #endif
778
779 /* Forcibly disallow execution from data pages on even if the arch
780 * normally permits it. */
781 if ((header->flags & MH_NO_HEAP_EXECUTION) && !(imgp->ip_flags & IMGPF_ALLOW_DATA_EXEC)) {
782 vm_map_disallow_data_exec(map);
783 }
784
785 /*
786 * Compute a random offset for ASLR, and an independent random offset for dyld.
787 */
788 if (!(imgp->ip_flags & IMGPF_DISABLE_ASLR)) {
789 vm_map_get_max_aslr_slide_section(map, &aslr_section_offset, &aslr_section_size);
790 aslr_section_offset = (random() % aslr_section_offset) * aslr_section_size;
791
792 aslr_page_offset = random();
793 aslr_page_offset = (aslr_page_offset % (vm_map_get_max_aslr_slide_pages(map) - 1)) + 1;
794 aslr_page_offset <<= vm_map_page_shift(map);
795
796 dyld_aslr_page_offset = random();
797 dyld_aslr_page_offset = (dyld_aslr_page_offset %
798 (vm_map_get_max_loader_aslr_slide_pages(map) - 1)) + 1;
799 dyld_aslr_page_offset <<= vm_map_page_shift(map);
800
801 aslr_page_offset += aslr_section_offset;
802 }
803 if (vm_map_page_shift(map) < (int)PAGE_SHIFT) {
804 DEBUG4K_LOAD("slide=0x%llx dyld_slide=0x%llx\n", aslr_page_offset, dyld_aslr_page_offset);
805 }
806
807 if (!result) {
808 result = &myresult;
809 }
810
811 *result = load_result_null;
812
813 /*
814 * re-set the bitness on the load result since we cleared the load result above.
815 */
816 result->is_64bit_addr = ((imgp->ip_flags & IMGPF_IS_64BIT_ADDR) == IMGPF_IS_64BIT_ADDR);
817 result->is_64bit_data = ((imgp->ip_flags & IMGPF_IS_64BIT_DATA) == IMGPF_IS_64BIT_DATA);
818
819 lret = parse_machfile(vp, map, thread, header, file_offset, macho_size,
820 0, aslr_page_offset, dyld_aslr_page_offset, result,
821 NULL, imgp);
822
823 if (lret != LOAD_SUCCESS) {
824 imgp->ip_free_map = map;
825 return lret;
826 }
827
828 /*
829 * From now on it's safe to query entitlements via the vnode interface. Let's get figuring
830 * out whether we're a security relevant binary out of the way immediately.
831 */
832 switch (exec_check_security_entitlement(imgp, HARDENED_PROCESS)) {
833 case EXEC_SECURITY_INVALID_CONFIG:
834 imgp->ip_free_map = map;
835 return LOAD_BADMACHO;
836 case EXEC_SECURITY_ENTITLED: {
837 /*
838 * Set the latest version of the hardened process version entitlement
839 * if not specified
840 */
841 uint64_t value;
842 if (IOVnodeGetIntegerEntitlement(imgp->ip_vp,
843 (int64_t)imgp->ip_arch_offset, HARDENED_PROCESS_VERSION, &value)) {
844 result->hardened_process_version = (uint8_t)value;
845 } else {
846 result->hardened_process_version = HARDENED_PROCESS_VERSION_LATEST;
847 }
848 break;
849 }
850 case EXEC_SECURITY_NOT_ENTITLED:
851 result->hardened_process_version = HARDENED_PROCESS_DISABLED;
852 break;
853 }
854
855 #if __x86_64__
856 /*
857 * On x86, for compatibility, don't enforce the hard page-zero restriction for 32-bit binaries.
858 */
859 if (!result->is_64bit_addr) {
860 enforce_hard_pagezero = FALSE;
861 }
862
863 /*
864 * For processes with IMGPF_HIGH_BITS_ASLR, add a few random high bits
865 * to the start address for "anywhere" memory allocations.
866 */
867 #define VM_MAP_HIGH_START_BITS_COUNT 8
868 #define VM_MAP_HIGH_START_BITS_SHIFT 27
869 if (result->is_64bit_addr &&
870 (imgp->ip_flags & IMGPF_HIGH_BITS_ASLR)) {
871 int random_bits;
872 vm_map_offset_t high_start;
873
874 random_bits = random();
875 random_bits &= (1 << VM_MAP_HIGH_START_BITS_COUNT) - 1;
876 high_start = (((vm_map_offset_t)random_bits)
877 << VM_MAP_HIGH_START_BITS_SHIFT);
878 vm_map_set_high_start(map, high_start);
879 }
880 #endif /* __x86_64__ */
881
882 /*
883 * Check to see if the page zero is enforced by the map->min_offset.
884 */
885 if (enforce_hard_pagezero &&
886 (vm_map_has_hard_pagezero(map, 0x1000) == FALSE)) {
887 #if __arm64__
888 if (
889 !result->is_64bit_addr && /* not 64-bit address space */
890 !(header->flags & MH_PIE) && /* not PIE */
891 (vm_map_page_shift(map) != FOURK_PAGE_SHIFT ||
892 PAGE_SHIFT != FOURK_PAGE_SHIFT) && /* page size != 4KB */
893 result->has_pagezero && /* has a "soft" page zero */
894 fourk_binary_compatibility_unsafe) {
895 /*
896 * For backwards compatibility of "4K" apps on
897 * a 16K system, do not enforce a hard page zero...
898 */
899 } else
900 #endif /* __arm64__ */
901 {
902 imgp->ip_free_map = map;
903 return LOAD_BADMACHO;
904 }
905 }
906
907 #if __arm64__
908 if (enforce_hard_pagezero && result->is_64bit_addr && (header->cputype == CPU_TYPE_ARM64)) {
909 /* 64 bit ARM binary must have "hard page zero" of 4GB to cover the lower 32 bit address space */
910 if (vm_map_has_hard_pagezero(map, 0x100000000) == FALSE) {
911 imgp->ip_free_map = map;
912 return LOAD_BADMACHO;
913 }
914 }
915 #endif
916
917 vm_commit_pagezero_status(map);
918
919 /*
920 * If this is an exec, then we are going to destroy the old
921 * task, and it's correct to halt it; if it's spawn, the
922 * task is not yet running, and it makes no sense.
923 */
924 if (in_exec) {
925 proc_t p = current_proc();
926 /*
927 * Mark the task as halting and start the other
928 * threads towards terminating themselves. Then
929 * make sure any threads waiting for a process
930 * transition get informed that we are committed to
931 * this transition, and then finally complete the
932 * task halting (wait for threads and then cleanup
933 * task resources).
934 *
935 * NOTE: task_start_halt() makes sure that no new
936 * threads are created in the task during the transition.
937 * We need to mark the workqueue as exiting before we
938 * wait for threads to terminate (at the end of which
939 * we no longer have a prohibition on thread creation).
940 *
941 * Finally, clean up any lingering workqueue data structures
942 * that may have been left behind by the workqueue threads
943 * as they exited (and then clean up the work queue itself).
944 */
945 kret = task_start_halt(task);
946 if (kret != KERN_SUCCESS) {
947 imgp->ip_free_map = map;
948 return LOAD_FAILURE;
949 }
950 proc_transcommit(p, 0);
951 workq_mark_exiting(p);
952 task_complete_halt(task);
953 workq_exit(p);
954
955 /*
956 * Roll up accounting info to new task. The roll up is done after
957 * task_complete_halt to make sure the thread accounting info is
958 * rolled up to current_task.
959 */
960 task_rollup_accounting_info(get_threadtask(thread), task);
961 }
962 *mapp = map;
963
964 #if XNU_TARGET_OS_OSX
965 if (process_is_plugin_host(imgp, result)) {
966 /*
967 * We need to disable security policies for processes
968 * that run third party plugins.
969 */
970 imgp->ip_flags |= IMGPF_3P_PLUGINS;
971 }
972
973 #if __has_feature(ptrauth_calls)
974 /*
975 * arm64e plugin hosts currently run with JOP keys disabled, since they
976 * may need to run arm64 plugins.
977 */
978 if (imgp->ip_flags & IMGPF_3P_PLUGINS) {
979 imgp->ip_flags |= IMGPF_NOJOP;
980 pmap_disable_user_jop(pmap);
981 }
982
983 #if CONFIG_ROSETTA
984 /* Disable JOP keys if the Rosetta runtime being used isn't arm64e */
985 if (result->is_rosetta && (imgp->ip_flags & IMGPF_NOJOP)) {
986 pmap_disable_user_jop(pmap);
987 }
988 #endif /* CONFIG_ROSETTA */
989 #endif /* __has_feature(ptrauth_calls)*/
990 #endif /* XNU_TARGET_OS_OSX */
991
992
993 return LOAD_SUCCESS;
994 }
995
996 int macho_printf = 0;
997 #define MACHO_PRINTF(args) \
998 do { \
999 if (macho_printf) { \
1000 printf args; \
1001 } \
1002 } while (0)
1003
1004
1005 static boolean_t
pie_required(cpu_type_t exectype,cpu_subtype_t execsubtype)1006 pie_required(
1007 cpu_type_t exectype,
1008 cpu_subtype_t execsubtype)
1009 {
1010 switch (exectype) {
1011 case CPU_TYPE_X86_64:
1012 return FALSE;
1013 case CPU_TYPE_ARM64:
1014 return TRUE;
1015 case CPU_TYPE_ARM:
1016 switch (execsubtype) {
1017 case CPU_SUBTYPE_ARM_V7K:
1018 return TRUE;
1019 }
1020 break;
1021 }
1022 return FALSE;
1023 }
1024
1025 /*
1026 * Grades the specified CPU type, CPU subtype, CPU features to determine an absolute weight, used in the determination
1027 * of running the associated binary on this machine.
1028 *
1029 * If an override boot-arg is specified, the boot-arg is parsed and its values are stored for later use in overriding
1030 * the system's hard-coded binary grading values.
1031 */
1032 int
grade_binary(cpu_type_t exectype,cpu_subtype_t execsubtype,cpu_subtype_t execfeatures,bool allow_simulator_binary)1033 grade_binary(cpu_type_t exectype, cpu_subtype_t execsubtype, cpu_subtype_t execfeatures, bool allow_simulator_binary)
1034 {
1035 extern int ml_grade_binary(cpu_type_t, cpu_subtype_t, cpu_subtype_t, bool);
1036
1037 int binary_grade;
1038
1039 if ((binary_grade = grade_binary_override(exectype, execsubtype, execfeatures, allow_simulator_binary)) < 0) {
1040 return ml_grade_binary(exectype, execsubtype, execfeatures, allow_simulator_binary);
1041 }
1042
1043 return binary_grade;
1044 }
1045
1046 /*
1047 * The file size of a mach-o file is limited to 32 bits; this is because
1048 * this is the limit on the kalloc() of enough bytes for a mach_header and
1049 * the contents of its sizeofcmds, which is currently constrained to 32
1050 * bits in the file format itself. We read into the kernel buffer the
1051 * commands section, and then parse it in order to parse the mach-o file
1052 * format load_command segment(s). We are only interested in a subset of
1053 * the total set of possible commands. If "map"==VM_MAP_NULL or
1054 * "thread"==THREAD_NULL, do not make permament VM modifications,
1055 * just preflight the parse.
1056 */
1057 static
1058 load_return_t
parse_machfile(struct vnode * vp,vm_map_t map,thread_t thread,struct mach_header * header,off_t file_offset,off_t macho_size,int depth,int64_t aslr_offset,int64_t dyld_aslr_offset,load_result_t * result,load_result_t * binresult,struct image_params * imgp)1059 parse_machfile(
1060 struct vnode *vp,
1061 vm_map_t map,
1062 thread_t thread,
1063 struct mach_header *header,
1064 off_t file_offset,
1065 off_t macho_size,
1066 int depth,
1067 int64_t aslr_offset,
1068 int64_t dyld_aslr_offset,
1069 load_result_t *result,
1070 load_result_t *binresult,
1071 struct image_params *imgp
1072 )
1073 {
1074 uint32_t ncmds;
1075 struct load_command *lcp;
1076 struct dylinker_command *dlp = 0;
1077 void * control;
1078 load_return_t ret = LOAD_SUCCESS;
1079 void * addr;
1080 vm_size_t alloc_size, cmds_size;
1081 size_t offset;
1082 size_t oldoffset; /* for overflow check */
1083 int pass;
1084 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
1085 int error;
1086 int resid = 0;
1087 int spawn = (imgp->ip_flags & IMGPF_SPAWN);
1088 size_t mach_header_sz = sizeof(struct mach_header);
1089 boolean_t abi64;
1090 boolean_t got_code_signatures = FALSE;
1091 boolean_t found_header_segment = FALSE;
1092 boolean_t found_xhdr = FALSE;
1093 boolean_t found_version_cmd = FALSE;
1094 int64_t slide = 0;
1095 boolean_t dyld_no_load_addr = FALSE;
1096 boolean_t is_dyld = FALSE;
1097 vm_map_offset_t effective_page_mask = PAGE_MASK;
1098 #if __arm64__
1099 uint64_t pagezero_end = 0;
1100 uint64_t executable_end = 0;
1101 uint64_t writable_start = 0;
1102 vm_map_size_t effective_page_size;
1103
1104 effective_page_mask = vm_map_page_mask(map);
1105 effective_page_size = vm_map_page_size(map);
1106 #endif /* __arm64__ */
1107
1108 if (header->magic == MH_MAGIC_64 ||
1109 header->magic == MH_CIGAM_64) {
1110 mach_header_sz = sizeof(struct mach_header_64);
1111 }
1112
1113 /*
1114 * Break infinite recursion
1115 */
1116 if (depth > 2) {
1117 return LOAD_FAILURE;
1118 }
1119
1120 depth++;
1121
1122 /*
1123 * Set CS_NO_UNTRUSTED_HELPERS by default; load_dylinker and load_rosetta
1124 * will unset it if necessary.
1125 */
1126 if (depth == 1) {
1127 result->csflags |= CS_NO_UNTRUSTED_HELPERS;
1128 }
1129
1130 /*
1131 * Check to see if right machine type.
1132 */
1133 if (((cpu_type_t)(header->cputype & ~CPU_ARCH_MASK) != (cpu_type() & ~CPU_ARCH_MASK))
1134 ) {
1135 return LOAD_BADARCH;
1136 }
1137
1138 if (!grade_binary(header->cputype,
1139 header->cpusubtype & ~CPU_SUBTYPE_MASK,
1140 header->cpusubtype & CPU_SUBTYPE_MASK, TRUE)) {
1141 return LOAD_BADARCH;
1142 }
1143
1144 abi64 = ((header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64);
1145
1146 switch (header->filetype) {
1147 case MH_EXECUTE:
1148 if (depth != 1 && depth != 3) {
1149 return LOAD_FAILURE;
1150 }
1151 if (header->flags & MH_DYLDLINK) {
1152 /* Check properties of dynamic executables */
1153 if (!(header->flags & MH_PIE) && pie_required(header->cputype, header->cpusubtype & ~CPU_SUBTYPE_MASK)) {
1154 return LOAD_FAILURE;
1155 }
1156 result->needs_dynlinker = TRUE;
1157 } else if (header->cputype == CPU_TYPE_X86_64) {
1158 /* x86_64 static binaries allowed */
1159 #if CONFIG_ROSETTA
1160 } else if (imgp->ip_flags & IMGPF_ROSETTA) {
1161 /* Rosetta runtime allowed */
1162 #endif /* CONFIG_X86_64_COMPAT */
1163 } else {
1164 /* Check properties of static executables (disallowed except for development) */
1165 #if !(DEVELOPMENT || DEBUG)
1166 return LOAD_FAILURE;
1167 #endif
1168 }
1169 break;
1170 case MH_DYLINKER:
1171 if (depth != 2) {
1172 return LOAD_FAILURE;
1173 }
1174 is_dyld = TRUE;
1175 break;
1176
1177 default:
1178 return LOAD_FAILURE;
1179 }
1180
1181 /*
1182 * For PIE and dyld, slide everything by the ASLR offset.
1183 */
1184 if ((header->flags & MH_PIE) || is_dyld) {
1185 slide = aslr_offset;
1186 }
1187
1188 /*
1189 * Get the pager for the file.
1190 */
1191 control = ubc_getobject(vp, UBC_FLAGS_NONE);
1192
1193 /* ensure header + sizeofcmds falls within the file */
1194 if (os_add_overflow(mach_header_sz, header->sizeofcmds, &cmds_size) ||
1195 (off_t)cmds_size > macho_size ||
1196 round_page_overflow(cmds_size, &alloc_size) ||
1197 alloc_size > INT_MAX) {
1198 return LOAD_BADMACHO;
1199 }
1200
1201 /*
1202 * Map the load commands into kernel memory.
1203 */
1204 addr = kalloc_data(alloc_size, Z_WAITOK);
1205 if (addr == NULL) {
1206 return LOAD_NOSPACE;
1207 }
1208
1209 error = vn_rdwr(UIO_READ, vp, addr, (int)alloc_size, file_offset,
1210 UIO_SYSSPACE, 0, vfs_context_ucred(imgp->ip_vfs_context), &resid, p);
1211 if (error) {
1212 kfree_data(addr, alloc_size);
1213 return LOAD_IOERROR;
1214 }
1215
1216 if (resid) {
1217 {
1218 /* We must be able to read in as much as the mach_header indicated */
1219 kfree_data(addr, alloc_size);
1220 return LOAD_BADMACHO;
1221 }
1222 }
1223
1224 /*
1225 * Scan through the commands, processing each one as necessary.
1226 * We parse in three passes through the headers:
1227 * 0: determine if TEXT and DATA boundary can be page-aligned, load platform version
1228 * 1: thread state, uuid, code signature
1229 * 2: segments
1230 * 3: dyld, encryption, check entry point
1231 */
1232
1233 boolean_t slide_realign = FALSE;
1234 #if __arm64__
1235 if (!abi64) {
1236 slide_realign = TRUE;
1237 }
1238 #endif
1239
1240 for (pass = 0; pass <= 3; pass++) {
1241 if (pass == 1) {
1242 #if __arm64__
1243 boolean_t is_pie;
1244 int64_t adjust;
1245
1246 is_pie = ((header->flags & MH_PIE) != 0);
1247 if (pagezero_end != 0 &&
1248 pagezero_end < effective_page_size) {
1249 /* need at least 1 page for PAGEZERO */
1250 adjust = effective_page_size;
1251 MACHO_PRINTF(("pagezero boundary at "
1252 "0x%llx; adjust slide from "
1253 "0x%llx to 0x%llx%s\n",
1254 (uint64_t) pagezero_end,
1255 slide,
1256 slide + adjust,
1257 (is_pie
1258 ? ""
1259 : " BUT NO PIE ****** :-(")));
1260 if (is_pie) {
1261 slide += adjust;
1262 pagezero_end += adjust;
1263 executable_end += adjust;
1264 writable_start += adjust;
1265 }
1266 }
1267 if (pagezero_end != 0) {
1268 result->has_pagezero = TRUE;
1269 }
1270 if (executable_end == writable_start &&
1271 (executable_end & effective_page_mask) != 0 &&
1272 (executable_end & FOURK_PAGE_MASK) == 0) {
1273 /*
1274 * The TEXT/DATA boundary is 4K-aligned but
1275 * not page-aligned. Adjust the slide to make
1276 * it page-aligned and avoid having a page
1277 * with both write and execute permissions.
1278 */
1279 adjust =
1280 (effective_page_size -
1281 (executable_end & effective_page_mask));
1282 MACHO_PRINTF(("page-unaligned X-W boundary at "
1283 "0x%llx; adjust slide from "
1284 "0x%llx to 0x%llx%s\n",
1285 (uint64_t) executable_end,
1286 slide,
1287 slide + adjust,
1288 (is_pie
1289 ? ""
1290 : " BUT NO PIE ****** :-(")));
1291 if (is_pie) {
1292 slide += adjust;
1293 }
1294 }
1295 #endif /* __arm64__ */
1296
1297 if (dyld_no_load_addr && binresult) {
1298 /*
1299 * The dyld Mach-O does not specify a load address. Try to locate
1300 * it right after the main binary. If binresult == NULL, load
1301 * directly to the given slide.
1302 */
1303 mach_vm_address_t max_vm_addr = binresult->max_vm_addr;
1304 slide = vm_map_round_page(slide + max_vm_addr, effective_page_mask);
1305 }
1306 }
1307
1308 /*
1309 * Check that the entry point is contained in an executable segment
1310 */
1311 if ((pass == 3) && (thread != THREAD_NULL)) {
1312 if (depth == 1 && imgp && (imgp->ip_flags & IMGPF_DRIVER)) {
1313 /* Driver binaries must have driverkit platform */
1314 if (result->ip_platform == PLATFORM_DRIVERKIT) {
1315 /* Driver binaries have no entry point */
1316 ret = setup_driver_main(thread, slide, result);
1317 } else {
1318 ret = LOAD_FAILURE;
1319 }
1320 } else if (!result->using_lcmain && result->validentry == 0) {
1321 ret = LOAD_FAILURE;
1322 }
1323 if (ret != KERN_SUCCESS) {
1324 thread_state_initialize(thread);
1325 break;
1326 }
1327 }
1328
1329 /*
1330 * Check that some segment maps the start of the mach-o file, which is
1331 * needed by the dynamic loader to read the mach headers, etc.
1332 */
1333 if ((pass == 3) && (found_header_segment == FALSE)) {
1334 ret = LOAD_BADMACHO;
1335 break;
1336 }
1337
1338 /*
1339 * Loop through each of the load_commands indicated by the
1340 * Mach-O header; if an absurd value is provided, we just
1341 * run off the end of the reserved section by incrementing
1342 * the offset too far, so we are implicitly fail-safe.
1343 */
1344 offset = mach_header_sz;
1345 ncmds = header->ncmds;
1346
1347 while (ncmds--) {
1348 /* ensure enough space for a minimal load command */
1349 if (offset + sizeof(struct load_command) > cmds_size) {
1350 ret = LOAD_BADMACHO;
1351 break;
1352 }
1353
1354 /*
1355 * Get a pointer to the command.
1356 */
1357 lcp = (struct load_command *)((uintptr_t)addr + offset);
1358 oldoffset = offset;
1359
1360 /*
1361 * Perform prevalidation of the struct load_command
1362 * before we attempt to use its contents. Invalid
1363 * values are ones which result in an overflow, or
1364 * which can not possibly be valid commands, or which
1365 * straddle or exist past the reserved section at the
1366 * start of the image.
1367 */
1368 if (os_add_overflow(offset, lcp->cmdsize, &offset) ||
1369 lcp->cmdsize < sizeof(struct load_command) ||
1370 offset > cmds_size) {
1371 ret = LOAD_BADMACHO;
1372 break;
1373 }
1374
1375 /*
1376 * Act on struct load_command's for which kernel
1377 * intervention is required.
1378 * Note that each load command implementation is expected to validate
1379 * that lcp->cmdsize is large enough to fit its specific struct type
1380 * before dereferencing fields not covered by struct load_command.
1381 */
1382 switch (lcp->cmd) {
1383 case LC_SEGMENT: {
1384 struct segment_command *scp = (struct segment_command *) lcp;
1385 if (scp->cmdsize < sizeof(*scp)) {
1386 ret = LOAD_BADMACHO;
1387 break;
1388 }
1389 if (pass == 0) {
1390 if (is_dyld && scp->vmaddr == 0 && scp->fileoff == 0) {
1391 dyld_no_load_addr = TRUE;
1392 if (!slide_realign) {
1393 /* got what we need, bail early on pass 0 */
1394 continue;
1395 }
1396 }
1397
1398 #if __arm64__
1399 assert(!abi64);
1400
1401 if (scp->initprot == 0 && scp->maxprot == 0 && scp->vmaddr == 0) {
1402 /* PAGEZERO */
1403 if (os_add3_overflow(scp->vmaddr, scp->vmsize, slide, &pagezero_end) || pagezero_end > UINT32_MAX) {
1404 ret = LOAD_BADMACHO;
1405 break;
1406 }
1407 }
1408 if (scp->initprot & VM_PROT_EXECUTE) {
1409 /* TEXT */
1410 if (os_add3_overflow(scp->vmaddr, scp->vmsize, slide, &executable_end) || executable_end > UINT32_MAX) {
1411 ret = LOAD_BADMACHO;
1412 break;
1413 }
1414 }
1415 if (scp->initprot & VM_PROT_WRITE) {
1416 /* DATA */
1417 if (os_add_overflow(scp->vmaddr, slide, &writable_start) || writable_start > UINT32_MAX) {
1418 ret = LOAD_BADMACHO;
1419 break;
1420 }
1421 }
1422 #endif /* __arm64__ */
1423 break;
1424 }
1425
1426 if (pass == 1 && !strncmp(scp->segname, "__XHDR", sizeof(scp->segname))) {
1427 found_xhdr = TRUE;
1428 }
1429
1430 if (pass != 2) {
1431 break;
1432 }
1433
1434 if (abi64) {
1435 /*
1436 * Having an LC_SEGMENT command for the
1437 * wrong ABI is invalid <rdar://problem/11021230>
1438 */
1439 ret = LOAD_BADMACHO;
1440 break;
1441 }
1442
1443 ret = load_segment(lcp,
1444 header->filetype,
1445 control,
1446 file_offset,
1447 macho_size,
1448 vp,
1449 map,
1450 slide,
1451 result,
1452 imgp);
1453 if (ret == LOAD_SUCCESS && scp->fileoff == 0 && scp->filesize > 0) {
1454 /* Enforce a single segment mapping offset zero, with R+X
1455 * protection. */
1456 if (found_header_segment ||
1457 ((scp->initprot & (VM_PROT_READ | VM_PROT_EXECUTE)) != (VM_PROT_READ | VM_PROT_EXECUTE))) {
1458 ret = LOAD_BADMACHO;
1459 break;
1460 }
1461 found_header_segment = TRUE;
1462 }
1463
1464 break;
1465 }
1466 case LC_SEGMENT_64: {
1467 struct segment_command_64 *scp64 = (struct segment_command_64 *) lcp;
1468 if (scp64->cmdsize < sizeof(*scp64)) {
1469 ret = LOAD_BADMACHO;
1470 break;
1471 }
1472 if (pass == 0) {
1473 if (is_dyld && scp64->vmaddr == 0 && scp64->fileoff == 0) {
1474 dyld_no_load_addr = TRUE;
1475 }
1476 /* got what we need, bail early on pass 0 */
1477 continue;
1478 }
1479
1480 if (pass == 1 && !strncmp(scp64->segname, "__XHDR", sizeof(scp64->segname))) {
1481 found_xhdr = TRUE;
1482 }
1483
1484 if (pass != 2) {
1485 break;
1486 }
1487
1488 if (!abi64) {
1489 /*
1490 * Having an LC_SEGMENT_64 command for the
1491 * wrong ABI is invalid <rdar://problem/11021230>
1492 */
1493 ret = LOAD_BADMACHO;
1494 break;
1495 }
1496
1497 ret = load_segment(lcp,
1498 header->filetype,
1499 control,
1500 file_offset,
1501 macho_size,
1502 vp,
1503 map,
1504 slide,
1505 result,
1506 imgp);
1507
1508 if (ret == LOAD_SUCCESS && scp64->fileoff == 0 && scp64->filesize > 0) {
1509 /* Enforce a single segment mapping offset zero, with R+X
1510 * protection. */
1511 if (found_header_segment ||
1512 ((scp64->initprot & (VM_PROT_READ | VM_PROT_EXECUTE)) != (VM_PROT_READ | VM_PROT_EXECUTE))) {
1513 ret = LOAD_BADMACHO;
1514 break;
1515 }
1516 found_header_segment = TRUE;
1517 }
1518
1519 break;
1520 }
1521 case LC_UNIXTHREAD: {
1522 boolean_t is_x86_64_compat_binary = FALSE;
1523 if (pass != 1) {
1524 break;
1525 }
1526 #if CONFIG_ROSETTA
1527 if (depth == 2 && (imgp->ip_flags & IMGPF_ROSETTA)) {
1528 // Ignore dyld, Rosetta will parse it's load commands to get the
1529 // entry point.
1530 result->validentry = 1;
1531 break;
1532 }
1533 #endif
1534 ret = load_unixthread(
1535 (struct thread_command *) lcp,
1536 thread,
1537 slide,
1538 is_x86_64_compat_binary,
1539 result);
1540 break;
1541 }
1542 case LC_MAIN:
1543 if (pass != 1) {
1544 break;
1545 }
1546 if (depth != 1) {
1547 break;
1548 }
1549 ret = load_main(
1550 (struct entry_point_command *) lcp,
1551 thread,
1552 slide,
1553 result);
1554 break;
1555 case LC_LOAD_DYLINKER:
1556 if (pass != 3) {
1557 break;
1558 }
1559 if ((depth == 1) && (dlp == 0)) {
1560 dlp = (struct dylinker_command *)lcp;
1561 } else {
1562 ret = LOAD_FAILURE;
1563 }
1564 break;
1565 case LC_UUID:
1566 if (pass == 1 && depth == 1) {
1567 ret = load_uuid((struct uuid_command *) lcp,
1568 (char *)addr + cmds_size,
1569 result);
1570 }
1571 break;
1572 case LC_CODE_SIGNATURE:
1573 /* CODE SIGNING */
1574 if (pass != 1) {
1575 break;
1576 }
1577
1578 /* pager -> uip ->
1579 * load signatures & store in uip
1580 * set VM object "signed_pages"
1581 */
1582 ret = load_code_signature(
1583 (struct linkedit_data_command *) lcp,
1584 vp,
1585 file_offset,
1586 macho_size,
1587 header->cputype,
1588 header->cpusubtype,
1589 result,
1590 imgp);
1591 if (ret != LOAD_SUCCESS) {
1592 printf("proc %d: load code signature error %d "
1593 "for file \"%s\"\n",
1594 proc_getpid(p), ret, vp->v_name);
1595 /*
1596 * Allow injections to be ignored on devices w/o enforcement enabled
1597 */
1598 if (!cs_process_global_enforcement()) {
1599 ret = LOAD_SUCCESS; /* ignore error */
1600 }
1601 } else {
1602 got_code_signatures = TRUE;
1603 }
1604
1605 if (got_code_signatures) {
1606 unsigned tainted = CS_VALIDATE_TAINTED;
1607 boolean_t valid = FALSE;
1608 vm_size_t off = 0;
1609
1610
1611 if (cs_debug > 10) {
1612 printf("validating initial pages of %s\n", vp->v_name);
1613 }
1614
1615 while (off < alloc_size && ret == LOAD_SUCCESS) {
1616 tainted = CS_VALIDATE_TAINTED;
1617
1618 valid = cs_validate_range(vp,
1619 NULL,
1620 file_offset + off,
1621 (const void *)((uintptr_t)addr + off),
1622 MIN(PAGE_SIZE, cmds_size),
1623 &tainted);
1624 if (!valid || (tainted & CS_VALIDATE_TAINTED)) {
1625 if (cs_debug) {
1626 printf("CODE SIGNING: %s[%d]: invalid initial page at offset %lld validated:%d tainted:%d csflags:0x%x\n",
1627 vp->v_name, proc_getpid(p), (long long)(file_offset + off), valid, tainted, result->csflags);
1628 }
1629 if (cs_process_global_enforcement() ||
1630 (result->csflags & (CS_HARD | CS_KILL | CS_ENFORCEMENT))) {
1631 ret = LOAD_FAILURE;
1632 }
1633 result->csflags &= ~CS_VALID;
1634 }
1635 off += PAGE_SIZE;
1636 }
1637 }
1638
1639 break;
1640 #if CONFIG_CODE_DECRYPTION
1641 case LC_ENCRYPTION_INFO:
1642 case LC_ENCRYPTION_INFO_64:
1643 if (pass != 3) {
1644 break;
1645 }
1646 ret = set_code_unprotect(
1647 (struct encryption_info_command *) lcp,
1648 addr, map, slide, vp, file_offset,
1649 header->cputype, header->cpusubtype);
1650 if (ret != LOAD_SUCCESS) {
1651 os_reason_t load_failure_reason = OS_REASON_NULL;
1652 printf("proc %d: set_code_unprotect() error %d "
1653 "for file \"%s\"\n",
1654 proc_getpid(p), ret, vp->v_name);
1655 /*
1656 * Don't let the app run if it's
1657 * encrypted but we failed to set up the
1658 * decrypter. If the keys are missing it will
1659 * return LOAD_DECRYPTFAIL.
1660 */
1661 if (ret == LOAD_DECRYPTFAIL) {
1662 /* failed to load due to missing FP keys */
1663 proc_lock(p);
1664 p->p_lflag |= P_LTERM_DECRYPTFAIL;
1665 proc_unlock(p);
1666
1667 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1668 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_FAIRPLAY_DECRYPT, 0, 0);
1669 load_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_FAIRPLAY_DECRYPT);
1670 } else {
1671 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1672 proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_DECRYPT, 0, 0);
1673 load_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_DECRYPT);
1674 }
1675
1676 /*
1677 * Don't signal the process if it was forked and in a partially constructed
1678 * state as part of a spawn -- it will just be torn down when the exec fails.
1679 */
1680 if (!spawn) {
1681 assert(load_failure_reason != OS_REASON_NULL);
1682 {
1683 psignal_with_reason(current_proc(), SIGKILL, load_failure_reason);
1684 load_failure_reason = OS_REASON_NULL;
1685 }
1686 } else {
1687 os_reason_free(load_failure_reason);
1688 load_failure_reason = OS_REASON_NULL;
1689 }
1690 }
1691 break;
1692 #endif
1693 case LC_VERSION_MIN_IPHONEOS:
1694 case LC_VERSION_MIN_MACOSX:
1695 case LC_VERSION_MIN_WATCHOS:
1696 case LC_VERSION_MIN_TVOS: {
1697 struct version_min_command *vmc;
1698
1699 if (depth != 1 || pass != 0) {
1700 break;
1701 }
1702 vmc = (struct version_min_command *) lcp;
1703 ret = load_version(vmc, &found_version_cmd, imgp, result);
1704 #if XNU_TARGET_OS_OSX
1705 if (ret == LOAD_SUCCESS) {
1706 if (result->ip_platform == PLATFORM_IOS) {
1707 vm_map_mark_alien(map);
1708 } else {
1709 assert(!vm_map_is_alien(map));
1710 }
1711 }
1712 #endif /* XNU_TARGET_OS_OSX */
1713 break;
1714 }
1715 case LC_BUILD_VERSION: {
1716 if (depth != 1 || pass != 0) {
1717 break;
1718 }
1719 struct build_version_command* bvc = (struct build_version_command*)lcp;
1720 if (bvc->cmdsize < sizeof(*bvc)) {
1721 ret = LOAD_BADMACHO;
1722 break;
1723 }
1724 if (found_version_cmd == TRUE) {
1725 ret = LOAD_BADMACHO;
1726 break;
1727 }
1728 result->ip_platform = bvc->platform;
1729 result->lr_sdk = bvc->sdk;
1730 result->lr_min_sdk = bvc->minos;
1731 found_version_cmd = TRUE;
1732 #if XNU_TARGET_OS_OSX
1733 if (result->ip_platform == PLATFORM_IOS) {
1734 vm_map_mark_alien(map);
1735 } else {
1736 assert(!vm_map_is_alien(map));
1737 }
1738 #endif /* XNU_TARGET_OS_OSX */
1739 break;
1740 }
1741 default:
1742 /* Other commands are ignored by the kernel */
1743 ret = LOAD_SUCCESS;
1744 break;
1745 }
1746 if (ret != LOAD_SUCCESS) {
1747 break;
1748 }
1749 }
1750 if (ret != LOAD_SUCCESS) {
1751 break;
1752 }
1753 }
1754
1755 if (ret == LOAD_SUCCESS) {
1756 if (!got_code_signatures && cs_process_global_enforcement()) {
1757 ret = LOAD_FAILURE;
1758 }
1759
1760 /* Make sure if we need dyld, we got it */
1761 if (result->needs_dynlinker && !dlp) {
1762 ret = LOAD_FAILURE;
1763 }
1764
1765 if ((ret == LOAD_SUCCESS) && (dlp != 0)) {
1766 /*
1767 * load the dylinker, and slide it by the independent DYLD ASLR
1768 * offset regardless of the PIE-ness of the main binary.
1769 */
1770 ret = load_dylinker(dlp, header->cputype, map, thread, depth,
1771 dyld_aslr_offset, result, imgp);
1772 }
1773
1774 #if CONFIG_ROSETTA
1775 if ((ret == LOAD_SUCCESS) && (depth == 1) && (imgp->ip_flags & IMGPF_ROSETTA)) {
1776 ret = load_rosetta(map, thread, result, imgp);
1777 if (ret == LOAD_SUCCESS) {
1778 if (result->user_stack_alloc_size != 0) {
1779 // If a stack allocation is required then add a 4gb gap after the main
1780 // binary/dyld for the worst case static translation size.
1781 mach_vm_size_t reserved_aot_size = 0x100000000;
1782 vm_map_offset_t mask = vm_map_page_mask(map);
1783
1784 mach_vm_address_t vm_end;
1785 if (dlp != 0) {
1786 vm_end = vm_map_round_page(result->dynlinker_max_vm_addr, mask);
1787 } else {
1788 vm_end = vm_map_round_page(result->max_vm_addr, mask);
1789 }
1790
1791 mach_vm_size_t user_stack_size = vm_map_round_page(result->user_stack_alloc_size, mask);
1792 result->user_stack = vm_map_round_page(vm_end + user_stack_size + reserved_aot_size + slide, mask);
1793 }
1794 }
1795 }
1796 #endif
1797
1798 if ((ret == LOAD_SUCCESS) && (depth == 1)) {
1799 if (result->thread_count == 0) {
1800 ret = LOAD_FAILURE;
1801 }
1802 #if CONFIG_ENFORCE_SIGNED_CODE
1803 if (!(result->csflags & CS_NO_UNTRUSTED_HELPERS)) {
1804 ret = LOAD_FAILURE;
1805 }
1806 #endif
1807 }
1808 }
1809
1810 if (ret == LOAD_BADMACHO && found_xhdr) {
1811 ret = LOAD_BADMACHO_UPX;
1812 }
1813
1814 kfree_data(addr, alloc_size);
1815
1816 return ret;
1817 }
1818
1819 load_return_t
validate_potential_simulator_binary(cpu_type_t exectype __unused,struct image_params * imgp __unused,off_t file_offset __unused,off_t macho_size __unused)1820 validate_potential_simulator_binary(
1821 cpu_type_t exectype __unused,
1822 struct image_params *imgp __unused,
1823 off_t file_offset __unused,
1824 off_t macho_size __unused)
1825 {
1826 #if __x86_64__
1827 /* Allow 32 bit exec only for simulator binaries */
1828 if (bootarg_no32exec && imgp != NULL && exectype == CPU_TYPE_X86) {
1829 if (imgp->ip_simulator_binary == IMGPF_SB_DEFAULT) {
1830 boolean_t simulator_binary = check_if_simulator_binary(imgp, file_offset, macho_size);
1831 imgp->ip_simulator_binary = simulator_binary ? IMGPF_SB_TRUE : IMGPF_SB_FALSE;
1832 }
1833
1834 if (imgp->ip_simulator_binary != IMGPF_SB_TRUE) {
1835 return LOAD_BADARCH;
1836 }
1837 }
1838 #endif
1839 return LOAD_SUCCESS;
1840 }
1841
1842 #if __x86_64__
1843 static boolean_t
check_if_simulator_binary(struct image_params * imgp,off_t file_offset,off_t macho_size)1844 check_if_simulator_binary(
1845 struct image_params *imgp,
1846 off_t file_offset,
1847 off_t macho_size)
1848 {
1849 struct mach_header *header;
1850 char *ip_vdata = NULL;
1851 kauth_cred_t cred = NULL;
1852 uint32_t ncmds;
1853 struct load_command *lcp;
1854 boolean_t simulator_binary = FALSE;
1855 void * addr = NULL;
1856 vm_size_t alloc_size, cmds_size;
1857 size_t offset;
1858 proc_t p = current_proc(); /* XXXX */
1859 int error;
1860 int resid = 0;
1861 size_t mach_header_sz = sizeof(struct mach_header);
1862
1863
1864 cred = kauth_cred_proc_ref(p);
1865
1866 /* Allocate page to copyin mach header */
1867 ip_vdata = kalloc_data(PAGE_SIZE, Z_WAITOK | Z_ZERO);
1868 if (ip_vdata == NULL) {
1869 goto bad;
1870 }
1871
1872 /* Read the Mach-O header */
1873 error = vn_rdwr(UIO_READ, imgp->ip_vp, ip_vdata,
1874 PAGE_SIZE, file_offset,
1875 UIO_SYSSPACE, (IO_UNIT | IO_NODELOCKED),
1876 cred, &resid, p);
1877 if (error) {
1878 goto bad;
1879 }
1880
1881 header = (struct mach_header *)ip_vdata;
1882
1883 if (header->magic == MH_MAGIC_64 ||
1884 header->magic == MH_CIGAM_64) {
1885 mach_header_sz = sizeof(struct mach_header_64);
1886 }
1887
1888 /* ensure header + sizeofcmds falls within the file */
1889 if (os_add_overflow(mach_header_sz, header->sizeofcmds, &cmds_size) ||
1890 (off_t)cmds_size > macho_size ||
1891 round_page_overflow(cmds_size, &alloc_size) ||
1892 alloc_size > INT_MAX) {
1893 goto bad;
1894 }
1895
1896 /*
1897 * Map the load commands into kernel memory.
1898 */
1899 addr = kalloc_data(alloc_size, Z_WAITOK);
1900 if (addr == NULL) {
1901 goto bad;
1902 }
1903
1904 error = vn_rdwr(UIO_READ, imgp->ip_vp, addr, (int)alloc_size, file_offset,
1905 UIO_SYSSPACE, IO_NODELOCKED, cred, &resid, p);
1906 if (error) {
1907 goto bad;
1908 }
1909
1910 if (resid) {
1911 /* We must be able to read in as much as the mach_header indicated */
1912 goto bad;
1913 }
1914
1915 /*
1916 * Loop through each of the load_commands indicated by the
1917 * Mach-O header; if an absurd value is provided, we just
1918 * run off the end of the reserved section by incrementing
1919 * the offset too far, so we are implicitly fail-safe.
1920 */
1921 offset = mach_header_sz;
1922 ncmds = header->ncmds;
1923
1924 while (ncmds--) {
1925 /* ensure enough space for a minimal load command */
1926 if (offset + sizeof(struct load_command) > cmds_size) {
1927 break;
1928 }
1929
1930 /*
1931 * Get a pointer to the command.
1932 */
1933 lcp = (struct load_command *)((uintptr_t)addr + offset);
1934
1935 /*
1936 * Perform prevalidation of the struct load_command
1937 * before we attempt to use its contents. Invalid
1938 * values are ones which result in an overflow, or
1939 * which can not possibly be valid commands, or which
1940 * straddle or exist past the reserved section at the
1941 * start of the image.
1942 */
1943 if (os_add_overflow(offset, lcp->cmdsize, &offset) ||
1944 lcp->cmdsize < sizeof(struct load_command) ||
1945 offset > cmds_size) {
1946 break;
1947 }
1948
1949 /* Check if its a simulator binary. */
1950 switch (lcp->cmd) {
1951 case LC_VERSION_MIN_WATCHOS:
1952 simulator_binary = TRUE;
1953 break;
1954
1955 case LC_BUILD_VERSION: {
1956 struct build_version_command *bvc;
1957
1958 bvc = (struct build_version_command *) lcp;
1959 if (bvc->cmdsize < sizeof(*bvc)) {
1960 /* unsafe to use this command struct if cmdsize
1961 * validated above is too small for it to fit */
1962 break;
1963 }
1964 if (bvc->platform == PLATFORM_IOSSIMULATOR ||
1965 bvc->platform == PLATFORM_WATCHOSSIMULATOR) {
1966 simulator_binary = TRUE;
1967 }
1968
1969 break;
1970 }
1971
1972 case LC_VERSION_MIN_IPHONEOS: {
1973 simulator_binary = TRUE;
1974 break;
1975 }
1976
1977 default:
1978 /* ignore other load commands */
1979 break;
1980 }
1981
1982 if (simulator_binary == TRUE) {
1983 break;
1984 }
1985 }
1986
1987 bad:
1988 if (ip_vdata) {
1989 kfree_data(ip_vdata, PAGE_SIZE);
1990 }
1991
1992 if (cred) {
1993 kauth_cred_unref(&cred);
1994 }
1995
1996 if (addr) {
1997 kfree_data(addr, alloc_size);
1998 }
1999
2000 return simulator_binary;
2001 }
2002 #endif /* __x86_64__ */
2003
2004 #if CONFIG_CODE_DECRYPTION
2005
2006 #define APPLE_UNPROTECTED_HEADER_SIZE (3 * 4096)
2007
2008 static load_return_t
unprotect_dsmos_segment(uint64_t file_off,uint64_t file_size,struct vnode * vp,off_t macho_offset,vm_map_t map,vm_map_offset_t map_addr,vm_map_size_t map_size)2009 unprotect_dsmos_segment(
2010 uint64_t file_off,
2011 uint64_t file_size,
2012 struct vnode *vp,
2013 off_t macho_offset,
2014 vm_map_t map,
2015 vm_map_offset_t map_addr,
2016 vm_map_size_t map_size)
2017 {
2018 kern_return_t kr;
2019 uint64_t slice_off;
2020
2021 /*
2022 * The first APPLE_UNPROTECTED_HEADER_SIZE bytes (from offset 0 of
2023 * this part of a Universal binary) are not protected...
2024 * The rest needs to be "transformed".
2025 */
2026 slice_off = file_off - macho_offset;
2027 if (slice_off <= APPLE_UNPROTECTED_HEADER_SIZE &&
2028 slice_off + file_size <= APPLE_UNPROTECTED_HEADER_SIZE) {
2029 /* it's all unprotected, nothing to do... */
2030 kr = KERN_SUCCESS;
2031 } else {
2032 if (slice_off <= APPLE_UNPROTECTED_HEADER_SIZE) {
2033 /*
2034 * We start mapping in the unprotected area.
2035 * Skip the unprotected part...
2036 */
2037 uint64_t delta_file;
2038 vm_map_offset_t delta_map;
2039
2040 delta_file = (uint64_t)APPLE_UNPROTECTED_HEADER_SIZE;
2041 delta_file -= slice_off;
2042 if (os_convert_overflow(delta_file, &delta_map)) {
2043 return LOAD_BADMACHO;
2044 }
2045 if (os_add_overflow(map_addr, delta_map, &map_addr)) {
2046 return LOAD_BADMACHO;
2047 }
2048 if (os_sub_overflow(map_size, delta_map, &map_size)) {
2049 return LOAD_BADMACHO;
2050 }
2051 }
2052 /* ... transform the rest of the mapping. */
2053 struct pager_crypt_info crypt_info;
2054 crypt_info.page_decrypt = dsmos_page_transform;
2055 crypt_info.crypt_ops = NULL;
2056 crypt_info.crypt_end = NULL;
2057 #pragma unused(vp, macho_offset)
2058 crypt_info.crypt_ops = (void *)0x2e69cf40;
2059 vm_map_offset_t crypto_backing_offset;
2060 crypto_backing_offset = -1; /* i.e. use map entry's offset */
2061 #if VM_MAP_DEBUG_APPLE_PROTECT
2062 if (vm_map_debug_apple_protect) {
2063 struct proc *p;
2064 p = current_proc();
2065 printf("APPLE_PROTECT: %d[%s] map %p "
2066 "[0x%llx:0x%llx] %s(%s)\n",
2067 proc_getpid(p), p->p_comm, map,
2068 (uint64_t) map_addr,
2069 (uint64_t) (map_addr + map_size),
2070 __FUNCTION__, vp->v_name);
2071 }
2072 #endif /* VM_MAP_DEBUG_APPLE_PROTECT */
2073
2074 /* The DSMOS pager can only be used by apple signed code */
2075 struct cs_blob * blob = csvnode_get_blob(vp, file_off);
2076 if (blob == NULL || !blob->csb_platform_binary || blob->csb_platform_path) {
2077 return LOAD_FAILURE;
2078 }
2079
2080 kr = vm_map_apple_protected(map,
2081 map_addr,
2082 map_addr + map_size,
2083 crypto_backing_offset,
2084 &crypt_info,
2085 CRYPTID_APP_ENCRYPTION);
2086 }
2087
2088 if (kr != KERN_SUCCESS) {
2089 return LOAD_FAILURE;
2090 }
2091 return LOAD_SUCCESS;
2092 }
2093 #else /* CONFIG_CODE_DECRYPTION */
2094 static load_return_t
unprotect_dsmos_segment(__unused uint64_t file_off,__unused uint64_t file_size,__unused struct vnode * vp,__unused off_t macho_offset,__unused vm_map_t map,__unused vm_map_offset_t map_addr,__unused vm_map_size_t map_size)2095 unprotect_dsmos_segment(
2096 __unused uint64_t file_off,
2097 __unused uint64_t file_size,
2098 __unused struct vnode *vp,
2099 __unused off_t macho_offset,
2100 __unused vm_map_t map,
2101 __unused vm_map_offset_t map_addr,
2102 __unused vm_map_size_t map_size)
2103 {
2104 return LOAD_SUCCESS;
2105 }
2106 #endif /* CONFIG_CODE_DECRYPTION */
2107
2108
2109 /*
2110 * map_segment:
2111 * Maps a Mach-O segment.
2112 */
2113 static kern_return_t
map_segment(vm_map_t map,vm_map_offset_t vm_start,vm_map_offset_t vm_end,vm_map_kernel_flags_t vmk_flags,memory_object_control_t control,vm_map_offset_t file_start,vm_map_offset_t file_end,vm_prot_t initprot,vm_prot_t maxprot,load_result_t * result)2114 map_segment(
2115 vm_map_t map,
2116 vm_map_offset_t vm_start,
2117 vm_map_offset_t vm_end,
2118 vm_map_kernel_flags_t vmk_flags,
2119 memory_object_control_t control,
2120 vm_map_offset_t file_start,
2121 vm_map_offset_t file_end,
2122 vm_prot_t initprot,
2123 vm_prot_t maxprot,
2124 load_result_t *result)
2125 {
2126 kern_return_t ret;
2127 vm_map_offset_t effective_page_mask;
2128
2129 if (vm_end < vm_start ||
2130 file_end < file_start) {
2131 return LOAD_BADMACHO;
2132 }
2133 if (vm_end == vm_start ||
2134 file_end == file_start) {
2135 /* nothing to map... */
2136 return LOAD_SUCCESS;
2137 }
2138
2139 effective_page_mask = vm_map_page_mask(map);
2140
2141 if (vm_map_page_aligned(vm_start, effective_page_mask) &&
2142 vm_map_page_aligned(vm_end, effective_page_mask) &&
2143 vm_map_page_aligned(file_start, effective_page_mask) &&
2144 vm_map_page_aligned(file_end, effective_page_mask)) {
2145 /* all page-aligned and map-aligned: proceed */
2146 } else {
2147 /*
2148 * There's no more fourk_pager to handle mis-alignments;
2149 * all binaries should be page-aligned and map-aligned
2150 */
2151 return LOAD_BADMACHO;
2152 }
2153
2154 #if !defined(XNU_TARGET_OS_OSX)
2155 (void) result;
2156 #else /* !defined(XNU_TARGET_OS_OSX) */
2157 /*
2158 * This process doesn't have its new csflags (from
2159 * the image being loaded) yet, so tell VM to override the
2160 * current process's CS_ENFORCEMENT for this mapping.
2161 */
2162 if (result->csflags & CS_ENFORCEMENT) {
2163 vmk_flags.vmkf_cs_enforcement = TRUE;
2164 } else {
2165 vmk_flags.vmkf_cs_enforcement = FALSE;
2166 }
2167 vmk_flags.vmkf_cs_enforcement_override = TRUE;
2168 #endif /* !defined(XNU_TARGET_OS_OSX) */
2169
2170 if (result->is_rosetta && (initprot & VM_PROT_EXECUTE) == VM_PROT_EXECUTE) {
2171 vmk_flags.vmkf_translated_allow_execute = TRUE;
2172 }
2173
2174 if (control != MEMORY_OBJECT_CONTROL_NULL) {
2175 /* no copy-on-read for mapped binaries */
2176 vmk_flags.vmkf_no_copy_on_read = 1;
2177 ret = vm_map_enter_mem_object_control(
2178 map,
2179 &vm_start,
2180 file_end - file_start,
2181 (mach_vm_offset_t)0,
2182 vmk_flags,
2183 control,
2184 file_start,
2185 TRUE, /* copy */
2186 initprot, maxprot,
2187 VM_INHERIT_DEFAULT);
2188 } else {
2189 ret = mach_vm_map_kernel(
2190 map,
2191 &vm_start,
2192 file_end - file_start,
2193 (mach_vm_offset_t)0,
2194 vmk_flags,
2195 IPC_PORT_NULL,
2196 0, /* offset */
2197 TRUE, /* copy */
2198 initprot, maxprot,
2199 VM_INHERIT_DEFAULT);
2200 }
2201 if (ret != KERN_SUCCESS) {
2202 return LOAD_NOSPACE;
2203 }
2204 return LOAD_SUCCESS;
2205 }
2206
2207 static
2208 load_return_t
load_segment(struct load_command * lcp,uint32_t filetype,void * control,off_t pager_offset,off_t macho_size,struct vnode * vp,vm_map_t map,int64_t slide,load_result_t * result,struct image_params * imgp)2209 load_segment(
2210 struct load_command *lcp,
2211 uint32_t filetype,
2212 void * control,
2213 off_t pager_offset,
2214 off_t macho_size,
2215 struct vnode *vp,
2216 vm_map_t map,
2217 int64_t slide,
2218 load_result_t *result,
2219 struct image_params *imgp)
2220 {
2221 struct segment_command_64 segment_command, *scp;
2222 kern_return_t ret;
2223 vm_map_size_t delta_size;
2224 vm_prot_t initprot;
2225 vm_prot_t maxprot;
2226 size_t segment_command_size, total_section_size,
2227 single_section_size;
2228 uint64_t file_offset, file_size;
2229 vm_map_offset_t vm_offset;
2230 size_t vm_size;
2231 vm_map_offset_t vm_start, vm_end, vm_end_aligned;
2232 vm_map_offset_t file_start, file_end;
2233 vm_map_kernel_flags_t vmk_flags;
2234 kern_return_t kr;
2235 boolean_t verbose;
2236 vm_map_size_t effective_page_size;
2237 vm_map_offset_t effective_page_mask;
2238 #if __arm64__
2239 boolean_t fourk_align;
2240 #endif /* __arm64__ */
2241
2242 (void)imgp;
2243
2244 effective_page_size = vm_map_page_size(map);
2245 effective_page_mask = vm_map_page_mask(map);
2246 vmk_flags = VM_MAP_KERNEL_FLAGS_FIXED();
2247
2248 verbose = FALSE;
2249 if (LC_SEGMENT_64 == lcp->cmd) {
2250 segment_command_size = sizeof(struct segment_command_64);
2251 single_section_size = sizeof(struct section_64);
2252 #if __arm64__
2253 /* 64-bit binary: should already be 16K-aligned */
2254 fourk_align = FALSE;
2255
2256 if (vm_map_page_shift(map) == FOURK_PAGE_SHIFT &&
2257 PAGE_SHIFT != FOURK_PAGE_SHIFT) {
2258 fourk_align = TRUE;
2259 verbose = TRUE;
2260 }
2261 #endif /* __arm64__ */
2262 } else {
2263 segment_command_size = sizeof(struct segment_command);
2264 single_section_size = sizeof(struct section);
2265 #if __arm64__
2266 /* 32-bit binary or arm64_32 binary: should already be page-aligned */
2267 fourk_align = FALSE;
2268 #endif /* __arm64__ */
2269 }
2270 if (lcp->cmdsize < segment_command_size) {
2271 DEBUG4K_ERROR("LOAD_BADMACHO cmdsize %d < %zu\n", lcp->cmdsize, segment_command_size);
2272 return LOAD_BADMACHO;
2273 }
2274 total_section_size = lcp->cmdsize - segment_command_size;
2275
2276 if (LC_SEGMENT_64 == lcp->cmd) {
2277 scp = (struct segment_command_64 *)lcp;
2278 } else {
2279 scp = &segment_command;
2280 widen_segment_command((struct segment_command *)lcp, scp);
2281 }
2282
2283 if (verbose) {
2284 MACHO_PRINTF(("+++ load_segment %s "
2285 "vm[0x%llx:0x%llx] file[0x%llx:0x%llx] "
2286 "prot %d/%d flags 0x%x\n",
2287 scp->segname,
2288 (uint64_t)(slide + scp->vmaddr),
2289 (uint64_t)(slide + scp->vmaddr + scp->vmsize),
2290 pager_offset + scp->fileoff,
2291 pager_offset + scp->fileoff + scp->filesize,
2292 scp->initprot,
2293 scp->maxprot,
2294 scp->flags));
2295 }
2296
2297 /*
2298 * Make sure what we get from the file is really ours (as specified
2299 * by macho_size).
2300 */
2301 if (scp->fileoff + scp->filesize < scp->fileoff ||
2302 scp->fileoff + scp->filesize > (uint64_t)macho_size) {
2303 DEBUG4K_ERROR("LOAD_BADMACHO fileoff 0x%llx filesize 0x%llx macho_size 0x%llx\n", scp->fileoff, scp->filesize, (uint64_t)macho_size);
2304 return LOAD_BADMACHO;
2305 }
2306 /*
2307 * Ensure that the number of sections specified would fit
2308 * within the load command size.
2309 */
2310 if (total_section_size / single_section_size < scp->nsects) {
2311 DEBUG4K_ERROR("LOAD_BADMACHO 0x%zx 0x%zx %d\n", total_section_size, single_section_size, scp->nsects);
2312 return LOAD_BADMACHO;
2313 }
2314 /*
2315 * Make sure the segment is page-aligned in the file.
2316 */
2317 if (os_add_overflow(pager_offset, scp->fileoff, &file_offset)) {
2318 DEBUG4K_ERROR("LOAD_BADMACHO file_offset: 0x%llx + 0x%llx\n", pager_offset, scp->fileoff);
2319 return LOAD_BADMACHO;
2320 }
2321 file_size = scp->filesize;
2322 #if __arm64__
2323 if (fourk_align) {
2324 if ((file_offset & FOURK_PAGE_MASK) != 0) {
2325 /*
2326 * we can't mmap() it if it's not at least 4KB-aligned
2327 * in the file
2328 */
2329 DEBUG4K_ERROR("LOAD_BADMACHO file_offset 0x%llx\n", file_offset);
2330 return LOAD_BADMACHO;
2331 }
2332 } else
2333 #endif /* __arm64__ */
2334 if ((file_offset & PAGE_MASK_64) != 0 ||
2335 /* we can't mmap() it if it's not page-aligned in the file */
2336 (file_offset & vm_map_page_mask(map)) != 0) {
2337 /*
2338 * The 1st test would have failed if the system's page size
2339 * was what this process believe is the page size, so let's
2340 * fail here too for the sake of consistency.
2341 */
2342 DEBUG4K_ERROR("LOAD_BADMACHO file_offset 0x%llx\n", file_offset);
2343 return LOAD_BADMACHO;
2344 }
2345
2346 /*
2347 * If we have a code signature attached for this slice
2348 * require that the segments are within the signed part
2349 * of the file.
2350 */
2351 if (result->cs_end_offset &&
2352 result->cs_end_offset < (off_t)scp->fileoff &&
2353 result->cs_end_offset - scp->fileoff < scp->filesize) {
2354 if (cs_debug) {
2355 printf("section outside code signature\n");
2356 }
2357 DEBUG4K_ERROR("LOAD_BADMACHO end_offset 0x%llx fileoff 0x%llx filesize 0x%llx\n", result->cs_end_offset, scp->fileoff, scp->filesize);
2358 return LOAD_BADMACHO;
2359 }
2360
2361 if (os_add_overflow(scp->vmaddr, slide, &vm_offset)) {
2362 if (cs_debug) {
2363 printf("vmaddr too large\n");
2364 }
2365 DEBUG4K_ERROR("LOAD_BADMACHO vmaddr 0x%llx slide 0x%llx vm_offset 0x%llx\n", scp->vmaddr, slide, (uint64_t)vm_offset);
2366 return LOAD_BADMACHO;
2367 }
2368
2369 if (scp->vmsize > SIZE_MAX) {
2370 DEBUG4K_ERROR("LOAD_BADMACHO vmsize 0x%llx\n", scp->vmsize);
2371 return LOAD_BADMACHO;
2372 }
2373
2374 vm_size = (size_t)scp->vmsize;
2375
2376 if (vm_size == 0) {
2377 return LOAD_SUCCESS;
2378 }
2379 if (scp->vmaddr == 0 &&
2380 file_size == 0 &&
2381 vm_size != 0 &&
2382 (scp->initprot & VM_PROT_ALL) == VM_PROT_NONE &&
2383 (scp->maxprot & VM_PROT_ALL) == VM_PROT_NONE) {
2384 if (map == VM_MAP_NULL) {
2385 return LOAD_SUCCESS;
2386 }
2387
2388 /*
2389 * For PIE, extend page zero rather than moving it. Extending
2390 * page zero keeps early allocations from falling predictably
2391 * between the end of page zero and the beginning of the first
2392 * slid segment.
2393 */
2394 /*
2395 * This is a "page zero" segment: it starts at address 0,
2396 * is not mapped from the binary file and is not accessible.
2397 * User-space should never be able to access that memory, so
2398 * make it completely off limits by raising the VM map's
2399 * minimum offset.
2400 */
2401 vm_end = (vm_map_offset_t)(vm_offset + vm_size);
2402 if (vm_end < vm_offset) {
2403 DEBUG4K_ERROR("LOAD_BADMACHO vm_end 0x%llx vm_offset 0x%llx vm_size 0x%llx\n", (uint64_t)vm_end, (uint64_t)vm_offset, (uint64_t)vm_size);
2404 return LOAD_BADMACHO;
2405 }
2406
2407 if (verbose) {
2408 MACHO_PRINTF(("++++++ load_segment: "
2409 "page_zero up to 0x%llx\n",
2410 (uint64_t) vm_end));
2411 }
2412 #if __arm64__
2413 if (fourk_align) {
2414 /* raise min_offset as much as page-alignment allows */
2415 vm_end_aligned = vm_map_trunc_page(vm_end,
2416 effective_page_mask);
2417 } else
2418 #endif /* __arm64__ */
2419 {
2420 vm_end = vm_map_round_page(vm_end,
2421 PAGE_MASK_64);
2422 vm_end_aligned = vm_end;
2423 }
2424 ret = vm_map_raise_min_offset(map,
2425 vm_end_aligned);
2426 if (ret != KERN_SUCCESS) {
2427 DEBUG4K_ERROR("LOAD_FAILURE ret 0x%x\n", ret);
2428 return LOAD_FAILURE;
2429 }
2430 return LOAD_SUCCESS;
2431 } else {
2432 #if !defined(XNU_TARGET_OS_OSX)
2433 /* not PAGEZERO: should not be mapped at address 0 */
2434 if (filetype != MH_DYLINKER && (imgp->ip_flags & IMGPF_ROSETTA) == 0 && scp->vmaddr == 0) {
2435 DEBUG4K_ERROR("LOAD_BADMACHO filetype %d vmaddr 0x%llx\n", filetype, scp->vmaddr);
2436 return LOAD_BADMACHO;
2437 }
2438 #endif /* !defined(XNU_TARGET_OS_OSX) */
2439 }
2440
2441 #if __arm64__
2442 if (fourk_align) {
2443 /* 4K-align */
2444 file_start = vm_map_trunc_page(file_offset,
2445 FOURK_PAGE_MASK);
2446 file_end = vm_map_round_page(file_offset + file_size,
2447 FOURK_PAGE_MASK);
2448 vm_start = vm_map_trunc_page(vm_offset,
2449 FOURK_PAGE_MASK);
2450 vm_end = vm_map_round_page(vm_offset + vm_size,
2451 FOURK_PAGE_MASK);
2452
2453 if (file_offset - file_start > FOURK_PAGE_MASK ||
2454 file_end - file_offset - file_size > FOURK_PAGE_MASK) {
2455 DEBUG4K_ERROR("LOAD_BADMACHO file_start / file_size wrap "
2456 "[0x%llx:0x%llx] -> [0x%llx:0x%llx]\n",
2457 file_offset,
2458 file_offset + file_size,
2459 (uint64_t) file_start,
2460 (uint64_t) file_end);
2461 return LOAD_BADMACHO;
2462 }
2463
2464 if (!strncmp(scp->segname, "__LINKEDIT", 11) &&
2465 page_aligned(file_start) &&
2466 vm_map_page_aligned(file_start, vm_map_page_mask(map)) &&
2467 page_aligned(vm_start) &&
2468 vm_map_page_aligned(vm_start, vm_map_page_mask(map))) {
2469 /* XXX last segment: ignore mis-aligned tail */
2470 file_end = vm_map_round_page(file_end,
2471 effective_page_mask);
2472 vm_end = vm_map_round_page(vm_end,
2473 effective_page_mask);
2474 }
2475 } else
2476 #endif /* __arm64__ */
2477 {
2478 file_start = vm_map_trunc_page(file_offset,
2479 effective_page_mask);
2480 file_end = vm_map_round_page(file_offset + file_size,
2481 effective_page_mask);
2482 vm_start = vm_map_trunc_page(vm_offset,
2483 effective_page_mask);
2484 vm_end = vm_map_round_page(vm_offset + vm_size,
2485 effective_page_mask);
2486
2487 if (file_offset - file_start > effective_page_mask ||
2488 file_end - file_offset - file_size > effective_page_mask) {
2489 DEBUG4K_ERROR("LOAD_BADMACHO file_start / file_size wrap "
2490 "[0x%llx:0x%llx] -> [0x%llx:0x%llx]\n",
2491 file_offset,
2492 file_offset + file_size,
2493 (uint64_t) file_start,
2494 (uint64_t) file_end);
2495 return LOAD_BADMACHO;
2496 }
2497 }
2498
2499 if (vm_start < result->min_vm_addr) {
2500 result->min_vm_addr = vm_start;
2501 }
2502 if (vm_end > result->max_vm_addr) {
2503 result->max_vm_addr = vm_end;
2504 }
2505
2506 if (map == VM_MAP_NULL) {
2507 return LOAD_SUCCESS;
2508 }
2509
2510 if (scp->flags & SG_READ_ONLY) {
2511 /*
2512 * Record the VM start/end of a segment which should
2513 * be RO after fixups. Only __DATA_CONST should
2514 * have this flag.
2515 */
2516 if (result->ro_vm_start != MACH_VM_MIN_ADDRESS ||
2517 result->ro_vm_end != MACH_VM_MIN_ADDRESS) {
2518 DEBUG4K_ERROR("LOAD_BADMACHO segment flags [%x] "
2519 "multiple segments with SG_READ_ONLY flag\n",
2520 scp->flags);
2521 return LOAD_BADMACHO;
2522 }
2523
2524 result->ro_vm_start = vm_start;
2525 result->ro_vm_end = vm_end;
2526 }
2527
2528 if (vm_size > 0) {
2529 #if !__x86_64__
2530 if (!strncmp(scp->segname, "__LINKEDIT", 11)) {
2531 vmk_flags.vmf_permanent = true;
2532 }
2533 #endif /* !__x86_64__ */
2534 initprot = (scp->initprot) & VM_PROT_ALL;
2535 maxprot = (scp->maxprot) & VM_PROT_ALL;
2536 /*
2537 * Map a copy of the file into the address space.
2538 */
2539 if (verbose) {
2540 MACHO_PRINTF(("++++++ load_segment: "
2541 "mapping at vm [0x%llx:0x%llx] of "
2542 "file [0x%llx:0x%llx]\n",
2543 (uint64_t) vm_start,
2544 (uint64_t) vm_end,
2545 (uint64_t) file_start,
2546 (uint64_t) file_end));
2547 }
2548 ret = map_segment(map,
2549 vm_start,
2550 vm_end,
2551 vmk_flags,
2552 control,
2553 file_start,
2554 file_end,
2555 initprot,
2556 maxprot,
2557 result);
2558 if (ret) {
2559 DEBUG4K_ERROR("LOAD_NOSPACE start 0x%llx end 0x%llx ret 0x%x\n", (uint64_t)vm_start, (uint64_t)vm_end, ret);
2560 return LOAD_NOSPACE;
2561 }
2562
2563 #if FIXME
2564 /*
2565 * If the file didn't end on a page boundary,
2566 * we need to zero the leftover.
2567 */
2568 delta_size = map_size - scp->filesize;
2569 if (delta_size > 0) {
2570 void *tmp = kalloc_data(delta_size, Z_WAITOK | Z_ZERO);
2571 int rc;
2572
2573 if (tmp == NULL) {
2574 DEBUG4K_ERROR("LOAD_RESOURCE delta_size 0x%llx ret 0x%x\n", delta_size, ret);
2575 return LOAD_RESOURCE;
2576 }
2577
2578 rc = copyout(tmp, map_addr + scp->filesize, delta_size);
2579 kfree_data(tmp, delta_size);
2580
2581 if (rc) {
2582 DEBUG4K_ERROR("LOAD_FAILURE copyout 0x%llx 0x%llx\n", map_addr + scp->filesize, delta_size);
2583 return LOAD_FAILURE;
2584 }
2585 }
2586 #endif /* FIXME */
2587 }
2588
2589 /*
2590 * If the virtual size of the segment is greater
2591 * than the size from the file, we need to allocate
2592 * zero fill memory for the rest.
2593 */
2594 if ((vm_end - vm_start) > (file_end - file_start)) {
2595 delta_size = (vm_end - vm_start) - (file_end - file_start);
2596 } else {
2597 delta_size = 0;
2598 }
2599 if (delta_size > 0) {
2600 vm_map_offset_t tmp_start;
2601 vm_map_offset_t tmp_end;
2602
2603 if (os_add_overflow(vm_start, file_end - file_start, &tmp_start)) {
2604 DEBUG4K_ERROR("LOAD_NOSPACE tmp_start: 0x%llx + 0x%llx\n", (uint64_t)vm_start, (uint64_t)(file_end - file_start));
2605 return LOAD_NOSPACE;
2606 }
2607
2608 if (os_add_overflow(tmp_start, delta_size, &tmp_end)) {
2609 DEBUG4K_ERROR("LOAD_NOSPACE tmp_end: 0x%llx + 0x%llx\n", (uint64_t)tmp_start, (uint64_t)delta_size);
2610 return LOAD_NOSPACE;
2611 }
2612
2613 if (verbose) {
2614 MACHO_PRINTF(("++++++ load_segment: "
2615 "delta mapping vm [0x%llx:0x%llx]\n",
2616 (uint64_t) tmp_start,
2617 (uint64_t) tmp_end));
2618 }
2619 kr = map_segment(map,
2620 tmp_start,
2621 tmp_end,
2622 vmk_flags,
2623 MEMORY_OBJECT_CONTROL_NULL,
2624 0,
2625 delta_size,
2626 scp->initprot,
2627 scp->maxprot,
2628 result);
2629 if (kr != KERN_SUCCESS) {
2630 DEBUG4K_ERROR("LOAD_NOSPACE 0x%llx 0x%llx kr 0x%x\n", (unsigned long long)tmp_start, (uint64_t)delta_size, kr);
2631 return LOAD_NOSPACE;
2632 }
2633 }
2634
2635 if ((scp->fileoff == 0) && (scp->filesize != 0)) {
2636 result->mach_header = vm_offset;
2637 }
2638
2639 if (scp->flags & SG_PROTECTED_VERSION_1) {
2640 ret = unprotect_dsmos_segment(file_start,
2641 file_end - file_start,
2642 vp,
2643 pager_offset,
2644 map,
2645 vm_start,
2646 vm_end - vm_start);
2647 if (ret != LOAD_SUCCESS) {
2648 DEBUG4K_ERROR("unprotect 0x%llx 0x%llx ret %d \n", (uint64_t)vm_start, (uint64_t)vm_end, ret);
2649 return ret;
2650 }
2651 } else {
2652 ret = LOAD_SUCCESS;
2653 }
2654
2655 if (LOAD_SUCCESS == ret &&
2656 filetype == MH_DYLINKER &&
2657 result->all_image_info_addr == MACH_VM_MIN_ADDRESS) {
2658 note_all_image_info_section(scp,
2659 LC_SEGMENT_64 == lcp->cmd,
2660 single_section_size,
2661 ((const char *)lcp +
2662 segment_command_size),
2663 slide,
2664 result);
2665 }
2666
2667 if (result->entry_point != MACH_VM_MIN_ADDRESS) {
2668 if ((result->entry_point >= vm_offset) && (result->entry_point < (vm_offset + vm_size))) {
2669 if ((scp->initprot & (VM_PROT_READ | VM_PROT_EXECUTE)) == (VM_PROT_READ | VM_PROT_EXECUTE)) {
2670 result->validentry = 1;
2671 } else {
2672 /* right range but wrong protections, unset if previously validated */
2673 result->validentry = 0;
2674 }
2675 }
2676 }
2677
2678 if (ret != LOAD_SUCCESS && verbose) {
2679 DEBUG4K_ERROR("ret %d\n", ret);
2680 }
2681 return ret;
2682 }
2683
2684 static
2685 load_return_t
load_uuid(struct uuid_command * uulp,char * command_end,load_result_t * result)2686 load_uuid(
2687 struct uuid_command *uulp,
2688 char *command_end,
2689 load_result_t *result
2690 )
2691 {
2692 /*
2693 * We need to check the following for this command:
2694 * - The command size should be atleast the size of struct uuid_command
2695 * - The UUID part of the command should be completely within the mach-o header
2696 */
2697
2698 if ((uulp->cmdsize < sizeof(struct uuid_command)) ||
2699 (((char *)uulp + sizeof(struct uuid_command)) > command_end)) {
2700 return LOAD_BADMACHO;
2701 }
2702
2703 memcpy(&result->uuid[0], &uulp->uuid[0], sizeof(result->uuid));
2704 return LOAD_SUCCESS;
2705 }
2706
2707 static
2708 load_return_t
load_version(struct version_min_command * vmc,boolean_t * found_version_cmd,struct image_params * imgp __unused,load_result_t * result)2709 load_version(
2710 struct version_min_command *vmc,
2711 boolean_t *found_version_cmd,
2712 struct image_params *imgp __unused,
2713 load_result_t *result
2714 )
2715 {
2716 uint32_t platform = 0;
2717 uint32_t sdk;
2718 uint32_t min_sdk;
2719
2720 if (vmc->cmdsize < sizeof(*vmc)) {
2721 return LOAD_BADMACHO;
2722 }
2723 if (*found_version_cmd == TRUE) {
2724 return LOAD_BADMACHO;
2725 }
2726 *found_version_cmd = TRUE;
2727 sdk = vmc->sdk;
2728 min_sdk = vmc->version;
2729 switch (vmc->cmd) {
2730 case LC_VERSION_MIN_MACOSX:
2731 platform = PLATFORM_MACOS;
2732 break;
2733 #if __x86_64__ /* __x86_64__ */
2734 case LC_VERSION_MIN_IPHONEOS:
2735 platform = PLATFORM_IOSSIMULATOR;
2736 break;
2737 case LC_VERSION_MIN_WATCHOS:
2738 platform = PLATFORM_WATCHOSSIMULATOR;
2739 break;
2740 case LC_VERSION_MIN_TVOS:
2741 platform = PLATFORM_TVOSSIMULATOR;
2742 break;
2743 #else
2744 case LC_VERSION_MIN_IPHONEOS: {
2745 #if __arm64__
2746 if (vmc->sdk < (12 << 16)) {
2747 /* app built with a pre-iOS12 SDK: apply legacy footprint mitigation */
2748 result->legacy_footprint = TRUE;
2749 }
2750 #endif /* __arm64__ */
2751 platform = PLATFORM_IOS;
2752 break;
2753 }
2754 case LC_VERSION_MIN_WATCHOS:
2755 platform = PLATFORM_WATCHOS;
2756 break;
2757 case LC_VERSION_MIN_TVOS:
2758 platform = PLATFORM_TVOS;
2759 break;
2760 #endif /* __x86_64__ */
2761 /* All LC_VERSION_MIN_* load commands are legacy and we will not be adding any more */
2762 default:
2763 sdk = (uint32_t)-1;
2764 min_sdk = (uint32_t)-1;
2765 __builtin_unreachable();
2766 }
2767 result->ip_platform = platform;
2768 result->lr_min_sdk = min_sdk;
2769 result->lr_sdk = sdk;
2770 return LOAD_SUCCESS;
2771 }
2772
2773 static
2774 load_return_t
load_main(struct entry_point_command * epc,thread_t thread,int64_t slide,load_result_t * result)2775 load_main(
2776 struct entry_point_command *epc,
2777 thread_t thread,
2778 int64_t slide,
2779 load_result_t *result
2780 )
2781 {
2782 mach_vm_offset_t addr;
2783 kern_return_t ret;
2784
2785 if (epc->cmdsize < sizeof(*epc)) {
2786 return LOAD_BADMACHO;
2787 }
2788 if (result->thread_count != 0) {
2789 return LOAD_FAILURE;
2790 }
2791
2792 if (thread == THREAD_NULL) {
2793 return LOAD_SUCCESS;
2794 }
2795
2796 /*
2797 * LC_MAIN specifies stack size but not location.
2798 * Add guard page to allocation size (MAXSSIZ includes guard page).
2799 */
2800 if (epc->stacksize) {
2801 if (os_add_overflow(epc->stacksize, 4 * PAGE_SIZE, &result->user_stack_size)) {
2802 /*
2803 * We are going to immediately throw away this result, but we want
2804 * to make sure we aren't loading a dangerously close to
2805 * overflowing value, since this will have a guard page added to it
2806 * and be rounded to page boundaries
2807 */
2808 return LOAD_BADMACHO;
2809 }
2810 result->user_stack_size = epc->stacksize;
2811 if (os_add_overflow(epc->stacksize, PAGE_SIZE, &result->user_stack_alloc_size)) {
2812 return LOAD_BADMACHO;
2813 }
2814 result->custom_stack = TRUE;
2815 } else {
2816 result->user_stack_alloc_size = MAXSSIZ;
2817 }
2818
2819 /* use default location for stack */
2820 ret = thread_userstackdefault(&addr, result->is_64bit_addr);
2821 if (ret != KERN_SUCCESS) {
2822 return LOAD_FAILURE;
2823 }
2824
2825 /* The stack slides down from the default location */
2826 result->user_stack = (user_addr_t)mach_vm_trunc_page((user_addr_t)addr - slide);
2827
2828 if (result->using_lcmain || result->entry_point != MACH_VM_MIN_ADDRESS) {
2829 /* Already processed LC_MAIN or LC_UNIXTHREAD */
2830 return LOAD_FAILURE;
2831 }
2832
2833 /* kernel does *not* use entryoff from LC_MAIN. Dyld uses it. */
2834 result->needs_dynlinker = TRUE;
2835 result->using_lcmain = TRUE;
2836
2837 ret = thread_state_initialize( thread );
2838 if (ret != KERN_SUCCESS) {
2839 return LOAD_FAILURE;
2840 }
2841
2842 result->unixproc = TRUE;
2843 result->thread_count++;
2844
2845 return LOAD_SUCCESS;
2846 }
2847
2848 static
2849 load_return_t
setup_driver_main(thread_t thread,int64_t slide,load_result_t * result)2850 setup_driver_main(
2851 thread_t thread,
2852 int64_t slide,
2853 load_result_t *result
2854 )
2855 {
2856 mach_vm_offset_t addr;
2857 kern_return_t ret;
2858
2859 /* Driver binaries have no LC_MAIN, use defaults */
2860
2861 if (thread == THREAD_NULL) {
2862 return LOAD_SUCCESS;
2863 }
2864
2865 result->user_stack_alloc_size = MAXSSIZ;
2866
2867 /* use default location for stack */
2868 ret = thread_userstackdefault(&addr, result->is_64bit_addr);
2869 if (ret != KERN_SUCCESS) {
2870 return LOAD_FAILURE;
2871 }
2872
2873 /* The stack slides down from the default location */
2874 result->user_stack = (user_addr_t)addr;
2875 result->user_stack -= slide;
2876
2877 if (result->using_lcmain || result->entry_point != MACH_VM_MIN_ADDRESS) {
2878 /* Already processed LC_MAIN or LC_UNIXTHREAD */
2879 return LOAD_FAILURE;
2880 }
2881
2882 result->needs_dynlinker = TRUE;
2883
2884 ret = thread_state_initialize( thread );
2885 if (ret != KERN_SUCCESS) {
2886 return LOAD_FAILURE;
2887 }
2888
2889 result->unixproc = TRUE;
2890 result->thread_count++;
2891
2892 return LOAD_SUCCESS;
2893 }
2894
2895 static
2896 load_return_t
load_unixthread(struct thread_command * tcp,thread_t thread,int64_t slide,boolean_t is_x86_64_compat_binary,load_result_t * result)2897 load_unixthread(
2898 struct thread_command *tcp,
2899 thread_t thread,
2900 int64_t slide,
2901 boolean_t is_x86_64_compat_binary,
2902 load_result_t *result
2903 )
2904 {
2905 load_return_t ret;
2906 int customstack = 0;
2907 mach_vm_offset_t addr;
2908 if (tcp->cmdsize < sizeof(*tcp)) {
2909 return LOAD_BADMACHO;
2910 }
2911 if (result->thread_count != 0) {
2912 return LOAD_FAILURE;
2913 }
2914
2915 if (thread == THREAD_NULL) {
2916 return LOAD_SUCCESS;
2917 }
2918
2919 ret = load_threadstack(thread,
2920 (uint32_t *)(((vm_offset_t)tcp) +
2921 sizeof(struct thread_command)),
2922 tcp->cmdsize - sizeof(struct thread_command),
2923 &addr, &customstack, is_x86_64_compat_binary, result);
2924 if (ret != LOAD_SUCCESS) {
2925 return ret;
2926 }
2927
2928 /* LC_UNIXTHREAD optionally specifies stack size and location */
2929
2930 if (customstack) {
2931 result->custom_stack = TRUE;
2932 } else {
2933 result->user_stack_alloc_size = MAXSSIZ;
2934 }
2935
2936 /* The stack slides down from the default location */
2937 result->user_stack = (user_addr_t)mach_vm_trunc_page((user_addr_t)addr - slide);
2938
2939 {
2940 ret = load_threadentry(thread,
2941 (uint32_t *)(((vm_offset_t)tcp) +
2942 sizeof(struct thread_command)),
2943 tcp->cmdsize - sizeof(struct thread_command),
2944 &addr);
2945 if (ret != LOAD_SUCCESS) {
2946 return ret;
2947 }
2948
2949 if (result->using_lcmain || result->entry_point != MACH_VM_MIN_ADDRESS) {
2950 /* Already processed LC_MAIN or LC_UNIXTHREAD */
2951 return LOAD_FAILURE;
2952 }
2953
2954 result->entry_point = (user_addr_t)addr;
2955 result->entry_point += slide;
2956
2957 ret = load_threadstate(thread,
2958 (uint32_t *)(((vm_offset_t)tcp) + sizeof(struct thread_command)),
2959 tcp->cmdsize - sizeof(struct thread_command),
2960 result);
2961 if (ret != LOAD_SUCCESS) {
2962 return ret;
2963 }
2964 }
2965
2966 result->unixproc = TRUE;
2967 result->thread_count++;
2968
2969 return LOAD_SUCCESS;
2970 }
2971
2972 static
2973 load_return_t
load_threadstate(thread_t thread,uint32_t * ts,uint32_t total_size,load_result_t * result)2974 load_threadstate(
2975 thread_t thread,
2976 uint32_t *ts,
2977 uint32_t total_size,
2978 load_result_t *result
2979 )
2980 {
2981 uint32_t size;
2982 int flavor;
2983 uint32_t thread_size;
2984 uint32_t *local_ts = NULL;
2985 uint32_t local_ts_size = 0;
2986 int ret;
2987
2988 (void)thread;
2989
2990 if (total_size > 0) {
2991 local_ts_size = total_size;
2992 local_ts = (uint32_t *)kalloc_data(local_ts_size, Z_WAITOK);
2993 if (local_ts == NULL) {
2994 return LOAD_FAILURE;
2995 }
2996 memcpy(local_ts, ts, local_ts_size);
2997 ts = local_ts;
2998 }
2999
3000 /*
3001 * Validate the new thread state; iterate through the state flavors in
3002 * the Mach-O file.
3003 * XXX: we should validate the machine state here, to avoid failing at
3004 * activation time where we can't bail out cleanly.
3005 */
3006 while (total_size > 0) {
3007 if (total_size < 2 * sizeof(uint32_t)) {
3008 return LOAD_BADMACHO;
3009 }
3010
3011 flavor = *ts++;
3012 size = *ts++;
3013
3014 if (os_add_and_mul_overflow(size, 2, sizeof(uint32_t), &thread_size) ||
3015 os_sub_overflow(total_size, thread_size, &total_size)) {
3016 ret = LOAD_BADMACHO;
3017 goto bad;
3018 }
3019
3020 ts += size; /* ts is a (uint32_t *) */
3021 }
3022
3023 result->threadstate = local_ts;
3024 result->threadstate_sz = local_ts_size;
3025 return LOAD_SUCCESS;
3026
3027 bad:
3028 if (local_ts) {
3029 kfree_data(local_ts, local_ts_size);
3030 }
3031 return ret;
3032 }
3033
3034
3035 static
3036 load_return_t
load_threadstack(thread_t thread,uint32_t * ts,uint32_t total_size,mach_vm_offset_t * user_stack,int * customstack,__unused boolean_t is_x86_64_compat_binary,load_result_t * result)3037 load_threadstack(
3038 thread_t thread,
3039 uint32_t *ts,
3040 uint32_t total_size,
3041 mach_vm_offset_t *user_stack,
3042 int *customstack,
3043 __unused boolean_t is_x86_64_compat_binary,
3044 load_result_t *result
3045 )
3046 {
3047 kern_return_t ret;
3048 uint32_t size;
3049 int flavor;
3050 uint32_t stack_size;
3051
3052 if (total_size == 0) {
3053 return LOAD_BADMACHO;
3054 }
3055
3056 while (total_size > 0) {
3057 if (total_size < 2 * sizeof(uint32_t)) {
3058 return LOAD_BADMACHO;
3059 }
3060
3061 flavor = *ts++;
3062 size = *ts++;
3063 if (UINT32_MAX - 2 < size ||
3064 UINT32_MAX / sizeof(uint32_t) < size + 2) {
3065 return LOAD_BADMACHO;
3066 }
3067 stack_size = (size + 2) * sizeof(uint32_t);
3068 if (stack_size > total_size) {
3069 return LOAD_BADMACHO;
3070 }
3071 total_size -= stack_size;
3072
3073 /*
3074 * Third argument is a kernel space pointer; it gets cast
3075 * to the appropriate type in thread_userstack() based on
3076 * the value of flavor.
3077 */
3078 {
3079 ret = thread_userstack(thread, flavor, (thread_state_t)ts, size, user_stack, customstack, result->is_64bit_data);
3080 if (ret != KERN_SUCCESS) {
3081 return LOAD_FAILURE;
3082 }
3083 }
3084
3085 ts += size; /* ts is a (uint32_t *) */
3086 }
3087 return LOAD_SUCCESS;
3088 }
3089
3090 static
3091 load_return_t
load_threadentry(thread_t thread,uint32_t * ts,uint32_t total_size,mach_vm_offset_t * entry_point)3092 load_threadentry(
3093 thread_t thread,
3094 uint32_t *ts,
3095 uint32_t total_size,
3096 mach_vm_offset_t *entry_point
3097 )
3098 {
3099 kern_return_t ret;
3100 uint32_t size;
3101 int flavor;
3102 uint32_t entry_size;
3103
3104 /*
3105 * Set the thread state.
3106 */
3107 *entry_point = MACH_VM_MIN_ADDRESS;
3108 while (total_size > 0) {
3109 if (total_size < 2 * sizeof(uint32_t)) {
3110 return LOAD_BADMACHO;
3111 }
3112
3113 flavor = *ts++;
3114 size = *ts++;
3115 if (UINT32_MAX - 2 < size ||
3116 UINT32_MAX / sizeof(uint32_t) < size + 2) {
3117 return LOAD_BADMACHO;
3118 }
3119 entry_size = (size + 2) * sizeof(uint32_t);
3120 if (entry_size > total_size) {
3121 return LOAD_BADMACHO;
3122 }
3123 total_size -= entry_size;
3124 /*
3125 * Third argument is a kernel space pointer; it gets cast
3126 * to the appropriate type in thread_entrypoint() based on
3127 * the value of flavor.
3128 */
3129 ret = thread_entrypoint(thread, flavor, (thread_state_t)ts, size, entry_point);
3130 if (ret != KERN_SUCCESS) {
3131 return LOAD_FAILURE;
3132 }
3133 ts += size; /* ts is a (uint32_t *) */
3134 }
3135 return LOAD_SUCCESS;
3136 }
3137
3138 struct macho_data {
3139 struct nameidata __nid;
3140 union macho_vnode_header {
3141 struct mach_header mach_header;
3142 struct fat_header fat_header;
3143 char __pad[512];
3144 } __header;
3145 };
3146
3147 #define DEFAULT_DYLD_PATH "/usr/lib/dyld"
3148
3149 #if (DEVELOPMENT || DEBUG)
3150 extern char dyld_alt_path[];
3151 extern int use_alt_dyld;
3152
3153 extern char dyld_suffix[];
3154 extern int use_dyld_suffix;
3155
3156 typedef struct _dyld_suffix_map_entry {
3157 const char *suffix;
3158 const char *path;
3159 } dyld_suffix_map_entry_t;
3160
3161 static const dyld_suffix_map_entry_t _dyld_suffix_map[] = {
3162 [0] = {
3163 .suffix = "",
3164 .path = DEFAULT_DYLD_PATH,
3165 }, {
3166 .suffix = "release",
3167 .path = DEFAULT_DYLD_PATH,
3168 }, {
3169 .suffix = "bringup",
3170 .path = "/usr/appleinternal/lib/dyld.bringup",
3171 },
3172 };
3173 #endif
3174
3175 static load_return_t
load_dylinker(struct dylinker_command * lcp,cpu_type_t cputype,vm_map_t map,thread_t thread,int depth,int64_t slide,load_result_t * result,struct image_params * imgp)3176 load_dylinker(
3177 struct dylinker_command *lcp,
3178 cpu_type_t cputype,
3179 vm_map_t map,
3180 thread_t thread,
3181 int depth,
3182 int64_t slide,
3183 load_result_t *result,
3184 struct image_params *imgp
3185 )
3186 {
3187 const char *name;
3188 struct vnode *vp = NULLVP; /* set by get_macho_vnode() */
3189 struct mach_header *header;
3190 off_t file_offset = 0; /* set by get_macho_vnode() */
3191 off_t macho_size = 0; /* set by get_macho_vnode() */
3192 load_result_t *myresult;
3193 kern_return_t ret;
3194 struct macho_data *macho_data;
3195 struct {
3196 struct mach_header __header;
3197 load_result_t __myresult;
3198 struct macho_data __macho_data;
3199 } *dyld_data;
3200
3201 if (lcp->cmdsize < sizeof(*lcp) || lcp->name.offset >= lcp->cmdsize) {
3202 return LOAD_BADMACHO;
3203 }
3204
3205 name = (const char *)lcp + lcp->name.offset;
3206
3207 /* Check for a proper null terminated string. */
3208 size_t maxsz = lcp->cmdsize - lcp->name.offset;
3209 size_t namelen = strnlen(name, maxsz);
3210 if (namelen >= maxsz) {
3211 return LOAD_BADMACHO;
3212 }
3213
3214 #if (DEVELOPMENT || DEBUG)
3215
3216 /*
3217 * rdar://23680808
3218 * If an alternate dyld has been specified via boot args, check
3219 * to see if PROC_UUID_ALT_DYLD_POLICY has been set on this
3220 * executable and redirect the kernel to load that linker.
3221 */
3222
3223 if (use_alt_dyld) {
3224 int policy_error;
3225 uint32_t policy_flags = 0;
3226 int32_t policy_gencount = 0;
3227
3228 policy_error = proc_uuid_policy_lookup(result->uuid, &policy_flags, &policy_gencount);
3229 if (policy_error == 0) {
3230 if (policy_flags & PROC_UUID_ALT_DYLD_POLICY) {
3231 name = dyld_alt_path;
3232 }
3233 }
3234 } else if (use_dyld_suffix) {
3235 size_t i = 0;
3236
3237 #define countof(x) (sizeof(x) / sizeof(x[0]))
3238 for (i = 0; i < countof(_dyld_suffix_map); i++) {
3239 const dyld_suffix_map_entry_t *entry = &_dyld_suffix_map[i];
3240
3241 if (strcmp(entry->suffix, dyld_suffix) == 0) {
3242 name = entry->path;
3243 break;
3244 }
3245 }
3246 }
3247 #endif
3248
3249 #if !(DEVELOPMENT || DEBUG)
3250 if (0 != strcmp(name, DEFAULT_DYLD_PATH)) {
3251 return LOAD_BADMACHO;
3252 }
3253 #endif
3254
3255 /* Allocate wad-of-data from heap to reduce excessively deep stacks */
3256
3257 dyld_data = kalloc_type(typeof(*dyld_data), Z_WAITOK);
3258 header = &dyld_data->__header;
3259 myresult = &dyld_data->__myresult;
3260 macho_data = &dyld_data->__macho_data;
3261
3262 {
3263 cputype = (cputype & CPU_ARCH_MASK) | (cpu_type() & ~CPU_ARCH_MASK);
3264 }
3265
3266 ret = get_macho_vnode(name, cputype, header,
3267 &file_offset, &macho_size, macho_data, &vp, imgp);
3268 if (ret) {
3269 goto novp_out;
3270 }
3271
3272 *myresult = load_result_null;
3273 myresult->is_64bit_addr = result->is_64bit_addr;
3274 myresult->is_64bit_data = result->is_64bit_data;
3275
3276 ret = parse_machfile(vp, map, thread, header, file_offset,
3277 macho_size, depth, slide, 0, myresult, result, imgp);
3278
3279 if (ret == LOAD_SUCCESS) {
3280 if (result->threadstate) {
3281 /* don't use the app's threadstate if we have a dyld */
3282 kfree_data(result->threadstate, result->threadstate_sz);
3283 }
3284 result->threadstate = myresult->threadstate;
3285 result->threadstate_sz = myresult->threadstate_sz;
3286
3287 result->dynlinker = TRUE;
3288 result->entry_point = myresult->entry_point;
3289 result->validentry = myresult->validentry;
3290 result->all_image_info_addr = myresult->all_image_info_addr;
3291 result->all_image_info_size = myresult->all_image_info_size;
3292 if (!myresult->platform_binary) {
3293 result->csflags &= ~CS_NO_UNTRUSTED_HELPERS;
3294 }
3295
3296 #if CONFIG_ROSETTA
3297 if (imgp->ip_flags & IMGPF_ROSETTA) {
3298 extern const struct fileops vnops;
3299 // Save the file descriptor and mach header address for dyld. These will
3300 // be passed on the stack for the Rosetta runtime's use.
3301 struct fileproc *fp;
3302 int dyld_fd;
3303 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
3304 int error = falloc_exec(p, imgp->ip_vfs_context, &fp, &dyld_fd);
3305 if (error == 0) {
3306 error = VNOP_OPEN(vp, FREAD, imgp->ip_vfs_context);
3307 if (error == 0) {
3308 fp->fp_glob->fg_flag = FREAD;
3309 fp->fp_glob->fg_ops = &vnops;
3310 fp_set_data(fp, vp);
3311
3312 proc_fdlock(p);
3313 procfdtbl_releasefd(p, dyld_fd, NULL);
3314 fp_drop(p, dyld_fd, fp, 1);
3315 proc_fdunlock(p);
3316
3317 vnode_ref(vp);
3318
3319 result->dynlinker_fd = dyld_fd;
3320 result->dynlinker_fp = fp;
3321 result->dynlinker_mach_header = myresult->mach_header;
3322 result->dynlinker_max_vm_addr = myresult->max_vm_addr;
3323 result->dynlinker_ro_vm_start = myresult->ro_vm_start;
3324 result->dynlinker_ro_vm_end = myresult->ro_vm_end;
3325 } else {
3326 fp_free(p, dyld_fd, fp);
3327 ret = LOAD_IOERROR;
3328 }
3329 } else {
3330 ret = LOAD_IOERROR;
3331 }
3332 }
3333 #endif
3334 }
3335
3336 struct vnode_attr *va;
3337 va = kalloc_type(struct vnode_attr, Z_WAITOK | Z_ZERO);
3338 VATTR_INIT(va);
3339 VATTR_WANTED(va, va_fsid64);
3340 VATTR_WANTED(va, va_fsid);
3341 VATTR_WANTED(va, va_fileid);
3342 int error = vnode_getattr(vp, va, imgp->ip_vfs_context);
3343 if (error == 0) {
3344 imgp->ip_dyld_fsid = vnode_get_va_fsid(va);
3345 imgp->ip_dyld_fsobjid = va->va_fileid;
3346 }
3347
3348 vnode_put(vp);
3349 kfree_type(struct vnode_attr, va);
3350 novp_out:
3351 kfree_type(typeof(*dyld_data), dyld_data);
3352 return ret;
3353 }
3354
3355 #if CONFIG_ROSETTA
3356 static const char* rosetta_runtime_path = "/usr/libexec/rosetta/runtime";
3357
3358 #if (DEVELOPMENT || DEBUG)
3359 static const char* rosetta_runtime_path_alt_x86 = "/usr/local/libexec/rosetta/runtime_internal";
3360 static const char* rosetta_runtime_path_alt_arm = "/usr/local/libexec/rosetta/runtime_arm_internal";
3361 #endif
3362
3363 static load_return_t
load_rosetta(vm_map_t map,thread_t thread,load_result_t * result,struct image_params * imgp)3364 load_rosetta(
3365 vm_map_t map,
3366 thread_t thread,
3367 load_result_t *result,
3368 struct image_params *imgp)
3369 {
3370 struct vnode *vp = NULLVP; /* set by get_macho_vnode() */
3371 struct mach_header *header;
3372 off_t file_offset = 0; /* set by get_macho_vnode() */
3373 off_t macho_size = 0; /* set by get_macho_vnode() */
3374 load_result_t *myresult;
3375 kern_return_t ret;
3376 struct macho_data *macho_data;
3377 const char *rosetta_file_path;
3378 struct {
3379 struct mach_header __header;
3380 load_result_t __myresult;
3381 struct macho_data __macho_data;
3382 } *rosetta_data;
3383 mach_vm_address_t rosetta_load_addr;
3384 mach_vm_size_t rosetta_size;
3385 mach_vm_address_t shared_cache_base = SHARED_REGION_BASE_ARM64;
3386 int64_t slide = 0;
3387
3388 /* Allocate wad-of-data from heap to reduce excessively deep stacks */
3389 rosetta_data = kalloc_type(typeof(*rosetta_data), Z_WAITOK | Z_NOFAIL);
3390 header = &rosetta_data->__header;
3391 myresult = &rosetta_data->__myresult;
3392 macho_data = &rosetta_data->__macho_data;
3393
3394 rosetta_file_path = rosetta_runtime_path;
3395
3396 #if (DEVELOPMENT || DEBUG)
3397 bool use_alt_rosetta = false;
3398 if (imgp->ip_flags & IMGPF_ALT_ROSETTA) {
3399 use_alt_rosetta = true;
3400 } else {
3401 int policy_error;
3402 uint32_t policy_flags = 0;
3403 int32_t policy_gencount = 0;
3404 policy_error = proc_uuid_policy_lookup(result->uuid, &policy_flags, &policy_gencount);
3405 if (policy_error == 0 && (policy_flags & PROC_UUID_ALT_ROSETTA_POLICY) != 0) {
3406 use_alt_rosetta = true;
3407 }
3408 }
3409
3410 if (use_alt_rosetta) {
3411 if (imgp->ip_origcputype == CPU_TYPE_X86_64) {
3412 rosetta_file_path = rosetta_runtime_path_alt_x86;
3413 } else if (imgp->ip_origcputype == CPU_TYPE_ARM64) {
3414 rosetta_file_path = rosetta_runtime_path_alt_arm;
3415 } else {
3416 ret = LOAD_BADARCH;
3417 goto novp_out;
3418 }
3419 }
3420 #endif
3421
3422 ret = get_macho_vnode(rosetta_file_path, CPU_TYPE_ARM64, header,
3423 &file_offset, &macho_size, macho_data, &vp, imgp);
3424 if (ret) {
3425 goto novp_out;
3426 }
3427
3428 *myresult = load_result_null;
3429 myresult->is_64bit_addr = TRUE;
3430 myresult->is_64bit_data = TRUE;
3431
3432 ret = parse_machfile(vp, NULL, NULL, header, file_offset, macho_size,
3433 2, 0, 0, myresult, NULL, imgp);
3434 if (ret != LOAD_SUCCESS) {
3435 goto out;
3436 }
3437
3438 if (!(imgp->ip_flags & IMGPF_DISABLE_ASLR)) {
3439 slide = random();
3440 slide = (slide % (vm_map_get_max_loader_aslr_slide_pages(map) - 1)) + 1;
3441 slide <<= vm_map_page_shift(map);
3442 }
3443
3444 if (imgp->ip_origcputype == CPU_TYPE_X86_64) {
3445 shared_cache_base = SHARED_REGION_BASE_X86_64;
3446 }
3447
3448 rosetta_size = round_page(myresult->max_vm_addr - myresult->min_vm_addr);
3449 rosetta_load_addr = shared_cache_base - rosetta_size - slide;
3450
3451 *myresult = load_result_null;
3452 myresult->is_64bit_addr = TRUE;
3453 myresult->is_64bit_data = TRUE;
3454 myresult->is_rosetta = TRUE;
3455
3456 ret = parse_machfile(vp, map, thread, header, file_offset, macho_size,
3457 2, rosetta_load_addr, 0, myresult, result, imgp);
3458 if (ret == LOAD_SUCCESS) {
3459 if (result) {
3460 if (result->threadstate) {
3461 /* don't use the app's/dyld's threadstate */
3462 kfree_data(result->threadstate, result->threadstate_sz);
3463 }
3464 assert(myresult->threadstate != NULL);
3465
3466 result->is_rosetta = TRUE;
3467
3468 result->threadstate = myresult->threadstate;
3469 result->threadstate_sz = myresult->threadstate_sz;
3470
3471 result->entry_point = myresult->entry_point;
3472 result->validentry = myresult->validentry;
3473 if (!myresult->platform_binary) {
3474 result->csflags &= ~CS_NO_UNTRUSTED_HELPERS;
3475 }
3476
3477 if ((header->cpusubtype & ~CPU_SUBTYPE_MASK) != CPU_SUBTYPE_ARM64E) {
3478 imgp->ip_flags |= IMGPF_NOJOP;
3479 }
3480 }
3481 }
3482
3483 out:
3484 vnode_put(vp);
3485 novp_out:
3486 kfree_type(typeof(*rosetta_data), rosetta_data);
3487 return ret;
3488 }
3489 #endif
3490
3491 static void
set_signature_error(struct vnode * vp,struct image_params * imgp,const char * fatal_failure_desc,const size_t fatal_failure_desc_len)3492 set_signature_error(
3493 struct vnode* vp,
3494 struct image_params * imgp,
3495 const char* fatal_failure_desc,
3496 const size_t fatal_failure_desc_len)
3497 {
3498 char *vn_path = NULL;
3499 vm_size_t vn_pathlen = MAXPATHLEN;
3500 char const *path = NULL;
3501
3502 vn_path = zalloc(ZV_NAMEI);
3503 if (vn_getpath(vp, vn_path, (int*)&vn_pathlen) == 0) {
3504 path = vn_path;
3505 } else {
3506 path = "(get vnode path failed)";
3507 }
3508 os_reason_t reason = os_reason_create(OS_REASON_CODESIGNING,
3509 CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG);
3510
3511 if (reason == OS_REASON_NULL) {
3512 printf("load_code_signature: %s: failure to allocate exit reason for validation failure: %s\n",
3513 path, fatal_failure_desc);
3514 goto out;
3515 }
3516
3517 imgp->ip_cs_error = reason;
3518 reason->osr_flags = (OS_REASON_FLAG_GENERATE_CRASH_REPORT |
3519 OS_REASON_FLAG_CONSISTENT_FAILURE);
3520
3521 mach_vm_address_t data_addr = 0;
3522
3523 int reason_error = 0;
3524 int kcdata_error = 0;
3525
3526 if ((reason_error = os_reason_alloc_buffer_noblock(reason, kcdata_estimate_required_buffer_size
3527 (1, (uint32_t)fatal_failure_desc_len))) == 0 &&
3528 (kcdata_error = kcdata_get_memory_addr(&reason->osr_kcd_descriptor,
3529 EXIT_REASON_USER_DESC, (uint32_t)fatal_failure_desc_len,
3530 &data_addr)) == KERN_SUCCESS) {
3531 kern_return_t mc_error = kcdata_memcpy(&reason->osr_kcd_descriptor, (mach_vm_address_t)data_addr,
3532 fatal_failure_desc, (uint32_t)fatal_failure_desc_len);
3533
3534 if (mc_error != KERN_SUCCESS) {
3535 printf("load_code_signature: %s: failed to copy reason string "
3536 "(kcdata_memcpy error: %d, length: %lu)\n",
3537 path, mc_error, fatal_failure_desc_len);
3538 }
3539 } else {
3540 printf("load_code_signature: %s: failed to allocate space for reason string "
3541 "(os_reason_alloc_buffer error: %d, kcdata error: %d, length: %lu)\n",
3542 path, reason_error, kcdata_error, fatal_failure_desc_len);
3543 }
3544 out:
3545 if (vn_path) {
3546 zfree(ZV_NAMEI, vn_path);
3547 }
3548 }
3549
3550 static load_return_t
load_code_signature(struct linkedit_data_command * lcp,struct vnode * vp,off_t macho_offset,off_t macho_size,cpu_type_t cputype,cpu_subtype_t cpusubtype,load_result_t * result,struct image_params * imgp)3551 load_code_signature(
3552 struct linkedit_data_command *lcp,
3553 struct vnode *vp,
3554 off_t macho_offset,
3555 off_t macho_size,
3556 cpu_type_t cputype,
3557 cpu_subtype_t cpusubtype,
3558 load_result_t *result,
3559 struct image_params *imgp)
3560 {
3561 int ret;
3562 kern_return_t kr;
3563 vm_offset_t addr;
3564 int resid;
3565 struct cs_blob *blob;
3566 int error;
3567 vm_size_t blob_size;
3568 uint32_t sum;
3569 boolean_t anyCPU;
3570
3571 addr = 0;
3572 blob = NULL;
3573
3574 cpusubtype &= ~CPU_SUBTYPE_MASK;
3575
3576 blob = ubc_cs_blob_get(vp, cputype, cpusubtype, macho_offset);
3577
3578 if (blob != NULL) {
3579 /* we already have a blob for this vnode and cpu(sub)type */
3580 anyCPU = blob->csb_cpu_type == -1;
3581 if ((blob->csb_cpu_type != cputype &&
3582 blob->csb_cpu_subtype != cpusubtype && !anyCPU) ||
3583 (blob->csb_base_offset != macho_offset) ||
3584 ((blob->csb_flags & CS_VALID) == 0)) {
3585 /* the blob has changed for this vnode: fail ! */
3586 ret = LOAD_BADMACHO;
3587 const char* fatal_failure_desc = "embedded signature doesn't match attached signature";
3588 const size_t fatal_failure_desc_len = strlen(fatal_failure_desc) + 1;
3589
3590 printf("load_code_signature: %s\n", fatal_failure_desc);
3591 set_signature_error(vp, imgp, fatal_failure_desc, fatal_failure_desc_len);
3592 goto out;
3593 }
3594
3595 /* It matches the blob we want here, let's verify the version */
3596 if (!anyCPU && ubc_cs_generation_check(vp) == 0) {
3597 /* No need to revalidate, we're good! */
3598 ret = LOAD_SUCCESS;
3599 goto out;
3600 }
3601
3602 /* That blob may be stale, let's revalidate. */
3603 error = ubc_cs_blob_revalidate(vp, blob, imgp, 0, result->ip_platform);
3604 if (error == 0) {
3605 /* Revalidation succeeded, we're good! */
3606 /* If we were revaliding a CS blob with any CPU arch we adjust it */
3607 if (anyCPU) {
3608 vnode_lock_spin(vp);
3609 struct cs_cpu_info cpu_info = {
3610 .csb_cpu_type = cputype,
3611 .csb_cpu_subtype = cpusubtype
3612 };
3613 zalloc_ro_update_field(ZONE_ID_CS_BLOB, blob, csb_cpu_info, &cpu_info);
3614 vnode_unlock(vp);
3615 }
3616 ret = LOAD_SUCCESS;
3617 goto out;
3618 }
3619
3620 if (error != EAGAIN) {
3621 printf("load_code_signature: revalidation failed: %d\n", error);
3622 ret = LOAD_FAILURE;
3623 goto out;
3624 }
3625
3626 assert(error == EAGAIN);
3627
3628 /*
3629 * Revalidation was not possible for this blob. We just continue as if there was no blob,
3630 * rereading the signature, and ubc_cs_blob_add will do the right thing.
3631 */
3632 blob = NULL;
3633 }
3634
3635 if (lcp->cmdsize != sizeof(struct linkedit_data_command)) {
3636 ret = LOAD_BADMACHO;
3637 goto out;
3638 }
3639
3640 sum = 0;
3641 if (os_add_overflow(lcp->dataoff, lcp->datasize, &sum) || sum > macho_size) {
3642 ret = LOAD_BADMACHO;
3643 goto out;
3644 }
3645
3646 blob_size = lcp->datasize;
3647 kr = ubc_cs_blob_allocate(&addr, &blob_size);
3648 if (kr != KERN_SUCCESS) {
3649 ret = LOAD_NOSPACE;
3650 goto out;
3651 }
3652
3653 resid = 0;
3654 error = vn_rdwr(UIO_READ,
3655 vp,
3656 (caddr_t) addr,
3657 lcp->datasize,
3658 macho_offset + lcp->dataoff,
3659 UIO_SYSSPACE,
3660 0,
3661 kauth_cred_get(),
3662 &resid,
3663 current_proc());
3664 if (error || resid != 0) {
3665 ret = LOAD_IOERROR;
3666 goto out;
3667 }
3668
3669 if (ubc_cs_blob_add(vp,
3670 result->ip_platform,
3671 cputype,
3672 cpusubtype,
3673 macho_offset,
3674 &addr,
3675 lcp->datasize,
3676 imgp,
3677 0,
3678 &blob,
3679 CS_BLOB_ADD_ALLOW_MAIN_BINARY)) {
3680 if (addr) {
3681 ubc_cs_blob_deallocate(addr, blob_size);
3682 addr = 0;
3683 }
3684 ret = LOAD_FAILURE;
3685 goto out;
3686 } else {
3687 /* ubc_cs_blob_add() has consumed "addr" */
3688 addr = 0;
3689 }
3690
3691 #if CHECK_CS_VALIDATION_BITMAP
3692 ubc_cs_validation_bitmap_allocate( vp );
3693 #endif
3694
3695 ret = LOAD_SUCCESS;
3696 out:
3697 if (ret == LOAD_SUCCESS) {
3698 if (blob == NULL) {
3699 panic("success, but no blob!");
3700 }
3701
3702 result->csflags |= blob->csb_flags;
3703 result->platform_binary = blob->csb_platform_binary;
3704 result->cs_end_offset = blob->csb_end_offset;
3705 }
3706 if (addr != 0) {
3707 ubc_cs_blob_deallocate(addr, blob_size);
3708 addr = 0;
3709 }
3710
3711 return ret;
3712 }
3713
3714
3715 #if CONFIG_CODE_DECRYPTION
3716
3717 static load_return_t
set_code_unprotect(struct encryption_info_command * eip,caddr_t addr,vm_map_t map,int64_t slide,struct vnode * vp,off_t macho_offset,cpu_type_t cputype,cpu_subtype_t cpusubtype)3718 set_code_unprotect(
3719 struct encryption_info_command *eip,
3720 caddr_t addr,
3721 vm_map_t map,
3722 int64_t slide,
3723 struct vnode *vp,
3724 off_t macho_offset,
3725 cpu_type_t cputype,
3726 cpu_subtype_t cpusubtype)
3727 {
3728 int error, len;
3729 pager_crypt_info_t crypt_info;
3730 const char * cryptname = 0;
3731 char *vpath;
3732
3733 size_t offset;
3734 struct segment_command_64 *seg64;
3735 struct segment_command *seg32;
3736 vm_map_offset_t map_offset, map_size;
3737 vm_object_offset_t crypto_backing_offset;
3738 kern_return_t kr;
3739
3740 if (eip->cmdsize < sizeof(*eip)) {
3741 return LOAD_BADMACHO;
3742 }
3743
3744 switch (eip->cryptid) {
3745 case 0:
3746 /* not encrypted, just an empty load command */
3747 return LOAD_SUCCESS;
3748 case 1:
3749 cryptname = "com.apple.unfree";
3750 break;
3751 case 0x10:
3752 /* some random cryptid that you could manually put into
3753 * your binary if you want NULL */
3754 cryptname = "com.apple.null";
3755 break;
3756 default:
3757 return LOAD_BADMACHO;
3758 }
3759
3760 if (map == VM_MAP_NULL) {
3761 return LOAD_SUCCESS;
3762 }
3763 if (NULL == text_crypter_create) {
3764 return LOAD_FAILURE;
3765 }
3766
3767 vpath = zalloc(ZV_NAMEI);
3768
3769 len = MAXPATHLEN;
3770 error = vn_getpath(vp, vpath, &len);
3771 if (error) {
3772 zfree(ZV_NAMEI, vpath);
3773 return LOAD_FAILURE;
3774 }
3775
3776 if (eip->cryptsize == 0) {
3777 printf("%s:%d '%s': cryptoff 0x%llx cryptsize 0x%llx cryptid 0x%x ignored\n", __FUNCTION__, __LINE__, vpath, (uint64_t)eip->cryptoff, (uint64_t)eip->cryptsize, eip->cryptid);
3778 zfree(ZV_NAMEI, vpath);
3779 return LOAD_SUCCESS;
3780 }
3781
3782 /* set up decrypter first */
3783 crypt_file_data_t crypt_data = {
3784 .filename = vpath,
3785 .cputype = cputype,
3786 .cpusubtype = cpusubtype,
3787 .origin = CRYPT_ORIGIN_APP_LAUNCH,
3788 };
3789 kr = text_crypter_create(&crypt_info, cryptname, (void*)&crypt_data);
3790 #if VM_MAP_DEBUG_APPLE_PROTECT
3791 if (vm_map_debug_apple_protect) {
3792 struct proc *p;
3793 p = current_proc();
3794 printf("APPLE_PROTECT: %d[%s] map %p %s(%s) -> 0x%x\n",
3795 proc_getpid(p), p->p_comm, map, __FUNCTION__, vpath, kr);
3796 }
3797 #endif /* VM_MAP_DEBUG_APPLE_PROTECT */
3798 zfree(ZV_NAMEI, vpath);
3799
3800 if (kr) {
3801 printf("set_code_unprotect: unable to create decrypter %s, kr=%d\n",
3802 cryptname, kr);
3803 if (kr == kIOReturnNotPrivileged) {
3804 /* text encryption returned decryption failure */
3805 return LOAD_DECRYPTFAIL;
3806 } else {
3807 return LOAD_RESOURCE;
3808 }
3809 }
3810
3811 /* this is terrible, but we have to rescan the load commands to find the
3812 * virtual address of this encrypted stuff. This code is gonna look like
3813 * the dyld source one day... */
3814 struct mach_header *header = (struct mach_header *)addr;
3815 size_t mach_header_sz = sizeof(struct mach_header);
3816 if (header->magic == MH_MAGIC_64 ||
3817 header->magic == MH_CIGAM_64) {
3818 mach_header_sz = sizeof(struct mach_header_64);
3819 }
3820 offset = mach_header_sz;
3821 uint32_t ncmds = header->ncmds;
3822 while (ncmds--) {
3823 /*
3824 * Get a pointer to the command.
3825 */
3826 struct load_command *lcp = (struct load_command *)(addr + offset);
3827 offset += lcp->cmdsize;
3828
3829 switch (lcp->cmd) {
3830 case LC_SEGMENT_64:
3831 seg64 = (struct segment_command_64 *)lcp;
3832 if ((seg64->fileoff <= eip->cryptoff) &&
3833 (seg64->fileoff + seg64->filesize >=
3834 eip->cryptoff + eip->cryptsize)) {
3835 map_offset = (vm_map_offset_t)(seg64->vmaddr + eip->cryptoff - seg64->fileoff + slide);
3836 map_size = eip->cryptsize;
3837 crypto_backing_offset = macho_offset + eip->cryptoff;
3838 goto remap_now;
3839 }
3840 break;
3841 case LC_SEGMENT:
3842 seg32 = (struct segment_command *)lcp;
3843 if ((seg32->fileoff <= eip->cryptoff) &&
3844 (seg32->fileoff + seg32->filesize >=
3845 eip->cryptoff + eip->cryptsize)) {
3846 map_offset = (vm_map_offset_t)(seg32->vmaddr + eip->cryptoff - seg32->fileoff + slide);
3847 map_size = eip->cryptsize;
3848 crypto_backing_offset = macho_offset + eip->cryptoff;
3849 goto remap_now;
3850 }
3851 break;
3852 }
3853 }
3854
3855 /* if we get here, did not find anything */
3856 return LOAD_BADMACHO;
3857
3858 remap_now:
3859 /* now remap using the decrypter */
3860 MACHO_PRINTF(("+++ set_code_unprotect: vm[0x%llx:0x%llx]\n",
3861 (uint64_t) map_offset,
3862 (uint64_t) (map_offset + map_size)));
3863 kr = vm_map_apple_protected(map,
3864 map_offset,
3865 map_offset + map_size,
3866 crypto_backing_offset,
3867 &crypt_info,
3868 CRYPTID_APP_ENCRYPTION);
3869 if (kr) {
3870 printf("set_code_unprotect(): mapping failed with %x\n", kr);
3871 return LOAD_PROTECT;
3872 }
3873
3874 return LOAD_SUCCESS;
3875 }
3876
3877 #endif
3878
3879 /*
3880 * This routine exists to support the load_dylinker().
3881 *
3882 * This routine has its own, separate, understanding of the FAT file format,
3883 * which is terrifically unfortunate.
3884 */
3885 static
3886 load_return_t
get_macho_vnode(const char * path,cpu_type_t cputype,struct mach_header * mach_header,off_t * file_offset,off_t * macho_size,struct macho_data * data,struct vnode ** vpp,struct image_params * imgp)3887 get_macho_vnode(
3888 const char *path,
3889 cpu_type_t cputype,
3890 struct mach_header *mach_header,
3891 off_t *file_offset,
3892 off_t *macho_size,
3893 struct macho_data *data,
3894 struct vnode **vpp,
3895 struct image_params *imgp
3896 )
3897 {
3898 struct vnode *vp;
3899 vfs_context_t ctx = vfs_context_current();
3900 proc_t p = vfs_context_proc(ctx);
3901 kauth_cred_t kerncred;
3902 struct nameidata *ndp = &data->__nid;
3903 boolean_t is_fat;
3904 struct fat_arch fat_arch;
3905 int error;
3906 int resid;
3907 union macho_vnode_header *header = &data->__header;
3908 off_t fsize = (off_t)0;
3909
3910 /*
3911 * Capture the kernel credential for use in the actual read of the
3912 * file, since the user doing the execution may have execute rights
3913 * but not read rights, but to exec something, we have to either map
3914 * or read it into the new process address space, which requires
3915 * read rights. This is to deal with lack of common credential
3916 * serialization code which would treat NOCRED as "serialize 'root'".
3917 */
3918 kerncred = vfs_context_ucred(vfs_context_kernel());
3919
3920 /* init the namei data to point the file user's program name */
3921 NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW | LOCKLEAF, UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
3922
3923 if ((error = namei(ndp)) != 0) {
3924 if (error == ENOENT) {
3925 error = LOAD_ENOENT;
3926 } else {
3927 error = LOAD_FAILURE;
3928 }
3929 return error;
3930 }
3931 nameidone(ndp);
3932 vp = ndp->ni_vp;
3933
3934 /* check for regular file */
3935 if (vp->v_type != VREG) {
3936 error = LOAD_PROTECT;
3937 goto bad1;
3938 }
3939
3940 /* get size */
3941 if ((error = vnode_size(vp, &fsize, ctx)) != 0) {
3942 error = LOAD_FAILURE;
3943 goto bad1;
3944 }
3945
3946 /* Check mount point */
3947 if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
3948 error = LOAD_PROTECT;
3949 goto bad1;
3950 }
3951
3952 /* check access */
3953 if ((error = vnode_authorize(vp, NULL, KAUTH_VNODE_EXECUTE | KAUTH_VNODE_READ_DATA, ctx)) != 0) {
3954 error = LOAD_PROTECT;
3955 goto bad1;
3956 }
3957
3958 /* try to open it */
3959 if ((error = VNOP_OPEN(vp, FREAD, ctx)) != 0) {
3960 error = LOAD_PROTECT;
3961 goto bad1;
3962 }
3963
3964 if ((error = vn_rdwr(UIO_READ, vp, (caddr_t)header, sizeof(*header), 0,
3965 UIO_SYSSPACE, IO_NODELOCKED, kerncred, &resid, p)) != 0) {
3966 error = LOAD_IOERROR;
3967 goto bad2;
3968 }
3969
3970 if (resid) {
3971 error = LOAD_BADMACHO;
3972 goto bad2;
3973 }
3974
3975 if (header->mach_header.magic == MH_MAGIC ||
3976 header->mach_header.magic == MH_MAGIC_64) {
3977 is_fat = FALSE;
3978 } else if (OSSwapBigToHostInt32(header->fat_header.magic) == FAT_MAGIC) {
3979 is_fat = TRUE;
3980 } else {
3981 error = LOAD_BADMACHO;
3982 goto bad2;
3983 }
3984
3985 if (is_fat) {
3986 error = fatfile_validate_fatarches((vm_offset_t)(&header->fat_header),
3987 sizeof(*header), fsize);
3988 if (error != LOAD_SUCCESS) {
3989 goto bad2;
3990 }
3991
3992 /* Look up our architecture in the fat file. */
3993 error = fatfile_getbestarch_for_cputype(cputype, CPU_SUBTYPE_ANY,
3994 (vm_offset_t)(&header->fat_header), sizeof(*header), imgp, &fat_arch);
3995 if (error != LOAD_SUCCESS) {
3996 goto bad2;
3997 }
3998
3999 /* Read the Mach-O header out of it */
4000 error = vn_rdwr(UIO_READ, vp, (caddr_t)&header->mach_header,
4001 sizeof(header->mach_header), fat_arch.offset,
4002 UIO_SYSSPACE, IO_NODELOCKED, kerncred, &resid, p);
4003 if (error) {
4004 error = LOAD_IOERROR;
4005 goto bad2;
4006 }
4007
4008 if (resid) {
4009 error = LOAD_BADMACHO;
4010 goto bad2;
4011 }
4012
4013 /* Is this really a Mach-O? */
4014 if (header->mach_header.magic != MH_MAGIC &&
4015 header->mach_header.magic != MH_MAGIC_64) {
4016 error = LOAD_BADMACHO;
4017 goto bad2;
4018 }
4019
4020 *file_offset = fat_arch.offset;
4021 *macho_size = fat_arch.size;
4022 } else {
4023 /*
4024 * Force get_macho_vnode() to fail if the architecture bits
4025 * do not match the expected architecture bits. This in
4026 * turn causes load_dylinker() to fail for the same reason,
4027 * so it ensures the dynamic linker and the binary are in
4028 * lock-step. This is potentially bad, if we ever add to
4029 * the CPU_ARCH_* bits any bits that are desirable but not
4030 * required, since the dynamic linker might work, but we will
4031 * refuse to load it because of this check.
4032 */
4033 if ((cpu_type_t)header->mach_header.cputype != cputype) {
4034 error = LOAD_BADARCH;
4035 goto bad2;
4036 }
4037
4038 *file_offset = 0;
4039 *macho_size = fsize;
4040 }
4041
4042 *mach_header = header->mach_header;
4043 *vpp = vp;
4044
4045 ubc_setsize(vp, fsize);
4046 return error;
4047
4048 bad2:
4049 (void) VNOP_CLOSE(vp, FREAD, ctx);
4050 bad1:
4051 vnode_put(vp);
4052 return error;
4053 }
4054