unkernel-rs 0.6.0

Native Rust + Wasmtime host library and CLI for unkernel (Linux 7.x on WebAssembly) — zero Node, zero JSPI, zero KVM
Documentation
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
//! Untamperable host-side runtime monitoring, audit event streaming, interactive approval gates
//! (network + 9P filesystem + sensitive credential reads), and whole-VM time-stop pause/resume.

use crate::vmi::{ProcInfo, VmiTracker};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs::{File, OpenOptions};
use std::io::{BufRead, Write};
use std::net::Ipv4Addr;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, OnceLock, mpsc};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use wasmtime::{Engine, Result};

/// Policy decision recorded in audit logs or returned by an interactive approval handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalDecision {
    AllowOnce,
    AllowAlways,
    DenyOnce,
    DenyAlways,
}

impl ApprovalDecision {
    pub fn is_allowed(self) -> bool {
        matches!(self, Self::AllowOnce | Self::AllowAlways)
    }
}

/// Kind of sandbox operation intercepted for interactive judgment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalKind {
    NetConnect,
    FsWrite,
    FsSensitiveRead,
}

/// Details of an intercepted operation paused awaiting an external Allow/Deny decision.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApprovalRequest {
    pub approval_id: u64,
    pub kind: ApprovalKind,
    pub target: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proc: Option<ProcInfo>,
}

/// Structured host-side audit event emitted outside the guest VM (untamperable by guest root).
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum AuditEvent {
    #[serde(rename = "proc.exec")]
    ProcExec {
        ts_ms: u64,
        pid: u32,
        ppid: u32,
        comm: String,
    },
    #[serde(rename = "proc.exit")]
    ProcExit { ts_ms: u64, pid: u32, comm: String },
    #[serde(rename = "net.dns")]
    NetDns {
        ts_ms: u64,
        domain: String,
        qtype: u16,
        resolved_ips: Vec<String>,
        decision: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        proc: Option<ProcInfo>,
    },
    #[serde(rename = "net.connect")]
    NetConnect {
        ts_ms: u64,
        ip: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        domain: Option<String>,
        port: u16,
        decision: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        proc: Option<ProcInfo>,
    },
    #[serde(rename = "net.tls_sni")]
    NetTlsSni {
        ts_ms: u64,
        ip: String,
        port: u16,
        sni: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        proc: Option<ProcInfo>,
    },
    #[serde(rename = "net.tls_decrypted")]
    NetTlsDecrypted {
        ts_ms: u64,
        ip: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        domain: Option<String>,
        port: u16,
        /// `"vmi"` (zero-touch SharedMemory key extraction) or `"mitm"` (host TLS proxy).
        method: String,
        /// `"tx"` (guest -> remote) or `"rx"` (remote -> guest).
        direction: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        http_summary: Option<String>,
        preview: String,
        bytes: usize,
        #[serde(skip_serializing_if = "Option::is_none")]
        proc: Option<ProcInfo>,
    },
    #[serde(rename = "net.http")]
    NetHttp {
        ts_ms: u64,
        ip: String,
        port: u16,
        method: String,
        path: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        host: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        proc: Option<ProcInfo>,
    },
    #[serde(rename = "net.close")]
    NetClose {
        ts_ms: u64,
        ip: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        domain: Option<String>,
        port: u16,
        bytes_tx: u64,
        bytes_rx: u64,
        duration_ms: u64,
        #[serde(skip_serializing_if = "Option::is_none")]
        proc: Option<ProcInfo>,
    },
    #[serde(rename = "fs.op")]
    FsOp {
        ts_ms: u64,
        mount: String,
        op: String,
        path: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        target_path: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        bytes: Option<usize>,
        sensitive: bool,
        decision: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        proc: Option<ProcInfo>,
    },
    #[serde(rename = "vm.paused")]
    VmPaused { ts_ms: u64, reason: String },
    #[serde(rename = "vm.resumed")]
    VmResumed { ts_ms: u64, paused_ms: u64 },
    #[serde(rename = "approval.required")]
    ApprovalRequired {
        ts_ms: u64,
        approval_id: u64,
        kind: ApprovalKind,
        target: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        detail: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        proc: Option<ProcInfo>,
    },
    #[serde(rename = "approval.resolved")]
    ApprovalResolved {
        ts_ms: u64,
        approval_id: u64,
        kind: ApprovalKind,
        target: String,
        decision: ApprovalDecision,
    },
}

