Daniel's Blog
15 Jun/11 0

12 measures to a Linux Apache MySQL PHP web server root LAMP secure


The frequency of hacking has increased dramatically in recent months. Especially a lot of data to be picked up by hacks on web servers. Even the Sony PSN hack took advantage of an unpatched vulnerability in Apache Web Server. So here I am raising measures that the server can own a bit safer against attacks from outside. Of course, this also does not provide 100% protection, but it is better to make the bad guys the game a little more difficult. Some of the measures require only a minimal installation and maintenance. Others need a lot of time and knowledge of PHP to catch. You should always pay attention to the cost-benefit ratio in the selection of security measures. It makes no sense to protect a small, private site like the Federal Reserve Bank. However, few specific changes to the system already has a large mean more security. And that you should treat even before it's too late ....

All tips and Codesnips refer to a current Debian box.

First The firewall - prohibit Once everything

Most Linux distributions in their default installations open any ports to the outside that are not absolutely necessary. This situation can change quickly, however, even when the server
playing around and trying things. Suddenly, even the media server is listening on the Internet or the database
accepts connections from the Internet. Therefore, it is not wrong to discipline themselves and put on a very restrictive firewall that basically prohibits Once all connections from the outside and allows only (self-) selected compounds. Fortunately, this is done quickly with iptables. In this way one can no longer provide services to make accessible to the world that have no business there. Unfortunately, you pay a little comfort - the firewall must be adjusted every time when you wish to offer new services. Nevertheless, the effort is small and the benefits large.

 # / Bin / bash

 # Delete existing tables
 iptables-F

 # Prohibit all incoming connections
 iptables-P INPUT DROP
 iptables-P FORWARD DROP

 # Allow all outgoing
 iptables-P OUTPUT ACCEPT

 # Allow SSH
 iptables-A INPUT-j ACCEPT-p tcp - dport 22 

 # Allow HTTP
 iptables-A INPUT-j ACCEPT-p tcp - dport 80 

 # Further service (UDP) allow, for example, game server
 iptables-A INPUT-j ACCEPT-p tcp - dport 4534 

 # Allow everything from localhost.  (To allow unimpeded access to the server itself, its services,
 # For example, PHP on the local database
 iptables-A INPUT-s 127.0.0.1-j ACCEPT

 # Already established connections will be accepted at each port
 # (Required for some daemons)
 iptables-A INPUT-m state - state ESTABLISHED, RELATED-j ACCEPT

This little backbone we can simply continue to expand and add their own services. When working on the firewall, you should always make provisions for the case that locks out yourself. Especially for remote servers to which you do not have physical access, it is very annoying to lose by a failed firewall rule their own access. In order to avoid this problem out of the way, you can leave work to start at the firewall temporarily just a cron job that resets the firewall every few minutes or the server restarts. Are the rules later tested and loved, the cronjob will be deactivated and the new rules remain permanently active.

To find out which services are just around listening to your own server, you can use netstat:

 # For TCP sockets:
 netstat-lpn | grep tcp

 # Similarly for UDP:
 netstat-lpn | grep udp

To test if the firewall really works, you can port scan your own server from another computer. Everything worked out and it should result in only the even ports that are open:

 # For TCP:
 nmap-p1-65 535 meinserver.de

 # For UDP:
 nmap-sU-p1-65 535 meinserver.de

Second SSH logins ban

On its own root server you have full SSH access. This is quite handy, as you can from any SSH client to the server times just to work on it. The downside of this is that the course can anyone who unfortunately is somehow taken over their own passwords. It's much safer to allow SSH logins only with a valid key file. Therefore, the public key of the client to the server and copied interactive logins are disabled by entering a password.

 # On the client, create a public key
 # If specified when generating a password, one needs to
 # Log file later, the key AND the password.  Otherwise
 # Only needed the key.

 ssh-keygen-t rsa

 # Copy the generated key to the server

 ssh-copy-id-i ~ / .ssh / id_rsa.pub root@meinserver.de

 # Now adjust sshd_config on the server / etc / ssh /
 .
 .
 PasswordAuthentication no
 .
 .

 # Then start again RearBBpos
 / Etc / init.d / ssh restart

