LAMP security reinforcement

Source: Internet
Author: User
Tags apache php openssl x509 server website speling strong password startssl modsecurity

Apache:
 
1. Modify the banner compilation source code and modify the default banner ServerTokens ProductOnly ServerSignature Off.
Find ap_release.h in the apache source code package and change # define AP_SERVER_BASEPRODUCT "Apache" to # define AP_SERVER_BASEPRODUCT "Microsoft-IIS/6.0" OS/unix OS. hfile # define PLATFORM "Unix"
Change to # define PLATFORM "Win32"
 
2. Modify default http status response code 404,503 and other default pages
 
3. Apache access permission control htpasswd-B-c/(password file path )/
. 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 the dangerous command to clear FollowSymlinks. Disable the index directory Options Indexes FollowSymLinks.
Shut down CGI execution Program
 
5. open_basedir restrict directory usage: php_admin_value open_basedir
/Var/www 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 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 rewrite rule Scope
 
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 meaning is as follows: in order to allow users to access the traditional http: // to https,
The rewrite rule is used. The first sentence is to 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 used (0 or 1 ),
(. *) Indicates the start of the rewrite module,
Change the url content of all requests that do not access port 443,
Change http: // to https: // 9. The Speling Module removes the url case and confirms 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
Install: tar zxvf mod_limitipconn-0.04.tar.gz cd mod_limitipconn-0.04 make APXS =/usr/local/apache/bin/apxs
 
Set make install APXS =/usr/local/apache/bin/apxs ???
Edit httpd. conf in your own path.
Global variables: <IfModule mod_limitipconn.c> <Location/> #
MaxConnPerIP 3 #
Each IP address allows only three concurrent connections to NoIPLimit image /*#
No IP address limit on images </Location> <Location/mp3> #
MaxConnPerIP 1 #
Each IP address only allows 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
Go to the rm-rf ssl. */server. * directory where the HTTP server configuration file is located .*
Delete the default or residual server certificate file rpm-qa | grep 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
Restart the service netstat-ntpl | grep 443 to get a valid certificate from the http://www.startssl.com (free of charge)
 
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? The zxvf modsecurity-1.8.7.tar.gz #
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 mod_security configuration http://www.modsecurity.org/docum... Ultipage/index.html
 
Php:
 

1. Open the php security mode. The php security mode is a very important embedded security mechanism that can control some php functions,
For example, passwd, but the default php. ini does not enable the security mode,
Open it: safe_mode = on when safe_mode is enabled and safe_mode_gid is disabled, the php script can access the file, and users in the same group can also access the file.
We recommend that you set this parameter to safe_mode_gid = off. If you do not set this parameter,
We may not be able to operate the files in the directory of our server website, for example, when we need to operate the files.
 
2. In security mode, when the main directory of the program is enabled in security mode but some programs are to be executed,
You can specify the main directory of the program to be executed: safe_mode_exec_dir = D:/usr/bin. Generally, no program needs to be executed,
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. If you want to include certain public files in safe mode, modify the option: 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. Use the open_basedir option to control that PHP scripts can only access specified directories,
This prevents PHP scripts from accessing files that should not be accessed, and limits the harm of phpshell to a certain extent,
Generally, we can set it to only access the website directory: open_basedir =/var/www/html
 
5. Disable dangerous functions. If security mode is enabled, function disabling is unnecessary,
But we still need to consider it for security.
For example, we do not want to execute a php function that can execute commands, such as system,
You can also disable phpinfo () and other functions that can view php information:
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 php version information on the server,
You can disable this information Skew 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 the variables submitted by registering global variables in PHP, including those submitted using POST or GET,
Are automatically registered as global variables and can be accessed directly. This 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,
When obtaining the corresponding variable, you must use a reasonable method, such as obtaining the variable var submitted by GET,
You need to use $ _ GET ['var'] to obtain it. This php programmer should pay attention to it.
 
8. It is very dangerous to open magic_quotes_gpc to prevent SQL injection,
Small, the website is infiltrated in the background, and the whole server is crashed, so be careful.
In php. ini, magic_quotes_gpc = Off is disabled by default,
If it is enabled, it will automatically convert the SQL query submitted by the user,
For example, convert 'to' to ', which plays a major role in preventing SQL injection.
Therefore, we recommend setting 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 of the php script or the queried SQL statement,
This type of information is insecure after it is provided to hackers,
Therefore, it is recommended that the server disable the error prompt: display_errors = Off. If you want to display the error message,
Make sure to set the Display error level, for example, to display only the warning information:
Error_reporting = E_WARNING & E_ERROR
Of course, we recommend that you disable the error message.
 
10. We recommend that you record the error information after you disable display_errors.
It is easy to find the reason for running the server: log_errors = On
You must also 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. Close Remote File opening allow_url_fopen = off to prevent remote Inclusion Vulnerability
 
12. Php. ini contains the patch file referenced in php. ini. If referenced in the configuration file, the website will be affected,
Include 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 "include_path =".; f: PHPnowhtdocs"
 
13. Use Suhosin to protect the PHP application system,
Specific reference www.2cto.com http://www.hardened-php.net/suhosin/configuration.html
 
