ntoseye 0.25.0

WinDbg-like kernel debugger for Windows, from Linux and macOS
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
use std::{
    fs,
    net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket},
    path::PathBuf,
    time::{SystemTime, UNIX_EPOCH},
};

#[cfg(target_os = "linux")]
use std::path::Path;

use dialoguer::{Confirm, Input, Select};
use owo_colors::OwoColorize;

#[cfg(any(target_os = "linux", test))]
use crate::DEFAULT_GDB_ADDR;
use crate::{
    DEFAULT_KD_SOCKET,
    error::{Error, Result},
    symbols,
};

#[cfg(target_os = "linux")]
mod libvirt;
#[cfg(any(target_os = "macos", test))]
mod utm;
#[cfg(target_os = "linux")]
mod vmware;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
    Configure,
    Remove,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BackendSelection {
    Kd,
    KdNet,
    #[cfg(any(target_os = "linux", test))]
    Gdb,
    #[cfg(any(target_os = "linux", test))]
    KdAndGdb,
    Memory,
}

impl BackendSelection {
    pub fn kd(self) -> bool {
        match self {
            Self::Kd => true,
            #[cfg(any(target_os = "linux", test))]
            Self::KdAndGdb => true,
            _ => false,
        }
    }

    #[cfg(any(target_os = "linux", test))]
    pub fn gdb(self) -> bool {
        matches!(self, Self::Gdb | Self::KdAndGdb)
    }
}

#[derive(Clone, Debug)]
pub struct Guest {
    pub id: String,
    pub name: String,
    pub state: String,
    pub stopped: bool,
}

#[derive(Clone, Debug)]
pub enum ProbeStatus {
    Detected(String),
    Unavailable(String),
    NotDetected,
}

#[derive(Clone, Copy, Debug)]
pub struct ConfigureRequest {
    pub action: Action,
    pub backend: Option<BackendSelection>,
    pub kdnet_host: Option<Ipv4Addr>,
    #[cfg(any(target_os = "linux", test))]
    pub vmcoreinfo: bool,
}

