Build linux + nginx + PHP FPM MySQL (MariaDB) environment

Posted by Darghon on Thu, 10 Feb 2022 17:04:27 +0100

Build linux + nginx + PHP FPM MySQL (MariaDB) environment

1.Linux selects centos7 installed before

Thoughts on security reinforcement of mainframe based on CentOS 7

Although there are a lot of data summary and reference here, what you can remember is that you know the significance of reinforcement. In other words, you have really attacked from here, or you just look at the flowers. At the same time, the safety problems here are limited by their lack of professionalism, but they just think about it by themselves.

a. Account number

cat  /etc/pwsswd | wc -l How many users are counted

cat /etc/passwd | grep :0 see root Users with permissions

cat /etc/shadow have! *Users who are locked and unable to log in

cat /etc/group View user groups

(these provide the basic account information of a Linux host. Of course, there are account uid and other details under the extension. I won't repeat them first. The purpose of these is to form their own context. The following are summarized to level 2. They don't go deep into Level 3 and level 4 operations.)

vi /etc/pam.d/su Edit this setting to disable ordinary users su reach root

b. Authorization

chmod Command sets the permissions of important files, such as log file, historical command record file, account configuration file, etc.

umask Set as 027

Service authorization such as ftp The service prohibits some users from logging in anonymously


c. Password

vi /etc/pam.d/system-auth Password complexity settings, such as numbers, uppercase and lowercase letters and special characters composed of eight digits or more. More often, the penetration is weak, the password is fatal and the light is black. 123456 eternal God.

vi /etc/pam.d/sshd Continuous password error locking to avoid blasting

vi /etc/login.defs The password update cycle is forced to be updated every how many days, and it should be different before and after.

d. Remote login

vi /etc/hosts.allow(deny) limit IP Access to household accounts

vi /etc/profile Timeout setting

vi /etc/ssh/sshd_config Prohibit direct login root Account, need from general account su reach root;Combined with the prohibition in front su reach root,Only local root The account is logged in.


e. Port off

First of all, the firewall must be on,

firewall-cmd --list-port See which ports are open

firewall-cmd --zone=public --add-port=3838/tcp --permanent increase tcp When the port is closed add Change to remove

firewall-cmd --zone=public --add-port=3838/udp --permanent

firewall-cmd --reload Reloading does not interrupt user connection and lose status information. I've learned that I used to restart here. It's a great blessing that I didn't die in the production environment. Shit.

f. Log

audit To record security related logs, you need to adjust the rule base in combination with the business syslog It is an error log biased towards the application layer.

Configure log server for important logs

g. Kernel adjustment

Prevent stack overflow. I just read it and don't understand it.

h. Address resolution order

Change the host address resolution order to prevent IP deception.

i. Patch update

uname -a Look at the version leak ms17-010 This kind of, new three years old three years, ah, patch server settings.

j.banner information shielding

system banner Information(/etc/rc.d/rc.local),ftp banner(/etc/vsftp.d/vsftp.conf)Information, etc#Drop.

2.Nginx installation

2.1 preparation before Yum installation: since there is no Yum source by default, you need to add nginx to the yum source and install nginx

rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