Even here one should take precautions to not shut out even if something does not work.
The public key on a USB stick with the corresponding password in your head makes it much harder for bad guys to get a shell.

Third SSH Bruteforcing prevent denyhosts

If advice is not practical 2 and you do not give up the convenience of password-based logins want, you can at least prevent the automated password rates of attackers on the server. A lot of bots on the internet all day looking to do nothing more than to SSH servers and try out in your various passwords. With a reasonably secure password is not a big problem, but there is a better feeling, not even if that's possible. In addition, it also protects its users, if there are on the server and user accounts. Here, you can not rely on users to use secure passwords. denyhosts constantly reviewed and ssh logins on the user locks for a while who have entered their password incorrectly repeated. The IP's of users temporarily go into / etc / hosts.deny, so that they no longer have access to is possible. This SSH Bruteforcing to a very lengthy and not very promising task.

 apt-get install denyhosts

 # Denyhosts works right after installation.  It can be
 # In the file / etc / denyhosts.conf fine tune

4th Blacklists used to block out known problem IPs

In various Internet blacklists are maintained, which list a large number of criminal / chopped / spammy / fraudulent servers. These IP lists can be entered directly into the firewall, so that from this is known not to trusted computers can not connect at all to its own server. So you can reduce the amount of spam on their own server dramatically and one or the other script kiddie lock out, because his Russian proxy suddenly stops working. How to do that I have been in another blog article described the example of the blacklist of Infiltrated.net.

5th Do not use FTP to work on server

FTP is a relic of better times when the Internet was a small village still trusted. Many administrators of websites still use FTP to transfer files to the server or to work on their own website. Unfortunately, this is very uncertain, since FTP transmits all data unsecured. Passwords and data can be read without any problems at each hop between servers and clients. Much safer to go with sshfs. Allows you to mount a directory via ssh on the remote server's local file system. You can then work on the server as if he was on the local computer. All file access to files on the server are completely transparent, so you can open with the local graphics program to edit an image on the server directly, and then save. More comfort and safety without much effort.

 # Install sshfs
 apt-get install sshfs

 # Create mountpoint on the local file system
 mkdir / media / myserver

 # Server to the local file system mount
 sshfs www-data@mein-server.de :/ var / www / media / myserver

 # Now the directory is / var / www on my local server under / media / myserver available

6th Install Updates

A super secure system will not help if the system itself is flawed and a known vulnerability can be exploited. In most cases, these vulnerabilities closed quickly, but often forgotten admin regular updates of the system to make. Whether you should enable automatic updates on Linux servers or not is a contentious issue. Some would never do, because it naturally with a lot of bad luck may be that the updates make the system unusable. This happened to me in over 10 years of work on Debian systems, but never and I appreciate the benefits of timely and regular updates, a much higher, as the resulting risk.

 # This line in the / etc / crontab, updates the system clock every day at 6 am
 0 6 *** root apt-get update && apt-get-y upgrade

These quick-and-dirty method worked for me so far always good. I recently read that in the Debian repository and the package unattended-upgrades exists that solves the problem probably more elegant, but I have not been tested.

Even with these vollautomtischen system updates it is not completely off the hook. If a kernel update has been delivered, you have to boot the system yet again by hand, otherwise the changes will not be active.

If we use third-party PHP code on the server, such as an open source CMS or a forum, it is of course absolutely necessary and this code with new versions up to date. Since Debian does not update its changes to those applications in the rules covering this manual labor is required. The best way to read your mailing lists with the corresponding products in order to be always up to date.

7th PHP with open_basedir imprison

Many hacks based on the fact that a vulnerability in the PHP code is used to access files in the file system access that do not belong to the site, but the system itself is why you should lock up PHP so that it read only in specifically designated directories and write allowed. For this, the php.ini the open_basedir configuration option. PHP has the option to put only allowed access to the directories there. Files such as / etc / passwd are out of reach. Hosting multiple websites on one server you should set open_basedir in each virtual host configuration on each side.

 # Global php.ini via:
 # / Etc/php5/apache2/php.ini
 open_basedir = / var / www / :/ tmp /

 # Per Site in the VirtualHost config:
 php_value open_basedir / var / www / site / :/ tmp /