#[derive(Clone, Debug, Default)]
pub struct Instructions {
    pub guest: Vec<String>,
    pub run: Vec<String>,
    pub notes: Vec<String>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct GuestInspection {
    pub targets: Vec<ConfiguredTarget>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConfiguredTarget {
    pub backend: BackendSelection,
    pub endpoint: String,
    pub guest_port: Option<usize>,
    pub elevated: bool,
}

impl ConfiguredTarget {
    pub fn kd(endpoint: impl Into<String>, guest_port: usize, elevated: bool) -> Self {
        Self {
            backend: BackendSelection::Kd,
            endpoint: endpoint.into(),
            guest_port: Some(guest_port),
            elevated,
        }
    }

    #[cfg(any(target_os = "linux", test))]
    pub fn gdb(endpoint: impl Into<String>) -> Self {
        Self {
            backend: BackendSelection::Gdb,
            endpoint: endpoint.into(),
            guest_port: None,
            elevated: false,
        }
    }

    fn label(&self) -> &'static str {
        match self.backend {
            BackendSelection::Kd => "KD",
            BackendSelection::KdNet => {
                unreachable!("KDNET guest configuration is not host-inspectable")
            }
            #[cfg(any(target_os = "linux", test))]
            BackendSelection::Gdb => "GDB",
            #[cfg(any(target_os = "linux", test))]
            BackendSelection::KdAndGdb => {
                unreachable!("status targets represent one configured backend")
            }
            BackendSelection::Memory => {
                unreachable!("status targets represent one configured backend")
            }
        }
    }

    fn run_command(&self) -> String {
        let executable = if self.elevated {
            "sudo ntoseye"
        } else {
            "ntoseye"
        };
        match self.backend {
            BackendSelection::Kd if self.endpoint == DEFAULT_KD_SOCKET => executable.to_string(),
            BackendSelection::Kd => {
                format!("{executable} --connect {}", shell_quote(&self.endpoint))
            }
            BackendSelection::KdNet => {
                unreachable!("KDNET guest configuration is not host-inspectable")
            }
            #[cfg(any(target_os = "linux", test))]
            BackendSelection::Gdb if self.endpoint == DEFAULT_GDB_ADDR => {
                format!("{executable} --backend gdb")
            }
            #[cfg(any(target_os = "linux", test))]
            BackendSelection::Gdb => format!(
                "{executable} --backend gdb --connect {}",
                shell_quote(&self.endpoint)
            ),
            #[cfg(any(target_os = "linux", test))]
            BackendSelection::KdAndGdb => {
                unreachable!("status targets represent one configured backend")
            }
            BackendSelection::Memory => {
                unreachable!("status targets represent one configured backend")
            }
        }
    }
}

pub struct ApplyResult {
    pub backup: PathBuf,
}

pub trait ConfigurationPlan {
    fn changes(&self) -> &[String];
    fn instructions(&self) -> &Instructions;
    fn apply(&self) -> Result<ApplyResult>;
}

pub trait Configurator {
    fn name(&self) -> &'static str;
    fn probe(&self) -> ProbeStatus;
    fn guests(&self) -> Result<Vec<Guest>>;
    fn inspect(&self, guest: &Guest) -> Result<GuestInspection>;
    fn supported_backends(&self) -> &'static [BackendSelection];
    #[cfg(any(target_os = "linux", test))]
    fn supports_vmcoreinfo(&self) -> bool {
        false
    }
    fn plan(&self, guest: &Guest, request: ConfigureRequest) -> Result<Box<dyn ConfigurationPlan>>;
}

pub fn kdnet_instructions(request: ConfigureRequest, elevated: bool) -> Instructions {
    let host = request
        .kdnet_host
        .expect("KDNET configure requests have a host IP");
    let executable = if elevated { "sudo ntoseye" } else { "ntoseye" };
    Instructions {
        guest: vec![
            "bcdedit /debug on".to_string(),
            format!("bcdedit /dbgsettings net hostip:{host} port:50000"),
            "Restart-Computer".to_string(),
        ],
        run: vec![format!("{executable} --backend kdnet --kdnet-key KEY")],
        notes: vec![
            format!(
                "Prefer `kdnet.exe {host} 50000` when available; it validates the debug NIC and configures busparams."
            ),
            "Replace KEY with the four-part key printed by kdnet.exe or bcdedit.".to_string(),
            "Permit inbound UDP port 50000 through the host firewall.".to_string(),
        ],
    }
}

pub fn run_interactive() -> Result<()> {
    let configurators = host_configurators();
    let probes = configurators
        .iter()
        .map(|configurator| configurator.probe())
        .collect::<Vec<_>>();
    let hypervisor_items = configurators
        .iter()
        .zip(&probes)
        .map(|(configurator, probe)| format_probe(configurator.name(), probe))
        .collect::<Vec<_>>();

    let Some(hypervisor_idx) = prompt_select("Hypervisor", &hypervisor_items)? else {
        return cancelled();
    };
    let configurator = &configurators[hypervisor_idx];
    match &probes[hypervisor_idx] {
        ProbeStatus::Detected(_) => {}
        ProbeStatus::Unavailable(reason) => {
            return Err(Error::DebugInfo(format!(
                "{} was detected but is unavailable: {reason}",
                configurator.name()
            )));
        }
        ProbeStatus::NotDetected => {
            return Err(Error::DebugInfo(format!(
                "{} was not detected on this host",
                configurator.name()
            )));
        }
    }

    let guests = configurator.guests()?;
    if guests.is_empty() {
        return Err(Error::DebugInfo(format!(
            "{} reported no virtual machines",
            configurator.name()
        )));
    }
    let guest_items = guests
        .iter()
        .map(|guest| format!("{} ({})", guest.name, guest.state))
        .collect::<Vec<_>>();
    let Some(guest_idx) = prompt_select("Virtual machine", &guest_items)? else {
        return cancelled();
    };
    let guest = &guests[guest_idx];
    if !guest.stopped {
        return Err(Error::DebugInfo(format!(
            "'{}' is {}; shut it down before changing its configuration",
            guest.name, guest.state
        )));
    }

    let action_items = vec![
        "configure debug backend".to_string(),
        "remove ntoseye debug configuration".to_string(),
    ];
    let action = match prompt_select("Action", &action_items)? {
        Some(0) => Action::Configure,
        Some(1) => Action::Remove,
        _ => return cancelled(),
    };

    let backend = if action == Action::Configure {
        let supported = configurator.supported_backends();
        let items = supported
            .iter()
            .map(|backend| backend_label(*backend))
            .collect::<Vec<_>>();
        let Some(selected) = prompt_select("Backend", &items)? else {
            return cancelled();
        };
        let backend = supported[selected];
        if backend == BackendSelection::Memory {
            println!();
            println!(
                "{}",
                "No host or guest configuration is required for memory introspection.".green()
            );
            println!("run:");
            println!("  ntoseye --backend memory");
            return Ok(());
        }
        Some(backend)
    } else {
        None
    };
    let kdnet_host = if backend == Some(BackendSelection::KdNet) {
        Some(prompt_ipv4(
            "Host IPv4 address reachable from the guest",
            default_host_ipv4(),
        )?)
    } else {
        None
    };

    #[cfg(any(target_os = "linux", test))]
    let vmcoreinfo = action == Action::Configure
        && configurator.supports_vmcoreinfo()
        && prompt_confirm(
            "Enable crash-dump generation (vmcoreinfo, used by 'virsh dump --format=win-dmp')?",
        )?;
    let plan = configurator.plan(
        guest,
        ConfigureRequest {
            action,
            backend,
            kdnet_host,
            #[cfg(any(target_os = "linux", test))]
            vmcoreinfo,
        },
    )?;

    if plan.changes().is_empty() {
        println!();
        println!("No configuration changes needed for '{}'.", guest.name);
        print_instructions(plan.instructions());
        return Ok(());
    }

    println!();
    println!("{}", "Planned changes".bold());
    for change in plan.changes() {
        println!("  {} {change}", "+".green());
    }
    println!();
    if !prompt_confirm("Apply changes?")? {
        return cancelled();
    }

    let applied = plan.apply()?;
    println!();
    println!("{}", "Configuration applied.".green());
    println!("backup: {}", applied.backup.display());
    print_instructions(plan.instructions());
    Ok(())
}

pub fn print_status() -> Result<()> {
    let configurators = host_configurators();
    for (index, configurator) in configurators.iter().enumerate() {
        if index > 0 {
            println!();
        }
        let probe = configurator.probe();
        println!("{}", format_probe(configurator.name(), &probe).bold());
        if !matches!(probe, ProbeStatus::Detected(_)) {
            continue;
        }

        let guests = match configurator.guests() {
            Ok(guests) => guests,
            Err(error) => {
                println!("  unavailable: {error}");
                continue;
            }
        };
        if guests.is_empty() {
            println!("  no virtual machines");
            continue;
        }
        for guest in &guests {
            match configurator.inspect(guest) {
                Ok(inspection) => print!("{}", render_guest_status(guest, &inspection)),
                Err(error) => {
                    println!("  {} ({})", guest.name, guest.state);
                    println!("    inspection failed: {error}");
                }
            }
        }
    }
    Ok(())
}

fn render_guest_status(guest: &Guest, inspection: &GuestInspection) -> String {
    let mut output = format!("  {} ({})\n", guest.name, guest.state);
    if inspection.targets.is_empty() {
        output.push_str("    Debug backend: not configured\n");
        return output;
    }

    for target in &inspection.targets {
        output.push_str(&format!("    {}\n", target.label()));
        if let Some(port) = target.guest_port {
            output.push_str(&format!("      Guest port: COM{port}\n"));
        }
        output.push_str(&format!("      Endpoint: {}\n", target.endpoint));
    }
    output.push_str("    Run\n");
    for target in &inspection.targets {
        output.push_str(&format!("      {}\n", target.run_command()));
    }
    output
}

fn host_configurators() -> Vec<Box<dyn Configurator>> {
    #[cfg(target_os = "linux")]
    {
        vec![Box::new(libvirt::Libvirt), Box::new(vmware::Vmware)]
    }
    #[cfg(target_os = "macos")]
    {
        vec![Box::new(utm::Utm)]
    }
}

fn format_probe(name: &str, status: &ProbeStatus) -> String {
    match status {
        ProbeStatus::Detected(detail) if detail.is_empty() => {
            format!("{name} ({})", "detected".green())
        }
        ProbeStatus::Detected(detail) => {
            format!("{name} ({}: {detail})", "detected".green())
        }
        ProbeStatus::Unavailable(reason) => {
            format!("{name} ({}: {reason})", "unavailable".yellow())
        }
        ProbeStatus::NotDetected => format!("{name} ({})", "not detected".dimmed()),
    }
}

fn backend_label(backend: BackendSelection) -> String {
    match backend {
        BackendSelection::Kd => {
            format!("KD (Windows kernel debugging) {}", "(recommended)".green())
        }
        BackendSelection::KdNet => "KDNET (encrypted network kernel debugging)".to_string(),
        #[cfg(any(target_os = "linux", test))]
        BackendSelection::Gdb => "GDB (hypervisor debug stub)".to_string(),
        #[cfg(any(target_os = "linux", test))]
        BackendSelection::KdAndGdb => "KD + GDB (configure both transports)".to_string(),
        BackendSelection::Memory => "Memory (passive introspection, no configuration)".to_string(),
    }
}

fn print_instructions(instructions: &Instructions) {
    if !instructions.guest.is_empty() {
        println!();
        println!("{}", "Guest setup".bold());
        for line in &instructions.guest {
            println!("  {line}");
        }
    }
    if !instructions.notes.is_empty() {
        println!();
        for note in &instructions.notes {
            println!("{} {note}", "note:".cyan().bold());
        }
    }
    if !instructions.run.is_empty() {
        println!();
        println!("{}", "Run".bold());
        for line in &instructions.run {
            println!("  {line}");
        }
    }
}

pub fn prompt_select(prompt: &str, items: &[String]) -> Result<Option<usize>> {
    let mut choices = items.to_vec();
    choices.push("cancel".to_string());
    let selected = Select::new()
        .with_prompt(prompt)
        .items(&choices)
        .default(0)
        .interact()
        .map_err(prompt_error)?;
    if selected == items.len() {
        Ok(None)
    } else {
        Ok(Some(selected))
    }
}

pub fn prompt_confirm(prompt: &str) -> Result<bool> {
    Confirm::new()
        .with_prompt(prompt)
        .default(false)
        .interact()
        .map_err(prompt_error)
}

fn prompt_ipv4(prompt: &str, default: Option<Ipv4Addr>) -> Result<Ipv4Addr> {
    let input = Input::<Ipv4Addr>::new().with_prompt(prompt);
    match default {
        Some(address) => input.default(address),
        None => input,
    }
    .interact_text()
    .map_err(prompt_error)
}

fn default_host_ipv4() -> Option<Ipv4Addr> {
    let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).ok()?;
    // UDP connect selects a route without sending traffic. The chosen local
    // address is the best general default; users can override it for NATs with
    // a special guest-visible gateway such as QEMU user networking.
    socket.connect((Ipv4Addr::new(1, 1, 1, 1), 80)).ok()?;
    socket.local_addr().ok().and_then(routable_ipv4)
}

