Home >Backend Development >PHP Tutorial >PHP anti-injection configuration and php anti-injection code_PHP tutorial

PHP anti-injection configuration and php anti-injection code_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:11:001004browse

There are two types of anti-injection in php. One is sql anti-injection. The other is a process like many cms that all submitted variables. The other is to configure php.ini directly. I will introduce them to you below. introduce.

1. Pass safe.func.php to the directory of the file to be included

2. There are two ways to add protection to the page. You can choose one according to the situation:

a). Add code to the page that needs protection

require_once('safe.func.php');
You can achieve page injection prevention and cross-site
If you want to prevent injection for the entire site, just put it in a public file on the website, such as the database link file config.inc.php!
Add require_once('safe.func.php'); to call this code

safe.func.php code is as follows:

The code is as follows Copy code
 代码如下 复制代码

/**
* 防注入
*
* "

操作IP: ".$_SERVER["REMOTE_ADDR"]."
操作时间: ".strftime("%Y-%m-%d %H:%M:%S")."
操作页面:".$_SERVER["PHP_SELF"]."
提交方式: ".$_SERVER["REQUEST_METHOD"]."
提交参数: ".$StrFiltKey."
提交数据: ".$StrFiltValue);
 */

function safe_custom_error($errno, $errstr, $errfile, $errline) {
 echo "Error number: [$errno],error on line $errline in $errfile
";
 die();
}


set_error_handler("safe_custom_error", E_ERROR);

function safe_stop_attack($k, $v, $method=0) {
 $filter = array(
  "'|(and|or).+?(>|<|=|in|like)|/*.+?*/| "(and|or).{1,6}?(=|>|<|in|like)|/*.+?*/| );

$filter = isset($filter[$method]) ? $filter[$method] : $filter[0];

if(is_array($v)) {
$v = implode($v);
}
if (preg_match("/" . $filter . "/is", $v) == 1) {
exit("本次操作已记录。请不要继续非法操作。");
}
}

if (isset($_GET)) {
foreach($_GET as $k => $v) safe_stop_attack($k, $v, 0);
}
if (isset($_POST)) {
 foreach($_POST as $k => $v) safe_stop_attack($k, $v, 1);
}
if (isset($_COOKIE)) {
 foreach($_COOKIE as $k => $v) safe_stop_attack($k, $v, 1);
}

/**

* Anti-injection
代码如下 复制代码

/* 过滤所有GET过来变量 */
foreach ($_GET as $get_key=>$get_var)
{
if (is_numeric($get_var)) {
$get[strtolower($get_key)] = get_int($get_var);
} else {
$get[strtolower($get_key)] = get_str($get_var);
}
}
/* 过滤所有POST过来的变量 */
foreach ($_POST as $post_key=>$post_var)
{
 if (is_numeric($post_var))
 {
  $post[strtolower($post_key)] = get_int($post_var);
 }
 else
 {
  $post[strtolower($post_key)] = get_str($post_var);
 }
}
/* 过滤函数 */
//整型过滤函数
function get_int($number)
{
 return intval($number);
}
//字符串型过滤函数
function get_str($string)
{
 if (!get_magic_quotes_gpc())
 {
  return addslashes($string);
 }
 return $string;
}
?>

* * "

Operation IP: ".$_SERVER["REMOTE_ADDR"]."
Operation time: ".strftime("%Y-%m-%d %H:%M: %S")."
Operation page:".$_SERVER["PHP_SELF"]."
Submission method: ".$_SERVER["REQUEST_METHOD"]."
Submission parameters: " .$StrFiltKey."
Submit data: ".$StrFiltValue); ​*/ function safe_custom_error($errno, $errstr, $errfile, $errline) { echo "Error number: [$errno],error on line $errline in $errfile
"; die(); } set_error_handler("safe_custom_error", E_ERROR); function safe_stop_attack($k, $v, $method=0) { $filter = array( "'|(and|or) .+?(>|<|=|in|like)|/*.+?*/| " (and|or) .{1,6}?(=|>|<| in | like )|/*.+?*/| );<🎜> <🎜> $filter = isset($filter[$method]) ? $filter[$method] : $filter[0];<🎜> <🎜> if(is_array($v)) {<🎜> $v = implode($v);<🎜> }<🎜> if (preg_match("/" . $filter . "/is", $v) == 1) {<🎜> exit("This operation has been recorded. Please do not continue illegal operations.");<🎜> }<🎜> }<🎜> <🎜>if (isset($_GET)) {<🎜> foreach($_GET as $k => $v) safe_stop_attack($k, $v, 0); } if (isset($_POST)) { foreach($_POST as $k => $v) safe_stop_attack($k, $v, 1); } if (isset($_COOKIE)) { foreach($_COOKIE as $k => $v) safe_stop_attack($k, $v, 1); } The above is more suitable for preventing SQL injection
The code is as follows Copy code
/* Filter all GET variables */<🎜> foreach ($_GET as $get_key=>$get_var) { if (is_numeric($get_var)) { $get[strtolower($get_key)] = get_int($get_var); } else { $get[strtolower($get_key)] = get_str($get_var); } } /* Filter all POST variables */ foreach ($_POST as $post_key=>$post_var) { if (is_numeric($post_var)) { $post[strtolower($post_key)] = get_int($post_var); } else { $post[strtolower($post_key)] = get_str($post_var); } } /* Filter function */ //Integer filter function function get_int($number) { return intval($number); } //String filter function function get_str($string) { if (!get_magic_quotes_gpc()) { return addslashes($string); } return $string; } ?>

