Php security configuration records and common errors

Source: Internet
Author: User
Tags http 200 openlog symlink
After the php environment is deployed, some security settings are made. in addition to being familiar with various php vulnerabilities, you can also configure php. ini to reinforce the runtime environment of PHP, and PHP has been officially modified for many times. the default settings of ini. After the php environment is deployed, some security settings are made. in addition to being familiar with various php vulnerabilities, you can also configure php. ini to reinforce the runtime environment of PHP, and PHP has been officially modified for many times. the default settings of ini.

The following describes the configuration of some security-related parameters in php. ini.

When register_globals is register_globals = ON, PHP does not know where the variable comes from, and is prone to variable overwrites. Therefore, from the perspective of best practices, it is strongly recommended to set register_globals = OFF, which is also the default setting in the new PHP version. Open_basediropen_basedir can restrict PHP to operate only files in the specified directory. This is useful in defending against attacks such as file inclusion and directory traversal. you should set a value for this option. Note that if the set value is a specified directory, you need to add "/" at the end of the Directory. Otherwise, it will be considered as the prefix of the Directory. Open_basedir =/home/web/html/allow_url_include = Off to prevent remote file inclusion, disable this option. this option is not available for general applications. We recommend that you disable allow_url_fopen. Display_errors = Off error Echo, which is usually used in development mode. However, many applications forget to disable this option in the formal environment. Error Echo can expose a large amount of sensitive information to facilitate the next attack. Disable this option. Log_errors = On can be used in the official environment to record the error information in the log. You can disable error echo. It is recommended to disable magic_quotes_gpc = Off. it is not worth relying on (see the "injection attack" chapter). several methods are available to bypass it, even because of its existence, some new security problems arise. Vulnerabilities such as XSS and SQL injection should be solved by the application in the correct place. Disabling it also improves performance. Cgi. fix_pathinfo = 0 if PHP is installed using CGI, disable this option to avoid file parsing problems (see the "file Upload vulnerability" chapter ). Session. cookie_httponly = 1 enable HttpOnly session. cookie_secure = 1 enable this option for full-site HTTPS. Whether SQL. safe_mode = Off PHP's security mode should be enabled remains controversial. On the one hand, it will affect many functions; on the other hand, it is difficult to choose because it is constantly bypassed by hackers. If it is a shared environment (such as App Engine), we recommend that you enable safe_mode for use with disable_functions. if it is a separate application environment, you can disable it, it depends more on disable_functions to control the running environment security. Disable_functions = the function can be disabled in PHP (nothing is configured after the above default = ). This is a double-edged sword. disabling a function may cause inconvenience to development. However, disabling too few functions may increase the chance of developing insecure code and facilitate hackers to obtain webshells. In general, if it is an independent application environment, we recommend that you disable the following functions: disable_functions = escapeshellarg, role, exec, passthru, proc_close, proc_get_status, proc_open, proc_nice, proc_terminate, shell_exec, ini_restore, popen, dl, disk_free_space, diskfreespace, kernel, tmpfile, fopen, readfile, fpassthru, fsockopen, mail, ini_alter, highlight_file, openlog, show_source, symlink, example, apache_getenv, apache_note, apache_setenv, parse_ini_file

Uploading large files in php involves configuring the upload_max_filesize and post_max_size options.