ps: it has been installed through source code compilation before. For source code installation, you should first install GCC compiler (compile the source code into binary program), PCRE (parse regular expression), zlib (function library providing data compression), OpenSSL (NGINX application HTTPS, MD5, SHA1, etc.

2.2 successful installation

ps:Nginx configuration information

Default directory for storing website files

/usr/share/nginx/html

Site default site configuration

/etc/nginx/conf.d/default.conf

Customize the storage directory of Nginx site configuration files

/etc/nginx/conf.d/

Nginx global configuration

/etc/nginx/nginx.conf

Thoughts on security reinforcement of web container based on nginx

As an excellent forward and reverse proxy web server, nginx has the characteristics of multithreading and high concurrency. By the way, write down the forward and reverse proxy. The proxy client is the forward, while the proxy server is the reverse proxy. In addition, the forward agent can be used as the management of online behavior; In addition to load balancing, reverse proxy exposes the IP of the proxy server on the public network and hides the intranet web server.

For nginx, remember to restart the backup every time you modify it. It is recommended to restart nginx -s reload smoothly

a. Restrict directory access

vi /etc/nginx/nginx.conf stay HTTP Module addition autoindex off; because nginx Will download automatically web Files in the directory to increase threat exposure.

b. Hide version information

vi /etc/nginx/nginx.conf stay HTTP Module addition server_tokens off Hide version information, such as HTTP I can't see it in the response. You have to restart here. Reloading the configuration doesn't work.

c. Restrict HTTP request methods

vi /etc/nginx/conf.d/default.conf stay server Module addition

if ($request_method !~* GET|POST|HEAD) {
    return 403;
    } //Reject requests other than get|post|head

d.nginx power reduction

vi /etc/nginx/nginx.conf increase user nobody; That's it web If the service authority fails, it will not be root jurisdiction. This also involves operation and maintenance knowledge, nobody yes Linux Users who are used to execute processes other than the main process of the service. In order to achieve the effect of loss without loss, if they are used at the beginning root Deployed nginx,After load balancing, restart the service every time root,Trouble; And if you want to change it, it will also lead to insufficient cache access rights, slow process, service paralysis and other future problems.

e. Anti theft chain

edit nginx.conf configuration file(vi /etc/nginx/nginx.conf ),stay server Add the following contents to the label:

location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {
    valid_referers none blocked server_names *.nsfocus.com http://localhost baidu.com;
    if ($invalid_referer) {
        rewrite ^/ [img]http://www.XXX.com/images/default/logo.gif[/img];
      #return 403;
     }
}

f. Restrict IP access

edit nginx.conf configuration file(vi /etc/nginx/nginx.conf ),stay server Add the following contents to the label:

location / {
deny ip;  
allow ip;
}

g. Patch update

nginx -v #View version information
nginx -t #View profile

Then select the patch

3. Install PHP FPM

3.1 integrate the following commands to install PHP

yum install php php-fpm php-mysql php-mbstring php-xml -y

3.2 check whether php and its extensions are installed successfully

Thoughts on security reinforcement based on PHP FPM

PHP FPM configuration file path: / etc / PHP FPM d/www.conf
php configuration file path: / etc / php ini

a. PHP FPM weight reduction

modify/etc/php-fpm.d/www.conf,take user = apache group = apache,Change to user = nobody group = nobody;about nobody stay Linux The role of the system is mentioned above.

b. Security mode

Originally, but it was abandoned after 5.3.

c. Disable unsafe PHP functions

vi /etc/php.ini  

disable_functions = passthru,exec,system,chroot,chgrp,chown,shell_exec,proc_open,proc_get_status,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,stream_socket_server,fsocket,phpinfo 

#In this way, the previously tested php nginx and the general phpinfo function will fail.

d. Close error log

vi /etc/php.ini  

display_errors = Off  

#Avoid file upload or sql error injection and getshell caused by exposing the physical path. One of the previous ctf primary training camps in i spring and autumn is to use PHP to report errors and check the database version.

e. Enable HTTPOnly

vi /etc/php.ini  

session.cookie_httponly = 1

adopt document Embezzle cookie prevention XSS,But you can socket Layer capture program advanced attack.

f. Turn off PHP information

vi /etc/php.ini  

expose_php = Off

This is set in http I can't see it in the request x-powered-by:php/5.4.16 Yes

g. Restrict directory access

vi /etc/php.ini  

open_basedir = ./:/tmp:/home/www/The disadvantage of the configured directory is the impact IO flow

h. Restricted upload directory

vi /etc/php.ini  

upload_tmp_dir = /tmp Directory traversal is defined to prevent uploading.


4. The connection test between nginx and PHP FPM is successful

In index Write <? php phpinfo(); ?>, Then visit the browser and you can see that the PHP code has been executed successfully.

It should be noted that the default site configuration file of nginx website has been modified: remove the annotation symbol #, as shown in the above figure, and $document_root has been modified, and don't forget to indicate the PHP file storage path to PHP FPM: / usrshare/nginx/html. I have installed it many times before and found that this problem will not exist in the source code compilation and installation, and this path will exist in the yum installation, indicating that the problem needs special attention!!

5. Install MySQL (MariaDB is now installed after the acquisition)

5.1 install mysql using yum

yum install mariadb* -y

Start and set the self starting mysql service at the same time.

5.2 setting mysql password:

mysql -uroot -p

The database here needs to change the initial password before it can be used. In addition, delete from under the update statement correction.

Thoughts on security reinforcement based on mysql

a. Running mysql under a general account

vi /etc/my.cnf
[mysql.server]
user=mysql

b.root remote login restrictions - trusted IP login, etc

mysql> grant all privileges on *.* to 'root' @localhost identified by 'password'with grant option;
mysql> flush priveleges;

mysql> grant all privileges on *.* to 'user name' @'Access allowed IP address' identified by 'password'with grant option;
mysql> flush priveleges;   //Only this address is allowed, but all permissions are given

mysql> grant all privileges on *.* to 'user name' @'Access allowed IP address' identified by 'password';
mysql> flush priveleges;  //Only this address is allowed, but not all permissions are given

c. Delete empty password account (anonymous account)

mysql> delete from user where user="";
mysql> flush priveleges;

d. Historical command protection to prevent the disclosure of sensitive information such as configuration

rm .bash_history .mysql_history //Delete history
ln -s /dev/null .bash_history 
ln -s /dev/null .mysql_history //Set the database operation record not to be recorded in 2 files

e. Configure log, password complexity and replacement cycle, limit the number of single user sessions, login failure processing functions, etc

6. The connection test between PHP and mysql is successful

cd /usr/share/nginx/html/

vi mysql.php        //Write PHP test code connecting mysql.

7. Summary

If you step on the pit, pay attention to the alignment of the configuration file format. yum install nginx to indicate the path to read the PHP file; Then, PHP supports mysqli after the higher version; Make sure to back up before modifying anything, write out the technical scheme first, and restart or reload after modification; The first step of mysql is to modify the empty password before it can be used;

Gain a lot, let the fragmentary knowledge coupled, deployment and reinforcement at the same time, can realize the importance of integrating attack and defense to promote progress. For example, when strengthening PHP HTTPOnly, it is associated with the content of cosine's "uncover the secrets of web front-end hacker technology", which is more integrated and promotes understanding. More profound understanding of the interaction between PHP: fastm and CGI: fastm

Topics: Linux Operation & Maintenance Database CentOS Nginx