pub fn now_unix_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

/// Sink callback receiving real-time structured [`AuditEvent`]s from the VM host.
pub type AuditCallback = Arc<dyn Fn(AuditEvent) + Send + Sync>;

/// Synchronous approval callback (used for interactive CLI prompts or custom Rust policies).
pub type ApprovalCallback = Arc<dyn Fn(&ApprovalRequest) -> ApprovalDecision + Send + Sync>;

/// Monitoring, interactive approval, and freeze-on-ask configuration for [`crate::VmConfig`].
#[derive(Clone, Default)]
pub struct MonitorConfig {
    /// Emit audit events to this callback (in addition to `audit_file` if set).
    pub audit_callback: Option<AuditCallback>,
    /// Optional pre-opened JSONL audit log file (opened before Landlock).
    pub audit_file: Option<Arc<Mutex<File>>>,
    /// Emit audit events even when no approval gates are enabled.
    pub audit_enabled: bool,
    /// Require approval before opening outbound TCP connections (after static LAN/allowlist checks).
    pub ask_net: bool,
    /// Require approval before mutating files on mounted 9P directories (`create`, `write`, `unlink`, `rename`, `mkdir`).
    pub ask_fs_write: bool,
    /// Require approval before opening sensitive credential-like paths (`.env`, `.npmrc`, `.ssh`, `.aws`, etc.) on mounted 9P dirs.
    pub ask_sensitive_read: bool,
    /// Automatically freeze the entire guest Linux VM while waiting on an interactive approval decision.
    pub freeze_on_ask: bool,
    /// Optional synchronous callback for resolving approvals; when `None`, approvals wait on
    /// [`crate::Vm::resolve_approval`] (used by NDJSON `serve` mode and async controllers).
    pub approval_callback: Option<ApprovalCallback>,
}

impl std::fmt::Debug for MonitorConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MonitorConfig")
            .field("audit_callback", &self.audit_callback.is_some())
            .field("audit_file", &self.audit_file.is_some())
            .field("audit_enabled", &self.audit_enabled)
            .field("ask_net", &self.ask_net)
            .field("ask_fs_write", &self.ask_fs_write)
            .field("ask_sensitive_read", &self.ask_sensitive_read)
            .field("freeze_on_ask", &self.freeze_on_ask)
            .field("approval_callback", &self.approval_callback.is_some())
            .finish()
    }
}

/// Open/create a JSONL audit log file (call BEFORE Landlock so writes continue working inside sandbox).
pub fn open_audit_file(path: &Path) -> Result<Arc<Mutex<File>>> {
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent)?;
    }
    let f = OpenOptions::new().create(true).append(true).open(path)?;
    Ok(Arc::new(Mutex::new(f)))
}

/// Whole-VM time-stop controller backed by Wasmtime `epoch_interruption` and paused guest clock accounting.
pub struct PauseController {
    engine: Engine,
    paused: AtomicBool,
    aborted: AtomicBool,
    paused_total_ns: AtomicU64,
    inner: Mutex<PauseInner>,
    cv: Condvar,
}

struct PauseInner {
    depth: usize,
    paused_since: Option<Instant>,
}

impl PauseController {
    pub fn new(engine: Engine) -> Arc<Self> {
        Arc::new(Self {
            engine,
            paused: AtomicBool::new(false),
            aborted: AtomicBool::new(false),
            paused_total_ns: AtomicU64::new(0),
            inner: Mutex::new(PauseInner {
                depth: 0,
                paused_since: None,
            }),
            cv: Condvar::new(),
        })
    }

    pub fn is_paused(&self) -> bool {
        self.paused.load(Ordering::Acquire)
    }

    /// Increment pause refcount and interrupt all running Wasmtime kthreads immediately.
    /// Returns `true` if this call transitioned the VM from running -> paused.
    pub fn pause(&self) -> bool {
        if self.aborted.load(Ordering::SeqCst) {
            return false;
        }
        let mut g = self.inner.lock().unwrap();
        g.depth += 1;
        if g.depth == 1 {
            g.paused_since = Some(Instant::now());
            self.paused.store(true, Ordering::Release);
            drop(g);
            self.engine.increment_epoch();
            true
        } else {
            false
        }
    }

