# Tsecbench 托管模式镜像（控制层 agent + worker 本地子进程模式）
#
# 构建（在 WSL 中执行 tencent/build.sh 自动完成）：
#   bash tencent/build.sh
#
# 构建上下文为项目根目录，通过 .dockerignore 排除无关文件。
# 镜像内不含 Docker daemon，worker 通过本地子进程（supervisor.sh）运行。
#
# 镜像内目录结构：
#   /opt/agent/agent              Go 控制层二进制
#   /opt/agent/web/static/        前端静态资源
#   /opt/agent/pi-coop/           worker 运行时（findCoopRuntime 查找此目录）
#     ├── supervisor.sh           worker 调度脚本
#     ├── coop.ts                 pi extension
#     ├── AGENTS.md               协作协议
#     ├── prompts/agent.md        worker 系统提示
#     └── extensions/coop.ts      extension 副本
#   /opt/agent/data/              运行时数据（会话、配置）
#   /opt/tools/                   安全工具集
#     ├── nuclei-templates/       Nuclei 模板库
#     └── observer_ward/plugins/  observer_ward 指纹规则库

FROM node:22-alpine

# ---- 系统工具 + Python + 二进制分析工具 ----
# 启用 community 仓库（gdb/radare2/john 等在其中）
RUN sed -i 's|https://dl-cdn.alpinelinux.org|http://mirrors.tuna.tsinghua.edu.cn|g' /etc/apk/repositories \
  && echo "http://mirrors.tuna.tsinghua.edu.cn/alpine/v3.20/community" >> /etc/apk/repositories \
  && apk update \
  && apk add --no-cache \
      bash ca-certificates git ripgrep \
      curl wget jq openssl file \
      python3 py3-pip \
      binutils gdb radare2 \
      netcat-openbsd socat \
      tmux rlwrap \
      zip unzip tar gzip xz bzip2 \
      bind-tools whois \
      john \
      proxychains-ng

# ---- Python 常用库 ----
RUN pip3 install --no-cache-dir --break-system-packages \
      -i https://pypi.tuna.tsinghua.edu.cn/simple \
      requests urllib3 certifi idna charset-normalizer \
      cryptography pyOpenSSL paramiko pyjwt \
      PyYAML beautifulsoup4 lxml \
      python-dotenv click tqdm \
      numpy pandas \
      httpx aiohttp websockets dnspython \
      psutil pillow

# ---- Python 二进制分析工具 ----
# pwntools 强制依赖 unicorn；angr 依赖 lmdb（需 patch），均在 Alpine musl + Python 3.14 下编译困难，故不安装
# 保留有预编译 wheel 的工具：ROPgadget（ROP 搜索）、capstone（反汇编）、pyelftools（ELF 解析）、pycryptodome（加密）
RUN pip3 install --no-cache-dir --break-system-packages \
      -i https://pypi.tuna.tsinghua.edu.cn/simple \
      ROPgadget \
      capstone \
      pycryptodome \
      pyelftools

# ---- impacket（SMB/LDAP/WinRM/MSSQL 等协议攻击套件，纯 Python，含 impacket-* 命令）----
# 注意：impacket 依赖 pycryptodomex（模块名 Cryptodome），与上方 pycryptodome（模块名 Crypto）可共存
# Alpine 的 pip 不会生成 console_scripts 入口，故为常用命令手动创建 shim 到 /usr/local/bin；
# 逐模块检查存在性，不存在的模块自动跳过，避免生成坏 shim
RUN pip3 install --no-cache-dir --break-system-packages \
      -i https://pypi.tuna.tsinghua.edu.cn/simple \
      impacket \
  && for t in secretsdump smbclient mssqlclient psexec wmiexec ntlmrelayx GetNPUsers GetUserSPNs smbexec atexec; do \
       if python3 -c "import importlib; importlib.import_module('impacket.examples.$t')" 2>/dev/null; then \
         printf '#!/bin/sh\nexec python3 -m impacket.examples.%s "$@"\n' "$t" > /usr/local/bin/impacket-$t \
         && chmod +x /usr/local/bin/impacket-$t; \
       fi; \
     done

# ---- 全局安装 pi coding agent ----
RUN npm install -g --ignore-scripts \
      --registry=https://registry.npmmirror.com \
      @earendil-works/pi-coding-agent@latest

# ---- agent 程序 ----
RUN mkdir -p /opt/agent/web/static \
             /opt/agent/pi-coop/extensions \
             /opt/agent/pi-coop/prompts \
             /opt/agent/data \
             /opt/tools/observer_ward

COPY tencent/agent-linux-amd64 /opt/agent/agent
COPY web/static/ /opt/agent/web/static/
COPY pi-coop/supervisor.sh /opt/agent/pi-coop/supervisor.sh
COPY pi-coop/coop.ts /opt/agent/pi-coop/coop.ts
COPY pi-coop/coop.ts /opt/agent/pi-coop/extensions/coop.ts
COPY pi-coop/AGENTS.md /opt/agent/pi-coop/AGENTS.md
COPY pi-coop/prompts/ /opt/agent/pi-coop/prompts/
RUN chmod +x /opt/agent/agent /opt/agent/pi-coop/supervisor.sh

# ---- 安全工具（自定义二进制 + 规则库）----
# nuclei：漏洞扫描器（静态 Go 二进制，无依赖）
COPY tencent/tools/nuclei /usr/local/bin/nuclei
RUN chmod +x /usr/local/bin/nuclei

# observer_ward：指纹识别（静态 Rust 二进制，无依赖）
COPY tencent/tools/observer_ward /usr/local/bin/observer_ward
RUN chmod +x /usr/local/bin/observer_ward

