WordPress Security Tips Part 8 – Restrict Direct Access to Plugin and Theme PHP files

Allowing direct access to PHP files can be dangerous for a number of reasons. Some plugins and theme files can contain PHP files that are not designed to be called directly because the file would be calling functions that would have been defined in other files. This may cause the PHP interpreter to display errors or warnings which may lead to information disclosure.

Another reason for restricting direct access to PHP files is to prevent attackers from bypassing or avoiding security measures (such as authentication) when code is split-up into smaller files (which will then be included and used together with other code)

Some plugins and themes split-up code into smaller files and include these files into larger pieces of code. An attacker may sometimes be able to call one of the smaller files directly and avoid various security measures such as input validation checks since. Most of the times this occurs because the validation would not performed in other files and not in the mentioned smaller modules.

Furthermore, if the register_globals directive is enabled on the server (directive is disabled by default in PHP versions 4.2.0 and greater), with direct access to a PHP file, an attacker may be able to carry out several malicious actions including the ability to define PHP variables from GET/POST requests and to bypass various protection mechanisms.

The vast majority of plugins and themes would not require a user to make HTTP requests to PHP files directly, however, should there be an exception, you can whitelist files and directories that require direct access to PHP files. The following rule will redirect any direct requests to PHP files to a page of your choosing (in the following example the server will respond with a 404 page and status code).

# Restrict access to PHP files from plugin and theme directories

RewriteCond %{REQUEST_URI} !^/wp-content/plugins/file/to/exclude\.php

RewriteCond %{REQUEST_URI} !^/wp-content/plugins/directory/to/exclude/

RewriteRule wp-content/plugins/(.*\.php)$ - [R=404,L]

RewriteCond %{REQUEST_URI} !^/wp-content/themes/file/to/exclude\.php

RewriteCond %{REQUEST_URI} !^/wp-content/themes/directory/to/exclude/

RewriteRule wp-content/themes/(.*\.php)$ - [R=404,L]

Part 9 in the Series on WordPress Security will discuss: Preventing PHP files from executing
Read the previous article in the series about WordPress Security – Enabling HTTPS for all logins and wp-admin

Share this post

Leave a Reply

Your email address will not be published.