This article mainly introduces the PHP security Configuration records and common error carding detailed, interested in the friend's reference, I hope to be helpful to everyone.
Usually after the deployment of the PHP environment will be some security settings, in addition to familiar with a variety of PHP vulnerabilities, but also through the configuration of php.ini to strengthen the environment of PHP, the official PHP has been modified several times the default settings php.ini.
The following is a description of the configuration of some of the security-related parameters in php.ini
Register_globals when register_globals = on, PHP does not know where the variable comes from and is prone to some variable coverage issues. Therefore, from a best practice standpoint, it is strongly recommended to set register_globals = OFF, which is the default setting in the new version of PHP. Open_basediropen_basedir can restrict PHP to operate only files in the specified directory. This is useful for attacks such as file containment, directory traversal, and you should set a value for this option. Note that if you set the value to be a specified directory, you need to add a "/" to the directory at the end, otherwise it will be considered a prefix for the directory. Open_basedir =/home/web/html/allow_url_include = off to combat remote file inclusion, turn off this option, which is not available for general applications. Also recommended is the closure of the Allow_url_fopen. Display_errors = off error echo, commonly used in development mode, but many applications in the formal environment also forget to turn off this option. Error echo can expose a lot of sensitive information to facilitate attackers ' next attack. It is recommended to turn this option off. Log_errors = On Use this in a formal environment and record the error message in the log. The error echo can be turned off exactly. MAGIC_QUOTES_GPC = Off is recommended to close, it is not worth relying on (refer to the "Injection Attack" chapter), there are already several methods known to bypass it, and even because of its existence, it can derive some new security problems. Vulnerabilities such as XSS, SQL injection, and so on, should be addressed by the application in the right place. It also improves performance by turning it off at the same time. Cgi.fix_pathinfo = 0 if PHP is installed as a CGI, you need to close this key to avoid file parsing problems (refer to the "File Upload Vulnerability" chapter). Session.cookie_httponly = 1 on HttpOnly session.cookie_secure = 1 If the whole station is HTTPS, turn this on. Sql.safe_mode = Off PHP security mode should open the controversy has been relatively large. On the one hand, it will affect many functions, on the other hand, it is constantly being bypassed by hackers, so it is difficult to choose. If it is a shared environment (such as app Engine), it is recommended to turn on Safe_mode, which can be used in conjunction with disable_functions, and if it is a separate application environment, consider shutting it down and relying more on disable_functions to control the operationEnvironmental safety. Disable_functions = Ability to disable functions in PHP (e.g. nothing is configured after the default = number above). This is a double-edged sword, disabling functions can be inconvenient for development, but disabling fewer functions may increase the chances of developing unsafe code, while facilitating hackers ' access to Webshell. In general, it is recommended to disable the following functions if it is a standalone application environment: Disable_functions = Escapeshellarg, Escapeshellcmd, Exec,passthru, Proc_close, proc_get_ Status, Proc_open, Proc_nice,proc_terminate, Shell_exec, System, Ini_restore, Popen, Dl,disk_free_space, Diskfreespace , Set_time_limit, Tmpfile, Fopen,readfile, Fpassthru, fsockopen, Mail, Ini_alter, Highlight_file,openlog, Show_source, Symlink, Apache_child_terminate,apache_get_modules, Apache_get_version, Apache_getenv,apache_note, Apache_setenv, Parse_ini_file
PHP uploading large files mainly involves configuring Upload_max_filesize and post_max_size two options
Once encountered the problem: in the background of the site upload a picture of a very strange problem, and sometimes form submission can get the value, sometimes it is not get, and even ordinary fields are not get, think about still not solved, finally asked the master, the teacher Read said very strange, and then asked me Upload_max_ FileSize value changed, I said changed Ah, Master also can not solve. After a while, the teacher asked Post_max_size changed, I said that and upload it doesn't matter, master did not mind me, I still follow their own ideas continue to test, get a half day or not, finally tried the advice of the master, success, the original upload is and post_max_size have relations. Summary: The default file upload size in the php.ini configuration file is 2M, the default upload_max_filesize = 2M, that is, the file upload size is 2M, if you want to upload more than 8M files, such as 20M, you must set the Upload_max_filesize = 20M. However, the light setting upload_max_filesize = 20M is not capable of uploading large files, you must modify the Post_max_size option in the php.ini configuration file, which represents the maximum byte length of data that is allowed to post, and the default is 8M. If the post data exceeds the limit, then $_post and $_files will be empty. To upload a large file, you must set the value of the option to be greater than the upload_max_filesize instruction, and I generally set the upload_max_filesize and post_max_size values equal. In addition, if memory limits are enabled, the value should be less than the value of the Memory_limit option. Other notes on file upload: When uploading large files, you will have a slow upload, and when more than a certain time, will report the script to execute more than 30 seconds of error, because in the php.ini configuration file max_execution_time configuration options in Mischief, It represents the maximum allowable execution time (in seconds) for each script, and 0 means no limit. You can adjust the value of the max_execution_time appropriately, and it is not recommended to set to 0. Explain: See the (php.ini core configuration options in the PHP manual for a description of the maximum number of files uploaded by)upload_max_filesizeSize. Post_max_size sets the maximum size allowed for POST data. Memory_limit sets the maximum number of bytes of memory that a script can request. Generally speaking: Memory_limit > Post_max_size > Upload_max_filesize upload_max_filesize is the maximum limit for this upload post_max_ Size is the maximum value of the post data, and the maximum value of the data submitted by post is typically uploaded in PHP using post
PHP error log parameters in PHP.ini: display_errors and Log_errors differences
1) Display_errors error echo, common terminology development mode, but many applications in the formal environment also forgot to turn off this option. Error echo can expose a lot of sensitive information to facilitate attackers ' next attack. It is recommended to turn this option off. Display_errors = On is on, if an error occurs, an error occurs, and a false hint appears. All error messages are displayed. Dispaly_errors = Off state, if an error occurs, the server is wrong, but the error message does not appear. Close all error messages 2) Log_errors Use this in a formal environment and record the error message in the log. The error echo can be turned off exactly. Log_errors = ON//Note that if the log_errors is set to ON, then the dispaly_errors is set to off and the two cannot be turned on at the same time. Error_log =/data/logs/php/error.log//Note that when the log_errors is set to ON, the log file path of the error_log must be set, and the log file should have permission to write correctly. That is, log_errors = ON, you must specify the Error_log file, if not specified or the specified file does not have permission to write, then will be output to the normal output channel, then the display_errors this specified off to fail, The error message is still printed out. For PHP developers, once the project is online, the first thing to do is to turn off the display_errors option to avoid hackers being hacked by the paths, database connections, data tables, and other information that these errors reveal. ---------------------------------------------------generally: Error log settings in php.ini in test environment: error_reporting = E_all Display_ Errors = on html_errors = on log_errors = off error log settings in php.ini in the formal environment: error_reporting = E_all &~ e_notice &~ e_ WARNING//Note This setting, remember one time because of this setup error, resulting in a business access to the online Nginx 500 error! This led to the PHP framework error! Display_errors = Off log_errors= on html_errors = Off Error_log =/data/logs/php/error.log Ignore_repeated_errors = on ignore_repeated_source = on simple Explain the meanings of each configuration: error_reporting: Sets which errors are reported display_errors: Sets whether errors are displayed as part of the output html_errors: Sets whether the error message is in HTML format log_errors: Set whether Log error message Error_log: Set error message record file Ignore_repeated_errors: whether to repeat the same error message in the same row Ignore_repeated_source: whether to repeatedly display errors from the same file's peer code
By the way, the PHP page always reports the time zone error processing process:
Warning:phpinfo (): It is not safe for rely on the system ' s timezone settings. You is *required* to use the Date.timezone setting or the Date_default_timezone_set () function. In case you used any of those methods and you is still getting this warning, your most likely misspelled the timezone Iden Tifier. We selected the timezone ' UTC ' for now, but please set Date.timezone to select your timezone. in/usr/local/www/zabbix2/phpinfo.php on line 2 date/time support Enabled "Olson" Timezone Database Version 2013.8 Timezone Database internal Default timezone UTC modifies php.ini file # Vim/usr/local/php/etc/php.ini ... [Date]; Defines the default timezone used by the date functions; Http://php.net/date.timezone Date.timezone = Asia/shanghai Note must be php.ini copy to/usr/local/php/lib/, otherwise the PHP service will default to this Lib Directory to read the php.ini file, no, it is the default time zone UTC, this time zone and Beijing time difference of 8 hours. [Root@i-gxcmjlge lib]# pwd/usr/local/php/lib[root@i-gxcmjlge lib]# ll total drwxr-xr-x root root 4096 Nov 18 01:11 php-rw-r--r--1 root root 65681 15:01 php.ini Then restart the PHP service and Nginx/apache service
In addition to the php.ini file, also note the php-fpm.conf configuration, as follows:
[Root@i-v5lmgh7y etc]# cat php-fpm.conf|grep-v "^;" | Grep-v "^$" [global] pid = run/php-fpm.pid//pid settings, default in the installation directory Var/run/php-fpm.pid, recommended to open Error_log = log/php-fpm.log//Error Day Var/log/php-fpm.log Log_level = notice//error level in the installation directory by default. The available levels are: alert (which must be processed immediately), error (Error condition), warning (warning condition), notice (general important information), debug (debug information). Default: Notice. Emergency_restart_threshold = Emergency_restart_interval = 60s//indicated in Emergency_restart_ If the number of php-cgi processes with SIGSEGV or sigbus errors within the values set by interval is more than Emergency_restart_threshold, PHP-FPM will be gracefully restarted. These two options generally leave the default values. Process_control_timeout = 0//sets the time-out period for the child process to accept the master process multiplexing signal. Available units: s (seconds), M (min), H (Hours), or D (day) default units: s (seconds). Default value: 0. daemonize = yes//background execution FPM, default is yes, if for debugging you can change to No. In FPM, you can use different settings to run multiple process pools. These settings can be set individually for each process pool. [www] user = nobody//START process Account Group = nobody//start the process of groups listen = 127.0.0.1:9000//FPM listening port, that is, nginx in the address of the PHP processing, the general default value can be. The available formats are: ' Ip:port ', ' Port ', '/path/to/unix/socket '. Each process pool needs to be set. Listen.backlog =//backlog number, determined by the operating system, 1 means no limit. You can also comment out this line. Listen.allowed_clients = 127.0.0.1//(Can not set thisLine) allows access to the IP of the fastcgi process and allows any server to request a connection if it is not set or is empty. Set any to No limit IP, if you want to set the other host's Nginx can also access this FPM process, listen to set the cost of the IP can be accessed. The default value is any. Each address is separated by commas. PM = static//For dedicated servers, PM can be set to static, how to control child processes, options have static and dynamic. If Static is selected, the number of fixed child processes is specified by Pm.max_children. If dynamic is selected, it is determined by the following argument: Pm.max_children = 512//child process Max Pm.start_servers = 387//Number of processes on startup pm.min_spare_servers = 32//Guaranteed Idle Process count The minimum value, if the idle process is less than this value, creates a new child process Pm.max_spare_servers = 387//guarantees the maximum number of idle processes, if the idle process is greater than this value, this is cleaned pm.max_requests = 1024// Sets the number of requests for the service before each child process is reborn. is useful for third-party modules that may have a memory leak. If set to ' 0 ', the request is always accepted. Equivalent to the PHP_FCGI_MAX_REQUESTS environment variable. Default value: 0 pm.status_path =/status The URL of the//FPM status page. If not set, the status page cannot be accessed. Default value: None. The Munin Monitor uses a ping URL to the Ping.path =/ping//fpm monitoring page. If not set, the ping page cannot be accessed. This page is used to externally detect whether FPM is alive and can respond to requests. Note that you must start with a slash (/). You can not set this line. Ping.response = Pong//is used to define the return of the ping request accordingly. Returns the Text/plain format text for HTTP 200. Default value: Pong. You can not set this line. Slowlog = var/log/slow.log//Slow request logging, mate request_slowlog_timeout Use request_slowlog_timeout = 0//Set timeout time for individual requests. This option may cause the ' max_execution_time ' in the php.ini setting to not abort for some special reasonThe script for the row is useful. Set to ' 0 ' for ' Off '. You can try changing this option when a 502 error occurs frequently. Request_terminate_timeout = 10s//When a time-out is requested for this setting, the corresponding PHP call stack information is written to the slow log. Set to ' 0 ' to indicate ' Off '. You can not set this line. Rlimit_files = 65535//Set Rlimit limit for File open descriptor. Default: System-defined value default open handle is 1024, can be viewed using ULIMIT-N, ulimit-n 2048 modified. Rlimit_core = 0//Set core Rlimit maximum limit value. Available values: ' Unlimited ', 0, or positive integer. Default value: System-defined value. Catch_workers_output = yes//redirect stdout and stderr in the run process to the primary error log file. If not set, stdout and stderr will be redirected to/dev/null according to the FASTCGI rules. Default value: Empty.
Restricting the Site Directory------------------------nginx+php prevents cross-site configuration scenario logging (using Open_basedir)-------------------
Method 1) In the Nginx configuration file, add:
Fastcgi_param php_value "open_basedir= $document _root:/tmp/:/proc/";
Usually nginx site configuration file with include fastcgi.conf, so, add this line in the fastcgi.conf is OK.
If a site needs to set up additional directories separately, write the above code in the include Fastcgi.conf, and the line below will be OK, overwriting the settings in the fastcgi.conf.
This mode of Setup requires the restart of Nginx to take effect.
Method 2) Add in the php.ini
[Host=www.wangshibo.com] Open_basedir=/home/www/www.wangshibo.com:/tmp/:/proc/[path=/home/www/www.wangshibo.com ] open_basedir=/home/www/www.wangshibo.com:/tmp/:/proc/
This mode of Setup requires a restart of php-fpm after it takes effect.
Method 3) Create the. user.ini file in the root directory of the Web site and write the following information in the file:
open_basedir=/home/www/www.wangshibo.com:/tmp/:/proc/
There is no need to restart the Nginx or PHP-FPM service in this way. For security reasons, you should cancel the Write permission for the. user.ini file.
The following functions are recommended in php.ini:
Disable_functions = Pcntl_alarm, Pcntl_fork, Pcntl_waitpid, pcntl_wait, pcntl_wifexited, pcntl_wifstopped, Pcntl_ Wifsignaled, Pcntl_wexitstatus, Pcntl_wtermsig, Pcntl_wstopsig, Pcntl_signal, Pcntl_signal_dispatch, Pcntl_get_last_ Error, Pcntl_strerror, Pcntl_sigprocmask, Pcntl_sigwaitinfo, pcntl_sigtimedwait, Pcntl_exec, pcntl_getpriority, Pcntl _setpriority, eval, Popen, PassThru, exec, System, shell_exec, Proc_open, Proc_get_status, Chroot, Chgrp, Chown, Ini_alter , Ini_restore, DL, Pfsockopen, Openlog, Syslog, Readlink, Symlink, Popepassthru, Stream_socket_server, Fsocket, chdir
----------------------------------------------after PHP started, Port 9000 is not up? --------------------------------------------
Problem Description:
PHP service after installation, start PHP-FPM, start without error. Then Ps-ef|grep PHP did not find the process up, lsof-i:9000 found that the port is not up.
Review the log and discover that the number of files allowed to open in the system exceeds the predetermined setting.
[Root@i-v5lmgh7y etc]#/usr/local/php/sbin/php-fpm [root@i-v5lmgh7y etc]# ps-ef|grep php [root@i-v5lmgh7y etc] #lsof-I : 9000 [root@i-v5lmgh7y etc]# View error log found issue: [Root@i-v5lmgh7y log]# tail-f Php-fpm.log [15-nov-2015 23:53:15] NOTICE:FPM is Running, PID 18277 [15-nov-2015 23:53:15] error:failed to prepare the stderr pipe:too many open files [15-nov-2015 23:53:16] notice:exiting, bye-bye! [15-nov-2015 23:53:59] NOTICE:FPM is running, PID 18855 [15-nov-2015 23:53:59] error:failed to prepare the stderr pipe:too many open files (24 ) [15-nov-2015 23:54:00] notice:exiting, bye-bye! The discovery is that the system allows the number of open files to exceed the predetermined setting. This value needs to be adjusted: [root@i-v5lmgh7y etc]# ulimit-n 1024x768 [root@i-v5lmgh7y etc]# ulimit-n 65535//temporary solution [Root@i-v5lmgh7y etc]# Uli Mit-n 65535 Permanent workaround: Add the following four lines of content at the bottom of the/etc/security/limits.conf file: [root@i-v5lmgh7y etc]# cat/etc/security/limits.conf ..... .... # End of File * Soft Nproc unlimited * hard nproc Unlimited * Soft nofile 65535 * Hard nofile 65535 then start the PHP-FPM program again, The 9000 port will start normally. [RoOt@i-v5lmgh7y etc]#/usr/local/php/sbin/php-fpm [root@i-v5lmgh7y etc]# ps-ef|grep php root 21055 1 0 00:12? 00:00:00 Php-fpm:master Process (/usr/local/php/etc/php-fpm.conf) Nobody 21056 21055 0 00:12? 00:00:00 Php-fpm:pool www Nobody 21057 21055 0 00:12? 00:00:00 Php-fpm:pool www
----------------------------below to comb a few common PHP improper configuration caused by the problem-----------------------------
1) If the value of Request_terminate_timeout is set to 0 or too long, it may cause problems with file_get_contents resources. If the remote resource that accesses the request reacts too slowly, the php-cgi process will remain stuck there and will not time out. Although the max_execution_time in the php.ini file can set the maximum execution time for PHP scripts, this parameter does not work in php-cgi (PHP-FPM). The real ability to control the maximum execution time of a PHP script is the request_terminate_timeout parameter in the php-fpm.conf configuration file. The default value for Request_terminate_timeout is 0 seconds, meaning that the PHP script will continue to execute. So when all the php-cgi process is stuck, this nginx+php webserver can no longer handle the new PHP request, Nginx will return to the user "502 Bad Gateway". To modify this parameter, it is necessary to set the maximum execution time for a PHP script, but the symptom is not a cure. For example, to 30s, if the access to get Web page content is slow, this means that 150 php-cgi process, only 5 requests per second, webserver also difficult to avoid "502 bad Gateway." The workaround is to set the request_terminate_timeout to 10s or a reasonable value. 2) Improper configuration of the max_requests parameter may cause intermittent 502 errors to set the number of requests for the service before each child process is reborn. is useful for third-party modules that may have a memory leak. If set to 0, the request is always accepted, equivalent to the php_fcgi_max_requests environment variable. The default value is 0. For example: pm.max_requests = 1000 This configuration means that the process is automatically restarted when the number of requests processed by a php-cgi process accumulates to 500. But why restart the process? Generally in the project, more or less will use some PHP third-party libraries, these third-party libraries often have a memory leak problem, if you do not periodically restart the php-cgi process, it is bound to cause memory usage is increasing. So php-fpm, as the manager of PHP-CGI, provides a monitoring function that restarts the PHP-CGI process that requests a specified number of times to ensure that the amount of memory is not increased. It is because of this mechanism, in high-concurrency sites, often lead to 502 of errors, the current solution is to set this value as large as possible, to minimize the number of php-cgi re-spawn,It can also improve overall performance. In the actual production environment, it is found that if the memory leak is not obvious, the value can be set very large (for example, 204800). To set this value according to your own situation (for example, we set 1024 on the line), can not blindly increase. In other words, the purpose of this mechanism is only to ensure that the php-cgi does not take up too much memory, so why not handle it by detecting memory? Restarting the php-cgi process by setting the peak intrinsic consumption of the process can be a better solution. 3) php-fpm slow log, Debug and exception troubleshooting artifact Request_slowlog_timeout set a timeout parameter, Slowlog set the slow log storage location
The above is the whole content of this article, I hope that everyone's study has helped.