Skip to content

fix: prevent appconfig path traversal to RCE via public_/remote_ keys - #41803

Merged
oc-tmueller merged 3 commits into
10.16from
fix/oc10-146-appconfig-path-traversal
Sep 23, 2026
Merged

oc-tmueller merged 3 commits into
10.16from
fix/oc10-146-appconfig-path-traversal

Conversation

@oc-tmueller

@oc-tmueller oc-tmueller commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

An authenticated admin could set the core appconfig key public_webdav (or any public_/remote_ key) to a value that public.php then require_once'd on the next GET /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.php included the stored handler path relative to the app directory with no check at all. The first version of this PR added remote.php's existing ../ substring check, but that is not sufficient, as the review pointed out:

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. AppManager::isInstalled() does not stop it either, because it only tests for an appconfig enabled row, 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 of bogusapp//etc/passwd returned the contents of /etc/passwd.

The include now goes through a new OC_App::getServiceHandlerPath($app, $relativePath), which returns the target only if it realpath()s to an existing .php file inside that app's own directory, and false otherwise — which callers treat as "refuse". Being realpath()-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 named handler.php inside an app would be require_once'd, which is an E_COMPILE_ERROR — not catchable by the catch (\Throwable) in either entry script, so it would produce a white screen with nothing logged rather than the error page.

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 there is unaffected: it serves a hardcoded list from OC::$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

AppConfigController blocked admins from setting public_/remote_ keys on core with 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 the core row, defeating the guard — the same mechanism as the earlier core%81 truncation 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 core under the deployment's collation, which is an open set. Two spellings survive strtolower(trim(cleanAppId(...))):

  • blank padding that truncates into the varchar(32) appid column — "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 the core row;
  • a trailing invalid byte, i.e. the core%81 case, which neither cleanAppId() nor trim() strips.

So instead of enumerating spellings, any app id outside the canonical charset /^[a-zA-Z0-9_.-]{1,32}\z/ is now refused with 400 from setValue, deleteKey and deleteApp. 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 like appId003 — and a case-insensitive collation remains covered because the core check lowercases before comparing.

Two details worth naming, because both were defects in the first attempt at this:

  • The pattern is anchored with \z, not $. PCRE's $ also matches before a single trailing newline, so str_repeat('a', 32) . "\n" passed a $-anchored check and then truncated into the 32-byte column onto an existing row.
  • It also tests is_string(). (string) on an array yields the literal "Array", which matches the charset, so app[]=core previously passed both guards and died inside AppConfig::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 was strpos($key, 'public_') === 0. Under a case-insensitive configkey collation, PUBLIC_webdav is not caught by that test, yet AppConfig::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 to UPDATE … WHERE appid = ? AND configkey = ?, which overwrites the real public_webdav. deleteKey likewise deletes it, breaking public links and WebDAV.

The prefix test is now case-insensitive. Because an accent-insensitive collation folds públic_webdav onto the row too — which no prefix test can catch — a key that is not canonical (/^[a-zA-Z0-9_.-]{1,64}\z/, matching the varchar(64) column) is refused outright, but only when the app is core. On a fresh install core has 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_sharing legitimately owns public_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.php mirrors both guards. Its core guard only fired for a request that carried a key, so action=deleteApp&app=core still reached deleteApp() and dropped every core row, including the programmatically registered handlers the guard exists to protect. It now has its own guard.

Tests

  • tests/lib/legacy/AppTest.php covers 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 named handler.php, a non-.php target, 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 hardcoded remote.php service resolves through the app path as app dav, so they all flow through the new code.
  • tests/Settings/Controller/AppConfigControllerTest.php covers the mangled core spellings, 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 including files_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 .php suffix, is_file(), is_string(), \z vs $, the case-insensitive prefix, the canonical-key check, and the canonical-id check (which alone fails 18 cases).

Verified in owncloudci/php:7.4 on sqlite — tests/Settings/: OK, 299 tests / 868 assertions; Test\legacy\AppTest: OK, 27 tests / 44 assertions. php-cs-fixer reports 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-.php file in a real app) are all refused, while public.php/webdav, public.php/files, remote.php/webdav and remote.php/dav all still serve normally.

One honest caveat: the realpath() === false early return in the new helper is defensive and not reachable in practice, because getAppPath() 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.


Resubmission of #41802, re-authored and SSH-signed under @oc-tmueller.

… (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]>
@CLAassistant

CLAassistant commented Sep 2, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Comment thread changelog/unreleased/41803 Outdated
app-id guard can no longer be bypassed by mangled spellings such as a trailing
space.

