Create a super secure LAMP server under Linux

xiaoxiao2021-03-06  81

Create a super-secure LAMP server under Linux (from phpx.com)

Before editing: This article introduces the method of reinforcing Apache PHP MySQL under Linux, by carefully reading this article, you can quickly grasp the security configuration Apache, PHP, and MySQL, and the frontier technology of Chroot Relying on these knowledge, you can completely allow your WWW server to stand in an endless SQL injection (SQL Injection) and CROSS Site script.

Several vulnerabilities from the moving network were black, and the script attacked the boiling boiling, and it was visible that it finally showed his importance in the cyber attack. Due to the unintentional or intention of the program developers, the scripts written by Perl, PHP, ASP, etc., such as erroneous, and lightly cause the leak path, which causes the entire server to be captured and even spread throughout the network. Don't we read the scripts used by the scripts used, seriously analyze? I believe that everyone has this skill, even if there is such a skill, there will be so many time and energy.

You may ask: "I want to use online free programs, and I don't want to be hit hard. Is there a two full way?"

For Windows Host, we can use IiSlockDown, Secureiis.

For the * NIX host, two programs are put forward, one is to install the MOD-Security module for Apache, and another way is to place the LAMP in a chroot jail environment. Of course, the strongest is still combined with two programs :)

Below, let us share these two programs together

Prerequisites: We only need to have ordinary Linux operation experience, including VI usage, etc.

First of all, let's figure out a few concepts first.

What is Debian: A completely free Linux operating system, his most made my favorite is his APT package management tool, let you install or upgrade the software worry-free! If you are a CERNET user, I recommend you to the electronic capital http://debian.ustc.edu.cn or my website http://secu.zzu.edu.cn Upgrade, CHINANET users can at http: // mirror. GennkBone.org upgrade

What is lamp: is the abbreviation of Linux Apache MySQL PHP, almost the strongest standing station combination

What is chroot: is the abbreviation of Change root, which is to limit a process daemon in a particular root environment. This is almost close to any file or space that is almost close to this root, this root is almost close to any file or space that is almost close to this root. The directory (that is, the jail we said below) contains all the files required to execute the process daemon. After you configure it correctly, most intruders are impossible to jump out of Jail and come out of the file. This way we can maximize the invaders to protect themselves.

Software involved in this article

Makejail http://www.floc.net/makejail/

It is a software that automatically puts the program required by establishing Jail into Jail, writing using Python, he has the version of Debian and OpenBSD.

Zend Performance Suit http://www.zend.com

A set of PHP accelerated in Zend, including a code optimizer (Optimizer) and an accelerator (Accelerator)

There is also a cache function, so, make it, the PHP program runs together! You can apply for a 30-day trial version. If you feel easy to use, buy it :)

MOD-security http://www.modsecurity.org/

He is a module of Apache, he has functions such as filtration, log audit, can prevent SQL INJECTION, cross-station script attack, very good module OK, hands-on

We assume that we have a debian woody in hand, and the APT source has been properly set.

If you don't say it, you will be upgraded to Debian Sarge, which is the Testing version. I think this version is still good because his software is relatively new, and there is security support, the main version of the software list contains Makejail this software.

First SU to the root upgrade system and install Apache, PHP, MySQL, GD

Update the APT source, I am in education network, so use the APT source of the Chinese University Debian.ustc.edu.cn is very fast

[root @ Debian /] APT-GET UPDATE (Figure Update.jpg)

Update all packages

[root @ Debian /] APT-GET DIST-UPGRADE (Figure UPGRADE.JPG)

[root @ Debian /] APT-GET Install Apache PHP4 PHP4-GD2 PHP4-MySQL MYSQL-Server MySQL-Client

And add extension = gd.so and extension = mysql.so to pHP.ini

Your system has already installed apache-1.3.27, php-4.1.2, mysql-4.0.13

Such a basic LAMP is coming, simple.

Add a system user, this user is our waiting for Chroot.

[root @ Debian /] adduser - HOME / chroot / apache --shell / dev / null - no-create-home --system - country chrapax

Then we edit the httpd.conf file and make some modifications, delete the extra Apache modules and activate the PHP module.

[root @ Debian /] vi /etc/apache/httpd.conf

Note All modules except MOD_ACCESS, MOD_AUTH, MOD_DIR, MOD_LOG_CONFIG, MOD_MIME, MOD_ALIAS

Remove the note loadModule PHP4_Module /usR/LIB/apache/1.3/libphp4.so to support PHP (as shown apache_mod.jpg)

Set serveadmin fatb@zzu.edu.cn

