CEH Module 15: SQL Injection

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Password Grabbing

'+login+'/'+password+'

Blind SQL Injection: Boolean Exploitation

(sometimes called inferential SQL Injection) this is performed by asking the right questions to the application database

Perform Double Blind SQL Injection—Classical Exploitation (MySQL)

Also called time-based SQL injection In this SQL injection technique, entries are read symbol by symbol. In a typical attack, the functions benchmark() and sleep() are used to process the time delays.

Find & Bypass Admin Panel of a Website

Attackers try to find the admin panel of a website using simple Google dorks and bypass the administrator authentication using SQL injection attack An attacker generally uses Google dorks to find the URL of an admin panel

Out-of-Band SQL Injection

Attackers use different communication channels (such as database email functionality, or file writing and loading functions) to perform the attack and obtain the results difficult to perform because the attacker needs to communicate with the server and acquire features of the database server used by the web application. Attackers use DNS and HTTP requests to retrieve data from the database server

Bypass Website Logins Using SQL

Bypassing website logins is a fundamental and common malicious activity that an attacker can perform by using SQL injection. This is the easiest way to exploit any SQL injection vulnerability of the application. website login forms: o admin' -- o admin' # o admin'/* o ' or 1=1-- o ' or 1=1# o ' or 1=1/* o ') or '1'='1-- o ') or ('1'='1--

Evasion Technique: In-line Comment

Evasion technique is successful when a signature filters white spaces in the input string Obscures input strings by inserting in-line comments between SQL keywords.

HTTP POST Request

HTTP POST Request carries the requested data as a part of the message body. Thus, it is considered more secure than HTTP GET

Evasion Technique: URL Encoding

It is performed by replacing the characters with their ASCII code in hexadecimal form preceding each code point with a percent sign "%".

Interacting with OS

Read/Write System Files from disk Remote shell cmd

Network Reconnaissance

Reverse DNS lookups Reverse Ping OPENROWEST xp_cmdshell

SQL Injection & Server-side Technologies

Server-side technology smoothly accesses, delivers, stores, and restores information. Include -ASP -ASP.Net -Cold Fusion -JSP -PHP -Python -Ruby on Rails.

Perform Blind SQL Injection

o Exploitation (MySQL) o Extract database user o Extract database name o Extract column name o Extract data from ROWS

jSQL injection

A Java application for automatic SQL database injection. It is a lightweight application used to find database information from a distant server. Features o Multiple injection strategies: Normal, Error, Blind, and Time o Multiple injection structures: Standard, Zipped, Dump In One Shot o SQL engine to study and optimize SQL expressions o Injection of multiple targets o Creation and visualization of Web shell and SQL shell o Read and write files on host using injection

Even More Countermeasures to defend against SQL

Apply least privilege rule to run the applications that access the DBMS Validate user-supplied data as well as data obtained from untrusted sources on the server side Avoid quoted/delimited identifiers as they significantly complicate all whitelisting, black-listing and escaping efforts Use a prepared statement to create a parameterized query to block the execution of query Ensure that all user inputs are sanitized before using them in dynamic SQL statements Use regular expressions and stored procedures to detect potentially harmful code Avoid the use of any web application which is not tested by web server Isolate the web server by locking it in different domains Ensure all software patches are updated regularly Regular monitoring of SQL statements from database-connected applications to identify malicious SQL statements Use of Views should be necessary to protect the data in the base tables by restricting access and performing transformations Disable shell access to the database Do not disclose database error information to the end users Use safe API that offers a parameterized interface or that avoids the use of the interpreter completely

Countermeasures to Defend Against SQL Injection

Make no assumptions about the size, type, or content of the data that is received by your application Test the size and data type of input and enforce appropriate limits to prevent buffer overruns Test the content of string variables and accept only expected values Reject entries that contain binary data, escape sequences, and comment characters Never build Transact-SQL statements directly from user input and use stored procedures to validate user input Implement multiple layers of validation and never concatenate user input that is not validated Avoid constructing dynamic SQL with concatenated input values Ensure that the Web config files for each application do not contain sensitive information Use most restrictive SQL account types for applications Use Network, host, and application intrusion detection systems to monitor the injection attack