https://github.com/owncloud/core/pull/41802

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do we do about this?

The PR number is off-by-one. The master PR #41804 has the correct numbers.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — this entry now links /pull/41803, and the master one links both 41804 and 41803.

phil-davis
phil-davis previously approved these changes Sep 4, 2026

@phil-davis phil-davis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@oc-tmueller you can decide if you update the PR number in the changelog entry.

@kw-fscheuer kw-fscheuer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the two-layer approach — the reported PoC is definitely dead: "core " no longer slips past isCoreApp(), and files/../…/poc.php is rejected before the include. I'm requesting changes on one blocking point: the new guard in public.php isn't yet a containment check, so the bug class isn't closed.

1. public.php doesn't contain the include to the app directory (blocking)

public.php:65-67 rejects ../ and /.., but the include at public.php:85 is still

require_once OC_App::getAppPath($app) . '/' . $parts[1];

and getAppPath() returns false for an app id that has no directory on disk (lib/private/App/AppManager.php:682-690), while OC_App::loadApp() returns silently in that case rather than failing (lib/private/legacy/app.php:174-179). false . '/' is '/', so the include path becomes absolute — and an absolute path contains no ../, so the new guard passes it.

The isInstalled($app) check at public.php:77 doesn't stop that, because it isn't a filesystem check: AppManager::isInstalled() is isset($installedApps[$appId]) over getInstalledAppsValues(), which is built purely from appconfig enabled rows (AppManager.php:136-151, :256-259). A row for an app id that doesn't exist on disk can be created through this same admin endpoint ({"app":"<any-id>","key":"enabled","value":"yes"} — no guard applies, the app id isn't core). With such a row in place, a stored handler value of <that-id>/<absolute-path-to-a-php-file> is included from /, with no traversal sequence anywhere in the value.

Suggested containment check at the include site (keep the cheap substring check in front of it as a fast path if you like):

$appPath = OC_App::getAppPath($app);
if ($appPath === false || !isset($parts[1]) || $parts[1] === '') {
    throw new Exception('Path not allowed');
}
$base   = \realpath($appPath);
$target = \realpath($appPath . '/' . $parts[1]);
if ($base === false || $target === false
    || \strpos($target, $base . '/') !== 0
    || \substr($target, -4) !== '.php') {
    throw new Exception('Path not allowed');
}
require_once $target;

That is DB-independent — the property the commit message wants from this layer — and it also covers a symlink out of the app tree. Legitimate values are unaffected: every programmatic writer stores <appId>/<path-from-info.xml> (lib/private/legacy/app.php:989,992, lib/private/Installer.php:160,163 and :557,560), which always resolves inside the app directory.

remote.php builds its include path the same way in the default: branch of switch ($app), so it needs the same treatment (the core branch there is fine — hardcoded services + OC::$SERVERROOT).

2. The app-id normalization can't enumerate database foldings

isCoreApp() (settings/Controller/AppConfigController.php:115-117) catches whitespace, case, / and ... But the only requirement for a bypass is that the written app id be collation-equal to core, which is an open set. Two spellings that survive strtolower(trim(cleanAppId(...))):

  • a trailing invalid byte — i.e. the core%81 truncation this PR cites from OC10-5: cleanAppId() doesn't strip it and neither does trim();
  • an accent-insensitive collation (utf8mb4_0900_ai_ci, the MySQL 8 default) makes e.g. córe compare equal to core.

Either way AppConfig::setValue() reconciles onto the existing row via UPDATE … WHERE appid = :app (lib/private/AppConfig.php:157-184). Rather than enumerating spellings, validating the charset and rejecting anything that isn't a canonical app id closes the class:

private function isCoreApp($app) {
    $app = (string)$app;
    // any spelling the database could fold onto "core" is outside this charset
    if (\preg_match('/^[a-z0-9_.-]{1,32}$/', $app) !== 1) {
        return true;   // not a canonical app id → refuse the service-key write
    }
    return $app === 'core';
}

(Returning 400 for a non-canonical app id in setValue/deleteKey/deleteApp would be equivalent and clearer. A key-prefix-only block would over-reach — files_sharing legitimately owns public_share_sharers_groups_allowlist*, apps/files_sharing/lib/SharingAllowlist.php:72,80.)

3. core/ajax/appconfig.php didn't get the deleteApp half

