-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlib.rs
More file actions
2300 lines (2039 loc) · 82.2 KB
/
Copy pathlib.rs
File metadata and controls
2300 lines (2039 loc) · 82.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
//! Zero-OS G.2 Live Patching (no_std)
//!
//! This crate implements a minimal livepatch mechanism:
//! - Patch authenticity check: **ECDSA P-256 + SHA-256** (KAT-gated verification)
//! - Detour: overwrite first byte of a target function with **INT3 (0xCC)**
//! - Redirect: a **#BP** handler rewrites `RIP` to the patch handler address
//! - Lifecycle: register / enable / disable with an explicit state machine
//!
//! # Patch image format
//!
//! All integers are little-endian. Signature is a fixed 64-byte `(r||s)` blob.
//!
//! ```text
//! 0x00 4 magic = "ZLP2"
//! 0x04 2 version = 1
//! 0x06 2 header_len = 72
//! 0x08 4 flags (bit 0: HAS_DEPS)
//! 0x0C 4 reserved0 = 0
//! 0x10 8 target_addr (kernel VA of function entry)
//! 0x18 8 handler_addr (kernel VA; 0 means handler is in patch_data)
//! 0x20 4 patch_data_len (bytes)
//! 0x24 4 reserved1 = 0
//! 0x28 32 patch_data_sha256 (SHA-256 of patch_data)
//! 0x48 64 signature (ECDSA P-256, r||s; covers header||patch_data)
//! 0x88 .. patch_data (dep table if HAS_DEPS + handler code blob)
//! ```
//!
//! # SMP safety
//!
//! - The detour write is a **single-byte atomic store**.
//! - The handler lookup is lock-free (fixed patch table; atomics only).
//! - Cross-core instruction stream synchronization is delegated to `KernelOps::sync_cores()`.
#![no_std]
#![feature(abi_x86_interrupt)]
extern crate alloc;
#[macro_use]
extern crate klog;
// R93-2 FIX: Never allow the insecure ECDSA stub in production builds.
// R94-7 FIX: Use `not(debug_assertions)` instead of `feature = "release"`.
// Cargo's `--release` flag does NOT automatically enable a "release" feature,
// but it DOES disable debug_assertions. This ensures the guard actually fires
// in production builds regardless of explicit feature configuration.
#[cfg(all(feature = "insecure-ecdsa-stub", not(any(test, debug_assertions))))]
compile_error!("livepatch: feature `insecure-ecdsa-stub` must not be enabled in release builds");
use alloc::boxed::Box;
use alloc::vec;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering};
use spin::{Mutex, Once};
use x86_64::structures::idt::InterruptStackFrame;
use x86_64::VirtAddr;
// Expose only the KAT function for compliance module, not the full verification API.
// This minimizes API surface while allowing FIPS self-tests to use the existing ECDSA KAT.
pub mod ecdsa_p256;
// ============================================================================
// Public constants / syscall numbers
// ============================================================================
pub const SYS_KPATCH_LOAD: u64 = 509;
pub const SYS_KPATCH_ENABLE: u64 = 510;
pub const SYS_KPATCH_DISABLE: u64 = 511;
pub const SYS_KPATCH_UNLOAD: u64 = 512;
/// P1-4: Enable all loaded patches in topological dependency order.
pub const SYS_KPATCH_ENABLE_ALL: u64 = 514;
/// P1-4: Disable all enabled patches in reverse topological dependency order.
pub const SYS_KPATCH_DISABLE_ALL: u64 = 515;
// ============================================================================
// Error model (minimal errno subset)
// ============================================================================
#[repr(i64)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Errno {
EPERM = -1,
ENOENT = -2,
E2BIG = -7,
ENOMEM = -12,
EACCES = -13,
EFAULT = -14,
EBUSY = -16,
EEXIST = -17,
EINVAL = -22,
ENOSYS = -38,
EOVERFLOW = -75,
EALREADY = -114,
}
impl Errno {
#[inline]
pub const fn as_i64(self) -> i64 {
self as i64
}
}
// ============================================================================
// Kernel hooks
// ============================================================================
/// Kernel-provided operations required by the livepatch module.
pub trait KernelOps: Sync {
/// Returns true if the calling task is privileged (CAP_ADMIN or equivalent).
fn is_privileged(&self) -> bool;
// ========================================================================
// R102-13 FIX: LSM hook delegates for livepatch operations.
//
// The livepatch crate does not depend on the `lsm` crate directly.
// Instead, the KernelOps implementor (in kernel_core or the main kernel)
// is responsible for calling `lsm::hook_kpatch_*` and translating
// `LsmError` to `Errno`. R103-5 FIX: Default implementations now DENY
// all operations (fail-closed). Implementors must explicitly wire in
// the LSM hooks to permit livepatch operations.
// ========================================================================
/// LSM check before loading a livepatch module.
///
/// Implementors should call `lsm::hook_kpatch_load(task, patch_len)`
/// and return `Err(Errno::EPERM)` on denial.
///
/// R103-5 FIX: Default to `Err(EPERM)` (fail-closed).
///
/// The previous default `Ok(())` silently permitted all livepatch operations
/// whenever the KernelOps implementor did not override these methods. Since
/// livepatch introduces arbitrary kernel code, the fail-safe default must
/// DENY operations until the implementor explicitly wires in the LSM hooks.
fn check_lsm_kpatch_load(&self, _patch_len: usize) -> Result<(), Errno> {
Err(Errno::EPERM)
}
/// LSM check before enabling a livepatch.
///
/// R103-5 FIX: Fail-closed default.
fn check_lsm_kpatch_enable(&self, _patch_id: u64) -> Result<(), Errno> {
Err(Errno::EPERM)
}
/// LSM check before disabling a livepatch.
///
/// R103-5 FIX: Fail-closed default.
fn check_lsm_kpatch_disable(&self, _patch_id: u64) -> Result<(), Errno> {
Err(Errno::EPERM)
}
/// LSM check before unloading a livepatch.
///
/// R103-5 FIX: Fail-closed default.
fn check_lsm_kpatch_unload(&self, _patch_id: u64) -> Result<(), Errno> {
Err(Errno::EPERM)
}
/// Copy from user memory into a kernel buffer.
///
/// # Safety
/// Implementations must validate that `user_src..user_src+len` is readable user memory.
unsafe fn copy_from_user(&self, dst: *mut u8, user_src: usize, len: usize)
-> Result<(), Errno>;
/// Allocate an executable region and return its kernel VA.
///
/// # Safety
///
/// SECURITY: The returned mapping must be kernel-only (not user-accessible).
/// Prefer W^X: allocate RW, copy bytes, then transition to RX via `seal_exec`.
unsafe fn alloc_exec(&self, len: usize) -> Result<usize, Errno>;
/// Tighten permissions on an exec region after initialization (e.g., RW->RX).
///
/// # Safety
///
/// R93-11 FIX: This method is now REQUIRED. A no-op implementation would silently
/// violate W^X, leaving handler memory both writable and executable.
/// Implementations MUST transition the region from RW to RX.
unsafe fn seal_exec(&self, addr: usize, len: usize) -> Result<(), Errno>;
/// Free an executable region previously allocated with `alloc_exec`.
///
/// # Safety
///
/// Caller must ensure the region is no longer in use and addr/len match a prior alloc_exec.
unsafe fn free_exec(&self, addr: usize, len: usize);
/// Temporarily make kernel text writable for patching.
///
/// # Safety
///
/// SECURITY: Must only permit kernel text pages, and must be safe against
/// concurrent calls (or callers must serialize externally).
unsafe fn make_text_writable(&self, addr: usize, len: usize) -> Result<(), Errno>;
/// Restore .text to read-only+executable after patching.
///
/// # Safety
///
/// Caller must ensure the range matches a prior make_text_writable call.
unsafe fn make_text_readonly(&self, addr: usize, len: usize);
/// Ensure instruction stream synchronization across all CPUs after text modification.
///
/// SECURITY: After this returns, no CPU may execute stale instruction bytes from
/// the modified region. Implementations must use IPI + serializing instructions.
fn sync_cores(&self);
/// Flush/serialize instruction fetch for the given region.
fn flush_icache(&self, addr: usize, len: usize);
}
static KERNEL_OPS: Once<&'static dyn KernelOps> = Once::new();
/// KSA-009: live patching is unsupported until kernel hooks, provisioned trust
/// keys and cross-core patch/rollback validation are supplied together.
pub const SUPPORTED: bool = false;
pub const UNSUPPORTED_REASON: &str = "kernel hooks and production trust keys are not provisioned";
/// Initialize the livepatch module and install kernel hooks.
pub fn init(ops: &'static dyn KernelOps) -> Result<(), Errno> {
if !SUPPORTED {
return Err(Errno::ENOSYS);
}
let _ = KERNEL_OPS.call_once(|| ops);
let _ = PATCH_TABLE.call_once(init_patch_table);
Ok(())
}
// ============================================================================
// P1-4: Tamper-evident audit integration
//
// Livepatch must not depend on the `audit` crate directly to avoid circular
// dependencies. Instead, the kernel wires in a callback after audit::init()
// so livepatch lifecycle events (load/enable/disable/unload) are recorded in
// the hash-chained audit log.
// ============================================================================
/// Callback signature for emitting tamper-evident audit events.
///
/// # Arguments
/// * `action` — 0=load, 1=enable, 2=disable, 3=unload
/// * `patch_id` — Patch identifier returned by `kpatch_load`
/// * `target_addr` — Target function address
/// * `extra` — Action-specific data: \[handler_addr, dep_count, 0\] for load; \[0;3\] otherwise
/// * `timestamp` — TSC value at the time of the transition
pub type LivepatchAuditFn =
fn(action: u64, patch_id: u64, target_addr: u64, extra: [u64; 3], timestamp: u64);
/// Registered audit callback. Protected by `Mutex` for IRQ-safe access.
static LIVEPATCH_AUDIT_CB: Mutex<Option<LivepatchAuditFn>> = Mutex::new(None);
/// Register the tamper-evident audit callback for livepatch lifecycle events.
///
/// Called from `main.rs` after the audit subsystem is initialized.
pub fn register_audit_callback(cb: LivepatchAuditFn) {
*LIVEPATCH_AUDIT_CB.lock() = Some(cb);
}
/// Emit a livepatch lifecycle audit event via the registered callback.
///
/// Copies the function pointer out of the lock before invoking it to avoid
/// holding the callback lock across the audit subsystem call path.
#[inline]
fn emit_livepatch_audit(action: u64, patch_id: u64, target_addr: u64, extra: [u64; 3]) {
let cb = { *LIVEPATCH_AUDIT_CB.lock() };
if let Some(emit) = cb {
emit(action, patch_id, target_addr, extra, read_tsc());
}
}
/// R101-4 FIX: Check whether all ECDSA key slots are empty placeholders.
///
/// Returns `true` if all key slots contain all-zero bytes, meaning livepatch
/// signature verification is non-functional. The kernel entry point should call
/// this at boot and emit a warning via its own `kprintln!` macro.
pub fn has_placeholder_keys() -> bool {
TRUSTED_P256_PUBKEYS_UNCOMPRESSED
.iter()
.all(|k| k.iter().all(|&b| b == 0))
}
#[inline]
fn ops() -> Result<&'static dyn KernelOps, Errno> {
if !SUPPORTED {
return Err(Errno::ENOSYS);
}
KERNEL_OPS.get().copied().ok_or(Errno::ENOSYS)
}
// ============================================================================
// Patch format constants
// ============================================================================
const PATCH_MAGIC: [u8; 4] = *b"ZLP2";
const PATCH_VERSION: u16 = 1;
const PATCH_HEADER_LEN: usize = 72;
const PATCH_SIGNATURE_LEN: usize = 64;
const INT3: u8 = 0xCC;
/// Flag bit 0: patch_data starts with a dependency table.
const PATCH_FLAG_HAS_DEPS: u32 = 1;
/// Maximum number of dependencies a single patch may declare.
const MAX_PATCH_DEPS: usize = 4;
/// Limit patch image size copied from userspace.
pub const MAX_PATCH_BYTES: usize = 64 * 1024;
#[derive(Clone, Copy, Debug)]
#[allow(dead_code)]
struct PatchHeader {
#[allow(dead_code)]
flags: u32,
target_addr: u64,
handler_addr: u64,
patch_data_len: u32,
patch_data_sha256: [u8; 32],
}
#[derive(Debug)]
struct PatchImage<'a> {
raw_header: &'a [u8],
header: PatchHeader,
signature: &'a [u8; 64],
patch_data: &'a [u8],
}
impl<'a> PatchImage<'a> {
fn parse(buf: &'a [u8]) -> Result<Self, Errno> {
if buf.len() < PATCH_HEADER_LEN + PATCH_SIGNATURE_LEN {
return Err(Errno::EINVAL);
}
let raw_header = &buf[..PATCH_HEADER_LEN];
// magic
if raw_header[0..4] != PATCH_MAGIC {
return Err(Errno::EINVAL);
}
let version = read_le_u16(raw_header, 0x04)?;
if version != PATCH_VERSION {
return Err(Errno::EINVAL);
}
let header_len = read_le_u16(raw_header, 0x06)? as usize;
if header_len != PATCH_HEADER_LEN {
return Err(Errno::EINVAL);
}
let flags = read_le_u32(raw_header, 0x08)?;
let target_addr = read_le_u64(raw_header, 0x10)?;
let handler_addr = read_le_u64(raw_header, 0x18)?;
let patch_data_len = read_le_u32(raw_header, 0x20)?;
let mut patch_data_sha256 = [0u8; 32];
patch_data_sha256.copy_from_slice(&raw_header[0x28..0x48]);
let total_len = PATCH_HEADER_LEN
.checked_add(PATCH_SIGNATURE_LEN)
.and_then(|v| v.checked_add(patch_data_len as usize))
.ok_or(Errno::EINVAL)?;
// Require exact length to avoid hidden bytes not covered by signature.
if buf.len() != total_len {
return Err(Errno::EINVAL);
}
let sig_off = PATCH_HEADER_LEN;
let data_off = PATCH_HEADER_LEN + PATCH_SIGNATURE_LEN;
let signature: &'a [u8; 64] = buf[sig_off..sig_off + PATCH_SIGNATURE_LEN]
.try_into()
.map_err(|_| Errno::EINVAL)?;
let patch_data = &buf[data_off..data_off + patch_data_len as usize];
let header = PatchHeader {
flags,
target_addr,
handler_addr,
patch_data_len,
patch_data_sha256,
};
Ok(Self {
raw_header,
header,
signature,
patch_data,
})
}
}
// ============================================================================
// Dependency metadata
// ============================================================================
/// Per-patch dependency metadata, immutable after registration.
///
/// Stored in a parallel table alongside `PatchSlot`, protected by `PATCH_REG_LOCK`.
#[derive(Clone, Copy, Debug)]
struct PatchMeta {
/// Unique identifier for this patch: SHA-256 of patch_data from the ZLPM header.
patch_uid: [u8; 32],
/// Number of valid entries in `deps` (0..=MAX_PATCH_DEPS).
dep_count: u8,
/// UIDs of patches that must be in `Enabled` state before this patch can be enabled.
deps: [[u8; 32]; MAX_PATCH_DEPS],
}
/// Extract dependency metadata from a parsed patch image.
///
/// If `PATCH_FLAG_HAS_DEPS` is set in the header flags, `patch_data` is prefixed with:
///
/// ```text
/// [0] dep_count (1..=4)
/// [1..33] dep_uid[0] (SHA-256)
/// [33..65] dep_uid[1] (if dep_count >= 2)
/// ...
/// ```
///
/// Returns `(meta, handler_offset)` where `handler_offset` is the byte offset within
/// `patch_data` where the actual handler code begins (past the dep table).
fn extract_patch_meta(img: &PatchImage<'_>) -> Result<(PatchMeta, usize), Errno> {
let patch_uid = img.header.patch_data_sha256;
let mut meta = PatchMeta {
patch_uid,
dep_count: 0,
deps: [[0u8; 32]; MAX_PATCH_DEPS],
};
if (img.header.flags & PATCH_FLAG_HAS_DEPS) == 0 {
return Ok((meta, 0));
}
// HAS_DEPS requires at least 1 byte for dep_count.
if img.patch_data.is_empty() {
return Err(Errno::EINVAL);
}
let dep_count = img.patch_data[0] as usize;
if dep_count == 0 || dep_count > MAX_PATCH_DEPS {
return Err(Errno::EINVAL);
}
// dep table = 1 byte count + dep_count * 32 bytes UIDs.
let table_len = 1usize
.checked_add(dep_count.checked_mul(32).ok_or(Errno::EINVAL)?)
.ok_or(Errno::EINVAL)?;
if img.patch_data.len() < table_len {
return Err(Errno::EINVAL);
}
for i in 0..dep_count {
let start = 1 + i * 32;
meta.deps[i].copy_from_slice(&img.patch_data[start..start + 32]);
}
meta.dep_count = dep_count as u8;
// Self-dependency is structurally invalid.
for dep_uid in meta.deps.iter().take(dep_count) {
if ct_eq(dep_uid, &meta.patch_uid) {
return Err(Errno::EINVAL);
}
}
Ok((meta, table_len))
}
// ============================================================================
// Patch state machine + fixed patch table
// ============================================================================
const MAX_PATCHES: usize = 64;
/// Retired handler regions are quarantined instead of being freed immediately.
/// A signed handler is arbitrary kernel code and cannot be trusted to execute
/// the optional return hook, so reclamation must never depend on cooperation
/// from that code. The fixed bound keeps unload/reload memory use finite; once
/// the quarantine is full, a further unload fails closed with `EBUSY`.
const MAX_RETIRED_EXEC: usize = MAX_PATCHES;
#[derive(Clone, Copy)]
struct RetiredExec {
addr: usize,
len: usize,
}
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PatchState {
Empty = 0,
Loading = 1,
Registered = 2,
Enabling = 3,
Enabled = 4,
Disabling = 5,
Disabled = 6,
Failed = 7,
/// The slot has been unloaded but its executable blob is quarantined.
/// It is intentionally never reused: a signed handler may return late
/// through an old slot index, and reusing the index would let that stale
/// callback mutate a newer patch's in-flight accounting.
Retired = 8,
}
impl PatchState {
#[inline]
fn from_u8(v: u8) -> PatchState {
match v {
0 => PatchState::Empty,
1 => PatchState::Loading,
2 => PatchState::Registered,
3 => PatchState::Enabling,
4 => PatchState::Enabled,
5 => PatchState::Disabling,
6 => PatchState::Disabled,
8 => PatchState::Retired,
_ => PatchState::Failed,
}
}
#[inline]
fn is_bp_active(self) -> bool {
matches!(
self,
PatchState::Enabling | PatchState::Enabled | PatchState::Disabling
)
}
}
struct PatchSlot {
state: AtomicU8,
id: AtomicU64,
target: AtomicUsize,
handler: AtomicUsize,
// Saved original first byte for rollback.
orig_valid: AtomicU8,
orig_byte: AtomicU8,
// Optional allocated handler blob region.
exec_addr: AtomicUsize,
exec_len: AtomicUsize,
// TSC tick (RDTSC) when the patch transitioned to Enabled; 0 = never/unknown.
// Used for panic-time rollback of recently-enabled patches.
enabled_tsc: AtomicU64,
// R103-2 FIX: In-flight dispatch counter.
//
// Incremented by `breakpoint_dispatch` before redirecting RIP into the handler
// and optionally decremented by a cooperative return hook. Unload safety does
// not depend on this counter: executable blobs and their slot indices are both
// retired permanently, because signed handler code may omit or delay the hook.
in_flight: AtomicU32,
}
impl PatchSlot {
const fn new() -> Self {
Self {
state: AtomicU8::new(PatchState::Empty as u8),
id: AtomicU64::new(0),
target: AtomicUsize::new(0),
handler: AtomicUsize::new(0),
orig_valid: AtomicU8::new(0),
orig_byte: AtomicU8::new(0),
exec_addr: AtomicUsize::new(0),
exec_len: AtomicUsize::new(0),
enabled_tsc: AtomicU64::new(0),
in_flight: AtomicU32::new(0), // R103-2 FIX
}
}
}
static PATCH_TABLE: Once<&'static [PatchSlot]> = Once::new();
static NEXT_PATCH_ID: AtomicU64 = AtomicU64::new(1);
/// R94-3 FIX: Serialize patch registration to prevent duplicate-target races.
static PATCH_REG_LOCK: Mutex<()> = Mutex::new(());
/// R94-5 FIX: Serialize text patching to prevent concurrent page-permission conflicts.
static TEXT_PATCH_LOCK: Mutex<()> = Mutex::new(());
/// Per-slot dependency metadata, parallel to PATCH_TABLE.
///
/// P2-3 FIX: Replaced `static mut` with `Mutex` to eliminate undefined behavior
/// from unsynchronized mutable access. All reads and writes are serialized by
/// both `PATCH_REG_LOCK` (for the patch lifecycle) and this inner `Mutex` (for
/// memory safety). The double-lock is acceptable because `PATCH_META_TABLE` is
/// only accessed in cold registration/unload/dependency-check paths.
static PATCH_META_TABLE: Mutex<[Option<PatchMeta>; MAX_PATCHES]> = Mutex::new([None; MAX_PATCHES]);
static RETIRED_EXEC: Mutex<[Option<RetiredExec>; MAX_RETIRED_EXEC]> =
Mutex::new([None; MAX_RETIRED_EXEC]);
/// Place an executable region in the never-reused quarantine. This is the
/// safety backstop for handlers that do not call `kpatch_handler_return` (or
/// call it too late): an in-flight CPU can continue executing valid bytes even
/// after the slot is cleared and reused.
fn quarantine_exec(addr: usize, len: usize) -> bool {
if addr == 0 || len == 0 {
return true;
}
let mut retired = RETIRED_EXEC.lock();
if retired
.iter()
.flatten()
.any(|entry| entry.addr == addr && entry.len == len)
{
return true;
}
if let Some(slot) = retired.iter_mut().find(|entry| entry.is_none()) {
*slot = Some(RetiredExec { addr, len });
true
} else {
false
}
}
fn init_patch_table() -> &'static [PatchSlot] {
let mut v = Vec::with_capacity(MAX_PATCHES);
for _ in 0..MAX_PATCHES {
v.push(PatchSlot::new());
}
Box::leak(v.into_boxed_slice())
}
#[inline]
fn patch_table() -> &'static [PatchSlot] {
PATCH_TABLE.call_once(init_patch_table);
PATCH_TABLE.get().copied().unwrap_or(&[])
}
#[inline]
fn patch_table_get() -> Option<&'static [PatchSlot]> {
PATCH_TABLE.get().copied()
}
fn find_slot_index_by_id(id: u64) -> Option<(usize, &'static PatchSlot)> {
for (idx, slot) in patch_table().iter().enumerate() {
let st = PatchState::from_u8(slot.state.load(Ordering::Acquire));
if st != PatchState::Empty && slot.id.load(Ordering::Acquire) == id {
return Some((idx, slot));
}
}
None
}
fn find_slot_by_id(id: u64) -> Option<&'static PatchSlot> {
find_slot_index_by_id(id).map(|(_, slot)| slot)
}
/// Query current state for a loaded patch id.
pub fn patch_state(id: u64) -> Option<PatchState> {
if !SUPPORTED {
return None;
}
find_slot_by_id(id).map(|s| PatchState::from_u8(s.state.load(Ordering::Acquire)))
}
// ============================================================================
// Dependency enforcement
// ============================================================================
/// Verify that all dependencies of the patch at `slot_index` are currently `Enabled`.
///
/// Returns `ENOENT` if a required dependency UID is not loaded at all,
/// or `EBUSY` if a dependency is loaded but not in `Enabled` state.
///
/// Must be called before transitioning a patch to `Enabled`.
fn check_dependencies(slot_index: usize) -> Result<(), Errno> {
let table = patch_table();
let _guard = PATCH_REG_LOCK.lock();
let meta_table = PATCH_META_TABLE.lock();
let meta = match meta_table.get(slot_index).copied().flatten() {
Some(m) => m,
None => return Err(Errno::EINVAL),
};
let dep_count = meta.dep_count as usize;
if dep_count == 0 {
return Ok(());
}
for dep_uid in meta.deps.iter().take(dep_count) {
let mut found = false;
let mut enabled = false;
for (other_idx, other_slot) in table.iter().enumerate() {
if other_idx == slot_index {
continue;
}
let st = PatchState::from_u8(other_slot.state.load(Ordering::Acquire));
if st == PatchState::Empty {
continue;
}
// SAFETY: PATCH_REG_LOCK is held.
let other_meta = match meta_table.get(other_idx).copied().flatten() {
Some(m) => m,
None => continue,
};
if ct_eq(&other_meta.patch_uid, dep_uid) {
found = true;
if st == PatchState::Enabled {
enabled = true;
}
break;
}
}
if !found {
return Err(Errno::ENOENT);
}
if !enabled {
return Err(Errno::EBUSY);
}
}
Ok(())
}
/// Verify that no `Enabled`/`Enabling` patch depends on the patch at `slot_index`.
///
/// Returns `EBUSY` if any active patch lists this patch's UID as a dependency.
///
/// Must be called before transitioning a patch to `Disabled` or unloading it.
fn check_no_dependents(slot_index: usize) -> Result<(), Errno> {
let table = patch_table();
let _guard = PATCH_REG_LOCK.lock();
let meta_table = PATCH_META_TABLE.lock();
let meta = match meta_table.get(slot_index).copied().flatten() {
Some(m) => m,
None => return Err(Errno::EINVAL),
};
let patch_uid = meta.patch_uid;
for (other_idx, other_slot) in table.iter().enumerate() {
if other_idx == slot_index {
continue;
}
let st = PatchState::from_u8(other_slot.state.load(Ordering::Acquire));
if !matches!(st, PatchState::Enabled | PatchState::Enabling) {
continue;
}
// SAFETY: PATCH_REG_LOCK is held.
let other_meta = match meta_table.get(other_idx).copied().flatten() {
Some(m) => m,
None => continue,
};
let dep_count = other_meta.dep_count as usize;
for dep_uid in other_meta.deps.iter().take(dep_count) {
if ct_eq(dep_uid, &patch_uid) {
return Err(Errno::EBUSY);
}
}
}
Ok(())
}
// ============================================================================
// P1-4: Topological ordering for batch enable/disable
// ============================================================================
/// Collect all non-empty patch slots into a (slot_index, id, meta) list.
///
/// Requires `PATCH_REG_LOCK` to be held by the caller.
/// Returns `EBUSY` if any slot is in a transitional state.
fn collect_patch_nodes(table: &'static [PatchSlot]) -> Result<Vec<(usize, u64, PatchMeta)>, Errno> {
let meta_table = PATCH_META_TABLE.lock();
let mut nodes = Vec::new();
for (slot_index, slot) in table.iter().enumerate() {
let st = PatchState::from_u8(slot.state.load(Ordering::Acquire));
if st == PatchState::Empty {
continue;
}
if matches!(
st,
PatchState::Loading | PatchState::Enabling | PatchState::Disabling
) {
return Err(Errno::EBUSY);
}
if matches!(st, PatchState::Failed | PatchState::Retired) {
continue; // Skip failed patches — they cannot participate in batch ops.
}
// R110-1 FIX: Treat missing metadata on a non-empty, non-failed slot as an
// internal consistency error rather than silently skipping it. A slot that
// is Registered/Enabled/Disabled MUST have associated PatchMeta.
let meta = match meta_table.get(slot_index).copied().flatten() {
Some(m) => m,
None => return Err(Errno::EINVAL),
};
let id = slot.id.load(Ordering::Acquire);
nodes.push((slot_index, id, meta));
}
Ok(nodes)
}
/// Build a topological order of all non-empty patches by UID dependency.
///
/// Uses Kahn's algorithm. Returns patch IDs in dependency-first order
/// (roots first, leaves last).
///
/// - Returns `ENOENT` if a dependency UID is not loaded.
/// - Returns `EINVAL` on dependency cycle.
/// - Returns `EBUSY` if any patch is in a transitional state.
fn topo_sort_patch_ids() -> Result<Vec<u64>, Errno> {
let table = patch_table();
let _guard = PATCH_REG_LOCK.lock();
let nodes = collect_patch_nodes(table)?;
let n = nodes.len();
if n == 0 {
return Ok(Vec::new());
}
// Build adjacency: for each node, compute in-degree and dependents list.
let mut indegree = vec![0u16; n];
let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); n];
for (i, (_, _, meta)) in nodes.iter().enumerate() {
let dep_count = meta.dep_count as usize;
for dep_uid in meta.deps.iter().take(dep_count) {
let dep_idx = nodes
.iter()
.position(|(_, _, m)| ct_eq(&m.patch_uid, dep_uid))
.ok_or(Errno::ENOENT)?;
dependents[dep_idx].push(i);
indegree[i] = indegree[i].checked_add(1).ok_or(Errno::EINVAL)?;
}
}
// Kahn's algorithm: repeatedly pick a zero-indegree node.
let mut processed = vec![false; n];
let mut order: Vec<usize> = Vec::with_capacity(n);
for _ in 0..n {
let next = (0..n).find(|&i| !processed[i] && indegree[i] == 0);
let i = next.ok_or(Errno::EINVAL)?; // Cycle detected
processed[i] = true;
order.push(i);
for &child in dependents[i].iter() {
indegree[child] = indegree[child].saturating_sub(1);
}
}
let ids: Vec<u64> = order.iter().map(|&idx| nodes[idx].1).collect();
Ok(ids)
}
/// P1-4: Enable all loaded patches in topological dependency order.
///
/// Patches that are already `Enabled` are skipped. On failure, all patches
/// enabled by this batch are rolled back (disabled) in reverse order.
///
/// Returns `EPERM` if the caller is not privileged.
pub fn sys_kpatch_enable_all() -> i64 {
match do_sys_kpatch_enable_all() {
Ok(()) => 0,
Err(e) => e.as_i64(),
}
}
fn do_sys_kpatch_enable_all() -> Result<(), Errno> {
let ops = ops()?;
let _ = patch_table();
if !ops.is_privileged() {
return Err(Errno::EPERM);
}
let order = topo_sort_patch_ids()?;
let mut enabled_by_batch: Vec<u64> = Vec::new();
for &id in order.iter() {
// Recheck state — another thread could have changed it.
let st = match patch_state(id) {
Some(s) => s,
None => {
// Patch disappeared (unloaded concurrently); rollback and fail.
rollback_batch(&enabled_by_batch);
return Err(Errno::ENOENT);
}
};
if st == PatchState::Enabled {
continue; // Already enabled — skip.
}
if !matches!(st, PatchState::Registered | PatchState::Disabled) {
// Not in an enable-able state — rollback and fail.
rollback_batch(&enabled_by_batch);
return Err(Errno::EBUSY);
}
ops.check_lsm_kpatch_enable(id)?;
if let Err(e) = kpatch_enable(id) {
rollback_batch(&enabled_by_batch);
return Err(e);
}
enabled_by_batch.push(id);
}
Ok(())
}
/// P1-4: Disable all enabled patches in reverse topological dependency order.
///
/// Patches that are not `Enabled` are skipped. On failure, all patches
/// disabled by this batch are re-enabled in reverse order.
///
/// Returns `EPERM` if the caller is not privileged.
pub fn sys_kpatch_disable_all() -> i64 {
match do_sys_kpatch_disable_all() {
Ok(()) => 0,
Err(e) => e.as_i64(),
}
}
fn do_sys_kpatch_disable_all() -> Result<(), Errno> {
let ops = ops()?;
let _ = patch_table();
if !ops.is_privileged() {
return Err(Errno::EPERM);
}
let order = topo_sort_patch_ids()?;
let mut disabled_by_batch: Vec<u64> = Vec::new();
// Disable in reverse topological order (leaves first, roots last).
for &id in order.iter().rev() {
let st = match patch_state(id) {
Some(s) => s,
None => {
reenable_batch(&disabled_by_batch);
return Err(Errno::ENOENT);
}
};
if st != PatchState::Enabled {
continue; // Not enabled — skip.
}
ops.check_lsm_kpatch_disable(id)?;
if let Err(e) = kpatch_disable(id) {
reenable_batch(&disabled_by_batch);
return Err(e);
}
disabled_by_batch.push(id);
}
Ok(())
}
/// Rollback helper: disable patches enabled by a failed enable-all batch.
fn rollback_batch(enabled_ids: &[u64]) {
for &id in enabled_ids.iter().rev() {
let _ = kpatch_disable(id);
}
}
/// Rollback helper: re-enable patches disabled by a failed disable-all batch.
fn reenable_batch(disabled_ids: &[u64]) {
for &id in disabled_ids.iter().rev() {
let _ = kpatch_enable(id);
}
}
// ============================================================================
// Panic/fault rollback policy
// ============================================================================
/// Read the Time Stamp Counter (RDTSC) for timestamp tracking.
///
/// Returns TSC ticks since CPU reset. This is a monotonic counter on modern x86_64
/// CPUs with invariant TSC. Used for panic-time rollback window calculation.
#[inline]
fn read_tsc() -> u64 {
#[cfg(target_arch = "x86_64")]
{
let low: u32;
let high: u32;
// SAFETY: RDTSC is a safe instruction on x86_64.
unsafe {
core::arch::asm!(
"rdtsc",
out("eax") low,
out("edx") high,
options(nomem, nostack, preserves_flags)
);
}
((high as u64) << 32) | (low as u64)
}