Set servername secu.zzu.edu.cn

Put

The following Options Indexes Includedes Followsymlinks MultiViews is removed, which avoids being indexed by others.

Create users and groups into Chrapax

User Chrapax

GROUP Chrapax

In the following, INDEX.PHP is as follows

DirectoryIndex index.php index.html index.htm index.shtml index.cgi

By default use Chinese character set

AdddefaultCharset GB2312

Adding a wrong weight, so when the following error occurs, the user will be reset to the page you specified.

ErrorDocument 404 http://secu.zzu.edu.cn/index.php

ErrorDocument 402 http://secu.zzu.edu.cn/index.php

ErrorDocument 403 http://secu.zzu.edu.cn/index.php

ErrorDocument 500 http://secu.zzu.edu.cn/index.php

Turn off Signature

Serversignature Off If Signature is open, some error messages will appear when someone accesses a page that is banned or does not exist.

Such information is not good, remove him (see Figure 403.jpg)

If you don't need CGI support, delete

Scriptalias / CGI-BIN / / USR / LIB / CGI-BIN /

ALLOWOVERRIDE NONE

Options execci -multiviews

ORDER ALOW, DENY

ALLOW FROM ALL

The comment of this line is removed because we need PHP support

Put AddType Application / X-httpd-PHP .php

Finally, take extra Alias, Directory, Location, save exit

OK, Apache is configured, I prefer a clean configuration file, the following command can remove httpd.conf # headed

[root @ Debian /] mv httpd.conf httpd.conf.bak

[root @ Debian /] grep -v '#' httpd.conf.bak> httpd.conf

So far, the Apache profile editing is completed.

Then we start reinforcing PHP, we open php.ini

[root @ Debian /] vi /etc/php4/apache/php.ini

First open the security mode, open his advantage is that the PHP file can only access the owner and the PHP file all the same files, even in the Chroot environment, it is impossible to access different files in Jail, similar to the back door like PHP shell. I have no use of Wu, PHPSHELL is a popular PHP back door, he can execute system commands, just like his name, and shell is very close (as shown in PHPSHELL.JPG)

SAFE_MODE = ON

If the PHP program does not indicate that register_global, it is best to set the register_globals to OFF, which avoids many security issues.

For example, we have such a PHP file fragment called Test.php

// front code

IF ($ authorised) {

/ / Execute some protected actions

}

// The rest of the code

}

?>

If register_globle is open, the intruder can bypass the verification by submitting such a request.

http://www.test.com/test.php?authorised=1

Of course, if you have to use register_globle, we can also use mod-security to limit it.

Open_BASEDIR = / VAR / WWW /

The above setting limits the directory range of fopen (), file () and other functions, avoiding intruders illegally reading files, must add "/" after / var / wwww, otherwise / var / wwww Document can also be accessed

It is forbidden to use PHPINFO and GET_CFG_VAR functions, which avoids leak service information.

Disable_functions = phpinfo, get_cfg_var

If we use the PHPINFO function that is banned, we can see such an error.

Warning: phpinfo () HAS BEEN DISABED for Security Reasons In /Var/www/info.php on line 1

Set the PHP program error log so that we can know the program problem very clearly.

Error_Reporting = E_ALL

Log_ERRORS = ON

ERROR_LOG = /VAR/LOG/PHP_ERR.LOG The default Display_Error is open, we have opened him before jail is not good, maybe the error message can give us a little prompt, but remember to close this option after completion, because he shows Some error messages may be exposed to your physical path.

In this process, what is the most important thing to pay is to use root as the primary owner of the PHP program, otherwise the PHP program can access his home owner, that is, all the files of root, so that it is completely lost SAFE_MODE.

Do not open the remote address, remember the vulnerability of the recent PHP INCLUDE? That is, in a PHP program, the invader can use this control server to perform remote PHP programs locally, such as PHPSHELL, so we close this

Allow_url_fopen = off

OK, save exit

As soon as possible, the security optimization of PHP is basically completed, and we started to "do your hands" for MySQL "

Using the APT Mysql by default, it has been banned from network connection MySQL. We can see from his profile my.cnf, but you have to pay attention to the RPM, FreeBSD ports installation, Skip-networking is a comment Falling, that is, listening to 3306 port, if Mysql has a problem, others can have the opportunity to use

[root @ Debian /] grep net /etc/mysql/my.cnf

# The skip-networkin Option will no longer be set via debconf menu.

# You Have to Manually Change It if you want networking i.e. The Server

SKIP-NETWORKING

In this regard, Debian is doing, but the system-loaded mysqld is dynamic link under Debian and FreeBSD, and the RPM installation of Redhat is static, we can view the following command.