The legacy endpoint's guard (core/ajax/appconfig.php:41-42) only fires when $_POST['key'] is set, so action=deleteApp&app=core still reaches $appConfig->deleteApp($app) at :69 and drops every core row — including the programmatically registered public_*/remote_* handlers that the new block at AppConfigController.php:171 exists to protect. The route is live (core/routes.php:90-91).

if ($normalizedApp === 'core' && $action === 'deleteApp') {
    OC_JSON::error(['data' => ['message' => 'Unexpected error!']]);
    return;
}

4. Smaller notes

  • The sink guard — the layer the commit message calls essential — is the one with no test; all the new assertions are on the controller. An acceptance scenario (occ config:app:set core public_zzz --value "files/../../../etc/passwd", then GET /public.php/zzz) would pin it, plus the app-id-without-a-directory case once the containment check is in.
  • changelog/unreleased/41803 still links …/pull/41802 (as already noted above).

All of the above applies unchanged to #41804, which is byte-identical apart from the changelog.

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]>
@oc-tmueller oc-tmueller changed the title fix: prevent appconfig path traversal to RCE via public_/remote_ keys (OC10-146) fix: prevent appconfig path traversal to RCE via public_/remote_ keys Sep 22, 2026
@oc-tmueller

Copy link
Copy Markdown
Contributor Author

All four points are addressed on both PRs. Two places where I found the reasoning narrower or wider than stated are flagged below rather than quietly worked around.

1. Containment at the sink — fixed, and it was worse than described

Confirmed, and it was not merely an incomplete guard: it was live. I reproduced it on a running instance. With only the ../ substring check this PR originally shipped, an appconfig value of bogusapp//etc/passwd on a core public_* key returns the contents of /etc/passwd from GET /public.php/<service>. With the containment check in place it is refused. So the layer the commit message called "the essential, DB-independent gate" did not hold, exactly as you said.

The include now goes through a new OC_App::getServiceHandlerPath($app, $relativePath) rather than an inline check, for the reason in point 4 below. It returns the target only when it realpath()s to a .php file inside that app's own directory, and false otherwise. remote.php's default: branch gets the same treatment; its core branch is untouched, as you noted.

One deviation from your snippet: the containment comparison is against $base . DIRECTORY_SEPARATOR, not bare $base. Without the separator apps/files would also accept targets under apps/files_sharing. This is also why I did not reuse the existing OC_Helper::isSubDirectory() (lib/private/legacy/helper.php:382), which does strpos($realpathSub, $realpathParent) === 0 with no separator — it has the same weakness, and its callers in lib/private/L10N/Factory.php:276-279 pass a parent with a trailing slash that realpath() then strips. That looks like a real latent issue, but fixing it would pull L10N\Factory into a security patch that needs to stay backportable, so I have left it alone. Happy to file it separately.

On the .php requirement: I checked 693 info.xml files across the local app trees, including an enterprise one. Only three distinct handler values exist — appinfo/v1/publicwebdav.php, public.php and user_shibboleth's appinfo/remote.php — and all end in .php. user_shibboleth is a real app that goes through the remote.php default: branch, so it is the case most at risk from this change, and it is fine. If you would rather not have the suffix requirement at all, say so and I will drop it; it is one line.

2. Non-canonical app ids — implemented as an explicit 400, with a correction

Implemented, as the explicit 400 from your parenthetical rather than by folding the charset check into isCoreApp(). isCoreApp() stays a normalized recognizer that means what its name says; a separate isCanonicalAppId() gates setValue, deleteKey and deleteApp. Both layers turn out to be load-bearing: core.. passes the charset regex because . is in the class, and is caught only by isCoreApp()'s cleanAppId(), while core and CORE fail the regex.

Two corrections to the mechanics, neither of which changes your conclusion:

The collation examples do not apply to an ownCloud-provisioned database. ConnectionFactory.php:210,219 and Setup/MySQL.php:71 force utf8_bin / utf8mb4_bin, which are both case- and accent-sensitive, so neither CORE nor córe folds onto core there. They do fold on a database the admin pre-created with the MySQL 8 utf8mb4_0900_ai_ci default, which the install docs invite, so the vector is real — just not on a default install.

The length cap is doing more work than the charset. appid is varchar(32) (db_structure.xml:21-27), so "core" + 28 spaces + "X" is not equal to "core" in PHP, survives trim() because it ends in X, and truncates to "core" + 28 spaces, which a PAD SPACE collation folds onto the core row. That one works on a default install wherever sql_mode is not strict. It is in the tests.