    /// Decrement pause refcount; resumes the VM when count reaches 0.
    /// Returns `Some(paused_ms)` if this call transitioned paused -> running.
    pub fn resume(&self) -> Option<u64> {
        let mut g = self.inner.lock().unwrap();
        if g.depth == 0 {
            return None;
        }
        g.depth -= 1;
        if g.depth == 0 {
            let elapsed = g
                .paused_since
                .take()
                .map(|t| t.elapsed())
                .unwrap_or_default();
            self.paused_total_ns
                .fetch_add(elapsed.as_nanos() as u64, Ordering::Relaxed);
            self.paused.store(false, Ordering::Release);
            self.cv.notify_all();
            Some(elapsed.as_millis() as u64)
        } else {
            None
        }
    }

    /// Total nanoseconds the VM has spent frozen (including any currently active freeze).
    pub fn paused_ns(&self) -> u64 {
        let base = self.paused_total_ns.load(Ordering::Relaxed);
        if self.paused.load(Ordering::Acquire) {
            let g = self.inner.lock().unwrap();
            let extra = g
                .paused_since
                .map(|t| t.elapsed().as_nanos() as u64)
                .unwrap_or(0);
            base.saturating_add(extra)
        } else {
            base
        }
    }

    /// Block the calling kthread while the VM is frozen. Returns `false` if aborted/exited.
    pub fn wait_if_paused(&self) -> bool {
        if !self.paused.load(Ordering::Acquire) {
            return !self.aborted.load(Ordering::SeqCst);
        }
        let mut g = self.inner.lock().unwrap();
        while g.depth > 0 && !self.aborted.load(Ordering::SeqCst) {
            g = self.cv.wait(g).unwrap();
        }
        !self.aborted.load(Ordering::SeqCst)
    }

    /// Permanently unblock all paused kthreads during VM shutdown/timeout.
    pub fn abort(&self) {
        self.aborted.store(true, Ordering::SeqCst);
        let mut g = self.inner.lock().unwrap();
        g.depth = 0;
        g.paused_since = None;
        self.paused.store(false, Ordering::Release);
        self.cv.notify_all();
    }
}

/// Shared host monitor coordinating audit logging, remembered rules, pending approval gates,
/// and optional whole-VM freeze-on-ask.
pub struct Monitor {
    cfg: MonitorConfig,
    pause: Arc<PauseController>,
    vmi: OnceLock<Arc<VmiTracker>>,
    next_approval_id: AtomicU64,
    closed: AtomicBool,
    rules: Mutex<PolicyCache>,
    pending: Mutex<HashMap<u64, PendingApproval>>,
}

#[derive(Default)]
struct PolicyCache {
    allowed: HashSet<(ApprovalKind, String)>,
    denied: HashSet<(ApprovalKind, String)>,
}

struct PendingApproval {
    req: ApprovalRequest,
    tx: mpsc::SyncSender<ApprovalDecision>,
}

impl Monitor {
    pub fn new(cfg: MonitorConfig, pause: Arc<PauseController>) -> Arc<Self> {
        Arc::new(Self {
            cfg,
            pause,
            vmi: OnceLock::new(),
            next_approval_id: AtomicU64::new(1),
            closed: AtomicBool::new(false),
            rules: Mutex::new(PolicyCache::default()),
            pending: Mutex::new(HashMap::new()),
        })
    }

    pub fn attach_vmi(&self, vmi: Arc<VmiTracker>) {
        let _ = self.vmi.set(vmi);
    }

    pub fn p9_proc(&self) -> Option<ProcInfo> {
        self.vmi.get().and_then(|v| v.last_p9_proc())
    }

    pub fn net_proc(&self) -> Option<ProcInfo> {
        self.vmi.get().and_then(|v| v.last_net_proc())
    }

    pub fn is_active(&self) -> bool {
        self.cfg.audit_enabled
            || self.cfg.audit_callback.is_some()
            || self.cfg.audit_file.is_some()
            || self.cfg.ask_net
            || self.cfg.ask_fs_write
            || self.cfg.ask_sensitive_read
    }

