Tuesday, July 7, 2009

HOWTO : Hardening your Apache and PHP on Ubuntu 9.04 Server

You have installed LAMP and OpenSSH on your Ubuntu 9.04 Server. The first thing to do is to harden it in order to avoid some kind of attacks.

You can do the following steps in front of your Ubuntu 9.04 Server or remote access it via OpenSSH.

For OpenSSH, your Ubuntu 9.04 Server is at 192.168.0.10 :

ssh 192.168.0.10 -l samiux


Step 1 :

The avoid someone to list your files on your Apache directory, you should do the following step.

sudo nano /etc/apache2/sites-available/default


Add a minus "-" in the front of "Indexes" and it will looking like this :

<Directory /var/www/>
Options -Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>


Step 2 :

To enable the rewrite module of Apache.

sudo a2enmod rewrite


To avoid Cross-Site-Tracing attack. Add the following lines within " <VirtualHost *:80>" :

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]
</IfModule>


Step 3 :

To avoid HTTP DoS, DDoS or Brute Force attack, you should install this module.

sudo apt-get install libapache2-mod-evasive


Step 4 :

To screen out bad URL requests, such as /etc/shadow or MySQL injection and etc. You should install mod_security module. If you installed a amd64 (64-bit) version of Ubuntu Server, please replaced i386 with amd64 for the following commands.

wget http://etc.inittab.org/~agi/debian/libapache-mod-security2/libapache-mod-security_2.5.9-1_i386.deb

wget http://etc.inittab.org/~agi/debian/libapache-mod-security2/mod-security-common_2.5.9-1_all.deb

sudo dpkg -i libapache-mod-security_2.5.9-1_i386.deb mod-security-common_2.5.9-1_all.deb

Step 5 :

Do not allow any Apache and Ubuntu Server information to be print on the error pages.

sudo nano /etc/apache2/conf.d/security


Change the following lines as the following :

ServerToken Prod
ServerSignature Off

Step 6 :

Now, it is time to harden the PHP.

sudo nano /etc/php5/apache2/php.ini


Change the following lines as the following :

display_errors = Off
log_errors = On
allow_url_fopen = Off
safe_mode = On
expose_php = Off
enable_dl = Off
disable_functions = system, show_source, symlink, exec, dl, shell_exec, passthru, phpinfo, escapeshellarg, escapeshellcmd


Step 7 :

Final step is to restart Apache server.

sudo /etc/init.d/apache2 restart

Step 8 :

sudo nano /etc/sysctl.conf
Uncomment the following line and make it look like this.

#Enable TCP SYN Cookie Protection
net.ipv4.tcp_syncookies = 1

Make the change active.

sudo /sbin/sysctl -p


That's all. See you!