In addition to preventing injection directly in php, we can also configure the php.ini file

. We first use any editing tool to open /usr/local/php/etc/php.ini. If you install it in other ways, the configuration file may not be in this directory. ​

(1) Turn on PHP’s safe mode PHP’s safe mode is a very important built-in security mechanism that can control some functions in PHP, such as system(),

At the same time, the permissions of many file operation functions are controlled, and certain key files, such as /etc/passwd, are not allowed.
​But the default php.ini does not open safe mode, let’s open it:
​safe_mode = on


(2) User group security


When safe_mode is turned on, safe_mode_gid is turned off, then the php script can access the file, and the same
Users in the group can also access the file.
It is recommended to set it to:


safe_mode_gid = off If we do not set it, we may not be able to operate the files in our server website directory. For example, we need
When operating on files.


(3) Execute program home directory in safe mode


If safe mode is turned on but you want to execute certain programs, you can specify the home directory of the program to be executed:


​safe_mode_exec_dir = D:/usr/bin


Under normal circumstances, there is no need to execute any program, so it is recommended not to execute the system program directory. You can point to a directory,
Then copy the program that needs to be executed, such as:


​safe_mode_exec_dir = D:/tmp/cmd


However, I recommend not to execute any program, then you can point to our web directory:


​safe_mode_exec_dir = D:/usr/www


(4) Include files in safe mode


If you want to include some public files in safe mode, then modify the options:


safe_mode_include_dir = D:/usr/www/include/ In fact, generally the files included in PHP scripts have been written in the program itself. This can be set according to specific needs.


(5) Control the directories that php scripts can access


Use the open_basedir option to control the PHP script to only access the specified directory, which can prevent the PHP script from accessing
Files that should not be accessed limit the harm of phpshell to a certain extent. We can generally set it to only access the website directory:


open_basedir = D:/usr/www


(6) Close dangerous functions


If safe mode is turned on, function prohibition is not necessary, but we still consider it for safety. For example,
We feel that we do not want to execute PHP functions including system() that can execute commands, or that can view PHP information
phpinfo() and other functions, then we can disable them:


Disable_functions = system, passthru, exec, shell_exec, popen, phpinfo If you want to prohibit any file and directory operations, you can turn off many file operations


disable_functions = chdir,chroot,dir,getcwd,opendir,readdir,scandir,fopen,unlink,delete,copy,mkdir, rmdir,rename,file,file_get_contents,fputs,fwrite,chgrp,chmod,chown


The above only lists some of the commonly used file processing functions. You can also combine the above execution command function with this function,
It can resist most phpshells.


(7) Close the leakage of PHP version information in the http header


In order to prevent hackers from obtaining the PHP version information in the server, we can turn off the information in the http header:


Expose_php = Off For example, when a hacker telnet www.12345.com 80, he will not be able to see PHP information.


(8) Close registration of global variables


Variables submitted in PHP, including those submitted using POST or GET, will be automatically registered as global variables and can be accessed directly,
This is very unsafe for the server, so we can’t register it as a global variable, so we turn off the register global variable option:
​register_globals = Off
Of course, if this is set, then reasonable methods must be used to obtain the corresponding variables, such as obtaining the variable var submitted by GET,
Then you must use $_GET['var'] to obtain it. PHP programmers should pay attention to this.


(9) Turn on magic_quotes_gpc to prevent SQL injection


SQL injection is a very dangerous problem. It can cause the website backend to be invaded, or the entire server to fall.


So be careful. There is a setting in php.ini:


​magic_quotes_gpc = Off


This is turned off by default. If it is turned on, it will automatically convert the SQL query submitted by the user,
For example, converting ‘ to ‘ etc., this plays a significant role in preventing sql injection. So we recommend setting it to:


​magic_quotes_gpc = On


(10) Error message control


Generally, php will prompt an error when it is not connected to the database or under other circumstances. Generally, the error message will contain the php script when
The previous path information or the query SQL statement and other information are not safe after this type of information is provided to hackers, so it is generally recommended that the server disable error prompts:


display_errors = Off If you want to display error messages, be sure to set the level of display errors, such as only displaying information above warnings:


​error_reporting = E_WARNING & E_ERROR​ Of course, I still recommend turning off the error prompt.


(11) Error log


It is recommended to record the error information after closing display_errors to facilitate finding the reason for the server operation:


Log_errors = On At the same time, you must also set the directory where the error log is stored. It is recommended that the root apache log be stored together:


​error_log = D:/usr/local/apache2/logs/php_error.log​ Note: The file must be given to allow the apache user and group to have write permissions.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629619.htmlTechArticleThere are two types of anti-injection in php, one is sql anti-injection, and the other is a process like many cms For all submitted variables, there is another way to configure php.ini directly. I will tell you respectively below...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn