Skip to content

Commit 3657a18

Browse files
committed
fix(Cache): reject separators and dot-only prefixes in validateKey()
- validate the file name returned by parent::validateKey(), so keys over MAX_KEY_LENGTH are still hashed before validation - reject only "/", "\" and null bytes, keeping characters that are valid in file names on Linux and macOS - reject a prefix that consists only of dots and spaces, because such a prefix makes every cache file hidden: getCacheInfo() does not report it, deleteMatching() does not remove it and clean() does not delete it - document the risks of relaxing reservedCharacters and the behavior change
1 parent 33e6dad commit 3657a18

4 files changed

Lines changed: 400 additions & 52 deletions

File tree

‎docs/installation/upgrade_477.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ Please refer to the upgrade instructions corresponding to your installation meth
1010

1111
## Breaking Changes
1212

13+
### File Cache Rejects Directory Separators and Dot-Only Prefixes
14+
15+
For security reasons, `FileHandler::validateKey()` now rejects `/`, `\` and null bytes in the cache item file name, independently of the `Config\Cache::$reservedCharacters` setting. A cache key can no longer point outside the cache directory when that setting is relaxed.
16+
17+
With the default configuration most applications are unaffected, because `/`, `\` and `:` are already reserved characters. Applications that emptied `$reservedCharacters` to share one key namespace between handlers and used directory separators in File cache keys now get an `InvalidArgumentException`. Build keys from identifiers with a controlled format, or hash the input, instead of relaxing `$reservedCharacters`. See [Caching](../libraries/caching.md). A `$prefix` that consists only of dots and spaces is rejected as well, because it would make every cache file a hidden file that `getCacheInfo()` does not report, `deleteMatching()` does not remove and `clean()` does not delete.
18+
1319
## Breaking Enhancements
1420

1521
## Project Files

‎docs/libraries/caching.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,28 @@ In the case that the first choice `$handler` is not available, this is the next
4646

4747
If you have more than one application using the same cache storage, you can add a custom prefix string here that is prepended to all key names.
4848

49+
The File handler rejects a prefix that consists only of dots and spaces. Such a prefix would turn every cache file into a hidden file, which `getCacheInfo()` does not report, `deleteMatching()` does not remove and `clean()` does not delete. A prefix that merely starts with a dot, such as `.app`, is still accepted for backward compatibility, even though it also produces hidden files.
50+
4951
### $ttl
5052

5153
The default number of seconds to save items when none is specified.
5254

5355
WARNING: This is not used by framework handlers where 60 seconds is hard-coded, but may be useful to projects and modules. This will replace the hard-coded value in a future release.
5456

57+
### $reservedCharacters
58+
59+
A string of characters that are not allowed in cache keys or tags. Handlers throw an `InvalidArgumentException` when a key contains one of them. The default, `{}()/\@:`, is required for PSR-6 compliance.
60+
61+
Relaxing `$reservedCharacters` relaxes key validation for every cache handler. The File handler still rejects `/`, `\` and null bytes in the resulting file name, so a cache key cannot point outside the cache directory. The characters left in `$reservedCharacters` still keep keys from being interpreted differently by a handler or by the file system.
62+
63+
On Windows, keep `:` reserved: it separates an NTFS alternate data stream, so a key such as `file:stream` refers to a stream of a file in the cache directory rather than to a new cache item.
64+
65+
Do not use unvalidated user input directly as a cache key. Build keys from identifiers with a controlled format, or hash the input:
66+
67+
```php
68+
$key = 'search_' . hash('sha256', $userInput);
69+
```
70+
5571
### $file
5672

5773
This is an array of settings specific to the **File** handler to determine how it should save the cache files.
@@ -310,7 +326,7 @@ var_dump($cache->getMetadata('my_cached_item'));
310326

311327
- **Return type**: `string`
312328

313-
This method is used by handler methods to check that keys are valid. It will throw an `InvalidArgumentException` for non-strings, invalid characters, and empty lengths.
329+
This method is used by handler methods to check that keys are valid. It will throw an `InvalidArgumentException` for non-strings, invalid characters, and empty lengths. The File handler additionally rejects `/`, `\` and null bytes in the resulting file name, even when `Config\Cache::$reservedCharacters` is relaxed. It also rejects a prefix that consists only of dots and spaces.
314330

315331
Example:
316332

‎system/Cache/Handlers/FileHandler.php‎

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -78,31 +78,42 @@ public function initialize(): void
7878
}
7979

8080
/**
81-
* Validates a cache key, ensuring it contains no directory traversal sequences
82-
* or path separators, regardless of the configured reservedCharacters setting.
81+
* Validates a cache key and returns the file name the item is stored under.
82+
*
83+
* The file name must not contain a directory separator or a null byte, so a
84+
* cache item can never be written outside the cache directory, even when
85+
* `Config\Cache::$reservedCharacters` is relaxed. Other characters are left
86+
* to the configured reserved characters, because rejecting characters that
87+
* are valid in file names on some platforms would break existing keys.
88+
*
89+
* A prefix made only of dots and spaces is rejected as well, because it
90+
* would turn every cache file into a hidden file that `getCacheInfo()` does
91+
* not report, `deleteMatching()` does not remove and
92+
* `clean()` does not delete.
8393
*
8494
* @param mixed $key The key to validate
8595
* @param string $prefix Optional prefix to include in length calculations
8696
*
87-
* @throws InvalidArgumentException When $key is not valid or contains path separators
97+
* @throws InvalidArgumentException When $key is not valid, the resulting
98+
* file name contains a directory separator
99+
* or a null byte, or $prefix consists only
100+
* of dots and spaces
88101
*/
89102
public static function validateKey($key, $prefix = ''): string
90103
{
91-
if (! is_string($key)) {
92-
throw new InvalidArgumentException('Cache key must be a string');
93-
}
104+
// Parent validation also hashes keys that exceed MAX_KEY_LENGTH, so
105+
// validate the returned file name and not the raw key.
106+
$key = parent::validateKey($key, $prefix);
94107

95-
$target = $prefix . $key;
108+
if ($prefix !== '' && trim($prefix, '. ') === '') {
109+
throw new InvalidArgumentException('Cache key prefix cannot consist only of dots and spaces.');
110+
}
96111

97-
if (
98-
$target === ''
99-
|| strpbrk($target, "/\\:\0") !== false
100-
|| trim($target, '. ') === ''
101-
) {
102-
throw new InvalidArgumentException('Cache key cannot contain directory separators or traversal sequences.');
112+
if (strpbrk($key, '/\\') !== false || str_contains($key, "\0")) {
113+
throw new InvalidArgumentException('Cache key cannot contain directory separators or null bytes.');
103114
}
104115

105-
return parent::validateKey($key, $prefix);
116+
return $key;
106117
}
107118

108119
public function get(string $key): mixed

0 commit comments

Comments
 (0)