    pub fn ask_net(&self) -> bool {
        self.cfg.ask_net
    }

    pub fn ask_fs_write(&self) -> bool {
        self.cfg.ask_fs_write
    }

    pub fn ask_sensitive_read(&self) -> bool {
        self.cfg.ask_sensitive_read
    }

    pub fn pause_controller(&self) -> &Arc<PauseController> {
        &self.pause
    }

    pub fn emit(&self, ev: AuditEvent) {
        if let Some(f) = &self.cfg.audit_file
            && let Ok(line) = serde_json::to_string(&ev)
            && let Ok(mut guard) = f.lock()
        {
            let _ = writeln!(guard, "{line}");
            let _ = guard.flush();
        }
        if let Some(cb) = &self.cfg.audit_callback {
            cb(ev);
        }
    }

    /// Pause the VM explicitly and emit `vm.paused`.
    pub fn pause_vm(&self, reason: impl Into<String>) -> bool {
        let changed = self.pause.pause();
        if changed {
            self.emit(AuditEvent::VmPaused {
                ts_ms: now_unix_ms(),
                reason: reason.into(),
            });
        }
        changed
    }

    /// Resume the VM explicitly and emit `vm.resumed`.
    pub fn resume_vm(&self) -> Option<u64> {
        let ms = self.pause.resume();
        if let Some(paused_ms) = ms {
            self.emit(AuditEvent::VmResumed {
                ts_ms: now_unix_ms(),
                paused_ms,
            });
        }
        ms
    }

    /// Request an external decision for an intercepted operation.
    /// Checks cached `AllowAlways` / `DenyAlways` rules first; if unknown, holds the calling
    /// host driver thread (and optionally freezes the entire guest VM if `freeze_on_ask`) until
    /// resolved via `approval_callback` or [`Self::resolve_approval`].
    pub fn request_approval(
        &self,
        kind: ApprovalKind,
        remember_key: &str,
        target: String,
        detail: Option<String>,
    ) -> ApprovalDecision {
        if self.closed.load(Ordering::SeqCst) {
            return ApprovalDecision::DenyOnce;
        }
        let cache_key = (kind, remember_key.to_string());
        {
            let rules = self.rules.lock().unwrap();
            if rules.allowed.contains(&cache_key) {
                return ApprovalDecision::AllowAlways;
            }
            if rules.denied.contains(&cache_key) {
                return ApprovalDecision::DenyAlways;
            }
        }

        let id = self.next_approval_id.fetch_add(1, Ordering::SeqCst);
        let proc_info = match kind {
            ApprovalKind::NetConnect => self.net_proc(),
            ApprovalKind::FsWrite | ApprovalKind::FsSensitiveRead => self.p9_proc(),
        };
        let req = ApprovalRequest {
            approval_id: id,
            kind,
            target: target.clone(),
            detail: detail.clone(),
            proc: proc_info.clone(),
        };

        let froze = if self.cfg.freeze_on_ask {
            self.pause_vm(format!("approval #{id}: {target}"))
        } else {
            false
        };

        self.emit(AuditEvent::ApprovalRequired {
            ts_ms: now_unix_ms(),
            approval_id: id,
            kind,
            target: target.clone(),
            detail,
            proc: proc_info,
        });

        let decision = if let Some(cb) = &self.cfg.approval_callback {
            cb(&req)
        } else {
            let (tx, rx) = mpsc::sync_channel(1);
            {
                let mut map = self.pending.lock().unwrap();
                if self.closed.load(Ordering::SeqCst) {
                    if froze {
                        self.resume_vm();
                    }
                    return ApprovalDecision::DenyOnce;
                }
                map.insert(id, PendingApproval { req, tx });
            }
            rx.recv().unwrap_or(ApprovalDecision::DenyOnce)
        };

        match decision {
            ApprovalDecision::AllowAlways => {
                self.rules.lock().unwrap().allowed.insert(cache_key);
            }
            ApprovalDecision::DenyAlways => {
                self.rules.lock().unwrap().denied.insert(cache_key);
            }
            ApprovalDecision::AllowOnce | ApprovalDecision::DenyOnce => {}
        }

        self.emit(AuditEvent::ApprovalResolved {
            ts_ms: now_unix_ms(),
            approval_id: id,
            kind,
            target,
            decision,
        });

        if froze {
            self.resume_vm();
        }
        decision
    }

