terminal-mcp 0.1.5

Model Context Protocol (MCP) server for long-lived shell execution.
// src/security/detect/bash/rules/ssh_backdoor.rs

use tree_sitter::Node;

use crate::security::detect::bash::ast::get_command_name;
use crate::security::detect::bash::utils::{
    best_hit, collect_args, command_basename, redirect_target, unwrap_command,
};
use crate::sec_bash_detector_rule_metadata;
use crate::security::detect::{EvaluateResult, Rule, Severity, ShellContext};

const AUTHORIZED_KEYS_MARKER: &str = "authorized_keys";

/// 向 authorized_keys 写入公钥即植入 SSH 后门。
pub struct RuleSshBackdoor;

impl RuleSshBackdoor {
    sec_bash_detector_rule_metadata!(
        "bash_ssh_backdoor",
        "Detects writes to ~/.ssh/authorized_keys, a common SSH backdoor \
         used to retain remote access",
        Severity::Low
    );
}

fn analyze_command(node: &Node, source: &[u8]) -> Option<(Severity, String)> {
    let raw_cmd = get_command_name(node, source)?;
    let cmd_name = command_basename(raw_cmd);
    let args = collect_args(node, source);
    let (real_cmd, real_args) = unwrap_command(&cmd_name, &args, &["tee", "cp", "install", "mv"])?;

    match real_cmd {
        "tee" => {
            let has_append = real_args.iter().any(|a| *a == "-a" || *a == "--append");
            if let Some(t) = real_args
                .iter()
                .find(|a| a.contains(AUTHORIZED_KEYS_MARKER))
            {
                let sev = if has_append {
                    Severity::Critical
                } else {
                    Severity::High
                };
                return Some((
                    sev,
                    format!("command={:?} tee write to {:?}", raw_cmd, t),
                ));
            }
            None
        }
        "cp" | "install" | "mv" => {
            if let Some(dest) = real_args
                .last()
                .filter(|a| a.contains(AUTHORIZED_KEYS_MARKER))
            {
                return Some((
                    Severity::High,
                    format!("command={:?} {} overwrites {:?}", raw_cmd, real_cmd, dest),
                ));
            }
            None
        }
        _ => None,
    }
}

fn analyze_redirect(node: &Node, source: &[u8]) -> Option<(Severity, String)> {
    let (op, dest) = redirect_target(node, source)?;
    if !dest.contains(AUTHORIZED_KEYS_MARKER) {
        return None;
    }
    let sev = if op == ">>" {
        Severity::Critical
    } else {
        Severity::High
    };
    Some((
        sev,
        format!("{} write to {:?}", op, dest),
    ))
}

fn analyze(node: &Node, source: &[u8]) -> Option<(Severity, String)> {
    match node.kind() {
        "command" => analyze_command(node, source),
        "file_redirect" => analyze_redirect(node, source),
        _ => None,
    }
}

#[async_trait::async_trait]
impl Rule for RuleSshBackdoor {
    fn meta(&self) -> &crate::security::detect::RuleMetadata {
        Self::get_meta()
    }

    async fn evaluate(
        &self,
        _data: &str,
        ctx: &ShellContext,
    ) -> anyhow::Result<EvaluateResult> {
        let best = best_hit(ctx, analyze).await?;
        Ok(match best {
            Some((sev, evidence)) => EvaluateResult::hit_with_severity(evidence, sev),
            None => EvaluateResult::Miss,
        })
    }
}

#[cfg(test)]
mod test {
    use std::collections::HashMap;

    use super::*;
    use crate::security::detect::bash::BashDetector;
    use crate::security::detect::{DetectResult, Detector, ShellContext};

    fn get_detector() -> BashDetector {
        let ctx = ShellContext::new("/bin/bash", HashMap::new(), 100);
        BashDetector::new(ctx, 4096)
    }

    async fn expect_hit(detector: &BashDetector, payload: &str, expected: Severity) {
        let res = detector.detect(payload.to_string(), false, true).await;
        match &res {
            DetectResult::ThreatDetected(hits) => {
                let hit = hits
                    .iter()
                    .find(|h| h.rule_meta.name == "bash_ssh_backdoor")
                    .unwrap_or_else(|| {
                        panic!("payload {:?} did not trigger bash_ssh_backdoor: {:#?}", payload, res)
                    });
                assert_eq!(
                    hit.final_severity, expected,
                    "payload {:?}, evidence {:?}",
                    payload, hit.evidence
                );
            }
            _ => panic!("payload {:?} expected ThreatDetected, got {:#?}", payload, res),
        }
    }

    async fn expect_safe(detector: &BashDetector, payload: &str) {
        let res = detector.detect(payload.to_string(), false, true).await;
        let hit = match &res {
            DetectResult::ThreatDetected(hits) => {
                hits.iter().find(|h| h.rule_meta.name == "bash_ssh_backdoor")
            }
            _ => None,
        };
        assert!(
            hit.is_none(),
            "payload {:?} should not trigger bash_ssh_backdoor, got {:#?}",
            payload, res
        );
    }

    #[tokio::test]
    async fn test_ssh_backdoor_append_critical() {
        let d = get_detector();
        expect_hit(
            &d,
            "echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ' >> ~/.ssh/authorized_keys",
            Severity::Critical,
        )
        .await;
        expect_hit(&d, "echo KEY >> /root/.ssh/authorized_keys", Severity::Critical).await;
        expect_hit(&d, "printf 'k1' >> /home/u/.ssh/authorized_keys", Severity::Critical).await;
        expect_hit(&d, "cat pubkey >> authorized_keys", Severity::Critical).await;
        expect_hit(&d, "tee -a /root/.ssh/authorized_keys", Severity::Critical).await;
    }

    #[tokio::test]
    async fn test_ssh_backdoor_overwrite_high() {
        let d = get_detector();
        expect_hit(&d, "cat pub > /root/.ssh/authorized_keys", Severity::High).await;
        expect_hit(&d, "tee /root/.ssh/authorized_keys", Severity::High).await;
        expect_hit(&d, "cp /tmp/key ~/.ssh/authorized_keys", Severity::High).await;
        expect_hit(&d, "sudo tee -a /root/.ssh/authorized_keys", Severity::Critical).await;
    }

    #[tokio::test]
    async fn test_ssh_backdoor_safe() {
        let d = get_detector();
        expect_safe(&d, "cat ~/.ssh/authorized_keys").await;
        expect_safe(&d, "ssh-keyscan github.com").await;
        expect_safe(&d, "ls ~/.ssh").await;
        expect_safe(&d, "cp ~/.ssh/id_rsa.pub /tmp/pub").await;
        expect_safe(&d, "echo 'cat ~/.ssh/authorized_keys'").await;
    }
}