-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlib.rs
More file actions
559 lines (514 loc) · 19.7 KB
/
Copy pathlib.rs
File metadata and controls
559 lines (514 loc) · 19.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
//! Security Hardening Module for Zero-OS
//!
//! This module provides enterprise-grade security hardening features:
//!
//! - **W^X Enforcement**: Validates that no memory pages are both writable and executable
//! - **Identity Map Cleanup**: Removes or hardens the bootloader's identity mapping
//! - **NX Enforcement**: Ensures data pages have the No-Execute bit set
//! - **Hardware RNG**: RDRAND/RDSEED integration with CSPRNG (ChaCha20)
//! - **kptr Guard**: Obfuscates kernel pointers before logging to prevent KASLR bypass
//! - **Spectre/Meltdown Mitigations**: IBRS/IBPB/STIBP initialization
//! - **Runtime Security Tests**: Lightweight self-tests for core protections
//!
//! # Security Design Principles
//!
//! 1. **Defense in Depth**: Multiple layers of protection
//! 2. **Fail-Secure**: Errors result in more restrictive states
//! 3. **Least Privilege**: Minimal permissions by default
//! 4. **Audit Trail**: All security events are logged
//!
//! # Usage
//!
//! ```rust,ignore
//! let config = SecurityConfig::default();
//! let mut allocator = FrameAllocator::new();
//! let report = security::init(config, &mut allocator)?;
//! ```
#![no_std]
#![allow(clippy::empty_line_after_doc_comments)]
#![allow(clippy::empty_line_after_outer_attr)]
#![allow(unused_doc_comments)]
#![allow(dead_code)]
#![allow(clippy::missing_safety_doc)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::fn_to_numeric_cast)]
#![allow(clippy::identity_op)]
#![allow(clippy::derivable_impls)]
#![allow(clippy::collapsible_if)]
#![allow(clippy::manual_range_contains)]
#![allow(clippy::manual_memcpy)]
#![allow(function_casts_as_integer)]
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::manual_is_multiple_of)]
#![allow(clippy::manual_div_ceil)]
#![allow(clippy::doc_overindented_list_items)]
#![allow(clippy::needless_range_loop)]
#![feature(abi_x86_interrupt)]
extern crate alloc;
extern crate drivers;
#[macro_use]
extern crate klog;
pub mod fips;
pub mod kaslr;
pub mod kptr;
pub mod memory_hardening;
pub mod rng;
pub mod spectre;
pub mod tests;
pub mod wxorx;
use mm::memory::FrameAllocator;
use x86_64::VirtAddr;
// Re-export public types
pub use kaslr::{
enable_partial_kaslr, get_kernel_layout, init as init_kaslr, install_kpti_context,
is_kaslr_enabled, is_kpti_enabled, is_partial_kaslr_enabled, kernel_stack_slide,
partial_kaslr_status, randomized_mmap_base, text_kaslr_status, BootKaslrState, KernelLayout,
KptiContext, PartialKaslrFeature, PartialKaslrStatus, TextKaslrStatus, TrampolineDesc,
KERNEL_PHYS_BASE, KERNEL_VIRT_BASE,
};
pub use kptr::{kptr_strongly_seeded, KptrGuard};
pub use memory_hardening::{
CleanupOutcome, HardeningError, IdentityCleanupStrategy, NxEnforcementSummary,
};
// R141-8 FIX: Removed ChaCha20Rng and rdrand64_early from public exports to
// enforce the FIPS boundary. External callers use fill_random() for random bytes
// and chacha20_xor_keystream() for keyed encryption.
// R149-5 FIX: Removed random_u32, random_u64 from public re-exports to match
// FIPS boundary (INV-FIPS-01). External callers use fill_random() instead.
pub use rng::{chacha20_xor_keystream, fill_random, rdrand_available, try_fill_random, RngError};
pub use spectre::{MitigationStatus, SpectreError, VulnerabilityInfo};
pub use tests::{run_security_tests, SecurityTest, TestContext, TestReport, TestResult};
pub use wxorx::{PageLevel, ValidationSummary, Violation, WxorxError};
/// Security subsystem error types
#[derive(Debug)]
pub enum SecurityError {
/// Memory hardening error (identity map, NX enforcement)
Memory(HardeningError),
/// W^X validation error
Wxorx(WxorxError),
/// Random number generator error
Rng(RngError),
/// Spectre/Meltdown mitigation error
Spectre(SpectreError),
}
impl From<HardeningError> for SecurityError {
fn from(err: HardeningError) -> Self {
SecurityError::Memory(err)
}
}
impl From<WxorxError> for SecurityError {
fn from(err: WxorxError) -> Self {
SecurityError::Wxorx(err)
}
}
impl From<RngError> for SecurityError {
fn from(err: RngError) -> Self {
SecurityError::Rng(err)
}
}
impl From<SpectreError> for SecurityError {
fn from(err: SpectreError) -> Self {
SecurityError::Spectre(err)
}
}
/// Security hardening configuration
#[derive(Debug, Clone, Copy)]
pub struct SecurityConfig {
/// Physical memory offset for page table access
pub phys_offset: VirtAddr,
/// Strategy for cleaning up identity mapping
pub cleanup_strategy: IdentityCleanupStrategy,
/// Whether to enforce NX bit on data pages
pub enforce_nx: bool,
/// Whether to validate W^X policy
pub validate_wxorx: bool,
/// Whether to initialize hardware RNG and CSPRNG
pub initialize_rng: bool,
/// Whether to panic on W^X violation (strict mode)
pub strict_wxorx: bool,
/// Whether to enable kernel pointer obfuscation
pub enable_kptr_guard: bool,
/// Whether to enable Spectre/Meltdown mitigations
pub enable_spectre_mitigations: bool,
/// Whether to run security self-tests
pub run_security_tests: bool,
}
impl Default for SecurityConfig {
fn default() -> Self {
SecurityConfig {
phys_offset: VirtAddr::new(mm::page_table::PHYSICAL_MEMORY_OFFSET),
cleanup_strategy: IdentityCleanupStrategy::RemoveWritable,
enforce_nx: true,
validate_wxorx: true,
initialize_rng: true,
strict_wxorx: false, // Don't panic by default, just warn
enable_kptr_guard: true,
enable_spectre_mitigations: true,
run_security_tests: false, // Disable by default, enable in strict mode
}
}
}
impl SecurityConfig {
/// Create a strict security configuration (production recommended)
pub fn strict() -> Self {
SecurityConfig {
strict_wxorx: true,
run_security_tests: true,
..Self::default()
}
}
/// Create a permissive configuration (for debugging)
pub fn permissive() -> Self {
SecurityConfig {
enforce_nx: false,
validate_wxorx: false,
strict_wxorx: false,
enable_kptr_guard: false,
enable_spectre_mitigations: false,
run_security_tests: false,
..Self::default()
}
}
}
/// Security hardening report
#[derive(Debug)]
pub struct SecurityReport {
/// Identity map cleanup outcome
pub identity_cleanup: CleanupOutcome,
/// NX enforcement summary (if enabled)
pub nx_summary: Option<NxEnforcementSummary>,
/// W^X validation summary (if enabled)
pub wxorx_summary: Option<ValidationSummary>,
/// Whether CSPRNG is ready
pub rng_ready: bool,
/// Whether kptr guard is active
pub kptr_guard_active: bool,
/// Spectre/Meltdown mitigation status
pub spectre_status: Option<MitigationStatus>,
/// Security test report (if tests were run)
pub test_report: Option<TestReport>,
/// Total security violations detected (0 = secure)
pub total_violations: usize,
}
impl SecurityReport {
/// Create an empty report
fn empty() -> Self {
SecurityReport {
identity_cleanup: CleanupOutcome::Skipped,
nx_summary: None,
wxorx_summary: None,
rng_ready: false,
kptr_guard_active: false,
spectre_status: None,
test_report: None,
total_violations: 0,
}
}
/// Check if the system is in a secure state
/// R178-L5 FIX: Consider skipped protections and test warnings
pub fn is_secure(&self) -> bool {
// Tests must pass (no failures) and have no warnings
let tests_ok = self.test_report.as_ref().map(|t| t.ok()).unwrap_or(false);
// Identity cleanup must not be skipped
let identity_ok = !matches!(self.identity_cleanup, CleanupOutcome::Skipped);
// NX/W^X must be enabled (not None)
let nx_enabled = self.nx_summary.is_some();
let wxorx_enabled = self.wxorx_summary.is_some();
// RF178-29 FIX: Presence alone is not a mitigation guarantee.
let spectre_enabled = self
.spectre_status
.as_ref()
.map(MitigationStatus::hardened)
.unwrap_or(false);
self.total_violations == 0
&& self.rng_ready
&& self.kptr_guard_active
&& tests_ok
&& identity_ok
&& nx_enabled
&& wxorx_enabled
&& spectre_enabled
}
/// Print the security report to console
pub fn print(&self) {
klog!(Info, "=== Security Hardening Report ===");
klog!(Info, "Identity Map: {:?}", self.identity_cleanup);
if let Some(ref nx) = self.nx_summary {
klog!(Info, "NX Enforcement:");
klog!(Info, " Text (R-X): {} pages", nx.text_rx_pages);
klog!(Info, " RoData (R--): {} pages", nx.ro_pages);
klog!(Info, " Data (RW-): {} pages", nx.data_nx_pages);
}
if let Some(ref wx) = self.wxorx_summary {
klog!(Info, "W^X Validation:");
klog!(Info, " Scanned: {} entries", wx.scanned_entries);
klog!(Info, " Violations: {}", wx.violations);
}
klog!(
Info,
"CSPRNG: {}",
if self.rng_ready { "Ready" } else { "Not Ready" }
);
klog!(
Info,
"kptr Guard: {}",
if self.kptr_guard_active {
"Active"
} else {
"Disabled"
}
);
if let Some(ref spectre) = self.spectre_status {
klog!(Info, "Spectre/Meltdown Mitigations:");
klog!(
Info,
" IBRS: {} (supported: {})",
if spectre.ibrs_enabled {
"enabled"
} else {
"disabled"
},
spectre.ibrs_supported
);
klog!(
Info,
" STIBP: {} (supported: {})",
if spectre.stibp_enabled {
"enabled"
} else {
"disabled"
},
spectre.stibp_supported
);
klog!(Info, " IBPB: supported: {}", spectre.ibpb_supported);
klog!(Info, " Status: {}", spectre.summary());
}
if let Some(ref tests) = self.test_report {
klog!(Info, "Security Self-Tests:");
klog!(
Info,
" Passed: {}, Failed: {}, Warnings: {}, Deferred: {}, Skipped: {}",
tests.passed,
tests.failed,
tests.warnings,
tests.deferred,
tests.skipped
);
}
klog!(Info, "Total Violations: {}", self.total_violations);
klog!(
Info,
"Overall Status: {}",
if self.is_secure() {
"SECURE"
} else {
"WARNINGS"
}
);
}
}
/// Initialize the security subsystem
///
/// This function performs the following hardening steps:
/// 1. Initialize kptr guard for pointer obfuscation
/// 2. Clean up or harden the identity mapping
/// 3. Enforce NX bit on data pages (if enabled)
/// 4. Validate W^X policy (if enabled)
/// 5. Initialize hardware RNG and CSPRNG (if enabled)
/// 6. Enable Spectre/Meltdown mitigations (if enabled)
/// 7. Run security self-tests (optional)
///
/// # Arguments
///
/// * `config` - Security configuration
/// * `frame_allocator` - Physical frame allocator for page table modifications
///
/// # Returns
///
/// A security report on success, or an error if critical hardening fails.
///
/// # Security Note
///
/// This function should be called early in kernel initialization,
/// after memory management but before enabling interrupts.
pub fn init(
config: SecurityConfig,
frame_allocator: &mut FrameAllocator,
) -> Result<SecurityReport, SecurityError> {
let mut report = SecurityReport::empty();
// RF178-23 FIX: Publish the selected boot policy before BSP/AP or
// scheduler mitigation hooks can run.
spectre::set_policy_enabled(config.enable_spectre_mitigations);
klog_always!(" Initializing security hardening...");
// Step 1: Initialize kptr guard (early, to protect all subsequent logs)
if config.enable_kptr_guard {
klog_always!(" [1/7] Enabling kptr guard...");
kptr::init();
kptr::enable();
report.kptr_guard_active = true;
} else {
klog_always!(" [1/7] kptr guard: SKIPPED (disabled)");
kptr::disable();
}
// Step 2: Clean up identity mapping
klog_always!(
" [2/7] Cleaning identity map ({:?})...",
config.cleanup_strategy
);
let cleanup =
memory_hardening::cleanup_identity_map(config.phys_offset, config.cleanup_strategy)?;
report.identity_cleanup = cleanup;
// Step 3: Enforce NX on kernel data sections
if config.enforce_nx {
klog_always!(" [3/7] Enforcing NX bit on data pages...");
let nx_summary =
memory_hardening::enforce_nx_for_kernel(config.phys_offset, frame_allocator)?;
report.nx_summary = Some(nx_summary);
} else {
klog_always!(" [3/7] NX enforcement: SKIPPED (disabled)");
}
// Step 4: Validate W^X policy
if config.validate_wxorx {
klog_always!(" [4/7] Validating W^X policy...");
match wxorx::validate_active(config.phys_offset) {
Ok(summary) => {
// X-3 FIX: Ok now means zero violations by contract
report.wxorx_summary = Some(summary);
}
Err(WxorxError::PolicyViolation(summary)) => {
// X-3 FIX: PolicyViolation now contains the full summary
report.wxorx_summary = Some(summary);
report.total_violations += summary.violations;
if config.strict_wxorx {
klog!(
Error,
" {} W^X violation(s) detected (strict mode)",
summary.violations
);
return Err(SecurityError::Wxorx(WxorxError::PolicyViolation(summary)));
}
klog!(
Warn,
" WARNING: {} W^X violation(s) detected",
summary.violations
);
}
Err(WxorxError::Violation(v)) => {
report.total_violations += 1;
report.wxorx_summary = Some(ValidationSummary {
scanned_entries: 0,
violations: 1,
first_violation: Some(v),
});
if config.strict_wxorx {
klog!(
Error,
" W^X violation at {:?} (strict mode)",
v.virt_base
);
return Err(SecurityError::Wxorx(WxorxError::Violation(v)));
}
klog!(Warn, " WARNING: W^X violation at {:?}", v.virt_base);
}
Err(e) => {
if config.strict_wxorx {
klog!(Error, " W^X validation error: {:?} (strict mode)", e);
return Err(SecurityError::Wxorx(e));
}
klog!(Warn, " WARNING: W^X validation error: {:?}", e);
}
}
} else {
klog_always!(" [4/7] W^X validation: SKIPPED (disabled)");
}
// Step 5: Initialize hardware RNG and CSPRNG
if config.initialize_rng {
klog_always!(" [5/7] Initializing hardware RNG and CSPRNG...");
match rng::init_global() {
Ok(()) => {
report.rng_ready = true;
// Verify RNG is working with a test read
match rng::random_u64() {
Ok(_) => {
klog_always!(" CSPRNG verified operational");
// Reseed kptr guard with strong entropy
if config.enable_kptr_guard {
kptr::reseed_from_entropy();
}
}
Err(e) => {
klog!(Warn, " WARNING: CSPRNG verification failed: {:?}", e);
report.rng_ready = false;
}
}
}
Err(e) => {
klog!(Warn, " WARNING: RNG initialization failed: {:?}", e);
report.rng_ready = false;
}
}
} else {
klog_always!(" [5/7] RNG initialization: SKIPPED (disabled)");
}
// Step 6: Enable Spectre/Meltdown mitigations
if config.enable_spectre_mitigations {
klog_always!(" [6/7] Enabling Spectre/Meltdown mitigations...");
match spectre::init() {
Ok(status) => {
klog_always!(" Mitigations: {}", status.summary());
if !status.hardened() {
klog!(Warn, " WARNING: Retpoline required but not available");
report.total_violations += 1;
}
report.spectre_status = Some(status);
}
Err(e) => {
klog!(Warn, " WARNING: Spectre mitigations failed: {:?}", e);
// Don't increment violations for unsupported CPUs
if !matches!(e, SpectreError::Unsupported(_)) {
report.total_violations += 1;
}
}
}
} else {
klog_always!(" [6/7] Spectre mitigations: SKIPPED (disabled)");
}
// Step 7: Run security self-tests (optional)
if config.run_security_tests {
klog_always!(" [7/7] Running security self-tests...");
let ctx = TestContext {
phys_offset: config.phys_offset,
};
let test_report = tests::run_security_tests(&ctx);
if test_report.failed > 0 {
klog!(
Warn,
" WARNING: {} security tests failed",
test_report.failed
);
report.total_violations += test_report.failed;
} else if test_report.ok() {
klog_always!(" All {} tests passed", test_report.passed);
} else {
klog_always!(" Security tests: {} passed, {} warnings, {} deferred, {} skipped; qualification pending", test_report.passed, test_report.warnings, test_report.deferred, test_report.skipped);
}
test_report.emit_evidence("SECURITY-BOOT");
report.test_report = Some(test_report);
} else {
klog_always!(" [7/7] Security self-tests: SKIPPED (disabled)");
}
Ok(report)
}
/// Quick security check (for runtime validation)
///
/// This function performs a lightweight W^X check on the current page tables.
/// It can be called periodically to detect runtime violations.
pub fn quick_check(phys_offset: VirtAddr) -> Result<bool, SecurityError> {
match wxorx::validate_active(phys_offset) {
// X-3 FIX: Ok now means zero violations by contract
Ok(_) => Ok(true),
// X-3 FIX: PolicyViolation means violations found
Err(WxorxError::PolicyViolation(_)) => Ok(false),
Err(e) => Err(SecurityError::Wxorx(e)),
}
}