Once encountered a problem: a very strange problem occurred when uploading images in the website background. sometimes the value can be obtained after submitting a form, and sometimes the value cannot be obtained, I couldn't even get the common fields, and thought it was not solved. I finally asked the master, but the master said it was strange. then I asked if the value of upload_max_filesize was changed, I said it was changed, and the master cannot solve it. After a while, the master asked if post_max_size was changed. I said it had nothing to do with the upload. the master did not care about me. I still continued the test based on my own ideas. after a long time, I still couldn't do it, finally, I tried my opinion and succeeded. the original upload was related to post_max_size. Problem Summary: php. the default file upload size in the ini configuration file is 2 M, and the default upload_max_filesize = 2 M, that is, the file upload size is 2 M. If you want to upload files larger than 8 M, such as 20 M, you must set upload_max_filesize to 20 M. However, if you set upload_max_filesize = 20 m, you still cannot upload large files. you must modify php. the post_max_size option in the ini configuration file, which indicates the maximum length of bytes allowed for POST data. the default value is 8 MB. If the POST data exceeds the limit, $ _ POST and $ _ FILES will be empty. To upload a large file, you must set the option value to be greater than the value of the upload_max_filesize command. I usually set the value of upload_max_filesize to be equal to that of post_max_size. In addition, if the memory limit is enabled, this value should be smaller than the value of the memory_limit option. Other considerations for file upload: when uploading a large file, you may feel slow uploading. if the upload speed exceeds a certain period of time, an error occurs that the script is executed for more than 30 seconds. in the ini configuration file, the max_execution_time configuration option is incorrect. it indicates the maximum allowed execution time (in seconds) of each script, and 0 indicates no limit. You can adjust the value of max_execution_time appropriately. it is not recommended to set it to 0. **************************************** **************************************** * *********************** Explanation: for details, see [PHP. ini core configuration option description] maximum size of the file uploaded by upload_max_filesize. Post_max_size: set the maximum size allowed by POST data. Memory_limit specifies the maximum number of memory bytes that a script can apply. Generally, memory_limit> post_max_size> upload_max_filesize limits the maximum value of this Upload. post_max_size indicates the maximum value of post data. The maximum value of data submitted through POST is usually used for POST Upload in php.

Parameters for recording php error logs in PHP. ini: display_errors and log_errors

1) display_errors error Echo, which is commonly used in development mode. However, many applications forget to disable this option in the formal environment. Error Echo can expose a large amount of sensitive information to facilitate the next attack. Disable this option. Display_errors = when On is enabled, if an error occurs, an error is returned. All error messages are displayed. When dispaly_errors = Off is disabled, if an error occurs, the system prompts: server error, but no error prompt appears. Disable all error messages. 2) use log_errors in the official environment and record the error information in the log. You can disable error echo. Log_errors = On // note that after log_errors is set to On, dispaly_errors must be set to Off, which cannot be enabled at the same time. Error_log =/Data/logs/php/error. log // Note: When log_errors is set to On, you must set the log file path of error_log and the log file must have the permission to write normally. That is to say, when log_errors = On, the error_log file must be specified. if the specified file is not specified or the specified file does not have the write permission, the file will still be output to the normal output channel, in this case, the specified Off of display_errors is invalid, and the error message is printed. For PHP developers, once the project is launched, the first thing is to disable the display_errors option, this prevents hackers from attacking the paths, database connections, data tables, and other information exposed by these errors. ------------------------------------------------- Php in the Test environment. error log settings in ini: error_reporting = E_ALL display_errors = On html_errors = On log_errors = Off php in the official environment. error log settings in ini: error_reporting = E_ALL &~ E_NOTICE &~ E_WARNING // pay attention to this setting. remember that this setting is incorrect once, leading to an error in nginx 500 during online business access! This leads to an error in the php framework! Display_errors = Off log_errors = On html_errors = Off error_log =/Data/logs/php/error. log ignore_repeated_errors = On ignore_repeated_source = On briefly explains the meaning of each configuration: error_reporting: sets which errors are reported display_errors: Sets whether the error is shown as part of the output html_errors: set whether the error message is in the html format log_errors: set whether to record the error message error_log: Set the file ignore_repeated_errors for the error information record: whether the same error message ignore_repeated_source is repeatedly displayed in the same: whether to repeatedly display code errors from the same file

By the way, the php page always reports the time zone error handling process:

Warning: phpinfo (): It is not safe to rely on the system's timezone settings. you are * required * to use the date. timezone setting or the date_default_timezone_set () function. in case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. 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 modify 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 that php is required. copy the ini file to/usr/local/php/lib/. Otherwise, the php service will read php under the lib directory by default. ini file, if not, it is the default time zone UTC, which is 8 hours different from Beijing time. [Root @ I-gxcmjlge lib] # pwd/usr/local/php/lib [root @ I-gxcmjlge lib] # ll total 72 drwxr-xr-x 14 root 4096 Nov 18 php-rw-r -- 1 root 65681 Nov 18 php. ini and then restart the php service and nginx/apache service.

