SSL Cracking POC For SSL Cracking in Black Hat

0 Comments

Independent hacker Moxie Marlinspike has unveiled new techniques to defeat SSL encryption, which would leave common web applications such as online banking or secure website logins vulnerable to attack.

This would mean that the padlock icon in the corner of supposedly ‘safe’ websites and touted as optimal security by companies like security-with-verisign" target="_blank">Verisign may not be as safe as people generally believe.

Marlinspike revealed his findings at the Black Hat security conference in Washington DC, showing a number of ways where the “chain of trust” fell apart around SSL encryption.

He looked at the possibilities for new vectors of attack against HTTPS, the combination of HTTP and a network security protocol, which are often used for payment and sensitive corporate transactions.

Marlinspike also revealed a free software tool called “SSL Strip”, which could be deployed on a network and used for a man in the middle attack on all potential SSL connections.

It stripped away the SSL encryption, substituting a look-alike HTTPS site, while still convincing the user and website the security was in place.

Reference: https://www.blackhat.com/presentations/bh-dc-09/Marlinspike/BlackHat-DC-09-Marlinspike-Defeating-SSL.pdf

XSS Hacking XSS (Cross Site Scripting) Prevention Cheat Sheet from OWASP

0 Comments

Introduction

This article provides a simple positive model for preventing XSS using output escaping/encoding properly. While there are a huge number of XSS attack vectors, following a few simple rules can completely defend against this serious attack.

These rules apply to all the different varieties of XSS. Both reflected and stored XSS can be addressed by performing the appropriate escaping on the server-side. The use of an escaping/encoding library like the one in ESAPI is strongly recommended as there are many special cases. DOM Based XSS can be addressed by applying these rules on the client on untrusted data.

For a great cheatsheet on the attack vectors related to XSS, please refer to the excellent XSS Cheat Sheet by RSnake. More background on browser security and the various browsers can be found in the Browser Security Handbook.

Untrusted Data

Untrusted data is most often data that comes from the HTTP request, in the form of URL parameters, form fields, headers, or cookies. But data that comes from databases, web services, and other sources is frequently untrusted from a security perspective. That is, it might not have been perfectly validated. The OWASP Code Review Guide has a decent list of methods that return tainted data in various languages, but you should be careful about your own methods as well.

Untrusted data should always be treated as though it contains an attack. That means you should not send it anywhere without taking steps to make sure that any attacks are detected and neutralized. As applications get more and more interconnected, the likelihood of a buried attack being executed by a downstream interpreter increases rapidly.

Traditionally, input validation has been the preferred approach for handling untrusted data. However, input validation is not a great solution for injection attacks. First, input validation is typically done when the data is received, before the destination is known. That means that we don’t know which characters might be significant in the target interpreter. Second, and possibly even more importantly, applications must allow potentially harmful characters in. For example, should poor Mr. O’Malley be prevented from registering in the database simply because SQL considers ‘ a special character?

While input validation is important and should always be performed, it is not a complete solution for injection attacks. It’s better to think of input validation as Defense in depth" href="http://www.owasp.org/index.php/Defense_in_depth">defense in depth and use escaping as described below as the primary defense.

Escaping (aka Output Encoding)

Escaping” is a technique used to ensure that characters are treated as data, not as characters that are relevant to the interpreter’s parser. There are lots of different types of escaping, sometimes confusingly called output “encoding.” Some of these techniques define a special “escape” character, and other techniques have a more sophisticated syntax that involves several characters.

Do not confuse output escaping with the notion of Unicode character encoding, which involves mapping a Unicode character to a sequence of bits. This level of encoding is automatically decoded, and does not defuse attacks. However, if there are misunderstandings about the intended charset between the server and browser, it may cause unintended characters to be communicated, possibly enabling XSS attacks. This is why it is still important to specify the Unicode character encoding (charset), such as UTF-8, for all communications.

Escaping is the primary means to make sure that untrusted data can’t be used to convey an injection attack. There is no harm in escaping data – it will still render in the browser properly. Escaping merely prevents attacks from working.

Reference: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

XSS Hacking Preventing XSS in java…

0 Comments

Cross site scripting issues are everywhere – I’ll try to provide as many resources as possible for programmers in different programming languages and show them how to take the basic steps in the way of protection.

Remember the basics: Always perform encoding at the time of displaying dynamic data to browsers. If you browse around the blog you should find more information on XSS and how to educate yourself as a programmer or individual (well programmers are individuals too, yeah.)

If your programming language is Java, then you should take a look at the StringEscapeUtils java class which belongs to the Apache commons namespace. It provides a nice set of encoding methods/functions that you need to have handy at the time of programming web based interfaces.

The Url for such class can be found here:

http://jakarta.apache.org/commons/lang/api/org/apache/commons/lang/StringEscapeUtils.html

In addition to providing encoding methods, the StringEscapeUtils class also provides decoding functionality – both encoding and decoding available in their Html, Javascript, Java, Xml and SQL versions (this last one not meant for XSS, but worth mentioning.)

Here’s a table of the different methods and references:

staticString escapeHtml(String str)
Escapes the characters in a String using HTML entities.

I will also cover in future posts any other encoding libraries available out there. For the moment, a nice alternative could be Michael Eddington’s encoding library named ‘Reform’ and which has recently (?) been adopted by the OWASP Encoding project. The library and the project can be found at:http://www.owasp.org/index.php/Category:OWASP_Encoding_Project

SQL Hacking How to use SQLMap…

0 Comments

Scenario

Let’s say that you are auditing a web application and found a web page that accepts dynamic user-provided values on GET or POST parameters or HTTP Cookie values or HTTP User-Agent header value. You now want to test if these are affected by a SQL injection vulnerability, and if so, exploit them to retrieve as much information as possible out of the web application’s back-end database management system or even be able to access the underlying operating system.

Consider that the target url is:

http://192.168.1.121/sqlmap/mysql/get_int.php?id=1

Assume that:

http://192.168.1.121/sqlmap/mysql/get_int.php?id=1+AND+1=1

is the same page as the original one and:

http://192.168.1.121/sqlmap/mysql/get_int.php?id=1+AND+1=2

differs from the original one, it means that you are in front of a SQL injection vulnerability in the id GET parameter of the index.php web application page which means that no IDS/IPS, no web application firewall, no parameters’ value sanitization is performed on the server-side.

Reference: http://sqlmap.sourceforge.net/doc/README.html

Web Hacking Hardening against path traversal attacks

0 Comments

What is Path Traversal

Web servers generally are set up to restrict public access to a specific portion of the Web server’s file system, typically called the “Web document root” directory. This directory contains the files intended for public access and any scripts necessary to provide Web application functionality.

In a path traversal attack, an intruder manipulates a URL in such a way that the Web server executes or reveals the contents of a file anywhere on the server, including those lying outside the document root directory. Path traversal attacks take advantage of special-characters sequences in URL input parameters, cookies and HTTP request header.[1]

Real world examples of path traversal strings:

../../../../../../../etc
../../../../../../../../../../etc/passwd
../windows\\winhelp.exe
..\\..\\..\\..\\..\\..\\..\\..\\..\\_private/

String examples

Path traversal issues can allow an intruder perform arbitrary code execution, stored XSS attacks or second order SQL injections. By simply uploading malicious code that later on is going to retrieved by a user, uploading a JavaScript file that later is going to be executed by another user or a piece of code that is going to execute an SQL query.

Why Path Traversal happens

A path traversal attack happens because user controllable data is used by the application to access files and directories in the application server or other back end file systems.? A path traversal attack is possible in parts of the web application that legitimate file uploading takes place, but it also can happen in parts of the web application that there are dynamic execution issues.

In a search engine field for example:

$searchForData = $_GET[searchForData ];

eval(’searchForData;’);

Code example in PHP.

A very straightforward example of path traversal attacks using a RFI (Remote File Inclusion attack) vulnerability.Remote File Inclusion attacks allow malicious users to run their own PHP code on a vulnerable website. The attacker is allowed to include his own malicious code in the space provided for PHP programs on a web page. For instance, a piece of vulnerable PHP code would look like this:[3]

include($page . ‘.php’);

This line of PHP code, is then used in URLs like the following example:

http://www.vulnerable.example.org/index.php?page=archive

Because there is no filtering someone can upload malicious PHP code such as a webshell and embed his code to the current file.

