-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec.rs
More file actions
2967 lines (2716 loc) · 94.2 KB
/
Copy pathexec.rs
File metadata and controls
2967 lines (2716 loc) · 94.2 KB
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
//! linux-parity: complete
//! linux-source: vendor/linux/kernel
//! test-origin: linux:vendor/linux/kernel
//! ELF binfmt + `execve` core flow (M24).
//!
//! This module implements Linux-shaped `execve` plumbing over the current
//! kernel substrate: path resolution from initramfs, ELF PT_LOAD mapping into
//! a fresh `mm_struct`, initial userspace stack/auxv synthesis, and per-task
//! start-context publication for the arch return path.
extern crate alloc;
use alloc::{
boxed::Box,
string::{String, ToString},
vec,
vec::Vec,
};
use core::ffi::c_char;
use core::sync::atomic::Ordering;
use spin::Mutex;
use crate::arch::x86::mm::paging::{
p4d_offset, pgd_none, pgd_offset_pgd, pgd_t, pmd_huge, pmd_none, pmd_offset, pte_offset_kernel,
pte_phys, pte_present, pte_t, pte_write, pud_huge, pud_none, pud_offset,
};
use crate::include::uapi::{
mount::MS_NOSUID,
stat::{S_ISGID, S_ISUID},
};
use crate::kernel::{
capability::KernelCapT,
cred::{self, Cred, KGid, KUid},
sched,
task::TaskStruct,
};
use crate::mm::{
buddy::{is_buddy_ready, page_to_pfn, with_global_buddy},
fault::{FAULT_FLAG_USER, FAULT_FLAG_WRITE, VM_FAULT_ERROR, handle_mm_fault},
frame::PAGE_SIZE,
mm_types::MmStruct,
mmap::{
MAP_ANONYMOUS, MAP_FIXED, MAP_GROWSDOWN, MAP_PRIVATE, PROT_EXEC, PROT_READ, PROT_WRITE,
TASK_SIZE, do_mmap,
},
page_flags::GFP_KERNEL,
vma::find_vma,
};
use crate::security;
const ELF_MAGIC: &[u8; 4] = b"\x7FELF";
const ELFCLASS64: u8 = 2;
const ELFDATA2LSB: u8 = 1;
const EV_CURRENT: u8 = 1;
const ET_EXEC: u16 = 2;
const ET_DYN: u16 = 3;
const EM_X86_64: u16 = 62;
const PT_LOAD: u32 = 1;
const PT_DYNAMIC: u32 = 2;
const PT_INTERP: u32 = 3;
const PF_X: u32 = 1;
const PF_W: u32 = 2;
const PF_R: u32 = 4;
const DT_NULL: i64 = 0;
const DT_RELA: i64 = 7;
const DT_RELASZ: i64 = 8;
const DT_RELAENT: i64 = 9;
const DT_RELRSZ: i64 = 35;
const DT_RELR: i64 = 36;
const DT_RELRENT: i64 = 37;
const R_X86_64_RELATIVE: u64 = 8;
const MAX_INTERP_RECURSION: usize = 4;
const MAX_ARG_STRLEN: usize = 128 * 1024;
const MAX_ARG_COUNT: usize = 4096;
const MAX_EXEC_FILE_BYTES: usize = 128 * 1024 * 1024;
const BINPRM_BUF_SIZE: usize = 256;
const EXEC_READ_CHUNK: usize = 64 * 1024;
const ELF_PHDR_SIZE: u16 = 56;
const ELF_MAX_PHDR_BYTES: usize = 65_536;
const PATH_MAX: u64 = 4096;
const STACK_SIZE: u64 = 8 * 1024 * 1024;
const PIE_LOAD_BIAS: u64 = 0x0000_5555_5555_4000;
const INTERP_LOAD_BIAS: u64 = 0x0000_7fff_0000_0000;
pub const AT_NULL: u64 = 0;
pub const AT_PHDR: u64 = 3;
pub const AT_PHENT: u64 = 4;
pub const AT_PHNUM: u64 = 5;
pub const AT_PAGESZ: u64 = 6;
pub const AT_BASE: u64 = 7;
pub const AT_ENTRY: u64 = 9;
pub const AT_UID: u64 = 11;
pub const AT_EUID: u64 = 12;
pub const AT_GID: u64 = 13;
pub const AT_EGID: u64 = 14;
pub const AT_HWCAP: u64 = 16;
pub const AT_SECURE: u64 = 23;
pub const AT_RANDOM: u64 = 25;
pub const AT_EXECFN: u64 = 31;
pub const AT_SYSINFO_EHDR: u64 = 33;
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct UserStartContext {
pub ip: u64,
pub sp: u64,
pub rflags: u64,
pub old_mm: usize,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ElfLoadSegment {
pub vaddr: u64,
pub memsz: u64,
pub filesz: u64,
pub flags: u32,
pub offset: u64,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ElfDynamicSegment {
pub offset: u64,
pub vaddr: u64,
pub filesz: u64,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ElfImage {
pub entry: u64,
pub et_dyn: bool,
pub phoff: u64,
pub phentsize: u16,
pub phnum: u16,
pub interp: Option<String>,
pub dynamic: Option<ElfDynamicSegment>,
pub load_segments: Vec<ElfLoadSegment>,
}
#[derive(Clone)]
pub struct ExecResolution {
pub requested_path: String,
pub resolved_path: String,
pub elf: ElfImage,
pub inode: crate::fs::types::InodeRef,
pub dentry: crate::fs::types::DentryRef,
pub mount: alloc::sync::Arc<crate::fs::mount::Mount>,
}
#[derive(Clone)]
struct LoadedImage {
path: String,
elf: ElfImage,
bytes: Vec<u8>,
complete_bytes: bool,
inode: crate::fs::types::InodeRef,
dentry: crate::fs::types::DentryRef,
mount: alloc::sync::Arc<crate::fs::mount::Mount>,
from_script: bool,
}
#[derive(Clone)]
struct LoadedProgram {
main: LoadedImage,
interp: Option<LoadedImage>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ExecLoadLayout {
main_bias: u64,
interp_bias: u64,
at_base: u64,
entry_ip: u64,
at_entry: u64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ExecRelocationPlan {
relocate_main_relative: bool,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct ElfDynamicRelocations {
rela_vaddr: u64,
rela_size: usize,
rela_ent: usize,
relr_vaddr: u64,
relr_size: usize,
relr_ent: usize,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ElfLoadWindow {
map_start: u64,
map_len: u64,
file_offset: usize,
file_len: usize,
zero_start: u64,
zero_len: u64,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct ShebangSpec {
interpreter: String,
arg: Option<String>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ExecSecurityContext {
pub uid: u32,
pub euid: u32,
pub gid: u32,
pub egid: u32,
pub secure_exec: bool,
}
struct ProposedExecCreds {
cred: *mut Cred,
security: ExecSecurityContext,
}
impl Drop for ProposedExecCreds {
fn drop(&mut self) {
if !self.cred.is_null() {
unsafe { Cred::put(self.cred) };
}
}
}
impl ProposedExecCreds {
fn security(&self) -> ExecSecurityContext {
self.security
}
fn commit(mut self) {
let cred = self.cred;
self.cred = core::ptr::null_mut();
cred::commit_creds(cred);
}
}
fn securebit_mask(bit: u32) -> u32 {
1u32 << bit
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ExecFileCaps {
effective: bool,
permitted: KernelCapT,
inheritable: KernelCapT,
}
const VFS_CAP_REVISION_MASK: u32 = 0xFF00_0000;
const VFS_CAP_FLAGS_EFFECTIVE: u32 = 0x0000_0001;
const VFS_CAP_REVISION_1: u32 = 0x0100_0000;
const VFS_CAP_REVISION_2: u32 = 0x0200_0000;
const VFS_CAP_REVISION_3: u32 = 0x0300_0000;
const XATTR_CAPS_SZ_1: usize = 12;
const XATTR_CAPS_SZ_2: usize = 20;
const XATTR_CAPS_SZ_3: usize = 24;
fn cap_intersect(a: KernelCapT, b: KernelCapT) -> KernelCapT {
KernelCapT {
cap: [a.cap[0] & b.cap[0], a.cap[1] & b.cap[1]],
}
}
fn cap_combine(a: KernelCapT, b: KernelCapT) -> KernelCapT {
KernelCapT {
cap: [a.cap[0] | b.cap[0], a.cap[1] | b.cap[1]],
}
}
fn cap_issubset(a: KernelCapT, b: KernelCapT) -> bool {
a.cap[0] & !b.cap[0] == 0 && a.cap[1] & !b.cap[1] == 0
}
fn cap_grew(target: KernelCapT, source: KernelCapT) -> bool {
!cap_issubset(target, source)
}
fn read_le32(value: &[u8], offset: usize) -> u32 {
u32::from_le_bytes([
value[offset],
value[offset + 1],
value[offset + 2],
value[offset + 3],
])
}
fn valid_cap_mask() -> KernelCapT {
let full = KernelCapT::full();
KernelCapT {
cap: [full.cap[0], full.cap[1]],
}
}
fn parse_vfs_cap_xattr(value: &[u8]) -> Result<Option<ExecFileCaps>, i32> {
if value.len() < core::mem::size_of::<u32>() {
return Err(-22);
}
let magic = read_le32(value, 0);
let revision = magic & VFS_CAP_REVISION_MASK;
if magic & !VFS_CAP_FLAGS_EFFECTIVE != revision {
return Err(-22);
}
let words = match revision {
VFS_CAP_REVISION_1 if value.len() == XATTR_CAPS_SZ_1 => 1,
VFS_CAP_REVISION_2 if value.len() == XATTR_CAPS_SZ_2 => 2,
VFS_CAP_REVISION_3 if value.len() == XATTR_CAPS_SZ_3 => {
let rootid = read_le32(value, 20);
if rootid != 0 {
return Ok(None);
}
2
}
_ => return Err(-22),
};
let mut permitted = KernelCapT::empty();
let mut inheritable = KernelCapT::empty();
for idx in 0..words {
permitted.cap[idx] = read_le32(value, 4 + idx * 8);
inheritable.cap[idx] = read_le32(value, 8 + idx * 8);
}
let valid = valid_cap_mask();
permitted = cap_intersect(permitted, valid);
inheritable = cap_intersect(inheritable, valid);
Ok(Some(ExecFileCaps {
effective: magic & VFS_CAP_FLAGS_EFFECTIVE != 0,
permitted,
inheritable,
}))
}
fn exec_creds_require_secure_mode(old: &Cred, new: &Cred, file_caps: Option<ExecFileCaps>) -> bool {
// vendor/linux/security/commoncap.c:cap_bprm_creds_from_file() marks
// AT_SECURE for privilege-elevating execs. In particular, dropping
// effective capabilities or resetting saved/fs IDs on an ordinary exec
// is *not* a secure exec. Treating any credential-field difference as
// privilege elevation makes glibc's secure_getenv() hide the complete
// environment from daemons which dropped privileges before exec.
let id_changed = new.euid != old.euid || new.egid != old.egid;
let non_root = new.uid.0 != 0 || new.euid.0 != 0;
let file_caps_secure = file_caps.is_some_and(|caps| {
non_root && (caps.effective || cap_grew(new.cap_permitted, new.cap_ambient))
});
id_changed || new.euid != old.uid || new.egid != old.gid || file_caps_secure
}
fn final_exec_nosuid(program: &LoadedProgram) -> bool {
(program.main.mount.flags.load(Ordering::Acquire) & MS_NOSUID as u32) != 0
}
fn final_exec_file_caps(image: &LoadedImage) -> Result<Option<ExecFileCaps>, i32> {
let xattrs = image.inode.xattrs.lock();
match xattrs.get("security.capability") {
Some(value) => parse_vfs_cap_xattr(value),
None => Ok(None),
}
}
fn prepare_exec_creds(program: &LoadedProgram) -> Result<ProposedExecCreds, i32> {
let task = unsafe { sched::get_current() };
let old_ptr = cred::current_cred();
if old_ptr.is_null() {
return Err(-3);
}
let Some(new_ptr) = cred::prepare_creds() else {
return Err(-12);
};
let new = unsafe { &mut *new_ptr };
let old = unsafe { &*old_ptr };
let mode = program.main.inode.mode.load(Ordering::Acquire);
let file_uid = KUid(program.main.inode.uid.load(Ordering::Acquire));
let file_gid = KGid(program.main.inode.gid.load(Ordering::Acquire));
let no_new_privs = !task.is_null() && unsafe { (*task).m27.no_new_privs != 0 };
let nosuid = final_exec_nosuid(program);
let script = program.main.from_script;
let file_caps = if nosuid || script {
None
} else {
final_exec_file_caps(&program.main)?
};
let has_file_caps = file_caps.is_some();
let setid_or_caps = (mode & (S_ISUID | S_ISGID)) != 0 || has_file_caps;
let allow_privilege = !nosuid && !no_new_privs && !script;
if allow_privilege {
if mode & S_ISUID != 0 {
new.euid = file_uid;
new.fsuid = file_uid;
}
if mode & S_ISGID != 0 {
new.egid = file_gid;
new.fsgid = file_gid;
}
}
// POSIX exec semantics reset the saved IDs to the post-exec effective IDs
// for every successful exec, not only when setuid/setgid bits are honored.
new.suid = new.euid;
new.sgid = new.egid;
if has_file_caps || (!allow_privilege && setid_or_caps) {
new.cap_ambient = KernelCapT::empty();
}
if allow_privilege && let Some(caps) = file_caps {
new.cap_permitted = cap_combine(
cap_intersect(new.cap_bset, caps.permitted),
cap_intersect(new.cap_inheritable, caps.inheritable),
);
}
if new.euid.0 == 0
&& old.euid.0 != 0
&& !(has_file_caps && new.uid.0 != 0)
&& new.securebits & securebit_mask(cred::securebits::SECURE_NOROOT) == 0
&& new.securebits & securebit_mask(cred::securebits::SECURE_NO_SETUID_FIXUP) == 0
{
new.cap_permitted = new.cap_bset;
new.cap_effective = new.cap_permitted;
}
let applied_file_caps = allow_privilege && has_file_caps;
if applied_file_caps {
let caps = file_caps.expect("has_file_caps");
new.cap_effective = if caps.effective {
new.cap_permitted
} else {
new.cap_ambient
};
} else if new.euid.0 != 0
&& new.securebits & securebit_mask(cred::securebits::SECURE_NO_SETUID_FIXUP) == 0
{
new.cap_effective = KernelCapT::empty();
}
let secure_exec = exec_creds_require_secure_mode(old, new, file_caps);
let security = ExecSecurityContext {
uid: new.uid.0,
euid: new.euid.0,
gid: new.gid.0,
egid: new.egid.0,
secure_exec,
};
Ok(ProposedExecCreds {
cred: new_ptr,
security,
})
}
static EXEC_STARTS: Mutex<Vec<(i32, UserStartContext)>> = Mutex::new(Vec::new());
pub fn take_exec_start_for_current() -> Option<UserStartContext> {
let task = unsafe { sched::get_current() };
if task.is_null() {
return None;
}
if let Some(ctx) = crate::kernel::fork::take_heap_task_exec_start(task) {
return Some(ctx);
}
let pid = unsafe { (*task).pid };
let mut starts = EXEC_STARTS.lock();
let idx = starts.iter().position(|(p, _)| *p == pid)?;
Some(starts.swap_remove(idx).1)
}
fn set_exec_start_for_task(task: *mut TaskStruct, pid: i32, ctx: UserStartContext) {
if crate::kernel::fork::set_heap_task_exec_start(task, ctx) {
return;
}
let mut starts = EXEC_STARTS.lock();
if let Some(entry) = starts.iter_mut().find(|(p, _)| *p == pid) {
*entry = (pid, ctx);
} else {
starts.push((pid, ctx));
}
}
pub fn parse_elf_image(bytes: &[u8]) -> Result<ElfImage, i32> {
if bytes.len() < 64 {
return Err(-8); // ENOEXEC
}
if &bytes[0..4] != ELF_MAGIC {
return Err(-8);
}
if bytes[4] != ELFCLASS64 || bytes[5] != ELFDATA2LSB || bytes[6] != EV_CURRENT {
return Err(-8);
}
let e_type = read_u16(bytes, 16)?;
let e_machine = read_u16(bytes, 18)?;
let e_entry = read_u64(bytes, 24)?;
let e_phoff = read_u64(bytes, 32)?;
let e_phentsize = read_u16(bytes, 54)?;
let e_phnum = read_u16(bytes, 56)?;
if (e_type != ET_EXEC && e_type != ET_DYN) || e_machine != EM_X86_64 {
return Err(-8);
}
if e_phentsize != ELF_PHDR_SIZE {
return Err(-8);
}
let mut interp = None;
let mut dynamic = None;
let mut loads = Vec::new();
for idx in 0..e_phnum {
let off = e_phoff as usize + (idx as usize * e_phentsize as usize);
let end = off.checked_add(e_phentsize as usize).ok_or(-8)?;
if end > bytes.len() {
return Err(-8);
}
let p_type = read_u32(bytes, off)?;
let p_flags = read_u32(bytes, off + 4)?;
let p_offset = read_u64(bytes, off + 8)?;
let p_vaddr = read_u64(bytes, off + 16)?;
let p_filesz = read_u64(bytes, off + 32)?;
let p_memsz = read_u64(bytes, off + 40)?;
if p_type == PT_LOAD {
loads.push(ElfLoadSegment {
vaddr: p_vaddr,
memsz: p_memsz,
filesz: p_filesz,
flags: p_flags,
offset: p_offset,
});
} else if p_type == PT_DYNAMIC {
dynamic = Some(ElfDynamicSegment {
offset: p_offset,
vaddr: p_vaddr,
filesz: p_filesz,
});
} else if p_type == PT_INTERP {
let start = p_offset as usize;
let stop = start.checked_add(p_filesz as usize).ok_or(-8)?;
if stop > bytes.len() || p_filesz == 0 {
return Err(-8);
}
let raw = &bytes[start..stop];
let nul = raw.iter().position(|b| *b == 0).ok_or(-8)?;
let txt = core::str::from_utf8(&raw[..nul]).map_err(|_| -8)?;
interp = Some(txt.to_string());
}
}
if loads.is_empty() {
return Err(-8);
}
Ok(ElfImage {
entry: e_entry,
et_dyn: e_type == ET_DYN,
phoff: e_phoff,
phentsize: e_phentsize,
phnum: e_phnum,
interp,
dynamic,
load_segments: loads,
})
}
pub fn resolve_exec_image(path: &str) -> Result<ExecResolution, i32> {
let loaded = load_image_with_shebang(path, 0)?;
Ok(ExecResolution {
requested_path: path.to_string(),
resolved_path: loaded.path,
elf: loaded.elf,
inode: loaded.inode,
dentry: loaded.dentry,
mount: loaded.mount,
})
}
fn load_program(path: &str) -> Result<LoadedProgram, i32> {
let main = load_image_with_shebang(path, 0)?;
let interp = if let Some(ref interp_path) = main.elf.interp {
Some(load_image_with_shebang(interp_path, 0)?)
} else {
None
};
Ok(LoadedProgram { main, interp })
}
fn load_image_with_shebang(path: &str, depth: usize) -> Result<LoadedImage, i32> {
if depth > MAX_INTERP_RECURSION {
return Err(-40); // ELOOP
}
let meta = read_exec_file_meta(path)?;
if let Some(next) = parse_shebang_interpreter(&meta.bytes)? {
let mut image = load_image_with_shebang(&next.interpreter, depth + 1)?;
image.from_script = true;
return Ok(image);
}
let elf = parse_elf_image(&meta.bytes)?;
Ok(LoadedImage {
path: normalize_exec_path(path),
elf,
bytes: meta.bytes,
complete_bytes: meta.complete_bytes,
inode: meta.inode,
dentry: meta.dentry,
mount: meta.mount,
from_script: false,
})
}
fn read_shebang_spec(path: &str) -> Result<Option<ShebangSpec>, i32> {
let bytes = read_exec_file(path)?;
parse_shebang_interpreter(&bytes)
}
struct ExecFileMeta {
bytes: Vec<u8>,
complete_bytes: bool,
inode: crate::fs::types::InodeRef,
dentry: crate::fs::types::DentryRef,
mount: alloc::sync::Arc<crate::fs::mount::Mount>,
}
fn read_exec_file(path: &str) -> Result<Vec<u8>, i32> {
read_exec_file_meta(path).map(|meta| meta.bytes)
}
fn read_exec_file_meta(path: &str) -> Result<ExecFileMeta, i32> {
let (mount, dentry) =
crate::fs::mount::resolve_path_follow(path).map_err(|errno| -(errno as i32))?;
let inode = dentry.inode().ok_or(-2)?;
if inode.kind != crate::fs::types::InodeKind::Regular {
return Err(-13);
}
let (bytes, complete_bytes) = match &inode.private {
crate::fs::types::InodePrivate::StaticBytes(bytes) => Ok((bytes.to_vec(), true)),
crate::fs::types::InodePrivate::StaticCowBytes { base, overlay } => {
if let Some(bytes) = overlay.lock().as_ref() {
Ok((bytes.clone(), true))
} else {
Ok((base.to_vec(), true))
}
}
crate::fs::types::InodePrivate::RamBytes(bytes) => Ok((bytes.lock().clone(), true)),
_ => read_regular_exec_metadata_bytes(path, dentry.clone(), inode.clone()),
}?;
Ok(ExecFileMeta {
bytes,
complete_bytes,
inode,
dentry,
mount,
})
}
fn read_regular_exec_metadata_bytes(
path: &str,
dentry: crate::fs::types::DentryRef,
inode: crate::fs::types::InodeRef,
) -> Result<(Vec<u8>, bool), i32> {
let size = inode.size.load(Ordering::Acquire) as usize;
if size > MAX_EXEC_FILE_BYTES {
return Err(-7); // E2BIG
}
let prefix_len = core::cmp::min(BINPRM_BUF_SIZE, size);
let mut metadata =
read_regular_inode_range(path, dentry.clone(), inode.clone(), 0, prefix_len, false)?;
if metadata.len() < 64 || metadata.get(0..4) != Some(ELF_MAGIC) {
let complete = metadata.len() == size;
return Ok((metadata, complete));
}
let phoff = read_u64(&metadata, 32)?;
let phentsize = read_u16(&metadata, 54)?;
let phnum = read_u16(&metadata, 56)?;
if phentsize != ELF_PHDR_SIZE || phnum == 0 {
return Ok((metadata, false));
}
let phdr_bytes = (phentsize as usize).checked_mul(phnum as usize).ok_or(-8)?;
if phdr_bytes == 0 || phdr_bytes > ELF_MAX_PHDR_BYTES {
return Ok((metadata, false));
}
let phoff_usize = usize::try_from(phoff).map_err(|_| -8)?;
let phend = phoff_usize.checked_add(phdr_bytes).ok_or(-8)?;
if phend > MAX_EXEC_FILE_BYTES {
return Err(-8);
}
if metadata.len() < phend {
metadata.resize(phend, 0);
}
let phdrs =
read_regular_inode_range(path, dentry.clone(), inode.clone(), phoff, phdr_bytes, true)?;
metadata[phoff_usize..phend].copy_from_slice(&phdrs);
for idx in 0..phnum {
let off = idx as usize * phentsize as usize;
let p_type = read_u32(&phdrs, off)?;
if p_type != PT_INTERP {
continue;
}
let p_offset = read_u64(&phdrs, off + 8)?;
let p_filesz = read_u64(&phdrs, off + 32)?;
if !(2..=PATH_MAX).contains(&p_filesz) {
return Err(-8);
}
let interp_start = usize::try_from(p_offset).map_err(|_| -8)?;
let interp_len = usize::try_from(p_filesz).map_err(|_| -8)?;
let interp_end = interp_start.checked_add(interp_len).ok_or(-8)?;
if interp_end > MAX_EXEC_FILE_BYTES {
return Err(-8);
}
if metadata.len() < interp_end {
metadata.resize(interp_end, 0);
}
let interp = read_regular_inode_range(
path,
dentry.clone(),
inode.clone(),
p_offset,
interp_len,
true,
)?;
metadata[interp_start..interp_end].copy_from_slice(&interp);
break;
}
let complete = metadata.len() == size;
Ok((metadata, complete))
}
fn read_regular_inode_range(
path: &str,
dentry: crate::fs::types::DentryRef,
inode: crate::fs::types::InodeRef,
offset: u64,
len: usize,
exact: bool,
) -> Result<Vec<u8>, i32> {
let mut out = vec![0u8; len];
if len == 0 {
return Ok(out);
}
let file = crate::fs::file::alloc_file(
dentry,
crate::include::uapi::fcntl::O_RDONLY,
inode.mode.load(Ordering::Acquire),
inode.fops,
);
crate::fs::file::set_path_hint(&file, path.to_string());
let result = (|| {
let read = file.fops.read.ok_or(-38)?;
let mut pos = offset;
let mut filled = 0usize;
while filled < len {
let n = read(&file, &mut out[filled..], &mut pos).map_err(|errno| -(errno as i32))?;
if n == 0 {
break;
}
filled = filled.checked_add(n).ok_or(-7)?;
}
if exact && filled != len {
return Err(-5); // EIO, matching elf_read() short-read handling.
}
out.truncate(filled);
Ok(out)
})();
crate::fs::file::fput(file);
result
}
fn read_regular_inode_bytes(
path: &str,
dentry: crate::fs::types::DentryRef,
inode: crate::fs::types::InodeRef,
) -> Result<Vec<u8>, i32> {
let expected = inode.size.load(Ordering::Acquire) as usize;
if expected > MAX_EXEC_FILE_BYTES {
return Err(-7); // E2BIG
}
let file = crate::fs::file::alloc_file(
dentry,
crate::include::uapi::fcntl::O_RDONLY,
inode.mode.load(Ordering::Acquire),
inode.fops,
);
crate::fs::file::set_path_hint(&file, path.to_string());
let result = (|| {
let mut out = Vec::with_capacity(expected);
let mut chunk = vec![0u8; EXEC_READ_CHUNK.min(MAX_EXEC_FILE_BYTES)];
loop {
let n = crate::fs::read_write::vfs_read(&file, &mut chunk)
.map_err(|errno| -(errno as i32))?;
if n == 0 {
break;
}
let next_len = out.len().checked_add(n).ok_or(-7)?;
if next_len > MAX_EXEC_FILE_BYTES {
return Err(-7);
}
out.extend_from_slice(&chunk[..n]);
}
Ok(out)
})();
crate::fs::file::fput(file);
result
}
fn parse_shebang_interpreter(bytes: &[u8]) -> Result<Option<ShebangSpec>, i32> {
if bytes.len() < 2 || &bytes[0..2] != b"#!" {
return Ok(None);
}
let line_end = bytes
.iter()
.position(|b| *b == b'\n')
.unwrap_or(bytes.len());
let line = core::str::from_utf8(&bytes[2..line_end]).map_err(|_| -8)?;
let mut words = line.split_whitespace();
let interpreter = words.next().ok_or(-8)?;
if interpreter.is_empty() {
return Err(-8);
}
Ok(Some(ShebangSpec {
interpreter: interpreter.to_string(),
arg: words.next().map(ToString::to_string),
}))
}
fn rewrite_argv_for_shebang(script_path: &str, argv: &[String], spec: &ShebangSpec) -> Vec<String> {
let mut rewritten = Vec::with_capacity(argv.len() + 3);
rewritten.push(spec.interpreter.clone());
if let Some(arg) = spec.arg.as_ref() {
rewritten.push(arg.clone());
}
rewritten.push(script_path.to_string());
if argv.len() > 1 {
rewritten.extend_from_slice(&argv[1..]);
}
rewritten
}
fn normalize_exec_path(path: &str) -> String {
crate::fs::fs_struct::absolute_from_cwd(path)
}
fn resolve_exec_path_for_load(path: &str) -> Result<String, i32> {
let mut normalized = normalize_exec_path(path);
for _ in 0..8 {
match crate::fs::proc::fd::current_fd_path_from_proc_path(&normalized) {
Some(Ok(path)) => {
#[cfg(not(test))]
if crate::kernel::debug_trace::proc_enabled()
&& (normalized.starts_with("/proc/self/fd/")
|| normalized.starts_with("/dev/fd/"))
{
crate::linux_driver_abi::tty::serial_println!(
"trace-proc-exec-resolve path={} resolved={}",
normalized,
path
);
}
normalized = normalize_exec_path(&path);
}
Some(Err(errno)) => {
#[cfg(not(test))]
if crate::kernel::debug_trace::proc_enabled()
&& (normalized.starts_with("/proc/self/fd/")
|| normalized.starts_with("/dev/fd/"))
{
crate::linux_driver_abi::tty::serial_println!(
"trace-proc-exec-resolve path={} errno={}",
normalized,
errno
);
}
return Err(-(errno as i32));
}
None => {
#[cfg(not(test))]
if crate::kernel::debug_trace::proc_enabled()
&& (normalized.starts_with("/proc/self/fd/")
|| normalized.starts_with("/dev/fd/"))
{
crate::linux_driver_abi::tty::serial_println!(
"trace-proc-exec-resolve path={} miss",
normalized
);
}
return Ok(normalized);
}
}
}
Err(-40)
}
fn exec_load_layout(program: &LoadedProgram) -> Result<ExecLoadLayout, i32> {
let main_bias = if program.main.elf.et_dyn {
PIE_LOAD_BIAS
} else {
0
};
let at_entry = main_bias.checked_add(program.main.elf.entry).ok_or(-12)?;
if let Some(interp) = program.interp.as_ref() {
let interp_bias = if interp.elf.et_dyn {
INTERP_LOAD_BIAS
} else {
0
};
let entry_ip = interp_bias.checked_add(interp.elf.entry).ok_or(-12)?;
Ok(ExecLoadLayout {
main_bias,
interp_bias,
at_base: interp_bias,
entry_ip,
at_entry,
})
} else {
Ok(ExecLoadLayout {
main_bias,
interp_bias: 0,
at_base: 0,
entry_ip: at_entry,
at_entry,
})
}
}
fn exec_relocation_plan(program: &LoadedProgram) -> ExecRelocationPlan {
let _ = program;
ExecRelocationPlan {
// Linux's ELF loader maps the executable image and enters either the
// PT_INTERP loader or the program entry point. Dynamic relocations are
// resolved in userspace: by ld.so for interpreted PIEs, or by the
// static PIE startup code for ET_DYN binaries without PT_INTERP.
relocate_main_relative: false,
}
}
unsafe fn copy_user_cstr(ptr: *const c_char) -> Result<String, i32> {
if ptr.is_null() {
return Err(-14); // EFAULT
}
let mut out = Vec::new();
for i in 0..MAX_ARG_STRLEN {
let b = unsafe { *ptr.add(i) } as u8;
if b == 0 {
let s = core::str::from_utf8(&out).map_err(|_| -14)?;
return Ok(s.to_string());
}
out.push(b);
}
Err(-7) // E2BIG
}
unsafe fn copy_user_cstr_array(list: *const *const c_char) -> Result<Vec<String>, i32> {
if list.is_null() {
return Ok(Vec::new());
}
let mut out = Vec::new();
for idx in 0..MAX_ARG_COUNT {
let p = unsafe { *list.add(idx) };
if p.is_null() {
return Ok(out);
}
out.push(unsafe { copy_user_cstr(p)? });
}
Err(-7) // E2BIG
}
fn set_task_comm_from_path(task: *mut TaskStruct, path: &str) {
let base = path.rsplit('/').next().unwrap_or(path).as_bytes();
let n = core::cmp::min(base.len(), 15);
unsafe {
(*task).comm.fill(0);
(&mut (*task).comm)[..n].copy_from_slice(&base[..n]);
}
}
#[cfg(not(test))]
fn trace_ping_exec_commit(path: &str, exec_path: &str) {
let task = unsafe { crate::kernel::sched::get_current() };
let pid = if task.is_null() {
-1
} else {
unsafe { (*task).pid }
};
if crate::kernel::debug_trace::remember_ping_pid_for_exec(pid, path, exec_path) {
crate::linux_driver_abi::tty::serial_println!(
"trace-ping-track pid={} path={} exec_path={}",