I kept uppercase in the charset — /^[a-zA-Z0-9_.-]{1,32}$/ rather than /^[a-z0-9_.-]{1,32}$/. Your version rejects the mixed-case ids this endpoint has always accepted (the existing tests use appId003, so it also fails them), and case is already covered because the core comparison lowercases. Every actual folding vector — padding, invalid bytes, accents, over-length — still needs a character outside the charset.

Also confirmed your point about over-reach: files_sharing does own public_share_sharers_groups_allowlist*, so a key-prefix-only block would break it. There is now a test pinning that, so nobody "simplifies" it into a prefix check later.

Two defects in my own first attempt at this, both now fixed and tested, because they are the same mistake you were pointing at:

  • The pattern was anchored with $, and PCRE's $ also matches before a single trailing newline. str_repeat('a', 32) . "\n" passed the check and then truncated into the 32-byte column onto an existing row. It is \z now.
  • It did not test is_string(). (string) on an array yields the literal "Array", which matches the charset, so app[]=core passed both guards and died inside AppConfig::setValue() as a 500 rather than being refused with a 400.

2b. The key had the same defect, and I had missed it

Your argument about the app id applies verbatim to the key, and my first version did not follow it: isCoreApp() normalized the app but the key test was strpos($key, 'public_') === 0. Under a case-insensitive configkey collation, PUBLIC_webdav is not caught, yet AppConfig::setValue() reconciles onto the existing row — hasKey() misses because the in-memory cache is exact-match, insertIfNotExist() finds the row under the collation and skips the insert, and control falls through to UPDATE … WHERE appid = ? AND configkey = ?, overwriting the real public_webdav. deleteKey deletes it outright, which breaks public links and WebDAV.

The prefix test is case-insensitive now. And because an accent-insensitive collation folds públic_webdav onto the row as well — which no prefix test can catch — a key that is not canonical (/^[a-zA-Z0-9_.-]{1,64}\z/, matching the varchar(64) column) is refused outright, but only when the app is core. On a fresh install core has five keys, all canonical ASCII and at most 21 bytes, so there is nothing legitimate to break.

3. deleteApp on the legacy endpoint — fixed

Confirmed exactly as described: the guard at core/ajax/appconfig.php:42 only fires when $_POST['key'] is set, so action=deleteApp&app=core reached deleteApp() at :69 and dropped every core row. It has its own guard now, and the canonical-id check is mirrored there for the mutating actions.

4. Testing the sink — done, but not the way you suggested

The acceptance scenario cannot work on this PR: 10.16 has no acceptance workflow. Its .github/workflows/ contains only ci, lint-and-codestyle, lint-pr-title, php-unit, stale and translation-sync; acceptance.yml exists on master only. An acceptance test added here would never run.

That is the reason the containment check is an extracted helper instead of inline code in the entry script: as a method on OC_App it is unit-testable, so it runs in php-unit on both branches. tests/lib/legacy/AppTest.php now covers a file inside the app, traversal that stays inside, traversal out of the app, the sibling-directory boundary, a non-.php target, a missing file, empty arguments, and the app-id-with-no-directory case that is the actual bypass from point 1.

There is also now a data-provider test pinning all six shipped handler values, which is the case most at risk from this change. Worth noting for anyone reading the switch in remote.php: every hardcoded service resolves to a dav/... path, so $parts[0] is always dav and they all flow through the default: branch — case 'core': is unreachable, which is why leaving it uncontained is safe.

Every new guard was mutation-tested — reverting each line individually turns the corresponding test red: the containment check, the trailing separator, the .php suffix, is_file(), is_string(), \z vs $, the case-insensitive prefix, the canonical-key check, and the canonical-id check, which alone fails 18 cases. I also ran the end-to-end check on a live instance: the three attack values are refused while public.php/webdav, public.php/files, remote.php/webdav and remote.php/dav all still serve normally.

One more thing the containment check needed: is_file(), not just the .php suffix. realpath() succeeds for a directory too, so a directory named handler.php inside an app would have been require_once'd — an E_COMPILE_ERROR, which neither entry script's catch (\Throwable) can handle, so it would be a white screen with nothing logged.

One thing I will not claim coverage for: the realpath() === false early return is defensive and unreachable, because getAppPath() only ever returns directories that exist. I kept it because without the base half a false base would degenerate the prefix to / and accept any absolute path, but no test can reach it.

The changelog PR number is fixed, and the ticket references are out of the source comments and the PR title — this repo is public.