[root @ Debian ~] file` What mysqld`

/ usr / sbin / mysqld: ELF 32-BIT LSB EXECUTABLE, Intel 80386, Version 1 (Sysv), For GNU / Linux 2.2.0, DynamicalLinked (Uses Shared Libs), Stripped

We can see the words "DynamicalLinked", which is more troublesome when Chroot MySQL, because there is a lot of shared libraries, but in Debian we have makejail :), etc., we can see his power.

Then we modify the things in the mysql database, but no matter what, we must first give mysql to set a password and modify the administrator username (default is root), but must remember, no matter how to change the password, there will be recorded, If you have changed via mysqladmin, the history of the shell will be changed. If you log in to MySQL, modify it, then you will be recorded in ~ / .mysql_history, so we must handle these two historical files, we deleted them, then / dev / null is a soft connection to solve the problem.

[root @ Debian /] CD ~

[root @ Debian ~] LL

Total 13K

-rw ------- 1 root root 1.8k Sep 28 21:05 .bash_history

-rw ------- 1 root root 14 Sep 29 09:29 .mysql_history We can see that all of these two files have been recorded, let's handle them

[root @ Debian ~] rm .bash_history

[root @ Debian ~] rm .mysql_history

[root @ Debian ~] ln -s / dev / null .bash_history

[root @ Debian ~] ln -s / dev / null .mysql_history

Let's take a look

[root @ Debian ~] [root @ debian ~] ll

Total 10K

LRWXRWXRWX 1 root root 9 Sep 29 09:29 .bash_history -> / dev / null

LRWXRWXRWX 1 root root 9 Sep 29 09:29 .MYSQL_HISTORY -> / dev / null

Now you can set your password.

[root @ Debian ~] mysqladmin -u root password mypasswd

This way, we will have access to the mysql database through the password of "mypasswd".

Then we delete extra databases and remove anonymous accounts

[root @ Debian ~] mysql -u root -p

ENTER Password: XXXXXX

mysql> DROP DATABASE TEST;

Mysql> USE Mysql;

Mysql> delete from db;

Mysql> delete from user where not (host = "localhost" and user = "root");

mysql> flush privileges;

Then modify the default administrator account root for you, I changed to FATB

MySQL> Update User Set User = "FATB" Where user = "root";

mysql> flush privileges;

We have to access the mysql database through the FATB account.

[root @ Debian ~] mysql -u root -p

ENTER Password:

Error 1045: Access Denied for User: 'root @ localhost' (Using Password: YES)

[root @ Debian ~] mysql -u fatb -p

ENTER Password:

Welcome to the mysql monitor. Commands end with; or g.

Your MySQL Connection ID IS 14 TO Server Version: 4.0.13-log

Here, the security settings of MySQL are basically completed.

Now we installed mod-security, Debian is equally simple, and automatically adds the module to httpd.conf

[root @ Debian /] APT-GET Install libapache-mod-all @Security

The default this module is not activated, edit the httpd.conf file and remove the comment below.

LoadModule Security_Module /usr/lib/apache/1.3/mod_security.so

Then in the end of httpd.conf

# Open or close the filter engine

SECFILTERENGINE ON

# Set the default action

SECFILTERDEFAULTACTION "DENY, LOG, STATUS: 404"

# Turn the settings to the word directory secfilterinheritance off

# Detect if the URL encoding is correct

SecfilterCheckurlencoding on

# Detect the length of the content to avoid a stack of overflow attacks

SECFILTERFORCEBYTERANGE 32 126

# Location and name of the log file

SECAUDITLOG logs / audit_log

# debug settings

SECFILTERDEBUGLOG LOGS / MODSEC_DEBUG_LOG

SECFILTERDebuglevel 0

# Detect POST data

Secfilterscanpost On

# When you match the SH, you will reordfor from a special page, so that the attacker knows difficult

Secfilter sh redirect: http://secu.zzu.edu.cn/hack/fu.htm

# Only Check The Body of The Post Request

# Filter some sensitive things, we use * is to use /etc/./passwd to use /etc/./passwd to bypass detection

SECFILTER / ETC / * Passwd

SECFILTER / BIN / * SH

# Prevent Double Dot attack, that is, http://www.test.com/openfile.php? Path = / .. / .. / .., although this vulnerability seems to be mentally, many websites have, such as CERNET a picture station :)

SECFILTER "../"

# Prevent cross-site script (CSS) attack

Secfilter "<(|) * script"

SECFILTER "<(. |) >"

# Prevent SQL Injection Attack

