Home  >  Article  >  Backend Development  >  How to prevent sql injection in php_PHP tutorial

How to prevent sql injection in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:10:56829browse

Because SQL injection requires operating the database, it generally looks for SQL statement keywords: insert, delete, update, select, and checks whether the passed variable parameters are user-controllable and whether security processing has been done

How SQL injection works

Constructing a database query is a very straightforward process. Typically, it will be implemented along the following lines. Just for illustrative purposes, we'll assume you have one

There is a wine database table "wines", one of which is "variety" (i.e. wine type):

1. Provide a form - allow users to submit something to search for. Let's assume that the user chooses to search for wine of type "lagrein".

2. Retrieve the user's search term and save it - by assigning it to a variable like this:

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

$variety = $_POST['variety'];

$variety = $_POST['variety'];

Therefore, the value of variable $variety is now:

lagrein

3. Then, use the variable to construct a database query in the WHERE clause:
 代码如下 复制代码

$query = “SELECT * FROM wines WHERE variety=’$variety’”;

The code is as follows Copy code

$query = “SELECT * FROM wines WHERE variety=’$variety’”;

 代码如下 复制代码

SELECT * FROM wines WHERE variety=’lagrein’

So, the value of variable $query now looks like this:

The code is as follows Copy code
SELECT * FROM wines WHERE variety=’lagrein’

4. Submit the query to the MySQL server.

5. MySQL returns all records in the wines table - among them, the value of field variety is "lagrein".

By now, this should be a familiar and easy process. Unfortunately, sometimes the processes we are familiar with and comfortable with are easy

Leading us to complacency. Now, let's reanalyze the query we just constructed.
 代码如下 复制代码

$query = ” SELECT * FROM wines WHERE variety = ‘”;

1. The fixed part of the query you create ends with a single quote, which you will use to describe the beginning of the variable value:

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

$query .= $variety;

$query = ” SELECT * FROM wines WHERE variety = ‘”;

2. Use the original fixed part and contain the value of the user-submitted variable:
 代码如下 复制代码

$ query .= “‘”;

The code is as follows Copy code
$query .= $variety;
3. You then use another single quote to concatenate this result - describing the end of the variable value:
The code is as follows Copy code
$ query .= “‘”;

So, the value of $query is as follows:

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

SELECT * FROM wines WHERE variety = ‘lagrein’

SELECT * FROM wines WHERE variety = ‘lagrein’

The success of this construct relies on user input. In this example, you are using a single word (or possibly a group of words) to specify a type of wine.

So the query is constructed without any issues and the result is what you would expect - a list of wines with the wine type "lagrein". Now

