a9320/code-risk-agent

GitHub: a9320/code-risk-agent

一款完全在本地 AMD GPU 上运行的 AI 驱动代码安全分析智能体,解决企业源代码无法上传云端的合规与隐私痛点。

Stars: 0 | Forks: 0

# CodeRisk Agent 🛡️ **AI 驱动的代码安全分析 — 完全在您的本地 AMD GPU 上运行** [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/) [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) [![ROCm](https://img.shields.io/badge/ROCm-7.2-red.svg)](https://rocm.docs.amd.com/) ## 为什么选择 CodeRisk Agent? 企业需要 AI 驱动的代码安全方案,但**无法将源代码上传到云端服务**。合规性要求(HIPAA、GDPR)、知识产权和公司政策都严禁此类行为。 CodeRisk Agent 解决了这个问题:**深度 AI 分析 100% 在本地 AMD Radeon GPU 上运行**。代码永远不会离开本机。 | 功能 | Semgrep | 云端 AI (Copilot) | **CodeRisk Agent** | |---------|---------|--------------------|--------------------| | 本地执行 | ✅ | ❌ | ✅ | | 理解代码逻辑 | ❌ | ✅ | ✅ | | CVE/NVD 集成 | ❌ | ❌ | ✅ | | 自学习记忆 | ❌ | ❌ | ✅ | | 证据链 | 仅模式匹配 | 黑盒 | **完全可追溯** | ## 架构 ``` User uploads code ↓ ┌───────────────────┐ │ Orchestrator │ State machine: INIT → PARSE → ANALYZE → VERIFY → REPORT └───────┬───────────┘ ↓ ┌───────┴────────┐ │ │ ↓ ↓ Agent 1 Agent 2 ← Parallel execution Static Analyzer Semantic Analyzer (CPU + tools) (GPU + LLM) │ │ └───────┬────────┘ ↓ ┌───┴───┐ │ Self- │ ← Agent 3 flags missed risks, triggers re-analysis │Reflect│ └───┬───┘ ↓ Agent 3 ← Triple cross-validation Deep Verifier (Tool + Knowledge Base + Local CVE DB) (GPU + LLM + Local DB) ↓ Agent 4 ← Structured reports Report Generator (JSON + Markdown + Terminal) ↓ ┌─────────────┐ │ Memory Layer │ Correct memory + Error memory │ (JSON) │ "Learns" from every scan └─────────────┘ ``` ### 四大 Agent | Agent | 角色 | 计算 | 功能 | |-------|------|---------|--------------| | **Agent 1:静态分析器** | 模式匹配 | CPU | 27 条检测规则(缓冲区溢出、格式化字符串、双重释放、命令注入等) | | **Agent 2:语义分析器** | LLM 驱动分析 | GPU | 验证发现结果,发现遗漏的漏洞,生成攻击场景 | | **Agent 3:深度验证器** | 三重交叉验证 | GPU + CPU | CWE 知识库 + 本地 CVE 数据库 + 自反思循环 | | **Agent 4:报告生成器** | 输出格式化 | CPU | JSON、Markdown、带有 CWE/CVE 可点击链接的 Rich 终端 | ### 独特之处 - **三重交叉验证** — 工具确认 + CWE 知识库 + 本地 CVE 数据库查询 - **自反思循环** — Agent 3 会问“我们漏掉了什么?”并重新进行分析 - **双重记忆** — 正确的模式提升置信度;错误模式抑制误报 - **证据链** — 每个风险都包含源代码片段、CWE 分类和推理分析 ## 快速开始 ### 前置条件 - Python 3.10+ - 支持 ROCm 的 AMD GPU(可选,用于 GPU 加速) - Semgrep(可选,用于增强静态分析) ### 安装 ``` git clone https://github.com/a9320/code-risk-agent.git cd code-risk-agent pip install -e . ``` ### 配置 ``` cp .env.example .env # 编辑 .env 以配置 LLM backend ``` 支持两种后端: | 后端 | 用例 | 配置 | |---------|----------|--------| | `local_llama_cpp` | 本地 GPU 推理(推荐) | 将 `LOCAL_MODEL_PATH` 设置为 GGUF 文件 | | `local_http` | 本地 llama-server | 设置 `LOCAL_HTTP_URL` | ### 数据准备(一次性设置) 首次使用前,请构建本地漏洞数据库: ``` # 下载 NVD CVE 数据 → data/vuln_db.sqlite(约 10-50MB) python scripts/download_cve_data.py --years 2023 2024 2025 2026 # 下载 OSV 依赖项漏洞数据 → data/osv/(约 100MB) python scripts/download_osv_data.py ``` ### 用法 ``` # 分析目录 code-risk analyze ./src/ # 分析单个文件 code-risk analyze vulnerable.c # 快速演示(无 LLM,快速) code-risk demo # 显示配置 code-risk info ``` ### 选项 ``` code-risk analyze [options] Options: --no-ai Disable LLM semantic analysis (fast, CPU-only) --semgrep-config Semgrep rules (default: p/default) --output Output: terminal|json|md|all (default: terminal) ``` ## 示例输出 ``` ═══════════════════════════════════════════════════════════ CodeRisk Agent — Analysis Report ═══════════════════════════════════════════════════════════ Files analyzed: 5 Total risks: 47 Analysis time: 2 min (GPU inference) ┌─────────┬──────────┬──────────────────────────────┐ │ Severity│ CWE │ Title │ ├─────────┼──────────┼──────────────────────────────┤ │ CRITICAL│ CWE-120 │ Buffer overflow: strcpy() │ │ CRITICAL│ CWE-78 │ Command injection: system() │ │ HIGH │ CWE-415 │ Double free detected │ │ HIGH │ CWE-502 │ Unsafe deserialization │ │ MEDIUM │ CWE-476 │ NULL pointer dereference │ └─────────┴──────────┴──────────────────────────────┘ Each risk includes: ✓ Source code evidence with line numbers ✓ CWE classification with MITRE link ✓ CVE references with NVD link ✓ Concrete fix suggestion ═══════════════════════════════════════════════════════════ ``` ## ROCm GPU 加速 CodeRisk Agent 通过 ROCm/HIP 针对 AMD Radeon GPU 进行了优化。 ### 性能 | 指标 | CPU | AMD GPU (HIP) | 提速 | |--------|-----|---------------|---------| | Token 生成 | 6.8 t/s | 105 t/s | **15.4×** | | Prompt 处理 | ~40 t/s | 628 t/s | **15.7×** | | VRAM 使用 | — | 41% (~19.6 GB / 48 GB) | — | ### 使用 ROCm 构建 llama.cpp ``` # 使用 HIP backend 克隆并构建 git clone https://github.com/ggerganov/llama.cpp cd llama.cpp ROCM_PATH=/opt/rocm cmake -B build -DGGML_HIP=ON -DLLAMA_BUILD_SERVER=ON cmake --build build --config Release -j$(nproc) # 下载 Qwen2.5-Coder-32B-Instruct GGUF huggingface-cli download Qwen/Qwen2.5-Coder-32B-Instruct-GGUF \ qwen2.5-coder-32b-instruct-q4_k_m.gguf --local-dir models/ # 运行推理 ./build/bin/llama-server -m models/qwen2.5-coder-32b-instruct-q4_k_m.gguf -ngl 999 -fa 1 ``` ## 项目结构 ``` code-risk-agent/ ├── main.py # CLI entry point ├── orchestrator.py # State machine pipeline ├── agents/ │ ├── static_analyzer.py # Agent 1: Pattern matching (27 rules, C + Python) │ ├── semantic_analyzer.py # Agent 2: LLM-driven analysis │ ├── deep_verifier.py # Agent 3: Triple cross-validation │ └── report_generator.py # Agent 4: Output formatting ├── core/ │ ├── models.py # Data models (Risk, CodeFile, etc.) │ ├── llm_client.py # Unified LLM client (2 local backends) │ ├── memory.py # Dual memory system │ ├── cve_client.py # Local CVE database client (SQLite) │ ├── semgrep_runner.py # Semgrep integration │ ├── taint_analyzer.py # Data flow tracking │ ├── dependency_scanner.py # Vulnerable dependency detection (local OSV data) │ ├── attack_knowledge.py # CWE/ATT&CK knowledge base │ └── retry.py # Unified retry policy ├── tests/ │ ├── test_static_analyzer.py │ ├── test_cve_client.py │ ├── test_llm_client.py │ ├── test_memory.py │ ├── test_schemas.py │ └── test_cases/ │ ├── buffer_overflow.c │ ├── command_injection.c │ ├── memory_issues.c │ ├── code_injection.py │ └── sql_injection.py ├── docs/ │ ├── project-specification.md │ ├── architecture-review.md │ ├── module-analysis.md │ ├── rocm-optimization.md │ ├── demo-video-script.md │ └── submission-checklist.md ├── data/ # Local vulnerability databases │ ├── vuln_db.sqlite # CVE data (built by download_cve_data.py) │ └── osv/ │ └── index.json # OSV data (built by download_osv_data.py) ├── scripts/ │ ├── run_demo.sh │ ├── download_cve_data.py # NVD CVE database builder │ └── download_osv_data.py # OSV vulnerability data builder ├── pyproject.toml └── .env.example ``` ## 测试 ``` # 运行所有测试 pytest # 运行并附带 coverage pytest --cov=. --cov-report=html ``` 包含 51 个单元测试,涵盖缓冲区溢出、命令注入、代码注入、反序列化以及安全代码检测。 ## 技术栈 | 组件 | 技术 | |-----------|-----------| | 语言 | Python 3.12 | | LLM | Qwen2.5-Coder-32B-Instruct (GGUF Q4_K_M) | | LLM Runtime | 带 HIP 后端的 llama.cpp | | 静态分析 | Regex + Semgrep | | CVE 数据库 | 本地 SQLite(从 NVD 预先下载) | | 依赖扫描 | 本地 OSV 数据 + 回退字典 | | 记忆 | 基于 JSON 的双重记忆系统 | | 输出格式 | JSON、Markdown、SARIF 2.1.0、Rich 终端 | | CLI | Rich 终端 UI | | GPU | AMD Radeon Pro W7900 (48GB) + ROCm 7.2.4 | ## 团队 | 成员 | 角色 | |--------|------| | **Yang Weike** | 队长 / 产品 / 安全测试 | | **lolo** | 全栈开发 / 架构 | ## 许可证 MIT ## 已知限制 - **Radeon Cloud 容器:** HIP 后端需要 `GGML_HIP=ON`(而不是旧版的 `GGML_HIPBLAS=ON`)。在裸机系统上,这两个标志可能都有效。 - **语言支持:** 目前仅支持 C 和 Python。Java、Go 和 Rust 计划在未来版本中支持。 - **污点分析:** 仅限单函数变量跟踪。跨函数数据流需要调用图(已规划)。 - **记忆学习:** 需要 2 次或更多次扫描才能激活误报抑制。单次运行的结果可能包含已知的误报。 - **Semgrep 集成:** 需要单独安装 Semgrep CLI。系统在没有它的情况下也能工作,但会失去一层分析。 ## 致谢 - [Qwen](https://github.com/QwenLM) 提供优秀的代码模型 - [llama.cpp](https://github.com/ggerganov/llama.cpp) 提供本地推理 - [Semgrep](https://semgrep.dev/) 提供静态分析规则 - [AMD](https://developer.amd.com/) 提供 Radeon Cloud 平台和黑客松
标签:AI智能体, 云安全监控, 安全大模型, 本地大模型, 逆向工具, 静态分析