Skip to main content

unkernel_rs/
monitor.rs

1//! Untamperable host-side runtime monitoring, audit event streaming, interactive approval gates
2//! (network + 9P filesystem + sensitive credential reads), and whole-VM time-stop pause/resume.
3
4use crate::vmi::{ProcInfo, VmiTracker};
5use serde::{Deserialize, Serialize};
6use std::collections::{HashMap, HashSet};
7use std::fs::{File, OpenOptions};
8use std::io::{BufRead, Write};
9use std::net::Ipv4Addr;
10use std::path::Path;
11use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
12use std::sync::{Arc, Condvar, Mutex, OnceLock, mpsc};
13use std::time::{Instant, SystemTime, UNIX_EPOCH};
14use wasmtime::{Engine, Result};
15
16/// Policy decision recorded in audit logs or returned by an interactive approval handler.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum ApprovalDecision {
20    AllowOnce,
21    AllowAlways,
22    DenyOnce,
23    DenyAlways,
24}
25
26impl ApprovalDecision {
27    pub fn is_allowed(self) -> bool {
28        matches!(self, Self::AllowOnce | Self::AllowAlways)
29    }
30}
31
32/// Kind of sandbox operation intercepted for interactive judgment.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum ApprovalKind {
36    NetConnect,
37    FsWrite,
38    FsSensitiveRead,
39}
40
41/// Details of an intercepted operation paused awaiting an external Allow/Deny decision.
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct ApprovalRequest {
44    pub approval_id: u64,
45    pub kind: ApprovalKind,
46    pub target: String,
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub detail: Option<String>,
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub proc: Option<ProcInfo>,
51}
52
53/// Structured host-side audit event emitted outside the guest VM (untamperable by guest root).
54#[derive(Debug, Clone, Serialize)]
55#[serde(tag = "event", rename_all = "snake_case")]
56pub enum AuditEvent {
57    #[serde(rename = "proc.exec")]
58    ProcExec {
59        ts_ms: u64,
60        pid: u32,
61        ppid: u32,
62        comm: String,
63    },
64    #[serde(rename = "proc.exit")]
65    ProcExit { ts_ms: u64, pid: u32, comm: String },
66    #[serde(rename = "net.dns")]
67    NetDns {
68        ts_ms: u64,
69        domain: String,
70        qtype: u16,
71        resolved_ips: Vec<String>,
72        decision: String,
73        #[serde(skip_serializing_if = "Option::is_none")]
74        proc: Option<ProcInfo>,
75    },
76    #[serde(rename = "net.connect")]
77    NetConnect {
78        ts_ms: u64,
79        ip: String,
80        #[serde(skip_serializing_if = "Option::is_none")]
81        domain: Option<String>,
82        port: u16,
83        decision: String,
84        #[serde(skip_serializing_if = "Option::is_none")]
85        proc: Option<ProcInfo>,
86    },
87    #[serde(rename = "net.tls_sni")]
88    NetTlsSni {
89        ts_ms: u64,
90        ip: String,
91        port: u16,
92        sni: String,
93        #[serde(skip_serializing_if = "Option::is_none")]
94        proc: Option<ProcInfo>,
95    },
96    #[serde(rename = "net.tls_decrypted")]
97    NetTlsDecrypted {
98        ts_ms: u64,
99        ip: String,
100        #[serde(skip_serializing_if = "Option::is_none")]
101        domain: Option<String>,
102        port: u16,
103        /// `"vmi"` (zero-touch SharedMemory key extraction) or `"mitm"` (host TLS proxy).
104        method: String,
105        /// `"tx"` (guest -> remote) or `"rx"` (remote -> guest).
106        direction: String,
107        #[serde(skip_serializing_if = "Option::is_none")]
108        http_summary: Option<String>,
109        preview: String,
110        bytes: usize,
111        #[serde(skip_serializing_if = "Option::is_none")]
112        proc: Option<ProcInfo>,
113    },
114    #[serde(rename = "net.http")]
115    NetHttp {
116        ts_ms: u64,
117        ip: String,
118        port: u16,
119        method: String,
120        path: String,
121        #[serde(skip_serializing_if = "Option::is_none")]
122        host: Option<String>,
123        #[serde(skip_serializing_if = "Option::is_none")]
124        proc: Option<ProcInfo>,
125    },
126    #[serde(rename = "net.close")]
127    NetClose {
128        ts_ms: u64,
129        ip: String,
130        #[serde(skip_serializing_if = "Option::is_none")]
131        domain: Option<String>,
132        port: u16,
133        bytes_tx: u64,
134        bytes_rx: u64,
135        duration_ms: u64,
136        #[serde(skip_serializing_if = "Option::is_none")]
137        proc: Option<ProcInfo>,
138    },
139    #[serde(rename = "fs.op")]
140    FsOp {
141        ts_ms: u64,
142        mount: String,
143        op: String,
144        path: String,
145        #[serde(skip_serializing_if = "Option::is_none")]
146        target_path: Option<String>,
147        #[serde(skip_serializing_if = "Option::is_none")]
148        bytes: Option<usize>,
149        sensitive: bool,
150        decision: String,
151        #[serde(skip_serializing_if = "Option::is_none")]
152        proc: Option<ProcInfo>,
153    },
154    #[serde(rename = "vm.paused")]
155    VmPaused { ts_ms: u64, reason: String },
156    #[serde(rename = "vm.resumed")]
157    VmResumed { ts_ms: u64, paused_ms: u64 },
158    #[serde(rename = "approval.required")]
159    ApprovalRequired {
160        ts_ms: u64,
161        approval_id: u64,
162        kind: ApprovalKind,
163        target: String,
164        #[serde(skip_serializing_if = "Option::is_none")]
165        detail: Option<String>,
166        #[serde(skip_serializing_if = "Option::is_none")]
167        proc: Option<ProcInfo>,
168    },
169    #[serde(rename = "approval.resolved")]
170    ApprovalResolved {
171        ts_ms: u64,
172        approval_id: u64,
173        kind: ApprovalKind,
174        target: String,
175        decision: ApprovalDecision,
176    },
177}
178
179pub fn now_unix_ms() -> u64 {
180    SystemTime::now()
181        .duration_since(UNIX_EPOCH)
182        .unwrap_or_default()
183        .as_millis() as u64
184}
185
186/// Sink callback receiving real-time structured [`AuditEvent`]s from the VM host.
187pub type AuditCallback = Arc<dyn Fn(AuditEvent) + Send + Sync>;
188
189/// Synchronous approval callback (used for interactive CLI prompts or custom Rust policies).
190pub type ApprovalCallback = Arc<dyn Fn(&ApprovalRequest) -> ApprovalDecision + Send + Sync>;
191
192/// Monitoring, interactive approval, and freeze-on-ask configuration for [`crate::VmConfig`].
193#[derive(Clone, Default)]
194pub struct MonitorConfig {
195    /// Emit audit events to this callback (in addition to `audit_file` if set).
196    pub audit_callback: Option<AuditCallback>,
197    /// Optional pre-opened JSONL audit log file (opened before Landlock).
198    pub audit_file: Option<Arc<Mutex<File>>>,
199    /// Emit audit events even when no approval gates are enabled.
200    pub audit_enabled: bool,
201    /// Require approval before opening outbound TCP connections (after static LAN/allowlist checks).
202    pub ask_net: bool,
203    /// Require approval before mutating files on mounted 9P directories (`create`, `write`, `unlink`, `rename`, `mkdir`).
204    pub ask_fs_write: bool,
205    /// Require approval before opening sensitive credential-like paths (`.env`, `.npmrc`, `.ssh`, `.aws`, etc.) on mounted 9P dirs.
206    pub ask_sensitive_read: bool,
207    /// Automatically freeze the entire guest Linux VM while waiting on an interactive approval decision.
208    pub freeze_on_ask: bool,
209    /// Optional synchronous callback for resolving approvals; when `None`, approvals wait on
210    /// [`crate::Vm::resolve_approval`] (used by NDJSON `serve` mode and async controllers).
211    pub approval_callback: Option<ApprovalCallback>,
212}
213
214impl std::fmt::Debug for MonitorConfig {
215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216        f.debug_struct("MonitorConfig")
217            .field("audit_callback", &self.audit_callback.is_some())
218            .field("audit_file", &self.audit_file.is_some())
219            .field("audit_enabled", &self.audit_enabled)
220            .field("ask_net", &self.ask_net)
221            .field("ask_fs_write", &self.ask_fs_write)
222            .field("ask_sensitive_read", &self.ask_sensitive_read)
223            .field("freeze_on_ask", &self.freeze_on_ask)
224            .field("approval_callback", &self.approval_callback.is_some())
225            .finish()
226    }
227}
228
229/// Open/create a JSONL audit log file (call BEFORE Landlock so writes continue working inside sandbox).
230pub fn open_audit_file(path: &Path) -> Result<Arc<Mutex<File>>> {
231    if let Some(parent) = path.parent()
232        && !parent.as_os_str().is_empty()
233    {
234        std::fs::create_dir_all(parent)?;
235    }
236    let f = OpenOptions::new().create(true).append(true).open(path)?;
237    Ok(Arc::new(Mutex::new(f)))
238}
239
240/// Whole-VM time-stop controller backed by Wasmtime `epoch_interruption` and paused guest clock accounting.
241pub struct PauseController {
242    engine: Engine,
243    paused: AtomicBool,
244    aborted: AtomicBool,
245    paused_total_ns: AtomicU64,
246    inner: Mutex<PauseInner>,
247    cv: Condvar,
248}
249
250struct PauseInner {
251    depth: usize,
252    paused_since: Option<Instant>,
253}
254
255impl PauseController {
256    pub fn new(engine: Engine) -> Arc<Self> {
257        Arc::new(Self {
258            engine,
259            paused: AtomicBool::new(false),
260            aborted: AtomicBool::new(false),
261            paused_total_ns: AtomicU64::new(0),
262            inner: Mutex::new(PauseInner {
263                depth: 0,
264                paused_since: None,
265            }),
266            cv: Condvar::new(),
267        })
268    }
269
270    pub fn is_paused(&self) -> bool {
271        self.paused.load(Ordering::Acquire)
272    }
273
274    /// Increment pause refcount and interrupt all running Wasmtime kthreads immediately.
275    /// Returns `true` if this call transitioned the VM from running -> paused.
276    pub fn pause(&self) -> bool {
277        if self.aborted.load(Ordering::SeqCst) {
278            return false;
279        }
280        let mut g = self.inner.lock().unwrap();
281        g.depth += 1;
282        if g.depth == 1 {
283            g.paused_since = Some(Instant::now());
284            self.paused.store(true, Ordering::Release);
285            drop(g);
286            self.engine.increment_epoch();
287            true
288        } else {
289            false
290        }
291    }
292
293    /// Decrement pause refcount; resumes the VM when count reaches 0.
294    /// Returns `Some(paused_ms)` if this call transitioned paused -> running.
295    pub fn resume(&self) -> Option<u64> {
296        let mut g = self.inner.lock().unwrap();
297        if g.depth == 0 {
298            return None;
299        }
300        g.depth -= 1;
301        if g.depth == 0 {
302            let elapsed = g
303                .paused_since
304                .take()
305                .map(|t| t.elapsed())
306                .unwrap_or_default();
307            self.paused_total_ns
308                .fetch_add(elapsed.as_nanos() as u64, Ordering::Relaxed);
309            self.paused.store(false, Ordering::Release);
310            self.cv.notify_all();
311            Some(elapsed.as_millis() as u64)
312        } else {
313            None
314        }
315    }
316
317    /// Total nanoseconds the VM has spent frozen (including any currently active freeze).
318    pub fn paused_ns(&self) -> u64 {
319        let base = self.paused_total_ns.load(Ordering::Relaxed);
320        if self.paused.load(Ordering::Acquire) {
321            let g = self.inner.lock().unwrap();
322            let extra = g
323                .paused_since
324                .map(|t| t.elapsed().as_nanos() as u64)
325                .unwrap_or(0);
326            base.saturating_add(extra)
327        } else {
328            base
329        }
330    }
331
332    /// Block the calling kthread while the VM is frozen. Returns `false` if aborted/exited.
333    pub fn wait_if_paused(&self) -> bool {
334        if !self.paused.load(Ordering::Acquire) {
335            return !self.aborted.load(Ordering::SeqCst);
336        }
337        let mut g = self.inner.lock().unwrap();
338        while g.depth > 0 && !self.aborted.load(Ordering::SeqCst) {
339            g = self.cv.wait(g).unwrap();
340        }
341        !self.aborted.load(Ordering::SeqCst)
342    }
343
344    /// Permanently unblock all paused kthreads during VM shutdown/timeout.
345    pub fn abort(&self) {
346        self.aborted.store(true, Ordering::SeqCst);
347        let mut g = self.inner.lock().unwrap();
348        g.depth = 0;
349        g.paused_since = None;
350        self.paused.store(false, Ordering::Release);
351        self.cv.notify_all();
352    }
353}
354
355/// Shared host monitor coordinating audit logging, remembered rules, pending approval gates,
356/// and optional whole-VM freeze-on-ask.
357pub struct Monitor {
358    cfg: MonitorConfig,
359    pause: Arc<PauseController>,
360    vmi: OnceLock<Arc<VmiTracker>>,
361    next_approval_id: AtomicU64,
362    closed: AtomicBool,
363    rules: Mutex<PolicyCache>,
364    pending: Mutex<HashMap<u64, PendingApproval>>,
365}
366
367#[derive(Default)]
368struct PolicyCache {
369    allowed: HashSet<(ApprovalKind, String)>,
370    denied: HashSet<(ApprovalKind, String)>,
371}
372
373struct PendingApproval {
374    req: ApprovalRequest,
375    tx: mpsc::SyncSender<ApprovalDecision>,
376}
377
378impl Monitor {
379    pub fn new(cfg: MonitorConfig, pause: Arc<PauseController>) -> Arc<Self> {
380        Arc::new(Self {
381            cfg,
382            pause,
383            vmi: OnceLock::new(),
384            next_approval_id: AtomicU64::new(1),
385            closed: AtomicBool::new(false),
386            rules: Mutex::new(PolicyCache::default()),
387            pending: Mutex::new(HashMap::new()),
388        })
389    }
390
391    pub fn attach_vmi(&self, vmi: Arc<VmiTracker>) {
392        let _ = self.vmi.set(vmi);
393    }
394
395    pub fn p9_proc(&self) -> Option<ProcInfo> {
396        self.vmi.get().and_then(|v| v.last_p9_proc())
397    }
398
399    pub fn net_proc(&self) -> Option<ProcInfo> {
400        self.vmi.get().and_then(|v| v.last_net_proc())
401    }
402
403    pub fn is_active(&self) -> bool {
404        self.cfg.audit_enabled
405            || self.cfg.audit_callback.is_some()
406            || self.cfg.audit_file.is_some()
407            || self.cfg.ask_net
408            || self.cfg.ask_fs_write
409            || self.cfg.ask_sensitive_read
410    }
411
412    pub fn ask_net(&self) -> bool {
413        self.cfg.ask_net
414    }
415
416    pub fn ask_fs_write(&self) -> bool {
417        self.cfg.ask_fs_write
418    }
419
420    pub fn ask_sensitive_read(&self) -> bool {
421        self.cfg.ask_sensitive_read
422    }
423
424    pub fn pause_controller(&self) -> &Arc<PauseController> {
425        &self.pause
426    }
427
428    pub fn emit(&self, ev: AuditEvent) {
429        if let Some(f) = &self.cfg.audit_file
430            && let Ok(line) = serde_json::to_string(&ev)
431            && let Ok(mut guard) = f.lock()
432        {
433            let _ = writeln!(guard, "{line}");
434            let _ = guard.flush();
435        }
436        if let Some(cb) = &self.cfg.audit_callback {
437            cb(ev);
438        }
439    }
440
441    /// Pause the VM explicitly and emit `vm.paused`.
442    pub fn pause_vm(&self, reason: impl Into<String>) -> bool {
443        let changed = self.pause.pause();
444        if changed {
445            self.emit(AuditEvent::VmPaused {
446                ts_ms: now_unix_ms(),
447                reason: reason.into(),
448            });
449        }
450        changed
451    }
452
453    /// Resume the VM explicitly and emit `vm.resumed`.
454    pub fn resume_vm(&self) -> Option<u64> {
455        let ms = self.pause.resume();
456        if let Some(paused_ms) = ms {
457            self.emit(AuditEvent::VmResumed {
458                ts_ms: now_unix_ms(),
459                paused_ms,
460            });
461        }
462        ms
463    }
464
465    /// Request an external decision for an intercepted operation.
466    /// Checks cached `AllowAlways` / `DenyAlways` rules first; if unknown, holds the calling
467    /// host driver thread (and optionally freezes the entire guest VM if `freeze_on_ask`) until
468    /// resolved via `approval_callback` or [`Self::resolve_approval`].
469    pub fn request_approval(
470        &self,
471        kind: ApprovalKind,
472        remember_key: &str,
473        target: String,
474        detail: Option<String>,
475    ) -> ApprovalDecision {
476        if self.closed.load(Ordering::SeqCst) {
477            return ApprovalDecision::DenyOnce;
478        }
479        let cache_key = (kind, remember_key.to_string());
480        {
481            let rules = self.rules.lock().unwrap();
482            if rules.allowed.contains(&cache_key) {
483                return ApprovalDecision::AllowAlways;
484            }
485            if rules.denied.contains(&cache_key) {
486                return ApprovalDecision::DenyAlways;
487            }
488        }
489
490        let id = self.next_approval_id.fetch_add(1, Ordering::SeqCst);
491        let proc_info = match kind {
492            ApprovalKind::NetConnect => self.net_proc(),
493            ApprovalKind::FsWrite | ApprovalKind::FsSensitiveRead => self.p9_proc(),
494        };
495        let req = ApprovalRequest {
496            approval_id: id,
497            kind,
498            target: target.clone(),
499            detail: detail.clone(),
500            proc: proc_info.clone(),
501        };
502
503        let froze = if self.cfg.freeze_on_ask {
504            self.pause_vm(format!("approval #{id}: {target}"))
505        } else {
506            false
507        };
508
509        self.emit(AuditEvent::ApprovalRequired {
510            ts_ms: now_unix_ms(),
511            approval_id: id,
512            kind,
513            target: target.clone(),
514            detail,
515            proc: proc_info,
516        });
517
518        let decision = if let Some(cb) = &self.cfg.approval_callback {
519            cb(&req)
520        } else {
521            let (tx, rx) = mpsc::sync_channel(1);
522            {
523                let mut map = self.pending.lock().unwrap();
524                if self.closed.load(Ordering::SeqCst) {
525                    if froze {
526                        self.resume_vm();
527                    }
528                    return ApprovalDecision::DenyOnce;
529                }
530                map.insert(id, PendingApproval { req, tx });
531            }
532            rx.recv().unwrap_or(ApprovalDecision::DenyOnce)
533        };
534
535        match decision {
536            ApprovalDecision::AllowAlways => {
537                self.rules.lock().unwrap().allowed.insert(cache_key);
538            }
539            ApprovalDecision::DenyAlways => {
540                self.rules.lock().unwrap().denied.insert(cache_key);
541            }
542            ApprovalDecision::AllowOnce | ApprovalDecision::DenyOnce => {}
543        }
544
545        self.emit(AuditEvent::ApprovalResolved {
546            ts_ms: now_unix_ms(),
547            approval_id: id,
548            kind,
549            target,
550            decision,
551        });
552
553        if froze {
554            self.resume_vm();
555        }
556        decision
557    }
558
559    /// Resolve a pending approval by `approval_id` (returns `false` if not found).
560    pub fn resolve_approval(&self, approval_id: u64, decision: ApprovalDecision) -> bool {
561        let entry = self.pending.lock().unwrap().remove(&approval_id);
562        match entry {
563            Some(p) => {
564                let _ = p.tx.send(decision);
565                true
566            }
567            None => false,
568        }
569    }
570
571    /// Snapshot currently pending approval requests.
572    pub fn pending_approvals(&self) -> Vec<ApprovalRequest> {
573        self.pending
574            .lock()
575            .unwrap()
576            .values()
577            .map(|p| p.req.clone())
578            .collect()
579    }
580
581    /// Unblock all pending approvals and pauses during VM shutdown.
582    pub fn shutdown(&self) {
583        self.closed.store(true, Ordering::SeqCst);
584        let drained: Vec<PendingApproval> = self
585            .pending
586            .lock()
587            .unwrap()
588            .drain()
589            .map(|(_, p)| p)
590            .collect();
591        for p in drained {
592            let _ = p.tx.send(ApprovalDecision::DenyOnce);
593        }
594        self.pause.abort();
595    }
596}
597
598/// Interactive terminal prompt callback for CLI `--ask-*` usage (reads from `/dev/tty` pre-opened
599/// before Landlock on Unix, or `CONIN$`/`CONOUT$` on Windows, falling back to deny if non-interactive).
600pub fn terminal_approval_callback() -> ApprovalCallback {
601    #[cfg(unix)]
602    let tty_handles: Option<Arc<Mutex<(File, File)>>> = OpenOptions::new()
603        .read(true)
604        .write(true)
605        .open("/dev/tty")
606        .ok()
607        .and_then(|f| f.try_clone().ok().map(|w| Arc::new(Mutex::new((f, w)))));
608
609    #[cfg(windows)]
610    let tty_handles: Option<Arc<Mutex<(File, File)>>> = OpenOptions::new()
611        .read(true)
612        .open("CONIN$")
613        .ok()
614        .and_then(|r| {
615            OpenOptions::new()
616                .write(true)
617                .open("CONOUT$")
618                .ok()
619                .map(|w| Arc::new(Mutex::new((r, w))))
620        });
621
622    #[cfg(not(any(unix, windows)))]
623    let tty_handles: Option<Arc<Mutex<(File, File)>>> = None;
624
625    Arc::new(move |req: &ApprovalRequest| {
626        let Some(tty) = &tty_handles else {
627            eprintln!(
628                "[unkernel-rs] approval #{} ({:?} {}): no interactive console available -> DENY",
629                req.approval_id, req.kind, req.target
630            );
631            return ApprovalDecision::DenyOnce;
632        };
633        let mut guard = tty.lock().unwrap();
634        let (ref mut rd, ref mut wr) = *guard;
635        let detail = req
636            .detail
637            .as_deref()
638            .map(|d| format!(" ({d})"))
639            .unwrap_or_default();
640        let proc_tag = req
641            .proc
642            .as_ref()
643            .map(|p| format!(" [proc={} pid={}]", p.comm, p.pid))
644            .unwrap_or_default();
645        let _ = write!(
646            wr,
647            "\n[SANDBOX APPROVAL #{}] {:?}: {}{}{}\n  [a]llow once / [A]llow always / [d]eny once / [D]eny always > ",
648            req.approval_id, req.kind, req.target, detail, proc_tag
649        );
650        let _ = wr.flush();
651
652        let mut reader = std::io::BufReader::new(rd);
653        let mut line = String::new();
654        if reader.read_line(&mut line).is_err() {
655            return ApprovalDecision::DenyOnce;
656        }
657        match line.trim() {
658            "a" | "y" | "allow" => ApprovalDecision::AllowOnce,
659            "A" | "Y" | "always" => ApprovalDecision::AllowAlways,
660            "D" | "never" => ApprovalDecision::DenyAlways,
661            _ => ApprovalDecision::DenyOnce,
662        }
663    })
664}
665
666/// Heuristic detector for credential/secret paths commonly targeted by supply-chain malware
667/// (e.g. Shai-Hulud scanning for `.env`, `.npmrc`, AWS/GitHub/SSH keys, kubeconfigs).
668pub fn is_sensitive_path(path: &str) -> bool {
669    let lower = path.replace('\\', "/").to_ascii_lowercase();
670    let file_name = lower.rsplit('/').next().unwrap_or(&lower);
671
672    if file_name == ".env"
673        || file_name.starts_with(".env.")
674        || file_name == ".npmrc"
675        || file_name == ".netrc"
676        || file_name == ".pypirc"
677        || file_name == ".git-credentials"
678        || file_name == "credentials"
679        || file_name == "credentials.json"
680        || file_name == "id_rsa"
681        || file_name == "id_ed25519"
682        || file_name == "id_ecdsa"
683        || file_name == "id_dsa"
684        || file_name.ends_with(".pem")
685        || file_name.ends_with(".key")
686        || file_name.ends_with(".p12")
687        || file_name.ends_with(".pfx")
688    {
689        return true;
690    }
691
692    if lower.contains("/.ssh/")
693        || lower.starts_with(".ssh/")
694        || lower.contains("/.aws/")
695        || lower.starts_with(".aws/")
696        || lower.contains("/.gnupg/")
697        || lower.starts_with(".gnupg/")
698        || lower.contains("/.kube/")
699        || lower.starts_with(".kube/")
700        || lower.contains("/.config/gh/")
701        || lower.starts_with(".config/gh/")
702        || lower.contains("secret")
703        || lower.contains("token")
704    {
705        return true;
706    }
707    false
708}
709
710/// Extract the TLS Server Name Indication (SNI) hostname from an outbound TLS `ClientHello`
711/// record (RFC 5246 / RFC 8446). Returns `None` if `data` is not a TLS ClientHello with SNI.
712pub fn extract_tls_sni(data: &[u8]) -> Option<String> {
713    // TLS record header: content_type=0x16 (Handshake), version=0x03 0x00..0x04, length (u16)
714    if data.len() < 43 || data[0] != 0x16 || data[1] != 0x03 {
715        return None;
716    }
717    let rec_len = u16::from_be_bytes([data[3], data[4]]) as usize;
718    let end = data.len().min(5 + rec_len);
719    if end < 43 {
720        return None;
721    }
722    // Handshake header: msg_type=0x01 (ClientHello), 3-byte length
723    if data[5] != 0x01 {
724        return None;
725    }
726    let mut p = 9usize; // skip record(5) + handshake_hdr(4)
727    p += 2 + 32; // client_version(2) + random(32)
728    if p >= end {
729        return None;
730    }
731    let sid_len = data[p] as usize;
732    p += 1 + sid_len;
733    if p + 2 > end {
734        return None;
735    }
736    let cs_len = u16::from_be_bytes([data[p], data[p + 1]]) as usize;
737    p += 2 + cs_len;
738    if p + 1 > end {
739        return None;
740    }
741    let comp_len = data[p] as usize;
742    p += 1 + comp_len;
743    if p + 2 > end {
744        return None;
745    }
746    let ext_total = u16::from_be_bytes([data[p], data[p + 1]]) as usize;
747    p += 2;
748    let ext_end = end.min(p + ext_total);
749
750    while p + 4 <= ext_end {
751        let ext_type = u16::from_be_bytes([data[p], data[p + 1]]);
752        let ext_len = u16::from_be_bytes([data[p + 2], data[p + 3]]) as usize;
753        p += 4;
754        if p + ext_len > ext_end {
755            break;
756        }
757        if ext_type == 0x0000 && ext_len >= 5 {
758            // server_name_list: list_len(2), name_type(1)==0 (host_name), name_len(2), bytes
759            let mut ep = p + 2;
760            let list_end = p + ext_len;
761            while ep + 3 <= list_end {
762                let name_type = data[ep];
763                let name_len = u16::from_be_bytes([data[ep + 1], data[ep + 2]]) as usize;
764                ep += 3;
765                if ep + name_len > list_end {
766                    break;
767                }
768                if name_type == 0 {
769                    return std::str::from_utf8(&data[ep..ep + name_len])
770                        .ok()
771                        .map(|s| s.to_string());
772                }
773                ep += name_len;
774            }
775        }
776        p += ext_len;
777    }
778    None
779}
780
781/// Extract HTTP/1.x `(method, path, Host)` from the beginning of a cleartext outbound TCP stream.
782pub fn extract_http_request(data: &[u8]) -> Option<(String, String, Option<String>)> {
783    let head = std::str::from_utf8(&data[..data.len().min(2048)]).ok()?;
784    let mut lines = head.split("\r\n");
785    let first = lines.next()?;
786    let mut parts = first.split_whitespace();
787    let method = parts.next()?;
788    if !matches!(
789        method,
790        "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS" | "CONNECT"
791    ) {
792        return None;
793    }
794    let path = parts.next()?;
795    let proto = parts.next()?;
796    if !proto.starts_with("HTTP/1.") {
797        return None;
798    }
799    let mut host = None;
800    for line in lines {
801        if line.is_empty() {
802            break;
803        }
804        if let Some((k, v)) = line.split_once(':')
805            && k.eq_ignore_ascii_case("host")
806        {
807            host = Some(v.trim().to_string());
808            break;
809        }
810    }
811    Some((method.to_string(), path.to_string(), host))
812}
813
814pub fn format_net_target(domain: Option<&str>, ip: Ipv4Addr, port: u16) -> (String, String) {
815    match domain {
816        Some(d) => (d.to_ascii_lowercase(), format!("{d}:{port}")),
817        None => (ip.to_string(), format!("{ip}:{port}")),
818    }
819}
820
821#[cfg(test)]
822mod tests {
823    use super::*;
824
825    #[test]
826    fn sensitive_path_detection_catches_supply_chain_targets() {
827        assert!(is_sensitive_path(".env"));
828        assert!(is_sensitive_path("app/.env.production"));
829        assert!(is_sensitive_path(".npmrc"));
830        assert!(is_sensitive_path(".ssh/id_ed25519"));
831        assert!(is_sensitive_path(".aws/credentials"));
832        assert!(is_sensitive_path("certs/private.pem"));
833        assert!(is_sensitive_path("config/github_token.txt"));
834        assert!(!is_sensitive_path("src/main.rs"));
835        assert!(!is_sensitive_path("package.json"));
836        assert!(!is_sensitive_path("README.md"));
837    }
838
839    #[test]
840    fn extracts_tls_sni_from_client_hello() {
841        // Minimal synthetic TLS 1.2 ClientHello containing SNI "evil.example.com"
842        let host = b"evil.example.com";
843        let mut sni_ext = Vec::new();
844        let entry_len = 1 + 2 + host.len();
845        sni_ext.extend_from_slice(&(entry_len as u16).to_be_bytes());
846        sni_ext.push(0); // host_name
847        sni_ext.extend_from_slice(&(host.len() as u16).to_be_bytes());
848        sni_ext.extend_from_slice(host);
849
850        let mut exts = Vec::new();
851        exts.extend_from_slice(&0x0000u16.to_be_bytes()); // SNI ext type
852        exts.extend_from_slice(&(sni_ext.len() as u16).to_be_bytes());
853        exts.extend_from_slice(&sni_ext);
854
855        let mut body = Vec::new();
856        body.extend_from_slice(&[0x03, 0x03]); // TLS 1.2
857        body.extend_from_slice(&[0u8; 32]); // random
858        body.push(0); // session_id len
859        body.extend_from_slice(&2u16.to_be_bytes()); // cipher suites len
860        body.extend_from_slice(&[0x13, 0x01]);
861        body.push(1); // compression len
862        body.push(0);
863        body.extend_from_slice(&(exts.len() as u16).to_be_bytes());
864        body.extend_from_slice(&exts);
865
866        let mut hs = Vec::new();
867        hs.push(0x01); // ClientHello
868        let blen = body.len();
869        hs.push(((blen >> 16) & 0xff) as u8);
870        hs.push(((blen >> 8) & 0xff) as u8);
871        hs.push((blen & 0xff) as u8);
872        hs.extend_from_slice(&body);
873
874        let mut rec = Vec::new();
875        rec.extend_from_slice(&[0x16, 0x03, 0x01]);
876        rec.extend_from_slice(&(hs.len() as u16).to_be_bytes());
877        rec.extend_from_slice(&hs);
878
879        assert_eq!(extract_tls_sni(&rec).as_deref(), Some("evil.example.com"));
880        assert_eq!(extract_tls_sni(b"GET / HTTP/1.1\r\n\r\n"), None);
881    }
882
883    #[test]
884    fn extracts_http_method_path_and_host() {
885        let req =
886            b"POST /exfil?a=1 HTTP/1.1\r\nHost: webhook.site\r\nContent-Length: 5\r\n\r\nhello";
887        assert_eq!(
888            extract_http_request(req),
889            Some((
890                "POST".to_string(),
891                "/exfil?a=1".to_string(),
892                Some("webhook.site".to_string())
893            ))
894        );
895        assert_eq!(extract_http_request(b"\x16\x03\x01binary"), None);
896    }
897}