Fixing the problem in Web Application

Multiple levels of security should be used to defeat the vulnerability. All Web Application functionality that is responsible for uploading the file (if that is necessary for some reason ) should take into consideration the following counter measures:

1. All user supplied data should be decoded and canonicalized and then check if the user supplied data contain any path traversal sequences such as ../, ..//,..\/, also this measure should filterout the all null characters e.g. ../../../../../../../../../../../../../../../../../../boot.ini%00.jpg .The “%00″ sequence is used both to bypass a simple file extension check and to cut off the extension when the file is read and processed by the CGI application.[1]

2. The Web Application should perform a while list filtering removing all non allowed characters or dropping immediately all user supplied data if they do not comply with the white list filter.

3. Use a Chroot environment can be used to create and host a separate virtualized copy of the operating system. in order to restrict the user from accessing the parts of file system that should not.

4. The malicious user trying to perform the path traversal attack has the same privileges with the Web Application process handling the whole interaction. Make sure the Web Application has only the needed privileges to perform it tasks.

5. All malicious activity should be logged, so as to have an understanding of what is attempted.

API used to defeat the path traversal issues:

1. In java is java.io.File object. Use the getCanonicalPath function.

2. In ASP .NET the System.Io.GetFullPath should be used.

Fixing the problem in IIS

The easiest way to tighten an IIS Web server against this and other attacks is to download and run the IISLockdown tool, free from http://download.microsoft.com. URLScan, which is installed when you run IISLockdown, blocks requests that contain unsafe characters. IISLockdown also disables the parent paths setting, which prevents the use of “..” in script and application calls. Finally, IIS Web administrators should check all Web permissions, which provide an extra layer of security to NTFS file permissions, and consider upgrading to IIS 6.0, which provides significantly enhanced default security over previous versions of IIS.[1]

Reference [1]: http://searchsecurity.techtarget.com/tip/1,289483,sid14_gci1134252,00.html

Reference [2]: http://en.wikipedia.org/wiki/Remote_File_Inclusion

Reference [3]: The Web Application Hackers Hand Book, Chapter 10 page 345.

Web Hacking Hackers quick reference list…

0 Comments

1. Map Web Application

1.a Explore all visible content (e.g. all linked content)

a. Find all linked content using both passive and active spidering (use Burp Spider).

b. Find all none linked content (use Wikto BackEnd, and Google by using inlink, filetype and site
keywords).

c. Find all default content (use Nikto, Wikto BackEnd).

d. Find all cached web site content from search engines (e.g. use the above Google keywords to check cached information).

2. Identify functionality and technologies used

2.a Identify core functionality:

a. Login functions (if concurrent logins are allowed then check for session hijacking ).

b. Logout functions (check if proper session termination is done).

c. User registration mechanism (to test trust boundaries).

d. Password recovery mechanism (the error messages allow user enumeration?).

e. Major Web Application functionality (find the purpose of web site functionality).

2.b Identify platforms

a. Programming language used (see ending of web page, php, jsp etc.).

b. Web Application platform used (see http header with Burp for banner advertisement or server ip
disclosure).

c. Web Server used (use Httprint).

d. Make sure if any Web Application firewall or proxy, or IPS is in front of the Web Application.

3. Test Client Side

a. Check if client side cookie manipulation is done (with the use of Javascript or VBScript).

b. Check if client side session management exists (with the use of Javascript or VBScript).

c. Check if client side input validation is not the only input validation used (by passing client validation is trivial).

d. Check data transmission by making sure secure flag is set.

e. Check data transmission by making sure httpOnly is flag is set.

f. Check data transmission by making sure that proper SSL enforcement is applied by requesting pages without the s in https.

h. Verify non critical variables are passed through hidden fields (see how core web site functionality uses hidden variables).

i. Verify that no Javascript or Html or VBScript comments exits that reveal the web application internals.

j. Test all client side components (e.g. decompile Java Applets returned back from the web
application, use ollyDebuger to debug activeX controls).

k. Test possible function identifiers, and try to perform identifier guessing (e.g. /admin?licenseId=123).

4. Test Authentication Mechanisms

a. Go through the whole authentication mechanism (e.g. locate login mechanism, password recovery mechanism, registration process etc.).

b. Test password and username security policies (e.g. validate and try to bypass the default password complexity and make sure each user name is unique and is associated with only one password).

c. Test lock out mechanism (e.g. brute force the web application using the Burp intruder)

d. Run a brute force attack or a dictionary attack against the web application, then log the errors returned from the web application and make sure there is no information disclosure issues.

d. Try to perform user enumeration using the responses from the server (e.g. try login using many different valid usernames with invalid password and analyse the error messages).

e. Test for auto generated credentials predictability if applicable (e.g. generate a large amount for usernames and
passwords to see how predictable are).

5. Test Session Management Mechanism

a. Test for session fixation. Go to the home page, capture the generated token session, then login, if no new session token is generated then session fixation is possible.

b. Capture a large amount of sessions tokens and test for token predictability (Use the Burp sequencer). If the tokens are predictable then there is session fixation issue.

c. Login using some valid user credentials then go back to the login page and login using some other user credentials, if no new session token is generated then there is a session fixation issue.

d. If the application does not support login but you can access sensitive data (e.g. such as payment details) using an old sessions then there is a session fixation issue.

e. If the web application relies only in cookie session, does not distinguish between GET and POST requests and is vulnerable to XSS then is also vulnerable to XSRF attacks.

f. If the session token is passed inside URL’s or the Http Header referer then there is a session information
disclosure issue (e.g. off site links, web server logs and proxy logs). g. Check if session termination de validates properly the user session by using terminated sessions access data.

h. Check if the cookie scope restricts cookies only to the current cookie.

7. Test Access Control

a. Test for user information disclosure using the broken links.

c. Test for vertical privilege escalation by replaying requests of users with the same privileges trying to access resources of different users using the same privilege cookie.

d. Test for horizontal privilege escalation using the broken links identified earlier and try to replay requests of users with higher privileges using the a low privilege cookie.

e. Test for insecure access control implementations.

6. Test Input Based Vulnerabilities

a. Test for SQL injections.

b. Test for XSS attacks.

c. Test for XSRF attacks (if concurrent logins are allowed and the web application is ).

d. Test for Path traversal attacks.

e. Test for Perform fuzzing.

f. Test for String format attacks.

g. Test for command injection issues

7. Test for Web Server Vulnerabilities

a. Check for default content using Nikto and Wikto Back End.

b. Check for default user credentials while trying to access administrative control panels.

c. Check for Http methods, such as OPTIONS, PUT, DELETE, TRACE and CONNECT.

d. Check if WebDav is enabled using a WebDav client.

e Check for weak SSL ciphers using SSLdigger or THCSSLCheck.

f. Check for directory listing.

g. Check Http header injection using the Line Feed character and return carriage character (encoded %0a and %0d).

Reference:

http://portswigger.net/wahh/

The Web Application Hacker’s Handbook: Detecting and Exploiting Security Flaws
Authors: Dafydd Stuttard & Marcus Pinto

Web Hacking Hacker’s check list

1 Comment

1. Map Web Application

1.a Explore all visible content (e.g. all linked content)

By saying all visible content I mean all content that has links inside the targeted website using a web
crawler. A web crawler (also known as a web spider, web robot, or?€”especially in the FOAF community?€”web scutter[1]) is a program or automated script which browses the World Wide Web in a
methodical, automated manner.

Suggested programs:

a. Burp Spider: Burp Spider enables you to obtain a detailed understanding of how a web
application works, avoiding the time-consuming and unreliable task of manually following links, submitting forms and scouring HTML source code.

URL: http://portswigger.net/spider/

b. WebScarab Spider:WebScarab is a Web Application Review tool. It sprang from the designs of the
people inhabiting the WebAppSec list run from SourceForge, for a powerful, free, open tool for reviewing web applications for security vulnerabilities.

URL:http://dawes.za.net/rogan/webscarab/

1.b Explore all none visible content

By saying none linked content I mean all all default, dynamic and none linked content. How? Simple using
the most privileged account to login and the using a crawler and of course Wikto back end and other search engines.

Suggested programs/methods:

a. Wikto back-end: The Back-End miner section in Wikto is used to find interesting files and
directories on a web server. It is using the default database from Nitko to be updated.

URL: http://www.sensepost.com/research/wikto/

