Due to scripting language and early version design, PHP projects have many security risks. From the configuration options, the following optimizations can be made.

1. Block PHP error output.

In /etc/php.ini(the default configuration file location), change the following configuration values to Off

display_errors=Off
Copy the code

Do not print the error stack directly to a web page to prevent hackers from taking advantage of the information.

The correct method is to write error logs to log files for troubleshooting.

2. Block the PHP version.

By default, the PHP version is displayed in the return header, as in:

Response Headers X-powered-by: PHP/7.2.0
Copy the code

Change the following configuration value in php.ini to Off

expose_php=Off
Copy the code

3. Close global variables.

If global variables are enabled, some form submitted data will be automatically registered as global variables. The code is as follows:

<form action="/login" method="post">
<input name="username" type="text">
<input name="password" type="password">
<input type="submit" value="submit" name="submit">
</form>
Copy the code

If global variables are enabled, server-side PHP scripts can use username and username and username and password to get the username and password, which can be extremely dangerous for script injection.

To enable this function, modify php.ini as follows:

register_globals=On
Copy the code

You are advised to disable the function. The parameters are as follows:

register_globals=Off
Copy the code

When disabled, only parameters can be obtained from POST, _POST, POST, _GET, and $_REQUEST.

4. File system restrictions

You can use open_basedir to limit the system directories that PHP can access.

If you do not restrict the use of the following script (hack.php) to obtain the system password.


      

echo file_get_contents('/etc/passwd');
Copy the code

If this parameter is set, an error message will be displayed, so that system directory B will not be accessed illegally:

PHP Warning: file_get_contents(): open_basedir restriction in effect. File(/etc/passwd) is not within the allowed path(s): (/var/www) in /var/www/hack.php on line 3
Copy the code
Warning: file_get_contents(): open_basedir restriction in effect. File(/etc/passwd) is not within the allowed path(s): (/var/www) in /var/www/hack.php on line 3 PHP Warning: file_get_contents(/etc/passwd): failed to open stream: Operation not permitted in /var/www/hack.php on line 3

Warning: file_get_contents(/etc/passwd): failed to open stream: Operation not permitted in /var/www/hack.php on line 3
Copy the code

The setting method is as follows:

open_basedir=/var/www
Copy the code

5. Disable remote resource access.

allow_url_fopen=Off  allow_url_include=Off
Copy the code

Other third-party security extensions

6. Suhosin.

Suhosin is a protected system for PHP applications. It is designed to protect servers and users from known and unknown flaws in PHP programs and PHP cores (it feels practical and can be used against minor attacks). Suhosin has two separate parts that can be used separately or in combination.

The first part is a patch for the PHP core that protects against buffer overflows or formatting string weaknesses (a must!). ;

The second part is a powerful PHP extension (good extension mode, easy to install…). , including all other protection measures.

Install the extension

wget http:/ / download.suhosin.org/suhosin-0.9.37.1.tar.gz
tar zxvf suhosin-0.9.37.1.tar.gz
cd suhosin-0.9.37.1/ phpize./configure --with-php-config=/usr/local/bin/php-config make make install extension=suhosin.soCopy the code

features

  1. Simulator protection mode
  2. Add two functions sha256() and sha256_file() to the PHP core
  3. For all platforms, add CRYPT_BLOWFISH to function crypt()
  4. Turn on transparent protection for phpInfo () pages
  5. SQL database user protection

Runtime protection

Encrypting cookies to prevent different kinds of inclusion vulnerabilities (remote urls are not allowed to include (black/white list); Not allowed to include uploaded files; Prevent directory traversal attacks) Allows to disable preg_replace() allows to disable the eval() function by configuring a maximum execution depth, To prevent infinite recursion support for each vhost configuration whitelist provides separate function whitelist for code execution prevent HTTP response split vulnerability prevent scripts control memory_limit options protect PHP superglobals, such as function extract(), Import_request_vars () prevents newline attacks from the mail() function

The Session to protect

Encrypting session data Prevents session hijacking Prevents excessively long session ids prevents malicious session ids

SESSION data is usually stored in clear text on the server. $_SESSION is encrypted and decrypted on the server side. In this way, the Session handle stored in Memcache or database will not be easily broken. In many cases, the Session data will store some sensitive fields.