Now, let’s imagine that instead of entering a simple wine type of type “lagrein”, your user enters the following (note the package

(including two punctuation marks):
 代码如下 复制代码

lagrein’ or 1=1;

The code is as follows Copy code

lagrein’ or 1=1;

 代码如下 复制代码

SELECT * FROM wines WHERE variety = ‘

Now, you continue to construct your query using the previously fixed parts (here, we only show the result value of the $query variable):

The code is as follows Copy code
SELECT * FROM wines WHERE variety = ‘
 代码如下 复制代码

SELECT * FROM wines WHERE variety = ‘lagrein’ or 1=1;

You then connect to it using the value of the variable containing the user input (shown here in bold):

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

SELECT * FROM wines WHERE variety = ‘lagrein’ or 1=1;’

SELECT * FROM wines WHERE variety = ‘lagrein’ or 1=1;
Finally, add the lower quotes above and below:
The code is as follows Copy code
SELECT * FROM wines WHERE variety = ‘lagrein’ or 1=1;’

We can prevent the above problems by writing a function.

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

/**
+----------------------------------------------------------
* 防挂马、防跨站攻击、防sql注入函数
+----------------------------------------------------------
*$date 传入的参数,要是个变量或者数组;$ignore_magic_quotes变量的魔术引用
+----------------------------------------------------------
*/
function in($data,$ignore_magic_quotes=false)
{
 if(is_string($data))
 {
  $data=trim(htmlspecialchars($data));//防止被挂马,跨站攻击
  if(($ignore_magic_quotes==true)||(!get_magic_quotes_gpc()))
  {
     $data = addslashes($data);//防止sql注入
  }
  return  $data;
 }
 else if(is_array($data))//如果是数组采用递归过滤
 {
  foreach($data as $key=>$value)
  {
    $data[$key]=in($value);
  }
  return $data;
 }
 else
 {
  return $data;
 } 
}

/**

+------------------------------------------------- ----------

* Anti-horse, anti-cross-site attack, anti-sql injection function

+------------------------------------------------- ---------- *The parameter passed in by $date must be a variable or array; the magic reference of the $ignore_magic_quotes variable +------------------------------------------------- ----------

*/

function in($data,$ignore_magic_quotes=false)
{

if(is_string($data))

{

$data=trim(htmlspecialchars($data));//Prevent being hacked and cross-site attacks

if(($ignore_magic_quotes==true)||(!get_magic_quotes_gpc()))

{

$data = addslashes($data);//Prevent sql injection

}

return $data;

}

else if(is_array($data))//If it is an array, use recursive filtering

{

foreach($data as $key=>$value)

{

$data[$key]=in($value);

}

Return $data;

}

else

{

Return $data;

}

}

When we accept the data above, we can prevent malware, cross-site attacks, and SQL injection waiting

The following will introduce security configuration on the server side
 代码如下 复制代码

safe_mode_exec_dir = D:/usr/bin

(1) Turn on the safe mode of php

 代码如下 复制代码

safe_mode_exec_dir = D:/tmp/cmd

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.
 代码如下 复制代码

safe_mode_exec_dir = D:/usr/www

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 it is the same Users in the group can also access the file. Recommended settings are: safe_mode_gid = off If we don’t set it up, we may not be able to operate the files in our server website directory. For example, we need to When operating on files. (3) The main directory of the execution program 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:
The code is as follows Copy code
safe_mode_exec_dir = D:/usr/bin
Generally, 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:
The code is as follows Copy code
safe_mode_exec_dir = D:/tmp/cmd
However, I recommend not to execute any program, then you can point to our web directory:
The code is as follows Copy code
safe_mode_exec_dir = D:/usr/www

(4) Include files in safe mode

If you want to include certain public files in safe mode, then change the options:

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

safe_mode_include_dir = D:/usr/www/include/

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

The code is as follows Copy code

open_basedir = D:/usr/www

(6) Turn off dangerous functions

If safe mode is turned on, function prohibition is not necessary, but we still consider it for safety. For example,

We don’t think we want to execute PHP functions including system() that can execute commands, or that can view PHP information

 代码如下 复制代码

disable_functions = system,passthru,exec,shell_exec,popen,phpinfo

phpinfo() and other functions, then we can ban them:

The code is as follows Copy code
disable_functions = system,passthru,exec,shell_exec,popen,phpinfo
 代码如下 复制代码

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

If you want to prohibit any file and directory operations, you can close many file operations

The code is as follows Copy code

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,

 代码如下 复制代码

expose_php = Off

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:

The code is as follows Copy code
expose_php = Off

For example, when a hacker telnet www.12345.com 80, he will not be able to see PHP information.
 代码如下 复制代码

register_globals = Off

(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 let it be registered as a global variable, so we turn off the register global variable option:
The code is as follows Copy code
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 need to use $_GET['var'] to get 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. In the smallest case, the website backend may be invaded, or in the worst case, the entire server may collapse.

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

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

magic_quotes_gpc = Off

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, convert ' to ', etc., which plays a significant role in preventing sql injection. So we recommend setting it to:
 代码如下 复制代码

magic_quotes_gpc = On

The code is as follows Copy code

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 a PHP script when

The path information before
 代码如下 复制代码

display_errors = Off

or the query SQL statement and other information are unsafe if provided to hackers, so it is generally recommended that servers disable error prompts:

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

error_reporting = E_WARNING & E_ERROR

If you want to display an error message, be sure to set the level of display error, for example, only display information above warning:

The code is as follows Copy code

error_reporting = E_WARNING & E_ERROR

Of course, I still recommend turning off error prompts.

 代码如下 复制代码

log_errors = On

(11) Error log

It is recommended to record the error information after turning off display_errors, so as to find the reason why the server is running:
 代码如下 复制代码

error_log = D:/usr/local/apache2/logs/php_error.log

The code is as follows Copy code
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:
The code is as follows Copy code
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.


MYSQL’s privilege-reduced operation

Create a new user such as mysqlstart

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

net user mysqlstart fuckmicrosoft /add

net localgroup users mysqlstart /del

Copy code

net user mysqlstart fuckmicrosoft /add

net localgroup users mysqlstart /del

Does not belong to any group

If MYSQL is installed in d:mysql, then give mysqlstart full control permissions
 代码如下 复制代码

net user apache fuckmicrosoft /add

net localgroup users apache /del

Then set the MYSQL service properties in the system service. In the login properties, select this user mysqlstart and enter the password and confirm.

Restart the MYSQL service, and then MYSQL will run with low privileges.

If apache is built on a windos platform, we need to pay attention to one thing. Apache runs with system permissions by default,

This is scary, this makes people feel very uncomfortable. Then let’s lower the permissions of apache.

ok. We created a user apche that does not belong to any group.
The code is as follows

Copy code

net user apache fuckmicrosoft /add


net localgroup users apache /del

We open the computer manager, select services, click on the properties of the apache service, we select log on, select this account, we fill in the values ​​created above

’s account and password, Restart the apache service, ok, apache is running with low permissions. In fact, we can also set the permissions of each folder so that the apache user can only perform what we want it to do, and create a for each directory. A single user who can read and write This article covers everything from the program to the database and the final WEB server configuration. You should be much safer after referring to this article. General injection There is no way to achieve it.
http://www.bkjia.com/PHPjc/629642.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629642.htmlTechArticleSQL injection requires operating the database, so it generally looks for SQL statement keywords: insert, delete, update, select, Check whether the passed variable parameters are user-controllable and whether safety measures have been taken...
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