More Countermeasures to Defend Against SQL Injection

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 In the absence of parameterized API, use specific escape syntax for the interpreter to eliminate the special characters Use a secure hash algorithm such as SHA256 to store the user passwords rather than in plaintext Use data access abstraction layer application to enforce secure data access across an entire Ensure that the code tracing and debug messages are removed prior to deploying an application Design the code in such a way it traps and handles exceptions appropriately

Source Code Analysis Tools

Veracode (https://www.veracode.com) RIPS (http://rips-scanner.sourceforge.net) PVS studio (https://www.viva64.com) Coverity Code Advisor (https://scan.coverity.com) Parasoft Test (https://www.parasoft.com) CAST Application Intelligence Platform (AIP) (http://www.castsoftware.com) Klocwork (https://www.klocwork.com) SONAR Qube (https://www.sonarqube.org) Flawfinder (https://www.dwheeler.com) Roslyn Security Guard (https://dotnet-security-guard.github.io) FlexNet Code Insight (https://www.flexera.com) Find Security Bugs (http://find-sec-bugs.github.io) Brakeman (https://brakemanscanner.org) php-reaper (https://github.com) Yasca (http://www.scovetta.com) VisualCodeGrepper (https://sourceforge.net)

Testing MySQL & MSSQL

An attacker can identify blind SQL injection vulnerabilities just by testing the URLs of a target website. For example, consider the following URL: *shop.com/items.php?id=101* The corresponding SQL query is *( SELECT * FROM ITEMS WHERE ID = 101* )* Now, give a malicious input such as 1=0, to perform blind SQL injection *shop.com/items.php?id=101 and 1=0* The resultant SQL query is *( SELECT * FROM ITEMS WHERE ID = 101 AND 1 = 0 )* The above query will always return FALSE because 1 never equals to 0. Now, attackers try to obtain TRUE result by injecting 1=1 *(shop.com/items.php?id=101 and 1=1 The resultant SQL query is SELECT * FROM ITEMS WHERE ID = 101 AND 1 = 1 )* Finally, the shopping web application returns the original items page. With the above result, an attacker identifies that the above URL is vulnerable to blind SQL injection attack.

SQL Injection Query

An attacker submits a request with values that will execute normally but will return data from the database that attacker wants.

Evasion Technique: Null Byte

An attacker uses null byte (%00) character prior to a string in order to bypass detection mechanism

sqlmap

Automates the process of detecting and exploiting SQL injection flaws and taking over the database servers.Python Script, low failure rate and comes with w3af. Most important tool for injection testing/exploitation. Features o Full support for six SQL injection techniques: boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries, and out-of-band o Support to directly connect to the database without passing via an SQL injection, by providing DBMS credentials, IP address, and port and database name o Support to enumerate users, password hashes, privileges, roles, databases, tables, and columns

SQL Injection Black Box Pen Testing

Detecting SQL Injection Issues o Send single quotes and double quotes can be used as input data to finds where the user input is not sanitized Detecting Input Sanitization o Use right square bracket (the ] character) as the input data to catch instances where the user input is used as part of an SQL identifier without any input sanitization Detecting Truncation Issues o Send long strings of junk data, just as you would send strings to detect buffer overruns; this action might throw SQL errors on the page Detecting SQL Modification o Send long strings of single quote characters (or right square brackets or double quotes) o These max out the return values from REPLACE and QUOTEN

Evasion Technique: Case Variation

Due to the case-insensitive option of regular expression signatures in the filters, attackers can mix uppercase and lowercase letters in an attack vector to bypass detection mechanism.

Evasion Technique: Declare Variable

During web sessions, an attacker carefully observes all the queries that can help him/her to acquire important data from the database. Using those queries, an attacker can identify a variable that can be used to pass a series of specially crafted SQL statements to create a sophisticated injection that can easily go undetected through the signature mechanism.

Two most common types of In-Based SQL

Error-Based -Attackers intentionally insert bad input into an application causing it to throw database errors. Union SQL - an attacker uses a UNION clause to append a malicious query to the requested query -attacker checks for the UNION SQL Injection vulnerability by adding a single quote character (') to the end of a ".php? id=" command.

Examples of Web Apps Vulnerable to SQL Injection

For example, the following text entered into the txtFilter textbox may reveal the names of the user tables in the database: The UNION statement in particular is useful to a hacker because it splices the results of one query into another UNION SELECT id, name, '', 0 FROM sysobjects WHERE xtype ='U' -- BadProductList.aspx CertifiedHackerShop.com

SQL Injection Vulnerability Detection

Function testing -a type of software testing technique, where a software or a system is tested against a set of inputs according to the end user's needs. Fuzzing Testing -It is an adaptive SQL injection testing technique used to discover coding errors by inputting massive amount of random data and observing the changes in the output. Static/Dynamic Testing -Analyzes web application source code

SQL Power Injector

Helps attackers find and exploit SQL injections on a web page. It is SQL Server, Oracle, MySQL, Sybase/Adaptive Server, and DB2 compliant, but it is possible to use it with any existing DBMS when using in-line injection (normal mode). It can also perform blind SQL injection. Features o Create/modify/delete loaded string and cookies parameters directly in the datagrids o Single and Blind SQL injection o Response of the SQL injection in a customized browser o Fine tuning parameters and cookies injection o Can parameterize the size of the length and count of the expected result to optimize the time taken by the application to execute the SQL injection

DB, Table & Column Enumeration

Identify User Level Privilege DB Administrators -include sa, system, sys, dba, admin, root, and many others. The dbo is a user that has implied permissions to perform all activities in the database. Discover DB Structure -Determine table and column names ' group by columnnames having 1=1 -- -Discover column name types ' union select sum(columnname ) from tablename -- -Enumerate user defined tables ' and 1 in (select min(name) from sysobjects where xtype = 'U' and name > '.') -- Column Enumeration in DB o MySQL show columns from tablename o Oracle SELECT * FROM all_tab_columns WHERE table_name='tablename ' o DB2 SELECT * FROM syscat.columns WHERE tabname= 'tablename ' o Postgres SELECT attnum,attname from pg_class, pg_attribute WHERE relname= 'tablename ' AND pg_class.oid=attrelid AND attnum > 0

Peform Union SQL Injection

In UNION SQL injection, an attacker uses the UNION clause to concatenate a malicious query with the original query in order to retrieve results from the target database table. Extract Database Name *http://www.certifiedhacker.com/page.aspx?id=1 UNION SELECT ALL 1,DB_NAME,3,4-* [DB_NAME] Returned from the serve Extract Database Tables http://www.certifiedhacker.com/page.aspx?id=1 *UNION SELECT ALL 1,TABLE_NAME,3,4 from sysobjects where xtype=char(85)--* [EMPLOYEE_TABLE] Returned from the server Extract Table Column Names *( http://www.certifiedhacker.com/page.aspx?id=1 UNION SELECT ALL 1,column_name,3,4 from DB_NAME.information_schema.columns where table_name ='EMPLOYEE_TABLE'--[EMPLOYEE_NAME] Extract 1st Field Data *( http://www.certifiedhacker.com/page.aspx?id=1 UNION SELECT ALL 1,COLUMN-NAME-1,3,4 from EMPLOYEE_NAME -- )* [FIELD 1 VALUE] Returned from the server

Blind/Inferential SQL Injection

In case of SQL injection, no data is transmitted through the web application, and it is not possible for an attacker to retrieve the actual result of the injection; therefore, it is called blind SQL injection. takes longer time to execute because the result returned is generally in the form of boolean. Attackers can steal the data by asking a series of true or false questions through SQL statements. Used when database has custom error messages

Information Gathering Stage

In this stage, attackers try to gather information about the target database such as database name, version, users, output mechanism, DB type, user privilege level, and OS interaction level. 1. Identifying Data Entry Paths - analyze GET and POST requests -Tools- Tamper Data, Burp Suite 2. Extracting Info via Error Messages

Interacting with File System

LOAD_FILE() -MySQL is used to read and return the contents of a file located within the MySQL server OUTFILE() -n MySQL is often used to run a query, and dump the results into a file.

Creating DB Accounts

Microsoft SQL Server -exec sp_addlogin 'victor', 'Pass123' exec sp_addsrvrolemember 'victor', 'sysadmin' Oracle -CREATE USER victor IDENTIFIED BY Pass123 TEMPORARY TABLESPACE temp Microsoft Access -CREATE USER victor IDENTIFIED BY 'Pass123' MySQL -INSERT INTO mysql.user (user, host, password) VALUES ('victor', 'localhost', PASSWORD('Pass123')

Bypass FW

Normalization Blind Injection -one of the easiest way to exploit the vulnerability as it replaces WAF signatures with their synonyms by using SQL functions. The following requests allow an attacker to perform SQL injection attack and bypass the firewall. HTTP Parameter Pollution (HPP) - is an easy and effective technique, which effects both server and client having feasibility to override or add HTTP GET/POST parameters by injecting delimiting characters in query strings. HTTP Parameter Fragmentation (HPF) -is basically used with the idea of bypassing security filters as it is capable of operating HTTP data directly. This technique can be used along with HPP by using UNION operator to bypass firewalls. Signature Bypass -An attacker can transform the signature of SQL queries in such a way that a firewall cannot detect them leading to malicious results.

Exploiting Second-Order SQL Injection

Ooccurs when data input is stored in database and used in processing another SQL query without validating or without using parameterized queries. -The attacker submits a crafted input in an HTTP request -The application saves the input in the database to use it later and gives response to the HTTP request -Now, the attacker submits another request -The web application processes the second request using the first input stored in database and executes the SQL injection query The results of the query in response to the second request are returned to the attacker, if applicable

Extracting Info via Error Messages

Parameter tampering- grouping error, type mismatch, blind injection -Parameter tampering- give the attacker information such as name of the database server, structure of the directory, and functions -Determining Database Engine Type -Determining a SELECT Query Structur -Injections -Grouping errors -Type Mismatch -Blind injection

SQL Injection

Passing SQL cmd through a web application for execution by a backend Database This is a textual language used by a database server. Its used to perform operations on the database include INSERT, SELECT, UPDATE, and DELETE. Programmers use these commands to manipulate data in the database server.

Grabbing SQL Svr Hashes

SELECT password FROM master..sysxlogins Hex each hash

IBM Security AppScan

SQL Injection Detection Tool enhances web application security and mobile application security, improves application security, and strengthens regulatory compliance. Features o Identifies and fixes vulnerabilities o Maximizes remediation efforts o Decreases the likelihood of attacks

Acunetix Web Vulnerability Scanner

SQL injection detection tool Vulnerability Scanner provides automated web application security testing with innovative technologies including: DeepScan and AcuSensor Technology. Features : o Crawl and scan HTML5 web applications, and execute JavaScript like a real browser o Detects advanced DOM-based Cross-site Scripting o Provides a stack-trace of the injected DOM-based XSS payload o Checks for blind XSS and XML External Entity Injection (XXE) o Checks for Server-Side Request Forgery (SSRF) and Host Header Attacks o Checks Email Header Injection and Password Reset Poisoning

Evasion Technique: Sophisticated Match

Signature matches usually succeed in catching the most common classical matches, such as "OR 1=1".

Source Code Analysis

Source code review - method that involves systematic examination of the source code for various types of vulnerabilities. - intended to detect and fix security mistakes made by the programmers during the development phase -A type of white-box testing Two types o Static o Dynamic

Two basic types of Source Code Review

Static Code Analysis -This type of source code analysis is performed to detect the possible vulnerabilities in source code when the code is not executing, that is, is static. -source code analysis is performed using techniques such as Taint Analysis, Lexical Analysis, and Data Flow Analysis. Dynamic Code Analysis -analysis, the source code of the application is analyzed during execution of the code. -Is capable of detecting SQL injection-related security flaws encountered due to interaction of the code with SQL databases, web services, and so on.

Testing for SQL Injection

String Concatenation o MySQL - ( concat(,) ) o MSSQL - ( + ) o MS Access - ( & ) o Oracle and PostgreSQL - ( || ) o DB2 - All except & Request Union and Sub-request o All Stored Procedure o Oracle, MSSQL and PostgreSQL - Yes o MySQL, MS Access, and DB2 - No String Comments o MySQL - (-) , (/* */) and ( # ) o MSSQL, Oracle and PostgreSQL - (-) and (/*) o MS Access - none o DB2 - (-)

In-Band SQL Injection

These are error-based SQL injection and UNION SQL injection uses the same communication channel to perform the attack and retrieve the results These are commonly used and easy-to-exploit SQL injection attacks

Perform Error-Based SQL Injection

These messages help an attacker to build a vulnerability exploit request. There is even a potential to create automated exploits, depending on the error messages generated by the database server. Extract Database Name *( http://www.certifiedhacker.com/page.aspx?id=1 or 1=convert(int,(DB_NAME))-- )* -Syntax error converting the nvarchar value '[DB NAME]' to a column of data type int. Extract 1st Database Table *( http://www.certifiedhacker.com/page.aspx?id=1 or 1=convert(int,(select top 1 name from sysobjects where xtype=char(85)))-- )* -Syntax error converting the nvarchar value '[TABLE NAME 1]' to a column of data type int. Extract 1st Table Column Name *( http://www.certifiedhacker.com/page.aspx?id=1 or 1=convert(int, (select top 1 column_name from DBNAME.information_schema.columns where table_name='TABLE-NAME-1'))-- )* -Syntax error converting the nvarchar value '[COLUMN NAME 1]' to a column of data type int. Extract 1st Field of 1st Row (Data) *( http://www.certifiedhacker.com/page.aspx?id=1 or 1=convert(int, (select top 1 COLUMN-NAME-1 from TABLE-NAME-1))-- )* -Syntax error converting the nvarchar value '[FIELD 1 VALUE]' to a column of data type in

Blind SQL Injection: Heavy Query

This can be used to perform time delay SQL injection attack without using time delay functions. Newest type of sql attack

Normal SQL Query

This include data selection, data retrieval, inserting/updating data, and creating data objects like databases and tables. Query statements begin with a command such as SELECT, UPDATE, CREATE, or DELETE. SELECT Count(*) FROM Users WHERE UserName='Jason' AND Password='Springfield'

Evasion Technique: String Concatenation

This technique breaks a single string into a number of pieces and concatenates them at the SQL level. attacker uses concatenation to break-up identifiable keywords to evade intrusion detection systems

Blind SQL Injection: WAITFOR DELAY (YES or NO Response)

Time Delay SQL injection (sometimes called Time-based SQL injection) evaluates the time delay that occurs in response to true or false queries sent to the database A waitfor statement stops SQL Server for a specific amount of time

Evasion Technique: Obfuscated Code

Two ways o Wrapping: An attacker uses a wrap utility to obfuscate malicious SQL query, and then sends it to the database. An IDS signature will not detect such an obfuscated query and will allow it to pass through, as it does not match the IDS signature. o SQL string obfuscation: In the SQL string obfuscation method, SQL strings are obfuscated using a concatenation of SQL strings, encrypting or hashing the strings, and then decrypting them at runtime. -not detected in the IDS signature

Evasion Technique: Char Encoding

With the char() function, an attacker can encode a common injection variable present in the input string in an attempt to avoid detection in the signature of network security measures. This char() function converts hexadecimal and decimal values into characters that can easily pass through SQL engine parsing. Char() function can be used to inject SQL injection statements into MySQL without using double quotes.

Mole

an automatic SQL injection exploitation tool. uses a command-based interface, allowing the user to indicate the action he wants to perform easily. The CLI also provides auto completion on both commands and command arguments, making the user type as less as possible Features o Supports MySQL, Postgres, SQL Server, and Oracle o Automatic SQL injection exploitation using union technique o Automatic blind SQL injection exploitation o Exploits SQL injection in GET/POST/Cookie parameters

SQL Injection Tools for Mobile

o Andro Hackbar- is a web penetration tool built for Android where you can perform SQL injection, XSS, and LFI flaws o DroidSQLi - is the automated MySQL injection tool for Android. It allows you to test MySQL-based web application against SQL injection attacks. sqlmapchik - is a cross-platform sqlmap GUI for sqlmap tool. It is primarily aimed to be used on mobile devices.

SQL Injection Detection Tools

o IBM Security AppScan o Acunetix Web Vulnerability Scanner o Snort Netsparker Web Application Security Scanner (https://www.netsparker.com) w3af (http://w3af.org) Burp Suite (https://www.portswigger.net) NCC SQuirreL Suite (https://www.nccgroup.com) N-Stalker Web Application Security Scanner (https://www.nstalker.com) Fortify WebInspect (https://software.microfocus.com) WSSA - Web Site Security Scanning Service (https://www.beyondsecurity.com) SolarWinds® Log & Event Manager (https://www.solarwinds.com) AlienVault USM (https://www.alienvault.com) dotDefender (http://www.applicure.com

Types of Signature Evasion Techniques

o In-line Comment: Obscures input strings by inserting in-line comments between SQL keywords. o Char Encoding: Uses built-in CHAR function to represent a character. o String Concatenation: Concatenates text to create SQL keyword using DB specific instructions. o Obfuscated Codes: Obfuscated code is an SQL statement that has been made difficult to understand. o Manipulating White Spaces: Obscures input strings by dropping white space between SQL keyword. o Hex Encoding: Uses hexadecimal encoding to represent a SQL query string. o Sophisticated Matches: Uses alternative expression of "OR 1=1". o URL Encoding: Obscure input string by adding percent sign '%' before each code point. o Case Variation: Obfuscate SQL statement by mixing it with upper case and lower case letters. o Null Byte: Uses null byte (%00) character prior to a string in order to bypass detection mechanism. o Declare Variables: Uses variable that can be used to pass a series of specially crafted SQL statements and bypass detection mechanism. o IP Fragmentation: Uses packet fragments to obscure attack payload which goes undetected by signature mechanism.

Evasion Technique: IP Fragmentation

o Take a pause in sending parts of an attack with a hope that an IDS would time-out before the target computer does o Send the packets in reverse order o Send the packets in proper order except the first fragment which is sent in the last o Send the packets in proper order except the last fragment which is sent in the first o Send packets out of order or randomly

Why are Web Applications Vulnerable to SQL Injection Attacks?

o The database server runs OS commands o They are using privileged account to connect to the database o They have error message revealing important information o No data validation at the server o To much privilege o Implementing Consistent Coding Standards o Not Firewalling the SQL Server

PL/SQL Exploitation

similar to stored procedure is vulnerable to various SQL injection attacks. Has same vulnerabilities similar to dynamic queries that integrate user input at run-time. Can be exploited in two different ways: -Exploiting Quotes - if an attacker injects malicious input such as 'x' OR '1'='1' into the user password field, the modified query given in the procedure returns a row without providing a valid password -Exploitation by Truncation -An attacker may use in-line comments to bypass certain parts of SQL statement. The attacker uses in-line comments along with username

Evasion Technique: Manipulating White Spaces

technique obfuscates input strings by dropping or adding white spaces between SQL keyword and string or number literals without altering execution of SQL statements. Adding white spaces using special characters such as tab, carriage return, or linefeeds makes an SQL statement completely untraceable without changing the execution of the statement

Union SQL Injection

An attacker combines a forged query with a query requested by the user by using a UNION clause.

Export a Value via Regex Attack

An attacker performs SQL injection using regular expressions on a known table to learn values of confidential information such as passwords.

Creating Server Backdoors

Getting OS shell o Using Outfile o Finding Directory Structure o Using Built-in DBMS Functions o Creating Database Backdoors -DB triggers

Transfer DB to Attacker Machine

OPENROWSET on Remote port 80

Types of In-Based SQL Injections

o Illegal/Logically Incorrect Query o Union SQL injection o Error-Based Injections o System Stores procedure o Tautology - uses OR o End-of-line Command -(--) show as o In-line Command - lots of inputs -This type of injections allows an attacker to bypass blacklisting, remove spaces, obfuscate, and determine database versions. o Piggybacked Query -also known as stacked query -adds addtional code to original

Three Main types of SQL Injections

o In-Based SQL Injection -uses the same communication channels -commonly used -generic error message o Blind/Inferential SQL Injection -Takes longer -results returned in boolean -can't see results o Out-of-Band SQL Injection -Different communication channels -Difficult to perform

SQL Injection Tools

o SQL Power Injector o sqlmap o Mole o jSQL injection


Ensembles d'études connexes

TERP10 - Unit 6: Plan-to-Produce Processing

View Set

Fundamentals of nursing test #2 ch. 30, 31, 41, 44, 49

View Set

Social Media Marketing Midterm Review

View Set

chapter 16: the endocrine system

View Set

1.2 Science in Context assessment

View Set

Product Owner role and responsibilities

View Set

образование платное или бесплатное

View Set