One pre-existing flake worth knowing about, found while verifying this on master: AppManager::getAppInfoByPath() does \version_compare($appIdData['info']['version'], $info['version']) (lib/private/App/AppManager.php:535) without checking either key. tests/lib/legacy/AppTest.php's fixture app declares no <version>, so once the appInfo cache is warm that line raises "Undefined array key" and the surrounding tests error. It only triggers when the cache survives from a previous process — reusing a persistent install locally reproduces it in roughly one run in three, while a fresh install is green every time, so CI is unaffected and this is not a blocker here. I left it alone because it is unrelated to this patch, but it is a real latent bug in the version-comparison branch.

Two smaller things I noticed and deliberately did not bundle, both pre-existing: the OC_Helper::isSubDirectory() separator issue above, and OC_App::cleanAppId() at lib/private/legacy/app.php:75, whose '\0' is a single-quoted two-character string rather than a NUL byte, so it never strips what it looks like it intends to. Harmless once non-canonical ids are refused.

Addresses a re-review of the two commits before it. None of it re-opens
the include sink; the RCE class stays closed by getServiceHandlerPath().

The guards were hand-copied between AppConfigController and
core/ajax/appconfig.php, which is exactly what let the legacy endpoint
ship without the deleteApp guard in the first place. isCoreApp(),
isCanonicalAppId(), isCanonicalConfigKey(), isServiceHandlerKey() and
isProtectedCoreServiceKey() are now OC_App statics that both call, with
their own tests, and the endpoint's comment block shrinks to what is
actually endpoint-specific. The endpoint also requires cleanAppId() to be
a no-op on the app id, so that it agrees with the controller, which
validates and writes the raw value: the canonical charset permits `.`, so
`co..re` would otherwise pass validation here and be written as `core`,
and `..` as the empty app id.

Only the write paths were guarded. The legacy endpoint had no read guard
at all, so `GET .../core/ajax/appconfig.php?action=getValue&app=core&
key=public_webdav` returned the stored handler path; the canonical-app-id
check was gated on a mutating action, and the key guard read only
$_POST['key'], which is null on a GET. The guard now checks the key in
every source the dispatch below might read it from, not just the first one
it finds: the write actions take $_POST['key'] while getValue/hasKey take
$_GET['key'], and an attacker controls both independently, so validating
one source lets a harmless decoy in the other satisfy the guard while the
action consumes the real key. getValue() in the controller refused the
exact lowercase prefix already but not a mangled spelling of it, and was
missing the key charset check its siblings have; it carries the same pair
now, so all three entry points share one predicate and cannot drift apart.
(A read cannot fold onto a stored row - OC\AppConfig::getValue() is an
exact lookup in the preloaded cache, so the collation never sees the key -
it is the case-insensitive prefix match that mattered here.)

isProtectedCoreServiceKey() compared preg_match() === 1 where its two
siblings compare !== 1, so a PCRE error made it fail open. It now fails
closed like the others, through the extracted isServiceHandlerKey().

`app[]=core` stringified to "Array" - passing the charset test and landing
a row under the app id `Array` - because the endpoint cast before
validating. A non-string app id is refused outright now, and so is a
non-string key on a write: it reaches OC\AppConfig as an array subscript,
which is an "Illegal offset type" warning on PHP 7 and a TypeError on PHP
8, and then binds as "Array".

getServiceHandlerPath() documents that callers must treat false as
"refuse", but a stored NUL byte reached realpath() - and, through
getAppPath(), is_dir() - which warn on PHP 7 and throw on PHP 8. Both
arguments are now tested for it before either is used as a path.

deleteKey() no longer demands a canonical app id outright: a row written
under a non-canonical one before that guard existed - through this
endpoint, occ, or an app calling setAppValue() - was left undeletable
through both admin paths. It may only be removed key by key and only for a
canonical, non-handler key, because isCoreApp() compares a normalized
string and cannot see a spelling that only the collation folds onto
"core": on an accent-insensitive collation - utf8mb4_general_ci or
utf8mb4_0900_ai_ci, the MySQL default whenever the database is pre-created
rather than created by ownCloud - deleting "córe"/"public_webdav" would
otherwise remove core's registered handler, which is only re-registered on
an app version bump. Blank padding plus varchar(32) truncation gets there
without any exotic collation at all. Canonical app ids are untouched, so
files_sharing keeps its legitimate public_share_* keys. deleteApp() keeps
the blanket check, since dropping the whole core appconfig is not
recoverable at all.

