Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,7 @@ data/
logs/
config/


# Local environment and secret files (Zero secret leakage invariant)
.env
.env.*
!.env.example
18 changes: 18 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ killswitch-orchestrator = { path = "crates/killswitch-orchestrator" }
killswitch-server = { path = "crates/killswitch-server" }
killswitch-cli = { path = "crates/killswitch-cli" }
killswitch-conformal = { path = "crates/killswitch-conformal" }
killswitch-kernel-patcher = { path = "crates/killswitch-kernel-patcher" }


# OpenTelemetry & OpenLineage Integration
Expand Down Expand Up @@ -82,6 +83,8 @@ windows = { version = "0.58", features = [
"Win32_System_Threading",
"Win32_System_Diagnostics_ToolHelp",
"Win32_Security",
"Win32_Security_Isolation",
"Win32_Security_Authorization",
"Win32_Security_WinTrust",
"Win32_Security_Cryptography",
"Win32_System_LibraryLoader",
Expand Down
1 change: 1 addition & 0 deletions crates/killswitch-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ killswitch-telemetry = { workspace = true }
killswitch-orchestrator = { workspace = true }
killswitch-server = { workspace = true }
killswitch-conformal = { workspace = true }
killswitch-kernel-patcher = { workspace = true }

# Web & async runtime
axum = { workspace = true, features = ["macros"] }
Expand Down
94 changes: 94 additions & 0 deletions crates/killswitch-cli/src/bin/killswitch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,30 @@ enum Commands {
#[arg(long)]
token: Option<String>,
},

/// Scan OS kernel vulnerabilities against NVD API 2.0 / CISA KEV and orchestrate native patching
#[command(name = "patch-kernel", visible_alias = "kernel-patch")]
PatchKernel {
/// Output planned OS patch command without executing or modifying system state
#[arg(long)]
dry_run: bool,

/// Filter findings to CISA Known Exploited Vulnerabilities (KEV) only
#[arg(long)]
kev_only: bool,

/// Minimum CVSS v3.1 base score threshold (e.g. 7.0)
#[arg(long)]
min_cvss: Option<f32>,

/// Override target CPE 2.3 string (defaults to auto-detected host kernel)
#[arg(long)]
cpe: Option<String>,

/// Orchestrate native OS kernel patch workflow after scanning
#[arg(long)]
apply: bool,
},
}

#[derive(Subcommand, Debug)]
Expand Down Expand Up @@ -631,7 +655,77 @@ async fn main() -> Result<()> {
}) => {
killswitch_cli::siquery_cli::handle_siquery(query, &format, tables, sweep, token)?;
}
Some(Commands::PatchKernel {
dry_run,
kev_only,
min_cvss,
cpe,
apply,
}) => {
killswitch_cli::commands::handle_patch_kernel(dry_run, kev_only, min_cvss, cpe, apply)
.await?;
}
}

Ok(())
}

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

#[test]
fn test_patch_kernel_cli_parsing() {
let cli = Cli::try_parse_from([
"killswitch",
"patch-kernel",
"--dry-run",
"--kev-only",
"--min-cvss",
"7.5",
"--cpe",
"cpe:2.3:o:microsoft:windows_11_23h2:*:*:*:*:*:*:*:*",
"--apply",
])
.expect("Failed to parse patch-kernel subcommand");

match cli.command {
Some(Commands::PatchKernel {
dry_run,
kev_only,
min_cvss,
cpe,
apply,
}) => {
assert!(dry_run);
assert!(kev_only);
assert_eq!(min_cvss, Some(7.5));
assert_eq!(
cpe.as_deref(),
Some("cpe:2.3:o:microsoft:windows_11_23h2:*:*:*:*:*:*:*:*")
);
assert!(apply);
}
other => panic!("Expected Commands::PatchKernel, got {:?}", other),
}
}