b. Google:The keywords filetype, inurl, site, relevant and other keywords can be used to extract
cached and none cached information about the targeted website.

2. Identify functionality and technologies used

2.a Identify core functionality:

a. Login functions (e.g. Are concurrentlogins allowed? Is there a lockout mechanism?).

b. Logout functions (e.g. Is propersession termination is done?).

c. User registration mechanism.

d. Password recovery mechanism (e.g. does it allow user enumeration?).

e. Major Web Application functionality.

2.b Identify platforms

Platform used:

a. Programming language used.

b. Web Application platform used.

c. Web Server used.

Programs suggested:

HttpPrint: HttPrint is a web server fingerprinting tool. It relies on web server characteristics
to accurately identify web servers, despite the fact that they may have been obfuscated by changing the server banner strings, or by plug-ins such as mod_security or servermask.

URL: http://www.net-square.com/httprint/

3. Define Web Application Attack Surface

Associate core functionality and web application content with known vulnerabilities, e.g. file uploading
with path traversal.

4. Test Client Side Functionality

4.a Make sure that no security mechanisms exist in the client side (e.g. client side cookie
manipulation, client side session management, client side input validation).

4.b Test data transmission (e.g. make sure secure flag and httpOnly flag are enabled).

4.c Verify no critical variables are passed through hidden fields, if any, and make sure the application
is not vulnerable to repudiation attacks (e.g. replay old client request to bypass access control mechanisms).

4.d Verify that no comments exits in the content returned back to the client that reveal the internals of
the web application (e.g. Javascript and Html comments).

4.e Test thick client components (e.g. decompile Java Applets returned back from the web application).

Programs suggested:

Firebug: Integrates with Firefox to put a wealth of development tools at your fingertips while you
browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.

URL:https://addons.mozilla.org/en-US/firefox/addon/1843

5. Test Authentication Mechanisms

5.aGo through the whole authentication mechanism (e.g. locate login mechanism, password recovery mechanism, registration process etc.)

5.b Test password and username security policies (e.g. validate and try to bypass the default password
complexity and then make sure that the each user name is unique and is associated with only one password).

5.c Test lock out mechanism (e.g. Does the web application have a lockout mechanism and how effective is?)

5.d Run a brute force attack and a dictionary attack against the web application, then log the errors
returned from the web application and make sure there is no information disclosure issue.

5.d Try to perform user enumeration using the responses from the server (e.g. try login using many
different valid usernames with invalid password and analyse the error messages).

5.e Test for auto generated credentials predictability (e.g. if usernames and passwords are generated from
the web application, generate a large amount for usernames and passwords to see how predictable are).

5.f Test for unsafe credential transmission (e.g. There is no SSL enforcement, secure and httpOnly flags are not set and hidden fields are used to pass user credentials or critical variables). Verify that no user credentials are passed to the cookie (e.g. XSS attacks), the referrer header (e.g. session fixation attacks) when third party links are allowed inside the web application or the url query string (e.g. web server logs and and internet browsers will save user credentials into the history).

6. Test Session Management Mechanism

Understand what a session is composed from(e.g. Variables in hidden fields, cookies, URL identifiers e.t.c). Understand meaning of session and try to reproduce valid sessions using various user credentials. Test session generation and session termination. Test for session fixation (e.g. try to produce valid sessions, try to replay a request using an old session or replay a request using a from the targeted web application a session ( captured before a successful login) trying to retrieve authenticated pages, after the user has logged in. Try to perform CSRF.

Programs suggested:

Stompy: Stompy is a free tool to perform a fairly detailed black-box assessment of WWW session identifier generation algorithms. Session IDs are commonly used to track authenticated users, and as such, whenever they’re predictable or simply vulnerable to brute-force attacks, we do have a problem.

URL:http://www.securiteam.com/tools/5VP0O2AKAG.html

7. Test Access Control

Look for broken links (e.g. access variables with high user account privileges simply by guessing URL ID’s).

8. Test Input Based Vulnerabilities

Test for:

a. SQL injections

b. XSS attacks

c. XSRF attacks

d. Path traversal attacks

e. Perform fuzzing

10. Test for Web Server Vulnerabilities

Check Http header injection, server banner advertisement, enabled Http methods and supported protocols
that run over Http (e.g. WebDev). Also check Web Server default content and configuration.

Nikto: Is an Open Source (GPL)web server scanner which performs comprehensive tests against web
servers for multiple items, including over 3500 potentially dangerousfiles/CGIs, versions on over 900 servers, and version specific problems on over 250 servers.

URL:http://www.cirt.net/nikto2

Reference [1]:
http://en.wikipedia.org/wiki/Web_crawler

SQL Hacking Defending against SQL injections

1 Comment

Importance SQL injection

According to a 2006 report from Fortify Software, the top 3 software security vulnerabilities are:

1. Cross-Site Scripting (21.5%)
2. SQL Injection (14.0%)
3. PHP includes (9.5%)[1]

The impact of SQL injection attacks

1) Gathering of sensitive data to manipulating database information.

2) Executing system level commands to denial of service of the application

The impact also depends on the database on the target machine and the roles and privileges the SQL statement is running with. Basically there are two types of SQL injections, the First Order Attacks and the Second Order Attacks. The outcome of first order SQL injection attack is immediate, and we commonly refer to that type of attack as SQL injection attacks. The second order SQL injection is an attack that takes into consideration the web application logic and tries to find how someone can use to an SQL query to cause similar damage using not show obvious means (e.g. SQL inject the cookie!). For example, if user input is stored in a database by using one ASP page, and then the user input is retrieved from the database and is used to construct dynamic SQL statements in a different ASP page, an attacker can inject SQL commands into an SQL statement and then misuse it. This is generally known as a Second Order SQL injection vulnerability. [5]

In First Order Attacks, the attacker can simply enter a malicious string and cause the modified code to be executed immediately. In the Second Order Attacks The attacker injects into persistent storage (such as a table row) which is deemed as a trusted source and the attack is subsequently executed by another activity.

When dealing with SQL injection issues, the following three things should be taken into consideration:

1) User input filtering (black and white listing for first order SQL injections).

2) User output filtering (black and white listing for second order SQL injections).

3) User privilege attributes (for limited access to database functionality).

White listing versus Black listing

One traditional approach to preventing SQL injection attacks is to handle them as an input validation problem and either accept only characters from a whitelist of safe values or identify and escape a blacklist of potentially malicious values. White listing can be a very effective means of enforcing strict input validation rules compared to black listing.[2] Because when you do white listing you are allowing only the characters your application can use to pass through. But when you are doing black listing you have to constantly update your black list with all new malicious input found (e.g. detect all possible input based the database provided functionality).

Parameterized SQL statements

In order to talk about parameterized SQL statements, someone has to understand what a parameterized stored procedure and a parameterized prepared statement. Both Stored Procedures and prepared statements are compiled and cached by the database and? that is why it reduces the processing burden on the client.

Parameterized SQL statements require less maintenance and can offer more guarantees with respect to security. As is almost always the case, blacklisting is riddled with loopholes that make it ineffective at preventing SQL injection attacks. For example, attackers can:[2]

1) Target fields that are not quoted
2) Find ways to bypass the need for certain escaped meta-characters
3) Use stored procedures to hide the injected meta-characters

In VB. NET you can create a safe parameterized select statement using the following API:

<%@ import Namespace=”System.Data” %>
<%@ import Namespace=”System.Data.SqlClient” %>
<%@ Import Namespace=”System.Web.Security” %>
<%@ Import Namespace=”System.Text.RegularExpressions.Regex” %>

A code example would be something like that:

Sub LoginBtn_Click(ByVal Sender As Object, ByVal E As EventArgs)

Dim passwordFormatMatch As Match = Regex.Match(UserName.Text, “[a-zA-Z][0-9]“)

Dim connectionString As String = “Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=E:\mydb\test.mdb”

Dim dbConnection As System.Data.IDbConnection = New System.Data.OleDb.OleDbConnection(connectionString)

Dim queryString As String = “SELECT [Users].[Usernames], [Users].[Passwords] FROM [Users] WHERE (([Users].[Usernames] = @Usernames) AND ([Users].[Passwords] = @Passwords))”

Dim dbCommand As System.Data.IDbCommand = New System.Data.OleDb.OleDbCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dbParam_usernames As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_usernames.ParameterName = “@Usernames”
dbParam_usernames.Value = UserName.Text
dbParam_usernames.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_usernames)

