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 entire article on How to prevent a WordPress hack

SHARE THIS POST
THE AUTHOR
Ian Muscat

Ian Muscat used to be a technical resource and speaker for Acunetix. More recently, his work centers around cloud security and phishing simulation.