In addition to the php. ini file, pay attention to 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, by default var/run/php-fpm.pid in the installation directory, we recommend that you enable error_log = log/php-fpm.log // error log, by default, var/log/php-fpm.log log_level = notice // error level in the installation directory. available level: alert (must be handled immediately), error (error), warning (warning), notice (important information), debug (debugging information ). default value: notice. emergency_restart_threshold = 60 emergency_restart_interval = 60 s // indicates If the number of php-cgi processes with SIGSEGV or SIGBUS errors within the cy_restart_interval value exceeds emergency_restart_threshold, php-fpm restarts elegantly. These two options are generally kept by default. Process_control_timeout = 0 // Set the timeout time for the sub-process to receive the multiplexing signal of the main process. available unit: s (seconds), m (minutes), h (hours), or d (days) default unit: s (seconds ). default value: 0. daemonize = yes // fpm is executed in the background. the default value is yes. you can change it to no for debugging. In FPM, you can use different settings to run multiple process pools. These settings can be set separately for each process pool. [Www] user = nobody // account for starting the process group = nobody // The listen group for starting the process = 127.0.0.1: 9000 // fpm listening port, that is, the php address in nginx, generally, the default value is enough. Available Formats: 'Ip: port', 'port', '/path/to/unix/socket '. each process pool needs to be set. listen. backlog = 1024 // Number of backlogs, determined by the operating system.-1 indicates no limit. You can also comment out this line. Listen. allowed_clients = 127.0.0.1 // (this row can be left unspecified) allow access to the IP address of the FastCGI Process. If this parameter is not set or is null, any server is allowed to request a connection. Set any to an unlimited IP address. if you want to set nginx of other hosts to access this FPM process, set the IP address that can be accessed at a cost in listen. The default value is any. Each address is separated by commas. pm = static // for dedicated servers, pm can be set to static. for how to control sub-processes, the options are static and dynamic. If static is selected, a fixed number of sub-processes is specified by pm. max_children. If dynamic is selected, it is determined by the following parameters: pm. max_children = 512 // maximum number of child processes pm. start_servers = 387 // number of processes at startup pm. min_spare_servers = 32 // The minimum number of idle processes. if the number of idle processes is smaller than this value, a new sub-process pm is created. max_spare_servers = 387 // ensure the maximum number of idle processes. if the number of idle processes exceeds this value, clean pm. max_requests = 1024 // sets the number of service requests before each sub-process is reborn. it is very useful for third-party modules that may have memory leaks. if it is set to '0', the request is always accepted. equivalent to the PHP_FCGI_MAX_REQUESTS environment variable. default value: 0. status_path =/status // fpm status page URL. if not set, the status page cannot be accessed. default value: none. mu Nin monitoring uses ping. path =/ping // ping URL on the fpm monitoring page. if this parameter is not set, the ping page cannot be accessed. this page is used to check whether FPM is alive and can respond to requests. note that it must start with a slash (/). You can leave this line unspecified. Ping. response = pong // defines the response of the ping request. the response is in the text/plain format of HTTP 200. the default value is pong. You can leave this line unspecified. Slowlog = var/log/slow. log // logs of slow requests. use request_slowlog_timeout to use request_slowlog_timeout = 0 // to set the time-out stop time for a single request. this option may apply to php. the 'max _ execution_time 'in ini settings is not useful for stopping the running script for some special reasons. set to '0' to 'off '. you can try to change this option when 502 errors occur frequently. Request_terminate_timeout = 10 s // when a request times out, the corresponding PHP call stack information is completely written to the slow log. if it is set to '0', it indicates 'off '. You can leave this line unspecified. Rlimit_files = 65535 // Set the rlimit limit of the file opening descriptor. default value: the default value of the system defined value is 1024. you can use ulimit-n to view the limit and modify the value of ulimit-n 2048. Rlimit_core = 0 // set the maximum rlimit value of the core. available value: 'limited', 0, or positive integer. default value: System defined value. catch_workers_output = yes // redirects stdout and stderr during running to the main error log file. if not set, stdout and stderr will be redirected to/dev/null according to FastCGI rules. default value: Null.

------------------------ Restrict the site directory in Nginx + Php to prevent cross-site configuration Scheme Record (use open_basedir )-------------------

Method 1) add the following to the Nginx configuration file:

fastcgi_param PHP_VALUE "open_basedir=$document_root:/tmp/:/proc/";

Generally, include fastcgi. conf; is used in the nginx site configuration file. in this way, it is okay to add this line to fastcgi. conf.

If an additional directory needs to be set for a site, write the above code in include fastcgi. conf. in this line, the settings in fastcgi. conf will be overwritten.

This setting takes effect after nginx is restarted.

Method 2) add in 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 setting takes effect after you restart php-fpm.

