Lamp security reinforcement (by Kindle brother)

Source: Internet
Author: User
Tags apache php openssl x509 response code speling strong password startssl modsecurity

Securing _ & _ hardening_linux_v1.0
L.a. m.p environment configuration document update
Installation, optimization, and security settings of Apache 2.x in centos
After completing the configuration, start to enter the subject
Apache:
1. Modify banner
Compile the source code and modify the default banner.
ServerTokens productonly
Serversignature off
In the Apache source package, find ap_release.h
# Define ap_server_baseproduct "Apache"
Change
# Define ap_server_baseproduct "Microsoft-IIS/6.0"
OS. h file in OS/Unix
# Define platform "UNIX"
Change
# Define platform "Win32"
2. Modify default HTTP status response code 404,503 and other default pages
3. Access Control for Apache
Htpasswd-B-c/(path for storing the password file)/. htpasswd Username Password
Alias/hack "/var/www/html/hack /"
<Directory "/var/www/html/hack">
Authname "test"
Authtype basic
Authuserfile/var/www/html/hack/. htpasswd
Require user kindle
</Directory>
4. Disable Dangerous commands
Clear followsymlinks command
Disable INDEX DIRECTORY
Options indexes followsymlinks
Shut down CGI execution Program
5. open_basedir restriction directory
Usage: php_admin_value open_basedir/var/WWW
Solution to file upload failure caused by php_admin_value open_basedir
Add the temporary directory of the uploaded file to the end of php_admin_value open_basedir and it looks like this:
<Virtualhost *: 80>
Php_admin_value open_basedir "/usr/local/Apache/htdocs/www/:/tmp /"
</Virtualhost>
Note: two directories are separated by colons.
Limiting PHP script operations to web directories can prevent programmers from using the copy function to copy system files to web directories. Move_uploaded_file is not restricted by open_basedir, so you do not need to modify the upload_tmp_dir value in PHP. ini.
6. Master Apache order allow deny judgment principles
1. First, determine the default value;
2. Then judge before the comma;
3. The last comma after the judgment;
4. The final result of the judgment is superimposed in order.
Ex:
Apache PHP extension Parsing Vulnerability
<Files ~ "/. (PHP. | php3.)">
Order allow, deny
Deny from all
</Files>
Apache does not have the execution permission to set the upload directory.
<Directory "/www/home/upload">
<Files ~ ". Php">
Order allow, deny
Deny from all
</Files>
</Directory>
7. mod_rewrite rewrite URL
Applicability of Rewrite Rules
1. Use it in the Apache main configuration file httpd. conf.
2. Use the configuration defined in httpd. conf.
3. Use the. htaccess configuration file in the basic directory.
1. URL redirection from port 80 to port 443
Rewriteengine on
Rewritecond % {server_port }! ^ 443 $
Rewriterule ^ /? (. *) $ Https://www.kindle.com/#1 [L, R]
The rewrite rule is used to allow users to access the traditional http: // to https:
First sentence: Start the rewrite Engine
The rewrite condition is that the accessed server port is not port 443.
The third sentence: This is a regular expression, ^ is the beginning, $ is the end ,/? Indicates whether/can be (0 or 1), and (. *) is any number of arbitrary characters.
Start the rewrite module to change the URL content of all requests that access non-port 443 from http: // to https ://
9. Remove the URL case in the speling Module
Confirm that the speling module exists and has been loaded
Start speling
<Directory "/usr/local/downloads">
Checkspelling.
AllowOverride none
Order allow, deny
Allow from all
</Directory>
8. The limit module limits the number of IP connections
Download module http://dominia.org/djao/limit/mod_limitipconn-0.04.tar.gz
Installation:
Tar zxvf mod_limitipconn-0.04.tar.gz
CD mod_limitipconn-0.04
Make apxs =/usr/local/Apache/bin/apxs restart -- set it according to your own path.
Make install apxs =/usr/local/Apache/bin/apxs restart -- set it according to your own path.
Edit httpd. conf
Add
Global variables:
<Ifmodule mod_limitipconn.c>
<Location/> # all virtual hosts/directory
Maxconnperip 3 # Each IP address only allows three concurrent connections
Noiplimit image/* # No IP address limit on Images
</Location>
<Location/MP3> # All Hosts/MP3 Directories
Maxconnperip 1 # Each IP allows only one connection request
Onlyiplimit audio/MPEG Video # This restriction only applies to video and audio files.
</Location>
</Ifmodule>
9. Enable Apache to support secure HTTPS protocol
Yum-y install mod_ssl
CD/etc/httpd/conf enter the directory where the HTTP server configuration file is located
Rm-rf ssl. */server. * delete default or residual server certificate files
Rpm-Qa | grep OpenSSL
OpenSSL genrsa-out www.kindle.com. Key 1024 create a server key
OpenSSL req-New-key www.kindle.com. Key-out www.kindle.com. CSR create the server Public Key
OpenSSL X509-req-days 365-In www.kindle.com. CSR-signkey www.kindle.com. Key-out www.kindle.com. CRT create a server certificate
/Etc/rc. d/init. d/httpd restart the service
Netstat-ntpl | grep 443
Legal certificate available to http://www.startssl.com (free)
10. install and configure mod_security
Download: http://www.modsecurity.org/download/modsecurity-1.8.7.tar.gz
Http://fedoranews.org/jorge/mod_security/mod_security.conf
Install: Download to the/opt/soft directory.
# Tar-zxvf modsecurity-1.8.7.tar.gz
# Cd modsecurity-1.8.7
# Cd apache2
#/Opt/Apache/bin/apxs-CIA mod_security.c
# Copy mod_security.conf/opt/Apache/Conf
Configuration:
Add the following line to/opt/Apache/CONF/httpd. conf:
Include CONF/mod_security.conf
/Opt/Apache/bin/apachectl stop
/Opt/Apache/bin/apachectl startssl
More detailed configuration of mod_security
Http://www.modsecurity.org/docum... ultipage/index.html
PHP:
1. Enable the PHP security mode
The security mode of PHP is a very important embedded security mechanism that can control some functions in PHP, such as system () and control permissions for many file operation functions, files of some key files, such as/etc/passwd, but the default PHP. INI does not enable the security mode. We open it: safe_mode = on
When safe_mode is enabled and safe_mode_gid is disabled, PHP scripts can access files and users in the same group can also access the files. Recommended Value: safe_mode_gid = off
If you do not set it, you may not be able to operate the files under the website directory of our server, for example, when you need to operate the files.
2. Main directory of the execution program in Safe Mode
If security mode is enabled, but you want to execute some programs, you can specify the main directory of the program to be executed: safe_mode_exec_dir = D:/usr/bin
Generally, you do not need to execute any program. Therefore, we recommend that you do not execute the system program directory. you can point to a directory and copy the program to be executed. For example: safe_mode_exec_dir = D: /tmp/CMD
However, I recommend that you do not execute any program, so you can point to our webpage directory:
Safe_mode_exec_dir = D:/usr/WWW
3. File Inclusion in Safe Mode
If you want to include some public files in safe mode, modify the following options:
Safe_mode_include_dir = D:/usr/www/include/
In fact, the files contained in the PHP script are all written in the program itself, which can be set as needed.
4. Control the directory that PHP scripts can access
You can use the open_basedir option to control the PHP script to access only the specified directory, which can avoid PHP script access. files that should not be accessed limit the harm of phpshell to a certain extent. We can generally set to only access the website directory:
Open_basedir =/var/www/html
5. Disable dangerous functions
If the security mode is enabled, the function is not required, but we should consider it for security. For example, we do not want to execute a PHP function that can execute commands, such as system (), or a phpinfo () function that can view PHP information, then we can disable them:
Disable_functions = system, passthru, exec, shell_exec, popen, phpinfo
If you want to disable operations on any files and directories, you can disable many file operations.
Disable_functions = phpinfo, exec, system, passthru, shell_exec, escapeshellarg, escapeshellcmd, proc_close, proc_open, DL, popen, show_source
The above only lists some file processing functions that are not commonly used. You can also combine the preceding command functions with this function,
You can resist most phpshells.
Note: disable_classes can disable some classes. If multiple classes are separated by commas (,),
6. Disable PHP version information leakage in the HTTP header.
To prevent hackers from obtaining information about the PHP version on the server, we can disable this information in the HTTP header:
Expose_php = off
For example, when hackers Telnet www.12345.com 80, they will not be able to see the PHP information.
7. Disable registration of global variables
Variables submitted in PHP, including those submitted using post or get, will be automatically registered as global variables for direct access, which is very insecure for the server, therefore, if we cannot register it as a global variable, we disable the register global variable option:
Register_globals = off
Of course, if this is set, a reasonable way should be used to obtain the corresponding variable, such as getting the variable VAR submitted by get, you need to use $ _ Get ['var'] to obtain it. This PHP programmer should pay attention to it.
8. Enable magic_quotes_gpc to prevent SQL injection.
SQL injection is a very dangerous problem. If the website is compromised in the background, the entire server is compromised. Therefore, be careful. PHP. INI has a setting:
Magic_quotes_gpc = off
This is disabled by default. If it is enabled, it will automatically convert the SQL query submitted by the user, such as converting 'to/', which plays a major role in preventing SQL injection. Therefore, we recommend the following settings:
Magic_quotes_gpc = on
9. error message control
Generally, PHP prompts an error when it is not connected to the database or in other cases. The error message contains the current path information of the PHP script or the queried SQL statement, this type of information is insecure when it is provided to hackers. Therefore, we recommend that you disable the following error message on the server:
Display_errors = off
If you want to display the error information, you must set the Display error level. For example, only the warning information is displayed:
Error_reporting = e_warning & e_error
Of course, we recommend that you disable the error message.
10. Error Log
We recommend that you record the error information after you disable display_errors to find out the reason for running the server:
Log_errors = on
At the same time, you must set the directory where error logs are stored. It is recommended that the logs of the root Apache exist together:
Error_log = D:/usr/local/apache2/logs/php_error.log
Note: You must grant write permissions to Apache users and groups.
11. Disable Remote File opening
Allow_url_fopen = off
Remote remote Inclusion Vulnerability prevention
12. php. ini contains patch files
Reference in PHP. ini. If referenced in the configuration file, the website will be affected, including all pages.
In PHP. ini, find this section:
; Automatically add files before or after any PHP document.
; Auto_prepend_file = "phpids. php"
; Auto_append_file = "alert. php"
The default value is null. Add the included files. At the same time, find:
; Unix: "/path1:/path2 ″
; Include_path = ".:/PHP/shortdes"
;
Windows: "/path1;/path2 ″
Export de_path = ".; F:/phpnow/htdocs" 13. Use suhosin to protect the PHP application system, refer to the http://www.hardened-php.net/suhosin/configuration.html
MySQL:
1. Modify the root user password and delete the empty password.
By default, the root user of the installed MySQL instance has a blank password. For security reasons, it must be changed to a strong password. The so-called strong password should be at least 8 characters long, an irregular password consisting of letters, numbers, and symbols. Use the MySQL Command mysaladmin to change the root password. You can also log on to the database and modify the field content of the User table under MySQL. The modification method is as follows:
#/Usr/local/MySQL/bin/mysqladmin-u Root Password "upassword" // use mysqladmin
# Mysql> use MySQL;
# Mysql> Update user SET Password = PASSWORD ('upassword') where user = 'root ';
# Mysql> flush privileges; // force refresh the memory authorization table. Otherwise, the password is still cached in the memory.
2. delete default databases and database users
Generally, the MySQL database is installed locally and only needs a local PHP script to read mysql. Therefore, many users do not need it, especially those installed by default. After MySQL initialization, empty users and test libraries are automatically generated for installation testing. This poses a threat to the security of the database. It is necessary to delete all of them. The final state is only one root, add users and databases as needed.
# Mysql> show databases;
# Mysql> drop database test; // Delete the database Test
# Use MySQL;
# Delete from dB; // Delete the table information that stores the database because there is no database information.
# Mysql> Delete from user where not (user = 'root'); // delete an initial non-Root User
# Mysql> Delete from user where user = 'root' and Password = "; // Delete the root with an empty password, and repeat the operation as much as possible
Query OK, 2 rows affected (0.00 Sec)
# Mysql> flush privileges; // force refresh the memory authorization table.
3. Change the default MySQL Administrator Account
4. Password Management
Password is an important factor in database security management. Do not save a plain text password to the database. If your computer is at risk, intruders can get all the passwords and use them. Instead, MD5 (), sha1 (), or unidirectional hash functions should be used. Do not select passwords from the dictionary. Special programs can be used to crack them. Select a strong password consisting of at least eight characters including letters, numbers, and symbols. When accessing the password, use the SQL statement of MySQL's built-in function password () to encrypt and store the password. For example, add a new user to the users table.
# Mysql> insert into users values (1, password (1234), 'test ');
5. Run msyql with an independent user
Never run the MySQL server as a root user. This operation is very dangerous because any user with File Permission can use root to create files (for example ,~ Root/. bashrc ). Mysqld rejects root running unless the-user = root option is explicitly specified. Mysqld should be run with a normal non-authorized user. As in the previous installation process, create an independent MySQL account in Linux for the database. This account is only used to manage and run MySQL.
To start mysqld with other Unix users, add the user option to specify the username of the [mysqld] group in the/etc/My. CNF option file or the my. CNF option file of the server data directory.
# Vi/etc/My. CNF
[Mysqld]
User = MySQL
This command enables the server to start with a specified user. Whether you start it manually or through mysqld_safe or MySQL. server, you can ensure that you use the MySQL identity. You can also add the USER parameter when starting the database.
#/Usr/local/MySQL/bin/mysqld_safe-user = MySQL &
As other Linux users, you do not need to run mysqld as root. You do not need to change the root user name in the User table because the MySQL account user name is irrelevant to the Linux account user name. Make sure that only Linux users with read or write permissions on the database directory are used to run mysqld.
6. Disable remote connection to the database
Under the command line netstat-ant, the default port 3306 is enabled. In this case, the mysqld network listener is enabled, allowing you to remotely connect to the local database using the account password, by default, data can be remotely connected. To disable this function, start skip-networking and do not listen to any SQL TCP/IP connection, cut off the remote access right and ensure security. To remotely manage databases, you can install phpMyAdmin. If you do need to remotely connect to the database, at least modify the default listening port, and add firewall rules, only allow data passing through the trusted network's MySQL listening port.
# Vi/etc/My. cf
Remove the # Skip-networking annotation.
#/Usr/local/MySQL/bin/mysqladmin-u root-P shutdown // stop the database
#/Usr/local/MySQL/bin/mysqld_safe-user = MySQL & // start MySQL with mysql users in the background
7. Limit the number of connected users
If a user of a database remotely connects to the database multiple times, the performance may decrease and the operations of other users may be affected. Therefore, it is necessary to restrict the operation. You can set the max_user_connections variable in mysqld of the my. CNF file to limit the number of connections allowed by a single account. The grant statement can also support resource control options to limit the scope of use allowed by the server to an account.
# Vi/etc/My. CNF
[Mysqld]
Max_user_connections 2
8. user directory permission restrictions
The default MySQL is installed in/usr/local/MySQL, and the corresponding database file is in the/usr/local/MySQL/var directory. Therefore, you must ensure that this directory cannot allow unauthorized users to package and copy the database. Therefore, you must restrict access to this directory. Make sure that only Linux users with read or write permissions on the database directory are used to run mysqld.
# Chown-r root/usr/local/MySQL // MySQL home directory to root
# Chown-r mysql. MySQL/usr/local/MySQL/var // ensure that the permission of the database directory belongs to the MySQL user
9. Command history Protection
Database-related shell operation commands are recorded in. bash_history: if these files are accidentally read, the Database Password, database structure, and other information will be leaked, and the operations after logging on to the database will be recorded in. in the mysql_history file, if you use the update table information to modify the database user password, the password will also be read. Therefore, you need to delete these two files, during password-related operations such as login or database backup, you should use the-p parameter to add the prompt to enter the password, and then enter the password implicitly. We recommend that you leave the above files blank.
# Rm. bash_history. mysql_history // Delete the history
# Ln-S/dev/null. bash_history // empty the shell record file
# Ln-S/dev/null. mysql_history // leave the MySQL record file empty
10. Prohibit MySQL from accessing local files
In MySQL, the local file is read and the load data local infile command is used. This option is enabled by default in MySQL 5.0, this operation will use MySQL to read local files to the database, and then the user can obtain sensitive information illegally. If you do not need to read local files, be sure to disable it. MySQL should be prohibited from using the "load data local infile" command. Some attack methods circulating on the Internet use load data local infile, and it is also a method used by many new SQL injection attacks! Hackers can also use load datalocal infile to load "/etc/passwd" into a database table and then use select to display it. This operation is fatal to server security. You can add local-infile = 0 to my. CNF, or add the Parameter Local-infile = 0 to start MySQL.
#/Usr/local/MySQL/bin/mysqld_safe-user = mysql-local-infile = 0 &
# Mysql> load data local infile 'sqlfile.txt 'into Table users fields terminated ',';
# Error 1148 (42000): The used command is not allowed with this MySQL version
-Local-infile = 0: Enable mysqld to disable all load data local commands from the server. If you need to obtain local files, open the command but disable it.
11. MySQL Server permission Control
The main function of the MySQL permission system is to confirm the user connected to a given host and grant the user the select, insert, update, and delete permissions on the database (see the user Super User table for details ). Its additional functions include anonymous users and the ability to authorize and manage mysql-specific functions, such as load data infile.
The administrator can configure tables such as user, DB, and host to control the user's access permissions. The user table permission is the Super User permission. It is wise to grant only the permissions of the User table to a Super User, such as a server or database supervisor. For other users, you should set the permissions in the User table to 'N' and grant permissions only on the basis of a specific database. You can authorize a specific database, table, or column. The File Permission gives you the permission to use load data infile and select... The into OUTFILE statement reads and writes files on the server. Any user granted the File Permission can read or write any files that the MySQL server can read or write. (The user can read files in any database directory because the server can access these files ). The File Permission allows you to create new files in a directory with write permission on the MySQL server, but cannot overwrite existing files in the file_priv of the User table to set Y or N ., Therefore, when you do not need to read server files, disable this permission.
# Mysql> load data infile 'sqlfile.txt 'into Table LoadFile. Users fields terminated ',';
Query OK, 4 rows affected (0.00 Sec) // read the response information sqlfile.txt'
Records: 4 Deleted: 0 skipped: 0 Warnings: 0
# Mysql> Update user set file_priv = 'n' 'where user = 'root'; // read permission prohibited
Query OK, 1 row affected (0.00 Sec)
Rows matched: 1 changed: 1 Warnings: 0
Mysql> flush privileges; // refresh the authorization table
Query OK, 0 rows affected (0.00 Sec)
# Mysql> load data infile 'sqlfile.txt 'into Table users fields terminated by', '; // re-log in to read the file
# Error 1045 (28000): Access denied for user 'root' @ 'localhost' (using password: Yes) // failure
# Mysql> select * From LoadFile. users into OUTFILE 'test.txt 'fields terminated ',';
Error 1045 (28000): Access denied for user 'root' @ 'localhost' (using password: Yes)
To ensure security, use the show grants statement at any time to check who has accessed what. Then, use the revoke statement to delete unnecessary permissions.
12. Use the chroot method to control the MySQL running directory
Chroot is a kind of advanced system protection in Linux. Its establishment will completely isolate it from the main system. That is to say, once any problem occurs, it will not endanger the running main system. This is a very effective method, especially when configuring network service programs.
13. Disable access to unrelated web programs
If you do not want to allow web access to the MySQL database and do not provide Web languages such as PHP, reset or compile your PHP and cancel their default support for MySQL. If PHP and other web programs are used in the server, try illegal requests in the web form. If any form of MySQL error is obtained, analyze the cause immediately, modify the web program in time, and block the vulnerability, prevent MySQL from being exposed to the Web.
For Web security checks, we recommend that you check the following list for Web applications in the MySQL official documentation:
Try inputting single quotes and double quotation marks (''' and '"') on the web '"'). If you get any form of MySQL error, analyze the cause immediately.
Try to modify the dynamic URL. You can add % 22 ('"'), % 23 ('#'), and % 27 (''').
Try to modify the data type in the dynamic URL by using the characters in the previous example, including numbers and character types. Your application should be secure enough to prevent such modifications and similar attacks.
Try to enter characters, spaces, and special characters. Do not enter numbers in numeric fields. Your application should delete or generate errors before passing them to MySQL. It is dangerous to pass unchecked values to MySQL!
Check the data size before passing it to MySQL.
Use a user name other than the management account to connect the application to the database. Do not grant unnecessary access permissions to the application.
14. database backup policy
It is very easy to back up data using mysqldump. If you want to back up the database "nagios_db_backup", run the command and compress the backup file using the gzip command of the MPs queue. We recommend that you use remote backup, you can use rsync to mount the directory of the backup server to the database server, package the database file backup, and regularly back up data through crontab:
#! /Bin/sh
Time = 'date + "(" % F ")" % R'
$/Usr/local/MySQL/bin/mysqldump-u Nagios-pnagios Nagios | gzip>/home/sszheng/nfs58/nagiosbackup/nagios_backup.1_time.gz
# Crontab-l
# M h Dom mon Dow command
00 00 ***/home/sszheng/shnagios/backup. Sh
Run the following command to restore data:
Gzip-D nagios_backup./(2008-01-24/) 00/: 00.gz
Nagios_backup. ()
# Mysql-u root-P Nagios 15. mysqld security-related startup options
-Local-infile [= {0 | 1}]
If-local-infile = 0 is used to start the server, the client cannot use the local in load data statement.
-Old-passwords
Force the server to generate a short (pre-4.1) password hash for the new password. It is useful to ensure compatibility when the server must support Old Client versions.
(Obsolete)-safe-show-Database
In earlier versions of MySQL, this option enables the show databases statement to display only the names of databases with certain permissions. In MySQL 5.1, this option is no longer used as the default action. You can use the show databases permission to control the access to the database name of each account.
-Safe-user-create
If enabled, you cannot use the grant statement to create a new user, unless you have the insert permission for the mysql. User table. If you want to authorize a user to create a new user, you must grant the following permissions to the user:
Mysql> grant insert (User) on MySQL. User to 'user _ name' @ 'host _ name ';
In this way, you cannot directly change the permission column. You must use the grant statement to grant this permission to other users.
-Secure-auth
An account with an old (pre-4.1) password cannot be authenticated.
16. information_schema Security
From the user's perspective, information_schema is only a storage engine that exists as a plug-in. during compilation and installation
-Disable-information-schema.
Added trigger_acl check for I _s.triggers
Http://bugs.mysql.com/bug.php? Id = 38837
Http://bugs.mysql.com/bug.php? Id = 27629
PhpMyAdmin hide Method
$ Cfg ['servers'] [$ I] ['hide _ db'] = 'information _ scheme ';
Combining vsftpd with pam_mysql is basically finished on a Web server.
Iptables:
Iptables-F
Iptables-x
Iptables-z
Iptables-A input-I lo-J accept
Iptables-P intput drop
Iptables-A input-p tcp-dport 21-J accept
Iptables-A input-p tcp-dport 22-J accept
Iptables-A input-p tcp-dport 80-J accept
Iptables-A input-p tcp-dport 80-M recent-name bad_http_access-Update-seconds 60-hitcount 30-J reject
Iptables-A input-p tcp-dport 80-M recent-name bad_http_access-set-J accept
Iptables-P output drop
Iptables-A output-p tcp-sport 80-J accept
Iptables-A output-p tcp-sport 21-J accept
Iptables-A output-p tcp-sport 22-J accept
Iptables-A input-M State-State related, established-J accept
Iptables-A output-p tcp-dport 80-M recent-name bad_http_access-Update-seconds 60-hitcount 30-J reject
Iptables-A input-p tcp-dport 80-M recent-name bad_http_access-set-J accept
Iptables-A output-M State-State related, established-J accept
If you are not at ease, use various security scanning tools to scan for other vulnerabilities on the server.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.