安装部署

系统要求: Go 1.21+, Rust 1.70+, Docker 20.10+
1

克隆项目

# 克隆仓库
git clone https://github.com/your-username/WasmSentinel
cd WasmSentinel

# 检查依赖
go version  # 需要 1.21+
rustc --version  # 需要 1.70+
docker --version  # 需要 20.10+
2

构建项目

# 自动构建
./scripts/build.sh

# 手动构建
cd rules/suspicious-shell
cargo build --target wasm32-wasi --release
cd ../../host
go mod tidy
go build -o ../wasmsentinel ./cmd/main.go
3

启动服务

# 直接启动
./wasmsentinel

# Docker 部署
docker-compose up -d

# Kubernetes 部署
kubectl apply -f k8s/

配置说明

环境变量配置

# 基础配置
export WASM_RULES_DIR=./rules
export LOG_LEVEL=info
export METRICS_PORT=8080
export HEALTH_PORT=8080

# 高级配置
export WASM_ENGINE_TYPE=wasmtime  # wasmtime 或 simple
export EVENT_BUFFER_SIZE=1000
export THREAT_THRESHOLD=0.7

配置文件示例

# config.yaml
server:
  host: "0.0.0.0"
  port: 8080
  metrics_path: "/metrics"
  health_path: "/health"

engine:
  type: "wasmtime"
  rules_dir: "./rules"
  max_instances: 10

logging:
  level: "info"
  format: "json"
  output: "stdout"

monitoring:
  prometheus:
    enabled: true
    port: 9090
  
collectors:
  process:
    enabled: true
    buffer_size: 1000
  network:
    enabled: true
    interfaces: ["eth0", "wlan0"]

使用指南

基本命令

# 启动检测器
./wasmsentinel --config config.yaml

# 加载特定规则
./wasmsentinel --rules ./rules/suspicious-shell/target/wasm32-wasi/release/suspicious_shell.wasm

# 调试模式
./wasmsentinel --debug --log-level debug

API接口

# 健康检查
curl http://localhost:8080/health

# 获取指标
curl http://localhost:8080/metrics

# 查看已加载规则
curl http://localhost:8080/api/rules

# 实时威胁事件流
curl http://localhost:8080/api/events/stream

测试验证

# 快速测试
./test-datasets/evaluation/quick_test.sh

# 综合测试
./test-datasets/evaluation/comprehensive_test.sh

# 性能测试
./test-datasets/evaluation/performance_test.sh

# 模拟攻击
./test-datasets/malicious-commands/reverse_shell.sh

规则开发

Rust规则开发

// src/lib.rs
use wasm_bindgen::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
pub struct Event {
    pub event_type: String,
    pub process: Option,
    pub network: Option,
    pub timestamp: i64,
}

#[derive(Serialize)]
pub struct DetectionResult {
    pub threat: bool,
    pub confidence: f32,
    pub severity: String,
    pub description: String,
}

#[wasm_bindgen]
pub fn detect_threat(event_json: &str) -> String {
    let event: Event = serde_json::from_str(event_json).unwrap_or_default();
    
    let result = match event.event_type.as_str() {
        "process" => detect_process_threat(&event),
        "network" => detect_network_threat(&event),
        _ => DetectionResult {
            threat: false,
            confidence: 0.0,
            severity: "info".to_string(),
            description: "Unknown event type".to_string(),
        }
    };
    
    serde_json::to_string(&result).unwrap()
}

fn detect_process_threat(event: &Event) -> DetectionResult {
    if let Some(process) = &event.process {
        // 检测危险命令
        let dangerous_commands = ["rm -rf", "dd if=", "mkfs", ":(){:|:&};:"];
        
        for cmd in dangerous_commands {
            if process.command.contains(cmd) {
                return DetectionResult {
                    threat: true,
                    confidence: 1.0,
                    severity: "critical".to_string(),
                    description: format!("Dangerous command detected: {}", cmd),
                };
            }
        }
    }
    
    DetectionResult {
        threat: false,
        confidence: 0.0,
        severity: "info".to_string(),
        description: "No threat detected".to_string(),
    }
}

构建规则

# 创建新规则项目
cargo new --lib my-rule
cd my-rule

# 配置 Cargo.toml
[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

# 添加 WASI 目标
rustup target add wasm32-wasi

# 构建规则
cargo build --target wasm32-wasi --release

监控集成

Prometheus指标

# prometheus.yml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'wasmsentinel'
    static_configs:
      - targets: ['localhost:8080']
    metrics_path: '/metrics'
    scrape_interval: 5s

Grafana仪表盘

{
  "dashboard": {
    "title": "WASM威胁检测",
    "panels": [
      {
        "title": "威胁检测趋势",
        "type": "graph",
        "targets": [
          {
            "expr": "rate(wasmsentinel_threats_total[5m])",
            "legendFormat": "检测率/秒"
          }
        ]
      },
      {
        "title": "威胁严重程度分布",
        "type": "piechart",
        "targets": [
          {
            "expr": "wasmsentinel_threats_total",
            "legendFormat": "{{severity}}"
          }
        ]
      }
    ]
  }
}

告警规则

# alerting.yml
groups:
  - name: wasmsentinel
    rules:
      - alert: HighThreatDetectionRate
        expr: rate(wasmsentinel_threats_total[5m]) > 10
        for: 1m
        labels:
          severity: warning
        annotations:
          summary: "威胁检测率过高"
          description: "5分钟内威胁检测率超过10次/秒"
      
      - alert: CriticalThreatDetected
        expr: wasmsentinel_threats_total{severity="critical"} > 0
        for: 0s
        labels:
          severity: critical
        annotations:
          summary: "检测到严重威胁"
          description: "发现严重级别安全威胁"

故障排除

常见问题

WASM规则加载失败

症状: 启动时提示 "failed to load wasm module"

解决:

# 检查WASM文件是否存在
ls -la rules/*/target/wasm32-wasi/release/*.wasm

# 重新构建规则
cd rules/suspicious-shell
cargo clean
cargo build --target wasm32-wasi --release

# 验证WASM文件
file target/wasm32-wasi/release/suspicious_shell.wasm

内存使用过高

症状: 内存占用持续增长

解决:

# 调整缓冲区大小
export EVENT_BUFFER_SIZE=500

# 限制WASM实例数
export MAX_WASM_INSTANCES=5

# 启用内存限制
ulimit -m 1048576  # 1GB 限制

性能问题

症状: 检测延迟过高

解决:

# 使用简化引擎
export WASM_ENGINE_TYPE=simple

# 调整线程数
export GOMAXPROCS=4

# 优化规则
# 减少正则表达式使用
# 提前返回检测结果
# 使用更高效的算法

日志分析

# 启用调试日志
./wasmsentinel --log-level debug

# 查看特定组件日志
grep "wasm_engine" /var/log/wasmsentinel.log

# 分析性能日志
grep "detection_time" /var/log/wasmsentinel.log | awk '{print $4}' | sort -n

性能分析

# Go性能分析
go tool pprof http://localhost:8080/debug/pprof/profile

# 内存分析
go tool pprof http://localhost:8080/debug/pprof/heap

# CPU分析
go tool pprof http://localhost:8080/debug/pprof/cpu