Dim dbParam_passwords As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_passwords.ParameterName = “@Passwords”
dbParam_passwords.Value = UserPass.Text
dbParam_passwords.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_passwords)

dbConnection.Open()

Dim dataReader As System.Data.IDataReader =? dbCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection)

Prepared Statements

1. Instances of PreparedStatement contain an SQL statement that has already been compiled. This is what makes a statement “prepared.”[6]

2. The SQL statement contained in a PreparedStatement object may have one or more IN parameters. An IN parameter is a parameter whose value is not specified when the SQL statement is created. Instead, the statement has a question mark (”?”) as a placeholder for each IN parameter. The “?” is also known as a parameter marker. An application must set a value for each question mark in a prepared statement before executing the prepared statement.[6]

Stored procedures

Stored procedures are implemented differently from database to database. For simplicity when referring to stored procedures we will mean Microsoft SQL Server 2000 stored procedures. A stored procedure is a group of Transact-SQL statements compiled into a single execution plan[7], and can provide customized granular access control, based on privileges of the user? account accessing the database.

That is a code example:

IF (@QuantityOrdered < (SELECT QuantityOnHand
                  FROM Inventory
                  WHERE PartID = @PartOrdered) )
   BEGIN
   -- SQL statements to update tables and process order.
   END
ELSE
   BEGIN
   -- SELECT statement to retrieve the IDs of alternate items
   -- to suggest as replacements to the customer.
   END

Code example [7]

In SQL Server version 6.5 and earlier, stored procedures were a way to partially precompile an execution plan. At the time the stored procedure was created, a partially compiled execution plan was stored in a system table. Executing a stored procedure was more efficient than executing an SQL statement because SQL Server did not have to compile an execution plan completely, it only had to finish optimizing the stored plan for the procedure. Also, the fully compiled execution plan for the stored procedure was retained in the SQL Server procedure cache, meaning that subsequent executions of the stored procedure could use the precompiled execution plan.[7]

Stored procedures Versus Prepared Statements

Prepared Statements pros:

1. Prepared Statements are some sort of precomputed SQL queries and are always type-safe. That is the reason why Prepared Statements are always not vulnerable to SQL injection.

2. Don’t tie you in to a particular database vendor if you write portable SQL code.

Prepared Statements cons:

1. Prepared Statements do not provide customized access control based on user privileges.

Stored procedures pros

1. Stored procedures can provide customized access control based on user privileges.

Stored procedures cons

1. Stored procedures are not always safe from SQL injection, only parameterized stored procedures are safe from SQL injection.

2. Do tie you in to a particular database vendor by splitting the web application business logic into both the web application and the database.

Single point of failure (SPF)

Handling SQL injections only as an input validation issue is wrong. Trying to make sure that you are clean from SQL injections by filtering user inputs introduces a bad security practice called single point of failure and gives you a false sense of security. Now depending on the current situation you might not have to use white listing and black listing at the same time or might not be able use both for various reasons.

To make it more clear, if you have a multi tier web application you can set up different filters into different tires (by using the term tier I mean different machines or software layers, e.g. one filter for the web application server and one filter for the database server). The following diagram is self explanatory:

What is a filtering?

It gets a little confusing to completely understand what is filtering. A filter generally speaking can only do three things:

1) Remove characters (e.g. Look for “‘ or 1=1 –” character patterns).

2) Replace characters (e.g. replace ‘ with ”).

3) Encode characters (e.g. Similar to XSS encoding).

Now when we are talking about black list filtering we mean that you must have a specified list of character patterns that you want to cut off (e.g. ‘ or 1=1 –, ‘ or 9=9 — e.t.c) or have a list of illegal characters that you want to cut off (e.g. –,=,+ e.t.c).White listing is the opposite , which means that you must have a set of allowed characters that you can forward to the web application without causing any security issues.

When and why?

You can use white listing and black listing at the same time when your white list must allow some characters that can be used to create unwanted character patterns. For example you web application must allow the single quote, the equal sign, the dash character and numerical values (meaning ‘,1,= and -), but cannot allow to create a single quote , or one equals one dash dash, meaning the ‘ or 1=1 — character pattern.

Examples:

User input –> ‘ or 1=1 — (White listing) –> OK –> (Black listing) –> Blocked (bad character pattern)

User input –> ” or 1=1 — (White listing) –> Blocked (bad character “)

Some real world examples (ASP .NET 1.1)

Included in this post are VB.NET samples that can be used to screen incoming query-string, form and cookie values for potential Sql injection values. However because valid input data varies from website to website, it is not possible to write a one-size-fits-all screening mechanism. You can modify the sample code included in this post to tighten or loosen the character sequences as appropriate for your website. [3]

Also as a reminder, if a website makes heavy use of dynamically constructed Sql (as opposed to parameterized Sql or parameterized stored procedures) it is a best practice to escape all single quotes contained in un-trusted web input. Since it is not possible to make this replacement using the HttpModule/BeginRequest approaches shown below, you can instead scrub a website’s code and perform the escaping in all places where dynamic Sql is being built.[3]

//C# snippet
private string SafeSqlLiteral(string inputSQL)
{
  return inputSQL.Replace("'", "''");
}

You can screen all incoming query-string, form and cookie values by running code during the BeginRequest event. A central location to register this code is in a website’s global.asax file. The sample code below will check incoming data and automatically redirect to a page called “Error.aspx” if suspicious character sequences are found.[3]

First you will need to add a new namespace import at the top of your global.asax file:

<%@ Import namespace="System.Globalization" %>

Next place the following variable definition and private function somewhere in your global.asax file between the <script> tags:

    //Defines the set of characters that will be checked.
    //You can add to this list, or remove items from this list, as appropriate for your site
    public static string[] blackList = {"--",";--",";","/*","*/","@@","@",
                                         "char","nchar","varchar","nvarchar",
                                         "alter","begin","cast","create","cursor","declare","delete","drop","end","exec","execute",
                                         "fetch","insert","kill","open",
                                         "select", "sys","sysobjects","syscolumns",
                                         "table","update"};

    //The utility method that performs the blacklist comparisons
    //You can change the error handling, and error redirect location to whatever makes sense for your site.
    private void CheckInput(string parameter)
    {
        CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo;

        for (int i = 0; i < blackList.Length; i++)
        {
            if (comparer.IndexOf(parameter,blackList[i],CompareOptions.IgnoreCase) >= 0)
            {
                //
                //Handle the discovery of suspicious Sql characters here
                //
                Response.Redirect("~/Error.aspx");  //generic error page on your site
            }
        }
    }

You then need to register the HttpModule with ASP.NET.

If you are running ASP.NET 2.0 on IIS6, or ASP.NET 2.0 on IIS7 in Classic Mode, place the bolded module registration shown below inside of the system.web/httpModules section:

<system.web>
     ?€¦
     <httpModules>
          ?€¦
          <add name="SampleSqlInjectionScreeningModuleCS" type="Sample.SampleSqlInjectionScreeningModuleCS"/>
          ?€¦
     </httpModules>
     ?€¦
</system.web>

However if you are running ASP.NET 2.0 on IIS7 in Integrated Mode, you instead need to place the bolded module registration shown below inside of the system.webServer/modules section:

<system.webServer>
     ?€¦
     <modules>
          ?€¦
          <add name="SampleSqlInjectionScreeningModuleCS" type="Sample.SampleSqlInjectionScreeningModuleCS" preCondition="managedHandler"/>
          ?€¦
     </modules>
     ?€¦
</system.webServer>

Lastly place the following function definition somewhere in your global.asax file between the <script> tags. This is the function definition that tells ASP.NET to run string checks during the BeginRequest event. If your global.asax file already has a function called Application_BeginRequest, you should instead place the contents of the function definition below into your existing version of Application_BeginRequest.[3]

    void Application_BeginRequest(object sender, EventArgs e)
    {
        foreach (string key in Request.QueryString)
            CheckInput(Request.QueryString[key]);
        foreach (string key in Request.Form)
            CheckInput(Request.Form[key]);
        foreach (string key in Request.Cookies)
            CheckInput(Request.Cookies[key].Value);
    }

Conclusion

When you have a system in production it is everyone responsible to maintain secure the web application system. If you have multiple security defenses then the web application can remain secure even lots of modifications have been made to the system.