#[test]
fn test_patch_kernel_secret_hygiene_no_nvd_api_key_flag() {
// Assert that passing --nvd-api-key is rejected as an unrecognized argument
let res = Cli::try_parse_from([
"killswitch",
"patch-kernel",
"--nvd-api-key",
"secret_test_key",
]);
assert!(res.is_err(), "Expected error for --nvd-api-key CLI flag");
let err_msg = res.unwrap_err().to_string();
assert!(
err_msg.contains("unexpected argument")
|| err_msg.contains("not recognized")
|| err_msg.contains("--nvd-api-key")
);
}
}
3 changes: 3 additions & 0 deletions crates/killswitch-cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ use crate::client::KillSwitchClient;
use crate::verify::SubsystemVerifier;
use anyhow::{bail, Result};

pub mod patch_kernel;
pub use patch_kernel::handle_patch_kernel;

pub async fn handle_status(client: &KillSwitchClient) -> Result<()> {
let status = client.get_status().await?;
println!("\n================================================================================");
Expand Down
172 changes: 172 additions & 0 deletions crates/killswitch-cli/src/commands/patch_kernel.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
//! # OS Kernel Vulnerability Scanning & Native Patch Orchestration CLI Handler

use anyhow::Result;
use killswitch_kernel_patcher::{
is_elevated, HostKernelInfo, KernelPatcher, PatcherError, ScanOptions,
};

/// Handles the `killswitch patch-kernel` CLI subcommand.
///
/// Discovers the running OS kernel, queries the NVD API 2.0 for matching CVEs / CISA KEV entries,
/// formats structured findings, and optionally invokes OS-native kernel patch workflows.
///
/// # Secret Hygiene Invariant
/// `NVD_API_KEY` is NEVER accepted as a CLI parameter (preventing OS process-table leaks).
/// It is read strictly from `std::env::var("NVD_API_KEY")`.
pub async fn handle_patch_kernel(
dry_run: bool,
kev_only: bool,
min_cvss: Option<f32>,
cpe: Option<String>,
apply: bool,
) -> Result<()> {
// 1. Host Kernel Discovery
let host_info = match HostKernelInfo::detect_host_kernel() {
Ok(info) => info,
Err(e) => {
eprintln!("❌ Host kernel detection failed: {}", e);
return Err(e.into());
}
};

let target_cpe = cpe.unwrap_or_else(|| host_info.cpe23.clone());
let has_env_key = std::env::var("NVD_API_KEY").is_ok();

println!("\n================================================================================");
println!("🛡️ HOST KERNEL DISCOVERY & NVD VULNERABILITY SCANNER");
println!("================================================================================");
println!(" OS Family: {}", host_info.os_family);
println!(" OS Version: {}", host_info.os_version);
println!(" Kernel Release: {}", host_info.kernel_release);
println!(" Architecture: {}", host_info.architecture);
println!(" Target CPE 2.3: {}", target_cpe);
println!(
" NVD API Key: {}",
if has_env_key {
"Configured via NVD_API_KEY environment variable"
} else {
"None (public rate-limited mode)"
}
);
if kev_only {
println!(" Filter Mode: CISA KEV Only");
}
if let Some(cvss) = min_cvss {
println!(" Min CVSS Score: {:.1}", cvss);
}
println!("================================================================================\n");

// 2. Vulnerability Scan against NVD API 2.0
println!(
"🔍 Querying NVD API 2.0 for kernel vulnerabilities affecting '{}'...",
target_cpe
);

let options = ScanOptions {
cpe: Some(target_cpe.clone()),
min_cvss_score: min_cvss,
kev_only,
api_key: std::env::var("NVD_API_KEY").ok(),
timeout_secs: 30,
};

let patcher = KernelPatcher::new();
match patcher.scan_kernel_vulnerabilities(&options).await {
Ok(vulns) => {
if vulns.is_empty() {
println!("✅ Zero vulnerabilities found matching the specified criteria.");
} else {
let kev_count = vulns.iter().filter(|v| v.is_cisa_kev).count();
println!(
"\n⚠️ Found {} vulnerabilities affecting target kernel ({} CISA KEV):\n",
vulns.len(),
kev_count
);
for v in &vulns {
println!("--------------------------------------------------------------------------------");
let score_str = match v.cvss_v31_score {
Some(score) => format!("{:.1}", score),
None => "N/A".to_string(),
};
let sev_str = v.cvss_v31_severity.as_deref().unwrap_or("UNKNOWN");

if v.is_cisa_kev {
println!(
"🚨 [CISA KEV] {} | CVSS v3.1: {} ({})",
v.cve_id, score_str, sev_str
);
if let Some(ref name) = v.cisa_vulnerability_name {
println!(" Vulnerability Name: {}", name);
}
if let Some(ref added) = v.cisa_exploit_add {
println!(" Added to KEV: {}", added);
}
if let Some(ref due) = v.cisa_action_due {
println!(" Remediation Due: {}", due);
}
if let Some(ref action) = v.cisa_required_action {
println!(" Required Action: {}", action);
}
} else {
println!("⚠️ {} | CVSS v3.1: {} ({})", v.cve_id, score_str, sev_str);
}
if !v.description.is_empty() {
println!(" Description: {}", v.description);
}
}
println!("--------------------------------------------------------------------------------\n");
}
}
Err(PatcherError::RateLimited) => {
eprintln!("⚠️ Rate limited by NIST NVD API 2.0. Set the NVD_API_KEY environment variable to increase NIST rate limits.");
}
Err(e) => {
eprintln!("⚠️ NVD vulnerability scan query notice: {}", e);
}
}

// 3. Patch Orchestration
let should_patch = apply || dry_run;
if should_patch {
let is_dry_run = dry_run || !apply;
println!("🔧 Orchestrating native OS kernel patch workflow...");
if is_dry_run {
println!(" [DRY-RUN SIMULATION - No kernel or OS changes will be applied]");
} else if !is_elevated() {
eprintln!("❌ Insufficient privileges: OS-native kernel patch execution requires Administrator/root privileges.");
return Err(PatcherError::InsufficientPrivileges.into());
}

let exec_result = patcher.apply_os_kernel_patch(is_dry_run).await?;
println!(
"\n================================================================================"
);
println!("🛡️ NATIVE KERNEL PATCH ORCHESTRATION RESULT");
println!(
"================================================================================"
);
println!(" Target Subsystem: {}", exec_result.os_subsystem);
println!(
" Mode: {}",
if exec_result.dry_run {
"Dry-Run Simulation"
} else {
"Live Execution"
}
);
println!(
" Command: {} {}",
exec_result.command,
exec_result.args.join(" ")
);
println!(" Success: {}", exec_result.success);
println!(" Output:\n{}", exec_result.output);
println!(
"================================================================================\n"
);
} else {
println!("💡 Tip: Pass '--apply --dry-run' (or '--dry-run') to preview OS-native patch command, or '--apply' with elevated privileges to execute.\n");
}

Ok(())
}
18 changes: 15 additions & 3 deletions crates/killswitch-cli/src/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,22 @@ impl SubsystemVerifier {

/// Executes subsystem diagnostics, optionally including Phase 8 (CAGE Governance).
pub async fn run_with_governance(cage_governance: bool) -> Result<VerificationReport> {
struct SelfDiagnosticGuard {
had_env: bool,
}
impl Drop for SelfDiagnosticGuard {
fn drop(&mut self) {
killswitch_core::wfp::set_in_process_self_diagnostic(false);
if !self.had_env {
std::env::remove_var("KILLSWITCH_SELF_DIAGNOSTIC");
}
}
}
let had_env = std::env::var("KILLSWITCH_SELF_DIAGNOSTIC").is_ok();
killswitch_core::wfp::set_in_process_self_diagnostic(true);
std::env::set_var("KILLSWITCH_SELF_DIAGNOSTIC", "1");
let res = Self::run_with_governance_inner(cage_governance).await;
std::env::remove_var("KILLSWITCH_SELF_DIAGNOSTIC");
res
let _guard = SelfDiagnosticGuard { had_env };
Self::run_with_governance_inner(cage_governance).await
}

async fn run_with_governance_inner(cage_governance: bool) -> Result<VerificationReport> {
Expand Down
Loading
Loading