Securing Apache and PHP in Ubuntu

Many of us know that Linux is a very secure system and Ubuntu is nowadays one of the most chosen options by many system administrators, however, a basic installation is not always perfect and we need to “touch things” in order to make it as good as possible.

The problem in Linux, specially in version 12.04, is that a basic installation of Apache 2 and PHP leaves a lot of clues about what we are actually using, so the ideal scenario would be to hide such information to avoid as much as possible an external attack because we have provided, for example, the PHP version that the system is using. Image that, for some reason, tomorrow somebody discovers a lack of security in our PHP version and we are announcing widely in the server’s headers that this version is the one we use. This could potentially be used by hackers in order to attack our systems.

As an example of this just use the following command agains the IP address of a plan Ubuntu installation with just Apache and PHP:

curl -X https://direcciondelservidor

you would probably get something like this:

Date: Fri, 19 Sep 2014 13:09:20 GMT

Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: PHP/5.3.10-1ubuntu3.11

Obviously we are giving “too much” information to any possible attacker so what we need to do is to remove it. To do that we need to do the following steps:

Edit the file /etc/php5/apache2/php.ini and add or modify the following lines:

disable_functions = exec,system,shell_exec,passthru
register_globals = Off
expose_php = Off
display_errors = Off
track_errors = Off
html_errors = Off
magic_quotes_gpc = Off

Following that edit the file /etc/php5/apache2/conf.d/security and do the same operation but with the following lines:

ServerTokens Prod
ServerSignature Off
TraceEnable Off
Header unset ETag
FileETag None

Finally we need to edit the Apache config file where you have defined your website. If you have not changed the default one then it should be /etc/apache2/sites-available/default, and as before we need to add/edit some lines. These ones need to go where you have defined your VirtualHost block:

RewriteEngine On
RewriteRule .* – [R=405,L]

These lines require to have the Apache’s module mod_rewrite activated, so in order to make sure it is being used, execute the following command:

sudo a2enmod rewrite

And finally…

sudo service apache2 restart

If everything went fine we can execute again the curl command against our server and we will see something similar to this:

Date: Fri, 19 Sep 2014 13:17:29 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN

Much better now, isn’t it?