This feature is enabled by default and can be modified via php.ini:

suhosin.session.encrypt = On
suhosin.session.cryptkey = zuHywawAthLavJohyRilvyecyondOdjo
suhosin.session.cryptua = On
suhosin.session.cryptdocroot = On

;; IPv4 only
suhosin.session.cryptraddr = 0
suhosin.session.checkraddr = 0
Copy the code

Cookies are encrypted

Cookies transmit HTTP headers in the client browser in clear text. By encrypting cookies, you can protect your application against numerous attacks such as

Cookie tampering: An attacker may try to guess other reasonable Cookie values to attack a program. Using cookies across applications: Improperly configured applications may have the same session store, such as all sessions stored in the/TMP directory by default, and cookies from one application may never be reused for another application as long as the encryption key is different.

Cookie encryption in php.ini:

suhosin.cookie.encrypt = On

;; the cryptkey should be generated, e.g. with 'apg -m 32'
suhosin.cookie.cryptkey = oykBicmyitApmireipsacsumhylWaps1
suhosin.cookie.cryptua = On
suhosin.cookie.cryptdocroot = On

;; whitelist/blacklist (use only one)
;suhosin.cookie.cryptlist = WALLET,IDEAS
suhosin.cookie.plainlist = LANGUAGE

;; IPv4 only
suhosin.cookie.cryptraddr = 0
suhosin.cookie.checkraddr = 0Blocking Functions provides testThe default PHP Session is stored in TMP
ll  -rt /tmp | grep sess
View sesson data when the extension is not enabled
cat  sess_ururh83qvkkhv0n51lg17r4aj6
// Records are in plaintext
## View sesson data after the extension is enabled
cat  sess_ukkiiiheedupem8k4hheo0b0v4
// Records are ciphertextYou can see the importance of encryption for securityCopy the code

Stop function

White list

## Explicitly specifies the specified whitelist list
suhosin.executor.func.whitelist = htmlentities,htmlspecialchars,base64_encode
suhosin.executor.eval.whitelist = htmlentities,htmlspecialchars,base64_encode


      
echo htmlentities('<test>');
eval('echo htmlentities("
      
       "); '
      );
Copy the code

The blacklist

## Explicitly specify the specified blacklist list
suhosin.executor.func.blacklist = assert,unserialize,exec,popen,proc_open,passthru,shell_exec,system,hail,parse_str,mt_srand
suhosin.executor.evalWhitelist = assert, unserialize, exec, popen, proc_open, passthru, shell_exec, system, hail, parse_str, mt_srand to log to check illegal call black and white list suhosin.simulation =1
suhosin.log.file = 511
suhosin.log.file.name = /tmp/suhosin-alert.log
Copy the code

Other Configuration Items

suhosin.executor.includeMax_traversal The maximum depth of a directory that can be traversed without switching to an illegal path suhosin.executor.include.whitelist Contains urls that are allowed, suhosin.executor separated by commas.includeThe urls that are prohibited by a blacklist are separated by commas (,). Suhosin.executor. Disable_eval = On Is disabledevalMax_uploads suhosin.upload.disallow_elf suhosin.upload.disallow_binary suhosin.upload.remove_binary Suhosin. Upload. Verification_script check script upload files, you can upload to detect whether the contents of the include webshell characteristicsCopy the code

With Suhosin, you can get error logs, which you can write to the system log or to any other log file.

It can also create a blacklist and whitelist for each virtual host;

Filter GET and POST requests, file uploads, and cookies;

You can also send encrypted sessions and cookies, set up untransmittable storage, and so on.

Unlike the original PHP enhancement patch, Suhosin is compatible with third-party extensions like Zend Optimizer.

The above content hopes to help you, more free PHP factory PDF, PHP advanced architecture video materials, PHP wonderful good article can be wechat search concerns: PHP open source community

2021 Jinsanyin four big factory interview real questions collection, must see!

Four years of PHP technical articles collation collection – PHP framework

A collection of four years’ worth of PHP technical articles – Microservices Architecture

Distributed Architecture is a four-year collection of PHP technical articles

Four years of PHP technical essays – High Concurrency scenarios

Four years of elite PHP technical article collation collection – database