Two pre-existing bugs in the reworked flow: getAppValue() returns '' for
an unregistered service rather than null, so the `$file === null` test
never fired and the service came back as a logged 500 on public.php and as
a malformed status line on remote.php instead of a 404. And a
RemoteException thrown without a status code has getCode() 0, which
OC_Response::setStatus() turns into that same bogus `HTTP/1.1 0` - read as
a success by caches, monitoring and sync clients - so every throw now
carries an explicit status. The refusals get 503 rather than 404, because
that is what handleException() already answered on a WebDAV request (code
0 matches no case in its switch and falls through to ServiceUnavailable),
and a sync client must not be told the root is gone.

Finally, remote.php's `case 'core':` branch is the one include site
without a containment check and is unreachable by contradiction - that
reasoning is now written down next to it, since the sibling branch being
hardened invites a future change to assume it is safe.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@oc-tmueller

Copy link
Copy Markdown
Contributor Author

Pushed 1d871b8 addressing the review. Below is what changed, then three items I answered rather than coded.

Fixed

The read path was unguarded. The legacy endpoint had no read guard at all, so GET .../core/ajax/appconfig.php?action=getValue&app=core&key=public_webdav returned the stored handler path: the canonical-app-id check was gated on a mutating action, and the key guard only looked at $_POST['key'], which is null on a GET. hasKey was open the same way. Both are covered now, and the guard checks the key in every source the dispatch might read it from rather than the first one it finds — the write actions take it from $_POST and the reads from $_GET, and both are attacker-controlled independently, so validating one source alone let a harmless decoy in the other satisfy the guard while the action consumed the real key. AppConfigController::getValue() already refused the exact lowercase prefix, but not a mangled spelling of it, and was missing the key charset check its siblings have.

The guards are no longer hand-duplicated. isCoreApp(), isCanonicalAppId(), isCanonicalConfigKey(), isServiceHandlerKey() and isProtectedCoreServiceKey() are OC_App statics with their own unit tests; both endpoints call them instead of carrying copies of the regexes, and the 34-line comment block explaining how the copy differed from the original is gone. That duplication is exactly what let the deleteApp guard be missing from the legacy endpoint in the first place.

isProtectedCoreServiceKey() failed open where its two siblings fail closed — it compared preg_match() === 1, so a PCRE error read as "not protected".

app[]=core stringified to "Array", passed the charset test and landed a row under the app id Array, because the endpoint cast before validating. A non-string app id is refused outright now, and so is a non-string key on a write — it reaches OC\AppConfig as an array subscript, an "Illegal offset type" warning on PHP 7 and a TypeError on PHP 8. The endpoint additionally requires cleanAppId() to be a no-op, so co..re can no longer pass validation and then be written as core (the canonical charset permits .), and .. can no longer be written as the empty app id.

getServiceHandlerPath() and a NUL byte. The docblock promises false, but a stored …webdav.php\0.jpg reached realpath() and a NUL in the app id reached is_dir() through getAppPath() — a warning on PHP 7, a throw on PHP 8. Both arguments are tested before either is used as a path. (cleanAppId() does not help: its '\0' is a literal backslash-zero.)

Pre-existing rows under a non-canonical app id were undeletable. deleteKey no longer demands a canonical app id outright — but such a row may only be removed key by key and only for a canonical, non-handler key. isCoreApp() compares a normalized string, so it cannot see a spelling that only the collation folds: on an accent-insensitive collation (utf8mb4_general_ci, utf8mb4_0900_ai_ci — the MySQL default whenever the database is pre-created rather than created by ownCloud), or simply via blank padding plus varchar(32) truncation, deleteKey('córe', 'public_webdav') would otherwise delete core's registered handler, and that is only re-registered on an app version bump. Canonical app ids are untouched, so files_sharing keeps its legitimate public_share_* keys. deleteApp keeps the blanket check, since dropping the whole core appconfig is not recoverable at all.

if ($file === null) was dead code — getAppValue() returns '', never null — so an unregistered service fell through to App not installed: and surfaced as a logged 500 on public.php and a malformed status line on remote.php. Both answer 404 now.

A RemoteException thrown without a code emitted HTTP/1.1 0, which caches, monitoring and sync clients read as a success. Every throw carries a status now. The refusals answer 503 rather than 404 deliberately: that is what handleException() already produced on a WebDAV request (code 0 matches no case in its switch and falls through to ServiceUnavailable), and a sync client must not be told the root is gone.

remote.php's case 'core': is the one require_once site without a containment check. It is unreachable by contradiction — reaching it needs a stored remote_<service> value starting core/, which means $service was not hardcoded, which the in_array() above then rejects — and that reasoning is written down next to it now, since hardening the sibling branch invites a future change to assume this one is safe.

