This repository has been archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
kern_exec.c
7174 lines (6342 loc) · 205 KB
/
kern_exec.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000-2020 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
/*
* Mach Operating System
* Copyright (c) 1987 Carnegie-Mellon University
* All rights reserved. The CMU software License Agreement specifies
* the terms and conditions for use and redistribution.
*/
/*-
* Copyright (c) 1982, 1986, 1991, 1993
* The Regents of the University of California. All rights reserved.
* (c) UNIX System Laboratories, Inc.
* All or some portions of this file are derived from material licensed
* to the University of California by American Telephone and Telegraph
* Co. or Unix System Laboratories, Inc. and are reproduced herein with
* the permission of UNIX System Laboratories, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* from: @(#)kern_exec.c 8.1 (Berkeley) 6/10/93
*/
/*
* NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
* support for mandatory and extensible security protections. This notice
* is included in support of clause 2.2 (b) of the Apple Public License,
* Version 2.0.
*/
#include <machine/reg.h>
#include <machine/cpu_capabilities.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/filedesc.h>
#include <sys/kernel.h>
#include <sys/proc_internal.h>
#include <sys/kauth.h>
#include <sys/user.h>
#include <sys/socketvar.h>
#include <sys/malloc.h>
#include <sys/namei.h>
#include <sys/mount_internal.h>
#include <sys/vnode_internal.h>
#include <sys/file_internal.h>
#include <sys/stat.h>
#include <sys/uio_internal.h>
#include <sys/acct.h>
#include <sys/exec.h>
#include <sys/kdebug.h>
#include <sys/signal.h>
#include <sys/aio_kern.h>
#include <sys/sysproto.h>
#include <sys/persona.h>
#include <sys/reason.h>
#if SYSV_SHM
#include <sys/shm_internal.h> /* shmexec() */
#endif
#include <sys/ubc_internal.h> /* ubc_map() */
#include <sys/spawn.h>
#include <sys/spawn_internal.h>
#include <sys/process_policy.h>
#include <sys/codesign.h>
#include <sys/random.h>
#include <crypto/sha1.h>
#include <libkern/libkern.h>
#include <libkern/crypto/sha2.h>
#include <security/audit/audit.h>
#include <ipc/ipc_types.h>
#include <mach/mach_param.h>
#include <mach/mach_types.h>
#include <mach/port.h>
#include <mach/task.h>
#include <mach/task_access.h>
#include <mach/thread_act.h>
#include <mach/vm_map.h>
#include <mach/mach_vm.h>
#include <mach/vm_param.h>
#include <kern/sched_prim.h> /* thread_wakeup() */
#include <kern/affinity.h>
#include <kern/assert.h>
#include <kern/task.h>
#include <kern/coalition.h>
#include <kern/policy_internal.h>
#include <kern/kalloc.h>
#include <os/log.h>
#if CONFIG_MACF
#include <security/mac_framework.h>
#include <security/mac_mach_internal.h>
#endif
#if CONFIG_AUDIT
#include <bsm/audit_kevents.h>
#endif
#if CONFIG_ARCADE
#include <kern/arcade.h>
#endif
#include <vm/vm_map.h>
#include <vm/vm_kern.h>
#include <vm/vm_protos.h>
#include <vm/vm_kern.h>
#include <vm/vm_fault.h>
#include <vm/vm_pageout.h>
#include <kdp/kdp_dyld.h>
#include <machine/machine_routines.h>
#include <machine/pal_routines.h>
#include <pexpert/pexpert.h>
#if CONFIG_MEMORYSTATUS
#include <sys/kern_memorystatus.h>
#endif
#include <IOKit/IOBSD.h>
extern boolean_t vm_darkwake_mode;
extern int bootarg_execfailurereports; /* bsd_init.c */
boolean_t unentitled_ios_sim_launch = FALSE;
#if __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX)
static TUNABLE(bool, bootarg_arm64e_preview_abi, "-arm64e_preview_abi", false);
#endif /* __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX) */
#if CONFIG_DTRACE
/* Do not include dtrace.h, it redefines kmem_[alloc/free] */
extern void dtrace_proc_exec(proc_t);
extern void (*dtrace_proc_waitfor_exec_ptr)(proc_t);
/*
* Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c,
* we will store its value before actually calling it.
*/
static void (*dtrace_proc_waitfor_hook)(proc_t) = NULL;
#include <sys/dtrace_ptss.h>
#endif
#if __has_feature(ptrauth_calls)
static int vm_shared_region_per_team_id = 1;
static int vm_shared_region_by_entitlement = 1;
/* Flag to control whether shared cache randomized resliding is enabled */
#if DEVELOPMENT || DEBUG || XNU_TARGET_OS_IOS
static int vm_shared_region_reslide_aslr = 1;
#else /* DEVELOPMENT || DEBUG || XNU_TARGET_OS_IOS */
static int vm_shared_region_reslide_aslr = 0;
#endif /* DEVELOPMENT || DEBUG || XNU_TARGET_OS_IOS */
/*
* Flag to control what processes should get shared cache randomize resliding
* after a fault in the shared cache region:
*
* 0 - all processes get a new randomized slide
* 1 - only platform processes get a new randomized slide
*/
int vm_shared_region_reslide_restrict = 1;
#if DEVELOPMENT || DEBUG
SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_per_team_id, CTLFLAG_RW, &vm_shared_region_per_team_id, 0, "");
SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_by_entitlement, CTLFLAG_RW, &vm_shared_region_by_entitlement, 0, "");
SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_reslide_restrict, CTLFLAG_RW, &vm_shared_region_reslide_restrict, 0, "");
SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_reslide_aslr, CTLFLAG_RW, &vm_shared_region_reslide_aslr, 0, "");
#endif
#endif /* __has_feature(ptrauth_calls) */
/* support for child creation in exec after vfork */
thread_t fork_create_child(task_t parent_task,
coalition_t *parent_coalition,
proc_t child_proc,
int inherit_memory,
int is_64bit_addr,
int is_64bit_data,
int in_exec);
void vfork_exit(proc_t p, int rv);
extern void proc_apply_task_networkbg_internal(proc_t, thread_t);
extern void task_set_did_exec_flag(task_t task);
extern void task_clear_exec_copy_flag(task_t task);
proc_t proc_exec_switch_task(proc_t p, task_t old_task, task_t new_task, thread_t new_thread, void **inherit);
boolean_t task_is_active(task_t);
boolean_t thread_is_active(thread_t thread);
void thread_copy_resource_info(thread_t dst_thread, thread_t src_thread);
void *ipc_importance_exec_switch_task(task_t old_task, task_t new_task);
extern void ipc_importance_release(void *elem);
extern boolean_t task_has_watchports(task_t task);
extern void task_set_no_smt(task_t task);
#if defined(HAS_APPLE_PAC)
char *task_get_vm_shared_region_id_and_jop_pid(task_t task, uint64_t *jop_pid);
#endif
task_t convert_port_to_task(ipc_port_t port);
/*
* Mach things for which prototypes are unavailable from Mach headers
*/
#define IPC_KMSG_FLAGS_ALLOW_IMMOVABLE_SEND 0x1
void ipc_task_reset(
task_t task);
void ipc_thread_reset(
thread_t thread);
kern_return_t ipc_object_copyin(
ipc_space_t space,
mach_port_name_t name,
mach_msg_type_name_t msgt_name,
ipc_object_t *objectp,
mach_port_context_t context,
mach_msg_guard_flags_t *guard_flags,
uint32_t kmsg_flags);
void ipc_port_release_send(ipc_port_t);
#if DEVELOPMENT || DEBUG
void task_importance_update_owner_info(task_t);
#endif
extern struct savearea *get_user_regs(thread_t);
__attribute__((noinline)) int __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port, int32_t new_pid);
#include <kern/thread.h>
#include <kern/task.h>
#include <kern/ast.h>
#include <kern/mach_loader.h>
#include <kern/mach_fat.h>
#include <mach-o/fat.h>
#include <mach-o/loader.h>
#include <machine/vmparam.h>
#include <sys/imgact.h>
#include <sys/sdt.h>
/*
* EAI_ITERLIMIT The maximum number of times to iterate an image
* activator in exec_activate_image() before treating
* it as malformed/corrupt.
*/
#define EAI_ITERLIMIT 3
/*
* For #! interpreter parsing
*/
#define IS_WHITESPACE(ch) ((ch == ' ') || (ch == '\t'))
#define IS_EOL(ch) ((ch == '#') || (ch == '\n'))
extern vm_map_t bsd_pageable_map;
extern const struct fileops vnops;
extern int nextpidversion;
#define USER_ADDR_ALIGN(addr, val) \
( ( (user_addr_t)(addr) + (val) - 1) \
& ~((val) - 1) )
/*
* For subsystem root support
*/
#define SPAWN_SUBSYSTEM_ROOT_ENTITLEMENT "com.apple.private.spawn-subsystem-root"
/* Platform Code Exec Logging */
static int platform_exec_logging = 0;
SYSCTL_DECL(_security_mac);
SYSCTL_INT(_security_mac, OID_AUTO, platform_exec_logging, CTLFLAG_RW, &platform_exec_logging, 0,
"log cdhashes for all platform binary executions");
static os_log_t peLog = OS_LOG_DEFAULT;
struct exec_port_actions {
uint32_t portwatch_count;
uint32_t registered_count;
ipc_port_t *portwatch_array;
ipc_port_t *registered_array;
};
struct image_params; /* Forward */
static int exec_activate_image(struct image_params *imgp);
static int exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp);
static int load_return_to_errno(load_return_t lrtn);
static int execargs_alloc(struct image_params *imgp);
static int execargs_free(struct image_params *imgp);
static int exec_check_permissions(struct image_params *imgp);
static int exec_extract_strings(struct image_params *imgp);
static int exec_add_apple_strings(struct image_params *imgp, const load_result_t *load_result);
static int exec_handle_sugid(struct image_params *imgp);
static int sugid_scripts = 0;
SYSCTL_INT(_kern, OID_AUTO, sugid_scripts, CTLFLAG_RW | CTLFLAG_LOCKED, &sugid_scripts, 0, "");
static kern_return_t create_unix_stack(vm_map_t map, load_result_t* load_result, proc_t p);
static int copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size);
static void exec_resettextvp(proc_t, struct image_params *);
static int check_for_signature(proc_t, struct image_params *);
static void exec_prefault_data(proc_t, struct image_params *, load_result_t *);
static errno_t exec_handle_port_actions(struct image_params *imgp,
struct exec_port_actions *port_actions);
static errno_t exec_handle_spawnattr_policy(proc_t p, thread_t thread, int psa_apptype, uint64_t psa_qos_clamp,
task_role_t psa_darwin_role, struct exec_port_actions *port_actions);
static void exec_port_actions_destroy(struct exec_port_actions *port_actions);
/*
* exec_add_user_string
*
* Add the requested string to the string space area.
*
* Parameters; struct image_params * image parameter block
* user_addr_t string to add to strings area
* int segment from which string comes
* boolean_t TRUE if string contributes to NCARGS
*
* Returns: 0 Success
* !0 Failure errno from copyinstr()
*
* Implicit returns:
* (imgp->ip_strendp) updated location of next add, if any
* (imgp->ip_strspace) updated byte count of space remaining
* (imgp->ip_argspace) updated byte count of space in NCARGS
*/
__attribute__((noinline))
static int
exec_add_user_string(struct image_params *imgp, user_addr_t str, int seg, boolean_t is_ncargs)
{
int error = 0;
do {
size_t len = 0;
int space;
if (is_ncargs) {
space = imgp->ip_argspace; /* by definition smaller than ip_strspace */
} else {
space = imgp->ip_strspace;
}
if (space <= 0) {
error = E2BIG;
break;
}
if (!UIO_SEG_IS_USER_SPACE(seg)) {
char *kstr = CAST_DOWN(char *, str); /* SAFE */
error = copystr(kstr, imgp->ip_strendp, space, &len);
} else {
error = copyinstr(str, imgp->ip_strendp, space, &len);
}
imgp->ip_strendp += len;
imgp->ip_strspace -= len;
if (is_ncargs) {
imgp->ip_argspace -= len;
}
} while (error == ENAMETOOLONG);
return error;
}
/*
* dyld is now passed the executable path as a getenv-like variable
* in the same fashion as the stack_guard and malloc_entropy keys.
*/
#define EXECUTABLE_KEY "executable_path="
/*
* exec_save_path
*
* To support new app package launching for Mac OS X, the dyld needs the
* first argument to execve() stored on the user stack.
*
* Save the executable path name at the bottom of the strings area and set
* the argument vector pointer to the location following that to indicate
* the start of the argument and environment tuples, setting the remaining
* string space count to the size of the string area minus the path length.
*
* Parameters; struct image_params * image parameter block
* char * path used to invoke program
* int segment from which path comes
*
* Returns: int 0 Success
* EFAULT Bad address
* copy[in]str:EFAULT Bad address
* copy[in]str:ENAMETOOLONG Filename too long
*
* Implicit returns:
* (imgp->ip_strings) saved path
* (imgp->ip_strspace) space remaining in ip_strings
* (imgp->ip_strendp) start of remaining copy area
* (imgp->ip_argspace) space remaining of NCARGS
* (imgp->ip_applec) Initial applev[0]
*
* Note: We have to do this before the initial namei() since in the
* path contains symbolic links, namei() will overwrite the
* original path buffer contents. If the last symbolic link
* resolved was a relative pathname, we would lose the original
* "path", which could be an absolute pathname. This might be
* unacceptable for dyld.
*/
static int
exec_save_path(struct image_params *imgp, user_addr_t path, int seg, const char **excpath)
{
int error;
size_t len;
char *kpath;
// imgp->ip_strings can come out of a cache, so we need to obliterate the
// old path.
memset(imgp->ip_strings, '\0', strlen(EXECUTABLE_KEY) + MAXPATHLEN);
len = MIN(MAXPATHLEN, imgp->ip_strspace);
switch (seg) {
case UIO_USERSPACE32:
case UIO_USERSPACE64: /* Same for copyin()... */
error = copyinstr(path, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len);
break;
case UIO_SYSSPACE:
kpath = CAST_DOWN(char *, path); /* SAFE */
error = copystr(kpath, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len);
break;
default:
error = EFAULT;
break;
}
if (!error) {
bcopy(EXECUTABLE_KEY, imgp->ip_strings, strlen(EXECUTABLE_KEY));
len += strlen(EXECUTABLE_KEY);
imgp->ip_strendp += len;
imgp->ip_strspace -= len;
if (excpath) {
*excpath = imgp->ip_strings + strlen(EXECUTABLE_KEY);
}
}
return error;
}
/*
* exec_reset_save_path
*
* If we detect a shell script, we need to reset the string area
* state so that the interpreter can be saved onto the stack.
*
* Parameters; struct image_params * image parameter block
*
* Returns: int 0 Success
*
* Implicit returns:
* (imgp->ip_strings) saved path
* (imgp->ip_strspace) space remaining in ip_strings
* (imgp->ip_strendp) start of remaining copy area
* (imgp->ip_argspace) space remaining of NCARGS
*
*/
static int
exec_reset_save_path(struct image_params *imgp)
{
imgp->ip_strendp = imgp->ip_strings;
imgp->ip_argspace = NCARGS;
imgp->ip_strspace = (NCARGS + PAGE_SIZE);
return 0;
}
/*
* exec_shell_imgact
*
* Image activator for interpreter scripts. If the image begins with
* the characters "#!", then it is an interpreter script. Verify the
* length of the script line indicating the interpreter is not in
* excess of the maximum allowed size. If this is the case, then
* break out the arguments, if any, which are separated by white
* space, and copy them into the argument save area as if they were
* provided on the command line before all other arguments. The line
* ends when we encounter a comment character ('#') or newline.
*
* Parameters; struct image_params * image parameter block
*
* Returns: -1 not an interpreter (keep looking)
* -3 Success: interpreter: relookup
* >0 Failure: interpreter: error number
*
* A return value other than -1 indicates subsequent image activators should
* not be given the opportunity to attempt to activate the image.
*/
static int
exec_shell_imgact(struct image_params *imgp)
{
char *vdata = imgp->ip_vdata;
char *ihp;
char *line_startp, *line_endp;
char *interp;
/*
* Make sure it's a shell script. If we've already redirected
* from an interpreted file once, don't do it again.
*/
if (vdata[0] != '#' ||
vdata[1] != '!' ||
(imgp->ip_flags & IMGPF_INTERPRET) != 0) {
return -1;
}
if (imgp->ip_origcputype != 0) {
/* Fat header previously matched, don't allow shell script inside */
return -1;
}
imgp->ip_flags |= IMGPF_INTERPRET;
imgp->ip_interp_sugid_fd = -1;
imgp->ip_interp_buffer[0] = '\0';
/* Check to see if SUGID scripts are permitted. If they aren't then
* clear the SUGID bits.
* imgp->ip_vattr is known to be valid.
*/
if (sugid_scripts == 0) {
imgp->ip_origvattr->va_mode &= ~(VSUID | VSGID);
}
/* Try to find the first non-whitespace character */
for (ihp = &vdata[2]; ihp < &vdata[IMG_SHSIZE]; ihp++) {
if (IS_EOL(*ihp)) {
/* Did not find interpreter, "#!\n" */
return ENOEXEC;
} else if (IS_WHITESPACE(*ihp)) {
/* Whitespace, like "#! /bin/sh\n", keep going. */
} else {
/* Found start of interpreter */
break;
}
}
if (ihp == &vdata[IMG_SHSIZE]) {
/* All whitespace, like "#! " */
return ENOEXEC;
}
line_startp = ihp;
/* Try to find the end of the interpreter+args string */
for (; ihp < &vdata[IMG_SHSIZE]; ihp++) {
if (IS_EOL(*ihp)) {
/* Got it */
break;
} else {
/* Still part of interpreter or args */
}
}
if (ihp == &vdata[IMG_SHSIZE]) {
/* A long line, like "#! blah blah blah" without end */
return ENOEXEC;
}
/* Backtrack until we find the last non-whitespace */
while (IS_EOL(*ihp) || IS_WHITESPACE(*ihp)) {
ihp--;
}
/* The character after the last non-whitespace is our logical end of line */
line_endp = ihp + 1;
/*
* Now we have pointers to the usable part of:
*
* "#! /usr/bin/int first second third \n"
* ^ line_startp ^ line_endp
*/
/* copy the interpreter name */
interp = imgp->ip_interp_buffer;
for (ihp = line_startp; (ihp < line_endp) && !IS_WHITESPACE(*ihp); ihp++) {
*interp++ = *ihp;
}
*interp = '\0';
exec_reset_save_path(imgp);
exec_save_path(imgp, CAST_USER_ADDR_T(imgp->ip_interp_buffer),
UIO_SYSSPACE, NULL);
/* Copy the entire interpreter + args for later processing into argv[] */
interp = imgp->ip_interp_buffer;
for (ihp = line_startp; (ihp < line_endp); ihp++) {
*interp++ = *ihp;
}
*interp = '\0';
#if CONFIG_SETUID
/*
* If we have an SUID or SGID script, create a file descriptor
* from the vnode and pass /dev/fd/%d instead of the actual
* path name so that the script does not get opened twice
*/
if (imgp->ip_origvattr->va_mode & (VSUID | VSGID)) {
proc_t p;
struct fileproc *fp;
int fd;
int error;
p = vfs_context_proc(imgp->ip_vfs_context);
error = falloc(p, &fp, &fd, imgp->ip_vfs_context);
if (error) {
return error;
}
fp->fp_glob->fg_flag = FREAD;
fp->fp_glob->fg_ops = &vnops;
fp->fp_glob->fg_data = (caddr_t)imgp->ip_vp;
proc_fdlock(p);
procfdtbl_releasefd(p, fd, NULL);
fp_drop(p, fd, fp, 1);
proc_fdunlock(p);
vnode_ref(imgp->ip_vp);
imgp->ip_interp_sugid_fd = fd;
}
#endif /* CONFIG_SETUID */
return -3;
}
/*
* exec_fat_imgact
*
* Image activator for fat 1.0 binaries. If the binary is fat, then we
* need to select an image from it internally, and make that the image
* we are going to attempt to execute. At present, this consists of
* reloading the first page for the image with a first page from the
* offset location indicated by the fat header.
*
* Parameters; struct image_params * image parameter block
*
* Returns: -1 not a fat binary (keep looking)
* -2 Success: encapsulated binary: reread
* >0 Failure: error number
*
* Important: This image activator is byte order neutral.
*
* Note: A return value other than -1 indicates subsequent image
* activators should not be given the opportunity to attempt
* to activate the image.
*
* If we find an encapsulated binary, we make no assertions
* about its validity; instead, we leave that up to a rescan
* for an activator to claim it, and, if it is claimed by one,
* that activator is responsible for determining validity.
*/
static int
exec_fat_imgact(struct image_params *imgp)
{
proc_t p = vfs_context_proc(imgp->ip_vfs_context);
kauth_cred_t cred = kauth_cred_proc_ref(p);
struct fat_header *fat_header = (struct fat_header *)imgp->ip_vdata;
struct _posix_spawnattr *psa = NULL;
struct fat_arch fat_arch;
int resid, error;
load_return_t lret;
if (imgp->ip_origcputype != 0) {
/* Fat header previously matched, don't allow another fat file inside */
error = -1; /* not claimed */
goto bad;
}
/* Make sure it's a fat binary */
if (OSSwapBigToHostInt32(fat_header->magic) != FAT_MAGIC) {
error = -1; /* not claimed */
goto bad;
}
/* imgp->ip_vdata has PAGE_SIZE, zerofilled if the file is smaller */
lret = fatfile_validate_fatarches((vm_offset_t)fat_header, PAGE_SIZE);
if (lret != LOAD_SUCCESS) {
error = load_return_to_errno(lret);
goto bad;
}
/* If posix_spawn binprefs exist, respect those prefs. */
psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
if (psa != NULL && psa->psa_binprefs[0] != 0) {
uint32_t pr = 0;
/* Check each preference listed against all arches in header */
for (pr = 0; pr < NBINPREFS; pr++) {
cpu_type_t pref = psa->psa_binprefs[pr];
cpu_type_t subpref = psa->psa_subcpuprefs[pr];
if (pref == 0) {
/* No suitable arch in the pref list */
error = EBADARCH;
goto bad;
}
if (pref == CPU_TYPE_ANY) {
/* Fall through to regular grading */
goto regular_grading;
}
lret = fatfile_getbestarch_for_cputype(pref,
subpref,
(vm_offset_t)fat_header,
PAGE_SIZE,
imgp,
&fat_arch);
if (lret == LOAD_SUCCESS) {
goto use_arch;
}
}
/* Requested binary preference was not honored */
error = EBADEXEC;
goto bad;
}
regular_grading:
/* Look up our preferred architecture in the fat file. */
lret = fatfile_getbestarch((vm_offset_t)fat_header,
PAGE_SIZE,
imgp,
&fat_arch,
(p->p_flag & P_AFFINITY) != 0);
if (lret != LOAD_SUCCESS) {
error = load_return_to_errno(lret);
goto bad;
}
use_arch:
/* Read the Mach-O header out of fat_arch */
error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata,
PAGE_SIZE, fat_arch.offset,
UIO_SYSSPACE, (IO_UNIT | IO_NODELOCKED),
cred, &resid, p);
if (error) {
goto bad;
}
if (resid) {
memset(imgp->ip_vdata + (PAGE_SIZE - resid), 0x0, resid);
}
/* Success. Indicate we have identified an encapsulated binary */
error = -2;
imgp->ip_arch_offset = (user_size_t)fat_arch.offset;
imgp->ip_arch_size = (user_size_t)fat_arch.size;
imgp->ip_origcputype = fat_arch.cputype;
imgp->ip_origcpusubtype = fat_arch.cpusubtype;
bad:
kauth_cred_unref(&cred);
return error;
}
static int
activate_exec_state(task_t task, proc_t p, thread_t thread, load_result_t *result)
{
int ret;
task_set_dyld_info(task, MACH_VM_MIN_ADDRESS, 0);
task_set_64bit(task, result->is_64bit_addr, result->is_64bit_data);
if (result->is_64bit_addr) {
OSBitOrAtomic(P_LP64, &p->p_flag);
} else {
OSBitAndAtomic(~((uint32_t)P_LP64), &p->p_flag);
}
task_set_mach_header_address(task, result->mach_header);
ret = thread_state_initialize(thread);
if (ret != KERN_SUCCESS) {
return ret;
}
if (result->threadstate) {
uint32_t *ts = result->threadstate;
uint32_t total_size = (uint32_t)result->threadstate_sz;
while (total_size > 0) {
uint32_t flavor = *ts++;
uint32_t size = *ts++;
ret = thread_setstatus(thread, flavor, (thread_state_t)ts, size);
if (ret) {
return ret;
}
ts += size;
total_size -= (size + 2) * sizeof(uint32_t);
}
}
thread_setentrypoint(thread, result->entry_point);
return KERN_SUCCESS;
}
/*
* Set p->p_comm and p->p_name to the name passed to exec
*/
static void
set_proc_name(struct image_params *imgp, proc_t p)
{
int p_name_len = sizeof(p->p_name) - 1;
if (imgp->ip_ndp->ni_cnd.cn_namelen > p_name_len) {
imgp->ip_ndp->ni_cnd.cn_namelen = p_name_len;
}
bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_name,
(unsigned)imgp->ip_ndp->ni_cnd.cn_namelen);
p->p_name[imgp->ip_ndp->ni_cnd.cn_namelen] = '\0';
if (imgp->ip_ndp->ni_cnd.cn_namelen > MAXCOMLEN) {
imgp->ip_ndp->ni_cnd.cn_namelen = MAXCOMLEN;
}
bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_comm,
(unsigned)imgp->ip_ndp->ni_cnd.cn_namelen);
p->p_comm[imgp->ip_ndp->ni_cnd.cn_namelen] = '\0';
}
#if __has_feature(ptrauth_calls)
/**
* Returns a team ID string that may be used to assign a shared region.
*
* Platform binaries do not have team IDs and will return NULL. Non-platform
* binaries without a team ID will be assigned an artificial team ID of ""
* (empty string) so that they will not be assigned to the default shared
* region.
*
* @param imgp image parameter block
* @return NULL if this is a platform binary, or an appropriate team ID string
* otherwise
*/
static inline const char *
get_teamid_for_shared_region(struct image_params *imgp)
{
assert(imgp->ip_vp != NULL);
const char *ret = csvnode_get_teamid(imgp->ip_vp, imgp->ip_arch_offset);
if (ret) {
return ret;
}
struct cs_blob *blob = csvnode_get_blob(imgp->ip_vp, imgp->ip_arch_offset);
if (csblob_get_platform_binary(blob)) {
return NULL;
} else {
static const char *NO_TEAM_ID = "";
return NO_TEAM_ID;
}
}
/**
* Determines whether ptrauth should be enabled for the provided arm64 CPU subtype.
*
* @param cpusubtype Mach-O style CPU subtype
* @return whether the CPU subtype matches arm64e with the current ptrauth ABI
*/
static inline bool
arm64_cpusubtype_uses_ptrauth(cpu_subtype_t cpusubtype)
{
return (cpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E &&
CPU_SUBTYPE_ARM64_PTR_AUTH_VERSION(cpusubtype) == CPU_SUBTYPE_ARM64_PTR_AUTH_CURRENT_VERSION;
}
#endif /* __has_feature(ptrauth_calls) */
/**
* Returns whether a type/subtype slice matches the requested
* type/subtype.
*
* @param mask Bits to mask from the requested/tested cpu type
* @param req_cpu Requested cpu type
* @param req_subcpu Requested cpu subtype
* @param test_cpu Tested slice cpu type
* @param test_subcpu Tested slice cpu subtype
*/
boolean_t
binary_match(cpu_type_t mask, cpu_type_t req_cpu,
cpu_subtype_t req_subcpu, cpu_type_t test_cpu,
cpu_subtype_t test_subcpu)
{
if ((test_cpu & ~mask) != (req_cpu & ~mask)) {
return FALSE;
}
test_subcpu &= ~CPU_SUBTYPE_MASK;
req_subcpu &= ~CPU_SUBTYPE_MASK;
if (test_subcpu != req_subcpu && req_subcpu != (CPU_SUBTYPE_ANY & ~CPU_SUBTYPE_MASK)) {
return FALSE;
}
return TRUE;
}
/*
* exec_mach_imgact
*
* Image activator for mach-o 1.0 binaries.
*
* Parameters; struct image_params * image parameter block
*
* Returns: -1 not a fat binary (keep looking)
* -2 Success: encapsulated binary: reread
* >0 Failure: error number
* EBADARCH Mach-o binary, but with an unrecognized
* architecture
* ENOMEM No memory for child process after -
* can only happen after vfork()
*
* Important: This image activator is NOT byte order neutral.
*
* Note: A return value other than -1 indicates subsequent image
* activators should not be given the opportunity to attempt
* to activate the image.
*
* TODO: More gracefully handle failures after vfork
*/
static int
exec_mach_imgact(struct image_params *imgp)
{
struct mach_header *mach_header = (struct mach_header *)imgp->ip_vdata;
proc_t p = vfs_context_proc(imgp->ip_vfs_context);
int error = 0;
task_t task;
task_t new_task = NULL; /* protected by vfexec */
thread_t thread;
struct uthread *uthread;
vm_map_t old_map = VM_MAP_NULL;
vm_map_t map = VM_MAP_NULL;
load_return_t lret;
load_result_t load_result = {};
struct _posix_spawnattr *psa = NULL;
int spawn = (imgp->ip_flags & IMGPF_SPAWN);
int vfexec = (imgp->ip_flags & IMGPF_VFORK_EXEC);
int exec = (imgp->ip_flags & IMGPF_EXEC);