fn routable_ipv4(address: SocketAddr) -> Option<Ipv4Addr> {
    match address.ip() {
        IpAddr::V4(ip) if !ip.is_unspecified() && !ip.is_loopback() => Some(ip),
        _ => None,
    }
}

fn prompt_error(error: dialoguer::Error) -> Error {
    Error::DebugInfo(format!("interactive prompt failed: {error}"))
}

fn cancelled() -> Result<()> {
    println!("cancelled");
    Ok(())
}

pub fn backup_file(
    hypervisor: &str,
    guest: &str,
    extension: &str,
    contents: &[u8],
) -> Result<PathBuf> {
    let root = symbols::ntoseye_home().ok_or(Error::StorageNotFound)?;
    let dir = root
        .join("config-backups")
        .join(sanitize_filename(hypervisor))
        .join(sanitize_filename(guest));
    fs::create_dir_all(&dir)?;
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|err| Error::DebugInfo(format!("system clock error: {err}")))?
        .as_secs();
    let path = dir.join(format!("{timestamp}.{extension}"));
    fs::write(&path, contents)?;
    Ok(path)
}

#[cfg(target_os = "linux")]
pub fn atomic_replace(path: &Path, contents: &[u8]) -> Result<()> {
    let parent = path.parent().ok_or_else(|| {
        Error::DebugInfo(format!(
            "configuration path has no parent: {}",
            path.display()
        ))
    })?;
    let name = path
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| {
            Error::DebugInfo(format!("invalid configuration path: {}", path.display()))
        })?;
    let temporary = parent.join(format!(".{name}.ntoseye.tmp"));
    fs::copy(path, &temporary)?;
    if let Err(error) = fs::write(&temporary, contents) {
        let _ = fs::remove_file(&temporary);
        return Err(error.into());
    }
    if let Err(error) = fs::rename(&temporary, path) {
        let _ = fs::remove_file(&temporary);
        return Err(error.into());
    }
    Ok(())
}