SECFILTER "Delete (Space |) from"

SECFILTER "INSERT (Space |) INTO"

Secfilter "SELECT" SELECT FROM "

Secfilter "Union (space |) from"

# The following is to limit the upload.php file that can only be used to upload a picture of JPEG.BMP and GIF

SECFILTERINHERITANCE OFF

Secfilterselective Post_Payload "! Image / (JPEG | BMP | GIF)"

With mod-security, you can improve your website security, you can find more settings in the manual in his belt, with a more detailed rule included in the CD

(MOD-Security.Rule.txt)

Then we installed Zend Performance Suit, when he was installed, he asked the users you used, remember to write Chrapax instead of www-data

ORDER ALOW, DENY

ALLOW from 211.43.125.63 (your IP)

Deny from all

Options all

The following weights will be played, Chroot is a very important step, but maybe still a simple step, first copy a few Python written to / etc / makejail

[root @ Debian / etc / makejail] cp /usr/share/doc/makejail/examples/apache.py ./

Then edit the Apache.py file to add a modified information

Users = ["chrapax"]

Groups = ["chrapax"]

Packages = ["Apache", "Apache-Common", "PHP4", "PHP4-GD", "MySQL-Common", "Libapache-Mod-Security"] then execute the makejail command

[root @ Debian / etc / makejail] makejail apache.py

After completing, we have to make a soft connection and separate Chrapax from passwd and group file.

[root @ Debian / etc / makejail] ln -s / var / chroot / apache / apache

[root @ Debian / etc / makejail] grep chrapax / etc / passwd> / apache / etc / passwd

[root @ Debian / etc / makejail] GREP Chrapax / etc / group> / apache / etc / group

[root @ Debian / etc / makejail] cp /etc/mime.types / apache / etc /

Then build a file called Chrapax in /etc/init.d and let him execry, see the CHRAPAX in the CD.

[root @ Debian / etc / makejail] cat> /etc/init.d/chrapax

[root @ Debian / etc / makejail] chmod x /etc/init.d/chrapax

Then use the rcconf command to activate when the system is started (Figure Rcconf.bmp)

[root @ Debian / etc / makejail] rcconf

Start Chroot Apache

[root @ Debian /etc/makejail]/etc/init.d/chrapax start

Test if PHP and MySQL connections have problems

[root @ debian / etc / makejail] cat> /apache/var/www/mysql.php

$ conn = mysql_connect ("localhost", "fatb", "urpassword")

OR DIE;

Print "PHP Can Work with MySQL Now";

MySQL_Close ($ conn);

PHPINFO ();

?>

Result Browser Returns

WARNING: Can't connect to local mysql server through socket '/var/run/mysqld/mysqld.sock' (2) in /var/www/mysql.php on line 2

But we can see that there is a mysqld.sock file in / var / run / mysqld /, is actually because we already chroot apache, he can only visit the things in Apache root jail, that is, / var / chroot / apache Things, and mysqld.sock is obvious outside Jail, so it can't be connected, of course, it is normal, and the method of solving this problem is also very simple. It is a hard connection.

[root @ Debian / apache / var / run / mysqld] ln /var/run/mysqld/mysqld.sock mysqld.sock

Take a look at Mysql.php, it's ok (as shown in Figure ok.bmp)

It is very troublesome to do hard connectivity, and when accessing mysqld, the Apache has a good resource, and the solution is to add bind-address 127.0.0.1 in MySQLD configuration files. This is connected through the TCP connection instead of the Socket. One, the entire LAMP server is much safe, even if the unsafe of the PHP program is unsafe or apache, what is PHP, I want to invade and jump out root jail is still very difficult.

reference:

Security Apache Step by STEP

Security PHP Step by STEP

Security MySQL Step by Step

(I don't know why I don't know these three articles at home, at www.securityfosuc.com, I am interested in seeing)

MOD-Security Manual

SAN PHP security configuration

http://www.xfocus.net/articles/200111/304.html

Version Information

V1@2003.11 initial version

V2@2004.1 Apache consumes a large number of resources when adding Mysql after PHP program

Fix ustc.edu.cn is an electronic department rather than China University :)

V3@2004.9 Addable_url_fopen = OFF

Add MOD-Security to SQL Injection Filtering

FATB (FATB_AT_SECURITY.ZZ.ha.cn)

Bun @ 郑 州 University Network Safety Park http://secu.zzu.edu.cn

Posted at 17:31:07 on 09/29/04 by

Sadly - category:

Linux article

转载请注明原文地址:https://www.9cbs.com/read-107621.html

New Post(0)