Method 3) create the. user. ini file under the root directory of the website, and write the following information into the file:

open_basedir=/home/www/www.wangshibo.com:/tmp/:/proc/

In this way, you do not need to restart the nginx or php-fpm service. To ensure security, you should cancel the write permission for the. user. ini file.

The recommended function in php. ini is as follows:

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 is started, Port 9000 is unavailable? --------------------------------------------

Problem description:

After the php service is installed, start php-fpm and no error is reported during startup. Then ps-ef | grep php does not find the process, and lsof-I: 9000 does not find the port.

View the log and find that the number of files allowed to be opened by the system exceeds the predefined 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 discovery problem: [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 open files (24) [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 workflow open files (24) [15-Nov-2015 23:54:00] NOTICE: exiting, bye-bye! It is found that the number of files allowed to be opened by the system exceeds the predefined settings. You need to increase the value: [root @ i-v5lmgh7y etc] # ulimit-n 1024 [root @ i-v5lmgh7y etc] # ulimit-n 65535 // temporary solution [root @ i-v5lmgh7y etc] # ulimit-n 65535 permanent solution method: in/etc/security/limits. add the following four lines at the bottom of the 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 and then start the php-fpm program again, port 9000 can be started normally [root @ i-v5lmgh7y etc] #/us R/local/php/sbin/php-fpm [root @ i-v5lmgh7y etc] # ps-ef | grep php root 21055 1 0? 00:00:00 php-fpm: master process (/usr/local/php/etc/php-fpm.conf) nobody 21056 21055 0? 00:00:00 php-fpm: pool www nobody 21057 21055 0? 00:00:00 php-fpm: pool www

-------------------------- Below we will sort out several common problems caused by improper php configuration -----------------------------

1) if the value of request_terminate_timeout is set to 0 or too long, it may cause file_get_contents resource problems. If the remote resource response of the access request is too slow, the php-cgi process will remain stuck there without timeout. Although max_execution_time in the php. ini file can set the maximum execution time of the PHP script, this parameter does not take effect in php-cgi (php-fpm. The request_terminate_timeout parameter in the php-fpm.conf configuration file is really able to control the maximum execution time of PHP scripts. The default value of request_terminate_timeout is 0 seconds. that is to say, the PHP script will continue to be executed. In this way, when all the php-cgi processes are stuck, this Nginx + PHP WebServer can no longer process new PHP requests, and Nginx will return "502 Bad Gateway" to the user ". Modify this parameter to set the maximum execution time of a PHP script. For example, if it is changed to 30 s, if the webpage content is slow to be accessed, this means that 150 php-cgi processes can only process 5 requests per second, webServer is also difficult to avoid "502 Bad Gateway ". The solution is to set request_terminate_timeout to 10 s or a reasonable value. 2) the max_requests parameter is improperly configured and may cause intermittent 502 errors. set the number of requests for each sub-process before it is reborn. it is very useful for third-party modules that may have memory leaks. if it is set to 0, the request is always accepted, which is equivalent to the php_fcgi_max_requests environment variable. The default value is 0. for example, pm. max_requests = 1000 indicates that the process is automatically restarted when the number of requests processed by a php-cgi process reaches 500. But why do we need to restart the process? Generally, some PHP third-party libraries are used in projects. these third-party libraries often have memory leakage problems. if the php-cgi process is restarted occasionally, the memory usage will inevitably increase. Therefore, as the manager of php-cgi, php-fpm provides such a monitoring function to restart the php-cgi process with a specified number of requests to ensure that the memory usage does not increase. This mechanism often leads to 502 errors in highly concurrent sites. The current solution is to set this value as large as possible to minimize the number of php-cgi re-SPAWN requests, it also improves the overall performance. In the actual production environment, if the memory leakage is not obvious, you can set this value to a very large value (such as 204800 ). You must set this value based on your actual situation (for example, we set 1024 online) and cannot blindly increase it. In other words, the purpose of this mechanism is to ensure that php-cgi only occupies memory in different places. why not use the memory detection method? It is a better solution to restart the php-cgi process by setting the internal usage of the process peak. 3) set a timeout parameter for php-fpm slow logs, debug and exception troubleshooting tool request_slowlog_timeout, and slowlog to set the location for storing slow logs.

The above is a detailed summary of php security configuration records and common errors. For more information, see other related articles in the first PHP community!

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.