Reference [1]:http://st-curriculum.oracle.com/tutorial/SQLInjection/html/lesson1/les01_whylearnit.htm

Reference [2]: http://www.owasp.org/index.php/SQL_injection

Reference [3]: http://forums.asp.net/t/1254125.aspx

Reference [4]: http://www.iec-usa.com/Browse05/GLSS.html

Reference [5]: http://support.microsoft.com/kb/954476

Reference [6]: http://java.sun.com/j2se/1.5.0/docs/guide/jdbc/getstart/preparedstatement.html

Reference [7]:? http://msdn.microsoft.com/en-us/library/aa174792.aspx#sql:stored_procedure

SQL Hacking Blind SQL injections for dummies

0 Comments

Introduction

This article describes how attackers take advantage of SQL Injection vulnerabilities by using time-based blind SQL injection with heavy queries. Our goal is to highlight the need for establishing secure development best practices for Web applications instead of relying only on the security provided by the perimeter defenses. This article shows exploit examples for Microsoft SQL Server and Microsoft Access database, MySQL and PostgreSQL engines, but the present technique is applicable to any other database product in the market.[10]

The definition

SQL injection is a technique that exploits a Security vulnerability" onclick="urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/edit.php?paged=2');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');" href="http://en.wikipedia.org/wiki/Security_vulnerability">security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is in fact an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another.[11]

The first references

The first references to ?€?blind attacks?€ can be found in Chris Anley?€™s June 2002 paper ?€?(More) Advanced SQL Injection?€ [1], in which he calls attention to the possibility of creating such attacks — in this specific case, time-based, one of the less common. Chris gives some examples of blind SQL injection techniques:[10]

<<?€??€??€??€??€??€? if (ascii(substring(@s, @byte, 1)) & ( power(2, @bit))) > 0 waitfor delay ‘0:0:5′
?€¦it is possible to determine whether a given bit in a string is ‘1′ or ?€™0?€™.That is, the above query will pause for five seconds if bit ‘@bit’ of byte ‘@byte’ in string ‘@s’ is ‘1.’

For example, the following query:

declare @s varchar(8000) select @s = db_name() if (ascii(substring(@s, 1, 1)) & ( power(2, 0))) > 0 waitfor delay ‘0:0:5′

Will pause for five seconds if the first bit of the first byte of the name of the current database is 1.[10]

As these examples show, the information is extracted from the database using a vulnerable parameter. Code is then injected to generate a delay in response time when the condition is true.[10]

After the first reference

After this first reference, blind SQL injection techniques continued to be studied with most techniques generating error messages from the attack system, because of the simplicity, quick execution, and extension of showing an error message versus delaying the database. One year later, in September 2003, Ofer Maor and Amichai Shulman published the paper ?€?Blindfolded SQL Injection?€ [2]. Here, they analyze different ways to identify a vulnerable parameter on a SQL Injection system, even when the information processed and returned by the system is not visible.

At the 2004 BlackHat Conference, Cameron Hotchkies presented his paper ?€?Blind SQL Injection Automation Techniques?€ [3]. He proposed alternative methods to automate the exploitation of a Blind SQL Injection vulnerable parameter, using different custom tools. He suggested three different solutions for the automation: (1) Searching for keywords on positive and negative results; (2) Using MD5 signatures to discriminate positive and negative results; (3) Using textual difference engine. He also introduced SQueal, an automatic tool to extract information through Blind SQL Injection, which evolved later to another tool called Absinthe [4].

In September 2005, David Litchfield published the article ?€?Data Mining with SQL Injection and Inference?€ [5], where he discussed the time-based inference techniques, and proposed other ways to obtain time delays using calls to stored procedures, such as xp_cmdshell on MS SQL Server to do a ping.

xp_cmdshell ?€?ping ?€“n 10 127.0.0.1?€™ ?†’ application paused 10 seconds.

Time-based techniques can be extended to any action performed by a stored procedure and able to generate a time delay or any other measurable action.

In December 2006, Ronald van den Heetkamp published the ?€?SQL Injection Cheat Sheet?€ [6], including Blind SQL Injection tricks for MySQL with some examples based on benchmark functions that can generate time delays. For instance:

SELECT BENCHMARK(10000000,ENCODE(’abc’,'123′)); [around 5 sec]
SELECT BENCHMARK(1000000,MD5(CHAR(116))) [ around 7 sec]
Example: SELECT IF( user = ‘root’, BENCHMARK(1000000,MD5( ‘x’ )),NULL) FROM login

A recent exploit [7], published in June 2007 at http://www.milw0rm.com (a Web site dedicated to exploits and security) shows how this technique could be used to attack a game server called Solar Empire:

??$sql=”F***You’),(1,2,3,4,5,(SELECT IF (ASCII (SUBSTRING(se_games.admin_pw, “.$j.”, 1)) =”.$i.”) & 1, benchmark(200000000,CHAR(0)),0) FROM se_games))/*”;

As the studies of the time-based Blind SQL Injection techniques are moving forward, some new tools have been created, such as SQL Ninja [8], which uses the Wait-for method for Microsoft SQL Server engines, or SQL PowerInjector[9], which implements the Wait-for method for Microsoft SQL Server Database engines, Benchmark functions for MySQL engines, and an extension of the Wait-for method for Oracle engines, using calls to DBMS_LOCK methods.

Real world examples

  • On October 26, 2005, Unknown Heise readers replaced a page owned by the German TV station ARD which advertised a pro-RIAA sitcom with Goatse using SQL injection[3]
  • On November 01, 2005, A high school student used a SQL injection to break into the site of a Taiwanese information security magazine from the Tech Target group and steal customer’s information.[4]
  • On January 13, 2006, Russian hackers broke into a Rhode Island government web site and allegedly stole credit card data from individuals who have done business online with state agencies.[5]
  • On March 29, 2006, Susam Pal discovered an SQL injection flaw in an official Indian government tourism site.[6]
  • On March 2, 2007, Sebastian Bauer discovered an SQL injection flaw in the knorr.de login page.[7]
  • On June 29, 2007, Hacker Defaces Microsoft U.K. Web Page using SQL injection. [8][9]. U.K. website The Register quoted a Microsoft spokesperson acknowledging the problem.
  • On August 12, 2007, The United Nations web site was defaced using SQL injection.[10]
  • In May 2008, a server farm inside China used automated queries to Google’s search engine to identify SQL server websites which were vulnerable to the attack of an automated SQL injection tool. [11][13]
  • In May 2008, discussion groups covering identity theft problems faced by Lifelock’s president exploited an SQL Injection vulnerability in Lifelock’s server that would result in yearly membership for $0.00. [14]

Identifying SQL Injection Vulnerable Parameters

To better understand how this is done, it is important to understand the basic types of data in SQL. SQL fields can normally be classified as one of three main types: Number, String or Date. Each main type has many different flavors, but these are irrelevant for the injection process. Each parameter transferred from the web application to the SQL query is considered as one of these types, and it is usually very simple to determine the type (’abc’ is obviously a string, whereas 4 is likely to be an number, although it must be considered as a string as well).[2]

In the SQL language, numeric parameters are passed to the server as is, whereas strings or dates are passed with quotes around them. For example:[2]

SELECT * FROM Products WHERE ProdID = 4

vs.

SELECT * FROM Products WHERE ProdName = ‘Book’

The SQL server, however, does not care what type of an expression it receives, as long as it is indeed of the relevant type. This behavior gives the attacker the best way of identifying whether an error is indeed an SQL one or unrelated. With numeric values, the easiest way to handle this is by using basic arithmetic operations. For instance, let’s look at the following request:[2]

/myecommercesite/proddetails.asp?ProdID=4

Testing this for SQL injection is very simple. One attempt is done by injecting 4′ as the parameter. The other is done using 3 + 1 as the parameter. Assuming this parameter is indeed passed to an SQL request, the result of the two tests will be the following two SQL queries:[2]

(1) SELECT * FROM Products WHERE ProdID = 4′
(2) SELECT * FROM Products WHERE ProdID = 3 + 1

The first one will definitely generate an error, as this is bad SQL syntax. The second, however, will execute smoothly, returning the same product as the original request (with 4 as the ProdID), indicating that this parameter is indeed vulnerable to SQL injection.[2]

A similar technique can be used for replacing the parameter with an SQL syntax string expression. There are only two differences. First, string parameters are held inside quotes, so breaking out of the quotes is necessary. Secondly, different SQL servers use different syntax for string concatenation. For instance, Microsoft SQL Server uses the + sign to concatenate string, whereas Oracle uses || for the same task. Other than that, the same technique is used. For instance:[2]

/myecommercesite/proddetails.asp?ProdName=Book

Testing this for SQL injection involves replacing the ProdName parameter, once with an invalid string such as B’, the other with one that will generate a valid string expression, such as B’ + ‘ook (or B’ || ‘ook with Oracle). This results with the following queries:[2]

(1) SELECT * FROM Products WHERE ProdName = ‘Book”
(2) SELECT * FROM Products WHERE ProdID = ‘B’ + ‘ook’

Again, the first query is likely to generate an SQL error, while the second is expected to return the same product as the original request, with Book as its value.[2]

Similarly, any other expression can be used to replace the original parameters. Specific system functions can be used to return either a number, a string or a date (for instance, in Oracle, sysdate returns a date expression, whereas in SQL Server getdate() does the same task). Other techniques can also be used to determine whether SQL injection occurs.[2]

As can be seen, identifying whether SQL injection occurs is a very simple task even without detailed error messages, allowing the attacker to easily continue with the attack.[2]

Detecting in MySQL blind SQL injection issues

SELECT IF(1=1,’true’,'false’)

IF EXISTS (SELECT * FROM users WHERE username = ‘root’) BENCHMARK(1000000000,MD5(1))

IF (SELECT * FROM login) BENCHMARK(1,SELECT USER())

Important note for CONCAT:Returns the string that results from concatenating the arguments.
May have one or more arguments. If all arguments are non-binary strings, the result is a
non-binary string. If the arguments include any binary strings, the result is a binary string.
A numeric argument is converted to its equivalent binary string form; if you want to avoid that,
you can use an explicit type cast.

SELECT CONCAT(’vari’,'able’)
SELECT CONCAT(”vari”,”able”)

Important note for CONCAT_WS: CONCAT_WS() stands for Concatenate With Separator and is a special
form of CONCAT(). The first argument is the separator for the rest of the arguments. The separator
is added between the strings to be concatenated. The separator can be a string, as can the rest of
the arguments. If the separator is NULL, the result is NULL.

SELECT CONCAT_WS(’,',’My’,NULL,’Variable’)

SELECT CONCAT_WS(’,',’My’,NULL,’Variable’)

Interesting functions (semicolons don’t count):

SELECT USER()

SELECT VERSION()

SELECT NOW()

SELECT SYSDATE()

Interesting select queries (requesting for constants) that return integers:

SELECT NULL

SELECT @NULL

SELECT @@auto_increment_increment

SELECT @@hot_cache.key_buffer_size

SELECT @@cold_cache.key_cache_block_size

SELECT @@hot_cache.key_buffer_size

SELECT @@hot_cache.key_cache_block_size

SELECT @default

For length limitation we can use the keyword LIKE and request system variables:

SHOW VARIABLES LIKE ‘auto_inc%’;

SHOW VARIABLES LIKE ‘key_buffer%’

SHOW VARIABLES LIKE ‘key%’

SHOW VARIABLES LIKE ‘k%’

SHOW VARIABLES LIKE ‘_%’

SHOW VARIABLES LIKE “_%”

Creating constants and requesting constants:

SET @MY_VAR=’Test’

SELECT @MY_VAR

SET GLOBAL hot_cache.key_buffer_size = 4

Important note for LOWER and UPPER: LOWER() (and UPPER()) are ineffective when applied to binary strings (BINARY, VARBINARY, BLOB):

SELECT UPPER(’variable’)

SELECT UPPER(”variable”)

SELECT LOWER(’variable’)

SELECT LOWER(”variable”)

SELECT LOWER(USER())

SELECT UPPER(USER())

SELECT UPPER(VERSION())

SELECT LOWER(VERSION())

Important note for LOAD_FILE(file_name):Reads the file and returns the file contents as a string. To use this function,the file must be located on the server host, you must specify the full pathname to the file, and you must have the FILE privilege. The file must be readable by all and its size less than max_allowed_packet bytes.

If the file does not exist or cannot be read because one of the preceding conditions is not satisfied, the function returns NULL.As of MySQL 5.0.19, the character_set_filesystem system variable controls interpretation of filenames that are given as literal strings.

UPDATE table

SET blob_col=LOAD_FILE(’/tmp/picture’)

WHERE id=1;

Detecting in MS SQL Server blind SQL injection vulnerabilities

Using true/false and waitfor statements:

IF (1=1) SELECT ‘true’ ELSE SELECT ‘false’

if (select user) = ’sa’ waitfor delay ‘0:0:10′

Variable = 1;waitfor delay ‘0:0:10′–

Variable =1);waitfor delay ‘0:0:10′–

Variable =1′;waitfor delay ‘0:0:10′–

Variable =1′);waitfor delay ‘0:0:10′–

Variable =1));waitfor delay ‘0:0:10′–

Variable =1′));waitfor delay ‘0:0:10′–

Variable = 1;waitfor delay ‘0:0:0.51′–

Variable =1);waitfor delay ‘0:0:0.51′–

Variable =1′;waitfor delay ‘0:0:0.51′–

Variable =1′);waitfor delay ‘0:0:0.51′–

Variable =1));waitfor delay ‘0:0:0.51′–

Variable =1′));waitfor delay ‘0:0:0.51′–

Var+ ‘ ‘ +iable

Using system variables:

SELECT @@VERSION

SELECT @@VERSION

SELECT @@VERSION

Time and day functions:

SELECT MONTH(’03/12/1998′)

SELECT DAY(’03/14/1999′)

SELECT GETUTCDATE()

SELECT YEAR(’03/12/1998′)

Detecting in PostgreSQL blind SQL injection vulnerabilities

Using the pg_sleep function:

SELECT pg_sleep(10);

Detecting in Oracle blind SQL injection vulnerabilities

Using the concat function:

concat(’Var’, ‘iable’);

Detecting in IBM DB2 blind SQL injection vulnerabilities

Conclusion

The best defense against SQL injection is to apply comprehensive input validation, use a parameterized API, and never to compose query strings on an ad-hoc basis. In addition, a strong SQL Server lock down is essential, incorporating strong passwords.[1]

Although awareness of SQL injection is increasing, many products and bespoke applications are still vulnerable; from this we infer that SQL injection is likely to be around for a long time to come. It is worth investing the time to fully understand it.[1]

Reference [1]: ?€?(more) Advanced SQL Injection?€ by Chris Anley, NGS Software

URL: http://www.nextgenss.com/papers/more_advanced_sql_injection.pdf

Reference [2]: ?€?Blindfolded SQL Injection?€ by Ofer Maor and Amichai Shulman, Imperva

URL: http://www.imperva.com/application_defense_center/white_papers/blind_sql_server_injection.html

Reference [3]: ?€?Blind SQL Injection Automation Techniques?€ by Cameron Hotchkies, BlackHat Conferences

URL: https://www.blackhat.com/presentations/bh-usa-04/bh-us-04-hotchkies/bh-us-04-hotchkies.pdf

Reference [4]: ?€?Absinthe?€ by Cameron Hotchkies, 0×90.

URL: http://www.0×90.org/releases/absinthe/download.php

Reference [5]: ?€?Data Mining with SQL Injection and Inference?€ by David Litchfield, NGS Software

URL: http://www.ngssoftware.com/research/papers/sqlinference.pdf

Reference [6]: ?€?SQL Injection Cheat Sheet?€ by Ronald van den Heetkamp, 0×000000

URL: http://www.0×000000.com/?i=14&bin=1110

Reference [7]: ?€? Solar Empire Exploit?€ by Blackhawk. Milw0rm.

URL: http://www.milw0rm.com/exploits/4078

Reference [8]: ?€??€¦a SQL Server Injection & takeover tool?€¦ ?€ by icesurfer, SQLNinja

URL: http://sqlninja.sourceforge.net

Reference [9]: ?€?SQL PowerInjector?€ by Francois Larouche, SQL PowerInjector

URL: http://www.sqlpowerinjector.com

Reference [10]:http://technet.microsoft.com/en-us/library/cc512676.aspx

Reference [11]: http://en.wikipedia.org/wiki/SQL_injection

Web Hacking Web app security tools…

1 Comment

Introduction

This section is going to be a live article about the current web app security testing tools:

Web scanners:

WebInspect : A Powerful Web Application Scanner SPI Dynamics’ WebInspect application security assessment tool helps identify known and unknown vulnerabilities within the Web application layer. WebInspect can also help check that a Web server is configured properly, and attempts common web attacks such as parameter injection, cross-site scripting, directory traversal, and more.[1]

NTOSpider is the first next-generation web application vulnerability scanner, providing automated vulnerability assessment with unprecedented accuracy and comprehensiveness. Able to quickly scan and analyze large complex web sites/applications, NTOSpider identifies application vulnerabilities as well as site exposure risk, ranks threat priority, produces highly graphical, intuitive HTML reports, and indicates site security posture by vulnerabilities and threat exposure.[24]

Acunetix Web Vulnerability Scanner : Commercial Web Vulnerability Scanner Acunetix WVS automatically checks your web applications for vulnerabilities such as SQL Injection, cross site scripting, and weak password strength on authentication pages. Acunetix WVS boasts a comfortable GUI and an ability to create professional website security audit reports.[1]

Nikto : A more comprehensive web scanner Nikto is an open source (GPL) web server scanner which performs comprehensive tests against web servers for multiple items, including over 3200 potentially dangerous files/CGIs, versions on over 625 servers, and version specific problems on over 230 servers. Scan items and plugins are frequently updated and can be automatically updated (if desired). It uses Whisker/libwhisker for much of its underlying functionality. It is a great tool, but the value is limited by its infrequent updates. The newest and most critical vulnerabilities are often not detected.[1]

Whisker/libwhisker : Rain.Forest.Puppy’s CGI vulnerability scanner and library Libwhisker is a Perl module geared geared towards HTTP testing. It provides functions for testing HTTP servers for many known security holes, particularly the presence of dangerous CGIs. Whisker is a scanner that used libwhisker but is now deprecated in favor of Nikto which also uses libwhisker.[1]

Wikto : Web Server Assessment Tool Wikto is a tool that checks for flaws in webservers. It provides much the same functionality as Nikto but adds various interesting pieces of functionality, such as a Back-End miner and close Google integration. Wikto is written for the MS .NET environment and registration is required to download the binary and/or source code.[1]

N-Stealth : Web server scanner N-Stealth is a commercial web server security scanner. It is generally updated more frequently than free web scanners such as Whisker/libwhisker and Nikto, but do take their web site with a grain of salt. The claims of “30,000 vulnerabilities and exploits” and “Dozens of vulnerability checks are added every day” are highly questionable. Also note that essentially all general VA tools such as Nessus, ISS Internet Scanner, Retina, SAINT, and Sara include web scanning components. They may not all be as up-to-date or flexible though. N-Stealth is Windows only and no source code is provided.[1]

Security/?referer=http://blog.kassaras.com/wp-admin/edit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php/?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.windowsecurity.com/software/Web-Application-Security/?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=38&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');" href="http://www.windowsecurity.com/software/Web-Application-Security/">The ScanDo Web: ScanDo web application scanner allows the enterprise to conduct ongoing risk assessments to identify the vulnerability of Web applications to hostile attack. It identifies security weaknesses in the Web applications environment and helps eliminate them before they are exploited by hackers and thieves. It scans Web application technologies, including Flash, JavaScript, ASP, XML and Web Services. ScanDo offers control of both automated and manual scanning as well as the ability to replay discovered vulnerabilities to conduct in-depth analysis.

It supports a database for all scanning results with Web reporting for centralized management, and it provides privacy through detection of Social Security and credit card numbers. ScanDo offers a three-stage process for application risk assessment. First, it explores the entire Web application environment and registers its structure and contents. Then it mimics actual hacking methods to identify and uncover the details of any point that is susceptible to attack. In the third stage, ScanDo outputs all scan results into reports that show how to eliminate vulnerabilities.[2]

VForce is a web application security scanner, that simulates attacks for the purpose of testing and analysing a web application for security weaknesses. Like other tools it scans for buffer overruns, manipulation of HTTP requests, brute force vulnerabilities, etc.[2]

ratproxy is a semi-automated, largely passive web application security audit tool, optimized for an accurate and sensitive detection, and automatic annotation, of potential problems and security-relevant design patterns based on the observation of existing, user-initiated traffic in complex web 2.0 environments.[19]

Goolag Scanner is a standalone windows GUI based application.

1. Configuration. gS uses one xml-based configuration file for its
settings (see Settings).

2. Data-House-holding. All dorks coming with the distribution of gS
are kept inside one file, which resides in
{$Goolag Scanner-Installation Directory}/DorkData/gdorks.xml

The name gdorks.xml is predefined from the configuration (see
above).[22]

security testing tool. It has automated testing module for detecting common web application vulnerabilities, and features geared at aiding manual penetration tests. The only system requirement is Java 5; Windows, Linux and Macintosh builds are available. " target="_blank">Grendel-Scan is an open-source web application security testing tool. It has automated testing module for detecting common web application vulnerabilities, and features geared at aiding manual penetration tests. The only system requirement is Java 5; Windows, Linux and Macintosh builds are available.[23]

APACHE_USERS: Apache username enumerator, via /~username requests. This script uses a list of common system names like root, admin etc … You should manually check the issue to establish the http return code, ie: 403 as this is needed for the command line. No native SSL support.[7]

nnikto a console app to perform forced browsing checks against a web server. The application uses a simple algorithm and various techniques to prevent/reduce false positives.[25]

Manual security testing:

Paros proxy : A web application vulnerability assessment proxy A Java based web proxy for assessing web application vulnerability. It supports editing/viewing HTTP/HTTPS messages on-the-fly to change items such as cookies and form fields. It includes a web traffic recorder, web spider, hash calculator, and a scanner for testing common web application attacks such as SQL injection and cross-site scripting.[1]

WebScarab : A framework for analyzing applications that communicate using the HTTP and HTTPS protocols In its simplest form, WebScarab records the conversations (requests and responses) that it observes, and allows the operator to review them in various ways. WebScarab is designed to be a tool for anyone who needs to expose the workings of an HTTP(S) based application, whether to allow the developer to debug otherwise difficult problems, or to allow a security specialist to identify vulnerabilities in the way that the application has been designed or implemented.[1]

Burpsuite : An integrated platform for attacking web applications Burp suite allows an attacker to combine manual and automated techniques to enumerate, analyze, attack and exploit web applications. The various burp tools work together effectively to share information and allow findings identified within one tool to form the basis of an attack using another.[1]

SPIKE Proxy : HTTP Hacking Spike Proxy is an open source HTTP proxy for finding security flaws in web sites. It is part of the Spike Application Testing Suite and supports automated SQL injection detection, web site crawling, login form brute forcing, overflow detection, and directory traversal detection.[1]

CAL9000: CAL9000 brings together a host of web application security testing tools into one convenient package. It is designed to be used in the Firefox browser. CAL9000 functionality may be limited when used with other browsers.[11]

httpedit:httpedit is a ‘low-level’ interface to HTTP. The application allows you to write a raw HTTP request, send it against a web server and review the response, all from within the same app.[11]

Decompilers:

Jad is a Java decompiler, i.e. program that reads one or more Java class files and converts them into Java source files which can be compiled again.[3]

Jad can be used:

  • for recovering lost source codes;
  • for exploring the sources of Java runtime libraries;
  • as a Java disassembler;
  • as a Java source code cleaner and beautifier. just kidding

Web session analyzers:

Stompy is an advanced utility to test the quality of WWW session identifiers and other tokens that are meant to be unpredictable. It is fully automated, employs a remarkably advanced collection of tests, and probably scratches an important pen-testing itch.[4]

Web fuzzers:

PROTOS HTTP-reply – Another fuzzer from the PROTOS dudes for attack HTTP responses, useful for browser vulns.[5]

Screaming Cobra - Name makes the fuzzer sound better than it really is, but is good for finding CGI bugs. Also, its a perl scrpt so easy to modify or extend.[5]

Mangle – A fuzzer for generating odd HTML tags, it will also autolaunch a browser. Mangle found the infamous IFRAME IE bug.[5]

FUZZLED: Fuzzled is a powerful fuzzing framework. Fuzzled includes helper functions, namespaces, factories which allow a wide variety of fuzzing tools to be developed. Fuzzled comes with several example protocols and drivers for them .This most recent release includes : * Support for a raft of additional protocols, including HTTPInject, NNTP, SMTP and IMAP. * New and improved namespaces. * Improvements to the pattern factory. * Documentation on writing a fuzzer in Fuzzled. * Numerous bugfixes and other minor improvements.[7]

RFuzz is a Ruby library to easily test web applications from the outside using a fast HttpClient and wicked evil RandomGenerator allowing the average programmer to use advanced fuzzing techniques for just pennies a day.[16]

PROTOS HTTP-reply – Another fuzzer from the PROTOS dudes for attack HTTP responses, useful for broswer vulns.[15]

Ajax Security:

Spajax is a security .NET ajax scanning tools from OWASP.[6]

XSS exploiting

XSSshell: XSS Tunnel is a proxy which allows you to traffic any HTTP traffic through a Cross-site Scripting (XSS) Channel opened by XSS Shell. This release includes a new version of XSS Shell, XSS Tunnel and source codes. Please refer to the white paper for details.[7]

XSSSHELL: XSS Shell is a powerful XSS backdoor. XSS Shell allows interactively getting control over a Cross-site Scripting (XSS) vulnerability in a web application. Demonstrates the real power and damage of Cross-site Scripting attacks.[7]

SQL injection exploiting

SqlServerDataExtractor Sometimes we need to drop a binary onto a box and extract the data. This application allows you to specify the connection string and SQL statement. Once the SQL statement executed, the data is output to a file in the application directory, which is loaded into a browser control on the second tab. The reason for using HTML to display the data, is that the application should be flexible enough to handle alot of data.[25]

SSL enumeration & exploitation

ManySSL:Primarily a tool for Linux users to enumerate the SSL ciphers in use on any SSL encrypted service, including mail servers that utilise starttls. This tool has an option to identify only the weak ciphers (Ciphers under 128 bit) so administrators can know which ciphers to remove from their service.[7]

SSLDigger v1.02 Released 8/26/2004. Copyright 2004 (c) by Foundstone, Inc.SSLDigger v1.02 is a tool to assess the strength of SSL servers by testing the ciphers supported. Some of these ciphers are known to be insecure.[8]

THCIISSLame version 0.2 IIS 5 SSL remote root exploit. Uses a connect back shell. [13]

THC SSL Check is a small tool that checks the remote SSL stack for supported ciphers and versions. Useful for pentesting for weak SSL configuration discovery.[13]

THCSSLProxy THCSSLProxy is a small command-line SSL proxy for Window that is useful for penetration testing SSL services like HTTPS, SMTPS, LDAPS, POP3S, and more.[13]

sslciphercheck a new console tool to check supported SSL ciphers, it will also retrieve and extract the certificate information including whether Server Gated Cryptography (SGC) is supported The main problem with existing tools e.g. SSLDigger and thcsslcheck is that they either don’t support SSLv2 or they don’t retrieve the certificate information, so you cannot tell if Server Gated Cryptography is supported…sslciphercheck is designed to over come these issues.[25]

Web Service scanner

WSDigger v1.0 Released 7/12/2005. Copyright 2005 (c) by Foundstone, Inc. WSDigger is a free open source tool designed by Foundstone to automate black-box web services security testing (also known as penetration testing). WSDigger is more than a tool, it is a web services testing framework. Version one of this framework contains sample attack plug-ins for SQL injection, cross site scripting and XPATH injection attacks. A web service vulnerable to XPATH injection is provided as an example with the tool. By releasing the framework as an open-source tool, users are encouraged to develop and share their own plug-ins.System requirements Windows: .NET Framework

Http probers

hoppy:Hoppy (*[H]ttp [O]ptions [P]rober In [PY]thon*) is a http server method prober written in python, does exactly what it says on the tin. It tests http methods for configuration issues leaking information or just to see if they are enabled. Latest Version is 1.5.1[7]

httprint:httprint is a web server fingerprinting tool. It relies on web server characteristics to accurately identify web servers, despite the fact that they may have been obfuscated by changing the server banner strings, or by plug-ins such as mod_security or servermask.

THCSSLProxy: Small commandline SSL proxy for windows useful for pentesting SSL services like HTTPS, SMTPS, LDAPS, POP3S etc.[12]

Web spiders:

SiteDigger v2.0 Released 1/06/2005. Copyright 2005 (c) by Foundstone, Inc. SiteDigger 2.0 searches Google?€™s cache to look for vulnerabilities, errors, configuration issues, proprietary information, and interesting security nuggets on web sites.[10]
What’s New in SiteDigger 2.0

* 10 times more results! Now you can use FSDB / GHDB and generate 10 results per signature.
* Improved user interface, help file, signature update and results page.
* Decreased false positives.
* Latest signatures (open webcams, credit card numbers, etc).
* Ability to raw search.

Aura:A while back Google encouraged developers to make use of their API. Many people built applications around the API, but alas Google has stopped issuing API keys. This means that those applications (like wikto / etc) lost large portions of their functionality. SensePost AURA (Api Usable / Re-usable Again) will help to get those tools working again. Aura is a very simple web app that runs as an executable on your windows machine and listens on 127.0.0.1:80. [11]

HTTrack:HTTrack is a free and easy-to-use offline browser utility. It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer.

Web Brute forcer’s

WWWhack is a brute force utility that will try to crack web sites guarded by an web access password. This utility can use a word file or try all possible combinations, and by trial-and-error, will attempt to find a combination of username/password that is accepted by the web server.[14]

Database enumeration

Sqlmap is an automatic SQL injection tool developed in Python. Its goal is to detect and take advantage of SQL injection vulnerabilities on web applications. Once it detects one or more SQL injections on the target host, the user can choose among a variety of options to perform an extensive back-end database management system fingerprint, retrieve DBMS session user and database, enumerate users, password hashes, privileges, databases, dump entire or user’s specific DBMS tables/columns, run his own SQL SELECT statement, read specific files on the file system and much more.[18]

Frameworks

ProxMon is an extensible Python based framework that reduces testing effort, improves consistency and reduces errors. Its use requires limited additional effort as it processes the proxy logs that you?€™re already generating and reports discovered issues. In addition to penetration testing, ProxMon is useful in QA, developer testing and regression testing scenarios.[20]

Pantera uses an improved version of SpikeProxy to provide a powerful web application analysis engine.[21]

Reference [1]:http://sectools.org/web-scanners.html

Reference [2]:http://www.windowsecurity.com/software/Web-Application-Security/

Reference [3]:http://www.kpdus.com/jad.html#general

Reference [4]:http://lcamtuf.coredump.cx/

Reference [5]:http://www.infosecinstitute.com/blog/2005/12/fuzzers-ultimate-list.html

Reference [6]:http://cvs.drupal.org/viewvc.py/drupal/contributions/modules/spajax/

Reference [7]: http://www.portcullis.co.uk/16.php

Reference [8]:http://www.foundstone.com/us/resources/proddesc/ssldigger.htm

Reference [9]:http://www.foundstone.com/us/resources/proddesc/wsdigger.htm

Reference [10]:http://www.foundstone.com/us/resources/proddesc/sitedigger.htm

Reference [11]:http://www.hacktoolrepository.com/category.pl?cid=8&categoryname=Web%20applications

Reference [12]:http://freeworld.thc.org/root/tools/

Reference [13]:http://packetstormsecurity.org/groups/thc/index5.html

Reference[14]:http://www.darknet.org.uk/2006/12/wwwhack-19-download-wwwhack19zip-web-hacking-tool/

Reference [15]:http://www.infosecinstitute.com/blog/2005/12/fuzzers-ultimate-list.html

Reference [16]:http://rfuzz.rubyforge.org/

Reference [17]:http://www.gnucitizen.org/blog/web-client-fuzzer_py/

Reference [18]:http://sqlmap.sourceforge.net/

Reference [19]:security.html" target="_blank">http://code.google.com/p/ratproxy/

Reference [20]:http://www.isecpartners.com/proxmon.html

Reference [21]:http://www.owasp.org/index.php/Category:OWASP_Pantera_Web_Assessment_Studio_Project

Reference [22]: http://www.goolag.org/specifications.html

Reference [23]: http://www.grendel-scan.com/

Reference [24]: http://www.ntobjectives.com/products/ntospider.php

Reference [25]: http://www.woany.co.uk