Jascha030
Jascha030

Reputation: 73

How to safely evaluate a file's contents before including it in PHP

I am using PHP files returning arrays as a means of configuration. To process these configuration files I made a class to search the provided configuration directories for PHP files and store their values in a configuration container using include().

Now I was just wondering about the safety of this method. What if somebody puts malicious code inside one of these files?

What would be the safest way to evaluate these files before including them and potentially triggering unwanted side effects?

I was thinking about using file_get_contents() to load the file as a string and look for any function calls, but I don't want to restrict users from using functions to resolve, for instance, conditional configuration values.

This is the current code, just for an idea of the workings:

public function load(): void
{
    $iterator = $this->createFinder()->getIterator();

    foreach ($iterator as $file) {
        $config = include $file;

        if (! is_array($config)) {
            throw new \RuntimeException("Invalid config \"{$file->getRealPath()}\", Config files should return an array.");
        }

        $this->config[$file->getBasename()] = $config;
    }
}

private function createFinder(): Finder
{
    $this->finder = (new Finder())
        ->in($this->directories)
        ->files()
        ->name('*.php');

    return $this->finder;
}

Upvotes: 0

Views: 58

Answers (1)

yivi
yivi

Reputation: 47329

Don't bother with any kind of "security" checks. Simply, you should never, ever include, require or eval the contents of a non-trusted file.

Configuration files are not something where "somebody could put malicious code into". If they are, something is seriously broken with the application setup; and that's what needs fixing, not trying to add half-baked "security" checks to account for this glaring security problem.

Configuration should only be performed by someone with the appropriate security clearance. If the person or persons responsible for deploying/configuring the application are your antagonists, then it's already too late too worry about security.

If you want to have a "friendly" configuration format and not worry about the security implications of third party users providing this configuration, provide a way to configure the application with non-runnable code. E.g. parsing text files, XML, ini files, etc.

Configuration still should be performed by trusted application users, but at least they won't be able to execute arbitrary code on the server (without resorting to an exploit).

Upvotes: 2

Related Questions