Security of generated PHP files

Last updated on
9 January 2017

Drupal 8 heavily relies on generated PHP files. This obviously raises security concerns: if an attacker can alter or add to them, arbitrary PHP code might be run. Not just by reaching the generated PHP file via a web browser but also by Drupal including it.

Drupal 8 offers several solutions to this problem: it is possible to generate PHP files in a staging environment and on production use a read only storage class. Also, the default storage class uses a special file name for the dumped code. This file name is a hash from a secret and the containing directory modification time. On read, it also checks that the file modification time is not larger than the directory modification time. These combined mean that although the default storage permissions lets anyone write the compiled files when they are opened and written, the hash immediately becomes invalid. Similarly with deleting the file and writing a new file under the same name. The secret is stored together with the database credentials in settings.php so if the attacker can learn that secret the site is already compromised.

File permissions

Here are some permissions someone might want to set from the docroot of Drupal.  You would use the MYUSER account to deploy any version control changes.  It's assumed www-data is the user/group your Apache or Nginx server is using.  These permissions will prevent Drupal editing any of its own files so an attacker would not be able to change the source code via the website.  The Security Review module can check your file permissions (and much else besides). 

sudo chown -R MYUSER:www-data *
sudo find . -type d -exec chmod 755 {} \;
sudo find . -type f -exec chmod 640 {} \;
sudo find sites/default/files/config* -type f -exec chmod 664 {} \;