# chisel：内网隧道（静态 Go 二进制，无依赖；Alpine 仓库无此包，故直接打包）
COPY tencent/tools/chisel /usr/local/bin/chisel
RUN chmod +x /usr/local/bin/chisel

# nuclei-templates：Nuclei 漏洞模板库
COPY tencent/tools/nuclei-templates/ /opt/tools/nuclei-templates/

# FingerprintHub 指纹规则库（observer_ward 使用）
COPY tencent/tools/FingerprintHub-defaultv4/plugins/ /opt/tools/observer_ward/plugins/

# ---- 工具清单（供 worker agent 读取，了解容器内可用工具）----
RUN cat > /opt/tools/TOOLS.md <<'TOOLSEQ'
# 容器内可用工具清单

## 漏洞扫描
- `nuclei -u <url> -t /opt/tools/nuclei-templates/` — 漏洞扫描器，模板库已预装
- `nuclei -l urls.txt -severity critical,high` — 批量扫描
- `nuclei -u <url> -t /opt/tools/nuclei-templates/http/cves/` — 只跑 CVE 模板

## 指纹识别
- `observer_ward -t <url> -p /opt/tools/observer_ward/plugins/` — Web 指纹识别
- `observer_ward -t <url> --json` — JSON 格式输出

## 二进制分析（系统级）
- `objdump -d <binary>` — 反汇编
- `objdump -t <binary>` — 查看符号表
- `readelf -a <binary>` — ELF 文件信息（节区、段、重定位）
- `nm <binary>` — 符号列表
- `strings <binary>` — 提取字符串
- `r2 -A <binary>` — radare2 逆向分析（aaa 自动分析，pdf 反汇编，s 跳转）
- `gdb <binary>` — 动态调试（break, run, x/, info registers）
- `john --wordlist=<wordlist> <hashfile>` — 密码破解

## 二进制分析（Python 库）
- `ROPgadget --binary <binary>` — 搜索 ROP gadget
- `python3 -c "import capstone; ..."` — 反汇编引擎（x86/ARM/MIPS）
- `python3 -c "from elftools.elf.elffile import ELFFile; ..."` — ELF 解析
- `python3 -c "from Crypto.Cipher import AES; ..."` — 加密解密（AES/RSA）

## 网络
- `nc <host> <port>` — 端口连接 / 反弹 shell
- `socat TCP-LISTEN:<port>,fork TCP:<host>:<port>` — 端口转发
- `dig <domain>` / `nslookup <domain>` — DNS 查询
- `whois <domain>` — 域名信息
- `curl -v <url>` — HTTP 请求
- `wget <url>` — 文件下载
- `chisel client <server>:<port> <remote>` — 内网隧道（客户端）
- `chisel server -p <port> --reverse` — 内网隧道（服务端）
- `proxychains4 <cmd>` — 代理链执行命令（先编辑 /etc/proxychains/proxychains.conf 配 SOCKS5 代理）

## Windows 内网渗透（impacket）
- `impacket-secretsdump <user>:<pass>@<host>` — 远程转储 SAM/LSA/NTDS 哈希
- `impacket-smbclient <user>@<host>` — SMB 交互客户端（共享枚举/上传下载）
- `impacket-mssqlclient <user>:<pass>@<host>` — MSSQL 客户端（可执行 xp_cmdshell）
- `impacket-psexec <user>:<pass>@<host>` — 通过 SMB 获得 SYSTEM shell
- `impacket-wmiexec <user>:<pass>@<host>` — 通过 WMI 执行命令
- `impacket-ntlmrelayx -t <target>` — NTLM 中继攻击
- `impacket-GetNPUsers -dc-ip <host> <domain>/` — 无口令 AS-REP Roast 提取
- `python3 -c "from impacket.smbconnection import SMBConnection; ..."` — 库方式调用

## 文件处理
- `file <file>` — 文件类型识别
- `xxd <file>` — 十六进制转储（需 xxd，或用 `od -A x -t x1z`）
- `zip`/`unzip`/`tar`/`gzip`/`xz`/`bzip2` — 压缩解压

## Python 环境
- Python 3.14 + pip，已安装：requests, httpx, aiohttp, paramiko, PyYAML, lxml, numpy, pandas, cryptography, pycryptodome, pycryptodomex, websockets, dnspython, impacket
- `pip3 list` — 查看所有已安装包

## 注意
- 当前用户为 node（非 root），部分系统级操作可能需要 sudo（未安装）
- 工作目录为 /blackboard/workspace/，产物写到这里
- 环境变量：NUCLEI_TEMPLATES_PATH, OBSERVER_WARD_PLUGINS 已预配置
TOOLSEQ

# ---- 非 root 用户 ----
# node:22-alpine 自带 node 用户（uid 1000），与 pi-coop 镜像对齐。
RUN chown -R node:node /opt/agent /opt/tools
USER node
WORKDIR /opt/agent

# ---- 环境变量 ----
# AGENT_WORKSPACE / AGENT_DATA_DIR / AGENT_PORT 控制 agent 运行时路径
# COOP_DIR 让 findCoopRuntime 定位到 /opt/agent/pi-coop/
# NUCLEI_TEMPLATES_PATH 让 nuclei 直接找到模板库
# OBSERVER_WARD_PLUGINS 让 observer_ward 找到指纹规则库
# LLM 相关配置（API_KEY/BASE_URL/MODEL 等）由平台运行时注入
ENV AGENT_WORKSPACE=/opt/agent
ENV AGENT_DATA_DIR=/opt/agent/data
ENV AGENT_PORT=8080
ENV COOP_DIR=/opt/agent
ENV NUCLEI_TEMPLATES_PATH=/opt/tools/nuclei-templates
ENV OBSERVER_WARD_PLUGINS=/opt/tools/observer_ward/plugins

EXPOSE 8080
ENTRYPOINT ["/opt/agent/agent"]