    /// Resolve a pending approval by `approval_id` (returns `false` if not found).
    pub fn resolve_approval(&self, approval_id: u64, decision: ApprovalDecision) -> bool {
        let entry = self.pending.lock().unwrap().remove(&approval_id);
        match entry {
            Some(p) => {
                let _ = p.tx.send(decision);
                true
            }
            None => false,
        }
    }

    /// Snapshot currently pending approval requests.
    pub fn pending_approvals(&self) -> Vec<ApprovalRequest> {
        self.pending
            .lock()
            .unwrap()
            .values()
            .map(|p| p.req.clone())
            .collect()
    }

    /// Unblock all pending approvals and pauses during VM shutdown.
    pub fn shutdown(&self) {
        self.closed.store(true, Ordering::SeqCst);
        let drained: Vec<PendingApproval> = self
            .pending
            .lock()
            .unwrap()
            .drain()
            .map(|(_, p)| p)
            .collect();
        for p in drained {
            let _ = p.tx.send(ApprovalDecision::DenyOnce);
        }
        self.pause.abort();
    }
}

/// Interactive terminal prompt callback for CLI `--ask-*` usage (reads from `/dev/tty` pre-opened
/// before Landlock on Unix, or `CONIN$`/`CONOUT$` on Windows, falling back to deny if non-interactive).
pub fn terminal_approval_callback() -> ApprovalCallback {
    #[cfg(unix)]
    let tty_handles: Option<Arc<Mutex<(File, File)>>> = OpenOptions::new()
        .read(true)
        .write(true)
        .open("/dev/tty")
        .ok()
        .and_then(|f| f.try_clone().ok().map(|w| Arc::new(Mutex::new((f, w)))));

    #[cfg(windows)]
    let tty_handles: Option<Arc<Mutex<(File, File)>>> = OpenOptions::new()
        .read(true)
        .open("CONIN$")
        .ok()
        .and_then(|r| {
            OpenOptions::new()
                .write(true)
                .open("CONOUT$")
                .ok()
                .map(|w| Arc::new(Mutex::new((r, w))))
        });

    #[cfg(not(any(unix, windows)))]
    let tty_handles: Option<Arc<Mutex<(File, File)>>> = None;

    Arc::new(move |req: &ApprovalRequest| {
        let Some(tty) = &tty_handles else {
            eprintln!(
                "[unkernel-rs] approval #{} ({:?} {}): no interactive console available -> DENY",
                req.approval_id, req.kind, req.target
            );
            return ApprovalDecision::DenyOnce;
        };
        let mut guard = tty.lock().unwrap();
        let (ref mut rd, ref mut wr) = *guard;
        let detail = req
            .detail
            .as_deref()
            .map(|d| format!(" ({d})"))
            .unwrap_or_default();
        let proc_tag = req
            .proc
            .as_ref()
            .map(|p| format!(" [proc={} pid={}]", p.comm, p.pid))
            .unwrap_or_default();
        let _ = write!(
            wr,
            "\n[SANDBOX APPROVAL #{}] {:?}: {}{}{}\n  [a]llow once / [A]llow always / [d]eny once / [D]eny always > ",
            req.approval_id, req.kind, req.target, detail, proc_tag
        );
        let _ = wr.flush();

        let mut reader = std::io::BufReader::new(rd);
        let mut line = String::new();
        if reader.read_line(&mut line).is_err() {
            return ApprovalDecision::DenyOnce;
        }
        match line.trim() {
            "a" | "y" | "allow" => ApprovalDecision::AllowOnce,
            "A" | "Y" | "always" => ApprovalDecision::AllowAlways,
            "D" | "never" => ApprovalDecision::DenyAlways,
            _ => ApprovalDecision::DenyOnce,
        }
    })
}

