Repository navigation
fix: prevent appconfig path traversal to RCE via public_/remote_ keys - #41804
oc-tmueller wants to merge 2 commits into
Conversation
… (OC10-146) An authenticated admin could set the core appconfig key `public_webdav` (or any `public_`/`remote_` key) to a path-traversal value and have it `require_once`'d by public.php on the next `GET /public.php/webdav`, achieving remote code execution. Two independent defects made this possible: 1. Sink: public.php included the stored handler path relative to the app directory with no traversal check, unlike remote.php which already rejects `../`. This is the essential, DB-independent gate: add the same guard so a traversal path can never be included. 2. Guard bypass: AppConfigController used a strict `$app === 'core'` compare to block admins from setting `public_`/`remote_` keys on core. A mangled app id such as `"core "` (trailing space) is not equal to `"core"` in PHP yet the database folds it back to the core row, defeating the guard. This is the same defeat mechanism as OC10-5 (`core%81` truncation). Normalize the app id (cleanAppId + trim + strtolower) before the check, in both the controller (getValue/setValue/deleteKey) and the legacy core/ajax/appconfig.php endpoint, and block deleting the whole core appconfig via deleteApp. Adds regression tests covering the mangled `core` spellings and the allowed near-misses. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Thomas Müller <[email protected]>
a47964f to
dd2f58a
Compare
| // mangled spellings which the database folds back to the "core" row | ||
| // (e.g. "core " with a trailing space) cannot slip past the guard. See OC10-146. | ||
| $normalizedApp = isset($app) ? \strtolower(\trim((string)$app)) : $app; | ||
| if ($normalizedApp === 'core' && isset($_POST['key']) &&(\substr((string)$_POST['key'], 0, 7) === 'remote_' || \substr((string)$_POST['key'], 0, 7) === 'public_')) { |
There was a problem hiding this comment.
I thought that code-style would complain about &&( (no space), but that was already in the previous code anyway.
There was a problem hiding this comment.
Good hunch to check, but the ruleset would never have flagged it: vendor-bin/owncloud-codestyle/vendor/owncloud/coding-standard/src/Config.php is @PSR1 plus a hand-picked set of PSR-2 rules, and binary_operator_spaces — the fixer that would insert that space — is not in it. It is not part of @PSR12 either; it lives in @Symfony. That is why the construct sat in the tree for years with PHP Code Style green.
Moot now in any case — the later review rounds rewrote this whole condition into a multi-line && (!\is_string($postedKey) || …), so &&( is gone from the file.
| ['CORE', 'public_key1', 'foo'], | ||
| ['Core', 'remote_key1', 'foo'], | ||
| ['core/', 'public_key1', 'foo'], | ||
| ['core..', 'remote_key1', 'foo'], |
There was a problem hiding this comment.
Note: OC_App::cleanAppId removes junk like .. so this test case is also equivalent to trying to set a key for "core".
There was a problem hiding this comment.
Agreed on cleanAppId — it strips .., so isCoreApp('core..') normalizes to 'core' and the guard does fire. Two refinements though, because the distinction turned out to matter in the later review rounds:
It is not equivalent at the database level in this file. AppConfigController passes the raw $app to $this->appConfig->setValue($app, …), not the cleaned one — so had the guard not fired, core.. would have written a distinct core.. row, which no collation folds onto core. So core.. is not actually a bypass vector here; the guard over-blocks it, fail-safe. Your sentence is literally true for core/ajax/appconfig.php, which applies cleanAppId at line 31 before using the value and therefore really does write to the core row.
The case is worth keeping rather than dropping as redundant. It is the only one pinning the cleanAppId call inside isCoreApp(): without it, 'core..' stays 'core..', which is !== 'core'; it then passes the canonical-charset check (. is in the charset, length 6), no guard fires, setValue is reached, and the data set's expects($this->never()) fails. The neighbouring ['core', 'remote_key1', 'foo'] case does not cover that path.
Addresses review feedback on the appconfig path traversal fix. The `../` substring check added to public.php is not a containment check, so it does not deliver the database-independent gate it was meant to be: `OC_App::getAppPath()` returns false for an app id that has no directory on disk, and `false . '/'` is `'/'`, so the include path becomes absolute - and an absolute path contains no traversal sequence. `isInstalled()` does not stop that, because it only tests for an appconfig `enabled` row, not for a directory, and an admin can create such a row for any app id. Verified on a live instance: a stored value of `<dirless app>//etc/passwd` returned the contents of /etc/passwd. Resolve the stored `<appId>/<path>` value through a new `OC_App::getServiceHandlerPath()` instead, which requires the target to realpath() inside the app's own directory and to be an existing .php file. This also covers a symlink out of the app tree, and the is_file() test matters because require_once on a directory named `x.php` is an E_COMPILE_ERROR the callers' catch (\Throwable) cannot handle. remote.php builds its include path the same way in the default branch of its service switch, so it gets the same treatment; the core branch is unaffected because it serves a hardcoded list from OC::$SERVERROOT. Every programmatic writer stores `<appId>/<path from info.xml>`, which always resolves inside the app directory, so legitimate values are unaffected - there is now a test pinning all six shipped handlers. Enumerating mangled spellings of "core" cannot be complete either: the only requirement for a bypass is that the written app id compares equal to "core" under the database collation, which is an open set. Blank padding into the varchar(32) appid column, an accent-insensitive collation and a trailing invalid byte all survive the normalization. Reject any app id outside the canonical charset from setValue, deleteKey and deleteApp instead, in the controller and in the legacy endpoint. The charset is anchored with \z rather than $, because $ also matches before a trailing newline, which would let a 33-byte id truncate onto an existing row. The same reasoning applies to the key, which was compared case sensitively: under a case-insensitive collation `PUBLIC_webdav` folds onto the stored `public_webdav` row, so an admin could overwrite or delete a registered handler. The prefix test is now case-insensitive, and a key that is not canonical is refused outright on core, because an accent-insensitive collation folds `públic_webdav` onto it as well. The legacy endpoint also only applied its core guard to requests that carry a key, so `action=deleteApp&app=core` still wiped every core row, including the programmatically registered handlers. It now has its own guard. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
The review feedback on #41803 applies here verbatim, and the same commit is on this branch — see the detailed reply there. The two branch diffs are byte-identical apart from the changelog filename and its extra PR link. Verified separately on PHP 8.3: The approval here was dismissed by the push, which is expected — this round changed real behaviour rather than just adding tests. |
| $base = \realpath($appPath); | ||
| $target = \realpath($appPath . '/' . $relativePath); |
There was a problem hiding this comment.
I'm not sure how much of a security risk this is, because since it will follow symlinks it might be possible to access to directories out of the OC's control.
Summary
An authenticated admin could set the
coreappconfig keypublic_webdav(or anypublic_/remote_key) to a value thatpublic.phpthenrequire_once'd on the nextGET /public.php/<service>, achieving remote code execution.Two layers are fixed here.
1. Sink — the handler include is now contained to the app directory
public.phpincluded the stored handler path relative to the app directory with no check at all. The first version of this PR addedremote.php's existing../substring check, but that is not sufficient, as the review pointed out:OC_App::getAppPath()returnsfalsefor an app id that has no directory on disk, andfalse . '/'is'/'— so the include path becomes absolute, and an absolute path contains no traversal sequence.AppManager::isInstalled()does not stop it either, because it only tests for an appconfigenabledrow, not for a directory, and such a row can be created for any app id. A stored value of<dirless-app-id>/<absolute path to a php file>was therefore included from/.This was reproduced on a live instance: with only the substring check,
GET /public.php/<service>for a value ofbogusapp//etc/passwdreturned the contents of/etc/passwd.The include now goes through a new
OC_App::getServiceHandlerPath($app, $relativePath), which returns the target only if itrealpath()s to an existing.phpfile inside that app's own directory, andfalseotherwise — which callers treat as "refuse". Beingrealpath()-based it also covers a symlink out of the app tree, and it is database- and endpoint-independent, which is the property this layer was supposed to have.The
is_file()half of that test matters on its own:realpath()also succeeds for a directory, so without it a directory namedhandler.phpinside an app would berequire_once'd, which is anE_COMPILE_ERROR— not catchable by thecatch (\Throwable)in either entry script, so it would produce a white screen with nothing logged rather than the error page.remote.phpbuilds its include path the same way in thedefault:branch of its service switch, so it gets the same treatment. Thecorebranch there is unaffected: it serves a hardcoded list fromOC::$SERVERROOT.No legitimate value is affected. Every programmatic writer stores
<appId>/<path from info.xml>(lib/private/Installer.php:160,163,551,554,lib/private/legacy/app.php:989,992), which always resolves inside the app directory.2. App id — non-canonical ids are refused instead of enumerated
AppConfigControllerblocked admins from settingpublic_/remote_keys oncorewith a strict$app === 'core'compare. A mangled app id such as"core "(trailing space) is not equal to"core"in PHP, yet the database folds it back to thecorerow, defeating the guard — the same mechanism as the earliercore%81truncation bypass.Normalizing the app id fixes the reported spellings but cannot be complete: the only requirement for a bypass is that the written id compare equal to
coreunder the deployment's collation, which is an open set. Two spellings survivestrtolower(trim(cleanAppId(...))):varchar(32)appidcolumn —"core" + 28 spaces + "X"is not equal to"core"in PHP, trims to itself, and truncates to"core" + 28 spaces, which a PAD SPACE collation folds onto thecorerow;core%81case, which neithercleanAppId()nortrim()strips.So instead of enumerating spellings, any app id outside the canonical charset
/^[a-zA-Z0-9_.-]{1,32}\z/is now refused with400fromsetValue,deleteKeyanddeleteApp. Every folding vector needs a character outside that charset. Case is deliberately still accepted — this endpoint has always taken mixed-case ids, and the existing tests use ids likeappId003— and a case-insensitive collation remains covered because thecorecheck lowercases before comparing.Two details worth naming, because both were defects in the first attempt at this:
\z, not$. PCRE's$also matches before a single trailing newline, sostr_repeat('a', 32) . "\n"passed a$-anchored check and then truncated into the 32-byte column onto an existing row.is_string().(string)on an array yields the literal"Array", which matches the charset, soapp[]=corepreviously passed both guards and died insideAppConfig::setValue()as a 500 instead of being refused with a 400.3. The key was compared case-sensitively
The same argument applies to the key, and the first version of this change missed it.
isCoreApp()normalized the app id but the key test wasstrpos($key, 'public_') === 0. Under a case-insensitiveconfigkeycollation,PUBLIC_webdavis not caught by that test, yetAppConfig::setValue()reconciles onto the existing row —hasKey()misses (the in-memory cache is exact-match),insertIfNotExist()finds the row under the collation and skips the insert, and control falls through toUPDATE … WHERE appid = ? AND configkey = ?, which overwrites the realpublic_webdav.deleteKeylikewise deletes it, breaking public links and WebDAV.The prefix test is now case-insensitive. Because an accent-insensitive collation folds
públic_webdavonto the row too — which no prefix test can catch — a key that is not canonical (/^[a-zA-Z0-9_.-]{1,64}\z/, matching thevarchar(64)column) is refused outright, but only when the app iscore. On a fresh installcorehas five keys, all canonical ASCII and at most 21 bytes.A key-prefix-only block would have been simpler than any of this but over-reaches:
files_sharinglegitimately ownspublic_share_sharers_groups_allowlist*(apps/files_sharing/lib/SharingAllowlist.php:72,80). There is now a test pinning that.4. Legacy endpoint
core/ajax/appconfig.phpmirrors both guards. Itscoreguard only fired for a request that carried a key, soaction=deleteApp&app=corestill reacheddeleteApp()and dropped everycorerow, including the programmatically registered handlers the guard exists to protect. It now has its own guard.Tests
tests/lib/legacy/AppTest.phpcovers the new helper: a file inside the app, traversal that stays inside, traversal out of the app, an app id with no directory on disk (the absolute-path vector above), the sibling-directory boundary, a directory namedhandler.php, a non-.phptarget, a missing file, and empty arguments. It also pins all six shipped handler values (dav/appinfo/v1/{webdav,caldav,carddav,publicwebdav}.php,dav/appinfo/v2/remote.php,files_sharing/public.php) so this cannot silently break production — note every hardcodedremote.phpservice resolves through the app path as appdav, so they all flow through the new code.tests/Settings/Controller/AppConfigControllerTest.phpcovers the mangledcorespellings, the non-canonical ids (blank-padded truncation, trailing invalid byte, accented, over-length, trailing newline, illegal character, empty, non-string), the case-folded and accent-folded service keys, and the allowed near-misses includingfiles_sharing/public_share_*.Every new guard was mutation-tested — reverting its line individually turns the corresponding test red: the containment check, the trailing separator, the
.phpsuffix,is_file(),is_string(),\zvs$, the case-insensitive prefix, the canonical-key check, and the canonical-id check (which alone fails 18 cases).Verified in
owncloudci/php:7.4on sqlite —tests/Settings/: OK, 299 tests / 868 assertions;Test\legacy\AppTest: OK, 27 tests / 44 assertions.php-cs-fixerreports 0 of 2407 files needing changes.End-to-end on a live instance, the three attack values (traversal, absolute path via a dirless app, non-
.phpfile in a real app) are all refused, whilepublic.php/webdav,public.php/files,remote.php/webdavandremote.php/davall still serve normally.One honest caveat: the
realpath() === falseearly return in the new helper is defensive and not reachable in practice, becausegetAppPath()only ever returns directories that exist. It is kept because without it a false base would degenerate the prefix to/and accept any absolute path.Forward-port of #41803 to
master. That PR targets the10.16release branch;mastercarries the identical vulnerable code. The two branch diffs are byte-identical apart from the changelog filename and its extra PR link. Verified separately inowncloudci/php:8.3:tests/Settings/OK, 297 tests / 861 assertions,Test\legacy\AppTestOK, 27 tests / 44 assertions,php-cs-fixer0 of 2433 files.