pub fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

fn sanitize_filename(name: &str) -> String {
    name.chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') {
                ch
            } else {
                '_'
            }
        })
        .collect()
}

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

    #[test]
    fn backup_names_are_path_safe() {
        assert_eq!(sanitize_filename("win/11 test"), "win_11_test");
    }

    #[test]
    fn shell_values_are_quoted() {
        assert_eq!(shell_quote("it's here"), "'it'\\''s here'");
    }

    #[test]
    fn default_targets_produce_minimal_run_commands() {
        assert_eq!(
            ConfiguredTarget::kd(DEFAULT_KD_SOCKET, 1, false).run_command(),
            "ntoseye"
        );
        assert_eq!(
            ConfiguredTarget::gdb(DEFAULT_GDB_ADDR).run_command(),
            "ntoseye --backend gdb"
        );
    }

    #[test]
    fn status_renders_configured_targets_and_commands() {
        let guest = Guest {
            id: "windows".to_string(),
            name: "Windows".to_string(),
            state: "running".to_string(),
            stopped: false,
        };
        let inspection = GuestInspection {
            targets: vec![
                ConfiguredTarget::kd(DEFAULT_KD_SOCKET, 2, false),
                ConfiguredTarget::gdb(DEFAULT_GDB_ADDR),
            ],
        };
        assert_eq!(
            render_guest_status(&guest, &inspection),
            concat!(
                "  Windows (running)\n",
                "    KD\n",
                "      Guest port: COM2\n",
                "      Endpoint: /tmp/ntoseye-kd.sock\n",
                "    GDB\n",
                "      Endpoint: 127.0.0.1:1234\n",
                "    Run\n",
                "      ntoseye\n",
                "      ntoseye --backend gdb\n",
            )
        );
    }

    #[test]
    fn status_marks_guests_without_managed_transports() {
        let guest = Guest {
            id: "windows".to_string(),
            name: "Windows".to_string(),
            state: "stopped".to_string(),
            stopped: true,
        };
        assert_eq!(
            render_guest_status(&guest, &GuestInspection::default()),
            "  Windows (stopped)\n    Debug backend: not configured\n"
        );
    }

    #[test]
    fn kdnet_setup_uses_selected_host_and_runtime_key_placeholder() {
        let instructions = kdnet_instructions(
            ConfigureRequest {
                action: Action::Configure,
                backend: Some(BackendSelection::KdNet),
                kdnet_host: Some(Ipv4Addr::new(192, 168, 122, 1)),
                vmcoreinfo: false,
            },
            false,
        );
        assert_eq!(
            instructions.guest,
            [
                "bcdedit /debug on",
                "bcdedit /dbgsettings net hostip:192.168.122.1 port:50000",
                "Restart-Computer",
            ]
        );
        assert_eq!(
            instructions.run,
            ["ntoseye --backend kdnet --kdnet-key KEY"]
        );
        assert!(
            instructions
                .notes
                .iter()
                .any(|note| note.contains("kdnet.exe 192.168.122.1 50000"))
        );
    }

    #[test]
    fn default_host_address_accepts_only_non_loopback_ipv4() {
        assert_eq!(
            routable_ipv4("192.168.122.1:50000".parse().unwrap()),
            Some(Ipv4Addr::new(192, 168, 122, 1))
        );
        assert_eq!(routable_ipv4("127.0.0.1:50000".parse().unwrap()), None);
        assert_eq!(routable_ipv4("[::1]:50000".parse().unwrap()), None);
    }
}