|
14 | 14 | namespace CodeIgniter\Cache\Handlers; |
15 | 15 |
|
16 | 16 | use CodeIgniter\Cache\Exceptions\CacheException; |
| 17 | +use CodeIgniter\Exceptions\InvalidArgumentException; |
17 | 18 | use CodeIgniter\I18n\Time; |
18 | 19 | use Config\Cache; |
19 | 20 | use FilesystemIterator; |
@@ -76,6 +77,35 @@ public function initialize(): void |
76 | 77 | { |
77 | 78 | } |
78 | 79 |
|
| 80 | + /** |
| 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 | + * @param mixed $key The key to validate |
| 90 | + * @param string $prefix Optional prefix to include in length calculations |
| 91 | + * |
| 92 | + * @throws InvalidArgumentException When $key is not valid or the resulting |
| 93 | + * file name contains a directory separator |
| 94 | + * or a null byte |
| 95 | + */ |
| 96 | + public static function validateKey($key, $prefix = ''): string |
| 97 | + { |
| 98 | + // Parent validation also hashes keys that exceed MAX_KEY_LENGTH, so |
| 99 | + // validate the returned file name and not the raw key. |
| 100 | + $key = parent::validateKey($key, $prefix); |
| 101 | + |
| 102 | + if (strpbrk($key, '/\\') !== false || str_contains($key, "\0")) { |
| 103 | + throw new InvalidArgumentException('Cache key cannot contain directory separators or null bytes.'); |
| 104 | + } |
| 105 | + |
| 106 | + return $key; |
| 107 | + } |
| 108 | + |
79 | 109 | public function get(string $key): mixed |
80 | 110 | { |
81 | 111 | $key = static::validateKey($key, $this->prefix); |
|
0 commit comments