Mysql:

 
1. Modify the root user password, and delete the default installed MySQL root user with a null password,
To ensure security, you must change the password to a strong password. The so-called strong password must be at least 8 characters in length and contain irregular passwords consisting of letters, numbers, and symbols.
Use the MySQL Command mysaladmin to change the root password and log on to the database,
Modify the field content of the user table in mysql 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 databases. Generally, the MySQL database is installed locally,
In addition, you only need a local php script to read mysql, so 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, which threatens the security of the database,
It is necessary to delete all of them. The final state is to retain only a single root. Of course, users and databases will be added as needed.

# Mysql> show databases; # mysql> drop database test; // Delete the database test
# Use mysql; # delete from db; // delete the table information stored in 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 account with an empty password. Try to repeat 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 is an important factor in database security management. Do not store plain text passwords in 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.
Also, do not select passwords from the dictionary. You can use special programs 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 it is used? 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,
Ensure that the identity of mysql is used.
You can also add the user parameter when starting the database.
#/Usr/local/mysql/bin/mysqld_safe? User = mysql & runs mysqld as other linux users without using root,
You do not need to change the root user name in the user table, because the MySQL account user name has nothing to do with 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.
 
In this case, the mysqld network listener is enabled, allowing users to remotely connect to local databases through account passwords,
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. If you need to remotely manage the database,
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 a mysql user in the background
 
7. restrict the number of users connected to a database. A user remotely connects to the database multiple times,
It may lead to performance degradation and other users' operations, and it is necessary to limit it. You can limit the number of connections allowed by a single account,
Set the max_user_connections variable in mysqld of the my. cnf file. 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,
The corresponding database file is in the/usr/local/mysql/var directory,
Therefore, you must ensure that this directory does not allow unauthorized users to package and copy the database,
Therefore, you must restrict access to this directory. Make sure that when mysqld is running,
Only linux users with read or write permissions on the database directory are used for running. # Chown-R root/usr/local/mysql ///

To the root # chown-R mysql. mysql/usr/local/mysql/var //

Make sure that the mysql user to which the database directory permission belongs
 
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 logged 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 must delete these two files and perform 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 history # ln-s/dev/null. bash_history //
Leave the shell record file blank # ln-s/dev/null. mysql_history // empty the mysql record file
 
10. mySQL is prohibited from accessing local files in mysql and provides reading of local files. The load data local infile command is used. This option is enabled by default in version 5.0, this operation will use MySQL to read local files to the database,
Then the user can obtain the sensitive information illegally. If you do not need to read the local file, 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 LOAD "/etc/passwd" into a database table by using load datalocal infile,
Then you can 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 local load data commands from the server. If you need to obtain LOCAL files,
Yes, but we recommend that you disable it.
 
11. the main function of the MySQL server permission control MySQL permission system is to verify that a user connects to a given host, and grant the user the SELECT, INSERT, UPDATE, and DELETE permissions on the database (for details, see the user Super user table ).
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 ).
FILE Permission allows you to create new files in a directory on the MySQL server with write permission,
But cannot overwrite existing files in the user table File_priv 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 by', '; Query OK, 4 rows affected (0.00 sec )//
Read the metadata information sqlfile.txt 'records: 4 Deleted: 0 Skipped: 0 Warnings: 0 # mysql> update user set File_priv = 'n' 'where user = 'root ';//
Prohibit read permission 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 ',';//
Re-log in to read the file # ERROR 1045 (28000): Access denied for user 'root' @ 'localhost' (using password: YES )//
Failed # mysql> select * from loadfile. users into outfile 'test.txt 'fields terminated by', '; 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. using 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, once there is any problem, it will not compromise 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 use the MySQL database and do not provide Web languages such as PHP, reset or compile your PHP, remove their default support for MySQL. If php and other web programs are used in the server, try to use illegal Web requests. If you get any form of MySQL errors, analyze the cause immediately,
Modify Web programs in time to block vulnerabilities and 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. It is very easy to back up the database using mysqldump. If you want to back up the database "nagios_db_backup ",

Use the command and gzip command to compress the backup file. We recommend that you use remote backup or Rsync,

Mount the directory of the backup server to the database server, package backup of database files, 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.$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. (). gz nagios_backup. () # mysql? U root-p nagios
</Home/sszheng/nfs58/nagiosbackup/nagios_backup. ()
 
15. What are the startup options for Mysqld security? Local-infile [= {0 | 1}] If? If local-infile = 0, the client cannot use the LOCAL in load data statement.
? Old-passwords forces 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 MySQL earlier versions, this option enables the show databases statement to display only the names of DATABASES with partial 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.
? If safe-user-create is 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 is the added TRIGGER_ACL check for I _S.TRIGGERS http://bugs.mysql.com/bug.php? Id = 38837
Http://bugs.mysql.com/bug.php? Id = 27629
The method $ cfg ['servers'] [$ I] ['hide _ db'] = 'information _ scheme' is hidden in Phpmyadmin ';
 
Using vsftpd in combination with pam_mysql is basically a web server that has roughly completed 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.
 
If the system is of the windows series, you can modify the relevant path ~

Author: ITLEAF's BLOG

Related Article

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.