Reprinted. Please keep the author information.
Steamed Stuffed Bun @ Zhengzhou University Network Security Park
Http://secu.zzu.edu.cn
This article has already been contributed to the article of the black line of defense in the 11th issue of the 03 years. It provides a detailed description of the basics. If you are interested, click it :)
I would like to share this document with the leaders and teachers of Zhengzhou University's network center.
I wish you good health, smooth work, successful academic achievements, and a new year!
Before Compilation: This article describes how to reinforce Apache + PHP + MySql in Linux. By carefully reading this article, you can quickly master the Security Configuration of Apache, PHP, and all aspects of MySQL, as well as the cutting-edge and powerful technology of chroot, relying on this knowledge, can make your WWW server in an endless stream of SQL injection (SQL injection) and cross-site scripting (CSS ).
From several vulnerabilities on the Internet to the hacking of the website of the lone swordsman, script attacks have stirred up. As a result, it has finally shown its importance in network attacks. Due to unintentional or unintentional carelessness of program developers, errors such as one or more may occur in scripts written with Perl, PHP, and ASP, which may lead to path leakage, heavy Load causes the entire server to be attacked or even spread to the entire network. Do we have to read the script n times and analyze it carefully? I believe that not everyone has the same level of skill, and even such skill will not waste so much time and energy.
You may ask: "I want to use free online programs, and I don't want to be hit. Isn't there a two-way solution ?"
For Windows hosts, we can use iislockdown, secureiis, and so on.
Two solutions are proposed for * nix hosts. One is to install the mod-security module for Apache, and the other is to place lamp in a chroot jail environment. Of course, the strongest one is to combine the two solutions :)
Next, let's share the two solutions.
Prerequisites: we only need to have normal LINUX operation experience, including VI usage.
First, let's clarify several concepts.
What is Debian? A completely free Linux operating system. What I like most is his apt package management tool, which makes it easy for you to install or upgrade the software! If you are a CERNET user, we recommend you go to the E-tech http://debian.ustc.edu.cn or my website http://secu.zzu.edu.cn upgrade, Chinanet users can upgrade in http://mirror.gennkbone.org
What is lamp: it is the abbreviation of Linux Apache MySQL PHP, which is almost the strongest combination of racks
What is chroot: the abbreviation of change root is to restrict a process daemon to a specific root environment, the chroot program is almost unable to access any files or space that exceeds the root account. This root directory (jail) contains all the files required to run the process daemon. After you configure the files correctly, most intruders cannot jump out of jail and access the files outside. In this way, we can restrict intruders to the maximum extent to protect themselves.
Software involved in this article
Makejail http://www.floc.net/makejail/
Is a software that automatically puts the program required to build jail into jail. It is written in Python and has versions of Debian and OpenBSD.
Zend performance suit http://www.zend.com
Zend developed a set of things to accelerate PHP, including a code optimizer and an accelerator)
And the cache function. With it, the PHP program runs like flying! You can apply for a 30-day trial version. If you think it is easy to use, buy it :)
Mod-security http://www.modsecurity.org/
He is a module of Apache, and has functions such as request filtering and log auditing to prevent SQL injection and cross-site scripting attacks. This is a good module.
OK
Assume that we have a Debian Woody installed on our hands and the APT source has been correctly set.
Upgrade Debian Sarge, that is, testing. I think this version is good, because its software is newer and has security support, the main version of the software list contains the makejail Software
First, Su to root to upgrade the system and install Apache, PHP, MySQL, and GD.
I updated the apt source on CERNET, so I used the apt source debian.ustc.edu.cn of HKUST at a very fast speed.
[Root @ Debian/] apt-Get update (update.jpg)
Update all software packages
[Root @ Debian/] apt-Get dist-upgrade(upgrade.jpg)
[Root @ Debian/] apt-Get install Apache PhP4 php4-gd2 php4-mysql mysql-server mysql-Client
Add extension = Gd. So and extension = mysql. So to PhP. ini.
Your system has been installed with Apache-1.3.27, php-4.1.2, mysql-4.0.13
This is a basic lamp.
Add another system user. This user will be used by chroot.
[Root @ Debian/] adduser -- home/chroot/Apache -- shell/dev/null -- no-create-home -- System -- group chrapax
Next, edit the httpd. conf file and make some modifications to delete the redundant Apache module and activate the PHP module.
[Root @ Debian/] vi/etc/Apache/httpd. conf
Comment out all modules except mod_access, mod_auth, mod_dir, mod_log_config, mod_mime, and mod_alias.
Remove the annotation loadmodule php4_module/usr/lib/Apache/1.3/libphp4.so to support PHP (apache_mod.jpg)
Set serveradmin fatb@zzu.edu.cn
Set servername secu.zzu.edu.cn
Set
The options indexes des followsymlinks Multiviews below are removed to avoid being indexed by others.
Change users and groups to chrapax
User chrapax
Group chrapax
Add index. php below:
Directoryindex index. php index.html index.htm index.shtml index. cgi
The Chinese character set is used by default.
Adddefacharcharset gb2312
Add error redirection, so that when the following error occurs, the user will be redirected 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
Disable Signature
Serversignature off
If signature is enabled, when someone accesses a disabled or nonexistent page, some error messages may occur.
This information is not good. Remove it (403.jpg)
If you do not need CGI support, delete it.
ScriptAlias/cgi-bin // usr/lib/cgi-bin/
AllowOverride none
Options execcgi-Multiviews
Order allow, deny
Allow from all
This line of comment is removed because we need PHP support.
Add addtype application/X-httpd-PHP. php
Finally, remove the redundant alias, directory, and location, save and exit.
OK. Apache configuration is complete. I prefer a clean configuration file. The following command can remove the # hitting line in httpd. conf.
[Root @ Debian/] MV httpd. conf httpd. conf. Bak
[Root @ Debian/] grep-V '# 'httpd. conf. Bak> httpd. conf
So far, the Apache configuration file has been edited
Then we start to reinforce PHP and open PHP. ini.
[Root @ Debian/] vi/etc/PhP4/Apache/PHP. ini
First, open the security mode. The advantage of opening the PHP file is that the PHP file can only access all the same files as the PHP file. Even in the chroot environment, it cannot access files with different masters in jail, similar to PhP example)
Safe_mode = on
If the PHP program does not specify that register_globals is required, set register_globals to off to avoid many security problems.
For example, we have a PHP file snippet named test. php.
// Previous Code
If ($ authorised ){
// Perform some protected actions
}
// Other code
}
?>
If register_globle is enabled, intruders can submit such a request to bypass verification.
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 later.
Open_basedir =/var/www/
The above settings limit the directory range that can be operated by functions such as fopen () and file () to avoid illegal file reading by intruders, you must add "/" to/var/WWW; otherwise, files under/var/wwww can also be accessed.
Disable the phpinfo and get_cfg_var functions to avoid service information leakage.
Disable_functions = phpinfo, get_assist_var
If we use the banned phpinfo function, we can see this error.
Warning: phpinfo () has been disabled for security reasons in/var/www/info. php on line 1
Set the PHP program error log so that we can clearly understand the program problem.
Error_reporting = e_all
Log_errors = on
Error_log =/var/log/php_err.log
Display_error is enabled by default. We can enable it before jail is ready. You may be prompted for the error message, but remember to disable this option after completion, because some of the error information displayed by him may expose your physical path.
In this process, the most important thing to note is that you cannot use root as the owner of the PHP program. Otherwise, the PHP program will be able to access all the files of the root program at will, in this way, the meaning of safe_mode is completely lost.
Disable remote address opening. Do you remember the latest vulnerability in PHP Include? If a variable is included in a PHP program, the attacker can use this control server to execute a remote php program, such as phpshell, locally, so we can close this
Allow_url_fopen = off
OK, save and exit
So far, the security Optimization for PHP has basically been completed. Let's start to give MySQL "Hands and feet ".
MySQL installed with APT In Debian has disabled connection to MySQL from the network by default. We can use its configuration file my. it can be seen in CNF, but note that the RedHat RPM, FreeBSD ports installation, and skip-networking are commented out, that is, listening to port 3306, if something goes wrong with MySQL, someone else can take advantage of it.
[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 does a good job, but the mysqld installed in the Debian and FreeBSD systems is dynamically linked, and the RedHat RPM is static. We can view it through the following command.
[Root @ Debian ~] File 'which mysqld'
/Usr/sbin/mysqld: Elf 32-bit LSB executable, Intel 80386, Version 1 (sysv), for GNU/Linux 2.2.0, dynamically linked (uses SHARED libs), stripped
We can see the words "dynamically linked", which makes chroot MySQL a lot of trouble because many shared libraries need to be copied, however, In Debian, We have makejail :) and we will be able to see its power.
Next, let's modify the items in the MySQL database. However, we have to first set a password for MySQL and change the administrator username (root by default), but remember, no matter how you change the password, there will be records. If you use mysqladmin to modify the password, there will be shell history records. If you log on to MySQL and then modify the password ~ /. Mysql_history records, so we must process these two history files. We have deleted them, and then made a soft connection from/dev/null to solve the problem.
[Root @ Debian/] CD ~
[Root @ Debian ~] Ll
Total 13 K
-RW ------- 1 Root 1.8 K Sep 28. bash_history
-RW ------- 1 Root 14 Sep 29. mysql_history
We can see that there are records in these two files. Next we will process 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 10 K
Lrwxrwxrwx 1 Root 9 Sep 29 09:29. bash_history->/dev/null
Lrwxrwxrwx 1 Root 9 Sep 29 09:29. mysql_history->/dev/null
Now you can safely set the password.
[Root @ Debian ~] Mysqladmin-u Root Password mypasswd
In this way, the root user needs to access the MySQL database using the password "mypasswd ".
Then we delete unnecessary 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;
Modify the default Administrator account root as your favorite. Change it to fatb here.
Mysql> Update user set user = "fatb" where user = "root ";
Mysql> flush privileges;
In the future, we will 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
At this point, the MySQL security settings are basically complete.
Now we have installed mod-security, which is also very simple In Debian and will automatically add modules to httpd. conf.
[Root @ Debian/] apt-Get install libapache-mod-Security
This module is not activated by default. Edit the httpd. conf file and remove the comments in the following line.
Loadmodule security_module/usr/lib/Apache/1.3/mod_security.so
Add
# Enable or disable the filter Engine
Secfilterengine on
# Set the default action
Secfilterdefaultaction "Deny, log, status: 404"
# Pass the settings to the word directory
Secfilterinheritance off
# Check whether URL encoding is correct
Secfiltercheckurlencoding on
# Check the content length to avoid Heap Overflow attacks
Secfilterforcebyterange 32 126
# Log File Location and name
Secauditlog logs/audit_log
# Debug settings
Secfilterdebuglog logs/modsec_debug_log
Secfilterdebuglevel 0
# Checking Post Data
Secfilterscanpost on
# When matching SH, redirect to a special page, making it difficult for attackers to leave.
Secfilter sh redirect: http://secu.zzu.edu.cn/hack/fu.htm
# Only check the body of the POST request
# Filter sensitive things. We use * to prevent attackers from using/etc/./passwd.
Secfilter/etc/* passwd
Secfilter/bin/* Sh
# Prevent double dot attacks, that is, like http://www.test.com/openfile.php? Path =/... although this vulnerability seems to be mentally retarded, many websites have it, such as a picture station of a CERNET University :)
Secfilter "../"
# Preventing cross-site scripting (CSS) Attacks
Secfilter "<(|) * script"
Secfilter "<(. |) +>"
# Prevent SQL insert attacks
Secfilter "Delete (space |) + from"
Secfilter "insert (space |) +"
Secfilter "select (space |) + from"
Secfilter "Union (space |) + from"
# The following is a restricted upload.php file that can only be used to upload images like. BMP and GIF.
Secfilterinheritance off
Secfilterselective post_payload "! Image/(JPEG | BMP | GIF )"
With mod-security, you can greatly improve the security of your website. You can find more settings in manual, more detailed rules are attached to the CD
(Mod-security.rule.txt)
Then we installed Zend performance suit. When installing Zend performance suit, he asked the user, remember to write chrapax instead of WWW-data.
Order allow, deny
Allow from 211.43.125.63 (your IP address)
Deny from all
Options all
Chroot is a very important step, but it may be a relatively simple step. First copy several configuration files written in Python to/etc/makejail.
[Root @ Debian/etc/makejail] CP/usr/share/doc/makejail/examples/Apache. py ./
Edit the Apache. py file to add and modify the corresponding information.
Users = ["chrapax"]
Groups = ["chrapax"]
Packages = ["Apache", "Apache-common", "PhP4", "php4-gd", "mysql-common", "libapache-mod-Security"]
Then run the makejail command.
[Root @ Debian/etc/makejail] makejail Apache. py
After that, we have to make a soft connection and separate chrapax from the passwd and group files.
[Root @ Debian/etc/makejail] ln-S/var/chroot/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, create a chrapax file in/etc/init. d and make it executable. For details, see chrapax in the CD.
[Root @ Debian/etc/makejail] cat>/etc/init. d/chrapax
[Root @ Debian/etc/makejail] chmod + x/etc/init. d/chrapax
Use the rcconfcommand to enable the system to wait for startup (rcconf.bmp)
[Root @ Debian/etc/makejail] rcconf
Start Apache of chroot
[Root @ Debian/etc/makejail]/etc/init. d/chrapax start
First, test whether the connection between PHP and MySQL is correct.
[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 returned by the browser
Warning: Can't connect to local MySQL server through socket '/var/run/mysqld. Sock' (2) in/var/www/MySQL. php on line 2
However, we can see that mysqld exists under/var/run/mysqld. the sock file is actually because we already have chroot Apache. He can only access the items in Apache Root jail, that is, the items under/var/chroot/Apache, and mysqld. sock is obviously outside jail, so it is normal that the connection fails. The solution to this problem is also very simple. Just make a hard connection.
[Root @ Debian/Apache/var/run/mysqld] ln/var/run/mysqld. Sock mysqld. Sock
Check mysql.php again and click OK (OK .bmp)
Hard connection is troublesome, and Apache uses resources badly when accessing mysqld, the solution is to add bind-address 127.0.0.1 to the configuration file of mysqld so that the connection is established through TCP instead of through socket.
With this solution, the entire lamp server is much more secure, even if the PHP program is not secure or Apache, what is the vulnerability in PHP, it is still very difficult to intrude in and jump out of root jail.
Refer:
Security Apache step by step
Security PHP step by step
Security MySQL step by step
(I don't know why I couldn't find these three articles online at home. If you are interested in www.securityfosuc.com, go and have a look)
Mod-Security Manual
San's PHP security configuration
Http://www.xfocus.net/articles/200111/304.html
Version Information
V1@2003.11 initial edition
V2@2004.1 to solve the chroot PHP program connection MySQL Apache consumes a lot of resources
Corrected ustc.edu.cn to E-Science and Technology University rather than Chinese Science and Technology University :)
V3@2004.9 added allow_url_fopen = off
Adds mod-Security to filter SQL injection.