-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.rs
More file actions
1434 lines (1295 loc) · 56.7 KB
/
Copy pathmain.rs
File metadata and controls
1434 lines (1295 loc) · 56.7 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
#![no_std]
#![no_main]
extern crate alloc;
use alloc::vec::Vec;
use log::info;
use uefi::prelude::*;
use uefi::proto::console::gop::{GraphicsOutput, PixelFormat as GopPixelFormat};
use uefi::proto::loaded_image::LoadedImage;
use uefi::proto::media::file::{File, FileAttribute, FileInfo, FileMode};
use uefi::proto::media::fs::SimpleFileSystem;
use uefi::table::boot::{AllocateType, BootServices, MemoryType};
use uefi::table::cfg::{ACPI2_GUID, ACPI_GUID};
use uefi::CStr16;
use uefi::Identify;
use xmas_elf::program::Type;
use xmas_elf::sections::SectionData;
use xmas_elf::ElfFile;
// ============================================================================
// R39-7 FIX: KASLR Configuration
// ============================================================================
/// Kernel load base physical address (matches kernel/security/kaslr.rs)
const KERNEL_PHYS_BASE: u64 = 0x100000;
/// Kernel virtual base address matching the linker script.
/// Used to filter out non-kernel LOAD segments (e.g., `.rela.dyn` metadata at VA 0).
const KERNEL_VIRT_BASE: u64 = 0xffffffff80000000;
/// R167-C: BootInfo ABI version. MUST match `BOOT_INFO_VERSION` in
/// `kernel/mm/memory.rs`. Bump on any change to the `BootInfo` layout.
const BOOT_INFO_VERSION: u64 = 2;
/// BootInfo `kaslr_flags`: the exact placement order was produced by a
/// complete, unbiased RDRAND-backed shuffle. A non-zero relocation slide
/// without this bit is availability relocation, not KASLR.
const BOOT_INFO_KASLR_RANDOMIZED: u64 = 1 << 0;
/// Maximum KASLR slide (512 MiB, within the 1GB high-half mapping)
const KASLR_MAX_SLIDE: u64 = 512 * 1024 * 1024;
/// KASLR slide granularity. The initial page tables cover the whole 1 GiB
/// window, so placement does not need to be constrained to huge-page
/// boundaries. A 64 KiB quantum provides materially more than the old
/// eight-bit placement entropy while keeping the bounded permutation small.
const KASLR_SLIDE_GRANULARITY: u64 = 64 * 1024;
/// Physical window covered by the initial high-half 1 GiB mapping.
const KERNEL_PHYS_WINDOW_END: u64 = 1024 * 1024 * 1024;
/// Defensive upper bound for the kernel file read. The UEFI file metadata is
/// untrusted input; refusing an absurd length keeps a corrupt directory entry
/// from turning the bootloader's initial allocation into an unbounded request.
const KERNEL_MAX_FILE_SIZE: usize = 64 * 1024 * 1024;
/// Maximum post-ExitBootServices memory-map snapshot. The buffer is sized for
/// a deliberately generous descriptor budget (2 MiB) and is checked against
/// the firmware-reported byte count before copying; a corrupt/hostile map is
/// rejected without an out-of-bounds write.
const MEMORY_MAP_COPY_PAGES: usize = 512;
/// Number of bounded placement slots, including slide zero.
const KASLR_SLOT_COUNT: usize = (KASLR_MAX_SLIDE / KASLR_SLIDE_GRANULARITY + 1) as usize;
const _: () = assert!(KASLR_MAX_SLIDE.is_multiple_of(KASLR_SLIDE_GRANULARITY));
const _: () = assert!(KERNEL_PHYS_BASE + KASLR_MAX_SLIDE < KERNEL_PHYS_WINDOW_END);
const _: () = assert!(KASLR_SLOT_COUNT <= u16::MAX as usize + 1);
/// ELF relocation type: R_X86_64_RELATIVE (base + addend)
const R_X86_64_RELATIVE: u32 = 8;
/// Apply `.rela.dyn` relocations to the loaded kernel image.
///
/// A static-PIE kernel emits only `R_X86_64_RELATIVE` relocations (no GOT/PLT
/// symbol references). Each entry patches an absolute address in the loaded
/// image: `*site = addend + load_bias`.
///
/// # Arguments
///
/// * `elf` — Parsed ELF file (still refers to the original in-memory buffer)
/// * `kernel_min_vaddr` — Lowest virtual address among LOAD segments (link-time base)
/// * `kernel_phys_base` — Physical address where the kernel image is loaded
/// * `load_bias` — KASLR slide: the delta between the actual and linked load addresses
///
/// # Panics
///
/// Panics if:
/// - `load_bias != 0` but the kernel has no `.rela.dyn` section
/// - Any relocation type other than `R_X86_64_RELATIVE` is encountered
/// - A relocation targets a VA below `kernel_min_vaddr`
/// - A relocation target + 8 exceeds the kernel image bounds
fn apply_rela_dyn_relocations(
elf: &ElfFile<'_>,
kernel_min_vaddr: u64,
kernel_size: u64,
kernel_phys_base: u64,
load_bias: u64,
) {
let rela_dyn = match elf.find_section_by_name(".rela.dyn") {
Some(section) => section,
None => {
if load_bias != 0 {
// R120-4 FIX: Do not include the KASLR slide value in the panic
// string — it would be captured by UEFI firmware logs, serial
// console, or BMC/IPMI history, leaking the slide in release builds.
panic!(
"KASLR slide is non-zero but kernel has no .rela.dyn section — \
kernel must be compiled as PIE (-C relocation-model=pie) \
and keep relocation sections in the linker script"
);
}
// No relocations and no slide — nothing to do
return;
}
};
let relas = match rela_dyn
.get_data(elf)
.expect("Failed to parse .rela.dyn section data")
{
SectionData::Rela64(relas) => relas,
_ => panic!("Unexpected .rela.dyn format (expected Rela64 for x86_64 kernel)"),
};
if relas.is_empty() {
return;
}
// R119-1 FIX: Gate load_bias value behind debug_assertions to prevent KASLR
// slide leak to serial console observers. The relocation count is safe to log.
#[cfg(debug_assertions)]
info!(
"Applying {} .rela.dyn relocations (load_bias=0x{:x})",
relas.len(),
load_bias
);
#[cfg(not(debug_assertions))]
info!("Applying {} .rela.dyn relocations", relas.len());
let mut applied = 0u64;
for rela in relas {
let rtype = rela.get_type();
if rtype != R_X86_64_RELATIVE {
panic!(
"Unsupported relocation type {} at offset 0x{:x} — \
static-PIE kernel should only emit R_X86_64_RELATIVE (type 8)",
rtype,
rela.get_offset()
);
}
// R_X86_64_RELATIVE must have symbol index 0
if rela.get_symbol_table_index() != 0 {
panic!(
"R_X86_64_RELATIVE at offset 0x{:x} has unexpected symbol index {} — \
expected 0 for base-relative relocations",
rela.get_offset(),
rela.get_symbol_table_index()
);
}
let reloc_va = rela.get_offset();
if reloc_va < kernel_min_vaddr {
panic!(
"Relocation target VA 0x{:x} is below kernel base VA 0x{:x}",
reloc_va, kernel_min_vaddr
);
}
let offset_in_image = reloc_va - kernel_min_vaddr;
// Each relocation writes a u64 (8 bytes); ensure the write stays within
// the allocated kernel image to prevent out-of-bounds memory corruption.
if offset_in_image + 8 > kernel_size {
panic!(
"Relocation at VA 0x{:x} (offset 0x{:x}) + 8 exceeds kernel image size 0x{:x}",
reloc_va, offset_in_image, kernel_size
);
}
// Translate the virtual address to the physical address in the loaded image
let site_phys = kernel_phys_base + offset_in_image;
// R_X86_64_RELATIVE: *site = addend + load_bias
// addend is the link-time absolute VA; adding load_bias shifts it to the slid VA
let value = rela.get_addend().wrapping_add(load_bias);
unsafe {
core::ptr::write_unaligned(site_phys as *mut u64, value);
}
applied += 1;
}
info!(" {} relocations applied successfully", applied);
}
#[cfg(feature = "kaslr")]
#[derive(Clone, Copy)]
struct HardwareEntropyCapabilities {
rdseed: bool,
rdrand: bool,
}
/// Detect each hardware entropy instruction independently.
///
/// CPUID leaf 7 is queried only when the maximum basic leaf advertises it.
/// This distinction is load-bearing: RDRAND support does not imply RDSEED
/// support, and executing an unsupported instruction raises #UD in firmware.
#[cfg(feature = "kaslr")]
fn hardware_entropy_capabilities() -> HardwareEntropyCapabilities {
use core::arch::x86_64::{__cpuid, __cpuid_count};
let maximum_basic_leaf = unsafe { __cpuid(0) }.eax;
let rdrand = if maximum_basic_leaf >= 1 {
(unsafe { __cpuid(1) }.ecx & (1 << 30)) != 0
} else {
false
};
let rdseed = if maximum_basic_leaf >= 7 {
(unsafe { __cpuid_count(7, 0) }.ebx & (1 << 18)) != 0
} else {
false
};
HardwareEntropyCapabilities { rdseed, rdrand }
}
/// Probe hardware entropy safely before the permutation consumes additional
/// samples. RDSEED is preferred when present; RDRAND is retained as a
/// fallback. The capability set is carried through the whole permutation so
/// no later sample can execute an instruction that CPUID did not authorize;
/// transient RDSEED backpressure can still fall through to supported RDRAND.
/// A successful sample is deliberately discarded; provenance is published
/// only after the complete unbiased shuffle succeeds.
#[cfg(feature = "kaslr")]
fn probe_entropy_sources() -> Option<HardwareEntropyCapabilities> {
let capabilities = hardware_entropy_capabilities();
let rdseed_ready = capabilities.rdseed && unsafe { next_rdseed_u64() }.is_some();
let rdrand_ready = capabilities.rdrand && unsafe { next_rdrand_u64() }.is_some();
if rdseed_ready || rdrand_ready {
Some(capabilities)
} else {
None
}
}
#[cfg(feature = "kaslr")]
/// Read one RDSEED sample with bounded retries.
///
/// # Safety
///
/// The caller must first verify CPUID.07H:EBX[18]. Executing RDSEED without
/// that capability raises #UD before the bootloader can install an exception
/// handler.
unsafe fn next_rdseed_u64() -> Option<u64> {
for _ in 0..16 {
let value: u64;
let success: u8;
unsafe {
core::arch::asm!(
"rdseed {value}",
"setc {success}",
value = out(reg) value,
success = out(reg_byte) success,
options(nostack, nomem),
);
}
if success == 1 {
return Some(value);
}
}
None
}
#[cfg(feature = "kaslr")]
#[inline]
fn read_tsc_entropy() -> u64 {
let low: u32;
let high: u32;
unsafe {
core::arch::asm!(
"rdtsc",
out("eax") low,
out("edx") high,
options(nostack, nomem, preserves_flags),
);
}
(u64::from(high) << 32) | u64::from(low)
}
#[cfg(feature = "kaslr")]
/// Read one RDRAND sample with bounded retries.
///
/// # Safety
///
/// The caller must first verify CPUID.01H:ECX[30]. Executing RDRAND without
/// that capability raises #UD before the bootloader can install an exception
/// handler.
unsafe fn next_rdrand_u64() -> Option<u64> {
for _ in 0..10 {
let value: u64;
let success: u8;
unsafe {
core::arch::asm!(
"rdrand {value}",
"setc {success}",
value = out(reg) value,
success = out(reg_byte) success,
options(nostack, nomem),
);
}
if success == 1 {
return Some(value);
}
}
None
}
#[cfg(feature = "kaslr")]
fn next_entropy_u64(sources: HardwareEntropyCapabilities) -> Option<u64> {
let tsc = read_tsc_entropy();
if sources.rdseed {
if let Some(seed) = unsafe { next_rdseed_u64() } {
return Some(seed ^ tsc.rotate_left(17));
}
}
if sources.rdrand {
return unsafe { next_rdrand_u64() }.map(|random| random ^ tsc.rotate_left(29));
}
None
}
#[cfg(feature = "kaslr")]
fn uniform_entropy_below(upper: u64, sources: HardwareEntropyCapabilities) -> Option<u64> {
assert!(upper > 0, "entropy bound must be non-zero");
let threshold = upper.wrapping_neg() % upper;
for _ in 0..32 {
let value = next_entropy_u64(sources)?;
if value >= threshold {
return Some(value % upper);
}
}
None
}
/// RF180-32 FIX: build a complete exact-address candidate order.
///
/// With healthy entropy this is an unbiased Fisher-Yates permutation, so the
/// first UEFI-allocatable member is uniform over the viable subset even when
/// much of the configured window is absent. If CPUID, RDRAND, or any shuffle
/// sample fails, discard the partial permutation and search every slot in a
/// deterministic order for availability without claiming KASLR.
fn kernel_placement_order() -> ([u16; KASLR_SLOT_COUNT], bool) {
let mut deterministic = [0u16; KASLR_SLOT_COUNT];
for (index, slot) in deterministic.iter_mut().enumerate() {
*slot = u16::try_from(index).expect("KASLR slot index exceeds u16");
}
#[cfg(feature = "kaslr")]
{
let Some(sources) = probe_entropy_sources() else {
return (deterministic, false);
};
let mut shuffled = deterministic;
for upper in (2..=KASLR_SLOT_COUNT).rev() {
let Some(other) = uniform_entropy_below(upper as u64, sources) else {
return (deterministic, false);
};
shuffled.swap(upper - 1, other as usize);
}
(shuffled, true)
}
#[cfg(not(feature = "kaslr"))]
{
(deterministic, false)
}
}
/// RF180-32 FIX: allocate the kernel at an exact, relocatable address inside
/// the initial high-half physical window.
///
/// UEFI `AllocateType::Address` is the allocation authority. A memory-map
/// snapshot would introduce a stale-snapshot TOCTOU, so this consumes the
/// complete candidate order above and lets exact allocation decide. The first
/// exact allocation wins; no failed candidate publishes state.
fn allocate_kernel_image_pages(
boot_services: &BootServices,
pages: usize,
alloc_bytes: u64,
) -> (u64, u64, bool) {
assert!(
pages > 0,
"ELF kernel allocation must contain at least one page"
);
assert!(alloc_bytes > 0, "ELF kernel allocation must contain bytes");
let (order, randomized) = kernel_placement_order();
for (attempt, slot) in order.into_iter().enumerate() {
let slide = u64::from(slot)
.checked_mul(KASLR_SLIDE_GRANULARITY)
.expect("KASLR slot multiplication overflow");
let candidate = KERNEL_PHYS_BASE
.checked_add(slide)
.expect("KASLR physical base overflow");
let candidate_end = candidate
.checked_add(alloc_bytes)
.expect("KASLR physical extent overflow");
if candidate_end > KERNEL_PHYS_WINDOW_END {
continue;
}
match boot_services.allocate_pages(
AllocateType::Address(candidate),
MemoryType::LOADER_DATA,
pages,
) {
Ok(allocated) => {
if allocated != candidate {
let freed = unsafe { boot_services.free_pages(allocated, pages) };
assert!(
freed.is_ok(),
"UEFI returned and retained an unexpected kernel allocation"
);
panic!("UEFI violated exact-address kernel allocation semantics");
}
#[cfg(debug_assertions)]
if attempt != 0 {
info!(
"Kernel placement used bounded fallback attempt {} of {}",
attempt + 1,
KASLR_SLOT_COUNT
);
}
#[cfg(not(debug_assertions))]
if attempt != 0 {
info!("Kernel placement used bounded exact-address fallback");
}
return (allocated, slide, randomized);
}
Err(error) => match error.status() {
uefi::Status::NOT_FOUND | uefi::Status::OUT_OF_RESOURCES => continue,
uefi::Status::INVALID_PARAMETER => {
panic!("UEFI rejected a validated kernel allocation request")
}
_ => panic!("UEFI returned an unexpected kernel allocation failure"),
},
}
}
panic!(
"FATAL: no contiguous {}-page kernel range exists in the bounded {}-slot high-half window",
pages, KASLR_SLOT_COUNT
);
}
/// Locate the ACPI RSDP via the UEFI configuration table.
///
/// Prefers ACPI 2.0 GUID, falls back to ACPI 1.0 GUID if not available.
/// Returns 0 if RSDP cannot be found.
fn find_rsdp_address(system_table: &SystemTable<Boot>) -> u64 {
// Try ACPI 2.0 first (preferred)
for entry in system_table.config_table() {
if entry.guid == ACPI2_GUID {
let addr = entry.address as usize as u64;
info!("ACPI 2.0 RSDP found at 0x{:x}", addr);
return addr;
}
}
// Fall back to ACPI 1.0
for entry in system_table.config_table() {
if entry.guid == ACPI_GUID {
let addr = entry.address as usize as u64;
info!("ACPI 1.0 RSDP found at 0x{:x}", addr);
return addr;
}
}
info!("ACPI RSDP not found in UEFI configuration table");
0
}
/// P1-1: Read UEFI load options (boot command line) into a fixed-size ASCII buffer.
///
/// UEFI load options are UCS-2 (little-endian u16) encoded. This function
/// down-converts ASCII-range code points to single bytes (non-ASCII → `?`)
/// and truncates to 256 bytes. Returns `(len, buffer)`.
///
/// Must be called **before** `exit_boot_services()` — the LoadedImage
/// protocol becomes inaccessible after that point.
fn read_uefi_cmdline(handle: Handle, system_table: &SystemTable<Boot>) -> (usize, [u8; 256]) {
let mut cmdline = [0u8; 256];
let mut cmdline_len = 0usize;
let boot_services = system_table.boot_services();
if let Ok(loaded_image) = boot_services.open_protocol_exclusive::<LoadedImage>(handle) {
if let Some(bytes) = loaded_image.load_options_as_bytes() {
// UCS-2 little-endian: each character is 2 bytes (lo, hi).
let mut i = 0;
while i + 1 < bytes.len() && cmdline_len < cmdline.len() {
let lo = bytes[i];
let hi = bytes[i + 1];
i += 2;
// Stop at NUL terminator
if lo == 0 && hi == 0 {
break;
}
// ASCII range: hi == 0 && lo <= 0x7F
cmdline[cmdline_len] = if hi == 0 && lo <= 0x7F { lo } else { b'?' };
cmdline_len += 1;
}
}
}
(cmdline_len, cmdline)
}
/// 内存映射信息,传递给内核
#[repr(C)]
pub struct MemoryMapInfo {
pub buffer: u64, // 内存映射缓冲区地址
pub size: usize, // 缓冲区大小
pub descriptor_size: usize, // 每个描述符的大小
pub descriptor_version: u32, // 描述符版本
}
/// 像素格式
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub enum PixelFormat {
/// RGB (8位红, 8位绿, 8位蓝, 8位保留)
Rgb = 0,
/// BGR (8位蓝, 8位绿, 8位红, 8位保留)
Bgr = 1,
/// 未知格式
Unknown = 2,
}
/// 帧缓冲区信息 (GOP framebuffer)
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct FramebufferInfo {
/// 帧缓冲区物理地址
pub base: u64,
/// 帧缓冲区大小(字节)
pub size: usize,
/// 水平分辨率(像素)
pub width: u32,
/// 垂直分辨率(像素)
pub height: u32,
/// 每行的字节数(stride)
pub stride: u32,
/// 像素格式
pub pixel_format: PixelFormat,
}
/// 引导信息结构,传递给内核
#[repr(C)]
pub struct BootInfo {
pub memory_map: MemoryMapInfo,
pub framebuffer: FramebufferInfo,
/// R39-7/RF180-32: relocation slide. Randomization is reported separately
/// in `kaslr_flags`; zero is a valid randomly selected slot.
pub kaslr_slide: u64,
/// ACPI RSDP physical address (from UEFI configuration table)
pub rsdp_address: u64,
/// P1-1: UEFI boot command line length in bytes (ASCII, max 256).
pub cmdline_len: usize,
/// P1-1: UEFI boot command line buffer (ASCII, NUL-padded).
pub cmdline: [u8; 256],
/// R167-C: physical base where the kernel image was loaded
/// (`KERNEL_PHYS_BASE + kaslr_slide`).
pub kernel_phys_base: u64,
/// R167-C: in-memory size of the kernel image in bytes.
pub kernel_phys_size: u64,
/// R167-C: BootInfo ABI version (see `BOOT_INFO_VERSION`).
pub version: u64,
/// RF180-32: placement provenance flags. `BOOT_INFO_KASLR_RANDOMIZED`
/// means the complete candidate order was uniformly randomized; the slide
/// alone never proves KASLR because deterministic relocation is permitted.
pub kaslr_flags: u64,
}
const KERNEL_PAGE_SIZE: u64 = 4096;
const KERNEL_PAGE_EXECUTABLE: u8 = 1 << 0;
const KERNEL_PAGE_WRITABLE: u8 = 1 << 1;
const KERNEL_PAGE_CLAIMED: u8 = 1 << 2;
struct KernelPagePermissions {
phys_base: u64,
pages: Vec<u8>,
}
impl KernelPagePermissions {
fn get(&self, phys_page: u64) -> Option<u8> {
let offset = phys_page.checked_sub(self.phys_base)?;
if !offset.is_multiple_of(KERNEL_PAGE_SIZE) {
return None;
}
let index = usize::try_from(offset / KERNEL_PAGE_SIZE).ok()?;
self.pages.get(index).copied()
}
}
#[entry]
fn efi_main(handle: Handle, mut system_table: SystemTable<Boot>) -> Status {
uefi::helpers::init(&mut system_table).unwrap();
info!("Rust Microkernel Bootloader v0.1");
info!("Initializing...");
// R39-7/RF180-32: get entry, relocation slide, image size, and provenance.
// Codex Review Fix: kernel_size needed for accurate page table setup
let (
entry_point,
kaslr_slide,
kernel_size,
kaslr_randomized,
actual_phys_base,
kernel_permissions,
) = {
let boot_services = system_table.boot_services();
let fs_handle = boot_services
.locate_handle_buffer(uefi::table::boot::SearchType::ByProtocol(
&SimpleFileSystem::GUID,
))
.expect("Failed to locate file system handles");
let fs_handle = fs_handle[0];
let mut fs = boot_services
.open_protocol_exclusive::<SimpleFileSystem>(fs_handle)
.expect("Failed to open file system protocol");
let mut root_dir = fs.open_volume().expect("Failed to open root directory");
info!("Loading kernel...");
let kernel_path = CStr16::from_u16_with_nul(&[
b'k' as u16,
b'e' as u16,
b'r' as u16,
b'n' as u16,
b'e' as u16,
b'l' as u16,
b'.' as u16,
b'e' as u16,
b'l' as u16,
b'f' as u16,
0,
])
.unwrap();
let mut kernel_file = root_dir
.open(kernel_path, FileMode::Read, FileAttribute::empty())
.expect("Failed to open kernel.elf")
.into_regular_file()
.expect("kernel.elf is not a regular file");
let mut info_buffer = [0u8; 512];
let info = kernel_file
.get_info::<FileInfo>(&mut info_buffer)
.expect("Failed to get file info");
let file_size =
usize::try_from(info.file_size()).expect("kernel file size does not fit in usize");
if file_size == 0 || file_size > KERNEL_MAX_FILE_SIZE {
panic!("kernel.elf size outside the supported bootloader bound");
}
let mut kernel_data = Vec::new();
kernel_data
.try_reserve_exact(file_size)
.expect("kernel.elf allocation failed");
kernel_data.resize(file_size, 0);
// 循环读取直到完整读取整个文件
let mut total_read = 0usize;
while total_read < file_size {
let read_size = kernel_file
.read(&mut kernel_data[total_read..])
.expect("Failed to read kernel file");
if read_size == 0 {
// 读取返回0但文件未读完,说明发生了截断
panic!(
"Kernel file read truncated: expected {} bytes, got {} bytes",
file_size, total_read
);
}
total_read += read_size;
}
info!("Kernel loaded: {} bytes", total_read);
info!("Parsing ELF...");
let elf = ElfFile::new(&kernel_data).expect("Failed to parse ELF file");
let entry_point = elf.header.pt2.entry_point();
info!("Entry point: 0x{:x}", entry_point);
assert_eq!(
elf.header.pt1.magic,
[0x7f, 0x45, 0x4c, 0x46],
"Invalid ELF magic"
);
// 首先,计算内核需要的总内存大小
let mut min_addr = u64::MAX;
let mut max_addr = 0u64;
for program_header in elf.program_iter() {
if program_header.get_type() != Ok(Type::Load) {
continue;
}
let virt_addr = program_header.virtual_addr();
// Skip non-kernel LOAD segments (e.g., .rela.dyn metadata at VA 0
// emitted by PIE linking). Only kernel segments reside in the
// high-half virtual range.
if virt_addr < KERNEL_VIRT_BASE {
continue;
}
let mem_size = program_header.mem_size();
if virt_addr < min_addr {
min_addr = virt_addr;
}
// R120-1 FIX: Use checked arithmetic to detect crafted ELF
// headers with wrapping virt_addr + mem_size values.
let end_addr = virt_addr
.checked_add(mem_size)
.expect("ELF LOAD segment virt_addr + mem_size overflow");
if end_addr > max_addr {
max_addr = end_addr;
}
}
// 分配一块连续的内存来容纳整个内核
//
// Text KASLR: The kernel is compiled as a static PIE with
// `-C relocation-model=pie`. The bootloader:
// 1. Builds an unbiased random permutation of every 2 MiB slot when
// RDRAND is healthy; otherwise uses a deterministic full search
// 2. Lets exact UEFI allocation choose the first available slot
// 3. Carries randomization provenance separately from relocation
// 4. Loads LOAD segments into the allocated region
// 5. Applies .rela.dyn R_X86_64_RELATIVE relocations with slide as load_bias
// 6. Jumps to entry_point + slide
// R120-1 FIX: Use checked subtraction to detect empty LOAD segment set
// (where no valid high-half segments were found).
let kernel_size = max_addr
.checked_sub(min_addr)
.expect("ELF LOAD: max_addr < min_addr (no valid kernel segments)")
as usize;
// R120-1 FIX: Use checked arithmetic for page computation to prevent
// wrapping on crafted ELF headers with absurd segment sizes.
let pages = kernel_size
.checked_add(0xFFF)
.expect("ELF kernel size + page alignment overflow")
/ 0x1000;
let alloc_bytes = pages
.checked_mul(0x1000)
.expect("Kernel allocation pages * 0x1000 overflow");
// R119-1 FIX: Gate physical addresses and KASLR slide behind debug_assertions
#[cfg(debug_assertions)]
info!(
"Allocating {} pages ({} bytes) for kernel",
pages, kernel_size
);
#[cfg(not(debug_assertions))]
info!(
"Allocating {} pages ({} bytes) for kernel",
pages, kernel_size
);
let (actual_phys_base, kaslr_slide, kaslr_randomized) = allocate_kernel_image_pages(
boot_services,
pages,
u64::try_from(alloc_bytes).expect("kernel allocation size exceeds u64"),
);
// R119-1 FIX: Gate allocated address and slide behind debug_assertions
#[cfg(debug_assertions)]
info!(
"Kernel memory allocated at 0x{:x} (final slide=0x{:x}, randomized={})",
actual_phys_base, kaslr_slide, kaslr_randomized
);
#[cfg(not(debug_assertions))]
info!(
"Kernel memory allocated ({})",
if kaslr_randomized {
"randomized placement"
} else if kaslr_slide != 0 {
"deterministic availability relocation"
} else {
"fixed placement"
}
);
// R120-1 FIX: Zero the entire page-aligned allocation (alloc_bytes),
// not just kernel_size. This ensures the tail bytes (up to 4095) in
// the last page are zeroed, preventing stale UEFI memory from being
// mapped into the kernel's high-half virtual address range.
unsafe {
core::ptr::write_bytes(actual_phys_base as *mut u8, 0, alloc_bytes);
}
if !actual_phys_base.is_multiple_of(KERNEL_PAGE_SIZE) {
panic!("UEFI kernel allocation is not page aligned");
}
let mut page_permissions = Vec::new();
page_permissions
.try_reserve_exact(pages)
.expect("kernel page-permission allocation failed");
page_permissions.resize(pages, 0);
let mut kernel_permissions = KernelPagePermissions {
phys_base: actual_phys_base,
pages: page_permissions,
};
// 加载所有程序段 to the exact UEFI-selected physical address.
for program_header in elf.program_iter() {
if program_header.get_type() != Ok(Type::Load) {
continue;
}
let virt_addr = program_header.virtual_addr();
// Skip non-kernel LOAD segments (e.g., .rela.dyn metadata at VA 0)
if virt_addr < KERNEL_VIRT_BASE {
continue;
}
let mem_size = program_header.mem_size();
let file_size = program_header.file_size();
let file_offset = program_header.offset();
// A zero-sized LOAD contributes no image bytes or permissions;
// skip it before the inclusive page-range calculation so
// `mem_size - 1` cannot accidentally classify the preceding page.
if mem_size == 0 {
continue;
}
// R188-U55-2 FIX: ELF metadata is attacker-controlled at the boot
// boundary. A LOAD segment may not copy more initialized bytes
// than its destination reservation, and every arithmetic step must
// remain inside the exact page-aligned image allocation.
if file_size > mem_size {
panic!("ELF LOAD file_size exceeds mem_size");
}
let mem_size_usize =
usize::try_from(mem_size).expect("ELF LOAD mem_size does not fit in usize");
let file_size_usize =
usize::try_from(file_size).expect("ELF LOAD file_size does not fit in usize");
// R24-10 fix: Validate that file_offset + file_size doesn't exceed kernel_data bounds
// A malformed ELF could have segments pointing beyond the file, causing OOB read
let file_end = file_offset
.checked_add(file_size)
.expect("ELF segment offset+size overflow");
if file_end as usize > kernel_data.len() {
panic!(
"ELF segment out of bounds: offset=0x{:x}, file_size=0x{:x}, file_len=0x{:x}",
file_offset,
file_size,
kernel_data.len()
);
}
// 计算物理地址:虚拟地址 - 虚拟基址 + 物理基址
// 虚拟基址是 min_addr (0xffffffff80000000),物理基址是 actual_phys_base (0x100000)
let segment_offset = virt_addr
.checked_sub(min_addr)
.expect("ELF LOAD virtual address below image base");
let phys_addr = actual_phys_base
.checked_add(segment_offset)
.expect("ELF LOAD physical address overflow");
let image_end = actual_phys_base
.checked_add(u64::try_from(alloc_bytes).expect("allocation size overflow"))
.expect("ELF image allocation end overflow");
let segment_mem_end = phys_addr
.checked_add(mem_size)
.expect("ELF LOAD destination overflow");
let segment_file_end = phys_addr
.checked_add(file_size)
.expect("ELF LOAD file destination overflow");
if phys_addr < actual_phys_base
|| segment_mem_end > image_end
|| segment_file_end > image_end
{
panic!("ELF LOAD destination exceeds allocated image");
}
// Classify final permissions at the architectural 4 KiB page
// granularity. The kernel's legitimate text/data boundary can
// share a 2 MiB bucket, especially with a 64 KiB KASLR slide; a
// huge-page-only classifier would reject that image or force the
// whole bucket W+X. Mixed buckets are split into 4 KiB leaves
// when the new page tables are built below.
let first_page = usize::try_from(
phys_addr
.checked_sub(actual_phys_base)
.expect("ELF LOAD starts below kernel allocation")
/ KERNEL_PAGE_SIZE,
)
.expect("ELF LOAD first page index overflow");
let last_page = usize::try_from(
segment_mem_end
.saturating_sub(1)
.checked_sub(actual_phys_base)
.expect("ELF LOAD ends below kernel allocation")
/ KERNEL_PAGE_SIZE,
)
.expect("ELF LOAD last page index overflow");
if last_page >= kernel_permissions.pages.len() {
panic!("ELF LOAD permission range exceeds allocated image");
}
let segment_executable = program_header.flags().is_execute();
let segment_writable = program_header.flags().is_write();
let segment_permissions = KERNEL_PAGE_CLAIMED
| if segment_executable {
KERNEL_PAGE_EXECUTABLE
} else {
0
}
| if segment_writable {
KERNEL_PAGE_WRITABLE
} else {
0
};
for page_index in first_page..=last_page {
let current = kernel_permissions.pages[page_index];
if (segment_executable && current & KERNEL_PAGE_WRITABLE != 0)
|| (segment_writable && current & KERNEL_PAGE_EXECUTABLE != 0)
{
panic!("ELF LOAD segments require a writable/executable 4 KiB page");
}
kernel_permissions.pages[page_index] = current | segment_permissions;
}
// 清零整个段内存区域(包括.bss)
unsafe {
let dest = phys_addr as *mut u8;
core::ptr::write_bytes(dest, 0, mem_size_usize);
}
// 复制段数据(file_size可能小于mem_size,剩余部分已清零)
if file_size > 0 {
unsafe {
let dest = phys_addr as *mut u8;
let src = kernel_data.as_ptr().add(file_offset as usize);
core::ptr::copy_nonoverlapping(src, dest, file_size_usize);
}
}
// R119-1 FIX: Physical addresses reveal KASLR slide; gate behind debug_assertions.
// Virtual addresses are link-time public and safe to log.
#[cfg(debug_assertions)]
info!(
"Loaded segment: virt=0x{:x}, phys=0x{:x}, filesz=0x{:x}, memsz=0x{:x}",
virt_addr, phys_addr, file_size, mem_size
);
#[cfg(not(debug_assertions))]
info!(
"Loaded segment: virt=0x{:x}, filesz=0x{:x}, memsz=0x{:x}",
virt_addr, file_size, mem_size
);
}
// R119-1 FIX: Verification dump reveals physical load address; gate behind
// debug_assertions. In release, just do a volatile read to confirm accessibility.
#[cfg(debug_assertions)]
unsafe {
let kernel_start = actual_phys_base as *const u8;
let first_bytes = core::slice::from_raw_parts(kernel_start, 16);
info!(
"First 16 bytes at phys 0x{:x}: {:x?}",
actual_phys_base, first_bytes
);
}
#[cfg(not(debug_assertions))]
{
let kernel_start = actual_phys_base as *const u8;
let _ = unsafe { core::ptr::read_volatile(kernel_start) };
info!("Kernel image load verified");
}
for permissions in &kernel_permissions.pages {
if permissions & KERNEL_PAGE_EXECUTABLE != 0 && permissions & KERNEL_PAGE_WRITABLE != 0
{
panic!("ELF LOAD segments require a writable/executable 4 KiB page");
}
}
// Text KASLR: Apply PIE relocations so absolute addresses in the
// kernel image point to the correct (slid) virtual addresses.
// This is a no-op when kaslr_slide == 0 and no .rela.dyn section exists.
apply_rela_dyn_relocations(
&elf,