/// Heuristic detector for credential/secret paths commonly targeted by supply-chain malware
/// (e.g. Shai-Hulud scanning for `.env`, `.npmrc`, AWS/GitHub/SSH keys, kubeconfigs).
pub fn is_sensitive_path(path: &str) -> bool {
    let lower = path.replace('\\', "/").to_ascii_lowercase();
    let file_name = lower.rsplit('/').next().unwrap_or(&lower);

    if file_name == ".env"
        || file_name.starts_with(".env.")
        || file_name == ".npmrc"
        || file_name == ".netrc"
        || file_name == ".pypirc"
        || file_name == ".git-credentials"
        || file_name == "credentials"
        || file_name == "credentials.json"
        || file_name == "id_rsa"
        || file_name == "id_ed25519"
        || file_name == "id_ecdsa"
        || file_name == "id_dsa"
        || file_name.ends_with(".pem")
        || file_name.ends_with(".key")
        || file_name.ends_with(".p12")
        || file_name.ends_with(".pfx")
    {
        return true;
    }

    if lower.contains("/.ssh/")
        || lower.starts_with(".ssh/")
        || lower.contains("/.aws/")
        || lower.starts_with(".aws/")
        || lower.contains("/.gnupg/")
        || lower.starts_with(".gnupg/")
        || lower.contains("/.kube/")
        || lower.starts_with(".kube/")
        || lower.contains("/.config/gh/")
        || lower.starts_with(".config/gh/")
        || lower.contains("secret")
        || lower.contains("token")
    {
        return true;
    }
    false
}

/// Extract the TLS Server Name Indication (SNI) hostname from an outbound TLS `ClientHello`
/// record (RFC 5246 / RFC 8446). Returns `None` if `data` is not a TLS ClientHello with SNI.
pub fn extract_tls_sni(data: &[u8]) -> Option<String> {
    // TLS record header: content_type=0x16 (Handshake), version=0x03 0x00..0x04, length (u16)
    if data.len() < 43 || data[0] != 0x16 || data[1] != 0x03 {
        return None;
    }
    let rec_len = u16::from_be_bytes([data[3], data[4]]) as usize;
    let end = data.len().min(5 + rec_len);
    if end < 43 {
        return None;
    }
    // Handshake header: msg_type=0x01 (ClientHello), 3-byte length
    if data[5] != 0x01 {
        return None;
    }
    let mut p = 9usize; // skip record(5) + handshake_hdr(4)
    p += 2 + 32; // client_version(2) + random(32)
    if p >= end {
        return None;
    }
    let sid_len = data[p] as usize;
    p += 1 + sid_len;
    if p + 2 > end {
        return None;
    }
    let cs_len = u16::from_be_bytes([data[p], data[p + 1]]) as usize;
    p += 2 + cs_len;
    if p + 1 > end {
        return None;
    }
    let comp_len = data[p] as usize;
    p += 1 + comp_len;
    if p + 2 > end {
        return None;
    }
    let ext_total = u16::from_be_bytes([data[p], data[p + 1]]) as usize;
    p += 2;
    let ext_end = end.min(p + ext_total);

    while p + 4 <= ext_end {
        let ext_type = u16::from_be_bytes([data[p], data[p + 1]]);
        let ext_len = u16::from_be_bytes([data[p + 2], data[p + 3]]) as usize;
        p += 4;
        if p + ext_len > ext_end {
            break;
        }
        if ext_type == 0x0000 && ext_len >= 5 {
            // server_name_list: list_len(2), name_type(1)==0 (host_name), name_len(2), bytes
            let mut ep = p + 2;
            let list_end = p + ext_len;
            while ep + 3 <= list_end {
                let name_type = data[ep];
                let name_len = u16::from_be_bytes([data[ep + 1], data[ep + 2]]) as usize;
                ep += 3;
                if ep + name_len > list_end {
                    break;
                }
                if name_type == 0 {
                    return std::str::from_utf8(&data[ep..ep + name_len])
                        .ok()
                        .map(|s| s.to_string());
                }
                ep += name_len;
            }
        }
        p += ext_len;
    }
    None
}