Also dropped the test asserting that a traversal resolving back inside the app directory is accepted through the entry points — it cannot be, both reject ../ earlier — but kept it as a test of the helper's own documented contract, so a later change to ban .. outright cannot pass silently.

Answered, not coded

  • Pushing the charset enforcement down into OC\AppConfig::setValue() so it covers occ and every app calling setAppValue() would be the tidier design and would make both endpoint copies redundant. It changes IConfig::setAppValue() for every writer, though, which belongs in a major release rather than a patch — and occ access is already shell access, so this is design cleanliness rather than a gap. Worth a follow-up issue.
  • core/ajax/appconfig.php still has no automated coverage. It calls OCP\JSON::callCheck() → passesCSRFCheck(), so no API test can reach it without a browser session, and there is no harness for core/ajax/* scripts. What I could do instead was move the logic out — the shared predicates above are unit-tested, so what is left unpinned is the wiring. I verified that wiring by hand over HTTP on a live instance: every guard above refuses, and GET getValue core/lastupdatedat, a files_sharing key, setValue on a normal app, deleteKey('app!','key1'), WebDAV PROPFIND (207), /remote.php/dav/files/… (207) and a files_sharing public link (401 challenge) all still work, with the public_webdav row intact after every delete attempt.
  • public.php still answers a logged 500 for a handler that fails containment, where remote.php now answers an unlogged 503. Making the two consistent means giving public.php a RemoteException equivalent, which is more than this fix should carry; noting it rather than folding it in.

Verification

tests/lib/legacy/AppTest.php and tests/Settings/Controller/AppConfigControllerTest.php are green on PHP 7.4 — 89 and 308 tests — and I confirmed each new test goes red without its fix rather than trusting a green run. php-cs-fixer clean on all seven touched files.

This needs a fresh look, since the push dismissed the previous state.

@kw-fscheuer kw-fscheuer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at 1d871b8. Everything from my previous round is addressed — this looks good to me.

The containment helper is the right shape, and promoting the predicates to OC_App statics removes the duplication that caused the earlier drift between the controller and the legacy endpoint.

Three things you fixed better than I flagged them:

  • The read guard collects both $_POST['key'] and $_GET['key'] and checks both. I'd only asked for the read path to be guarded at all; the point that picking one source lets a decoy in the other satisfy the guard is a sharper reading than mine.
  • I flagged the NUL byte in $relativePath — catching it in $app too, because getAppPath() reaches is_dir() which fails the same way, closes the half I missed.
  • cleanAppId() stripping .., so the charset alone would let co..re be written as core on the legacy endpoint, is something I didn't spot at all. The $app !== $rawApp test is the right answer.

One correction to my own earlier comment: I claimed a read could fold onto the stored row under an accent-insensitive collation. That was wrong, and your comment in getValue() has it right — loadConfigValues() selects the whole table into a PHP array and hasKey() is an exact isset(), so no collation is consulted on a read. The write-side fold was the real one, and that was already closed. Adding the read guard for predicate consistency still looks worth it.

Nothing blocking from me. The one thing I'd still leave on the list, and it does not need to hold up this PR: core/ajax/appconfig.php has no test of its own. The predicates are well covered now, but the endpoint's wiring — the two-source key collection, the action lists, the $app !== $rawApp test — grew a lot this round and is exactly the part that drifted from the controller before.

@oc-tmueller
oc-tmueller merged commit b46c15d into 10.16 Sep 23, 2026
11 checks passed
@oc-tmueller
oc-tmueller deleted the fix/oc10-146-appconfig-path-traversal branch September 23, 2026 12:58
oc-tmueller added a commit that referenced this pull request Sep 25, 2026
Bump version.php to 10.16.5 and materialize the changelog fragments for
this release.

$OC_Version becomes [10, 16, 5, 0]: the 4th digit is the internal
DB-upgrade patch level, not the public patch number, and nothing in this
release needs it moved.

The 11 fragments in changelog/unreleased/ move into
changelog/10.16.5_2026-09-25/ (git mv, so the renames stay tracked) and
CHANGELOG.md is regenerated with calens. unreleased/ keeps its .gitkeep
and is now empty, ready for the next cycle.

Security:

- #41784 update PHP dependencies to close published advisories
- #41803 prevent path traversal via appconfig public_/remote_ keys
- #41827 reject SVG/script content before it reaches ImageMagick bitmap
  previews
- #41834 pin the Imagick coder for each preview provider

Bugfixes:

- #41782 restore index usage for filecache writes on Oracle
- #41808 avoid a deprecation notice when hashing the file cache path on
  Oracle
- #41814 show federated users in the share dialog when local users also
  match
- #41819 speed up Oracle schema introspection
- #41835 release the file handle when a bitmap preview cannot be decoded
- #41855 report a preview file that cannot be opened without logging
  noise

Changes:

- #41788 update PHP dependencies

Same shape as 852062d ("feat: release 10.16.4"), which did the changelog
and the version bump in one commit. Once merged, v10.16.5 gets tagged on
the merged commit and the release bundles are built and published from
owncloud/server-release.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Thomas Müller <[email protected]>
oc-tmueller added a commit that referenced this pull request Sep 25, 2026
* feat: release 10.16.5

Bump version.php to 10.16.5 and materialize the changelog fragments for
this release.

$OC_Version becomes [10, 16, 5, 0]: the 4th digit is the internal
DB-upgrade patch level, not the public patch number, and nothing in this
release needs it moved.

The 11 fragments in changelog/unreleased/ move into
changelog/10.16.5_2026-09-25/ (git mv, so the renames stay tracked) and
CHANGELOG.md is regenerated with calens. unreleased/ keeps its .gitkeep
and is now empty, ready for the next cycle.

Security:

- #41784 update PHP dependencies to close published advisories
- #41803 prevent path traversal via appconfig public_/remote_ keys
- #41827 reject SVG/script content before it reaches ImageMagick bitmap
  previews
- #41834 pin the Imagick coder for each preview provider

Bugfixes:

- #41782 restore index usage for filecache writes on Oracle
- #41808 avoid a deprecation notice when hashing the file cache path on
  Oracle
- #41814 show federated users in the share dialog when local users also
  match
- #41819 speed up Oracle schema introspection
- #41835 release the file handle when a bitmap preview cannot be decoded
- #41855 report a preview file that cannot be opened without logging
  noise

Changes:

- #41788 update PHP dependencies

Same shape as 852062d ("feat: release 10.16.4"), which did the changelog
and the version bump in one commit. Once merged, v10.16.5 gets tagged on
the merged commit and the release bundles are built and published from
owncloud/server-release.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Thomas Müller <[email protected]>

* fix: correct three defects in the 10.16.5 release notes

Found reviewing the release commit, all three in text that ships inside the
tarball, so this is the last point at which they are free to fix.

**Six updated dependencies were unnamed.** Diffing composer.lock at v10.16.4
against this branch gives 17 changed production packages; the entry listed 11.
Missing: sabre/dav (4.7.0 to 4.7.1), sabre/event (5.1.7 to 5.1.9),
sabre/vobject (4.5.8 to 4.6.1), pimple/pimple (v3.6.1 to v3.6.2),
nikic/php-parser (v5.7.0 to v5.9.0) and dg/composer-cleaner (v2.2.1 to
v2.2.2). All but sabre/event are direct entries in composer.json's require,
and sabre/vobject is a minor bump of the vCard/iCalendar parser behind CalDAV
and CardDAV — an administrator auditing what moved in that stack for 10.16.5
would have seen nothing. Five of the six came from #41787, whose URL was
missing from the entry as well; nikic/php-parser then went on to v5.9.0 in
#41830, which was already listed. Earlier releases on this branch do list
sabre bumps here (10.10.0, 10.11.0, 10.12.0), so the omission also broke the
house convention.

**Two entries linked a pull request that never reached this branch.** #41819
was merged into ci/oracle-db-in-github-actions-10.16, an intermediate branch
that no longer exists on the remote; the change reached 10.16 through #41815
(9408736). Likewise the 41835 entry cited only master's #41835, while the
10.16 delivery was #41837 (6443822). Both now cite the 10.16 pull request
first, matching what 41827, 41834 and 41855 already do with #41863 — so
calens also makes the branch's own pull request the primary link.

CHANGELOG.md is regenerated with calens and, as on the rest of this branch,
written without a trailing newline: `ocrelease changelog` captures calens'
stdout through execa, which strips it, and every released section on 10.16 was
produced that way. Adding one here would only create churn at the next
release.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Thomas Müller <[email protected]>

* chore: fold the federated address book sync fix into the 10.16.5 release notes

Its fix merged into 10.16 after the release notes were first prepared, so
its changelog fragment was still sitting in changelog/unreleased and would
have been deferred to the next release while the fix itself shipped in this
one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Thomas Müller <[email protected]>

---------

Signed-off-by: Thomas Müller <[email protected]>
Co-authored-by: Thomas Müller <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants