Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Security

- `setDefault()` and `change()` now reject a language identifier that is empty or
contains anything other than letters, digits, `_` and `-` (checked with `\A…\z`,
so a trailing newline is rejected too) by throwing `TranslatorException` before
any file is read. Previously the identifier was joined into the path of a file
that was `require`d, so a request-supplied value such as `../config/install`
could run PHP files outside the language directory. The translator's state is
unchanged when a code is rejected. Codes such as `en`, `en_US` and `pt-BR` keep
working; a language pack whose name used `.` or `/` must be renamed.
- `setDefault()` and `change()` now reject a language identifier that is empty,
contains `/`, `\` or a NUL byte, or consists only of dots and spaces (`.`, `..`,
and the forms Windows normalises to them) by throwing `TranslatorException`
before any file is read. Previously the identifier was joined into the path of a
file that was `require`d, so a request-supplied value such as `../config/install`
could run PHP files outside the language directory. Codes that pointed into a
sub-directory of the language directory (`sub/en`, and `sub\en` on POSIX) worked
in 2.0.0 in both modes and are now rejected; a language pack must sit directly
in the language directory (or be a directory of its own in directory mode).
Every other name keeps working exactly as in 2.0.0 (`en_US`, `pt-BR`,
`sr@latin`, `zh.Hant`, `türkçe`, names with a space). On Windows a `:` is also
rejected, as it is not valid in a file name there. The translator's state is unchanged when a code is rejected.
- In directory mode the language path is matched literally by `glob()`: `*`, `?`
and `[` in a language code or in the base directory are no longer wildcards, so
a directory named like `.*` cannot also pull in the files of its parent.

### Fixed

Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,9 @@ $lang->translate('errorMsg', null, ['code' => 2005]);
All configuration methods return `$this`, so calls can be chained.

> **Security:** the identifier given to `setDefault()` / `change()` is joined into
> a file path and the file is `require`d, so only letters, digits, `_` and `-` are
> accepted; anything else throws a `TranslatorException` before a file is touched.
> Still check request input (`$_GET`, cookies, headers) against an allow-list such
> a file path and the file is `require`d, so an empty identifier, one containing `/`,
> `\` or a NUL byte, or one made only of dots and spaces (`.`, `..`) throws a
> `TranslatorException` before a file is touched. Still check request input (`$_GET`, cookies, headers) against an allow-list such
> as `['en', 'tr', 'fr']` first, so an unsupported language falls back instead of
> throwing. See
> [Exceptions](docs/Exceptions.md#validate-user-supplied-language-codes).
Expand Down
10 changes: 5 additions & 5 deletions docs/API-Reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,12 @@ has been chosen yet, this language also becomes the active one.

- **`$default`** — language identifier (a file name without extension in file
mode, or a sub-directory name in directory mode). It is joined into a path and
the file is `require`d, so only letters, digits, `_` and `-` are accepted;
the file is `require`d, so it must be a single path component (see
[Validate user-supplied language codes](Exceptions.md#validate-user-supplied-language-codes));
validate request input against an allow-list anyway — see
[Validate user-supplied language codes](Exceptions.md#validate-user-supplied-language-codes).
- **Throws** [`TranslatorException`](Exceptions.md) if the identifier is empty or
contains any other character, if the directory is unset, or the language pack
- **Throws** [`TranslatorException`](Exceptions.md) if the identifier is empty,
contains `/`, `\` or a NUL byte, or consists only of dots and spaces, if the directory is unset, or the language pack
is missing, unreadable, or does not return an array. On any of these the
translator keeps its previous state (see [Exceptions](Exceptions.md)).

Expand All @@ -119,8 +120,7 @@ Switches the active language, loading it on first use. If no default language ha
been set yet, the given language also becomes the default.

- **`$current`** — language identifier to activate. Like `setDefault()`, it is
joined into a path and the file is `require`d, so only letters, digits, `_` and
`-` are accepted. Do not pass request input directly; check it against an
joined into a path and the file is `require`d, so the same rule applies. Do not pass request input directly; check it against an
allow-list first — see
[Validate user-supplied language codes](Exceptions.md#validate-user-supplied-language-codes).
- **Throws** [`TranslatorException`](Exceptions.md) under the same conditions as
Expand Down
30 changes: 23 additions & 7 deletions docs/Exceptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class TranslatorException extends \Exception {}
| A language **file** is missing (file mode) | `setDefault()` / `change()` | `The translation file was not found: "/app/languages/de.php".` |
| A language **directory** is missing (directory mode) | `setDefault()` / `change()` | `The translation directory was not found: "/app/languages/de/".` |
| A directory could not be read | `setDefault()` / `change()` | `The translation directory could not be read: "...".` |
| The language identifier contains anything other than letters, digits, `_` and `-` (or is empty) | `setDefault()` / `change()` | `The language code is invalid. Only letters, digits, "_" and "-" are allowed.` |
| The language identifier is empty, contains `/`, `\` or a NUL byte (or `:` on Windows), or consists only of dots and spaces | `setDefault()` / `change()` | `The language code is invalid. It must not be empty, contain "/", "\" or a NUL byte (or ":" on Windows), or consist only of dots and spaces.` |
| A language file does not `return` an array | `setDefault()` / `change()` | `The translation file "/app/languages/en.php" must return an array.` |

Every message names the offending path or condition.
Expand Down Expand Up @@ -77,13 +77,29 @@ try {

## Validate user-supplied language codes

`setDefault()` and `change()` only accept identifiers made of letters, digits,
`_` and `-` (`en`, `en_US`, `pt-BR`). The identifier is appended to the directory
The identifier given to `setDefault()` and `change()` is appended to the directory
you gave `setDir()` (`<dir>/<identifier>.php` in file mode,
`<dir>/<identifier>/*.php` in directory mode) and the result is `require`d, so
anything else — `../config/install`, a `/`, a `.`, a trailing newline, a NUL
byte, an empty string — is rejected with a `TranslatorException` **before** any
file is touched.
`<dir>/<identifier>/*.php` in directory mode) and the result is `require`d. It
must therefore be a single, ordinary path component, and these are rejected with
a `TranslatorException` **before** any file is touched:

- an empty identifier,
- a `/` or a `\` (both separate path components on Windows), so `../config/install`
and `en/../../x` cannot leave the language directory,
- a NUL byte,
- a `:` on Windows, where it is not valid in a file name and could only address a
drive-relative path or an alternate data stream,
- an identifier made only of dots and spaces: `.` and `..`, and the forms Windows
normalises to them (`...`, `.. `, `. .`).

Everything else is an ordinary file name and works as before: `en`, `en_US`,
`pt-BR`, `sr@latin`, `zh.Hant`, `türkçe`, even a name with a space. Outside
Windows a `:` is an ordinary character, too; a drive letter or a stream-wrapper
prefix such as `phar:` or `php:` only counts at the very start of a path, and that
start is your `setDir()` path. Because a code cannot contain a separator it is one
path component and cannot leave the language directory. In
directory mode the `*`, `?` and `[` characters are matched literally, not as
`glob()` wildcards.

The check only keeps the lookup inside the language directory. It does not know
which languages you support: a well-formed code such as `xx` still throws
Expand Down
8 changes: 4 additions & 4 deletions docs/Quick-Start.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ $lang->setDir(__DIR__ . '/languages/')
->setDefault('en');

// Per request, choose a language. The identifier becomes part of a file path
// (anything but letters, digits, "_" and "-" is rejected), and an unknown but
// well-formed code throws, so pass a value from your own allow-list:
// (a separator, a NUL byte, an empty value or ".." is rejected), and an unknown
// but well-formed code throws, so pass a value from your own allow-list:
$supported = ['en', 'tr', 'fr'];
$requested = $_GET['lang'] ?? 'en';

Expand All @@ -130,8 +130,8 @@ echo $lang->translate('welcome', 'Welcome {user}', [
## Common mistakes

- **Passing request input straight to `change()`.** The identifier is joined
into a path and the file is `require`d. Characters outside `[A-Za-z0-9_-]` are
rejected, but an unsupported code still throws — see
into a path and the file is `require`d. A separator, a NUL byte, an empty value
or `..` is rejected, but an unsupported code still throws — see
[Exceptions](Exceptions.md#validate-user-supplied-language-codes).
- **Setting the layout mode too late.** Calling `useDirectory()` after a language
has loaded throws. Set the mode first — see [Troubleshooting](Troubleshooting.md).
Expand Down
6 changes: 3 additions & 3 deletions docs/Recipes.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ te('hello'); // echoes
## Pick the language per request

Resolve the active language from the request, always validating against a known
list. `change()` builds a file path from its argument: characters outside
`[A-Za-z0-9_-]` throw, and an unsupported code throws a file-not-found error, so
an unvalidated value breaks the request instead of falling back (see
list. `change()` builds a file path from its argument: a separator, a NUL byte,
an empty value or `..` throws, and an unsupported code throws a file-not-found
error, so an unvalidated value breaks the request instead of falling back (see
[Exceptions](Exceptions.md#validate-user-supplied-language-codes)):

```php
Expand Down
40 changes: 31 additions & 9 deletions src/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
use function is_dir;
use function is_file;
use function method_exists;
use function preg_match;
use function rtrim;
use function str_contains;
use function strpbrk;
use function strtolower;
use function strtr;

Expand Down Expand Up @@ -257,25 +257,47 @@ private function interpolate(string $message, array $context): string
}

/**
* Rejects a language identifier that could escape the language directory.
* Rejects a language identifier that is not a single, ordinary path component.
*
* The identifier is joined into a path that is then `require`d, so only
* letters, digits, `_` and `-` are accepted. `\z` (not `$`) keeps a trailing
* newline from slipping through.
* The identifier is joined into a path that is then `require`d, so it must
* stay inside the language directory: it may not be empty, contain a path
* separator (`/`, and `\` which separates on Windows) or a NUL byte, and may
* not consist only of dots and spaces. The last rule covers `.` and `..` and
* the forms Windows normalises to them (`...`, `.. `, `. .`), which would
* select the language directory itself or its parent. Everything else, such
* as `en_US`, `sr@latin`, `zh.Hant` or `türkçe`, is an ordinary file name.
*
* @param string $lang The language identifier to check.
* @return void
* @throws TranslatorException If the identifier contains any other character, or is empty.
* @throws TranslatorException If the identifier is rejected.
*/
private function assertValidLanguageCode(string $lang): void
{
if (preg_match('/\A[A-Za-z0-9_-]+\z/', $lang) !== 1) {
// ":" is not valid in a Windows file name; there it can only address a
// drive-relative path or an alternate data stream, so it is refused.
$windowsColon = DIRECTORY_SEPARATOR === '\\' && str_contains($lang, ':');

if ($lang === '' || strpbrk($lang, "/\\\0") !== false || rtrim($lang, ' .') === '' || $windowsColon) {
throw new TranslatorException(
'The language code is invalid. Only letters, digits, "_" and "-" are allowed.',
'The language code is invalid. It must not be empty, contain "/", "\\" or a NUL byte '
. '(or ":" on Windows), or consist only of dots and spaces.',
);
}
}

/**
* Escapes the characters `glob()` treats as wildcards, so that a language
* code such as `.*` or `[.][.]` names a directory literally instead of
* expanding to `..` and reaching files outside the language directory.
*
* @param string $path The literal path to use as a glob pattern.
* @return string The pattern that matches exactly that path.
*/
private function escapeGlob(string $path): string
{
return strtr($path, ['*' => '[*]', '?' => '[?]', '[' => '[[]']);
}

/**
* Loads a language into the in-memory cache if it is not already present.
*
Expand Down Expand Up @@ -344,7 +366,7 @@ private function load(string $lang): void
throw new TranslatorException('The translation directory was not found: "' . $path . '".');
}

$files = glob($path . '*.php');
$files = glob($this->escapeGlob($path) . '*.php');
if ($files === false) {
throw new TranslatorException('The translation directory could not be read: "' . $path . '".');
}
Expand Down
14 changes: 8 additions & 6 deletions src/TranslatorInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,10 @@ public function setDir(string $dir): TranslatorInterface;
* extension in file mode, or a sub-directory name in
* directory mode).
* @return TranslatorInterface The same instance, for chaining.
* @throws TranslatorException If the identifier is empty or contains anything
* other than letters, digits, `_` and `-`, the
* directory is not set, or the language pack cannot
* @throws TranslatorException If the identifier is empty, contains `/`, `\`
* or a NUL byte (or `:` on Windows), or consists
* only of dots and spaces, the directory is not
* set, or the language pack cannot
* be found, read or does not return an array. The
* translator keeps its previous state on failure.
*/
Expand Down Expand Up @@ -91,9 +92,10 @@ public function useDirectory(): TranslatorInterface;
*
* @param string $current Language identifier to activate.
* @return TranslatorInterface The same instance, for chaining.
* @throws TranslatorException If the identifier is empty or contains anything
* other than letters, digits, `_` and `-`, the
* directory is not set, or the language pack cannot
* @throws TranslatorException If the identifier is empty, contains `/`, `\`
* or a NUL byte (or `:` on Windows), or consists
* only of dots and spaces, the directory is not
* set, or the language pack cannot
* be found, read or does not return an array. The
* translator keeps its previous state on failure.
*/
Expand Down
Loading
Loading