/// Extract HTTP/1.x `(method, path, Host)` from the beginning of a cleartext outbound TCP stream.
pub fn extract_http_request(data: &[u8]) -> Option<(String, String, Option<String>)> {
    let head = std::str::from_utf8(&data[..data.len().min(2048)]).ok()?;
    let mut lines = head.split("\r\n");
    let first = lines.next()?;
    let mut parts = first.split_whitespace();
    let method = parts.next()?;
    if !matches!(
        method,
        "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS" | "CONNECT"
    ) {
        return None;
    }
    let path = parts.next()?;
    let proto = parts.next()?;
    if !proto.starts_with("HTTP/1.") {
        return None;
    }
    let mut host = None;
    for line in lines {
        if line.is_empty() {
            break;
        }
        if let Some((k, v)) = line.split_once(':')
            && k.eq_ignore_ascii_case("host")
        {
            host = Some(v.trim().to_string());
            break;
        }
    }
    Some((method.to_string(), path.to_string(), host))
}

pub fn format_net_target(domain: Option<&str>, ip: Ipv4Addr, port: u16) -> (String, String) {
    match domain {
        Some(d) => (d.to_ascii_lowercase(), format!("{d}:{port}")),
        None => (ip.to_string(), format!("{ip}:{port}")),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sensitive_path_detection_catches_supply_chain_targets() {
        assert!(is_sensitive_path(".env"));
        assert!(is_sensitive_path("app/.env.production"));
        assert!(is_sensitive_path(".npmrc"));
        assert!(is_sensitive_path(".ssh/id_ed25519"));
        assert!(is_sensitive_path(".aws/credentials"));
        assert!(is_sensitive_path("certs/private.pem"));
        assert!(is_sensitive_path("config/github_token.txt"));
        assert!(!is_sensitive_path("src/main.rs"));
        assert!(!is_sensitive_path("package.json"));
        assert!(!is_sensitive_path("README.md"));
    }

    #[test]
    fn extracts_tls_sni_from_client_hello() {
        // Minimal synthetic TLS 1.2 ClientHello containing SNI "evil.example.com"
        let host = b"evil.example.com";
        let mut sni_ext = Vec::new();
        let entry_len = 1 + 2 + host.len();
        sni_ext.extend_from_slice(&(entry_len as u16).to_be_bytes());
        sni_ext.push(0); // host_name
        sni_ext.extend_from_slice(&(host.len() as u16).to_be_bytes());
        sni_ext.extend_from_slice(host);

        let mut exts = Vec::new();
        exts.extend_from_slice(&0x0000u16.to_be_bytes()); // SNI ext type
        exts.extend_from_slice(&(sni_ext.len() as u16).to_be_bytes());
        exts.extend_from_slice(&sni_ext);

        let mut body = Vec::new();
        body.extend_from_slice(&[0x03, 0x03]); // TLS 1.2
        body.extend_from_slice(&[0u8; 32]); // random
        body.push(0); // session_id len
        body.extend_from_slice(&2u16.to_be_bytes()); // cipher suites len
        body.extend_from_slice(&[0x13, 0x01]);
        body.push(1); // compression len
        body.push(0);
        body.extend_from_slice(&(exts.len() as u16).to_be_bytes());
        body.extend_from_slice(&exts);

        let mut hs = Vec::new();
        hs.push(0x01); // ClientHello
        let blen = body.len();
        hs.push(((blen >> 16) & 0xff) as u8);
        hs.push(((blen >> 8) & 0xff) as u8);
        hs.push((blen & 0xff) as u8);
        hs.extend_from_slice(&body);

        let mut rec = Vec::new();
        rec.extend_from_slice(&[0x16, 0x03, 0x01]);
        rec.extend_from_slice(&(hs.len() as u16).to_be_bytes());
        rec.extend_from_slice(&hs);

        assert_eq!(extract_tls_sni(&rec).as_deref(), Some("evil.example.com"));
        assert_eq!(extract_tls_sni(b"GET / HTTP/1.1\r\n\r\n"), None);
    }

    #[test]
    fn extracts_http_method_path_and_host() {
        let req =
            b"POST /exfil?a=1 HTTP/1.1\r\nHost: webhook.site\r\nContent-Length: 5\r\n\r\nhello";
        assert_eq!(
            extract_http_request(req),
            Some((
                "POST".to_string(),
                "/exfil?a=1".to_string(),
                Some("webhook.site".to_string())
            ))
        );
        assert_eq!(extract_http_request(b"\x16\x03\x01binary"), None);
    }
}