It is important to consider whether all sites have been added to the scripts usually need to have access, otherwise it may be that you are disabled and legitimate functions of the PHP application.

8th Create your own websites for MySQL users

Use your own PHP-MySQL application, you should absolutely create for Apllikation own MySQL user and under no circumstances use the MySQL root user requests. You should also restrict the user's rights so far that really only operations are allowed, which requires the PHP script. CREATE TABLE and DROP TABLE are as common in SQL injections and used in most PHP applications never required. It hosts multiple websites with multiple databases on a server, you should create your own databases for all users. Thus, after a successful attack, an attacker only has access to one of the databases and not directly at all. If you do not want to try the command line to manage the MySQL user accounts, user management functions also quite easy with phpMyAdmin under the tab "rights".

9th PHP error messages off

PHP error messages an attacker can reveal a lot about your own server: directory structures, database structures, configuration errors, etc. They also look for the user very unprofessional. For this reason they should be on a live web server, always switch off because you're just going to continue to see in the logs.

 # Global php.ini via:
 # / Etc/php5/apache2/php.ini
 display_errors = Off

 # Per Site in the VirtualHost config:
 php_flag display_errors Off

 # Error messages read it anyway:
 cat / var/log/apache2/error.log | grep php

10th Target for SQL injection limit with ModSecurity

SQL injections are the most frequently used method of attack on web server. Accessed directly through the web application and it meets a browser to perform them. Here are transmitted by the user variables built SQL queries sent to the privileges of the database user all of its database at will delete read or edit them. A real genuine protection against SQL injection exists only if the PHP code was written the site in relation to these attacks. Each variable from user input, which could get into an SQL query, it must be tested and escaped. PHP offers the function real_mysql_escape_string ().

If you are not sure if the code is clean, can mod_security for Apache help ward off a large amount of these attacks anyway. mod_security constant review all requests to the Web server and responds to pre-pattern which many SQL injection attacks can be blocked. Unfortunately, only works well with mod_security manual effort. Often after a fresh install mod_security blocks also required (regular) functions of your PHP code, so that one has no other choice, as the complete application to test out the installation again. Only then does one find out whether mod_security might not even want blocking functions. If so, then the filter list to be adjusted to disappear so that the false positives.

The configuration of mod_security is somewhat complicated and is beyond the scope of this article, but there are tons of good tutorials on the Internet mod_security.

11th ID check - Apache does not know who he is
This is not really effective method against a hack, it makes automated scripts that are looking for server versions, but slightly heavier. Usually the Apache points to pages with error messages (eg 404 Not Found) its server signature.

 Apache/2.2.16 (Unix) Server at www.daniel-ritter.de Port 80

It eliminates any potential aggressor will receive at least once before about the eigesetzten Web server and the version level. The signature server is turned off quickly:

 # / Etc/apache2/conf.d/security
 ServerSignature Off

12th Do not use disable apache modules

By default, Apache has loaded some modules that are almost never needed. On Debian you can find the loaded modules
as a soft link in / etc/apache2/mods-enabled.

Can be removed almost always:

mod_cgi

Used to run CGI scripts. This technique dates back to the dawn of the Web and was the forefather of modern scripting languages ​​to allow for dynamic websites. mod_cgi is unnecessary for 99% of PHP sites and with a faulty Apache config is a potential security hole

 a2dismod cgi

mod_status

Allows browsers to read status information on the Apache. It is almost never used for "normal" sites, provides status information about the attackers but Apache.

 a2dismod status

mod_autoindex

mod_autoindex ensures that directories can be listed on the web server, if there is not a valid index page in the appropriate directory. If this functionality is not desired, you should disable it, since it whole directory trees on the web server can be externally visible.

 a2dismod autoindex
Comments (0) Trackbacks (1)

    Leave a comment

    * Copy this password:

    * Type or paste password here:

    484 Spam Comments Blocked so far by Spam Free Wordpress

    Please copy the string to the field below ycH3QP: